diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6853d5e3a..22ae067c7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -169,7 +169,7 @@ jobs: - name: Build env: - MACOSX_DEPLOYMENT_TARGET: "11" + MACOSX_DEPLOYMENT_TARGET: "12" run: | VERSION="$(tr -d '\r\n' < VERSION)" SKIP_CODESIGN="${{ env.IS_FORK }}" @@ -228,7 +228,7 @@ jobs: shell: cmd run: | call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat" - set PATH=C:\Qt\6.9.3\msvc2022_64\bin;%PATH% + set PATH=%GITHUB_WORKSPACE%\dependencies\pdfium\win\x64;C:\Qt\6.9.3\msvc2022_64\bin;%PATH% ctest --test-dir build --output-on-failure - name: Upload executables for signing @@ -683,4 +683,3 @@ jobs: files: staging/* env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - diff --git a/AGENTS.md b/AGENTS.md index 894bf8776..05d8ae365 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ Out-of-source builds are required. In-source builds will be rejected by CMake. ```bash cmake -B build -DCMAKE_BUILD_TYPE=Release -cmake --build build --parallel +cmake --build build --parallel 16 ``` Build options: @@ -16,6 +16,7 @@ Build options: - `PDF_BACKEND`: `pdfium` | `poppler` | `pdfkit` | `no_pdf` (default: pdfium on Windows, pdfkit on macOS, poppler on Linux) - `BUILD_SERVER_STANDALONE=ON`: builds only `YACReaderLibraryServer` (headless), requires only Qt 6.4+ - `BUILD_TESTS=ON` (default): enables the test suite +- Always use the highest parallelism allowed by the CPU. ## Translations diff --git a/CHANGELOG.md b/CHANGELOG.md index eaded1d2d..f80f1e308 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,27 @@ Version counting is based on semantic versioning (Major.Feature.Patch) +## 10.3.0 + +### YACReaderLibrary +* Unify folder and comic browsing in the grid view. The side information panel can show information about folders, lists and selected items. There are settings to decide if folders should be displayed alongside comics and if folders and comics should be kept visually separated. +* Fix drag & drop for sorting comics in lists. +* Add state restoration when going back and forth through the navigation history. +* Add scroll and current item restoration when switching between content views. +* Keep current scroll position when editing comics. +* Fix info panel in the grid view not getting updates when the selected comic metadata changes. +* Fix rating context menu in the grid view. +* Add reset rating to the comic context menu. +* Add support for renaming folders inside the app. This preserves the state of the folder and its subfolders (completed, read, dates, etc.) rather than creating a new folder like updating the library does if you rename the folder directly on the file system. +* Add organizing functionalities for renaming files and creating folder structures based on metadata. Highly experimental. +* Support for dropping images onto folders and comics to change their covers. + +### WebUI +* Add per-library search. +* Use the same sorting as the rest of the apps. +* Restore the previous scroll position when navigating back through library folders. +* Add per-library continue reading list. + ## 10.2.0 ### YACReader diff --git a/CLAUDE.md b/CLAUDE.md index c17412640..05d8ae365 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1 +1,105 @@ -See AGENTS.md for project context. +# AGENTS GUIDANCE + +This file provides guidance to AI agents when working with code in this repository. + +## Build + +Out-of-source builds are required. In-source builds will be rejected by CMake. + +```bash +cmake -B build -DCMAKE_BUILD_TYPE=Release +cmake --build build --parallel 16 +``` + +Build options: +- `DECOMPRESSION_BACKEND`: `unarr` | `7zip` | `libarchive` (default: 7zip on Windows/macOS, libarchive on Linux) +- `PDF_BACKEND`: `pdfium` | `poppler` | `pdfkit` | `no_pdf` (default: pdfium on Windows, pdfkit on macOS, poppler on Linux) +- `BUILD_SERVER_STANDALONE=ON`: builds only `YACReaderLibraryServer` (headless), requires only Qt 6.4+ +- `BUILD_TESTS=ON` (default): enables the test suite +- Always use the highest parallelism allowed by the CPU. + +## Translations + +Use CMake translation targets (Qt LinguistTools integration), not ad-hoc `lupdate` calls. + +Update `.ts` files from source code (C++ + QML): + +```bash +cmake --build build --target update_translations +``` + +On multi-config generators (Visual Studio / Ninja Multi-Config), include config: + +```bash +cmake --build build --config Release --target update_translations +``` + +Build `.qm` files: + +```bash +cmake --build build --target release_translations +``` + +Multi-config variant: + +```bash +cmake --build build --config Release --target release_translations +``` + +Important: +- Do not run `lupdate` only on a hand-picked subset of QML files, because that can mark unrelated translations as obsolete. +- In `YACReaderLibrary`, `qt_add_translations(...)` is configured to scan full target sources and include the QML files directly. +- `update_translations` updates both locale TS files and `*_source.ts` template files for all apps. +- `*_source.ts` files are translator base templates and must not be treated as shipped locales. + +## Tests + +```bash +ctest --test-dir build --output-on-failure +``` + +Tests live in `tests/` and are built as Qt Test executables (`compressed_archive_test`, `concurrent_queue_test`). + +## Code Formatting + +CI enforces `clang-format`. Run it before committing. There are multiple `.clang-format` files — subdirectories for third-party code have their own to opt out of reformatting. Always run recursively from the repo root via the provided scripts: + +- Linux: `scripts/clang-format-linux.sh` +- macOS: `scripts/clang-format-macos.sh` +- Windows: `scripts\clang-format-windows.cmd` (or `.ps1`) + +Style is WebKit-based with custom brace wrapping (braces on same line for control flow, new line after functions/classes), no column limit, and `SortIncludes: false`. + +## Architecture + +The repo builds three applications that share a common set of static libraries: + +| App | Description | +|-----|-------------| +| `YACReader` | Comic viewer | +| `YACReaderLibrary` | Comic library manager (GUI) | +| `YACReaderLibraryServer` | Headless HTTP server | + +### Static library dependency layers (bottom to top) + +1. **`yr_global`** — version/global constants, no GUI, used by everything +2. **`naturalsort`, `concurrent_queue`, `worker`** — utilities +3. **`common_all`** — shared non-GUI: `ComicDB`, `Folder`, `Bookmarks`, HTTP helpers, cover utils +4. **`comic_backend`** — comic file abstraction + PDF backend (source varies by `PDF_BACKEND`) +5. **`cbx_backend`** — compressed archive abstraction (in `compressed_archive/`) +6. **`db_helper`** — SQLite database layer: schema management, reading lists, query parser +7. **`library_common`** — library scanning, bundle creation, XML metadata parsing; shared between `YACReaderLibrary` and `YACReaderLibraryServer` +8. **`common_gui`** — GUI widgets, themes infrastructure, version check (not built in `BUILD_SERVER_STANDALONE`) +9. **`rhi_flow_reader` / `rhi_flow_library`** — RHI-based 3D coverflow widget, compiled twice with different defines (`YACREADER` vs `YACREADER_LIBRARY`); shaders compiled via `qt_add_shaders()` + +### Key design notes + +- **Theme system**: `theme_manager.h/cpp` is NOT part of `common_gui` because it depends on app-specific `Theme` structs. Each app (`YACReader/themes/`, `YACReaderLibrary/themes/`) defines its own `theme.h` and includes `theme_manager` directly. +- **Compile-time app identity**: `YACREADER` or `YACREADER_LIBRARY` defines distinguish shared source compiled into different apps. +- **PDF backend**: resolved at configure time into an `INTERFACE` target `pdf_backend_iface` (see `cmake/PdfBackend.cmake`); `comic_backend` and `common_all` link against this interface. +- **Third-party code**: `third_party/` contains QsLog, KDToolBox, QtWebApp, QrCode — each has its own `.clang-format` to prevent reformatting. +- **Runtime dependencies**: Qt binaries must be in `PATH`; third-party DLLs/dylibs must be next to the executable. Check an existing YACReader installation for the required files. + +### PRs + +Target branch is always `develop`. diff --git a/CMakeLists.txt b/CMakeLists.txt index 06c9dd077..00a529b43 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -126,7 +126,7 @@ if(BUILD_SERVER_STANDALONE) Sql ) else() - find_package(Qt6 6.7 REQUIRED COMPONENTS + find_package(Qt6 6.9 REQUIRED COMPONENTS Core Core5Compat Gui @@ -173,6 +173,7 @@ add_subdirectory(YACReaderLibrary/server) if(NOT BUILD_SERVER_STANDALONE) add_subdirectory(YACReaderLibrary/comic_vine) + add_subdirectory(YACReaderLibrary/organize_files) endif() # Always add YACReaderLibrary: defines library_common and db_helper (shared with server) diff --git a/README.md b/README.md index 485fa3e5e..bf35ae677 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ Contributions are not restricted to coding; you can help the project by bringing If you can't do it yourself please don't open PRs based on ideas developed using AI. If you are a software engineer it's ok to use AI as long as you know what you are doing, understanding and reviewing agent generated code before opening a PR is a must. Code that just works won't be enough to ensure I'll accept your contribution. #### Dev Setup -YACReader is developed in *C++/Qt* and built with *CMake*. You need a *C++20* compiler and *Qt 6.7+*. In *Windows* I use *Visual Studio 2022* and in *macOS* I use Xcode, but I do all the coding using *QtCreator*. +YACReader is developed in *C++/Qt* and built with *CMake*. You need a *C++20* compiler and *Qt 6.9+*. In *Windows* I use *Visual Studio 2022* and in *macOS* I use Xcode, but I do all the coding using *QtCreator*. The repo includes binaries for the dependencies needed for *Windows* (MSVC compiler) and *macOS* (clang). The *7zip* decompression backend source is downloaded automatically by CMake during configuration. @@ -86,4 +86,4 @@ YACReader is free but it needs money to keep being alive, so please, if you like If you are interested in YACReader, please contact me so we can discuss your next steps. ## Sponsors -Free code signing on Windows provided by [SignPath.io](https://signpath.io/), certificate by [SignPath Foundation](https://signpath.org/) \ No newline at end of file +Free code signing on Windows provided by [SignPath.io](https://signpath.io/), certificate by [SignPath Foundation](https://signpath.org/) diff --git a/VERSION b/VERSION index fe46e0dd3..6495db7e2 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -10.2.0 \ No newline at end of file +10.3.0 \ No newline at end of file diff --git a/YACReader/render.cpp b/YACReader/render.cpp index 03a4dd4b7..c75319cd6 100644 --- a/YACReader/render.cpp +++ b/YACReader/render.cpp @@ -12,6 +12,7 @@ #include #include +#include template inline const T &kClamp(const T &x, const T &low, const T &high) @@ -382,14 +383,14 @@ Render::Render() Render::~Render() { - for (auto *pr : pageRenders) { + for (auto *pr : std::as_const(pageRenders)) { if (pr != nullptr && pr->wait()) { delete pr; } } // TODO move to share_ptr - for (auto *filter : filters) { + for (auto *filter : std::as_const(filters)) { delete filter; } @@ -693,23 +694,24 @@ void Render::load(const QString &path, const ComicDB &comicDB) { // TODO prepare filters for (int i = 0; i < filters.count(); i++) { - if (typeid(*filters[i]) == typeid(BrightnessFilter)) { + auto *filter = filters.at(i); + if (typeid(*filter) == typeid(BrightnessFilter)) { if (comicDB.info.brightness == -1) - filters[i]->setLevel(0); + filter->setLevel(0); else - filters[i]->setLevel(comicDB.info.brightness); + filter->setLevel(comicDB.info.brightness); } - if (typeid(*filters[i]) == typeid(ContrastFilter)) { + if (typeid(*filter) == typeid(ContrastFilter)) { if (comicDB.info.contrast == -1) - filters[i]->setLevel(100); + filter->setLevel(100); else - filters[i]->setLevel(comicDB.info.contrast); + filter->setLevel(comicDB.info.contrast); } - if (typeid(*filters[i]) == typeid(GammaFilter)) { + if (typeid(*filter) == typeid(GammaFilter)) { if (comicDB.info.gamma == -1) - filters[i]->setLevel(100); + filter->setLevel(100); else - filters[i]->setLevel(comicDB.info.gamma); + filter->setLevel(comicDB.info.gamma); } } createComic(path); @@ -1128,12 +1130,13 @@ void Render::reload() void Render::updateFilters(int brightness, int contrast, int gamma) { for (int i = 0; i < filters.count(); i++) { - if (typeid(*filters[i]) == typeid(BrightnessFilter)) - filters[i]->setLevel(brightness); - if (typeid(*filters[i]) == typeid(ContrastFilter)) - filters[i]->setLevel(contrast); - if (typeid(*filters[i]) == typeid(GammaFilter)) - filters[i]->setLevel(gamma); + auto *filter = filters.at(i); + if (typeid(*filter) == typeid(BrightnessFilter)) + filter->setLevel(brightness); + if (typeid(*filter) == typeid(ContrastFilter)) + filter->setLevel(contrast); + if (typeid(*filter) == typeid(GammaFilter)) + filter->setLevel(gamma); } reload(); diff --git a/YACReader/yacreader_de.ts b/YACReader/yacreader_de.ts index 70c25659e..ecfbb9a2c 100644 --- a/YACReader/yacreader_de.ts +++ b/YACReader/yacreader_de.ts @@ -188,27 +188,23 @@ FileComic - + + Format not supported Format wird nicht unterstützt - + 7z not found 7z nicht gefunden - + Unknown error opening the file Unbekannter Fehler beim Öffnen des Files - - Unsupported EPUB: %1 - - - - + CRC error on page (%1): some of the pages will not be displayed correctly CRC Error auf Seite (%1): Einige Seiten werden nicht korrekt dargestellt @@ -371,7 +367,7 @@ Löschen - + Comics directory Comics-Verzeichnis @@ -774,48 +770,48 @@ Wenn keiner aktiv ist, geschieht beim Drücken der Escape-Taste nichts. Viewer - + Page not available! Seite nicht verfügbar! - - + + Press 'O' to open comic. 'O' drücken, um Comic zu öffnen. - + Error opening comic Fehler beim Öffnen des Comics - + Cover! Titelseite! - + CRC Error CRC Fehler - + Comic not found Comic nicht gefunden - + Not found Nicht gefunden - + Last page! Letzte Seite! - + Loading...please wait! Ladevorgang... Bitte warten! diff --git a/YACReader/yacreader_en.ts b/YACReader/yacreader_en.ts index 71ff4c863..907e5d398 100644 --- a/YACReader/yacreader_en.ts +++ b/YACReader/yacreader_en.ts @@ -188,30 +188,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly CRC error on page (%1): some of the pages will not be displayed correctly - + Unknown error opening the file Unknown error opening the file - + 7z not found 7z not found - + + Format not supported Format not supported - - - Unsupported EPUB: %1 - - GoToDialog @@ -536,7 +532,7 @@ If none is active, Escape does nothing. Options - + Comics directory Comics directory @@ -774,48 +770,48 @@ If none is active, Escape does nothing. Viewer - - + + Press 'O' to open comic. Press 'O' to open comic. - + Not found Not found - + Comic not found Comic not found - + Error opening comic Error opening comic - + CRC Error CRC Error - + Loading...please wait! Loading...please wait! - + Page not available! Page not available! - + Cover! Cover! - + Last page! Last page! diff --git a/YACReader/yacreader_es.ts b/YACReader/yacreader_es.ts index 19c9df467..c86436dfc 100644 --- a/YACReader/yacreader_es.ts +++ b/YACReader/yacreader_es.ts @@ -188,27 +188,23 @@ FileComic - + + Format not supported Formato no soportado - + 7z not found 7z no encontrado - + Unknown error opening the file Error desconocido abriendo el archivo - - Unsupported EPUB: %1 - - - - + CRC error on page (%1): some of the pages will not be displayed correctly Error CRC en la página (%1): algunas de las páginas no se mostrarán correctamente @@ -371,7 +367,7 @@ Limpiar - + Comics directory Directorio de cómics @@ -774,48 +770,48 @@ Si ninguno está activo, la tecla Esc no hace nada. Viewer - + Page not available! ¡Página no disponible! - - + + Press 'O' to open comic. Pulsa 'O' para abrir un fichero. - + Error opening comic Error abriendo cómic - + Cover! ¡Portada! - + CRC Error Error CRC - + Comic not found Cómic no encontrado - + Not found No encontrado - + Last page! ¡Última página! - + Loading...please wait! Cargando...espere, por favor! diff --git a/YACReader/yacreader_fr.ts b/YACReader/yacreader_fr.ts index f86d19b94..74ad2acdc 100644 --- a/YACReader/yacreader_fr.ts +++ b/YACReader/yacreader_fr.ts @@ -188,27 +188,23 @@ FileComic - + + Format not supported Format non supporté - + 7z not found 7z introuvable - + Unknown error opening the file Erreur inconnue lors de l'ouverture du fichier - - Unsupported EPUB: %1 - - - - + CRC error on page (%1): some of the pages will not be displayed correctly Erreur CRC sur la page (%1): certaines pages ne s'afficheront pas correctement @@ -346,7 +342,7 @@ Clair - + Comics directory Répertoire des bandes dessinées @@ -774,48 +770,48 @@ Si aucun n’est actif, la touche Échap ne fait rien. Viewer - + Page not available! Page non disponible ! - - + + Press 'O' to open comic. Appuyez sur "O" pour ouvrir une bande dessinée. - + Error opening comic Erreur d'ouverture de la bande dessinée - + Cover! Couverture! - + CRC Error Erreur CRC - + Comic not found Bande dessinée introuvable - + Not found Introuvable - + Last page! Dernière page! - + Loading...please wait! Chargement... Patientez diff --git a/YACReader/yacreader_it.ts b/YACReader/yacreader_it.ts index f6271e7a2..cdf846cee 100644 --- a/YACReader/yacreader_it.ts +++ b/YACReader/yacreader_it.ts @@ -188,27 +188,23 @@ FileComic - + + Format not supported Formato non supportato - + 7z not found 7z non trovato - + Unknown error opening the file Errore sconosciuto aprendo il file - - Unsupported EPUB: %1 - - - - + CRC error on page (%1): some of the pages will not be displayed correctly Errore CRC alla pagina (%1): alcune pagine non saranno visualizzate correttamente @@ -346,7 +342,7 @@ Cancella - + Comics directory Cartella Fumetti @@ -463,7 +459,7 @@ If none is active, Escape does nothing. Tooltip listing the order in which modes are cancelled. Only the first active mode in the list is cancelled per Escape keypress. Il tasto Esc annulla la prima modalità attiva tra le seguenti: -1. Lente d'ingrandimento +1. Lente d'ingrandimento 2. Dizionario 3. Barra Vai alla pagina 4. Schermo intero @@ -774,48 +770,48 @@ Se non è attiva alcuna modalità, il tasto Esc non esegue alcuna azione. Viewer - + Page not available! Pagina non disponibile! - - + + Press 'O' to open comic. Premi "O" per aprire il fumettto. - + Error opening comic Errore nell'apertura - + Cover! Copertina! - + CRC Error Errore CRC - + Comic not found Fumetto non trovato - + Not found Non trovato - + Last page! Ultima pagina! - + Loading...please wait! In caricamento...Attendi! diff --git a/YACReader/yacreader_ko.ts b/YACReader/yacreader_ko.ts index 475e4c299..4d6e3d09c 100644 --- a/YACReader/yacreader_ko.ts +++ b/YACReader/yacreader_ko.ts @@ -188,30 +188,26 @@ FileComic - + 7z not found 7z를 찾을 수 없습니다 - + CRC error on page (%1): some of the pages will not be displayed correctly %1번 페이지에서 CRC 오류 발생: 일부 페이지가 올바르게 표시되지 않을 수 있습니다 - + Unknown error opening the file 파일을 여는 중 알 수 없는 오류가 발생했습니다 - + + Format not supported 지원하지 않는 형식입니다 - - - Unsupported EPUB: %1 - - GoToDialog @@ -536,7 +532,7 @@ If none is active, Escape does nothing. 재시작이 필요합니다 - + Comics directory 만화 폴더 @@ -774,48 +770,48 @@ If none is active, Escape does nothing. Viewer - - + + Press 'O' to open comic. 'O'를 눌러 만화를 열어보세요. - + Not found 찾을 수 없음 - + Comic not found 만화를 찾을 수 없습니다 - + Error opening comic 만화를 여는 중 오류가 발생했습니다 - + CRC Error CRC 오류 - + Loading...please wait! 불러오는 중... 잠시 기다려주세요! - + Page not available! 페이지를 불러올 수 없습니다! - + Cover! 표지! - + Last page! 마지막 페이지! @@ -1002,12 +998,12 @@ If none is active, Escape does nothing. Extract page(s) - + 페이지 추출 Extract page(s) from the original source - + 원본 소스에서 페이지 추출 @@ -1302,32 +1298,32 @@ If none is active, Escape does nothing. Overwrite file? - + 파일을 덮어쓰시겠습니까? The file already exists. Do you want to overwrite it? - + 파일이 이미 존재합니다. 덮어쓰시겠습니까? The current page could not be extracted. - + 현재 페이지를 추출할 수 없습니다. Overwrite files? - + 파일을 덮어쓰시겠습니까? Some files already exist. Do you want to overwrite them? - + 일부 파일이 이미 존재합니다. 덮어쓰시겠습니까? Some pages could not be extracted. - + 일부 페이지를 추출할 수 없습니다. @@ -1495,12 +1491,12 @@ If none is active, Escape does nothing. Release notes are not available. - + 릴리스 노트를 사용할 수 없습니다. Previous versions - + 이전 버전 diff --git a/YACReader/yacreader_nl.ts b/YACReader/yacreader_nl.ts index 17fd353fb..9f21bbf61 100644 --- a/YACReader/yacreader_nl.ts +++ b/YACReader/yacreader_nl.ts @@ -188,30 +188,26 @@ FileComic - + 7z not found 7Z Archiefbestand niet gevonden - + CRC error on page (%1): some of the pages will not be displayed correctly CRC-fout op pagina (%1): sommige pagina's worden niet correct weergegeven - + Unknown error opening the file Onbekende fout bij het openen van het bestand - + + Format not supported Formaat niet ondersteund - - - Unsupported EPUB: %1 - - GoToDialog @@ -371,7 +367,7 @@ Duidelijk - + Comics directory Strips map @@ -774,48 +770,48 @@ Als geen enkele modus actief is, doet de Escape-toets niets. Viewer - - + + Press 'O' to open comic. Druk 'O' om een strip te openen. - + Cover! Omslag! - + Comic not found Strip niet gevonden - + Not found Niet gevonden - + Last page! Laatste pagina! - + Loading...please wait! Inladen...even wachten! - + Error opening comic Fout bij openen strip - + CRC Error CRC-fout - + Page not available! Pagina niet beschikbaar! diff --git a/YACReader/yacreader_pt.ts b/YACReader/yacreader_pt.ts index 2adf055d5..404ca2f64 100644 --- a/YACReader/yacreader_pt.ts +++ b/YACReader/yacreader_pt.ts @@ -188,30 +188,26 @@ FileComic - + 7z not found 7z não encontrado - + CRC error on page (%1): some of the pages will not be displayed correctly Erro CRC na página (%1): algumas páginas não serão exibidas corretamente - + Unknown error opening the file Erro desconhecido ao abrir o arquivo - + + Format not supported Formato não suportado - - - Unsupported EPUB: %1 - - GoToDialog @@ -316,7 +312,7 @@ Claro - + Comics directory Diretório de quadrinhos @@ -774,48 +770,48 @@ Se nenhum estiver ativo, a tecla Escape não faz nada. Viewer - - + + Press 'O' to open comic. Pressione 'O' para abrir um quadrinho. - + Loading...please wait! Carregando... por favor, aguarde! - + Not found Não encontrado - + Comic not found Quadrinho não encontrado - + Error opening comic Erro ao abrir quadrinho - + CRC Error Erro CRC - + Page not available! Página não disponível! - + Cover! Cobrir! - + Last page! Última página! diff --git a/YACReader/yacreader_ru.ts b/YACReader/yacreader_ru.ts index 25966fa4b..7f19829fe 100644 --- a/YACReader/yacreader_ru.ts +++ b/YACReader/yacreader_ru.ts @@ -188,27 +188,23 @@ FileComic - + + Format not supported Формат не поддерживается - + 7z not found 7z не найден - + Unknown error opening the file Неизвестная ошибка при открытии файла - - Unsupported EPUB: %1 - - - - + CRC error on page (%1): some of the pages will not be displayed correctly Ошибка контрольной суммы CRC на странице (%1): некоторые страницы будут отображаться неправильно @@ -346,7 +342,7 @@ Очистить - + Comics directory Папка комиксов @@ -774,48 +770,48 @@ If none is active, Escape does nothing. Viewer - + Page not available! Страница недоступна! - - + + Press 'O' to open comic. Нажмите "O" чтобы открыть комикс. - + Error opening comic Ошибка открытия комикса - + Cover! Начало! - + CRC Error Ошибка CRC - + Comic not found Комикс не найден - + Not found Не найдено - + Last page! Конец! - + Loading...please wait! Загрузка... Пожалуйста подождите! diff --git a/YACReader/yacreader_source.ts b/YACReader/yacreader_source.ts index b0f23d4a1..1fb32d883 100644 --- a/YACReader/yacreader_source.ts +++ b/YACReader/yacreader_source.ts @@ -184,30 +184,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly - + Unknown error opening the file - + 7z not found - + + Format not supported - - - Unsupported EPUB: %1 - - GoToDialog @@ -525,7 +521,7 @@ If none is active, Escape does nothing. - + Comics directory @@ -760,48 +756,48 @@ If none is active, Escape does nothing. Viewer - - + + Press 'O' to open comic. - + Not found - + Comic not found - + Error opening comic - + CRC Error - + Loading...please wait! - + Page not available! - + Cover! - + Last page! diff --git a/YACReader/yacreader_tr.ts b/YACReader/yacreader_tr.ts index d397cdd45..410cd3f9b 100644 --- a/YACReader/yacreader_tr.ts +++ b/YACReader/yacreader_tr.ts @@ -188,30 +188,26 @@ FileComic - + 7z not found 7z bulunamadı - + CRC error on page (%1): some of the pages will not be displayed correctly (%1). sayfada CRC hatası : bazı sayfalar düzgün görüntülenmeyecek - + Unknown error opening the file Dosya açılırken bilinmeyen hata - + + Format not supported Biçim desteklenmiyor - - - Unsupported EPUB: %1 - - GoToDialog @@ -371,7 +367,7 @@ Temizle - + Comics directory Çizgi roman konumu @@ -774,48 +770,48 @@ Hiçbiri etkin değilse Escape tuşu hiçbir şey yapmaz. Viewer - - + + Press 'O' to open comic. 'O'ya basarak aç. - + Cover! Kapak! - + Comic not found Çizgi roman bulunamadı - + Not found Bulunamadı - + Last page! Son sayfa! - + Loading...please wait! Yükleniyor... lütfen bekleyin! - + Error opening comic Çizgi roman açılırken hata - + CRC Error CRC Hatası - + Page not available! Sayfa bulunamadı! diff --git a/YACReader/yacreader_zh_CN.ts b/YACReader/yacreader_zh_CN.ts index 0a717df42..8c5ea5d41 100644 --- a/YACReader/yacreader_zh_CN.ts +++ b/YACReader/yacreader_zh_CN.ts @@ -188,27 +188,27 @@ FileComic - + + Format not supported 不支持的文件格式 - + 7z not found 未找到 7z - + Unknown error opening the file 打开文件时出现未知错误 - Unsupported EPUB: %1 - 不支持的 EPUB 格式:%1 + 不支持的 EPUB 格式:%1 - + CRC error on page (%1): some of the pages will not be displayed correctly 第 %1 页 CRC 校验失败: 部分页面将无法正确显示 @@ -466,7 +466,7 @@ If none is active, Escape does nothing. 清空 - + Comics directory 漫画目录 @@ -774,48 +774,48 @@ If none is active, Escape does nothing. Viewer - + Page not available! 页面不可用! - - + + Press 'O' to open comic. 按下 'O' 以打开漫画. - + Error opening comic 打开漫画时发生错误 - + Cover! 封面! - + CRC Error CRC 校验失败 - + Comic not found 未找到漫画 - + Not found 未找到 - + Last page! 尾页! - + Loading...please wait! 载入中... 请稍候! diff --git a/YACReader/yacreader_zh_HK.ts b/YACReader/yacreader_zh_HK.ts index 67c895019..512e3cf62 100644 --- a/YACReader/yacreader_zh_HK.ts +++ b/YACReader/yacreader_zh_HK.ts @@ -188,30 +188,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly 第 %1 頁 CRC 校驗失敗: 部分頁面將無法正確顯示 - + Unknown error opening the file 打開檔時出現未知錯誤 - + 7z not found 未找到 7z - + + Format not supported 不支持的檔格式 - - - Unsupported EPUB: %1 - - GoToDialog @@ -536,7 +532,7 @@ If none is active, Escape does nothing. 選項 - + Comics directory 漫畫目錄 @@ -774,48 +770,48 @@ If none is active, Escape does nothing. Viewer - - + + Press 'O' to open comic. 按下 'O' 以打開漫畫. - + Not found 未找到 - + Comic not found 未找到漫畫 - + Error opening comic 打開漫畫時發生錯誤 - + CRC Error CRC 校驗失敗 - + Loading...please wait! 載入中... 請稍候! - + Page not available! 頁面不可用! - + Cover! 封面! - + Last page! 尾頁! diff --git a/YACReader/yacreader_zh_TW.ts b/YACReader/yacreader_zh_TW.ts index 4c7fb9b82..d4001e464 100644 --- a/YACReader/yacreader_zh_TW.ts +++ b/YACReader/yacreader_zh_TW.ts @@ -188,30 +188,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly 第 %1 頁 CRC 校驗失敗: 部分頁面將無法正確顯示 - + Unknown error opening the file 打開檔時出現未知錯誤 - + 7z not found 未找到 7z - + + Format not supported 不支持的檔格式 - - - Unsupported EPUB: %1 - - GoToDialog @@ -536,7 +532,7 @@ If none is active, Escape does nothing. 選項 - + Comics directory 漫畫目錄 @@ -774,48 +770,48 @@ If none is active, Escape does nothing. Viewer - - + + Press 'O' to open comic. 按下 'O' 以打開漫畫. - + Not found 未找到 - + Comic not found 未找到漫畫 - + Error opening comic 打開漫畫時發生錯誤 - + CRC Error CRC 校驗失敗 - + Loading...please wait! 載入中... 請稍候! - + Page not available! 頁面不可用! - + Cover! 封面! - + Last page! 尾頁! diff --git a/YACReaderLibrary/CMakeLists.txt b/YACReaderLibrary/CMakeLists.txt index 803149a7c..805fb58a4 100644 --- a/YACReaderLibrary/CMakeLists.txt +++ b/YACReaderLibrary/CMakeLists.txt @@ -86,6 +86,23 @@ qt_add_executable(YACReaderLibrary WIN32 library_window.cpp library_window_actions.h library_window_actions.cpp + library_window_menus.h + library_window_menus.cpp + library_search_coordinator.h + library_search_coordinator.cpp + comic_management_coordinator.h + comic_management_coordinator.cpp + reading_list_management_coordinator.h + reading_list_management_coordinator.cpp + folder_management_coordinator.h + folder_management_coordinator.cpp + library_database_maintenance_coordinator.h + library_database_maintenance_coordinator.cpp + library_repair_coordinator.h + library_repair_coordinator.cpp + library_management_coordinator.h + library_management_coordinator.cpp + feature_flags.h create_library_dialog.h create_library_dialog.cpp add_library_dialog.h @@ -122,16 +139,17 @@ qt_add_executable(YACReaderLibrary WIN32 yacreader_main_toolbar.cpp comics_view.h comics_view.cpp + content_view_state.h comics_view_transition.h comics_view_transition.cpp classic_comics_view.h classic_comics_view.cpp grid_comics_view.h grid_comics_view.cpp + grid_content_model.h + grid_content_model.cpp no_search_results_widget.h no_search_results_widget.cpp - folder_content_view.h - folder_content_view.cpp recent_visibility_coordinator.h recent_visibility_coordinator.cpp library_comic_opener.h @@ -228,6 +246,7 @@ set(yacreaderlibrary_image_files ${PROJECT_SOURCE_DIR}/images/comics_view_toolbar/getInfo.svg ${PROJECT_SOURCE_DIR}/images/comics_view_toolbar/hideComicFlow.svg ${PROJECT_SOURCE_DIR}/images/comics_view_toolbar/openInYACReader.svg + ${PROJECT_SOURCE_DIR}/images/comics_view_toolbar/organize.svg ${PROJECT_SOURCE_DIR}/images/comics_view_toolbar/selectAll.svg ${PROJECT_SOURCE_DIR}/images/comics_view_toolbar/setReadButton.svg ${PROJECT_SOURCE_DIR}/images/comics_view_toolbar/setUnread.svg @@ -348,7 +367,15 @@ set_source_files_properties( ) set(yacreaderlibrary_qml_files ${CMAKE_CURRENT_SOURCE_DIR}/qml/GridComicsView.qml - ${CMAKE_CURRENT_SOURCE_DIR}/qml/FolderContentView.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/ComicGridDelegate.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/EmptyInfoView.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/FolderCover.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/FolderGridDelegate.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/FolderInfoView.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/SelectedComicsInfoView.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/LibraryInfoView.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/ListInfoView.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/ContinueReadingGridHeader.qml ${CMAKE_CURRENT_SOURCE_DIR}/qml/FlowView.qml ${CMAKE_CURRENT_SOURCE_DIR}/qml/InfoTick.qml ${CMAKE_CURRENT_SOURCE_DIR}/qml/InfoFavorites.qml @@ -370,7 +397,15 @@ set(yacreaderlibrary_qml_files ) set(yacreaderlibrary_qml_translation_files ${CMAKE_CURRENT_SOURCE_DIR}/qml/GridComicsView.qml - ${CMAKE_CURRENT_SOURCE_DIR}/qml/FolderContentView.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/ComicGridDelegate.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/EmptyInfoView.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/FolderCover.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/FolderGridDelegate.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/FolderInfoView.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/SelectedComicsInfoView.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/LibraryInfoView.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/ListInfoView.qml + ${CMAKE_CURRENT_SOURCE_DIR}/qml/ContinueReadingGridHeader.qml ${CMAKE_CURRENT_SOURCE_DIR}/qml/FlowView.qml ${CMAKE_CURRENT_SOURCE_DIR}/qml/InfoTick.qml ${CMAKE_CURRENT_SOURCE_DIR}/qml/InfoFavorites.qml @@ -477,6 +512,7 @@ qt_add_translations(YACReaderLibrary custom_widgets_library shortcuts_library comic_vine + organize_files # Keep extraction scoped to targets used by this app and add the QML files # directly so qsTr() strings in QML are collected too. TS_FILES @@ -520,6 +556,7 @@ target_link_libraries(YACReaderLibrary PRIVATE shortcuts_library server comic_vine + organize_files cbx_backend concurrent_queue worker diff --git a/YACReaderLibrary/Info.plist b/YACReaderLibrary/Info.plist index 44a203e8c..881c7c560 100644 --- a/YACReaderLibrary/Info.plist +++ b/YACReaderLibrary/Info.plist @@ -14,7 +14,7 @@ YACReaderLibrary CFBundleIdentifier com.yacreader.YACReaderLibrary - NOTE - This file was generated by Qt/QMake. + NSSupportsAutomaticGraphicsSwitching + diff --git a/YACReaderLibrary/classic_comics_view.cpp b/YACReaderLibrary/classic_comics_view.cpp index ba7c6a082..98cef21da 100644 --- a/YACReaderLibrary/classic_comics_view.cpp +++ b/YACReaderLibrary/classic_comics_view.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -16,7 +17,7 @@ #include ClassicComicsView::ClassicComicsView(QWidget *parent) - : ComicsView(parent), searching(false) + : ComicsView(parent), toolbar(nullptr), startSeparatorAction(nullptr), searching(false) { auto layout = new QHBoxLayout; @@ -64,6 +65,13 @@ ClassicComicsView::ClassicComicsView(QWidget *parent) connect(tableView, &QAbstractItemView::doubleClicked, this, &ClassicComicsView::selectedComicForOpening); connect(comicFlow, &ComicFlowWidget::centerIndexChanged, this, &ClassicComicsView::updateTableView); connect(tableView, &YACReaderTableView::comicRated, this, &ComicsView::comicRated); + connect(tableView, &YACReaderTableView::customCoverDropped, this, [this](const QString &imagePath, const QModelIndex &index) { + emit customComicCoverRequested(index.data(ComicModel::IdRole).toULongLong(), imagePath); + }); + connect(comicFlow, &ComicFlowWidget::customCoverDropped, this, [this](const QString &imagePath, int index) { + if (model && index >= 0 && index < model->rowCount()) + emit customComicCoverRequested(model->index(index, 0).data(ComicModel::IdRole).toULongLong(), imagePath); + }); connect(comicFlow, &ComicFlowWidget::selected, this, &ComicsView::selected); connect(tableView->horizontalHeader(), &QHeaderView::sectionMoved, this, &ClassicComicsView::saveTableHeadersStatus); connect(tableView->horizontalHeader(), &QHeaderView::sectionResized, this, &ClassicComicsView::saveTableHeadersStatus); @@ -132,10 +140,33 @@ void ClassicComicsView::hideComicFlow(bool hide) void ClassicComicsView::setToolBar(QToolBar *toolBar) { static_cast(comics->layout())->insertWidget(0, toolBar); - this->toolbar = toolBar; + toolbar = toolBar; - startSeparatorAction = toolBar->addSeparator(); - toolBar->addAction(hideFlowViewAction); + if (!startSeparatorAction) { + startSeparatorAction = new QAction(this); + startSeparatorAction->setSeparator(true); + } + + const auto actions = toolbar->actions(); + if (!actions.contains(startSeparatorAction)) + toolbar->addAction(startSeparatorAction); + if (!actions.contains(hideFlowViewAction)) + toolbar->addAction(hideFlowViewAction); +} + +void ClassicComicsView::releaseToolBar() +{ + if (!toolbar) + return; + + toolbar->removeAction(startSeparatorAction); + toolbar->removeAction(hideFlowViewAction); +} + +void ClassicComicsView::saveViewConfig() +{ + saveTableHeadersStatus(); + saveSplitterStatus(); } void ClassicComicsView::setModel(ComicModel *model) @@ -235,6 +266,49 @@ void ClassicComicsView::scrollTo(const QModelIndex &mi, QAbstractItemView::Scrol comicFlow->setCenterIndex(mi.row()); } +ContentViewState ClassicComicsView::captureViewState() const +{ + ContentViewState state; + const auto topIndex = tableView->indexAt(QPoint(0, 0)); + if (topIndex.isValid()) { + state.topItem.kind = ContentItemRef::Comic; + state.topItem.id = topIndex.data(ComicModel::IdRole).toULongLong(); + state.fallbackComicRow = topIndex.row(); + state.offset = -tableView->visualRect(topIndex).top(); + state.itemExtent = tableView->rowHeight(topIndex.row()); + } + + const auto selectedIndex = tableView->currentIndex(); + if (selectedIndex.isValid()) { + state.currentItem.kind = ContentItemRef::Comic; + state.currentItem.id = selectedIndex.data(ComicModel::IdRole).toULongLong(); + } + return state; +} + +void ClassicComicsView::restoreViewState(const ContentViewState &state) +{ + if (!model || model->rowCount() == 0) + return; + + if (state.currentItem.kind == ContentItemRef::Comic) { + const auto current = model->getIndexFromId(state.currentItem.id); + if (current.isValid()) { + tableView->setCurrentIndex(current); + comicFlow->setCenterIndexWithoutAnimation(current.row()); + } + } + + const auto topIndex = state.topItem.kind == ContentItemRef::Comic ? model->getIndexFromId(state.topItem.id) : QModelIndex(); + const auto fallbackRow = qBound(0, state.fallbackComicRow, model->rowCount() - 1); + const auto restoreIndex = topIndex.isValid() ? topIndex : model->index(fallbackRow, 0); + if (restoreIndex.isValid()) { + tableView->scrollTo(restoreIndex, QAbstractItemView::PositionAtTop); + if (state.offset > 0) + tableView->verticalScrollBar()->setValue(tableView->verticalScrollBar()->value() + qRound(state.offset)); + } +} + void ClassicComicsView::toFullScreen() { comicFlow->hide(); @@ -383,12 +457,20 @@ void ClassicComicsView::saveSplitterStatus() void ClassicComicsView::applyModelChanges(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles) { - Q_UNUSED(topLeft); - Q_UNUSED(bottomRight); if (roles.contains(ComicModel::ReadColumnRole)) { comicFlow->setMarks(model->getReadList()); comicFlow->updateMarks(); } + + if (roles.contains(ComicModel::CoverPathRole)) { + const auto centerIndex = comicFlow->centerIndex(); + for (auto row = topLeft.row(); row <= bottomRight.row(); ++row) { + comicFlow->remove(row); + comicFlow->add(model->index(row, 0).data(ComicModel::CoverPathRole).toUrl().toLocalFile(), row); + } + comicFlow->setMarks(model->getReadList()); + comicFlow->setCenterIndexWithoutAnimation(centerIndex); + } } void ClassicComicsView::removeItemsFromFlow(const QModelIndex &parent, int from, int to) @@ -409,11 +491,8 @@ void ClassicComicsView::addItemsToFlow(const QModelIndex &parent, int from, int void ClassicComicsView::closeEvent(QCloseEvent *event) { - toolbar->removeAction(startSeparatorAction); - toolbar->removeAction(hideFlowViewAction); - - saveTableHeadersStatus(); - saveSplitterStatus(); + releaseToolBar(); + saveViewConfig(); ComicsView::closeEvent(event); } diff --git a/YACReaderLibrary/classic_comics_view.h b/YACReaderLibrary/classic_comics_view.h index 836dce9c1..729c1f0d6 100644 --- a/YACReaderLibrary/classic_comics_view.h +++ b/YACReaderLibrary/classic_comics_view.h @@ -27,6 +27,8 @@ class ClassicComicsView : public ComicsView, protected Themable protected: void applyTheme(const Theme &theme) override; void setToolBar(QToolBar *toolBar) override; + void releaseToolBar() override; + void saveViewConfig() override; void setModel(ComicModel *model) override; QModelIndex currentIndex() override; @@ -39,6 +41,8 @@ class ClassicComicsView : public ComicsView, protected Themable void selectIndex(int index) override; void updateCurrentComicView() override; void focusComicsNavigation(Qt::FocusReason reason) override; + ContentViewState captureViewState() const override; + void restoreViewState(const ContentViewState &state) override; public slots: void setCurrentIndex(const QModelIndex &index) override; diff --git a/YACReaderLibrary/comic_files_manager.cpp b/YACReaderLibrary/comic_files_manager.cpp index 9512def19..a71bb2651 100644 --- a/YACReaderLibrary/comic_files_manager.cpp +++ b/YACReaderLibrary/comic_files_manager.cpp @@ -12,19 +12,19 @@ ComicFilesManager::ComicFilesManager(QObject *parent) { } -void ComicFilesManager::copyComicsTo(const QList> &sourceComics, const QString &folderDest, const QModelIndex &dest) +void ComicFilesManager::copyComicsTo(const QList> &sourceComics, const QString &folderDest, qulonglong destinationFolderId) { comics = sourceComics; folder = folderDest; - folderDestinationModelIndex = dest; + this->destinationFolderId = destinationFolderId; move = false; } -void ComicFilesManager::moveComicsTo(const QList> &sourceComics, const QString &folderDest, const QModelIndex &dest) +void ComicFilesManager::moveComicsTo(const QList> &sourceComics, const QString &folderDest, qulonglong destinationFolderId) { comics = sourceComics; folder = folderDest; - folderDestinationModelIndex = dest; + this->destinationFolderId = destinationFolderId; move = true; } @@ -69,7 +69,7 @@ void ComicFilesManager::process() if (canceled) { if (successProcesingFiles) - emit success(folderDestinationModelIndex); + emit success(destinationFolderId); emit finished(); return; // TODO rollback? @@ -91,7 +91,7 @@ void ComicFilesManager::process() } if (successProcesingFiles) - emit success(folderDestinationModelIndex); + emit success(destinationFolderId); emit finished(); } diff --git a/YACReaderLibrary/comic_files_manager.h b/YACReaderLibrary/comic_files_manager.h index 870f85a82..be4931f32 100644 --- a/YACReaderLibrary/comic_files_manager.h +++ b/YACReaderLibrary/comic_files_manager.h @@ -2,9 +2,9 @@ #define COMIC_FILES_MANAGER_H #include -#include #include #include +#include // this class is intended to work in background, just use moveToThread and process to start working class ComicFilesManager : public QObject @@ -12,14 +12,14 @@ class ComicFilesManager : public QObject Q_OBJECT public: explicit ComicFilesManager(QObject *parent = nullptr); - void copyComicsTo(const QList> &sourceComics, const QString &folderDest, const QModelIndex &dest); - void moveComicsTo(const QList> &comics, const QString &folderDest, const QModelIndex &dest); + void copyComicsTo(const QList> &sourceComics, const QString &folderDest, qulonglong destinationFolderId); + void moveComicsTo(const QList> &comics, const QString &folderDest, qulonglong destinationFolderId); static QList> getDroppedFiles(const QList &urls); signals: void currentComic(QString); void progress(int); void finished(); - void success(QModelIndex); // at least one comics has been copied or moved + void success(qulonglong destinationFolderId); // at least one comic has been copied or moved public slots: void process(); void cancel(); @@ -29,7 +29,7 @@ public slots: bool canceled; QList> comics; QString folder; - QModelIndex folderDestinationModelIndex; + qulonglong destinationFolderId = 0; }; #endif // COMIC_FILES_MANAGER_H diff --git a/YACReaderLibrary/comic_flow_widget.cpp b/YACReaderLibrary/comic_flow_widget.cpp index 0c2b603ed..ac0bbed08 100644 --- a/YACReaderLibrary/comic_flow_widget.cpp +++ b/YACReaderLibrary/comic_flow_widget.cpp @@ -1,5 +1,10 @@ #include "comic_flow_widget.h" +#include "cover_utils.h" + +#include +#include +#include #include ComicFlowWidget::ComicFlowWidget(QWidget *parent) @@ -16,6 +21,7 @@ ComicFlowWidget::ComicFlowWidget(QWidget *parent) setLayout(l); setAutoFillBackground(true); + setAcceptDrops(true); initTheme(this); } @@ -92,6 +98,11 @@ void ComicFlowWidget::setCenterIndex(int index) flow->setCenterIndex(index); } +void ComicFlowWidget::setCenterIndexWithoutAnimation(int index) +{ + flow->setCurrentIndexWithoutAnimation(index); +} + void ComicFlowWidget::showSlide(int index) { flow->showSlide(index); @@ -149,6 +160,28 @@ void ComicFlowWidget::mouseDoubleClickEvent(QMouseEvent *event) flow->mouseDoubleClickEvent(event); } +void ComicFlowWidget::dragEnterEvent(QDragEnterEvent *event) +{ + if (event->mimeData()->hasUrls() && !YACReader::droppedImagePath(event->mimeData()->urls()).isEmpty()) { + event->setDropAction(Qt::CopyAction); + event->accept(); + } +} + +void ComicFlowWidget::dropEvent(QDropEvent *event) +{ + const auto imagePath = event->mimeData()->hasUrls() ? YACReader::droppedImagePath(event->mimeData()->urls()) : QString(); + const auto index = centerIndex(); + if (imagePath.isEmpty() || index < 0) { + event->ignore(); + return; + } + + emit customCoverDropped(imagePath, index); + event->setDropAction(Qt::CopyAction); + event->accept(); +} + void ComicFlowWidget::updateConfig(QSettings *settings) { Performance performance = medium; diff --git a/YACReaderLibrary/comic_flow_widget.h b/YACReaderLibrary/comic_flow_widget.h index 175564967..64126c8a3 100644 --- a/YACReaderLibrary/comic_flow_widget.h +++ b/YACReaderLibrary/comic_flow_widget.h @@ -26,6 +26,7 @@ public slots: void clear(); void setImagePaths(QStringList paths); void setCenterIndex(int index); + void setCenterIndexWithoutAnimation(int index); void showSlide(int index); int centerIndex(); void updateMarks(); @@ -39,6 +40,7 @@ public slots: signals: void centerIndexChanged(int); void selected(unsigned int); + void customCoverDropped(const QString &imagePath, int index); protected: void applyTheme(const Theme &theme) override; @@ -47,6 +49,8 @@ public slots: void mousePressEvent(QMouseEvent *event) override; void resizeEvent(QResizeEvent *event) override; void mouseDoubleClickEvent(QMouseEvent *event) override; + void dragEnterEvent(QDragEnterEvent *event) override; + void dropEvent(QDropEvent *event) override; QSize minimumSizeHint() const override; QSize sizeHint() const override; diff --git a/YACReaderLibrary/comic_management_coordinator.cpp b/YACReaderLibrary/comic_management_coordinator.cpp new file mode 100644 index 000000000..6e1ab5dcd --- /dev/null +++ b/YACReaderLibrary/comic_management_coordinator.cpp @@ -0,0 +1,599 @@ +#include "comic_management_coordinator.h" + +#include "api_key_dialog.h" +#include "comic_files_manager.h" +#include "comic_vine_dialog.h" +#include "comics_remover.h" +#include "cover_utils.h" +#include "db_helper.h" +#include "folder_model.h" +#include "initial_comic_info_extractor.h" +#include "library_comic_opener.h" +#include "properties_dialog.h" +#include "reading_list_model.h" +#include "yacreader_global_gui.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#ifdef Q_OS_WIN +#include + +#include +#endif + +namespace { +template +void moveAndConnectRemoverToThread(Remover *remover, QThread *thread) +{ + Q_ASSERT(remover); + Q_ASSERT(thread); + remover->moveToThread(thread); + QObject::connect(thread, &QThread::started, remover, &Remover::process); + QObject::connect(remover, &Remover::finished, remover, &QObject::deleteLater); + QObject::connect(remover, &Remover::finished, thread, &QThread::quit); + QObject::connect(thread, &QThread::finished, thread, &QObject::deleteLater); +} +} + +ComicManagementCoordinator::ComicManagementCoordinator(QWidget *window, + QSettings *settings, + ComicModel *comicsModel, + FolderModel *foldersModel, + FolderModelProxy *foldersModelProxy, + PropertiesDialog *propertiesDialog, + ComicVineDialog *comicVineDialog, + SelectionProvider selectionProvider, + CurrentListProvider currentListProvider, + CurrentFolderProvider currentFolderProvider, + CurrentComicProvider currentComicProvider, + ComicOpeningAllowedProvider comicOpeningAllowedProvider, + LibraryIdProvider libraryIdProvider, + LibraryPathProvider libraryPathProvider) + : QObject(window), window(window), settings(settings), comicsModel(comicsModel), foldersModel(foldersModel), foldersModelProxy(foldersModelProxy), propertiesDialog(propertiesDialog), comicVineDialog(comicVineDialog), selectionProvider(std::move(selectionProvider)), currentListProvider(std::move(currentListProvider)), currentFolderProvider(std::move(currentFolderProvider)), currentComicProvider(std::move(currentComicProvider)), comicOpeningAllowedProvider(std::move(comicOpeningAllowedProvider)), libraryIdProvider(std::move(libraryIdProvider)), libraryPathProvider(std::move(libraryPathProvider)) +{ + connect(propertiesDialog, &PropertiesDialog::coverChangedSignal, comicsModel, &ComicModel::notifyCoverChange); + connect(propertiesDialog, &QDialog::accepted, this, &ComicManagementCoordinator::currentSourceRefreshAccepted); + connect(propertiesDialog, &QDialog::rejected, this, &ComicManagementCoordinator::currentSourceRefreshCancelled); + connect(comicVineDialog, &QDialog::accepted, this, &ComicManagementCoordinator::currentSourceRefreshAccepted, Qt::QueuedConnection); + connect(comicVineDialog, &QDialog::rejected, this, &ComicManagementCoordinator::currentSourceRefreshCancelled); +} + +void ComicManagementCoordinator::copyAndImportComicsToCurrentFolder(const QList> &comics) +{ + copyAndImportComics(comics, currentFolderProvider(), libraryPathProvider()); +} + +void ComicManagementCoordinator::moveAndImportComicsToCurrentFolder(const QList> &comics) +{ + moveAndImportComics(comics, currentFolderProvider(), libraryPathProvider()); +} + +void ComicManagementCoordinator::copyAndImportComicsToFolder(const QList> &comics, const QModelIndex &folder) +{ + const auto destinationFolder = foldersModelProxy->mapToSource(folder); + if (destinationFolder.isValid()) + copyAndImportComics(comics, destinationFolder, libraryPathProvider()); +} + +void ComicManagementCoordinator::moveAndImportComicsToFolder(const QList> &comics, const QModelIndex &folder) +{ + const auto destinationFolder = foldersModelProxy->mapToSource(folder); + if (destinationFolder.isValid()) + moveAndImportComics(comics, destinationFolder, libraryPathProvider()); +} + +void ComicManagementCoordinator::addSelectedComicsToFavorites() +{ + comicsModel->addComicsToFavorites(selectionProvider()); +} + +void ComicManagementCoordinator::addSelectedComicsToLabel(qulonglong labelId) +{ + comicsModel->addComicsToLabel(selectionProvider(), labelId); +} + +void ComicManagementCoordinator::openCurrentComic() +{ + if (!comicOpeningAllowedProvider()) + return; + + const auto currentComic = currentComicProvider(); + if (!currentComic.isValid()) + return; + + openComic(comicsModel->getComic(currentComic), comicsModel->getMode()); +} + +void ComicManagementCoordinator::openComic(const ComicDB &comic, ComicModel::Mode mode) +{ + const auto source = mode == ComicModel::ReadingList + ? OpenComicSource::Source::ReadingList + : OpenComicSource::Source::Folder; + const auto libraryPath = libraryPathProvider(); + const auto thirdPartyReaderCommand = settings->value(THIRD_PARTY_READER_COMMAND, "").toString(); + + if (thirdPartyReaderCommand.isEmpty()) { + const auto yacreaderFound = YACReader::openComic(comic, libraryIdProvider(), libraryPath, OpenComicSource { source, comicsModel->getSourceId() }); + if (!yacreaderFound) { +#ifdef Q_OS_WIN + QMessageBox::critical(window, tr("YACReader not found"), tr("YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary.")); +#else + QMessageBox::critical(window, tr("YACReader not found"), tr("YACReader not found. There might be a problem with your YACReader installation.")); +#endif + } + return; + } + + if (!YACReader::openComicInThirdPartyApp(thirdPartyReaderCommand, QDir::cleanPath(libraryPath + comic.path))) + QMessageBox::critical(window, tr("Error"), tr("Error opening comic with third party reader.")); +} + +void ComicManagementCoordinator::openContainingFolderOfCurrentComic() +{ + const auto currentComic = currentComicProvider(); + if (!currentComic.isValid()) + return; + + const QFileInfo file(QDir::cleanPath(libraryPathProvider() + comicsModel->getComicPath(currentComic))); +#if defined Q_OS_UNIX && !defined Q_OS_MACOS + QDesktopServices::openUrl(QUrl("file:///" + file.absolutePath(), QUrl::TolerantMode)); +#endif + +#ifdef Q_OS_MACOS + // `open -R` reveals and selects the file in Finder without sending an Apple + // Event, so it doesn't trigger the macOS automation permission prompt. + QStringList arguments; + arguments << "-R"; + arguments << file.absoluteFilePath(); + QProcess::startDetached("open", arguments); +#endif + +#ifdef Q_OS_WIN + const auto cmdArgs = QString("/select,\"") + QDir::toNativeSeparators(file.absoluteFilePath()) + QStringLiteral("\""); + ShellExecuteW(0, L"open", L"explorer.exe", reinterpret_cast(cmdArgs.utf16()), 0, SW_NORMAL); +#endif +} + +void ComicManagementCoordinator::showComicVineScraper() +{ + QSettings comicVineSettings(YACReader::getSettingsPath() + "/YACReaderLibrary.ini", QSettings::IniFormat); // TODO unificar la creación del fichero de config con el servidor + comicVineSettings.beginGroup("ComicVine"); + + if (!comicVineSettings.contains(COMIC_VINE_API_KEY)) { + ApiKeyDialog dialog; + dialog.exec(); + } + + if (!comicVineSettings.contains(COMIC_VINE_API_KEY)) + return; + + const auto comics = comicsModel->getComics(selectionProvider()); + comicVineDialog->databasePath = foldersModel->getDatabase(); + comicVineDialog->basePath = libraryPathProvider(); + comicVineDialog->setComics(comics); + + emit currentSourceRefreshStarted(); + comicVineDialog->show(); +} + +void ComicManagementCoordinator::copyAndImportComics(const QList> &comics, + const QModelIndex &destinationFolder, + const QString &libraryPath) +{ + if (comics.isEmpty()) + return; + + const auto destinationPath = QDir::cleanPath(libraryPath + foldersModel->getFolderPath(destinationFolder)); + const auto destinationFolderId = destinationFolder.data(FolderModel::IdRole).toULongLong(); + QLOG_DEBUG() << "Copying comics to" << destinationPath; + auto progressDialog = newProgressDialog(QCoreApplication::translate("LibraryWindow", "Copying comics..."), comics.size()); + auto comicFilesManager = new ComicFilesManager; + comicFilesManager->copyComicsTo(comics, destinationPath, destinationFolderId); + processComicFiles(comicFilesManager, progressDialog); +} + +void ComicManagementCoordinator::moveAndImportComics(const QList> &comics, + const QModelIndex &destinationFolder, + const QString &libraryPath) +{ + if (comics.isEmpty()) + return; + + const auto destinationPath = QDir::cleanPath(libraryPath + foldersModel->getFolderPath(destinationFolder)); + const auto destinationFolderId = destinationFolder.data(FolderModel::IdRole).toULongLong(); + QLOG_DEBUG() << "Moving comics to" << destinationPath; + auto progressDialog = newProgressDialog(QCoreApplication::translate("LibraryWindow", "Moving comics..."), comics.size()); + auto comicFilesManager = new ComicFilesManager; + comicFilesManager->moveComicsTo(comics, destinationPath, destinationFolderId); + processComicFiles(comicFilesManager, progressDialog); +} + +void ComicManagementCoordinator::showProperties() +{ + const auto indexList = selectionProvider(); + const auto comics = comicsModel->getComics(indexList); + if (comics.isEmpty()) + return; + + propertiesDialog->databasePath = foldersModel->getDatabase(); + propertiesDialog->basePath = libraryPathProvider(); + + if (indexList.length() > 1) { + propertiesDialog->setComics(comics); + } else { + const auto allComics = comicsModel->getAllComics(); + propertiesDialog->setComicsForSequentialEditing(allComics.indexOf(comics.constFirst()), allComics); + } + + emit currentSourceRefreshStarted(); + propertiesDialog->show(); +} + +void ComicManagementCoordinator::setSelectedComicsRead() +{ + comicsModel->setComicsRead(selectionProvider(), YACReader::Read); + emit currentComicViewUpdateRequested(); +} + +void ComicManagementCoordinator::setSelectedComicsUnread() +{ + comicsModel->setComicsRead(selectionProvider(), YACReader::Unread); + emit currentComicViewUpdateRequested(); +} + +void ComicManagementCoordinator::setComicUnread(qulonglong libraryId, const ComicDB &comic) +{ + auto info = comic.info; + info.setRead(false); + info.currentPage = 1; + info.hasBeenOpened = false; + info.lastTimeOpened = QVariant(); + DBHelper::update(libraryId, info); + emit rootContinueReadingReloadRequested(); +} + +void ComicManagementCoordinator::setSelectedComicsType(YACReader::FileType type) +{ + comicsModel->setComicsType(selectionProvider(), type); +} + +void ComicManagementCoordinator::resetSelectedComicRatings() +{ + const auto indexList = selectionProvider(); + comicsModel->startTransaction(); + for (const auto &index : indexList) + comicsModel->resetComicRating(index); + comicsModel->finishTransaction(); +} + +void ComicManagementCoordinator::assignNumbers() +{ + const auto selectedIds = selectedComicIds(); + if (selectedIds.isEmpty()) + return; + + const auto source = currentSource(); + const auto initialIndexes = indexesForComicIds(selectedIds, source); + if (initialIndexes.isEmpty()) + return; + + int startingNumber = initialIndexes.constFirst().row() + 1; + if (initialIndexes.count() > 1) { + bool accepted; + startingNumber = QInputDialog::getInt(window, + QCoreApplication::translate("LibraryWindow", "Assign comics numbers"), + QCoreApplication::translate("LibraryWindow", "Assign numbers starting in:"), + startingNumber, + 0, + 2147483647, + 1, + &accepted); + if (!accepted) + return; + } + + const auto indexList = indexesForComicIds(selectedIds, source); + if (indexList.isEmpty()) + return; + + emit comicNumbersAssigned(comicsModel->asignNumbers(indexList, startingNumber)); +} + +void ComicManagementCoordinator::deleteMetadataFromSelectedComics() +{ + auto comics = comicsModel->getComics(selectionProvider()); + if (comics.isEmpty()) + return; + + for (auto &comic : comics) + comic.info.deleteMetadata(); + + DBHelper::updateComicsInfo(comics, foldersModel->getDatabase()); + comicsModel->reload(); +} + +void ComicManagementCoordinator::deleteSelectedComics() +{ + const auto comicIds = selectedComicIds(); + if (comicIds.isEmpty()) + return; + + const auto source = currentSource(); + const auto listIndex = currentListProvider(); + if (listIndex.isValid()) { + deleteComicsFromList(comicIds, + source, + listIndex.data(ReadingListModel::TypeListsRole).toInt(), + listIndex.data(ReadingListModel::IDRole).toULongLong()); + } else { + deleteComicsFromDisk(comicIds, source); + } +} + +void ComicManagementCoordinator::saveSelectedCoversTo() +{ + const auto comicIds = selectedComicIds(); + if (comicIds.isEmpty()) + return; + + const auto source = currentSource(); + const auto destinationFolder = QFileDialog::getExistingDirectory(window, + QCoreApplication::translate("LibraryWindow", "Save covers"), + QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)); + if (destinationFolder.isEmpty()) + return; + + const auto indexList = indexesForComicIds(comicIds, source); + for (const auto &comic : indexList) { + QString origin = comic.data(ComicModel::CoverPathRole).toString().remove("file:///").remove("file:"); + const auto destination = QDir(destinationFolder).filePath(comic.data(ComicModel::FileNameRole).toString() + ".jpg"); + + QLOG_DEBUG() << "From : " << origin; + QLOG_DEBUG() << "To : " << destination; + + QFile::copy(origin, destination); + } +} + +void ComicManagementCoordinator::setCustomCover(qulonglong comicId, const QString &imagePath) +{ + if (!comicOpeningAllowedProvider()) + return; + + const auto index = comicsModel->getIndexFromId(comicId); + if (!index.isValid()) + return; + + const QImage cover(imagePath); + if (cover.isNull()) { + QMessageBox::warning(window, + QCoreApplication::translate("LibraryWindow", "Invalid image"), + QCoreApplication::translate("LibraryWindow", "The selected file is not a valid image.")); + return; + } + + auto comic = comicsModel->getComic(index); + const auto coverPath = YACReader::LibraryPaths::coverPath(libraryPathProvider(), comic.info.hash); + if (!YACReader::saveCover(coverPath, cover)) { + QMessageBox::warning(window, + QCoreApplication::translate("LibraryWindow", "Error saving cover"), + QCoreApplication::translate("LibraryWindow", "There was an error saving the cover image.")); + return; + } + + comic.info.coverPage = QVariant(); + comic.info.originalCoverSize = QStringLiteral("%1x%2").arg(cover.width()).arg(cover.height()); + comic.info.coverSizeRatio = static_cast(cover.width()) / cover.height(); + comic.info.lastTimeCoverSet = QDateTime::currentSecsSinceEpoch(); + comic.info.usesExternalCover = true; + DBHelper::update(libraryIdProvider(), comic.info); + comicsModel->notifyCoverChange(comic); +} + +bool ComicManagementCoordinator::hasCustomCoverInSelection() const +{ + const auto comics = comicsModel->getComics(selectionProvider()); + return std::any_of(comics.cbegin(), comics.cend(), [](const ComicDB &comic) { + return comic.info.usesExternalCover.toBool(); + }); +} + +void ComicManagementCoordinator::resetSelectedCustomCovers() +{ + if (!comicOpeningAllowedProvider()) + return; + + const auto libraryPath = libraryPathProvider(); + const auto libraryId = libraryIdProvider(); + const auto indexes = selectionProvider(); + for (const auto &index : indexes) { + auto comic = comicsModel->getComic(index); + if (!comic.info.usesExternalCover.toBool()) + continue; + + YACReader::InitialComicInfoExtractor extractor(QDir::cleanPath(libraryPath + comic.path), QString(), 1); + extractor.extract(); + if (!extractor.hasValidCover()) + continue; + + const auto cover = extractor.getCoverImage(); + const auto coverPath = YACReader::LibraryPaths::coverPath(libraryPath, comic.info.hash); + if (!YACReader::saveCover(coverPath, cover)) + continue; + + const auto originalCoverSize = extractor.getOriginalCoverSize(); + comic.info.coverPage = QVariant(); + comic.info.originalCoverSize = QStringLiteral("%1x%2").arg(originalCoverSize.first).arg(originalCoverSize.second); + comic.info.coverSizeRatio = static_cast(originalCoverSize.first) / originalCoverSize.second; + comic.info.lastTimeCoverSet = QDateTime::currentSecsSinceEpoch(); + comic.info.usesExternalCover = false; + DBHelper::update(libraryId, comic.info); + comicsModel->notifyCoverChange(comic); + } +} + +QProgressDialog *ComicManagementCoordinator::newProgressDialog(const QString &label, int maximum) +{ + auto progressDialog = new QProgressDialog(label, QStringLiteral("Cancel"), 0, maximum, window); + progressDialog->setWindowModality(Qt::WindowModal); + progressDialog->setMinimumWidth(350); + progressDialog->show(); + return progressDialog; +} + +void ComicManagementCoordinator::processComicFiles(ComicFilesManager *comicFilesManager, QProgressDialog *progressDialog) +{ + connect(comicFilesManager, &ComicFilesManager::progress, progressDialog, &QProgressDialog::setValue); + + auto thread = new QThread; + comicFilesManager->moveToThread(thread); + + connect(progressDialog, &QProgressDialog::canceled, comicFilesManager, &ComicFilesManager::cancel, Qt::DirectConnection); + connect(thread, &QThread::started, comicFilesManager, &ComicFilesManager::process); + connect(comicFilesManager, &ComicFilesManager::success, this, &ComicManagementCoordinator::importRequested); + connect(comicFilesManager, &ComicFilesManager::finished, thread, &QThread::quit); + connect(comicFilesManager, &ComicFilesManager::finished, comicFilesManager, &QObject::deleteLater); + connect(comicFilesManager, &ComicFilesManager::finished, progressDialog, &QWidget::close); + connect(comicFilesManager, &ComicFilesManager::finished, progressDialog, &QObject::deleteLater); + connect(thread, &QThread::finished, thread, &QObject::deleteLater); + + thread->start(); +} + +QList ComicManagementCoordinator::selectedComicIds() const +{ + QList comicIds; + const auto selection = selectionProvider(); + comicIds.reserve(selection.size()); + for (const auto &index : selection) + comicIds.append(index.data(ComicModel::IdRole).toULongLong()); + return comicIds; +} + +ComicManagementCoordinator::SourceContext ComicManagementCoordinator::currentSource() const +{ + return { libraryPathProvider(), static_cast(comicsModel->getMode()), comicsModel->getSourceId() }; +} + +QModelIndexList ComicManagementCoordinator::indexesForComicIds(const QList &comicIds, const SourceContext &source) const +{ + if (!isCurrentSource(source)) + return { }; + + auto indexes = comicsModel->getIndexesFromIds(comicIds); + if (std::any_of(indexes.cbegin(), indexes.cend(), [](const QModelIndex &index) { return !index.isValid(); })) + return { }; + + std::sort(indexes.begin(), indexes.end(), [](const QModelIndex &left, const QModelIndex &right) { + return left.row() < right.row(); + }); + return indexes; +} + +bool ComicManagementCoordinator::isCurrentSource(const SourceContext &source) const +{ + return QDir::cleanPath(foldersModel->getDatabase()) == QDir::cleanPath(YACReader::LibraryPaths::libraryDataPath(source.libraryPath)) && static_cast(comicsModel->getMode()) == source.mode && comicsModel->getSourceId() == source.sourceId; +} + +void ComicManagementCoordinator::deleteComicsFromDisk(const QList &comicIds, const SourceContext &source) +{ + const auto answer = QMessageBox::question(window, + QCoreApplication::translate("LibraryWindow", "Delete comics"), + QCoreApplication::translate("LibraryWindow", "All the selected comics will be deleted from your disk. Are you sure?"), + QMessageBox::Yes, + QMessageBox::No); + if (answer != QMessageBox::Yes) + return; + + auto indexList = indexesForComicIds(comicIds, source); + auto comics = comicsModel->getComics(indexList); + if (comics.isEmpty()) + return; + + QList paths; + paths.reserve(comics.size()); + for (const auto &comic : std::as_const(comics)) { + paths.append(source.libraryPath + comic.path); + QLOG_TRACE() << comic.path; + QLOG_TRACE() << comic.id; + QLOG_TRACE() << comic.parentId; + } + + auto remover = new ComicsRemover(indexList, paths, comics.constFirst().parentId); + auto thread = new QThread(this); + moveAndConnectRemoverToThread(remover, thread); + + comicDeletionFailed = false; + comicsModel->startTransaction(); + + connect(remover, &ComicsRemover::remove, comicsModel, &ComicModel::remove); + connect(remover, &ComicsRemover::removeError, this, [this] { comicDeletionFailed = true; }); + connect(remover, &ComicsRemover::finished, comicsModel, &ComicModel::finishTransaction); + connect(remover, &ComicsRemover::removedItemsFromFolder, foldersModel, &FolderModel::updateFolderChildrenInfo); + connect(remover, &ComicsRemover::finished, this, &ComicManagementCoordinator::finishComicDeletion); + + thread->start(); +} + +void ComicManagementCoordinator::deleteComicsFromList(const QList &comicIds, const SourceContext &source, int listType, qulonglong listId) +{ + const auto answer = QMessageBox::question(window, + QCoreApplication::translate("LibraryWindow", "Remove comics"), + QCoreApplication::translate("LibraryWindow", "Comics will only be deleted from the current label/list. Are you sure?"), + QMessageBox::Yes, + QMessageBox::No); + if (answer != QMessageBox::Yes) + return; + + const auto currentList = currentListProvider(); + if (!currentList.isValid() || currentList.data(ReadingListModel::TypeListsRole).toInt() != listType || currentList.data(ReadingListModel::IDRole).toULongLong() != listId) + return; + + const auto indexList = indexesForComicIds(comicIds, source); + if (indexList.isEmpty()) + return; + + switch (static_cast(listType)) { + case ReadingListModel::SpecialList: + comicsModel->deleteComicsFromSpecialList(indexList, listId); + break; + case ReadingListModel::Label: + comicsModel->deleteComicsFromLabel(indexList, listId); + break; + case ReadingListModel::ReadingList: + comicsModel->deleteComicsFromReadingList(indexList, listId); + break; + case ReadingListModel::Separator: + break; + } +} + +void ComicManagementCoordinator::finishComicDeletion() +{ + emit comicDeletionFinished(); + if (comicDeletionFailed) { + QMessageBox::critical(window, + QCoreApplication::translate("LibraryWindow", "Unable to delete"), + QCoreApplication::translate("LibraryWindow", "There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder.")); + } + comicDeletionFailed = false; +} diff --git a/YACReaderLibrary/comic_management_coordinator.h b/YACReaderLibrary/comic_management_coordinator.h new file mode 100644 index 000000000..ebaf0be66 --- /dev/null +++ b/YACReaderLibrary/comic_management_coordinator.h @@ -0,0 +1,130 @@ +#ifndef COMIC_MANAGEMENT_COORDINATOR_H +#define COMIC_MANAGEMENT_COORDINATOR_H + +#include "comic_model.h" +#include "yacreader_global.h" + +#include +#include +#include +#include +#include + +#include + +class ComicFilesManager; +class ComicDB; +class ComicVineDialog; +class FolderModel; +class FolderModelProxy; +class PropertiesDialog; +class QProgressDialog; +class QSettings; +class QWidget; + +class ComicManagementCoordinator : public QObject +{ + Q_OBJECT + +public: + using SelectionProvider = std::function; + using CurrentListProvider = std::function; + using CurrentFolderProvider = std::function; + using CurrentComicProvider = std::function; + using ComicOpeningAllowedProvider = std::function; + using LibraryIdProvider = std::function; + using LibraryPathProvider = std::function; + + explicit ComicManagementCoordinator(QWidget *window, + QSettings *settings, + ComicModel *comicsModel, + FolderModel *foldersModel, + FolderModelProxy *foldersModelProxy, + PropertiesDialog *propertiesDialog, + ComicVineDialog *comicVineDialog, + SelectionProvider selectionProvider, + CurrentListProvider currentListProvider, + CurrentFolderProvider currentFolderProvider, + CurrentComicProvider currentComicProvider, + ComicOpeningAllowedProvider comicOpeningAllowedProvider, + LibraryIdProvider libraryIdProvider, + LibraryPathProvider libraryPathProvider); + + bool hasCustomCoverInSelection() const; + +public slots: + void copyAndImportComicsToCurrentFolder(const QList> &comics); + void moveAndImportComicsToCurrentFolder(const QList> &comics); + void copyAndImportComicsToFolder(const QList> &comics, const QModelIndex &folder); + void moveAndImportComicsToFolder(const QList> &comics, const QModelIndex &folder); + void addSelectedComicsToFavorites(); + void addSelectedComicsToLabel(qulonglong labelId); + void openCurrentComic(); + void openComic(const ComicDB &comic, ComicModel::Mode mode); + void openContainingFolderOfCurrentComic(); + void showComicVineScraper(); + void showProperties(); + void setSelectedComicsRead(); + void setSelectedComicsUnread(); + void setSelectedComicsType(YACReader::FileType type); + void resetSelectedComicRatings(); + void assignNumbers(); + void deleteMetadataFromSelectedComics(); + void deleteSelectedComics(); + void saveSelectedCoversTo(); + void setCustomCover(qulonglong comicId, const QString &imagePath); + void resetSelectedCustomCovers(); + + void setComicUnread(qulonglong libraryId, const ComicDB &comic); + +signals: + void importRequested(qulonglong destinationFolderId); + void currentComicViewUpdateRequested(); + void currentSourceRefreshStarted(); + void currentSourceRefreshAccepted(); + void currentSourceRefreshCancelled(); + void comicNumbersAssigned(qint64 editedComicId); + void comicDeletionFinished(); + void rootContinueReadingReloadRequested(); + +private: + struct SourceContext { + QString libraryPath; + int mode; + qulonglong sourceId; + }; + + QProgressDialog *newProgressDialog(const QString &label, int maximum); + void copyAndImportComics(const QList> &comics, + const QModelIndex &destinationFolder, + const QString &libraryPath); + void moveAndImportComics(const QList> &comics, + const QModelIndex &destinationFolder, + const QString &libraryPath); + void processComicFiles(ComicFilesManager *comicFilesManager, QProgressDialog *progressDialog); + QList selectedComicIds() const; + SourceContext currentSource() const; + QModelIndexList indexesForComicIds(const QList &comicIds, const SourceContext &source) const; + bool isCurrentSource(const SourceContext &source) const; + void deleteComicsFromDisk(const QList &comicIds, const SourceContext &source); + void deleteComicsFromList(const QList &comicIds, const SourceContext &source, int listType, qulonglong listId); + void finishComicDeletion(); + + QWidget *window; + QSettings *settings; + ComicModel *comicsModel; + FolderModel *foldersModel; + FolderModelProxy *foldersModelProxy; + PropertiesDialog *propertiesDialog; + ComicVineDialog *comicVineDialog; + SelectionProvider selectionProvider; + CurrentListProvider currentListProvider; + CurrentFolderProvider currentFolderProvider; + CurrentComicProvider currentComicProvider; + ComicOpeningAllowedProvider comicOpeningAllowedProvider; + LibraryIdProvider libraryIdProvider; + LibraryPathProvider libraryPathProvider; + bool comicDeletionFailed { false }; +}; + +#endif // COMIC_MANAGEMENT_COORDINATOR_H diff --git a/YACReaderLibrary/comic_vine/comic_vine_all_volume_comics_retriever.cpp b/YACReaderLibrary/comic_vine/comic_vine_all_volume_comics_retriever.cpp index 6e5092d38..77d46923f 100644 --- a/YACReaderLibrary/comic_vine/comic_vine_all_volume_comics_retriever.cpp +++ b/YACReaderLibrary/comic_vine/comic_vine_all_volume_comics_retriever.cpp @@ -7,6 +7,8 @@ #include #include +#include + ComicVineAllVolumeComicsRetriever::ComicVineAllVolumeComicsRetriever(const QString &volumeURLString, const QString &userAgent, QObject *parent) : QObject(parent), volumeURLString(volumeURLString), userAgent(userAgent) { @@ -54,7 +56,7 @@ QString ComicVineAllVolumeComicsRetriever::consolidateJSON() QJsonObject consolidatedJSON; QJsonArray comicsInfo; - for (const auto &json : jsonResponses) { + for (const auto &json : std::as_const(jsonResponses)) { QJsonDocument doc = QJsonDocument::fromJson(json); if (doc.isNull() || !doc.isObject() || doc.isEmpty()) { diff --git a/YACReaderLibrary/comic_vine/comic_vine_dialog.cpp b/YACReaderLibrary/comic_vine/comic_vine_dialog.cpp index ff4910e32..2e68974ec 100644 --- a/YACReaderLibrary/comic_vine/comic_vine_dialog.cpp +++ b/YACReaderLibrary/comic_vine/comic_vine_dialog.cpp @@ -110,8 +110,6 @@ void ComicVineDialog::doConnections() connect(selectVolumeWidget, &SelectVolume::loadPage, this, &ComicVineDialog::searchVolume); connect(selectComicWidget, &SelectComic::loadPage, this, &ComicVineDialog::getVolumeComicsInfo); connect(sortVolumeComicsWidget, &SortVolumeComics::loadPage, this, &ComicVineDialog::getVolumeComicsInfo); - - connect(this, &QDialog::accepted, this, &QWidget::close, Qt::QueuedConnection); } void ComicVineDialog::goNext() @@ -463,7 +461,7 @@ void ComicVineDialog::getComicsInfo(QList> matchingInfo, DBHelper::updateComicsInfo(comics, databasePath); - emit accepted(); + finishSuccessfully(); } void ComicVineDialog::getComicInfo(const QString &comicId, const SelectedVolumeInfo &volumeInfo) @@ -474,12 +472,11 @@ void ComicVineDialog::getComicInfo(const QString &comicId, const SelectedVolumeI bool timeout; QByteArray result = comicVineClient->getComicDetail(comicId, error, timeout); // TODO check timeOut or Connection error if (error || timeout) { - // TODO - if (mode == ScraperMode::SingleComic || currentIndex == (comics.count() - 1)) { - emit accepted(); - } else { + if (mode == ScraperMode::SingleComic || currentIndex == (comics.count() - 1)) + finishSuccessfully(); + else goToNextComic(); - } + return; } ComicDB comic = YACReader::parseCVJSONComicInfo(comics[currentIndex], result, volumeInfo); // TODO check result error @@ -499,7 +496,7 @@ void ComicVineDialog::getComicInfo(const QString &comicId, const SelectedVolumeI QSqlDatabase::removeDatabase(connectionName); if (mode == ScraperMode::SingleComic || currentIndex == (comics.count() - 1)) { - emit accepted(); + finishSuccessfully(); } else { goToNextComic(); } @@ -535,7 +532,7 @@ QString ComicVineDialog::volumeSearchStringFromComic(const ComicDB &comic) void ComicVineDialog::goToNextComic() { if (mode == ScraperMode::SingleComic || currentIndex == (comics.count() - 1)) { - emit accepted(); + finishSuccessfully(); return; } @@ -554,6 +551,16 @@ void ComicVineDialog::clearState() selectVolumeWidget->clearFilter(); } +void ComicVineDialog::finishSuccessfully() +{ + // Scraping completion may be reported from a worker thread. Complete the + // dialog through QDialog's canonical success path on the GUI thread so it + // closes and emits accepted exactly once. + QMetaObject::invokeMethod(this, [this]() { + clearState(); + accept(); }, Qt::QueuedConnection); +} + void ComicVineDialog::showLoading(const QString &message) { content->setCurrentIndex(0); diff --git a/YACReaderLibrary/comic_vine/comic_vine_dialog.h b/YACReaderLibrary/comic_vine/comic_vine_dialog.h index ecd4485b6..547bbfc5b 100644 --- a/YACReaderLibrary/comic_vine/comic_vine_dialog.h +++ b/YACReaderLibrary/comic_vine/comic_vine_dialog.h @@ -68,6 +68,7 @@ protected slots: private: void clearState(); + void finishSuccessfully(); void toggleSkipButton(); QString volumeSearchStringFromComic(const ComicDB &comic); diff --git a/YACReaderLibrary/comic_vine/model/local_comic_list_model.h b/YACReaderLibrary/comic_vine/model/local_comic_list_model.h index dd2cde968..620a47bf6 100644 --- a/YACReaderLibrary/comic_vine/model/local_comic_list_model.h +++ b/YACReaderLibrary/comic_vine/model/local_comic_list_model.h @@ -17,7 +17,7 @@ class LocalComicListModel : public QAbstractItemModel QModelIndex parent(const QModelIndex &index) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent) const override; - QVariant data(const QModelIndex &index, int role) const; + QVariant data(const QModelIndex &index, int role) const override; Qt::ItemFlags flags(const QModelIndex &index) const override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; diff --git a/YACReaderLibrary/comics_view.cpp b/YACReaderLibrary/comics_view.cpp index 149b2057f..1cbb1f9c6 100644 --- a/YACReaderLibrary/comics_view.cpp +++ b/YACReaderLibrary/comics_view.cpp @@ -8,6 +8,8 @@ #include #include +#include + ComicsView::ComicsView(QWidget *parent) : QWidget(parent), model(nullptr), comicDB(nullptr) { @@ -20,13 +22,13 @@ ComicsView::ComicsView(QWidget *parent) view->setResizeMode(QQuickWidget::SizeRootObjectToView); connect( view, &QQuickWidget::statusChanged, this, - [=](QQuickWidget::Status status) { + [=, this](QQuickWidget::Status status) { if (status == QQuickWidget::Error) { QLOG_ERROR() << view->errors(); } }); - auto comicDB = new ComicDB(); + comicDB = new ComicDB(); auto comicInfo = &(comicDB->info); QQmlContext *ctxt = view->rootContext(); @@ -55,8 +57,10 @@ void ComicsView::updateInfoForIndex(int index) { QQmlContext *ctxt = view->rootContext(); - if (comicDB != nullptr) - delete comicDB; + // Clear the member before destroying the object. Deleting ComicDB notifies + // QML and can re-enter this method; an invalid index must also not leave a + // dangling pointer that is deleted again when the next comic is selected. + delete std::exchange(comicDB, nullptr); if ((index < 0) || (index >= model->rowCount())) { ctxt->setContextProperty("comic", nullptr); diff --git a/YACReaderLibrary/comics_view.h b/YACReaderLibrary/comics_view.h index 22ab71e38..cd7ca632b 100644 --- a/YACReaderLibrary/comics_view.h +++ b/YACReaderLibrary/comics_view.h @@ -2,6 +2,7 @@ #define COMICS_VIEW_H #include "comic_model.h" +#include "content_view_state.h" #include #include @@ -20,6 +21,8 @@ class ComicsView : public QWidget public: explicit ComicsView(QWidget *parent = nullptr); virtual void setToolBar(QToolBar *toolBar) = 0; + virtual void releaseToolBar() = 0; + virtual void saveViewConfig() { } virtual void setModel(ComicModel *model); virtual void setCurrentIndex(const QModelIndex &index) = 0; virtual QModelIndex currentIndex() = 0; @@ -33,6 +36,8 @@ class ComicsView : public QWidget virtual void updateCurrentComicView() = 0; virtual void focusComicsNavigation(Qt::FocusReason reason) = 0; virtual void reloadContent(); + virtual ContentViewState captureViewState() const { return { }; } + virtual void restoreViewState(const ContentViewState &state) { Q_UNUSED(state); } public slots: virtual void updateInfoForIndex(int index); @@ -51,6 +56,8 @@ public slots: // Drops void copyComicsToCurrentFolder(QList>); void moveComicsToCurrentFolder(QList>); + void customComicCoverRequested(qulonglong comicId, const QString &imagePath); + void customFolderCoverRequested(qulonglong folderId, const QString &imagePath); protected: ComicModel *model; diff --git a/YACReaderLibrary/content_view_state.h b/YACReaderLibrary/content_view_state.h new file mode 100644 index 000000000..399262aed --- /dev/null +++ b/YACReaderLibrary/content_view_state.h @@ -0,0 +1,26 @@ +#ifndef CONTENT_VIEW_STATE_H +#define CONTENT_VIEW_STATE_H + +#include + +struct ContentItemRef { + enum Kind { + None, + Comic, + Folder, + Header + }; + + Kind kind = None; + qulonglong id = 0; +}; + +struct ContentViewState { + ContentItemRef topItem; + int fallbackComicRow = -1; + qreal offset = 0; + qreal itemExtent = 0; + ContentItemRef currentItem; +}; + +#endif // CONTENT_VIEW_STATE_H diff --git a/YACReaderLibrary/db/comic_model.cpp b/YACReaderLibrary/db/comic_model.cpp index 0368175f1..bcaab8543 100644 --- a/YACReaderLibrary/db/comic_model.cpp +++ b/YACReaderLibrary/db/comic_model.cpp @@ -15,6 +15,8 @@ #include #include +#include + #ifdef use_unarr #include #endif @@ -61,14 +63,18 @@ bool ComicModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, i // TODO: optimize this method (seriously) bool ComicModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { - - QAbstractItemModel::dropMimeData(data, action, row, column, parent); QLOG_TRACE() << ">>>>>>>>>>>>>>dropMimeData ComicModel<<<<<<<<<<<<<<<<<" << parent << row << "," << column; - if (!data->formats().contains(YACReader::YACReaderLibrarComiscSelectionMimeDataFormat)) + if (!canDropMimeData(data, action, row, column, parent)) return false; const QList comicIds = YACReader::mimeDataToComicsIds(data); + if (comicIds.isEmpty()) + return false; + + if (row < 0 || row > _data.count()) + row = _data.count(); + QList currentIndexes; int i; { @@ -85,6 +91,9 @@ bool ComicModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int } } + if (currentIndexes.size() != comicIds.size()) + return false; + std::sort(currentIndexes.begin(), currentIndexes.end()); QList resortedData; @@ -132,26 +141,24 @@ bool ComicModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int int tempRow = row; - if (tempRow < 0) - tempRow = _data.count(); - for (const auto id : comicIds) { int i = 0; const auto dataSnapshot = _data; for (auto *item : dataSnapshot) { if (item->data(Id) == id) { - beginMoveRows(parent, i, i, parent, tempRow); - - bool skipElement = i == tempRow || i + 1 == tempRow; + const bool skipElement = i == tempRow || i + 1 == tempRow; if (!skipElement) { + if (!beginMoveRows(parent, i, i, parent, tempRow)) + return false; + if (i > tempRow) _data.move(i, tempRow); else _data.move(i, tempRow - 1); - } - endMoveRows(); + endMoveRows(); + } if (i > tempRow) tempRow++; @@ -327,9 +334,13 @@ QVariant ComicModel::data(const QModelIndex &index, int role) const return item->data(FileName); else if (role == RatingRole) return item->data(Rating); - else if (role == CoverPathRole) - return getCoverUrlPathForComicHash(item->data(Hash).toString()); - else if (role == NumPagesRole) + else if (role == CoverPathRole) { + auto coverUrl = getCoverUrlPathForComicHash(item->data(Hash).toString()); + const auto revision = coverRevisions.value(item->data(Id).toULongLong()); + if (revision > 0) + coverUrl.setQuery(QStringLiteral("revision=%1").arg(revision)); + return coverUrl; + } else if (role == NumPagesRole) return item->data(NumPages); else if (role == CurrentPageRole) return item->data(CurrentPage); @@ -339,6 +350,8 @@ QVariant ComicModel::data(const QModelIndex &index, int role) const return item->data(HasBeenOpened); else if (role == IdRole) return item->data(Id); + else if (role == HashRole) + return item->data(Hash); else if (role == PublicationDateRole) return QVariant(localizedDate(item->data(PublicationDate).toString())); else if (role == AddedRole) @@ -1224,20 +1237,16 @@ void ComicModel::resetComicRating(const QModelIndex &mi) void ComicModel::notifyCoverChange(const ComicDB &comic) { auto it = std::find_if(_data.begin(), _data.end(), [comic](ComicItem *item) { return item->data(ComicModel::Id).toULongLong() == comic.id; }); - auto itemIndex = std::distance(_data.begin(), it); - auto item = _data[itemIndex]; - - // emiting a dataChage doesn't work in QML for some reason, CoverPathRole is requested but the view doesn't update the image - // removing and reading again works with the flow views without any additional code, but it's not the best solution - beginRemoveRows(QModelIndex(), itemIndex, itemIndex); - _data.removeAt(itemIndex); - endRemoveRows(); - - beginInsertRows(QModelIndex(), itemIndex, itemIndex); - _data.insert(itemIndex, item); - endInsertRows(); + if (it == _data.end()) + return; - // this doesn't work in QML -> emit dataChanged(index(itemIndex, 0), index(itemIndex, 0), QVector() << CoverPathRole); + // Keep cover changes non-structural. Removing and reinserting the row makes + // views adjust their selection and scroll position before the edit refresh can + // capture them. Changing the URL also makes QML reload the image even though + // the underlying cover file path is unchanged. + ++coverRevisions[comic.id]; + const auto itemIndex = std::distance(_data.begin(), it); + emit dataChanged(index(itemIndex, 0), index(itemIndex, columnCount() - 1), { CoverPathRole }); } QUrl ComicModel::getCoverUrlPathForComicHash(const QString &hash) const @@ -1262,6 +1271,12 @@ void ComicModel::addComicsToFavorites(const QList &comicsList) connectionName = db.connectionName(); } QSqlDatabase::removeDatabase(connectionName); + + QList comicIds; + comicIds.reserve(comics.size()); + for (const auto &comic : std::as_const(comics)) + comicIds.append(comic.id); + emit favoritesChanged(comicIds); } void ComicModel::addComicsToLabel(const QList &comicIds, qulonglong labelId) @@ -1312,6 +1327,12 @@ void ComicModel::deleteComicsFromFavorites(const QList &comicsList) } QSqlDatabase::removeDatabase(connectionName); + QList comicIds; + comicIds.reserve(comics.size()); + for (const auto &comic : std::as_const(comics)) + comicIds.append(comic.id); + emit favoritesChanged(comicIds); + if (mode == Favorites) deleteComicsFromModel(comicsList); } diff --git a/YACReaderLibrary/db/comic_model.h b/YACReaderLibrary/db/comic_model.h index 9426ed57b..c996bd93d 100644 --- a/YACReaderLibrary/db/comic_model.h +++ b/YACReaderLibrary/db/comic_model.h @@ -4,6 +4,7 @@ #include "yacreader_global.h" #include +#include #include #include #include @@ -173,6 +174,7 @@ public slots: protected: private: + QHash coverRevisions; QList createModelData(QSqlQuery &sqlquery) const; QList createModelDataForList(QSqlQuery &sqlquery) const; @@ -201,6 +203,7 @@ public slots: signals: void isEmpty(); + void favoritesChanged(const QList &comicIds); void searchNumResults(int); void resortedIndexes(QList); void newSelectedIndex(const QModelIndex &); diff --git a/YACReaderLibrary/db/comic_query_result_processor.cpp b/YACReaderLibrary/db/comic_query_result_processor.cpp index 6d473c358..65d289119 100644 --- a/YACReaderLibrary/db/comic_query_result_processor.cpp +++ b/YACReaderLibrary/db/comic_query_result_processor.cpp @@ -17,7 +17,7 @@ void YACReader::ComicQueryResultProcessor::createModelData(const QString &filter { querySearchQueue.cancelPending(); - querySearchQueue.enqueue([=] { + querySearchQueue.enqueue([=, this] { QString connectionName = ""; { QSqlDatabase db = DataBaseManagement::loadDatabase(databasePath); diff --git a/YACReaderLibrary/db/data_base_management.cpp b/YACReaderLibrary/db/data_base_management.cpp index fe3f3bedc..ee4adfc55 100644 --- a/YACReaderLibrary/db/data_base_management.cpp +++ b/YACReaderLibrary/db/data_base_management.cpp @@ -10,6 +10,8 @@ #include #include +#include + #ifdef Q_OS_WIN #include #else @@ -857,8 +859,6 @@ void DataBaseManagement::exportComicsInfo(QString source, QString dest) // TODO_METADATA: validate imported info bool DataBaseManagement::importComicsInfo(QString source, QString dest) { - QString error; - QString driver; QStringList hashes; bool b = false; @@ -1293,10 +1293,10 @@ int DataBaseManagement::compareVersions(const QString &v1, const QString v2) QList v1il; QList v2il; - for (const auto &s : v1l) + for (const auto &s : std::as_const(v1l)) v1il.append(s.toInt()); - for (const auto &s : v2l) + for (const auto &s : std::as_const(v2l)) v2il.append(s.toInt()); for (int i = 0; i < qMin(v1il.length(), v2il.length()); i++) { @@ -1943,8 +1943,9 @@ DatabaseSalvageResult DataBaseManagement::salvageLibrary(const QString &libraryP connectionName = db.connectionName(); if (db.isOpen()) { QSqlQuery reindex(db); - if (!reindex.exec("REINDEX")) + if (!reindex.exec("REINDEX")) { QLOG_INFO() << "REINDEX did not complete during salvage:" << reindex.lastError().text(); + } } } if (!connectionName.isEmpty()) diff --git a/YACReaderLibrary/db/folder_model.cpp b/YACReaderLibrary/db/folder_model.cpp index 3048f60fd..8ade93f03 100644 --- a/YACReaderLibrary/db/folder_model.cpp +++ b/YACReaderLibrary/db/folder_model.cpp @@ -7,8 +7,10 @@ #include "qnaturalsorting.h" #include "yacreader_global.h" +#include #include #include +#include #include #include @@ -51,8 +53,6 @@ QIcon drawFinishedFolderIcon(const QPixmap &overlay) return finishedIcon; } -#define ROOT 1 - struct FolderColumns { int name; int path; @@ -123,14 +123,14 @@ FolderItem *createRoot(QSqlDatabase &db) data[0] = "root"; auto root = new FolderItem(data); - root->id = ROOT; + root->id = FolderModel::RootFolderId; root->parentItem = nullptr; return root; } FolderModel::FolderModel(QObject *parent) - : QAbstractItemModel(parent), isSubfolder(false), rootItem(nullptr), showRecent(false), recentDays(1) + : QAbstractItemModel(parent), rootItem(nullptr), showRecent(false), recentDays(1) { initTheme(this); } @@ -190,49 +190,19 @@ void FolderModel::reload() if (rootItem == nullptr) return; - if (!isSubfolder) { - auto newModelData = createModelData(_databasePath); - - takeUpdatedChildrenInfo(rootItem, QModelIndex(), newModelData.rootItem); - - // copy items from newModelData to this model that are not in this model - for (const auto key : newModelData.items.keys()) { - if (!items.contains(key)) { - items[key] = (newModelData.items[key]); - } - } - - delete newModelData.rootItem; - } else { - QString connectionName = ""; - { - QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath); - - QSqlQuery selectQuery(db); - selectQuery.prepare("SELECT * FROM folder WHERE parentId = :parentId and id <> 1"); - selectQuery.bindValue(":parentId", rootItem->id); - selectQuery.exec(); - - auto tempRoot = new FolderItem(rootItem->getData(), rootItem->parentItem); - tempRoot->id = rootItem->id; - auto newModelData = createModelData(selectQuery, tempRoot); - takeUpdatedChildrenInfo(rootItem, QModelIndex(), newModelData.rootItem); - - items = newModelData.items; - - // copy items from newModelData to this model that are not in this model - for (const auto key : newModelData.items.keys()) { - if (!items.contains(key)) { - items[key] = (newModelData.items[key]); - } - } + auto newModelData = createModelData(_databasePath); - delete newModelData.rootItem; + takeUpdatedChildrenInfo(rootItem, QModelIndex(), newModelData.rootItem); - connectionName = db.connectionName(); + // copy items from newModelData to this model that are not in this model + const auto newItemKeys = newModelData.items.keys(); + for (const auto key : newItemKeys) { + if (!items.contains(key)) { + items[key] = (newModelData.items[key]); } - QSqlDatabase::removeDatabase(connectionName); } + + delete newModelData.rootItem; } void FolderModel::takeUpdatedChildrenInfo(FolderItem *parent, const QModelIndex &parentModelIndex, FolderItem *updated) @@ -327,7 +297,7 @@ void FolderModel::takeUpdatedChildrenInfo(FolderItem *parent, const QModelIndex } } -Folder FolderModel::folderFromItem(FolderItem *folderItem) +Folder FolderModel::folderFromItem(FolderItem *folderItem) const { auto name = folderItem->data(FolderModel::Name).toString(); auto parentItem = folderItem->parent(); @@ -601,6 +571,9 @@ QString FolderModel::getFolderPath(const QModelIndex &folder) void FolderModel::updateFolderCompletedStatus(const QModelIndexList &list, bool status) { + if (list.isEmpty()) + return; + QString connectionName = ""; { QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath); @@ -609,22 +582,24 @@ void FolderModel::updateFolderCompletedStatus(const QModelIndexList &list, bool auto item = static_cast(mi.internalPointer()); item->setData(FolderModel::Completed, status); - if (!isSubfolder) { - Folder f = DBHelper::loadFolder(item->id, db); - f.completed = status; - DBHelper::update(f, db); - } + Folder f = DBHelper::loadFolder(item->id, db); + f.completed = status; + DBHelper::update(f, db); } db.commit(); connectionName = db.connectionName(); } QSqlDatabase::removeDatabase(connectionName); - emit dataChanged(index(list.first().row(), FolderModel::Name), index(list.last().row(), FolderModel::Updated)); + const auto parent = list.first().parent(); + emit dataChanged(index(list.first().row(), FolderModel::Name, parent), index(list.last().row(), FolderModel::Updated, parent)); } void FolderModel::updateFolderFinishedStatus(const QModelIndexList &list, bool status) { + if (list.isEmpty()) + return; + QString connectionName = ""; { QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath); @@ -633,22 +608,24 @@ void FolderModel::updateFolderFinishedStatus(const QModelIndexList &list, bool s auto item = static_cast(mi.internalPointer()); item->setData(FolderModel::Finished, status); - if (!isSubfolder) { - Folder f = DBHelper::loadFolder(item->id, db); - f.finished = status; - DBHelper::update(f, db); - } + Folder f = DBHelper::loadFolder(item->id, db); + f.finished = status; + DBHelper::update(f, db); } db.commit(); connectionName = db.connectionName(); } QSqlDatabase::removeDatabase(connectionName); - emit dataChanged(index(list.first().row(), FolderModel::Name), index(list.last().row(), FolderModel::Updated)); + const auto parent = list.first().parent(); + emit dataChanged(index(list.first().row(), FolderModel::Name, parent), index(list.last().row(), FolderModel::Updated, parent)); } void FolderModel::updateFolderType(const QModelIndexList &list, YACReader::FileType type) { + if (list.isEmpty()) + return; + QString connectionName = ""; { QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath); @@ -660,23 +637,93 @@ void FolderModel::updateFolderType(const QModelIndexList &list, YACReader::FileT setType = [&setType](FolderItem *item, YACReader::FileType type) -> void { item->setData(FolderModel::Type, QVariant::fromValue(type)); - for (auto child : item->children()) { + const auto children = item->children(); + for (auto child : children) { setType(child, type); } }; setType(item, type); - if (!isSubfolder) { - DBHelper::updateFolderTreeType(item->id, db, type); - } + DBHelper::updateFolderTreeType(item->id, db, type); } db.commit(); connectionName = db.connectionName(); } QSqlDatabase::removeDatabase(connectionName); - emit dataChanged(index(list.first().row(), FolderModel::Name), index(list.last().row(), FolderModel::Updated)); + const auto parent = list.first().parent(); + emit dataChanged(index(list.first().row(), FolderModel::Name, parent), index(list.last().row(), FolderModel::Updated, parent)); +} + +bool FolderModel::renameFolder(const QModelIndex &folder, const QString &name, QString *error) +{ + if (!folder.isValid()) + return false; + + auto item = static_cast(folder.internalPointer()); + const auto oldPath = item->data(FolderModel::Path).toString(); + const auto parentPath = item->parent()->data(FolderModel::Path).toString(); + const auto newPath = QDir::cleanPath(parentPath + "/" + name); + + QString connectionName; + bool success = false; + { + QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath); + connectionName = db.connectionName(); + + if (!db.isValid() || !db.isOpen()) { + if (error != nullptr) + *error = db.lastError().text(); + } else if (!db.transaction()) { + if (error != nullptr) + *error = db.lastError().text(); + } else if (!DBHelper::renameFolder(item->id, name, oldPath, newPath, db, error)) { + db.rollback(); + } else if (!db.commit()) { + if (error != nullptr) + *error = db.lastError().text(); + db.rollback(); + } else { + success = true; + } + } + QSqlDatabase::removeDatabase(connectionName); + + if (!success) + return false; + + item->setData(FolderModel::Name, name); + + const auto updatePath = [&oldPath, &newPath](auto &&self, FolderItem *folderItem) -> void { + const auto path = folderItem->data(FolderModel::Path).toString(); + folderItem->setData(FolderModel::Path, newPath + path.mid(oldPath.size())); + const auto children = folderItem->children(); + for (auto child : children) + self(self, child); + }; + updatePath(updatePath, item); + + auto parentItem = item->parent(); + const auto oldRow = item->row(); + auto newRow = 0; + const auto siblings = parentItem->children(); + for (auto sibling : siblings) { + if (sibling != item && !naturalSortLessThanCI(name, sibling->data(FolderModel::Name).toString())) + ++newRow; + } + + if (newRow != oldRow) { + const auto destination = newRow > oldRow ? newRow + 1 : newRow; + beginMoveRows(folder.parent(), oldRow, oldRow, folder.parent(), destination); + parentItem->removeChild(item); + parentItem->appendChild(item); + endMoveRows(); + } + + const auto renamedIndex = index(item->row(), FolderModel::Name, folder.parent()); + emit dataChanged(renamedIndex, index(item->row(), FolderModel::Path, folder.parent())); + return true; } void FolderModel::updateTreeType(YACReader::FileType type) @@ -692,16 +739,15 @@ void FolderModel::updateTreeType(YACReader::FileType type) setType = [&setType](FolderItem *item, YACReader::FileType type) -> void { item->setData(FolderModel::Type, QVariant::fromValue(type)); - for (auto child : item->children()) { + const auto children = item->children(); + for (auto child : children) { setType(child, type); } }; setType(item, type); - if (!isSubfolder) { - DBHelper::updateDBType(db, type); - } + DBHelper::updateDBType(db, type); db.commit(); connectionName = db.connectionName(); } @@ -727,7 +773,8 @@ void FolderModel::setCustomFolderCover(const QModelIndex &index, const QString & } QSqlDatabase::removeDatabase(connectionName); - emit dataChanged(index, index); + ++coverRevisions[index.data(FolderModel::IdRole).toULongLong()]; + emit dataChanged(index, index, { CoverPathRole }); } void FolderModel::resetFolderCover(const QModelIndex &index) @@ -776,50 +823,7 @@ QStringList FolderModel::getSubfoldersNames(const QModelIndex &mi) return result; } -FolderModel *FolderModel::getSubfoldersModel(const QModelIndex &mi) -{ - qulonglong id = 1; - FolderItem *parent = nullptr; - if (mi.isValid()) { - auto item = static_cast(mi.internalPointer()); - parent = new FolderItem(item->getData(), item->parent()); - id = parent->id = item->id; - } - - if (id == 1) { - if (parent != nullptr) { - delete parent; - } - return this; - } - - auto model = new FolderModel(); - - QString connectionName = ""; - { - QSqlDatabase db = DataBaseManagement::loadDatabase(_databasePath); - - QSqlQuery selectQuery(db); // TODO check - selectQuery.prepare("SELECT * FROM folder WHERE parentId = :parentId and id <> 1"); - selectQuery.bindValue(":parentId", id); - selectQuery.exec(); - - if (parent != nullptr) { - model->setModelData(createModelData(selectQuery, parent)); - } - - connectionName = db.connectionName(); - } - QSqlDatabase::removeDatabase(connectionName); - - model->_databasePath = _databasePath; - - model->isSubfolder = true; - - return model; -} - -Folder FolderModel::getRootFolder() +Folder FolderModel::getRootFolder() const { if (this->rootItem == nullptr) { return Folder(); @@ -828,7 +832,7 @@ Folder FolderModel::getRootFolder() return folderFromItem(this->rootItem); } -Folder FolderModel::getFolder(const QModelIndex &mi) +Folder FolderModel::getFolder(const QModelIndex &mi) const { if (!mi.isValid()) { return Folder(); @@ -936,7 +940,11 @@ QUrl FolderModel::getCoverUrlPathForComicHash(const QString &hash) const QUrl FolderModel::getCoverUrlPathForFolderId(qulonglong folderId) const { auto coverPath = LibraryPaths::customFolderCoverPathFromDataPath(_databasePath, QString::number(folderId)); - return QUrl::fromLocalFile(coverPath); + auto coverUrl = QUrl::fromLocalFile(coverPath); + const auto revision = coverRevisions.value(folderId); + if (revision > 0) + coverUrl.setQuery(QStringLiteral("revision=%1").arg(revision)); + return coverUrl; } void FolderModel::setShowRecent(bool showRecent) @@ -946,7 +954,7 @@ void FolderModel::setShowRecent(bool showRecent) this->showRecent = showRecent; - emit dataChanged(index(0, 0), index(rowCount() - 1, 0), { FolderModel::ShowRecentRole }); + emitDataChangedRecursively({ }, FolderModel::ShowRecentRole); } void FolderModel::setRecentRange(int days) @@ -956,7 +964,18 @@ void FolderModel::setRecentRange(int days) this->recentDays = days; - emit dataChanged(index(0, 0), index(rowCount() - 1, 0), { FolderModel::RecentRangeRole }); + emitDataChangedRecursively({ }, FolderModel::RecentRangeRole); +} + +void FolderModel::emitDataChangedRecursively(const QModelIndex &parent, int role) +{ + const auto rows = rowCount(parent); + if (rows == 0) + return; + + emit dataChanged(index(0, 0, parent), index(rows - 1, 0, parent), { role }); + for (int row = 0; row < rows; ++row) + emitDataChangedRecursively(index(row, 0, parent), role); } void FolderModel::deleteFolder(const QModelIndex &mi) diff --git a/YACReaderLibrary/db/folder_model.h b/YACReaderLibrary/db/folder_model.h index f1cf381ba..28c4b31a1 100644 --- a/YACReaderLibrary/db/folder_model.h +++ b/YACReaderLibrary/db/folder_model.h @@ -7,6 +7,7 @@ #include "yacreader_global.h" #include +#include #include #include #include @@ -44,6 +45,8 @@ class FolderModel : public QAbstractItemModel, protected Themable friend class YACReader::FolderQueryResultProcessor; public: + static constexpr qulonglong RootFolderId = 1; + explicit FolderModel(QObject *parent = nullptr); ~FolderModel() override; @@ -70,15 +73,15 @@ class FolderModel : public QAbstractItemModel, protected Themable void updateFolderCompletedStatus(const QModelIndexList &list, bool status); void updateFolderFinishedStatus(const QModelIndexList &list, bool status); void updateFolderType(const QModelIndexList &list, YACReader::FileType type); + bool renameFolder(const QModelIndex &folder, const QString &name, QString *error = nullptr); void updateTreeType(YACReader::FileType type); void setCustomFolderCover(const QModelIndex &index, const QString &path); void resetFolderCover(const QModelIndex &index); QStringList getSubfoldersNames(const QModelIndex &mi); - FolderModel *getSubfoldersModel(const QModelIndex &mi); // it creates a model that contains just the direct subfolders - Folder getRootFolder(); - Folder getFolder(const QModelIndex &mi); + Folder getRootFolder() const; + Folder getFolder(const QModelIndex &mi) const; QModelIndex getIndexFromFolderId(qulonglong folderId, const QModelIndex &parent = QModelIndex()); QModelIndex getIndexFromFolder(const Folder &folder, const QModelIndex &parent = QModelIndex()); @@ -117,12 +120,13 @@ class FolderModel : public QAbstractItemModel, protected Themable RecentRangeRole, }; - bool isSubfolder; public slots: void deleteFolder(const QModelIndex &mi); void updateFolderChildrenInfo(qulonglong folderId); private: + void emitDataChangedRecursively(const QModelIndex &parent, int role); + struct ModelData { FolderItem *rootItem; // items tree QMap items; // items lookup @@ -135,7 +139,7 @@ public slots: // parent contains the current data in the model (parentModelIndex is its index), updated contains fresh info loaded from the DB, void takeUpdatedChildrenInfo(FolderItem *parent, const QModelIndex &parentModelIndex, FolderItem *updated); - Folder folderFromItem(FolderItem *item); + Folder folderFromItem(FolderItem *item) const; FolderItem *rootItem; // items tree QMap items; // items lookup @@ -147,6 +151,7 @@ public slots: bool showRecent; qlonglong recentDays; + QHash coverRevisions; protected: void applyTheme(const Theme &theme) override; diff --git a/YACReaderLibrary/db/folder_query_result_processor.cpp b/YACReaderLibrary/db/folder_query_result_processor.cpp index 6ce4705c7..751aca9dd 100644 --- a/YACReaderLibrary/db/folder_query_result_processor.cpp +++ b/YACReaderLibrary/db/folder_query_result_processor.cpp @@ -21,7 +21,7 @@ void YACReader::FolderQueryResultProcessor::createModelData(const QString &filte { querySearchQueue.cancelPending(); - querySearchQueue.enqueue([=] { + querySearchQueue.enqueue([=, this] { QString connectionName = ""; { QSqlDatabase db = DataBaseManagement::loadDatabase(model->getDatabase()); diff --git a/YACReaderLibrary/db_helper.cpp b/YACReaderLibrary/db_helper.cpp index 469c05f2e..6dda78507 100644 --- a/YACReaderLibrary/db_helper.cpp +++ b/YACReaderLibrary/db_helper.cpp @@ -24,6 +24,7 @@ #include #include +#include using namespace YACReader; @@ -1416,6 +1417,196 @@ void DBHelper::updateComicsInfo(QList &comics, const QString &databaseP QSqlDatabase::removeDatabase(connectionName); } +bool DBHelper::renameFolder(qulonglong id, const QString &name, const QString &oldPath, const QString &newPath, QSqlDatabase &db, QString *error) +{ + if (error != nullptr) + error->clear(); + + const auto execute = [error](QSqlQuery &query) { + if (query.exec()) + return true; + + if (error != nullptr) + *error = query.lastError().text(); + return false; + }; + + QSqlQuery renameFolder(db); + renameFolder.prepare("UPDATE folder SET name = :name, path = :newPath WHERE id = :id AND path = :oldPath"); + renameFolder.bindValue(":name", name); + renameFolder.bindValue(":newPath", newPath); + renameFolder.bindValue(":id", id); + renameFolder.bindValue(":oldPath", oldPath); + if (!execute(renameFolder) || renameFolder.numRowsAffected() != 1) { + if (error != nullptr && error->isEmpty()) + *error = QCoreApplication::translate("DBHelper", "The folder entry could not be found in the library database."); + return false; + } + + QSqlQuery updateSubfolders(db); + updateSubfolders.prepare("UPDATE folder SET path = :newPath || substr(path, length(:oldPath) + 1) " + "WHERE substr(path, 1, length(:oldPath) + 1) = :oldPath || '/'"); + updateSubfolders.bindValue(":newPath", newPath); + updateSubfolders.bindValue(":oldPath", oldPath); + if (!execute(updateSubfolders)) + return false; + + QSqlQuery updateComics(db); + updateComics.prepare("UPDATE comic SET path = :newPath || substr(path, length(:oldPath) + 1) " + "WHERE substr(path, 1, length(:oldPath) + 1) = :oldPath || '/'"); + updateComics.bindValue(":newPath", newPath); + updateComics.bindValue(":oldPath", oldPath); + return execute(updateComics); +} + +bool DBHelper::moveComic(qulonglong comicId, qulonglong newParentId, const QString &newFileName, const QString &newRelativePath, QSqlDatabase &db) +{ + QSqlQuery query(db); + query.prepare("UPDATE comic SET parentId = :parentId, fileName = :fileName, path = :path WHERE id = :id"); + query.bindValue(":parentId", newParentId); + query.bindValue(":fileName", newFileName); + query.bindValue(":path", newRelativePath); + query.bindValue(":id", comicId); + + return query.exec() && query.numRowsAffected() == 1; +} + +qulonglong DBHelper::ensureFolderPath(const QString &relativePath, QSqlDatabase &db, QList *createdFolderIds) +{ + const auto segments = relativePath.split('/', Qt::SkipEmptyParts); + + qulonglong parentId = 1; + auto inheritedType = DBHelper::loadFolder(parentId, db).type; + QString currentPath; + + for (const auto &segment : segments) { + currentPath += '/' + segment; + + const auto existing = DBHelper::loadFolder(segment, parentId, db); + if (existing.knownId) { + parentId = existing.id; + inheritedType = existing.type; + continue; + } + + Folder folder(segment, currentPath); + folder.setFather(parentId); + folder.type = inheritedType; + + parentId = DBHelper::insert(&folder, db); + if (createdFolderIds != nullptr) + createdFolderIds->append(parentId); + } + + return parentId; +} + +void DBHelper::syncFolderAddedFromContents(const QList &folderIds, QSqlDatabase &db) +{ + QSqlQuery query(db); + query.prepare("UPDATE folder SET added = COALESCE(" + "(SELECT MIN(ci.added) FROM comic c INNER JOIN comic_info ci ON c.comicInfoId = ci.id WHERE c.parentId = folder.id), added) " + "WHERE id = :id"); + + for (const auto id : folderIds) { + query.bindValue(":id", id); + if (!query.exec()) { + QLOG_ERROR() << "syncFolderAddedFromContents: update failed for folder" << id << query.lastError().text(); + } + } +} + +void DBHelper::removeEmptyFolderPaths(const QStringList &relativePaths, QSqlDatabase &db, QList *removedRows) +{ + QSqlQuery select(db); + select.prepare("SELECT * FROM folder WHERE path = :path AND id <> 1" + " AND NOT EXISTS (SELECT 1 FROM comic WHERE comic.parentId = folder.id)" + " AND NOT EXISTS (SELECT 1 FROM folder AS child WHERE child.parentId = folder.id)"); + + QSqlQuery remove(db); + remove.prepare("DELETE FROM folder WHERE id = :id"); + + for (const auto &path : relativePaths) { + select.bindValue(":path", path); + if (!select.exec()) { + QLOG_ERROR() << "removeEmptyFolderPaths: select failed for" << path << select.lastError().text(); + continue; + } + + if (!select.next()) + continue; + + const auto record = select.record(); + + QVariantMap row; + for (int i = 0; i < record.count(); ++i) + row.insert(record.fieldName(i), record.value(i)); + + remove.bindValue(":id", row.value(QStringLiteral("id"))); + if (!remove.exec()) { + QLOG_ERROR() << "removeEmptyFolderPaths: delete failed for" << path << remove.lastError().text(); + continue; + } + + if (removedRows != nullptr) + removedRows->append(row); + } +} + +void DBHelper::removeEmptyFolderRows(const QList &folderIds, QSqlDatabase &db) +{ + QSqlQuery remove(db); + remove.prepare("DELETE FROM folder WHERE id = :id AND id <> 1" + " AND NOT EXISTS (SELECT 1 FROM comic WHERE comic.parentId = folder.id)" + " AND NOT EXISTS (SELECT 1 FROM folder AS child WHERE child.parentId = folder.id)"); + + for (const auto id : folderIds) { + remove.bindValue(":id", id); + if (!remove.exec()) { + QLOG_ERROR() << "removeEmptyFolderRows: delete failed for folder" << id << remove.lastError().text(); + } + } +} + +bool DBHelper::restoreFolderRows(const QList &rows, QSqlDatabase &db) +{ + // A child cannot be inserted before its parent, because parentId is a foreign + // key into the same table. + auto ordered = rows; + std::sort(ordered.begin(), ordered.end(), [](const QVariantMap &a, const QVariantMap &b) { + return a.value(QStringLiteral("path")).toString().count(QLatin1Char('/')) < b.value(QStringLiteral("path")).toString().count(QLatin1Char('/')); + }); + + bool success = true; + + for (const auto &row : std::as_const(ordered)) { + if (row.value(QStringLiteral("id")).toULongLong() == 0) + continue; + + QStringList columns; + QStringList placeholders; + for (auto it = row.constBegin(); it != row.constEnd(); ++it) { + columns << it.key(); + placeholders << QLatin1Char(':') + it.key(); + } + + QSqlQuery insert(db); + insert.prepare(QStringLiteral("INSERT OR IGNORE INTO folder (%1) VALUES (%2)") + .arg(columns.join(QStringLiteral(", ")), placeholders.join(QStringLiteral(", ")))); + + for (auto it = row.constBegin(); it != row.constEnd(); ++it) + insert.bindValue(QLatin1Char(':') + it.key(), it.value()); + + if (!insert.exec()) { + QLOG_ERROR() << "restoreFolderRows: insert failed for" + << row.value(QStringLiteral("path")).toString() << insert.lastError().text(); + success = false; + } + } + + return success; +} + // inserts qulonglong DBHelper::insert(Folder *folder, QSqlDatabase &db) { @@ -2182,15 +2373,14 @@ bool DBHelper::isFavoriteComic(qulonglong id, QSqlDatabase &db) return false; } -QString DBHelper::getLibraryInfo(QUuid id) +QVariantMap DBHelper::getLibraryInfoData(QUuid id) { - QString info; - QString libraryPath = DBHelper::getLibraries().getPath(id); - - info = "Library path:
" + libraryPath + "

"; + const QString libraryPath = DBHelper::getLibraries().getPath(id); + QVariantMap info { + { QStringLiteral("path"), libraryPath }, + }; QString connectionName = ""; - QList list; { QSqlDatabase db = DataBaseManagement::loadDatabase(LibraryPaths::libraryDataPath(libraryPath)); connectionName = db.connectionName(); @@ -2198,22 +2388,29 @@ QString DBHelper::getLibraryInfo(QUuid id) // num folders auto foldersQuery = db.exec("SELECT COUNT(*) FROM folder WHERE id <> 1"); foldersQuery.next(); - - info += "Number of folders:
" + foldersQuery.value(0).toString() + "

"; + info.insert(QStringLiteral("folderCount"), foldersQuery.value(0)); // num comics auto comicsQuery = db.exec("SELECT COUNT(*) FROM comic"); comicsQuery.next(); - - info += "Number of comics:
" + comicsQuery.value(0).toString() + "

"; + info.insert(QStringLiteral("comicCount"), comicsQuery.value(0)); // num read comics auto readComicsQuery = db.exec("SELECT count(*) FROM comic c INNER JOIN comic_info ci ON c.comicInfoId = ci.id WHERE ci.read = 1"); readComicsQuery.next(); - - info += "Number of read comics:
" + readComicsQuery.value(0).toString() + "

"; + info.insert(QStringLiteral("readComicCount"), readComicsQuery.value(0)); } QSqlDatabase::removeDatabase(connectionName); return info; } + +QString DBHelper::getLibraryInfo(QUuid id) +{ + const auto libraryInfo = getLibraryInfoData(id); + QString info = "Library path:
" + libraryInfo.value(QStringLiteral("path")).toString() + "

"; + info += "Number of folders:
" + libraryInfo.value(QStringLiteral("folderCount")).toString() + "

"; + info += "Number of comics:
" + libraryInfo.value(QStringLiteral("comicCount")).toString() + "

"; + info += "Number of read comics:
" + libraryInfo.value(QStringLiteral("readComicCount")).toString() + "

"; + return info; +} diff --git a/YACReaderLibrary/db_helper.h b/YACReaderLibrary/db_helper.h index c67b38921..febd4d92b 100644 --- a/YACReaderLibrary/db_helper.h +++ b/YACReaderLibrary/db_helper.h @@ -6,6 +6,7 @@ class QString; #include #include +#include class ComicDB; class Folder; @@ -81,6 +82,13 @@ class DBHelper static void updateFromRemoteClientWithHash(const QList &comics); static void renameLabel(qulonglong id, const QString &name, QSqlDatabase &db); static void renameList(qulonglong id, const QString &name, QSqlDatabase &db); + static bool renameFolder(qulonglong id, const QString &name, const QString &oldPath, const QString &newPath, QSqlDatabase &db, QString *error = nullptr); + static bool moveComic(qulonglong comicId, qulonglong newParentId, const QString &newFileName, const QString &newRelativePath, QSqlDatabase &db); + static qulonglong ensureFolderPath(const QString &relativePath, QSqlDatabase &db, QList *createdFolderIds = nullptr); + static void syncFolderAddedFromContents(const QList &folderIds, QSqlDatabase &db); + static void removeEmptyFolderPaths(const QStringList &relativePaths, QSqlDatabase &db, QList *removedRows = nullptr); + static bool restoreFolderRows(const QList &rows, QSqlDatabase &db); + static void removeEmptyFolderRows(const QList &folderIds, QSqlDatabase &db); static void reasignOrderToSublists(QList ids, QSqlDatabase &db); static void reasignOrderToComicsInFavorites(QList comicIds, QSqlDatabase &db); static void reasignOrderToComicsInLabel(qulonglong labelId, QList comicIds, QSqlDatabase &db); @@ -108,6 +116,7 @@ class DBHelper static bool isFavoriteComic(qulonglong id, QSqlDatabase &db); // library + static QVariantMap getLibraryInfoData(QUuid id); static QString getLibraryInfo(QUuid id); }; diff --git a/YACReaderLibrary/empty_special_list.cpp b/YACReaderLibrary/empty_special_list.cpp index 8f0b9d1a6..891457aa7 100644 --- a/YACReaderLibrary/empty_special_list.cpp +++ b/YACReaderLibrary/empty_special_list.cpp @@ -23,7 +23,7 @@ void EmptySpecialListWidget::showReading() void EmptySpecialListWidget::showRecent() { currentType = Recent; - setPixmap(QPixmap()); + setPixmap(theme.emptyContainer.emptyRecentIcon); setText(tr("There are no recent comics!")); } @@ -43,6 +43,8 @@ void EmptySpecialListWidget::updateIcon() setPixmap(theme.emptyContainer.emptyCurrentReadingsIcon); break; case Recent: + setPixmap(theme.emptyContainer.emptyRecentIcon); + break; case None: break; } diff --git a/YACReaderLibrary/feature_flags.h b/YACReaderLibrary/feature_flags.h new file mode 100644 index 000000000..270c5906f --- /dev/null +++ b/YACReaderLibrary/feature_flags.h @@ -0,0 +1,12 @@ +#ifndef YACREADER_LIBRARY_FEATURE_FLAGS_H +#define YACREADER_LIBRARY_FEATURE_FLAGS_H + +namespace YACReader::FeatureFlags { + +// The file organization workflow is still experimental. Keep its actions out +// of menus and shortcut management until the feature is ready for production. +inline constexpr bool organizeFiles = true; + +} // namespace YACReader::FeatureFlags + +#endif // YACREADER_LIBRARY_FEATURE_FLAGS_H diff --git a/YACReaderLibrary/folder_content_view.cpp b/YACReaderLibrary/folder_content_view.cpp deleted file mode 100644 index 7f8faaa58..000000000 --- a/YACReaderLibrary/folder_content_view.cpp +++ /dev/null @@ -1,319 +0,0 @@ -#include "folder_content_view.h" - -#include "QsLog.h" -#include "comic.h" -#include "comic_files_manager.h" -#include "folder_model.h" -#include "grid_comics_view.h" -#include "yacreader_global_gui.h" -#include "yacreader_tool_bar_stretch.h" - -#include -#include -#include -#include -#include -#include -#include - -using namespace YACReader; - -FolderContentView::FolderContentView(QAction *toogleRecentVisibilityAction, QWidget *parent) - : QWidget { parent }, parent(QModelIndex()), comicModel(new ComicModel()), folderModel(new FolderModel()), smallZoomLabel(nullptr), bigZoomLabel(nullptr) -{ - qmlRegisterType("com.yacreader.FolderModel", 1, 0, "FolderModel"); - - settings = new QSettings(YACReader::getSettingsPath() + "/YACReaderLibrary.ini", QSettings::IniFormat, this); - settings->beginGroup("libraryConfig"); - - view = new QQuickWidget(); - - view->setResizeMode(QQuickWidget::SizeRootObjectToView); - connect( - view, &QQuickWidget::statusChanged, this, - [=](QQuickWidget::Status status) { - if (status == QQuickWidget::Error) { - QLOG_ERROR() << view->errors(); - } - }); - - coverSizeSliderWidget = new QWidget(this); - coverSizeSliderWidget->setFixedWidth(200); - coverSizeSlider = new QSlider(coverSizeSliderWidget); - coverSizeSlider->setOrientation(Qt::Horizontal); - coverSizeSlider->setRange(YACREADER_MIN_GRID_ZOOM_WIDTH, YACREADER_MAX_GRID_ZOOM_WIDTH); - - const auto &comicsToolbar = theme.comicsViewToolbar; - - auto horizontalLayout = new QHBoxLayout(); - smallZoomLabel = new QLabel(); - smallZoomLabel->setPixmap(comicsToolbar.smallGridZoomIcon.pixmap(18, 18)); - horizontalLayout->addWidget(smallZoomLabel); - horizontalLayout->addWidget(coverSizeSlider, 0, Qt::AlignVCenter); - bigZoomLabel = new QLabel(); - bigZoomLabel->setPixmap(comicsToolbar.bigGridZoomIcon.pixmap(18, 18)); - horizontalLayout->addWidget(bigZoomLabel); - horizontalLayout->addSpacing(10); - horizontalLayout->setContentsMargins(0, 0, 0, 0); - - coverSizeSliderWidget->setLayout(horizontalLayout); - - connect(coverSizeSlider, &QAbstractSlider::valueChanged, this, &FolderContentView::setCoversSize); - - toolbar = new QToolBar(); - toolbar->setIconSize(QSize(18, 18)); - toolbar->addWidget(new YACReaderToolBarStretch); - toolbar->addAction(toogleRecentVisibilityAction); - toolbar->addSeparator(); - toolbar->addWidget(coverSizeSliderWidget); - - auto l = new QVBoxLayout; - setContentsMargins(0, 0, 0, 0); - l->setContentsMargins(0, 0, 0, 0); - l->setSpacing(0); - l->addWidget(view); - l->addWidget(toolbar); - this->setLayout(l); - - QQmlContext *ctxt = view->rootContext(); - - // fonts settings (not theme-dependent) - int fontSize = QApplication::font().pointSize(); - if (fontSize == -1) - fontSize = QApplication::font().pixelSize(); - ctxt->setContextProperty("fontSize", fontSize); - ctxt->setContextProperty("fontFamily", QApplication::font().family()); - ctxt->setContextProperty("fontSpacing", 0.5); - - // Apply theme colors - initTheme(this); - - updateCoversSizeInContext(YACREADER_MIN_COVER_WIDTH, ctxt); - - ctxt->setContextProperty("comicsList", comicModel.get()); - ctxt->setContextProperty("foldersList", folderModel); - - auto showContinueReading = settings->value(DISPLAY_GLOBAL_CONTINUE_READING_IN_GRID_VIEW, true).toBool(); - ctxt->setContextProperty("showContinueReading", QVariant(showContinueReading)); - - ctxt->setContextProperty("openHelper", this); - ctxt->setContextProperty("dropManager", this); - ctxt->setContextProperty("contextMenuHelper", this); - - view->setSource(QUrl("qrc:/qml/FolderContentView.qml")); -} - -void FolderContentView::setModel(const QModelIndex &parent, FolderModel *model) -{ - this->parent = parent; - QQmlContext *ctxt = view->rootContext(); - - ctxt->setContextProperty("foldersList", model); - - // when the root folder is set, FolderModel just returns itself in `getSubfoldersModel`, I need to measure the performance of create a deep copy... - if (folderModel->isSubfolder) { - delete folderModel; - } - folderModel = model; - - auto *root = view->rootObject(); - auto grid = root ? root->findChild(QStringLiteral("grid")) : nullptr; - - if (grid != nullptr) { - grid->setProperty("currentIndex", 0); - } -} - -void FolderContentView::setContinueReadingModel(ComicModel *model) -{ - QQmlContext *ctxt = view->rootContext(); - - ctxt->setContextProperty("comicsList", model); - this->comicModel.reset(model); - - auto *root = view->rootObject(); - auto list = root ? root->findChild(QStringLiteral("list")) : nullptr; - - if (list != nullptr) { - list->setProperty("currentIndex", 0); - } -} - -void FolderContentView::reloadContent() -{ - folderModel->reload(); - reloadContinueReadingModel(); -} - -void FolderContentView::reloadContinueReadingModel() -{ - if (!folderModel->isSubfolder) { - comicModel->reloadContinueReading(); - } -} - -void FolderContentView::setShowRecent(bool visible) -{ - folderModel->setShowRecent(visible); -} - -void FolderContentView::setRecentRange(int days) -{ - folderModel->setRecentRange(days); -} - -void FolderContentView::updateSettings() -{ - QQmlContext *ctxt = view->rootContext(); - - auto showContinueReading = settings->value(DISPLAY_GLOBAL_CONTINUE_READING_IN_GRID_VIEW, true).toBool(); - ctxt->setContextProperty("showContinueReading", QVariant(showContinueReading)); -} - -void FolderContentView::openFolder(int index) -{ - emit subfolderSelected(this->parent, index); -} - -void FolderContentView::openComicFromContinueReadingList(int index) -{ - auto comic = comicModel->getComic(comicModel->index(index, 0)); - emit openComic(comic, ComicModel::Folder); -} - -void FolderContentView::requestedFolderContextMenu(QPoint point, int index) -{ - auto folder = folderModel->getFolder(folderModel->index(index, 0)); - emit openFolderContextMenu(point, folder); -} - -void FolderContentView::requestedContinueReadingComicContextMenu(QPoint point, int index) -{ - auto comic = comicModel->getComic(comicModel->index(index, 0)); - emit openContinueReadingComicContextMenu(point, comic); -} - -void FolderContentView::updateCoversSizeInContext(int width, QQmlContext *ctxt) -{ - int cellBottomMarging = 8 * (1 + 2 * (1 - (float(YACREADER_MAX_GRID_ZOOM_WIDTH - width) / (YACREADER_MAX_GRID_ZOOM_WIDTH - YACREADER_MIN_GRID_ZOOM_WIDTH)))); - - ctxt->setContextProperty("cellCustomHeight", ((width * YACREADER_MAX_COVER_HEIGHT) / YACREADER_MIN_COVER_WIDTH) + 51 + cellBottomMarging); - ctxt->setContextProperty("cellCustomWidth", (width * YACREADER_MIN_CELL_CUSTOM_WIDTH) / YACREADER_MIN_COVER_WIDTH); - - ctxt->setContextProperty("itemWidth", width); - ctxt->setContextProperty("itemHeight", ((width * YACREADER_MAX_COVER_HEIGHT) / YACREADER_MIN_COVER_WIDTH) + 51); - - ctxt->setContextProperty("coverWidth", width); - ctxt->setContextProperty("coverHeight", (width * YACREADER_MAX_COVER_HEIGHT) / YACREADER_MIN_COVER_WIDTH); -} - -void FolderContentView::setCoversSize(int width) -{ - QQmlContext *ctxt = view->rootContext(); - - auto *root = view->rootObject(); - auto grid = root ? root->findChild(QStringLiteral("grid")) : nullptr; - - if (grid != 0) { - QVariant cellCustomWidth = (width * YACREADER_MIN_CELL_CUSTOM_WIDTH) / YACREADER_MIN_GRID_ZOOM_WIDTH; - QMetaObject::invokeMethod(grid, "calculateCellWidths", - Q_ARG(QVariant, cellCustomWidth)); - } - - updateCoversSizeInContext(width, ctxt); - - settings->setValue(COMICS_GRID_COVER_SIZES, coverSizeSlider->value()); -} - -void FolderContentView::showEvent(QShowEvent *event) -{ - QWidget::showEvent(event); - - int coverSize = settings->value(COMICS_GRID_COVER_SIZES, YACREADER_MIN_COVER_WIDTH).toInt(); - - coverSizeSlider->setValue(coverSize); - setCoversSize(coverSize); -} - -bool FolderContentView::canDropUrls(const QList &urls, Qt::DropAction action) -{ - if (action == Qt::CopyAction) { - QString currentPath; - for (const auto &url : urls) { - // comics or folders are accepted, folders' content is validate in dropEvent (avoid any lag before droping) - currentPath = url.toLocalFile(); - if (Comic::fileIsComic(currentPath) || QFileInfo(currentPath).isDir()) - return true; - } - } - return false; -} - -bool FolderContentView::canDropFormats(const QString &formats) -{ - return true; -} - -void FolderContentView::droppedFiles(const QList &urls, Qt::DropAction action) -{ - bool validAction = action == Qt::CopyAction; // TODO add move - - if (validAction) { - QList> droppedFiles = ComicFilesManager::getDroppedFiles(urls); - emit copyComicsToCurrentFolder(droppedFiles); - } -} - -void FolderContentView::applyTheme(const Theme &theme) -{ - QQmlContext *ctxt = view->rootContext(); - const auto &giv = theme.gridAndInfoView; - - toolbar->setStyleSheet(theme.comicsViewToolbar.toolbarQSS); - - // Continue reading section colors - ctxt->setContextProperty("continueReadingBackgroundColor", giv.continueReadingBackgroundColor); - ctxt->setContextProperty("continueReadingTextColor", giv.continueReadingTextColor); - - // Grid colors - ctxt->setContextProperty("backgroundColor", giv.backgroundColor); - ctxt->setContextProperty("cellColor", giv.cellColor); - ctxt->setContextProperty("cellSelectedColor", giv.cellSelectedColor); - ctxt->setContextProperty("cellSelectedBorderColor", giv.cellSelectedBorderColor); - ctxt->setContextProperty("borderColor", giv.borderColor); - ctxt->setContextProperty("itemTitleColor", giv.itemTitleColor); - ctxt->setContextProperty("itemDetailsColor", giv.itemDetailsColor); - ctxt->setContextProperty("dropShadow", QVariant(giv.showDropShadow)); - - // Info panel colors - ctxt->setContextProperty("infoBackgroundColor", giv.infoBackgroundColor); - ctxt->setContextProperty("infoMetadataTextColor", giv.infoMetadataTextColor); - ctxt->setContextProperty("infoTextColor", giv.infoTextColor); - - // Rating and favorite colors - ctxt->setContextProperty("ratingUnselectedColor", giv.ratingUnselectedColor); - ctxt->setContextProperty("ratingSelectedColor", giv.ratingSelectedColor); - ctxt->setContextProperty("favUncheckedColor", giv.favUncheckedColor); - ctxt->setContextProperty("favCheckedColor", giv.favCheckedColor); - ctxt->setContextProperty("readTickUncheckedColor", giv.readTickUncheckedColor); - ctxt->setContextProperty("readTickCheckedColor", giv.readTickCheckedColor); - - // New item indicator, cover borders, placeholder pages, scrollbar - ctxt->setContextProperty("newItemColor", giv.newItemColor); - ctxt->setContextProperty("scrollbarColor", giv.scrollbarColor); - ctxt->setContextProperty("scrollbarBorderColor", giv.scrollbarBorderColor); - ctxt->setContextProperty("comicCoverBorderColor", giv.comicCoverBorderColor); - ctxt->setContextProperty("folderCoverBorderColor", giv.folderCoverBorderColor); - ctxt->setContextProperty("placeholderFolder1Color", giv.placeholderFolder1Color); - ctxt->setContextProperty("placeholderFolder1BorderColor", giv.placeholderFolder1BorderColor); - ctxt->setContextProperty("placeholderFolder2Color", giv.placeholderFolder2Color); - ctxt->setContextProperty("placeholderFolder2BorderColor", giv.placeholderFolder2BorderColor); - - // Update zoom slider icons - if (smallZoomLabel) { - smallZoomLabel->setPixmap(theme.comicsViewToolbar.smallGridZoomIcon.pixmap(18, 18)); - } - if (bigZoomLabel) { - bigZoomLabel->setPixmap(theme.comicsViewToolbar.bigGridZoomIcon.pixmap(18, 18)); - } -} diff --git a/YACReaderLibrary/folder_content_view.h b/YACReaderLibrary/folder_content_view.h deleted file mode 100644 index 22d124779..000000000 --- a/YACReaderLibrary/folder_content_view.h +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef FOLDERCONTENTVIEW_H -#define FOLDERCONTENTVIEW_H - -#include "comic_db.h" -#include "comic_model.h" -#include "folder.h" -#include "themable.h" - -#include -#include -#include -#include - -class FolderModel; -class ComicModel; -class YACReaderToolBarStretch; - -class QQuickWidget; -class QQmlContext; - -class FolderContentView : public QWidget, protected Themable -{ - Q_OBJECT -public: - explicit FolderContentView(QAction *toogleRecentVisibilityAction, QWidget *parent = nullptr); - void setModel(const QModelIndex &parent, FolderModel *model); - void setContinueReadingModel(ComicModel *model); - void reloadContent(); - void reloadContinueReadingModel(); - void setShowRecent(bool visible); - void setRecentRange(int days); - - FolderModel *currentFolderModel() { return folderModel; } - -public slots: - void updateSettings(); - -signals: - void subfolderSelected(QModelIndex, int); - void openComic(const ComicDB &comic, const ComicModel::Mode mode); - - // Drops - void copyComicsToCurrentFolder(QList>); - void moveComicsToCurrentFolder(QList>); - - void openFolderContextMenu(QPoint point, Folder folder); - void openContinueReadingComicContextMenu(QPoint point, ComicDB comic); - -protected slots: - // void onItemClicked(const QModelIndex &mi); - void updateCoversSizeInContext(int width, QQmlContext *ctxt); - void setCoversSize(int width); - virtual void showEvent(QShowEvent *event) override; - void openFolder(int index); - void openComicFromContinueReadingList(int index); - void requestedFolderContextMenu(QPoint point, int index); - void requestedContinueReadingComicContextMenu(QPoint point, int index); - bool canDropUrls(const QList &urls, Qt::DropAction action); - bool canDropFormats(const QString &formats); - void droppedFiles(const QList &urls, Qt::DropAction action); - -protected: - QQuickWidget *view; - QModelIndex parent; - - std::unique_ptr comicModel; - FolderModel *folderModel; - - void applyTheme(const Theme &theme) override; - -private: - QSettings *settings; - QToolBar *toolbar; - YACReaderToolBarStretch *toolBarStretch; - QAction *toolBarStretchAction; - QWidget *coverSizeSliderWidget; - QSlider *coverSizeSlider; - QAction *coverSizeSliderAction; - QAction *showInfoAction; - QAction *showInfoSeparatorAction; - - // Zoom slider labels (for theming) - QLabel *smallZoomLabel; - QLabel *bigZoomLabel; -}; - -#endif // FOLDERCONTENTVIEW_H diff --git a/YACReaderLibrary/folder_management_coordinator.cpp b/YACReaderLibrary/folder_management_coordinator.cpp new file mode 100644 index 000000000..10ce9fe66 --- /dev/null +++ b/YACReaderLibrary/folder_management_coordinator.cpp @@ -0,0 +1,375 @@ +#include "folder_management_coordinator.h" + +#include "comics_remover.h" +#include "cover_utils.h" +#include "folder_model.h" +#include "yacreader_global.h" +#include "yacreader_global_gui.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace { +bool containsInvalidFolderNameCharacters(const QString &folderName) +{ + static const QRegularExpression invalidCharacters(QStringLiteral("[\\/\\\\:*?\"<>|]")); + return folderName.contains(invalidCharacters); +} +} + +FolderManagementCoordinator::FolderManagementCoordinator(FolderModel *foldersModel, + QWidget *dialogParent, + CurrentFolderProvider currentFolderProvider, + SelectedFolderProvider selectedFolderProvider, + LibraryPathProvider libraryPathProvider) + : QObject(dialogParent), foldersModel(foldersModel), dialogParent(dialogParent), currentFolderProvider(std::move(currentFolderProvider)), selectedFolderProvider(std::move(selectedFolderProvider)), libraryPathProvider(std::move(libraryPathProvider)) +{ +} + +QModelIndex FolderManagementCoordinator::createFolder(const QModelIndex &parent, const QString &parentPath, const QString &folderName) +{ + if (folderName.isEmpty() || containsInvalidFolderNameCharacters(folderName)) + return { }; + + QDir parentDirectory(parentPath); + const QDir newFolder(parentDirectory.filePath(folderName)); + if (!parentDirectory.mkdir(folderName) && !newFolder.exists()) + return { }; + + return foldersModel->addFolderAtParent(folderName, parent); +} + +void FolderManagementCoordinator::addFolderToCurrentFolder() +{ + emit folderCreationStarted(); + + const auto parent = selectedFolderProvider(); + bool accepted = false; + const auto folderName = QInputDialog::getText(dialogParent, + tr("Add new folder"), + tr("Folder name:"), + QLineEdit::Normal, + QString(), + &accepted); + if (!accepted) + return; + + const auto parentPath = QDir::cleanPath(libraryPathProvider() + foldersModel->getFolderPath(parent)); + const auto folder = createFolder(parent, parentPath, folderName); + if (folder.isValid()) + emit folderNavigationRequested(folder); +} + +void FolderManagementCoordinator::openCurrentFolder() +{ + const auto libraryPath = libraryPathProvider(); + const auto folder = currentFolderProvider(); + const auto path = folder.isValid() + ? QDir::cleanPath(libraryPath + foldersModel->getFolderPath(folder)) + : QDir::cleanPath(libraryPath); + QDesktopServices::openUrl(QUrl("file:///" + path, QUrl::TolerantMode)); +} + +void FolderManagementCoordinator::openFolder(qulonglong folderId, const QString &libraryPath) +{ + const auto folder = folderIndex(folderId, libraryPath); + if (!folder.isValid()) + return; + + QDesktopServices::openUrl(QUrl("file:///" + QDir::cleanPath(libraryPath + foldersModel->getFolderPath(folder)), QUrl::TolerantMode)); +} + +FolderManagementCoordinator::RenameResult FolderManagementCoordinator::renameFolder(const QModelIndex &folder, const QString &libraryPath, const QString &newName) +{ + const auto oldName = folder.data(FolderModel::FolderNameRole).toString(); + if (newName.isEmpty() || newName == "." || newName == ".." || containsInvalidFolderNameCharacters(newName)) + return { RenameError::InvalidName }; + + const auto oldPath = QDir::cleanPath(libraryPath + foldersModel->getFolderPath(folder)); + const QFileInfo oldFolder(oldPath); + QDir parentDirectory(oldFolder.absolutePath()); + const auto newPath = QDir::cleanPath(parentDirectory.filePath(newName)); + + if (QFileInfo::exists(newPath) && QString::compare(oldPath, newPath, Qt::CaseInsensitive) != 0) + return { RenameError::TargetAlreadyExists }; + + if (!parentDirectory.rename(oldName, newName)) + return { RenameError::FileSystemRenameFailed, oldPath }; + + QString databaseError; + if (foldersModel->renameFolder(folder, newName, &databaseError)) + return { }; + + if (!parentDirectory.rename(newName, oldName)) + return { RenameError::DatabaseUpdateAndRollbackFailed, oldPath, databaseError }; + + return { RenameError::DatabaseUpdateFailed, oldPath, databaseError }; +} + +void FolderManagementCoordinator::renameFolder(qulonglong folderId, const QString &libraryPath) +{ + renameFolder(folderIndex(folderId, libraryPath), libraryPath); +} + +void FolderManagementCoordinator::renameCurrentFolder() +{ + const auto libraryPath = libraryPathProvider(); + const auto folder = selectedFolderProvider(); + if (!folder.isValid()) { + QMessageBox::information(dialogParent, + QCoreApplication::translate("LibraryWindow", "No folder selected"), + QCoreApplication::translate("LibraryWindow", "Please, select a folder first")); + return; + } + + renameFolder(folder.data(FolderModel::IdRole).toULongLong(), libraryPath); +} + +void FolderManagementCoordinator::renameFolder(const QModelIndex &folder, const QString &libraryPath) +{ + if (!folder.isValid()) { + QMessageBox::information(dialogParent, + QCoreApplication::translate("LibraryWindow", "No folder selected"), + QCoreApplication::translate("LibraryWindow", "Please, select a folder first")); + return; + } + + const auto oldName = folder.data(FolderModel::FolderNameRole).toString(); + bool accepted = false; + const auto newName = QInputDialog::getText(dialogParent, + QCoreApplication::translate("LibraryWindow", "Rename folder"), + QCoreApplication::translate("LibraryWindow", "Folder name:"), + QLineEdit::Normal, + oldName, + &accepted); + if (!accepted || newName == oldName) + return; + + const auto result = renameFolder(folder, libraryPath, newName); + switch (result.error) { + case RenameError::None: + emit folderRenamed(); + return; + case RenameError::InvalidName: + QMessageBox::warning(dialogParent, + QCoreApplication::translate("LibraryWindow", "Invalid folder name"), + QCoreApplication::translate("LibraryWindow", "The folder name is empty or contains characters that are not supported.")); + return; + case RenameError::TargetAlreadyExists: + QMessageBox::warning(dialogParent, + QCoreApplication::translate("LibraryWindow", "Unable to rename folder"), + QCoreApplication::translate("LibraryWindow", "A file or folder named '%1' already exists.").arg(newName)); + return; + case RenameError::FileSystemRenameFailed: + QMessageBox::critical(dialogParent, + QCoreApplication::translate("LibraryWindow", "Unable to rename folder"), + QCoreApplication::translate("LibraryWindow", "The folder could not be renamed on disk. Please check the folder name and write permissions.\n\nFolder: %1").arg(result.folderPath)); + return; + case RenameError::DatabaseUpdateFailed: + case RenameError::DatabaseUpdateAndRollbackFailed: { + auto message = result.error == RenameError::DatabaseUpdateFailed + ? QCoreApplication::translate("LibraryWindow", "The library database could not be updated. The folder rename on disk was reverted.") + : QCoreApplication::translate("LibraryWindow", "The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually."); + if (!result.databaseError.isEmpty()) + message += "\n\n" + result.databaseError; + QMessageBox::critical(dialogParent, QCoreApplication::translate("LibraryWindow", "Unable to rename folder"), message); + return; + } + } +} + +void FolderManagementCoordinator::deleteCurrentFolder() +{ + const auto folder = selectedFolderProvider(); + if (!folder.isValid()) { + QMessageBox::information(dialogParent, + QCoreApplication::translate("LibraryWindow", "No folder selected"), + QCoreApplication::translate("LibraryWindow", "Please, select a folder first")); + return; + } + + const auto libraryPath = QDir::cleanPath(libraryPathProvider()); + const auto relativePath = foldersModel->getFolderPath(folder); + const auto folderPath = QDir::cleanPath(libraryPath + relativePath); + if (libraryPath == folderPath || relativePath.isEmpty() || relativePath == "/") { + QMessageBox::critical(dialogParent, + QCoreApplication::translate("LibraryWindow", "Error in path"), + QCoreApplication::translate("LibraryWindow", "There was an error accessing the folder's path")); + return; + } + + const auto result = QMessageBox::question( + dialogParent, + QCoreApplication::translate("LibraryWindow", "Delete folder"), + QCoreApplication::translate("LibraryWindow", "The selected folder and all its contents will be deleted from your disk. Are you sure?") + "\n\nFolder : " + folderPath, + QMessageBox::Yes, + QMessageBox::No); + if (result != QMessageBox::Yes) + return; + + emit folderAboutToBeDeleted(folder.parent()); + deleteFolder(folder, folderPath); +} + +void FolderManagementCoordinator::deleteFolder(const QModelIndex &folder, const QString &folderPath) +{ + QModelIndexList folders { folder }; + QList paths { folderPath }; + + auto remover = new FoldersRemover(folders, paths); + auto thread = new QThread(this); + remover->moveToThread(thread); + + connect(thread, &QThread::started, remover, &FoldersRemover::process); + connect(remover, &FoldersRemover::remove, foldersModel, &FolderModel::deleteFolder); + connect(remover, &FoldersRemover::removeError, this, &FolderManagementCoordinator::showFolderDeletionError); + connect(remover, &FoldersRemover::finished, this, &FolderManagementCoordinator::folderDeletionFinished); + connect(remover, &FoldersRemover::finished, remover, &QObject::deleteLater); + connect(remover, &FoldersRemover::finished, thread, &QThread::quit); + connect(thread, &QThread::finished, thread, &QObject::deleteLater); + + thread->start(); +} + +void FolderManagementCoordinator::showFolderDeletionError() +{ + QMessageBox::critical(dialogParent, + QCoreApplication::translate("LibraryWindow", "Unable to delete"), + QCoreApplication::translate("LibraryWindow", "There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files.")); +} + +void FolderManagementCoordinator::setFolderCompleted(qulonglong folderId, const QString &libraryPath, bool completed) +{ + const auto index = folderIndex(folderId, libraryPath); + if (index.isValid()) + foldersModel->updateFolderCompletedStatus({ index }, completed); +} + +void FolderManagementCoordinator::setFolderRead(qulonglong folderId, const QString &libraryPath, bool read) +{ + const auto index = folderIndex(folderId, libraryPath); + if (index.isValid()) + foldersModel->updateFolderFinishedStatus({ index }, read); +} + +void FolderManagementCoordinator::setFolderType(qulonglong folderId, const QString &libraryPath, YACReader::FileType type) +{ + const auto index = folderIndex(folderId, libraryPath); + if (index.isValid()) + foldersModel->updateFolderType({ index }, type); +} + +void FolderManagementCoordinator::setCurrentFolderCompleted(bool completed) +{ + const auto index = currentFolderProvider(); + if (index.isValid()) + setFolderCompleted(index.data(FolderModel::IdRole).toULongLong(), libraryPathProvider(), completed); +} + +void FolderManagementCoordinator::setCurrentFolderRead(bool read) +{ + const auto index = currentFolderProvider(); + if (index.isValid()) + setFolderRead(index.data(FolderModel::IdRole).toULongLong(), libraryPathProvider(), read); +} + +void FolderManagementCoordinator::setCurrentFolderType(YACReader::FileType type) +{ + const auto index = currentFolderProvider(); + if (index.isValid()) + setFolderType(index.data(FolderModel::IdRole).toULongLong(), libraryPathProvider(), type); +} + +void FolderManagementCoordinator::selectAndSetCurrentFolderCover() +{ + const auto index = currentFolderProvider(); + if (index.isValid()) + selectAndSetCustomCover(index.data(FolderModel::IdRole).toULongLong(), libraryPathProvider()); +} + +void FolderManagementCoordinator::resetCurrentFolderCover() +{ + const auto index = currentFolderProvider(); + if (index.isValid()) + resetCustomCover(index.data(FolderModel::IdRole).toULongLong(), libraryPathProvider()); +} + +void FolderManagementCoordinator::selectAndSetCustomCover(qulonglong folderId, const QString &libraryPath) +{ + if (!folderIndex(folderId, libraryPath).isValid()) + return; + + const auto sourceImagePath = YACReader::imageFileLoader(dialogParent); + if (sourceImagePath.isEmpty()) + return; + + setCustomCover(folderId, libraryPath, sourceImagePath); +} + +void FolderManagementCoordinator::setCustomCover(qulonglong folderId, const QString &imagePath) +{ + setCustomCover(folderId, libraryPathProvider(), imagePath); +} + +void FolderManagementCoordinator::setCustomCover(qulonglong folderId, const QString &libraryPath, const QString &imagePath) +{ + if (imagePath.isEmpty()) + return; + + const auto index = folderIndex(folderId, libraryPath); + if (!index.isValid()) + return; + + const QImage cover(imagePath); + if (cover.isNull()) { + QMessageBox::warning(dialogParent, + QCoreApplication::translate("LibraryWindow", "Invalid image"), + QCoreApplication::translate("LibraryWindow", "The selected file is not a valid image.")); + return; + } + + auto folderCoverPath = YACReader::LibraryPaths::customFolderCoverPath(libraryPath, QString::number(folderId)); + if (!YACReader::saveCover(folderCoverPath, cover)) { + QMessageBox::warning(dialogParent, + QCoreApplication::translate("LibraryWindow", "Error saving cover"), + QCoreApplication::translate("LibraryWindow", "There was an error saving the cover image.")); + return; + } + + const auto coversPath = YACReader::LibraryPaths::libraryCoversFolderPath(libraryPath); + foldersModel->setCustomFolderCover(index, folderCoverPath.remove(coversPath)); +} + +void FolderManagementCoordinator::resetCustomCover(qulonglong folderId, const QString &libraryPath) +{ + const auto index = folderIndex(folderId, libraryPath); + if (!index.isValid()) + return; + + const auto folderCoverPath = YACReader::LibraryPaths::customFolderCoverPath(libraryPath, QString::number(folderId)); + if (QFile::exists(folderCoverPath)) + QFile::remove(folderCoverPath); + + foldersModel->resetFolderCover(index); +} + +QModelIndex FolderManagementCoordinator::folderIndex(qulonglong folderId, const QString &libraryPath) const +{ + if (QDir::cleanPath(foldersModel->getDatabase()) != QDir::cleanPath(YACReader::LibraryPaths::libraryDataPath(libraryPath))) + return { }; + + return foldersModel->getIndexFromFolderId(folderId); +} diff --git a/YACReaderLibrary/folder_management_coordinator.h b/YACReaderLibrary/folder_management_coordinator.h new file mode 100644 index 000000000..71b2c4393 --- /dev/null +++ b/YACReaderLibrary/folder_management_coordinator.h @@ -0,0 +1,89 @@ +#ifndef FOLDER_MANAGEMENT_COORDINATOR_H +#define FOLDER_MANAGEMENT_COORDINATOR_H + +#include "yacreader_global.h" + +#include +#include +#include + +#include + +class FolderModel; +class QWidget; + +class FolderManagementCoordinator : public QObject +{ + Q_OBJECT + +public: + using CurrentFolderProvider = std::function; + using SelectedFolderProvider = std::function; + using LibraryPathProvider = std::function; + + explicit FolderManagementCoordinator(FolderModel *foldersModel, + QWidget *dialogParent, + CurrentFolderProvider currentFolderProvider, + SelectedFolderProvider selectedFolderProvider, + LibraryPathProvider libraryPathProvider); + + void renameFolder(qulonglong folderId, const QString &libraryPath); + void setFolderCompleted(qulonglong folderId, const QString &libraryPath, bool completed); + void setFolderRead(qulonglong folderId, const QString &libraryPath, bool read); + void setFolderType(qulonglong folderId, const QString &libraryPath, YACReader::FileType type); + void openFolder(qulonglong folderId, const QString &libraryPath); + void selectAndSetCustomCover(qulonglong folderId, const QString &libraryPath); + void setCustomCover(qulonglong folderId, const QString &imagePath); + void resetCustomCover(qulonglong folderId, const QString &libraryPath); + +public slots: + void addFolderToCurrentFolder(); + void openCurrentFolder(); + void renameCurrentFolder(); + void deleteCurrentFolder(); + void setCurrentFolderCompleted(bool completed); + void setCurrentFolderRead(bool read); + void setCurrentFolderType(YACReader::FileType type); + void selectAndSetCurrentFolderCover(); + void resetCurrentFolderCover(); + +signals: + void folderCreationStarted(); + void folderNavigationRequested(const QModelIndex &folder); + void folderRenamed(); + void folderAboutToBeDeleted(const QModelIndex &parentFolder); + void folderDeletionFinished(); + +private: + QModelIndex createFolder(const QModelIndex &parent, const QString &parentPath, const QString &folderName); + + enum class RenameError { + None, + InvalidName, + TargetAlreadyExists, + FileSystemRenameFailed, + DatabaseUpdateFailed, + DatabaseUpdateAndRollbackFailed + }; + + struct RenameResult { + RenameError error { RenameError::None }; + QString folderPath; + QString databaseError; + }; + + void renameFolder(const QModelIndex &folder, const QString &libraryPath); + RenameResult renameFolder(const QModelIndex &folder, const QString &libraryPath, const QString &newName); + void deleteFolder(const QModelIndex &folder, const QString &folderPath); + void showFolderDeletionError(); + QModelIndex folderIndex(qulonglong folderId, const QString &libraryPath) const; + void setCustomCover(qulonglong folderId, const QString &libraryPath, const QString &imagePath); + + FolderModel *foldersModel; + QWidget *dialogParent; + CurrentFolderProvider currentFolderProvider; + SelectedFolderProvider selectedFolderProvider; + LibraryPathProvider libraryPathProvider; +}; + +#endif // FOLDER_MANAGEMENT_COORDINATOR_H diff --git a/YACReaderLibrary/grid_comics_view.cpp b/YACReaderLibrary/grid_comics_view.cpp index 970b66d63..c98f52f44 100644 --- a/YACReaderLibrary/grid_comics_view.cpp +++ b/YACReaderLibrary/grid_comics_view.cpp @@ -4,31 +4,59 @@ #include "comic.h" #include "comic_db.h" #include "comic_files_manager.h" +#include "cover_utils.h" #include "current_comic_view_helper.h" +#include "folder_model.h" +#include "grid_content_model.h" +#include "reading_list_model.h" #include "yacreader_comic_info_helper.h" #include "yacreader_comics_selection_helper.h" #include "yacreader_global_gui.h" #include +#include #include #include #include #include #include #include +#include #include #include +#include + +#include + +namespace { +QString pixmapDataUrl(const QPixmap &pixmap) +{ + if (pixmap.isNull()) + return { }; + + QByteArray data; + QBuffer buffer(&data); + buffer.open(QIODevice::WriteOnly); + pixmap.save(&buffer, "PNG"); + return QStringLiteral("data:image/png;base64,") + QString::fromLatin1(data.toBase64()); +} +} // namespace GridComicsView::GridComicsView(QWidget *parent) - : ComicsView(parent), filterEnabled(false), smallZoomLabel(nullptr), bigZoomLabel(nullptr) + : ComicsView(parent), toolbar(nullptr), coverSizeSliderWidget(nullptr), coverSizeSlider(nullptr), coverSizeSliderAction(nullptr), showInfoSeparatorAction(nullptr), startSeparatorAction(nullptr), filterEnabled(false), contentModel(new GridContentModel(this)), viewStateTimer(new QTimer(this)), smallZoomLabel(nullptr), bigZoomLabel(nullptr) { + qmlRegisterUncreatableType("com.yacreader.GridContentModel", 1, 0, "GridContentModel", QStringLiteral("GridContentModel is provided by GridComicsView")); + settings = new QSettings(YACReader::getSettingsPath() + "/YACReaderLibrary.ini", QSettings::IniFormat, this); settings->beginGroup("libraryConfig"); // view->setFocusPolicy(Qt::TabFocus); selectionHelper = new YACReaderComicsSelectionHelper(this); - connect(selectionHelper, &YACReaderComicsSelectionHelper::selectionChanged, this, &GridComicsView::dummyUpdater); + connect(selectionHelper, &YACReaderComicsSelectionHelper::selectionChanged, this, [this]() { + emit comicSelectionStateChanged(selectionHelper->numItemsSelected() > 0); + emit selectedComicsInfoChanged(); + }); comicInfoHelper = new YACReaderComicInfoHelper(this); @@ -49,30 +77,45 @@ GridComicsView::GridComicsView(QWidget *parent) auto model = new ComicModel(); selectionHelper->setModel(model); - ctxt->setContextProperty("comicsList", model); + contentModel->setComicModel(model); + connect(contentModel, &QAbstractItemModel::modelReset, this, [this]() { + if (focusedFolderIndex.isValid()) + setFocusedFolder(focusedFolderIndex.row()); + else + clearFocusedFolder(); + }); + connect(contentModel, &QAbstractItemModel::dataChanged, this, [this](const QModelIndex &topLeft, const QModelIndex &bottomRight) { + const auto focusedRow = focusedFolderRow(); + if (focusedRow >= topLeft.row() && focusedRow <= bottomRight.row()) + setFocusedFolder(focusedRow); + }); + ctxt->setContextProperty("comicsList", contentModel); ctxt->setContextProperty("comicsSelection", selectionHelper->selectionModel()); ctxt->setContextProperty("contextMenuHelper", this); ctxt->setContextProperty("comicsSelectionHelper", selectionHelper); ctxt->setContextProperty("currentIndexHelper", this); ctxt->setContextProperty("comicRatingHelper", this); - ctxt->setContextProperty("dummyValue", true); ctxt->setContextProperty("dragManager", this); ctxt->setContextProperty("dropManager", this); ctxt->setContextProperty("comicOpener", this); + rootContinueReadingModelStorage = std::make_unique(); + globalContinueReadingEnabled = settings->value(DISPLAY_GLOBAL_CONTINUE_READING_IN_GRID_VIEW, true).toBool(); + contentModel->setMixFoldersAndComics(settings->value(COMICS_GRID_MIX_FOLDERS_AND_COMICS, true).toBool()); + contentModel->setStartComicsOnNewRow(settings->value(COMICS_GRID_START_COMICS_ON_NEW_ROW, false).toBool()); + + viewStateTimer->setSingleShot(true); + connect(viewStateTimer, &QTimer::timeout, this, &GridComicsView::applyPendingViewState); bool showInfo = settings->value(COMICS_GRID_SHOW_INFO, false).toBool(); ctxt->setContextProperty("showInfo", showInfo); - auto comicDB = new ComicDB(); - auto comicInfo = &(comicDB->info); - ctxt->setContextProperty("currentComic", comicDB); - ctxt->setContextProperty("currentComicInfo", comicInfo); - ctxt->setContextProperty("showCurrentComic", QVariant(false)); + ctxt->setContextProperty("currentComic", ¤tComic); + ctxt->setContextProperty("currentComicInfo", ¤tComic.info); showInfoAction = new QAction(tr("Show info"), this); showInfoAction->setCheckable(true); showInfoAction->setChecked(showInfo); - connect(showInfoAction, &QAction::toggled, this, &GridComicsView::showInfo); + connect(showInfoAction, &QAction::toggled, this, &GridComicsView::updateInfoPanelVisibility); updateCoversSizeInContext(YACREADER_MIN_COVER_WIDTH, ctxt); @@ -140,37 +183,119 @@ void GridComicsView::createCoverSizeSliderWidget() void GridComicsView::setToolBar(QToolBar *toolBar) { static_cast(this->layout())->insertWidget(1, toolBar); - this->toolbar = toolBar; + toolbar = toolBar; + + if (!coverSizeSliderWidget) + createCoverSizeSliderWidget(); + + if (!startSeparatorAction) { + startSeparatorAction = new QAction(this); + startSeparatorAction->setSeparator(true); + } + if (!showInfoSeparatorAction) { + showInfoSeparatorAction = new QAction(this); + showInfoSeparatorAction->setSeparator(true); + } + if (!coverSizeSliderAction) { + auto *sliderAction = new QWidgetAction(this); + sliderAction->setDefaultWidget(coverSizeSliderWidget); + coverSizeSliderAction = sliderAction; + } + + const auto actions = toolbar->actions(); + if (!actions.contains(startSeparatorAction)) + toolbar->addAction(startSeparatorAction); + if (!actions.contains(showInfoAction)) + toolbar->addAction(showInfoAction); + if (!actions.contains(showInfoSeparatorAction)) + toolbar->addAction(showInfoSeparatorAction); + if (!actions.contains(coverSizeSliderAction)) + toolbar->addAction(coverSizeSliderAction); +} - createCoverSizeSliderWidget(); +void GridComicsView::releaseToolBar() +{ + if (!toolbar) + return; + + toolbar->removeAction(startSeparatorAction); + toolbar->removeAction(showInfoAction); + toolbar->removeAction(showInfoSeparatorAction); + toolbar->removeAction(coverSizeSliderAction); +} - startSeparatorAction = toolBar->addSeparator(); - toolBar->addAction(showInfoAction); - showInfoSeparatorAction = toolBar->addSeparator(); - coverSizeSliderAction = toolBar->addWidget(coverSizeSliderWidget); +void GridComicsView::saveViewConfig() +{ + int infoWidth = 0; + if (auto *rootObject = view->rootObject()) { + auto infoContainer = rootObject->findChild("infoContainer", Qt::FindChildrenRecursively); + infoWidth = QQmlProperty(infoContainer, "width").read().toInt(); + } + + if (coverSizeSlider) + settings->setValue(COMICS_GRID_COVER_SIZES, coverSizeSlider->value()); + settings->setValue(COMICS_GRID_SHOW_INFO, showInfoAction->isChecked()); + settings->setValue(COMICS_GRID_INFO_WIDTH, infoWidth); } void GridComicsView::setModel(ComicModel *model) { - if (model == NULL) + if (model == nullptr) return; + // Keep the previous frame visible while QML resets the model. The pending + // origin/anchor is applied before painting is enabled again. + view->setUpdatesEnabled(false); + + clearFocusedFolder(); + disconnect(modelDataChangedConnection); + disconnect(modelFavoritesChangedConnection); ComicsView::setModel(model); - setCurrentComicIfNeeded(); + modelDataChangedConnection = connect(model, &QAbstractItemModel::dataChanged, this, [this](const QModelIndex &topLeft, const QModelIndex &bottomRight) { + if (selectionHelper->numItemsSelected() > 1) { + const auto selectedRows = selectionHelper->selectedRows(); + const bool selectedComicChanged = std::any_of(selectedRows.cbegin(), selectedRows.cend(), [topLeft, bottomRight](const QModelIndex &index) { + return index.row() >= topLeft.row() && index.row() <= bottomRight.row(); + }); + if (selectedComicChanged) + emit selectedComicsInfoChanged(); + } + + if (!showInfoAction->isChecked() || focusedFolderIndex.isValid()) + return; + + const auto index = currentIndex(); + if (index.isValid() && index.row() >= topLeft.row() && index.row() <= bottomRight.row()) + updateInfoForIndex(index.row()); + }); + + modelFavoritesChangedConnection = connect(model, &ComicModel::favoritesChanged, this, [this](const QList &comicIds) { + if (!showInfoAction->isChecked() || focusedFolderIndex.isValid()) + return; + + const auto index = currentIndex(); + if (index.isValid() && comicIds.contains(index.data(ComicModel::IdRole).toULongLong())) + updateInfoForIndex(index.row()); + }); + + updateCurrentComicBanner(); selectionHelper->setModel(model); comicInfoHelper->setModel(model); + contentModel->setComicModel(model); + + if (model->getMode() != ComicModel::Folder) + clearFolderModel(); QQmlContext *ctxt = view->rootContext(); - ctxt->setContextProperty("comicsList", model); + ctxt->setContextProperty("comicsList", contentModel); ctxt->setContextProperty("comicsSelection", selectionHelper->selectionModel()); ctxt->setContextProperty("contextMenuHelper", this); ctxt->setContextProperty("comicsSelectionHelper", selectionHelper); ctxt->setContextProperty("currentIndexHelper", this); ctxt->setContextProperty("comicRatingHelper", this); - ctxt->setContextProperty("dummyValue", true); ctxt->setContextProperty("dragManager", this); ctxt->setContextProperty("dropManager", this); ctxt->setContextProperty("comicInfoHelper", comicInfoHelper); @@ -178,40 +303,36 @@ void GridComicsView::setModel(ComicModel *model) auto *root = view->rootObject(); auto grid = root ? root->findChild(QStringLiteral("grid")) : nullptr; - if (grid != nullptr) { - grid->setProperty("currentIndex", 0); - } + if (grid != nullptr) + grid->setProperty("currentIndex", -1); updateBackgroundConfig(); selectionHelper->clear(); + updateInfoForIndex(-1); - if (model->rowCount() > 0) { - setCurrentIndex(model->index(0, 0)); - if (showInfoAction->isChecked()) - updateInfoForIndex(0); - } - - // If the currentComicView was hidden before showing it sometimes the scroll view doesn't show it - // this is a hacky solution... - QTimer::singleShot(0, this, &GridComicsView::resetScroll); + pendingViewState.reset(); + viewStateTimer->start(0); } void GridComicsView::updateBackgroundConfig() { - if (this->model == NULL) + if (this->model == nullptr) return; QQmlContext *ctxt = view->rootContext(); // backgroun image configuration - bool useBackgroundImage = settings->value(USE_BACKGROUND_IMAGE_IN_GRID_VIEW, true).toBool(); + const bool useBackgroundImage = settings->value(USE_BACKGROUND_IMAGE_IN_GRID_VIEW, true).toBool(); + const bool hasBackgroundComic = this->model->rowCount() > 0; + const bool showBackgroundImage = useBackgroundImage && hasBackgroundComic; - if (useBackgroundImage && this->model->rowCount() > 0) { + if (showBackgroundImage) { float opacity = settings->value(OPACITY_BACKGROUND_IMAGE_IN_GRID_VIEW, 0.2).toFloat(); float blurRadius = settings->value(BLUR_RADIUS_BACKGROUND_IMAGE_IN_GRID_VIEW, 75).toInt(); - int row = settings->value(USE_SELECTED_COMIC_COVER_AS_BACKGROUND_IMAGE_IN_GRID_VIEW, false).toBool() ? currentIndex().row() : 0; + const auto selectedIndex = currentIndex(); + int row = settings->value(USE_SELECTED_COMIC_COVER_AS_BACKGROUND_IMAGE_IN_GRID_VIEW, false).toBool() && selectedIndex.isValid() ? selectedIndex.row() : 0; ctxt->setContextProperty("backgroundImage", this->model->data(this->model->index(row, 0), ComicModel::CoverPathRole)); ctxt->setContextProperty("backgroundBlurOpacity", opacity); @@ -226,23 +347,29 @@ void GridComicsView::updateBackgroundConfig() // Use theme colors for cell and selected colors const auto &giv = theme.gridAndInfoView; - ctxt->setContextProperty("backgroundColor", useBackgroundImage ? giv.backgroundBlurOverlayColor : giv.backgroundColor); - ctxt->setContextProperty("cellColor", useBackgroundImage ? giv.cellColorWithBackground : giv.cellColor); + ctxt->setContextProperty("backgroundColor", showBackgroundImage ? giv.backgroundBlurOverlayColor : giv.backgroundColor); + ctxt->setContextProperty("cellColor", showBackgroundImage ? giv.cellColorWithBackground : giv.cellColor); ctxt->setContextProperty("cellSelectedColor", giv.cellSelectedColor); } -void GridComicsView::showInfo() +void GridComicsView::updateInfoPanelVisibility() { QQmlContext *ctxt = view->rootContext(); ctxt->setContextProperty("showInfo", showInfoAction->isChecked()); - updateInfoForIndex(currentIndex().row()); + if (!focusedFolderIndex.isValid()) + updateInfoForIndex(currentIndex().row()); } void GridComicsView::setCurrentIndex(const QModelIndex &index) { - selectionHelper->clear(); - selectionHelper->selectIndex(index.row()); + clearFocusedFolder(); + selectionHelper->selectOnly(index.row()); + + auto *root = view->rootObject(); + auto grid = root ? root->findChild(QStringLiteral("grid")) : nullptr; + if (grid) + grid->setProperty("currentIndex", contentModel->viewRowForComicRow(index.row())); if (settings->value(USE_SELECTED_COMIC_COVER_AS_BACKGROUND_IMAGE_IN_GRID_VIEW, false).toBool()) updateBackgroundConfig(); @@ -251,11 +378,6 @@ void GridComicsView::setCurrentIndex(const QModelIndex &index) updateInfoForIndex(index.row()); } -void GridComicsView::setCurrentIndex(int index) -{ - setCurrentIndex(model->index(index, 0)); -} - QModelIndex GridComicsView::currentIndex() { return selectionHelper->currentIndex(); @@ -294,20 +416,25 @@ void GridComicsView::enableFilterMode(bool enabled) QQmlContext *ctxt = view->rootContext(); if (enabled) { - ctxt->setContextProperty("showCurrentComic", QVariant(false)); + if (currentComicBannerVisible) { + currentComicBannerVisible = false; + emit currentComicBannerVisibleChanged(); + } ctxt->setContextProperty("currentComic", nullptr); } else { - setCurrentComicIfNeeded(); + updateCurrentComicBanner(); } } void GridComicsView::selectAll() { + clearFocusedFolder(); selectionHelper->selectAll(); } void GridComicsView::selectIndex(int index) { + clearFocusedFolder(); selectionHelper->selectIndex(index); } @@ -322,8 +449,25 @@ void GridComicsView::triggerOpenCurrentComic() void GridComicsView::updateSettings() { + contentModel->setMixFoldersAndComics(settings->value(COMICS_GRID_MIX_FOLDERS_AND_COMICS, true).toBool()); + contentModel->setStartComicsOnNewRow(settings->value(COMICS_GRID_START_COMICS_ON_NEW_ROW, false).toBool()); + if (currentLocationInfo.value(QStringLiteral("kind")).toString() == QStringLiteral("recent")) { + currentLocationInfo.insert(QStringLiteral("recentDays"), settings->value(NUM_DAYS_TO_CONSIDER_RECENT, 1).toInt()); + emit currentLocationInfoChanged(); + } + updateBannerSettings(); updateBackgroundConfig(); - setCurrentComicIfNeeded(); +} + +void GridComicsView::updateBannerSettings() +{ + const bool enabled = settings->value(DISPLAY_GLOBAL_CONTINUE_READING_IN_GRID_VIEW, true).toBool(); + if (globalContinueReadingEnabled != enabled) { + globalContinueReadingEnabled = enabled; + emit globalContinueReadingEnabledChanged(); + } + + updateCurrentComicBanner(); } void GridComicsView::rate(int index, int rating) @@ -331,11 +475,313 @@ void GridComicsView::rate(int index, int rating) model->updateRating(rating, model->index(index, 0)); } -void GridComicsView::requestedContextMenu(const QPoint &point) +void GridComicsView::requestItemContextMenu(const QPoint &point, int viewRow) { + if (contentModel->isFolderRow(viewRow)) { + emit openFolderContextMenu(point, contentModel->folderAt(viewRow)); + return; + } + emit customContextMenuViewRequested(point); } +void GridComicsView::requestOpenLibraryFolder() +{ + emit openLibraryFolderRequested(); +} + +void GridComicsView::setFolderModel(FolderModel *model, const QModelIndex &folderIndex, const QString &rootName, const QVariantMap &libraryInfo) +{ + clearFocusedFolder(); + contentModel->setFolderModel(model, folderIndex); + const bool selectedFolderIsRoot = !folderIndex.isValid(); + if (rootFolder != selectedFolderIsRoot) { + rootFolder = selectedFolderIsRoot; + emit rootFolderChanged(); + } + + if (selectedFolderIsRoot) { + currentLocationInfo = libraryInfo; + currentLocationInfo.insert(QStringLiteral("kind"), QStringLiteral("library")); + currentLocationInfo.insert(QStringLiteral("name"), rootName); + } else { + const auto folder = model->getFolder(folderIndex); + const auto cover = folder.customImage.isEmpty() ? model->getCoverUrlPathForComicHash(folder.firstChildHash) : model->getCoverUrlPathForFolderId(folder.id); + currentLocationInfo = makeFolderInfo(folder, cover); + } + emit currentLocationInfoChanged(); +} + +void GridComicsView::clearFolderModel() +{ + clearFocusedFolder(); + contentModel->clearFolderModel(); + if (rootFolder) { + rootFolder = false; + emit rootFolderChanged(); + } +} + +void GridComicsView::setCurrentList(const QModelIndex &listIndex) +{ + const auto listType = static_cast(listIndex.data(ReadingListModel::TypeListsRole).toInt()); + QString kind; + int labelColor = -1; + int recentDays = 0; + int sublistCount = 0; + + switch (listType) { + case ReadingListModel::SpecialList: { + const auto specialType = static_cast(listIndex.data(ReadingListModel::SpecialListTypeRole).toInt()); + switch (specialType) { + case ReadingListModel::TypeSpecialList::Favorites: + kind = QStringLiteral("favorites"); + break; + case ReadingListModel::TypeSpecialList::Reading: + kind = QStringLiteral("reading"); + break; + case ReadingListModel::TypeSpecialList::Recent: + kind = QStringLiteral("recent"); + recentDays = settings->value(NUM_DAYS_TO_CONSIDER_RECENT, 1).toInt(); + break; + } + break; + } + case ReadingListModel::Label: { + kind = QStringLiteral("tag"); + labelColor = listIndex.data(ReadingListModel::LabelColorRole).toInt(); + break; + } + case ReadingListModel::ReadingList: { + kind = QStringLiteral("readingList"); + sublistCount = listIndex.model()->rowCount(listIndex); + break; + } + case ReadingListModel::Separator: + return; + } + + currentLocationInfo = { + { QStringLiteral("kind"), kind }, + { QStringLiteral("name"), listIndex.data(Qt::DisplayRole).toString() }, + { QStringLiteral("itemCount"), model ? model->rowCount() : 0 }, + { QStringLiteral("labelColor"), labelColor }, + { QStringLiteral("recentDays"), recentDays }, + { QStringLiteral("sublistCount"), sublistCount }, + }; + updateCurrentListIcon(); + emit currentLocationInfoChanged(); +} + +void GridComicsView::updateCurrentListIcon() +{ + const auto kind = currentLocationInfo.value(QStringLiteral("kind")).toString(); + QPixmap icon; + + if (kind == QStringLiteral("favorites")) + icon = theme.emptyContainer.emptyFavoritesIcon; + else if (kind == QStringLiteral("reading")) + icon = theme.emptyContainer.emptyCurrentReadingsIcon; + else if (kind == QStringLiteral("recent")) + icon = theme.emptyContainer.emptyRecentIcon; + else if (kind == QStringLiteral("tag")) + icon = theme.emptyContainer.emptyLabelIcons.value(currentLocationInfo.value(QStringLiteral("labelColor")).toInt()); + else if (kind == QStringLiteral("readingList")) + icon = theme.emptyContainer.emptyReadingListIcon; + else + return; + + currentLocationInfo.insert(QStringLiteral("icon"), pixmapDataUrl(icon)); +} + +void GridComicsView::setRootContinueReadingModel(std::unique_ptr model) +{ + rootContinueReadingModelStorage = std::move(model); + emit rootContinueReadingModelChanged(); +} + +void GridComicsView::clearRootContinueReadingModel() +{ + setRootContinueReadingModel(nullptr); +} + +ComicModel *GridComicsView::rootContinueReadingModel() const +{ + return rootContinueReadingModelStorage.get(); +} + +bool GridComicsView::isRootFolder() const +{ + return rootFolder; +} + +bool GridComicsView::isGlobalContinueReadingEnabled() const +{ + return globalContinueReadingEnabled; +} + +bool GridComicsView::isCurrentComicBannerVisible() const +{ + return currentComicBannerVisible; +} + +int GridComicsView::focusedFolderRow() const +{ + return focusedFolderIndex.isValid() ? focusedFolderIndex.row() : -1; +} + +QVariantMap GridComicsView::folderInfoForFocusedFolder() const +{ + return focusedFolderInfo; +} + +QVariantMap GridComicsView::locationInfo() const +{ + return currentLocationInfo; +} + +bool GridComicsView::hasComicSelection() const +{ + return selectionHelper->numItemsSelected() > 0; +} + +int GridComicsView::selectedComicCount() const +{ + return selectionHelper->numItemsSelected(); +} + +QVariantMap GridComicsView::selectedComicsInfo() const +{ + return selectionHelper->selectionInfo(); +} + +void GridComicsView::reloadRootContinueReadingModel() +{ + if (rootFolder && rootContinueReadingModelStorage) + rootContinueReadingModelStorage->reloadContinueReading(); +} + +ContentViewState GridComicsView::captureViewState() const +{ + ContentViewState state; + auto *rootObject = view->rootObject(); + auto *scrollView = rootObject ? rootObject->findChild(QStringLiteral("topScrollView"), Qt::FindChildrenRecursively) : nullptr; + if (!scrollView) + return state; + + QVariant position; + QMetaObject::invokeMethod(scrollView, "capturePosition", Q_RETURN_ARG(QVariant, position)); + const auto values = position.toMap(); + const auto viewRow = values.value(QStringLiteral("viewRow"), -1).toInt(); + + state.offset = values.value(QStringLiteral("offset")).toReal(); + state.itemExtent = values.value(QStringLiteral("itemExtent")).toReal(); + if (model && model->rowCount() > 0) + state.fallbackComicRow = qBound(0, contentModel->sourceComicRow(viewRow), model->rowCount() - 1); + + if (values.value(QStringLiteral("header")).toBool()) { + state.topItem.kind = ContentItemRef::Header; + } else if (viewRow >= 0 && viewRow < contentModel->rowCount()) { + const auto index = contentModel->index(viewRow, 0); + const auto kind = contentModel->data(index, GridContentModel::ItemKindRole).toInt(); + state.topItem.kind = kind == GridContentModel::FolderItem ? ContentItemRef::Folder : ContentItemRef::Comic; + state.topItem.id = contentModel->data(index, GridContentModel::IdRole).toULongLong(); + } + + if (focusedFolderIndex.isValid()) { + state.currentItem.kind = ContentItemRef::Folder; + state.currentItem.id = focusedFolderIndex.data(FolderModel::IdRole).toULongLong(); + } else if (const auto index = selectionHelper->currentIndex(); index.isValid()) { + state.currentItem.kind = ContentItemRef::Comic; + state.currentItem.id = index.data(ComicModel::IdRole).toULongLong(); + } + + return state; +} + +void GridComicsView::restoreViewState(const ContentViewState &state) +{ + pendingViewState = state; + viewStateTimer->start(0); +} + +void GridComicsView::openContinueReadingComic(int sourceRow) +{ + if (!rootContinueReadingModelStorage || sourceRow < 0 || sourceRow >= rootContinueReadingModelStorage->rowCount()) + return; + + emit openComic(rootContinueReadingModelStorage->getComic(rootContinueReadingModelStorage->index(sourceRow, 0)), ComicModel::Folder); +} + +void GridComicsView::requestContinueReadingComicContextMenu(const QPoint &point, int sourceRow) +{ + if (!rootContinueReadingModelStorage || sourceRow < 0 || sourceRow >= rootContinueReadingModelStorage->rowCount()) + return; + + emit openContinueReadingComicContextMenu(point, rootContinueReadingModelStorage->getComic(rootContinueReadingModelStorage->index(sourceRow, 0))); +} + +void GridComicsView::openFolder(int viewRow) +{ + const QPersistentModelIndex sourceIndex(contentModel->sourceFolderIndex(viewRow)); + if (!sourceIndex.isValid()) + return; + + // setupFolderModelData()/setFolderModel() reset the model that owns the QML + // delegate. Defer navigation until Qt Quick finishes dispatching the event. + QTimer::singleShot(0, this, [this, sourceIndex]() { + if (sourceIndex.isValid()) + emit folderSelected(sourceIndex); + }); +} + +void GridComicsView::focusItem(int viewRow) +{ + if (contentModel->isSpacerRow(viewRow)) + return; + + if (contentModel->isFolderRow(viewRow)) { + selectionHelper->clear(); + setFocusedFolder(viewRow); + return; + } + + const auto sourceRow = contentModel->sourceComicRow(viewRow); + if (sourceRow >= 0 && model && sourceRow < model->rowCount()) + setCurrentIndex(model->index(sourceRow, 0)); +} + +void GridComicsView::selectComicRange(int from, int to) +{ + clearFocusedFolder(); + + if (from > to) + std::swap(from, to); + + const auto firstComic = qMax(from, contentModel->viewRowForComicRow(0)); + const auto lastComic = qMin(to, contentModel->rowCount() - 1); + for (auto row = firstComic; row <= lastComic; ++row) + selectionHelper->selectIndex(contentModel->sourceComicRow(row)); +} + +int GridComicsView::viewRowForComicRow(int sourceRow) const +{ + return contentModel->viewRowForComicRow(sourceRow); +} + +void GridComicsView::setGridColumnCount(int columns) +{ + contentModel->setGridColumnCount(columns); +} + +int GridComicsView::nearestSelectableRow(int viewRow, int direction) const +{ + if (!contentModel->isSpacerRow(viewRow)) + return viewRow; + + return direction < 0 ? contentModel->visibleFolderCount() - 1 : contentModel->viewRowForComicRow(0); +} + void GridComicsView::setCoversSize(int width) { QQmlContext *ctxt = view->rootContext(); @@ -370,13 +816,7 @@ void GridComicsView::updateCoversSizeInContext(int width, QQmlContext *ctxt) ctxt->setContextProperty("coverHeight", (width * YACREADER_MAX_COVER_HEIGHT) / YACREADER_MIN_COVER_WIDTH); } -void GridComicsView::dummyUpdater() -{ - QQmlContext *ctxt = view->rootContext(); - ctxt->setContextProperty("dummyValue", true); -} - -void GridComicsView::setCurrentComicIfNeeded() +void GridComicsView::updateCurrentComicBanner() { if (model == nullptr) { return; @@ -389,24 +829,151 @@ void GridComicsView::setCurrentComicIfNeeded() ComicModel::Mode mode = model->getMode(); - bool showCurrentComic = found && + const bool showCurrentComic = found && filterEnabled == false && (mode == ComicModel::Mode::Folder || mode == ComicModel::Mode::ReadingList) && settings->value(DISPLAY_CONTINUE_READING_IN_GRID_VIEW, true).toBool(); ctxt->setContextProperty("currentComic", ¤tComic); ctxt->setContextProperty("currentComicInfo", &(currentComic.info)); - ctxt->setContextProperty("showCurrentComic", QVariant(showCurrentComic)); + if (currentComicBannerVisible != showCurrentComic) { + currentComicBannerVisible = showCurrentComic; + emit currentComicBannerVisibleChanged(); + } +} + +void GridComicsView::clearFolderFocus() +{ + clearFocusedFolder(); +} + +QVariantMap GridComicsView::makeFolderInfo(const Folder &folder, const QVariant &cover) const +{ + QString typeName; + switch (folder.type) { + case YACReader::FileType::Manga: + typeName = tr("Manga"); + break; + case YACReader::FileType::WesternManga: + typeName = tr("Western manga"); + break; + case YACReader::FileType::WebComic: + typeName = tr("Web comic"); + break; + case YACReader::FileType::Yonkoma: + typeName = tr("Yonkoma"); + break; + case YACReader::FileType::Comic: + default: + typeName = tr("Comic"); + break; + } + + const QVariant itemCount = folder.numChildren < 0 ? QVariant(tr("Unknown")) : QVariant(folder.numChildren); + return { + { QStringLiteral("kind"), QStringLiteral("folder") }, + { QStringLiteral("name"), folder.name }, + { QStringLiteral("path"), folder.path }, + { QStringLiteral("cover"), cover }, + { QStringLiteral("itemCount"), itemCount }, + { QStringLiteral("typeName"), typeName }, + { QStringLiteral("finished"), folder.finished }, + { QStringLiteral("completed"), folder.completed }, + { QStringLiteral("added"), folder.added }, + { QStringLiteral("updated"), folder.updated }, + }; } -void GridComicsView::resetScroll() +void GridComicsView::setFocusedFolder(int viewRow) +{ + if (!contentModel->isFolderRow(viewRow)) { + clearFocusedFolder(); + return; + } + + const auto sourceIndex = contentModel->sourceFolderIndex(viewRow); + if (!sourceIndex.isValid()) { + clearFocusedFolder(); + return; + } + + focusedFolderIndex = sourceIndex; + focusedFolderInfo = makeFolderInfo(contentModel->folderAt(viewRow), sourceIndex.data(FolderModel::CoverPathRole)); + emit focusedFolderChanged(); +} + +void GridComicsView::clearFocusedFolder() +{ + if (!focusedFolderIndex.isValid() && focusedFolderInfo.isEmpty()) + return; + + focusedFolderIndex = QModelIndex(); + focusedFolderInfo.clear(); + emit focusedFolderChanged(); +} + +void GridComicsView::applyPendingViewState() { auto *rootObject = view->rootObject(); - if (!rootObject) + if (!rootObject) { + view->setUpdatesEnabled(true); return; + } auto scrollView = rootObject->findChild("topScrollView", Qt::FindChildrenRecursively); + if (!scrollView) { + view->setUpdatesEnabled(true); + return; + } + + if (!pendingViewState) { + QMetaObject::invokeMethod(scrollView, "scrollToOrigin"); + view->setUpdatesEnabled(true); + view->update(); + return; + } + + const auto state = *pendingViewState; + pendingViewState.reset(); + + if (state.currentItem.kind != ContentItemRef::None) { + const auto currentRow = viewRowForItem(state.currentItem); + if (currentRow >= 0) + focusItem(currentRow); + } + + auto viewRow = viewRowForItem(state.topItem); + if (state.topItem.kind == ContentItemRef::Header) { + viewRow = -1; + } else if (viewRow < 0 && contentModel->rowCount() > 0) { + if (model && model->rowCount() > 0 && state.fallbackComicRow >= 0) { + const auto comicRow = qBound(0, state.fallbackComicRow, model->rowCount() - 1); + viewRow = contentModel->viewRowForComicRow(comicRow); + } else { + viewRow = 0; + } + viewRow = nearestSelectableRow(viewRow, 1); + } + + QMetaObject::invokeMethod(scrollView, "restorePosition", + Q_ARG(QVariant, viewRow), + Q_ARG(QVariant, state.offset), + Q_ARG(QVariant, state.itemExtent)); + view->setUpdatesEnabled(true); + view->update(); +} - QMetaObject::invokeMethod(scrollView, "scrollToOrigin"); +int GridComicsView::viewRowForItem(const ContentItemRef &item) const +{ + switch (item.kind) { + case ContentItemRef::Comic: + return contentModel->viewRowForComicId(item.id); + case ContentItemRef::Folder: + return contentModel->viewRowForFolderId(item.id); + case ContentItemRef::None: + case ContentItemRef::Header: + return -1; + } + return -1; } void GridComicsView::showEvent(QShowEvent *event) @@ -432,7 +999,7 @@ QByteArray GridComicsView::getMimeDataFromSelection() void GridComicsView::updateCurrentComicView() { - setCurrentComicIfNeeded(); + updateCurrentComicBanner(); } void GridComicsView::focusComicsNavigation(Qt::FocusReason reason) @@ -450,7 +1017,7 @@ void GridComicsView::startDrag() { auto drag = new QDrag(this); drag->setMimeData(model->mimeData(selectionHelper->selectedRows())); - drag->setPixmap(hdpiPixmap(":/images/comics_view_toolbar/openInYACReader.svg", QSize(18, 18))); // TODO add better image + drag->setPixmap(theme.comicsViewToolbar.openInYACReaderIcon.pixmap(18, 18)); // TODO add better image /*Qt::DropAction dropAction =*/drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction); } @@ -469,7 +1036,12 @@ bool GridComicsView::canDropUrls(const QList &urls, Qt::DropAction action) return false; } -bool GridComicsView::canDropFormats(const QString &formats) +bool GridComicsView::canDropImage(const QList &urls) +{ + return !YACReader::droppedImagePath(urls).isEmpty(); +} + +bool GridComicsView::canDropFormats(const QStringList &formats) { return (formats.contains(YACReader::YACReaderLibrarComiscSelectionMimeDataFormat) && model->canBeResorted()); } @@ -484,16 +1056,42 @@ void GridComicsView::droppedFiles(const QList &urls, Qt::DropAction action } } +void GridComicsView::droppedImageAt(const QList &urls, int viewRow) +{ + const auto imagePath = YACReader::droppedImagePath(urls); + if (imagePath.isEmpty() || viewRow < 0 || viewRow >= contentModel->rowCount()) + return; + + if (contentModel->isFolderRow(viewRow)) { + emit customFolderCoverRequested(contentModel->folderAt(viewRow).id, imagePath); + return; + } + + const auto comicRow = contentModel->sourceComicRow(viewRow); + const auto comicIndex = model && comicRow >= 0 ? model->index(comicRow, 0) : QModelIndex(); + if (comicIndex.isValid()) + emit customComicCoverRequested(comicIndex.data(ComicModel::IdRole).toULongLong(), imagePath); +} + void GridComicsView::droppedComicsForResortingAt(const QString &data, int index) { Q_UNUSED(data); - model->dropMimeData(model->mimeData(selectionHelper->selectedRows()), Qt::MoveAction, index, 0, QModelIndex()); + const auto comicIndex = qBound(0, contentModel->sourceComicRow(index), model->rowCount()); + model->dropMimeData(model->mimeData(selectionHelper->selectedRows()), Qt::MoveAction, comicIndex, 0, QModelIndex()); } -void GridComicsView::selectedItem(int index) +void GridComicsView::activateItem(int viewRow) { - emit selected(index); + if (viewRow < 0 || viewRow >= contentModel->rowCount() || contentModel->isSpacerRow(viewRow)) + return; + + if (contentModel->isFolderRow(viewRow)) { + openFolder(viewRow); + return; + } + + emit selected(contentModel->sourceComicRow(viewRow)); } void GridComicsView::applyTheme(const Theme &theme) @@ -501,6 +1099,9 @@ void GridComicsView::applyTheme(const Theme &theme) QQmlContext *ctxt = view->rootContext(); const auto &giv = theme.gridAndInfoView; + ctxt->setContextProperty("continueReadingBackgroundColor", giv.continueReadingBackgroundColor); + ctxt->setContextProperty("continueReadingTextColor", giv.continueReadingTextColor); + // Grid colors ctxt->setContextProperty("backgroundColor", giv.backgroundColor); ctxt->setContextProperty("backgroundBlurOverlayColor", giv.backgroundBlurOverlayColor); @@ -538,6 +1139,11 @@ void GridComicsView::applyTheme(const Theme &theme) ctxt->setContextProperty("scrollbarBorderColor", giv.scrollbarBorderColor); ctxt->setContextProperty("infoScrollbarColor", giv.infoScrollbarColor); ctxt->setContextProperty("comicCoverBorderColor", giv.comicCoverBorderColor); + ctxt->setContextProperty("folderCoverBorderColor", giv.folderCoverBorderColor); + ctxt->setContextProperty("placeholderFolder1Color", giv.placeholderFolder1Color); + ctxt->setContextProperty("placeholderFolder1BorderColor", giv.placeholderFolder1BorderColor); + ctxt->setContextProperty("placeholderFolder2Color", giv.placeholderFolder2Color); + ctxt->setContextProperty("placeholderFolder2BorderColor", giv.placeholderFolder2BorderColor); ctxt->setContextProperty("currentComicCoverShadowColor", giv.currentComicCoverShadowColor); ctxt->setContextProperty("buttonShadowColor", giv.buttonShadowColor); @@ -554,6 +1160,12 @@ void GridComicsView::applyTheme(const Theme &theme) if (bigZoomLabel) { bigZoomLabel->setPixmap(theme.comicsViewToolbar.bigGridZoomIcon.pixmap(18, 18)); } + + const auto locationKind = currentLocationInfo.value(QStringLiteral("kind")).toString(); + if (locationKind == QStringLiteral("favorites") || locationKind == QStringLiteral("reading") || locationKind == QStringLiteral("recent") || locationKind == QStringLiteral("tag") || locationKind == QStringLiteral("readingList")) { + updateCurrentListIcon(); + emit currentLocationInfoChanged(); + } } void GridComicsView::setShowMarks(bool show) @@ -564,16 +1176,8 @@ void GridComicsView::setShowMarks(bool show) void GridComicsView::closeEvent(QCloseEvent *event) { - toolbar->removeAction(startSeparatorAction); - toolbar->removeAction(showInfoAction); - toolbar->removeAction(showInfoSeparatorAction); - toolbar->removeAction(coverSizeSliderAction); - - int infoWidth = 0; - if (auto *rootObject = view->rootObject()) { - auto infoContainer = rootObject->findChild("infoContainer", Qt::FindChildrenRecursively); - infoWidth = QQmlProperty(infoContainer, "width").read().toInt(); - } + releaseToolBar(); + saveViewConfig(); /*QObject *object = view->rootObject(); QMetaObject::invokeMethod(object, "exit"); @@ -582,9 +1186,4 @@ void GridComicsView::closeEvent(QCloseEvent *event) event->accept(); ComicsView::closeEvent(event); - - // save settings - settings->setValue(COMICS_GRID_COVER_SIZES, coverSizeSlider->value()); - settings->setValue(COMICS_GRID_SHOW_INFO, showInfoAction->isChecked()); - settings->setValue(COMICS_GRID_INFO_WIDTH, infoWidth); } diff --git a/YACReaderLibrary/grid_comics_view.h b/YACReaderLibrary/grid_comics_view.h index b3b674fff..77d763024 100644 --- a/YACReaderLibrary/grid_comics_view.h +++ b/YACReaderLibrary/grid_comics_view.h @@ -7,15 +7,24 @@ #include #include +#include +#include + +#include +#include class QAbstractListModel; class QItemSelectionModel; class QQuickWidget; class QQmlContext; +class QTimer; class YACReaderToolBarStretch; class YACReaderComicsSelectionHelper; class YACReaderComicInfoHelper; +class GridContentModel; +class FolderModel; +class Folder; // values relative to visible cells const unsigned int YACREADER_MIN_GRID_ZOOM_WIDTH = 156; @@ -36,14 +45,53 @@ const unsigned int YACREADER_MIN_ITEM_WIDTH = YACREADER_MIN_COVER_WIDTH; class GridComicsView : public ComicsView, protected Themable { Q_OBJECT + Q_PROPERTY(ComicModel *rootContinueReadingModel READ rootContinueReadingModel NOTIFY rootContinueReadingModelChanged) + Q_PROPERTY(bool rootFolder READ isRootFolder NOTIFY rootFolderChanged) + Q_PROPERTY(bool globalContinueReadingEnabled READ isGlobalContinueReadingEnabled NOTIFY globalContinueReadingEnabledChanged) + Q_PROPERTY(bool currentComicBannerVisible READ isCurrentComicBannerVisible NOTIFY currentComicBannerVisibleChanged) + Q_PROPERTY(int focusedFolderRow READ focusedFolderRow NOTIFY focusedFolderChanged) + Q_PROPERTY(QVariantMap focusedFolderInfo READ folderInfoForFocusedFolder NOTIFY focusedFolderChanged) + Q_PROPERTY(QVariantMap currentLocationInfo READ locationInfo NOTIFY currentLocationInfoChanged) + Q_PROPERTY(bool hasComicSelection READ hasComicSelection NOTIFY comicSelectionStateChanged) + Q_PROPERTY(int selectedComicCount READ selectedComicCount NOTIFY selectedComicsInfoChanged) + Q_PROPERTY(QVariantMap selectedComicsInfo READ selectedComicsInfo NOTIFY selectedComicsInfoChanged) public: explicit GridComicsView(QWidget *parent = nullptr); + ComicModel *rootContinueReadingModel() const; + bool isRootFolder() const; + bool isGlobalContinueReadingEnabled() const; + bool isCurrentComicBannerVisible() const; + int focusedFolderRow() const; + QVariantMap folderInfoForFocusedFolder() const; + QVariantMap locationInfo() const; + bool hasComicSelection() const; + int selectedComicCount() const; + QVariantMap selectedComicsInfo() const; + void setFolderModel(FolderModel *model, const QModelIndex &folderIndex, const QString &rootName = { }, const QVariantMap &libraryInfo = { }); + void clearFolderModel(); + void setCurrentList(const QModelIndex &listIndex); + void setModel(ComicModel *model) override; + void setRootContinueReadingModel(std::unique_ptr model); + void clearRootContinueReadingModel(); + void reloadRootContinueReadingModel(); + + Q_INVOKABLE void requestOpenLibraryFolder(); + Q_INVOKABLE void openFolder(int viewRow); + Q_INVOKABLE void focusItem(int viewRow); + Q_INVOKABLE void clearFolderFocus(); + Q_INVOKABLE void selectComicRange(int from, int to); + Q_INVOKABLE int viewRowForComicRow(int sourceRow) const; + Q_INVOKABLE void setGridColumnCount(int columns); + Q_INVOKABLE int nearestSelectableRow(int viewRow, int direction) const; + Q_INVOKABLE void openContinueReadingComic(int sourceRow); + Q_INVOKABLE void requestContinueReadingComicContextMenu(const QPoint &point, int sourceRow); protected: void applyTheme(const Theme &theme) override; ~GridComicsView() override; void setToolBar(QToolBar *toolBar) override; - void setModel(ComicModel *model) override; + void releaseToolBar() override; + void saveViewConfig() override; void setCurrentIndex(const QModelIndex &index) override; QModelIndex currentIndex() override; QItemSelectionModel *selectionModel() override; @@ -56,6 +104,8 @@ class GridComicsView : public ComicsView, protected Themable void updateCurrentComicView() override; void focusComicsNavigation(Qt::FocusReason reason) override; void reloadContent() override; + ContentViewState captureViewState() const override; + void restoreViewState(const ContentViewState &state) override; public slots: // ComicsView @@ -64,13 +114,13 @@ public slots: void selectIndex(int index) override; void triggerOpenCurrentComic(); void updateSettings(); + void updateBannerSettings(); void updateBackgroundConfig(); - void showInfo(); + void updateInfoPanelVisibility(); protected slots: - void setCurrentIndex(int index); // QML - double clicked item - void selectedItem(int index); + void activateItem(int viewRow); // QML - rating void rate(int index, int rating); @@ -78,25 +128,37 @@ protected slots: void startDrag(); // QML - dropManager bool canDropUrls(const QList &urls, Qt::DropAction action); - bool canDropFormats(const QString &formats); + bool canDropImage(const QList &urls); + bool canDropFormats(const QStringList &formats); void droppedFiles(const QList &urls, Qt::DropAction action); + void droppedImageAt(const QList &urls, int viewRow); void droppedComicsForResortingAt(const QString &data, int index); // QML - context menu - void requestedContextMenu(const QPoint &point); + void requestItemContextMenu(const QPoint &point, int viewRow); void setCoversSize(int width); void updateCoversSizeInContext(int width, QQmlContext *ctxt); - void dummyUpdater(); // TODO remove this - - void setCurrentComicIfNeeded(); + void updateCurrentComicBanner(); - void resetScroll(); + void applyPendingViewState(); virtual void showEvent(QShowEvent *event) override; signals: void onScrollToOrigin(); + void folderSelected(const QModelIndex &index); + void openFolderContextMenu(const QPoint &point, const Folder &folder); + void openContinueReadingComicContextMenu(const QPoint &point, const ComicDB &comic); + void comicSelectionStateChanged(bool hasSelection); + void selectedComicsInfoChanged(); + void rootContinueReadingModelChanged(); + void rootFolderChanged(); + void globalContinueReadingEnabledChanged(); + void currentComicBannerVisibleChanged(); + void focusedFolderChanged(); + void currentLocationInfoChanged(); + void openLibraryFolderRequested(); private: QSettings *settings; @@ -112,12 +174,28 @@ protected slots: YACReaderComicsSelectionHelper *selectionHelper; YACReaderComicInfoHelper *comicInfoHelper; + GridContentModel *contentModel; + std::unique_ptr rootContinueReadingModelStorage; + bool rootFolder = false; + bool globalContinueReadingEnabled = true; + bool currentComicBannerVisible = false; + QPersistentModelIndex focusedFolderIndex; + QVariantMap focusedFolderInfo; + QVariantMap currentLocationInfo; + QTimer *viewStateTimer; + std::optional pendingViewState; + QMetaObject::Connection modelDataChangedConnection; + QMetaObject::Connection modelFavoritesChangedConnection; ComicDB currentComic; - bool dummy; void closeEvent(QCloseEvent *event) override; void createCoverSizeSliderWidget(); + QVariantMap makeFolderInfo(const Folder &folder, const QVariant &cover) const; + void updateCurrentListIcon(); + void setFocusedFolder(int viewRow); + void clearFocusedFolder(); + int viewRowForItem(const ContentItemRef &item) const; // Zoom slider labels (for theming) QLabel *smallZoomLabel; diff --git a/YACReaderLibrary/grid_content_model.cpp b/YACReaderLibrary/grid_content_model.cpp new file mode 100644 index 000000000..d6fee766a --- /dev/null +++ b/YACReaderLibrary/grid_content_model.cpp @@ -0,0 +1,388 @@ +#include "grid_content_model.h" + +#include "comic_model.h" +#include "folder_model.h" + +#include + +GridContentModel::GridContentModel(QObject *parent) + : QAbstractListModel(parent) +{ +} + +int GridContentModel::rowCount(const QModelIndex &parent) const +{ + if (parent.isValid()) + return 0; + + const auto comics = comicModel ? comicModel->rowCount() : 0; + return visibleFolderCount() + spacerCount() + comics; +} + +QVariant GridContentModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid() || index.row() < 0 || index.row() >= rowCount()) + return { }; + + if (isFolderRow(index.row())) { + const auto sourceIndex = sourceFolderIndex(index.row()); + switch (role) { + case ItemKindRole: + return FolderItem; + case SourceIndexRole: + return sourceIndex.row(); + case TitleRole: + case FileNameRole: + return sourceIndex.data(FolderModel::FolderNameRole); + case IdRole: + return sourceIndex.data(FolderModel::IdRole); + case CoverPathRole: + return sourceIndex.data(FolderModel::CoverPathRole); + case AddedRole: + return sourceIndex.data(FolderModel::AddedRole); + case TypeRole: + return sourceIndex.data(FolderModel::TypeRole); + case ShowRecentRole: + return sourceIndex.data(FolderModel::ShowRecentRole); + case RecentRangeRole: + return sourceIndex.data(FolderModel::RecentRangeRole); + case UpdatedRole: + return sourceIndex.data(FolderModel::UpdatedRole); + case FinishedRole: + return sourceIndex.data(FolderModel::FinishedRole); + default: + return { }; + } + } + + if (isSpacerRow(index.row())) { + if (role == ItemKindRole) + return SpacerItem; + if (role == SourceIndexRole) + return -1; + return { }; + } + + if (!comicModel) + return { }; + + const auto sourceRow = sourceComicRow(index.row()); + const auto sourceIndex = comicModel->index(sourceRow, 0); + switch (role) { + case ItemKindRole: + return ComicItem; + case SourceIndexRole: + return sourceRow; + case NumberRole: + return sourceIndex.data(ComicModel::NumberRole); + case TitleRole: + return sourceIndex.data(ComicModel::TitleRole); + case FileNameRole: + return sourceIndex.data(ComicModel::FileNameRole); + case NumPagesRole: + return sourceIndex.data(ComicModel::NumPagesRole); + case IdRole: + return sourceIndex.data(ComicModel::IdRole); + case ReadRole: + return sourceIndex.data(ComicModel::ReadColumnRole); + case CurrentPageRole: + return sourceIndex.data(ComicModel::CurrentPageRole); + case RatingRole: + return sourceIndex.data(ComicModel::RatingRole); + case HasBeenOpenedRole: + return sourceIndex.data(ComicModel::HasBeenOpenedRole); + case CoverPathRole: + return sourceIndex.data(ComicModel::CoverPathRole); + case AddedRole: + return sourceIndex.data(ComicModel::AddedRole); + case TypeRole: + return sourceIndex.data(ComicModel::TypeRole); + case ShowRecentRole: + return sourceIndex.data(ComicModel::ShowRecentRole); + case RecentRangeRole: + return sourceIndex.data(ComicModel::RecentRangeRole); + default: + return { }; + } +} + +QHash GridContentModel::roleNames() const +{ + return { + { ItemKindRole, "item_kind" }, + { SourceIndexRole, "source_index" }, + { NumberRole, "number" }, + { TitleRole, "title" }, + { FileNameRole, "file_name" }, + { NumPagesRole, "num_pages" }, + { IdRole, "id" }, + { ReadRole, "read_column" }, + { CurrentPageRole, "current_page" }, + { RatingRole, "rating" }, + { HasBeenOpenedRole, "has_been_opened" }, + { CoverPathRole, "cover_path" }, + { AddedRole, "added_date" }, + { TypeRole, "type" }, + { ShowRecentRole, "show_recent" }, + { RecentRangeRole, "recent_range" }, + { UpdatedRole, "updated" }, + { FinishedRole, "is_finished" }, + }; +} + +void GridContentModel::setComicModel(ComicModel *model) +{ + if (comicModel == model) + return; + + beginResetModel(); + comicModel = model; + endResetModel(); + reconnectModels(); +} + +void GridContentModel::setFolderModel(FolderModel *model, const QModelIndex &folderIndex) +{ + beginResetModel(); + folderModel = model; + selectedFolderIndex = folderIndex; + selectedFolderIsRoot = model && !folderIndex.isValid(); + endResetModel(); + reconnectModels(); +} + +void GridContentModel::clearFolderModel() +{ + setFolderModel(nullptr, { }); +} + +void GridContentModel::setMixFoldersAndComics(bool enabled) +{ + if (mixFoldersAndComics == enabled) + return; + + beginResetModel(); + mixFoldersAndComics = enabled; + endResetModel(); +} + +void GridContentModel::setStartComicsOnNewRow(bool enabled) +{ + if (startComicsOnNewRow == enabled) + return; + + beginResetModel(); + startComicsOnNewRow = enabled; + endResetModel(); +} + +void GridContentModel::setGridColumnCount(int columns) +{ + columns = qMax(1, columns); + if (gridColumnCount == columns) + return; + + const auto previousSpacerCount = spacerCount(); + gridColumnCount = columns; + if (previousSpacerCount != spacerCount()) + resetFromSource(); +} + +bool GridContentModel::isFolderRow(int viewRow) const +{ + return viewRow >= 0 && viewRow < visibleFolderCount(); +} + +bool GridContentModel::isSpacerRow(int viewRow) const +{ + return viewRow >= visibleFolderCount() && viewRow < visibleFolderCount() + spacerCount(); +} + +int GridContentModel::visibleFolderCount() const +{ + const auto folders = sourceFolderCount(); + if (!mixFoldersAndComics && comicModel && comicModel->rowCount() > 0) + return 0; + return folders; +} + +int GridContentModel::sourceComicRow(int viewRow) const +{ + return viewRow - visibleFolderCount() - spacerCount(); +} + +int GridContentModel::viewRowForComicRow(int sourceRow) const +{ + return sourceRow < 0 ? -1 : visibleFolderCount() + spacerCount() + sourceRow; +} + +int GridContentModel::viewRowForComicId(qulonglong id) const +{ + if (!comicModel) + return -1; + + const auto sourceIndex = comicModel->getIndexFromId(id); + return sourceIndex.isValid() ? viewRowForComicRow(sourceIndex.row()) : -1; +} + +int GridContentModel::viewRowForFolderId(qulonglong id) const +{ + for (auto row = 0; row < visibleFolderCount(); ++row) { + if (data(index(row, 0), IdRole).toULongLong() == id) + return row; + } + return -1; +} + +QModelIndex GridContentModel::sourceFolderIndex(int viewRow) const +{ + if (!folderModel || !isFolderRow(viewRow)) + return { }; + const QModelIndex parent = selectedFolderIsRoot ? QModelIndex() : QModelIndex(selectedFolderIndex); + return folderModel->index(viewRow, 0, parent); +} + +Folder GridContentModel::folderAt(int viewRow) const +{ + if (!folderModel) + return { }; + + return folderModel->getFolder(sourceFolderIndex(viewRow)); +} + +QUrl GridContentModel::comicCoverUrlForHash(const QString &hash) const +{ + return comicModel ? comicModel->getCoverUrlPathForComicHash(hash) : QUrl(); +} + +void GridContentModel::reconnectModels() +{ + for (const auto &connection : std::as_const(sourceConnections)) + disconnect(connection); + sourceConnections.clear(); + + if (folderModel) { + sourceConnections << connect(folderModel, &QAbstractItemModel::modelReset, this, &GridContentModel::resetFromSource); + sourceConnections << connect(folderModel, &QAbstractItemModel::rowsAboutToBeInserted, this, [this](const QModelIndex &parent, int first, int last) { + if (parent == selectedFolderIndex && forwardsFolderRowsDirectly()) + beginInsertRows({ }, first, last); + }); + sourceConnections << connect(folderModel, &QAbstractItemModel::rowsInserted, this, [this](const QModelIndex &parent) { + if (parent != selectedFolderIndex) + return; + if (forwardsFolderRowsDirectly()) + endInsertRows(); + else if (mixFoldersAndComics) + resetFromSource(); + }); + sourceConnections << connect(folderModel, &QAbstractItemModel::rowsAboutToBeRemoved, this, [this](const QModelIndex &parent, int first, int last) { + if (parent == selectedFolderIndex && forwardsFolderRowsDirectly()) + beginRemoveRows({ }, first, last); + }); + sourceConnections << connect(folderModel, &QAbstractItemModel::rowsRemoved, this, [this](const QModelIndex &parent) { + if (parent != selectedFolderIndex) + return; + if (forwardsFolderRowsDirectly()) + endRemoveRows(); + else if (mixFoldersAndComics) + resetFromSource(); + }); + sourceConnections << connect(folderModel, &QAbstractItemModel::dataChanged, this, [this](const QModelIndex &topLeft, const QModelIndex &bottomRight) { + if (visibleFolderCount() > 0 && topLeft.parent() == selectedFolderIndex && bottomRight.parent() == selectedFolderIndex) + emit dataChanged(index(topLeft.row()), index(bottomRight.row())); + }); + } + + if (comicModel) { + sourceConnections << connect(comicModel, &QAbstractItemModel::modelReset, this, &GridContentModel::resetFromSource); + sourceConnections << connect(comicModel, &QAbstractItemModel::rowsAboutToBeInserted, this, [this](const QModelIndex &parent, int first, int last) { + if (parent.isValid()) + return; + if (!forwardsComicRowsDirectly()) + return; + const auto offset = visibleFolderCount(); + beginInsertRows({ }, offset + first, offset + last); + }); + sourceConnections << connect(comicModel, &QAbstractItemModel::rowsInserted, this, [this](const QModelIndex &parent) { + if (parent.isValid()) + return; + if (forwardsComicRowsDirectly()) + endInsertRows(); + else + resetFromSource(); + }); + sourceConnections << connect(comicModel, &QAbstractItemModel::rowsAboutToBeRemoved, this, [this](const QModelIndex &parent, int first, int last) { + if (parent.isValid()) + return; + if (!forwardsComicRowsDirectly()) + return; + const auto offset = visibleFolderCount(); + beginRemoveRows({ }, offset + first, offset + last); + }); + sourceConnections << connect(comicModel, &QAbstractItemModel::rowsRemoved, this, [this](const QModelIndex &parent) { + if (parent.isValid()) + return; + if (forwardsComicRowsDirectly()) + endRemoveRows(); + else + resetFromSource(); + }); + sourceConnections << connect(comicModel, &QAbstractItemModel::rowsAboutToBeMoved, this, [this](const QModelIndex &sourceParent, int first, int last, const QModelIndex &destinationParent, int destination) { + if (sourceParent.isValid() || destinationParent.isValid()) + return; + if (!forwardsComicRowsDirectly()) + return; + const auto offset = visibleFolderCount(); + beginMoveRows({ }, offset + first, offset + last, { }, offset + destination); + }); + sourceConnections << connect(comicModel, &QAbstractItemModel::rowsMoved, this, [this](const QModelIndex &sourceParent, int, int, const QModelIndex &destinationParent) { + if (sourceParent.isValid() || destinationParent.isValid()) + return; + if (forwardsComicRowsDirectly()) + endMoveRows(); + else + resetFromSource(); + }); + sourceConnections << connect(comicModel, &QAbstractItemModel::dataChanged, this, [this](const QModelIndex &topLeft, const QModelIndex &bottomRight) { + if (topLeft.parent().isValid() || bottomRight.parent().isValid()) + return; + emit dataChanged(index(viewRowForComicRow(topLeft.row())), index(viewRowForComicRow(bottomRight.row()))); + }); + } +} + +void GridContentModel::resetFromSource() +{ + beginResetModel(); + endResetModel(); +} + +int GridContentModel::sourceFolderCount() const +{ + if (!folderModel) + return 0; + if (selectedFolderIsRoot) + return folderModel->rowCount(); + return selectedFolderIndex.isValid() ? folderModel->rowCount(selectedFolderIndex) : 0; +} + +int GridContentModel::spacerCount() const +{ + const auto folders = visibleFolderCount(); + const auto comics = comicModel ? comicModel->rowCount() : 0; + if (!mixFoldersAndComics || !startComicsOnNewRow || folders == 0 || comics == 0) + return 0; + + return (gridColumnCount - (folders % gridColumnCount)) % gridColumnCount; +} + +bool GridContentModel::forwardsFolderRowsDirectly() const +{ + const auto comics = comicModel ? comicModel->rowCount() : 0; + return comics == 0 || (mixFoldersAndComics && !startComicsOnNewRow); +} + +bool GridContentModel::forwardsComicRowsDirectly() const +{ + return mixFoldersAndComics && !startComicsOnNewRow; +} diff --git a/YACReaderLibrary/grid_content_model.h b/YACReaderLibrary/grid_content_model.h new file mode 100644 index 000000000..6df74bc8f --- /dev/null +++ b/YACReaderLibrary/grid_content_model.h @@ -0,0 +1,87 @@ +#ifndef GRID_CONTENT_MODEL_H +#define GRID_CONTENT_MODEL_H + +#include +#include +#include + +class ComicModel; +class FolderModel; +class Folder; + +class GridContentModel : public QAbstractListModel +{ + Q_OBJECT + +public: + enum ItemKind { + FolderItem = 0, + ComicItem, + SpacerItem + }; + Q_ENUM(ItemKind) + + enum Roles { + ItemKindRole = Qt::UserRole + 1, + SourceIndexRole, + NumberRole, + TitleRole, + FileNameRole, + NumPagesRole, + IdRole, + ReadRole, + CurrentPageRole, + RatingRole, + HasBeenOpenedRole, + CoverPathRole, + AddedRole, + TypeRole, + ShowRecentRole, + RecentRangeRole, + UpdatedRole, + FinishedRole + }; + + explicit GridContentModel(QObject *parent = nullptr); + + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role) const override; + QHash roleNames() const override; + + void setComicModel(ComicModel *model); + void setFolderModel(FolderModel *model, const QModelIndex &selectedFolderIndex); + void clearFolderModel(); + void setMixFoldersAndComics(bool enabled); + void setStartComicsOnNewRow(bool enabled); + void setGridColumnCount(int columns); + + bool isFolderRow(int viewRow) const; + bool isSpacerRow(int viewRow) const; + int visibleFolderCount() const; + int sourceComicRow(int viewRow) const; + int viewRowForComicRow(int sourceRow) const; + int viewRowForComicId(qulonglong id) const; + int viewRowForFolderId(qulonglong id) const; + QModelIndex sourceFolderIndex(int viewRow) const; + Folder folderAt(int viewRow) const; + Q_INVOKABLE QUrl comicCoverUrlForHash(const QString &hash) const; + +private: + void reconnectModels(); + void resetFromSource(); + int sourceFolderCount() const; + int spacerCount() const; + bool forwardsFolderRowsDirectly() const; + bool forwardsComicRowsDirectly() const; + + ComicModel *comicModel = nullptr; + FolderModel *folderModel = nullptr; + QPersistentModelIndex selectedFolderIndex; + bool selectedFolderIsRoot = false; + bool mixFoldersAndComics = true; + bool startComicsOnNewRow = false; + int gridColumnCount = 1; + QList sourceConnections; +}; + +#endif // GRID_CONTENT_MODEL_H diff --git a/YACReaderLibrary/import_widget.cpp b/YACReaderLibrary/import_widget.cpp index 335ccda12..06305f97d 100644 --- a/YACReaderLibrary/import_widget.cpp +++ b/YACReaderLibrary/import_widget.cpp @@ -215,7 +215,8 @@ void ImportWidget::newComic(const QString &path, const QString &coverPath) previousWidth += 10 + p.width(); - for (auto *itemToRemove : coversScene->items()) { + const auto items = coversScene->items(); + for (auto *itemToRemove : items) { auto last = dynamic_cast(itemToRemove); if ((last->pos().x() + last->pixmap().width()) < coversView->horizontalScrollBar()->value()) // TODO check this @@ -255,7 +256,7 @@ void ImportWidget::addCoverTest() previousWidth += 10 + p.width(); coversScene->addItem(item); if (previousWidth >= coversView->width()) { - QGraphicsItem *last = coversScene->items().last(); + QGraphicsItem *last = coversScene->items().constLast(); int width = p.width(); if (j >= 1) { coversScene->removeItem(last); @@ -263,7 +264,8 @@ void ImportWidget::addCoverTest() } else j++; - for (auto *itemToMove : coversScene->items()) { + const auto items = coversScene->items(); + for (auto *itemToMove : items) { auto timer = new QTimeLine(/*350*/ 1000); timer->setFrameRange(0, 60); diff --git a/YACReaderLibrary/info_comics_view.cpp b/YACReaderLibrary/info_comics_view.cpp index 3bcaa6623..2e6ca9d7b 100644 --- a/YACReaderLibrary/info_comics_view.cpp +++ b/YACReaderLibrary/info_comics_view.cpp @@ -4,6 +4,7 @@ #include "comic.h" #include "comic_files_manager.h" #include "comic_model.h" +#include "cover_utils.h" #include "yacreader_comic_info_helper.h" #include "yacreader_comics_selection_helper.h" @@ -14,7 +15,7 @@ #include InfoComicsView::InfoComicsView(QWidget *parent) - : ComicsView(parent), flow(nullptr), list(nullptr) + : ComicsView(parent), toolbar(nullptr), flow(nullptr), list(nullptr) { // container->setFocusPolicy(Qt::StrongFocus); @@ -53,7 +54,11 @@ InfoComicsView::~InfoComicsView() void InfoComicsView::setToolBar(QToolBar *toolBar) { static_cast(this->layout())->insertWidget(1, toolBar); - this->toolbar = toolBar; + toolbar = toolBar; +} + +void InfoComicsView::releaseToolBar() +{ } void InfoComicsView::setModel(ComicModel *model) @@ -143,6 +148,36 @@ void InfoComicsView::scrollTo(const QModelIndex &mi, QAbstractItemView::ScrollHi Q_UNUSED(hint); } +ContentViewState InfoComicsView::captureViewState() const +{ + ContentViewState state; + const auto index = selectionHelper->currentIndex(); + if (index.isValid()) { + state.topItem.kind = ContentItemRef::Comic; + state.topItem.id = index.data(ComicModel::IdRole).toULongLong(); + state.fallbackComicRow = index.row(); + state.currentItem = state.topItem; + } + return state; +} + +void InfoComicsView::restoreViewState(const ContentViewState &state) +{ + if (!model || model->rowCount() == 0) + return; + + auto index = state.currentItem.kind == ContentItemRef::Comic ? model->getIndexFromId(state.currentItem.id) : QModelIndex(); + if (!index.isValid() && state.fallbackComicRow >= 0) + index = model->index(qBound(0, state.fallbackComicRow, model->rowCount() - 1), 0); + if (!index.isValid()) + return; + + selectionHelper->clear(); + selectionHelper->selectIndex(index.row()); + if (list) + QMetaObject::invokeMethod(list, "restoreCurrentIndex", Q_ARG(QVariant, index.row())); +} + void InfoComicsView::toFullScreen() { toolbar->hide(); @@ -202,6 +237,11 @@ bool InfoComicsView::canDropUrls(const QList &urls, Qt::DropAction action) return false; } +bool InfoComicsView::canDropImage(const QList &urls) +{ + return !YACReader::droppedImagePath(urls).isEmpty() && currentIndex().isValid(); +} + void InfoComicsView::droppedFiles(const QList &urls, Qt::DropAction action) { bool validAction = action == Qt::CopyAction; // TODO add move @@ -212,6 +252,14 @@ void InfoComicsView::droppedFiles(const QList &urls, Qt::DropAction action } } +void InfoComicsView::droppedImage(const QList &urls) +{ + const auto imagePath = YACReader::droppedImagePath(urls); + const auto index = currentIndex(); + if (!imagePath.isEmpty() && index.isValid()) + emit customComicCoverRequested(index.data(ComicModel::IdRole).toULongLong(), imagePath); +} + void InfoComicsView::requestedContextMenu(const QPoint &point) { emit customContextMenuViewRequested(point); diff --git a/YACReaderLibrary/info_comics_view.h b/YACReaderLibrary/info_comics_view.h index d898cee4e..c3868a84b 100644 --- a/YACReaderLibrary/info_comics_view.h +++ b/YACReaderLibrary/info_comics_view.h @@ -21,6 +21,7 @@ class InfoComicsView : public ComicsView, protected Themable void applyTheme(const Theme &theme) override; ~InfoComicsView() override; void setToolBar(QToolBar *toolBar) override; + void releaseToolBar() override; void setModel(ComicModel *model) override; void setCurrentIndex(const QModelIndex &index) override; QModelIndex currentIndex() override; @@ -33,6 +34,8 @@ class InfoComicsView : public ComicsView, protected Themable void selectIndex(int index) override; void updateCurrentComicView() override; void focusComicsNavigation(Qt::FocusReason reason) override; + ContentViewState captureViewState() const override; + void restoreViewState(const ContentViewState &state) override; public slots: void setShowMarks(bool show) override; @@ -42,7 +45,9 @@ protected slots: void setCurrentIndex(int index); bool canDropUrls(const QList &urls, Qt::DropAction action); + bool canDropImage(const QList &urls); void droppedFiles(const QList &urls, Qt::DropAction action); + void droppedImage(const QList &urls); void requestedContextMenu(const QPoint &point); diff --git a/YACReaderLibrary/initial_comic_info_extractor.cpp b/YACReaderLibrary/initial_comic_info_extractor.cpp index 5b9b47da2..05adac5bb 100644 --- a/YACReaderLibrary/initial_comic_info_extractor.cpp +++ b/YACReaderLibrary/initial_comic_info_extractor.cpp @@ -16,7 +16,7 @@ using namespace YACReader; bool InitialComicInfoExtractor::crash = false; InitialComicInfoExtractor::InitialComicInfoExtractor(QString fileSource, QString target, int coverPage, bool getXMLMetadata) - : _fileSource(fileSource), _target(target), _numPages(0), _coverSize(0, 0), _coverExtracted(false), _coverPage(coverPage), getXMLMetadata(getXMLMetadata), _xmlInfoData() + : _fileSource(fileSource), _target(target), _numPages(0), _coverSize(0, 0), _coverExtracted(false), _coverPage(coverPage), _fileSupported(true), getXMLMetadata(getXMLMetadata), _xmlInfoData() { if (coverPage <= 0) { _coverPage = 1; @@ -122,7 +122,12 @@ void InitialComicInfoExtractor::extract() if (isEpub) { const auto epub = FileComic::epubScanInfo(order, archive, _coverPage); if (!epub.isValid()) { - QLOG_WARN() << "Extracting cover: unsupported EPUB" << _fileSource << epub.error; + // An EPUB book is a different kind of file that happens to share the + // extension with EPUB comics. It is not a comic, so it is left alone. + QLOG_INFO() << "Skipping EPUB, it is not an image based comic" << _fileSource << epub.error; + _fileSupported = false; + _cover.load(":/images/notCover.png"); + return; } _numPages = epub.pageCount; coverArchiveIndex = epub.coverArchiveIndex; diff --git a/YACReaderLibrary/initial_comic_info_extractor.h b/YACReaderLibrary/initial_comic_info_extractor.h index e02ca6cd5..667e31986 100644 --- a/YACReaderLibrary/initial_comic_info_extractor.h +++ b/YACReaderLibrary/initial_comic_info_extractor.h @@ -24,6 +24,7 @@ class InitialComicInfoExtractor : public QObject QImage _cover; bool _coverExtracted; int _coverPage; + bool _fileSupported; int getXMLMetadata; static bool crash; QByteArray _xmlInfoData; @@ -35,6 +36,9 @@ public slots: QPixmap getCover() { return QPixmap::fromImage(_cover); } QImage getCoverImage() const { return _cover; } bool hasValidCover() const { return _coverExtracted; } + // False when the file is not a comic YACReader can show, e.g. an EPUB book made of + // text. Such a file has to be ignored, not stored as a comic without pages. + bool isFileSupported() const { return _fileSupported; } QPair getOriginalCoverSize() { return _coverSize; } QByteArray getXMLInfoRawData(); signals: diff --git a/YACReaderLibrary/ip_config_helper.cpp b/YACReaderLibrary/ip_config_helper.cpp index 8f33e4779..be45d9730 100644 --- a/YACReaderLibrary/ip_config_helper.cpp +++ b/YACReaderLibrary/ip_config_helper.cpp @@ -23,7 +23,8 @@ QList getIpAddresses() }; QList addresses; - for (auto add : QNetworkInterface::allAddresses()) { + const auto allAddresses = QNetworkInterface::allAddresses(); + for (const auto &add : allAddresses) { // Exclude loopback, local, multicast if (add.isGlobal()) { addresses.push_back(add.toString()); diff --git a/YACReaderLibrary/libraries_update_coordinator.cpp b/YACReaderLibrary/libraries_update_coordinator.cpp index 77aea39ab..0662f0247 100644 --- a/YACReaderLibrary/libraries_update_coordinator.cpp +++ b/YACReaderLibrary/libraries_update_coordinator.cpp @@ -156,7 +156,8 @@ LibrariesUpdateCoordinator::UpdateRequestResult LibrariesUpdateCoordinator::star QStringList targets = paths; if (targets.isEmpty()) { - for (const auto &library : libraries.getLibraries()) { + const auto availableLibraries = libraries.getLibraries(); + for (const auto &library : availableLibraries) { targets.append(library.getPath()); } } diff --git a/YACReaderLibrary/library_creator.cpp b/YACReaderLibrary/library_creator.cpp index ca578aced..ec242cd1b 100644 --- a/YACReaderLibrary/library_creator.cpp +++ b/YACReaderLibrary/library_creator.cpp @@ -19,6 +19,7 @@ #include #include +#include using namespace std; using namespace YACReader; @@ -102,7 +103,7 @@ void LibraryCreator::updateFolder(const QString &source, const QString &target, _currentPathFolders.append(rootFolder(db)); - for (const auto &folderName : folders) { + for (const auto &folderName : std::as_const(folders)) { if (folderName.isEmpty()) { break; } @@ -363,7 +364,6 @@ void LibraryCreator::create(QDir dir) if (stopRunning) return; QFileInfo fileInfo = list.at(i); - QString fileName = fileInfo.fileName(); #ifdef Q_OS_MACOS QStringList src = _source.split("/"); QString filePath = fileInfo.absoluteFilePath(); @@ -419,8 +419,18 @@ void LibraryCreator::insertComic(const QString &relativePath, const QFileInfo &f auto coverPath = LibraryPaths::coverPathFromLibraryDataPath(_target, hash); YACReader::InitialComicInfoExtractor ie(QDir::cleanPath(fileInfo.absoluteFilePath()), coverPath, comic.info.coverPage.toInt(), settings->value(IMPORT_COMIC_INFO_XML_METADATA, false).toBool()); - if (!(comic.hasCover() && exists)) { + // A comic_info row without pages describes a file that never produced a comic, so it + // is no proof that the file is one: check it again instead of taking the shortcut. + const bool knownComic = comic.hasCover() && comic.info.numPages.toInt() > 0; + + if (!(knownComic && exists)) { ie.extract(); + if (!ie.isFileSupported()) { + // Not a comic YACReader can show, so it does not belong to the library. It + // leaves no cover behind either, otherwise the next scan would take that + // cover as proof that the file had been imported before. + return; + } numPages = ie.getNumPages(); originalCoverSize = ie.getOriginalCoverSize(); if (numPages > 0) { diff --git a/YACReaderLibrary/library_database_maintenance_coordinator.cpp b/YACReaderLibrary/library_database_maintenance_coordinator.cpp new file mode 100644 index 000000000..c5835b755 --- /dev/null +++ b/YACReaderLibrary/library_database_maintenance_coordinator.cpp @@ -0,0 +1,255 @@ +#include "library_database_maintenance_coordinator.h" + +#include "data_base_management.h" +#include "yacreader_global.h" +#include "yacreader_libraries.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +using namespace YACReader; + +LibraryDatabaseMaintenanceCoordinator::LibraryDatabaseMaintenanceCoordinator(YACReaderLibraries &libraries, QWidget *dialogParent, CurrentLibraryNameProvider currentLibraryNameProvider) + : QObject(dialogParent), libraries(libraries), dialogParent(dialogParent), currentLibraryNameProvider(std::move(currentLibraryNameProvider)) +{ +} + +void LibraryDatabaseMaintenanceCoordinator::backupCurrentLibrary(const QString &dialogTitle) +{ + backupLibrary(libraries.getPath(currentLibraryNameProvider()), dialogTitle); +} + +void LibraryDatabaseMaintenanceCoordinator::restoreCurrentLibrary(const QString &dialogTitle) +{ + const auto libraryName = currentLibraryNameProvider(); + restoreLibrary(libraryName, libraries.getPath(libraryName), dialogTitle); +} + +void LibraryDatabaseMaintenanceCoordinator::backupLibrary(const QString &libraryPath, const QString &dialogTitle) +{ + if (libraryPath.isEmpty()) + return; + + auto version = DataBaseManagement::checkValidDB(LibraryPaths::libraryDatabasePath(libraryPath)); + if (version.isEmpty()) + version = "unknown"; + const auto suggestedName = QString("library-%1-db-%2-manual.ydb") + .arg(QDateTime::currentDateTime().toString("yyyyMMdd-HHmmss"), version); + const auto destination = QFileDialog::getSaveFileName(dialogParent, + dialogTitle, + QDir::home().filePath(suggestedName), + QCoreApplication::translate("LibraryWindow", "YACReader library database (*.ydb)")); + if (destination.isEmpty()) + return; + + struct BackupResult { + bool success { false }; + QString error; + }; + + auto result = std::make_shared(); + auto worker = QThread::create([libraryPath, destination, result] { + result->success = DataBaseManagement::backupLibrary(libraryPath, DatabaseBackupReason::Manual, &result->error, destination); + }); + + emit backupAvailabilityChanged(false); + connect(worker, &QThread::finished, this, [this, destination, dialogTitle, result] { + emit backupAvailabilityChanged(true); + if (result->success) { + QMessageBox::information(dialogParent, + dialogTitle, + QCoreApplication::translate("LibraryWindow", "The library database backup was created at:\n%1").arg(destination)); + } else { + QMessageBox::critical(dialogParent, + dialogTitle, + QCoreApplication::translate("LibraryWindow", "Unable to create the library database backup:\n%1").arg(result->error)); + } + }); + connect(worker, &QThread::finished, worker, &QObject::deleteLater); + worker->start(); +} + +void LibraryDatabaseMaintenanceCoordinator::restoreLibrary(const QString &libraryName, const QString &libraryPath, const QString &dialogTitle) +{ + if (libraryPath.isEmpty()) + return; + + const auto backupPath = QFileDialog::getOpenFileName(dialogParent, + dialogTitle, + QDir(LibraryPaths::libraryDataPath(libraryPath)).filePath("backups"), + QCoreApplication::translate("LibraryWindow", "YACReader library database (*.ydb)")); + if (backupPath.isEmpty()) + return; + + const auto answer = QMessageBox::warning(dialogParent, + dialogTitle, + QCoreApplication::translate("LibraryWindow", "Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue?"), + QMessageBox::Yes | QMessageBox::Cancel, + QMessageBox::Cancel); + if (answer == QMessageBox::Yes) + startLibraryRestore(libraryName, libraryPath, backupPath, dialogTitle); +} + +void LibraryDatabaseMaintenanceCoordinator::startLibraryRestore(const QString &libraryName, const QString &libraryPath, const QString &backupPath, const QString &dialogTitle, bool allowInvalidCurrent, bool removeStaleLock) +{ + auto result = std::make_shared(); + auto progress = new QProgressDialog(QCoreApplication::translate("LibraryWindow", "Restoring library database..."), QString(), 0, 0, dialogParent); + progress->setCancelButton(nullptr); + progress->setWindowModality(Qt::WindowModal); + progress->setMinimumDuration(0); + + emit maintenanceStarted(); + + auto worker = QThread::create([libraryPath, backupPath, allowInvalidCurrent, removeStaleLock, result] { + *result = DataBaseManagement::restoreLibrary(libraryPath, backupPath, allowInvalidCurrent, removeStaleLock); + }); + connect(worker, &QThread::finished, this, [this, libraryName, libraryPath, backupPath, dialogTitle, allowInvalidCurrent, result, progress] { + progress->deleteLater(); + + if (result->status == DatabaseRestoreStatus::InvalidCurrentDatabase && !allowInvalidCurrent) { + const auto answer = QMessageBox::warning(dialogParent, + dialogTitle, + QCoreApplication::translate("LibraryWindow", "The current library database is invalid. Restore the selected backup anyway?"), + QMessageBox::Yes | QMessageBox::Cancel, + QMessageBox::Cancel); + if (answer == QMessageBox::Yes) { + startLibraryRestore(libraryName, libraryPath, backupPath, dialogTitle, true); + return; + } + emit invalidDatabaseRestoreCancelled(); + return; + } else if (result->status == DatabaseRestoreStatus::LockFailed && !result->lockHolderIsRunningLocally) { + const auto answer = QMessageBox::warning(dialogParent, + dialogTitle, + QCoreApplication::translate("LibraryWindow", "The library maintenance lock may be stale. Remove it and retry?"), + QMessageBox::Yes | QMessageBox::Cancel, + QMessageBox::Cancel); + if (answer == QMessageBox::Yes) { + startLibraryRestore(libraryName, libraryPath, backupPath, dialogTitle, allowInvalidCurrent, true); + return; + } + emit libraryReloadRequested(libraryName); + return; + } + + if (!result->success()) { + auto error = result->error; + if (result->status == DatabaseRestoreStatus::RollbackFailed) + error += QCoreApplication::translate("LibraryWindow", "\n\nRestart YACReaderLibrary before attempting recovery again."); + QMessageBox::critical(dialogParent, dialogTitle, error); + if (result->status != DatabaseRestoreStatus::RollbackFailed) + emit libraryReloadRequested(libraryName); + else + emit databaseUnavailableAfterRestore(); + return; + } + + emit libraryReloadRequested(libraryName); + const auto answer = QMessageBox::question(dialogParent, + dialogTitle, + QCoreApplication::translate("LibraryWindow", "The library database was restored successfully. Update the library now?"), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::Yes); + if (answer == QMessageBox::Yes) + emit libraryUpdateRequested(); + }); + connect(worker, &QThread::finished, worker, &QObject::deleteLater); + worker->start(); +} + +void LibraryDatabaseMaintenanceCoordinator::offerDatabaseRecovery(const QString &libraryName, const QString &restoreDialogTitle) +{ + const auto libraryPath = libraries.getPath(libraryName); + QMessageBox messageBox(QMessageBox::Warning, + QCoreApplication::translate("LibraryWindow", "Library database damaged"), + QCoreApplication::translate("LibraryWindow", "The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed.").arg(libraryName), + QMessageBox::NoButton, + dialogParent); + const auto repairButton = messageBox.addButton(QCoreApplication::translate("LibraryWindow", "Attempt repair"), QMessageBox::AcceptRole); + const auto restoreButton = messageBox.addButton(QCoreApplication::translate("LibraryWindow", "Restore a backup..."), QMessageBox::ActionRole); + messageBox.addButton(QMessageBox::Cancel); + messageBox.setWindowModality(Qt::WindowModal); + messageBox.exec(); + + if (messageBox.clickedButton() == repairButton) + startDatabaseSalvage(libraryName, libraryPath); + else if (messageBox.clickedButton() == restoreButton) + restoreLibrary(libraryName, libraryPath, restoreDialogTitle); +} + +void LibraryDatabaseMaintenanceCoordinator::startDatabaseSalvage(const QString &libraryName, const QString &libraryPath, bool removeStaleLock) +{ + if (libraryPath.isEmpty()) + return; + + auto result = std::make_shared(); + auto progress = new QProgressDialog(QCoreApplication::translate("LibraryWindow", "Repairing library database..."), QString(), 0, 0, dialogParent); + progress->setCancelButton(nullptr); + progress->setWindowModality(Qt::WindowModal); + progress->setMinimumDuration(0); + + auto worker = QThread::create([libraryPath, removeStaleLock, result] { + *result = DataBaseManagement::salvageLibrary(libraryPath, removeStaleLock); + }); + connect(worker, &QThread::finished, this, [this, libraryName, libraryPath, result, progress] { + progress->deleteLater(); + + if (result->status == DatabaseSalvageStatus::LockFailed) { + if (!result->lockHolderIsRunningLocally) { + const auto answer = QMessageBox::warning(dialogParent, + QCoreApplication::translate("LibraryWindow", "Library database repair"), + QCoreApplication::translate("LibraryWindow", "The library maintenance lock may be stale. Remove it and retry?"), + QMessageBox::Yes | QMessageBox::Cancel, + QMessageBox::Cancel); + if (answer == QMessageBox::Yes) + startDatabaseSalvage(libraryName, libraryPath, true); + } else { + QMessageBox::warning(dialogParent, + QCoreApplication::translate("LibraryWindow", "Library database repair"), + QCoreApplication::translate("LibraryWindow", "Another maintenance operation is currently using this library. Try again after it finishes.")); + } + return; + } + + if (result->success()) { + emit libraryReloadRequested(libraryName); + if (result->status == DatabaseSalvageStatus::AlreadyValid) { + QMessageBox::information(dialogParent, + QCoreApplication::translate("LibraryWindow", "Library database repair"), + QCoreApplication::translate("LibraryWindow", "The library database is already valid.")); + } else if (result->status == DatabaseSalvageStatus::Reindexed) { + QMessageBox::information(dialogParent, + QCoreApplication::translate("LibraryWindow", "Library database repaired"), + QCoreApplication::translate("LibraryWindow", "The library database was repaired by rebuilding its indexes. The damaged original was preserved at:\n%1").arg(result->preservedDatabasePath)); + } else { + const auto answer = QMessageBox::question(dialogParent, + QCoreApplication::translate("LibraryWindow", "Library database rebuilt"), + QCoreApplication::translate("LibraryWindow", "The library database was rebuilt successfully. The damaged original was preserved at:\n%1\n\nUpdate the library now?").arg(result->preservedDatabasePath), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::Yes); + if (answer == QMessageBox::Yes) + emit libraryUpdateRequested(); + } + } else { + const auto recovery = result->preservedDatabasePath.isEmpty() + ? QString() + : QCoreApplication::translate("LibraryWindow", "\n\nThe damaged original was preserved at:\n%1").arg(result->preservedDatabasePath); + QMessageBox::critical(dialogParent, + QCoreApplication::translate("LibraryWindow", "Library database repair failed"), + QCoreApplication::translate("LibraryWindow", "The library database could not be repaired:\n%1%2\n\nYou can restore a backup from the Library menu or recreate the library.").arg(result->error, recovery)); + emit databaseSalvageFailed(); + } + }); + connect(worker, &QThread::finished, worker, &QObject::deleteLater); + worker->start(); +} diff --git a/YACReaderLibrary/library_database_maintenance_coordinator.h b/YACReaderLibrary/library_database_maintenance_coordinator.h new file mode 100644 index 000000000..88f67227c --- /dev/null +++ b/YACReaderLibrary/library_database_maintenance_coordinator.h @@ -0,0 +1,45 @@ +#ifndef LIBRARY_DATABASE_MAINTENANCE_COORDINATOR_H +#define LIBRARY_DATABASE_MAINTENANCE_COORDINATOR_H + +#include +#include + +#include + +class QWidget; +class YACReaderLibraries; + +class LibraryDatabaseMaintenanceCoordinator : public QObject +{ + Q_OBJECT + +public: + using CurrentLibraryNameProvider = std::function; + + LibraryDatabaseMaintenanceCoordinator(YACReaderLibraries &libraries, QWidget *dialogParent, CurrentLibraryNameProvider currentLibraryNameProvider); + + void backupCurrentLibrary(const QString &dialogTitle); + void restoreCurrentLibrary(const QString &dialogTitle); + void offerDatabaseRecovery(const QString &libraryName, const QString &restoreDialogTitle); + +signals: + void backupAvailabilityChanged(bool available); + void maintenanceStarted(); + void libraryReloadRequested(const QString &libraryName); + void libraryUpdateRequested(); + void invalidDatabaseRestoreCancelled(); + void databaseUnavailableAfterRestore(); + void databaseSalvageFailed(); + +private: + void backupLibrary(const QString &libraryPath, const QString &dialogTitle); + void restoreLibrary(const QString &libraryName, const QString &libraryPath, const QString &dialogTitle); + void startLibraryRestore(const QString &libraryName, const QString &libraryPath, const QString &backupPath, const QString &dialogTitle, bool allowInvalidCurrent = false, bool removeStaleLock = false); + void startDatabaseSalvage(const QString &libraryName, const QString &libraryPath, bool removeStaleLock = false); + + YACReaderLibraries &libraries; + QWidget *dialogParent; + CurrentLibraryNameProvider currentLibraryNameProvider; +}; + +#endif diff --git a/YACReaderLibrary/library_management_coordinator.cpp b/YACReaderLibrary/library_management_coordinator.cpp new file mode 100644 index 000000000..2149d5ef3 --- /dev/null +++ b/YACReaderLibrary/library_management_coordinator.cpp @@ -0,0 +1,482 @@ +#include "library_management_coordinator.h" + +#include "add_library_dialog.h" +#include "create_library_dialog.h" +#include "data_base_management.h" +#include "db_helper.h" +#include "export_library_dialog.h" +#include "folder_model.h" +#include "import_library_dialog.h" +#include "library_creator.h" +#include "package_manager.h" +#include "xml_info_library_scanner.h" +#include "yacreader_global.h" +#include "yacreader_libraries.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +using namespace YACReader; + +LibraryManagementCoordinator::LibraryManagementCoordinator(QSettings *settings, + YACReaderLibraries &libraries, + QWidget *dialogParent, + CreateLibraryDialog *createLibraryDialog, + AddLibraryDialog *addLibraryDialog, + ExportLibraryDialog *exportLibraryDialog, + ImportLibraryDialog *importLibraryDialog, + FolderModel *foldersModel, + CurrentLibraryNameProvider currentLibraryNameProvider, + CurrentFolderProvider currentFolderProvider, + QString libraryInfoDialogTitle) + : QObject(dialogParent), libraries(libraries), dialogParent(dialogParent), createLibraryDialog(createLibraryDialog), addLibraryDialog(addLibraryDialog), exportLibraryDialog(exportLibraryDialog), importLibraryDialog(importLibraryDialog), foldersModel(foldersModel), currentLibraryNameProvider(std::move(currentLibraryNameProvider)), currentFolderProvider(std::move(currentFolderProvider)), libraryInfoDialogTitle(std::move(libraryInfoDialogTitle)), libraryCreator(new LibraryCreator(settings)), packageManager(new PackageManager()), xmlInfoLibraryScanner(new XMLInfoLibraryScanner()) +{ + libraryCreator->setParent(this); + packageManager->setParent(this); + xmlInfoLibraryScanner->setParent(this); + + connect(this, &LibraryManagementCoordinator::upgradeFailed, this, [this](const QString &libraryDataPath) { QMessageBox::critical(this->dialogParent, + QCoreApplication::translate("LibraryWindow", "Upgrade failed"), + QCoreApplication::translate("LibraryWindow", "There were errors during library upgrade in: ") + libraryDataPath + "/library.ydb"); }, Qt::QueuedConnection); + + connect(libraryCreator, &QThread::finished, this, &LibraryManagementCoordinator::operationFinished); + connect(libraryCreator, &LibraryCreator::updated, this, &LibraryManagementCoordinator::currentLibraryReloadRequested); + connect(libraryCreator, &LibraryCreator::created, this, &LibraryManagementCoordinator::finishAddingLibrary); + connect(libraryCreator, &LibraryCreator::updatedCurrentFolder, this, &LibraryManagementCoordinator::folderUpdateFinished); + connect(libraryCreator, &LibraryCreator::comicAdded, this, &LibraryManagementCoordinator::comicAdded); + connect(libraryCreator, &LibraryCreator::failedCreatingDB, this, &LibraryManagementCoordinator::creationFailed); + connect(libraryCreator, &LibraryCreator::failedOpeningDB, this, &LibraryManagementCoordinator::handleCreatorOpeningFailure); + + connect(this, &LibraryManagementCoordinator::libraryReloadRequested, this, &LibraryManagementCoordinator::loadLibrary); + connect(this, &LibraryManagementCoordinator::libraryRecreationRequested, createLibraryDialog, &CreateLibraryDialog::setDataAndStart); + connect(this, &LibraryManagementCoordinator::openingError, this, [this](const QString &error) { + QMessageBox::critical(this->dialogParent, tr("Error opening the library"), error); + }); + connect(this, &LibraryManagementCoordinator::creationFailed, this, [this](const QString &error) { + QMessageBox::critical(this->dialogParent, tr("Error creating the library"), error); + }); + connect(this, &LibraryManagementCoordinator::updateFailed, this, [this](const QString &error) { + QMessageBox::critical(this->dialogParent, tr("Error updating the library"), error); + }); + + connect(createLibraryDialog, &CreateLibraryDialog::createLibrary, this, &LibraryManagementCoordinator::createLibrary); + connect(createLibraryDialog, &CreateLibraryDialog::libraryExists, this, &LibraryManagementCoordinator::showLibraryAlreadyExists); + connect(createLibraryDialog, &CreateLibraryDialog::cancelCreate, this, &LibraryManagementCoordinator::stop); + connect(addLibraryDialog, &AddLibraryDialog::addLibrary, this, &LibraryManagementCoordinator::addExistingLibrary); + + connect(exportLibraryDialog, &ExportLibraryDialog::exportPath, this, &LibraryManagementCoordinator::exportCurrentLibrary); + connect(exportLibraryDialog, &QDialog::rejected, packageManager, &PackageManager::cancel); + connect(packageManager, &PackageManager::exported, exportLibraryDialog, &ExportLibraryDialog::close); + connect(importLibraryDialog, &ImportLibraryDialog::unpackCLC, this, &LibraryManagementCoordinator::importLibraryPackage); + connect(importLibraryDialog, &QDialog::rejected, packageManager, &PackageManager::cancel); + connect(importLibraryDialog, &QDialog::rejected, this, [this] { deleteCurrentLibrary(true); }); + connect(importLibraryDialog, &ImportLibraryDialog::libraryExists, this, &LibraryManagementCoordinator::showLibraryAlreadyExists); + connect(packageManager, &PackageManager::imported, importLibraryDialog, &QWidget::hide); + connect(packageManager, &PackageManager::imported, this, &LibraryManagementCoordinator::finishAddingLibrary); + connect(packageManager, &PackageManager::failed, this, &LibraryManagementCoordinator::packageFailed); + + connect(xmlInfoLibraryScanner, &QThread::finished, this, &LibraryManagementCoordinator::xmlScanFinished); + connect(xmlInfoLibraryScanner, &XMLInfoLibraryScanner::comicScanned, this, &LibraryManagementCoordinator::xmlComicScanned); +} + +void LibraryManagementCoordinator::loadLibrary(const QString &libraryName) +{ + if (libraries.isEmpty()) { + emit noLibrariesRequested(); + return; + } + + loadLibraryAtPath(libraryName, libraries.getPath(libraryName)); +} + +void LibraryManagementCoordinator::loadLibraryAtPath(const QString &libraryName, const QString &libraryPath) +{ + emit loadStarted(); + + QString recoveryError; + if (!DataBaseManagement::recoverInterruptedRestore(libraryPath, &recoveryError)) { + QMessageBox::critical(dialogParent, QCoreApplication::translate("LibraryWindow", "Restore recovery failed"), recoveryError); + return; + } + + const auto libraryDataPath = LibraryPaths::libraryDataPath(libraryPath); + const auto customFolderCoversPath = LibraryPaths::libraryCustomFoldersCoverPath(libraryPath); + const auto databasePath = LibraryPaths::libraryDatabasePath(libraryPath); + QDir directory; + QString databaseVersion; + + if (directory.exists(libraryDataPath) && directory.exists(databasePath) && !(databaseVersion = DataBaseManagement::checkValidDB(databasePath)).isEmpty()) { + directory.mkdir(customFolderCoversPath); + + const auto versionComparison = DataBaseManagement::compareVersions(databaseVersion, DB_VERSION); + if (versionComparison < 0) { + if (!DataBaseManagement::isLibraryDatabaseValid(libraryPath)) { + emit libraryManagementOnlyRequested(); + emit databaseRecoveryRequested(libraryName); + return; + } + + const auto answer = QMessageBox::question(dialogParent, + QCoreApplication::translate("LibraryWindow", "Update needed"), + QCoreApplication::translate("LibraryWindow", "This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now?"), + QMessageBox::Yes, + QMessageBox::No); + if (answer == QMessageBox::Yes) { + startUpgrade(libraryName, libraryPath, libraryDataPath); + return; + } + + emit libraryManagementOnlyRequested(); + return; + } + + if (versionComparison == 0) { + QDir rootDirectory(libraryPath); + rootDirectory.setFilter(QDir::AllDirs | QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot); + emit libraryReady(libraryDataPath, rootDirectory.count() <= 1); + return; + } + + const auto answer = QMessageBox::question(dialogParent, + QCoreApplication::translate("LibraryWindow", "Download new version"), + QCoreApplication::translate("LibraryWindow", "This library was created with a newer version of YACReaderLibrary. Download the new version now?"), + QMessageBox::Yes, + QMessageBox::No); + if (answer == QMessageBox::Yes) + QDesktopServices::openUrl(QUrl("http://www.yacreader.com")); + emit libraryManagementOnlyRequested(); + return; + } + + emit libraryManagementOnlyRequested(); + + if (!directory.exists(libraryDataPath)) { + const auto libraryDescription = libraryName + " -> " + libraryPath; + if (QMessageBox::question(dialogParent, + QCoreApplication::translate("LibraryWindow", "Library not available"), + QCoreApplication::translate("LibraryWindow", "Library '%1' is no longer available. Do you want to remove it?").arg(libraryDescription), + QMessageBox::Yes, + QMessageBox::No) == QMessageBox::Yes) { + deleteLibrary(libraryName, true); + } + return; + } + + if (directory.exists(databasePath)) { + const auto database = DataBaseManagement::loadDatabase(libraryDataPath); + emit openingError(database.lastError().databaseText() + "-" + database.lastError().driverText()); + return; + } + + if (QMessageBox::question(dialogParent, + QCoreApplication::translate("LibraryWindow", "Old library"), + QCoreApplication::translate("LibraryWindow", "Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now?").arg(libraryName), + QMessageBox::Yes, + QMessageBox::No) == QMessageBox::Yes) { + emit libraryRecreationRequested(libraryName, libraryPath); + } +} + +QList> LibraryManagementCoordinator::loadLibraries() +{ + libraries.load(); + QList> result; + const auto libraryNames = libraries.getNames(); + result.reserve(libraryNames.size()); + for (const auto &libraryName : libraryNames) + result.append({ libraryName, libraries.getPath(libraryName) }); + return result; +} + +void LibraryManagementCoordinator::showCreateLibraryDialog() +{ + warnIfLibraryCountIsHigh(); + createLibraryDialog->open(libraries); +} + +void LibraryManagementCoordinator::showAddLibraryDialog() +{ + warnIfLibraryCountIsHigh(); + addLibraryDialog->open(); +} + +void LibraryManagementCoordinator::showExportLibraryDialog() +{ + exportLibraryDialog->open(); +} + +void LibraryManagementCoordinator::showImportLibraryDialog() +{ + importLibraryDialog->open(libraries); +} + +void LibraryManagementCoordinator::createLibrary(const QString &source, const QString &destination, const QString &name) +{ + QLOG_INFO() << QString("About to create a library from '%1' to '%2' with name '%3'").arg(source, destination, name); + pendingLibraryName = name; + pendingLibraryPath = source; + operationLibraryName = name; + operationLibraryPath = source; + emit creationStarted(); + libraryCreator->createLibrary(source, destination); + libraryCreator->start(); +} + +void LibraryManagementCoordinator::updateCurrentLibrary() +{ + const auto libraryName = currentLibraryNameProvider(); + updateLibrary(libraryName, libraries.getPath(libraryName)); +} + +void LibraryManagementCoordinator::updateCurrentFolder() +{ + updateFolder(currentFolderProvider()); +} + +void LibraryManagementCoordinator::updateFolder(const QModelIndex &folderIndex) +{ + const auto libraryName = currentLibraryNameProvider(); + const auto libraryPath = QDir::cleanPath(libraries.getPath(libraryName)); + emit updateStarted(); + startFolderUpdate( + libraryName, + libraryPath, + QDir::cleanPath(libraryPath + foldersModel->getFolderPath(folderIndex)), + folderIndex.data(FolderModel::IdRole).toULongLong()); +} + +void LibraryManagementCoordinator::updateLibrary(const QString &libraryName, const QString &libraryPath) +{ + operationLibraryName = libraryName; + operationLibraryPath = libraryPath; + emit updateStarted(); + libraryCreator->updateLibrary(libraryPath, LibraryPaths::libraryDataPath(libraryPath)); + libraryCreator->start(); +} + +void LibraryManagementCoordinator::startFolderUpdate(const QString &libraryName, const QString &libraryPath, const QString &folderPath, qulonglong folderId) +{ + operationLibraryName = libraryName; + operationLibraryPath = libraryPath; + libraryCreator->updateFolder(libraryPath, LibraryPaths::libraryDataPath(libraryPath), folderPath, folderId); + libraryCreator->start(); +} + +void LibraryManagementCoordinator::rescanCurrentLibraryForXMLInfo() +{ + const auto libraryPath = libraries.getPath(currentLibraryNameProvider()); + emit xmlScanStarted(); + xmlInfoLibraryScanner->scanLibrary(libraryPath, LibraryPaths::libraryDataPath(libraryPath)); +} + +void LibraryManagementCoordinator::rescanCurrentFolderForXMLInfo() +{ + rescanFolderForXMLInfo(currentFolderProvider()); +} + +void LibraryManagementCoordinator::rescanFolderForXMLInfo(const QModelIndex &folderIndex) +{ + if (!folderIndex.isValid()) + return; + + const auto libraryPath = libraries.getPath(currentLibraryNameProvider()); + emit xmlScanStarted(); + xmlInfoLibraryScanner->scanFolder( + libraryPath, + LibraryPaths::libraryDataPath(libraryPath), + QDir::cleanPath(libraryPath + foldersModel->getFolderPath(folderIndex)), + folderIndex); +} + +void LibraryManagementCoordinator::exportCurrentLibrary(const QString &destinationPath) +{ + const auto libraryName = currentLibraryNameProvider(); + packageManager->createPackage(LibraryPaths::libraryDataPath(libraries.getPath(libraryName)), destinationPath + "/" + libraryName); +} + +void LibraryManagementCoordinator::importLibraryPackage(const QString &packagePath, const QString &destinationPath, const QString &libraryName) +{ + const auto libraryPath = destinationPath + "/" + libraryName; + packageManager->extractPackage(packagePath, libraryPath); + prepareImportedLibrary(libraryName, libraryPath); +} + +void LibraryManagementCoordinator::addExistingLibrary(QString libraryPath, const QString &libraryName) +{ + if (libraries.contains(libraryName)) { + showLibraryAlreadyExists(libraryName); + return; + } + + libraryPath.remove("/.yacreaderlibrary"); + if (!QDir(LibraryPaths::libraryDataPath(libraryPath)).exists()) { + QMessageBox::warning(dialogParent, + QCoreApplication::translate("LibraryWindow", "Library not found"), + QCoreApplication::translate("LibraryWindow", "The selected folder doesn't contain any library.")); + return; + } + + prepareImportedLibrary(libraryName, libraryPath); + finishAddingLibrary(); +} + +void LibraryManagementCoordinator::prepareImportedLibrary(const QString &libraryName, const QString &libraryPath) +{ + pendingLibraryName = libraryName; + pendingLibraryPath = libraryPath; +} + +void LibraryManagementCoordinator::finishAddingLibrary() +{ + if (pendingLibraryName.isEmpty() || pendingLibraryPath.isEmpty()) + return; + + libraries.addLibrary(pendingLibraryName, pendingLibraryPath); + libraries.save(); + emit libraryAdded(pendingLibraryName, pendingLibraryPath); + pendingLibraryName.clear(); + pendingLibraryPath.clear(); +} + +void LibraryManagementCoordinator::askToRemoveCurrentLibrary() +{ + askToRemoveLibrary(currentLibraryNameProvider()); +} + +void LibraryManagementCoordinator::deleteCurrentLibrary(bool deleteMetadata) +{ + deleteLibrary(currentLibraryNameProvider(), deleteMetadata); +} + +void LibraryManagementCoordinator::renameCurrentLibrary(const QString &newName) +{ + const auto currentName = currentLibraryNameProvider(); + if (!renameLibrary(currentName, newName)) + return; + + emit libraryRenamed(currentName, newName); +} + +void LibraryManagementCoordinator::openCurrentLibraryFolder() +{ + const auto path = libraries.getPath(currentLibraryNameProvider()); + if (!path.isEmpty()) + QDesktopServices::openUrl(QUrl::fromLocalFile(QDir::cleanPath(path))); +} + +void LibraryManagementCoordinator::showCurrentLibraryInfo() +{ + const auto id = libraries.getUuid(currentLibraryNameProvider()); + const auto info = DBHelper::getLibraryInfo(id); + + QMessageBox messageBox(dialogParent); + messageBox.setWindowTitle(libraryInfoDialogTitle); + messageBox.setText(info); + auto horizontalSpacer = new QSpacerItem(420, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); + auto layout = qobject_cast(messageBox.layout()); + layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount()); + messageBox.setStandardButtons(QMessageBox::Close); + messageBox.setDefaultButton(QMessageBox::Close); + messageBox.exec(); +} + +void LibraryManagementCoordinator::askToRemoveLibrary(const QString &libraryName) +{ + QMessageBox messageBox(QMessageBox::Question, + QCoreApplication::translate("LibraryWindow", "Are you sure?"), + QCoreApplication::translate("LibraryWindow", "Do you want remove ") + libraryName + QCoreApplication::translate("LibraryWindow", " library?"), + QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No, + dialogParent); + messageBox.button(QMessageBox::YesToAll)->setText(QCoreApplication::translate("LibraryWindow", "Remove and delete metadata and backups")); + messageBox.setWindowModality(Qt::WindowModal); + + const auto answer = messageBox.exec(); + if (answer == QMessageBox::Yes) + deleteLibrary(libraryName, false); + else if (answer == QMessageBox::YesToAll) + deleteLibrary(libraryName, true); +} + +void LibraryManagementCoordinator::deleteLibrary(const QString &libraryName, bool deleteMetadata) +{ + const auto libraryPath = libraries.getPath(libraryName); + libraries.remove(libraryName); + + if (deleteMetadata) + QDir(LibraryPaths::libraryDataPath(libraryPath)).removeRecursively(); + + libraries.save(); + emit libraryRemoved(libraryName, libraries.isEmpty()); +} + +bool LibraryManagementCoordinator::renameLibrary(const QString ¤tName, const QString &newName) +{ + if (newName == currentName) + return true; + if (libraries.contains(newName)) { + showLibraryAlreadyExists(newName); + return false; + } + + libraries.rename(currentName, newName); + libraries.save(); + return true; +} + +void LibraryManagementCoordinator::warnIfLibraryCountIsHigh() +{ + if (libraries.getNames().size() < MAX_LIBRARIES_WARNING_NUM) + return; + + QMessageBox::warning(dialogParent, + QCoreApplication::translate("LibraryWindow", "You are adding too many libraries."), + QCoreApplication::translate("LibraryWindow", "You are adding too many libraries.\n\nYou probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar.\n\nYACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low.")); +} + +void LibraryManagementCoordinator::showLibraryAlreadyExists(const QString &libraryName) +{ + QMessageBox::information(dialogParent, + QCoreApplication::translate("LibraryWindow", "Library name already exists"), + QCoreApplication::translate("LibraryWindow", "There is another library with the name '%1'.").arg(libraryName)); +} + +void LibraryManagementCoordinator::stop() +{ + libraryCreator->stop(); + libraryCreator->wait(); + xmlInfoLibraryScanner->stop(); + xmlInfoLibraryScanner->wait(); +} + +void LibraryManagementCoordinator::startUpgrade(const QString &libraryName, const QString &libraryPath, const QString &libraryDataPath) +{ + emit upgradeStarted(); + upgradeFuture = std::async(std::launch::async, [this, libraryName, libraryPath, libraryDataPath] { + if (!DataBaseManagement::updateToCurrentVersion(libraryPath)) + emit upgradeFailed(libraryDataPath); + emit libraryReloadRequested(libraryName); + }); +} + +void LibraryManagementCoordinator::handleCreatorOpeningFailure(const QString &error) +{ + emit operationUiResetRequested(); + if (!operationLibraryPath.isEmpty() && QFile::exists(LibraryPaths::libraryDatabasePath(operationLibraryPath)) && !DataBaseManagement::isLibraryDatabaseValid(operationLibraryPath)) { + emit databaseRecoveryRequested(operationLibraryName); + return; + } + emit updateFailed(error); +} diff --git a/YACReaderLibrary/library_management_coordinator.h b/YACReaderLibrary/library_management_coordinator.h new file mode 100644 index 000000000..0557d3ac2 --- /dev/null +++ b/YACReaderLibrary/library_management_coordinator.h @@ -0,0 +1,136 @@ +#ifndef LIBRARY_MANAGEMENT_COORDINATOR_H +#define LIBRARY_MANAGEMENT_COORDINATOR_H + +#include +#include +#include + +#include +#include + +class AddLibraryDialog; +class CreateLibraryDialog; +class ExportLibraryDialog; +class FolderModel; +class ImportLibraryDialog; +class LibraryCreator; +class PackageManager; +class QSettings; +class QWidget; +class YACReaderLibraries; + +namespace YACReader { +class XMLInfoLibraryScanner; +} + +class LibraryManagementCoordinator : public QObject +{ + Q_OBJECT + +public: + using CurrentLibraryNameProvider = std::function; + using CurrentFolderProvider = std::function; + + LibraryManagementCoordinator(QSettings *settings, + YACReaderLibraries &libraries, + QWidget *dialogParent, + CreateLibraryDialog *createLibraryDialog, + AddLibraryDialog *addLibraryDialog, + ExportLibraryDialog *exportLibraryDialog, + ImportLibraryDialog *importLibraryDialog, + FolderModel *foldersModel, + CurrentLibraryNameProvider currentLibraryNameProvider, + CurrentFolderProvider currentFolderProvider, + QString libraryInfoDialogTitle); + + QList> loadLibraries(); + +public slots: + void loadLibrary(const QString &libraryName); + void showCreateLibraryDialog(); + void showAddLibraryDialog(); + void showExportLibraryDialog(); + void showImportLibraryDialog(); + void createLibrary(const QString &source, const QString &destination, const QString &name); + void updateCurrentLibrary(); + void updateCurrentFolder(); + void updateFolder(const QModelIndex &folderIndex); + void rescanCurrentLibraryForXMLInfo(); + void rescanCurrentFolderForXMLInfo(); + void rescanFolderForXMLInfo(const QModelIndex &folderIndex); + void exportCurrentLibrary(const QString &destinationPath); + void importLibraryPackage(const QString &packagePath, const QString &destinationPath, const QString &libraryName); + void addExistingLibrary(QString libraryPath, const QString &libraryName); + + void askToRemoveCurrentLibrary(); + void deleteCurrentLibrary(bool deleteMetadata); + void renameCurrentLibrary(const QString &newName); + void openCurrentLibraryFolder(); + void showCurrentLibraryInfo(); + + void warnIfLibraryCountIsHigh(); + void showLibraryAlreadyExists(const QString &libraryName); + void stop(); + +signals: + void loadStarted(); + void noLibrariesRequested(); + void libraryReady(const QString &libraryDataPath, bool readOnly); + void libraryManagementOnlyRequested(); + void databaseRecoveryRequested(const QString &libraryName); + void upgradeStarted(); + void upgradeFailed(const QString &libraryDataPath); + void libraryReloadRequested(const QString &libraryName); + void libraryRecreationRequested(const QString &libraryName, const QString &libraryPath); + void openingError(const QString &error); + + void creationStarted(); + void updateStarted(); + void operationUiResetRequested(); + void operationFinished(); + void currentLibraryReloadRequested(); + void libraryAdded(const QString &libraryName, const QString &libraryPath); + void libraryRemoved(const QString &libraryName, bool librariesEmpty); + void libraryRenamed(const QString &oldName, const QString &newName); + void folderUpdateFinished(qulonglong folderId); + void comicAdded(const QString &relativePath, const QString &coverPath); + void creationFailed(const QString &error); + void updateFailed(const QString &error); + void xmlScanStarted(); + void xmlScanFinished(); + void xmlComicScanned(const QString &relativePath, const QString &coverPath); + void packageFailed(const QString &error); + +private: + void loadLibraryAtPath(const QString &libraryName, const QString &libraryPath); + void updateLibrary(const QString &libraryName, const QString &libraryPath); + void startFolderUpdate(const QString &libraryName, const QString &libraryPath, const QString &folderPath, qulonglong folderId); + void prepareImportedLibrary(const QString &libraryName, const QString &libraryPath); + void finishAddingLibrary(); + void askToRemoveLibrary(const QString &libraryName); + void deleteLibrary(const QString &libraryName, bool deleteMetadata); + bool renameLibrary(const QString ¤tName, const QString &newName); + void startUpgrade(const QString &libraryName, const QString &libraryPath, const QString &libraryDataPath); + void handleCreatorOpeningFailure(const QString &error); + + YACReaderLibraries &libraries; + QWidget *dialogParent; + CreateLibraryDialog *createLibraryDialog; + AddLibraryDialog *addLibraryDialog; + ExportLibraryDialog *exportLibraryDialog; + ImportLibraryDialog *importLibraryDialog; + FolderModel *foldersModel; + CurrentLibraryNameProvider currentLibraryNameProvider; + CurrentFolderProvider currentFolderProvider; + QString libraryInfoDialogTitle; + LibraryCreator *libraryCreator; + PackageManager *packageManager; + YACReader::XMLInfoLibraryScanner *xmlInfoLibraryScanner; + QString pendingLibraryName; + QString pendingLibraryPath; + QString operationLibraryName; + QString operationLibraryPath; + std::future upgradeFuture; +}; + +#endif diff --git a/YACReaderLibrary/library_repair_coordinator.cpp b/YACReaderLibrary/library_repair_coordinator.cpp new file mode 100644 index 000000000..f3cd1b1cd --- /dev/null +++ b/YACReaderLibrary/library_repair_coordinator.cpp @@ -0,0 +1,101 @@ +#include "library_repair_coordinator.h" + +#include "comic_info_repairer.h" +#include "data_base_management.h" +#include "yacreader_global.h" +#include "yacreader_libraries.h" + +#include +#include +#include +#include +#include + +#include + +using namespace YACReader; + +LibraryRepairCoordinator::LibraryRepairCoordinator(QSettings *settings, YACReaderLibraries &libraries, QWidget *dialogParent, CurrentLibraryNameProvider currentLibraryNameProvider) + : QObject(dialogParent), libraries(libraries), dialogParent(dialogParent), currentLibraryNameProvider(std::move(currentLibraryNameProvider)), repairer(new ComicInfoRepairer(settings, this)) +{ + connect(repairer, &QThread::finished, this, &LibraryRepairCoordinator::handleFinished); + connect(repairer, &ComicInfoRepairer::comicProcessed, this, &LibraryRepairCoordinator::comicProcessed); + connect(repairer, &ComicInfoRepairer::failed, this, &LibraryRepairCoordinator::handleFailure); +} + +void LibraryRepairCoordinator::repairCurrentLibrary(const QString &dialogTitle) +{ + if (repairer->isRunning()) + return; + + libraryName = currentLibraryNameProvider(); + libraryPath = libraries.getPath(libraryName); + this->dialogTitle = dialogTitle; + startRepair(false); +} + +void LibraryRepairCoordinator::startRepair(bool removeStaleLock) +{ + if (libraryPath.isEmpty()) + return; + + emit repairStarted(); + repairer->repairLibrary(libraryPath, LibraryPaths::libraryDataPath(libraryPath), removeStaleLock); +} + +void LibraryRepairCoordinator::stop() +{ + repairer->stop(); + repairer->wait(); +} + +void LibraryRepairCoordinator::handleFinished() +{ + const auto summary = repairer->summary(); + emit repairFinished(); + + if (summary.lockedByAnotherProcess) { + if (summary.lockHolderIsRunningLocally) { + QMessageBox::information(dialogParent, + dialogTitle, + QCoreApplication::translate("LibraryWindow", "A repair of this library is already running (%1). Wait for it to finish.").arg(summary.lockHolderInfo)); + return; + } + + auto text = summary.lockHolderInfo.isEmpty() + ? QCoreApplication::translate("LibraryWindow", "The library is locked by a repair that did not finish.") + : QCoreApplication::translate("LibraryWindow", "The library is locked by a repair started by %1.").arg(summary.lockHolderInfo); + text += "\n\n"; + text += QCoreApplication::translate("LibraryWindow", "If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue?"); + + const auto answer = QMessageBox::question(dialogParent, + dialogTitle, + text, + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No); + if (answer == QMessageBox::Yes) + startRepair(true); + return; + } + + if (summary.canceled || !summary.error.isEmpty()) + return; + + QMessageBox messageBox(QMessageBox::Information, + dialogTitle, + QCoreApplication::translate("LibraryWindow", "Repaired: %1\nFailed: %2\nMissing files: %3").arg(summary.repaired).arg(summary.failed).arg(summary.missingFiles), + QMessageBox::Ok, + dialogParent); + if (!summary.failedFilePaths.isEmpty()) + messageBox.setDetailedText(summary.failedFilePaths.join('\n')); + messageBox.exec(); +} + +void LibraryRepairCoordinator::handleFailure(const QString &error) +{ + if (!libraryPath.isEmpty() && QFile::exists(LibraryPaths::libraryDatabasePath(libraryPath)) && !DataBaseManagement::isLibraryDatabaseValid(libraryPath)) { + emit databaseRecoveryRequested(libraryName); + return; + } + QMessageBox::critical(dialogParent, dialogTitle, error); +} diff --git a/YACReaderLibrary/library_repair_coordinator.h b/YACReaderLibrary/library_repair_coordinator.h new file mode 100644 index 000000000..cd7103a79 --- /dev/null +++ b/YACReaderLibrary/library_repair_coordinator.h @@ -0,0 +1,49 @@ +#ifndef LIBRARY_REPAIR_COORDINATOR_H +#define LIBRARY_REPAIR_COORDINATOR_H + +#include +#include + +#include + +class QSettings; +class QWidget; +class YACReaderLibraries; + +namespace YACReader { +class ComicInfoRepairer; +} + +class LibraryRepairCoordinator : public QObject +{ + Q_OBJECT + +public: + using CurrentLibraryNameProvider = std::function; + + LibraryRepairCoordinator(QSettings *settings, YACReaderLibraries &libraries, QWidget *dialogParent, CurrentLibraryNameProvider currentLibraryNameProvider); + + void repairCurrentLibrary(const QString &dialogTitle); + void stop(); + +signals: + void repairStarted(); + void repairFinished(); + void comicProcessed(const QString &relativePath, const QString &coverPath); + void databaseRecoveryRequested(const QString &libraryName); + +private: + void startRepair(bool removeStaleLock); + void handleFinished(); + void handleFailure(const QString &error); + + YACReaderLibraries &libraries; + QWidget *dialogParent; + CurrentLibraryNameProvider currentLibraryNameProvider; + YACReader::ComicInfoRepairer *repairer; + QString libraryName; + QString libraryPath; + QString dialogTitle; +}; + +#endif diff --git a/YACReaderLibrary/library_search_coordinator.cpp b/YACReaderLibrary/library_search_coordinator.cpp new file mode 100644 index 000000000..8ad6dce78 --- /dev/null +++ b/YACReaderLibrary/library_search_coordinator.cpp @@ -0,0 +1,82 @@ +#include "library_search_coordinator.h" + +#include "comic_item.h" +#include "comic_model.h" +#include "comics_view.h" +#include "folder_item.h" +#include "folder_model.h" +#include "yacreader_content_views_manager.h" +#include "yacreader_folders_view.h" + +LibrarySearchCoordinator::LibrarySearchCoordinator(FolderModel *foldersModel, + FolderModelProxy *foldersModelProxy, + ComicModel *comicsModel, + YACReaderFoldersView *foldersView, + YACReaderContentViewsManager *contentViewsManager, + ClearSearchInput clearSearchInput, + QObject *parent) + : QObject(parent), foldersModel(foldersModel), foldersModelProxy(foldersModelProxy), comicsModel(comicsModel), foldersView(foldersView), contentViewsManager(contentViewsManager), clearSearchInput(std::move(clearSearchInput)), folderQueryResultProcessor(std::make_unique(foldersModel)) +{ + qRegisterMetaType("FolderItem *"); + qRegisterMetaType *>("QMap *"); + + connect(&comicQueryResultProcessor, &YACReader::ComicQueryResultProcessor::newData, this, &LibrarySearchCoordinator::applyComicResults); + connect(folderQueryResultProcessor.get(), &YACReader::FolderQueryResultProcessor::newData, this, &LibrarySearchCoordinator::applyFolderResults); +} + +bool LibrarySearchCoordinator::isSearching() const +{ + return searching; +} + +bool LibrarySearchCoordinator::exitSearchMode() +{ + if (!searching) + return false; + + clearSearchInput(); + clearResults(); + return true; +} + +void LibrarySearchCoordinator::search(const QString &filter) +{ + if (!filter.isEmpty()) { + folderQueryResultProcessor->createModelData(filter); + comicQueryResultProcessor.createModelData(filter, foldersModel->getDatabase()); + } else if (searching) { + clearResults(); + emit previousNavigationStateRequested(); + } +} + +void LibrarySearchCoordinator::applyComicResults(QList *data, const QString &databasePath) +{ + searching = true; + + comicsModel->setModelData(data, databasePath); + contentViewsManager->comicsView->enableFilterMode(true); + contentViewsManager->comicsView->setModel(comicsModel); // TODO, columns are messed up after ResetModel some times, this shouldn't be necesary + + const bool noResults = comicsModel->rowCount() == 0; + if (noResults) + contentViewsManager->showNoSearchResults(); + else + contentViewsManager->showComicsView(); + + emit comicActionsDisabledChanged(noResults); +} + +void LibrarySearchCoordinator::applyFolderResults(QMap *filteredItems, FolderItem *root) +{ + foldersModelProxy->setFilterData(filteredItems, root); + foldersView->expandAll(); +} + +void LibrarySearchCoordinator::clearResults() +{ + foldersModelProxy->clear(); + contentViewsManager->comicsView->enableFilterMode(false); + foldersView->collapseAll(); + searching = false; +} diff --git a/YACReaderLibrary/library_search_coordinator.h b/YACReaderLibrary/library_search_coordinator.h new file mode 100644 index 000000000..2b22ad9ae --- /dev/null +++ b/YACReaderLibrary/library_search_coordinator.h @@ -0,0 +1,63 @@ +#ifndef LIBRARY_SEARCH_COORDINATOR_H +#define LIBRARY_SEARCH_COORDINATOR_H + +#include "comic_query_result_processor.h" +#include "folder_query_result_processor.h" + +#include + +#include +#include + +class ComicItem; +class ComicModel; +class FolderItem; +class FolderModel; +class FolderModelProxy; +class YACReaderContentViewsManager; +class YACReaderFoldersView; + +class LibrarySearchCoordinator : public QObject +{ + Q_OBJECT + +public: + using ClearSearchInput = std::function; + + LibrarySearchCoordinator(FolderModel *foldersModel, + FolderModelProxy *foldersModelProxy, + ComicModel *comicsModel, + YACReaderFoldersView *foldersView, + YACReaderContentViewsManager *contentViewsManager, + ClearSearchInput clearSearchInput, + QObject *parent = nullptr); + + bool isSearching() const; + bool exitSearchMode(); + +public slots: + void search(const QString &filter); + +signals: + void previousNavigationStateRequested(); + void comicActionsDisabledChanged(bool disabled); + +private slots: + void applyComicResults(QList *data, const QString &databasePath); + void applyFolderResults(QMap *filteredItems, FolderItem *root); + +private: + void clearResults(); + + FolderModel *foldersModel; + FolderModelProxy *foldersModelProxy; + ComicModel *comicsModel; + YACReaderFoldersView *foldersView; + YACReaderContentViewsManager *contentViewsManager; + ClearSearchInput clearSearchInput; + YACReader::ComicQueryResultProcessor comicQueryResultProcessor; + std::unique_ptr folderQueryResultProcessor; + bool searching { false }; +}; + +#endif // LIBRARY_SEARCH_COORDINATOR_H diff --git a/YACReaderLibrary/library_window.cpp b/YACReaderLibrary/library_window.cpp index 49f0ebf7e..7e6e9d3c7 100644 --- a/YACReaderLibrary/library_window.cpp +++ b/YACReaderLibrary/library_window.cpp @@ -1,72 +1,37 @@ #include "library_window.h" -#include "yacreader_global.h" -#include "yacreader_global_gui.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#ifdef Q_OS_WIN -#include - -#include -#endif - #include "QsLog.h" -#include "add_label_dialog.h" #include "add_library_dialog.h" -#include "api_key_dialog.h" #include "comic_db.h" -#include "comic_files_manager.h" -#include "comic_info_repairer.h" +#include "comic_management_coordinator.h" #include "comic_model.h" #include "comic_vine_dialog.h" -#include "comics_remover.h" #include "comics_view.h" -#include "cover_utils.h" #include "create_library_dialog.h" #include "data_base_management.h" #include "db_helper.h" #include "edit_shortcuts_dialog.h" #include "export_comics_info_dialog.h" #include "export_library_dialog.h" -#include "folder_content_view.h" +#include "feature_flags.h" #include "folder_item.h" +#include "folder_management_coordinator.h" #include "folder_model.h" +#include "grid_comics_view.h" #include "help_about_dialog.h" #include "import_comics_info_dialog.h" #include "import_library_dialog.h" #include "import_widget.h" -#include "library_comic_opener.h" -#include "library_creator.h" +#include "library_database_maintenance_coordinator.h" +#include "library_management_coordinator.h" +#include "library_repair_coordinator.h" +#include "library_search_coordinator.h" +#include "library_window_menus.h" #include "no_libraries_widget.h" #include "options_dialog.h" -#include "package_manager.h" +#include "organize_files_coordinator.h" #include "properties_dialog.h" -#include "reading_list_item.h" +#include "reading_list_management_coordinator.h" #include "reading_list_model.h" #include "recent_visibility_coordinator.h" #include "rename_library_dialog.h" @@ -76,9 +41,10 @@ #include "static.h" #include "trayicon_controller.h" #include "whats_new_controller.h" -#include "xml_info_library_scanner.h" #include "yacreader_content_views_manager.h" #include "yacreader_folders_view.h" +#include "yacreader_global.h" +#include "yacreader_global_gui.h" #include "yacreader_history_controller.h" #include "yacreader_http_server.h" #include "yacreader_library_list_widget.h" @@ -88,28 +54,35 @@ #include "yacreader_sidebar.h" #include "yacreader_titled_toolbar.h" #include "yacreader_tool_bar_stretch.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include extern YACReaderHttpServer *httpServer; #include -namespace { -template -void moveAndConnectRemoverToThread(Remover *remover, QThread *thread) -{ - Q_ASSERT(remover); - Q_ASSERT(thread); - remover->moveToThread(thread); - QObject::connect(thread, &QThread::started, remover, &Remover::process); - QObject::connect(remover, &Remover::finished, remover, &QObject::deleteLater); - QObject::connect(remover, &Remover::finished, thread, &QThread::quit); - QObject::connect(thread, &QThread::finished, thread, &QObject::deleteLater); -} -} - using namespace YACReader; LibraryWindow::LibraryWindow() - : QMainWindow(), fullscreen(false), previousFilter(""), fetching(false), status(LibraryWindow::Normal), removeError(false), pendingAfterLaunchTasks(false) + : QMainWindow(), fullscreen(false), pendingAfterLaunchTasks(false) { createSettings(); @@ -157,17 +130,19 @@ void LibraryWindow::showEvent(QShowEvent *event) bool LibraryWindow::eventFilter(QObject *object, QEvent *event) { if (this->isActiveWindow()) { - if (event->type() == QEvent::MouseButtonRelease) { + if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease) { auto mouseEvent = static_cast(event); if (mouseEvent->button() == Qt::ForwardButton) { - actions.forwardAction->trigger(); + if (event->type() == QEvent::MouseButtonRelease) + actions.forwardAction->trigger(); event->accept(); return true; } if (mouseEvent->button() == Qt::BackButton) { - actions.backAction->trigger(); + if (event->type() == QEvent::MouseButtonRelease) + actions.backAction->trigger(); event->accept(); return true; } @@ -213,11 +188,6 @@ void LibraryWindow::setupUI() { setUnifiedTitleAndToolBarOnMac(true); - libraryCreator = new LibraryCreator(settings); - packageManager = new PackageManager(); - xmlInfoLibraryScanner = new XMLInfoLibraryScanner(); - comicInfoRepairer = new ComicInfoRepairer(settings); - historyController = new YACReaderHistoryController(this); actions.createActions(this, settings); @@ -226,11 +196,42 @@ void LibraryWindow::setupUI() doDialogs(); doLayout(); createToolBars(); - createMenus(); + + librarySearchCoordinator = new LibrarySearchCoordinator( + foldersModel, + foldersModelProxy, + comicsModel, + foldersView, + contentViewsManager, + [this] { clearSearchInput(false); }, + this); + navigationController = new YACReaderNavigationController(this, contentViewsManager, librarySearchCoordinator); + connect(librarySearchCoordinator, &LibrarySearchCoordinator::previousNavigationStateRequested, navigationController, &YACReaderNavigationController::loadPreviousStatus); + connect(librarySearchCoordinator, &LibrarySearchCoordinator::comicActionsDisabledChanged, this, &LibraryWindow::setComicActionsDisabled); setupCoordinators(); - navigationController = new YACReaderNavigationController(this, contentViewsManager); + menus = new LibraryWindowMenus( + this, + actions, + selectedLibrary, + foldersView, + contentViewsManager, + foldersModel, + foldersModelProxy, + listsModel, + folderManagementCoordinator, + comicManagementCoordinator, + organizeFilesCoordinator, + [this] { return getSelectedComics(); }, + [this] { return static_cast(libraries.getId(selectedLibrary->currentText())); }, + [this] { return currentPath(); }, + [this]() -> const Theme & { return theme; }); + menus->setupMenus(); + contentViewsManager->setLibraryWindowMenus(menus); + connect(menus, &LibraryWindowMenus::currentLibraryTypeChangeRequested, this, &LibraryWindow::setCurrentLibraryAs); + connect(menus, &LibraryWindowMenus::folderUpdateRequested, libraryManagementCoordinator, &LibraryManagementCoordinator::updateFolder); + connect(menus, &LibraryWindowMenus::folderXmlRescanRequested, libraryManagementCoordinator, &LibraryManagementCoordinator::rescanFolderForXMLInfo); createConnections(); @@ -269,6 +270,12 @@ void LibraryWindow::setupUI() void LibraryWindow::applyTheme(const Theme &theme) { editInfoToolBar->setStyleSheet(theme.comicsViewToolbar.toolbarQSS); + // Both menu buttons carry their own icon, because neither has a default action + // to take one from. See createMenuToolButton(). + if (organizeToolButton != nullptr) + organizeToolButton->setIcon(theme.comicsViewToolbar.organizeIcon); + if (setTypeToolButton != nullptr) + setTypeToolButton->setIcon(theme.comicsViewToolbar.setAsNormalIcon); mainSplitter->setStyleSheet(theme.contentSplitter.horizontalSplitterQSS); // Update main toolbar and comics view toolbar icons @@ -365,9 +372,6 @@ void LibraryWindow::doLayout() importWidget = new ImportWidget(); mainWidget->addWidget(importWidget); - connect(noLibrariesWidget, &NoLibrariesWidget::createNewLibrary, this, &LibraryWindow::createLibrary); - connect(noLibrariesWidget, &NoLibrariesWidget::addExistingLibrary, this, &LibraryWindow::showAddLibrary); - // collapsible disabled in macosx (only temporaly) #ifdef Y_MAC_UI sHorizontal->setCollapsible(0, false); @@ -413,7 +417,6 @@ void LibraryWindow::doModels() // folders foldersModel = new FolderModel(this); foldersModelProxy = new FolderModelProxy(this); - folderQueryResultProcessor.reset(new FolderQueryResultProcessor(foldersModel)); // foldersModelProxy->setSourceModel(foldersModel); // comics comicsModel = new ComicModel(this); @@ -424,7 +427,198 @@ void LibraryWindow::doModels() void LibraryWindow::setupCoordinators() { - recentVisibilityCoordinator = new RecentVisibilityCoordinator(settings, foldersModel, contentViewsManager->folderContentView, comicsModel); + recentVisibilityCoordinator = new RecentVisibilityCoordinator(settings, foldersModel, comicsModel); + organizeFilesCoordinator = new OrganizeFilesCoordinator( + settings, + this, + comicsModel, + foldersModel, + [this] { return getSelectedComics(); }, + [this] { + // A search shows comics from the whole library while the folder + // tree keeps its old selection. That folder says nothing about the + // results, so the base is the library root, forced. + if (librarySearchCoordinator != nullptr && librarySearchCoordinator->isSearching()) + return QModelIndex(); + return getCurrentFolderIndex(); + }, + [this] { + const auto libraryName = selectedLibrary->currentText(); + return OrganizeFilesCoordinator::LibraryContext { static_cast(libraries.getId(libraryName)), libraries.getPath(libraryName) }; + }); + connect(organizeFilesCoordinator, &OrganizeFilesCoordinator::libraryContentChanged, this, &LibraryWindow::reloadCurrentLibrary); + comicManagementCoordinator = new ComicManagementCoordinator( + this, + settings, + comicsModel, + foldersModel, + foldersModelProxy, + propertiesDialog, + comicVineDialog, + [this] { return getSelectedComics(); }, + [this] { + if (listsView->selectionModel() == nullptr || listsView->selectionModel()->selectedRows().isEmpty()) + return QModelIndex(); + return listsModelProxy->mapToSource(listsView->currentIndex()); + }, + [this] { return getCurrentFolderIndex(); }, + [this] { return contentViewsManager->comicsView->currentIndex(); }, + [this] { return !importedCovers; }, + [this] { return static_cast(libraries.getId(selectedLibrary->currentText())); }, + [this] { return currentPath(); }); + contentViewsManager->setComicManagementCoordinator(comicManagementCoordinator); + connect(comicManagementCoordinator, &ComicManagementCoordinator::currentComicViewUpdateRequested, contentViewsManager, &YACReaderContentViewsManager::updateCurrentComicView); + connect(comicManagementCoordinator, &ComicManagementCoordinator::currentSourceRefreshStarted, navigationController, &YACReaderNavigationController::beginCurrentSourceRefresh); + connect(comicManagementCoordinator, &ComicManagementCoordinator::currentSourceRefreshAccepted, navigationController, &YACReaderNavigationController::refreshCurrentSource); + connect(comicManagementCoordinator, &ComicManagementCoordinator::currentSourceRefreshCancelled, navigationController, &YACReaderNavigationController::cancelCurrentSourceRefresh); + connect(comicManagementCoordinator, &ComicManagementCoordinator::comicNumbersAssigned, this, [this](qint64 editedComicId) { + navigationController->loadFolderContent(foldersModelProxy->mapToSource(foldersView->currentIndex())); + + const auto editedComic = comicsModel->getIndexFromId(editedComicId); + if (editedComic.isValid()) { + contentViewsManager->comicsView->scrollTo(editedComic, QAbstractItemView::PositionAtCenter); + contentViewsManager->comicsView->setCurrentIndex(editedComic); + } + }); + connect(comicManagementCoordinator, &ComicManagementCoordinator::comicDeletionFinished, this, &LibraryWindow::checkEmptyFolder); + connect(comicManagementCoordinator, &ComicManagementCoordinator::rootContinueReadingReloadRequested, navigationController, &YACReaderNavigationController::reloadRootContinueReading); + readingListManagementCoordinator = new ReadingListManagementCoordinator( + this, + listsModel, + comicsModel, + [this] { + if (listsView->selectionModel() == nullptr) + return QModelIndex(); + const auto selectedLists = listsView->selectionModel()->selectedIndexes(); + return selectedLists.isEmpty() ? QModelIndex() : listsModelProxy->mapToSource(selectedLists.constFirst()); + }); + connect(readingListManagementCoordinator, &ReadingListManagementCoordinator::currentListReselectionRequested, navigationController, &YACReaderNavigationController::reselectCurrentList); + folderManagementCoordinator = new FolderManagementCoordinator( + foldersModel, + this, + [this] { return foldersModelProxy->mapToSource(foldersView->currentIndex()); }, + [this] { return getCurrentFolderIndex(); }, + [this] { return currentPath(); }); + connect(folderManagementCoordinator, &FolderManagementCoordinator::folderRenamed, navigationController, &YACReaderNavigationController::refreshCurrentSource); + connect(folderManagementCoordinator, &FolderManagementCoordinator::folderCreationStarted, this, [this] { librarySearchCoordinator->exitSearchMode(); }); + connect(folderManagementCoordinator, &FolderManagementCoordinator::folderNavigationRequested, this, [this](const QModelIndex &folder) { + foldersView->setCurrentIndex(foldersModelProxy->mapFromSource(folder)); + navigationController->loadFolderContent(folder); + historyController->updateHistory(YACReaderLibrarySourceContainer(folder, YACReaderLibrarySourceContainer::Folder)); + }); + connect(folderManagementCoordinator, &FolderManagementCoordinator::folderAboutToBeDeleted, this, [this](const QModelIndex &parentFolder) { + // The unified grid observes the main folder model directly. Move away + // from the folder before removing its model index so the content view + // never retains the index being deleted. + if (parentFolder.isValid()) + foldersView->setCurrentIndex(foldersModelProxy->mapFromSource(parentFolder)); + else + setRootIndex(); + }); + connect(folderManagementCoordinator, &FolderManagementCoordinator::folderDeletionFinished, navigationController, &YACReaderNavigationController::reselectCurrentFolder); + connect(contentViewsManager->gridView(), &ComicsView::customFolderCoverRequested, folderManagementCoordinator, qOverload(&FolderManagementCoordinator::setCustomCover)); + libraryDatabaseMaintenanceCoordinator = new LibraryDatabaseMaintenanceCoordinator( + libraries, + this, + [this] { return selectedLibrary->currentText(); }); + connect(libraryDatabaseMaintenanceCoordinator, &LibraryDatabaseMaintenanceCoordinator::backupAvailabilityChanged, actions.backupLibraryAction, &QAction::setEnabled); + connect(libraryDatabaseMaintenanceCoordinator, &LibraryDatabaseMaintenanceCoordinator::maintenanceStarted, this, [this] { + contentViewsManager->comicsView->setModel(nullptr); + foldersView->setModel(nullptr); + listsView->setModel(nullptr); + actions.disableAllActions(); + }); + connect(libraryDatabaseMaintenanceCoordinator, &LibraryDatabaseMaintenanceCoordinator::invalidDatabaseRestoreCancelled, this, [this] { + actions.renameLibraryAction->setEnabled(true); + actions.removeLibraryAction->setEnabled(true); + actions.restoreLibraryAction->setEnabled(true); + }); + connect(libraryDatabaseMaintenanceCoordinator, &LibraryDatabaseMaintenanceCoordinator::databaseUnavailableAfterRestore, this, [this] { + actions.restoreLibraryAction->setEnabled(true); + actions.removeLibraryAction->setEnabled(true); + }); + connect(libraryDatabaseMaintenanceCoordinator, &LibraryDatabaseMaintenanceCoordinator::databaseSalvageFailed, this, [this] { + actions.restoreLibraryAction->setEnabled(true); + }); + libraryRepairCoordinator = new LibraryRepairCoordinator( + settings, + libraries, + this, + [this] { return selectedLibrary->currentText(); }); + connect(libraryRepairCoordinator, &LibraryRepairCoordinator::repairStarted, importWidget, &ImportWidget::setRepairLook); + connect(libraryRepairCoordinator, &LibraryRepairCoordinator::repairStarted, this, &LibraryWindow::showImportingWidget); + connect(libraryRepairCoordinator, &LibraryRepairCoordinator::repairFinished, this, &LibraryWindow::showRootWidget); + connect(libraryRepairCoordinator, &LibraryRepairCoordinator::repairFinished, this, &LibraryWindow::reloadCurrentLibrary); + connect(libraryRepairCoordinator, &LibraryRepairCoordinator::comicProcessed, importWidget, &ImportWidget::newComic); + libraryManagementCoordinator = new LibraryManagementCoordinator( + settings, + libraries, + this, + createLibraryDialog, + addLibraryDialog, + exportLibraryDialog, + importLibraryDialog, + foldersModel, + [this] { return selectedLibrary->currentText(); }, + [this] { return getCurrentFolderIndex(); }, + tr("Library info")); + connect(noLibrariesWidget, &NoLibrariesWidget::createNewLibrary, libraryManagementCoordinator, &LibraryManagementCoordinator::showCreateLibraryDialog); + connect(noLibrariesWidget, &NoLibrariesWidget::addExistingLibrary, libraryManagementCoordinator, &LibraryManagementCoordinator::showAddLibraryDialog); + connect(libraryDatabaseMaintenanceCoordinator, &LibraryDatabaseMaintenanceCoordinator::libraryReloadRequested, libraryManagementCoordinator, &LibraryManagementCoordinator::loadLibrary); + connect(comicManagementCoordinator, &ComicManagementCoordinator::importRequested, libraryManagementCoordinator, [this](qulonglong folderId) { + libraryManagementCoordinator->updateFolder(foldersModel->getIndexFromFolderId(folderId)); + }); + connect(contentViewsManager->gridView(), &GridComicsView::openLibraryFolderRequested, libraryManagementCoordinator, &LibraryManagementCoordinator::openCurrentLibraryFolder); + connect(libraryDatabaseMaintenanceCoordinator, &LibraryDatabaseMaintenanceCoordinator::libraryUpdateRequested, libraryManagementCoordinator, &LibraryManagementCoordinator::updateCurrentLibrary); + connect(libraryRepairCoordinator, &LibraryRepairCoordinator::databaseRecoveryRequested, libraryDatabaseMaintenanceCoordinator, [coordinator = libraryDatabaseMaintenanceCoordinator, restoreAction = actions.restoreLibraryAction](const QString &libraryName) { + coordinator->offerDatabaseRecovery(libraryName, restoreAction->text()); + }); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::loadStarted, this, [this] { + historyController->clear(); + showRootWidget(); + }); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::noLibrariesRequested, this, [this] { + actions.disableAllActions(); + showNoLibrariesWidget(); + }); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::libraryReady, this, &LibraryWindow::applyLoadedLibrary); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::libraryManagementOnlyRequested, this, &LibraryWindow::showLibraryManagementOnly); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::databaseRecoveryRequested, libraryDatabaseMaintenanceCoordinator, [coordinator = libraryDatabaseMaintenanceCoordinator, restoreAction = actions.restoreLibraryAction](const QString &libraryName) { + coordinator->offerDatabaseRecovery(libraryName, restoreAction->text()); + }); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::upgradeStarted, importWidget, &ImportWidget::setUpgradeLook); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::upgradeStarted, this, &LibraryWindow::showImportingWidget); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::creationStarted, importWidget, &ImportWidget::setImportLook); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::creationStarted, this, &LibraryWindow::showImportingWidget); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::updateStarted, importWidget, &ImportWidget::setUpdateLook); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::updateStarted, this, &LibraryWindow::showImportingWidget); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::operationUiResetRequested, this, &LibraryWindow::showRootWidget); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::operationFinished, this, &LibraryWindow::showRootWidget); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::currentLibraryReloadRequested, this, &LibraryWindow::reloadCurrentLibrary); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::libraryAdded, this, &LibraryWindow::addLibraryToSelector); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::libraryRemoved, this, &LibraryWindow::handleLibraryRemoved); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::libraryRenamed, this, [this](const QString &oldName, const QString &newName) { + if (newName == oldName) + return; + + selectedLibrary->renameCurrentLibrary(newName); +#ifndef Y_MAC_UI + if (!foldersModelProxy->mapToSource(foldersView->currentIndex()).isValid()) + libraryToolBar->setCurrentFolderName(newName); +#endif + }); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::folderUpdateFinished, this, [this](qulonglong folderId) { + reloadAfterCopyMove(foldersModel->getIndexFromFolderId(folderId)); + }); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::comicAdded, importWidget, &ImportWidget::newComic); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::xmlScanStarted, importWidget, &ImportWidget::setXMLScanLook); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::xmlScanStarted, this, &LibraryWindow::showImportingWidget); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::xmlScanFinished, this, &LibraryWindow::showRootWidget); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::xmlScanFinished, this, &LibraryWindow::reloadCurrentFolderComicsContent); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::xmlComicScanned, importWidget, &ImportWidget::newComic); + connect(libraryManagementCoordinator, &LibraryManagementCoordinator::packageFailed, this, [this](const QString &error) { + QMessageBox::critical(this, tr("Package operation failed"), error.isEmpty() ? tr("The covers package operation could not be completed.") : error); + }); auto canStartUpdateProvider = [this]() { return comicVineDialog->isVisible() == false && @@ -438,7 +632,7 @@ void LibraryWindow::setupCoordinators() connect(librariesUpdateCoordinator, &LibrariesUpdateCoordinator::updateStarted, sideBar->librariesTitle, &YACReaderTitledToolBar::showBusyIndicator); connect(librariesUpdateCoordinator, &LibrariesUpdateCoordinator::updateEnded, sideBar->librariesTitle, &YACReaderTitledToolBar::hideBusyIndicator); - connect(librariesUpdateCoordinator, &LibrariesUpdateCoordinator::updateStarted, this, [=]() { + connect(librariesUpdateCoordinator, &LibrariesUpdateCoordinator::updateStarted, this, [=, this]() { actions.disableAllActions(); }); connect(librariesUpdateCoordinator, &LibrariesUpdateCoordinator::updateEnded, this, &LibraryWindow::reloadCurrentLibrary); @@ -456,6 +650,29 @@ bool LibraryWindow::hasLoadedLibraryModels() const listsModelProxy->sourceModel() == listsModel; } +namespace { + +QToolButton *createMenuToolButton(const QList &entries, const QString &toolTip) +{ + Q_ASSERT(!entries.isEmpty()); + + auto button = new QToolButton(); + for (auto *entry : entries) + button->addAction(entry); + + button->setPopupMode(QToolButton::InstantPopup); + button->setToolTip(toolTip); + + auto *first = entries.first(); + const auto followFirstEntry = [button, first] { button->setEnabled(first->isEnabled()); }; + QObject::connect(first, &QAction::changed, button, followFirstEntry); + followFirstEntry(); + + return button; +} + +} + void LibraryWindow::createToolBars() { @@ -512,6 +729,11 @@ void LibraryWindow::createToolBars() editInfoToolBar->addAction(actions.openComicAction); editInfoToolBar->addSeparator(); editInfoToolBar->addAction(actions.editSelectedComicsAction); + if (YACReader::FeatureFlags::organizeFiles) { + organizeToolButton = createMenuToolButton({ actions.renameComicsFilesAction, actions.organizeComicsFilesAction }, + tr("Rename or organize files")); + editInfoToolBar->addWidget(organizeToolButton); + } editInfoToolBar->addAction(actions.getInfoAction); editInfoToolBar->addAction(actions.asignOrderAction); @@ -528,22 +750,20 @@ void LibraryWindow::createToolBars() editInfoToolBar->addSeparator(); - auto setTypeToolButton = new QToolButton(); - setTypeToolButton->addAction(actions.setNormalAction); - setTypeToolButton->addAction(actions.setMangaAction); - setTypeToolButton->addAction(actions.setWesternMangaAction); - setTypeToolButton->addAction(actions.setWebComicAction); - setTypeToolButton->addAction(actions.setYonkomaAction); - setTypeToolButton->setPopupMode(QToolButton::InstantPopup); - setTypeToolButton->setDefaultAction(actions.setNormalAction); + setTypeToolButton = createMenuToolButton({ actions.setNormalAction, actions.setMangaAction, + actions.setWesternMangaAction, actions.setWebComicAction, + actions.setYonkomaAction }, + tr("Set the type of the selected comics")); editInfoToolBar->addWidget(setTypeToolButton); editInfoToolBar->addSeparator(); editInfoToolBar->addAction(actions.deleteComicsAction); + comicToolbarEntries = editInfoToolBar->actions(); + auto toolBarStretch = new YACReaderToolBarStretch(this); - editInfoToolBar->addWidget(toolBarStretch); + comicToolbarEndAnchor = editInfoToolBar->addWidget(toolBarStretch); editInfoToolBar->addAction(actions.toogleShowRecentIndicatorAction); @@ -637,328 +857,37 @@ void LibraryWindow::showSearchSyntax() dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->open(); } - -void LibraryWindow::createMenus() -{ - foldersView->addAction(actions.addFolderAction); - foldersView->addAction(actions.deleteFolderAction); - YACReader::addSperator(foldersView); - - foldersView->addAction(actions.openContainingFolderAction); - foldersView->addAction(actions.updateFolderAction); - YACReader::addSperator(foldersView); - - foldersView->addAction(actions.setFolderAsNotCompletedAction); - foldersView->addAction(actions.setFolderAsCompletedAction); - YACReader::addSperator(foldersView); - - foldersView->addAction(actions.setFolderAsReadAction); - foldersView->addAction(actions.setFolderAsUnreadAction); - YACReader::addSperator(foldersView); - - foldersView->addAction(actions.setFolderAsNormalAction); - foldersView->addAction(actions.setFolderAsMangaAction); - foldersView->addAction(actions.setFolderAsWesternMangaAction); - foldersView->addAction(actions.setFolderAsWebComicAction); - foldersView->addAction(actions.setFolderAsYonkomaAction); - YACReader::addSperator(foldersView); - - foldersView->addAction(actions.setFolderCoverAction); - foldersView->addAction(actions.deleteCustomFolderCoverAction); - - selectedLibrary->addAction(actions.updateLibraryAction); - selectedLibrary->addAction(actions.renameLibraryAction); - selectedLibrary->addAction(actions.removeLibraryAction); - YACReader::addSperator(selectedLibrary); - - auto setNormalAction = new QAction(); - setNormalAction->setText(tr("comic")); - - auto setMangaAction = new QAction(); - setMangaAction->setText(tr("manga")); - - auto setWesternMangaAction = new QAction(); - setWesternMangaAction->setText(tr("western manga (left to right)")); - - auto setWebComicAction = new QAction(); - setWebComicAction->setText(tr("web comic")); - - auto setYonkomaAction = new QAction(); - setYonkomaAction->setText(tr("4koma (top to botom)")); - - setNormalAction->setCheckable(true); - setMangaAction->setCheckable(true); - setWesternMangaAction->setCheckable(true); - setWebComicAction->setCheckable(true); - setYonkomaAction->setCheckable(true); - - auto setupActions = [=](FileType type) { - setNormalAction->setChecked(false); - setMangaAction->setChecked(false); - setWesternMangaAction->setChecked(false); - setWebComicAction->setChecked(false); - setYonkomaAction->setChecked(false); - - switch (type) { - case YACReader::FileType::Comic: - setNormalAction->setChecked(true); - break; - case YACReader::FileType::Manga: - setMangaAction->setChecked(true); - break; - case YACReader::FileType::WesternManga: - setWesternMangaAction->setChecked(true); - break; - case YACReader::FileType::WebComic: - setWebComicAction->setChecked(true); - break; - case YACReader::FileType::Yonkoma: - setYonkomaAction->setChecked(true); - break; - } - }; - - connect(setNormalAction, &QAction::triggered, this, [=]() { setCurrentLibraryAs(FileType::Comic); }); - connect(setMangaAction, &QAction::triggered, this, [=]() { setCurrentLibraryAs(FileType::Manga); }); - connect(setWesternMangaAction, &QAction::triggered, this, [=]() { setCurrentLibraryAs(FileType::WesternManga); }); - connect(setWebComicAction, &QAction::triggered, this, [=]() { setCurrentLibraryAs(FileType::WebComic); }); - connect(setYonkomaAction, &QAction::triggered, this, [=]() { setCurrentLibraryAs(FileType::Yonkoma); }); - - auto typeMenu = new QMenu(tr("Set type"), selectedLibrary); - - connect(typeMenu, &QMenu::aboutToShow, this, [=]() { - auto folder = foldersModel->getRootFolder(); - setupActions(folder.type); - }); - - selectedLibrary->addAction(typeMenu->menuAction()); - YACReader::addSperator(selectedLibrary); - typeMenu->addAction(setNormalAction); - typeMenu->addAction(setMangaAction); - typeMenu->addAction(setWesternMangaAction); - typeMenu->addAction(setWebComicAction); - typeMenu->addAction(setYonkomaAction); - - selectedLibrary->addAction(actions.rescanLibraryForXMLInfoAction); - selectedLibrary->addAction(actions.repairLibraryAction); - YACReader::addSperator(selectedLibrary); - - selectedLibrary->addAction(actions.backupLibraryAction); - selectedLibrary->addAction(actions.restoreLibraryAction); - YACReader::addSperator(selectedLibrary); - - selectedLibrary->addAction(actions.exportComicsInfoAction); - selectedLibrary->addAction(actions.importComicsInfoAction); - YACReader::addSperator(selectedLibrary); - - selectedLibrary->addAction(actions.exportLibraryAction); - selectedLibrary->addAction(actions.importLibraryAction); - YACReader::addSperator(selectedLibrary); - - selectedLibrary->addAction(actions.openLibraryFolderAction); - selectedLibrary->addAction(actions.showLibraryInfo); - -// MacOSX app menus -#ifdef Q_OS_MACOS - QMenuBar *menu = this->menuBar(); - // about / preferences - // TODO - - // library - QMenu *libraryMenu = new QMenu(tr("Library")); - - libraryMenu->addAction(actions.updateLibraryAction); - libraryMenu->addAction(actions.renameLibraryAction); - libraryMenu->addAction(actions.removeLibraryAction); - libraryMenu->addSeparator(); - - libraryMenu->addMenu(typeMenu); - libraryMenu->addSeparator(); - - libraryMenu->addAction(actions.rescanLibraryForXMLInfoAction); - libraryMenu->addAction(actions.repairLibraryAction); - libraryMenu->addSeparator(); - - libraryMenu->addAction(actions.backupLibraryAction); - libraryMenu->addAction(actions.restoreLibraryAction); - libraryMenu->addSeparator(); - - libraryMenu->addAction(actions.exportComicsInfoAction); - libraryMenu->addAction(actions.importComicsInfoAction); - - libraryMenu->addSeparator(); - - libraryMenu->addAction(actions.exportLibraryAction); - libraryMenu->addAction(actions.importLibraryAction); - - libraryMenu->addSeparator(); - - libraryMenu->addAction(actions.openLibraryFolderAction); - libraryMenu->addAction(actions.showLibraryInfo); - - // folder - QMenu *folderMenu = new QMenu(tr("Folder")); - folderMenu->addAction(actions.openContainingFolderAction); - folderMenu->addAction(actions.updateFolderAction); - folderMenu->addSeparator(); - folderMenu->addAction(actions.rescanXMLFromCurrentFolderAction); - folderMenu->addSeparator(); - folderMenu->addAction(actions.setFolderAsNotCompletedAction); - folderMenu->addAction(actions.setFolderAsCompletedAction); - folderMenu->addSeparator(); - folderMenu->addAction(actions.setFolderAsReadAction); - folderMenu->addAction(actions.setFolderAsUnreadAction); - folderMenu->addSeparator(); - folderMenu->addAction(actions.setFolderAsNormalAction); - folderMenu->addAction(actions.setFolderAsMangaAction); - folderMenu->addAction(actions.setFolderAsWesternMangaAction); - folderMenu->addAction(actions.setFolderAsWebComicAction); - folderMenu->addAction(actions.setFolderAsYonkomaAction); - folderMenu->addSeparator(); - folderMenu->addAction(actions.setFolderCoverAction); - folderMenu->addAction(actions.deleteCustomFolderCoverAction); - - // comic - QMenu *comicMenu = new QMenu(tr("Comic")); - comicMenu->addAction(actions.openContainingFolderComicAction); - comicMenu->addSeparator(); - comicMenu->addAction(actions.resetComicRatingAction); - - menu->addMenu(libraryMenu); - menu->addMenu(folderMenu); - menu->addMenu(comicMenu); -#endif -} - void LibraryWindow::createConnections() { actions.createConnections( historyController, + navigationController, this, had, - exportLibraryDialog, contentViewsManager, editShortcutsDialog, foldersView, optionsDialog, serverConfigDialog, - recentVisibilityCoordinator); + recentVisibilityCoordinator, + comicManagementCoordinator, + readingListManagementCoordinator, + folderManagementCoordinator, + organizeFilesCoordinator, + libraryManagementCoordinator, + libraryDatabaseMaintenanceCoordinator, + libraryRepairCoordinator, + renameLibraryDialog); connect(actions.focusSearchLineAction, &QAction::triggered, this, &LibraryWindow::focusSearchInput); - // libraryCreator connections - connect(createLibraryDialog, &CreateLibraryDialog::createLibrary, this, QOverload::of(&LibraryWindow::create)); - connect(createLibraryDialog, &CreateLibraryDialog::libraryExists, this, &LibraryWindow::libraryAlreadyExists); connect(importComicsInfoDialog, &QDialog::finished, this, &LibraryWindow::reloadCurrentLibrary); - connect(libraryCreator, &LibraryCreator::finished, this, &LibraryWindow::showRootWidget); - connect(libraryCreator, &LibraryCreator::updated, this, &LibraryWindow::reloadCurrentLibrary); - connect(libraryCreator, &LibraryCreator::created, this, &LibraryWindow::openLastCreated); - connect(libraryCreator, &LibraryCreator::updatedCurrentFolder, this, [this](qulonglong folderId) { - reloadAfterCopyMove(foldersModel->getIndexFromFolderId(folderId)); - }); - connect(libraryCreator, &LibraryCreator::comicAdded, importWidget, &ImportWidget::newComic); - // libraryCreator errors - connect(libraryCreator, &LibraryCreator::failedCreatingDB, this, &LibraryWindow::manageCreatingError); - connect(libraryCreator, &LibraryCreator::failedOpeningDB, this, [this](const QString &error) { - showRootWidget(); - const auto libraryName = selectedLibrary->currentText(); - const auto libraryPath = libraries.getPath(libraryName); - if (!libraryPath.isEmpty() && QFile::exists(LibraryPaths::libraryDatabasePath(libraryPath)) && !DataBaseManagement::isLibraryDatabaseValid(libraryPath)) { - offerDatabaseRecovery(libraryName); - return; - } - manageUpdatingError(error); - }); - - connect(xmlInfoLibraryScanner, &QThread::finished, this, &LibraryWindow::showRootWidget); - connect(xmlInfoLibraryScanner, &QThread::finished, this, &LibraryWindow::reloadCurrentFolderComicsContent); - connect(xmlInfoLibraryScanner, &XMLInfoLibraryScanner::comicScanned, importWidget, &ImportWidget::newComic); - - connect(comicInfoRepairer, &QThread::finished, this, [this]() { - const auto summary = comicInfoRepairer->summary(); - showRootWidget(); - reloadCurrentLibrary(); - - if (summary.lockedByAnotherProcess) { - if (summary.lockHolderIsRunningLocally) { - QMessageBox::information(this, - actions.repairLibraryAction->text(), - tr("A repair of this library is already running (%1). Wait for it to finish.").arg(summary.lockHolderInfo)); - return; - } - - auto text = summary.lockHolderInfo.isEmpty() - ? tr("The library is locked by a repair that did not finish.") - : tr("The library is locked by a repair started by %1.").arg(summary.lockHolderInfo); - text += "\n\n"; - text += tr("If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue?"); - - const auto answer = QMessageBox::question(this, - actions.repairLibraryAction->text(), - text, - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No); - if (answer == QMessageBox::Yes) { - startLibraryRepair(true); - } - return; - } - - if (summary.canceled || !summary.error.isEmpty()) { - return; - } - - QMessageBox messageBox(QMessageBox::Information, - actions.repairLibraryAction->text(), - tr("Repaired: %1\nFailed: %2\nMissing files: %3").arg(summary.repaired).arg(summary.failed).arg(summary.missingFiles), - QMessageBox::Ok, - this); - if (!summary.failedFilePaths.isEmpty()) { - messageBox.setDetailedText(summary.failedFilePaths.join('\n')); - } - messageBox.exec(); - }); - connect(comicInfoRepairer, &ComicInfoRepairer::comicProcessed, importWidget, &ImportWidget::newComic); - connect(comicInfoRepairer, &ComicInfoRepairer::failed, this, [this](const QString &error) { - const auto libraryName = selectedLibrary->currentText(); - const auto libraryPath = libraries.getPath(libraryName); - if (!libraryPath.isEmpty() && QFile::exists(LibraryPaths::libraryDatabasePath(libraryPath)) && !DataBaseManagement::isLibraryDatabaseValid(libraryPath)) { - offerDatabaseRecovery(libraryName); - return; - } - QMessageBox::critical(this, actions.repairLibraryAction->text(), error); - }); - // new import widget - connect(importWidget, &ImportWidget::stop, this, &LibraryWindow::stopLibraryCreator); - connect(importWidget, &ImportWidget::stop, this, &LibraryWindow::stopXMLScanning); - connect(importWidget, &ImportWidget::stop, this, &LibraryWindow::stopComicInfoRepair); - - // packageManager connections - connect(exportLibraryDialog, &ExportLibraryDialog::exportPath, this, &LibraryWindow::exportLibrary); - connect(exportLibraryDialog, &QDialog::rejected, packageManager, &PackageManager::cancel); - connect(packageManager, &PackageManager::exported, exportLibraryDialog, &ExportLibraryDialog::close); - connect(importLibraryDialog, &ImportLibraryDialog::unpackCLC, this, &LibraryWindow::importLibrary); - connect(importLibraryDialog, &QDialog::rejected, packageManager, &PackageManager::cancel); - connect(importLibraryDialog, &QDialog::rejected, this, &LibraryWindow::deleteCurrentLibrary); - connect(importLibraryDialog, &ImportLibraryDialog::libraryExists, this, &LibraryWindow::libraryAlreadyExists); - connect(packageManager, &PackageManager::imported, importLibraryDialog, &QWidget::hide); - connect(packageManager, &PackageManager::imported, this, &LibraryWindow::openLastCreated); - connect(packageManager, &PackageManager::failed, this, [this](const QString &error) { - QMessageBox::critical(this, tr("Package operation failed"), error.isEmpty() ? tr("The covers package operation could not be completed.") : error); - }); - - // create and update dialogs - connect(createLibraryDialog, &CreateLibraryDialog::cancelCreate, this, &LibraryWindow::cancelCreating); - - // open existing library from dialog. - connect(addLibraryDialog, &AddLibraryDialog::addLibrary, this, &LibraryWindow::openLibrary); + connect(importWidget, &ImportWidget::stop, libraryManagementCoordinator, &LibraryManagementCoordinator::stop); + connect(importWidget, &ImportWidget::stop, libraryRepairCoordinator, &LibraryRepairCoordinator::stop); // load library when selected library changes - connect(selectedLibrary, &YACReaderLibraryListWidget::currentIndexChanged, this, &LibraryWindow::loadLibrary); - - // rename library dialog - connect(renameLibraryDialog, &RenameLibraryDialog::renameLibrary, this, &LibraryWindow::rename); + connect(selectedLibrary, &YACReaderLibraryListWidget::currentIndexChanged, libraryManagementCoordinator, &LibraryManagementCoordinator::loadLibrary); // navigations between view modes (tree,list and flow) // TODO connect(foldersView, SIGNAL(pressed(QModelIndex)), this, SLOT(updateFoldersViewConextMenu(QModelIndex))); @@ -966,19 +895,9 @@ void LibraryWindow::createConnections() // drops in folders view connect(foldersView, QOverload>, QModelIndex>::of(&YACReaderFoldersView::copyComicsToFolder), - this, &LibraryWindow::copyAndImportComicsToFolder); + comicManagementCoordinator, &ComicManagementCoordinator::copyAndImportComicsToFolder); connect(foldersView, QOverload>, QModelIndex>::of(&YACReaderFoldersView::moveComicsToFolder), - this, &LibraryWindow::moveAndImportComicsToFolder); - connect(foldersView, &QWidget::customContextMenuRequested, this, &LibraryWindow::showFoldersContextMenu); - - // properties & config - connect(propertiesDialog, &QDialog::accepted, contentViewsManager, &YACReaderContentViewsManager::updateCurrentContentView); - connect(propertiesDialog, &PropertiesDialog::coverChangedSignal, this, [=](const ComicDB &comic) { - comicsModel->notifyCoverChange(comic); - }); - - // comic vine - connect(comicVineDialog, &QDialog::accepted, contentViewsManager, &YACReaderContentViewsManager::updateCurrentContentView, Qt::QueuedConnection); + comicManagementCoordinator, &ComicManagementCoordinator::moveAndImportComicsToFolder); connect(optionsDialog, &YACReaderOptionsDialog::optionsChanged, this, &LibraryWindow::reloadOptions); connect(optionsDialog, &YACReaderOptionsDialog::editShortcuts, editShortcutsDialog, &QWidget::show); @@ -989,33 +908,10 @@ void LibraryWindow::createConnections() // Search filter #ifdef Y_MAC_UI connect(libraryToolBar, &YACReaderMacOSXToolbar::filterChanged, searchDebouncer, &KDToolBox::KDStringSignalDebouncer::throttle); - connect(searchDebouncer, &KDToolBox::KDStringSignalDebouncer::triggered, this, [=](QString filter) { - setSearchFilter(filter); - }); #else connect(searchEdit, &YACReaderSearchLineEdit::filterChanged, searchDebouncer, &KDToolBox::KDStringSignalDebouncer::throttle); - connect(searchDebouncer, &KDToolBox::KDStringSignalDebouncer::triggered, this, [=](QString filter) { - setSearchFilter(filter); - }); #endif - connect(&comicQueryResultProcessor, &ComicQueryResultProcessor::newData, this, &LibraryWindow::setComicSearchFilterData); - qRegisterMetaType("FolderItem *"); - qRegisterMetaType *>("QMap *"); - connect(folderQueryResultProcessor.get(), &FolderQueryResultProcessor::newData, this, &LibraryWindow::setFolderSearchFilterData); - - connect(listsModel, &ReadingListModel::addComicsToFavorites, comicsModel, QOverload &>::of(&ComicModel::addComicsToFavorites)); - connect(listsModel, &ReadingListModel::addComicsToLabel, comicsModel, QOverload &, qulonglong>::of(&ComicModel::addComicsToLabel)); - connect(listsModel, &ReadingListModel::addComicsToReadingList, comicsModel, QOverload &, qulonglong>::of(&ComicModel::addComicsToReadingList)); - //-- - - // upgrade library - connect(this, &LibraryWindow::libraryUpgraded, this, &LibraryWindow::loadLibrary, Qt::QueuedConnection); - connect(this, &LibraryWindow::errorUpgradingLibrary, this, &LibraryWindow::showErrorUpgradingLibrary, Qt::QueuedConnection); -} - -void LibraryWindow::showErrorUpgradingLibrary(const QString &path) -{ - QMessageBox::critical(this, tr("Upgrade failed"), tr("There were errors during library upgrade in: ") + path + "/library.ydb"); + connect(searchDebouncer, &KDToolBox::KDStringSignalDebouncer::triggered, librarySearchCoordinator, &LibrarySearchCoordinator::search); } void LibraryWindow::setCurrentLibraryAs(FileType fileType) @@ -1023,312 +919,56 @@ void LibraryWindow::setCurrentLibraryAs(FileType fileType) foldersModel->updateTreeType(fileType); } -void LibraryWindow::loadLibrary(const QString &name) -{ - if (!libraries.isEmpty()) // si hay bibliotecas... - { - historyController->clear(); - - showRootWidget(); - QString rootPath = libraries.getPath(name); - QString recoveryError; - if (!DataBaseManagement::recoverInterruptedRestore(rootPath, &recoveryError)) { - QMessageBox::critical(this, tr("Restore recovery failed"), recoveryError); - return; - } - QString path = LibraryPaths::libraryDataPath(rootPath); - QString customFolderCoversPath = LibraryPaths::libraryCustomFoldersCoverPath(rootPath); - QString databasePath = LibraryPaths::libraryDatabasePath(rootPath); - QDir d; // TODO change this by static methods (utils class?? with delTree for example) - QString dbVersion; - if (d.exists(path) && d.exists(databasePath) && (dbVersion = DataBaseManagement::checkValidDB(databasePath)) != "") // si existe en disco la biblioteca seleccionada, y es válida.. - { - // this folde was added in 9.16, it needs to exist before the user starts importing custom covers for folders - d.mkdir(customFolderCoversPath); - - int comparation = DataBaseManagement::compareVersions(dbVersion, DB_VERSION); - - if (comparation < 0) { - // a database that fails validation would block the upgrade backup and - // trap the user in the update-needed/upgrade-failed dialog cycle; - // offer recovery instead of the upgrade question - if (!DataBaseManagement::isLibraryDatabaseValid(rootPath)) { - contentViewsManager->comicsView->setModel(NULL); - foldersView->setModel(NULL); - listsView->setModel(NULL); - actions.disableAllActions(); - actions.renameLibraryAction->setEnabled(true); - actions.removeLibraryAction->setEnabled(true); - actions.restoreLibraryAction->setEnabled(true); - offerDatabaseRecovery(name); - return; - } - int ret = QMessageBox::question(this, tr("Update needed"), tr("This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now?"), QMessageBox::Yes, QMessageBox::No); - if (ret == QMessageBox::Yes) { - importWidget->setUpgradeLook(); - showImportingWidget(); - - upgradeLibraryFuture = std::async(std::launch::async, [this, name, path, rootPath] { - bool updated = DataBaseManagement::updateToCurrentVersion(rootPath); - - if (!updated) - emit errorUpgradingLibrary(path); - - emit libraryUpgraded(name); - }); - - return; - } else { - contentViewsManager->comicsView->setModel(NULL); - foldersView->setModel(NULL); - listsView->setModel(NULL); - actions.disableAllActions(); // TODO comprobar que se deben deshabilitar - // será possible renombrar y borrar estas bibliotecas - actions.renameLibraryAction->setEnabled(true); - actions.removeLibraryAction->setEnabled(true); - actions.restoreLibraryAction->setEnabled(true); - } - } - - if (comparation == 0) // en caso de que la versión se igual que la actual - { - foldersModel->setupModelData(path); - foldersModelProxy->setSourceModel(foldersModel); - foldersView->setModel(foldersModelProxy); - foldersView->setCurrentIndex(QModelIndex()); // why is this necesary?? by default it seems that returns an arbitrary index. - - listsModel->setupReadingListsData(path); - listsModelProxy->setSourceModel(listsModel); - listsView->setModel(listsModelProxy); - - if (foldersModel->rowCount(QModelIndex()) > 0) - actions.disableFoldersActions(false); - else - actions.disableFoldersActions(true); - - d.setCurrent(libraries.getPath(name)); - d.setFilter(QDir::AllDirs | QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot); - if (d.count() <= 1) // read only library - { - actions.disableLibrariesActions(false); - actions.updateLibraryAction->setDisabled(true); - actions.repairLibraryAction->setDisabled(true); - actions.openContainingFolderAction->setDisabled(true); - actions.rescanLibraryForXMLInfoAction->setDisabled(true); - - disableComicsActions(true); -#ifndef Q_OS_MACOS - actions.toggleFullScreenAction->setEnabled(true); -#endif - - importedCovers = true; - } else // librería normal abierta - { - actions.disableLibrariesActions(false); - importedCovers = false; - } - - setRootIndex(); - - clearSearchInput(true); - } else if (comparation > 0) { - int ret = QMessageBox::question(this, tr("Download new version"), tr("This library was created with a newer version of YACReaderLibrary. Download the new version now?"), QMessageBox::Yes, QMessageBox::No); - if (ret == QMessageBox::Yes) - QDesktopServices::openUrl(QUrl("http://www.yacreader.com")); - - contentViewsManager->comicsView->setModel(NULL); - foldersView->setModel(NULL); - listsView->setModel(NULL); - actions.disableAllActions(); // TODO comprobar que se deben deshabilitar - // será possible renombrar y borrar estas bibliotecas - actions.renameLibraryAction->setEnabled(true); - actions.removeLibraryAction->setEnabled(true); - actions.restoreLibraryAction->setEnabled(true); - } - } else { - contentViewsManager->comicsView->setModel(NULL); - foldersView->setModel(NULL); - listsView->setModel(NULL); - actions.disableAllActions(); // TODO comprobar que se deben deshabilitar - - // si la librería no existe en disco, se ofrece al usuario la posibiliad de eliminarla - if (!d.exists(path)) { - QString currentLibrary = selectedLibrary->currentText() + " -> " + libraries.getPath(name); - if (QMessageBox::question(this, tr("Library not available"), tr("Library '%1' is no longer available. Do you want to remove it?").arg(currentLibrary), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) { - deleteCurrentLibrary(); - } - // será possible renombrar y borrar estas bibliotecas - actions.renameLibraryAction->setEnabled(true); - actions.removeLibraryAction->setEnabled(true); - actions.restoreLibraryAction->setEnabled(true); - - } else // si existe el path, puede ser que la librería sea alguna versión pre-5.0 ó que esté corrupta o que no haya drivers sql - { - - if (d.exists(path + "/library.ydb")) { - QSqlDatabase db = DataBaseManagement::loadDatabase(path); - manageOpeningLibraryError(db.lastError().databaseText() + "-" + db.lastError().driverText()); - // será possible renombrar y borrar estas bibliotecas - actions.renameLibraryAction->setEnabled(true); - actions.removeLibraryAction->setEnabled(true); - actions.restoreLibraryAction->setEnabled(true); - } else { - QString currentLibrary = selectedLibrary->currentText(); - QString path = libraries.getPath(selectedLibrary->currentText()); - if (QMessageBox::question(this, tr("Old library"), tr("Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now?").arg(currentLibrary), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) { - createLibraryDialog->setDataAndStart(currentLibrary, path); - } - // será possible renombrar y borrar estas bibliotecas - actions.renameLibraryAction->setEnabled(true); - actions.removeLibraryAction->setEnabled(true); - actions.restoreLibraryAction->setEnabled(true); - } - } - } - } else // en caso de que no exista ninguna biblioteca se desactivan los botones pertinentes - { - actions.disableAllActions(); - showNoLibrariesWidget(); - } -} - -void LibraryWindow::loadCoversFromCurrentModel() -{ - contentViewsManager->comicsView->setModel(comicsModel); -} - -void LibraryWindow::copyAndImportComicsToCurrentFolder(const QList> &comics) -{ - QLOG_DEBUG() << "-copyAndImportComicsToCurrentFolder-"; - if (comics.size() > 0) { - QString destFolderPath = currentFolderPath(); - - QModelIndex folderDestination = getCurrentFolderIndex(); - - QProgressDialog *progressDialog = newProgressDialog(tr("Copying comics..."), comics.size()); - - auto comicFilesManager = new ComicFilesManager(); - comicFilesManager->copyComicsTo(comics, destFolderPath, folderDestination); - - processComicFiles(comicFilesManager, progressDialog); - } -} - -void LibraryWindow::moveAndImportComicsToCurrentFolder(const QList> &comics) -{ - QLOG_DEBUG() << "-moveAndImportComicsToCurrentFolder-"; - if (comics.size() > 0) { - QString destFolderPath = currentFolderPath(); - - QModelIndex folderDestination = getCurrentFolderIndex(); - - QProgressDialog *progressDialog = newProgressDialog(tr("Moving comics..."), comics.size()); - - auto comicFilesManager = new ComicFilesManager(); - comicFilesManager->moveComicsTo(comics, destFolderPath, folderDestination); - - processComicFiles(comicFilesManager, progressDialog); - } -} - -void LibraryWindow::copyAndImportComicsToFolder(const QList> &comics, const QModelIndex &miFolder) -{ - QLOG_DEBUG() << "-copyAndImportComicsToFolder-"; - if (comics.size() > 0) { - QModelIndex folderDestination = foldersModelProxy->mapToSource(miFolder); - - QString destFolderPath = QDir::cleanPath(currentPath() + foldersModel->getFolderPath(folderDestination)); - - QLOG_DEBUG() << "Coping to " << destFolderPath; - - QProgressDialog *progressDialog = newProgressDialog(tr("Copying comics..."), comics.size()); - - auto comicFilesManager = new ComicFilesManager(); - comicFilesManager->copyComicsTo(comics, destFolderPath, folderDestination); - - processComicFiles(comicFilesManager, progressDialog); - } -} - -void LibraryWindow::moveAndImportComicsToFolder(const QList> &comics, const QModelIndex &miFolder) +void LibraryWindow::applyLoadedLibrary(const QString &libraryDataPath, bool readOnly) { - QLOG_DEBUG() << "-moveAndImportComicsToFolder-"; - if (comics.size() > 0) { - QModelIndex folderDestination = foldersModelProxy->mapToSource(miFolder); - - QString destFolderPath = QDir::cleanPath(currentPath() + foldersModel->getFolderPath(folderDestination)); + foldersModel->setupModelData(libraryDataPath); + foldersModelProxy->setSourceModel(foldersModel); + foldersView->setModel(foldersModelProxy); + foldersView->setCurrentIndex(QModelIndex()); // By default this can return an arbitrary index. - QLOG_DEBUG() << "Moving to " << destFolderPath; + listsModel->setupReadingListsData(libraryDataPath); + listsModelProxy->setSourceModel(listsModel); + listsView->setModel(listsModelProxy); - QProgressDialog *progressDialog = newProgressDialog(tr("Moving comics..."), comics.size()); + actions.disableFoldersActions(foldersModel->rowCount(QModelIndex()) == 0); + actions.disableLibrariesActions(false); - auto comicFilesManager = new ComicFilesManager(); - comicFilesManager->moveComicsTo(comics, destFolderPath, folderDestination); + if (readOnly) { + actions.updateLibraryAction->setDisabled(true); + actions.repairLibraryAction->setDisabled(true); + actions.openContainingFolderAction->setDisabled(true); + actions.rescanLibraryForXMLInfoAction->setDisabled(true); - processComicFiles(comicFilesManager, progressDialog); + setComicActionsDisabled(true); +#ifndef Q_OS_MACOS + actions.toggleFullScreenAction->setEnabled(true); +#endif } -} - -void LibraryWindow::processComicFiles(ComicFilesManager *comicFilesManager, QProgressDialog *progressDialog) -{ - connect(comicFilesManager, &ComicFilesManager::progress, progressDialog, &QProgressDialog::setValue); - - QThread *thread = NULL; - - thread = new QThread(); - - comicFilesManager->moveToThread(thread); - - connect(progressDialog, &QProgressDialog::canceled, comicFilesManager, &ComicFilesManager::cancel, Qt::DirectConnection); - - connect(thread, &QThread::started, comicFilesManager, &ComicFilesManager::process); - connect(comicFilesManager, &ComicFilesManager::success, this, &LibraryWindow::updateCopyMoveFolderDestination); - connect(comicFilesManager, &ComicFilesManager::finished, thread, &QThread::quit); - connect(comicFilesManager, &ComicFilesManager::finished, comicFilesManager, &QObject::deleteLater); - connect(comicFilesManager, &ComicFilesManager::finished, progressDialog, &QWidget::close); - connect(comicFilesManager, &ComicFilesManager::finished, progressDialog, &QObject::deleteLater); - connect(thread, &QThread::finished, thread, &QObject::deleteLater); - - if (thread != NULL) - thread->start(); -} - -void LibraryWindow::updateCopyMoveFolderDestination(const QModelIndex &mi) -{ - updateFolder(mi); -} + importedCovers = readOnly; -void LibraryWindow::updateCurrentFolder() -{ - updateFolder(getCurrentFolderIndex()); + setRootIndex(); + clearSearchInput(true); } -void LibraryWindow::updateFolder(const QModelIndex &miFolder) +void LibraryWindow::showLibraryManagementOnly() { - QLOG_DEBUG() << "UPDATE FOLDER!!!!"; - - importWidget->setUpdateLook(); - showImportingWidget(); - - QString currentLibrary = selectedLibrary->currentText(); - QString path = QDir::cleanPath(libraries.getPath(currentLibrary)); - _lastAdded = currentLibrary; - libraryCreator->updateFolder(path, LibraryPaths::libraryDataPath(path), QDir::cleanPath(currentPath() + foldersModel->getFolderPath(miFolder)), miFolder.data(FolderModel::IdRole).toULongLong()); - libraryCreator->start(); + contentViewsManager->comicsView->setModel(nullptr); + foldersView->setModel(nullptr); + listsView->setModel(nullptr); + actions.disableAllActions(); + actions.renameLibraryAction->setEnabled(true); + actions.removeLibraryAction->setEnabled(true); + actions.restoreLibraryAction->setEnabled(true); } -QProgressDialog *LibraryWindow::newProgressDialog(const QString &label, int maxValue) +void LibraryWindow::loadCoversFromCurrentModel() { - QProgressDialog *progressDialog = new QProgressDialog(label, "Cancel", 0, maxValue, this); - progressDialog->setWindowModality(Qt::WindowModal); - progressDialog->setMinimumWidth(350); - progressDialog->show(); - return progressDialog; + contentViewsManager->comicsView->setModel(comicsModel); } void LibraryWindow::reloadCurrentFolderComicsContent() { - navigationController->loadFolderInfo(getCurrentFolderIndex()); + navigationController->loadFolderContent(getCurrentFolderIndex()); enableNeededActions(); } @@ -1344,7 +984,7 @@ void LibraryWindow::reloadAfterCopyMove(const QModelIndex &mi) foldersModel->reload(mi); } - contentViewsManager->updateCurrentContentView(); + navigationController->refreshCurrentSource(); } enableNeededActions(); @@ -1367,548 +1007,54 @@ void LibraryWindow::enableNeededActions() actions.disableFoldersActions(false); if (comicsModel->rowCount() > 0) - disableComicsActions(false); + setComicActionsDisabled(false); actions.disableLibrariesActions(false); } -void LibraryWindow::disableComicsActions(bool disabled) +void LibraryWindow::setComicActionsDisabled(bool disabled) { if (!disabled && librariesUpdateCoordinator->isRunning()) { - disableComicsActions(true); + setComicActionsDisabled(true); return; } - actions.disableComicsActions(disabled); + actions.setComicActionsDisabled(disabled); + setComicToolbarEntriesVisible(comicsModel != nullptr && comicsModel->rowCount() > 0); } -void LibraryWindow::addFolderToCurrentIndex() +void LibraryWindow::setComicToolbarEntriesVisible(bool visible) { - exitSearchMode(); // Creating a folder in search mode is broken => exit it. - - QModelIndex currentIndex = getCurrentFolderIndex(); - - bool ok; - QString newFolderName = QInputDialog::getText(this, tr("Add new folder"), - tr("Folder name:"), QLineEdit::Normal, - "", &ok); - - // chars not supported in a folder's name: / \ : * ? " < > | - QRegularExpression invalidChars("\\/\\:\\*\\?\\\"\\<\\>\\|\\\\"); // TODO this regexp is not properly written - bool isValid = !newFolderName.contains(invalidChars); - - if (ok && !newFolderName.isEmpty() && isValid) { - QString parentPath = QDir::cleanPath(currentPath() + foldersModel->getFolderPath(currentIndex)); - QDir parentDir(parentPath); - QDir newFolder(parentPath + "/" + newFolderName); - if (parentDir.mkdir(newFolderName) || newFolder.exists()) { - QModelIndex newIndex = foldersModel->addFolderAtParent(newFolderName, currentIndex); - foldersView->setCurrentIndex(foldersModelProxy->mapFromSource(newIndex)); - navigationController->loadFolderInfo(newIndex); - historyController->updateHistory(YACReaderLibrarySourceContainer(newIndex, YACReaderLibrarySourceContainer::Folder)); - // a new folder is always an empty folder - contentViewsManager->showFolderContentView(); - } - } -} + if (editInfoToolBar == nullptr || comicToolbarEndAnchor == nullptr) + return; -void LibraryWindow::deleteSelectedFolder() -{ - QModelIndex currentIndex = getCurrentFolderIndex(); - QString relativePath = foldersModel->getFolderPath(currentIndex); - QString folderPath = QDir::cleanPath(currentPath() + relativePath); - - if (!currentIndex.isValid()) - QMessageBox::information(this, tr("No folder selected"), tr("Please, select a folder first")); - else { - QString libraryPath = QDir::cleanPath(currentPath()); - if ((libraryPath == folderPath) || relativePath.isEmpty() || relativePath == "/") - QMessageBox::critical(this, tr("Error in path"), tr("There was an error accessing the folder's path")); - else { - int ret = QMessageBox::question(this, tr("Delete folder"), tr("The selected folder and all its contents will be deleted from your disk. Are you sure?") + "\n\nFolder : " + folderPath, QMessageBox::Yes, QMessageBox::No); - - if (ret == QMessageBox::Yes) { - // no folders multiselection by now - QModelIndexList indexList; - indexList << currentIndex; - - QList paths; - paths << folderPath; - - auto remover = new FoldersRemover(indexList, paths); - const auto thread = new QThread(this); - moveAndConnectRemoverToThread(remover, thread); - - connect(remover, &FoldersRemover::remove, foldersModel, &FolderModel::deleteFolder); - connect(remover, &FoldersRemover::removeError, this, &LibraryWindow::errorDeletingFolder); - connect(remover, &FoldersRemover::finished, navigationController, &YACReaderNavigationController::reselectCurrentFolder); - - thread->start(); - } - } + const auto currentActions = editInfoToolBar->actions(); + for (auto *action : std::as_const(comicToolbarEntries)) { + if (visible && !currentActions.contains(action)) + editInfoToolBar->insertAction(comicToolbarEndAnchor, action); + else if (!visible && currentActions.contains(action)) + editInfoToolBar->removeAction(action); } } -void LibraryWindow::errorDeletingFolder() +void LibraryWindow::setToolbarTitle(const QModelIndex &modelIndex) { - QMessageBox::critical(this, tr("Unable to delete"), tr("There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files.")); +#ifndef Y_MAC_UI + if (!modelIndex.isValid()) + libraryToolBar->setCurrentFolderName(selectedLibrary->currentText()); + else + libraryToolBar->setCurrentFolderName(modelIndex.data().toString()); +#endif } -void LibraryWindow::addNewReadingList() -{ - QModelIndexList selectedLists = listsView->selectionModel()->selectedIndexes(); - QModelIndex sourceMI; - if (!selectedLists.isEmpty()) - sourceMI = listsModelProxy->mapToSource(selectedLists.at(0)); - - if (selectedLists.isEmpty() || !listsModel->isReadingSubList(sourceMI)) { - bool ok; - QString newListName = QInputDialog::getText(this, tr("Add new reading lists"), - tr("List name:"), QLineEdit::Normal, - "", &ok); - if (ok) { - if (selectedLists.isEmpty() || !listsModel->isReadingList(sourceMI)) - listsModel->addReadingList(newListName); // top level - else { - listsModel->addReadingListAt(newListName, sourceMI); // sublist - } - } - } -} - -void LibraryWindow::deleteSelectedReadingList() -{ - QModelIndexList selectedLists = listsView->selectionModel()->selectedIndexes(); - if (!selectedLists.isEmpty()) { - QModelIndex mi = listsModelProxy->mapToSource(selectedLists.at(0)); - if (listsModel->isEditable(mi)) { - int ret = QMessageBox::question(this, tr("Delete list/label"), tr("The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure?"), QMessageBox::Yes, QMessageBox::No); - if (ret == QMessageBox::Yes) { - listsModel->deleteItem(mi); - navigationController->reselectCurrentList(); - } - } - } -} - -void LibraryWindow::showAddNewLabelDialog() -{ - auto dialog = new AddLabelDialog(); - int ret = dialog->exec(); - - if (ret == QDialog::Accepted) { - YACReader::LabelColors color = dialog->selectedColor(); - QString name = dialog->name(); - - listsModel->addNewLabel(name, color); - } -} - -// TODO implement editors in treeview -void LibraryWindow::showRenameCurrentList() -{ - QModelIndexList selectedLists = listsView->selectionModel()->selectedIndexes(); - if (!selectedLists.isEmpty()) { - QModelIndex mi = listsModelProxy->mapToSource(selectedLists.at(0)); - if (listsModel->isEditable(mi)) { - bool ok; - QString newListName = QInputDialog::getText(this, tr("Rename list name"), - tr("List name:"), QLineEdit::Normal, - listsModel->name(mi), &ok); - - if (ok) - listsModel->rename(mi, newListName); - } - } -} - -void LibraryWindow::addSelectedComicsToFavorites() -{ - QModelIndexList indexList = getSelectedComics(); - comicsModel->addComicsToFavorites(indexList); -} - -void LibraryWindow::showComicsViewContextMenu(const QPoint &point) -{ - showComicsContextMenu(point, true); -} - -void LibraryWindow::showComicsItemContextMenu(const QPoint &point) -{ - showComicsContextMenu(point, false); -} - -void LibraryWindow::showComicsContextMenu(const QPoint &point, bool showFullScreenAction) -{ - auto selection = this->getSelectedComics(); - - auto setNormalAction = new QAction(); - setNormalAction->setText(tr("comic")); - - auto setMangaAction = new QAction(); - setMangaAction->setText(tr("manga")); - - auto setWesternMangaAction = new QAction(); - setWesternMangaAction->setText(tr("western manga (left to right)")); - - auto setWebComicAction = new QAction(); - setWebComicAction->setText(tr("web comic")); - - auto setYonkomaAction = new QAction(); - setYonkomaAction->setText(tr("4koma (top to botom)")); - - setNormalAction->setCheckable(true); - setMangaAction->setCheckable(true); - setWesternMangaAction->setCheckable(true); - setWebComicAction->setCheckable(true); - setYonkomaAction->setCheckable(true); - - connect(setNormalAction, &QAction::triggered, actions.setNormalAction, &QAction::trigger); - connect(setMangaAction, &QAction::triggered, actions.setMangaAction, &QAction::trigger); - connect(setWesternMangaAction, &QAction::triggered, actions.setWesternMangaAction, &QAction::trigger); - connect(setWebComicAction, &QAction::triggered, actions.setWebComicAction, &QAction::trigger); - connect(setYonkomaAction, &QAction::triggered, actions.setYonkomaAction, &QAction::trigger); - - auto setupActions = [=](FileType type) { - switch (type) { - case YACReader::FileType::Comic: - setNormalAction->setChecked(true); - break; - case YACReader::FileType::Manga: - setMangaAction->setChecked(true); - break; - case YACReader::FileType::WesternManga: - setWesternMangaAction->setChecked(true); - break; - case YACReader::FileType::WebComic: - setWebComicAction->setChecked(true); - break; - case YACReader::FileType::Yonkoma: - setYonkomaAction->setChecked(true); - break; - } - }; - - if (selection.size() == 1) { - QModelIndex index = selection.at(0); - auto type = index.data(ComicModel::TypeRole).value(); - setupActions(type); - } - - QMenu menu; - - menu.addAction(actions.openComicAction); - menu.addAction(actions.saveCoversToAction); - menu.addSeparator(); - menu.addAction(actions.openContainingFolderComicAction); - menu.addAction(actions.updateCurrentFolderAction); - menu.addSeparator(); - menu.addAction(actions.resetComicRatingAction); - menu.addSeparator(); - menu.addAction(actions.editSelectedComicsAction); - menu.addAction(actions.getInfoAction); - menu.addAction(actions.asignOrderAction); - menu.addSeparator(); - menu.addAction(actions.selectAllComicsAction); - menu.addSeparator(); - menu.addAction(actions.setAsReadAction); - menu.addAction(actions.setAsNonReadAction); - menu.addSeparator(); - auto typeMenu = new QMenu(tr("Set type")); - menu.addMenu(typeMenu); - typeMenu->addAction(setNormalAction); - typeMenu->addAction(setMangaAction); - typeMenu->addAction(setWesternMangaAction); - typeMenu->addAction(setWebComicAction); - typeMenu->addAction(setYonkomaAction); - menu.addSeparator(); - menu.addAction(actions.deleteMetadataAction); - menu.addSeparator(); - menu.addAction(actions.deleteComicsAction); - menu.addSeparator(); - menu.addAction(actions.addToMenuAction); - QMenu subMenu; - setupAddToSubmenu(subMenu); - -#ifndef Q_OS_MACOS - if (showFullScreenAction) { - menu.addSeparator(); - menu.addAction(actions.toggleFullScreenAction); - } -#endif - - menu.exec(contentViewsManager->comicsView->mapToGlobal(point)); -} - -void LibraryWindow::showGridFoldersContextMenu(QPoint point, Folder folder) -{ - QMenu menu; - - const auto &menuIcons = theme.menuIcons; - - auto openContainingFolderAction = new QAction(); - openContainingFolderAction->setText(tr("Open folder...")); - openContainingFolderAction->setIcon(menuIcons.openContainingFolderIcon); - - auto updateFolderAction = new QAction(tr("Update folder"), this); - updateFolderAction->setIcon(menuIcons.updateCurrentFolderIcon); - - auto rescanLibraryForXMLInfoAction = new QAction(tr("Rescan library for XML info"), this); - - auto setFolderAsNotCompletedAction = new QAction(); - setFolderAsNotCompletedAction->setText(tr("Set as uncompleted")); - - auto setFolderAsCompletedAction = new QAction(); - setFolderAsCompletedAction->setText(tr("Set as completed")); - - auto setFolderAsReadAction = new QAction(); - setFolderAsReadAction->setText(tr("Set as read")); - - auto setFolderAsUnreadAction = new QAction(); - setFolderAsUnreadAction->setText(tr("Set as unread")); - - auto setFolderAsMangaAction = new QAction(); - setFolderAsMangaAction->setText(tr("manga")); - - auto setFolderAsNormalAction = new QAction(); - setFolderAsNormalAction->setText(tr("comic")); - - auto setFolderAsWesternMangaAction = new QAction(); - setFolderAsWesternMangaAction->setText(tr("western manga (left to right)")); - - auto setFolderAsWebComicAction = new QAction(); - setFolderAsWebComicAction->setText(tr("web comic")); - - auto setFolderAs4KomaAction = new QAction(); - setFolderAs4KomaAction->setText(tr("4koma (top to botom)")); - - auto setFolderCoverAction = new QAction(); - setFolderCoverAction->setText(tr("Set custom cover")); - - auto deleteCustomFolderCoverAction = new QAction(); - deleteCustomFolderCoverAction->setText(tr("Delete custom cover")); - - menu.addAction(openContainingFolderAction); - menu.addAction(updateFolderAction); - menu.addSeparator(); - menu.addAction(rescanLibraryForXMLInfoAction); - menu.addSeparator(); - if (folder.completed) - menu.addAction(setFolderAsNotCompletedAction); - else - menu.addAction(setFolderAsCompletedAction); - menu.addSeparator(); - if (folder.finished) - menu.addAction(setFolderAsUnreadAction); - else - menu.addAction(setFolderAsReadAction); - menu.addSeparator(); - - setFolderAsNormalAction->setCheckable(true); - setFolderAsMangaAction->setCheckable(true); - setFolderAsWesternMangaAction->setCheckable(true); - setFolderAsWebComicAction->setCheckable(true); - setFolderAs4KomaAction->setCheckable(true); - - switch (folder.type) { - case FileType::Comic: - setFolderAsNormalAction->setChecked(true); - break; - case FileType::Manga: - setFolderAsMangaAction->setChecked(true); - break; - case FileType::WesternManga: - setFolderAsWesternMangaAction->setChecked(true); - break; - case FileType::WebComic: - setFolderAsWebComicAction->setChecked(true); - break; - case FileType::Yonkoma: - setFolderAs4KomaAction->setChecked(true); - break; - } - - auto typeMenu = new QMenu(tr("Set type")); - menu.addMenu(typeMenu); - typeMenu->addAction(setFolderAsNormalAction); - typeMenu->addAction(setFolderAsMangaAction); - typeMenu->addAction(setFolderAsWesternMangaAction); - typeMenu->addAction(setFolderAsWebComicAction); - typeMenu->addAction(setFolderAs4KomaAction); - - auto subfolderModel = contentViewsManager->folderContentView->currentFolderModel(); - - connect(openContainingFolderAction, &QAction::triggered, this, [=]() { - QDesktopServices::openUrl(QUrl("file:///" + QDir::cleanPath(currentPath() + "/" + folder.path), QUrl::TolerantMode)); - }); - connect(updateFolderAction, &QAction::triggered, this, [=]() { - updateFolder(foldersModel->getIndexFromFolder(folder)); - }); - connect(rescanLibraryForXMLInfoAction, &QAction::triggered, this, [=]() { - rescanFolderForXMLInfo(foldersModel->getIndexFromFolder(folder)); - }); - connect(setFolderAsNotCompletedAction, &QAction::triggered, this, [=]() { - foldersModel->updateFolderCompletedStatus(QModelIndexList() << foldersModel->getIndexFromFolder(folder), false); - subfolderModel->updateFolderCompletedStatus(QModelIndexList() << subfolderModel->getIndexFromFolder(folder), false); - }); - connect(setFolderAsCompletedAction, &QAction::triggered, this, [=]() { - foldersModel->updateFolderCompletedStatus(QModelIndexList() << foldersModel->getIndexFromFolder(folder), true); - subfolderModel->updateFolderCompletedStatus(QModelIndexList() << subfolderModel->getIndexFromFolder(folder), true); - }); - connect(setFolderAsReadAction, &QAction::triggered, this, [=]() { - foldersModel->updateFolderFinishedStatus(QModelIndexList() << foldersModel->getIndexFromFolder(folder), true); - subfolderModel->updateFolderFinishedStatus(QModelIndexList() << subfolderModel->getIndexFromFolder(folder), true); - }); - connect(setFolderAsUnreadAction, &QAction::triggered, this, [=]() { - foldersModel->updateFolderFinishedStatus(QModelIndexList() << foldersModel->getIndexFromFolder(folder), false); - subfolderModel->updateFolderFinishedStatus(QModelIndexList() << subfolderModel->getIndexFromFolder(folder), false); - }); - connect(setFolderAsMangaAction, &QAction::triggered, this, [=]() { - foldersModel->updateFolderType(QModelIndexList() << foldersModel->getIndexFromFolder(folder), FileType::Manga); - subfolderModel->updateFolderType(QModelIndexList() << foldersModel->getIndexFromFolder(folder), FileType::Manga); - }); - connect(setFolderAsNormalAction, &QAction::triggered, this, [=]() { - foldersModel->updateFolderType(QModelIndexList() << foldersModel->getIndexFromFolder(folder), FileType::Comic); - subfolderModel->updateFolderType(QModelIndexList() << foldersModel->getIndexFromFolder(folder), FileType::Comic); - }); - connect(setFolderAsWesternMangaAction, &QAction::triggered, this, [=]() { - foldersModel->updateFolderType(QModelIndexList() << foldersModel->getIndexFromFolder(folder), FileType::WesternManga); - subfolderModel->updateFolderType(QModelIndexList() << foldersModel->getIndexFromFolder(folder), FileType::WesternManga); - }); - connect(setFolderAsWebComicAction, &QAction::triggered, this, [=]() { - foldersModel->updateFolderType(QModelIndexList() << foldersModel->getIndexFromFolder(folder), FileType::WebComic); - subfolderModel->updateFolderType(QModelIndexList() << foldersModel->getIndexFromFolder(folder), FileType::WebComic); - }); - connect(setFolderAs4KomaAction, &QAction::triggered, this, [=]() { - foldersModel->updateFolderType(QModelIndexList() << foldersModel->getIndexFromFolder(folder), FileType::Yonkoma); - subfolderModel->updateFolderType(QModelIndexList() << foldersModel->getIndexFromFolder(folder), FileType::Yonkoma); - }); - connect(setFolderCoverAction, &QAction::triggered, this, [=]() { - setCustomFolderCover(folder); - }); - - connect(deleteCustomFolderCoverAction, &QAction::triggered, this, [=]() { - resetFolderCover(folder); - }); - - menu.addSeparator(); - - menu.addAction(setFolderCoverAction); - if (!folder.customImage.isEmpty()) { - menu.addAction(deleteCustomFolderCoverAction); - } - - menu.exec(contentViewsManager->folderContentView->mapToGlobal(point)); -} - -void LibraryWindow::showContinueReadingContextMenu(QPoint point, ComicDB comic) -{ - QMenu menu; - - auto setAsUnReadAction = new QAction(); - setAsUnReadAction->setText(tr("Set as unread")); - setAsUnReadAction->setIcon(theme.comicsViewToolbar.setAsUnreadIcon); - - menu.addAction(setAsUnReadAction); - - connect(setAsUnReadAction, &QAction::triggered, this, [=]() { - auto libraryId = libraries.getId(selectedLibrary->currentText()); - auto info = comic.info; - info.setRead(false); - info.currentPage = 1; - info.hasBeenOpened = false; - info.lastTimeOpened = QVariant(); - DBHelper::update(libraryId, info); - - contentViewsManager->folderContentView->reloadContinueReadingModel(); - }); - - menu.exec(contentViewsManager->folderContentView->mapToGlobal(point)); -} - -void LibraryWindow::setupAddToSubmenu(QMenu &menu) -{ - menu.addAction(actions.addToFavoritesAction); - actions.addToMenuAction->setMenu(&menu); - - const QList labels = listsModel->getLabels(); - if (labels.count() > 0) - menu.addSeparator(); - for (auto *label : labels) { - auto action = new QAction(this); - action->setIcon(label->getIcon()); - action->setText(label->name()); - - action->setData(label->getId()); - - menu.addAction(action); - - connect(action, &QAction::triggered, this, &LibraryWindow::onAddComicsToLabel); - } -} - -void LibraryWindow::onAddComicsToLabel() -{ - auto action = static_cast(sender()); - - qulonglong labelId = action->data().toULongLong(); - - QModelIndexList comics = getSelectedComics(); - - comicsModel->addComicsToLabel(comics, labelId); -} - -void LibraryWindow::setToolbarTitle(const QModelIndex &modelIndex) -{ -#ifndef Y_MAC_UI - if (!modelIndex.isValid()) - libraryToolBar->setCurrentFolderName(selectedLibrary->currentText()); - else - libraryToolBar->setCurrentFolderName(modelIndex.data().toString()); -#endif -} - -void LibraryWindow::saveSelectedCoversTo() -{ - QFileDialog saveDialog; - QString folderPath = saveDialog.getExistingDirectory(this, tr("Save covers"), QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)); - if (!folderPath.isEmpty()) { - const auto comics = getSelectedComics(); - for (const auto &comic : comics) { - QString origin = comic.data(ComicModel::CoverPathRole).toString().remove("file:///").remove("file:"); - QString destination = QDir(folderPath).filePath(comic.data(ComicModel::FileNameRole).toString() + ".jpg"); - - QLOG_DEBUG() << "From : " << origin; - QLOG_DEBUG() << "To : " << destination; - - QFile::copy(origin, destination); - } - } -} - -void LibraryWindow::checkMaxNumLibraries() -{ - int numLibraries = libraries.getNames().length(); - if (numLibraries >= MAX_LIBRARIES_WARNING_NUM) { - QMessageBox::warning(this, tr("You are adding too many libraries."), tr("You are adding too many libraries.\n\nYou probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar.\n\nYACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low.")); - } -} - -void LibraryWindow::selectSubfolder(const QModelIndex &mi, int child) -{ - QModelIndex dest = foldersModel->index(child, 0, mi); - foldersView->setCurrentIndex(dest); - navigationController->selectedFolder(dest); -} - -// this methods is only using after deleting comics -// TODO broken window :) -void LibraryWindow::checkEmptyFolder() +// this methods is only using after deleting comics +// TODO broken window :) +void LibraryWindow::checkEmptyFolder() { if (comicsModel->rowCount() > 0 && !importedCovers) { - disableComicsActions(false); + setComicActionsDisabled(false); } else { - disableComicsActions(true); + setComicActionsDisabled(true); #ifndef Q_OS_MACOS if (comicsModel->rowCount() > 0) actions.toggleFullScreenAction->setEnabled(true); @@ -1918,565 +1064,47 @@ void LibraryWindow::checkEmptyFolder() } } -void LibraryWindow::openComic() -{ - if (!importedCovers) { - - auto comic = comicsModel->getComic(contentViewsManager->comicsView->currentIndex()); - auto mode = comicsModel->getMode(); - - openComic(comic, mode); - } -} - -void LibraryWindow::openComic(const ComicDB &comic, const ComicModel::Mode mode) -{ - auto libraryId = libraries.getId(selectedLibrary->currentText()); - - OpenComicSource::Source source; - - if (mode == ComicModel::ReadingList) { - source = OpenComicSource::Source::ReadingList; - } else if (mode == ComicModel::Reading) { - // TODO check where the comic was opened from the last time it was read - source = OpenComicSource::Source::Folder; - } else { - source = OpenComicSource::Source::Folder; - } - - auto thirdPartyReaderCommand = settings->value(THIRD_PARTY_READER_COMMAND, "").toString(); - if (thirdPartyReaderCommand.isEmpty()) { - auto yacreaderFound = YACReader::openComic(comic, libraryId, currentPath(), OpenComicSource { source, comicsModel->getSourceId() }); - - if (!yacreaderFound) { -#ifdef Q_OS_WIN - QMessageBox::critical(this, tr("YACReader not found"), tr("YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary.")); -#else - QMessageBox::critical(this, tr("YACReader not found"), tr("YACReader not found. There might be a problem with your YACReader installation.")); -#endif - } - } else { - auto exec = YACReader::openComicInThirdPartyApp(thirdPartyReaderCommand, QDir::cleanPath(currentPath() + comic.path)); - - if (!exec) { - QMessageBox::critical(this, tr("Error"), tr("Error opening comic with third party reader.")); - } - } -} - -void LibraryWindow::setCurrentComicsStatusReaded(YACReaderComicReadStatus readStatus) -{ - comicsModel->setComicsRead(getSelectedComics(), readStatus); - contentViewsManager->updateCurrentComicView(); -} - -void LibraryWindow::setCurrentComicReaded() -{ - this->setCurrentComicsStatusReaded(YACReader::Read); -} - -void LibraryWindow::setCurrentComicUnreaded() -{ - this->setCurrentComicsStatusReaded(YACReader::Unread); -} - -void LibraryWindow::setSelectedComicsType(FileType type) -{ - comicsModel->setComicsType(getSelectedComics(), type); -} - -void LibraryWindow::createLibrary() -{ - checkMaxNumLibraries(); - createLibraryDialog->open(libraries); -} - -void LibraryWindow::create(QString source, QString dest, QString name) -{ - QLOG_INFO() << QString("About to create a library from '%1' to '%2' with name '%3'").arg(source, dest, name); - libraryCreator->createLibrary(source, dest); - libraryCreator->start(); - _lastAdded = name; - _sourceLastAdded = source; - - importWidget->setImportLook(); - showImportingWidget(); -} - void LibraryWindow::reloadCurrentLibrary() { if (!hasLoadedLibraryModels()) return; foldersModel->reload(); - contentViewsManager->updateCurrentContentView(); + navigationController->refreshCurrentSource(); enableNeededActions(); } -void LibraryWindow::openLastCreated() -{ - - selectedLibrary->disconnect(); - - selectedLibrary->setCurrentIndex(selectedLibrary->findText(_lastAdded)); - libraries.addLibrary(_lastAdded, _sourceLastAdded); - selectedLibrary->addItem(_lastAdded, _sourceLastAdded); - selectedLibrary->setCurrentIndex(selectedLibrary->findText(_lastAdded)); - libraries.save(); - - connect(selectedLibrary, &YACReaderLibraryListWidget::currentIndexChanged, this, &LibraryWindow::loadLibrary); - - loadLibrary(_lastAdded); -} - -void LibraryWindow::showAddLibrary() -{ - checkMaxNumLibraries(); - addLibraryDialog->open(); -} - -void LibraryWindow::openLibrary(QString path, QString name) -{ - if (!libraries.contains(name)) { - // TODO: fix bug, /a/b/c/.yacreaderlibrary/d/e - path.remove("/.yacreaderlibrary"); - QDir d; // TODO change this by static methods (utils class?? with delTree for example) - auto libraryDataPath = LibraryPaths::libraryDataPath(path); - if (d.exists(libraryDataPath)) { - _lastAdded = name; - _sourceLastAdded = path; - openLastCreated(); - addLibraryDialog->close(); - } else - QMessageBox::warning(this, tr("Library not found"), tr("The selected folder doesn't contain any library.")); - } else { - libraryAlreadyExists(name); - } -} - void LibraryWindow::loadLibraries() { - libraries.load(); - const auto libraryNames = libraries.getNames(); - for (const auto &name : libraryNames) - selectedLibrary->addItem(name, libraries.getPath(name)); -} - -void LibraryWindow::saveLibraries() -{ - libraries.save(); + const auto storedLibraries = libraryManagementCoordinator->loadLibraries(); + for (const auto &[name, path] : storedLibraries) + selectedLibrary->addItem(name, path); } -void LibraryWindow::updateLibrary() +void LibraryWindow::addLibraryToSelector(const QString &libraryName, const QString &libraryPath) { - importWidget->setUpdateLook(); - showImportingWidget(); - - QString currentLibrary = selectedLibrary->currentText(); - QString path = libraries.getPath(currentLibrary); - _lastAdded = currentLibrary; - libraryCreator->updateLibrary(path, LibraryPaths::libraryDataPath(path)); - libraryCreator->start(); + const QSignalBlocker blocker(selectedLibrary); + selectedLibrary->addItem(libraryName, libraryPath); + selectedLibrary->setCurrentIndex(selectedLibrary->findText(libraryName)); + addLibraryDialog->close(); + libraryManagementCoordinator->loadLibrary(libraryName); } -void LibraryWindow::backupLibrary() +void LibraryWindow::handleLibraryRemoved(const QString &libraryName, bool librariesEmpty) { - const auto path = libraries.getPath(selectedLibrary->currentText()); - if (path.isEmpty()) - return; + const auto index = selectedLibrary->findText(libraryName); + if (index >= 0) + selectedLibrary->removeItem(index); - auto version = DataBaseManagement::checkValidDB(LibraryPaths::libraryDatabasePath(path)); - if (version.isEmpty()) - version = "unknown"; - const auto suggestedName = QString("library-%1-db-%2-manual.ydb") - .arg(QDateTime::currentDateTime().toString("yyyyMMdd-HHmmss"), version); - const auto destination = QFileDialog::getSaveFileName(this, - actions.backupLibraryAction->text(), - QDir::home().filePath(suggestedName), - tr("YACReader library database (*.ydb)")); - if (destination.isEmpty()) + if (!librariesEmpty) return; - struct BackupResult { - bool success { false }; - QString error; - }; - - auto result = std::make_shared(); - auto worker = QThread::create([path, destination, result] { - result->success = DataBaseManagement::backupLibrary(path, DatabaseBackupReason::Manual, &result->error, destination); - }); - - actions.backupLibraryAction->setDisabled(true); - connect(worker, &QThread::finished, this, [this, destination, result] { - actions.backupLibraryAction->setDisabled(false); - if (result->success) { - QMessageBox::information(this, - actions.backupLibraryAction->text(), - tr("The library database backup was created at:\n%1").arg(destination)); - } else { - QMessageBox::critical(this, - actions.backupLibraryAction->text(), - tr("Unable to create the library database backup:\n%1").arg(result->error)); - } - }); - connect(worker, &QThread::finished, worker, &QObject::deleteLater); - worker->start(); -} - -void LibraryWindow::restoreLibrary() -{ - const auto libraryPath = libraries.getPath(selectedLibrary->currentText()); - if (libraryPath.isEmpty()) - return; - - const auto backupPath = QFileDialog::getOpenFileName(this, - actions.restoreLibraryAction->text(), - QDir(LibraryPaths::libraryDataPath(libraryPath)).filePath("backups"), - tr("YACReader library database (*.ydb)")); - if (backupPath.isEmpty()) - return; - - const auto answer = QMessageBox::warning(this, - actions.restoreLibraryAction->text(), - tr("Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue?"), - QMessageBox::Yes | QMessageBox::Cancel, - QMessageBox::Cancel); - if (answer == QMessageBox::Yes) - startLibraryRestore(backupPath); -} - -void LibraryWindow::startLibraryRestore(const QString &backupPath, bool allowInvalidCurrent, bool removeStaleLock) -{ - const auto libraryName = selectedLibrary->currentText(); - const auto libraryPath = libraries.getPath(libraryName); - auto result = std::make_shared(); - auto progress = new QProgressDialog(tr("Restoring library database..."), QString(), 0, 0, this); - progress->setCancelButton(nullptr); - progress->setWindowModality(Qt::WindowModal); - progress->setMinimumDuration(0); - contentViewsManager->comicsView->setModel(nullptr); foldersView->setModel(nullptr); listsView->setModel(nullptr); actions.disableAllActions(); - - auto worker = QThread::create([libraryPath, backupPath, allowInvalidCurrent, removeStaleLock, result] { - *result = DataBaseManagement::restoreLibrary(libraryPath, backupPath, allowInvalidCurrent, removeStaleLock); - }); - connect(worker, &QThread::finished, this, [this, libraryName, backupPath, allowInvalidCurrent, result, progress] { - progress->deleteLater(); - - if (result->status == DatabaseRestoreStatus::InvalidCurrentDatabase && !allowInvalidCurrent) { - const auto answer = QMessageBox::warning(this, - actions.restoreLibraryAction->text(), - tr("The current library database is invalid. Restore the selected backup anyway?"), - QMessageBox::Yes | QMessageBox::Cancel, - QMessageBox::Cancel); - if (answer == QMessageBox::Yes) { - startLibraryRestore(backupPath, true); - return; - } - actions.renameLibraryAction->setEnabled(true); - actions.removeLibraryAction->setEnabled(true); - actions.restoreLibraryAction->setEnabled(true); - return; - } else if (result->status == DatabaseRestoreStatus::LockFailed && !result->lockHolderIsRunningLocally) { - const auto answer = QMessageBox::warning(this, - actions.restoreLibraryAction->text(), - tr("The library maintenance lock may be stale. Remove it and retry?"), - QMessageBox::Yes | QMessageBox::Cancel, - QMessageBox::Cancel); - if (answer == QMessageBox::Yes) { - startLibraryRestore(backupPath, allowInvalidCurrent, true); - return; - } - loadLibrary(libraryName); - return; - } - - if (!result->success()) { - auto error = result->error; - if (result->status == DatabaseRestoreStatus::RollbackFailed) - error += tr("\n\nRestart YACReaderLibrary before attempting recovery again."); - QMessageBox::critical(this, actions.restoreLibraryAction->text(), error); - if (result->status != DatabaseRestoreStatus::RollbackFailed) { - loadLibrary(libraryName); - } else { - actions.restoreLibraryAction->setEnabled(true); - actions.removeLibraryAction->setEnabled(true); - } - return; - } - - loadLibrary(libraryName); - const auto answer = QMessageBox::question(this, - actions.restoreLibraryAction->text(), - tr("The library database was restored successfully. Update the library now?"), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::Yes); - if (answer == QMessageBox::Yes) - updateLibrary(); - }); - connect(worker, &QThread::finished, worker, &QObject::deleteLater); - worker->start(); -} - -void LibraryWindow::offerDatabaseRecovery(const QString &libraryName) -{ - QMessageBox messageBox(QMessageBox::Warning, - tr("Library database damaged"), - tr("The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed.").arg(libraryName), - QMessageBox::NoButton, - this); - const auto repairButton = messageBox.addButton(tr("Attempt repair"), QMessageBox::AcceptRole); - const auto restoreButton = messageBox.addButton(tr("Restore a backup..."), QMessageBox::ActionRole); - messageBox.addButton(QMessageBox::Cancel); - messageBox.setWindowModality(Qt::WindowModal); - messageBox.exec(); - - if (messageBox.clickedButton() == repairButton) - startDatabaseSalvage(libraryName); - else if (messageBox.clickedButton() == restoreButton) - restoreLibrary(); -} - -void LibraryWindow::startDatabaseSalvage(const QString &libraryName, bool removeStaleLock) -{ - const auto libraryPath = libraries.getPath(libraryName); - if (libraryPath.isEmpty()) - return; - - auto result = std::make_shared(); - auto progress = new QProgressDialog(tr("Repairing library database..."), QString(), 0, 0, this); - progress->setCancelButton(nullptr); - progress->setWindowModality(Qt::WindowModal); - progress->setMinimumDuration(0); - - auto worker = QThread::create([libraryPath, removeStaleLock, result] { - *result = DataBaseManagement::salvageLibrary(libraryPath, removeStaleLock); - }); - connect(worker, &QThread::finished, this, [this, libraryName, result, progress] { - progress->deleteLater(); - - if (result->status == DatabaseSalvageStatus::LockFailed) { - if (!result->lockHolderIsRunningLocally) { - const auto answer = QMessageBox::warning(this, - tr("Library database repair"), - tr("The library maintenance lock may be stale. Remove it and retry?"), - QMessageBox::Yes | QMessageBox::Cancel, - QMessageBox::Cancel); - if (answer == QMessageBox::Yes) - startDatabaseSalvage(libraryName, true); - } else { - QMessageBox::warning(this, - tr("Library database repair"), - tr("Another maintenance operation is currently using this library. Try again after it finishes.")); - } - return; - } - - if (result->success()) { - loadLibrary(libraryName); - if (result->status == DatabaseSalvageStatus::AlreadyValid) { - QMessageBox::information(this, - tr("Library database repair"), - tr("The library database is already valid.")); - } else if (result->status == DatabaseSalvageStatus::Reindexed) { - QMessageBox::information(this, - tr("Library database repaired"), - tr("The library database was repaired by rebuilding its indexes. The damaged original was preserved at:\n%1").arg(result->preservedDatabasePath)); - } else { - const auto answer = QMessageBox::question(this, - tr("Library database rebuilt"), - tr("The library database was rebuilt successfully. The damaged original was preserved at:\n%1\n\nUpdate the library now?").arg(result->preservedDatabasePath), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::Yes); - if (answer == QMessageBox::Yes) - updateLibrary(); - } - } else { - auto recovery = result->preservedDatabasePath.isEmpty() - ? QString() - : tr("\n\nThe damaged original was preserved at:\n%1").arg(result->preservedDatabasePath); - QMessageBox::critical(this, - tr("Library database repair failed"), - tr("The library database could not be repaired:\n%1%2\n\nYou can restore a backup from the Library menu or recreate the library.").arg(result->error, recovery)); - actions.restoreLibraryAction->setEnabled(true); - } - }); - connect(worker, &QThread::finished, worker, &QObject::deleteLater); - worker->start(); -} - -void LibraryWindow::repairLibrary() -{ - startLibraryRepair(false); -} - -void LibraryWindow::startLibraryRepair(bool removeStaleLock) -{ - importWidget->setRepairLook(); - showImportingWidget(); - - const auto path = libraries.getPath(selectedLibrary->currentText()); - comicInfoRepairer->repairLibrary(path, LibraryPaths::libraryDataPath(path), removeStaleLock); -} - -void LibraryWindow::deleteCurrentLibrary() -{ - QString path = libraries.getPath(selectedLibrary->currentText()); - libraries.remove(selectedLibrary->currentText()); - selectedLibrary->removeItem(selectedLibrary->currentIndex()); - path = LibraryPaths::libraryDataPath(path); - - QDir d(path); - d.removeRecursively(); - if (libraries.isEmpty()) // no more libraries available. - { - contentViewsManager->comicsView->setModel(NULL); - foldersView->setModel(NULL); - listsView->setModel(NULL); - - actions.disableAllActions(); - showNoLibrariesWidget(); - } - libraries.save(); -} - -void LibraryWindow::removeLibrary() -{ - QString currentLibrary = selectedLibrary->currentText(); - QMessageBox *messageBox = new QMessageBox(QMessageBox::Question, - tr("Are you sure?"), - tr("Do you want remove ") + currentLibrary + tr(" library?"), - QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No, - this); - messageBox->button(QMessageBox::YesToAll)->setText(tr("Remove and delete metadata and backups")); - messageBox->setWindowModality(Qt::WindowModal); - int ret = messageBox->exec(); - if (ret == QMessageBox::Yes) { - libraries.remove(currentLibrary); - selectedLibrary->removeItem(selectedLibrary->currentIndex()); - // selectedLibrary->setCurrentIndex(0); - if (libraries.isEmpty()) // no more libraries available. - { - contentViewsManager->comicsView->setModel(NULL); - foldersView->setModel(NULL); - listsView->setModel(NULL); - - actions.disableAllActions(); - showNoLibrariesWidget(); - } - libraries.save(); - } else if (ret == QMessageBox::YesToAll) { - deleteCurrentLibrary(); - } -} - -void LibraryWindow::renameLibrary() -{ - renameLibraryDialog->open(); -} - -void LibraryWindow::rename(QString newName) // TODO replace -{ - QString currentLibrary = selectedLibrary->currentText(); - if (newName != currentLibrary) { - if (!libraries.contains(newName)) { - libraries.rename(currentLibrary, newName); - // selectedLibrary->removeItem(selectedLibrary->currentIndex()); - // libraries.addLibrary(newName,path); - selectedLibrary->renameCurrentLibrary(newName); - libraries.save(); - renameLibraryDialog->close(); -#ifndef Y_MAC_UI - if (!foldersModelProxy->mapToSource(foldersView->currentIndex()).isValid()) - libraryToolBar->setCurrentFolderName(selectedLibrary->currentText()); -#endif - } else { - libraryAlreadyExists(newName); - } - } else - renameLibraryDialog->close(); - // selectedLibrary->setCurrentIndex(selectedLibrary->findText(newName)); -} - -void LibraryWindow::rescanLibraryForXMLInfo() -{ - importWidget->setXMLScanLook(); - showImportingWidget(); - - QString currentLibrary = selectedLibrary->currentText(); - QString path = libraries.getPath(currentLibrary); - _lastAdded = currentLibrary; - - xmlInfoLibraryScanner->scanLibrary(path, LibraryPaths::libraryDataPath(path)); -} - -void LibraryWindow::showLibraryInfo() -{ - auto id = libraries.getUuid(selectedLibrary->currentText()); - auto info = DBHelper::getLibraryInfo(id); - - // TODO: use something nicer than a QMessageBox - QMessageBox msgBox; - msgBox.setWindowTitle(tr("Library info")); - msgBox.setText(info); - QSpacerItem *horizontalSpacer = new QSpacerItem(420, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); - QGridLayout *layout = (QGridLayout *)msgBox.layout(); - layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount()); - msgBox.setStandardButtons(QMessageBox::Close); - msgBox.setDefaultButton(QMessageBox::Close); - msgBox.exec(); -} - -void LibraryWindow::openLibraryFolder() -{ - const auto path = libraries.getPath(selectedLibrary->currentText()); - if (!path.isEmpty()) - QDesktopServices::openUrl(QUrl::fromLocalFile(QDir::cleanPath(path))); -} - -void LibraryWindow::rescanCurrentFolderForXMLInfo() -{ - rescanFolderForXMLInfo(getCurrentFolderIndex()); -} - -void LibraryWindow::rescanFolderForXMLInfo(QModelIndex modelIndex) -{ - importWidget->setXMLScanLook(); - showImportingWidget(); - - QString currentLibrary = selectedLibrary->currentText(); - QString path = libraries.getPath(currentLibrary); - _lastAdded = currentLibrary; - - xmlInfoLibraryScanner->scanFolder(path, LibraryPaths::libraryDataPath(path), QDir::cleanPath(currentPath() + foldersModel->getFolderPath(modelIndex)), modelIndex); -} - -void LibraryWindow::cancelCreating() -{ - stopLibraryCreator(); -} - -void LibraryWindow::stopLibraryCreator() -{ - libraryCreator->stop(); - libraryCreator->wait(); -} - -void LibraryWindow::stopXMLScanning() -{ - xmlInfoLibraryScanner->stop(); - xmlInfoLibraryScanner->wait(); -} - -void LibraryWindow::stopComicInfoRepair() -{ - comicInfoRepairer->stop(); - comicInfoRepairer->wait(); + showNoLibrariesWidget(); } void LibraryWindow::setRootIndex() @@ -2536,277 +1164,6 @@ void LibraryWindow::toNormal() #endif } -void LibraryWindow::setSearchFilter(QString filter) -{ - if (!filter.isEmpty()) { - folderQueryResultProcessor->createModelData(filter); - comicQueryResultProcessor.createModelData(filter, foldersModel->getDatabase()); - } else if (status == LibraryWindow::Searching) { // if no searching, then ignore this - clearSearchFilter(); - navigationController->loadPreviousStatus(); - } -} - -void LibraryWindow::setComicSearchFilterData(QList *data, const QString &databasePath) -{ - status = LibraryWindow::Searching; - - comicsModel->setModelData(data, databasePath); - contentViewsManager->comicsView->enableFilterMode(true); - contentViewsManager->comicsView->setModel(comicsModel); // TODO, columns are messed up after ResetModel some times, this shouldn't be necesary - - if (comicsModel->rowCount() == 0) { - contentViewsManager->showNoSearchResultsView(); - disableComicsActions(true); - } else { - contentViewsManager->showComicsView(); - disableComicsActions(false); - } -} - -void LibraryWindow::setFolderSearchFilterData(QMap *filteredItems, FolderItem *root) -{ - foldersModelProxy->setFilterData(filteredItems, root); - foldersView->expandAll(); -} - -void LibraryWindow::clearSearchFilter() -{ - foldersModelProxy->clear(); - contentViewsManager->comicsView->enableFilterMode(false); - foldersView->collapseAll(); - status = LibraryWindow::Normal; -} - -void LibraryWindow::showProperties() -{ - QModelIndexList indexList = getSelectedComics(); - - QList comics = comicsModel->getComics(indexList); - ComicDB c = comics[0]; - _comicIdEdited = c.id; // static_cast(indexList[0].internalPointer())->data(4).toULongLong(); - - propertiesDialog->databasePath = foldersModel->getDatabase(); - propertiesDialog->basePath = currentPath(); - - if (indexList.length() > 1) { // edit common properties - propertiesDialog->setComics(comics); - } else { - auto allComics = comicsModel->getAllComics(); - int index = allComics.indexOf(c); - propertiesDialog->setComicsForSequentialEditing(index, comicsModel->getAllComics()); - } - - propertiesDialog->show(); -} - -void LibraryWindow::showComicVineScraper() -{ - QSettings s(YACReader::getSettingsPath() + "/YACReaderLibrary.ini", QSettings::IniFormat); // TODO unificar la creación del fichero de config con el servidor - s.beginGroup("ComicVine"); - - if (!s.contains(COMIC_VINE_API_KEY)) { - ApiKeyDialog d; - d.exec(); - } - - // check if the api key was inserted - if (s.contains(COMIC_VINE_API_KEY)) { - QModelIndexList indexList = getSelectedComics(); - - const auto comics = comicsModel->getComics(indexList); - ComicDB c = comics[0]; - _comicIdEdited = c.id; // static_cast(indexList[0].internalPointer())->data(4).toULongLong(); - - comicVineDialog->databasePath = foldersModel->getDatabase(); - comicVineDialog->basePath = currentPath(); - comicVineDialog->setComics(comics); - - comicVineDialog->show(); - } -} - -void LibraryWindow::setRemoveError() -{ - removeError = true; -} - -void LibraryWindow::checkRemoveError() -{ - if (removeError) { - QMessageBox::critical(this, tr("Unable to delete"), tr("There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder.")); - } - removeError = false; -} - -void LibraryWindow::resetComicRating() -{ - QModelIndexList indexList = getSelectedComics(); - - comicsModel->startTransaction(); - for (auto &index : indexList) { - comicsModel->resetComicRating(index); - } - comicsModel->finishTransaction(); -} - -void LibraryWindow::checkSearchNumResults(int numResults) -{ - if (numResults == 0) - contentViewsManager->showNoSearchResultsView(); - else - contentViewsManager->showComicsView(); -} - -void LibraryWindow::asignNumbers() -{ - QModelIndexList indexList = getSelectedComics(); - - int startingNumber = indexList[0].row() + 1; - if (indexList.count() > 1) { - bool ok; - int n = QInputDialog::getInt(this, tr("Assign comics numbers"), - tr("Assign numbers starting in:"), startingNumber, 0, 2147483647, 1, &ok); - if (ok) - startingNumber = n; - else - return; - } - qint64 edited = comicsModel->asignNumbers(indexList, startingNumber); - - // TODO add resorting without reloading - navigationController->loadFolderInfo(foldersModelProxy->mapToSource(foldersView->currentIndex())); - - const QModelIndex &mi = comicsModel->getIndexFromId(edited); - if (mi.isValid()) { - contentViewsManager->comicsView->scrollTo(mi, QAbstractItemView::PositionAtCenter); - contentViewsManager->comicsView->setCurrentIndex(mi); - } -} - -void LibraryWindow::openContainingFolderComic() -{ - QModelIndex modelIndex = contentViewsManager->comicsView->currentIndex(); - QFileInfo file(QDir::cleanPath(currentPath() + comicsModel->getComicPath(modelIndex))); -#if defined Q_OS_UNIX && !defined Q_OS_MACOS - QString path = file.absolutePath(); - QDesktopServices::openUrl(QUrl("file:///" + path, QUrl::TolerantMode)); -#endif - -#ifdef Q_OS_MACOS - // `open -R` reveals and selects the file in Finder without sending an Apple - // Event, so it doesn't trigger the macOS automation permission prompt. - QStringList args; - args << "-R"; - args << file.absoluteFilePath(); - QProcess::startDetached("open", args); -#endif - -#ifdef Q_OS_WIN - QString filePath = file.absoluteFilePath(); - QString cmdArgs = QString("/select,\"") + QDir::toNativeSeparators(filePath) + QStringLiteral("\""); - ShellExecuteW(0, L"open", L"explorer.exe", reinterpret_cast(cmdArgs.utf16()), 0, SW_NORMAL); -#endif -} - -void LibraryWindow::openContainingFolder() -{ - QModelIndex modelIndex = foldersModelProxy->mapToSource(foldersView->currentIndex()); - QString path; - if (modelIndex.isValid()) - path = QDir::cleanPath(currentPath() + foldersModel->getFolderPath(modelIndex)); - else - path = QDir::cleanPath(currentPath()); - QDesktopServices::openUrl(QUrl("file:///" + path, QUrl::TolerantMode)); -} - -void LibraryWindow::setFolderAsNotCompleted() -{ - // foldersModel->updateFolderCompletedStatus(foldersView->selectionModel()->selectedRows(),false); - foldersModel->updateFolderCompletedStatus(QModelIndexList() << foldersModelProxy->mapToSource(foldersView->currentIndex()), false); -} - -void LibraryWindow::setFolderAsCompleted() -{ - // foldersModel->updateFolderCompletedStatus(foldersView->selectionModel()->selectedRows(),true); - foldersModel->updateFolderCompletedStatus(QModelIndexList() << foldersModelProxy->mapToSource(foldersView->currentIndex()), true); -} - -void LibraryWindow::setFolderAsRead() -{ - // foldersModel->updateFolderFinishedStatus(foldersView->selectionModel()->selectedRows(),true); - foldersModel->updateFolderFinishedStatus(QModelIndexList() << foldersModelProxy->mapToSource(foldersView->currentIndex()), true); -} - -void LibraryWindow::setFolderAsUnread() -{ - // foldersModel->updateFolderFinishedStatus(foldersView->selectionModel()->selectedRows(),false); - foldersModel->updateFolderFinishedStatus(QModelIndexList() << foldersModelProxy->mapToSource(foldersView->currentIndex()), false); -} - -void LibraryWindow::setFolderType(FileType type) -{ - foldersModel->updateFolderType(QModelIndexList() << foldersModelProxy->mapToSource(foldersView->currentIndex()), type); -} - -void LibraryWindow::setFolderCover() -{ - auto folder = foldersModel->getFolder(foldersModelProxy->mapToSource(foldersView->currentIndex())); - setCustomFolderCover(folder); -} - -void LibraryWindow::setCustomFolderCover(Folder folder) -{ - auto customCoverPath = YACReader::imageFileLoader(this); - if (!customCoverPath.isEmpty()) { - QImage cover(customCoverPath); - if (cover.isNull()) { - QMessageBox::warning(this, tr("Invalid image"), tr("The selected file is not a valid image.")); - return; - } - - auto folderCoverPath = LibraryPaths::customFolderCoverPath(libraries.getPath(selectedLibrary->currentText()), QString::number(folder.id)); - if (!YACReader::saveCover(folderCoverPath, cover)) { - QMessageBox::warning(this, tr("Error saving cover"), tr("There was an error saving the cover image.")); - } - - QModelIndex folderIndex = foldersModel->getIndexFromFolder(folder); - auto coversPath = LibraryPaths::libraryCoversFolderPath(libraries.getPath(selectedLibrary->currentText())); - auto relativePath = folderCoverPath.remove(coversPath); - foldersModel->setCustomFolderCover(folderIndex, relativePath); - } -} - -void LibraryWindow::deleteCustomFolderCover() -{ - auto folder = foldersModel->getFolder(foldersModelProxy->mapToSource(foldersView->currentIndex())); - resetFolderCover(folder); -} - -void LibraryWindow::resetFolderCover(Folder folder) -{ - auto folderCoverPath = LibraryPaths::customFolderCoverPath(libraries.getPath(selectedLibrary->currentText()), QString::number(folder.id)); - if (QFile::exists(folderCoverPath)) { - QFile::remove(folderCoverPath); - } - QModelIndex folderIndex = foldersModel->getIndexFromFolder(folder); - foldersModel->resetFolderCover(folderIndex); -} - -void LibraryWindow::exportLibrary(QString destPath) -{ - QString currentLibrary = selectedLibrary->currentText(); - QString path = LibraryPaths::libraryDataPath(libraries.getPath(currentLibrary)); - packageManager->createPackage(path, destPath + "/" + currentLibrary); -} - -void LibraryWindow::importLibrary(QString clc, QString destPath, QString name) -{ - packageManager->extractPackage(clc, destPath + "/" + name); - _lastAdded = name; - _sourceLastAdded = destPath + "/" + name; -} - void LibraryWindow::reloadOptions() { contentViewsManager->comicsView->updateConfig(settings); @@ -2821,20 +1178,6 @@ QString LibraryWindow::currentPath() return libraries.getPath(selectedLibrary->currentText()); } -QString LibraryWindow::currentFolderPath() -{ - QString path; - - if (foldersView->selectionModel()->selectedRows().length() > 0) - path = foldersModel->getFolderPath(foldersModelProxy->mapToSource(foldersView->currentIndex())); - else - path = foldersModel->getFolderPath(QModelIndex()); - - QLOG_DEBUG() << "current folder path : " << QDir::cleanPath(currentPath() + path); - - return QDir::cleanPath(currentPath() + path); -} - void LibraryWindow::showExportComicsInfo() { exportComicsInfoDialog->source = LibraryPaths::libraryDatabasePath(currentPath()); @@ -2859,14 +1202,14 @@ void LibraryWindow::prepareToCloseApp() { httpServer->stop(); - libraryCreator->stop(); + libraryManagementCoordinator->stop(); librariesUpdateCoordinator->stop(); - stopComicInfoRepair(); + libraryRepairCoordinator->stop(); settings->setValue(MAIN_WINDOW_GEOMETRY, saveGeometry()); settings->setValue(MAIN_WINDOW_STATE, saveState()); - contentViewsManager->comicsView->close(); + contentViewsManager->prepareToClose(); sideBar->close(); QApplication::instance()->processEvents(); @@ -2906,21 +1249,6 @@ void LibraryWindow::showImportingWidget() mainWidget->setCurrentIndex(2); } -void LibraryWindow::manageCreatingError(const QString &error) -{ - QMessageBox::critical(this, tr("Error creating the library"), error); -} - -void LibraryWindow::manageUpdatingError(const QString &error) -{ - QMessageBox::critical(this, tr("Error updating the library"), error); -} - -void LibraryWindow::manageOpeningLibraryError(const QString &error) -{ - QMessageBox::critical(this, tr("Error opening the library"), error); -} - bool lessThanModelIndexRow(const QModelIndex &m1, const QModelIndex &m2) { return m1.row() < m2.row(); @@ -2941,184 +1269,11 @@ QModelIndexList LibraryWindow::getSelectedComics() return selection; } -void LibraryWindow::deleteMetadataFromSelectedComics() -{ - QModelIndexList indexList = getSelectedComics(); - QList comics = comicsModel->getComics(indexList); - - for (auto &comic : comics) { - comic.info.deleteMetadata(); - } - - DBHelper::updateComicsInfo(comics, foldersModel->getDatabase()); - - comicsModel->reload(); -} - -void LibraryWindow::deleteComics() -{ - // TODO - if (!listsView->selectionModel()->selectedRows().isEmpty()) { - deleteComicsFromList(); - } else { - deleteComicsFromDisk(); - } -} - -void LibraryWindow::deleteComicsFromDisk() -{ - int ret = QMessageBox::question(this, tr("Delete comics"), tr("All the selected comics will be deleted from your disk. Are you sure?"), QMessageBox::Yes, QMessageBox::No); - - if (ret == QMessageBox::Yes) { - - QModelIndexList indexList = getSelectedComics(); - - QList comics = comicsModel->getComics(indexList); - - QList paths; - QString libraryPath = currentPath(); - for (const auto &comic : comics) { - paths.append(libraryPath + comic.path); - QLOG_TRACE() << comic.path; - QLOG_TRACE() << comic.id; - QLOG_TRACE() << comic.parentId; - } - - auto remover = new ComicsRemover(indexList, paths, comics.at(0).parentId); - const auto thread = new QThread(this); - moveAndConnectRemoverToThread(remover, thread); - - comicsModel->startTransaction(); - - connect(remover, &ComicsRemover::remove, comicsModel, &ComicModel::remove); - connect(remover, &ComicsRemover::removeError, this, &LibraryWindow::setRemoveError); - connect(remover, &ComicsRemover::finished, comicsModel, &ComicModel::finishTransaction); - connect(remover, &ComicsRemover::removedItemsFromFolder, foldersModel, &FolderModel::updateFolderChildrenInfo); - - connect(remover, &ComicsRemover::finished, this, &LibraryWindow::checkEmptyFolder); - connect(remover, &ComicsRemover::finished, this, &LibraryWindow::checkRemoveError); - - thread->start(); - } -} - -void LibraryWindow::deleteComicsFromList() -{ - int ret = QMessageBox::question(this, tr("Remove comics"), tr("Comics will only be deleted from the current label/list. Are you sure?"), QMessageBox::Yes, QMessageBox::No); - - if (ret == QMessageBox::Yes) { - QModelIndexList indexList = getSelectedComics(); - if (indexList.isEmpty()) - return; - - QModelIndex mi = listsModelProxy->mapToSource(listsView->currentIndex()); - - ReadingListModel::TypeList typeList = (ReadingListModel::TypeList)mi.data(ReadingListModel::TypeListsRole).toInt(); - - qulonglong id = mi.data(ReadingListModel::IDRole).toULongLong(); - switch (typeList) { - case ReadingListModel::SpecialList: - comicsModel->deleteComicsFromSpecialList(indexList, id); - break; - case ReadingListModel::Label: - comicsModel->deleteComicsFromLabel(indexList, id); - break; - case ReadingListModel::ReadingList: - comicsModel->deleteComicsFromReadingList(indexList, id); - break; - case ReadingListModel::Separator: - break; - } - } -} - -void LibraryWindow::showFoldersContextMenu(const QPoint &point) -{ - QModelIndex sourceMI = foldersModelProxy->mapToSource(foldersView->indexAt(point)); - - if (!sourceMI.isValid()) - return; - - auto folder = foldersModel->getFolder(sourceMI); - - actions.setFolderAsNormalAction->setCheckable(true); - actions.setFolderAsMangaAction->setCheckable(true); - actions.setFolderAsWesternMangaAction->setCheckable(true); - actions.setFolderAsWebComicAction->setCheckable(true); - actions.setFolderAsYonkomaAction->setCheckable(true); - - actions.setFolderAsNormalAction->setChecked(false); - actions.setFolderAsMangaAction->setChecked(false); - actions.setFolderAsWesternMangaAction->setChecked(false); - actions.setFolderAsWebComicAction->setChecked(false); - actions.setFolderAsYonkomaAction->setChecked(false); - - switch (folder.type) { - case FileType::Comic: - actions.setFolderAsNormalAction->setChecked(true); - break; - case FileType::Manga: - actions.setFolderAsMangaAction->setChecked(true); - break; - case FileType::WesternManga: - actions.setFolderAsWesternMangaAction->setChecked(true); - break; - case FileType::WebComic: - actions.setFolderAsWebComicAction->setChecked(true); - break; - case FileType::Yonkoma: - actions.setFolderAsYonkomaAction->setChecked(true); - break; - } - - QMenu menu; - - menu.addAction(actions.openContainingFolderAction); - menu.addAction(actions.updateFolderAction); - menu.addSeparator(); //------------------------------- - menu.addAction(actions.rescanXMLFromCurrentFolderAction); - menu.addSeparator(); //------------------------------- - if (folder.completed) - menu.addAction(actions.setFolderAsNotCompletedAction); - else - menu.addAction(actions.setFolderAsCompletedAction); - menu.addSeparator(); //------------------------------- - if (folder.finished) - menu.addAction(actions.setFolderAsUnreadAction); - else - menu.addAction(actions.setFolderAsReadAction); - menu.addSeparator(); //------------------------------- - auto typeMenu = new QMenu(tr("Set type")); - menu.addMenu(typeMenu); - typeMenu->addAction(actions.setFolderAsNormalAction); - typeMenu->addAction(actions.setFolderAsMangaAction); - typeMenu->addAction(actions.setFolderAsWesternMangaAction); - typeMenu->addAction(actions.setFolderAsWebComicAction); - typeMenu->addAction(actions.setFolderAsYonkomaAction); - menu.addSeparator(); //------------------------------- - menu.addAction(actions.setFolderCoverAction); - if (!folder.customImage.isEmpty()) { - menu.addAction(actions.deleteCustomFolderCoverAction); - } - - menu.exec(foldersView->mapToGlobal(point)); -} - -void LibraryWindow::libraryAlreadyExists(const QString &name) -{ - QMessageBox::information(this, tr("Library name already exists"), tr("There is another library with the name '%1'.").arg(name)); -} - -void LibraryWindow::importLibraryPackage() -{ - importLibraryDialog->open(libraries); -} - void LibraryWindow::updateViewsOnClientSync() { comicsModel->reload(); contentViewsManager->updateCurrentComicView(); - contentViewsManager->updateContinueReadingView(); + navigationController->reloadRootContinueReading(); } void LibraryWindow::updateViewsOnComicUpdateWithId(quint64 libraryId, quint64 comicId) @@ -3149,15 +1304,6 @@ void LibraryWindow::updateViewsOnComicUpdate(quint64 libraryId, const ComicDB &c if (libraryId == (quint64)libraries.getId(selectedLibrary->currentText())) { comicsModel->reload(comic); contentViewsManager->updateCurrentComicView(); - contentViewsManager->updateContinueReadingView(); + navigationController->reloadRootContinueReading(); } } - -bool LibraryWindow::exitSearchMode() -{ - if (status != LibraryWindow::Searching) - return false; - clearSearchInput(false); - clearSearchFilter(); - return true; -} diff --git a/YACReaderLibrary/library_window.h b/YACReaderLibrary/library_window.h index c418d745d..5e92a50a5 100644 --- a/YACReaderLibrary/library_window.h +++ b/YACReaderLibrary/library_window.h @@ -3,9 +3,7 @@ #include "comic_db.h" #include "comic_model.h" -#include "comic_query_result_processor.h" #include "folder.h" -#include "folder_query_result_processor.h" #include "libraries_update_coordinator.h" #include "library_window_actions.h" #include "themable.h" @@ -13,14 +11,9 @@ #include "yacreader_libraries.h" #include "yacreader_navigation_controller.h" -#include #include -#include #include -#include -#include - #ifdef Y_MAC_UI #include "yacreader_macosx_toolbar.h" #endif @@ -40,12 +33,9 @@ class ImportLibraryDialog; class ExportComicsInfoDialog; class ImportComicsInfoDialog; class AddLibraryDialog; -class LibraryCreator; class HelpAboutDialog; class RenameLibraryDialog; class PropertiesDialog; -class PackageManager; -class QCheckBox; class QPushButton; class ComicModel; class QSplitter; @@ -74,8 +64,6 @@ class GridComicsView; class ComicsViewTransition; class NoSearchResultsWidget; class EditShortcutsDialog; -class ComicFilesManager; -class QProgressDialog; class ReadingListModel; class ReadingListModelProxy; class YACReaderReadingListsView; @@ -84,11 +72,19 @@ class EmptyLabelWidget; class EmptySpecialListWidget; class EmptyReadingListWidget; class RecentVisibilityCoordinator; +class OrganizeFilesCoordinator; +class QToolButton; +class ComicManagementCoordinator; +class ReadingListManagementCoordinator; +class FolderManagementCoordinator; +class LibraryDatabaseMaintenanceCoordinator; +class LibraryRepairCoordinator; +class LibraryManagementCoordinator; +class LibraryWindowMenus; +class LibrarySearchCoordinator; namespace YACReader { class TrayIconController; -class XMLInfoLibraryScanner; -class ComicInfoRepairer; } #include "comic_db.h" @@ -110,9 +106,6 @@ class LibraryWindow : public QMainWindow, protected Themable ExportComicsInfoDialog *exportComicsInfoDialog; ImportComicsInfoDialog *importComicsInfoDialog; AddLibraryDialog *addLibraryDialog; - LibraryCreator *libraryCreator; - XMLInfoLibraryScanner *xmlInfoLibraryScanner; - ComicInfoRepairer *comicInfoRepairer; HelpAboutDialog *had; RenameLibraryDialog *renameLibraryDialog; PropertiesDialog *propertiesDialog; @@ -122,8 +115,6 @@ class LibraryWindow : public QMainWindow, protected Themable bool importedCovers; // if true, the library is read only (not updates,open comic or properties) bool fromMaximized; - PackageManager *packageManager; - QSize slideSizeW; QSize slideSizeF; // search filter @@ -133,12 +124,9 @@ class LibraryWindow : public QMainWindow, protected Themable YACReaderSearchLineEdit *searchEdit; #endif - QString previousFilter; - QCheckBox *includeComicsCheckBox; - //------------- - YACReaderNavigationController *navigationController; YACReaderContentViewsManager *contentViewsManager; + LibraryWindowMenus *menus; YACReaderFoldersView *foldersView; YACReaderReadingListsView *listsView; @@ -156,10 +144,6 @@ class LibraryWindow : public QMainWindow, protected Themable NoLibrariesWidget *noLibrariesWidget; ImportWidget *importWidget; - bool fetching; - - int i; - LibraryWindowActions actions; #ifdef Y_MAC_UI @@ -170,29 +154,17 @@ class LibraryWindow : public QMainWindow, protected Themable QToolBar *treeActions; QToolBar *comicsToolBar; QToolBar *editInfoToolBar; + QToolButton *organizeToolButton = nullptr; + QToolButton *setTypeToolButton = nullptr; + QList comicToolbarEntries; + QAction *comicToolbarEndAnchor = nullptr; OptionsDialog *optionsDialog; ServerConfigDialog *serverConfigDialog; - QString libraryPath; - QString comicsPath; - - QString _lastAdded; - QString _sourceLastAdded; - - quint64 _comicIdEdited; - - enum NavigationStatus { - Normal, // - Searching - }; - - NavigationStatus status; - void createSettings(); void setupUI(); void createToolBars(); - void createMenus(); void createConnections(); void doLayout(); void doDialogs(); @@ -208,7 +180,6 @@ class LibraryWindow : public QMainWindow, protected Themable void showSearchSyntax(); QString currentPath(); - QString currentFolderPath(); // settings QSettings *settings; @@ -216,8 +187,6 @@ class LibraryWindow : public QMainWindow, protected Themable // navigation backward and forward YACReaderHistoryController *historyController; - bool removeError; - // QTBUG-41883 QSize _size; QPoint _pos; @@ -231,131 +200,32 @@ class LibraryWindow : public QMainWindow, protected Themable LibraryWindow(); QString searchText() const; -signals: - void libraryUpgraded(const QString &libraryName); - void errorUpgradingLibrary(const QString &path); public slots: - void loadLibrary(const QString &path); - void selectSubfolder(const QModelIndex &mi, int child); void checkEmptyFolder(); - void openComic(); - void openComic(const ComicDB &comic, const ComicModel::Mode mode); - void createLibrary(); - void create(QString source, QString dest, QString name); - void showAddLibrary(); - void openLibrary(QString path, QString name); void loadLibraries(); - void saveLibraries(); void reloadCurrentLibrary(); - void openLastCreated(); - void updateLibrary(); - void backupLibrary(); - void restoreLibrary(); - void startLibraryRestore(const QString &backupPath, bool allowInvalidCurrent = false, bool removeStaleLock = false); - void offerDatabaseRecovery(const QString &libraryName); - void startDatabaseSalvage(const QString &libraryName, bool removeStaleLock = false); - void repairLibrary(); - void startLibraryRepair(bool removeStaleLock); - // void deleteLibrary(); - void openContainingFolder(); - void setFolderAsNotCompleted(); - void setFolderAsCompleted(); - void setFolderAsRead(); - void setFolderAsUnread(); - void setFolderType(FileType type); - void setFolderCover(); - void setCustomFolderCover(Folder folder); - void deleteCustomFolderCover(); - void resetFolderCover(Folder folder); - void openContainingFolderComic(); - void deleteCurrentLibrary(); - void removeLibrary(); - void renameLibrary(); - void rescanLibraryForXMLInfo(); - void showLibraryInfo(); - void openLibraryFolder(); - void rescanCurrentFolderForXMLInfo(); - void rescanFolderForXMLInfo(QModelIndex modelIndex); - void rename(QString newName); - void cancelCreating(); - void stopLibraryCreator(); - void stopXMLScanning(); - void stopComicInfoRepair(); void setRootIndex(); void toggleFullScreen(); void toNormal(); void toFullScreen(); - void setSearchFilter(QString filter); - void setComicSearchFilterData(QList *, const QString &); - void setFolderSearchFilterData(QMap *filteredItems, FolderItem *root); - void clearSearchFilter(); - void showProperties(); - void exportLibrary(QString destPath); - void importLibrary(QString clc, QString destPath, QString name); void reloadOptions(); - void setCurrentComicsStatusReaded(YACReaderComicReadStatus readStatus); - void setCurrentComicReaded(); - void setCurrentComicUnreaded(); - void setSelectedComicsType(FileType type); void showExportComicsInfo(); void showImportComicsInfo(); - void asignNumbers(); void showNoLibrariesWidget(); void showRootWidget(); void showImportingWidget(); - void manageCreatingError(const QString &error); - void manageUpdatingError(const QString &error); - void manageOpeningLibraryError(const QString &error); QModelIndexList getSelectedComics(); - void deleteMetadataFromSelectedComics(); - void deleteComics(); - void deleteComicsFromDisk(); - void deleteComicsFromList(); - void showFoldersContextMenu(const QPoint &point); - void showGridFoldersContextMenu(QPoint point, Folder folder); - void showContinueReadingContextMenu(QPoint point, ComicDB comic); - void libraryAlreadyExists(const QString &name); - void importLibraryPackage(); void updateViewsOnClientSync(); void updateViewsOnComicUpdateWithId(quint64 libraryId, quint64 comicId); void updateViewsOnComicUpdate(quint64 libraryId, const ComicDB &comic); - void showComicVineScraper(); - void setRemoveError(); - void checkRemoveError(); - void resetComicRating(); - void checkSearchNumResults(int numResults); void loadCoversFromCurrentModel(); - void copyAndImportComicsToCurrentFolder(const QList> &comics); - void moveAndImportComicsToCurrentFolder(const QList> &comics); - void copyAndImportComicsToFolder(const QList> &comics, const QModelIndex &miFolder); - void moveAndImportComicsToFolder(const QList> &comics, const QModelIndex &miFolder); - void processComicFiles(ComicFilesManager *comicFilesManager, QProgressDialog *progressDialog); - void updateCopyMoveFolderDestination(const QModelIndex &mi); // imports new comics from the current folder - void updateCurrentFolder(); - void updateFolder(const QModelIndex &miFolder); - QProgressDialog *newProgressDialog(const QString &label, int maxValue); void reloadCurrentFolderComicsContent(); void reloadAfterCopyMove(const QModelIndex &mi); QModelIndex getCurrentFolderIndex(); void enableNeededActions(); - void disableComicsActions(bool disabled); - void addFolderToCurrentIndex(); - void deleteSelectedFolder(); - void errorDeletingFolder(); - void addNewReadingList(); - void deleteSelectedReadingList(); - void showAddNewLabelDialog(); - void showRenameCurrentList(); - void addSelectedComicsToFavorites(); - void showComicsViewContextMenu(const QPoint &point); - void showComicsItemContextMenu(const QPoint &point); - void showComicsContextMenu(const QPoint &point, bool showFullScreenAction); - void setupAddToSubmenu(QMenu &menu); - void onAddComicsToLabel(); + void setComicActionsDisabled(bool disabled); + void setComicToolbarEntriesVisible(bool visible); void setToolbarTitle(const QModelIndex &modelIndex); - void saveSelectedCoversTo(); - void checkMaxNumLibraries(); - void showErrorUpgradingLibrary(const QString &path); void setCurrentLibraryAs(FileType fileType); void prepareToCloseApp(); @@ -366,18 +236,24 @@ public slots: bool eventFilter(QObject *object, QEvent *event) override; private: - //! @brief Exits search mode if it is active. - //! @return true If the search mode was active when this function was called. - bool exitSearchMode(); bool startsHiddenInTray() const; - std::future upgradeLibraryFuture; + void applyLoadedLibrary(const QString &libraryDataPath, bool readOnly); + void showLibraryManagementOnly(); + void addLibraryToSelector(const QString &libraryName, const QString &libraryPath); + void handleLibraryRemoved(const QString &libraryName, bool librariesEmpty); TrayIconController *trayIconController; - ComicQueryResultProcessor comicQueryResultProcessor; - std::unique_ptr folderQueryResultProcessor; + LibrarySearchCoordinator *librarySearchCoordinator; RecentVisibilityCoordinator *recentVisibilityCoordinator; + OrganizeFilesCoordinator *organizeFilesCoordinator; + ComicManagementCoordinator *comicManagementCoordinator; + ReadingListManagementCoordinator *readingListManagementCoordinator; + FolderManagementCoordinator *folderManagementCoordinator; + LibraryDatabaseMaintenanceCoordinator *libraryDatabaseMaintenanceCoordinator; + LibraryRepairCoordinator *libraryRepairCoordinator; + LibraryManagementCoordinator *libraryManagementCoordinator; bool pendingAfterLaunchTasks; }; diff --git a/YACReaderLibrary/library_window_actions.cpp b/YACReaderLibrary/library_window_actions.cpp index d6b634d20..6925dc20d 100644 --- a/YACReaderLibrary/library_window_actions.cpp +++ b/YACReaderLibrary/library_window_actions.cpp @@ -1,16 +1,25 @@ #include "library_window_actions.h" +#include "comic_management_coordinator.h" #include "edit_shortcuts_dialog.h" -#include "export_library_dialog.h" +#include "feature_flags.h" +#include "folder_management_coordinator.h" #include "help_about_dialog.h" +#include "library_database_maintenance_coordinator.h" +#include "library_management_coordinator.h" +#include "library_repair_coordinator.h" #include "library_window.h" +#include "organize_files_coordinator.h" +#include "reading_list_management_coordinator.h" #include "recent_visibility_coordinator.h" +#include "rename_library_dialog.h" #include "server_config_dialog.h" #include "shortcuts_manager.h" #include "theme_manager.h" #include "yacreader_content_views_manager.h" #include "yacreader_folders_view.h" #include "yacreader_history_controller.h" +#include "yacreader_navigation_controller.h" #include "yacreader_options_dialog.h" #include @@ -185,6 +194,9 @@ void LibraryWindowActions::createActions(LibraryWindow *window, QSettings *setti addFolderAction->setShortcut(ShortcutsManager::getShortcutsManager().getShortcut(ADD_FOLDER_ACTION_YL)); addFolderAction->setToolTip(tr("Add new folder to the current library")); + renameFolderAction = new QAction(tr("Rename folder"), window); + renameFolderAction->setToolTip(tr("Rename the current folder on disk and in the library")); + deleteFolderAction = new QAction(tr("Delete folder"), window); deleteFolderAction->setData(REMOVE_FOLDER_ACTION_YL); deleteFolderAction->setShortcut(ShortcutsManager::getShortcutsManager().getShortcut(REMOVE_FOLDER_ACTION_YL)); @@ -228,6 +240,18 @@ void LibraryWindowActions::createActions(LibraryWindow *window, QSettings *setti openContainingFolderAction->setData(OPEN_CONTAINING_FOLDER_ACTION_YL); openContainingFolderAction->setShortcut(ShortcutsManager::getShortcutsManager().getShortcut(OPEN_CONTAINING_FOLDER_ACTION_YL)); + renameFilesAction = new QAction(window); + renameFilesAction->setText(tr("Rename files...")); + renameFilesAction->setVisible(YACReader::FeatureFlags::organizeFiles); + renameFilesAction->setData(RENAME_FILES_ACTION_YL); + renameFilesAction->setShortcut(ShortcutsManager::getShortcutsManager().getShortcut(RENAME_FILES_ACTION_YL)); + + organizeFilesAction = new QAction(window); + organizeFilesAction->setText(tr("Organize into folders...")); + organizeFilesAction->setVisible(YACReader::FeatureFlags::organizeFiles); + organizeFilesAction->setData(ORGANIZE_FILES_ACTION_YL); + organizeFilesAction->setShortcut(ShortcutsManager::getShortcutsManager().getShortcut(ORGANIZE_FILES_ACTION_YL)); + setFolderAsNotCompletedAction = new QAction(window); setFolderAsNotCompletedAction->setText(tr("Set as uncompleted")); setFolderAsNotCompletedAction->setData(SET_FOLDER_AS_NOT_COMPLETED_ACTION_YL); @@ -290,8 +314,20 @@ void LibraryWindowActions::createActions(LibraryWindow *window, QSettings *setti openContainingFolderComicAction->setData(OPEN_CONTAINING_FOLDER_COMIC_ACTION_YL); openContainingFolderComicAction->setShortcut(ShortcutsManager::getShortcutsManager().getShortcut(OPEN_CONTAINING_FOLDER_COMIC_ACTION_YL)); + renameComicsFilesAction = new QAction(window); + renameComicsFilesAction->setText(tr("Rename files...")); + renameComicsFilesAction->setVisible(YACReader::FeatureFlags::organizeFiles); + renameComicsFilesAction->setData(RENAME_COMICS_FILES_ACTION_YL); + renameComicsFilesAction->setShortcut(ShortcutsManager::getShortcutsManager().getShortcut(RENAME_COMICS_FILES_ACTION_YL)); + + organizeComicsFilesAction = new QAction(window); + organizeComicsFilesAction->setText(tr("Organize into folders...")); + organizeComicsFilesAction->setVisible(YACReader::FeatureFlags::organizeFiles); + organizeComicsFilesAction->setData(ORGANIZE_COMICS_FILES_ACTION_YL); + organizeComicsFilesAction->setShortcut(ShortcutsManager::getShortcutsManager().getShortcut(ORGANIZE_COMICS_FILES_ACTION_YL)); + resetComicRatingAction = new QAction(window); - resetComicRatingAction->setText(tr("Reset comic rating")); + resetComicRatingAction->setText(tr("Reset rating")); resetComicRatingAction->setData(RESET_COMIC_RATING_ACTION_YL); resetComicRatingAction->setShortcut(ShortcutsManager::getShortcutsManager().getShortcut(RESET_COMIC_RATING_ACTION_YL)); @@ -401,6 +437,10 @@ void LibraryWindowActions::createActions(LibraryWindow *window, QSettings *setti // actions not asigned to any widget window->addAction(saveCoversToAction); window->addAction(openContainingFolderAction); + if (YACReader::FeatureFlags::organizeFiles) { + window->addAction(renameFilesAction); + window->addAction(organizeFilesAction); + } window->addAction(updateCurrentFolderAction); window->addAction(resetComicRatingAction); window->addAction(setFolderAsCompletedAction); @@ -417,6 +457,10 @@ void LibraryWindowActions::createActions(LibraryWindow *window, QSettings *setti window->addAction(deleteMetadataAction); window->addAction(rescanXMLFromCurrentFolderAction); window->addAction(openContainingFolderComicAction); + if (YACReader::FeatureFlags::organizeFiles) { + window->addAction(renameComicsFilesAction); + window->addAction(organizeComicsFilesAction); + } #ifndef Q_OS_MACOS window->addAction(toggleFullScreenAction); #endif @@ -427,47 +471,53 @@ void LibraryWindowActions::createActions(LibraryWindow *window, QSettings *setti void LibraryWindowActions::createConnections( YACReaderHistoryController *historyController, + YACReaderNavigationController *navigationController, LibraryWindow *window, HelpAboutDialog *had, - ExportLibraryDialog *exportLibraryDialog, YACReaderContentViewsManager *contentViewsManager, EditShortcutsDialog *editShortcutsDialog, YACReaderFoldersView *foldersView, YACReaderOptionsDialog *optionsDialog, ServerConfigDialog *serverConfigDialog, - RecentVisibilityCoordinator *recentVisibilityCoordinator) + RecentVisibilityCoordinator *recentVisibilityCoordinator, + ComicManagementCoordinator *comicManagementCoordinator, + ReadingListManagementCoordinator *readingListManagementCoordinator, + FolderManagementCoordinator *folderManagementCoordinator, + OrganizeFilesCoordinator *organizeFilesCoordinator, + LibraryManagementCoordinator *libraryManagementCoordinator, + LibraryDatabaseMaintenanceCoordinator *libraryDatabaseMaintenanceCoordinator, + LibraryRepairCoordinator *libraryRepairCoordinator, + RenameLibraryDialog *renameLibraryDialog) { - // history navigation - QObject::connect(backAction, &QAction::triggered, historyController, &YACReaderHistoryController::backward); - QObject::connect(forwardAction, &QAction::triggered, historyController, &YACReaderHistoryController::forward); - //-- + QObject::connect(backAction, &QAction::triggered, navigationController, &YACReaderNavigationController::backward); + QObject::connect(forwardAction, &QAction::triggered, navigationController, &YACReaderNavigationController::forward); QObject::connect(historyController, &YACReaderHistoryController::enabledBackward, backAction, &QAction::setEnabled); QObject::connect(historyController, &YACReaderHistoryController::enabledForward, forwardAction, &QAction::setEnabled); // connect(foldersView, SIGNAL(clicked(QModelIndex)), historyController, SLOT(updateHistory(QModelIndex))); // actions - QObject::connect(createLibraryAction, &QAction::triggered, window, &LibraryWindow::createLibrary); - QObject::connect(exportLibraryAction, &QAction::triggered, exportLibraryDialog, &ExportLibraryDialog::open); - QObject::connect(importLibraryAction, &QAction::triggered, window, &LibraryWindow::importLibraryPackage); + QObject::connect(createLibraryAction, &QAction::triggered, libraryManagementCoordinator, &LibraryManagementCoordinator::showCreateLibraryDialog); + QObject::connect(exportLibraryAction, &QAction::triggered, libraryManagementCoordinator, &LibraryManagementCoordinator::showExportLibraryDialog); + QObject::connect(importLibraryAction, &QAction::triggered, libraryManagementCoordinator, &LibraryManagementCoordinator::showImportLibraryDialog); - QObject::connect(openLibraryAction, &QAction::triggered, window, &LibraryWindow::showAddLibrary); - QObject::connect(setAsReadAction, &QAction::triggered, window, &LibraryWindow::setCurrentComicReaded); - QObject::connect(setAsNonReadAction, &QAction::triggered, window, &LibraryWindow::setCurrentComicUnreaded); + QObject::connect(openLibraryAction, &QAction::triggered, libraryManagementCoordinator, &LibraryManagementCoordinator::showAddLibraryDialog); + QObject::connect(setAsReadAction, &QAction::triggered, comicManagementCoordinator, &ComicManagementCoordinator::setSelectedComicsRead); + QObject::connect(setAsNonReadAction, &QAction::triggered, comicManagementCoordinator, &ComicManagementCoordinator::setSelectedComicsUnread); QObject::connect(setNormalAction, &QAction::triggered, window, [=]() { - window->setSelectedComicsType(FileType::Comic); + comicManagementCoordinator->setSelectedComicsType(FileType::Comic); }); QObject::connect(setMangaAction, &QAction::triggered, window, [=]() { - window->setSelectedComicsType(FileType::Manga); + comicManagementCoordinator->setSelectedComicsType(FileType::Manga); }); QObject::connect(setWesternMangaAction, &QAction::triggered, window, [=]() { - window->setSelectedComicsType(FileType::WesternManga); + comicManagementCoordinator->setSelectedComicsType(FileType::WesternManga); }); QObject::connect(setWebComicAction, &QAction::triggered, window, [=]() { - window->setSelectedComicsType(FileType::WebComic); + comicManagementCoordinator->setSelectedComicsType(FileType::WebComic); }); QObject::connect(setYonkomaAction, &QAction::triggered, window, [=]() { - window->setSelectedComicsType(FileType::Yonkoma); + comicManagementCoordinator->setSelectedComicsType(FileType::Yonkoma); }); // comicsInfoManagement @@ -475,42 +525,58 @@ void LibraryWindowActions::createConnections( QObject::connect(importComicsInfoAction, &QAction::triggered, window, &LibraryWindow::showImportComicsInfo); // ContextMenus - QObject::connect(openContainingFolderComicAction, &QAction::triggered, window, &LibraryWindow::openContainingFolderComic); - QObject::connect(setFolderAsNotCompletedAction, &QAction::triggered, window, &LibraryWindow::setFolderAsNotCompleted); - QObject::connect(setFolderAsCompletedAction, &QAction::triggered, window, &LibraryWindow::setFolderAsCompleted); - QObject::connect(setFolderAsReadAction, &QAction::triggered, window, &LibraryWindow::setFolderAsRead); - QObject::connect(setFolderAsUnreadAction, &QAction::triggered, window, &LibraryWindow::setFolderAsUnread); - QObject::connect(openContainingFolderAction, &QAction::triggered, window, &LibraryWindow::openContainingFolder); - QObject::connect(setFolderCoverAction, &QAction::triggered, window, &LibraryWindow::setFolderCover); - QObject::connect(deleteCustomFolderCoverAction, &QAction::triggered, window, &LibraryWindow::deleteCustomFolderCover); + QObject::connect(openContainingFolderComicAction, &QAction::triggered, comicManagementCoordinator, &ComicManagementCoordinator::openContainingFolderOfCurrentComic); + if (YACReader::FeatureFlags::organizeFiles) { + QObject::connect(renameComicsFilesAction, &QAction::triggered, organizeFilesCoordinator, &OrganizeFilesCoordinator::renameSelectedComics); + QObject::connect(organizeComicsFilesAction, &QAction::triggered, organizeFilesCoordinator, &OrganizeFilesCoordinator::organizeSelectedComics); + } + QObject::connect(setFolderAsNotCompletedAction, &QAction::triggered, folderManagementCoordinator, [folderManagementCoordinator] { + folderManagementCoordinator->setCurrentFolderCompleted(false); + }); + QObject::connect(setFolderAsCompletedAction, &QAction::triggered, folderManagementCoordinator, [folderManagementCoordinator] { + folderManagementCoordinator->setCurrentFolderCompleted(true); + }); + QObject::connect(setFolderAsReadAction, &QAction::triggered, folderManagementCoordinator, [folderManagementCoordinator] { + folderManagementCoordinator->setCurrentFolderRead(true); + }); + QObject::connect(setFolderAsUnreadAction, &QAction::triggered, folderManagementCoordinator, [folderManagementCoordinator] { + folderManagementCoordinator->setCurrentFolderRead(false); + }); + QObject::connect(openContainingFolderAction, &QAction::triggered, folderManagementCoordinator, &FolderManagementCoordinator::openCurrentFolder); + if (YACReader::FeatureFlags::organizeFiles) { + QObject::connect(renameFilesAction, &QAction::triggered, organizeFilesCoordinator, &OrganizeFilesCoordinator::renameCurrentFolder); + QObject::connect(organizeFilesAction, &QAction::triggered, organizeFilesCoordinator, &OrganizeFilesCoordinator::organizeCurrentFolder); + } + QObject::connect(setFolderCoverAction, &QAction::triggered, folderManagementCoordinator, &FolderManagementCoordinator::selectAndSetCurrentFolderCover); + QObject::connect(deleteCustomFolderCoverAction, &QAction::triggered, folderManagementCoordinator, &FolderManagementCoordinator::resetCurrentFolderCover); QObject::connect(setFolderAsMangaAction, &QAction::triggered, window, [=]() { - window->setFolderType(FileType::Manga); + folderManagementCoordinator->setCurrentFolderType(FileType::Manga); }); QObject::connect(setFolderAsNormalAction, &QAction::triggered, window, [=]() { - window->setFolderType(FileType::Comic); + folderManagementCoordinator->setCurrentFolderType(FileType::Comic); }); QObject::connect(setFolderAsWesternMangaAction, &QAction::triggered, window, [=]() { - window->setFolderType(FileType::WesternManga); + folderManagementCoordinator->setCurrentFolderType(FileType::WesternManga); }); QObject::connect(setFolderAsWebComicAction, &QAction::triggered, window, [=]() { - window->setFolderType(FileType::WebComic); + folderManagementCoordinator->setCurrentFolderType(FileType::WebComic); }); QObject::connect(setFolderAsYonkomaAction, &QAction::triggered, window, [=]() { - window->setFolderType(FileType::Yonkoma); + folderManagementCoordinator->setCurrentFolderType(FileType::Yonkoma); }); - QObject::connect(resetComicRatingAction, &QAction::triggered, window, &LibraryWindow::resetComicRating); + QObject::connect(resetComicRatingAction, &QAction::triggered, comicManagementCoordinator, &ComicManagementCoordinator::resetSelectedComicRatings); // Comicts edition - QObject::connect(editSelectedComicsAction, &QAction::triggered, window, &LibraryWindow::showProperties); - QObject::connect(asignOrderAction, &QAction::triggered, window, &LibraryWindow::asignNumbers); + QObject::connect(editSelectedComicsAction, &QAction::triggered, comicManagementCoordinator, &ComicManagementCoordinator::showProperties); + QObject::connect(asignOrderAction, &QAction::triggered, comicManagementCoordinator, &ComicManagementCoordinator::assignNumbers); - QObject::connect(deleteMetadataAction, &QAction::triggered, window, &LibraryWindow::deleteMetadataFromSelectedComics); + QObject::connect(deleteMetadataAction, &QAction::triggered, comicManagementCoordinator, &ComicManagementCoordinator::deleteMetadataFromSelectedComics); - QObject::connect(deleteComicsAction, &QAction::triggered, window, &LibraryWindow::deleteComics); + QObject::connect(deleteComicsAction, &QAction::triggered, comicManagementCoordinator, &ComicManagementCoordinator::deleteSelectedComics); - QObject::connect(getInfoAction, &QAction::triggered, window, &LibraryWindow::showComicVineScraper); + QObject::connect(getInfoAction, &QAction::triggered, comicManagementCoordinator, &ComicManagementCoordinator::showComicVineScraper); QObject::connect(focusComicsViewAction, &QAction::triggered, contentViewsManager, &YACReaderContentViewsManager::focusComicsViewViaShortcut); @@ -519,32 +585,41 @@ void LibraryWindowActions::createConnections( QObject::connect(quitAction, &QAction::triggered, window, &LibraryWindow::closeApp); // update folders (partial updates) - QObject::connect(updateCurrentFolderAction, &QAction::triggered, window, &LibraryWindow::updateCurrentFolder); - QObject::connect(updateFolderAction, &QAction::triggered, window, &LibraryWindow::updateCurrentFolder); + QObject::connect(updateCurrentFolderAction, &QAction::triggered, libraryManagementCoordinator, &LibraryManagementCoordinator::updateCurrentFolder); + QObject::connect(updateFolderAction, &QAction::triggered, libraryManagementCoordinator, &LibraryManagementCoordinator::updateCurrentFolder); - QObject::connect(rescanXMLFromCurrentFolderAction, &QAction::triggered, window, &LibraryWindow::rescanCurrentFolderForXMLInfo); + QObject::connect(rescanXMLFromCurrentFolderAction, &QAction::triggered, libraryManagementCoordinator, &LibraryManagementCoordinator::rescanCurrentFolderForXMLInfo); // lists - QObject::connect(addReadingListAction, &QAction::triggered, window, &LibraryWindow::addNewReadingList); - QObject::connect(deleteReadingListAction, &QAction::triggered, window, &LibraryWindow::deleteSelectedReadingList); - QObject::connect(addLabelAction, &QAction::triggered, window, &LibraryWindow::showAddNewLabelDialog); - QObject::connect(renameListAction, &QAction::triggered, window, &LibraryWindow::showRenameCurrentList); - - QObject::connect(updateLibraryAction, &QAction::triggered, window, &LibraryWindow::updateLibrary); - QObject::connect(backupLibraryAction, &QAction::triggered, window, &LibraryWindow::backupLibrary); - QObject::connect(restoreLibraryAction, &QAction::triggered, window, &LibraryWindow::restoreLibrary); - QObject::connect(repairLibraryAction, &QAction::triggered, window, &LibraryWindow::repairLibrary); - QObject::connect(renameLibraryAction, &QAction::triggered, window, &LibraryWindow::renameLibrary); + QObject::connect(addReadingListAction, &QAction::triggered, readingListManagementCoordinator, &ReadingListManagementCoordinator::addReadingList); + QObject::connect(deleteReadingListAction, &QAction::triggered, readingListManagementCoordinator, &ReadingListManagementCoordinator::deleteCurrentList); + QObject::connect(addLabelAction, &QAction::triggered, readingListManagementCoordinator, &ReadingListManagementCoordinator::addLabel); + QObject::connect(renameListAction, &QAction::triggered, readingListManagementCoordinator, &ReadingListManagementCoordinator::renameCurrentList); + + QObject::connect(updateLibraryAction, &QAction::triggered, libraryManagementCoordinator, &LibraryManagementCoordinator::updateCurrentLibrary); + QObject::connect(backupLibraryAction, &QAction::triggered, libraryDatabaseMaintenanceCoordinator, [this, libraryDatabaseMaintenanceCoordinator] { + libraryDatabaseMaintenanceCoordinator->backupCurrentLibrary(backupLibraryAction->text()); + }); + QObject::connect(restoreLibraryAction, &QAction::triggered, libraryDatabaseMaintenanceCoordinator, [this, libraryDatabaseMaintenanceCoordinator] { + libraryDatabaseMaintenanceCoordinator->restoreCurrentLibrary(restoreLibraryAction->text()); + }); + QObject::connect(repairLibraryAction, &QAction::triggered, libraryRepairCoordinator, [this, libraryRepairCoordinator] { + libraryRepairCoordinator->repairCurrentLibrary(repairLibraryAction->text()); + }); + QObject::connect(renameLibraryAction, &QAction::triggered, renameLibraryDialog, &QDialog::open); + QObject::connect(renameLibraryDialog, &RenameLibraryDialog::renameLibrary, libraryManagementCoordinator, &LibraryManagementCoordinator::renameCurrentLibrary); + QObject::connect(libraryManagementCoordinator, &LibraryManagementCoordinator::libraryRenamed, renameLibraryDialog, &QDialog::close); // connect(deleteLibraryAction,SIGNAL(triggered()),window,SLOT(deleteLibrary())); - QObject::connect(removeLibraryAction, &QAction::triggered, window, &LibraryWindow::removeLibrary); - QObject::connect(rescanLibraryForXMLInfoAction, &QAction::triggered, window, &LibraryWindow::rescanLibraryForXMLInfo); - QObject::connect(openLibraryFolderAction, &QAction::triggered, window, &LibraryWindow::openLibraryFolder); - QObject::connect(showLibraryInfo, &QAction::triggered, window, &LibraryWindow::showLibraryInfo); + QObject::connect(removeLibraryAction, &QAction::triggered, libraryManagementCoordinator, &LibraryManagementCoordinator::askToRemoveCurrentLibrary); + QObject::connect(rescanLibraryForXMLInfoAction, &QAction::triggered, libraryManagementCoordinator, &LibraryManagementCoordinator::rescanCurrentLibraryForXMLInfo); + QObject::connect(openLibraryFolderAction, &QAction::triggered, libraryManagementCoordinator, &LibraryManagementCoordinator::openCurrentLibraryFolder); + QObject::connect(showLibraryInfo, &QAction::triggered, libraryManagementCoordinator, &LibraryManagementCoordinator::showCurrentLibraryInfo); - QObject::connect(openComicAction, &QAction::triggered, window, QOverload<>::of(&LibraryWindow::openComic)); + QObject::connect(openComicAction, &QAction::triggered, comicManagementCoordinator, &ComicManagementCoordinator::openCurrentComic); QObject::connect(helpAboutAction, &QAction::triggered, had, &QWidget::show); - QObject::connect(addFolderAction, &QAction::triggered, window, &LibraryWindow::addFolderToCurrentIndex); - QObject::connect(deleteFolderAction, &QAction::triggered, window, &LibraryWindow::deleteSelectedFolder); + QObject::connect(addFolderAction, &QAction::triggered, folderManagementCoordinator, &FolderManagementCoordinator::addFolderToCurrentFolder); + QObject::connect(renameFolderAction, &QAction::triggered, folderManagementCoordinator, &FolderManagementCoordinator::renameCurrentFolder); + QObject::connect(deleteFolderAction, &QAction::triggered, folderManagementCoordinator, &FolderManagementCoordinator::deleteCurrentFolder); QObject::connect(setRootIndexAction, &QAction::triggered, window, &LibraryWindow::setRootIndex); QObject::connect(expandAllNodesAction, &QAction::triggered, foldersView, &QTreeView::expandAll); QObject::connect(colapseAllNodesAction, &QAction::triggered, foldersView, &QTreeView::collapseAll); @@ -557,10 +632,10 @@ void LibraryWindowActions::createConnections( QObject::connect(serverConfigAction, &QAction::triggered, serverConfigDialog, &QWidget::show); #endif - QObject::connect(addToFavoritesAction, &QAction::triggered, window, &LibraryWindow::addSelectedComicsToFavorites); + QObject::connect(addToFavoritesAction, &QAction::triggered, comicManagementCoordinator, &ComicManagementCoordinator::addSelectedComicsToFavorites); // save covers - QObject::connect(saveCoversToAction, &QAction::triggered, window, &LibraryWindow::saveSelectedCoversTo); + QObject::connect(saveCoversToAction, &QAction::triggered, comicManagementCoordinator, &ComicManagementCoordinator::saveSelectedCoversTo); QObject::connect(toogleShowRecentIndicatorAction, &QAction::toggled, recentVisibilityCoordinator, &RecentVisibilityCoordinator::toggleVisibility); } @@ -583,43 +658,56 @@ void LibraryWindowActions::setUpShortcutsManagement(EditShortcutsDialog *editSho // Get current theme for initial icons const auto &theme = ThemeManager::instance().getCurrentTheme(); - editShortcutsDialog->addActionsGroup("Comics", theme.shortcutsIcons.comicsIcon, - tmpList = QList() - << openComicAction - << saveCoversToAction - << setAsReadAction - << setAsNonReadAction - << setMangaAction - << setNormalAction - << openContainingFolderComicAction - << resetComicRatingAction - << selectAllComicsAction - << editSelectedComicsAction - << asignOrderAction - << deleteMetadataAction - << deleteComicsAction - << getInfoAction); + tmpList = QList() + << openComicAction + << saveCoversToAction + << setAsReadAction + << setAsNonReadAction + << setMangaAction + << setNormalAction + << openContainingFolderComicAction + << renameComicsFilesAction + << organizeComicsFilesAction + << resetComicRatingAction + << selectAllComicsAction + << editSelectedComicsAction + << asignOrderAction + << deleteMetadataAction + << deleteComicsAction + << getInfoAction; + if (!YACReader::FeatureFlags::organizeFiles) { + tmpList.removeOne(renameComicsFilesAction); + tmpList.removeOne(organizeComicsFilesAction); + } + editShortcutsDialog->addActionsGroup("Comics", theme.shortcutsIcons.comicsIcon, tmpList); allActions << tmpList; - editShortcutsDialog->addActionsGroup("Folders", theme.shortcutsIcons.foldersIcon, - tmpList = QList() - << addFolderAction - << deleteFolderAction - << setRootIndexAction - << expandAllNodesAction - << colapseAllNodesAction - << openContainingFolderAction - << setFolderAsNotCompletedAction - << setFolderAsCompletedAction - << setFolderAsReadAction - << setFolderAsUnreadAction - << setFolderAsMangaAction - << setFolderAsNormalAction - << updateCurrentFolderAction - << rescanXMLFromCurrentFolderAction - << setFolderCoverAction - << deleteCustomFolderCoverAction); + tmpList = QList() + << addFolderAction + << renameFolderAction + << deleteFolderAction + << setRootIndexAction + << expandAllNodesAction + << colapseAllNodesAction + << openContainingFolderAction + << renameFilesAction + << organizeFilesAction + << setFolderAsNotCompletedAction + << setFolderAsCompletedAction + << setFolderAsReadAction + << setFolderAsUnreadAction + << setFolderAsMangaAction + << setFolderAsNormalAction + << updateCurrentFolderAction + << rescanXMLFromCurrentFolderAction + << setFolderCoverAction + << deleteCustomFolderCoverAction; + if (!YACReader::FeatureFlags::organizeFiles) { + tmpList.removeOne(renameFilesAction); + tmpList.removeOne(organizeFilesAction); + } + editShortcutsDialog->addActionsGroup("Folders", theme.shortcutsIcons.foldersIcon, tmpList); allActions << tmpList; editShortcutsDialog->addActionsGroup("Lists", theme.shortcutsIcons.foldersIcon, // TODO change icon @@ -678,37 +766,44 @@ void LibraryWindowActions::setUpShortcutsManagement(EditShortcutsDialog *editSho ShortcutsManager::getShortcutsManager().registerActions(allActions); } -void LibraryWindowActions::disableComicsActions(bool disabled) +void LibraryWindowActions::setComicActionsDisabled(bool disabled) { // if there aren't comics, no fullscreen option will be available #ifndef Q_OS_MACOS toggleFullScreenAction->setDisabled(disabled); #endif // edit toolbar - openComicAction->setDisabled(disabled); - editSelectedComicsAction->setDisabled(disabled); + setComicSelectionActionsEnabled(!disabled); selectAllComicsAction->setDisabled(disabled); - asignOrderAction->setDisabled(disabled); - setAsReadAction->setDisabled(disabled); - setAsNonReadAction->setDisabled(disabled); - setNormalAction->setDisabled(disabled); - setMangaAction->setDisabled(disabled); - setWebComicAction->setDisabled(disabled); - setWesternMangaAction->setDisabled(disabled); - setYonkomaAction->setDisabled(disabled); // setAllAsReadAction->setDisabled(disabled); // setAllAsNonReadAction->setDisabled(disabled); showHideMarksAction->setDisabled(disabled); - deleteMetadataAction->setDisabled(disabled); - deleteComicsAction->setDisabled(disabled); - // context menu - openContainingFolderComicAction->setDisabled(disabled); - resetComicRatingAction->setDisabled(disabled); - - getInfoAction->setDisabled(disabled); - updateCurrentFolderAction->setDisabled(disabled); } + +void LibraryWindowActions::setComicSelectionActionsEnabled(bool enabled) +{ + openComicAction->setEnabled(enabled); + saveCoversToAction->setEnabled(enabled); + editSelectedComicsAction->setEnabled(enabled); + asignOrderAction->setEnabled(enabled); + setAsReadAction->setEnabled(enabled); + setAsNonReadAction->setEnabled(enabled); + setNormalAction->setEnabled(enabled); + setMangaAction->setEnabled(enabled); + setWebComicAction->setEnabled(enabled); + setWesternMangaAction->setEnabled(enabled); + setYonkomaAction->setEnabled(enabled); + deleteMetadataAction->setEnabled(enabled); + deleteComicsAction->setEnabled(enabled); + openContainingFolderComicAction->setEnabled(enabled); + renameComicsFilesAction->setEnabled(enabled); + organizeComicsFilesAction->setEnabled(enabled); + resetComicRatingAction->setEnabled(enabled); + getInfoAction->setEnabled(enabled); + addToMenuAction->setEnabled(enabled); + addToFavoritesAction->setEnabled(enabled); +} void LibraryWindowActions::disableLibrariesActions(bool disabled) { updateLibraryAction->setDisabled(disabled); @@ -743,14 +838,17 @@ void LibraryWindowActions::disableFoldersActions(bool disabled) colapseAllNodesAction->setDisabled(disabled); openContainingFolderAction->setDisabled(disabled); + renameFilesAction->setDisabled(disabled); + organizeFilesAction->setDisabled(disabled); + renameFolderAction->setDisabled(disabled); updateFolderAction->setDisabled(disabled); rescanXMLFromCurrentFolderAction->setDisabled(disabled); } void LibraryWindowActions::disableAllActions() { - disableComicsActions(true); + setComicActionsDisabled(true); disableLibrariesActions(true); disableFoldersActions(true); } @@ -767,6 +865,7 @@ void LibraryWindowActions::updateTheme(const Theme &theme) createLibraryAction->setIcon(sidebarIcons.newLibraryIcon); openLibraryAction->setIcon(sidebarIcons.openLibraryIcon); addFolderAction->setIcon(sidebarIcons.addNewIcon); + renameFolderAction->setIcon(sidebarIcons.renameListIcon); deleteFolderAction->setIcon(sidebarIcons.deleteIcon); setRootIndexAction->setIcon(sidebarIcons.setRootIcon); expandAllNodesAction->setIcon(sidebarIcons.expandIcon); diff --git a/YACReaderLibrary/library_window_actions.h b/YACReaderLibrary/library_window_actions.h index 4c60580ff..2c896c2af 100644 --- a/YACReaderLibrary/library_window_actions.h +++ b/YACReaderLibrary/library_window_actions.h @@ -8,14 +8,22 @@ class LibraryWindow; class YACReaderHistoryController; +class YACReaderNavigationController; class EditShortcutsDialog; class HelpAboutDialog; -class ExportLibraryDialog; class YACReaderContentViewsManager; class YACReaderFoldersView; class YACReaderOptionsDialog; class ServerConfigDialog; class RecentVisibilityCoordinator; +class ComicManagementCoordinator; +class ReadingListManagementCoordinator; +class FolderManagementCoordinator; +class OrganizeFilesCoordinator; +class LibraryManagementCoordinator; +class LibraryDatabaseMaintenanceCoordinator; +class LibraryRepairCoordinator; +class RenameLibraryDialog; struct Theme; class LibraryWindowActions @@ -56,6 +64,7 @@ class LibraryWindowActions // tree actions QAction *addFolderAction; + QAction *renameFolderAction; QAction *deleteFolderAction; //-- QAction *setRootIndexAction; @@ -63,6 +72,8 @@ class LibraryWindowActions QAction *colapseAllNodesAction; QAction *openContainingFolderAction; + QAction *renameFilesAction; + QAction *organizeFilesAction; QAction *saveCoversToAction; //-- QAction *setFolderAsNotCompletedAction; @@ -81,6 +92,8 @@ class LibraryWindowActions QAction *deleteCustomFolderCoverAction; QAction *openContainingFolderComicAction; + QAction *renameComicsFilesAction; + QAction *organizeComicsFilesAction; QAction *setAsReadAction; QAction *setAsNonReadAction; @@ -127,17 +140,26 @@ class LibraryWindowActions LibraryWindowActions(); void createActions(LibraryWindow *window, QSettings *settings); void createConnections(YACReaderHistoryController *historyController, + YACReaderNavigationController *navigationController, LibraryWindow *window, HelpAboutDialog *had, - ExportLibraryDialog *exportLibraryDialog, YACReaderContentViewsManager *contentViewsManager, EditShortcutsDialog *editShortcutsDialog, YACReaderFoldersView *foldersView, YACReaderOptionsDialog *optionsDialog, ServerConfigDialog *serverConfigDialog, - RecentVisibilityCoordinator *recentVisibilityCoordinator); - - void disableComicsActions(bool disabled); + RecentVisibilityCoordinator *recentVisibilityCoordinator, + ComicManagementCoordinator *comicManagementCoordinator, + ReadingListManagementCoordinator *readingListManagementCoordinator, + FolderManagementCoordinator *folderManagementCoordinator, + OrganizeFilesCoordinator *organizeFilesCoordinator, + LibraryManagementCoordinator *libraryManagementCoordinator, + LibraryDatabaseMaintenanceCoordinator *libraryDatabaseMaintenanceCoordinator, + LibraryRepairCoordinator *libraryRepairCoordinator, + RenameLibraryDialog *renameLibraryDialog); + + void setComicActionsDisabled(bool disabled); + void setComicSelectionActionsEnabled(bool enabled); void disableLibrariesActions(bool disabled); void disableNoUpdatedLibrariesActions(bool disabled); void disableFoldersActions(bool disabled); diff --git a/YACReaderLibrary/library_window_menus.cpp b/YACReaderLibrary/library_window_menus.cpp new file mode 100644 index 000000000..52a66b0ee --- /dev/null +++ b/YACReaderLibrary/library_window_menus.cpp @@ -0,0 +1,430 @@ +#include "library_window_menus.h" + +#include "comic_management_coordinator.h" +#include "comic_model.h" +#include "feature_flags.h" +#include "folder_management_coordinator.h" +#include "folder_model.h" +#include "grid_comics_view.h" +#include "library_window_actions.h" +#include "organize_files_coordinator.h" +#include "reading_list_item.h" +#include "reading_list_model.h" +#include "theme.h" +#include "yacreader_content_views_manager.h" +#include "yacreader_folders_view.h" +#include "yacreader_global_gui.h" +#include "yacreader_library_list_widget.h" + +#include +#include +#include +#include + +#include + +namespace { +struct TypeActions { + QAction *comic; + QAction *manga; + QAction *westernManga; + QAction *webComic; + QAction *yonkoma; +}; + +TypeActions addTypeActions(QMenu *menu) +{ + TypeActions typeActions { + new QAction(LibraryWindowMenus::tr("comic"), menu), + new QAction(LibraryWindowMenus::tr("manga"), menu), + new QAction(LibraryWindowMenus::tr("western manga (left to right)"), menu), + new QAction(LibraryWindowMenus::tr("web comic"), menu), + new QAction(LibraryWindowMenus::tr("4koma (top to botom)"), menu) + }; + + const QList actions { typeActions.comic, typeActions.manga, typeActions.westernManga, typeActions.webComic, typeActions.yonkoma }; + for (auto *action : actions) { + action->setCheckable(true); + menu->addAction(action); + } + + return typeActions; +} + +void setCheckedType(const TypeActions &actions, YACReader::FileType type) +{ + actions.comic->setChecked(type == YACReader::FileType::Comic); + actions.manga->setChecked(type == YACReader::FileType::Manga); + actions.westernManga->setChecked(type == YACReader::FileType::WesternManga); + actions.webComic->setChecked(type == YACReader::FileType::WebComic); + actions.yonkoma->setChecked(type == YACReader::FileType::Yonkoma); +} + +void connectTypeActions(const TypeActions &actions, QObject *context, const std::function &handler) +{ + QObject::connect(actions.comic, &QAction::triggered, context, [handler] { handler(YACReader::FileType::Comic); }); + QObject::connect(actions.manga, &QAction::triggered, context, [handler] { handler(YACReader::FileType::Manga); }); + QObject::connect(actions.westernManga, &QAction::triggered, context, [handler] { handler(YACReader::FileType::WesternManga); }); + QObject::connect(actions.webComic, &QAction::triggered, context, [handler] { handler(YACReader::FileType::WebComic); }); + QObject::connect(actions.yonkoma, &QAction::triggered, context, [handler] { handler(YACReader::FileType::Yonkoma); }); +} +} + +LibraryWindowMenus::LibraryWindowMenus(QMainWindow *window, + LibraryWindowActions &actions, + YACReaderLibraryListWidget *selectedLibrary, + YACReaderFoldersView *foldersView, + YACReaderContentViewsManager *contentViewsManager, + FolderModel *foldersModel, + FolderModelProxy *foldersModelProxy, + ReadingListModel *listsModel, + FolderManagementCoordinator *folderManagementCoordinator, + ComicManagementCoordinator *comicManagementCoordinator, + OrganizeFilesCoordinator *organizeFilesCoordinator, + ComicSelectionProvider comicSelectionProvider, + LibraryIdProvider libraryIdProvider, + LibraryPathProvider libraryPathProvider, + ThemeProvider themeProvider) + : QObject(window), window(window), actions(actions), selectedLibrary(selectedLibrary), foldersView(foldersView), contentViewsManager(contentViewsManager), foldersModel(foldersModel), foldersModelProxy(foldersModelProxy), listsModel(listsModel), folderManagementCoordinator(folderManagementCoordinator), comicManagementCoordinator(comicManagementCoordinator), organizeFilesCoordinator(organizeFilesCoordinator), comicSelectionProvider(std::move(comicSelectionProvider)), libraryIdProvider(std::move(libraryIdProvider)), libraryPathProvider(std::move(libraryPathProvider)), themeProvider(std::move(themeProvider)) +{ +} + +void LibraryWindowMenus::setupMenus() +{ + connect(foldersView, &QWidget::customContextMenuRequested, this, &LibraryWindowMenus::showFoldersContextMenu); + auto gridView = contentViewsManager->gridView(); + connect(gridView, &GridComicsView::openFolderContextMenu, this, [this, gridView](const QPoint &point, const Folder &folder) { + showGridFoldersContextMenu(gridView->mapToGlobal(point), folder); + }); + connect(gridView, &GridComicsView::openContinueReadingComicContextMenu, this, [this, gridView](const QPoint &point, const ComicDB &comic) { + showContinueReadingContextMenu(gridView->mapToGlobal(point), comic); + }); + + foldersView->addAction(actions.addFolderAction); + foldersView->addAction(actions.renameFolderAction); + foldersView->addAction(actions.deleteFolderAction); + YACReader::addSperator(foldersView); + + foldersView->addAction(actions.openContainingFolderAction); + foldersView->addAction(actions.updateFolderAction); + YACReader::addSperator(foldersView); + + foldersView->addAction(actions.setFolderAsNotCompletedAction); + foldersView->addAction(actions.setFolderAsCompletedAction); + YACReader::addSperator(foldersView); + + foldersView->addAction(actions.setFolderAsReadAction); + foldersView->addAction(actions.setFolderAsUnreadAction); + YACReader::addSperator(foldersView); + + foldersView->addAction(actions.setFolderAsNormalAction); + foldersView->addAction(actions.setFolderAsMangaAction); + foldersView->addAction(actions.setFolderAsWesternMangaAction); + foldersView->addAction(actions.setFolderAsWebComicAction); + foldersView->addAction(actions.setFolderAsYonkomaAction); + YACReader::addSperator(foldersView); + + foldersView->addAction(actions.setFolderCoverAction); + foldersView->addAction(actions.deleteCustomFolderCoverAction); + + selectedLibrary->addAction(actions.updateLibraryAction); + selectedLibrary->addAction(actions.renameLibraryAction); + selectedLibrary->addAction(actions.removeLibraryAction); + YACReader::addSperator(selectedLibrary); + + auto typeMenu = new QMenu(tr("Set type"), selectedLibrary); + const auto typeActions = addTypeActions(typeMenu); + connectTypeActions(typeActions, this, [this](YACReader::FileType type) { emit currentLibraryTypeChangeRequested(type); }); + connect(typeMenu, &QMenu::aboutToShow, this, [this, typeActions] { setCheckedType(typeActions, foldersModel->getRootFolder().type); }); + + selectedLibrary->addAction(typeMenu->menuAction()); + YACReader::addSperator(selectedLibrary); + + selectedLibrary->addAction(actions.rescanLibraryForXMLInfoAction); + selectedLibrary->addAction(actions.repairLibraryAction); + YACReader::addSperator(selectedLibrary); + + selectedLibrary->addAction(actions.backupLibraryAction); + selectedLibrary->addAction(actions.restoreLibraryAction); + YACReader::addSperator(selectedLibrary); + + selectedLibrary->addAction(actions.exportComicsInfoAction); + selectedLibrary->addAction(actions.importComicsInfoAction); + YACReader::addSperator(selectedLibrary); + + selectedLibrary->addAction(actions.exportLibraryAction); + selectedLibrary->addAction(actions.importLibraryAction); + YACReader::addSperator(selectedLibrary); + + selectedLibrary->addAction(actions.openLibraryFolderAction); + selectedLibrary->addAction(actions.showLibraryInfo); + +#ifdef Q_OS_MACOS + auto menuBar = window->menuBar(); + + auto libraryMenu = new QMenu(tr("Library"), menuBar); + libraryMenu->addAction(actions.updateLibraryAction); + libraryMenu->addAction(actions.renameLibraryAction); + libraryMenu->addAction(actions.removeLibraryAction); + libraryMenu->addSeparator(); + libraryMenu->addMenu(typeMenu); + libraryMenu->addSeparator(); + libraryMenu->addAction(actions.rescanLibraryForXMLInfoAction); + libraryMenu->addAction(actions.repairLibraryAction); + libraryMenu->addSeparator(); + libraryMenu->addAction(actions.backupLibraryAction); + libraryMenu->addAction(actions.restoreLibraryAction); + libraryMenu->addSeparator(); + libraryMenu->addAction(actions.exportComicsInfoAction); + libraryMenu->addAction(actions.importComicsInfoAction); + libraryMenu->addSeparator(); + libraryMenu->addAction(actions.exportLibraryAction); + libraryMenu->addAction(actions.importLibraryAction); + libraryMenu->addSeparator(); + libraryMenu->addAction(actions.openLibraryFolderAction); + libraryMenu->addAction(actions.showLibraryInfo); + + auto folderMenu = new QMenu(tr("Folder"), menuBar); + folderMenu->addAction(actions.openContainingFolderAction); + folderMenu->addAction(actions.renameFolderAction); + folderMenu->addAction(actions.updateFolderAction); + folderMenu->addSeparator(); + folderMenu->addAction(actions.rescanXMLFromCurrentFolderAction); + folderMenu->addSeparator(); + folderMenu->addAction(actions.setFolderAsNotCompletedAction); + folderMenu->addAction(actions.setFolderAsCompletedAction); + folderMenu->addSeparator(); + folderMenu->addAction(actions.setFolderAsReadAction); + folderMenu->addAction(actions.setFolderAsUnreadAction); + folderMenu->addSeparator(); + folderMenu->addAction(actions.setFolderAsNormalAction); + folderMenu->addAction(actions.setFolderAsMangaAction); + folderMenu->addAction(actions.setFolderAsWesternMangaAction); + folderMenu->addAction(actions.setFolderAsWebComicAction); + folderMenu->addAction(actions.setFolderAsYonkomaAction); + folderMenu->addSeparator(); + folderMenu->addAction(actions.setFolderCoverAction); + folderMenu->addAction(actions.deleteCustomFolderCoverAction); + + auto comicMenu = new QMenu(tr("Comic"), menuBar); + comicMenu->addAction(actions.openContainingFolderComicAction); + comicMenu->addSeparator(); + comicMenu->addAction(actions.resetComicRatingAction); + + menuBar->addMenu(libraryMenu); + menuBar->addMenu(folderMenu); + menuBar->addMenu(comicMenu); +#endif +} + +void LibraryWindowMenus::showComicsViewContextMenu(const QPoint &point) +{ + showComicsContextMenu(point, true); +} + +void LibraryWindowMenus::showComicsItemContextMenu(const QPoint &point) +{ + showComicsContextMenu(point, false); +} + +void LibraryWindowMenus::showComicsContextMenu(const QPoint &point, bool showFullScreenAction) +{ + const auto selection = comicSelectionProvider(); + auto menu = new QMenu(window); + connect(menu, &QMenu::aboutToHide, menu, &QObject::deleteLater); + + auto typeMenu = new QMenu(tr("Set type"), menu); + const auto typeActions = addTypeActions(typeMenu); + connectTypeActions(typeActions, menu, [this](YACReader::FileType type) { comicManagementCoordinator->setSelectedComicsType(type); }); + if (selection.size() == 1) + setCheckedType(typeActions, selection.constFirst().data(ComicModel::TypeRole).value()); + + menu->addAction(actions.openComicAction); + menu->addAction(actions.saveCoversToAction); + menu->addSeparator(); + menu->addAction(actions.openContainingFolderComicAction); + menu->addAction(actions.updateCurrentFolderAction); + menu->addSeparator(); + menu->addAction(actions.editSelectedComicsAction); + menu->addAction(actions.getInfoAction); + menu->addAction(actions.asignOrderAction); + if (YACReader::FeatureFlags::organizeFiles) { + menu->addSeparator(); + menu->addAction(actions.renameComicsFilesAction); + menu->addAction(actions.organizeComicsFilesAction); + } + menu->addSeparator(); + menu->addAction(actions.selectAllComicsAction); + menu->addSeparator(); + menu->addAction(actions.setAsReadAction); + menu->addAction(actions.setAsNonReadAction); + menu->addSeparator(); + menu->addMenu(typeMenu); + menu->addSeparator(); + menu->addAction(actions.resetComicRatingAction); + menu->addSeparator(); + menu->addAction(actions.deleteMetadataAction); + if (comicManagementCoordinator->hasCustomCoverInSelection()) { + auto resetCustomCoverAction = menu->addAction(tr("Delete custom cover")); + connect(resetCustomCoverAction, &QAction::triggered, menu, [this] { comicManagementCoordinator->resetSelectedCustomCovers(); }); + } + menu->addSeparator(); + menu->addAction(actions.deleteComicsAction); + menu->addSeparator(); + menu->addAction(actions.addToMenuAction); + auto subMenu = new QMenu(menu); + setupAddToSubmenu(*subMenu); + +#ifndef Q_OS_MACOS + if (showFullScreenAction) { + menu->addSeparator(); + menu->addAction(actions.toggleFullScreenAction); + } +#else + Q_UNUSED(showFullScreenAction); +#endif + + menu->popup(contentViewsManager->comicsView->mapToGlobal(point)); +} + +void LibraryWindowMenus::showGridFoldersContextMenu(const QPoint &point, const Folder &folder) +{ + auto menu = new QMenu(window); + connect(menu, &QMenu::aboutToHide, menu, &QObject::deleteLater); + + const auto folderId = folder.id; + const auto libraryPath = libraryPathProvider(); + const auto &theme = themeProvider(); + + auto openContainingFolderAction = new QAction(tr("Open folder..."), menu); + openContainingFolderAction->setIcon(theme.menuIcons.openContainingFolderIcon); + auto updateFolderAction = new QAction(tr("Update folder"), menu); + updateFolderAction->setIcon(theme.menuIcons.updateCurrentFolderIcon); + auto renameFolderAction = new QAction(tr("Rename folder"), menu); + renameFolderAction->setIcon(theme.sidebarIcons.renameListIcon); + auto renameFilesAction = new QAction(tr("Rename files..."), menu); + auto organizeFilesAction = new QAction(tr("Organize into folders..."), menu); + auto rescanLibraryForXMLInfoAction = new QAction(tr("Rescan library for XML info"), menu); + auto setFolderAsNotCompletedAction = new QAction(tr("Set as uncompleted"), menu); + auto setFolderAsCompletedAction = new QAction(tr("Set as completed"), menu); + auto setFolderAsReadAction = new QAction(tr("Set as read"), menu); + auto setFolderAsUnreadAction = new QAction(tr("Set as unread"), menu); + auto setFolderCoverAction = new QAction(tr("Set custom cover"), menu); + auto deleteCustomFolderCoverAction = new QAction(tr("Delete custom cover"), menu); + + menu->addAction(openContainingFolderAction); + menu->addAction(renameFolderAction); + menu->addAction(updateFolderAction); + if (YACReader::FeatureFlags::organizeFiles) { + menu->addSeparator(); + menu->addAction(renameFilesAction); + menu->addAction(organizeFilesAction); + } + menu->addSeparator(); + menu->addAction(rescanLibraryForXMLInfoAction); + menu->addSeparator(); + menu->addAction(folder.completed ? setFolderAsNotCompletedAction : setFolderAsCompletedAction); + menu->addSeparator(); + menu->addAction(folder.finished ? setFolderAsUnreadAction : setFolderAsReadAction); + menu->addSeparator(); + + auto typeMenu = new QMenu(tr("Set type"), menu); + const auto typeActions = addTypeActions(typeMenu); + setCheckedType(typeActions, folder.type); + menu->addMenu(typeMenu); + + connect(openContainingFolderAction, &QAction::triggered, menu, [this, folderId, libraryPath] { folderManagementCoordinator->openFolder(folderId, libraryPath); }); + connect(updateFolderAction, &QAction::triggered, menu, [this, folder] { emit folderUpdateRequested(foldersModel->getIndexFromFolder(folder)); }); + connect(renameFolderAction, &QAction::triggered, menu, [this, folderId, libraryPath] { folderManagementCoordinator->renameFolder(folderId, libraryPath); }); + connect(renameFilesAction, &QAction::triggered, menu, [this, folder] { organizeFilesCoordinator->renameFolder(foldersModel->getIndexFromFolder(folder)); }); + connect(organizeFilesAction, &QAction::triggered, menu, [this, folder] { organizeFilesCoordinator->organizeFolder(foldersModel->getIndexFromFolder(folder)); }); + connect(rescanLibraryForXMLInfoAction, &QAction::triggered, menu, [this, folder] { emit folderXmlRescanRequested(foldersModel->getIndexFromFolder(folder)); }); + connect(setFolderAsNotCompletedAction, &QAction::triggered, menu, [this, folderId, libraryPath] { folderManagementCoordinator->setFolderCompleted(folderId, libraryPath, false); }); + connect(setFolderAsCompletedAction, &QAction::triggered, menu, [this, folderId, libraryPath] { folderManagementCoordinator->setFolderCompleted(folderId, libraryPath, true); }); + connect(setFolderAsReadAction, &QAction::triggered, menu, [this, folderId, libraryPath] { folderManagementCoordinator->setFolderRead(folderId, libraryPath, true); }); + connect(setFolderAsUnreadAction, &QAction::triggered, menu, [this, folderId, libraryPath] { folderManagementCoordinator->setFolderRead(folderId, libraryPath, false); }); + connectTypeActions(typeActions, menu, [this, folderId, libraryPath](YACReader::FileType type) { folderManagementCoordinator->setFolderType(folderId, libraryPath, type); }); + connect(setFolderCoverAction, &QAction::triggered, menu, [this, folderId, libraryPath] { folderManagementCoordinator->selectAndSetCustomCover(folderId, libraryPath); }); + connect(deleteCustomFolderCoverAction, &QAction::triggered, menu, [this, folderId, libraryPath] { folderManagementCoordinator->resetCustomCover(folderId, libraryPath); }); + + menu->addSeparator(); + menu->addAction(setFolderCoverAction); + if (!folder.customImage.isEmpty()) + menu->addAction(deleteCustomFolderCoverAction); + + menu->popup(point); +} + +void LibraryWindowMenus::showContinueReadingContextMenu(const QPoint &point, const ComicDB &comic) +{ + QMenu menu; + auto setAsUnreadAction = new QAction(tr("Set as unread"), &menu); + setAsUnreadAction->setIcon(themeProvider().comicsViewToolbar.setAsUnreadIcon); + menu.addAction(setAsUnreadAction); + + connect(setAsUnreadAction, &QAction::triggered, &menu, [this, comic] { comicManagementCoordinator->setComicUnread(libraryIdProvider(), comic); }); + menu.exec(point); +} + +void LibraryWindowMenus::setupAddToSubmenu(QMenu &menu) +{ + menu.addAction(actions.addToFavoritesAction); + actions.addToMenuAction->setMenu(&menu); + + const auto labels = listsModel->getLabels(); + if (!labels.isEmpty()) + menu.addSeparator(); + for (auto *label : labels) { + auto action = new QAction(label->getIcon(), label->name(), &menu); + menu.addAction(action); + + const auto labelId = label->getId(); + connect(action, &QAction::triggered, comicManagementCoordinator, [coordinator = comicManagementCoordinator, labelId] { coordinator->addSelectedComicsToLabel(labelId); }); + } +} + +void LibraryWindowMenus::showFoldersContextMenu(const QPoint &point) +{ + const auto sourceIndex = foldersModelProxy->mapToSource(foldersView->indexAt(point)); + if (!sourceIndex.isValid()) + return; + + const auto folder = foldersModel->getFolder(sourceIndex); + const TypeActions typeActions { + actions.setFolderAsNormalAction, + actions.setFolderAsMangaAction, + actions.setFolderAsWesternMangaAction, + actions.setFolderAsWebComicAction, + actions.setFolderAsYonkomaAction + }; + const QList checkableActions { typeActions.comic, typeActions.manga, typeActions.westernManga, typeActions.webComic, typeActions.yonkoma }; + for (auto *action : checkableActions) + action->setCheckable(true); + setCheckedType(typeActions, folder.type); + + QMenu menu; + menu.addAction(actions.openContainingFolderAction); + menu.addAction(actions.renameFolderAction); + menu.addAction(actions.updateFolderAction); + if (YACReader::FeatureFlags::organizeFiles) { + menu.addSeparator(); + menu.addAction(actions.renameFilesAction); + menu.addAction(actions.organizeFilesAction); + } + menu.addSeparator(); + menu.addAction(actions.rescanXMLFromCurrentFolderAction); + menu.addSeparator(); + menu.addAction(folder.completed ? actions.setFolderAsNotCompletedAction : actions.setFolderAsCompletedAction); + menu.addSeparator(); + menu.addAction(folder.finished ? actions.setFolderAsUnreadAction : actions.setFolderAsReadAction); + menu.addSeparator(); + auto typeMenu = new QMenu(tr("Set type"), &menu); + menu.addMenu(typeMenu); + typeMenu->addActions(checkableActions); + menu.addSeparator(); + menu.addAction(actions.setFolderCoverAction); + if (!folder.customImage.isEmpty()) + menu.addAction(actions.deleteCustomFolderCoverAction); + + menu.exec(foldersView->mapToGlobal(point)); +} diff --git a/YACReaderLibrary/library_window_menus.h b/YACReaderLibrary/library_window_menus.h new file mode 100644 index 000000000..1e57bccbe --- /dev/null +++ b/YACReaderLibrary/library_window_menus.h @@ -0,0 +1,89 @@ +#ifndef LIBRARY_WINDOW_MENUS_H +#define LIBRARY_WINDOW_MENUS_H + +#include "comic_db.h" +#include "folder.h" +#include "yacreader_global.h" + +#include +#include + +#include + +class ComicManagementCoordinator; +class FolderManagementCoordinator; +class FolderModel; +class FolderModelProxy; +class LibraryWindowActions; +class OrganizeFilesCoordinator; +class QMainWindow; +class QMenu; +class QPoint; +class ReadingListModel; +struct Theme; +class YACReaderContentViewsManager; +class YACReaderFoldersView; +class YACReaderLibraryListWidget; + +class LibraryWindowMenus : public QObject +{ + Q_OBJECT + +public: + using ComicSelectionProvider = std::function; + using LibraryIdProvider = std::function; + using LibraryPathProvider = std::function; + using ThemeProvider = std::function; + + explicit LibraryWindowMenus(QMainWindow *window, + LibraryWindowActions &actions, + YACReaderLibraryListWidget *selectedLibrary, + YACReaderFoldersView *foldersView, + YACReaderContentViewsManager *contentViewsManager, + FolderModel *foldersModel, + FolderModelProxy *foldersModelProxy, + ReadingListModel *listsModel, + FolderManagementCoordinator *folderManagementCoordinator, + ComicManagementCoordinator *comicManagementCoordinator, + OrganizeFilesCoordinator *organizeFilesCoordinator, + ComicSelectionProvider comicSelectionProvider, + LibraryIdProvider libraryIdProvider, + LibraryPathProvider libraryPathProvider, + ThemeProvider themeProvider); + + void setupMenus(); + +public slots: + void showComicsViewContextMenu(const QPoint &point); + void showComicsItemContextMenu(const QPoint &point); + void showGridFoldersContextMenu(const QPoint &point, const Folder &folder); + void showContinueReadingContextMenu(const QPoint &point, const ComicDB &comic); + void showFoldersContextMenu(const QPoint &point); + +signals: + void currentLibraryTypeChangeRequested(YACReader::FileType type); + void folderUpdateRequested(const QModelIndex &folder); + void folderXmlRescanRequested(const QModelIndex &folder); + +private: + void showComicsContextMenu(const QPoint &point, bool showFullScreenAction); + void setupAddToSubmenu(QMenu &menu); + + QMainWindow *window; + LibraryWindowActions &actions; + YACReaderLibraryListWidget *selectedLibrary; + YACReaderFoldersView *foldersView; + YACReaderContentViewsManager *contentViewsManager; + FolderModel *foldersModel; + FolderModelProxy *foldersModelProxy; + ReadingListModel *listsModel; + FolderManagementCoordinator *folderManagementCoordinator; + ComicManagementCoordinator *comicManagementCoordinator; + OrganizeFilesCoordinator *organizeFilesCoordinator; + ComicSelectionProvider comicSelectionProvider; + LibraryIdProvider libraryIdProvider; + LibraryPathProvider libraryPathProvider; + ThemeProvider themeProvider; +}; + +#endif // LIBRARY_WINDOW_MENUS_H diff --git a/YACReaderLibrary/main.cpp b/YACReaderLibrary/main.cpp index a77c4925d..9808d57b8 100644 --- a/YACReaderLibrary/main.cpp +++ b/YACReaderLibrary/main.cpp @@ -24,6 +24,8 @@ #include #include + +#include #ifdef Q_OS_MACOS #include "trayhandler.h" #endif @@ -81,7 +83,7 @@ void logSystemAndConfig() auto libraries = DBHelper::getLibraries().getLibraries(); QLOG_INFO() << "Libraries: "; - for (auto library : libraries) { + for (const auto &library : std::as_const(libraries)) { QLOG_INFO() << " " << library; auto access = DataBaseManagement::getDatabaseAccess(library.getPath()); QLOG_INFO() << " > STATUS: " << access; diff --git a/YACReaderLibrary/options_dialog.cpp b/YACReaderLibrary/options_dialog.cpp index b3c68b757..bc041b992 100644 --- a/YACReaderLibrary/options_dialog.cpp +++ b/YACReaderLibrary/options_dialog.cpp @@ -90,6 +90,9 @@ void OptionsDialog::restoreOptions(QSettings *settings) displayGlobalContinueReadingBannerCheck->setChecked(settings->value(DISPLAY_GLOBAL_CONTINUE_READING_IN_GRID_VIEW, true).toBool()); displayContinueReadingBannerCheck->setChecked(settings->value(DISPLAY_CONTINUE_READING_IN_GRID_VIEW, true).toBool()); + mixFoldersAndComicsCheck->setChecked(settings->value(COMICS_GRID_MIX_FOLDERS_AND_COMICS, true).toBool()); + startComicsOnNewRowCheck->setChecked(settings->value(COMICS_GRID_START_COMICS_ON_NEW_ROW, false).toBool()); + startComicsOnNewRowCheck->setEnabled(mixFoldersAndComicsCheck->isChecked()); updateLibrariesAtStartupCheck->setChecked(settings->value(UPDATE_LIBRARIES_AT_STARTUP, false).toBool()); detectChangesAutomaticallyCheck->setChecked(settings->value(DETECT_CHANGES_IN_LIBRARIES_AUTOMATICALLY, false).toBool()); @@ -192,13 +195,13 @@ QWidget *OptionsDialog::createGeneralTab() startToTrayCheckbox = new QCheckBox(tr("Start into the system tray")); connect(trayIconCheckbox, &QCheckBox::clicked, this, - [=](bool checked) { + [=, this](bool checked) { settings->setValue(CLOSE_TO_TRAY, checked); startToTrayCheckbox->setEnabled(checked); emit optionsChanged(); }); connect(startToTrayCheckbox, &QCheckBox::clicked, this, - [=](bool checked) { + [=, this](bool checked) { settings->setValue(START_TO_TRAY, checked); }); @@ -219,7 +222,7 @@ QWidget *OptionsDialog::createGeneralTab() comicInfoXMLCheckbox = new QCheckBox(tr("Import metadata from ComicInfo.xml when adding new comics")); connect(comicInfoXMLCheckbox, &QCheckBox::clicked, this, - [=](bool checked) { + [=, this](bool checked) { settings->setValue(IMPORT_COMIC_INFO_XML_METADATA, checked); }); @@ -268,17 +271,17 @@ QWidget *OptionsDialog::createLibrariesTab() { updateLibrariesAtStartupCheck = new QCheckBox(tr("Update libraries at startup")); connect(updateLibrariesAtStartupCheck, &QCheckBox::clicked, this, - [=](bool checked) { + [=, this](bool checked) { settings->setValue(UPDATE_LIBRARIES_AT_STARTUP, checked); }); detectChangesAutomaticallyCheck = new QCheckBox(tr("Try to detect changes automatically")); connect(detectChangesAutomaticallyCheck, &QCheckBox::clicked, this, - [=](bool checked) { + [=, this](bool checked) { settings->setValue(DETECT_CHANGES_IN_LIBRARIES_AUTOMATICALLY, checked); }); updateLibrariesPeriodicallyCheck = new QCheckBox(tr("Update libraries periodically")); connect(updateLibrariesPeriodicallyCheck, &QCheckBox::clicked, this, - [=](bool checked) { + [=, this](bool checked) { settings->setValue(UPDATE_LIBRARIES_PERIODICALLY, checked); }); @@ -293,13 +296,13 @@ QWidget *OptionsDialog::createLibrariesTab() intervalComboBox->addItem(tr("daily"), static_cast::type>(LibrariesUpdateInterval::Daily)); connect(intervalComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, - [=](int index) { + [=, this](int index) { settings->setValue(UPDATE_LIBRARIES_PERIODICALLY_INTERVAL, index); }); updateLibrariesAtCertainTimeCheck = new QCheckBox(tr("Update libraries at certain time")); connect(updateLibrariesAtCertainTimeCheck, &QCheckBox::clicked, this, - [=](bool checked) { + [=, this](bool checked) { settings->setValue(UPDATE_LIBRARIES_AT_CERTAIN_TIME, checked); }); @@ -307,7 +310,7 @@ QWidget *OptionsDialog::createLibrariesTab() updateLibrariesTimeEdit = new QTimeEdit; updateLibrariesTimeEdit->setDisplayFormat("hh:mm"); connect(updateLibrariesTimeEdit, &QTimeEdit::timeChanged, this, - [=](const QTime &time) { + [=, this](const QTime &time) { settings->setValue(UPDATE_LIBRARIES_AT_CERTAIN_TIME_TIME, time.toString("hh:mm")); }); @@ -346,7 +349,7 @@ QWidget *OptionsDialog::createLibrariesTab() compareModifiedDateWhenUpdatingLibrariesCheck = new QCheckBox(tr("Compare the modified date of files when updating a library (not recommended)")); connect(compareModifiedDateWhenUpdatingLibrariesCheck, &QCheckBox::clicked, this, - [=](bool checked) { + [=, this](bool checked) { settings->setValue(COMPARE_MODIFIED_DATE_ON_LIBRARY_UPDATES, checked); }); @@ -421,6 +424,16 @@ QWidget *OptionsDialog::createGridTab() auto continueReadingGroup = new QGroupBox(tr("Continue reading")); continueReadingGroup->setLayout(continueReadingLayout); + mixFoldersAndComicsCheck = new QCheckBox(tr("Mix folders and comics")); + startComicsOnNewRowCheck = new QCheckBox(tr("Start comics on a new row")); + + auto gridContentLayout = new QVBoxLayout(); + gridContentLayout->addWidget(mixFoldersAndComicsCheck); + gridContentLayout->addWidget(startComicsOnNewRowCheck); + + auto gridContentGroup = new QGroupBox(tr("Content")); + gridContentGroup->setLayout(gridContentLayout); + connect(useBackgroundImageCheck, &QAbstractButton::clicked, this, &OptionsDialog::useBackgroundImageCheckClicked); connect(backgroundImageOpacitySlider, &QAbstractSlider::valueChanged, this, &OptionsDialog::backgroundImageOpacitySliderChanged); connect(backgroundImageBlurRadiusSlider, &QAbstractSlider::valueChanged, this, &OptionsDialog::backgroundImageBlurRadiusSliderChanged); @@ -440,8 +453,20 @@ QWidget *OptionsDialog::createGridTab() emit optionsChanged(); }); + connect(mixFoldersAndComicsCheck, &QCheckBox::clicked, this, [this](bool checked) { + settings->setValue(COMICS_GRID_MIX_FOLDERS_AND_COMICS, checked); + startComicsOnNewRowCheck->setEnabled(checked); + emit optionsChanged(); + }); + + connect(startComicsOnNewRowCheck, &QCheckBox::clicked, this, [this](bool checked) { + settings->setValue(COMICS_GRID_START_COMICS_ON_NEW_ROW, checked); + emit optionsChanged(); + }); + auto gridViewLayout = new QVBoxLayout(); gridViewLayout->addWidget(gridBackgroundGroup); + gridViewLayout->addWidget(gridContentGroup); gridViewLayout->addWidget(continueReadingGroup); gridViewLayout->addStretch(); diff --git a/YACReaderLibrary/options_dialog.h b/YACReaderLibrary/options_dialog.h index 017a3ced1..d1b4af090 100644 --- a/YACReaderLibrary/options_dialog.h +++ b/YACReaderLibrary/options_dialog.h @@ -63,6 +63,8 @@ private slots: QLabel *opacityLabel; QLabel *blurLabel; QPushButton *resetButton; + QCheckBox *mixFoldersAndComicsCheck; + QCheckBox *startComicsOnNewRowCheck; QWidget *createGeneralTab(); QWidget *createLibrariesTab(); diff --git a/YACReaderLibrary/organize_files/CMakeLists.txt b/YACReaderLibrary/organize_files/CMakeLists.txt new file mode 100644 index 000000000..43e17f36e --- /dev/null +++ b/YACReaderLibrary/organize_files/CMakeLists.txt @@ -0,0 +1,34 @@ +# File organization (rename files / organize into folders) for YACReaderLibrary + +add_library(organize_files STATIC + organize_files_plan.h + organize_files_plan.cpp + organize_files_journal.h + organize_files_journal.cpp + organize_files_worker.h + organize_files_worker.cpp + organize_files_dialog.h + organize_files_dialog.cpp + organize_files_coordinator.h + organize_files_coordinator.cpp +) +target_include_directories(organize_files PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} +) +yacreader_apply_build_options(organize_files) +# App-specific theme.h needed for themable.h → theme_manager.h → theme.h chain +target_include_directories(organize_files PRIVATE + ${PROJECT_SOURCE_DIR}/YACReaderLibrary/themes +) +# ComicModel and FolderModel live in the app target; their headers come from the +# db_helper include dirs, their symbols from the final app link. +target_link_libraries(organize_files PUBLIC + Qt6::Core + Qt6::Widgets + Qt6::Sql + common_all + common_gui + custom_widgets_library + db_helper + QsLog +) diff --git a/YACReaderLibrary/organize_files/organize_files_coordinator.cpp b/YACReaderLibrary/organize_files/organize_files_coordinator.cpp new file mode 100644 index 000000000..2b93a2f05 --- /dev/null +++ b/YACReaderLibrary/organize_files/organize_files_coordinator.cpp @@ -0,0 +1,390 @@ +#include "organize_files_coordinator.h" + +#include "QsLog.h" +#include "comic_model.h" +#include "data_base_management.h" +#include "db_helper.h" +#include "folder_model.h" +#include "organize_files_dialog.h" +#include "organize_files_journal.h" +#include "yacreader_global.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +using OrganizeFiles::ComicEntry; +using OrganizeFiles::FileMove; + +namespace { + +void collectComicsRecursively(qulonglong libraryId, qulonglong folderId, QList &out) +{ + const auto comics = DBHelper::getFolderComicsFromLibrary(libraryId, folderId); + for (auto *item : comics) { + if (auto *comic = static_cast(item)) + out.append(*comic); + } + qDeleteAll(comics); + + const auto subfolders = DBHelper::getFolderSubfoldersFromLibrary(libraryId, folderId); + for (auto *item : subfolders) + collectComicsRecursively(libraryId, item->id, out); + qDeleteAll(subfolders); +} + +QList buildEntries(const QList &comics, const QString &libraryRoot) +{ + QList entries; + entries.reserve(comics.size()); + + for (const ComicDB &comic : comics) { + ComicEntry entry; + entry.comicId = comic.id; + entry.sourceAbsolute = QDir::cleanPath(libraryRoot + comic.path); + + const QFileInfo info(entry.sourceAbsolute); + entry.missing = !info.exists(); + entry.baseName = info.completeBaseName(); + entry.extension = info.suffix().isEmpty() ? QString() : QLatin1Char('.') + info.suffix(); + + entry.publisher = comic.info.publisher.toString(); + entry.imprint = comic.info.imprint.toString(); + entry.series = comic.info.series.toString(); + entry.volume = comic.info.volume.toString(); + entry.number = comic.info.number.toString(); + entry.count = comic.info.count.toString(); + entry.title = comic.info.title.toString(); + OrganizeFiles::applyPublicationDate(entry, comic.info.date.toString()); + entry.storyArc = comic.info.storyArc.toString(); + entry.arcNumber = comic.info.arcNumber.toString(); + entry.writer = comic.info.writer.toString(); + + entries.append(entry); + } + + return entries; +} + +QString libraryRelativePath(const QString &libraryRoot, const QString &absolutePath) +{ + return QLatin1Char('/') + QDir(libraryRoot).relativeFilePath(absolutePath); +} + +} + +OrganizeFilesCoordinator::OrganizeFilesCoordinator(QSettings *settings, + QWidget *window, + ComicModel *comicsModel, + FolderModel *foldersModel, + SelectionProvider selectionProvider, + CurrentFolderProvider currentFolderProvider, + CurrentLibraryProvider currentLibraryProvider) + : QObject(window), settings(settings), window(window), comicsModel(comicsModel), foldersModel(foldersModel), selectionProvider(std::move(selectionProvider)), currentFolderProvider(std::move(currentFolderProvider)), currentLibraryProvider(std::move(currentLibraryProvider)) +{ +} + +void OrganizeFilesCoordinator::renameCurrentFolder() +{ + runOnFolder(OrganizeFiles::Mode::Rename, currentFolderProvider()); +} + +void OrganizeFilesCoordinator::organizeCurrentFolder() +{ + runOnFolder(OrganizeFiles::Mode::Organize, currentFolderProvider()); +} + +void OrganizeFilesCoordinator::renameFolder(const QModelIndex &folderIndex) +{ + runOnFolder(OrganizeFiles::Mode::Rename, folderIndex); +} + +void OrganizeFilesCoordinator::organizeFolder(const QModelIndex &folderIndex) +{ + runOnFolder(OrganizeFiles::Mode::Organize, folderIndex); +} + +void OrganizeFilesCoordinator::renameSelectedComics() +{ + runOnSelectedComics(OrganizeFiles::Mode::Rename); +} + +void OrganizeFilesCoordinator::organizeSelectedComics() +{ + runOnSelectedComics(OrganizeFiles::Mode::Organize); +} + +void OrganizeFilesCoordinator::runOnFolder(OrganizeFiles::Mode mode, const QModelIndex &folderIndex) +{ + if (!folderIndex.isValid()) + return; + + const auto library = currentLibraryProvider(); + const auto folder = foldersModel->getFolder(folderIndex); + const auto folderPath = QDir::cleanPath(library.rootPath + foldersModel->getFolderPath(folderIndex)); + + QApplication::setOverrideCursor(Qt::WaitCursor); + QList comics; + collectComicsRecursively(library.id, folder.id, comics); + QApplication::restoreOverrideCursor(); + + if (comics.isEmpty()) { + QMessageBox::information(window, tr("Organize files"), tr("This folder does not contain any comics.")); + return; + } + + organizeComics(mode, comics, library.rootPath, folderPath); +} + +void OrganizeFilesCoordinator::runOnSelectedComics(OrganizeFiles::Mode mode) +{ + const auto selection = selectionProvider(); + if (selection.isEmpty()) + return; + + const auto comics = comicsModel->getComics(selection); + if (comics.isEmpty()) + return; + + const auto folderIndex = currentFolderProvider(); + const auto library = currentLibraryProvider(); + const auto folderPath = folderIndex.isValid() + ? QDir::cleanPath(library.rootPath + foldersModel->getFolderPath(folderIndex)) + : QString(); + + organizeComics(mode, comics, library.rootPath, folderPath); +} + +void OrganizeFilesCoordinator::organizeComics(OrganizeFiles::Mode mode, const QList &comics, const QString &libraryRoot, const QString &folderPath) +{ + const QString cleanLibraryRoot = QDir::cleanPath(libraryRoot); + + LibraryMaintenanceLock maintenanceLock(cleanLibraryRoot); + if (!maintenanceLock.tryLock()) { + QMessageBox::warning(window, tr("Organize files"), + tr("This library is busy: %1").arg(maintenanceLock.errorString())); + return; + } + + OrganizeFilesDialog::Context context; + context.mode = mode; + context.libraryPath = cleanLibraryRoot; + const QString cleanFolderPath = folderPath.isEmpty() ? QString() : QDir::cleanPath(folderPath); + context.folderPath = cleanFolderPath == cleanLibraryRoot ? QString() : cleanFolderPath; + context.entries = buildEntries(comics, cleanLibraryRoot); + + OrganizeFilesDialog dialog(context, settings, window); + dialog.setApplier([this, cleanLibraryRoot](const QList &moves, const QStringList &removedDirectories, const QString &journalPath, QString *error) { + return applyToDatabase(moves, removedDirectories, cleanLibraryRoot, journalPath, { }, { }, error); + }); + dialog.setUndoer([this, cleanLibraryRoot](const QString &journalPath, QList *failures, QString *error, + const std::function &fileProgress, + const std::function &databasePhase) { + return undo(journalPath, cleanLibraryRoot, failures, error, fileProgress, databasePhase); + }); + + dialog.exec(); + + if (dialog.libraryChanged()) + emit libraryContentChanged(); +} + +bool OrganizeFilesCoordinator::applyToDatabase(const QList &moves, + const QStringList &removedDirectories, + const QString &libraryRoot, + const QString &journalPath, + const QList &foldersToRestore, + const QList &createdFolderIdsToRemove, + QString *error) +{ + bool success = true; + QString connectionName; + QList removedFolders; + QList createdFolders; + + { + QSqlDatabase db = DataBaseManagement::loadDatabase(YACReader::LibraryPaths::libraryDataPath(libraryRoot)); + if (!db.isOpen()) { + *error = tr("the library database could not be opened"); + return false; + } + + connectionName = db.connectionName(); + + if (!db.transaction()) { + *error = tr("the library database could not be locked for writing"); + db = QSqlDatabase(); + QSqlDatabase::removeDatabase(connectionName); + return false; + } + + // Restored before anything is repointed, so ensureFolderPath() finds the + // original rows instead of creating new ids (covers are keyed by id). + if (!foldersToRestore.isEmpty() && !DBHelper::restoreFolderRows(foldersToRestore, db)) { + *error = tr("a folder entry could not be restored"); + success = false; + } + + if (success) { + for (const auto &move : moves) { + const QString relativePath = libraryRelativePath(libraryRoot, move.destination); + const QString relativeDirectory = relativePath.left(relativePath.lastIndexOf(QLatin1Char('/'))); + const auto parentId = DBHelper::ensureFolderPath(relativeDirectory, db, &createdFolders); + + if (!DBHelper::moveComic(move.comicId, parentId, QFileInfo(move.destination).fileName(), relativePath, db)) { + *error = tr("a comic entry could not be updated"); + success = false; + break; + } + } + } + + if (success) { + QStringList removedPaths; + for (const auto &directory : removedDirectories) + removedPaths << libraryRelativePath(libraryRoot, directory); + + DBHelper::removeEmptyFolderPaths(removedPaths, db, &removedFolders); + // Undo: drop the rows the run created that are empty again. + DBHelper::removeEmptyFolderRows(createdFolderIdsToRemove, db); + DBHelper::syncFolderAddedFromContents(createdFolders, db); + DBHelper::updateChildrenInfo(db); + + if (!db.commit()) { + *error = tr("the library database could not be saved: %1").arg(db.lastError().text()); + db.rollback(); + removedFolders.clear(); + createdFolders.clear(); + success = false; + } + } else { + db.rollback(); + } + + db = QSqlDatabase(); + } + + QSqlDatabase::removeDatabase(connectionName); + + // Written only after the transaction is on disk, so the record never claims a + // folder was deleted that is still there. + if (success && (!removedFolders.isEmpty() || !createdFolders.isEmpty()) && !journalPath.isEmpty()) { + OrganizeFiles::Journal journal(libraryRoot); + if (journal.reopen(journalPath)) { + for (const auto &row : std::as_const(removedFolders)) + journal.appendRemovedFolder(row); + for (const auto id : std::as_const(createdFolders)) + journal.appendCreatedFolder(id); + journal.finish(); + } else { + // Nothing to roll back; without this record an undo recreates the + // deleted folders with new ids and their custom covers are lost. + QLOG_ERROR() << "organize: could not reopen the journal" << journalPath + << "to record the folder rows:" << journal.errorString(); + } + } + + return success; +} + +bool OrganizeFilesCoordinator::undo(const QString &journalPath, + const QString &libraryRoot, + QList *failures, + QString *error, + const std::function &fileProgress, + const std::function &databasePhase) +{ + OrganizeFiles::JournalData data; + if (!OrganizeFiles::Journal::read(libraryRoot, journalPath, &data)) { + *error = tr("the record of the last organize run could not be read"); + return false; + } + + QList restored; + + const int total = data.moves.size(); + int done = 0; + + for (int i = data.moves.size() - 1; i >= 0; --i) { + const auto &journalMove = data.moves.at(i); + + FileMove move; + move.comicId = journalMove.comicId; + move.source = OrganizeFiles::absoluteFromRelative(libraryRoot, journalMove.to); + move.destination = OrganizeFiles::absoluteFromRelative(libraryRoot, journalMove.from); + + fileProgress(++done, total, QDir(libraryRoot).relativeFilePath(move.destination)); + + // An earlier attempt already put this one back. Repoint the row again + // anyway, because that attempt may have failed after the file had moved. + const bool alreadyBack = !QFileInfo::exists(move.source) && QFileInfo::exists(move.destination); + + if (!alreadyBack) { + if (!QDir().mkpath(QFileInfo(move.destination).absolutePath())) { + failures->append({ move.source, tr("the folder %1 could not be created").arg(QDir::toNativeSeparators(QFileInfo(move.destination).absolutePath())) }); + continue; + } + + QString reason; + if (!OrganizeFiles::moveFile(move.source, move.destination, &reason)) { + failures->append({ move.source, reason }); + continue; + } + } + + restored.append(move); + } + + // A cycle in the plan was broken with a temporary name, so the journal holds two + // steps for one comic. Only the last step undone carries the original path. + QHash lastStepForComic; + for (int i = 0; i < restored.size(); ++i) + lastStepForComic.insert(restored.at(i).comicId, i); + + QList collapsed; + collapsed.reserve(restored.size()); + for (int i = 0; i < restored.size(); ++i) { + if (lastStepForComic.value(restored.at(i).comicId) == i) + collapsed.append(restored.at(i)); + } + + // Only the directories the run created; one it merely filled is not the undo's + // to delete, even when the undo leaves it empty. + QStringList createdDirectories; + for (const auto &relative : std::as_const(data.createdDirectories)) + createdDirectories << OrganizeFiles::absoluteFromRelative(libraryRoot, relative); + + const auto removedDirectories = OrganizeFiles::removeCreatedDirectories(createdDirectories); + + // Recorded parents first; reversed, a created branch deletes bottom-up. + QList createdFolderIds = data.createdFolders; + std::reverse(createdFolderIds.begin(), createdFolderIds.end()); + + if (!collapsed.isEmpty() || !data.removedFolders.isEmpty() || !createdFolderIds.isEmpty()) { + databasePhase(); + if (!applyToDatabase(collapsed, removedDirectories, libraryRoot, QString(), data.removedFolders, createdFolderIds, error)) + return false; + } + + // The journal is deleted only when every file is back; otherwise the user + // keeps a way to try again. + if (!failures->isEmpty()) { + *error = tr("%n file(s) could not be moved back", "", failures->size()); + return false; + } + + QFile::remove(journalPath); + + return true; +} diff --git a/YACReaderLibrary/organize_files/organize_files_coordinator.h b/YACReaderLibrary/organize_files/organize_files_coordinator.h new file mode 100644 index 000000000..9e3db2617 --- /dev/null +++ b/YACReaderLibrary/organize_files/organize_files_coordinator.h @@ -0,0 +1,79 @@ +#ifndef ORGANIZE_FILES_COORDINATOR_H +#define ORGANIZE_FILES_COORDINATOR_H + +#include "comic_db.h" +#include "organize_files_worker.h" + +#include +#include +#include + +#include + +class ComicModel; +class FolderModel; +class QSettings; +class QWidget; + +class OrganizeFilesCoordinator : public QObject +{ + Q_OBJECT +public: + struct LibraryContext { + qulonglong id; + QString rootPath; + }; + + using SelectionProvider = std::function; + using CurrentFolderProvider = std::function; + using CurrentLibraryProvider = std::function; + + explicit OrganizeFilesCoordinator(QSettings *settings, + QWidget *window, + ComicModel *comicsModel, + FolderModel *foldersModel, + SelectionProvider selectionProvider, + CurrentFolderProvider currentFolderProvider, + CurrentLibraryProvider currentLibraryProvider); + +public slots: + void renameCurrentFolder(); + void organizeCurrentFolder(); + void renameFolder(const QModelIndex &folderIndex); + void organizeFolder(const QModelIndex &folderIndex); + void renameSelectedComics(); + void organizeSelectedComics(); + +signals: + void libraryContentChanged(); + +private: + void runOnFolder(OrganizeFiles::Mode mode, const QModelIndex &folderIndex); + void runOnSelectedComics(OrganizeFiles::Mode mode); + void organizeComics(OrganizeFiles::Mode mode, const QList &comics, const QString &libraryRoot, const QString &folderPath); + + bool applyToDatabase(const QList &moves, + const QStringList &removedDirectories, + const QString &libraryRoot, + const QString &journalPath, + const QList &foldersToRestore, + const QList &createdFolderIdsToRemove, + QString *error); + // Runs on a worker thread; must not touch the GUI. + bool undo(const QString &journalPath, + const QString &libraryRoot, + QList *failures, + QString *error, + const std::function &fileProgress, + const std::function &databasePhase); + + QSettings *settings; + QWidget *window; + ComicModel *comicsModel; + FolderModel *foldersModel; + SelectionProvider selectionProvider; + CurrentFolderProvider currentFolderProvider; + CurrentLibraryProvider currentLibraryProvider; +}; + +#endif // ORGANIZE_FILES_COORDINATOR_H diff --git a/YACReaderLibrary/organize_files/organize_files_dialog.cpp b/YACReaderLibrary/organize_files/organize_files_dialog.cpp new file mode 100644 index 000000000..d46da33a4 --- /dev/null +++ b/YACReaderLibrary/organize_files/organize_files_dialog.cpp @@ -0,0 +1,1435 @@ +#include "organize_files_dialog.h" + +#include "organize_files_journal.h" +#include "yacreader_busy_widget.h" +#include "yacreader_global.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +using OrganizeFiles::ComicEntry; +using OrganizeFiles::FileFailure; +using OrganizeFiles::FileMove; +using OrganizeFiles::PlannedMove; + +namespace { + +constexpr int SourceRole = Qt::UserRole + 1; +constexpr int ExtensionRole = Qt::UserRole + 2; +// The path a folder row had before the user renamed it. The new path is read off +// the tree, and the old one is needed to find the moves the rename applies to. +constexpr int FolderPathRole = Qt::UserRole + 3; + +// The format field is typed into, so it waits for a pause. Every other input is a +// single discrete act, so it rebuilds on the next turn of the event loop. +constexpr int PatternDebounceMs = 300; +constexpr int ImmediateMs = 0; + +constexpr int LoadingPage = 0; +constexpr int PlanPage = 1; +constexpr int WorkingPage = 2; +constexpr int ResultPage = 3; + +class SegmentEditDelegate : public QStyledItemDelegate +{ +public: + using QStyledItemDelegate::QStyledItemDelegate; + + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override + { + if (index.column() != 0) + return nullptr; + return QStyledItemDelegate::createEditor(parent, option, index); + } + + void setEditorData(QWidget *editor, const QModelIndex &index) const override + { + auto *lineEdit = qobject_cast(editor); + if (lineEdit == nullptr) { + QStyledItemDelegate::setEditorData(editor, index); + return; + } + + QString text = index.data(Qt::EditRole).toString(); + const QString extension = index.data(ExtensionRole).toString(); + if (!extension.isEmpty() && text.endsWith(extension)) + text.chop(extension.size()); + + lineEdit->setText(text); + } + + void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override + { + auto *lineEdit = qobject_cast(editor); + if (lineEdit == nullptr) { + QStyledItemDelegate::setModelData(editor, model, index); + return; + } + + const QString name = OrganizeFiles::sanitizeSegment(lineEdit->text()); + if (name.isEmpty()) + return; + + model->setData(index, name + index.data(ExtensionRole).toString(), Qt::EditRole); + } +}; + +// Qt has no segmented control: two checkable buttons with the border between them +// collapsed. Colours come from the palette, which is what the theme system drives. +QString segmentedStyleSheet() +{ + return QStringLiteral( + "QPushButton {" + " border: 1px solid palette(mid);" + " padding: 4px 14px;" + " background-color: palette(button);" + " color: palette(button-text);" + "}" + "QPushButton:hover { background-color: palette(midlight); }" + "QPushButton:checked {" + " background-color: palette(highlight);" + " color: palette(highlighted-text);" + " border-color: palette(highlight);" + "}" + "QPushButton#organizeBaseLeft {" + " border-top-left-radius: 4px;" + " border-bottom-left-radius: 4px;" + " border-right: none;" + "}" + "QPushButton#organizeBaseRight {" + " border-top-right-radius: 4px;" + " border-bottom-right-radius: 4px;" + "}"); +} + +bool isExecutable(PlannedMove::Status status) +{ + return status == PlannedMove::Status::Move || status == PlannedMove::Status::Renamed || status == PlannedMove::Status::Incomplete; +} + +} + +OrganizeFilesDialog::OrganizeFilesDialog(const Context &context, QSettings *settings, QWidget *parent) + : QDialog(parent), context(context), settings(settings), planThread(nullptr), planWorker(nullptr), moveThread(nullptr), moveWorker(nullptr), undoThread(nullptr), undoWorker(nullptr), generation(0), updatingTree(false), changedLibrary(false), patternIsValid(true), moveRunning(false), undoRunning(false), planIsStale(true) +{ + qRegisterMetaType>(); + qRegisterMetaType(); + + setupPages(); + setupPlanWorker(); + + setModal(true); + setWindowTitle(renaming() ? tr("Rename files") : tr("Organize files")); + resize(760, 560); + + pages->setCurrentIndex(LoadingPage); + updateBasePathLabel(); + startBuild(); +} + +OrganizeFilesDialog::~OrganizeFilesDialog() +{ + if (planThread != nullptr) { + planThread->quit(); + planThread->wait(); + delete planWorker; + planWorker = nullptr; + } + + if (moveThread != nullptr) { + moveThread->quit(); + moveThread->wait(); + delete moveWorker; + moveWorker = nullptr; + } + + if (undoThread != nullptr) { + undoThread->quit(); + undoThread->wait(); + delete undoWorker; + undoWorker = nullptr; + } +} + +void OrganizeFilesDialog::setApplier(Applier applier) +{ + this->applier = std::move(applier); +} + +void OrganizeFilesDialog::setUndoer(Undoer undoer) +{ + this->undoer = std::move(undoer); +} + +bool OrganizeFilesDialog::libraryChanged() const +{ + return changedLibrary; +} + +void OrganizeFilesDialog::setupPages() +{ + pages = new QStackedWidget; + pages->addWidget(createLoadingPage()); + pages->addWidget(createPlanPage()); + pages->addWidget(createWorkingPage()); + pages->addWidget(createResultPage()); + + auto layout = new QVBoxLayout; + layout->addWidget(pages); + setLayout(layout); +} + +QWidget *OrganizeFilesDialog::createLoadingPage() +{ + auto page = new QWidget; + auto layout = new QVBoxLayout; + + loadingLabel = new QLabel(tr("Preparing the preview...")); + loadingLabel->setAlignment(Qt::AlignHCenter); + + layout->addStretch(); + layout->addWidget(new YACReaderBusyWidget, 0, Qt::AlignHCenter); + layout->addSpacing(12); + layout->addWidget(loadingLabel); + layout->addStretch(); + + page->setLayout(layout); + return page; +} + +QWidget *OrganizeFilesDialog::createPlanPage() +{ + auto page = new QWidget; + auto layout = new QVBoxLayout; + + const QString patternKey = renaming() ? QStringLiteral(ORGANIZE_FILES_FILENAME_PATTERN) : QStringLiteral(ORGANIZE_FILES_PATH_PATTERN); + const QString fallbackPattern = OrganizeFiles::defaultPattern(context.mode); + + auto formatLabel = new QLabel(renaming() ? tr("&Filename format:") : tr("&Path format:")); + patternEdit = new QLineEdit(settings != nullptr ? settings->value(patternKey, fallbackPattern).toString() : fallbackPattern); + patternEdit->setAccessibleName(renaming() ? tr("Filename format") : tr("Path format")); + formatLabel->setBuddy(patternEdit); + connect(patternEdit, &QLineEdit::textChanged, this, &OrganizeFilesDialog::patternEdited); + + auto presetsButton = new QPushButton(tr("Presets")); + presetsButton->setAutoDefault(false); + presetsMenu = new QMenu(presetsButton); + presetsButton->setMenu(presetsMenu); + rebuildPresetsMenu(); + + auto insertButton = new QPushButton(tr("Insert")); + insertButton->setAutoDefault(false); + auto insertMenu = new QMenu(insertButton); + + const auto tokens = OrganizeFiles::knownTokens(); + for (const QString &token : tokens) { + auto action = insertMenu->addAction(QStringLiteral("{") + token + QStringLiteral("}")); + connect(action, &QAction::triggered, this, [this, token] { + patternEdit->insert(QStringLiteral("{") + token + QStringLiteral("}")); + patternEdit->setFocus(); + }); + } + + insertMenu->addSeparator(); + + auto optionalAction = insertMenu->addAction(tr("Optional part < >")); + optionalAction->setToolTip(tr("Disappears completely when the fields inside it are empty.")); + connect(optionalAction, &QAction::triggered, this, &OrganizeFilesDialog::wrapSelectionInOptionalGroup); + + auto paddedAction = insertMenu->addAction(tr("Padded number {number:000}")); + connect(paddedAction, &QAction::triggered, this, [this] { + patternEdit->insert(QStringLiteral("{number:000}")); + patternEdit->setFocus(); + }); + + insertMenu->addSeparator(); + connect(insertMenu->addAction(tr("Format help...")), &QAction::triggered, this, &OrganizeFilesDialog::showFormatHelp); + + insertButton->setMenu(insertMenu); + + auto formatRow = new QHBoxLayout; + formatRow->addWidget(formatLabel); + formatRow->addWidget(patternEdit, 1); + formatRow->addWidget(insertButton); + formatRow->addWidget(presetsButton); + + patternError = new QLabel; + patternError->setWordWrap(true); + patternError->setVisible(false); + + folderBaseButton = new QPushButton(tr("selected folder")); + folderBaseButton->setObjectName(QStringLiteral("organizeBaseLeft")); + folderBaseButton->setToolTip(QDir::toNativeSeparators(context.folderPath)); + + rootBaseButton = new QPushButton(tr("library root")); + rootBaseButton->setObjectName(QStringLiteral("organizeBaseRight")); + rootBaseButton->setToolTip(QDir::toNativeSeparators(context.libraryPath)); + + auto baseButtons = new QButtonGroup(this); + baseButtons->setExclusive(true); + for (auto *segment : { folderBaseButton, rootBaseButton }) { + segment->setCheckable(true); + // A QPushButton inside a QDialog claims the default-button role, which + // would let Return trigger a setting instead of Move files. + segment->setAutoDefault(false); + baseButtons->addButton(segment); + } + + baseSelector = new QWidget; + auto segmented = new QHBoxLayout(baseSelector); + segmented->setSpacing(0); + segmented->setContentsMargins(0, 0, 0, 0); + segmented->addWidget(folderBaseButton); + segmented->addWidget(rootBaseButton); + baseSelector->setStyleSheet(segmentedStyleSheet()); + + basePathLabel = new QLabel; + basePathLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); + basePathLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); + + if (context.folderPath.isEmpty()) { + baseSelector->setVisible(false); + rootBaseButton->setChecked(true); + } else { + const bool relativeToRoot = settings != nullptr ? settings->value(ORGANIZE_FILES_RELATIVE_TO_ROOT, true).toBool() : true; + rootBaseButton->setChecked(relativeToRoot); + folderBaseButton->setChecked(!relativeToRoot); + // One click, not a stream of keystrokes, so there is nothing to wait for. + connect(rootBaseButton, &QPushButton::toggled, this, [this] { + updateBasePathLabel(); + markPlanStale(ImmediateMs); + }); + } + + auto baseRow = new QHBoxLayout; + baseRow->addWidget(new QLabel(tr("Move into"))); + baseRow->addSpacing(8); + baseRow->addWidget(baseSelector); + baseRow->addSpacing(12); + baseRow->addWidget(basePathLabel, 1); + + overridesBanner = new QLabel; + overridesBanner->setVisible(false); + + resetButton = new QPushButton(tr("Reset changes")); + resetButton->setVisible(false); + connect(resetButton, &QPushButton::clicked, this, &OrganizeFilesDialog::resetOverrides); + + removeButton = new QPushButton(tr("Remove selected")); + removeButton->setEnabled(false); + connect(removeButton, &QPushButton::clicked, this, &OrganizeFilesDialog::removeSelectedItems); + + showUnchangedCheck = new QCheckBox(tr("Show unchanged")); + if (settings != nullptr) + showUnchangedCheck->setChecked(settings->value(ORGANIZE_FILES_SHOW_UNCHANGED, false).toBool()); + connect(showUnchangedCheck, &QCheckBox::toggled, this, [this] { + rebuildTree(); + updateStatusLine(); + }); + + auto toolbar = new QHBoxLayout; + toolbar->addWidget(removeButton); + toolbar->addWidget(showUnchangedCheck); + toolbar->addStretch(); + toolbar->addWidget(overridesBanner); + toolbar->addWidget(resetButton); + + tree = new QTreeWidget; + tree->setColumnCount(3); + // The second header carries the verb: two neutral nouns side by side never say + // which way the change runs. + tree->setHeaderLabels(renaming() ? QStringList { tr("New name"), tr("Renamed from"), QString() } + : QStringList { tr("New location"), tr("Moved from"), QString() }); + tree->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed); + tree->setItemDelegate(new SegmentEditDelegate(tree)); + tree->setUniformRowHeights(true); + tree->setAlternatingRowColors(true); + tree->setSelectionMode(QAbstractItemView::ExtendedSelection); + tree->header()->setStretchLastSection(false); + tree->header()->setSectionResizeMode(1, QHeaderView::Stretch); + tree->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents); + connect(tree, &QTreeWidget::itemChanged, this, &OrganizeFilesDialog::itemChanged); + connect(tree, &QTreeWidget::itemSelectionChanged, this, &OrganizeFilesDialog::updateSelectionState); + + auto removeAction = new QAction(tr("Remove from list"), this); + removeAction->setShortcut(QKeySequence::Delete); + removeAction->setShortcutContext(Qt::WidgetShortcut); + connect(removeAction, &QAction::triggered, this, &OrganizeFilesDialog::removeSelectedItems); + tree->addAction(removeAction); + tree->setContextMenuPolicy(Qt::ActionsContextMenu); + + statusLabel = new QLabel; + warningLabel = new QLabel; + warningLabel->setWordWrap(true); + + moveButton = new QPushButton(renaming() ? tr("Rename files") : tr("Move files")); + moveButton->setDefault(true); + connect(moveButton, &QPushButton::clicked, this, &OrganizeFilesDialog::startMove); + + cancelButton = new QPushButton(tr("Cancel")); + connect(cancelButton, &QPushButton::clicked, this, &QDialog::reject); + + auto buttons = new QHBoxLayout; + buttons->addWidget(statusLabel); + buttons->addStretch(); + buttons->addWidget(moveButton); + buttons->addWidget(cancelButton); + + layout->addLayout(formatRow); + layout->addWidget(patternError); + if (!renaming()) + layout->addLayout(baseRow); + layout->addLayout(toolbar); + layout->addWidget(tree, 1); + layout->addWidget(warningLabel); + layout->addLayout(buttons); + + page->setLayout(layout); + return page; +} + +QWidget *OrganizeFilesDialog::createWorkingPage() +{ + auto page = new QWidget; + auto layout = new QVBoxLayout; + + progressBar = new QProgressBar; + progressLabel = new QLabel; + progressLabel->setWordWrap(true); + progressLabel->setAlignment(Qt::AlignHCenter); + + layout->addStretch(); + layout->addWidget(progressBar); + layout->addWidget(progressLabel); + layout->addStretch(); + + page->setLayout(layout); + return page; +} + +QWidget *OrganizeFilesDialog::createResultPage() +{ + auto page = new QWidget; + auto layout = new QVBoxLayout; + + resultLabel = new QLabel; + resultLabel->setWordWrap(true); + resultLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); + resultLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); + + resultTree = new QTreeWidget; + resultTree->setColumnCount(3); + resultTree->setRootIsDecorated(false); + resultTree->setUniformRowHeights(true); + resultTree->setAlternatingRowColors(true); + resultTree->setEditTriggers(QAbstractItemView::NoEditTriggers); + resultTree->setSelectionMode(QAbstractItemView::ExtendedSelection); + resultTree->header()->setSectionResizeMode(QHeaderView::Interactive); + resultTree->header()->setStretchLastSection(true); + resultTree->setVisible(false); + + failureList = new QListWidget; + failureList->setVisible(false); + + copyFailuresButton = new QPushButton(tr("Copy failure details")); + copyFailuresButton->setVisible(false); + connect(copyFailuresButton, &QPushButton::clicked, this, &OrganizeFilesDialog::copyFailures); + + undoButton = new QPushButton(tr("Undo")); + connect(undoButton, &QPushButton::clicked, this, &OrganizeFilesDialog::undo); + + finishButton = new QPushButton(tr("Finish")); + finishButton->setDefault(true); + connect(finishButton, &QPushButton::clicked, this, &QDialog::accept); + + auto buttons = new QHBoxLayout; + buttons->addWidget(copyFailuresButton); + buttons->addStretch(); + buttons->addWidget(undoButton); + buttons->addWidget(finishButton); + + layout->addWidget(resultLabel); + layout->addWidget(resultTree, 1); + layout->addWidget(failureList, 1); + layout->addLayout(buttons); + + page->setLayout(layout); + return page; +} + +void OrganizeFilesDialog::setupPlanWorker() +{ + planThread = new QThread(this); + planWorker = new OrganizeFiles::PlanWorker(context.entries, currentBase(), context.mode); + planWorker->moveToThread(planThread); + + connect(this, &OrganizeFilesDialog::buildRequested, planWorker, &OrganizeFiles::PlanWorker::build); + connect(planWorker, &OrganizeFiles::PlanWorker::built, this, &OrganizeFilesDialog::planBuilt); + + planThread->start(); + + buildTimer = new QTimer(this); + buildTimer->setSingleShot(true); + connect(buildTimer, &QTimer::timeout, this, &OrganizeFilesDialog::startBuild); +} + +void OrganizeFilesDialog::markPlanStale(int delayMs) +{ + planIsStale = true; + + // Dead before the click that follows the interaction is delivered — committing + // a tree editor by clicking Move files must not run the pre-edit plan. + moveButton->setEnabled(false); + + // QTimer::start(int) also sets the interval, so the delay is always passed. + buildTimer->start(delayMs); +} + +bool OrganizeFilesDialog::renaming() const +{ + return context.mode == OrganizeFiles::Mode::Rename; +} + +QString OrganizeFilesDialog::currentBase() const +{ + if (renaming()) + return context.libraryPath; + + if (context.folderPath.isEmpty() || rootBaseButton == nullptr || rootBaseButton->isChecked()) + return context.libraryPath; + + return context.folderPath; +} + +void OrganizeFilesDialog::updateBasePathLabel() +{ + const QString path = QDir::toNativeSeparators(currentBase()); + + basePathLabel->setToolTip(path); + basePathLabel->setText(basePathLabel->fontMetrics().elidedText(path, Qt::ElideMiddle, qMax(120, basePathLabel->width()))); +} + +QString OrganizeFilesDialog::presetsKey() const +{ + return renaming() ? QStringLiteral(ORGANIZE_FILES_FILENAME_PRESETS) : QStringLiteral(ORGANIZE_FILES_PATH_PRESETS); +} + +QList> OrganizeFilesDialog::userPresets() const +{ + QList> presets; + if (settings == nullptr) + return presets; + + const int size = settings->beginReadArray(presetsKey()); + for (int i = 0; i < size; ++i) { + settings->setArrayIndex(i); + const QString name = settings->value(QStringLiteral("name")).toString(); + const QString pattern = settings->value(QStringLiteral("pattern")).toString(); + if (!name.isEmpty() && !pattern.isEmpty()) + presets.append({ name, pattern }); + } + settings->endArray(); + + return presets; +} + +void OrganizeFilesDialog::saveUserPresets(const QList> &presets) +{ + if (settings == nullptr) + return; + + settings->remove(presetsKey()); + settings->beginWriteArray(presetsKey()); + for (int i = 0; i < presets.size(); ++i) { + settings->setArrayIndex(i); + settings->setValue(QStringLiteral("name"), presets.at(i).first); + settings->setValue(QStringLiteral("pattern"), presets.at(i).second); + } + settings->endArray(); +} + +void OrganizeFilesDialog::rebuildPresetsMenu() +{ + presetsMenu->clear(); + + const auto addPattern = [this](const QString &name, const QString &pattern) { + auto action = presetsMenu->addAction(name); + connect(action, &QAction::triggered, this, [this, pattern] { patternEdit->setText(pattern); }); + }; + + const auto custom = userPresets(); + for (const auto &preset : custom) + addPattern(preset.first, preset.second); + + if (!custom.isEmpty()) { + auto removeMenu = presetsMenu->addMenu(tr("Remove preset")); + for (const auto &preset : custom) { + const QString name = preset.first; + connect(removeMenu->addAction(name), &QAction::triggered, this, [this, name] { + auto presets = userPresets(); + presets.removeIf([&name](const QPair &preset) { return preset.first == name; }); + saveUserPresets(presets); + rebuildPresetsMenu(); + }); + } + presetsMenu->addSeparator(); + } + + const auto builtIn = OrganizeFiles::presets(context.mode); + for (const auto &preset : builtIn) + addPattern(preset.first, preset.second); + + presetsMenu->addSeparator(); + + auto saveAction = presetsMenu->addAction(tr("Save current format as preset...")); + saveAction->setEnabled(settings != nullptr); + connect(saveAction, &QAction::triggered, this, &OrganizeFilesDialog::saveCurrentPatternAsPreset); + + const QString fallback = OrganizeFiles::defaultPattern(context.mode); + connect(presetsMenu->addAction(tr("Reset to default format")), &QAction::triggered, this, [this, fallback] { patternEdit->setText(fallback); }); +} + +void OrganizeFilesDialog::saveCurrentPatternAsPreset() +{ + bool accepted = false; + const QString name = QInputDialog::getText(this, tr("Save preset"), tr("Preset name:"), QLineEdit::Normal, QString(), &accepted).trimmed(); + if (!accepted || name.isEmpty()) + return; + + auto presets = userPresets(); + presets.removeIf([&name](const QPair &preset) { return preset.first == name; }); + presets.append({ name, patternEdit->text() }); + saveUserPresets(presets); + rebuildPresetsMenu(); +} + +void OrganizeFilesDialog::patternEdited() +{ + const auto invalid = OrganizeFiles::invalidTokens(patternEdit->text()); + + const bool createsFolders = renaming() && OrganizeFiles::patternCreatesFolders(patternEdit->text()); + patternIsValid = invalid.isEmpty() && !createsFolders; + + if (!patternIsValid) { + if (createsFolders) + patternError->setText(tr("A filename format cannot contain \"/\". Use Organize files to move comics into folders.")); + else + patternError->setText(tr("This format cannot be used: %1").arg(invalid.join(QStringLiteral(" ")))); + patternError->setVisible(true); + moveButton->setEnabled(false); + // Bumping the generation drops a build still in flight, so it cannot land + // and report itself current while the format on screen is invalid. + planIsStale = true; + ++generation; + buildTimer->stop(); + return; + } + + patternError->setVisible(false); + scheduleBuild(); +} + +void OrganizeFilesDialog::scheduleBuild() +{ + markPlanStale(PatternDebounceMs); +} + +void OrganizeFilesDialog::startBuild() +{ + buildTimer->stop(); + emit buildRequested(patternEdit->text(), currentBase(), overrides, ++generation); +} + +void OrganizeFilesDialog::planBuilt(const QList &moves, quint64 buildGeneration) +{ + // An older build finishing after a newer one was asked for; the newer result + // is still on its way. + if (buildGeneration != generation) + return; + + // The user interacted again while this build was in flight (the timer has not + // fired yet, so the generation still matches). The pending rebuild covers it. + if (buildTimer->isActive()) + return; + + plan = moves; + planIsStale = false; + + planDestinations.clear(); + for (const auto &move : std::as_const(plan)) + planDestinations.insert(move.sourceAbsolute, move.destinationRelative); + + rebuildTree(); + updateStatusLine(); + + if (pages->currentIndex() == LoadingPage) + pages->setCurrentIndex(PlanPage); +} + +bool OrganizeFilesDialog::isFileItem(QTreeWidgetItem *item) const +{ + return item != nullptr && item->data(0, SourceRole).isValid(); +} + +void OrganizeFilesDialog::collectFileItems(QTreeWidgetItem *item, QList &out) const +{ + if (isFileItem(item)) { + out.append(item); + return; + } + + for (int i = 0; i < item->childCount(); ++i) + collectFileItems(item->child(i), out); +} + +QString OrganizeFilesDialog::relativePathForItem(QTreeWidgetItem *item) const +{ + QStringList segments; + for (QTreeWidgetItem *node = item; node != nullptr; node = node->parent()) { + const QString clean = OrganizeFiles::sanitizeSegment(node->text(0)); + if (!clean.isEmpty()) + segments.prepend(clean); + } + + return segments.join(QLatin1Char('/')); +} + +void OrganizeFilesDialog::rebuildTree() +{ + updatingTree = true; + + tree->clear(); + newFolderCount = 0; + + const QDir libraryDir(context.libraryPath); + const QString base = currentBase(); + const bool showUnchanged = showUnchangedCheck->isChecked(); + + const QColor mutedColor = tree->palette().color(QPalette::Disabled, QPalette::Text); + const bool dark = tree->palette().color(QPalette::Base).lightness() < 128; + const QColor warningColor = dark ? QColor(0xE0, 0xA0, 0x30) : QColor(0xB2, 0x6B, 0x00); + const QColor errorColor = dark ? QColor(0xE0, 0x6C, 0x5A) : QColor(0xC0, 0x39, 0x2B); + + QFont statusFont = QFontDatabase::systemFont(QFontDatabase::FixedFont); + statusFont.setPointSize(tree->font().pointSize()); + + const auto setStatus = [&](QTreeWidgetItem *item, const QString &glyph, const QString &text, const QColor &color) { + item->setText(2, glyph.isEmpty() ? text : glyph + QLatin1Char(' ') + text); + item->setForeground(2, color); + item->setFont(2, statusFont); + item->setTextAlignment(2, Qt::AlignRight | Qt::AlignVCenter); + }; + + QList visible; + for (const auto &move : std::as_const(plan)) { + if (move.status == PlannedMove::Status::Excluded) + continue; + if (move.status == PlannedMove::Status::Unchanged && !showUnchanged) + continue; + visible.append(move); + } + + std::sort(visible.begin(), visible.end(), [](const PlannedMove &a, const PlannedMove &b) { + return a.destinationRelative.compare(b.destinationRelative, Qt::CaseInsensitive) < 0; + }); + + QHash folders; + + for (const auto &move : std::as_const(visible)) { + const auto segments = move.destinationRelative.split(QLatin1Char('/'), Qt::SkipEmptyParts); + if (segments.isEmpty()) + continue; + + QTreeWidgetItem *parent = nullptr; + QString cumulative; + for (int i = 0; i < segments.size() - 1; ++i) { + cumulative += (cumulative.isEmpty() ? QString() : QStringLiteral("/")) + segments.at(i); + + QTreeWidgetItem *&folderItem = folders[cumulative]; + if (folderItem == nullptr) { + folderItem = parent != nullptr ? new QTreeWidgetItem(parent) : new QTreeWidgetItem(tree); + folderItem->setText(0, segments.at(i)); + folderItem->setData(0, FolderPathRole, cumulative); + + QFont folderFont = folderItem->font(0); + folderFont.setBold(true); + folderItem->setFont(0, folderFont); + + if (!renaming()) { + folderItem->setFlags(folderItem->flags() | Qt::ItemIsEditable); + + const QString absolute = base + QLatin1Char('/') + cumulative; + auto known = folderExistsCache.find(absolute); + if (known == folderExistsCache.end()) + known = folderExistsCache.insert(absolute, QDir(absolute).exists()); + + if (!known.value()) { + newFolderCount++; + setStatus(folderItem, QString(), tr("new folder"), mutedColor); + folderItem->setToolTip(2, tr("This folder does not exist yet. It will be created.")); + } + } + } + parent = folderItem; + } + + auto fileItem = parent != nullptr ? new QTreeWidgetItem(parent) : new QTreeWidgetItem(tree); + fileItem->setText(0, segments.last()); + fileItem->setData(0, SourceRole, move.sourceAbsolute); + fileItem->setData(0, ExtensionRole, QFileInfo(segments.last()).suffix().isEmpty() ? QString() : QLatin1Char('.') + QFileInfo(segments.last()).suffix()); + + // In rename mode the folder part is identical on both sides, so printing + // the whole path again would only repeat the tree above it. + fileItem->setText(1, renaming() ? QFileInfo(move.sourceAbsolute).fileName() : libraryDir.relativeFilePath(move.sourceAbsolute)); + fileItem->setForeground(1, mutedColor); + fileItem->setToolTip(1, QDir::toNativeSeparators(move.sourceAbsolute)); + + if (!move.note.isEmpty()) + fileItem->setToolTip(2, move.note); + + // Only the exceptions are marked. A row with no marker is the normal case, + // and marking that too would bury the rows that need attention. + switch (move.status) { + case PlannedMove::Status::Missing: + setStatus(fileItem, QStringLiteral("x"), tr("file not found"), errorColor); + fileItem->setToolTip(2, tr("This comic is in the library but not on disk. It is skipped.")); + fileItem->setDisabled(true); + break; + case PlannedMove::Status::Renamed: + setStatus(fileItem, QStringLiteral("!"), tr("name in use"), warningColor); + break; + case PlannedMove::Status::Incomplete: + setStatus(fileItem, QStringLiteral("?"), tr("no metadata"), warningColor); + break; + case PlannedMove::Status::Unchanged: + setStatus(fileItem, QStringLiteral("="), tr("already here"), mutedColor); + fileItem->setToolTip(2, tr("This file is already in the right place.")); + break; + default: + if (move.edited) + setStatus(fileItem, QString(), tr("edited"), mutedColor); + break; + } + + if (move.status != PlannedMove::Status::Missing) + fileItem->setFlags(fileItem->flags() | Qt::ItemIsEditable); + } + + tree->expandAll(); + tree->resizeColumnToContents(0); + + // A deeply indented file name sitting flush against a flat path reads as one + // string, so the first column keeps a gutter and never eats the second one. + const int viewportWidth = tree->viewport()->width(); + const int widest = viewportWidth > 0 ? viewportWidth * 3 / 5 : 420; + tree->setColumnWidth(0, qMin(tree->columnWidth(0) + 56, widest)); + + updatingTree = false; + + updateSelectionState(); +} + +void OrganizeFilesDialog::updateStatusLine() +{ + int willMove = 0; + int unchanged = 0; + int renamed = 0; + int excluded = 0; + int missing = 0; + + for (const auto &move : std::as_const(plan)) { + switch (move.status) { + case PlannedMove::Status::Unchanged: + unchanged++; + break; + case PlannedMove::Status::Excluded: + excluded++; + break; + case PlannedMove::Status::Missing: + missing++; + break; + case PlannedMove::Status::Renamed: + renamed++; + willMove++; + break; + default: + willMove++; + break; + } + } + + QStringList parts; + parts << (renaming() ? tr("%n will be renamed", "", willMove) : tr("%n will move", "", willMove)); + parts << tr("%n unchanged", "", unchanged); + if (renamed > 0) + parts << tr("%n renamed", "", renamed); + if (excluded > 0) + parts << tr("%n removed", "", excluded); + if (missing > 0) + parts << tr("%n missing", "", missing); + if (newFolderCount > 0) + parts << tr("%n new folder(s)", "", newFolderCount); + + statusLabel->setText(parts.join(QStringLiteral(" · "))); + + const bool hasOverrides = !overrides.isEmpty(); + overridesBanner->setText(tr("%n manual change(s) kept", "", overrides.size())); + overridesBanner->setVisible(hasOverrides); + resetButton->setVisible(hasOverrides); + + if (willMove == 0) { + warningLabel->setText(renaming() ? tr("Nothing would be renamed with this format.") + : tr("Nothing would move with this format.")); + } else if (renaming()) { + warningLabel->setText(tr("%n file(s) will be renamed. The folders do not change. You can undo it afterwards.", "", willMove)); + } else { + warningLabel->setText(tr("%n file(s) will move into %1. This changes your files on disk. You can undo it afterwards.", "", willMove) + .arg(QDir::toNativeSeparators(currentBase()))); + } + + // planIsStale keeps the button off while a rebuild is pending or in flight: + // the tree on screen is the plan from before the last interaction. + moveButton->setEnabled(willMove > 0 && patternIsValid && !moveRunning && !planIsStale); +} + +void OrganizeFilesDialog::updateSelectionState() +{ + removeButton->setEnabled(!tree->selectedItems().isEmpty()); +} + +void OrganizeFilesDialog::itemChanged(QTreeWidgetItem *item, int column) +{ + if (updatingTree || column != 0) + return; + + captureOverrides(item); + + // The item delegate is still closing its editor over this item, so the tree + // cannot be rebuilt before the event loop comes back around. + markPlanStale(ImmediateMs); +} + +void OrganizeFilesDialog::captureOverrides(QTreeWidgetItem *item) +{ + if (isFileItem(item)) { + const QString source = item->data(0, SourceRole).toString(); + const QString path = relativePathForItem(item); + + if (!path.isEmpty() && path != planDestinations.value(source)) + overrides[source].destinationRelative = path; + + return; + } + + // A folder rename is applied to the plan, not read off the tree: "Show + // unchanged" hides rows that belong to the folder just as much. + const QString oldPath = item->data(0, FolderPathRole).toString(); + const QString newPath = relativePathForItem(item); + + if (oldPath.isEmpty() || newPath.isEmpty() || oldPath == newPath) + return; + + const QString prefix = oldPath + QLatin1Char('/'); + + for (const auto &move : std::as_const(plan)) { + // A missing comic has its source path here, not a planned destination, and + // an override on it would do nothing but inflate the count of manual changes. + if (move.status == PlannedMove::Status::Missing) + continue; + + if (!move.destinationRelative.startsWith(prefix)) + continue; + + overrides[move.sourceAbsolute].destinationRelative = newPath + QLatin1Char('/') + move.destinationRelative.mid(prefix.size()); + } +} + +void OrganizeFilesDialog::removeSelectedItems() +{ + const auto selected = tree->selectedItems(); + if (selected.isEmpty()) + return; + + QList fileItems; + for (auto *item : selected) + collectFileItems(item, fileItems); + + for (auto *fileItem : std::as_const(fileItems)) + overrides[fileItem->data(0, SourceRole).toString()].excluded = true; + + markPlanStale(ImmediateMs); +} + +void OrganizeFilesDialog::resetOverrides() +{ + overrides.clear(); + markPlanStale(ImmediateMs); +} + +QList OrganizeFilesDialog::movesToExecute() const +{ + const QDir baseDir(currentBase()); + + QList moves; + for (const auto &move : std::as_const(plan)) { + if (!isExecutable(move.status)) + continue; + + FileMove fileMove; + fileMove.comicId = move.comicId; + fileMove.source = move.sourceAbsolute; + fileMove.destination = QDir::cleanPath(baseDir.absoluteFilePath(move.destinationRelative)); + moves.append(fileMove); + } + + return moves; +} + +void OrganizeFilesDialog::saveSettings() +{ + if (settings == nullptr) + return; + + if (patternIsValid) + settings->setValue(renaming() ? ORGANIZE_FILES_FILENAME_PATTERN : ORGANIZE_FILES_PATH_PATTERN, patternEdit->text()); + settings->setValue(ORGANIZE_FILES_SHOW_UNCHANGED, showUnchangedCheck->isChecked()); + if (!renaming() && !context.folderPath.isEmpty()) + settings->setValue(ORGANIZE_FILES_RELATIVE_TO_ROOT, rootBaseButton->isChecked()); +} + +void OrganizeFilesDialog::startMove() +{ + // The button is disabled in all of these cases. This is the second lock: a click + // that was already on its way when the state changed must not get through. + if (planIsStale || !patternIsValid || moveRunning) + return; + + const auto moves = movesToExecute(); + if (moves.isEmpty()) + return; + + saveSettings(); + lastRequestedMoves = moves; + + moveRunning = true; + moveButton->setEnabled(false); + + progressBar->setRange(0, moves.size()); + progressBar->setValue(0); + progressLabel->clear(); + pages->setCurrentIndex(WorkingPage); + + moveWorker = new OrganizeFiles::MoveWorker(context.libraryPath, currentBase(), moves, !renaming()); + // The database phase runs on the worker thread too; on the GUI thread it froze + // the window while the progress bar stood at 100%. + moveWorker->setApplier(applier); + moveThread = new QThread(this); + moveWorker->moveToThread(moveThread); + + connect(moveThread, &QThread::started, moveWorker, &OrganizeFiles::MoveWorker::process); + connect(moveWorker, &OrganizeFiles::MoveWorker::progress, this, &OrganizeFilesDialog::moveProgress); + connect(moveWorker, &OrganizeFiles::MoveWorker::updatingLibrary, this, &OrganizeFilesDialog::showUpdatingLibrary); + connect(moveWorker, &OrganizeFiles::MoveWorker::finished, this, &OrganizeFilesDialog::moveFinished); + + moveThread->start(); +} + +void OrganizeFilesDialog::moveProgress(int done, int total, const QString ¤tFile) +{ + progressBar->setRange(0, total); + progressBar->setValue(done); + progressLabel->setText(tr("Moving %1 of %2\n%3").arg(done).arg(total).arg(QDir::toNativeSeparators(currentFile))); +} + +void OrganizeFilesDialog::showUpdatingLibrary() +{ + progressBar->setRange(0, 0); + progressLabel->setText(tr("Updating the library...")); +} + +void OrganizeFilesDialog::showFailures(const QList &failures) +{ + failureList->clear(); + for (const auto &failure : failures) + failureList->addItem(QDir::toNativeSeparators(failure.path) + QStringLiteral(" — ") + failure.reason); + + // The failures are presented in the result table. This hidden list remains the + // source for Copy the list, so detailed diagnostics are still easy to share. + failureList->setVisible(false); + copyFailuresButton->setVisible(!failures.isEmpty()); +} + +void OrganizeFilesDialog::showCompletedMoves(const QList &moves, const QList &failures, bool restored) +{ + resultTree->clear(); + + if (renaming()) { + resultTree->setHeaderLabels(restored ? QStringList { tr("Restored name"), tr("Moved back from"), tr("Status") } + : QStringList { tr("Final name"), tr("Previous name"), tr("Status") }); + } else { + resultTree->setHeaderLabels(restored ? QStringList { tr("Restored location"), tr("Moved back from"), tr("Status") } + : QStringList { tr("Final location"), tr("Previous location"), tr("Status") }); + } + + const QDir libraryDir(context.libraryPath); + const auto displayPath = [this, &libraryDir](const QString &path) { + return renaming() ? QFileInfo(path).fileName() + : QDir::toNativeSeparators(libraryDir.relativeFilePath(path)); + }; + const auto addRow = [this, &displayPath](const QString &finalPath, const QString &previousPath, const QString &status, const QColor &color = QColor()) { + auto *item = new QTreeWidgetItem(resultTree); + item->setText(0, displayPath(finalPath)); + item->setText(1, displayPath(previousPath)); + item->setText(2, status); + item->setToolTip(0, QDir::toNativeSeparators(finalPath)); + item->setToolTip(1, QDir::toNativeSeparators(previousPath)); + item->setToolTip(2, status); + if (color.isValid()) { + for (int column = 0; column < resultTree->columnCount(); ++column) + item->setForeground(column, color); + } + }; + + QHash failureReasons; + for (const auto &failure : failures) + failureReasons.insert(QDir::cleanPath(failure.path), failure.reason); + + QList sortedMoves = moves; + std::sort(sortedMoves.begin(), sortedMoves.end(), [restored](const FileMove &a, const FileMove &b) { + const QString &aFinal = restored ? a.source : a.destination; + const QString &bFinal = restored ? b.source : b.destination; + return aFinal.compare(bFinal, Qt::CaseInsensitive) < 0; + }); + + for (const auto &move : std::as_const(sortedMoves)) { + const QString failureKey = QDir::cleanPath(restored ? move.destination : move.source); + if (failureReasons.contains(failureKey)) + continue; + + const QString finalPath = restored ? move.source : move.destination; + const QString previousPath = restored ? move.destination : move.source; + addRow(finalPath, previousPath, restored ? tr("Restored") : (renaming() ? tr("Renamed") : tr("Moved"))); + } + + const bool dark = resultTree->palette().color(QPalette::Base).lightness() < 128; + const QColor errorColor = dark ? QColor(0xFF, 0x7B, 0x72) : QColor(0xC0, 0x39, 0x2B); + for (const auto &failure : failures) { + const auto requested = std::find_if(lastRequestedMoves.cbegin(), lastRequestedMoves.cend(), [&failure, restored](const FileMove &move) { + const QString relevantPath = restored ? move.destination : move.source; + return QDir::cleanPath(relevantPath) == QDir::cleanPath(failure.path); + }); + + const QString finalPath = requested == lastRequestedMoves.cend() + ? failure.path + : (restored ? requested->source : requested->destination); + const QString previousPath = requested == lastRequestedMoves.cend() + ? failure.path + : (restored ? requested->destination : requested->source); + addRow(finalPath, previousPath, restored ? tr("Undo failed: %1").arg(failure.reason) : tr("Failed: %1").arg(failure.reason), + errorColor); + } + + resultTree->setVisible(!moves.isEmpty() || !failures.isEmpty()); + if (resultTree->isVisible()) { + const int availableWidth = qMax(resultTree->viewport()->width(), width() - 48); + resultTree->setColumnWidth(0, availableWidth * 2 / 5); + resultTree->setColumnWidth(1, availableWidth * 2 / 5); + } +} + +void OrganizeFilesDialog::moveFinished() +{ + moveThread->quit(); + moveThread->wait(); + + const auto completed = moveWorker->completedMoves(); + const auto failures = moveWorker->failures(); + const auto removedDirectories = moveWorker->removedDirectories(); + const QString journalPath = moveWorker->journalPath(); + const QString startError = moveWorker->startError(); + const QString recordError = moveWorker->recordError(); + const int notAttempted = moveWorker->notAttempted(); + const bool databaseUpdated = moveWorker->databaseUpdated(); + const QString databaseError = moveWorker->databaseError(); + + QStringList lines; + + if (!startError.isEmpty()) { + // Nothing was touched: the run refuses to start without a record. + lines << tr("Nothing was moved.") + << tr("The record this run could be undone from could not be written, so the run did not start: %1").arg(startError); + } else { + lines << (renaming() ? tr("%n file(s) renamed.", "", completed.size()) + : tr("%n file(s) moved into %1.", "", completed.size()).arg(QDir::toNativeSeparators(currentBase()))); + + if (!recordError.isEmpty()) { + lines << tr("The record of this run stopped early, so the run stopped with it: %1").arg(recordError); + if (notAttempted > 0) + lines << tr("%n file(s) were not moved.", "", notAttempted); + } + } + + if (!completed.isEmpty()) { + if (databaseUpdated) + changedLibrary = true; + else + lines << tr("The library database could not be updated: %1").arg(databaseError) + << tr("Use Undo to move the files back, or update the library to make it match the files."); + } + + if (!removedDirectories.isEmpty()) + lines << tr("%n empty folder(s) were removed.", "", removedDirectories.size()); + + if (!failures.isEmpty()) + lines << tr("%n file(s) could not be moved.", "", failures.size()); + + showFailures(failures); + showCompletedMoves(completed, failures); + + resultLabel->setText(lines.join(QStringLiteral("\n"))); + + lastJournalPath = journalPath; + lastCompletedMoves = completed; + undoButton->setEnabled(!journalPath.isEmpty() && !completed.isEmpty() && static_cast(undoer)); + + // Deleted directly: a deferred delete posted to a stopped thread never runs. + delete moveWorker; + moveWorker = nullptr; + moveThread->deleteLater(); + moveThread = nullptr; + moveRunning = false; + + pages->setCurrentIndex(ResultPage); +} + +void OrganizeFilesDialog::undo() +{ + const QString journalPath = lastJournalPath; + if (journalPath.isEmpty() || !undoer || undoRunning || moveRunning) + return; + + undoRunning = true; + undoButton->setEnabled(false); + + progressBar->setRange(0, 0); + progressBar->setValue(0); + progressLabel->setText(tr("Moving the files back...")); + pages->setCurrentIndex(WorkingPage); + + // Same treatment as the run it reverses: worker thread and progress page. + const Undoer runner = undoer; + undoWorker = new OrganizeFiles::UndoWorker( + [runner, journalPath](QList *failures, QString *error, + const std::function &fileProgress, + const std::function &databasePhase) { + return runner(journalPath, failures, error, fileProgress, databasePhase); + }); + undoThread = new QThread(this); + undoWorker->moveToThread(undoThread); + + connect(undoThread, &QThread::started, undoWorker, &OrganizeFiles::UndoWorker::process); + connect(undoWorker, &OrganizeFiles::UndoWorker::progress, this, &OrganizeFilesDialog::undoProgress); + connect(undoWorker, &OrganizeFiles::UndoWorker::updatingLibrary, this, &OrganizeFilesDialog::showUpdatingLibrary); + connect(undoWorker, &OrganizeFiles::UndoWorker::finished, this, &OrganizeFilesDialog::undoFinished); + + undoThread->start(); +} + +void OrganizeFilesDialog::undoProgress(int done, int total, const QString ¤tFile) +{ + progressBar->setRange(0, total); + progressBar->setValue(done); + progressLabel->setText(tr("Moving back %1 of %2\n%3").arg(done).arg(total).arg(QDir::toNativeSeparators(currentFile))); +} + +void OrganizeFilesDialog::undoFinished() +{ + undoThread->quit(); + undoThread->wait(); + + const bool success = undoWorker->succeeded(); + const auto failures = undoWorker->failures(); + const QString error = undoWorker->errorString(); + + delete undoWorker; + undoWorker = nullptr; + undoThread->deleteLater(); + undoThread = nullptr; + undoRunning = false; + + // Even a failed undo has moved files and touched the database. + changedLibrary = true; + + if (success) { + resultLabel->setText(tr("Everything was moved back.")); + showCompletedMoves(lastCompletedMoves, { }, true); + showFailures({ }); + undoButton->setEnabled(false); + } else { + resultLabel->setText(tr("The undo did not finish: %1").arg(error)); + showFailures(failures); + showCompletedMoves(lastCompletedMoves, failures, true); + // The journal survives a failed undo so it can be retried, and this button + // is the only way to reach it. + undoButton->setEnabled(true); + } + + pages->setCurrentIndex(ResultPage); +} + +void OrganizeFilesDialog::reject() +{ + if (moveRunning || undoRunning) + return; + + QDialog::reject(); +} + +void OrganizeFilesDialog::done(int result) +{ + saveSettings(); + QDialog::done(result); +} + +void OrganizeFilesDialog::resizeEvent(QResizeEvent *event) +{ + QDialog::resizeEvent(event); + updateBasePathLabel(); +} + +void OrganizeFilesDialog::closeEvent(QCloseEvent *event) +{ + if (moveRunning || undoRunning) { + event->ignore(); + return; + } + + QDialog::closeEvent(event); +} + +void OrganizeFilesDialog::wrapSelectionInOptionalGroup() +{ + QString text = patternEdit->text(); + int start = patternEdit->selectionStart(); + + if (start < 0) { + start = patternEdit->cursorPosition(); + text.insert(start, QStringLiteral("<>")); + patternEdit->setText(text); + patternEdit->setCursorPosition(start + 1); + } else { + const int length = patternEdit->selectedText().size(); + text.insert(start + length, QLatin1Char('>')); + text.insert(start, QLatin1Char('<')); + patternEdit->setText(text); + patternEdit->setCursorPosition(start + length + 2); + } + + patternEdit->setFocus(); +} + +void OrganizeFilesDialog::showFormatHelp() +{ + auto help = new QDialog(this); + help->setAttribute(Qt::WA_DeleteOnClose); + help->setWindowTitle(tr("Format help")); + + auto layout = new QVBoxLayout(help); + + const auto section = [&](const QString &title, const QString &description, const QString &example) { + auto group = new QGroupBox(title, help); + group->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); + auto groupLayout = new QVBoxLayout(group); + + auto text = new QLabel(description, group); + text->setWordWrap(true); + groupLayout->addWidget(text); + + auto code = new QLabel(example, group); + code->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); + code->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); + code->setMargin(6); + code->setTextInteractionFlags(Qt::TextSelectableByMouse); + groupLayout->addWidget(code); + + layout->addWidget(group); + }; + + const QChar lineBreak = QChar::LineFeed; + const QChar quote = QLatin1Char('"'); + const auto quoted = [quote](const QString &text) { return quote + text + quote; }; + + section(tr("Fields"), + tr("Every field is written between braces and is replaced by the metadata of the comic. " + "The Insert menu lists all of them."), + OrganizeFiles::knownTokens().join(QStringLiteral(" ")) + lineBreak + tr("{series} gives %1").arg(quoted(QStringLiteral("The Amazing Spider-Man")))); + + section(tr("Optional parts"), + tr("A part written between the signs < and > disappears completely when every field inside it is empty. " + "Use it for punctuation that belongs to a field, such as brackets or a leading number sign. " + "Text at the start or the end of a name is trimmed without it."), + tr("{series} ({year}) with no year gives %1").arg(quoted(QStringLiteral("Series ()"))) + lineBreak + tr("{series}< ({year})> with no year gives %1").arg(quoted(QStringLiteral("Series")))); + + section(tr("Numbers"), + tr("Write a colon and some zeros to pad the issue number. " + "This keeps the issues in order in a file browser."), + QStringLiteral("{number} ") + quoted(QStringLiteral("42")) + lineBreak + QStringLiteral("{number:000} ") + quoted(QStringLiteral("042"))); + + if (renaming()) { + section(tr("Folders"), + tr("A filename format cannot contain a slash. Every comic keeps its current folder. " + "Use Organize into folders to move comics."), + QStringLiteral("{series} #{number:000}")); + } else { + section(tr("Folders"), + tr("Each part separated by a slash becomes a folder. The last part becomes the file name. " + "The original extension is always kept."), + QStringLiteral("{publisher}/{series}/{number:000}")); + } + + auto buttons = new QDialogButtonBox(QDialogButtonBox::Close, help); + connect(buttons, &QDialogButtonBox::rejected, help, &QDialog::reject); + layout->addWidget(buttons); + + help->resize(540, help->sizeHint().height()); + help->open(); +} + +void OrganizeFilesDialog::copyFailures() +{ + QStringList lines; + for (int i = 0; i < failureList->count(); ++i) + lines << failureList->item(i)->text(); + + QApplication::clipboard()->setText(lines.join(QStringLiteral("\n"))); +} diff --git a/YACReaderLibrary/organize_files/organize_files_dialog.h b/YACReaderLibrary/organize_files/organize_files_dialog.h new file mode 100644 index 000000000..c07214f6f --- /dev/null +++ b/YACReaderLibrary/organize_files/organize_files_dialog.h @@ -0,0 +1,185 @@ +#ifndef ORGANIZE_FILES_DIALOG_H +#define ORGANIZE_FILES_DIALOG_H + +#include "organize_files_plan.h" +#include "organize_files_worker.h" + +#include +#include +#include + +#include + +class QCheckBox; +class QCloseEvent; +class QLabel; +class QLineEdit; +class QListWidget; +class QMenu; +class QProgressBar; +class QPushButton; +class QResizeEvent; +class QSettings; +class QStackedWidget; +class QToolButton; +class QThread; +class QTimer; +class QTreeWidget; +class QTreeWidgetItem; + +class OrganizeFilesDialog : public QDialog +{ + Q_OBJECT +public: + struct Context { + OrganizeFiles::Mode mode = OrganizeFiles::Mode::Organize; + QString libraryPath; + QString folderPath; + QList entries; + }; + + // Both run on a worker thread and must not touch the GUI. + using Applier = std::function &moves, const QStringList &removedDirectories, const QString &journalPath, QString *error)>; + using Undoer = std::function *failures, + QString *error, + const std::function &fileProgress, + const std::function &databasePhase)>; + + OrganizeFilesDialog(const Context &context, QSettings *settings, QWidget *parent = nullptr); + ~OrganizeFilesDialog() override; + + void setApplier(Applier applier); + void setUndoer(Undoer undoer); + + bool libraryChanged() const; + +private slots: + void patternEdited(); + void scheduleBuild(); + void startBuild(); + void planBuilt(const QList &moves, quint64 buildGeneration); + void itemChanged(QTreeWidgetItem *item, int column); + void removeSelectedItems(); + void resetOverrides(); + void updateSelectionState(); + void startMove(); + void moveProgress(int done, int total, const QString ¤tFile); + void showUpdatingLibrary(); + void moveFinished(); + void undo(); + void undoProgress(int done, int total, const QString ¤tFile); + void undoFinished(); + void copyFailures(); + void wrapSelectionInOptionalGroup(); + void showFormatHelp(); + void saveCurrentPatternAsPreset(); + +public slots: + void reject() override; + void done(int result) override; + +protected: + void closeEvent(QCloseEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + +signals: + void buildRequested(const QString &pattern, const QString &base, const OrganizeFiles::Overrides &overrides, quint64 generation); + +private: + void setupPages(); + QWidget *createLoadingPage(); + QWidget *createPlanPage(); + QWidget *createWorkingPage(); + QWidget *createResultPage(); + void setupPlanWorker(); + + // Every input that changes what the run would do goes through this: it arms + // the rebuild and keeps Move files refused until the rebuild lands. + void markPlanStale(int delayMs); + + bool renaming() const; + QString currentBase() const; + void updateBasePathLabel(); + void rebuildTree(); + void updateStatusLine(); + void captureOverrides(QTreeWidgetItem *item); + QString relativePathForItem(QTreeWidgetItem *item) const; + bool isFileItem(QTreeWidgetItem *item) const; + void collectFileItems(QTreeWidgetItem *item, QList &out) const; + QList movesToExecute() const; + void showCompletedMoves(const QList &moves, const QList &failures = { }, bool restored = false); + void showFailures(const QList &failures); + void saveSettings(); + QString presetsKey() const; + QList> userPresets() const; + void saveUserPresets(const QList> &presets); + void rebuildPresetsMenu(); + + Context context; + QSettings *settings; + + Applier applier; + Undoer undoer; + + QStackedWidget *pages; + + QLineEdit *patternEdit; + QLabel *patternError; + QMenu *presetsMenu; + QPushButton *folderBaseButton; + QPushButton *rootBaseButton; + QWidget *baseSelector; + QLabel *basePathLabel; + QLabel *overridesBanner; + QPushButton *resetButton; + QPushButton *removeButton; + QCheckBox *showUnchangedCheck; + QTreeWidget *tree; + QLabel *statusLabel; + QLabel *warningLabel; + QPushButton *moveButton; + QPushButton *cancelButton; + + QLabel *loadingLabel; + + QProgressBar *progressBar; + QLabel *progressLabel; + + QLabel *resultLabel; + QTreeWidget *resultTree; + QListWidget *failureList; + QPushButton *copyFailuresButton; + QPushButton *undoButton; + QPushButton *finishButton; + + QTimer *buildTimer; + QThread *planThread; + OrganizeFiles::PlanWorker *planWorker; + QThread *moveThread; + OrganizeFiles::MoveWorker *moveWorker; + QThread *undoThread; + OrganizeFiles::UndoWorker *undoWorker; + + OrganizeFiles::Overrides overrides; + QList plan; + QHash planDestinations; + // Valid for the dialog's whole life: nothing on disk moves until commit. + QHash folderExistsCache; + + QString lastJournalPath; + QList lastRequestedMoves; + QList lastCompletedMoves; + + int newFolderCount = 0; + + quint64 generation; + bool updatingTree; + bool changedLibrary; + bool patternIsValid; + bool moveRunning; + bool undoRunning; + bool planIsStale; +}; + +#endif // ORGANIZE_FILES_DIALOG_H diff --git a/YACReaderLibrary/organize_files/organize_files_journal.cpp b/YACReaderLibrary/organize_files/organize_files_journal.cpp new file mode 100644 index 000000000..2f6564be2 --- /dev/null +++ b/YACReaderLibrary/organize_files/organize_files_journal.cpp @@ -0,0 +1,229 @@ +#include "organize_files_journal.h" + +#include "yacreader_global.h" + +#include +#include +#include +#include +#include + +namespace OrganizeFiles { + +QString absoluteFromRelative(const QString &libraryPath, const QString &relativePath) +{ + return QDir::cleanPath(libraryPath + QLatin1Char('/') + relativePath); +} + +Journal::Journal(const QString &libraryPath) + : libraryPath(QDir::cleanPath(libraryPath)) +{ +} + +QString Journal::directory(const QString &libraryPath) +{ + return QDir(YACReader::LibraryPaths::libraryDataPath(libraryPath)).filePath(QStringLiteral("organize")); +} + +QString Journal::filePath() const +{ + return path; +} + +bool Journal::healthy() const +{ + return !broken; +} + +QString Journal::errorString() const +{ + return error; +} + +QString Journal::toRelative(const QString &absolutePath) const +{ + return QLatin1Char('/') + QDir(libraryPath).relativeFilePath(absolutePath); +} + +bool Journal::begin(const QString &base) +{ + const QString folder = directory(libraryPath); + if (!QDir().mkpath(folder)) { + broken = true; + error = QCoreApplication::translate("OrganizeFiles", "%1 could not be created").arg(QDir::toNativeSeparators(folder)); + return false; + } + + path = QDir(folder).filePath(QString::number(QDateTime::currentMSecsSinceEpoch()) + QStringLiteral(".jsonl")); + + file.setFileName(path); + if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) { + broken = true; + error = file.errorString(); + path.clear(); + return false; + } + + QJsonObject header; + header[QStringLiteral("type")] = QStringLiteral("header"); + header[QStringLiteral("version")] = 1; + header[QStringLiteral("startedAt")] = QDateTime::currentSecsSinceEpoch(); + header[QStringLiteral("base")] = toRelative(base); + + return writeLine(header); +} + +bool Journal::reopen(const QString &filePath) +{ + path = filePath; + + file.setFileName(path); + if (!file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) { + broken = true; + error = file.errorString(); + path.clear(); + return false; + } + + return true; +} + +bool Journal::writeLine(const QJsonObject &object) +{ + if (!file.isOpen()) { + broken = true; + return false; + } + + const QByteArray line = QJsonDocument(object).toJson(QJsonDocument::Compact) + '\n'; + + if (file.write(line) != line.size() || !file.flush()) { + broken = true; + error = file.errorString(); + return false; + } + + return true; +} + +void Journal::appendMove(qulonglong comicId, const QString &fromAbsolute, const QString &toAbsolute) +{ + QJsonObject move; + move[QStringLiteral("type")] = QStringLiteral("move"); + move[QStringLiteral("comicId")] = static_cast(comicId); + move[QStringLiteral("from")] = toRelative(fromAbsolute); + move[QStringLiteral("to")] = toRelative(toAbsolute); + writeLine(move); +} + +void Journal::appendRemovedDirectory(const QString &absolutePath) +{ + QJsonObject removed; + removed[QStringLiteral("type")] = QStringLiteral("removedDir"); + removed[QStringLiteral("path")] = toRelative(absolutePath); + writeLine(removed); +} + +void Journal::appendCreatedDirectory(const QString &absolutePath) +{ + QJsonObject created; + created[QStringLiteral("type")] = QStringLiteral("createdDir"); + created[QStringLiteral("path")] = toRelative(absolutePath); + writeLine(created); +} + +void Journal::appendRemovedFolder(const QVariantMap &row) +{ + QJsonObject removed; + removed[QStringLiteral("type")] = QStringLiteral("removedFolder"); + removed[QStringLiteral("row")] = QJsonObject::fromVariantMap(row); + writeLine(removed); +} + +void Journal::appendCreatedFolder(qulonglong folderId) +{ + QJsonObject created; + created[QStringLiteral("type")] = QStringLiteral("createdFolder"); + created[QStringLiteral("id")] = static_cast(folderId); + writeLine(created); +} + +void Journal::finish() +{ + QJsonObject footer; + footer[QStringLiteral("type")] = QStringLiteral("footer"); + footer[QStringLiteral("finishedAt")] = QDateTime::currentSecsSinceEpoch(); + footer[QStringLiteral("complete")] = !broken; + writeLine(footer); + + file.close(); +} + +QString Journal::latestPath(const QString &libraryPath) +{ + QDir folder(directory(libraryPath)); + const auto entries = folder.entryList({ QStringLiteral("*.jsonl") }, QDir::Files, QDir::Name); + + if (entries.isEmpty()) + return QString(); + + return folder.filePath(entries.last()); +} + +bool Journal::read(const QString &libraryPath, const QString &filePath, JournalData *data) +{ + QFile input(filePath); + if (!input.open(QIODevice::ReadOnly | QIODevice::Text)) + return false; + + data->filePath = filePath; + data->moves.clear(); + data->removedDirectories.clear(); + data->createdDirectories.clear(); + data->removedFolders.clear(); + data->createdFolders.clear(); + data->complete = false; + + while (!input.atEnd()) { + const QByteArray line = input.readLine().trimmed(); + if (line.isEmpty()) + continue; + + const auto object = QJsonDocument::fromJson(line).object(); + const QString type = object.value(QStringLiteral("type")).toString(); + + if (type == QLatin1String("header")) { + data->startedAt = static_cast(object.value(QStringLiteral("startedAt")).toDouble()); + data->base = absoluteFromRelative(libraryPath, object.value(QStringLiteral("base")).toString()); + } else if (type == QLatin1String("move")) { + JournalMove move; + move.comicId = static_cast(object.value(QStringLiteral("comicId")).toDouble()); + move.from = object.value(QStringLiteral("from")).toString(); + move.to = object.value(QStringLiteral("to")).toString(); + data->moves.append(move); + } else if (type == QLatin1String("removedDir")) { + data->removedDirectories.append(object.value(QStringLiteral("path")).toString()); + } else if (type == QLatin1String("createdDir")) { + data->createdDirectories.append(object.value(QStringLiteral("path")).toString()); + } else if (type == QLatin1String("removedFolder")) { + data->removedFolders.append(object.value(QStringLiteral("row")).toObject().toVariantMap()); + } else if (type == QLatin1String("createdFolder")) { + data->createdFolders.append(static_cast(object.value(QStringLiteral("id")).toDouble())); + } else if (type == QLatin1String("footer")) { + data->complete = object.value(QStringLiteral("complete")).toBool(); + } + } + + return true; +} + +void Journal::prune(const QString &libraryPath, int keep) +{ + QDir folder(directory(libraryPath)); + const auto entries = folder.entryList({ QStringLiteral("*.jsonl") }, QDir::Files, QDir::Name); + + for (int i = 0; i < entries.size() - keep; ++i) + QFile::remove(folder.filePath(entries.at(i))); +} + +} diff --git a/YACReaderLibrary/organize_files/organize_files_journal.h b/YACReaderLibrary/organize_files/organize_files_journal.h new file mode 100644 index 000000000..982366f17 --- /dev/null +++ b/YACReaderLibrary/organize_files/organize_files_journal.h @@ -0,0 +1,78 @@ +#ifndef ORGANIZE_FILES_JOURNAL_H +#define ORGANIZE_FILES_JOURNAL_H + +#include +#include +#include +#include +#include + +class QJsonObject; + +namespace OrganizeFiles { + +struct JournalMove { + qulonglong comicId = 0; + QString from; + QString to; +}; + +struct JournalData { + QString filePath; + QString base; + qint64 startedAt = 0; + bool complete = false; + QList moves; + QStringList removedDirectories; + // Undo may remove these and nothing else; a pre-existing directory is not the + // run's to delete. + QStringList createdDirectories; + // Full rows, so undo can restore them with the same ids (covers are keyed by id). + QList removedFolders; + // Parents before children; undo deletes the ones that are empty again. + QList createdFolders; +}; + +class Journal +{ +public: + explicit Journal(const QString &libraryPath); + + bool begin(const QString &base); + // Reopens to append: the database work runs after the moves and has to land in + // the same record. + bool reopen(const QString &filePath); + + void appendMove(qulonglong comicId, const QString &fromAbsolute, const QString &toAbsolute); + void appendRemovedDirectory(const QString &absolutePath); + void appendCreatedDirectory(const QString &absolutePath); + void appendRemovedFolder(const QVariantMap &row); + void appendCreatedFolder(qulonglong folderId); + void finish(); + + QString filePath() const; + // False once a line failed to reach the disk; the caller must stop moving files. + bool healthy() const; + QString errorString() const; + + static QString directory(const QString &libraryPath); + static QString latestPath(const QString &libraryPath); + static bool read(const QString &libraryPath, const QString &filePath, JournalData *data); + static void prune(const QString &libraryPath, int keep); + +private: + bool writeLine(const QJsonObject &object); + QString toRelative(const QString &absolutePath) const; + + QString libraryPath; + QString path; + QFile file; + bool broken = false; + QString error; +}; + +QString absoluteFromRelative(const QString &libraryPath, const QString &relativePath); + +} + +#endif // ORGANIZE_FILES_JOURNAL_H diff --git a/YACReaderLibrary/organize_files/organize_files_plan.cpp b/YACReaderLibrary/organize_files/organize_files_plan.cpp new file mode 100644 index 000000000..623781a0e --- /dev/null +++ b/YACReaderLibrary/organize_files/organize_files_plan.cpp @@ -0,0 +1,550 @@ +#include "organize_files_plan.h" + +#include +#include +#include +#include + +#include + +namespace { + +using OrganizeFiles::ComicEntry; + +QString translated(const char *text) +{ + return QCoreApplication::translate("OrganizeFiles", text); +} + +bool isReservedDeviceName(const QString &segment) +{ + static const QStringList reserved = { + QStringLiteral("CON"), QStringLiteral("PRN"), QStringLiteral("AUX"), QStringLiteral("NUL"), + QStringLiteral("COM1"), QStringLiteral("COM2"), QStringLiteral("COM3"), QStringLiteral("COM4"), + QStringLiteral("COM5"), QStringLiteral("COM6"), QStringLiteral("COM7"), QStringLiteral("COM8"), + QStringLiteral("COM9"), QStringLiteral("LPT1"), QStringLiteral("LPT2"), QStringLiteral("LPT3"), + QStringLiteral("LPT4"), QStringLiteral("LPT5"), QStringLiteral("LPT6"), QStringLiteral("LPT7"), + QStringLiteral("LPT8"), QStringLiteral("LPT9") + }; + + const QString stem = segment.section(QLatin1Char('.'), 0, 0); + return reserved.contains(stem, Qt::CaseInsensitive); +} + +QString rawValue(const QString &name, const ComicEntry &entry) +{ + if (name == QLatin1String("publisher")) + return entry.publisher; + if (name == QLatin1String("imprint")) + return entry.imprint; + if (name == QLatin1String("series")) + return entry.series; + if (name == QLatin1String("volume")) + return entry.volume; + if (name == QLatin1String("number")) + return entry.number; + if (name == QLatin1String("count")) + return entry.count; + if (name == QLatin1String("title")) + return entry.title; + if (name == QLatin1String("year")) + return entry.year; + if (name == QLatin1String("month")) + return entry.month; + if (name == QLatin1String("storyArc")) + return entry.storyArc; + if (name == QLatin1String("arcNumber")) + return entry.arcNumber; + if (name == QLatin1String("writer")) + return entry.writer; + if (name == QLatin1String("filename")) + return entry.baseName; + + return QString(); +} + +bool acceptsPadding(const QString &name) +{ + return name == QLatin1String("number") || name == QLatin1String("count") || name == QLatin1String("arcNumber"); +} + +int paddingWidth(const QString &spec) +{ + if (spec.isEmpty()) + return 0; + + for (const QChar c : spec) { + if (c != QLatin1Char('0')) + return 0; + } + + return spec.size(); +} + +QString resolveToken(const QString &name, + const QString &spec, + const ComicEntry &entry, + bool insideGroup, + bool *empty, + QStringList *fallbackFields) +{ + QString value = rawValue(name, entry).trimmed(); + + if (value.isEmpty() && !insideGroup) { + if (name == QLatin1String("series")) { + value = translated("Unknown Series"); + if (fallbackFields != nullptr) + *fallbackFields << translated("series"); + } else if (name == QLatin1String("publisher")) { + value = translated("Unknown Publisher"); + if (fallbackFields != nullptr) + *fallbackFields << translated("publisher"); + } else if (name == QLatin1String("title")) { + value = entry.series.trimmed().isEmpty() ? translated("Unknown Series") : entry.series.trimmed(); + if (fallbackFields != nullptr) + *fallbackFields << translated("title"); + } + } + + *empty = value.isEmpty(); + + if (acceptsPadding(name)) + value = OrganizeFiles::padNumber(value, paddingWidth(spec)); + + return value; +} + +QString expandTokens(const QString &text, + const ComicEntry &entry, + bool insideGroup, + bool *anyToken, + bool *allEmpty, + QStringList *fallbackFields) +{ + QString result; + int i = 0; + + while (i < text.size()) { + if (text.at(i) != QLatin1Char('{')) { + result += text.at(i); + ++i; + continue; + } + + const int close = text.indexOf(QLatin1Char('}'), i + 1); + if (close < 0) { + result += text.mid(i); + break; + } + + const QString content = text.mid(i + 1, close - i - 1); + const QString name = content.section(QLatin1Char(':'), 0, 0); + const QString spec = content.section(QLatin1Char(':'), 1); + + bool empty = true; + result += resolveToken(name, spec, entry, insideGroup, &empty, fallbackFields); + + if (anyToken != nullptr) + *anyToken = true; + if (allEmpty != nullptr && !empty) + *allEmpty = false; + + i = close + 1; + } + + return result; +} + +} + +namespace OrganizeFiles { + +QStringList knownTokens() +{ + return { QStringLiteral("publisher"), QStringLiteral("imprint"), QStringLiteral("series"), + QStringLiteral("volume"), QStringLiteral("number"), QStringLiteral("count"), + QStringLiteral("title"), QStringLiteral("year"), QStringLiteral("month"), + QStringLiteral("storyArc"), QStringLiteral("arcNumber"), QStringLiteral("writer"), + QStringLiteral("filename") }; +} + +QStringList invalidTokens(const QString &pattern) +{ + QStringList invalid; + + static const QRegularExpression tokenExpression(QStringLiteral("\\{([^{}]*)\\}")); + auto it = tokenExpression.globalMatch(pattern); + while (it.hasNext()) { + const auto match = it.next(); + const QString content = match.captured(1); + const QString name = content.section(QLatin1Char(':'), 0, 0); + const QString spec = content.section(QLatin1Char(':'), 1); + + const bool nameIsKnown = knownTokens().contains(name); + const bool specIsValid = spec.isEmpty() ? true : (acceptsPadding(name) && paddingWidth(spec) > 0); + + if (!nameIsKnown || !specIsValid) + invalid << match.captured(0); + } + + if (pattern.count(QLatin1Char('{')) != pattern.count(QLatin1Char('}'))) + invalid << QStringLiteral("{"); + + if (pattern.count(QLatin1Char('<')) != pattern.count(QLatin1Char('>'))) + invalid << QStringLiteral("<"); + + return invalid; +} + +bool patternCreatesFolders(const QString &pattern) +{ +#ifdef Q_OS_WIN + return pattern.contains(QLatin1Char('/')) || pattern.contains(QLatin1Char('\\')); +#else + return pattern.contains(QLatin1Char('/')); +#endif +} + +QString pathKey(const QString &path) +{ +#if defined(Q_OS_WIN) || defined(Q_OS_MACOS) + return path.toLower(); +#else + return path; +#endif +} + +QString sanitizeSegment(QString segment) +{ + static const QString invalid = QStringLiteral("<>:\"/\\|?*"); + for (QChar &c : segment) { + if (invalid.contains(c) || c < QChar(0x20)) + c = QLatin1Char('_'); + } + + segment = segment.simplified(); + + while (segment.endsWith(QLatin1Char('.')) || segment.endsWith(QLatin1Char(' '))) + segment.chop(1); + + while (segment.startsWith(QLatin1Char('-')) || segment.startsWith(QLatin1Char('_')) || segment.startsWith(QLatin1Char('.')) || segment.startsWith(QLatin1Char(' '))) + segment.remove(0, 1); + + while (segment.endsWith(QLatin1Char('-')) || segment.endsWith(QLatin1Char('_'))) + segment.chop(1); + + segment = segment.trimmed(); + + if (!segment.isEmpty() && isReservedDeviceName(segment)) + segment.append(QLatin1Char('_')); + + return segment; +} + +QString padNumber(const QString &number, int width) +{ + const QString trimmed = number.trimmed(); + if (width <= 0 || trimmed.isEmpty()) + return trimmed; + + int digits = 0; + while (digits < trimmed.size() && trimmed.at(digits).isDigit()) + ++digits; + + if (digits == 0) + return trimmed; + + QString leading = trimmed.left(digits); + while (leading.size() < width) + leading.prepend(QLatin1Char('0')); + + return leading + trimmed.mid(digits); +} + +// Every writer of the date column builds it differently: ComicInfo.xml gives +// "1/7/2018" and writes a 0 where a component is unknown, Comic Vine gives +// "01/07/2018", and the properties dialog gives whatever was typed. The tokens +// are normalised here so that one library cannot produce both "7" and "07". +void applyPublicationDate(ComicEntry &entry, const QString &date) +{ + const auto components = date.split(QLatin1Char('/')); + if (components.size() != 3) + return; + + bool valid = false; + + const int month = components.at(1).toInt(&valid); + if (valid && month >= 1 && month <= 12) + entry.month = QStringLiteral("%1").arg(month, 2, 10, QLatin1Char('0')); + + const int year = components.at(2).toInt(&valid); + if (valid && year > 0) + entry.year = QString::number(year); +} + +QString buildRelativePath(const QString &pattern, const ComicEntry &entry, QStringList *fallbackFields) +{ + QString expanded; + int i = 0; + + while (i < pattern.size()) { + if (pattern.at(i) == QLatin1Char('<')) { + const int close = pattern.indexOf(QLatin1Char('>'), i + 1); + if (close < 0) { + expanded += expandTokens(pattern.mid(i + 1), entry, false, nullptr, nullptr, fallbackFields); + break; + } + + bool anyToken = false; + bool allEmpty = true; + const QString group = expandTokens(pattern.mid(i + 1, close - i - 1), entry, true, &anyToken, &allEmpty, nullptr); + + if (!anyToken || !allEmpty) + expanded += group; + + i = close + 1; + continue; + } + + const int nextGroup = pattern.indexOf(QLatin1Char('<'), i); + const QString chunk = nextGroup < 0 ? pattern.mid(i) : pattern.mid(i, nextGroup - i); + expanded += expandTokens(chunk, entry, false, nullptr, nullptr, fallbackFields); + i = nextGroup < 0 ? pattern.size() : nextGroup; + } + +#ifdef Q_OS_WIN + expanded.replace(QLatin1Char('\\'), QLatin1Char('/')); +#endif + + const auto rawSegments = expanded.split(QLatin1Char('/'), Qt::KeepEmptyParts); + + QStringList segments; + for (const QString &raw : rawSegments) { + const QString clean = sanitizeSegment(raw); + if (!clean.isEmpty()) + segments << clean; + } + + // An empty last segment would turn the deepest folder into the file, so the + // original file name takes its place instead. + const bool fileSegmentIsEmpty = rawSegments.isEmpty() || sanitizeSegment(rawSegments.last()).isEmpty(); + if (segments.isEmpty() || fileSegmentIsEmpty) { + QString fallback = sanitizeSegment(entry.baseName); + if (fallback.isEmpty()) + fallback = sanitizeSegment(entry.title); + if (fallback.isEmpty()) + fallback = translated("Unknown Comic"); + + segments << fallback; + } + + return segments.join(QLatin1Char('/')) + entry.extension; +} + +QString defaultPattern(Mode mode) +{ + if (mode == Mode::Rename) + return QStringLiteral("{series}< #{number:000}>< - {title}>"); + + return QStringLiteral("{publisher}/{series}/{series}< #{number:000}>< - {title}>"); +} + +QList> presets(Mode mode) +{ + if (mode == Mode::Rename) { + return { + { translated("Series #Number - Title"), QStringLiteral("{series}< #{number:000}>< - {title}>") }, + { translated("Series #Number"), QStringLiteral("{series}< #{number:000}>") }, + { translated("Series #Number (of Count)"), QStringLiteral("{series}< #{number:000}>< (of {count})>") }, + { translated("Number - Title"), QStringLiteral("{number:000}< - {title}>") }, + { translated("Series #Number (Year)"), QStringLiteral("{series}< #{number:000}>< ({year})>") } + }; + } + + return { + { translated("Publisher / Series / Series #Number - Title"), QStringLiteral("{publisher}/{series}/{series}< #{number:000}>< - {title}>") }, + { translated("Publisher / Imprint / Series / Series #Number - Title"), QStringLiteral("{publisher}/<{imprint}/>{series}/{series}< #{number:000}>< - {title}>") }, + { translated("Series / Series #Number"), QStringLiteral("{series}/{series}< #{number:000}>") }, + { translated("Publisher / Series / Series #Number (Year)"), QStringLiteral("{publisher}/{series}/{series}< #{number:000}>< ({year})>") }, + { translated("Series / original file name"), QStringLiteral("{series}/{filename}") } + }; +} + +PlanBuilder::PlanBuilder(const QList &entries, const QString &base, Mode mode) + : entries(entries), base(QDir::cleanPath(base)), mode(mode) +{ + for (const auto &entry : entries) + sourcePaths.insert(pathKey(entry.sourceAbsolute)); +} + +void PlanBuilder::setBase(const QString &base) +{ + this->base = QDir::cleanPath(base); +} + +const QHash &PlanBuilder::namesIn(const QString &absoluteDirectory) +{ + const QString key = pathKey(absoluteDirectory); + + auto it = directoryNames.find(key); + if (it != directoryNames.end()) + return it.value(); + + QHash names; + const auto entryList = QDir(absoluteDirectory).entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); + for (const QString &name : entryList) + names.insert(pathKey(name), name); + + return directoryNames.insert(key, names).value(); +} + +// The casing this directory will actually have on disk — mkpath() never re-cases +// an existing one. The database rows are written from these strings, so they must match. +QString PlanBuilder::canonicalDirectory(const QString &absoluteDirectory) +{ + const QString clean = QDir::cleanPath(absoluteDirectory); + const QString folded = pathKey(clean); + + auto it = canonicalDirectories.find(folded); + if (it != canonicalDirectories.end()) + return it.value(); + + QString result = clean; + if (folded != pathKey(base) && folded.startsWith(pathKey(base) + QLatin1Char('/'))) { + const QString parent = canonicalDirectory(QFileInfo(clean).absolutePath()); + const QString name = QFileInfo(clean).fileName(); + result = parent + QLatin1Char('/') + namesIn(parent).value(pathKey(name), name); + } + + return canonicalDirectories.insert(folded, result).value(); +} + +QList PlanBuilder::build(const QString &pattern, const Overrides &overrides) +{ + const QDir baseDir(base); + + // A new directory's casing follows its first appearance in the current plan. + canonicalDirectories.clear(); + + // Two passes: entries that stay put claim their paths first, so placement + // cannot depend on the order of the entries. + struct Draft { + PlannedMove move; + QString destination; + QStringList fallbackFields; + bool needsPlacement = false; + }; + + QList drafts; + drafts.reserve(entries.size()); + + QSet claimed; + + for (const auto &original : std::as_const(entries)) { + ComicEntry entry = original; + + // Resolved here and not when the entry is built, because the base can + // change while the dialog is open. + const QString relativeDirectory = baseDir.relativeFilePath(QFileInfo(entry.sourceAbsolute).absolutePath()); + if (relativeDirectory != QLatin1String(".") && !relativeDirectory.startsWith(QLatin1String(".."))) + entry.folderRelative = relativeDirectory; + + PlannedMove move; + move.comicId = entry.comicId; + move.sourceAbsolute = entry.sourceAbsolute; + move.edited = !overrides.value(entry.sourceAbsolute).destinationRelative.isEmpty(); + + if (entry.missing) { + move.status = PlannedMove::Status::Missing; + move.destinationRelative = baseDir.relativeFilePath(entry.sourceAbsolute); + drafts.append({ move, QString(), { }, false }); + continue; + } + + const auto entryOverride = overrides.value(entry.sourceAbsolute); + + QStringList fallbackFields; + QString patterned = entryOverride.destinationRelative.isEmpty() + ? buildRelativePath(pattern, entry, &fallbackFields) + : entryOverride.destinationRelative; + + if (mode == Mode::Rename && entryOverride.destinationRelative.isEmpty()) { + const QString name = patterned.section(QLatin1Char('/'), -1); + patterned = entry.folderRelative.isEmpty() ? name : entry.folderRelative + QLatin1Char('/') + name; + } + + if (entryOverride.excluded) { + move.status = PlannedMove::Status::Excluded; + move.destinationRelative = patterned; + // The file stays where it is, so nothing else may be placed on it. + claimed.insert(pathKey(entry.sourceAbsolute)); + drafts.append({ move, QString(), { }, false }); + continue; + } + + // Only the directory part is bent to on-disk casing; a file, unlike a + // directory, really is renamed to its planned casing. + const QFileInfo plannedInfo(QDir::cleanPath(base + QLatin1Char('/') + patterned)); + const QString destination = canonicalDirectory(plannedInfo.absolutePath()) + QLatin1Char('/') + plannedInfo.fileName(); + + // Compared with case: a capitalisation fix is a real move, and pathKey() + // would call it unchanged. + if (destination == entry.sourceAbsolute) { + move.status = PlannedMove::Status::Unchanged; + move.destinationRelative = baseDir.relativeFilePath(destination); + claimed.insert(pathKey(destination)); + drafts.append({ move, QString(), { }, false }); + continue; + } + + drafts.append({ move, destination, fallbackFields, true }); + } + + QList moves; + moves.reserve(drafts.size()); + + for (auto &draft : drafts) { + if (!draft.needsPlacement) { + moves.append(draft.move); + continue; + } + + PlannedMove &move = draft.move; + const QString &destination = draft.destination; + const QStringList &fallbackFields = draft.fallbackFields; + + const QFileInfo destinationInfo(destination); + const QString directory = destinationInfo.absolutePath(); + const QString stem = destinationInfo.completeBaseName(); + const QString suffix = destinationInfo.suffix().isEmpty() ? QString() : QLatin1Char('.') + destinationInfo.suffix(); + + QString candidate = destination; + int counter = 1; + while (true) { + const bool takenInPlan = claimed.contains(pathKey(candidate)); + const bool takenOnDisk = namesIn(directory).contains(pathKey(QFileInfo(candidate).fileName())) && !sourcePaths.contains(pathKey(candidate)); + + if (!takenInPlan && !takenOnDisk) + break; + + candidate = QDir::cleanPath(directory + QLatin1Char('/') + stem + QStringLiteral(" (") + QString::number(counter++) + QLatin1Char(')') + suffix); + } + + claimed.insert(pathKey(candidate)); + move.destinationRelative = baseDir.relativeFilePath(candidate); + + if (candidate != destination) { + move.status = PlannedMove::Status::Renamed; + move.note = QCoreApplication::translate("OrganizeFiles", "Renamed, %1 is already in use").arg(destinationInfo.fileName()); + } else if (!fallbackFields.isEmpty()) { + move.status = PlannedMove::Status::Incomplete; + move.note = QCoreApplication::translate("OrganizeFiles", "Missing metadata: %1").arg(fallbackFields.join(QStringLiteral(", "))); + } + + moves.append(move); + } + + return moves; +} + +} diff --git a/YACReaderLibrary/organize_files/organize_files_plan.h b/YACReaderLibrary/organize_files/organize_files_plan.h new file mode 100644 index 000000000..415879d0d --- /dev/null +++ b/YACReaderLibrary/organize_files/organize_files_plan.h @@ -0,0 +1,116 @@ +#ifndef ORGANIZE_FILES_PLAN_H +#define ORGANIZE_FILES_PLAN_H + +#include +#include +#include +#include +#include +#include +#include + +namespace OrganizeFiles { + +// Rename keeps every comic in its own folder and only changes the file name. +// Organize may move files and create folders. +enum class Mode { + Rename, + Organize +}; + +struct ComicEntry { + qulonglong comicId = 0; + QString sourceAbsolute; + QString baseName; + QString extension; + QString folderRelative; + bool missing = false; + + QString publisher; + QString imprint; + QString series; + QString volume; + QString number; + QString count; + QString title; + QString year; + QString month; + QString storyArc; + QString arcNumber; + QString writer; +}; + +struct PlannedMove { + enum class Status { + Move, + Unchanged, + Renamed, + Incomplete, + Missing, + Excluded + }; + + qulonglong comicId = 0; + QString sourceAbsolute; + QString destinationRelative; + Status status = Status::Move; + bool edited = false; + QString note; +}; + +struct Override { + bool excluded = false; + QString destinationRelative; +}; + +using Overrides = QHash; + +QStringList knownTokens(); +QStringList invalidTokens(const QString &pattern); +bool patternCreatesFolders(const QString &pattern); + +// Folds a path the way the local file system compares them. Use it to decide +// whether two paths are the same file, never to decide whether a name changed. +QString pathKey(const QString &path); + +QString sanitizeSegment(QString segment); +QString padNumber(const QString &number, int width); + +// The database keeps the publication date as one d/M/yyyy string, so the year +// and the month tokens have to be read back out of it. +void applyPublicationDate(ComicEntry &entry, const QString &date); + +QString buildRelativePath(const QString &pattern, const ComicEntry &entry, QStringList *fallbackFields = nullptr); + +QString defaultPattern(Mode mode); +QList> presets(Mode mode); + +class PlanBuilder +{ +public: + PlanBuilder(const QList &entries, const QString &base, Mode mode); + + void setBase(const QString &base); + QList build(const QString &pattern, const Overrides &overrides); + +private: + const QHash &namesIn(const QString &absoluteDirectory); + QString canonicalDirectory(const QString &absoluteDirectory); + + QList entries; + QString base; + Mode mode; + QSet sourcePaths; + // Per directory: the names it holds on disk, folded key to actual casing. + QHash> directoryNames; + // Folded path to the casing the run will produce; rebuilt on every build(). + QHash canonicalDirectories; +}; + +} + +Q_DECLARE_METATYPE(OrganizeFiles::PlannedMove) +Q_DECLARE_METATYPE(QList) +Q_DECLARE_METATYPE(OrganizeFiles::Overrides) + +#endif // ORGANIZE_FILES_PLAN_H diff --git a/YACReaderLibrary/organize_files/organize_files_worker.cpp b/YACReaderLibrary/organize_files/organize_files_worker.cpp new file mode 100644 index 000000000..2b16c93c3 --- /dev/null +++ b/YACReaderLibrary/organize_files/organize_files_worker.cpp @@ -0,0 +1,433 @@ +#include "organize_files_worker.h" + +#include "organize_files_journal.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace { + +QString translated(const char *text) +{ + return QCoreApplication::translate("OrganizeFiles", text); +} + +QString temporaryNameFor(const QString &source) +{ + QString candidate = source + QStringLiteral(".yacreader-organize"); + int counter = 1; + while (QFileInfo::exists(candidate)) + candidate = source + QStringLiteral(".yacreader-organize-") + QString::number(counter++); + + return candidate; +} + +bool renameThroughTemporary(const QString &source, const QString &destination, QString *reason) +{ + const QString temporary = temporaryNameFor(source); + + QFile sourceFile(source); + if (!sourceFile.rename(temporary)) { + *reason = sourceFile.errorString(); + return false; + } + + QFile temporaryFile(temporary); + if (!temporaryFile.rename(destination)) { + *reason = temporaryFile.errorString(); + // Put it back, so a failure leaves nothing behind under a name the library + // does not know about. + temporaryFile.rename(source); + return false; + } + + return true; +} + +} + +namespace OrganizeFiles { + +bool moveFile(const QString &source, const QString &destination, QString *reason) +{ + if (source == destination) + return true; + + // A rename that only changes the capitalisation of the name has a destination + // that "already exists" on Windows and macOS, so it has to go around. + if (source.compare(destination, Qt::CaseInsensitive) == 0) + return renameThroughTemporary(source, destination, reason); + + QFile sourceFile(source); + if (sourceFile.rename(destination)) + return true; + + const QString renameError = sourceFile.errorString(); + + // Only a cross-volume rename is worth a copy. When the destination is taken, + // the copy fails for the same reason and the rename error is the useful one. + if (QFileInfo::exists(destination)) { + *reason = renameError; + return false; + } + + if (!QFile::copy(source, destination)) { + QFile copyTarget(destination); + *reason = translated("%1 (copy also failed: %2)").arg(renameError, copyTarget.errorString()); + return false; + } + + if (QFileInfo(destination).size() != QFileInfo(source).size()) { + QFile::remove(destination); + *reason = translated("the copy did not have the same size as the original"); + return false; + } + + if (!QFile::remove(source)) { + QFile::remove(destination); + *reason = translated("the original could not be deleted after it was copied"); + return false; + } + + return true; +} + +QList orderMoves(const QList &moves) +{ + // Sources and destinations are unique, so every move has at most one blocker + // and the graph is a set of chains and simple cycles. + QHash ownerOfSource; + for (int i = 0; i < moves.size(); ++i) + ownerOfSource.insert(pathKey(moves.at(i).source), i); + + QList blocker(moves.size(), -1); + QList blocked(moves.size(), -1); + + for (int i = 0; i < moves.size(); ++i) { + const int owner = ownerOfSource.value(pathKey(moves.at(i).destination), -1); + if (owner < 0 || owner == i) + continue; + + blocker[i] = owner; + blocked[owner] = i; + } + + QList ordered; + ordered.reserve(moves.size()); + + QList emitted(moves.size(), false); + + const auto emitChainFrom = [&](int start) { + for (int i = start; i >= 0 && !emitted.at(i); i = blocked.at(i)) { + emitted[i] = true; + ordered.append({ moves.at(i), false }); + } + }; + + // Chains first: an unblocked move goes straight away, its waiters follow. + for (int i = 0; i < moves.size(); ++i) { + if (blocker.at(i) < 0) + emitChainFrom(i); + } + + // Whatever is left is a cycle. Parking one member under a temporary name first + // frees its source for the rest of the ring. + for (int i = 0; i < moves.size(); ++i) { + if (emitted.at(i)) + continue; + + emitted[i] = true; + ordered.append({ moves.at(i), true }); + + emitChainFrom(blocked.at(i)); + } + + return ordered; +} + +QStringList removeEmptyDirectories(const QStringList &directories, const QString &boundary) +{ + const QString boundaryKey = pathKey(QDir::cleanPath(boundary)); + + QStringList ordered = directories; + ordered.removeDuplicates(); + std::sort(ordered.begin(), ordered.end(), [](const QString &a, const QString &b) { + return a.count(QLatin1Char('/')) > b.count(QLatin1Char('/')); + }); + + QStringList removed; + + for (const QString &candidate : std::as_const(ordered)) { + QString directory = QDir::cleanPath(candidate); + + // pathKey: base and directory can arrive with different capitalisation on + // Windows, and a plain prefix test would then remove nothing at all. + while (pathKey(directory).startsWith(boundaryKey + QLatin1Char('/'))) { + // Hidden entries count: a directory holding only a desktop.ini is not empty. + if (!QDir(directory).isEmpty(QDir::AllEntries | QDir::Hidden | QDir::System | QDir::NoDotAndDotDot)) + break; + + const QString parent = QFileInfo(directory).absolutePath(); + if (!QDir().rmdir(directory)) + break; + + removed.append(directory); + directory = parent; + } + } + + return removed; +} + +QStringList removeCreatedDirectories(const QStringList &directories) +{ + QStringList ordered = directories; + ordered.removeDuplicates(); + // Deepest first, so a parent is already empty by the time its turn comes. + std::sort(ordered.begin(), ordered.end(), [](const QString &a, const QString &b) { + return a.count(QLatin1Char('/')) > b.count(QLatin1Char('/')); + }); + + QStringList removed; + + for (const QString &directory : std::as_const(ordered)) { + if (!QDir(directory).exists()) + continue; + + if (!QDir(directory).isEmpty(QDir::AllEntries | QDir::Hidden | QDir::System | QDir::NoDotAndDotDot)) + continue; + + if (QDir().rmdir(directory)) + removed.append(directory); + } + + return removed; +} + +MoveWorker::MoveWorker(const QString &libraryPath, const QString &base, const QList &moves, bool removeEmptyFolders) + : libraryPath(QDir::cleanPath(libraryPath)), base(QDir::cleanPath(base)), moves(moves), removeEmptyFolders(removeEmptyFolders) +{ +} + +void MoveWorker::setApplier(Applier applier) +{ + this->applier = std::move(applier); +} + +QList MoveWorker::completedMoves() const +{ + return completed; +} + +QList MoveWorker::failures() const +{ + return failed; +} + +QStringList MoveWorker::removedDirectories() const +{ + return removed; +} + +QString MoveWorker::journalPath() const +{ + return journal; +} + +QString MoveWorker::startError() const +{ + return journalError; +} + +QString MoveWorker::recordError() const +{ + return journalBreak; +} + +int MoveWorker::notAttempted() const +{ + return moves.size() - completed.size() - failed.size(); +} + +bool MoveWorker::databaseUpdated() const +{ + return applied; +} + +QString MoveWorker::databaseError() const +{ + return applyError; +} + +void MoveWorker::process() +{ + Journal journalFile(libraryPath); + + // A run with no record cannot be undone, so it must not start. + if (!journalFile.begin(base)) { + journalError = journalFile.errorString(); + emit finished(); + return; + } + + journal = journalFile.filePath(); + + const auto ordered = orderMoves(moves); + const int total = ordered.size(); + int done = 0; + + QHash> deferred; + QSet createdDirectories; + + for (int i = 0; i < ordered.size(); ++i) { + const auto &step = ordered.at(i); + const auto &move = step.move; + + const QString target = step.viaTemporary ? temporaryNameFor(move.source) : move.destination; + const QString targetDirectory = QFileInfo(target).absolutePath(); + + // Noted before mkpath; afterwards there is no way to tell what the run made + // from what was already there. + QStringList aboutToCreate; + for (QString level = targetDirectory; + !level.isEmpty() && !QFileInfo::exists(level) && pathKey(level).startsWith(pathKey(base) + QLatin1Char('/')); + level = QFileInfo(level).absolutePath()) { + aboutToCreate.prepend(level); + } + + if (!QDir().mkpath(targetDirectory)) { + failed.append({ move.source, translated("The destination folder could not be created.") }); + } else { + for (const QString &level : std::as_const(aboutToCreate)) { + if (!createdDirectories.contains(level)) { + createdDirectories.insert(level); + journalFile.appendCreatedDirectory(level); + } + } + + // Stop before the move, not after it: a file moved with no record + // could never come back. + if (!journalFile.healthy()) { + journalBreak = journalFile.errorString(); + break; + } + + QString reason; + if (moveFile(move.source, target, &reason)) { + journalFile.appendMove(move.comicId, move.source, target); + + if (step.viaTemporary) + deferred.insert(i, { move, target }); + else + completed.append(move); + } else { + failed.append({ move.source, reason }); + } + } + + if (!journalFile.healthy()) { + journalBreak = journalFile.errorString(); + break; + } + + emit progress(++done, total, QDir(base).relativeFilePath(move.destination)); + } + + // The parked cycle members reach their destinations. Runs even after a journal + // break: a file must not survive the run under a temporary name. + for (auto it = deferred.constBegin(); it != deferred.constEnd(); ++it) { + const auto &move = it.value().first; + const QString &temporary = it.value().second; + + QString reason; + if (moveFile(temporary, move.destination, &reason)) { + journalFile.appendMove(move.comicId, temporary, move.destination); + completed.append(move); + } else { + // Put it back: at its source the file reads as already restored during + // an undo; at the temporary name it would be lost to the library. + QString backReason; + if (moveFile(temporary, move.source, &backReason)) + failed.append({ move.source, reason }); + else + failed.append({ move.source, translated("%1 (the file was left at %2)").arg(reason, QDir::toNativeSeparators(temporary)) }); + } + } + + if (removeEmptyFolders) { + QStringList sourceDirectories; + for (const auto &move : std::as_const(completed)) + sourceDirectories << QFileInfo(move.source).absolutePath(); + + removed = removeEmptyDirectories(sourceDirectories, base); + } + + for (const QString &directory : std::as_const(removed)) + journalFile.appendRemovedDirectory(directory); + + // A directory created for a move that then failed is empty and unknown to the + // database; only the empty ones are deleted, so used directories are untouched. + removeCreatedDirectories(createdDirectories.values()); + + // The database work reopens this file to append the folder rows it changes. + journalFile.finish(); + Journal::prune(libraryPath, 10); + + if (applier && !completed.isEmpty()) { + emit updatingLibrary(); + applied = applier(completed, removed, journal, &applyError); + } + + emit finished(); +} + +UndoWorker::UndoWorker(Runner runner) + : runner(std::move(runner)) +{ +} + +bool UndoWorker::succeeded() const +{ + return success; +} + +QList UndoWorker::failures() const +{ + return failed; +} + +QString UndoWorker::errorString() const +{ + return error; +} + +void UndoWorker::process() +{ + success = runner( + &failed, &error, + [this](int done, int total, const QString ¤tFile) { emit progress(done, total, currentFile); }, + [this] { emit updatingLibrary(); }); + + emit finished(); +} + +PlanWorker::PlanWorker(const QList &entries, const QString &base, Mode mode) + : builder(entries, base, mode) +{ +} + +void PlanWorker::build(const QString &pattern, const QString &base, const OrganizeFiles::Overrides &overrides, quint64 generation) +{ + builder.setBase(base); + emit built(builder.build(pattern, overrides), generation); +} + +} diff --git a/YACReaderLibrary/organize_files/organize_files_worker.h b/YACReaderLibrary/organize_files/organize_files_worker.h new file mode 100644 index 000000000..32140c79e --- /dev/null +++ b/YACReaderLibrary/organize_files/organize_files_worker.h @@ -0,0 +1,143 @@ +#ifndef ORGANIZE_FILES_WORKER_H +#define ORGANIZE_FILES_WORKER_H + +#include "organize_files_plan.h" + +#include +#include +#include +#include + +#include + +namespace OrganizeFiles { + +struct FileMove { + qulonglong comicId = 0; + QString source; + QString destination; +}; + +struct FileFailure { + QString path; + QString reason; +}; + +// Renames when it can, falls back to copy+verify+delete for cross-volume moves. +// Undo needs the same fallback, or a file that crossed a volume cannot get back. +bool moveFile(const QString &source, const QString &destination, QString *reason); + +QStringList removeEmptyDirectories(const QStringList &directories, const QString &boundary); + +// Removes exactly the listed directories, deepest first, only while each is empty. +QStringList removeCreatedDirectories(const QStringList &directories); + +// Orders the moves so a path is vacated before another file is moved onto it. +struct OrderedMove { + FileMove move; + // Part of a cycle: parked under a temporary name, finished at the end. + bool viaTemporary = false; +}; + +QList orderMoves(const QList &moves); + +class MoveWorker : public QObject +{ + Q_OBJECT +public: + // Runs on the worker thread; must not touch the GUI. + using Applier = std::function &completed, const QStringList &removedDirectories, const QString &journalPath, QString *error)>; + + MoveWorker(const QString &libraryPath, const QString &base, const QList &moves, bool removeEmptyFolders); + + void setApplier(Applier applier); + + QList completedMoves() const; + QList failures() const; + QStringList removedDirectories() const; + QString journalPath() const; + // Set when the run never started: the journal could not be written. + QString startError() const; + // Set when the journal broke mid-run and stopped it. + QString recordError() const; + // Files the run never reached because the journal broke. + int notAttempted() const; + + bool databaseUpdated() const; + QString databaseError() const; + +public slots: + void process(); + +signals: + void progress(int done, int total, const QString ¤tFile); + void updatingLibrary(); + void finished(); + +private: + QString libraryPath; + QString base; + QList moves; + bool removeEmptyFolders; + Applier applier; + QList completed; + QList failed; + QStringList removed; + QString journal; + QString journalError; + QString journalBreak; + bool applied = true; + QString applyError; +}; + +// Runs the undo callback off the GUI thread, with progress and a failure list. +class UndoWorker : public QObject +{ + Q_OBJECT +public: + using Runner = std::function *failures, QString *error, + const std::function &fileProgress, + const std::function &databasePhase)>; + + explicit UndoWorker(Runner runner); + + bool succeeded() const; + QList failures() const; + QString errorString() const; + +public slots: + void process(); + +signals: + void progress(int done, int total, const QString ¤tFile); + void updatingLibrary(); + void finished(); + +private: + Runner runner; + bool success = false; + QList failed; + QString error; +}; + +class PlanWorker : public QObject +{ + Q_OBJECT +public: + PlanWorker(const QList &entries, const QString &base, Mode mode); + +public slots: + void build(const QString &pattern, const QString &base, const OrganizeFiles::Overrides &overrides, quint64 generation); + +signals: + void built(const QList &moves, quint64 generation); + +private: + PlanBuilder builder; +}; + +} + +Q_DECLARE_METATYPE(OrganizeFiles::FileMove) + +#endif // ORGANIZE_FILES_WORKER_H diff --git a/YACReaderLibrary/properties_dialog.cpp b/YACReaderLibrary/properties_dialog.cpp index 0d900ca9b..207e1816e 100644 --- a/YACReaderLibrary/properties_dialog.cpp +++ b/YACReaderLibrary/properties_dialog.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -737,6 +738,8 @@ void PropertiesDialog::updateComics() itr->info.originalCoverSize = QString("%1x%2").arg(ie.getOriginalCoverSize().first).arg(ie.getOriginalCoverSize().second); itr->info.coverSizeRatio = static_cast(ie.getOriginalCoverSize().first) / ie.getOriginalCoverSize().second; } + itr->info.lastTimeCoverSet = QDateTime::currentSecsSinceEpoch(); + itr->info.usesExternalCover = false; emit coverChangedSignal(*itr); @@ -750,6 +753,8 @@ void PropertiesDialog::updateComics() auto height = customCover.height(); itr->info.originalCoverSize = QString("%1x%2").arg(width).arg(height); itr->info.coverSizeRatio = static_cast(width) / height; + itr->info.lastTimeCoverSet = QDateTime::currentSecsSinceEpoch(); + itr->info.usesExternalCover = true; DBHelper::update(&(itr->info), db); updated = true; @@ -1000,6 +1005,8 @@ void PropertiesDialog::save() comics[currentComicIndex].info.originalCoverSize = QString("%1x%2").arg(ie.getOriginalCoverSize().first).arg(ie.getOriginalCoverSize().second); comics[currentComicIndex].info.coverSizeRatio = static_cast(ie.getOriginalCoverSize().first) / ie.getOriginalCoverSize().second; } + comics[currentComicIndex].info.lastTimeCoverSet = QDateTime::currentSecsSinceEpoch(); + comics[currentComicIndex].info.usesExternalCover = false; comics[currentComicIndex].info.edited = true; @@ -1010,6 +1017,8 @@ void PropertiesDialog::save() comics[currentComicIndex].info.originalCoverSize = QString("%1x%2").arg(width).arg(height); comics[currentComicIndex].info.coverSizeRatio = static_cast(width) / height; + comics[currentComicIndex].info.lastTimeCoverSet = QDateTime::currentSecsSinceEpoch(); + comics[currentComicIndex].info.usesExternalCover = true; comics[currentComicIndex].info.edited = true; @@ -1061,7 +1070,6 @@ void PropertiesDialog::saveAndClose() updateComics(); close(); - emit accepted(); } void PropertiesDialog::setDisableUniqueValues(bool disabled) diff --git a/YACReaderLibrary/qml/ComicGridDelegate.qml b/YACReaderLibrary/qml/ComicGridDelegate.qml new file mode 100644 index 000000000..2b095be37 --- /dev/null +++ b/YACReaderLibrary/qml/ComicGridDelegate.qml @@ -0,0 +1,315 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Controls +import QtQuick.Controls.Basic +import QtQuick.Controls.impl + +// Delegate for GridContentModel comic rows; required properties intentionally match its role names. +Rectangle { + id: cell + + required property int index + required property int source_index + required property var number + required property string title + required property int num_pages + required property bool read_column + required property int current_page + required property int rating + required property bool has_been_opened + required property url cover_path + required property double added_date + required property bool show_recent + required property double recent_range + + required property int currentViewIndex + required property var selectionHelper + + readonly property int selectionRevision: selectionHelper.selectionRevision + readonly property bool selected: selectionRevision >= 0 && selectionHelper.isSelectedIndex(source_index) + + property alias interactionItem: realCell + + signal activateRequested(int viewRow) + signal clearFolderFocusRequested() + signal contextMenuRequested(point localPosition) + signal focusViewRowRequested(int viewRow) + signal rateRequested(int sourceRow, int rating) + signal selectRangeRequested(int from, int to) + signal setCurrentViewRowRequested(int viewRow) + signal setCurrentComicRowRequested(int sourceRow) + signal startDragRequested() + + color: "transparent" + scale: mouseArea.containsMouse ? 1.025 : 1 + + Behavior on scale { NumberAnimation { duration: 90 } } + + BorderImage { + anchors { + top: realCell.top + left: realCell.left + right: realCell.right + bottom: realCell.bottom + margins: -10 + } + border { left: 10; top: 10; right: 10; bottom: 10 } + horizontalTileMode: BorderImage.Stretch + verticalTileMode: BorderImage.Stretch + source: "prerendered_cover_shadow.png" + visible: showDropShadow + } + + Rectangle { + id: realCell + + property bool dragging: false + + Drag.active: mouseArea.drag.active + Drag.hotSpot.x: 32 + Drag.hotSpot.y: 32 + Drag.dragType: Drag.Automatic + Drag.proposedAction: Qt.CopyAction + Drag.onActiveChanged: { + if (!dragging) { + cell.startDragRequested() + dragging = true + } else { + dragging = false + } + } + + width: itemWidth + height: itemHeight + color: cell.selected ? cellSelectedColor : cellColor + anchors.horizontalCenter: parent.horizontalCenter + + Rectangle { + z: -1 + color: "transparent" + anchors { + fill: parent + margins: -2 + } + border.color: cellSelectedBorderColor + border.width: 3 + opacity: cell.selected ? 1 : 0 + radius: 2 + + Behavior on opacity { NumberAnimation { duration: 300 } } + } + + MouseArea { + id: mouseArea + + drag.target: realCell + drag.minimumX: 0 + drag.maximumX: 0 + drag.minimumY: 0 + drag.maximumY: 0 + anchors.fill: parent + acceptedButtons: Qt.LeftButton | Qt.RightButton + hoverEnabled: true + + onDoubleClicked: { + cell.selectionHelper.selectOnly(cell.source_index) + cell.setCurrentViewRowRequested(cell.index) + cell.activateRequested(cell.index) + } + + onPressed: mouse => { + const currentIndex = cell.currentViewIndex + cell.clearFolderFocusRequested() + + if (mouse.modifiers & Qt.ShiftModifier) { + if (cell.index < currentIndex) { + cell.selectRangeRequested(cell.index, currentIndex) + cell.setCurrentViewRowRequested(cell.index) + } else if (cell.index > currentIndex) { + cell.selectRangeRequested(currentIndex, cell.index) + cell.setCurrentViewRowRequested(cell.index) + } + } + + mouse.accepted = true + + if (mouse.button === Qt.RightButton) { + if (!cell.selectionHelper.isSelectedIndex(cell.source_index)) + cell.focusViewRowRequested(cell.index) + + cell.contextMenuRequested(Qt.point(mouseX, mouseY)) + mouse.accepted = false + } else { + if (mouse.modifiers & Qt.ControlModifier) { + if (cell.selectionHelper.isSelectedIndex(cell.source_index)) { + if (cell.selectionHelper.numItemsSelected() > 1) { + cell.selectionHelper.deselectIndex(cell.source_index) + if (cell.currentViewIndex === cell.index) + cell.setCurrentComicRowRequested(cell.selectionHelper.lastSelectedIndex()) + } + } else { + cell.selectionHelper.selectIndex(cell.source_index) + cell.setCurrentViewRowRequested(cell.index) + } + } + + if (!(mouse.modifiers & Qt.ControlModifier || mouse.modifiers & Qt.ShiftModifier)) { + if (!cell.selectionHelper.isSelectedIndex(cell.source_index)) + cell.focusViewRowRequested(cell.index) + + cell.setCurrentViewRowRequested(cell.index) + } + } + } + + onReleased: mouse => { + if (mouse.button === Qt.LeftButton + && !(mouse.modifiers & Qt.ControlModifier || mouse.modifiers & Qt.ShiftModifier) + && cell.selectionHelper.isSelectedIndex(cell.source_index)) { + cell.focusViewRowRequested(cell.index) + } + } + } + } + + Image { + id: coverElement + width: coverWidth + height: coverHeight + anchors { horizontalCenter: parent.horizontalCenter; top: realCell.top } + source: cell.cover_path + fillMode: Image.PreserveAspectCrop + smooth: true + mipmap: true + asynchronous: true + cache: false + } + + Rectangle { + width: 10 + height: 10 + radius: 5 + anchors { left: coverElement.left; top: coverElement.top; topMargin: 5; leftMargin: 5 } + color: newItemColor + visible: (((new Date() / 1000) - cell.added_date) < cell.recent_range) && cell.show_recent + } + + Rectangle { + width: coverElement.width + height: coverElement.height + anchors { horizontalCenter: parent.horizontalCenter; top: realCell.top } + color: "transparent" + border { color: comicCoverBorderColor; width: 1 } + } + + Image { + width: 23 + height: 23 + source: cell.read_column && show_marks ? "tick.svg" + : cell.has_been_opened && show_marks ? "reading.svg" : "" + anchors { right: coverElement.right; top: coverElement.top; topMargin: 9; rightMargin: 9 } + asynchronous: true + } + + Text { + anchors { top: coverElement.bottom; left: realCell.left; leftMargin: 4; rightMargin: 4; topMargin: 4 } + width: itemWidth - 8 + maximumLineCount: 2 + wrapMode: Text.WordWrap + text: cell.title + elide: Text.ElideRight + color: itemTitleColor + clip: true + font.letterSpacing: fontSpacing + font.pointSize: fontSize + font.family: fontFamily + } + + Text { + anchors { bottom: realCell.bottom; left: realCell.left; margins: 4 } + text: cell.number ? "#" + cell.number : "" + color: itemDetailsColor + font.letterSpacing: fontSpacing + font.pointSize: fontSize + font.family: fontFamily + } + + ColorImage { + id: pageImage + anchors { bottom: realCell.bottom; right: realCell.right; bottomMargin: 6; rightMargin: 4; leftMargin: 4 } + source: "page.svg" + color: itemDetailsColor + width: 8 + height: 10 + } + + Text { + id: pages + anchors { bottom: realCell.bottom; right: pageImage.left; margins: 4 } + text: cell.has_been_opened ? cell.current_page + "/" + cell.num_pages : cell.num_pages + color: itemDetailsColor + font.letterSpacing: fontSpacing + font.pointSize: fontSize + font.family: fontFamily + } + + ColorImage { + id: ratingImage + anchors { bottom: realCell.bottom; right: pageImage.left; bottomMargin: 6.5; rightMargin: Math.floor(pages.width) + 12 } + source: "star.svg" + color: itemDetailsColor + width: 11 + height: 11 + + MouseArea { + anchors.fill: parent + onPressed: { + cell.selectionHelper.selectOnly(cell.source_index) + cell.setCurrentViewRowRequested(cell.index) + ratingLoader.active = true + ratingLoader.item.popup() + } + } + + Loader { + id: ratingLoader + active: false + sourceComponent: ratingContextMenuComponent + } + + Component { + id: ratingContextMenuComponent + Menu { + id: ratingMenu + + readonly property real menuItemPadding: 6 + property TextMetrics resetRatingTextMetrics: TextMetrics { + font: ratingMenu.font + text: resetRatingAction.text + } + + implicitWidth: Math.ceil(resetRatingTextMetrics.advanceWidth) + 2 * menuItemPadding + leftPadding + rightPadding + + Action { text: "1"; onTriggered: cell.rateRequested(cell.source_index, 1) } + Action { text: "2"; onTriggered: cell.rateRequested(cell.source_index, 2) } + Action { text: "3"; onTriggered: cell.rateRequested(cell.source_index, 3) } + Action { text: "4"; onTriggered: cell.rateRequested(cell.source_index, 4) } + Action { text: "5"; onTriggered: cell.rateRequested(cell.source_index, 5) } + MenuSeparator {} + Action { id: resetRatingAction; text: qsTranslate("LibraryWindowActions", "Reset rating"); onTriggered: cell.rateRequested(cell.source_index, 0) } + + delegate: MenuItem { + implicitHeight: 30 + padding: ratingMenu.menuItemPadding + } + } + } + } + + Text { + anchors { bottom: realCell.bottom; right: ratingImage.left; margins: 4 } + text: cell.rating > 0 ? cell.rating : "-" + color: itemDetailsColor + } +} diff --git a/YACReaderLibrary/qml/ContinueReadingGridHeader.qml b/YACReaderLibrary/qml/ContinueReadingGridHeader.qml new file mode 100644 index 000000000..4e61efae2 --- /dev/null +++ b/YACReaderLibrary/qml/ContinueReadingGridHeader.qml @@ -0,0 +1,127 @@ +import QtQuick + +Rectangle { + id: header + + required property var contentModel + required property bool sectionVisible + + signal openRequested(int index) + signal contextMenuRequested(int index, point position) + + readonly property int sectionHeight: 430 + readonly property int topMargin: 20 + + function handlesWheelAt(position) { + const listPosition = list.mapFromItem(header, position.x, position.y) + return listPosition.x >= 0 && listPosition.x <= list.width + && listPosition.y >= 0 && listPosition.y <= list.height + && list.contentWidth > list.width + } + + color: "transparent" + height: list.count > 0 && sectionVisible ? sectionHeight : topMargin + + Rectangle { + width: header.width + height: header.sectionHeight - header.topMargin + visible: list.count > 0 && header.sectionVisible + color: continueReadingBackgroundColor + + Text { + id: heading + text: qsTr("Continue Reading...") + color: continueReadingTextColor + anchors { left: parent.left; top: parent.top; topMargin: 15; leftMargin: 25 } + font.pointSize: 18 + font.weight: Font.DemiBold + } + + ListView { + id: list + objectName: "continueReadingList" + anchors { + top: heading.bottom + left: parent.left + right: parent.right + bottom: parent.bottom + topMargin: 15 + bottomMargin: 20 + leftMargin: 25 + rightMargin: 20 + } + orientation: Qt.Horizontal + pixelAligned: true + model: header.contentModel + spacing: 20 + property int verticalPadding: 20 + + WheelHandler { + onWheel: event => { + if (list.contentWidth <= list.width) + return + list.contentX = Math.min(list.contentWidth - list.width - list.anchors.leftMargin, + Math.max(list.originX, list.contentX - event.angleDelta.y)) + } + } + + delegate: Rectangle { + width: Math.floor((list.height - (list.verticalPadding * 2)) * 0.65) + height: list.height - (list.verticalPadding * 2) + color: "transparent" + scale: mouseArea.containsMouse ? 1.025 : 1 + Behavior on scale { NumberAnimation { duration: 90 } } + + Image { + id: cover + anchors.fill: parent + source: cover_path + fillMode: Image.PreserveAspectCrop + smooth: true + mipmap: true + asynchronous: true + cache: true + } + + Text { + anchors { top: cover.bottom; left: cover.left; right: cover.right; leftMargin: 4; rightMargin: 4; topMargin: 4 } + maximumLineCount: 2 + wrapMode: Text.WordWrap + text: readable_title + elide: Text.ElideRight + color: itemTitleColor + font.letterSpacing: fontSpacing + font.pointSize: fontSize + font.family: fontFamily + } + + Rectangle { + anchors.fill: cover + color: "transparent" + border.color: comicCoverBorderColor + border.width: 1 + } + + MouseArea { + id: mouseArea + anchors.fill: parent + acceptedButtons: Qt.LeftButton | Qt.RightButton + hoverEnabled: true + + onDoubleClicked: { + list.currentIndex = index + header.openRequested(index) + } + onReleased: mouse => { + list.currentIndex = index + if (mouse.button === Qt.RightButton) { + var position = header.mapFromItem(cover, mouseX, mouseY) + header.contextMenuRequested(index, Qt.point(position.x, position.y)) + } + mouse.accepted = true + } + } + } + } + } +} diff --git a/YACReaderLibrary/qml/EmptyInfoView.qml b/YACReaderLibrary/qml/EmptyInfoView.qml new file mode 100644 index 000000000..af85f581e --- /dev/null +++ b/YACReaderLibrary/qml/EmptyInfoView.qml @@ -0,0 +1,40 @@ +import QtQuick +import QtQuick.Layouts + +Rectangle { + id: root + + color: "transparent" + height: 240 + + ColumnLayout { + anchors { + left: parent.left + right: parent.right + top: parent.top + margins: 30 + } + spacing: 8 + + Text { + Layout.fillWidth: true + text: qsTr("Nothing selected") + color: infoTextColor + font.family: "Arial" + font.bold: true + font.pixelSize: 21 + wrapMode: Text.WordWrap + horizontalAlignment: Text.AlignHCenter + } + + Text { + Layout.fillWidth: true + text: qsTr("Select a comic or folder to see its information.") + color: infoMetadataTextColor + font.family: "Arial" + font.pixelSize: 14 + wrapMode: Text.WordWrap + horizontalAlignment: Text.AlignHCenter + } + } +} diff --git a/YACReaderLibrary/qml/FlowView.qml b/YACReaderLibrary/qml/FlowView.qml index 5038ba001..8e5f95376 100644 --- a/YACReaderLibrary/qml/FlowView.qml +++ b/YACReaderLibrary/qml/FlowView.qml @@ -99,6 +99,16 @@ Rectangle { highlightMoveDuration: 250 + function restoreCurrentIndex(index) { + const previousDuration = highlightMoveDuration + highlightMoveDuration = 0 + currentIndex = index + positionViewAtIndex(index, ListView.SnapPosition) + Qt.callLater(function() { + list.highlightMoveDuration = previousDuration + }) + } + onCurrentIndexChanged: currentIndex => { if (list.currentIndex !== -1) { mainFlowContainer.currentCoverChanged(list.currentIndex); diff --git a/YACReaderLibrary/qml/FolderContentView.qml b/YACReaderLibrary/qml/FolderContentView.qml deleted file mode 100644 index cceea9adf..000000000 --- a/YACReaderLibrary/qml/FolderContentView.qml +++ /dev/null @@ -1,482 +0,0 @@ -import QtQuick - -import QtQuick.Controls -import QtQuick.Layouts - -import QtQuick.Effects - -import com.yacreader.ComicModel 1.0 - -import com.yacreader.ComicInfo 1.0 -import com.yacreader.ComicDB 1.0 - -import QtQuick.Controls.Basic - -Rectangle { - id: main - - property int continuReadingHeight: 430; - property int topContentMargin: 20; - - color: backgroundColor - anchors.margins: 0 - - Component { - id: appDelegate - Rectangle - { - id: cell - width: grid.cellWidth - height: grid.cellHeight - color: "#00000000" - - scale: mouseArea.containsMouse ? 1.025 : 1 - - Behavior on scale { - NumberAnimation { duration: 90 } - } - - Rectangle { - id: realCell - - property int position : 0 - - width: itemWidth - height: itemHeight - - color: "transparent" - anchors.horizontalCenter: parent.horizontalCenter - - MouseArea { - id: mouseArea - - anchors.fill: parent - acceptedButtons: Qt.LeftButton | Qt.RightButton - - hoverEnabled: true - - onDoubleClicked: { - openHelper.openFolder(index); - } - - onPressed: mouse => { - var ci = grid.currentIndex; //save current index - - mouse.accepted = true; - - if(mouse.button === Qt.RightButton) // context menu is requested - { - var coordinates = main.mapFromItem(realCell,mouseX,mouseY) - contextMenuHelper.requestedFolderContextMenu(Qt.point(coordinates.x,coordinates.y), index); - mouse.accepted = false; - - } - } - - } - } - - /**/ - - Rectangle { - transform: Rotation { origin.x: coverWidth / 2; origin.y: coverHeight / 2; angle: -4} - width: coverElement.width - height: coverElement.height - radius: 10 - anchors {horizontalCenter: parent.horizontalCenter; top: realCell.top; topMargin: 0} - color: placeholderFolder1Color - border { - color: placeholderFolder1BorderColor - width: 1 - } - } - - Rectangle { - transform: Rotation { origin.x: coverWidth / 2; origin.y: coverHeight / 2; angle: 3} - width: coverElement.width - height: coverElement.height - radius: 10 - anchors {horizontalCenter: parent.horizontalCenter; top: realCell.top; topMargin: 0} - color: placeholderFolder2Color - border { - color: placeholderFolder2BorderColor - width: 1 - } - } - - Item { - width: coverWidth - height: coverHeight - anchors {horizontalCenter: parent.horizontalCenter; top: realCell.top; topMargin: 0} - id: coverElement - - Image { - id: coverImage - anchors.fill: parent - source: cover_path - fillMode: Image.PreserveAspectCrop - smooth: true - mipmap: true - asynchronous : true - cache: true - visible: false - } - - Item { - id: coverMask - anchors.fill: parent - layer.enabled: true - layer.smooth: true - visible: false - - Rectangle { - anchors.fill: parent - radius: 10 - color: "black" - } - } - - MultiEffect { - source: coverImage - anchors.fill: coverImage - maskEnabled: true - maskSource: coverMask - maskThresholdMin: 0.5 - maskSpreadAtMin: 1.0 - } - } - - //is new - Rectangle { - width: 10 - height: 10 - radius: 5 - anchors { left: coverElement.left; top: coverElement.top; topMargin: 10; leftMargin: 10; } - color: newItemColor - visible: (((new Date() / 1000) - added) < recent_range || ((new Date() / 1000) - updated) < recent_range) && show_recent - } - - //border - Rectangle { - width: coverElement.width - height: coverElement.height - radius: 10 - anchors {horizontalCenter: parent.horizontalCenter; top: realCell.top; topMargin: 0} - color: "transparent" - border { - color: folderCoverBorderColor - width: 1 - } - } - - //folder name - Text { - id : titleText - anchors { top: coverElement.bottom; left: realCell.left; leftMargin: 4; rightMargin: 4; topMargin: 10; } - width: itemWidth - 8 - maximumLineCount: 2 - wrapMode: Text.WordWrap - text: name - elide: Text.ElideRight - color: itemTitleColor - font.letterSpacing: fontSpacing - font.pointSize: fontSize - font.family: fontFamily - } - } - } - - Rectangle { - id: scrollView - objectName: "topScrollView" - anchors.fill: parent - anchors.margins: 0 - children: grid - - color: "transparent" - - function scrollToOrigin() { - grid.contentY = grid.originY - grid.contentX = grid.originX - } - - property Component continueReadingView: Component { - id: continueReadingView - Rectangle { - id: continueReadingTopView - color: "#00000000" - - height: list.count > 0 && showContinueReading ? main.continuReadingHeight : main.topContentMargin - - Rectangle { - color: continueReadingBackgroundColor - - id: continueReadingBackground - - width: main.width - height: main.continuReadingHeight - main.topContentMargin - - visible: list.count > 0 && showContinueReading - - Text { - id: continueReadingText - text: qsTr("Continue Reading...") - color: continueReadingTextColor - anchors.left: parent.left - anchors.top: parent.top - anchors.topMargin: 15 - anchors.bottomMargin: 20 - anchors.leftMargin: 25 - anchors.rightMargin: 0 - font.pointSize: 18 - font.weight: Font.DemiBold - } - - ListView { - id: list - objectName: "list" - anchors { top: continueReadingText.bottom; left: parent.left; right: parent.right; bottom: parent.bottom; } - - property int previousIndex; - property int verticalPadding: 20 - - orientation: Qt.Horizontal - pixelAligned: true - - model: comicsList - - spacing: 20 - anchors.topMargin: 15 - anchors.bottomMargin: 20 - anchors.leftMargin: 25 - anchors.rightMargin: 20 - - WheelHandler { - onWheel: event => { - if (list.contentWidth <= list.width) { - return; - } - - var newValue = Math.min(list.contentWidth - list.width - anchors.leftMargin, (Math.max(list.originX , list.contentX - event.angleDelta.y))); - list.contentX = newValue - } - } - - delegate: Component { - - //cover - Rectangle { - width: Math.floor((list.height - (list.verticalPadding * 2)) * 0.65); - height: list.height - (list.verticalPadding * 2); - - color:"transparent" - - scale: mouseArea.containsMouse ? 1.025 : 1 - - Behavior on scale { - NumberAnimation { duration: 90 } - } - - Image { - id: coverElement - anchors.fill: parent - source: cover_path - fillMode: Image.PreserveAspectCrop - smooth: true - mipmap: true - asynchronous : true - cache: true - } - - //title - Text { - id : comicTitleText - anchors { top: coverElement.bottom; left: coverElement.left; right: coverElement.right; leftMargin: 4; rightMargin: 4; topMargin: 4; } - width: itemWidth - 8 - maximumLineCount: 2 - wrapMode: Text.WordWrap - text: readable_title - elide: Text.ElideRight - color: itemTitleColor - font.letterSpacing: fontSpacing - font.pointSize: fontSize - font.family: fontFamily - } - - //border - Rectangle { - width: coverElement.width - height: coverElement.height - anchors.centerIn: coverElement - color: "transparent" - border { - color: comicCoverBorderColor - width: 1 - } - } - - MouseArea { - id: mouseArea - anchors.fill: parent - acceptedButtons: Qt.LeftButton | Qt.RightButton - - hoverEnabled: true - - onDoubleClicked: { - list.currentIndex = index; - openHelper.openComicFromContinueReadingList(index); - } - - onReleased: mouse => { - list.currentIndex = index; - - if(mouse.button === Qt.RightButton) // context menu is requested - { - var coordinates = main.mapFromItem(coverElement,mouseX,mouseY) - contextMenuHelper.requestedContinueReadingComicContextMenu(Qt.point(coordinates.x,coordinates.y), index); - } - - mouse.accepted = true; - } - } - } - } - - focus: true - } - } - } - } - - GridView { - id:grid - objectName: "grid" - anchors.fill: parent - cellHeight: cellCustomHeight - header: continueReadingView - focus: true - model: foldersList - delegate: appDelegate - anchors.topMargin: 0 - anchors.bottomMargin: 10 - anchors.leftMargin: 0 - anchors.rightMargin: 0 - pixelAligned: true - highlightFollowsCurrentItem: true - - currentIndex: 0 - cacheBuffer: 0 - - interactive: true - - move: Transition { - NumberAnimation { properties: "x,y"; duration: 250 } - } - - moveDisplaced: Transition { - NumberAnimation { properties: "x,y"; duration: 250 } - } - - remove: Transition { - ParallelAnimation { - NumberAnimation { property: "opacity"; to: 0; duration: 250 } - - } - } - - removeDisplaced: Transition { - NumberAnimation { properties: "x,y"; duration: 250 } - } - - displaced: Transition { - NumberAnimation { properties: "x,y"; duration: 250 } - } - - function numCellsPerRow() { - return Math.floor(width / cellCustomWidth); - } - - onWidthChanged: { - calculateCellWidths(cellCustomWidth); - } - - function calculateCellWidths(cWidth) { - var wholeCells = Math.floor(width / cWidth); - var rest = width - (cWidth * wholeCells) - - grid.cellWidth = cWidth + Math.floor(rest / wholeCells); - } - - WheelHandler { - onWheel: event => { - if (grid.contentHeight <= grid.height) { - return; - } - - var newValue = Math.min((grid.contentHeight - grid.height + grid.originY), (Math.max(grid.originY , grid.contentY - event.angleDelta.y))); - grid.contentY = newValue; - } - } - - ScrollBar.vertical: ScrollBar { - visible: grid.contentHeight > grid.height - - contentItem: Item { - implicitWidth: 12 - implicitHeight: 26 - Rectangle { - color: scrollbarColor - anchors.fill: parent - anchors.topMargin: 6 - anchors.leftMargin: 3 - anchors.rightMargin: 2 - anchors.bottomMargin: 6 - border.color: scrollbarBorderColor - border.width: 1 - radius: 3.5 - } - } - } - - DropArea { - anchors.fill: parent - - onEntered: drag => { - if(drag.hasUrls) - { - if(dropManager.canDropUrls(drag.urls, drag.action)) - { - drag.accepted = true; - }else - drag.accepted = false; - } - else if (dropManager.canDropFormats(drag.formats)) { - drag.accepted = true; - } else - drag.accepted = false; - } - - onDropped: drop => { - if(drop.hasUrls && dropManager.canDropUrls(drop.urls, drop.action)) - { - dropManager.droppedFiles(drop.urls, drop.action); - } - else{ - if (dropManager.canDropFormats(drop.formats)) - { - var destItem = grid.itemAt(drop.x,drop.y + grid.contentY); - var destLocalX = grid.mapToItem(destItem,drop.x,drop.y + grid.contentY).x - var realIndex = grid.indexAt(drop.x,drop.y + grid.contentY); - - if(realIndex === -1) - realIndex = grid.count - 1; - - var destIndex = destLocalX < (grid.cellWidth / 2) ? realIndex : realIndex + 1; - dropManager.droppedComicsForResortingAt("", destIndex); - } - } - } - } - } - } -} diff --git a/YACReaderLibrary/qml/FolderCover.qml b/YACReaderLibrary/qml/FolderCover.qml new file mode 100644 index 000000000..702aa73e3 --- /dev/null +++ b/YACReaderLibrary/qml/FolderCover.qml @@ -0,0 +1,153 @@ +import QtQuick +import QtQuick.Effects + +Item { + id: root + + required property url coverSource + // Covers of the stack, from front to back. The first entry is the front + // cover, so only the two next ones are stacked behind it. + property var stackedCoverSources: [] + property bool selected: false + property bool showRecentIndicator: false + property bool showFinishedMark: false + property real cornerRadius: 10 + + readonly property int stackedCount: stackedCoverSources.length + readonly property url midCoverSource: stackedCount > 1 ? stackedCoverSources[1] : "" + readonly property url backCoverSource: stackedCount > 2 ? stackedCoverSources[2] : "" + + // A cover image with rounded corners and an outline. The mask is inset by + // one pixel so that the alpha fades out inside the item, which keeps the + // edges smooth when the cover is rotated. + component RoundedCover: Item { + id: cover + + required property url coverSource + property real cornerRadius: 10 + property color outlineColor: "transparent" + + Image { + id: coverImage + anchors.fill: parent + source: cover.coverSource + fillMode: Image.PreserveAspectCrop + smooth: true + mipmap: true + asynchronous: true + cache: true + visible: false + } + + Item { + id: coverMask + anchors.fill: parent + layer.enabled: true + layer.smooth: true + visible: false + + Rectangle { + anchors.fill: parent + anchors.margins: 1 + radius: cover.cornerRadius + color: "black" + } + } + + MultiEffect { + anchors.fill: parent + source: coverImage + maskEnabled: true + maskSource: coverMask + maskThresholdMin: 0.5 + maskSpreadAtMin: 1.0 + } + + Rectangle { + anchors.fill: parent + radius: cover.cornerRadius + color: "transparent" + border.color: cover.outlineColor + border.width: 1 + } + } + + Rectangle { + anchors.fill: parent + rotation: -4 + radius: root.cornerRadius + color: placeholderFolder1Color + border.color: placeholderFolder1BorderColor + border.width: 1 + visible: root.backCoverSource.toString().length === 0 + } + + RoundedCover { + anchors.fill: parent + rotation: -4 + opacity: 0.5 + coverSource: root.backCoverSource + cornerRadius: root.cornerRadius + outlineColor: placeholderFolder1BorderColor + visible: root.backCoverSource.toString().length > 0 + } + + Rectangle { + anchors.fill: parent + rotation: 3 + radius: root.cornerRadius + color: placeholderFolder2Color + border.color: placeholderFolder2BorderColor + border.width: 1 + visible: root.midCoverSource.toString().length === 0 + } + + RoundedCover { + anchors.fill: parent + rotation: 3 + opacity: 0.75 + coverSource: root.midCoverSource + cornerRadius: root.cornerRadius + outlineColor: placeholderFolder2BorderColor + visible: root.midCoverSource.toString().length > 0 + } + + RoundedCover { + anchors.fill: parent + coverSource: root.coverSource + cornerRadius: root.cornerRadius + outlineColor: folderCoverBorderColor + } + + Rectangle { + width: 10 + height: 10 + radius: 5 + anchors { left: parent.left; top: parent.top; topMargin: 10; leftMargin: 10 } + color: newItemColor + visible: root.showRecentIndicator + } + + Image { + z: 2 + width: 23 + height: 23 + source: "tick.svg" + visible: root.showFinishedMark + anchors { right: parent.right; top: parent.top; topMargin: 9; rightMargin: 9 } + asynchronous: true + } + + Rectangle { + z: 2 + anchors.fill: parent + anchors.margins: -3 + radius: root.cornerRadius + 3 + color: "transparent" + border.color: cellSelectedBorderColor + border.width: 3 + opacity: root.selected ? 1 : 0 + + Behavior on opacity { NumberAnimation { duration: 150 } } + } +} diff --git a/YACReaderLibrary/qml/FolderGridDelegate.qml b/YACReaderLibrary/qml/FolderGridDelegate.qml new file mode 100644 index 000000000..b62c92cee --- /dev/null +++ b/YACReaderLibrary/qml/FolderGridDelegate.qml @@ -0,0 +1,78 @@ +import QtQuick + +// Delegate for GridContentModel folder rows; required properties intentionally match its role names. +Rectangle { + id: cell + + required property int index + required property string title + required property url cover_path + required property double added_date + required property double updated + required property double recent_range + required property bool show_recent + required property bool is_finished + required property bool selected + + signal openRequested() + signal contextMenuRequested(point localPosition) + signal focusRequested() + + property alias interactionItem: realCell + + color: "transparent" + + scale: mouseArea.containsMouse ? 1.025 : 1 + Behavior on scale { NumberAnimation { duration: 90 } } + + Rectangle { + id: realCell + width: itemWidth + height: itemHeight + color: "transparent" + anchors.horizontalCenter: parent.horizontalCenter + + MouseArea { + id: mouseArea + anchors.fill: parent + acceptedButtons: Qt.LeftButton | Qt.RightButton + hoverEnabled: true + + onDoubleClicked: cell.openRequested() + onPressed: mouse => { + cell.focusRequested() + if (mouse.button === Qt.RightButton) { + cell.contextMenuRequested(Qt.point(mouseX, mouseY)) + mouse.accepted = false + } + } + } + } + + FolderCover { + id: coverElement + width: coverWidth + height: coverHeight + anchors { horizontalCenter: parent.horizontalCenter; top: realCell.top } + coverSource: cell.cover_path + selected: cell.selected + showFinishedMark: cell.is_finished && show_marks + showRecentIndicator: (((new Date() / 1000) - cell.added_date) < cell.recent_range + || ((new Date() / 1000) - cell.updated) < cell.recent_range) + && cell.show_recent + } + + Text { + z: 4 + anchors { top: coverElement.bottom; left: realCell.left; leftMargin: 4; rightMargin: 4; topMargin: 10 } + width: itemWidth - 8 + maximumLineCount: 2 + wrapMode: Text.WordWrap + text: cell.title + elide: Text.ElideRight + color: itemTitleColor + font.letterSpacing: fontSpacing + font.pointSize: fontSize + font.family: fontFamily + } +} diff --git a/YACReaderLibrary/qml/FolderInfoView.qml b/YACReaderLibrary/qml/FolderInfoView.qml new file mode 100644 index 000000000..194a10cf3 --- /dev/null +++ b/YACReaderLibrary/qml/FolderInfoView.qml @@ -0,0 +1,88 @@ +import QtQuick +import QtQuick.Layouts + +Rectangle { + id: root + + required property var folderInfo + + property int panelMargin: 30 + property color secondaryTextColor: infoMetadataTextColor + + component MetadataText: Text { + font.family: fontFamily + font.pointSize: fontSize + 1 + } + + color: "transparent" + height: content.implicitHeight + panelMargin * 2 + + function formattedDate(timestamp) { + if (!timestamp) + return qsTr("Unknown") + return new Date(timestamp * 1000).toLocaleDateString(Qt.locale(), Locale.ShortFormat) + } + + ColumnLayout { + id: content + x: root.panelMargin + y: root.panelMargin + width: root.width - root.panelMargin * 2 + spacing: 12 + + FolderCover { + Layout.alignment: Qt.AlignHCenter + Layout.preferredWidth: Math.min(220, content.width) + Layout.preferredHeight: Layout.preferredWidth * coverHeight / coverWidth + coverSource: root.folderInfo.cover ?? "" + } + + Text { + Layout.fillWidth: true + Layout.topMargin: 6 + text: root.folderInfo.name ?? "" + color: infoTextColor + font.family: "Arial" + font.bold: true + font.pixelSize: 21 + wrapMode: Text.WordWrap + horizontalAlignment: Text.AlignHCenter + } + + Text { + Layout.fillWidth: true + text: root.folderInfo.path ?? "" + color: root.secondaryTextColor + font.family: "Arial" + font.pixelSize: 13 + wrapMode: Text.WrapAnywhere + horizontalAlignment: Text.AlignHCenter + visible: text.length > 0 + } + + GridLayout { + Layout.fillWidth: true + columns: 2 + columnSpacing: 18 + rowSpacing: 9 + + MetadataText { text: qsTr("Items"); color: root.secondaryTextColor } + MetadataText { text: root.folderInfo.itemCount ?? 0; color: infoTextColor; Layout.fillWidth: true } + + MetadataText { text: qsTr("Type"); color: root.secondaryTextColor } + MetadataText { text: root.folderInfo.typeName ?? ""; color: infoTextColor; Layout.fillWidth: true } + + MetadataText { text: qsTr("Reading status"); color: root.secondaryTextColor } + MetadataText { text: root.folderInfo.finished ? qsTr("Read") : qsTr("Unread"); color: infoTextColor; Layout.fillWidth: true } + + MetadataText { text: qsTr("Collection status"); color: root.secondaryTextColor } + MetadataText { text: root.folderInfo.completed ? qsTr("Completed") : qsTr("In progress"); color: infoTextColor; Layout.fillWidth: true } + + MetadataText { text: qsTr("Added"); color: root.secondaryTextColor } + MetadataText { text: root.formattedDate(root.folderInfo.added); color: infoTextColor; Layout.fillWidth: true } + + MetadataText { text: qsTr("Updated"); color: root.secondaryTextColor } + MetadataText { text: root.formattedDate(root.folderInfo.updated); color: infoTextColor; Layout.fillWidth: true } + } + } +} diff --git a/YACReaderLibrary/qml/GridComicsView.qml b/YACReaderLibrary/qml/GridComicsView.qml index 1aa16186e..a9dabdf5b 100644 --- a/YACReaderLibrary/qml/GridComicsView.qml +++ b/YACReaderLibrary/qml/GridComicsView.qml @@ -1,4 +1,4 @@ -import QtQuick +import QtQuick import QtQuick.Controls import QtQuick.Layouts @@ -9,9 +9,10 @@ import com.yacreader.ComicModel 1.0 import com.yacreader.ComicInfo 1.0 import com.yacreader.ComicDB 1.0 +import com.yacreader.GridContentModel 1.0 import QtQuick.Controls.Basic -import QtQuick.Controls.impl +import QtQml.Models SplitView { orientation: Qt.Horizontal @@ -55,375 +56,67 @@ SplitView { height: parent.height anchors.margins: 0 - Component { + DelegateChooser { id: appDelegate - Rectangle - { - id: cell - width: grid.cellWidth - height: grid.cellHeight - color: "#00000000" + role: "item_kind" - scale: mouseArea.containsMouse ? 1.025 : 1 + DelegateChoice { + roleValue: GridContentModel.FolderItem - Behavior on scale { - NumberAnimation { duration: 90 } - } + FolderGridDelegate { + id: folderCell + width: grid.cellWidth + height: grid.cellHeight + selected: currentIndexHelper.focusedFolderRow === index - BorderImage { - anchors { - top: realCell.top - left: realCell.left - right: realCell.right - bottom: realCell.bottom - margins: -10 - } - border { left: 10; top: 10; right: 10; bottom: 10 } - horizontalTileMode: BorderImage.Stretch - verticalTileMode: BorderImage.Stretch - source: "prerendered_cover_shadow.png" - visible: showDropShadow - } - - Rectangle { - id: realCell - - property int position : 0 - property bool dragging: false; - Drag.active: mouseArea.drag.active - Drag.hotSpot.x: 32 - Drag.hotSpot.y: 32 - Drag.dragType: Drag.Automatic - //Drag.mimeData: { "x": 1 } - Drag.proposedAction: Qt.CopyAction - Drag.onActiveChanged: { - if(!dragging) - { - dragManager.startDrag(); - dragging = true; - }else - dragging = false; + onFocusRequested: { + comicsSelectionHelper.clear() + grid.focusItemFromPointer(index) } - - width: itemWidth - height: itemHeight - - color: ((dummyValue || !dummyValue) && comicsSelectionHelper.isSelectedIndex(index))?cellSelectedColor:cellColor; - //border.color: ((dummyValue || !dummyValue) && comicsSelectionHelper.isSelectedIndex(index))?cellSelectedBorderColor:borderColor; - //border.width: ?1:0; - anchors.horizontalCenter: parent.horizontalCenter - - Rectangle - { - id: mouseOverBorder - - property bool commonBorder : false - - property int lBorderwidth : 2 - property int rBorderwidth : 2 - property int tBorderwidth : 2 - property int bBorderwidth : 2 - - property int commonBorderWidth : 1 - - z : -1 - - color: "#00000000" - - anchors - { - left: parent.left - right: parent.right - top: parent.top - bottom: parent.bottom - - topMargin : commonBorder ? -commonBorderWidth : -tBorderwidth - bottomMargin : commonBorder ? -commonBorderWidth : -bBorderwidth - leftMargin : commonBorder ? -commonBorderWidth : -lBorderwidth - rightMargin : commonBorder ? -commonBorderWidth : -rBorderwidth - } - - border.color: cellSelectedBorderColor - border.width: 3 - - opacity: (dummyValue || !dummyValue) && comicsSelectionHelper.isSelectedIndex(index) ? 1 : 0 - - Behavior on opacity { - NumberAnimation { duration: 300 } - } - - radius : 2 + onOpenRequested: currentIndexHelper.openFolder(index) + onContextMenuRequested: localPosition => { + var coordinates = main.mapFromItem(folderCell.interactionItem, + localPosition.x, + localPosition.y) + contextMenuHelper.requestItemContextMenu(Qt.point(coordinates.x, coordinates.y), folderCell.index) } - - - MouseArea { - id: mouseArea - drag.target: realCell - - drag.minimumX: 0 - drag.maximumX: 0 - drag.minimumY: 0 - drag.maximumY: 0 - - anchors.fill: parent - acceptedButtons: Qt.LeftButton | Qt.RightButton - - hoverEnabled: true - - onDoubleClicked: { - comicsSelectionHelper.clear(); - - comicsSelectionHelper.selectIndex(index); - grid.currentIndex = index; - currentIndexHelper.selectedItem(index); - } - - function selectAll(from,to) - { - for(var i = from;i<=to;i++) - { - comicsSelectionHelper.selectIndex(i); - } - } - - onPressed: mouse => { - var ci = grid.currentIndex; //save current index - - /*if(mouse.button != Qt.RightButton && !(mouse.modifiers & Qt.ControlModifier || mouse.modifiers & Qt.ShiftModifier)) - { - if(!comicsSelectionHelper.isSelectedIndex(index)) - comicsSelectionHelper.clear(); - }*/ - - if(mouse.modifiers & Qt.ShiftModifier) - if(index < ci) - { - selectAll(index,ci); - grid.currentIndex = index; - } - else if (index > ci) - { - selectAll(ci,index); - grid.currentIndex = index; - } - - mouse.accepted = true; - - if(mouse.button === Qt.RightButton) // context menu is requested - { - if(!comicsSelectionHelper.isSelectedIndex(index)) //the context menu is requested outside the current selection, the selection will be - { - currentIndexHelper.setCurrentIndex(index) - grid.currentIndex = index; - } - - var coordinates = main.mapFromItem(realCell,mouseX,mouseY) - contextMenuHelper.requestedContextMenu(Qt.point(coordinates.x,coordinates.y)); - mouse.accepted = false; - - } else //left button - { - - if(mouse.modifiers & Qt.ControlModifier) - { - if(comicsSelectionHelper.isSelectedIndex(index)) - { - if(comicsSelectionHelper.numItemsSelected()>1) - { - comicsSelectionHelper.deselectIndex(index); - if(grid.currentIndex === index) - grid.currentIndex = comicsSelectionHelper.lastSelectedIndex(); - } - } - else - { - comicsSelectionHelper.selectIndex(index); - grid.currentIndex = index; - } - } - - if(mouse.button !== Qt.RightButton && !(mouse.modifiers & Qt.ControlModifier || mouse.modifiers & Qt.ShiftModifier)) //just left button click - { - if(comicsSelectionHelper.isSelectedIndex(index)) //the context menu is requested outside the current selection, the selection will be - { - - } - else - { - currentIndexHelper.setCurrentIndex(index) - } - - grid.currentIndex = index; - } - } - - } - - onReleased: mouse => { - if(mouse.button === Qt.LeftButton && !(mouse.modifiers & Qt.ControlModifier || mouse.modifiers & Qt.ShiftModifier)) - { - if(comicsSelectionHelper.isSelectedIndex(index)) - { - currentIndexHelper.setCurrentIndex(index) - grid.currentIndex = index; - } - } - } - } - } - - /**/ - - //cover - Image { - id: coverElement - width: coverWidth - height: coverHeight - anchors {horizontalCenter: parent.horizontalCenter; top: realCell.top; topMargin: 0} - source: cover_path - fillMode: Image.PreserveAspectCrop - smooth: true - mipmap: true - asynchronous : true - cache: false //TODO clear cache only when it is needed - - } - - //is new - Rectangle { - width: 10 - height: 10 - radius: 5 - anchors { left: coverElement.left; top: coverElement.top; topMargin: 5; leftMargin: 5; } - color: newItemColor - visible: (((new Date() / 1000) - added_date) < recent_range) && show_recent } + } - //border - Rectangle { - width: coverElement.width - height: coverElement.height - anchors {horizontalCenter: parent.horizontalCenter; top: realCell.top; topMargin: 0} - color: "transparent" - border { - color: comicCoverBorderColor - width: 1 + DelegateChoice { + roleValue: GridContentModel.ComicItem + + ComicGridDelegate { + id: comicCell + width: grid.cellWidth + height: grid.cellHeight + currentViewIndex: grid.currentIndex + selectionHelper: comicsSelectionHelper + + onActivateRequested: viewRow => currentIndexHelper.activateItem(viewRow) + onClearFolderFocusRequested: currentIndexHelper.clearFolderFocus() + onContextMenuRequested: localPosition => { + var coordinates = main.mapFromItem(comicCell.interactionItem, + localPosition.x, + localPosition.y) + contextMenuHelper.requestItemContextMenu(Qt.point(coordinates.x, coordinates.y), comicCell.index) } + onFocusViewRowRequested: viewRow => grid.focusItemFromPointer(viewRow) + onRateRequested: (sourceRow, rating) => comicRatingHelper.rate(sourceRow, rating) + onSelectRangeRequested: (from, to) => currentIndexHelper.selectComicRange(from, to) + onSetCurrentViewRowRequested: viewRow => grid.setCurrentIndexFromPointer(viewRow) + onSetCurrentComicRowRequested: sourceRow => { + grid.setCurrentIndexFromPointer(currentIndexHelper.viewRowForComicRow(sourceRow)) + } + onStartDragRequested: dragManager.startDrag() } + } - //mark - Image { - id: mark - width: 23 - height: 23 - source: read_column&&show_marks?"tick.svg":has_been_opened&&show_marks?"reading.svg":"" - anchors {right: coverElement.right; top: coverElement.top; topMargin: 9; rightMargin: 9} - asynchronous : true - } - - //title - Text { - id : titleText - anchors { top: coverElement.bottom; left: realCell.left; leftMargin: 4; rightMargin: 4; topMargin: 4; } - width: itemWidth - 8 - maximumLineCount: 2 - wrapMode: Text.WordWrap - text: title - elide: Text.ElideRight - color: itemTitleColor - clip: true - font.letterSpacing: fontSpacing - font.pointSize: fontSize - font.family: fontFamily - } - - //number - Text { - anchors {bottom: realCell.bottom; left: realCell.left; margins: 4} - text: number?"#"+number:"" - color: itemDetailsColor - font.letterSpacing: fontSpacing - font.pointSize: fontSize - font.family: fontFamily - } - - //page icon - ColorImage { - id: pageImage - anchors {bottom: realCell.bottom; right: realCell.right; bottomMargin: 6; rightMargin: 4; leftMargin: 4} - source: "page.svg" - color: itemDetailsColor - width: 8 - height: 10 - } - - //numPages - Text { - id: pages - anchors {bottom: realCell.bottom; right: pageImage.left; margins: 4} - text: has_been_opened?current_page+"/"+num_pages:num_pages - color: itemDetailsColor - font.letterSpacing: fontSpacing - font.pointSize: fontSize - font.family: fontFamily - } - - //rating icon - ColorImage { - id: ratingImage - anchors {bottom: realCell.bottom; right: pageImage.left; bottomMargin: 6.5; rightMargin: Math.floor(pages.width)+12} - source: "star.svg" - color: itemDetailsColor - width: 11 - height: 11 - - MouseArea { - anchors.fill: parent - onPressed: { - console.log("rating"); - comicsSelectionHelper.clear(); - comicsSelectionHelper.selectIndex(index); - grid.currentIndex = index; - ratingLoader.active = true; - ratingLoader.item.popup(); - } - } - - Loader { - id: ratingLoader - active: false - sourceComponent: ratingConextMenuComponent - } - - Component { - id: ratingConextMenuComponent - Menu { - background: Rectangle { - implicitWidth: 42 - implicitHeight: 100 - } - - id: ratingConextMenu - - Action { text: "1"; enabled: true; onTriggered: comicRatingHelper.rate(index,1) } - Action { text: "2"; enabled: true; onTriggered: comicRatingHelper.rate(index,2) } - Action { text: "3"; enabled: true; onTriggered: comicRatingHelper.rate(index,3) } - Action { text: "4"; enabled: true; onTriggered: comicRatingHelper.rate(index,4) } - Action { text: "5"; enabled: true; onTriggered: comicRatingHelper.rate(index,5) } - - delegate: MenuItem { - implicitHeight: 30 - } - } - } - } - - //comic rating - Text { - id: comicRating - anchors {bottom: realCell.bottom; right: ratingImage.left; margins: 4} - text: rating>0?rating:"-" - color: itemDetailsColor + DelegateChoice { + roleValue: GridContentModel.SpacerItem + Item { + width: grid.cellWidth + height: grid.cellHeight } } } @@ -442,13 +135,61 @@ SplitView { grid.contentX = grid.originX } + function capturePosition() { + const probeX = Math.max(1, grid.cellWidth / 2) + const viewRow = grid.indexAt(probeX, grid.contentY + 1) + if (viewRow < 0) { + return { + "header": true, + "viewRow": -1, + "offset": grid.contentY - grid.originY, + "itemExtent": Math.max(1, -grid.originY) + } + } + + const item = grid.itemAtIndex(viewRow) + return { + "header": false, + "viewRow": viewRow, + "offset": item ? grid.contentY - item.y : 0, + "itemExtent": grid.cellHeight + } + } + + function restorePosition(viewRow, offset, oldItemExtent) { + if (viewRow < 0) { + const currentExtent = Math.max(1, -grid.originY) + const restoredOffset = oldItemExtent === currentExtent + ? offset + : offset * currentExtent / Math.max(1, oldItemExtent) + grid.contentY = grid.originY + restoredOffset + return + } + + grid.positionViewAtIndex(viewRow, GridView.Beginning) + const restoredOffset = oldItemExtent === grid.cellHeight + ? offset + : offset * grid.cellHeight / Math.max(1, oldItemExtent) + const maximumY = Math.max(grid.originY, grid.contentHeight - grid.height + grid.originY) + grid.contentY = Math.max(grid.originY, Math.min(maximumY, grid.contentY + restoredOffset)) + } + property Component currentComicView: Component { id: currentComicView Rectangle { id: currentComicViewTopView color: "#00000000" - height: showCurrentComic ? 270 : 20 + function handlesWheelAt(position) { + const synopsisPosition = synopsisScroller.mapFromItem(currentComicViewTopView, + position.x, + position.y) + return synopsisPosition.x >= 0 && synopsisPosition.x <= synopsisScroller.width + && synopsisPosition.y >= 0 && synopsisPosition.y <= synopsisScroller.height + && synopsisScroller.contentHeight > synopsisScroller.availableHeight + } + + height: currentIndexHelper.currentComicBannerVisible ? 270 : 20 Rectangle { color: currentComicBackgroundColor @@ -458,7 +199,7 @@ SplitView { width: main.width height: 250 - visible: showCurrentComic + visible: currentIndexHelper.currentComicBannerVisible //cover Image { @@ -471,7 +212,7 @@ SplitView { anchors.rightMargin: 15 horizontalAlignment: Image.AlignLeft anchors {horizontalCenter: parent.horizontalCenter; top: parent.top; topMargin: 0} - source: comicsList.getCoverUrlPathForComicHash(currentComicInfo.hash.toString()) + source: comicsList.comicCoverUrlForHash(currentComicInfo.hash.toString()) fillMode: Image.PreserveAspectFit smooth: true mipmap: true @@ -698,12 +439,26 @@ SplitView { } } + property Component rootFolderHeader: Component { + ContinueReadingGridHeader { + id: continueReadingHeader + width: main.width + contentModel: currentIndexHelper.rootContinueReadingModel + sectionVisible: currentIndexHelper.globalContinueReadingEnabled + onOpenRequested: index => currentIndexHelper.openContinueReadingComic(index) + onContextMenuRequested: (index, position) => { + var coordinates = main.mapFromItem(continueReadingHeader, position.x, position.y) + currentIndexHelper.requestContinueReadingComicContextMenu(Qt.point(coordinates.x, coordinates.y), index) + } + } + } + GridView { id:grid objectName: "grid" anchors.fill: parent cellHeight: cellCustomHeight - header: currentComicView + header: currentIndexHelper.rootFolder ? scrollView.rootFolderHeader : scrollView.currentComicView focus: true model: comicsList delegate: appDelegate @@ -714,11 +469,37 @@ SplitView { pixelAligned: true highlightFollowsCurrentItem: true - currentIndex: 0 + currentIndex: -1 cacheBuffer: 0 + readonly property var wheelAwareHeader: headerItem interactive: true + // Clears the selection when the click does not land on an item. The + // MouseArea must be a child of the view content item, because a plain + // child of the view stays behind the flickable itself and never gets + // mouse events. Its geometry follows the viewport (in content + // coordinates), so the empty space after the last row is included too. + MouseArea { + parent: grid.contentItem + z: -1 + x: grid.contentX + y: grid.contentY + width: grid.width + height: grid.height + acceptedButtons: Qt.LeftButton + + onClicked: mouse => { + if (mouse.modifiers !== Qt.NoModifier) + return + + comicsSelectionHelper.clear() + currentIndexHelper.clearFolderFocus() + grid.currentIndex = -1 + grid.forceActiveFocus() + } + } + move: Transition { NumberAnimation { properties: "x,y"; duration: 250 } } @@ -748,25 +529,69 @@ SplitView { return Math.floor(width / cellCustomWidth); } + function firstVisibleSelectableIndex() { + if (count === 0) + return -1 + + const columns = Math.max(1, numCellsPerRow()) + const visibleRow = Math.max(0, Math.floor((contentY - originY) / cellHeight)) + const candidate = Math.min(visibleRow * columns, count - 1) + return currentIndexHelper.nearestSelectableRow(candidate, 1) + } + + function setCurrentIndexFromPointer(index) { + var previousContentX = contentX + var previousContentY = contentY + currentIndex = index + contentX = previousContentX + contentY = previousContentY + } + + function focusItemFromPointer(index) { + var previousContentX = contentX + var previousContentY = contentY + currentIndexHelper.focusItem(index) + currentIndex = index + contentX = previousContentX + contentY = previousContentY + } + onWidthChanged: { calculateCellWidths(cellCustomWidth); } function calculateCellWidths(cWidth) { - var wholeCells = Math.floor(width / cWidth); + var wholeCells = Math.max(1, Math.floor(width / cWidth)); var rest = width - (cWidth * wholeCells) grid.cellWidth = cWidth + Math.floor(rest / wholeCells); + currentIndexHelper.setGridColumnCount(wholeCells) } - WheelHandler { - onWheel: { - if (grid.contentHeight <= grid.height) { - return; + MouseArea { + id: gridWheelArea + anchors.fill: parent + acceptedButtons: Qt.NoButton + + onWheel: (wheel) => { + if (grid.wheelAwareHeader && grid.wheelAwareHeader.handlesWheelAt) { + const headerPosition = grid.wheelAwareHeader.mapFromItem(gridWheelArea, + wheel.x, + wheel.y) + if (grid.wheelAwareHeader.handlesWheelAt(headerPosition)) { + wheel.accepted = false + return + } } - var newValue = Math.min((grid.contentHeight - grid.height + grid.originY), (Math.max(grid.originY , grid.contentY - event.angleDelta.y))); - grid.contentY = newValue; + if (grid.contentHeight <= grid.height) + return + + var newValue = Math.min( + (grid.contentHeight - grid.height + grid.originY), + Math.max(grid.originY, grid.contentY - wheel.angleDelta.y) + ) + grid.contentY = newValue } } @@ -796,6 +621,25 @@ SplitView { return; } + if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + event.accepted = true + currentIndexHelper.activateItem(grid.currentIndex) + return + } + + const cursorKey = event.key === Qt.Key_Right || event.key === Qt.Key_Left + || event.key === Qt.Key_Up || event.key === Qt.Key_Down + if (cursorKey && grid.currentIndex < 0) { + const initialIndex = grid.firstVisibleSelectableIndex() + if (initialIndex >= 0) { + comicsSelectionHelper.clear() + currentIndexHelper.focusItem(initialIndex) + grid.currentIndex = initialIndex + } + event.accepted = true + return + } + var numCells = grid.numCellsPerRow(); var ci = 0; if (event.key === Qt.Key_Right) { @@ -813,20 +657,44 @@ SplitView { return; } + ci = currentIndexHelper.nearestSelectableRow(ci, + event.key === Qt.Key_Left || event.key === Qt.Key_Up ? -1 : 1) + event.accepted = true; grid.currentIndex = -1 comicsSelectionHelper.clear(); - currentIndexHelper.setCurrentIndex(ci); + currentIndexHelper.focusItem(ci); grid.currentIndex = ci; } DropArea { + id: gridDropArea anchors.fill: parent + function visibleItemIndexAt(x, y) { + const contentPosition = grid.contentItem.mapFromItem(gridDropArea, x, y) + const viewIndex = grid.indexAt(contentPosition.x, contentPosition.y) + if (viewIndex < 0) + return -1 + + const item = grid.itemAtIndex(viewIndex) + if (!item || !item.interactionItem) + return -1 + + const localPosition = item.interactionItem.mapFromItem(gridDropArea, x, y) + return localPosition.x >= 0 + && localPosition.x <= item.interactionItem.width + && localPosition.y >= 0 + && localPosition.y <= item.interactionItem.height + ? viewIndex + : -1 + } + onEntered: drag => { if(drag.hasUrls) { - if(dropManager.canDropUrls(drag.urls, drag.action)) + if(dropManager.canDropImage(drag.urls) + || dropManager.canDropUrls(drag.urls, drag.action)) { drag.accepted = true; }else @@ -839,21 +707,30 @@ SplitView { } onDropped: drop => { - if(drop.hasUrls && dropManager.canDropUrls(drop.urls, drop.action)) + if(drop.hasUrls && dropManager.canDropImage(drop.urls)) + { + var coverIndex = gridDropArea.visibleItemIndexAt(drop.x, drop.y); + if (coverIndex !== -1) { + dropManager.droppedImageAt(drop.urls, coverIndex); + drop.accepted = true; + } + } + else if(drop.hasUrls && dropManager.canDropUrls(drop.urls, drop.action)) { dropManager.droppedFiles(drop.urls, drop.action); } else{ if (dropManager.canDropFormats(drop.formats)) { - var destItem = grid.itemAt(drop.x,drop.y + grid.contentY); - var destLocalX = grid.mapToItem(destItem,drop.x,drop.y + grid.contentY).x var realIndex = grid.indexAt(drop.x,drop.y + grid.contentY); - - if(realIndex === -1) - realIndex = grid.count - 1; - - var destIndex = destLocalX < (grid.cellWidth / 2) ? realIndex : realIndex + 1; + var destIndex = grid.count; + if (realIndex !== -1) { + var destItem = grid.itemAtIndex(realIndex); + var destLocalX = grid.mapToItem(destItem, + drop.x, + drop.y + grid.contentY).x; + destIndex = destLocalX < (grid.cellWidth / 2) ? realIndex : realIndex + 1; + } dropManager.droppedComicsForResortingAt("", destIndex); } } @@ -883,19 +760,81 @@ SplitView { contentWidth: infoView.width contentHeight: infoView.height - ComicInfoView { + Loader { id: infoView width: info_container.width + sourceComponent: currentIndexHelper.focusedFolderRow >= 0 + ? folderInfoComponent + : currentIndexHelper.selectedComicCount > 1 + ? selectedComicsInfoComponent + : currentIndexHelper.hasComicSelection + ? comicInfoComponent + : currentIndexHelper.currentLocationInfo.kind === "folder" + ? folderInfoComponent + : currentIndexHelper.currentLocationInfo.kind === "library" + ? libraryInfoComponent + : currentIndexHelper.currentLocationInfo.name + ? listInfoComponent + : emptyInfoComponent } - WheelHandler { - onWheel: { - if (infoFlickable.contentHeight <= infoFlickable.height) { - return; - } + Component { + id: comicInfoComponent + ComicInfoView { width: infoView.width } + } + + Component { + id: selectedComicsInfoComponent + SelectedComicsInfoView { + width: infoView.width + selectionInfo: currentIndexHelper.selectedComicsInfo + } + } + + Component { + id: folderInfoComponent + FolderInfoView { + width: infoView.width + folderInfo: currentIndexHelper.focusedFolderRow >= 0 + ? currentIndexHelper.focusedFolderInfo + : currentIndexHelper.currentLocationInfo + } + } + + Component { + id: libraryInfoComponent + LibraryInfoView { + width: infoView.width + libraryInfo: currentIndexHelper.currentLocationInfo + } + } + + Component { + id: listInfoComponent + ListInfoView { + width: infoView.width + listInfo: currentIndexHelper.currentLocationInfo + } + } + + Component { + id: emptyInfoComponent + EmptyInfoView { width: infoView.width } + } + + MouseArea { + anchors.fill: parent + acceptedButtons: Qt.NoButton + + onWheel: (wheel) => { + if (infoFlickable.contentHeight <= infoFlickable.height) + return - var newValue = Math.min((infoFlickable.contentHeight - infoFlickable.height), (Math.max(infoFlickable.originY , infoFlickable.contentY - event.angleDelta.y))); - infoFlickable.contentY = newValue; + var newValue = Math.min( + (infoFlickable.contentHeight - infoFlickable.height), + Math.max(infoFlickable.originY, infoFlickable.contentY - wheel.angleDelta.y) + ) + infoFlickable.contentY = newValue } } diff --git a/YACReaderLibrary/qml/InfoComicsView.qml b/YACReaderLibrary/qml/InfoComicsView.qml index 66d169ea8..01dde2fd4 100644 --- a/YACReaderLibrary/qml/InfoComicsView.qml +++ b/YACReaderLibrary/qml/InfoComicsView.qml @@ -113,7 +113,8 @@ Rectangle { onEntered: { if(drag.hasUrls) { - if(dropManager.canDropUrls(drag.urls, drag.action)) + if(dropManager.canDropImage(drag.urls) + || dropManager.canDropUrls(drag.urls, drag.action)) { drag.accepted = true; }else @@ -122,7 +123,12 @@ Rectangle { } onDropped: { - if(drop.hasUrls && dropManager.canDropUrls(drop.urls, drop.action)) + if(drop.hasUrls && dropManager.canDropImage(drop.urls)) + { + dropManager.droppedImage(drop.urls); + drop.accepted = true; + } + else if(drop.hasUrls && dropManager.canDropUrls(drop.urls, drop.action)) { dropManager.droppedFiles(drop.urls, drop.action); } diff --git a/YACReaderLibrary/qml/LibraryInfoView.qml b/YACReaderLibrary/qml/LibraryInfoView.qml new file mode 100644 index 000000000..0e39d967b --- /dev/null +++ b/YACReaderLibrary/qml/LibraryInfoView.qml @@ -0,0 +1,84 @@ +import QtQuick +import QtQuick.Layouts + +Rectangle { + id: root + + required property var libraryInfo + + property int panelMargin: 30 + property color secondaryTextColor: infoMetadataTextColor + + color: "transparent" + height: content.implicitHeight + panelMargin * 2 + + component MetadataText: Text { + font.family: fontFamily + font.pointSize: fontSize + 1 + } + + ColumnLayout { + id: content + x: root.panelMargin + y: root.panelMargin + width: root.width - root.panelMargin * 2 + spacing: 12 + + Text { + Layout.fillWidth: true + text: root.libraryInfo.name ?? "" + color: infoTextColor + font.family: "Arial" + font.bold: true + font.pixelSize: 21 + wrapMode: Text.WordWrap + horizontalAlignment: Text.AlignHCenter + } + + Text { + Layout.fillWidth: true + text: qsTr("Library info") + color: root.secondaryTextColor + font.family: fontFamily + font.pointSize: fontSize + 1 + font.bold: true + horizontalAlignment: Text.AlignHCenter + } + + Text { + Layout.fillWidth: true + Layout.topMargin: 12 + text: root.libraryInfo.path ?? "" + color: themeLinkColor + font.family: fontFamily + font.pointSize: fontSize + 1 + font.underline: pathMouseArea.containsMouse + wrapMode: Text.WrapAtWordBoundaryOrAnywhere + + MouseArea { + id: pathMouseArea + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: currentIndexHelper.requestOpenLibraryFolder() + } + } + + GridLayout { + Layout.fillWidth: true + Layout.topMargin: 6 + columns: 2 + columnSpacing: 18 + rowSpacing: 12 + + MetadataText { text: qsTr("Number of folders"); color: root.secondaryTextColor } + MetadataText { text: root.libraryInfo.folderCount ?? 0; color: infoTextColor; Layout.fillWidth: true } + + MetadataText { text: qsTr("Number of comics"); color: root.secondaryTextColor } + MetadataText { text: root.libraryInfo.comicCount ?? 0; color: infoTextColor; Layout.fillWidth: true } + + MetadataText { text: qsTr("Number of read comics"); color: root.secondaryTextColor } + MetadataText { text: root.libraryInfo.readComicCount ?? 0; color: infoTextColor; Layout.fillWidth: true } + } + } +} diff --git a/YACReaderLibrary/qml/ListInfoView.qml b/YACReaderLibrary/qml/ListInfoView.qml new file mode 100644 index 000000000..a23a62115 --- /dev/null +++ b/YACReaderLibrary/qml/ListInfoView.qml @@ -0,0 +1,78 @@ +import QtQuick +import QtQuick.Layouts + +Rectangle { + id: root + + required property var listInfo + + property int panelMargin: 30 + property color secondaryTextColor: infoMetadataTextColor + + color: "transparent" + height: content.implicitHeight + panelMargin * 2 + + ColumnLayout { + id: content + x: root.panelMargin + y: root.panelMargin + width: root.width - root.panelMargin * 2 + spacing: 12 + + Image { + Layout.alignment: Qt.AlignHCenter + Layout.preferredWidth: Math.min(110, content.width) + Layout.preferredHeight: 95 + source: root.listInfo.icon ?? "" + fillMode: Image.PreserveAspectFit + visible: source.toString().length > 0 + } + + Text { + Layout.fillWidth: true + Layout.topMargin: 8 + text: root.listInfo.name ?? "" + color: infoTextColor + font.family: "Arial" + font.bold: true + font.pixelSize: 21 + wrapMode: Text.WordWrap + horizontalAlignment: Text.AlignHCenter + } + + Text { + Layout.fillWidth: true + text: (root.listInfo.itemCount ?? 0) === 1 + ? qsTr("1 comic") + : qsTr("%1 comics").arg(root.listInfo.itemCount ?? 0) + color: root.secondaryTextColor + font.family: fontFamily + font.pointSize: fontSize + 1 + horizontalAlignment: Text.AlignHCenter + } + + Text { + Layout.fillWidth: true + text: (root.listInfo.recentDays ?? 0) === 1 + ? qsTr("Last day") + : qsTr("Last %1 days").arg(root.listInfo.recentDays ?? 0) + color: root.secondaryTextColor + font.family: fontFamily + font.pointSize: fontSize + 1 + horizontalAlignment: Text.AlignHCenter + visible: (root.listInfo.recentDays ?? 0) > 0 + } + + Text { + Layout.fillWidth: true + text: (root.listInfo.sublistCount ?? 0) === 1 + ? qsTr("1 sublist") + : qsTr("%1 sublists").arg(root.listInfo.sublistCount ?? 0) + color: root.secondaryTextColor + font.family: fontFamily + font.pointSize: fontSize + 1 + horizontalAlignment: Text.AlignHCenter + visible: (root.listInfo.sublistCount ?? 0) > 0 + } + } +} diff --git a/YACReaderLibrary/qml/SelectedComicsInfoView.qml b/YACReaderLibrary/qml/SelectedComicsInfoView.qml new file mode 100644 index 000000000..338fed2a1 --- /dev/null +++ b/YACReaderLibrary/qml/SelectedComicsInfoView.qml @@ -0,0 +1,93 @@ +import QtQuick +import QtQuick.Layouts + +Rectangle { + id: root + + required property var selectionInfo + + property int panelMargin: 30 + property color secondaryTextColor: infoMetadataTextColor + + readonly property bool hasSeries: (selectionInfo.seriesCount ?? 0) > 0 + + color: "transparent" + height: content.implicitHeight + panelMargin * 2 + + component MetadataText: Text { + font.family: fontFamily + font.pointSize: fontSize + 1 + } + + function pagesText() { + const pages = root.selectionInfo.pageCount ?? 0 + const unknown = root.selectionInfo.unknownPageCount ?? 0 + if (pages === 0) + return qsTr("Unknown") + if (unknown > 0) + return qsTr("%1 (%2 unknown)").arg(pages).arg(unknown) + return pages + } + + function seriesText() { + const count = root.selectionInfo.seriesCount ?? 0 + if (count === 1) + return root.selectionInfo.seriesName ?? "" + return qsTr("%1 series").arg(count) + } + + ColumnLayout { + id: content + x: root.panelMargin + y: root.panelMargin + width: root.width - root.panelMargin * 2 + spacing: 12 + + FolderCover { + Layout.alignment: Qt.AlignHCenter + Layout.preferredWidth: Math.min(220, content.width) + Layout.preferredHeight: Layout.preferredWidth * coverHeight / coverWidth + readonly property var covers: root.selectionInfo.covers ?? [] + coverSource: covers.length > 0 ? covers[0] : "" + stackedCoverSources: covers + } + + Text { + Layout.fillWidth: true + Layout.topMargin: 6 + text: qsTr("%1 comics selected").arg(root.selectionInfo.count ?? 0) + color: infoTextColor + font.family: "Arial" + font.bold: true + font.pixelSize: 21 + wrapMode: Text.WordWrap + horizontalAlignment: Text.AlignHCenter + } + + GridLayout { + Layout.fillWidth: true + Layout.topMargin: 6 + columns: 2 + columnSpacing: 18 + rowSpacing: 9 + + MetadataText { text: qsTr("Series"); color: root.secondaryTextColor; visible: root.hasSeries } + MetadataText { text: root.seriesText(); color: infoTextColor; Layout.fillWidth: true; visible: root.hasSeries } + + MetadataText { text: qsTr("Read"); color: root.secondaryTextColor } + MetadataText { text: root.selectionInfo.readCount ?? 0; color: infoTextColor; Layout.fillWidth: true } + + MetadataText { text: qsTr("In progress"); color: root.secondaryTextColor } + MetadataText { text: root.selectionInfo.inProgressCount ?? 0; color: infoTextColor; Layout.fillWidth: true } + + MetadataText { text: qsTr("Unread"); color: root.secondaryTextColor } + MetadataText { text: root.selectionInfo.unreadCount ?? 0; color: infoTextColor; Layout.fillWidth: true } + + MetadataText { text: qsTr("Total pages"); color: root.secondaryTextColor } + MetadataText { text: root.pagesText(); color: infoTextColor; Layout.fillWidth: true } + + MetadataText { text: qsTr("Total size"); color: root.secondaryTextColor } + MetadataText { text: root.selectionInfo.size ?? ""; color: infoTextColor; Layout.fillWidth: true } + } + } +} diff --git a/YACReaderLibrary/reading_list_management_coordinator.cpp b/YACReaderLibrary/reading_list_management_coordinator.cpp new file mode 100644 index 000000000..a691097da --- /dev/null +++ b/YACReaderLibrary/reading_list_management_coordinator.cpp @@ -0,0 +1,87 @@ +#include "reading_list_management_coordinator.h" + +#include "add_label_dialog.h" +#include "comic_model.h" +#include "reading_list_model.h" + +#include +#include +#include +#include + +#include + +ReadingListManagementCoordinator::ReadingListManagementCoordinator(QWidget *dialogParent, + ReadingListModel *listsModel, + ComicModel *comicsModel, + CurrentListProvider currentListProvider) + : QObject(dialogParent), dialogParent(dialogParent), listsModel(listsModel), currentListProvider(std::move(currentListProvider)) +{ + connect(listsModel, &ReadingListModel::addComicsToFavorites, comicsModel, QOverload &>::of(&ComicModel::addComicsToFavorites)); + connect(listsModel, &ReadingListModel::addComicsToLabel, comicsModel, QOverload &, qulonglong>::of(&ComicModel::addComicsToLabel)); + connect(listsModel, &ReadingListModel::addComicsToReadingList, comicsModel, QOverload &, qulonglong>::of(&ComicModel::addComicsToReadingList)); +} + +void ReadingListManagementCoordinator::addReadingList() +{ + const auto currentList = currentListProvider(); + if (currentList.isValid() && listsModel->isReadingSubList(currentList)) + return; + + bool accepted = false; + const auto name = QInputDialog::getText(dialogParent, + tr("Add new reading lists"), + tr("List name:"), + QLineEdit::Normal, + { }, + &accepted); + if (!accepted) + return; + + if (currentList.isValid() && listsModel->isReadingList(currentList)) + listsModel->addReadingListAt(name, currentList); + else + listsModel->addReadingList(name); +} + +void ReadingListManagementCoordinator::deleteCurrentList() +{ + const auto currentList = currentListProvider(); + if (!currentList.isValid() || !listsModel->isEditable(currentList)) + return; + + const auto answer = QMessageBox::question(dialogParent, + tr("Delete list/label"), + tr("The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure?"), + QMessageBox::Yes, + QMessageBox::No); + if (answer != QMessageBox::Yes) + return; + + listsModel->deleteItem(currentList); + emit currentListReselectionRequested(); +} + +void ReadingListManagementCoordinator::addLabel() +{ + AddLabelDialog dialog(dialogParent); + if (dialog.exec() == QDialog::Accepted) + listsModel->addNewLabel(dialog.name(), dialog.selectedColor()); +} + +void ReadingListManagementCoordinator::renameCurrentList() +{ + const auto currentList = currentListProvider(); + if (!currentList.isValid() || !listsModel->isEditable(currentList)) + return; + + bool accepted = false; + const auto name = QInputDialog::getText(dialogParent, + tr("Rename list name"), + tr("List name:"), + QLineEdit::Normal, + listsModel->name(currentList), + &accepted); + if (accepted) + listsModel->rename(currentList, name); +} diff --git a/YACReaderLibrary/reading_list_management_coordinator.h b/YACReaderLibrary/reading_list_management_coordinator.h new file mode 100644 index 000000000..d41181efc --- /dev/null +++ b/YACReaderLibrary/reading_list_management_coordinator.h @@ -0,0 +1,40 @@ +#ifndef READING_LIST_MANAGEMENT_COORDINATOR_H +#define READING_LIST_MANAGEMENT_COORDINATOR_H + +#include +#include + +#include + +class ComicModel; +class ReadingListModel; +class QWidget; + +class ReadingListManagementCoordinator : public QObject +{ + Q_OBJECT + +public: + using CurrentListProvider = std::function; + + ReadingListManagementCoordinator(QWidget *dialogParent, + ReadingListModel *listsModel, + ComicModel *comicsModel, + CurrentListProvider currentListProvider); + +public slots: + void addReadingList(); + void deleteCurrentList(); + void addLabel(); + void renameCurrentList(); + +signals: + void currentListReselectionRequested(); + +private: + QWidget *dialogParent; + ReadingListModel *listsModel; + CurrentListProvider currentListProvider; +}; + +#endif // READING_LIST_MANAGEMENT_COORDINATOR_H diff --git a/YACReaderLibrary/recent_visibility_coordinator.cpp b/YACReaderLibrary/recent_visibility_coordinator.cpp index f62979e2a..151be5835 100644 --- a/YACReaderLibrary/recent_visibility_coordinator.cpp +++ b/YACReaderLibrary/recent_visibility_coordinator.cpp @@ -3,8 +3,8 @@ #include "yacreader_global_gui.h" -RecentVisibilityCoordinator::RecentVisibilityCoordinator(QSettings *settings, FolderModel *folderModel, FolderContentView *folderContentView, ComicModel *comicModel) - : QObject(), settings(settings), folderModel(folderModel), folderContentView(folderContentView), comicModel(comicModel) +RecentVisibilityCoordinator::RecentVisibilityCoordinator(QSettings *settings, FolderModel *folderModel, ComicModel *comicModel) + : QObject(), settings(settings), folderModel(folderModel), comicModel(comicModel) { updateVisibility(); updateTimeRange(); @@ -21,7 +21,6 @@ void RecentVisibilityCoordinator::updateTimeRange() { auto days = settings->value(NUM_DAYS_TO_CONSIDER_RECENT, 1).toInt(); folderModel->setRecentRange(days); - folderContentView->setRecentRange(days); comicModel->setRecentRange(days); } @@ -30,6 +29,5 @@ void RecentVisibilityCoordinator::updateVisibility() auto visibility = settings->value(DISPLAY_RECENTLY_INDICATOR, true).toBool(); folderModel->setShowRecent(visibility); - folderContentView->setShowRecent(visibility); comicModel->setShowRecent(visibility); } diff --git a/YACReaderLibrary/recent_visibility_coordinator.h b/YACReaderLibrary/recent_visibility_coordinator.h index b6e917ceb..729ba23b5 100644 --- a/YACReaderLibrary/recent_visibility_coordinator.h +++ b/YACReaderLibrary/recent_visibility_coordinator.h @@ -3,14 +3,13 @@ #define RECENT_VISIBILITY_COORDINATOR_H #include "comic_model.h" -#include "folder_content_view.h" #include "folder_model.h" class RecentVisibilityCoordinator : public QObject { Q_OBJECT public: - explicit RecentVisibilityCoordinator(QSettings *settings, FolderModel *folderModel, FolderContentView *folderContentView, ComicModel *comicModel); + explicit RecentVisibilityCoordinator(QSettings *settings, FolderModel *folderModel, ComicModel *comicModel); public slots: void toggleVisibility(bool visibility); @@ -19,7 +18,6 @@ public slots: private: QSettings *settings; FolderModel *folderModel; - FolderContentView *folderContentView; ComicModel *comicModel; void updateVisibility(); diff --git a/YACReaderLibrary/search_syntax_dialog.cpp b/YACReaderLibrary/search_syntax_dialog.cpp index f90e9e2c6..d4baf7ec7 100644 --- a/YACReaderLibrary/search_syntax_dialog.cpp +++ b/YACReaderLibrary/search_syntax_dialog.cpp @@ -265,7 +265,8 @@ QWidget *SearchSyntaxDialog::createFieldsTab() tr("Input"), tr("Example") }); - for (const auto category : fieldCategories()) { + const auto categories = fieldCategories(); + for (const auto category : categories) { QList categoryRow { new QStandardItem(categoryName(category)), new QStandardItem(), diff --git a/YACReaderLibrary/server/controllers/v2/favoritescontroller_v2.cpp b/YACReaderLibrary/server/controllers/v2/favoritescontroller_v2.cpp index b7e35dc50..d455537be 100644 --- a/YACReaderLibrary/server/controllers/v2/favoritescontroller_v2.cpp +++ b/YACReaderLibrary/server/controllers/v2/favoritescontroller_v2.cpp @@ -27,7 +27,7 @@ void FavoritesControllerV2::serviceContent(const int library, HttpResponse &resp { auto libraryUuid = DBHelper::getLibraries().getLibraryIdFromLegacyId(library); - QList comics = DBHelper::getFavorites(library); + const QList comics = DBHelper::getFavorites(library); QJsonArray items; diff --git a/YACReaderLibrary/server/controllers/v2/librariescontroller_v2.cpp b/YACReaderLibrary/server/controllers/v2/librariescontroller_v2.cpp index 4039ef2c8..ee32bbe15 100644 --- a/YACReaderLibrary/server/controllers/v2/librariescontroller_v2.cpp +++ b/YACReaderLibrary/server/controllers/v2/librariescontroller_v2.cpp @@ -12,7 +12,7 @@ void LibrariesControllerV2::service(HttpRequest & /* request */, HttpResponse &r { response.setHeader("Content-Type", "application/json"); - auto libraries = DBHelper::getLibraries().sortedLibraries(); + const auto libraries = DBHelper::getLibraries().sortedLibraries(); QJsonArray librariesJson; diff --git a/YACReaderLibrary/server/controllers/v2/readingcomicscontroller_v2.cpp b/YACReaderLibrary/server/controllers/v2/readingcomicscontroller_v2.cpp index 2b10a767c..78e552d91 100644 --- a/YACReaderLibrary/server/controllers/v2/readingcomicscontroller_v2.cpp +++ b/YACReaderLibrary/server/controllers/v2/readingcomicscontroller_v2.cpp @@ -30,7 +30,7 @@ void ReadingComicsControllerV2::serviceContent(const int &library, HttpResponse { auto libraryUuid = DBHelper::getLibraries().getLibraryIdFromLegacyId(library); - QList readingComics = DBHelper::getReading(library); + const QList readingComics = DBHelper::getReading(library); QJsonArray comics; diff --git a/YACReaderLibrary/server/controllers/v2/readinglistcontentcontroller_v2.cpp b/YACReaderLibrary/server/controllers/v2/readinglistcontentcontroller_v2.cpp index 353324ac6..089403c86 100644 --- a/YACReaderLibrary/server/controllers/v2/readinglistcontentcontroller_v2.cpp +++ b/YACReaderLibrary/server/controllers/v2/readinglistcontentcontroller_v2.cpp @@ -30,7 +30,7 @@ void ReadingListContentControllerV2::serviceContent(const int &library, const qu { auto libraryUuid = DBHelper::getLibraries().getLibraryIdFromLegacyId(library); - QList comics = DBHelper::getReadingListFullContent(library, readingListId); + const QList comics = DBHelper::getReadingListFullContent(library, readingListId); QJsonArray items; diff --git a/YACReaderLibrary/server/controllers/v2/readinglistinfocontroller_v2.cpp b/YACReaderLibrary/server/controllers/v2/readinglistinfocontroller_v2.cpp index 51a48b168..a120f1afc 100644 --- a/YACReaderLibrary/server/controllers/v2/readinglistinfocontroller_v2.cpp +++ b/YACReaderLibrary/server/controllers/v2/readinglistinfocontroller_v2.cpp @@ -26,7 +26,7 @@ void ReadingListInfoControllerV2::service(HttpRequest &request, HttpResponse &re void ReadingListInfoControllerV2::serviceComics(const int &library, const qulonglong &readingListId, HttpResponse &response) { - QList comics = DBHelper::getReadingListFullContent(library, readingListId); + const QList comics = DBHelper::getReadingListFullContent(library, readingListId); for (const ComicDB &comic : comics) { response.write(QString("/v2/library/%1/comic/%2:%3:%4:%5:%6\r\n") diff --git a/YACReaderLibrary/server/controllers/v2/tagcontentcontroller_v2.cpp b/YACReaderLibrary/server/controllers/v2/tagcontentcontroller_v2.cpp index 301f665ef..8b4e6c63e 100644 --- a/YACReaderLibrary/server/controllers/v2/tagcontentcontroller_v2.cpp +++ b/YACReaderLibrary/server/controllers/v2/tagcontentcontroller_v2.cpp @@ -32,7 +32,7 @@ void TagContentControllerV2::serviceContent(const int &library, const qulonglong { auto libraryUuid = DBHelper::getLibraries().getLibraryIdFromLegacyId(library); - QList comics = DBHelper::getLabelComics(library, tagId); + const QList comics = DBHelper::getLabelComics(library, tagId); QJsonArray items; diff --git a/YACReaderLibrary/server/controllers/v2/taginfocontroller_v2.cpp b/YACReaderLibrary/server/controllers/v2/taginfocontroller_v2.cpp index e7d3205ec..3cf49a05f 100644 --- a/YACReaderLibrary/server/controllers/v2/taginfocontroller_v2.cpp +++ b/YACReaderLibrary/server/controllers/v2/taginfocontroller_v2.cpp @@ -26,7 +26,7 @@ void TagInfoControllerV2::service(HttpRequest &request, HttpResponse &response) void TagInfoControllerV2::serviceComics(const int &library, const qulonglong &tagId, HttpResponse &response) { - QList comics = DBHelper::getLabelComics(library, tagId); + const QList comics = DBHelper::getLabelComics(library, tagId); for (const ComicDB &comic : comics) { response.write(QString("/v2/library/%1/comic/%2:%3:%4:%5:%6\r\n") diff --git a/YACReaderLibrary/server/controllers/webui/webuicontroller.cpp b/YACReaderLibrary/server/controllers/webui/webuicontroller.cpp index b2c01aece..c442f0336 100644 --- a/YACReaderLibrary/server/controllers/webui/webuicontroller.cpp +++ b/YACReaderLibrary/server/controllers/webui/webuicontroller.cpp @@ -459,6 +459,21 @@ void WebUIController::renderLibraryBrowser(HttpRequest &request,

{library.name}

+
diff --git a/YACReaderLibrary/server/requestmapper.cpp b/YACReaderLibrary/server/requestmapper.cpp index f7085e579..610715717 100644 --- a/YACReaderLibrary/server/requestmapper.cpp +++ b/YACReaderLibrary/server/requestmapper.cpp @@ -94,7 +94,6 @@ void RequestMapper::serviceV2(HttpRequest &request, HttpResponse &response) QRegExp comicOpenForRemoteReadingInAReadingList("/v2/library/.+/reading_list/[0-9]+/comic/[0-9]+/remote/?"); // the server will open for reading the comic QRegExp comicFullInfo("/v2/library/.+/comic/[0-9]+/fullinfo/?"); // get comic info QRegExp comicUpdate("/v2/library/.+/comic/[0-9]+/update/?"); // get comic info - QRegExp comicClose("/v2/library/.+/comic/[0-9]+/close/?"); // the server will close the comic and free memory QRegExp cover("/v2/library/.+/cover/.+"); // get comic cover (navigation) QRegExp comicPage("/v2/library/.+/comic/[0-9]+/page/[0-9]+/?"); // get comic page QRegExp comicPageRemote("/v2/library/.+/comic/[0-9]+/page/[0-9]+/remote?"); // get comic page (remote reading) diff --git a/YACReaderLibrary/themes/theme.h b/YACReaderLibrary/themes/theme.h index 57719ffca..445beead8 100644 --- a/YACReaderLibrary/themes/theme.h +++ b/YACReaderLibrary/themes/theme.h @@ -128,6 +128,7 @@ struct EmptyContainerTheme { QPixmap emptyFolderIcon; QPixmap emptyFavoritesIcon; QPixmap emptyCurrentReadingsIcon; + QPixmap emptyRecentIcon; QPixmap emptyReadingListIcon; QMap emptyLabelIcons; // Keyed by YACReader::LabelColors enum value }; @@ -211,7 +212,7 @@ struct NavigationTreeTheme { QIcon folderFinishedIcon; }; -// Grid and info view theme colors (used by GridComicsView, FolderContentView, InfoComicsView) +// Grid and info view theme colors (used by GridComicsView and InfoComicsView) struct GridAndInfoViewTheme { // Grid colors QColor backgroundColor; @@ -243,7 +244,7 @@ struct GridAndInfoViewTheme { // Current comic banner QColor currentComicBackgroundColor; - // Continue reading section (FolderContentView) + // Continue reading section (grid content view) QColor continueReadingBackgroundColor; QColor continueReadingTextColor; @@ -422,6 +423,7 @@ struct ComicsViewToolbarTheme { QIcon setAsMangaIcon; QIcon editComicIcon; QIcon getInfoIcon; + QIcon organizeIcon; QIcon assignNumberIcon; QIcon selectAllIcon; QIcon deleteIcon; diff --git a/YACReaderLibrary/themes/theme_factory.cpp b/YACReaderLibrary/themes/theme_factory.cpp index 11ead49c9..84557f177 100644 --- a/YACReaderLibrary/themes/theme_factory.cpp +++ b/YACReaderLibrary/themes/theme_factory.cpp @@ -176,7 +176,7 @@ struct GridAndInfoViewParams { // Current comic banner QColor currentComicBackgroundColor; - // Continue reading section (FolderContentView) + // Continue reading section (grid content view) QColor continueReadingBackgroundColor; QColor continueReadingTextColor; @@ -419,15 +419,17 @@ Theme makeTheme(const ThemeParams ¶ms) const auto &msd = params.metadataScraperDialogParams; const auto &t = msd.t; - auto recolor = [&](const QString &path, const QColor &color) { - return recoloredSvgToThemeFile(path, color, params.meta.id); + // Recolored icons are written to a flat per-theme folder keyed by the source file + // name, so any icon recolored more than once needs a suffix to get its own file. + auto recolor = [&](const QString &path, const QColor &color, const QString &suffix = { }) { + return recoloredSvgToThemeFile(path, color, params.meta.id, { .suffix = suffix }); }; theme.metadataScraperDialog.defaultLabelQSS = t.defaultLabelQSS.arg(msd.labelTextColor.name()); theme.metadataScraperDialog.titleLabelQSS = t.titleLabelQSS.arg(msd.labelTextColor.name()); theme.metadataScraperDialog.coverLabelQSS = t.coverLabelQSS.arg(msd.labelBackgroundColor.name(), msd.labelTextColor.name()); theme.metadataScraperDialog.radioButtonQSS = t.radioButtonQSS.arg(msd.buttonTextColor.name(), recolor(":/images/comic_vine/radioUnchecked.svg", msd.radioUncheckedColor), recoloredSvgToThemeFile(":/images/comic_vine/radioChecked.svg", msd.radioCheckedBackgroundColor, msd.radioCheckedIndicatorColor, params.meta.id)); - theme.metadataScraperDialog.checkBoxQSS = t.checkBoxQSS.arg(msd.buttonTextColor.name(), msd.buttonBorderColor.name(), msd.buttonBackgroundColor.name(), recolor(":/images/comic_vine/checkBoxTick.svg", msd.checkBoxTickColor)); + theme.metadataScraperDialog.checkBoxQSS = t.checkBoxQSS.arg(msd.buttonTextColor.name(), msd.buttonBorderColor.name(), msd.buttonBackgroundColor.name(), recolor(":/images/comic_vine/checkBoxTick.svg", msd.checkBoxTickColor, "_metadata_scraper")); theme.metadataScraperDialog.scraperLineEditTitleLabelQSS = t.scraperLineEditTitleLabelQSS.arg(msd.contentTextColor.name()); theme.metadataScraperDialog.scraperLineEditQSS = t.scraperLineEditQSS.arg(msd.contentAltBackgroundColor.name(), msd.contentTextColor.name(), "%1"); @@ -497,6 +499,7 @@ Theme makeTheme(const ThemeParams ¶ms) theme.emptyContainer.emptyFolderIcon = renderSvgToPixmap(recoloredSvgToThemeFile(":/images/empty_container/empty_folder.svg", ec.iconColor, params.meta.id), 319, 243, dpr); theme.emptyContainer.emptyFavoritesIcon = renderSvgToPixmap(recoloredSvgToThemeFile(":/images/empty_container/empty_favorites.svg", rli.favoritesMainColor, params.meta.id), 238, 223, dpr); theme.emptyContainer.emptyCurrentReadingsIcon = renderSvgToPixmap(recoloredSvgToThemeFile(":/images/empty_container/empty_current_readings.svg", ec.iconColor, params.meta.id), 167, 214, dpr); + theme.emptyContainer.emptyRecentIcon = renderSvgToPixmap(recoloredSvgToThemeFile(":/images/lists/default_2.svg", rli.currentlyReadingMainColor, rli.specialListShadowColor, rli.currentlyReadingOuterColor, params.meta.id), 167, dpr); theme.emptyContainer.emptyReadingListIcon = renderSvgToPixmap(recoloredSvgToThemeFile(":/images/empty_container/empty_reading_list.svg", ec.iconColor, params.meta.id), 248, 187, dpr); // Generate empty label icons for each label color @@ -822,6 +825,7 @@ Theme makeTheme(const ThemeParams ¶ms) theme.comicsViewToolbar.setAsMangaIcon = makeComicsViewIcon(":/images/comics_view_toolbar/setManga.svg"); theme.comicsViewToolbar.editComicIcon = makeComicsViewIcon(":/images/comics_view_toolbar/editComic.svg"); theme.comicsViewToolbar.getInfoIcon = makeComicsViewIcon(":/images/comics_view_toolbar/getInfo.svg"); + theme.comicsViewToolbar.organizeIcon = makeComicsViewIcon(":/images/comics_view_toolbar/organize.svg"); theme.comicsViewToolbar.assignNumberIcon = makeComicsViewIcon(":/images/comics_view_toolbar/asignNumber.svg"); theme.comicsViewToolbar.selectAllIcon = makeComicsViewIcon(":/images/comics_view_toolbar/selectAll.svg"); theme.comicsViewToolbar.deleteIcon = makeComicsViewIcon(":/images/comics_view_toolbar/trash.svg"); @@ -955,13 +959,13 @@ Theme makeTheme(const ThemeParams ¶ms) const auto &scd = params.serverConfigDialogParams; QColor cardColor = scd.backgroundColor; cardColor = cardColor.darker(cardColor.lightness() > 127 ? 104 : 112); - theme.serverConfigDialog.dialogQSS = scd.t.dialogQSS.arg(scd.backgroundColor.name(), scd.textColor.name(), scd.borderColor.name(), scd.accentColor.name(), cardColor.name(), recolor(":/images/chevronDown.svg", scd.accentColor), scd.secondaryTextColor.name(), scd.accentForegroundColor.name(), recolor(":/images/chevronDown.svg", scd.secondaryTextColor)); + theme.serverConfigDialog.dialogQSS = scd.t.dialogQSS.arg(scd.backgroundColor.name(), scd.textColor.name(), scd.borderColor.name(), scd.accentColor.name(), cardColor.name(), recolor(":/images/chevronDown.svg", scd.accentColor, "_accent"), scd.secondaryTextColor.name(), scd.accentForegroundColor.name(), recolor(":/images/chevronDown.svg", scd.secondaryTextColor, "_disabled")); theme.serverConfigDialog.titleLabelQSS = scd.t.titleLabelQSS.arg(scd.titleTextColor.name()); theme.serverConfigDialog.qrMessageLabelQSS = scd.t.qrMessageLabelQSS.arg(scd.qrMessageTextColor.name()); theme.serverConfigDialog.propagandaLabelQSS = scd.t.propagandaLabelQSS.arg(scd.propagandaTextColor.name()); theme.serverConfigDialog.textLabelQSS = scd.t.textLabelQSS.arg(scd.textColor.name()); theme.serverConfigDialog.secondaryLabelQSS = scd.t.secondaryLabelQSS.arg(scd.secondaryTextColor.name()); - theme.serverConfigDialog.checkBoxQSS = scd.t.checkBoxQSS.arg(scd.textColor.name(), scd.accentColor.name(), recolor(":/images/comic_vine/checkBoxTick.svg", scd.accentForegroundColor)); + theme.serverConfigDialog.checkBoxQSS = scd.t.checkBoxQSS.arg(scd.textColor.name(), scd.accentColor.name(), recolor(":/images/comic_vine/checkBoxTick.svg", scd.accentForegroundColor, "_server_config")); theme.serverConfigDialog.linkColor = scd.linkColor; theme.serverConfigDialog.qrBackgroundColor = scd.qrBackgroundColor; theme.serverConfigDialog.qrForegroundColor = scd.qrForegroundColor; diff --git a/YACReaderLibrary/trayicon_controller.cpp b/YACReaderLibrary/trayicon_controller.cpp index 4a9ae8098..837568540 100644 --- a/YACReaderLibrary/trayicon_controller.cpp +++ b/YACReaderLibrary/trayicon_controller.cpp @@ -36,7 +36,7 @@ TrayIconController::TrayIconController(QSettings *settings, LibraryWindow *windo } connect(&trayIcon, &QSystemTrayIcon::activated, this, - [=](QSystemTrayIcon::ActivationReason reason) { + [=, this](QSystemTrayIcon::ActivationReason reason) { #ifdef Q_OS_LINUX auto expectedReason = QSystemTrayIcon::Trigger; #else diff --git a/YACReaderLibrary/yacreader_comics_selection_helper.cpp b/YACReaderLibrary/yacreader_comics_selection_helper.cpp index 4aebc4fcd..0a109ff59 100644 --- a/YACReaderLibrary/yacreader_comics_selection_helper.cpp +++ b/YACReaderLibrary/yacreader_comics_selection_helper.cpp @@ -2,8 +2,15 @@ #include "comic_model.h" +#include +#include +#include + +#include +#include + YACReaderComicsSelectionHelper::YACReaderComicsSelectionHelper(QObject *parent) - : QObject(parent), _selectionModel(nullptr) + : QObject(parent) { } @@ -14,89 +21,148 @@ void YACReaderComicsSelectionHelper::setModel(ComicModel *model) this->model = model; - if (_selectionModel != nullptr) - delete _selectionModel; + delete itemSelectionModel; + + itemSelectionModel = new QItemSelectionModel(model, this); + connect(itemSelectionModel, &QItemSelectionModel::selectionChanged, this, [this]() { + ++revision; + emit selectionChanged(); + }); - _selectionModel = new QItemSelectionModel(model); + ++revision; + emit selectionChanged(); } void YACReaderComicsSelectionHelper::selectIndex(int index) { - if (_selectionModel != nullptr && model != nullptr) { - _selectionModel->select(model->index(index, 0), QItemSelectionModel::Select | QItemSelectionModel::Rows); + if (itemSelectionModel != nullptr && model != nullptr && index >= 0 && index < model->rowCount()) + itemSelectionModel->select(model->index(index, 0), QItemSelectionModel::Select | QItemSelectionModel::Rows); +} - emit selectionChanged(); - } +void YACReaderComicsSelectionHelper::selectOnly(int index) +{ + if (itemSelectionModel != nullptr && model != nullptr && index >= 0 && index < model->rowCount()) + itemSelectionModel->select(model->index(index, 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); } void YACReaderComicsSelectionHelper::deselectIndex(int index) { - if (_selectionModel != nullptr && model != nullptr) { - _selectionModel->select(model->index(index, 0), QItemSelectionModel::Deselect | QItemSelectionModel::Rows); - - emit selectionChanged(); - } + if (itemSelectionModel != nullptr && model != nullptr && index >= 0 && index < model->rowCount()) + itemSelectionModel->select(model->index(index, 0), QItemSelectionModel::Deselect | QItemSelectionModel::Rows); } bool YACReaderComicsSelectionHelper::isSelectedIndex(int index) const { - if (_selectionModel != nullptr && model != nullptr) { + if (itemSelectionModel != nullptr && model != nullptr) { QModelIndex mi = model->index(index, 0); - return _selectionModel->isSelected(mi); + return itemSelectionModel->isSelected(mi); } return false; } void YACReaderComicsSelectionHelper::clear() { - if (_selectionModel != nullptr) { - _selectionModel->clear(); - - emit selectionChanged(); - } + if (itemSelectionModel != nullptr) + itemSelectionModel->clear(); } QModelIndex YACReaderComicsSelectionHelper::currentIndex() { - if (!_selectionModel) + if (!itemSelectionModel) return QModelIndex(); - QModelIndexList indexes = _selectionModel->selectedRows(); + QModelIndexList indexes = itemSelectionModel->selectedRows(); if (indexes.length() > 0) return indexes[0]; - this->selectIndex(0); - indexes = _selectionModel->selectedRows(); - if (indexes.length() > 0) - return indexes[0]; - else - return QModelIndex(); + return QModelIndex(); } void YACReaderComicsSelectionHelper::selectAll() { + if (!itemSelectionModel || !model || model->rowCount() == 0) + return; + QModelIndex top = model->index(0, 0); QModelIndex bottom = model->index(model->rowCount() - 1, 0); QItemSelection selection(top, bottom); - _selectionModel->select(selection, QItemSelectionModel::Select | QItemSelectionModel::Rows); - - emit selectionChanged(); + itemSelectionModel->select(selection, QItemSelectionModel::Select | QItemSelectionModel::Rows); } QModelIndexList YACReaderComicsSelectionHelper::selectedRows(int column) const { - return _selectionModel->selectedRows(column); + return itemSelectionModel ? itemSelectionModel->selectedRows(column) : QModelIndexList(); } QList YACReaderComicsSelectionHelper::selectedIndexes() const { - return _selectionModel->selectedIndexes(); + return itemSelectionModel ? itemSelectionModel->selectedIndexes() : QModelIndexList(); +} + +QVariantMap YACReaderComicsSelectionHelper::selectionInfo() const +{ + QVariantMap info; + if (!itemSelectionModel || !model) + return info; + + // selectedRows() groups the indexes by selection range, so sort them to get + // the covers of the first comics of the selection, in the order they are + // shown in the grid. + auto rows = itemSelectionModel->selectedRows(); + std::sort(rows.begin(), rows.end(), [](const QModelIndex &a, const QModelIndex &b) { + return a.row() < b.row(); + }); + + int readCount = 0; + int inProgressCount = 0; + int pageCount = 0; + int unknownPageCount = 0; + qint64 totalSize = 0; + QSet series; + QVariantList covers; + + for (const auto &index : std::as_const(rows)) { + const bool read = index.data(ComicModel::ReadColumnRole).toBool(); + const bool inProgress = !read && index.data(ComicModel::HasBeenOpenedRole).toBool() && index.data(ComicModel::CurrentPageRole).toInt() > 0; + readCount += read ? 1 : 0; + inProgressCount += inProgress ? 1 : 0; + + const auto pages = index.data(ComicModel::NumPagesRole); + if (pages.isValid() && pages.toInt() > 0) + pageCount += pages.toInt(); + else + ++unknownPageCount; + + // The size in bytes is stored at the end of the hash, right after the 40 + // characters of the SHA1 digest. + totalSize += index.data(ComicModel::HashRole).toString().mid(40).toLongLong(); + + const QString seriesName = index.data(ComicModel::SeriesRole).toString().trimmed(); + if (!seriesName.isEmpty()) + series.insert(seriesName); + + if (covers.size() < 3) + covers.append(index.data(ComicModel::CoverPathRole)); + } + + info.insert(QStringLiteral("count"), rows.size()); + info.insert(QStringLiteral("readCount"), readCount); + info.insert(QStringLiteral("inProgressCount"), inProgressCount); + info.insert(QStringLiteral("unreadCount"), rows.size() - readCount - inProgressCount); + info.insert(QStringLiteral("pageCount"), pageCount); + info.insert(QStringLiteral("unknownPageCount"), unknownPageCount); + info.insert(QStringLiteral("size"), QLocale().formattedDataSize(totalSize, 2, QLocale::DataSizeTraditionalFormat)); + info.insert(QStringLiteral("seriesCount"), series.size()); + if (series.size() == 1) + info.insert(QStringLiteral("seriesName"), *series.cbegin()); + info.insert(QStringLiteral("covers"), covers); + return info; } int YACReaderComicsSelectionHelper::numItemsSelected() const { - if (_selectionModel != nullptr) { - return _selectionModel->selectedRows().length(); + if (itemSelectionModel != nullptr) { + return itemSelectionModel->selectedRows().length(); } return 0; @@ -104,8 +170,9 @@ int YACReaderComicsSelectionHelper::numItemsSelected() const int YACReaderComicsSelectionHelper::lastSelectedIndex() const { - if (_selectionModel != nullptr) { - return _selectionModel->selectedRows().last().row(); + if (itemSelectionModel != nullptr) { + const auto selectedRows = itemSelectionModel->selectedRows(); + return selectedRows.isEmpty() ? -1 : selectedRows.last().row(); } return -1; @@ -113,9 +180,10 @@ int YACReaderComicsSelectionHelper::lastSelectedIndex() const QItemSelectionModel *YACReaderComicsSelectionHelper::selectionModel() { - QModelIndexList indexes = _selectionModel->selectedRows(); - if (indexes.length() == 0) - this->selectIndex(0); + return itemSelectionModel; +} - return _selectionModel; +qulonglong YACReaderComicsSelectionHelper::selectionRevision() const +{ + return revision; } diff --git a/YACReaderLibrary/yacreader_comics_selection_helper.h b/YACReaderLibrary/yacreader_comics_selection_helper.h index 05566d89d..6c615de09 100644 --- a/YACReaderLibrary/yacreader_comics_selection_helper.h +++ b/YACReaderLibrary/yacreader_comics_selection_helper.h @@ -5,18 +5,21 @@ #include #include #include +#include class ComicModel; class YACReaderComicsSelectionHelper : public QObject { Q_OBJECT + Q_PROPERTY(qulonglong selectionRevision READ selectionRevision NOTIFY selectionChanged) public: explicit YACReaderComicsSelectionHelper(QObject *parent = nullptr); void setModel(ComicModel *model); Q_INVOKABLE void selectIndex(int index); + Q_INVOKABLE void selectOnly(int index); Q_INVOKABLE void deselectIndex(int index); Q_INVOKABLE bool isSelectedIndex(int index) const; Q_INVOKABLE void clear(); @@ -26,6 +29,8 @@ class YACReaderComicsSelectionHelper : public QObject Q_INVOKABLE void selectAll(); Q_INVOKABLE QModelIndexList selectedIndexes() const; Q_INVOKABLE QModelIndexList selectedRows(int column = 0) const; + QVariantMap selectionInfo() const; + qulonglong selectionRevision() const; QItemSelectionModel *selectionModel(); @@ -34,10 +39,10 @@ class YACReaderComicsSelectionHelper : public QObject public slots: -protected: - QItemSelectionModel *_selectionModel; - - ComicModel *model; +private: + QItemSelectionModel *itemSelectionModel = nullptr; + ComicModel *model = nullptr; + qulonglong revision = 0; }; #endif // YACREADERCOMICSSELECTIONHELPER_H diff --git a/YACReaderLibrary/yacreader_content_views_manager.cpp b/YACReaderLibrary/yacreader_content_views_manager.cpp index 6abacc2a5..98c42d09b 100644 --- a/YACReaderLibrary/yacreader_content_views_manager.cpp +++ b/YACReaderLibrary/yacreader_content_views_manager.cpp @@ -1,29 +1,28 @@ #include "yacreader_content_views_manager.h" #include "classic_comics_view.h" +#include "comic_management_coordinator.h" #include "comics_view_transition.h" #include "empty_folder_widget.h" #include "empty_label_widget.h" #include "empty_reading_list_widget.h" #include "empty_special_list.h" -#include "folder_content_view.h" #include "grid_comics_view.h" #include "info_comics_view.h" #include "library_window.h" +#include "library_window_menus.h" #include "no_search_results_widget.h" #include "options_dialog.h" -#include "reading_list_model.h" #include "yacreader_options_dialog.h" -#include "yacreader_reading_lists_view.h" #include "yacreader_sidebar.h" -//-- -#include "yacreader_search_line_edit.h" +#include YACReaderContentViewsManager::YACReaderContentViewsManager(QSettings *settings, LibraryWindow *parent) - : QObject(parent), libraryWindow(parent), classicComicsView(nullptr), gridComicsView(nullptr), infoComicsView(nullptr) + : QObject(parent), libraryWindow(parent), classicComicsView(nullptr), gridComicsView(nullptr), infoComicsView(nullptr), toolbarOwner(nullptr), comicManagementCoordinator(nullptr), libraryWindowMenus(nullptr) { comicsViewStack = new QStackedWidget(); + gridComicsView = new GridComicsView(); switch ((YACReader::ComicsViewStatus)settings->value(COMICS_VIEW_STATUS).toInt()) { case Flow: @@ -38,78 +37,119 @@ YACReaderContentViewsManager::YACReaderContentViewsManager(QSettings *settings, case Grid: default: - comicsView = gridComicsView = new GridComicsView(); - connect(libraryWindow->optionsDialog, &YACReaderOptionsDialog::optionsChanged, gridComicsView, &GridComicsView::updateBackgroundConfig); - connect(libraryWindow->optionsDialog, &YACReaderOptionsDialog::finished, gridComicsView, &GridComicsView::updateSettings); // TODO: we can link constante changes to updateSettings because of bad performance + comicsView = gridComicsView; comicsViewStatus = Grid; break; } - doComicsViewConnections(); + connectComicsViewConnections(comicsView); + toolbarOwner = comicsView; + connect(gridComicsView, &GridComicsView::comicSelectionStateChanged, this, [this](bool hasSelection) { + if (comicsViewStack->currentWidget() == gridComicsView) + libraryWindow->actions.setComicSelectionActionsEnabled(hasSelection); + }); + connect(libraryWindow->optionsDialog, &YACReaderOptionsDialog::optionsChanged, gridComicsView, &GridComicsView::updateSettings); comicsViewStack->addWidget(comicsViewTransition = new ComicsViewTransition()); - comicsViewStack->addWidget(folderContentView = new FolderContentView(parent->actions.toogleShowRecentIndicatorAction)); comicsViewStack->addWidget(emptyLabelWidget = new EmptyLabelWidget()); comicsViewStack->addWidget(emptySpecialList = new EmptySpecialListWidget()); comicsViewStack->addWidget(emptyReadingList = new EmptyReadingListWidget()); comicsViewStack->addWidget(emptyFolderWidget = new EmptyFolderWidget()); comicsViewStack->addWidget(noSearchResultsWidget = new NoSearchResultsWidget()); - comicsViewStack->addWidget(comicsView); + ensureInStack(comicsView); + ensureInStack(gridComicsView); comicsViewStack->setCurrentWidget(comicsView); - // connections - connect(folderContentView, &FolderContentView::copyComicsToCurrentFolder, libraryWindow, &LibraryWindow::copyAndImportComicsToCurrentFolder); - connect(folderContentView, &FolderContentView::moveComicsToCurrentFolder, libraryWindow, &LibraryWindow::moveAndImportComicsToCurrentFolder); - connect(libraryWindow->optionsDialog, &YACReaderOptionsDialog::optionsChanged, folderContentView, &FolderContentView::updateSettings); - initTheme(this); } +void YACReaderContentViewsManager::setComicManagementCoordinator(ComicManagementCoordinator *coordinator) +{ + if (comicManagementCoordinator == coordinator) + return; + + if (comicManagementCoordinator != nullptr) { + disconnect(comicsView, &ComicsView::selected, comicManagementCoordinator, &ComicManagementCoordinator::openCurrentComic); + disconnect(comicsView, &ComicsView::openComic, comicManagementCoordinator, &ComicManagementCoordinator::openComic); + disconnect(comicsView, &ComicsView::copyComicsToCurrentFolder, comicManagementCoordinator, &ComicManagementCoordinator::copyAndImportComicsToCurrentFolder); + disconnect(comicsView, &ComicsView::moveComicsToCurrentFolder, comicManagementCoordinator, &ComicManagementCoordinator::moveAndImportComicsToCurrentFolder); + disconnect(comicsView, &ComicsView::customComicCoverRequested, comicManagementCoordinator, &ComicManagementCoordinator::setCustomCover); + } + + comicManagementCoordinator = coordinator; + if (comicManagementCoordinator != nullptr) { + connect(comicsView, &ComicsView::selected, comicManagementCoordinator, &ComicManagementCoordinator::openCurrentComic, Qt::UniqueConnection); + connect(comicsView, &ComicsView::openComic, comicManagementCoordinator, &ComicManagementCoordinator::openComic, Qt::UniqueConnection); + connect(comicsView, &ComicsView::copyComicsToCurrentFolder, comicManagementCoordinator, &ComicManagementCoordinator::copyAndImportComicsToCurrentFolder, Qt::UniqueConnection); + connect(comicsView, &ComicsView::moveComicsToCurrentFolder, comicManagementCoordinator, &ComicManagementCoordinator::moveAndImportComicsToCurrentFolder, Qt::UniqueConnection); + connect(comicsView, &ComicsView::customComicCoverRequested, comicManagementCoordinator, &ComicManagementCoordinator::setCustomCover, Qt::UniqueConnection); + } +} + +void YACReaderContentViewsManager::setLibraryWindowMenus(LibraryWindowMenus *menus) +{ + if (libraryWindowMenus == menus) + return; + + if (libraryWindowMenus != nullptr) { + disconnect(comicsView, &ComicsView::customContextMenuViewRequested, libraryWindowMenus, &LibraryWindowMenus::showComicsViewContextMenu); + disconnect(comicsView, &ComicsView::customContextMenuItemRequested, libraryWindowMenus, &LibraryWindowMenus::showComicsItemContextMenu); + } + + libraryWindowMenus = menus; + if (libraryWindowMenus != nullptr) { + connect(comicsView, &ComicsView::customContextMenuViewRequested, libraryWindowMenus, &LibraryWindowMenus::showComicsViewContextMenu, Qt::UniqueConnection); + connect(comicsView, &ComicsView::customContextMenuItemRequested, libraryWindowMenus, &LibraryWindowMenus::showComicsItemContextMenu, Qt::UniqueConnection); + } +} + QWidget *YACReaderContentViewsManager::containerWidget() { return comicsViewStack; } -void YACReaderContentViewsManager::updateCurrentContentView() +GridComicsView *YACReaderContentViewsManager::gridView() const { - if (!libraryWindow->hasLoadedLibraryModels()) - return; + return gridComicsView; +} - if (libraryWindow->status == LibraryWindow::Searching) { - auto currentWidget = comicsViewStack->currentWidget(); +bool YACReaderContentViewsManager::isComicsViewVisible() const +{ + return comicsViewStack->currentWidget() == comicsView; +} - libraryWindow->comicsModel->reload(); +void YACReaderContentViewsManager::prepareToClose() +{ + const auto saveIfInactive = [this](ComicsView *view) { + if (view && view != comicsView) + view->saveViewConfig(); + }; - if (currentWidget == comicsView) { - comicsView->reloadContent(); - } - return; - } + saveIfInactive(classicComicsView); + saveIfInactive(gridComicsView); + saveIfInactive(infoComicsView); - if (!libraryWindow->listsView->selectionModel()->selectedRows().isEmpty()) { - auto currentListIndex = libraryWindow->listsModelProxy->mapToSource(libraryWindow->listsView->currentIndex()); - if (currentListIndex.isValid()) { - libraryWindow->navigationController->loadListInfo(currentListIndex); - return; - } - } + comicsView->close(); +} - libraryWindow->navigationController->loadFolderInfo(libraryWindow->getCurrentFolderIndex()); +ContentViewState YACReaderContentViewsManager::captureViewState() const +{ + const auto *view = qobject_cast(comicsViewStack->currentWidget()); + return view ? view->captureViewState() : ContentViewState { }; } -void YACReaderContentViewsManager::updateCurrentComicView() +void YACReaderContentViewsManager::restoreViewState(const ContentViewState &state) { - if (comicsViewStack->currentWidget() == comicsView) { - comicsView->updateCurrentComicView(); - } + if (auto *view = qobject_cast(comicsViewStack->currentWidget())) + view->restoreViewState(state); } -void YACReaderContentViewsManager::updateContinueReadingView() +void YACReaderContentViewsManager::updateCurrentComicView() { - if (comicsViewStack->currentWidget() == folderContentView) { - folderContentView->reloadContinueReadingModel(); + if (comicsViewStack->currentWidget() == comicsView) { + comicsView->updateCurrentComicView(); } } @@ -131,7 +171,9 @@ void YACReaderContentViewsManager::toNormal() void YACReaderContentViewsManager::showComicsView() { - comicsViewStack->setCurrentWidget(comicsView); + setToolBarOwner(comicsView); + + showStackWidget(comicsView, true); // TODO: check if this is still needed in the rhi implementation // BUG, ugly workaround for glitch when QOpenGLWidget (flow) is used just after any other widget in the views stack @@ -139,50 +181,67 @@ void YACReaderContentViewsManager::showComicsView() libraryWindow->sideBar->update(); } -void YACReaderContentViewsManager::showFolderContentView() +void YACReaderContentViewsManager::showFoldersOnlyGrid() { - comicsViewStack->setCurrentWidget(folderContentView); + setToolBarOwner(gridComicsView); + connectComicsViewConnections(gridComicsView); + ensureInStack(gridComicsView); + showStackWidget(gridComicsView, false); } -void YACReaderContentViewsManager::showEmptyLabelView() +void YACReaderContentViewsManager::showEmptyLabel(YACReader::LabelColors color) { - comicsViewStack->setCurrentWidget(emptyLabelWidget); + emptyLabelWidget->setColor(color); + showStackWidget(emptyLabelWidget, true); } -void YACReaderContentViewsManager::showEmptySpecialList() +void YACReaderContentViewsManager::showEmptySpecialList(ReadingListModel::TypeSpecialList type) { - comicsViewStack->setCurrentWidget(emptySpecialList); + switch (type) { + case ReadingListModel::TypeSpecialList::Favorites: + emptySpecialList->showFavorites(); + break; + case ReadingListModel::TypeSpecialList::Reading: + emptySpecialList->showReading(); + break; + case ReadingListModel::TypeSpecialList::Recent: + emptySpecialList->showRecent(); + break; + } + + showStackWidget(emptySpecialList, true); } -void YACReaderContentViewsManager::showEmptyReadingListWidget() +void YACReaderContentViewsManager::showEmptyReadingList() { - comicsViewStack->setCurrentWidget(emptyReadingList); + showStackWidget(emptyReadingList, true); } -void YACReaderContentViewsManager::showEmptyFolderWidget() +void YACReaderContentViewsManager::showEmptyFolder() { - comicsViewStack->setCurrentWidget(emptyFolderWidget); + showStackWidget(emptyFolderWidget, false); } -void YACReaderContentViewsManager::showNoSearchResultsView() +void YACReaderContentViewsManager::showNoSearchResults() { - comicsViewStack->setCurrentWidget(noSearchResultsWidget); + showStackWidget(noSearchResultsWidget, true); } -// TODO recover the current comics selection and restore it in the destination void YACReaderContentViewsManager::toggleComicsView() { + const auto viewState = captureViewState(); if (comicsViewStack->currentWidget() == comicsView) { QTimer::singleShot(0, this, &YACReaderContentViewsManager::showComicsViewTransition); - QTimer::singleShot(100, this, &YACReaderContentViewsManager::_toggleComicsView); + QTimer::singleShot(100, this, [this, viewState]() { switchToNextComicsView(viewState); }); } else { - _toggleComicsView(); + switchToNextComicsView(viewState); } } void YACReaderContentViewsManager::focusComicsViewViaShortcut() { - comicsView->focusComicsNavigation(Qt::ShortcutFocusReason); + if (auto *currentView = qobject_cast(comicsViewStack->currentWidget())) + currentView->focusComicsNavigation(Qt::ShortcutFocusReason); } // PROTECTED @@ -191,44 +250,55 @@ void YACReaderContentViewsManager::disconnectComicsViewConnections(ComicsView *w { disconnect(widget, &ComicsView::comicRated, libraryWindow->comicsModel, &ComicModel::updateRating); disconnect(libraryWindow->actions.showHideMarksAction, &QAction::toggled, widget, &ComicsView::setShowMarks); - disconnect(widget, &ComicsView::selected, libraryWindow, QOverload<>::of(&LibraryWindow::openComic)); - disconnect(widget, &ComicsView::openComic, libraryWindow, QOverload::of(&LibraryWindow::openComic)); disconnect(libraryWindow->actions.selectAllComicsAction, &QAction::triggered, widget, &ComicsView::selectAll); - disconnect(comicsView, &ComicsView::copyComicsToCurrentFolder, libraryWindow, &LibraryWindow::copyAndImportComicsToCurrentFolder); - disconnect(comicsView, &ComicsView::moveComicsToCurrentFolder, libraryWindow, &LibraryWindow::moveAndImportComicsToCurrentFolder); - disconnect(comicsView, &ComicsView::customContextMenuViewRequested, libraryWindow, &LibraryWindow::showComicsViewContextMenu); - disconnect(comicsView, &ComicsView::customContextMenuItemRequested, libraryWindow, &LibraryWindow::showComicsItemContextMenu); + if (comicManagementCoordinator != nullptr) { + disconnect(widget, &ComicsView::selected, comicManagementCoordinator, &ComicManagementCoordinator::openCurrentComic); + disconnect(widget, &ComicsView::openComic, comicManagementCoordinator, &ComicManagementCoordinator::openComic); + disconnect(widget, &ComicsView::copyComicsToCurrentFolder, comicManagementCoordinator, &ComicManagementCoordinator::copyAndImportComicsToCurrentFolder); + disconnect(widget, &ComicsView::moveComicsToCurrentFolder, comicManagementCoordinator, &ComicManagementCoordinator::moveAndImportComicsToCurrentFolder); + disconnect(widget, &ComicsView::customComicCoverRequested, comicManagementCoordinator, &ComicManagementCoordinator::setCustomCover); + } + if (libraryWindowMenus != nullptr) { + disconnect(widget, &ComicsView::customContextMenuViewRequested, libraryWindowMenus, &LibraryWindowMenus::showComicsViewContextMenu); + disconnect(widget, &ComicsView::customContextMenuItemRequested, libraryWindowMenus, &LibraryWindowMenus::showComicsItemContextMenu); + } } -void YACReaderContentViewsManager::doComicsViewConnections() +void YACReaderContentViewsManager::connectComicsViewConnections(ComicsView *view) { - connect(comicsView, &ComicsView::comicRated, libraryWindow->comicsModel, &ComicModel::updateRating); - connect(libraryWindow->actions.showHideMarksAction, &QAction::toggled, comicsView, &ComicsView::setShowMarks); - connect(comicsView, &ComicsView::selected, libraryWindow, QOverload<>::of(&LibraryWindow::openComic)); - connect(comicsView, &ComicsView::openComic, libraryWindow, QOverload::of(&LibraryWindow::openComic)); + connect(view, &ComicsView::comicRated, libraryWindow->comicsModel, &ComicModel::updateRating, Qt::UniqueConnection); + connect(libraryWindow->actions.showHideMarksAction, &QAction::toggled, view, &ComicsView::setShowMarks, Qt::UniqueConnection); - connect(libraryWindow->actions.selectAllComicsAction, &QAction::triggered, comicsView, &ComicsView::selectAll); + connect(libraryWindow->actions.selectAllComicsAction, &QAction::triggered, view, &ComicsView::selectAll, Qt::UniqueConnection); - connect(comicsView, &ComicsView::customContextMenuViewRequested, libraryWindow, &LibraryWindow::showComicsViewContextMenu); - connect(comicsView, &ComicsView::customContextMenuItemRequested, libraryWindow, &LibraryWindow::showComicsItemContextMenu); + if (libraryWindowMenus != nullptr) { + connect(view, &ComicsView::customContextMenuViewRequested, libraryWindowMenus, &LibraryWindowMenus::showComicsViewContextMenu, Qt::UniqueConnection); + connect(view, &ComicsView::customContextMenuItemRequested, libraryWindowMenus, &LibraryWindowMenus::showComicsItemContextMenu, Qt::UniqueConnection); + } // Drops - connect(comicsView, &ComicsView::copyComicsToCurrentFolder, libraryWindow, &LibraryWindow::copyAndImportComicsToCurrentFolder); - connect(comicsView, &ComicsView::moveComicsToCurrentFolder, libraryWindow, &LibraryWindow::moveAndImportComicsToCurrentFolder); + if (comicManagementCoordinator != nullptr) { + connect(view, &ComicsView::selected, comicManagementCoordinator, &ComicManagementCoordinator::openCurrentComic, Qt::UniqueConnection); + connect(view, &ComicsView::openComic, comicManagementCoordinator, &ComicManagementCoordinator::openComic, Qt::UniqueConnection); + connect(view, &ComicsView::copyComicsToCurrentFolder, comicManagementCoordinator, &ComicManagementCoordinator::copyAndImportComicsToCurrentFolder, Qt::UniqueConnection); + connect(view, &ComicsView::moveComicsToCurrentFolder, comicManagementCoordinator, &ComicManagementCoordinator::moveAndImportComicsToCurrentFolder, Qt::UniqueConnection); + connect(view, &ComicsView::customComicCoverRequested, comicManagementCoordinator, &ComicManagementCoordinator::setCustomCover, Qt::UniqueConnection); + } } -void YACReaderContentViewsManager::switchToComicsView(ComicsView *from, ComicsView *to) +void YACReaderContentViewsManager::switchToComicsView(ComicsView *from, ComicsView *to, const ContentViewState &viewState) { // setup views disconnectComicsViewConnections(from); - from->close(); + from->saveViewConfig(); + from->hide(); comicsView = to; - doComicsViewConnections(); + connectComicsViewConnections(comicsView); - comicsView->setToolBar(libraryWindow->editInfoToolBar); + setToolBarOwner(comicsView); comicsViewStack->removeWidget(from); - comicsViewStack->addWidget(comicsView); + ensureInStack(comicsView); // delete from; No need to delete the previews view, because all views are going to be kept in memory @@ -238,66 +308,120 @@ void YACReaderContentViewsManager::switchToComicsView(ComicsView *from, ComicsVi if (!libraryWindow->searchText().isEmpty()) { comicsView->enableFilterMode(true); } + + to->restoreViewState(viewState); + updateComicActionsForCurrentView(); } -void YACReaderContentViewsManager::showComicsViewTransition() +void YACReaderContentViewsManager::ensureInStack(ComicsView *view) { - comicsViewStack->setCurrentWidget(comicsViewTransition); + if (comicsViewStack->indexOf(view) < 0) + comicsViewStack->addWidget(view); +} + +void YACReaderContentViewsManager::showStackWidget(QWidget *widget, bool viewSelectorEnabled) +{ + // showFoldersOnlyGrid() lends the comics view connections to gridComicsView while + // another view mode owns comicsView. Take them back as soon as the grid stops + // being shown, otherwise it keeps reacting to comic actions while hidden. + if (widget != gridComicsView && comicsView != gridComicsView) + disconnectComicsViewConnections(gridComicsView); + + comicsViewStack->setCurrentWidget(widget); + setViewSelectorEnabled(viewSelectorEnabled); +} + +void YACReaderContentViewsManager::updateComicActionsForCurrentView() +{ + if (libraryWindow->comicsModel == nullptr) + return; + + libraryWindow->setComicActionsDisabled(libraryWindow->comicsModel->rowCount() == 0); + + // Only the grid tracks a live comic selection, and it can have a folder focused + // instead of a comic. Every other view keeps the comic actions available as long + // as the current content has comics. + if (comicsView == gridComicsView) + libraryWindow->actions.setComicSelectionActionsEnabled(gridComicsView->hasComicSelection()); } -void YACReaderContentViewsManager::_toggleComicsView() +void YACReaderContentViewsManager::setToolBarOwner(ComicsView *view) +{ + if (!view || toolbarOwner == view) + return; + + if (toolbarOwner) + toolbarOwner->releaseToolBar(); + + view->setToolBar(libraryWindow->editInfoToolBar); + toolbarOwner = view; +} + +void YACReaderContentViewsManager::setViewSelectorEnabled(bool enabled) +{ + libraryWindow->actions.toggleComicsViewAction->setEnabled(enabled); +} + +void YACReaderContentViewsManager::updateViewSelectorIcon(const Theme &theme) { const auto &mainToolbar = theme.mainToolbar; + QIcon icon; switch (comicsViewStatus) { - case Flow: { - QIcon icoViewsButton = mainToolbar.infoIcon; - libraryWindow->actions.toggleComicsViewAction->setIcon(icoViewsButton); + case Flow: + icon = mainToolbar.gridIcon; + break; + case Grid: + icon = mainToolbar.infoIcon; + break; + case Info: + icon = mainToolbar.flowIcon; + break; + } + + libraryWindow->actions.toggleComicsViewAction->setIcon(icon); #ifdef Y_MAC_UI - libraryWindow->libraryToolBar->updateViewSelectorIcon(icoViewsButton); + libraryWindow->libraryToolBar->updateViewSelectorIcon(icon); #endif - if (gridComicsView == nullptr) - gridComicsView = new GridComicsView(); +} + +void YACReaderContentViewsManager::showComicsViewTransition() +{ + comicsViewStack->setCurrentWidget(comicsViewTransition); +} - switchToComicsView(classicComicsView, gridComicsView); - connect(libraryWindow->optionsDialog, &YACReaderOptionsDialog::optionsChanged, gridComicsView, &GridComicsView::updateBackgroundConfig); - connect(libraryWindow->optionsDialog, &YACReaderOptionsDialog::finished, gridComicsView, &GridComicsView::updateSettings); // TODO: we can link constante changes to updateSettings because of bad performance +void YACReaderContentViewsManager::switchToNextComicsView(const ContentViewState &viewState) +{ + switch (comicsViewStatus) { + case Flow: { + switchToComicsView(classicComicsView, gridComicsView, viewState); comicsViewStatus = Grid; break; } case Grid: { - QIcon icoViewsButton = mainToolbar.flowIcon; - libraryWindow->actions.toggleComicsViewAction->setIcon(icoViewsButton); -#ifdef Y_MAC_UI - libraryWindow->libraryToolBar->updateViewSelectorIcon(icoViewsButton); -#endif if (infoComicsView == nullptr) infoComicsView = new InfoComicsView(); - switchToComicsView(gridComicsView, infoComicsView); + switchToComicsView(gridComicsView, infoComicsView, viewState); comicsViewStatus = Info; break; } case Info: { - QIcon icoViewsButton = mainToolbar.gridIcon; - libraryWindow->actions.toggleComicsViewAction->setIcon(icoViewsButton); -#ifdef Y_MAC_UI - libraryWindow->libraryToolBar->updateViewSelectorIcon(icoViewsButton); -#endif if (classicComicsView == nullptr) classicComicsView = new ClassicComicsView(); - switchToComicsView(infoComicsView, classicComicsView); + switchToComicsView(infoComicsView, classicComicsView, viewState); comicsViewStatus = Flow; break; } } + updateViewSelectorIcon(theme); libraryWindow->settings->setValue(COMICS_VIEW_STATUS, comicsViewStatus); if (comicsViewStack->currentWidget() == comicsViewTransition) @@ -306,25 +430,5 @@ void YACReaderContentViewsManager::_toggleComicsView() void YACReaderContentViewsManager::applyTheme(const Theme &theme) { - const auto &mainToolbar = theme.mainToolbar; - - // Update the toggle button icon based on current view status - // The icon shows what the NEXT view will be when clicked - QIcon icon; - switch (comicsViewStatus) { - case Flow: - icon = mainToolbar.gridIcon; - break; - case Grid: - icon = mainToolbar.infoIcon; - break; - case Info: - icon = mainToolbar.flowIcon; - break; - } - - libraryWindow->actions.toggleComicsViewAction->setIcon(icon); -#ifdef Y_MAC_UI - libraryWindow->libraryToolBar->updateViewSelectorIcon(icon); -#endif + updateViewSelectorIcon(theme); } diff --git a/YACReaderLibrary/yacreader_content_views_manager.h b/YACReaderLibrary/yacreader_content_views_manager.h index e78a1f62f..04a5fb6b4 100644 --- a/YACReaderLibrary/yacreader_content_views_manager.h +++ b/YACReaderLibrary/yacreader_content_views_manager.h @@ -1,6 +1,8 @@ #ifndef YACREADERCONTENTVIEWSMANAGER_H #define YACREADERCONTENTVIEWSMANAGER_H +#include "content_view_state.h" +#include "reading_list_model.h" #include "themable.h" #include "yacreader_global_gui.h" @@ -10,16 +12,19 @@ class LibraryWindow; class ComicsView; +class ComicModel; class ClassicComicsView; class GridComicsView; class InfoComicsView; class ComicsViewTransition; -class FolderContentView; class EmptyLabelWidget; class EmptySpecialListWidget; class EmptyReadingListWidget; class EmptyFolderWidget; class NoSearchResultsWidget; +class FolderModel; +class ComicManagementCoordinator; +class LibraryWindowMenus; using namespace YACReader; @@ -30,22 +35,19 @@ class YACReaderContentViewsManager : public QObject, protected Themable explicit YACReaderContentViewsManager(QSettings *settings, LibraryWindow *parent = nullptr); QWidget *containerWidget(); + GridComicsView *gridView() const; + bool isComicsViewVisible() const; + void prepareToClose(); + ContentViewState captureViewState() const; + void restoreViewState(const ContentViewState &state); + void setComicManagementCoordinator(ComicManagementCoordinator *coordinator); + void setLibraryWindowMenus(LibraryWindowMenus *menus); ComicsView *comicsView; ComicsViewTransition *comicsViewTransition; - FolderContentView *folderContentView; - EmptyLabelWidget *emptyLabelWidget; - EmptySpecialListWidget *emptySpecialList; - EmptyReadingListWidget *emptyReadingList; - EmptyFolderWidget *emptyFolderWidget; - - NoSearchResultsWidget *noSearchResultsWidget; - - void updateCurrentContentView(); void updateCurrentComicView(); - void updateContinueReadingView(); void toFullscreen(); void toNormal(); @@ -59,31 +61,44 @@ class YACReaderContentViewsManager : public QObject, protected Themable ClassicComicsView *classicComicsView; GridComicsView *gridComicsView; InfoComicsView *infoComicsView; + ComicsView *toolbarOwner; + ComicManagementCoordinator *comicManagementCoordinator; + LibraryWindowMenus *libraryWindowMenus; - void applyTheme(const Theme &theme) override; + EmptyLabelWidget *emptyLabelWidget; + EmptySpecialListWidget *emptySpecialList; + EmptyReadingListWidget *emptyReadingList; + EmptyFolderWidget *emptyFolderWidget; + NoSearchResultsWidget *noSearchResultsWidget; -signals: + void applyTheme(const Theme &theme) override; public slots: void toggleComicsView(); void focusComicsViewViaShortcut(); void showComicsView(); - void showFolderContentView(); - void showEmptyLabelView(); - void showEmptySpecialList(); - void showEmptyReadingListWidget(); - void showEmptyFolderWidget(); - void showNoSearchResultsView(); + void showFoldersOnlyGrid(); + void showEmptyLabel(YACReader::LabelColors color); + void showEmptySpecialList(ReadingListModel::TypeSpecialList type); + void showEmptyReadingList(); + void showEmptyFolder(); + void showNoSearchResults(); protected slots: void showComicsViewTransition(); - void _toggleComicsView(); void disconnectComicsViewConnections(ComicsView *widget); - void doComicsViewConnections(); - - void switchToComicsView(ComicsView *from, ComicsView *to); + void connectComicsViewConnections(ComicsView *view); + + void switchToNextComicsView(const ContentViewState &viewState); + void switchToComicsView(ComicsView *from, ComicsView *to, const ContentViewState &viewState); + void setToolBarOwner(ComicsView *view); + void setViewSelectorEnabled(bool enabled); + void updateViewSelectorIcon(const Theme &theme); + void ensureInStack(ComicsView *view); + void showStackWidget(QWidget *widget, bool viewSelectorEnabled); + void updateComicActionsForCurrentView(); }; #endif // YACREADERCONTENTVIEWSMANAGER_H diff --git a/YACReaderLibrary/yacreader_history_controller.cpp b/YACReaderLibrary/yacreader_history_controller.cpp index 9ac7d4017..a8ceacf2f 100644 --- a/YACReaderLibrary/yacreader_history_controller.cpp +++ b/YACReaderLibrary/yacreader_history_controller.cpp @@ -15,9 +15,10 @@ void YACReaderHistoryController::clear() emit enabledForward(false); } -void YACReaderHistoryController::backward() +void YACReaderHistoryController::backward(const ContentViewState ¤tViewState) { if (currentFolderNavigation > 0) { + history[currentFolderNavigation].viewState = currentViewState; currentFolderNavigation--; emit modelIndexSelected(history.at(currentFolderNavigation)); emit enabledForward(true); @@ -27,9 +28,10 @@ void YACReaderHistoryController::backward() emit enabledBackward(false); } -void YACReaderHistoryController::forward() +void YACReaderHistoryController::forward(const ContentViewState ¤tViewState) { if (currentFolderNavigation < history.count() - 1) { + history[currentFolderNavigation].viewState = currentViewState; currentFolderNavigation++; emit modelIndexSelected(history.at(currentFolderNavigation)); emit enabledBackward(true); @@ -39,6 +41,12 @@ void YACReaderHistoryController::forward() emit enabledForward(false); } +void YACReaderHistoryController::recordViewStateForCurrentEntry(const ContentViewState &state) +{ + if (!history.isEmpty()) + history[currentFolderNavigation].viewState = state; +} + void YACReaderHistoryController::updateHistory(const YACReaderLibrarySourceContainer &source) { // remove history from current index @@ -93,6 +101,11 @@ YACReaderLibrarySourceContainer::SourceType YACReaderLibrarySourceContainer::get return type; } +ContentViewState YACReaderLibrarySourceContainer::getViewState() const +{ + return viewState; +} + bool YACReaderLibrarySourceContainer::operator==(const YACReaderLibrarySourceContainer &other) const { return sourceModelIndex == other.sourceModelIndex && type == other.type; diff --git a/YACReaderLibrary/yacreader_history_controller.h b/YACReaderLibrary/yacreader_history_controller.h index 8bf539d6b..4ef66e35a 100644 --- a/YACReaderLibrary/yacreader_history_controller.h +++ b/YACReaderLibrary/yacreader_history_controller.h @@ -1,6 +1,8 @@ #ifndef YACREADER_HISTORY_CONTROLLER_H #define YACREADER_HISTORY_CONTROLLER_H +#include "content_view_state.h" + #include #include @@ -19,6 +21,7 @@ class YACReaderLibrarySourceContainer explicit YACReaderLibrarySourceContainer(const QModelIndex &sourceModelIndex, YACReaderLibrarySourceContainer::SourceType type); QModelIndex getSourceModelIndex() const; YACReaderLibrarySourceContainer::SourceType getType() const; + ContentViewState getViewState() const; bool operator==(const YACReaderLibrarySourceContainer &other) const; bool operator!=(const YACReaderLibrarySourceContainer &other) const; @@ -26,6 +29,7 @@ class YACReaderLibrarySourceContainer protected: QModelIndex sourceModelIndex; YACReaderLibrarySourceContainer::SourceType type; + ContentViewState viewState; friend class YACReaderHistoryController; }; @@ -45,9 +49,10 @@ class YACReaderHistoryController : public QObject public slots: void clear(); - void backward(); - void forward(); + void backward(const ContentViewState ¤tViewState); + void forward(const ContentViewState ¤tViewState); void updateHistory(const YACReaderLibrarySourceContainer &source); + void recordViewStateForCurrentEntry(const ContentViewState &state); YACReaderLibrarySourceContainer lastSourceContainer(); YACReaderLibrarySourceContainer currentSourceContainer(); diff --git a/YACReaderLibrary/yacreader_libraries.cpp b/YACReaderLibrary/yacreader_libraries.cpp index 6e16d97d2..b512bea07 100644 --- a/YACReaderLibrary/yacreader_libraries.cpp +++ b/YACReaderLibrary/yacreader_libraries.cpp @@ -94,14 +94,17 @@ bool YACReaderLibraries::contains(int id) const void YACReaderLibraries::remove(const QString &name) { auto library = std::find_if(libraries.begin(), libraries.end(), [name](const YACReaderLibrary &library) { return library.getName() == name; }); - libraries.erase(library); + if (library != libraries.end()) + libraries.erase(library); } void YACReaderLibraries::rename(const QString &oldName, const QString &newName) { auto library = std::find_if(libraries.begin(), libraries.end(), [oldName](const YACReaderLibrary &library) { return library.getName() == oldName; }); - libraries.erase(library); - libraries.append(YACReaderLibrary(newName, library->getPath(), library->getLegacyId(), library->getId())); + if (library == libraries.end()) + return; + + *library = YACReaderLibrary(newName, library->getPath(), library->getLegacyId(), library->getId()); } int YACReaderLibraries::getId(const QString &name) const diff --git a/YACReaderLibrary/yacreader_main_toolbar.cpp b/YACReaderLibrary/yacreader_main_toolbar.cpp index c074d41fc..7e49f0833 100644 --- a/YACReaderLibrary/yacreader_main_toolbar.cpp +++ b/YACReaderLibrary/yacreader_main_toolbar.cpp @@ -8,6 +8,8 @@ #include #include +#include + YACReaderMainToolBar::YACReaderMainToolBar(QWidget *parent) : QWidget(parent) { @@ -157,7 +159,7 @@ void YACReaderMainToolBar::applyTheme(const Theme &theme) currentFolder->setStyleSheet(mt.folderNameLabelQSS); // Update dividers - for (QLabel *divider : dividers) { + for (QLabel *divider : std::as_const(dividers)) { divider->setPixmap(mt.dividerPixmap); } diff --git a/YACReaderLibrary/yacreader_navigation_controller.cpp b/YACReaderLibrary/yacreader_navigation_controller.cpp index 2e728a5ff..79e08bb62 100644 --- a/YACReaderLibrary/yacreader_navigation_controller.cpp +++ b/YACReaderLibrary/yacreader_navigation_controller.cpp @@ -3,44 +3,66 @@ #include "QsLog.h" #include "comic_model.h" #include "comics_view.h" +#include "db_helper.h" #include "empty_label_widget.h" #include "empty_special_list.h" -#include "folder_content_view.h" #include "folder_item.h" #include "folder_model.h" +#include "grid_comics_view.h" +#include "library_search_coordinator.h" #include "library_window.h" #include "reading_list_model.h" #include "yacreader_content_views_manager.h" #include "yacreader_folders_view.h" #include "yacreader_global.h" #include "yacreader_history_controller.h" +#include "yacreader_library_list_widget.h" #include "yacreader_reading_lists_view.h" #include -YACReaderNavigationController::YACReaderNavigationController(LibraryWindow *parent, YACReaderContentViewsManager *contentViewsManager) - : QObject(parent), libraryWindow(parent), contentViewsManager(contentViewsManager) +#include + +YACReaderNavigationController::YACReaderNavigationController(LibraryWindow *parent, YACReaderContentViewsManager *contentViewsManager, LibrarySearchCoordinator *librarySearchCoordinator) + : QObject(parent), libraryWindow(parent), contentViewsManager(contentViewsManager), librarySearchCoordinator(librarySearchCoordinator) { setupConnections(); } -void YACReaderNavigationController::selectedFolder(const QModelIndex &mi) +void YACReaderNavigationController::selectedFolder(const QModelIndex &proxyIndex) { - // A proxy is used - QModelIndex modelIndex = libraryWindow->foldersModelProxy->mapToSource(mi); + const QModelIndex folderIndex = libraryWindow->foldersModelProxy->mapToSource(proxyIndex); - // update history - libraryWindow->historyController->updateHistory(YACReaderLibrarySourceContainer(modelIndex, YACReaderLibrarySourceContainer::Folder)); + if (!restoringHistorySelection) { + recordCurrentViewState(); + libraryWindow->historyController->updateHistory(YACReaderLibrarySourceContainer(folderIndex, YACReaderLibrarySourceContainer::Folder)); + } // when a folder is selected the search mode has to be reset - if (libraryWindow->exitSearchMode()) { - libraryWindow->foldersView->scrollTo(modelIndex, QAbstractItemView::PositionAtTop); - libraryWindow->foldersView->setCurrentIndex(modelIndex); + if (librarySearchCoordinator->exitSearchMode()) { + libraryWindow->foldersView->scrollTo(folderIndex, QAbstractItemView::PositionAtTop); + libraryWindow->foldersView->setCurrentIndex(folderIndex); } - loadFolderInfo(modelIndex); + loadFolderContent(folderIndex); + + libraryWindow->setToolbarTitle(folderIndex); +} + +void YACReaderNavigationController::navigateToFolder(const QModelIndex &sourceIndex) +{ + if (!sourceIndex.isValid()) + return; + + const QModelIndex proxyIndex = libraryWindow->foldersModelProxy->mapFromSource(sourceIndex); + if (!proxyIndex.isValid()) + return; + + disconnect(libraryWindow->foldersView, &YACReaderTreeView::currentIndexChanged, this, &YACReaderNavigationController::selectedFolder); + libraryWindow->foldersView->setCurrentIndex(proxyIndex); + connect(libraryWindow->foldersView, &YACReaderTreeView::currentIndexChanged, this, &YACReaderNavigationController::selectedFolder); - libraryWindow->setToolbarTitle(modelIndex); + selectedFolder(proxyIndex); } void YACReaderNavigationController::reselectCurrentFolder() @@ -48,60 +70,66 @@ void YACReaderNavigationController::reselectCurrentFolder() selectedFolder(libraryWindow->foldersView->currentIndex()); } -void YACReaderNavigationController::loadFolderInfo(const QModelIndex &modelIndex) +void YACReaderNavigationController::loadFolderContent(const QModelIndex &folderIndex) { - // Get FolderItem - qulonglong folderId = folderModelIndexToID(modelIndex); + loadedFolder = folderIndex; + + const qulonglong folderId = folderIdForIndex(folderIndex); + const bool isRoot = folderId == FolderModel::RootFolderId; - // check comics in folder with id = folderId libraryWindow->comicsModel->setupFolderModelData(folderId, libraryWindow->foldersModel->getDatabase()); - // configure views + if (isRoot) { + loadRootContinueReading(); + } else { + contentViewsManager->gridView()->clearRootContinueReadingModel(); + } + + const auto libraryName = libraryWindow->selectedLibrary->currentText(); + const auto libraryInfo = isRoot ? DBHelper::getLibraryInfoData(libraryWindow->libraries.getUuid(libraryName)) : QVariantMap(); + contentViewsManager->gridView()->setFolderModel(libraryWindow->foldersModel, folderIndex, libraryName, libraryInfo); + if (libraryWindow->comicsModel->rowCount() > 0) { - // updateView contentViewsManager->comicsView->setModel(libraryWindow->comicsModel); contentViewsManager->showComicsView(); - libraryWindow->disableComicsActions(false); - } else if (libraryWindow->foldersModel->rowCount(modelIndex) > 0 || !modelIndex.isValid()) { - // folder has subfolders (or is root), show folder content view - loadEmptyFolderInfo(modelIndex); - contentViewsManager->showFolderContentView(); - libraryWindow->disableComicsActions(true); + libraryWindow->setComicActionsDisabled(false); + } else if (libraryWindow->foldersModel->rowCount(folderIndex) > 0) { + // Folder has subfolders, so show the unified content grid. + contentViewsManager->gridView()->setModel(libraryWindow->comicsModel); + contentViewsManager->showFoldersOnlyGrid(); + libraryWindow->setComicActionsDisabled(true); } else { - // folder has no comics and no subfolders - contentViewsManager->showEmptyFolderWidget(); - libraryWindow->disableComicsActions(true); + contentViewsManager->showEmptyFolder(); + libraryWindow->setComicActionsDisabled(true); } - - // libraryWindow->updateFoldersViewConextMenu(modelIndex); - // if a folder is selected, listsView selection must be cleared libraryWindow->listsView->clearSelection(); } -void YACReaderNavigationController::loadListInfo(const QModelIndex &modelIndex) +void YACReaderNavigationController::loadListContent(const QModelIndex &listIndex) { - switch (modelIndex.data(ReadingListModel::TypeListsRole).toInt()) { + contentViewsManager->gridView()->clearFolderModel(); + switch (listIndex.data(ReadingListModel::TypeListsRole).toInt()) { case ReadingListModel::SpecialList: - loadSpecialListInfo(modelIndex); + loadSpecialListContent(listIndex); break; case ReadingListModel::Label: - loadLabelInfo(modelIndex); + loadLabelContent(listIndex); break; case ReadingListModel::ReadingList: - loadReadingListInfo(modelIndex); + loadReadingListContent(listIndex); break; } - + contentViewsManager->gridView()->setCurrentList(listIndex); // if a list is selected, foldersView selection must be cleared libraryWindow->foldersView->clearSelection(); } -void YACReaderNavigationController::loadSpecialListInfo(const QModelIndex &modelIndex) +void YACReaderNavigationController::loadSpecialListContent(const QModelIndex &listIndex) { - ReadingListModel::TypeSpecialList type = (ReadingListModel::TypeSpecialList)modelIndex.data(ReadingListModel::SpecialListTypeRole).toInt(); + const auto type = static_cast(listIndex.data(ReadingListModel::SpecialListTypeRole).toInt()); switch (type) { case ReadingListModel::TypeSpecialList::Favorites: @@ -119,29 +147,16 @@ void YACReaderNavigationController::loadSpecialListInfo(const QModelIndex &model if (libraryWindow->comicsModel->rowCount() > 0) { contentViewsManager->showComicsView(); - libraryWindow->disableComicsActions(false); + libraryWindow->setComicActionsDisabled(false); } else { - // setup empty special list widget - switch (type) { - case ReadingListModel::TypeSpecialList::Favorites: - contentViewsManager->emptySpecialList->showFavorites(); - break; - case ReadingListModel::TypeSpecialList::Reading: - contentViewsManager->emptySpecialList->showReading(); - break; - case ReadingListModel::TypeSpecialList::Recent: - contentViewsManager->emptySpecialList->showRecent(); - break; - } - - contentViewsManager->showEmptySpecialList(); - libraryWindow->disableComicsActions(true); + contentViewsManager->showEmptySpecialList(type); + libraryWindow->setComicActionsDisabled(true); } } -void YACReaderNavigationController::loadLabelInfo(const QModelIndex &modelIndex) +void YACReaderNavigationController::loadLabelContent(const QModelIndex &listIndex) { - qulonglong id = modelIndex.data(ReadingListModel::IDRole).toULongLong(); + const qulonglong id = listIndex.data(ReadingListModel::IDRole).toULongLong(); // check comics in label with id = id libraryWindow->comicsModel->setupLabelModelData(id, libraryWindow->foldersModel->getDatabase()); contentViewsManager->comicsView->setModel(libraryWindow->comicsModel); @@ -150,19 +165,18 @@ void YACReaderNavigationController::loadLabelInfo(const QModelIndex &modelIndex) if (libraryWindow->comicsModel->rowCount() > 0) { // updateView contentViewsManager->showComicsView(); - libraryWindow->disableComicsActions(false); + libraryWindow->setComicActionsDisabled(false); } else { // showEmptyFolder // loadEmptyLabelInfo(); //there is no info in an empty label by now, TODO design something - contentViewsManager->emptyLabelWidget->setColor((YACReader::LabelColors)modelIndex.data(ReadingListModel::LabelColorRole).toInt()); - contentViewsManager->showEmptyLabelView(); - libraryWindow->disableComicsActions(true); + contentViewsManager->showEmptyLabel(static_cast(listIndex.data(ReadingListModel::LabelColorRole).toInt())); + libraryWindow->setComicActionsDisabled(true); } } -void YACReaderNavigationController::loadReadingListInfo(const QModelIndex &modelIndex) +void YACReaderNavigationController::loadReadingListContent(const QModelIndex &listIndex) { - qulonglong id = modelIndex.data(ReadingListModel::IDRole).toULongLong(); + const qulonglong id = listIndex.data(ReadingListModel::IDRole).toULongLong(); // check comics in label with id = id libraryWindow->comicsModel->setupReadingListModelData(id, libraryWindow->foldersModel->getDatabase()); contentViewsManager->comicsView->setModel(libraryWindow->comicsModel); @@ -171,31 +185,30 @@ void YACReaderNavigationController::loadReadingListInfo(const QModelIndex &model if (libraryWindow->comicsModel->rowCount() > 0) { // updateView contentViewsManager->showComicsView(); - libraryWindow->disableComicsActions(false); + libraryWindow->setComicActionsDisabled(false); } else { - contentViewsManager->showEmptyReadingListWidget(); - libraryWindow->disableComicsActions(true); + contentViewsManager->showEmptyReadingList(); + libraryWindow->setComicActionsDisabled(true); } } -void YACReaderNavigationController::selectedList(const QModelIndex &mi) +void YACReaderNavigationController::selectedList(const QModelIndex &proxyIndex) { - // A proxy is used - QModelIndex modelIndex = libraryWindow->listsModelProxy->mapToSource(mi); + const QModelIndex listIndex = libraryWindow->listsModelProxy->mapToSource(proxyIndex); - // update history - libraryWindow->historyController->updateHistory(YACReaderLibrarySourceContainer(modelIndex, YACReaderLibrarySourceContainer::List)); + recordCurrentViewState(); + libraryWindow->historyController->updateHistory(YACReaderLibrarySourceContainer(listIndex, YACReaderLibrarySourceContainer::List)); // when a list is selected the search mode has to be reset - if (libraryWindow->exitSearchMode()) { + if (librarySearchCoordinator->exitSearchMode()) { - libraryWindow->listsView->scrollTo(mi, QAbstractItemView::PositionAtTop); - libraryWindow->listsView->setCurrentIndex(mi); + libraryWindow->listsView->scrollTo(proxyIndex, QAbstractItemView::PositionAtTop); + libraryWindow->listsView->setCurrentIndex(proxyIndex); } - loadListInfo(modelIndex); + loadListContent(listIndex); - libraryWindow->setToolbarTitle(modelIndex); + libraryWindow->setToolbarTitle(listIndex); } void YACReaderNavigationController::reselectCurrentList() @@ -215,12 +228,75 @@ void YACReaderNavigationController::reselectCurrentSource() } } +void YACReaderNavigationController::beginCurrentSourceRefresh() +{ + pendingRefreshViewState = contentViewsManager->captureViewState(); +} + +void YACReaderNavigationController::cancelCurrentSourceRefresh() +{ + pendingRefreshViewState.reset(); +} + +void YACReaderNavigationController::refreshCurrentSource() +{ + if (!libraryWindow->hasLoadedLibraryModels()) { + pendingRefreshViewState.reset(); + return; + } + + // Reloading resets the models used by every content view. Keep the view-specific + // state outside that operation so each view can restore its stable item anchor + // once the refreshed source has been populated. + const auto viewState = pendingRefreshViewState.value_or(contentViewsManager->captureViewState()); + pendingRefreshViewState.reset(); + + if (librarySearchCoordinator->isSearching()) { + libraryWindow->comicsModel->reload(); + + if (contentViewsManager->isComicsViewVisible()) + contentViewsManager->comicsView->reloadContent(); + + contentViewsManager->restoreViewState(viewState); + return; + } + + if (!libraryWindow->listsView->selectionModel()->selectedRows().isEmpty()) { + auto currentListIndex = libraryWindow->listsModelProxy->mapToSource(libraryWindow->listsView->currentIndex()); + if (currentListIndex.isValid()) { + loadListContent(currentListIndex); + contentViewsManager->restoreViewState(viewState); + return; + } + } + + // The folder on screen is the one to reload. The tree selection can point + // somewhere else (a right click on the tree selects a folder without + // navigating to it), and using it here would move the content view to + // another folder, without going through the navigation and history code. + loadFolderContent(loadedFolder); + contentViewsManager->restoreViewState(viewState); +} + +void YACReaderNavigationController::backward() +{ + libraryWindow->historyController->backward(contentViewsManager->captureViewState()); +} + +void YACReaderNavigationController::forward() +{ + libraryWindow->historyController->forward(contentViewsManager->captureViewState()); +} + void YACReaderNavigationController::selectedIndexFromHistory(const YACReaderLibrarySourceContainer &sourceContainer) { // TODO NO searching allowed, just disable backward/forward actions in searching mode // when a folder or a list is selected the search mode has to be reset - libraryWindow->exitSearchMode(); + librarySearchCoordinator->exitSearchMode(); + restoringHistorySelection = true; loadIndexFromHistory(sourceContainer); + contentViewsManager->restoreViewState(sourceContainer.getViewState()); + restoringHistorySelection = false; libraryWindow->setToolbarTitle(sourceContainer.getSourceModelIndex()); } @@ -229,20 +305,25 @@ void YACReaderNavigationController::loadIndexFromHistory(const YACReaderLibraryS QModelIndex sourceMI = sourceContainer.getSourceModelIndex(); switch (sourceContainer.getType()) { case YACReaderLibrarySourceContainer::Folder: { + if (!sourceMI.isValid()) { + libraryWindow->setRootIndex(); // TODO: we do a double update, without it the continue reading list height comes later and causes a small flash + break; + } + QModelIndex mi = libraryWindow->foldersModelProxy->mapFromSource(sourceMI); libraryWindow->foldersView->scrollTo(mi, QAbstractItemView::PositionAtTop); // currentIndexChanged is about to be emited, but we don't want it to end in YACReaderHistoryController::updateHistory disconnect(libraryWindow->foldersView, &YACReaderTreeView::currentIndexChanged, this, &YACReaderNavigationController::selectedFolder); libraryWindow->foldersView->setCurrentIndex(mi); connect(libraryWindow->foldersView, &YACReaderTreeView::currentIndexChanged, this, &YACReaderNavigationController::selectedFolder); - loadFolderInfo(sourceMI); + loadFolderContent(sourceMI); break; } case YACReaderLibrarySourceContainer::List: { QModelIndex mi = libraryWindow->listsModelProxy->mapFromSource(sourceMI); libraryWindow->listsView->scrollTo(mi, QAbstractItemView::PositionAtTop); libraryWindow->listsView->setCurrentIndex(mi); - loadListInfo(sourceMI); + loadListContent(sourceMI); break; } case YACReaderLibrarySourceContainer::None: @@ -251,28 +332,18 @@ void YACReaderNavigationController::loadIndexFromHistory(const YACReaderLibraryS } } -void YACReaderNavigationController::selectSubfolder(const QModelIndex &sourceMIParent, int child) -{ - QModelIndex dest = libraryWindow->foldersModel->index(child, 0, sourceMIParent); - libraryWindow->foldersView->setCurrentIndex(libraryWindow->foldersModelProxy->mapFromSource(dest)); - libraryWindow->historyController->updateHistory(YACReaderLibrarySourceContainer(dest, YACReaderLibrarySourceContainer::Folder)); - loadFolderInfo(dest); -} - -void YACReaderNavigationController::loadEmptyFolderInfo(const QModelIndex &modelIndex) +void YACReaderNavigationController::loadRootContinueReading() { - auto readingComicsModel = new ComicModel(); + auto readingComicsModel = std::make_unique(); - auto isRoot = !modelIndex.isValid(); + readingComicsModel->setupReadingModelData(libraryWindow->foldersModel->getDatabase()); - if (isRoot) { - readingComicsModel->setupReadingModelData(libraryWindow->foldersModel->getDatabase()); - } - - contentViewsManager->folderContentView->setContinueReadingModel(readingComicsModel); + contentViewsManager->gridView()->setRootContinueReadingModel(std::move(readingComicsModel)); +} - auto subFolderModel = libraryWindow->foldersModel->getSubfoldersModel(modelIndex); - contentViewsManager->folderContentView->setModel(modelIndex, subFolderModel); +void YACReaderNavigationController::reloadRootContinueReading() +{ + contentViewsManager->gridView()->reloadRootContinueReadingModel(); } void YACReaderNavigationController::loadPreviousStatus() @@ -283,26 +354,30 @@ void YACReaderNavigationController::loadPreviousStatus() void YACReaderNavigationController::setupConnections() { + auto *gridView = contentViewsManager->gridView(); + // we need YACReaderTreeView::currentIndexChanged to be able to navigate the folders tree using the keyboard cursors connect(libraryWindow->foldersView, &YACReaderTreeView::currentIndexChanged, this, &YACReaderNavigationController::selectedFolder); connect(libraryWindow->foldersView, &YACReaderTreeView::clicked, this, &YACReaderNavigationController::selectedFolder); connect(libraryWindow->listsView, &QAbstractItemView::clicked, this, &YACReaderNavigationController::selectedList); connect(libraryWindow->historyController, &YACReaderHistoryController::modelIndexSelected, this, &YACReaderNavigationController::selectedIndexFromHistory); - connect(contentViewsManager->folderContentView, &FolderContentView::subfolderSelected, this, &YACReaderNavigationController::selectSubfolder); - connect(contentViewsManager->folderContentView, &FolderContentView::openComic, libraryWindow, QOverload::of(&LibraryWindow::openComic)); - connect(contentViewsManager->folderContentView, &FolderContentView::openFolderContextMenu, libraryWindow, &LibraryWindow::showGridFoldersContextMenu); - connect(contentViewsManager->folderContentView, &FolderContentView::openContinueReadingComicContextMenu, libraryWindow, &LibraryWindow::showContinueReadingContextMenu); + connect(gridView, &GridComicsView::folderSelected, this, &YACReaderNavigationController::navigateToFolder); connect(libraryWindow->comicsModel, &ComicModel::isEmpty, this, &YACReaderNavigationController::reselectCurrentSource); } -qulonglong YACReaderNavigationController::folderModelIndexToID(const QModelIndex &mi) +void YACReaderNavigationController::recordCurrentViewState() +{ + libraryWindow->historyController->recordViewStateForCurrentEntry(contentViewsManager->captureViewState()); +} + +qulonglong YACReaderNavigationController::folderIdForIndex(const QModelIndex &folderIndex) const { - if (!mi.isValid()) - return 1; + if (!folderIndex.isValid()) + return FolderModel::RootFolderId; - auto folderItem = static_cast(mi.internalPointer()); + auto folderItem = static_cast(folderIndex.internalPointer()); if (folderItem != nullptr) return folderItem->id; - return 1; + return FolderModel::RootFolderId; } diff --git a/YACReaderLibrary/yacreader_navigation_controller.h b/YACReaderLibrary/yacreader_navigation_controller.h index 74a5588ef..eb2c1e665 100644 --- a/YACReaderLibrary/yacreader_navigation_controller.h +++ b/YACReaderLibrary/yacreader_navigation_controller.h @@ -1,8 +1,15 @@ #ifndef YACREADER_NAVIGATION_CONTROLLER_H #define YACREADER_NAVIGATION_CONTROLLER_H +#include "content_view_state.h" + #include +#include + +#include + class LibraryWindow; +class LibrarySearchCoordinator; class YACReaderLibrarySourceContainer; class YACReaderContentViewsManager; @@ -10,44 +17,48 @@ class YACReaderNavigationController : public QObject { Q_OBJECT public: - explicit YACReaderNavigationController(LibraryWindow *parent, YACReaderContentViewsManager *contentViewsManager); - -signals: + explicit YACReaderNavigationController(LibraryWindow *parent, YACReaderContentViewsManager *contentViewsManager, LibrarySearchCoordinator *librarySearchCoordinator); public slots: - // info origins - // folders view - void selectedFolder(const QModelIndex &mi); + void selectedFolder(const QModelIndex &proxyIndex); + void navigateToFolder(const QModelIndex &sourceIndex); void reselectCurrentFolder(); - // reading lists - void selectedList(const QModelIndex &mi); + void selectedList(const QModelIndex &proxyIndex); void reselectCurrentList(); void reselectCurrentSource(); + void beginCurrentSourceRefresh(); + void cancelCurrentSourceRefresh(); + void refreshCurrentSource(); // history navigation + void backward(); + void forward(); void selectedIndexFromHistory(const YACReaderLibrarySourceContainer &sourceContainer); void loadIndexFromHistory(const YACReaderLibrarySourceContainer &sourceContainer); - // empty subfolder - void selectSubfolder(const QModelIndex &sourceMI, int child); - - void loadEmptyFolderInfo(const QModelIndex &modelIndex); - void loadFolderInfo(const QModelIndex &modelIndex); - void loadListInfo(const QModelIndex &modelIndex); - void loadSpecialListInfo(const QModelIndex &modelIndex); - void loadLabelInfo(const QModelIndex &modelIndex); - void loadReadingListInfo(const QModelIndex &modelIndex); + void loadFolderContent(const QModelIndex &folderIndex); + void loadListContent(const QModelIndex &listIndex); + void loadSpecialListContent(const QModelIndex &listIndex); + void loadLabelContent(const QModelIndex &listIndex); + void loadReadingListContent(const QModelIndex &listIndex); void loadPreviousStatus(); + void reloadRootContinueReading(); private: void setupConnections(); + void loadRootContinueReading(); + void recordCurrentViewState(); + LibraryWindow *libraryWindow; YACReaderContentViewsManager *contentViewsManager; + LibrarySearchCoordinator *librarySearchCoordinator; + bool restoringHistorySelection = false; + std::optional pendingRefreshViewState; + QPersistentModelIndex loadedFolder; - // convenience methods - qulonglong folderModelIndexToID(const QModelIndex &mi); + qulonglong folderIdForIndex(const QModelIndex &folderIndex) const; }; #endif // YACREADER_NAVIGATION_CONTROLLER_H diff --git a/YACReaderLibrary/yacreaderlibrary_de.ts b/YACReaderLibrary/yacreaderlibrary_de.ts index ae6a71375..56b9242e6 100644 --- a/YACReaderLibrary/yacreaderlibrary_de.ts +++ b/YACReaderLibrary/yacreaderlibrary_de.ts @@ -202,11 +202,22 @@ ClassicComicsView - + Hide comic flow Comic Flow ausblenden + + ComicFilesCoordinator + + Copying comics... + Kopieren von Comics... + + + Moving comics... + Verschieben von Comics... + + ComicInfoView @@ -290,70 +301,99 @@ Charaktere + + ComicManagementCoordinator + + + + YACReader not found + YACReader nicht gefunden + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + YACReader nicht gefunden. YACReader muss im gleichen Ordner installiert sein wie YACReaderLibrary. + + + + YACReader not found. There might be a problem with your YACReader installation. + YACReader nicht gefunden. Eventuell besteht ein Problem mit Ihrer YACReader-Installation. + + + + Error + Fehler + + + + Error opening comic with third party reader. + Beim Öffnen des Comics mit dem Drittanbieter-Reader ist ein Fehler aufgetreten. + + ComicModel - + no Nein - + yes Ja - + Read Lesen - + Series Serie - + Volume Volumen - + Story Arc Handlungsbogen - + Size Größe - + Pages Seiten - + Title Titel - + Current Page Aktuelle Seite - + File Name Dateiname - + Publication Date Veröffentlichungsdatum - + Rating Bewertung @@ -381,13 +421,13 @@ schließen - - + + Retrieving tags for : %1 Herunterladen von Tags für : %1 - + Looking for comic... Suche nach Comic... @@ -397,34 +437,42 @@ suche - - - + + + Looking for volume... Suche nach Band.... - - + + comic %1 of %2 - %3 Comic %1 von %2 - %3 - + %1 comics selected %1 Comic ausgewählt - + Error connecting to ComicVine Fehler bei Verbindung zu ComicVine - + Retrieving volume info... Herunterladen von Info zu Ausgabe... + + ContinueReadingGridHeader + + + Continue Reading... + Weiterlesen... + + CreateLibraryDialog @@ -468,6 +516,14 @@ Pfad nicht gefunden + + DBHelper + + + The folder entry could not be found in the library database. + Der Ordnereintrag wurde in der Datenbank der Bibliothek nicht gefunden. + + EditShortcutsDialog @@ -504,6 +560,19 @@ Dieser Ordner enthält noch keine Comics + + EmptyInfoView + + + Nothing selected + Nichts ausgewählt + + + + Select a comic or folder to see its information. + Wählen Sie einen Comic oder Ordner aus, um Informationen anzuzeigen. + + EmptyLabelWidget @@ -617,27 +686,23 @@ FileComic - + + Format not supported Format nicht unterstützt - + 7z not found 7z nicht gefunden - + Unknown error opening the file Unbekannter Fehler beim Öffnen der Datei - - Unsupported EPUB: %1 - - - - + CRC error on page (%1): some of the pages will not be displayed correctly CRC Fehler auf Seite (%1): einige Seiten werden nicht korrekt dargestellt @@ -645,18 +710,134 @@ FolderContentView - Continue Reading... - Weiterlesen... + Weiterlesen... + + + + FolderInfoView + + + Unknown + Unbekannt + + + + Items + Elemente + + + + Type + Typ + + + + Reading status + Lesestatus + + + + Read + Lesen + + + + Unread + Ungelesen + + + + Collection status + Sammlungsstatus + + + + Completed + Abgeschlossen + + + + In progress + In Bearbeitung + + + + Added + Hinzugefügt + + + + Updated + Aktualisiert + + + + FolderManagementCoordinator + + + Add new folder + Neuen Ordner erstellen + + + + Folder name: + Ordnername GridComicsView - + Show info Info anzeigen + + Library + Bibliothek + + + Folder + Ordner + + + Favorites + Favoriten + + + Recently added + Kürzlich hinzugefügt + + + + Manga + Manga + + + + Western manga + Westlicher Manga + + + + Web comic + Webcomic + + + + Yonkoma + Yonkoma + + + + Comic + Comic + + + + Unknown + Unbekannt + HelpAboutDialog @@ -806,104 +987,94 @@ - LibraryWindow + LibraryInfoView - - The selected folder doesn't contain any library. - Der ausgewählte Ordner enthält keine Bibliothek. + + Library info + Informationen zur Bibliothek - - This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? - Diese Bibliothek wurde mit einer älteren Version von YACReader erzeugt. Sie muss geupdated werden. Jetzt updaten? + + Number of folders + Anzahl der Ordner - - Comic - Komisch + + Number of comics + Anzahl der Comics - + + Number of read comics + Anzahl der gelesenen Comics + + + + LibraryManagementCoordinator + + Error opening the library Fehler beim Öffnen der Bibliothek - - - YACReader not found - YACReader nicht gefunden + + Error creating the library + Fehler beim Erstellen der Bibliothek - Remove and delete metadata - Entferne und lösche Metadaten + + Error updating the library + Fehler beim Updaten der Bibliothek + + + LibraryWindow - - Old library - Alte Bibliothek + + The selected folder doesn't contain any library. + Der ausgewählte Ordner enthält keine Bibliothek. - - Set as completed - Als gelesen markieren + + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? + Diese Bibliothek wurde mit einer älteren Version von YACReader erzeugt. Sie muss geupdated werden. Jetzt updaten? - - Library - Bibliothek + Remove and delete metadata + Entferne und lösche Metadaten + + + + Old library + Alte Bibliothek - + This library was created with a newer version of YACReaderLibrary. Download the new version now? Die Bibliothek wurde mit einer neueren Version von YACReader erstellt. Die neue Version jetzt herunterladen? - + Library '%1' is no longer available. Do you want to remove it? Bibliothek '%1' ist nicht mehr verfügbar. Wollen Sie sie entfernen? - - Open folder... - Öffne Ordner... - - - + Do you want remove Möchten Sie entfernen - - Set as uncompleted - Als nicht gelesen markieren - - - - Error updating the library - Fehler beim Updaten der Bibliothek - - - - Folder - Ordner - - - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? Bibliothek '%1' wurde mit einer älteren Version von YACReader erstellt. Sie muss neu erzeugt werden. Wollen Sie die Bibliothek jetzt erzeugen? - - Set as read - Als gelesen markieren - - - + Library not available Bibliothek nicht verfügbar - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. Es gab ein Problem beim Löschen der ausgewählten Comics. Überprüfen Sie bitte die Schreibberechtigung für die ausgewählten Dateien oder Ordner. @@ -913,375 +1084,308 @@ YACReader Bibliothek - - Error creating the library - Fehler beim Erstellen der Bibliothek - - - + Update needed Update benötigt - + Library name already exists Bibliothek-Name bereits vorhanden - + There is another library with the name '%1'. Es gibt bereits eine Bibliothek mit dem Namen '%1'. - + Download new version Neue Version herunterladen - + Delete comics Comics löschen - + All the selected comics will be deleted from your disk. Are you sure? Alle ausgewählten Comics werden von Ihrer Festplatte gelöscht. Sind Sie sicher? - - - Set as unread - Als ungelesen markieren - - - + Library not found Bibliothek nicht gefunden - - - - manga - Manga - - - - - - comic - komisch - - - - - - web comic - Webcomic - - - - - - western manga (left to right) - Western-Manga (von links nach rechts) - - - - + + Unable to delete Löschen nicht möglich - - - - 4koma (top to botom) - 4koma (top to botom - 4koma (von oben nach unten) - - - + library? Bibliothek? - + Are you sure? Sind Sie sicher? - - Rescan library for XML info - Durchsuchen Sie die Bibliothek erneut nach XML-Informationen - - - - Add new folder - Neuen Ordner erstellen - - - + Delete folder Ordner löschen - - Update folder - Ordner aktualisieren - - - + Upgrade failed Update gescheitert - + There were errors during library upgrade in: Beim Upgrade der Bibliothek kam es zu Fehlern in: - - + Copying comics... Kopieren von Comics... - - + Moving comics... Verschieben von Comics... - + Folder name: Ordnername - + + + No folder selected Kein Ordner ausgewählt - + + + Please, select a folder first Bitte wählen Sie zuerst einen Ordner aus - + Error in path Fehler im Pfad - + There was an error accessing the folder's path Beim Aufrufen des Ordnerpfades kam es zu einem Fehler - + The selected folder and all its contents will be deleted from your disk. Are you sure? Der ausgewählte Ordner und sein gesamter Inhalt wird von Ihrer Festplatte gelöscht. Sind Sie sicher? - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. Beim Löschen des ausgewählten Ordners ist ein Problem aufgetreten. Bitte überprüfen Sie die Schreibrechte und stellen Sie sicher, dass keine Anwendung diese Ordner oder die darin enthaltenen Dateien verwendet. - - Add new reading lists - Neue Leseliste hinzufügen - - - - - List name: - Name der Liste - - - - Delete list/label - Ausgewählte/s Liste/Label löschen - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - Das ausgewählte Element wird gelöscht; Ihre Comics oder Ordner werden NICHT von Ihrer Festplatte gelöscht. Sind Sie sicher? - - - - Rename list name - Listenname ändern + + Rename or organize files + Dateien umbenennen oder organisieren - - - - - Set type - Typ festlegen + + Set the type of the selected comics + Typ der ausgewählten Comics festlegen - + Search filters Suchfilter - + Unread Ungelesen - + In progress In Bearbeitung - + Highly rated Hoch bewertet - + Recently added Kürzlich hinzugefügt - + Search syntax… Suchsyntax… - + A repair of this library is already running (%1). Wait for it to finish. Für diese Bibliothek läuft bereits eine Reparatur (%1). Warten Sie, bis sie abgeschlossen ist. - + The library is locked by a repair that did not finish. Die Bibliothek ist durch eine nicht abgeschlossene Reparatur gesperrt. - + The library is locked by a repair started by %1. Die Bibliothek ist durch eine von %1 gestartete Reparatur gesperrt. - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? Wenn Sie sicher sind, dass keine andere Reparatur läuft, kann die Sperre entfernt werden. Sperre entfernen und fortfahren? - + Package operation failed - + Paketvorgang fehlgeschlagen - + The covers package operation could not be completed. - + Der Vorgang mit dem Cover-Paket konnte nicht abgeschlossen werden. - + Restore recovery failed Wiederherstellung nach Abbruch fehlgeschlagen - - Set custom cover - Legen Sie ein benutzerdefiniertes Cover fest + + Rename folder + Ordner umbenennen - - Delete custom cover - Benutzerdefiniertes Cover löschen + + Invalid folder name + Ungültiger Ordnername - - Save covers - Titelbilder speichern + + The folder name is empty or contains characters that are not supported. + Der Ordnername ist leer oder enthält nicht unterstützte Zeichen. - - You are adding too many libraries. - Sie fügen zu viele Bibliotheken hinzu. + + + + Unable to rename folder + Ordner kann nicht umbenannt werden - - You are adding too many libraries. - -You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. + + A file or folder named '%1' already exists. + Eine Datei oder ein Ordner mit dem Namen „%1“ existiert bereits. + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. -YACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low. - Sie fügen zu viele Bibliotheken hinzu. +Folder: %1 + Der Ordner konnte auf dem Datenträger nicht umbenannt werden. Bitte prüfen Sie den Ordnernamen und die Schreibrechte. -Wahrscheinlich brauchen Sie nur eine Bibliothek in Ihrem obersten Comic-Ordner, Sie können alle Unterordner mit Hilfe des Ordnerbereichs in der linken Seitenleiste durchsuchen. - -YACReaderLibrary wird Sie nicht daran hindern, weitere Bibliotheken zu erstellen, aber Sie sollten die Anzahl der Bibliotheken gering halten. +Ordner: %1 - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - YACReader nicht gefunden. YACReader muss im gleichen Ordner installiert sein wie YACReaderLibrary. + + The library database could not be updated. The folder rename on disk was reverted. + Die Datenbank der Bibliothek konnte nicht aktualisiert werden. Die Umbenennung des Ordners auf dem Datenträger wurde rückgängig gemacht. - - YACReader not found. There might be a problem with your YACReader installation. - YACReader nicht gefunden. Eventuell besteht ein Problem mit Ihrer YACReader-Installation. + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + Die Datenbank der Bibliothek konnte nicht aktualisiert werden, und die Umbenennung des Ordners auf dem Datenträger konnte nicht rückgängig gemacht werden. Die Bibliothek muss jetzt manuell aktualisiert werden. - - Error - Fehler + + Save covers + Titelbilder speichern - - Error opening comic with third party reader. - Beim Öffnen des Comics mit dem Drittanbieter-Reader ist ein Fehler aufgetreten. + + You are adding too many libraries. + Sie fügen zu viele Bibliotheken hinzu. + + + + You are adding too many libraries. + +You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. + +YACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low. + Sie fügen zu viele Bibliotheken hinzu. + +Wahrscheinlich brauchen Sie nur eine Bibliothek in Ihrem obersten Comic-Ordner, Sie können alle Unterordner mit Hilfe des Ordnerbereichs in der linken Seitenleiste durchsuchen. + +YACReaderLibrary wird Sie nicht daran hindern, weitere Bibliotheken zu erstellen, aber Sie sollten die Anzahl der Bibliotheken gering halten. - - + + YACReader library database (*.ydb) YACReader-Bibliotheksdatenbank (*.ydb) - + The library database backup was created at: %1 Die Sicherung der Bibliotheksdatenbank wurde hier erstellt: %1 - + Unable to create the library database backup: %1 Die Sicherung der Bibliotheksdatenbank konnte nicht erstellt werden: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? Schließen Sie vor der Wiederherstellung YACReaderLibraryServer und alle anderen YACReader-Anwendungen, die diese Bibliothek verwenden. Fortfahren? - + Restoring library database... Bibliotheksdatenbank wird wiederhergestellt... - + The current library database is invalid. Restore the selected backup anyway? Die aktuelle Bibliotheksdatenbank ist ungültig. Die ausgewählte Sicherung trotzdem wiederherstellen? - - + + The library maintenance lock may be stale. Remove it and retry? Die Wartungssperre der Bibliothek ist möglicherweise veraltet. Entfernen und erneut versuchen? - + Restart YACReaderLibrary before attempting recovery again. @@ -1290,71 +1394,71 @@ Restart YACReaderLibrary before attempting recovery again. Starten Sie YACReaderLibrary neu, bevor Sie erneut eine Wiederherstellung versuchen. - + The library database was restored successfully. Update the library now? Die Bibliotheksdatenbank wurde erfolgreich wiederhergestellt. Bibliothek jetzt aktualisieren? - + Library database damaged Bibliotheksdatenbank beschädigt - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. Die Datenbank der Bibliothek '%1' ist beschädigt, daher sind normale Aktualisierungen, Wartungsarbeiten und Sicherungen nicht verfügbar. YACReader kann versuchen, die Datenbank zu reparieren. Einige beschädigte Daten können möglicherweise nicht wiederhergestellt werden. Vorhandene Sicherungen werden nicht verändert. - + Attempt repair Reparatur versuchen - + Restore a backup... Sicherung wiederherstellen... - + Repairing library database... Bibliotheksdatenbank wird repariert... - - - + + + Library database repair Reparatur der Bibliotheksdatenbank - + Another maintenance operation is currently using this library. Try again after it finishes. Ein anderer Wartungsvorgang verwendet diese Bibliothek derzeit. Versuchen Sie es nach dessen Abschluss erneut. - + The library database is already valid. Die Bibliotheksdatenbank ist bereits gültig. - + Library database repaired Bibliotheksdatenbank repariert - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 Die Bibliotheksdatenbank wurde durch den Neuaufbau ihrer Indizes repariert. Das beschädigte Original wurde hier aufbewahrt: %1 - + Library database rebuilt Bibliotheksdatenbank neu aufgebaut - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1365,7 +1469,7 @@ Update the library now? Bibliothek jetzt aktualisieren? - + The damaged original was preserved at: @@ -1376,12 +1480,12 @@ Das beschädigte Original wurde hier aufbewahrt: %1 - + Library database repair failed Reparatur der Bibliotheksdatenbank fehlgeschlagen - + The library database could not be repaired: %1%2 @@ -1392,57 +1496,57 @@ You can restore a backup from the Library menu or recreate the library. Sie können über das Bibliotheksmenü eine Sicherung wiederherstellen oder die Bibliothek neu erstellen. - + Remove and delete metadata and backups Metadaten und Sicherungen entfernen und löschen - + Library info Informationen zur Bibliothek - + Assign comics numbers Comics Nummern zuweisen - + Assign numbers starting in: Nummern zuweisen, beginnend mit: - + Invalid image Ungültiges Bild - + The selected file is not a valid image. Die ausgewählte Datei ist kein gültiges Bild. - + Error saving cover Fehler beim Speichern des Covers - + There was an error saving the cover image. Beim Speichern des Titelbildes ist ein Fehler aufgetreten. - + Remove comics Comics löschen - + Comics will only be deleted from the current label/list. Are you sure? Comics werden nur vom aktuellen Label/der aktuellen Liste gelöscht. Sind Sie sicher? - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1454,763 +1558,1596 @@ Fehlende Dateien: %3 LibraryWindowActions - + Create a new library Neue Bibliothek erstellen - + Open an existing library Eine vorhandede Bibliothek öffnen - - + + Export comics info Comicinfo exportieren - - + + Import comics info Importiere Comic-Info - + Pack covers Titelbild-Paket erzeugen - + Pack the covers of the selected library Packe die Titelbilder der ausgewählten Bibliothek in ein Paket - + Unpack covers Titelbilder entpacken - + Unpack a catalog Katalog entpacken - + Update library Bibliothek updaten - + Update current library Aktuelle Bibliothek updaten - + Back up library database Bibliotheksdatenbank sichern - + Create a backup of the current library database Eine Sicherung der aktuellen Bibliotheksdatenbank erstellen - + Restore library database backup Sicherung der Bibliotheksdatenbank wiederherstellen - + Restore the current library database from a backup Die aktuelle Bibliotheksdatenbank aus einer Sicherung wiederherstellen - + Repair covers and comic info Cover und Comic-Informationen reparieren - + Retry comics with missing covers or incomplete information Comics mit fehlenden Covern oder unvollständigen Informationen erneut verarbeiten - + Rename library Bibliothek umbenennen - + Rename current library Aktuelle Bibliothek umbenennen - + Remove library Bibliothek entfernen - + Remove current library from your collection Aktuelle Bibliothek aus der Sammlung entfernen - + Rescan library for XML info Durchsuchen Sie die Bibliothek erneut nach XML-Informationen - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. Versucht, in Comic-Dateien eingebettete XML-Informationen zu finden. Sie müssen dies nur tun, wenn die Bibliothek mit 9.8.2 oder früheren Versionen erstellt wurde oder wenn Sie Software von Drittanbietern verwenden, um XML-Informationen in die Dateien einzubetten. - + Open library folder... Bibliotheksordner öffnen... - + Open the root folder of the current library Stammordner der aktuellen Bibliothek öffnen - + Show library info Bibliotheksinformationen anzeigen - + Show information about the current library Informationen zur aktuellen Bibliothek anzeigen - + Open current comic Aktuellen Comic öffnen - + Open current comic on YACReader Aktuellen Comic mit YACReader öffnen - + Save selected covers to... Ausgewählte Titelbilder speichern in... - + Save covers of the selected comics as JPG files Titelbilder der ausgewählten Comics als JPG-Datei speichern - - + + Set as read Als gelesen markieren - + Set comic as read Comic als gelesen markieren - - + + Set as unread Als ungelesen markieren - + Set comic as unread Comic als ungelesen markieren - - + + manga Manga - + Set issue as manga Ausgabe als Manga festlegen - - + + comic komisch - + Set issue as normal Ausgabe als normal festlegen - + western manga Western-Manga - + Set issue as western manga Ausgabe als Western-Manga festlegen - - + + web comic Webcomic - + Set issue as web comic Ausgabe als Webcomic festlegen - - + + yonkoma Yonkoma - + Set issue as yonkoma Stellen Sie das Problem als Yonkoma ein - + Show/Hide marks Zeige/Verberge Markierungen - + Show or hide read marks Gelesen-Markierungen anzeigen oder verbergen - + Show/Hide recent indicator Aktuelle Anzeige ein-/ausblenden - + Show or hide recent indicator Aktuelle Anzeige anzeigen oder ausblenden - - + + Fullscreen mode on/off Vollbildmodus an/aus - + Help, About YACReader Hilfe, Über YACReader - + Add new folder Neuen Ordner erstellen - + Add new folder to the current library Neuen Ordner in der aktuellen Bibliothek erstellen - + + Rename folder + Ordner umbenennen + + + + Rename the current folder on disk and in the library + Den aktuellen Ordner auf dem Datenträger und in der Bibliothek umbenennen + + + Delete folder Ordner löschen - + Delete current folder from disk Aktuellen Ordner von der Festplatte löschen - + Select root node Ursprungsordner auswählen - + Expand all nodes Alle Unterordner anzeigen - + Collapse all nodes Alle Unterordner einklappen - + Show options dialog Zeige den Optionen-Dialog - + Show comics server options dialog Zeige Comic-Server-Optionen-Dialog - - + + Change between comics views Zwischen Comic-Anzeigemodi wechseln - + Open folder... Öffne Ordner... - + + + Rename files... + Organize files + Dateien umbenennen... + + + + + Organize into folders... + In Ordner organisieren... + + + Set as uncompleted Als nicht gelesen markieren - + Set as completed Als gelesen markieren - + Set custom cover Legen Sie ein benutzerdefiniertes Cover fest - + Delete custom cover Benutzerdefiniertes Cover löschen - + western manga (left to right) Western-Manga (von links nach rechts) - + Open containing folder... Öffne aktuellen Ordner... - Reset comic rating - Comic-Bewertung zurücksetzen + Comic-Bewertung zurücksetzen - + Select all comics Alle Comics auswählen - + Edit Bearbeiten - + Assign current order to comics Aktuele Sortierung auf Comics anwenden - + Update cover Titelbild updaten - + Delete selected comics Ausgewählte Comics löschen - + Delete metadata from selected comics Metadaten aus ausgewählten Comics löschen - + Download tags from Comic Vine Tags von Comic Vine herunterladen - + Focus search line Suchzeile fokussieren - + Focus comics view Fokus-Comic-Ansicht - + Edit shortcuts Kürzel bearbeiten - + &Quit &Schließen - + Update folder Ordner aktualisieren - + Update current folder Aktuellen Ordner aktualisieren - + Scan legacy XML metadata Scannen Sie ältere XML-Metadaten - + Add new reading list Neue Leseliste hinzufügen - + Add a new reading list to the current library Neue Leseliste zur aktuellen Bibliothek hinzufügen - + Remove reading list Leseliste entfernen - + Remove current reading list from the library Aktuelle Leseliste von der Bibliothek entfernen - - Add new label - Neues Label hinzufügen + + Add new label + Neues Label hinzufügen + + + + Add a new label to this library + Neues Label zu dieser Bibliothek hinzufügen + + + + Rename selected list + Ausgewählte Liste umbenennen + + + + Rename any selected labels or lists + Ausgewählte Labels oder Listen umbenennen + + + + Add to... + Hinzufügen zu... + + + + Favorites + Favoriten + + + + Add selected comics to favorites list + Ausgewählte Comics zu Favoriten hinzufügen + + + + + Reset rating + Bewertung zurücksetzen + + + + LibraryWindowMenus + + + comic + komisch + + + + manga + Manga + + + + western manga (left to right) + Western-Manga (von links nach rechts) + + + + web comic + Webcomic + + + + 4koma (top to botom) + 4koma (von oben nach unten) + + + + + + + Set type + Typ festlegen + + + + Library + Bibliothek + + + + Folder + Ordner + + + + Comic + Comic + + + + Open folder... + Öffne Ordner... + + + + Update folder + Ordner aktualisieren + + + + Rename folder + Ordner umbenennen + + + + Rename files... + Dateien umbenennen... + + + + Organize into folders... + In Ordner organisieren... + + + + Rescan library for XML info + Durchsuchen Sie die Bibliothek erneut nach XML-Informationen + + + + Set as uncompleted + Als nicht gelesen markieren + + + + Set as completed + Als gelesen markieren + + + + Set as read + Als gelesen markieren + + + + + Set as unread + Als ungelesen markieren + + + + Set custom cover + Legen Sie ein benutzerdefiniertes Cover fest + + + + Delete custom cover + Benutzerdefiniertes Cover löschen + + + + ListInfoView + + + 1 comic + 1 Comic + + + + %1 comics + %1 Comics + + + + Last day + Letzter Tag + + + + Last %1 days + Letzte %1 Tage + + + + 1 sublist + 1 Unterliste + + + + %1 sublists + %1 Unterlisten + + + + LocalComicListModel + + + file name + Dateiname + + + + NoLibrariesWidget + + + create your first library + Erstellen Sie Ihre erste Bibliothek + + + + You don't have any libraries yet + Sie haben aktuell noch keine Bibliothek + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <p>Sie können eine Bibliothek in jedem beliebigen Ordner erstellen, YACReaderLibrary wird alle Comics und Unterordner von diesem Ordner importieren. Wenn Sie bereits eine Bibliothek erstellt haben, können Sie sie öffnen.</p><p>Vergessen Sie nicht, dass Sie YACReader als eigentsändige Anwendung nutzen können, um Comics auf Ihrem Computer zu lesen.</p> + + + + add an existing one + Existierende hinzufügen + + + + NoSearchResultsWidget + + + No results + Keine Ergebnisse + + + + OptionsDialog + + + Appearance + Aussehen + + + + Options + Optionen + + + + Language + Sprache + + + + Application language + Anwendungssprache + + + + System default + Systemstandard + + + + Tray icon settings (experimental) + Taskleisten-Einstellungen (experimentell) + + + + Close to tray + In Taskleiste schließen + + + + Start into the system tray + In die Taskleiste starten + + + + Edit Comic Vine API key + Comic Vine API-Schlüssel ändern + + + + Comic Vine API key + Comic Vine API Schlüssel + + + + ComicInfo.xml legacy support + ComicInfo.xml-Legacy-Unterstützung + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + Importieren Sie Metadaten aus ComicInfo.xml, wenn Sie neue Comics hinzufügen + + + + Consider 'recent' items added or updated since X days ago + Berücksichtigen Sie „neue“ Elemente, die seit X Tagen hinzugefügt oder aktualisiert wurden + + + + Third party reader + Drittanbieter-Reader + + + + Write {comic_file_path} where the path should go in the command + Schreiben Sie {comic_file_path}, wohin der Pfad im Befehl gehen soll + + + + Clear + Löschen + + + + Update libraries at startup + Aktualisieren Sie die Bibliotheken beim Start + + + + Try to detect changes automatically + Versuchen Sie, Änderungen automatisch zu erkennen + + + + Update libraries periodically + Aktualisieren Sie die Bibliotheken regelmäßig + + + + Interval: + Intervall: + + + + 30 minutes + 30 Minuten + + + + 1 hour + 1 Stunde + + + + 2 hours + 2 Stunden + + + + 4 hours + 4 Stunden + + + + 8 hours + 8 Stunden + + + + 12 hours + 12 Stunden + + + + daily + täglich + + + + Update libraries at certain time + Aktualisieren Sie Bibliotheken zu einem bestimmten Zeitpunkt + + + + Time: + Zeit: + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNUNG! Während Bibliotheksaktualisierungen sind Schreibvorgänge in die Datenbank deaktiviert! +Planen Sie keine Updates, während Sie die App möglicherweise aktiv nutzen. +Bei automatischen Updates blockiert die App einige Aktionen, bis das Update abgeschlossen ist. +Um eine automatische Aktualisierung zu stoppen, tippen Sie auf die Ladeanzeige neben dem Titel „Bibliotheken“. + + + + Modifications detection + Erkennung von Änderungen + + + + Compare the modified date of files when updating a library (not recommended) + Vergleichen Sie das Änderungsdatum von Dateien beim Aktualisieren einer Bibliothek (nicht empfohlen) + + + + Enable background image + Hintergrundbild aktivieren + + + + Opacity level + Deckkraft-Stufe + + + + Blur level + Unschärfe-Stufe + + + + Use selected comic cover as background + Den ausgewählten Comic als Hintergrund verwenden + + + + Restore defautls + Standardwerte wiederherstellen + + + + Background + Hintergrund + + + + Display continue reading banner + Weiterlesen-Banner anzeigen + + + + Display current comic banner + Aktuelles Comic-Banner anzeigen + + + + Continue reading + Weiterlesen + + + + Mix folders and comics + Ordner und Comics mischen + + + + Start comics on a new row + Comics in einer neuen Zeile beginnen + + + + Content + Inhalt + + + + Comic Flow + Comic Flow + + + + + Libraries + Bibliotheken + + + + Grid view + Rasteransicht + + + + General + Allgemein + + + + Restart is needed + Neustart erforderlich + + + + OrganizeFiles + + + Renamed, %1 is already in use + Umbenannt, %1 wird bereits verwendet + + + + Missing metadata: %1 + Fehlende Metadaten: %1 + + + + %1 could not be created + %1 konnte nicht erstellt werden + + + + OrganizeFilesCoordinator + + + + Organize files + Dateien organisieren + + + + This folder does not contain any comics. + Dieser Ordner enthält keine Comics. + + + + This library is busy: %1 + Diese Bibliothek ist belegt: %1 + + + + the library database could not be opened + die Datenbank der Bibliothek konnte nicht geöffnet werden + + + + the library database could not be locked for writing + die Datenbank der Bibliothek konnte nicht zum Schreiben gesperrt werden + + + + a folder entry could not be restored + ein Ordnereintrag konnte nicht wiederhergestellt werden + + + + a comic entry could not be updated + ein Comic-Eintrag konnte nicht aktualisiert werden + + + + the library database could not be saved: %1 + die Datenbank der Bibliothek konnte nicht gespeichert werden: %1 + + + + the record of the last organize run could not be read + die Aufzeichnung des letzten Organisierens konnte nicht gelesen werden + + + + the folder %1 could not be created + der Ordner %1 konnte nicht erstellt werden + + + + %n file(s) could not be moved back + + %n Datei konnte nicht zurückverschoben werden + %n Dateien konnten nicht zurückverschoben werden + + + + + OrganizeFilesDialog + + Format: + Formatangabe: + + + + Organize files + Dateien organisieren + + + + + Rename files + Dateien umbenennen + + + + Preparing the preview... + Vorschau wird vorbereitet... + + + + &Filename format: + &Dateinamenformat: + + + + &Path format: + &Pfadformat: + + + + Filename format + Dateinamenformat + + + + Path format + Pfadformat + + + + Presets + Vorlagen + + + + Insert + Einfügen + + + + Optional part < > + Optionaler Teil < > + + + + Disappears completely when the fields inside it are empty. + Verschwindet vollständig, wenn die Felder darin leer sind. + + + + Padded number {number:000} + Nummer mit führenden Nullen {number:000} + + + + Format help... + Hilfe zum Format... + + + + selected folder + ausgewählter Ordner + + + + library root + Wurzel der Bibliothek + + + + Move into + Verschieben nach + + + + Reset changes + Änderungen zurücksetzen + + + + Remove selected + Ausgewählte entfernen + + + + Show unchanged + Unveränderte anzeigen + + + + New name + Neuer Name + + + + Renamed from + Vorheriger Name + + + + New location + Neuer Speicherort + + + + Moved from + Vorheriger Speicherort + + + + Remove from list + Aus der Liste entfernen + + + + Move files + Dateien verschieben + + + + Cancel + Abbrechen + + + Copy the list + Liste kopieren - - Add a new label to this library - Neues Label zu dieser Bibliothek hinzufügen + + Undo + Rückgängig - - Rename selected list - Ausgewählte Liste umbenennen + Close + Schließen - - Rename any selected labels or lists - Ausgewählte Labels oder Listen umbenennen + + Copy failure details + Fehlerdetails kopieren - - Add to... - Hinzufügen zu... + + Finish + Fertig - - Favorites - Favoriten + + Remove preset + Vorlage entfernen - - Add selected comics to favorites list - Ausgewählte Comics zu Favoriten hinzufügen + + Save current format as preset... + Aktuelles Format als Vorlage speichern... - - - LocalComicListModel - - file name - Dateiname + + Reset to default format + Auf Standardformat zurücksetzen - - - NoLibrariesWidget - - create your first library - Erstellen Sie Ihre erste Bibliothek + + Save preset + Vorlage speichern - - You don't have any libraries yet - Sie haben aktuell noch keine Bibliothek + + Preset name: + Name der Vorlage: - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <p>Sie können eine Bibliothek in jedem beliebigen Ordner erstellen, YACReaderLibrary wird alle Comics und Unterordner von diesem Ordner importieren. Wenn Sie bereits eine Bibliothek erstellt haben, können Sie sie öffnen.</p><p>Vergessen Sie nicht, dass Sie YACReader als eigentsändige Anwendung nutzen können, um Comics auf Ihrem Computer zu lesen.</p> + + A filename format cannot contain "/". Use Organize files to move comics into folders. + Ein Dateinamenformat darf kein "/" enthalten. Verwenden Sie Dateien organisieren, um Comics in Ordner zu verschieben. - - add an existing one - Existierende hinzufügen + + This format cannot be used: %1 + Dieses Format kann nicht verwendet werden: %1 - - - NoSearchResultsWidget - - No results - Keine Ergebnisse + + new folder + neuer Ordner - - - OptionsDialog - - Appearance - Aussehen + + This folder does not exist yet. It will be created. + Dieser Ordner existiert noch nicht. Er wird erstellt. - - Options - Optionen + + file not found + Datei nicht gefunden - - Language - Sprache + + This comic is in the library but not on disk. It is skipped. + Dieser Comic ist in der Bibliothek, aber nicht auf dem Datenträger. Er wird übersprungen. - - Application language - Anwendungssprache + + name in use + Name belegt - - System default - Systemstandard + + no metadata + keine Metadaten - - Tray icon settings (experimental) - Taskleisten-Einstellungen (experimentell) + + already here + schon hier - - Close to tray - In Taskleiste schließen + + This file is already in the right place. + Diese Datei ist bereits am richtigen Ort. - - Start into the system tray - In die Taskleiste starten + + edited + bearbeitet + + + + %n will be renamed + + %n wird umbenannt + %n werden umbenannt + + + + + %n will move + + %n wird verschoben + %n werden verschoben + + + + + %n unchanged + + %n unverändert + %n unverändert + + + + + %n renamed + + %n umbenannt + %n umbenannt + + + + + %n removed + + %n entfernt + %n entfernt + + + + + %n missing + + %n fehlt + %n fehlen + + + + + %n new folder(s) + + %n neuer Ordner + %n neue Ordner + + + + + %n manual change(s) kept + + %n manuelle Änderung beibehalten + %n manuelle Änderungen beibehalten + - - Edit Comic Vine API key - Comic Vine API-Schlüssel ändern + + Nothing would be renamed with this format. + Mit diesem Format würde nichts umbenannt. - - Comic Vine API key - Comic Vine API Schlüssel + + Nothing would move with this format. + Mit diesem Format würde nichts verschoben. + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + %n Datei wird umbenannt. Die Ordner ändern sich nicht. Sie können das danach rückgängig machen. + %n Dateien werden umbenannt. Die Ordner ändern sich nicht. Sie können das danach rückgängig machen. + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + %n Datei wird nach %1 verschoben. Das ändert Ihre Dateien auf dem Datenträger. Sie können das danach rückgängig machen. + %n Dateien werden nach %1 verschoben. Das ändert Ihre Dateien auf dem Datenträger. Sie können das danach rückgängig machen. + - - ComicInfo.xml legacy support - ComicInfo.xml-Legacy-Unterstützung + + Moving %1 of %2 +%3 + %1 von %2 wird verschoben +%3 - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics - Importieren Sie Metadaten aus ComicInfo.xml, wenn Sie neue Comics hinzufügen + + Updating the library... + Bibliothek wird aktualisiert... - - Consider 'recent' items added or updated since X days ago - Berücksichtigen Sie „neue“ Elemente, die seit X Tagen hinzugefügt oder aktualisiert wurden + + Restored name + Wiederhergestellter Name - - Third party reader - Drittanbieter-Reader + + + Moved back from + Zurückverschoben von - - Write {comic_file_path} where the path should go in the command - Schreiben Sie {comic_file_path}, wohin der Pfad im Befehl gehen soll + + + + + Status + Status - - Clear - Löschen + + Final name + Endgültiger Name - - Update libraries at startup - Aktualisieren Sie die Bibliotheken beim Start + + Previous name + Vorheriger Name - - Try to detect changes automatically - Versuchen Sie, Änderungen automatisch zu erkennen + + Restored location + Wiederhergestellter Speicherort - - Update libraries periodically - Aktualisieren Sie die Bibliotheken regelmäßig + + Final location + Endgültiger Speicherort - - Interval: - Intervall: + + Previous location + Vorheriger Speicherort - - 30 minutes - 30 Minuten + + Restored + Wiederhergestellt - - 1 hour - 1 Stunde + + Renamed + Umbenannt - - 2 hours - 2 Stunden + + Moved + Verschoben - - 4 hours - 4 Stunden + + Undo failed: %1 + Rückgängigmachen fehlgeschlagen: %1 - - 8 hours - 8 Stunden + + Failed: %1 + Fehlgeschlagen: %1 - - 12 hours - 12 Stunden + + Nothing was moved. + Es wurde nichts verschoben. - - daily - täglich + + The record this run could be undone from could not be written, so the run did not start: %1 + Die Aufzeichnung, mit der dieser Vorgang rückgängig gemacht werden könnte, konnte nicht geschrieben werden. Der Vorgang wurde daher nicht gestartet: %1 + + + + %n file(s) renamed. + + %n Datei umbenannt. + %n Dateien umbenannt. + + + + + %n file(s) moved into %1. + + %n Datei nach %1 verschoben. + %n Dateien nach %1 verschoben. + - - Update libraries at certain time - Aktualisieren Sie Bibliotheken zu einem bestimmten Zeitpunkt + + The record of this run stopped early, so the run stopped with it: %1 + Die Aufzeichnung dieses Vorgangs endete vorzeitig, deshalb wurde der Vorgang mit ihr beendet: %1 + + + + %n file(s) were not moved. + + %n Datei wurde nicht verschoben. + %n Dateien wurden nicht verschoben. + - - Time: - Zeit: + + The library database could not be updated: %1 + Die Datenbank der Bibliothek konnte nicht aktualisiert werden: %1 - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNUNG! Während Bibliotheksaktualisierungen sind Schreibvorgänge in die Datenbank deaktiviert! -Planen Sie keine Updates, während Sie die App möglicherweise aktiv nutzen. -Bei automatischen Updates blockiert die App einige Aktionen, bis das Update abgeschlossen ist. -Um eine automatische Aktualisierung zu stoppen, tippen Sie auf die Ladeanzeige neben dem Titel „Bibliotheken“. + + Use Undo to move the files back, or update the library to make it match the files. + Verwenden Sie Rückgängig, um die Dateien zurückzuverschieben, oder aktualisieren Sie die Bibliothek, damit sie zu den Dateien passt. + + + + %n empty folder(s) were removed. + + %n leerer Ordner wurde entfernt. + %n leere Ordner wurden entfernt. + + + + + %n file(s) could not be moved. + + %n Datei konnte nicht verschoben werden. + %n Dateien konnten nicht verschoben werden. + - - Modifications detection - Erkennung von Änderungen + + Moving the files back... + Dateien werden zurückverschoben... - - Compare the modified date of files when updating a library (not recommended) - Vergleichen Sie das Änderungsdatum von Dateien beim Aktualisieren einer Bibliothek (nicht empfohlen) + + Moving back %1 of %2 +%3 + %1 von %2 wird zurückverschoben +%3 - - Enable background image - Hintergrundbild aktivieren + + Everything was moved back. + Alles wurde zurückverschoben. - - Opacity level - Deckkraft-Stufe + + The undo did not finish: %1 + Das Rückgängigmachen wurde nicht abgeschlossen: %1 - - Blur level - Unschärfe-Stufe + + Format help + Hilfe zum Format - - Use selected comic cover as background - Den ausgewählten Comic als Hintergrund verwenden + + Fields + Felder - - Restore defautls - Standardwerte wiederherstellen + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + Jedes Feld wird in geschweiften Klammern geschrieben und durch die Metadaten des Comics ersetzt. Das Menü Einfügen listet alle Felder auf. - - Background - Hintergrund + + {series} gives %1 + {series} ergibt %1 - - Display continue reading banner - Weiterlesen-Banner anzeigen + + Optional parts + Optionale Teile - - Display current comic banner - Aktuelles Comic-Banner anzeigen + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + Ein Teil zwischen den Zeichen < und > verschwindet vollständig, wenn alle Felder darin leer sind. Verwenden Sie ihn für Satzzeichen, die zu einem Feld gehören, etwa Klammern oder ein vorangestelltes Nummernzeichen. Text am Anfang oder am Ende eines Namens wird auch ohne ihn gekürzt. - - Continue reading - Weiterlesen + + {series} ({year}) with no year gives %1 + {series} ({year}) ohne Jahr ergibt %1 - - Comic Flow - Comic Flow + + {series}< ({year})> with no year gives %1 + {series}< ({year})> ohne Jahr ergibt %1 - - - Libraries - Bibliotheken + + Numbers + Nummern - - Grid view - Rasteransicht + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + Schreiben Sie einen Doppelpunkt und einige Nullen, um die Ausgabennummer aufzufüllen. So bleiben die Ausgaben in einem Dateimanager in der richtigen Reihenfolge. - - General - Allgemein + + + Folders + Ordner - - Restart is needed - Neustart erforderlich + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + Ein Dateinamenformat darf keinen Schrägstrich enthalten. Jeder Comic bleibt in seinem aktuellen Ordner. Verwenden Sie In Ordner organisieren, um Comics zu verschieben. + + + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + Jeder durch einen Schrägstrich getrennte Teil wird zu einem Ordner. Der letzte Teil wird zum Dateinamen. Die ursprüngliche Erweiterung bleibt immer erhalten. @@ -2381,12 +3318,12 @@ Um eine automatische Aktualisierung zu stoppen, tippen Sie auf die Ladeanzeige n Anmerkungen: - + Invalid cover Ungültiger Versicherungsschutz - + The image is invalid. Das Bild ist ungültig. @@ -2536,6 +3473,35 @@ Um eine automatische Aktualisierung zu stoppen, tippen Sie auf die Ladeanzeige n Leselisten + + ReadingListManagementCoordinator + + + Add new reading lists + Neue Leseliste hinzufügen + + + + + List name: + Name der Liste + + + + Delete list/label + Ausgewählte/s Liste/Label löschen + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + Das ausgewählte Element wird gelöscht; Ihre Comics oder Ordner werden NICHT von Ihrer Festplatte gelöscht. Sind Sie sicher? + + + + Rename list name + Listenname ändern + + RenameLibraryDialog @@ -3249,6 +4215,61 @@ Use quotes to include spaces in a value. Bände + + SelectedComicsInfoView + + + Unknown + Unbekannt + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + %1 Comic ausgewählt + + + + Read + Lesen + + + + In progress + In Bearbeitung + + + + Unread + Ungelesen + + + + Total pages + + + + + Total size + + + + + Series + Serie + + SeriesQuestion @@ -3270,53 +4291,53 @@ Use quotes to include spaces in a value. ServerConfigDialog - - + + Server connectivity Serverkonnektivität - + Scan to connect Zum Verbinden scannen - + Devices on this network can reach your library at the address below. Geräte in diesem Netzwerk können Ihre Bibliothek unter der unten angegebenen Adresse erreichen. - + IP address IP-Adresse - + Port Anschluss - + Web interface Weboberfläche - + Copy link Link kopieren - + Open web UI Weboberfläche öffnen - + Enable the server Server aktivieren - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. YACReader ist für iOS und Android verfügbar. Entdecken Sie es für <a href='https://ios.yacreader.com'>iOS</a> oder <a href='https://android.yacreader.com'>Android</a>. @@ -3325,7 +4346,7 @@ Use quotes to include spaces in a value. Server aktivieren - + Set port set port Port festlegen diff --git a/YACReaderLibrary/yacreaderlibrary_en.ts b/YACReaderLibrary/yacreaderlibrary_en.ts index fe6cac159..2f2659e28 100644 --- a/YACReaderLibrary/yacreaderlibrary_en.ts +++ b/YACReaderLibrary/yacreaderlibrary_en.ts @@ -202,11 +202,22 @@ ClassicComicsView - + Hide comic flow Hide comic flow + + ComicFilesCoordinator + + Copying comics... + Copying comics... + + + Moving comics... + Moving comics... + + ComicInfoView @@ -290,70 +301,99 @@ b/w + + ComicManagementCoordinator + + + + YACReader not found + YACReader not found + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + + + + YACReader not found. There might be a problem with your YACReader installation. + YACReader not found. There might be a problem with your YACReader installation. + + + + Error + Error + + + + Error opening comic with third party reader. + Error opening comic with third party reader. + + ComicModel - + yes yes - + no no - + Title Title - + File Name File Name - + Pages Pages - + Size Size - + Read Read - + Current Page Current Page - + Publication Date Publication Date - + Rating Rating - + Series Series - + Volume Volume - + Story Arc Story Arc @@ -386,45 +426,53 @@ close - - - + + + Looking for volume... Looking for volume... - - + + comic %1 of %2 - %3 comic %1 of %2 - %3 - + %1 comics selected %1 comics selected - + Error connecting to ComicVine Error connecting to ComicVine - - + + Retrieving tags for : %1 Retrieving tags for : %1 - + Retrieving volume info... Retrieving volume info... - + Looking for comic... Looking for comic... + + ContinueReadingGridHeader + + + Continue Reading... + Continue Reading... + + CreateLibraryDialog @@ -468,6 +516,14 @@ The selected path does not exist or is not a valid path. Be sure that you have write access to this folder + + DBHelper + + + The folder entry could not be found in the library database. + The folder entry could not be found in the library database. + + EditShortcutsDialog @@ -504,6 +560,19 @@ This folder doesn't contain comics yet + + EmptyInfoView + + + Nothing selected + Nothing selected + + + + Select a comic or folder to see its information. + Select a comic or folder to see its information. + + EmptyLabelWidget @@ -617,46 +686,158 @@ FileComic - + 7z not found 7z not found - + CRC error on page (%1): some of the pages will not be displayed correctly CRC error on page (%1): some of the pages will not be displayed correctly - + Unknown error opening the file Unknown error opening the file - + + Format not supported Format not supported - - - Unsupported EPUB: %1 - - FolderContentView - Continue Reading... - Continue Reading... + Continue Reading... + + + + FolderInfoView + + + Unknown + Unknown + + + + Items + Items + + + + Type + Type + + + + Reading status + Reading status + + + + Read + Read + + + + Unread + Unread + + + + Collection status + Collection status + + + + Completed + Completed + + + + In progress + In progress + + + + Added + Added + + + + Updated + Updated + + + + FolderManagementCoordinator + + + Add new folder + Add new folder + + + + Folder name: + Folder name: GridComicsView - + Show info Show info + + Library + Library + + + Folder + Folder + + + Favorites + Favorites + + + Recently added + Recently added + + + + Manga + Manga + + + + Western manga + Western manga + + + + Web comic + Web comic + + + + Yonkoma + Yonkoma + + + + Comic + Comic + + + + Unknown + Unknown + HelpAboutDialog @@ -806,34 +987,50 @@ - LibraryWindow + LibraryInfoView - - Library - Library + + Library info + Library info - - Open folder... - Open folder... + + Number of folders + Number of folders - - - - western manga (left to right) - western manga (left to right) + + Number of comics + Number of comics - - - - 4koma (top to botom) - 4koma (top to botom - 4koma (top to botom) + + Number of read comics + Number of read comics + + + + LibraryManagementCoordinator + + + Error opening the library + Error opening the library + + + + Error creating the library + Error creating the library + + + + Error updating the library + Error updating the library + + + LibraryWindow - + Do you want remove Do you want remove @@ -843,306 +1040,254 @@ YACReader Library - - - - manga - manga - - - - - - comic - comic - - - + Are you sure? Are you sure? - - Rescan library for XML info - Rescan library for XML info - - - - Set as read - Set as read - - - - - Set as unread - Set as unread - - - - - - web comic - web comic - - - - Add new folder - Add new folder - - - + Delete folder Delete folder - - Set as uncompleted - Set as uncompleted - - - - Set as completed - Set as completed - - - - Update folder - Update folder - - - - Folder - Folder - - - - Comic - Comic - - - + Upgrade failed Upgrade failed - + There were errors during library upgrade in: There were errors during library upgrade in: - + Restore recovery failed Restore recovery failed - + Update needed Update needed - + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? - + Download new version Download new version - + This library was created with a newer version of YACReaderLibrary. Download the new version now? This library was created with a newer version of YACReaderLibrary. Download the new version now? - + Library not available Library not available - + Library '%1' is no longer available. Do you want to remove it? Library '%1' is no longer available. Do you want to remove it? - + Old library Old library - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? - - + Copying comics... Copying comics... - - + Moving comics... Moving comics... - + Folder name: Folder name: - + + + No folder selected No folder selected - + + + Please, select a folder first Please, select a folder first - + Error in path Error in path - + There was an error accessing the folder's path There was an error accessing the folder's path - + The selected folder and all its contents will be deleted from your disk. Are you sure? The selected folder and all its contents will be deleted from your disk. Are you sure? - - + + Unable to delete Unable to delete - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. - - - - Add new reading lists - Add new reading lists - - - - - List name: - List name: - - - - Delete list/label - Delete list/label - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. - - Rename list name - Rename list name + + Rename or organize files + Rename or organize files - - - - - Set type - Set type + + Set the type of the selected comics + Set the type of the selected comics - + Search filters Search filters - + Unread Unread - + In progress In progress - + Highly rated Highly rated - + Recently added Recently added - + Search syntax… Search syntax… - + A repair of this library is already running (%1). Wait for it to finish. A repair of this library is already running (%1). Wait for it to finish. - + The library is locked by a repair that did not finish. The library is locked by a repair that did not finish. - + The library is locked by a repair started by %1. The library is locked by a repair started by %1. - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? - + Package operation failed - + Package operation failed - + The covers package operation could not be completed. - + The covers package operation could not be completed. - - Set custom cover - Set custom cover + + Rename folder + Rename folder - - Delete custom cover - Delete custom cover + + Invalid folder name + Invalid folder name + + + + The folder name is empty or contains characters that are not supported. + The folder name is empty or contains characters that are not supported. + + + + + + Unable to rename folder + Unable to rename folder - + + A file or folder named '%1' already exists. + A file or folder named '%1' already exists. + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. + +Folder: %1 + The folder could not be renamed on disk. Please check the folder name and write permissions. + +Folder: %1 + + + + The library database could not be updated. The folder rename on disk was reverted. + The library database could not be updated. The folder rename on disk was reverted. + + + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + + + Save covers Save covers - + You are adding too many libraries. You are adding too many libraries. - + You are adding too many libraries. You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. @@ -1155,84 +1300,58 @@ You probably only need one library in your top level comics folder, you can brow YACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low. - - - YACReader not found - YACReader not found - - - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - - - - YACReader not found. There might be a problem with your YACReader installation. - YACReader not found. There might be a problem with your YACReader installation. - - - - Error - Error - - - - Error opening comic with third party reader. - Error opening comic with third party reader. - - - + Library not found Library not found - + The selected folder doesn't contain any library. The selected folder doesn't contain any library. - - + + YACReader library database (*.ydb) YACReader library database (*.ydb) - + The library database backup was created at: %1 The library database backup was created at: %1 - + Unable to create the library database backup: %1 Unable to create the library database backup: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? - + Restoring library database... Restoring library database... - + The current library database is invalid. Restore the selected backup anyway? The current library database is invalid. Restore the selected backup anyway? - - + + The library maintenance lock may be stale. Remove it and retry? The library maintenance lock may be stale. Remove it and retry? - + Restart YACReaderLibrary before attempting recovery again. @@ -1241,71 +1360,71 @@ Restart YACReaderLibrary before attempting recovery again. Restart YACReaderLibrary before attempting recovery again. - + The library database was restored successfully. Update the library now? The library database was restored successfully. Update the library now? - + Library database damaged Library database damaged - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. - + Attempt repair Attempt repair - + Restore a backup... Restore a backup... - + Repairing library database... Repairing library database... - - - + + + Library database repair Library database repair - + Another maintenance operation is currently using this library. Try again after it finishes. Another maintenance operation is currently using this library. Try again after it finishes. - + The library database is already valid. The library database is already valid. - + Library database repaired Library database repaired - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 - + Library database rebuilt Library database rebuilt - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1316,7 +1435,7 @@ Update the library now? Update the library now? - + The damaged original was preserved at: @@ -1327,12 +1446,12 @@ The damaged original was preserved at: %1 - + Library database repair failed Library database repair failed - + The library database could not be repaired: %1%2 @@ -1343,102 +1462,87 @@ You can restore a backup from the Library menu or recreate the library. You can restore a backup from the Library menu or recreate the library. - + library? library? - + Remove and delete metadata and backups Remove and delete metadata and backups - + Library info Library info - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. - + Assign comics numbers Assign comics numbers - + Assign numbers starting in: Assign numbers starting in: - + Invalid image Invalid image - + The selected file is not a valid image. The selected file is not a valid image. - + Error saving cover Error saving cover - + There was an error saving the cover image. There was an error saving the cover image. - - Error creating the library - Error creating the library - - - - Error updating the library - Error updating the library - - - - Error opening the library - Error opening the library - - - + Delete comics Delete comics - + All the selected comics will be deleted from your disk. Are you sure? All the selected comics will be deleted from your disk. Are you sure? - + Remove comics Remove comics - + Comics will only be deleted from the current label/list. Are you sure? Comics will only be deleted from the current label/list. Are you sure? - + Library name already exists Library name already exists - + There is another library with the name '%1'. There is another library with the name '%1'. - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1450,763 +1554,1596 @@ Missing files: %3 LibraryWindowActions - + Create a new library Create a new library - + Open an existing library Open an existing library - - + + Export comics info Export comics info - - + + Import comics info Import comics info - + Pack covers Pack covers - + Pack the covers of the selected library Pack the covers of the selected library - + Unpack covers Unpack covers - + Unpack a catalog Unpack a catalog - + Update library Update library - + Update current library Update current library - + Back up library database Back up library database - + Create a backup of the current library database Create a backup of the current library database - + Restore library database backup Restore library database backup - + Restore the current library database from a backup Restore the current library database from a backup - + Repair covers and comic info Repair covers and comic info - + Retry comics with missing covers or incomplete information Retry comics with missing covers or incomplete information - + Rename library Rename library - + Rename current library Rename current library - + Remove library Remove library - + Remove current library from your collection Remove current library from your collection - + Rescan library for XML info Rescan library for XML info - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. - + Open library folder... Open library folder... - + Open the root folder of the current library Open the root folder of the current library - + Show library info Show library info - + Show information about the current library Show information about the current library - + Open current comic Open current comic - + Open current comic on YACReader Open current comic on YACReader - + Save selected covers to... Save selected covers to... - + Save covers of the selected comics as JPG files Save covers of the selected comics as JPG files - - + + Set as read Set as read - + Set comic as read Set comic as read - - + + Set as unread Set as unread - + Set comic as unread Set comic as unread - - + + manga manga - + Set issue as manga Set issue as manga - - + + comic comic - + Set issue as normal Set issue as normal - + western manga western manga - + Set issue as western manga Set issue as western manga - - + + web comic web comic - + Set issue as web comic Set issue as web comic - - + + yonkoma yonkoma - + Set issue as yonkoma Set issue as yonkoma - + Show/Hide marks Show/Hide marks - + Show or hide read marks Show or hide read marks - + Show/Hide recent indicator Show/Hide recent indicator - + Show or hide recent indicator Show or hide recent indicator - - + + Fullscreen mode on/off Fullscreen mode on/off - + Help, About YACReader Help, About YACReader - + Add new folder Add new folder - + Add new folder to the current library Add new folder to the current library - + + Rename folder + Rename folder + + + + Rename the current folder on disk and in the library + Rename the current folder on disk and in the library + + + Delete folder Delete folder - + Delete current folder from disk Delete current folder from disk - + Select root node Select root node - + Expand all nodes Expand all nodes - + Collapse all nodes Collapse all nodes - + Show options dialog Show options dialog - + Show comics server options dialog Show comics server options dialog - - + + Change between comics views Change between comics views - + Open folder... Open folder... - + + + Rename files... + Organize files + Rename files... + + + + + Organize into folders... + Organize into folders... + + + Set as uncompleted Set as uncompleted - + Set as completed Set as completed - + Set custom cover Set custom cover - + Delete custom cover Delete custom cover - + western manga (left to right) western manga (left to right) - + Open containing folder... Open containing folder... - Reset comic rating - Reset comic rating + Reset comic rating - + Select all comics Select all comics - + Edit Edit - + Assign current order to comics Assign current order to comics - + Update cover Update cover - + Delete selected comics Delete selected comics - + Delete metadata from selected comics Delete metadata from selected comics - + Download tags from Comic Vine Download tags from Comic Vine - + Focus search line Focus search line - + Focus comics view Focus comics view - + Edit shortcuts Edit shortcuts - + &Quit &Quit - + Update folder Update folder - + Update current folder Update current folder - + Scan legacy XML metadata Scan legacy XML metadata - + Add new reading list Add new reading list - + Add a new reading list to the current library Add a new reading list to the current library - + Remove reading list Remove reading list - + Remove current reading list from the library Remove current reading list from the library - - Add new label - Add new label + + Add new label + Add new label + + + + Add a new label to this library + Add a new label to this library + + + + Rename selected list + Rename selected list + + + + Rename any selected labels or lists + Rename any selected labels or lists + + + + Add to... + Add to... + + + + Favorites + Favorites + + + + Add selected comics to favorites list + Add selected comics to favorites list + + + + + Reset rating + Reset rating + + + + LibraryWindowMenus + + + comic + comic + + + + manga + manga + + + + western manga (left to right) + western manga (left to right) + + + + web comic + web comic + + + + 4koma (top to botom) + 4koma (top to botom) + + + + + + + Set type + Set type + + + + Library + Library + + + + Folder + Folder + + + + Comic + Comic + + + + Open folder... + Open folder... + + + + Update folder + Update folder + + + + Rename folder + Rename folder + + + + Rename files... + Rename files... + + + + Organize into folders... + Organize into folders... + + + + Rescan library for XML info + Rescan library for XML info + + + + Set as uncompleted + Set as uncompleted + + + + Set as completed + Set as completed + + + + Set as read + Set as read + + + + + Set as unread + Set as unread + + + + Set custom cover + Set custom cover + + + + Delete custom cover + Delete custom cover + + + + ListInfoView + + + 1 comic + 1 comic + + + + %1 comics + %1 comics + + + + Last day + Last day + + + + Last %1 days + Last %1 days + + + + 1 sublist + 1 sublist + + + + %1 sublists + %1 sublists + + + + LocalComicListModel + + + file name + file name + + + + NoLibrariesWidget + + + You don't have any libraries yet + You don't have any libraries yet + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + + + + create your first library + create your first library + + + + add an existing one + add an existing one + + + + NoSearchResultsWidget + + + No results + No results + + + + OptionsDialog + + + Language + Language + + + + Application language + Application language + + + + System default + System default + + + + Tray icon settings (experimental) + Tray icon settings (experimental) + + + + Close to tray + Close to tray + + + + Start into the system tray + Start into the system tray + + + + Edit Comic Vine API key + Edit Comic Vine API key + + + + Comic Vine API key + Comic Vine API key + + + + ComicInfo.xml legacy support + ComicInfo.xml legacy support + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + Import metadata from ComicInfo.xml when adding new comics + + + + Consider 'recent' items added or updated since X days ago + Consider 'recent' items added or updated since X days ago + + + + Third party reader + Third party reader + + + + Write {comic_file_path} where the path should go in the command + Write {comic_file_path} where the path should go in the command + + + + Clear + Clear + + + + Update libraries at startup + Update libraries at startup + + + + Try to detect changes automatically + Try to detect changes automatically + + + + Update libraries periodically + Update libraries periodically + + + + Interval: + Interval: + + + + 30 minutes + 30 minutes + + + + 1 hour + 1 hour + + + + 2 hours + 2 hours + + + + 4 hours + 4 hours + + + + 8 hours + 8 hours + + + + 12 hours + 12 hours + + + + daily + daily + + + + Update libraries at certain time + Update libraries at certain time + + + + Time: + Time: + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + + + + Modifications detection + Modifications detection + + + + Compare the modified date of files when updating a library (not recommended) + Compare the modified date of files when updating a library (not recommended) + + + + Enable background image + Enable background image + + + + Opacity level + Opacity level + + + + Blur level + Blur level + + + + Use selected comic cover as background + Use selected comic cover as background + + + + Restore defautls + Restore defautls + + + + Background + Background + + + + Display continue reading banner + Display continue reading banner + + + + Display current comic banner + Display current comic banner + + + + Continue reading + Continue reading + + + + Mix folders and comics + Mix folders and comics + + + + Start comics on a new row + Start comics on a new row + + + + Content + Content + + + + Comic Flow + Comic Flow + + + + + Libraries + Libraries + + + + Grid view + Grid view + + + + General + General + + + + Appearance + Appearance + + + + Options + Options + + + + Restart is needed + Restart is needed + + + + OrganizeFiles + + + Renamed, %1 is already in use + Renamed, %1 is already in use + + + + Missing metadata: %1 + Missing metadata: %1 + + + + %1 could not be created + %1 could not be created + + + + OrganizeFilesCoordinator + + + + Organize files + Organize files + + + + This folder does not contain any comics. + This folder does not contain any comics. + + + + This library is busy: %1 + This library is busy: %1 + + + + the library database could not be opened + the library database could not be opened + + + + the library database could not be locked for writing + the library database could not be locked for writing + + + + a folder entry could not be restored + a folder entry could not be restored + + + + a comic entry could not be updated + a comic entry could not be updated + + + + the library database could not be saved: %1 + the library database could not be saved: %1 + + + + the record of the last organize run could not be read + the record of the last organize run could not be read + + + + the folder %1 could not be created + the folder %1 could not be created + + + + %n file(s) could not be moved back + + %n file could not be moved back + %n files could not be moved back + + + + + OrganizeFilesDialog + + Format: + Format: + + + + Organize files + Organize files + + + + + Rename files + Rename files + + + + Preparing the preview... + Preparing the preview... + + + + &Filename format: + &Filename format: + + + + &Path format: + &Path format: + + + + Filename format + Filename format + + + + Path format + Path format + + + + Presets + Presets + + + + Insert + Insert + + + + Optional part < > + Optional part < > + + + + Disappears completely when the fields inside it are empty. + Disappears completely when the fields inside it are empty. + + + + Padded number {number:000} + Padded number {number:000} + + + + Format help... + Format help... + + + + selected folder + selected folder + + + + library root + library root + + + + Move into + Move into + + + + Reset changes + Reset changes + + + + Remove selected + Remove selected + + + + Show unchanged + Show unchanged + + + + New name + New name + + + + Renamed from + Renamed from + + + + New location + New location + + + + Moved from + Moved from + + + + Remove from list + Remove from list + + + + Move files + Move files + + + + Cancel + Cancel + + + Copy the list + Copy the list - - Add a new label to this library - Add a new label to this library + + Undo + Undo - - Rename selected list - Rename selected list + Close + Close - - Rename any selected labels or lists - Rename any selected labels or lists + + Copy failure details + Copy failure details - - Add to... - Add to... + + Finish + Finish - - Favorites - Favorites + + Remove preset + Remove preset - - Add selected comics to favorites list - Add selected comics to favorites list + + Save current format as preset... + Save current format as preset... - - - LocalComicListModel - - file name - file name + + Reset to default format + Reset to default format - - - NoLibrariesWidget - - You don't have any libraries yet - You don't have any libraries yet + + Save preset + Save preset - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + + Preset name: + Preset name: - - create your first library - create your first library + + A filename format cannot contain "/". Use Organize files to move comics into folders. + A filename format cannot contain "/". Use Organize files to move comics into folders. - - add an existing one - add an existing one + + This format cannot be used: %1 + This format cannot be used: %1 - - - NoSearchResultsWidget - - No results - No results + + new folder + new folder - - - OptionsDialog - - Language - Language + + This folder does not exist yet. It will be created. + This folder does not exist yet. It will be created. - - Application language - Application language + + file not found + file not found - - System default - System default + + This comic is in the library but not on disk. It is skipped. + This comic is in the library but not on disk. It is skipped. - - Tray icon settings (experimental) - Tray icon settings (experimental) + + name in use + name in use - - Close to tray - Close to tray + + no metadata + no metadata - - Start into the system tray - Start into the system tray + + already here + already here - - Edit Comic Vine API key - Edit Comic Vine API key + + This file is already in the right place. + This file is already in the right place. - - Comic Vine API key - Comic Vine API key + + edited + edited + + + + %n will be renamed + + %n will be renamed + %n will be renamed + + + + + %n will move + + %n will move + %n will move + + + + + %n unchanged + + %n unchanged + %n unchanged + + + + + %n renamed + + %n renamed + %n renamed + + + + + %n removed + + %n removed + %n removed + + + + + %n missing + + %n missing + %n missing + + + + + %n new folder(s) + + %n new folder + %n new folders + + + + + %n manual change(s) kept + + %n manual change kept + %n manual changes kept + - - ComicInfo.xml legacy support - ComicInfo.xml legacy support + + Nothing would be renamed with this format. + Nothing would be renamed with this format. - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics - Import metadata from ComicInfo.xml when adding new comics + + Nothing would move with this format. + Nothing would move with this format. + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + %n file will be renamed. The folders do not change. You can undo it afterwards. + %n files will be renamed. The folders do not change. You can undo it afterwards. + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + %n file will move into %1. This changes your files on disk. You can undo it afterwards. + %n files will move into %1. This changes your files on disk. You can undo it afterwards. + - - Consider 'recent' items added or updated since X days ago - Consider 'recent' items added or updated since X days ago + + Moving %1 of %2 +%3 + Moving %1 of %2 +%3 - - Third party reader - Third party reader + + Updating the library... + Updating the library... - - Write {comic_file_path} where the path should go in the command - Write {comic_file_path} where the path should go in the command + + Restored name + Restored name - - Clear - Clear + + + Moved back from + Moved back from - - Update libraries at startup - Update libraries at startup + + + + + Status + Status - - Try to detect changes automatically - Try to detect changes automatically + + Final name + Final name - - Update libraries periodically - Update libraries periodically + + Previous name + Previous name - - Interval: - Interval: + + Restored location + Restored location - - 30 minutes - 30 minutes + + Final location + Final location - - 1 hour - 1 hour + + Previous location + Previous location - - 2 hours - 2 hours + + Restored + Restored - - 4 hours - 4 hours + + Renamed + Renamed - - 8 hours - 8 hours + + Moved + Moved - - 12 hours - 12 hours + + Undo failed: %1 + Undo failed: %1 - - daily - daily + + Failed: %1 + Failed: %1 - - Update libraries at certain time - Update libraries at certain time + + Nothing was moved. + Nothing was moved. - - Time: - Time: + + The record this run could be undone from could not be written, so the run did not start: %1 + The record this run could be undone from could not be written, so the run did not start: %1 + + + + %n file(s) renamed. + + %n file renamed. + %n files renamed. + + + + + %n file(s) moved into %1. + + %n file moved into %1. + %n files moved into %1. + - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. + + The record of this run stopped early, so the run stopped with it: %1 + The record of this run stopped early, so the run stopped with it: %1 + + + + %n file(s) were not moved. + + %n file was not moved. + %n files were not moved. + - - Modifications detection - Modifications detection + + The library database could not be updated: %1 + The library database could not be updated: %1 - - Compare the modified date of files when updating a library (not recommended) - Compare the modified date of files when updating a library (not recommended) + + Use Undo to move the files back, or update the library to make it match the files. + Use Undo to move the files back, or update the library to make it match the files. + + + + %n empty folder(s) were removed. + + %n empty folder was removed. + %n empty folders were removed. + + + + + %n file(s) could not be moved. + + %n file could not be moved. + %n files could not be moved. + - - Enable background image - Enable background image + + Moving the files back... + Moving the files back... - - Opacity level - Opacity level + + Moving back %1 of %2 +%3 + Moving back %1 of %2 +%3 - - Blur level - Blur level + + Everything was moved back. + Everything was moved back. - - Use selected comic cover as background - Use selected comic cover as background + + The undo did not finish: %1 + The undo did not finish: %1 - - Restore defautls - Restore defautls + + Format help + Format help - - Background - Background + + Fields + Fields - - Display continue reading banner - Display continue reading banner + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. - - Display current comic banner - Display current comic banner + + {series} gives %1 + {series} gives %1 - - Continue reading - Continue reading + + Optional parts + Optional parts - - Comic Flow - Comic Flow + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. - - - Libraries - Libraries + + {series} ({year}) with no year gives %1 + {series} ({year}) with no year gives %1 - - Grid view - Grid view + + {series}< ({year})> with no year gives %1 + {series}< ({year})> with no year gives %1 - - General - General + + Numbers + Numbers - - Appearance - Appearance + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. - - Options - Options + + + Folders + Folders - - Restart is needed - Restart is needed + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + + + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. @@ -2469,12 +3406,12 @@ To stop an automatic update tap on the loading indicator next to the Libraries t Edit selected comics information - + Invalid cover Invalid cover - + The image is invalid. The image is invalid. @@ -2532,6 +3469,35 @@ To stop an automatic update tap on the loading indicator next to the Libraries t Reading Lists + + ReadingListManagementCoordinator + + + Add new reading lists + Add new reading lists + + + + + List name: + List name: + + + + Delete list/label + Delete list/label + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + + + + Rename list name + Rename list name + + RenameLibraryDialog @@ -3245,6 +4211,61 @@ Use quotes to include spaces in a value. volume description unavailable + + SelectedComicsInfoView + + + Unknown + Unknown + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + %1 comics selected + + + + Read + Read + + + + In progress + In progress + + + + Unread + Unread + + + + Total pages + + + + + Total size + + + + + Series + Series + + SeriesQuestion @@ -3266,7 +4287,7 @@ Use quotes to include spaces in a value. ServerConfigDialog - + Set port set port Set port @@ -3288,53 +4309,53 @@ Use quotes to include spaces in a value. Choose an IP address - - + + Server connectivity Server connectivity - + Scan to connect Scan to connect - + Devices on this network can reach your library at the address below. Devices on this network can reach your library at the address below. - + IP address IP address - + Port Port - + Web interface Web interface - + Copy link Copy link - + Open web UI Open web UI - + Enable the server Enable the server - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. diff --git a/YACReaderLibrary/yacreaderlibrary_es.ts b/YACReaderLibrary/yacreaderlibrary_es.ts index a0741405e..b2349d73c 100644 --- a/YACReaderLibrary/yacreaderlibrary_es.ts +++ b/YACReaderLibrary/yacreaderlibrary_es.ts @@ -202,11 +202,22 @@ ClassicComicsView - + Hide comic flow Ocultar Comic Flow + + ComicFilesCoordinator + + Copying comics... + Copiando cómics... + + + Moving comics... + Moviendo cómics... + + ComicInfoView @@ -290,70 +301,99 @@ Personajes + + ComicManagementCoordinator + + + + YACReader not found + YACReader no encontrado + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + YACReader no encontrado. YACReader debería estar instalado en la misma carpeta que YACReaderLibrary. + + + + YACReader not found. There might be a problem with your YACReader installation. + YACReader no encontrado. Podría haber un problema con tu instalación de YACReader. + + + + Error + Fallo + + + + Error opening comic with third party reader. + Error al abrir el cómic con una aplicación de terceros. + + ComicModel - + no No - + yes - + Read Leído - + Series Serie - + Volume Volumen - + Story Arc Arco argumental - + Size Tamaño - + Pages Páginas - + Title Título - + Current Page Página Actual - + File Name Nombre de archivo - + Publication Date Fecha de publicación - + Rating Nota @@ -381,13 +421,13 @@ cerrar - - + + Retrieving tags for : %1 Recuperando etiquetas para : %1 - + Looking for comic... Buscando cómic... @@ -397,34 +437,42 @@ buscar - - - + + + Looking for volume... Buscando volumen... - - + + comic %1 of %2 - %3 cómic %1 de %2 - %3 - + %1 comics selected %1 cómics seleccionados - + Error connecting to ComicVine Error conectando a ComicVine - + Retrieving volume info... Recuperando información del volumen... + + ContinueReadingGridHeader + + + Continue Reading... + Continúa leyendo... + + CreateLibraryDialog @@ -468,6 +516,14 @@ Ruta no encontrada + + DBHelper + + + The folder entry could not be found in the library database. + No se ha encontrado la entrada de la carpeta en la base de datos de la biblioteca. + + EditShortcutsDialog @@ -504,6 +560,19 @@ Esta carpeta aún no contiene cómics + + EmptyInfoView + + + Nothing selected + Nada seleccionado + + + + Select a comic or folder to see its information. + Selecciona un cómic o una carpeta para ver su información. + + EmptyLabelWidget @@ -617,27 +686,23 @@ FileComic - + + Format not supported Formato no soportado - + 7z not found 7z no encontrado - + Unknown error opening the file Error desconocido abriendo el archivo - - Unsupported EPUB: %1 - - - - + CRC error on page (%1): some of the pages will not be displayed correctly Error CRC en la página (%1): algunas de las páginas no se mostrarán correctamente @@ -645,18 +710,134 @@ FolderContentView - Continue Reading... - Continúa leyendo... + Continúa leyendo... + + + + FolderInfoView + + + Unknown + Desconocido + + + + Items + Elementos + + + + Type + Tipo + + + + Reading status + Estado de lectura + + + + Read + Leído + + + + Unread + No leído + + + + Collection status + Estado de la colección + + + + Completed + Completado + + + + In progress + En curso + + + + Added + Añadido + + + + Updated + Actualizado + + + + FolderManagementCoordinator + + + Add new folder + Añadir carpeta + + + + Folder name: + Nombre de la carpeta: GridComicsView - + Show info Mostrar información + + Library + Librería + + + Folder + Carpeta + + + Favorites + Favoritos + + + Recently added + Añadido recientemente + + + + Manga + Manga + + + + Western manga + Manga occidental + + + + Web comic + Cómic web + + + + Yonkoma + Yonkoma + + + + Comic + Cómic + + + + Unknown + Desconocido + HelpAboutDialog @@ -806,104 +987,94 @@ - LibraryWindow + LibraryInfoView - - The selected folder doesn't contain any library. - La carpeta seleccionada no contiene ninguna biblioteca. + + Library info + Información de la biblioteca - - This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? - Esta biblioteca fue creada con una versión anterior de YACReaderLibrary. Es necesario que se actualice. ¿Deseas hacerlo ahora? + + Number of folders + Número de carpetas - - Comic - Cómic + + Number of comics + Número de cómics + + + + Number of read comics + Número de cómics leídos + + + LibraryManagementCoordinator - + Error opening the library Error abriendo la biblioteca - - - YACReader not found - YACReader no encontrado + + Error creating the library + Errar creando la biblioteca - Remove and delete metadata - Eliminar y borrar metadatos + + Error updating the library + Error actualizando la biblioteca + + + LibraryWindow - - Old library - Biblioteca antigua + + The selected folder doesn't contain any library. + La carpeta seleccionada no contiene ninguna biblioteca. - - Set as completed - Marcar como completo + + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? + Esta biblioteca fue creada con una versión anterior de YACReaderLibrary. Es necesario que se actualice. ¿Deseas hacerlo ahora? - - Library - Librería + Remove and delete metadata + Eliminar y borrar metadatos + + + + Old library + Biblioteca antigua - + This library was created with a newer version of YACReaderLibrary. Download the new version now? Esta biblioteca fue creada con una versión más nueva de YACReaderLibrary. ¿Deseas descargar la nueva versión ahora? - + Library '%1' is no longer available. Do you want to remove it? La biblioteca '%1' no está disponible. ¿Deseas eliminarla? - - Open folder... - Abrir carpeta... - - - + Do you want remove ¿Deseas eliminar la biblioteca - - Set as uncompleted - Marcar como incompleto - - - - Error updating the library - Error actualizando la biblioteca - - - - Folder - Carpeta - - - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? La biblioteca '%1' ha sido creada con una versión más antigua de YACReaderLibrary y debe ser creada de nuevo. ¿Deseas crear la biblioteca ahora? - - Set as read - Marcar como leído - - - + Library not available Biblioteca no disponible - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. Ha habido algún problema intentando borrar los cómics selecionados. Por favor, verifica los permisos de escritura en los arhicovs seleccionados o los directorios que los conienen. @@ -913,375 +1084,308 @@ Biblioteca YACReader - - Error creating the library - Errar creando la biblioteca - - - + Update needed Se necesita actualizar - + Library name already exists Ya existe el nombre de la biblioteca - + There is another library with the name '%1'. Hay otra biblioteca con el nombre '%1'. - + Download new version Descargar la nueva versión - + Delete comics Borrar cómics - + All the selected comics will be deleted from your disk. Are you sure? Todos los cómics seleccionados serán borrados de tu disco. ¿Estás seguro? - - - Set as unread - Marcar como no leído - - - + Library not found Biblioteca no encontrada - - - - manga - historieta manga - - - - - - comic - cómic - - - - - - web comic - cómic web - - - - - - western manga (left to right) - manga occidental (izquierda a derecha) - - - - + + Unable to delete No se ha podido borrar - - - - 4koma (top to botom) - 4koma (top to botom - 4koma (de arriba a abajo) - - - + library? ? - + Are you sure? ¿Estás seguro? - - Rescan library for XML info - Volver a escanear la biblioteca en busca de información XML - - - - Add new folder - Añadir carpeta - - - + Delete folder Borrar carpeta - - Update folder - Actualizar carpeta - - - + Upgrade failed La actualización falló - + There were errors during library upgrade in: Hubo errores durante la actualización de la biblioteca en: - - + Copying comics... Copiando cómics... - - + Moving comics... Moviendo cómics... - + Folder name: Nombre de la carpeta: - + + + No folder selected No has selecionado ninguna carpeta - + + + Please, select a folder first Por favor, selecciona una carpeta primero - + Error in path Error en la ruta - + There was an error accessing the folder's path Hubo un error al acceder a la ruta de la carpeta - + The selected folder and all its contents will be deleted from your disk. Are you sure? ¿Estás seguro de que deseas eliminar la carpeta seleccionada y todo su contenido de tu disco? - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. Se produjo un problema al intentar eliminar las carpetas seleccionadas. Por favor, verifica los permisos de escritura y asegúrate de que no haya aplicaciones usando estas carpetas o alguno de los archivos contenidos en ellas. - - Add new reading lists - Añadir nuevas listas de lectura - - - - - List name: - Nombre de la lista: - - - - Delete list/label - Eliminar lista/etiqueta - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - El elemento seleccionado se eliminará, tus cómics o carpetas NO se eliminarán de tu disco. ¿Estás seguro? - - - - Rename list name - Renombrar lista + + Rename or organize files + Renombrar u organizar archivos - - - - - Set type - Establecer tipo + + Set the type of the selected comics + Establecer el tipo de los cómics seleccionados - + Search filters Filtros de búsqueda - + Unread No leído - + In progress En curso - + Highly rated Con valoración alta - + Recently added Añadido recientemente - + Search syntax… Sintaxis de búsqueda… - + A repair of this library is already running (%1). Wait for it to finish. Ya se está ejecutando una reparación de esta biblioteca (%1). Espere a que finalice. - + The library is locked by a repair that did not finish. La biblioteca está bloqueada por una reparación que no finalizó. - + The library is locked by a repair started by %1. La biblioteca está bloqueada por una reparación iniciada por %1. - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? Si está seguro de que no se está ejecutando ninguna otra reparación, se puede eliminar el bloqueo. ¿Eliminar el bloqueo y continuar? - + Package operation failed - + Error en la operación de empaquetado - + The covers package operation could not be completed. - + No se ha podido completar la operación con el paquete de portadas. - + Restore recovery failed Error al recuperar la restauración - - Set custom cover - Establecer portada personalizada + + Rename folder + Renombrar carpeta - - Delete custom cover - Eliminar portada personalizada + + Invalid folder name + Nombre de carpeta no válido - - Save covers - Guardar portadas + + The folder name is empty or contains characters that are not supported. + El nombre de la carpeta está vacío o contiene caracteres que no se admiten. - - You are adding too many libraries. - Estás añadiendo demasiadas bibliotecas. + + + + Unable to rename folder + No se ha podido renombrar la carpeta - - You are adding too many libraries. - -You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. + + A file or folder named '%1' already exists. + Ya existe un archivo o una carpeta con el nombre '%1'. + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. -YACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low. - Estás añadiendo demasiadas bibliotecas. +Folder: %1 + No se ha podido renombrar la carpeta en el disco. Comprueba el nombre de la carpeta y los permisos de escritura. -Probablemente solo necesites una biblioteca en la carpeta principal de tus cómics, puedes explorar cualquier subcarpeta utilizando la sección de carpetas en la barra lateral izquierda. - -YACReaderLibrary no te detendrá de crear más bibliotecas, pero deberías mantener el número de bibliotecas bajo control. +Carpeta: %1 - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - YACReader no encontrado. YACReader debería estar instalado en la misma carpeta que YACReaderLibrary. + + The library database could not be updated. The folder rename on disk was reverted. + No se ha podido actualizar la base de datos de la biblioteca. Se ha deshecho el cambio de nombre de la carpeta en el disco. - - YACReader not found. There might be a problem with your YACReader installation. - YACReader no encontrado. Podría haber un problema con tu instalación de YACReader. + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + No se ha podido actualizar la base de datos de la biblioteca ni deshacer el cambio de nombre de la carpeta en el disco. Ahora hay que actualizar la biblioteca a mano. - - Error - Fallo + + Save covers + Guardar portadas - - Error opening comic with third party reader. - Error al abrir el cómic con una aplicación de terceros. + + You are adding too many libraries. + Estás añadiendo demasiadas bibliotecas. + + + + You are adding too many libraries. + +You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. + +YACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low. + Estás añadiendo demasiadas bibliotecas. + +Probablemente solo necesites una biblioteca en la carpeta principal de tus cómics, puedes explorar cualquier subcarpeta utilizando la sección de carpetas en la barra lateral izquierda. + +YACReaderLibrary no te detendrá de crear más bibliotecas, pero deberías mantener el número de bibliotecas bajo control. - - + + YACReader library database (*.ydb) Base de datos de biblioteca de YACReader (*.ydb) - + The library database backup was created at: %1 La copia de seguridad de la base de datos de la biblioteca se creó en: %1 - + Unable to create the library database backup: %1 No se pudo crear la copia de seguridad de la base de datos de la biblioteca: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? Cierra YACReaderLibraryServer y cualquier otra aplicación YACReader que esté usando esta biblioteca antes de restaurarla. ¿Quieres continuar? - + Restoring library database... Restaurando la base de datos de la biblioteca... - + The current library database is invalid. Restore the selected backup anyway? La base de datos actual de la biblioteca no es válida. ¿Quieres restaurar de todos modos la copia seleccionada? - - + + The library maintenance lock may be stale. Remove it and retry? El bloqueo de mantenimiento de la biblioteca puede estar obsoleto. ¿Quieres eliminarlo y volver a intentarlo? - + Restart YACReaderLibrary before attempting recovery again. @@ -1290,71 +1394,71 @@ Restart YACReaderLibrary before attempting recovery again. Reinicia YACReaderLibrary antes de volver a intentar la recuperación. - + The library database was restored successfully. Update the library now? La base de datos de la biblioteca se restauró correctamente. ¿Quieres actualizar la biblioteca ahora? - + Library database damaged Base de datos de la biblioteca dañada - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. La base de datos de la biblioteca '%1' está dañada, por lo que las actualizaciones, el mantenimiento y las copias de seguridad habituales no están disponibles. YACReader puede intentar reparar la base de datos. Es posible que algunos datos dañados no se puedan recuperar. Las copias de seguridad existentes no se modificarán. - + Attempt repair Intentar reparar - + Restore a backup... Restaurar una copia de seguridad... - + Repairing library database... Reparando la base de datos de la biblioteca... - - - + + + Library database repair Reparación de la base de datos de la biblioteca - + Another maintenance operation is currently using this library. Try again after it finishes. Otra operación de mantenimiento está usando esta biblioteca. Vuelve a intentarlo cuando termine. - + The library database is already valid. La base de datos de la biblioteca ya es válida. - + Library database repaired Base de datos de la biblioteca reparada - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 La base de datos de la biblioteca se reparó reconstruyendo sus índices. El original dañado se conservó en: %1 - + Library database rebuilt Base de datos de la biblioteca reconstruida - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1365,7 +1469,7 @@ Update the library now? ¿Quieres actualizar la biblioteca ahora? - + The damaged original was preserved at: @@ -1376,12 +1480,12 @@ El original dañado se conservó en: %1 - + Library database repair failed Error al reparar la base de datos de la biblioteca - + The library database could not be repaired: %1%2 @@ -1392,57 +1496,57 @@ You can restore a backup from the Library menu or recreate the library. Puedes restaurar una copia de seguridad desde el menú Biblioteca o volver a crear la biblioteca. - + Remove and delete metadata and backups Eliminar y borrar metadatos y copias de seguridad - + Library info Información de la biblioteca - + Assign comics numbers Asignar números a los cómics - + Assign numbers starting in: Asignar números comenzando en: - + Invalid image Imagen inválida - + The selected file is not a valid image. El archivo seleccionado no es una imagen válida. - + Error saving cover Error guardando portada - + There was an error saving the cover image. Hubo un error guardando la image de portada. - + Remove comics Eliminar cómics - + Comics will only be deleted from the current label/list. Are you sure? Los cómics sólo se eliminarán de la etiqueta/lista actual. ¿Estás seguro? - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1454,763 +1558,1596 @@ Archivos ausentes: %3 LibraryWindowActions - + Create a new library Crear una nueva biblioteca - + Open an existing library Abrir una biblioteca existente - - + + Export comics info Exportar información de los cómics - - + + Import comics info Importar información de cómics - + Pack covers Empaquetar portadas - + Pack the covers of the selected library Empaquetar las portadas de la biblioteca seleccionada - + Unpack covers Desempaquetar portadas - + Unpack a catalog Desempaquetar un catálogo - + Update library Actualizar biblioteca - + Update current library Actualizar la biblioteca seleccionada - + Back up library database Crear copia de seguridad de la base de datos - + Create a backup of the current library database Crear una copia de seguridad de la base de datos actual de la biblioteca - + Restore library database backup Restaurar copia de seguridad de la base de datos - + Restore the current library database from a backup Restaurar la base de datos actual de la biblioteca desde una copia de seguridad - + Repair covers and comic info Reparar portadas e información de cómics - + Retry comics with missing covers or incomplete information Volver a procesar cómics con portadas ausentes o información incompleta - + Rename library Renombrar biblioteca - + Rename current library Renombrar la biblioteca seleccionada - + Remove library Eliminar biblioteca - + Remove current library from your collection Eliminar biblioteca de la colección - + Rescan library for XML info Volver a escanear la biblioteca en busca de información XML - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. Intenta encontrar información XML incrustada en los archivos de cómic. Solo necesitas hacer esto si la biblioteca fue creada con la versión 9.8.2 o versiones anteriores o si estás utilizando software de terceros para incrustar información XML en los archivos. - + Open library folder... Abrir carpeta de la biblioteca... - + Open the root folder of the current library Abrir la carpeta raíz de la biblioteca actual - + Show library info Mostrar información de la biblioteca - + Show information about the current library Mostrar información de la biblioteca actual - + Open current comic Abrir cómic actual - + Open current comic on YACReader Abrir el cómic actual en YACReader - + Save selected covers to... Guardar las portadas seleccionadas en... - + Save covers of the selected comics as JPG files Guardar las portadas de los cómics seleccionados como archivos JPG - - + + Set as read Marcar como leído - + Set comic as read Marcar cómic como leído - - + + Set as unread Marcar como no leído - + Set comic as unread Marcar cómic como no leído - - + + manga historieta manga - + Set issue as manga Marcar número como manga - - + + comic cómic - + Set issue as normal Marcar número como cómic - + western manga manga occidental - + Set issue as western manga Marcar número como manga occidental - - + + web comic cómic web - + Set issue as web comic Marcar número como cómic web - - + + yonkoma tira yonkoma - + Set issue as yonkoma Marcar número como yonkoma - + Show/Hide marks Mostrar/Ocultar marcas - + Show or hide read marks Mostrar u ocultar marcas - + Show/Hide recent indicator Mostrar/Ocultar el indicador reciente - + Show or hide recent indicator Mostrar o ocultar el indicador reciente - - + + Fullscreen mode on/off Modo a pantalla completa on/off - + Help, About YACReader Ayuda, A cerca de... YACReader - + Add new folder Añadir carpeta - + Add new folder to the current library Añadir carpeta a la biblioteca actual - + + Rename folder + Renombrar carpeta + + + + Rename the current folder on disk and in the library + Renombrar la carpeta actual en el disco y en la biblioteca + + + Delete folder Borrar carpeta - + Delete current folder from disk Borrar carpeta actual del disco - + Select root node Seleccionar el nodo raíz - + Expand all nodes Expandir todos los nodos - + Collapse all nodes Contraer todos los nodos - + Show options dialog Mostrar opciones - + Show comics server options dialog Mostrar el diálogo de opciones del servidor de cómics - - + + Change between comics views Cambiar entre vistas de cómics - + Open folder... Abrir carpeta... - + + + Rename files... + Organize files + Renombrar archivos... + + + + + Organize into folders... + Organizar en carpetas... + + + Set as uncompleted Marcar como incompleto - + Set as completed Marcar como completo - + Set custom cover Establecer portada personalizada - + Delete custom cover Eliminar portada personalizada - + western manga (left to right) manga occidental (izquierda a derecha) - + Open containing folder... Abrir carpeta contenedora... - Reset comic rating - Reseteal cómic rating + Reseteal cómic rating - + Select all comics Seleccionar todos los cómics - + Edit Editar - + Assign current order to comics Asignar el orden actual a los cómics - + Update cover Actualizar portada - + Delete selected comics Borrar los cómics seleccionados - + Delete metadata from selected comics Borrar metadatos de los cómics seleccionados - + Download tags from Comic Vine Descargar etiquetas de Comic Vine - + Focus search line Selecionar el campo de búsqueda - + Focus comics view Selecionar la vista de cómics - + Edit shortcuts Editar atajos - + &Quit &Salir - + Update folder Actualizar carpeta - + Update current folder Actualizar carpeta actual - + Scan legacy XML metadata Escaneal metadatos XML - + Add new reading list Añadir lista de lectura - + Add a new reading list to the current library Añadir una nueva lista de lectura a la biblioteca actual - + Remove reading list Eliminar lista de lectura - + Remove current reading list from the library Eliminar la lista de lectura actual de la biblioteca - - Add new label - Añadir etiqueta + + Add new label + Añadir etiqueta + + + + Add a new label to this library + Añadir etiqueta a esta biblioteca + + + + Rename selected list + Renombrar la lista seleccionada + + + + Rename any selected labels or lists + Renombrar las etiquetas o listas seleccionadas + + + + Add to... + Añadir a... + + + + Favorites + Favoritos + + + + Add selected comics to favorites list + Añadir cómics seleccionados a la lista de favoritos + + + + + Reset rating + Restablecer valoración + + + + LibraryWindowMenus + + + comic + cómic + + + + manga + historieta manga + + + + western manga (left to right) + manga occidental (izquierda a derecha) + + + + web comic + cómic web + + + + 4koma (top to botom) + 4koma (de arriba a abajo) + + + + + + + Set type + Establecer tipo + + + + Library + Librería + + + + Folder + Carpeta + + + + Comic + Cómic + + + + Open folder... + Abrir carpeta... + + + + Update folder + Actualizar carpeta + + + + Rename folder + Renombrar carpeta + + + + Rename files... + Renombrar archivos... + + + + Organize into folders... + Organizar en carpetas... + + + + Rescan library for XML info + Volver a escanear la biblioteca en busca de información XML + + + + Set as uncompleted + Marcar como incompleto + + + + Set as completed + Marcar como completo + + + + Set as read + Marcar como leído + + + + + Set as unread + Marcar como no leído + + + + Set custom cover + Establecer portada personalizada + + + + Delete custom cover + Eliminar portada personalizada + + + + ListInfoView + + + 1 comic + 1 cómic + + + + %1 comics + %1 cómics + + + + Last day + Último día + + + + Last %1 days + Últimos %1 días + + + + 1 sublist + 1 sublista + + + + %1 sublists + %1 sublistas + + + + LocalComicListModel + + + file name + nombre de archivo + + + + NoLibrariesWidget + + + create your first library + crea tu primera biblioteca + + + + You don't have any libraries yet + Aún no tienes ninguna biblioteca + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <p>Puedes crear una biblioteca en cualquier carpeta, YACReaderLibrary importará todos las carpetas y cómics de esa carpeta. Si has creado alguna biblioteca anteriormente, puedes abrirla sin volver a crearla.</p><p>No olvides que puedes usar YACReader como una aplicación independiente para leer los cómics en tu ordenador.</p> + + + + add an existing one + añade una existente + + + + NoSearchResultsWidget + + + No results + Sin resultados + + + + OptionsDialog + + + Appearance + Apariencia + + + + Options + Opciones + + + + Language + Idioma + + + + Application language + Idioma de la aplicación + + + + System default + Predeterminado del sistema + + + + Tray icon settings (experimental) + Opciones de bandeja de sistema (experimental) + + + + Close to tray + Cerrar a la bandeja + + + + Start into the system tray + Comenzar en la bandeja de sistema + + + + Edit Comic Vine API key + Editar la clave API de Comic Vine + + + + Comic Vine API key + Clave API de Comic Vine + + + + ComicInfo.xml legacy support + Soporte para ComicInfo.xml + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + Importar metadatos desde ComicInfo.xml al añadir nuevos cómics + + + + Consider 'recent' items added or updated since X days ago + Considerar elementos 'recientes' añadidos o actualizados desde hace X días + + + + Third party reader + Lector externo + + + + Write {comic_file_path} where the path should go in the command + Escribe {comic_file_path} donde la ruta al cómic debería ir en el comando + + + + Clear + Borrar + + + + Update libraries at startup + Actualizar bibliotecas al inicio + + + + Try to detect changes automatically + Intentar detectar cambios automáticamente + + + + Update libraries periodically + Actualizar bibliotecas periódicamente + + + + Interval: + Intervalo: + + + + 30 minutes + 30 minutos + + + + 1 hour + 1 hora + + + + 2 hours + 2 horas + + + + 4 hours + 4 horas + + + + 8 hours + 8 horas + + + + 12 hours + 12 horas + + + + daily + dirariamente + + + + Update libraries at certain time + Actualizar bibliotecas en un momento determinado + + + + Time: + Hora: + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + ¡ADVERTENCIA! Durante las actualizaciones de la biblioteca se desactivan las escrituras en la base de datos. +No programes actualizaciones mientras puedas estar usando la aplicación activamente. +Durante las actualizaciones automáticas, la aplicación bloqueará algunas de las acciones hasta que la actualización esté terminada. +Para detener una actualización automática, toca en el indicador de carga junto al título de Bibliotecas. + + + + Modifications detection + Detección de modificaciones + + + + Compare the modified date of files when updating a library (not recommended) + Comparar la fecha de modificación de los archivos al actualizar una biblioteca (no recomendado) + + + + Enable background image + Activar imagen de fondo + + + + Opacity level + Nivel de opacidad + + + + Blur level + Nivel de desenfoque + + + + Use selected comic cover as background + Usar la portada del cómic seleccionado como fondo + + + + Restore defautls + Restaurar valores predeterminados + + + + Background + Fondo + + + + Display continue reading banner + Mostrar banner de "Continuar leyendo" + + + + Display current comic banner + Mostar el báner del cómic actual + + + + Continue reading + Continuar leyendo + + + + Mix folders and comics + Mezclar carpetas y cómics + + + + Start comics on a new row + Empezar los cómics en una fila nueva + + + + Content + Contenido + + + + Comic Flow + Comic Flow + + + + + Libraries + Bibliotecas + + + + Grid view + Vista en cuadrícula + + + + General + Opciones generales + + + + Restart is needed + Es necesario reiniciar + + + + OrganizeFiles + + + Renamed, %1 is already in use + Renombrado, %1 ya está en uso + + + + Missing metadata: %1 + Faltan metadatos: %1 + + + + %1 could not be created + No se ha podido crear %1 + + + + OrganizeFilesCoordinator + + + + Organize files + Organizar archivos + + + + This folder does not contain any comics. + Esta carpeta no contiene ningún cómic. + + + + This library is busy: %1 + Esta biblioteca está ocupada: %1 + + + + the library database could not be opened + no se ha podido abrir la base de datos de la biblioteca + + + + the library database could not be locked for writing + no se ha podido bloquear la base de datos de la biblioteca para escritura + + + + a folder entry could not be restored + no se ha podido restaurar una entrada de carpeta + + + + a comic entry could not be updated + no se ha podido actualizar una entrada de cómic + + + + the library database could not be saved: %1 + no se ha podido guardar la base de datos de la biblioteca: %1 + + + + the record of the last organize run could not be read + no se ha podido leer el registro de la última organización + + + + the folder %1 could not be created + no se ha podido crear la carpeta %1 + + + + %n file(s) could not be moved back + + no se ha podido devolver %n archivo a su sitio + no se han podido devolver %n archivos a su sitio + + + + + OrganizeFilesDialog + + Format: + Formato: + + + + Organize files + Organizar archivos + + + + + Rename files + Renombrar archivos + + + + Preparing the preview... + Preparando la vista previa... + + + + &Filename format: + &Formato del nombre de archivo: + + + + &Path format: + Formato de la &ruta: + + + + Filename format + Formato del nombre de archivo + + + + Path format + Formato de la ruta + + + + Presets + Predefinidos + + + + Insert + Insertar + + + + Optional part < > + Parte opcional < > + + + + Disappears completely when the fields inside it are empty. + Desaparece por completo cuando los campos que contiene están vacíos. + + + + Padded number {number:000} + Número con ceros {number:000} + + + + Format help... + Ayuda sobre el formato... + + + + selected folder + carpeta seleccionada + + + + library root + raíz de la biblioteca + + + + Move into + Mover a + + + + Reset changes + Descartar los cambios + + + + Remove selected + Quitar los seleccionados + + + + Show unchanged + Mostrar los que no cambian + + + + New name + Nombre nuevo + + + + Renamed from + Nombre anterior + + + + New location + Ubicación nueva + + + + Moved from + Ubicación anterior + + + + Remove from list + Quitar de la lista + + + + Move files + Mover los archivos + + + + Cancel + Cancelar + + + Copy the list + Copiar la lista - - Add a new label to this library - Añadir etiqueta a esta biblioteca + + Undo + Deshacer - - Rename selected list - Renombrar la lista seleccionada + Close + Cerrar - - Rename any selected labels or lists - Renombrar las etiquetas o listas seleccionadas + + Copy failure details + Copiar detalles de los errores - - Add to... - Añadir a... + + Finish + Finalizar - - Favorites - Favoritos + + Remove preset + Eliminar predefinido - - Add selected comics to favorites list - Añadir cómics seleccionados a la lista de favoritos + + Save current format as preset... + Guardar el formato actual como predefinido... - - - LocalComicListModel - - file name - nombre de archivo + + Reset to default format + Restablecer el formato predeterminado - - - NoLibrariesWidget - - create your first library - crea tu primera biblioteca + + Save preset + Guardar predefinido - - You don't have any libraries yet - Aún no tienes ninguna biblioteca + + Preset name: + Nombre del predefinido: - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <p>Puedes crear una biblioteca en cualquier carpeta, YACReaderLibrary importará todos las carpetas y cómics de esa carpeta. Si has creado alguna biblioteca anteriormente, puedes abrirla sin volver a crearla.</p><p>No olvides que puedes usar YACReader como una aplicación independiente para leer los cómics en tu ordenador.</p> + + A filename format cannot contain "/". Use Organize files to move comics into folders. + Un formato de nombre de archivo no puede contener "/". Usa Organizar archivos para mover cómics a carpetas. - - add an existing one - añade una existente + + This format cannot be used: %1 + No se puede usar este formato: %1 - - - NoSearchResultsWidget - - No results - Sin resultados + + new folder + carpeta nueva - - - OptionsDialog - - Appearance - Apariencia + + This folder does not exist yet. It will be created. + Esta carpeta todavía no existe. Se creará. - - Options - Opciones + + file not found + archivo no encontrado - - Language - Idioma + + This comic is in the library but not on disk. It is skipped. + Este cómic está en la biblioteca pero no en el disco. Se omite. - - Application language - Idioma de la aplicación + + name in use + nombre en uso - - System default - Predeterminado del sistema + + no metadata + sin metadatos - - Tray icon settings (experimental) - Opciones de bandeja de sistema (experimental) + + already here + ya está aquí - - Close to tray - Cerrar a la bandeja + + This file is already in the right place. + Este archivo ya está en el sitio correcto. - - Start into the system tray - Comenzar en la bandeja de sistema + + edited + editado + + + + %n will be renamed + + %n se renombrará + %n se renombrarán + + + + + %n will move + + %n se moverá + %n se moverán + + + + + %n unchanged + + %n sin cambios + %n sin cambios + + + + + %n renamed + + %n renombrado + %n renombrados + + + + + %n removed + + %n quitado + %n quitados + + + + + %n missing + + %n no encontrado + %n no encontrados + + + + + %n new folder(s) + + %n carpeta nueva + %n carpetas nuevas + + + + + %n manual change(s) kept + + Se mantiene %n cambio manual + Se mantienen %n cambios manuales + - - Edit Comic Vine API key - Editar la clave API de Comic Vine + + Nothing would be renamed with this format. + Con este formato no se renombraría nada. - - Comic Vine API key - Clave API de Comic Vine + + Nothing would move with this format. + Con este formato no se movería nada. + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + Se renombrará %n archivo. Las carpetas no cambian. Después puedes deshacerlo. + Se renombrarán %n archivos. Las carpetas no cambian. Después puedes deshacerlo. + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + %n archivo se moverá a %1. Esto cambia tus archivos en el disco. Después puedes deshacerlo. + %n archivos se moverán a %1. Esto cambia tus archivos en el disco. Después puedes deshacerlo. + - - ComicInfo.xml legacy support - Soporte para ComicInfo.xml + + Moving %1 of %2 +%3 + Moviendo %1 de %2 +%3 - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics - Importar metadatos desde ComicInfo.xml al añadir nuevos cómics + + Updating the library... + Actualizando la biblioteca... - - Consider 'recent' items added or updated since X days ago - Considerar elementos 'recientes' añadidos o actualizados desde hace X días + + Restored name + Nombre restaurado - - Third party reader - Lector externo + + + Moved back from + Movido de vuelta desde - - Write {comic_file_path} where the path should go in the command - Escribe {comic_file_path} donde la ruta al cómic debería ir en el comando + + + + + Status + Estado - - Clear - Borrar + + Final name + Nombre final - - Update libraries at startup - Actualizar bibliotecas al inicio + + Previous name + Nombre anterior - - Try to detect changes automatically - Intentar detectar cambios automáticamente + + Restored location + Ubicación restaurada - - Update libraries periodically - Actualizar bibliotecas periódicamente + + Final location + Ubicación final - - Interval: - Intervalo: + + Previous location + Ubicación anterior - - 30 minutes - 30 minutos + + Restored + Restaurado - - 1 hour - 1 hora + + Renamed + Renombrado - - 2 hours - 2 horas + + Moved + Movido - - 4 hours - 4 horas + + Undo failed: %1 + Error al deshacer: %1 - - 8 hours - 8 horas + + Failed: %1 + Error: %1 - - 12 hours - 12 horas + + Nothing was moved. + No se ha movido nada. - - daily - dirariamente + + The record this run could be undone from could not be written, so the run did not start: %1 + No se ha podido escribir el registro con el que se podría deshacer esta operación, así que la operación no ha empezado: %1 + + + + %n file(s) renamed. + + Se ha renombrado %n archivo. + Se han renombrado %n archivos. + + + + + %n file(s) moved into %1. + + Se ha movido %n archivo a %1. + Se han movido %n archivos a %1. + - - Update libraries at certain time - Actualizar bibliotecas en un momento determinado + + The record of this run stopped early, so the run stopped with it: %1 + El registro de esta operación se ha interrumpido, así que la operación se ha detenido con él: %1 + + + + %n file(s) were not moved. + + No se ha movido %n archivo. + No se han movido %n archivos. + - - Time: - Hora: + + The library database could not be updated: %1 + No se ha podido actualizar la base de datos de la biblioteca: %1 - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. - ¡ADVERTENCIA! Durante las actualizaciones de la biblioteca se desactivan las escrituras en la base de datos. -No programes actualizaciones mientras puedas estar usando la aplicación activamente. -Durante las actualizaciones automáticas, la aplicación bloqueará algunas de las acciones hasta que la actualización esté terminada. -Para detener una actualización automática, toca en el indicador de carga junto al título de Bibliotecas. + + Use Undo to move the files back, or update the library to make it match the files. + Usa Deshacer para devolver los archivos a su sitio, o actualiza la biblioteca para que coincida con los archivos. + + + + %n empty folder(s) were removed. + + Se ha eliminado %n carpeta vacía. + Se han eliminado %n carpetas vacías. + + + + + %n file(s) could not be moved. + + No se ha podido mover %n archivo. + No se han podido mover %n archivos. + - - Modifications detection - Detección de modificaciones + + Moving the files back... + Devolviendo los archivos a su sitio... - - Compare the modified date of files when updating a library (not recommended) - Comparar la fecha de modificación de los archivos al actualizar una biblioteca (no recomendado) + + Moving back %1 of %2 +%3 + Devolviendo %1 de %2 +%3 - - Enable background image - Activar imagen de fondo + + Everything was moved back. + Se ha devuelto todo a su sitio. - - Opacity level - Nivel de opacidad + + The undo did not finish: %1 + No se ha podido deshacer del todo: %1 - - Blur level - Nivel de desenfoque + + Format help + Ayuda sobre el formato - - Use selected comic cover as background - Usar la portada del cómic seleccionado como fondo + + Fields + Campos - - Restore defautls - Restaurar valores predeterminados + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + Cada campo se escribe entre llaves y se sustituye por los metadatos del cómic. El menú Insertar los muestra todos. - - Background - Fondo + + {series} gives %1 + {series} da %1 - - Display continue reading banner - Mostrar banner de "Continuar leyendo" + + Optional parts + Partes opcionales - - Display current comic banner - Mostar el báner del cómic actual + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + Una parte escrita entre los signos < y > desaparece por completo cuando todos los campos que contiene están vacíos. Úsala para la puntuación que acompaña a un campo, como los paréntesis o una almohadilla inicial. El texto al principio o al final de un nombre se recorta sin ella. - - Continue reading - Continuar leyendo + + {series} ({year}) with no year gives %1 + {series} ({year}) sin año da %1 - - Comic Flow - Comic Flow + + {series}< ({year})> with no year gives %1 + {series}< ({year})> sin año da %1 - - - Libraries - Bibliotecas + + Numbers + Números - - Grid view - Vista en cuadrícula + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + Escribe dos puntos y varios ceros para rellenar el número del ejemplar. Así los ejemplares se mantienen en orden en un explorador de archivos. - - General - Opciones generales + + + Folders + Carpetas - - Restart is needed - Es necesario reiniciar + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + Un formato de nombre de archivo no puede contener una barra. Cada cómic se queda en su carpeta actual. Usa Organizar en carpetas para mover cómics. + + + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + Cada parte separada por una barra se convierte en una carpeta. La última parte es el nombre del archivo. La extensión original siempre se mantiene. @@ -2381,12 +3318,12 @@ Para detener una actualización automática, toca en el indicador de carga junto Notas: - + Invalid cover Portada inválida - + The image is invalid. La imagen no es válida. @@ -2536,6 +3473,35 @@ Para detener una actualización automática, toca en el indicador de carga junto Listas de lectura + + ReadingListManagementCoordinator + + + Add new reading lists + Añadir nuevas listas de lectura + + + + + List name: + Nombre de la lista: + + + + Delete list/label + Eliminar lista/etiqueta + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + El elemento seleccionado se eliminará, tus cómics o carpetas NO se eliminarán de tu disco. ¿Estás seguro? + + + + Rename list name + Renombrar lista + + RenameLibraryDialog @@ -3249,6 +4215,61 @@ Use quotes to include spaces in a value. volúmenes + + SelectedComicsInfoView + + + Unknown + Desconocido + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + %1 cómics seleccionados + + + + Read + Leído + + + + In progress + En curso + + + + Unread + No leído + + + + Total pages + + + + + Total size + + + + + Series + Serie + + SeriesQuestion @@ -3270,53 +4291,53 @@ Use quotes to include spaces in a value. ServerConfigDialog - - + + Server connectivity Conectividad del servidor - + Scan to connect Escanea para conectar - + Devices on this network can reach your library at the address below. Los dispositivos de esta red pueden acceder a tu biblioteca en la dirección que aparece a continuación. - + IP address Dirección IP - + Port Puerto - + Web interface Interfaz web - + Copy link Copiar enlace - + Open web UI Abrir interfaz web - + Enable the server Activar el servidor - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. YACReader está disponible para iOS y Android. Descúbrelo para <a href='https://ios.yacreader.com'>iOS</a> o <a href='https://android.yacreader.com'>Android</a>. @@ -3325,7 +4346,7 @@ Use quotes to include spaces in a value. activar el servidor - + Set port set port Establecer puerto diff --git a/YACReaderLibrary/yacreaderlibrary_fr.ts b/YACReaderLibrary/yacreaderlibrary_fr.ts index 52135d086..e62af0466 100644 --- a/YACReaderLibrary/yacreaderlibrary_fr.ts +++ b/YACReaderLibrary/yacreaderlibrary_fr.ts @@ -202,11 +202,22 @@ ClassicComicsView - + Hide comic flow Masquer Comic Flow + + ComicFilesCoordinator + + Copying comics... + Copier la bande dessinée... + + + Moving comics... + Déplacer la bande dessinée... + + ComicInfoView @@ -290,70 +301,99 @@ lettreur + + ComicManagementCoordinator + + + + YACReader not found + YACReader introuvable + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + YACReader introuvable. YACReader doit être installé dans le même dossier que YACReaderLibrary. + + + + YACReader not found. There might be a problem with your YACReader installation. + YACReader introuvable. Il se peut qu'il y ait un problème avec votre installation de YACReader. + + + + Error + Erreur + + + + Error opening comic with third party reader. + Erreur lors de l'ouverture de la bande dessinée avec un lecteur tiers. + + ComicModel - + no non - + yes oui - + Read Lu - + Series Série - + Volume Tome - + Story Arc Arc d'histoire - + Size Taille - + Pages Feuilles - + Title Titre - + Current Page Page en cours - + File Name Nom du fichier - + Publication Date Date de publication - + Rating Note @@ -381,13 +421,13 @@ fermer - - + + Retrieving tags for : %1 Retrouver les infomartions de: %1 - + Looking for comic... Vous cherchez une bande dessinée ... @@ -397,34 +437,42 @@ chercher - - + + comic %1 of %2 - %3 bande dessinée %1 sur %2 - %3 - + %1 comics selected %1 bande(s) dessinnée(s) sélectionnée(s) - + Error connecting to ComicVine Erreur de connexion à Comic Vine - - - + + + Looking for volume... Vous cherchez du volume... - + Retrieving volume info... Récupération des informations sur le volume... + + ContinueReadingGridHeader + + + Continue Reading... + Continuer la lecture... + + CreateLibraryDialog @@ -468,6 +516,14 @@ Chemin introuvable + + DBHelper + + + The folder entry could not be found in the library database. + L'entrée du dossier est introuvable dans la base de données de la bibliothèque. + + EditShortcutsDialog @@ -504,6 +560,19 @@ Ce dossier ne contient pas encore de bandes dessinées + + EmptyInfoView + + + Nothing selected + Aucune sélection + + + + Select a comic or folder to see its information. + Sélectionnez une BD ou un dossier pour afficher ses informations. + + EmptyLabelWidget @@ -617,46 +686,158 @@ FileComic - + 7z not found 7z introuvable - + CRC error on page (%1): some of the pages will not be displayed correctly Erreur CRC sur la page (%1): certaines pages ne s'afficheront pas correctement - + Unknown error opening the file Erreur inconnue lors de l'ouverture du fichier - + + Format not supported Format non supporté - - - Unsupported EPUB: %1 - - FolderContentView - Continue Reading... - Continuer la lecture... + Continuer la lecture... + + + + FolderInfoView + + + Unknown + Inconnu + + + + Items + Éléments + + + + Type + Type + + + + Reading status + État de lecture + + + + Read + Lu + + + + Unread + Non lus + + + + Collection status + État de la collection + + + + Completed + Terminé + + + + In progress + En cours + + + + Added + Ajouté + + + + Updated + Mis à jour + + + + FolderManagementCoordinator + + + Add new folder + Ajouter un nouveau dossier + + + + Folder name: + Nom du dossier : GridComicsView - + Show info Afficher les informations + + Library + Librairie + + + Folder + Dossier + + + Favorites + Favoris + + + Recently added + Ajoutés récemment + + + + Manga + Manga + + + + Western manga + Manga occidental + + + + Web comic + Webcomic + + + + Yonkoma + Yonkoma + + + + Comic + Bande dessinée + + + + Unknown + Inconnu + HelpAboutDialog @@ -806,139 +987,99 @@ - LibraryWindow + LibraryInfoView - - The selected folder doesn't contain any library. - Le dossier sélectionné ne contient aucune librairie. + + Library info + Informations sur la bibliothèque - - This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? - Cette librairie a été créée avec une ancienne version de YACReaderLibrary. Mise à jour necessaire. Mettre à jour? + + Number of folders + Nombre de dossiers - - Comic - Bande dessinée + + Number of comics + Nombre de BD - + + Number of read comics + Nombre de BD lues + + + + LibraryManagementCoordinator + + Error opening the library Erreur lors de l'ouverture de la librairie - - - - manga - mangas + + Error creating the library + Erreur lors de la création de la librairie - - - - comic - comique + + Error updating the library + Erreur lors de la mise à jour de la librairie + + + LibraryWindow - - - - western manga (left to right) - manga occidental (de gauche à droite) + + The selected folder doesn't contain any library. + Le dossier sélectionné ne contient aucune librairie. - - - - 4koma (top to botom) - 4koma (top to botom - 4koma (de haut en bas) + + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? + Cette librairie a été créée avec une ancienne version de YACReaderLibrary. Mise à jour necessaire. Mettre à jour? Remove and delete metadata Supprimer les métadata - + Old library Ancienne librairie - - Set as completed - Marquer comme complet - - - - Library - Librairie - - - + This library was created with a newer version of YACReaderLibrary. Download the new version now? Cette librairie a été créée avec une version plus récente de YACReaderLibrary. Télécharger la nouvelle version? - - + Moving comics... Déplacer la bande dessinée... - - + Copying comics... Copier la bande dessinée... - + Library '%1' is no longer available. Do you want to remove it? La librarie '%1' n'est plus disponible. Voulez-vous la supprimer? - - Open folder... - Ouvrir le dossier... - - - + Do you want remove Voulez-vous supprimer - - Set as uncompleted - Marquer comme incomplet - - - - Error updating the library - Erreur lors de la mise à jour de la librairie - - - - Folder - Dossier - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - L'élément sélectionné sera supprimé, vos bandes dessinées ou dossiers ne seront pas supprimés de votre disque. Êtes-vous sûr? - - - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? La librarie '%1' a été créée avec une ancienne version de YACReaderLibrary. Elle doit être re-créée. Voulez-vous créer la librairie? - - Add new reading lists - Ajouter de nouvelles listes de lecture - - - + You are adding too many libraries. You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. @@ -951,12 +1092,7 @@ Vous n'avez probablement besoin que d'une bibliothèque dans votre dos YACReaderLibrary ne vous empêchera pas de créer plus de bibliothèques, mais vous devriez garder le nombre de bibliothèques bas. - - Set as read - Marquer comme lu - - - + Library not available Librairie non disponible @@ -966,317 +1102,285 @@ YACReaderLibrary ne vous empêchera pas de créer plus de bibliothèques, mais v Librairie de YACReader - - Error creating the library - Erreur lors de la création de la librairie - - - - Update folder - Mettre à jour le dossier - - - + Update needed Mise à jour requise - + Library name already exists Le nom de la librairie existe déjà - + There is another library with the name '%1'. Une autre librairie a le nom '%1'. - + Download new version Téléchrger la nouvelle version - + Delete comics Supprimer les comics - + All the selected comics will be deleted from your disk. Are you sure? Tous les comics sélectionnés vont être supprimés de votre disque. Êtes-vous sûr? - - - Set as unread - Marquer comme non-lu - - - + Library not found Librairie introuvable - + library? la librairie? - + Are you sure? Êtes-vous sûr? - - Rescan library for XML info - Réanalyser la bibliothèque pour les informations XML - - - - - - web comic - bande dessinée Web - - - - Add new folder - Ajouter un nouveau dossier - - - + Delete folder Supprimer le dossier - + Upgrade failed La mise à niveau a échoué - + There were errors during library upgrade in: Des erreurs se sont produites lors de la mise à niveau de la bibliothèque dans : - + Folder name: Nom du dossier : - + + + No folder selected Aucun dossier sélectionné - + + + Please, select a folder first Veuillez d'abord sélectionner un dossier - + Error in path Erreur dans le chemin - + There was an error accessing the folder's path Une erreur s'est produite lors de l'accès au chemin du dossier - + The selected folder and all its contents will be deleted from your disk. Are you sure? Le dossier sélectionné et tout son contenu seront supprimés de votre disque. Es-tu sûr? - - + + Unable to delete Impossible de supprimer - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. - Un problème est survenu lors de la tentative de suppression des dossiers sélectionnés. Veuillez vérifier les autorisations d'écriture et assurez-vous que toutes les applications utilisent ces dossiers ou l'un des fichiers contenus. - - - - - List name: - Nom de la liste : - - - - Delete list/label - Supprimer la liste/l'étiquette + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + Un problème est survenu lors de la tentative de suppression des dossiers sélectionnés. Veuillez vérifier les autorisations d'écriture et vous assurer qu'aucune application n'utilise ces dossiers ni aucun des fichiers qu'ils contiennent. - - Rename list name - Renommer le nom de la liste + + Rename or organize files + Renommer ou organiser les fichiers - - - - - Set type - Définir le type + + Set the type of the selected comics + Définir le type des bandes dessinées sélectionnées - + Search filters Filtres de recherche - + Unread Non lus - + In progress En cours - + Highly rated Très bien notés - + Recently added Ajoutés récemment - + Search syntax… Syntaxe de recherche… - + A repair of this library is already running (%1). Wait for it to finish. Une réparation de cette librairie est déjà en cours (%1). Attendez qu'elle se termine. - + The library is locked by a repair that did not finish. La librairie est verrouillée par une réparation qui ne s'est pas terminée. - + The library is locked by a repair started by %1. La librairie est verrouillée par une réparation démarrée par %1. - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? Si vous êtes sûr qu'aucune autre réparation n'est en cours, le verrou peut être supprimé. Supprimer le verrou et continuer ? - + Package operation failed - + Échec de l'opération de paquet - + The covers package operation could not be completed. - + L'opération sur le paquet de couvertures n'a pas pu être terminée. - + Restore recovery failed Échec de la récupération de la restauration - - Set custom cover - Définir une couverture personnalisée + + Rename folder + Renommer le dossier - - Delete custom cover - Supprimer la couverture personnalisée + + Invalid folder name + Nom de dossier non valide - - Save covers - Enregistrer les couvertures + + The folder name is empty or contains characters that are not supported. + Le nom du dossier est vide ou contient des caractères non pris en charge. - - You are adding too many libraries. - Vous ajoutez trop de bibliothèques. + + + + Unable to rename folder + Impossible de renommer le dossier - - - YACReader not found - YACReader introuvable + + A file or folder named '%1' already exists. + Un fichier ou un dossier nommé « %1 » existe déjà. - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - YACReader introuvable. YACReader doit être installé dans le même dossier que YACReaderLibrary. + + The folder could not be renamed on disk. Please check the folder name and write permissions. + +Folder: %1 + Le dossier n'a pas pu être renommé sur le disque. Vérifiez le nom du dossier et les droits d'écriture. + +Dossier : %1 - - YACReader not found. There might be a problem with your YACReader installation. - YACReader introuvable. Il se peut qu'il y ait un problème avec votre installation de YACReader. + + The library database could not be updated. The folder rename on disk was reverted. + La base de données de la bibliothèque n'a pas pu être mise à jour. Le renommage du dossier sur le disque a été annulé. - - Error - Erreur + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + La base de données de la bibliothèque n'a pas pu être mise à jour et le renommage du dossier sur le disque n'a pas pu être annulé. La bibliothèque doit maintenant être mise à jour manuellement. - - Error opening comic with third party reader. - Erreur lors de l'ouverture de la bande dessinée avec un lecteur tiers. + + Save covers + Enregistrer les couvertures + + + + You are adding too many libraries. + Vous ajoutez trop de bibliothèques. - - + + YACReader library database (*.ydb) Base de données de bibliothèque YACReader (*.ydb) - + The library database backup was created at: %1 La sauvegarde de la base de données de la bibliothèque a été créée ici : %1 - + Unable to create the library database backup: %1 Impossible de créer la sauvegarde de la base de données de la bibliothèque : %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? Fermez YACReaderLibraryServer et toute autre application YACReader utilisant cette bibliothèque avant la restauration. Continuer ? - + Restoring library database... Restauration de la base de données de la bibliothèque... - + The current library database is invalid. Restore the selected backup anyway? La base de données actuelle de la bibliothèque n'est pas valide. Restaurer quand même la sauvegarde sélectionnée ? - - + + The library maintenance lock may be stale. Remove it and retry? Le verrou de maintenance de la bibliothèque est peut-être obsolète. Le supprimer et réessayer ? - + Restart YACReaderLibrary before attempting recovery again. @@ -1285,71 +1389,71 @@ Restart YACReaderLibrary before attempting recovery again. Redémarrez YACReaderLibrary avant de tenter à nouveau la récupération. - + The library database was restored successfully. Update the library now? La base de données de la bibliothèque a été restaurée. Mettre à jour la bibliothèque maintenant ? - + Library database damaged Base de données de la bibliothèque endommagée - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. La base de données de la bibliothèque « %1 » est endommagée. Les mises à jour, la maintenance et les sauvegardes habituelles sont donc indisponibles. YACReader peut tenter de réparer la base de données. Certaines données endommagées peuvent être irrécupérables. Les sauvegardes existantes ne seront pas modifiées. - + Attempt repair Tenter la réparation - + Restore a backup... Restaurer une sauvegarde... - + Repairing library database... Réparation de la base de données... - - - + + + Library database repair Réparation de la base de données de la bibliothèque - + Another maintenance operation is currently using this library. Try again after it finishes. Une autre opération de maintenance utilise actuellement cette bibliothèque. Réessayez lorsqu'elle sera terminée. - + The library database is already valid. La base de données de la bibliothèque est déjà valide. - + Library database repaired Base de données de la bibliothèque réparée - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 La base de données de la bibliothèque a été réparée en reconstruisant ses index. L'original endommagé a été conservé ici : %1 - + Library database rebuilt Base de données de la bibliothèque reconstruite - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1360,7 +1464,7 @@ Update the library now? Mettre à jour la bibliothèque maintenant ? - + The damaged original was preserved at: @@ -1371,12 +1475,12 @@ L'original endommagé a été conservé ici : %1 - + Library database repair failed Échec de la réparation de la base de données - + The library database could not be repaired: %1%2 @@ -1387,62 +1491,62 @@ You can restore a backup from the Library menu or recreate the library. Vous pouvez restaurer une sauvegarde depuis le menu Bibliothèque ou recréer la bibliothèque. - + Remove and delete metadata and backups Retirer et supprimer les métadonnées et les sauvegardes - + Library info Informations sur la bibliothèque - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. Un problème est survenu lors de la tentative de suppression des bandes dessinées sélectionnées. Veuillez vérifier les autorisations d'écriture dans les fichiers sélectionnés ou le dossier contenant. - + Assign comics numbers Attribuer des numéros de bandes dessinées - + Assign numbers starting in: Attribuez des numéros commençant par : - + Invalid image Image invalide - + The selected file is not a valid image. Le fichier sélectionné n'est pas une image valide. - + Error saving cover Erreur lors de l'enregistrement de la couverture - + There was an error saving the cover image. Une erreur s'est produite lors de l'enregistrement de l'image de couverture. - + Remove comics Supprimer les bandes dessinées - + Comics will only be deleted from the current label/list. Are you sure? Les bandes dessinées seront uniquement supprimées du label/liste actuelle. Es-tu sûr? - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1454,763 +1558,1596 @@ Fichiers manquants : %3 LibraryWindowActions - + Create a new library Créer une nouvelle librairie - + Open an existing library Ouvrir une librairie existante - - + + Export comics info Exporter les infos des bandes dessinées - - + + Import comics info Importer les infos des bandes dessinées - + Pack covers Archiver les couvertures - + Pack the covers of the selected library Archiver les couvertures de la librairie sélectionnée - + Unpack covers Désarchiver les couvertures - + Unpack a catalog Désarchiver un catalogue - + Update library Mettre la librairie à jour - + Update current library Mettre à jour la librairie actuelle - + Back up library database Sauvegarder la base de données de la bibliothèque - + Create a backup of the current library database Créer une sauvegarde de la base de données actuelle de la bibliothèque - + Restore library database backup Restaurer une sauvegarde de la base de données - + Restore the current library database from a backup Restaurer la base de données actuelle de la bibliothèque depuis une sauvegarde - + Repair covers and comic info Réparer les couvertures et les informations des BD - + Retry comics with missing covers or incomplete information Réessayer les BD dont la couverture est manquante ou les informations incomplètes - + Rename library Renommer la librairie - + Rename current library Renommer la librairie actuelle - + Remove library Supprimer la librairie - + Remove current library from your collection Enlever cette librairie de votre collection - + Rescan library for XML info Réanalyser la bibliothèque pour les informations XML - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. Essaie de trouver des informations XML intégrées dans des fichiers de bandes dessinées. Vous ne devez le faire que si la bibliothèque a été créée avec la version 9.8.2 ou des versions antérieures ou si vous utilisez un logiciel tiers pour intégrer des informations XML dans les fichiers. - + Open library folder... Ouvrir le dossier de la bibliothèque... - + Open the root folder of the current library Ouvrir le dossier racine de la bibliothèque actuelle - + Show library info Afficher les informations sur la bibliothèque - + Show information about the current library Afficher des informations sur la bibliothèque actuelle - + Open current comic Ouvrir cette bande dessinée - + Open current comic on YACReader Ouvrir cette bande dessinée dans YACReader - + Save selected covers to... Exporter la couverture vers... - + Save covers of the selected comics as JPG files Enregistrer les couvertures des bandes dessinées sélectionnées en tant que fichiers JPG - - + + Set as read Marquer comme lu - + Set comic as read Marquer cette bande dessinée comme lu - - + + Set as unread Marquer comme non-lu - + Set comic as unread Marquer cette bande dessinée comme non-lu - - + + manga mangas - + Set issue as manga Définir le problème comme manga - - + + comic comique - + Set issue as normal Définir le problème comme d'habitude - + western manga manga occidental - + Set issue as western manga Définir le problème comme un manga occidental - - + + web comic bande dessinée Web - + Set issue as web comic Définir le problème comme bande dessinée Web - - + + yonkoma Yonkoma - + Set issue as yonkoma Définir le problème comme Yonkoma - + Show/Hide marks Afficher/Cacher les marqueurs - + Show or hide read marks Afficher ou masquer les marques de lecture - + Show/Hide recent indicator Afficher/Masquer l'indicateur récent - + Show or hide recent indicator Afficher ou masquer l'indicateur récent - - + + Fullscreen mode on/off Mode plein écran activé/désactivé - + Help, About YACReader Aide, à propos de YACReader - + Add new folder Ajouter un nouveau dossier - + Add new folder to the current library Ajouter un nouveau dossier à la bibliothèque actuelle - + + Rename folder + Renommer le dossier + + + + Rename the current folder on disk and in the library + Renommer le dossier actuel sur le disque et dans la bibliothèque + + + Delete folder Supprimer le dossier - + Delete current folder from disk Supprimer le dossier actuel du disque - + Select root node Allerà la racine - + Expand all nodes Afficher tous les noeuds - + Collapse all nodes Réduire tous les nœuds - + Show options dialog Ouvrir la boite de dialogue - + Show comics server options dialog Ouvrir la boite de dialogue du serveur - - + + Change between comics views Changement entre les vues de bandes dessinées - + Open folder... Ouvrir le dossier... - + + + Rename files... + Organize files + Renommer les fichiers... + + + + + Organize into folders... + Organiser en dossiers... + + + Set as uncompleted Marquer comme incomplet - + Set as completed Marquer comme complet - + Set custom cover Définir une couverture personnalisée - + Delete custom cover Supprimer la couverture personnalisée - + western manga (left to right) manga occidental (de gauche à droite) - + Open containing folder... Ouvrir le dossier... - Reset comic rating - Supprimer la note d'évaluation + Supprimer la note d'évaluation - + Select all comics Sélectionner toutes les bandes dessinées - + Edit Editer - + Assign current order to comics Assigner l'ordre actuel aux bandes dessinées - + Update cover Mise à jour des couvertures - + Delete selected comics Supprimer la bande dessinée sélectionnée - + Delete metadata from selected comics Supprimer les métadonnées des bandes dessinées sélectionnées - + Download tags from Comic Vine Télécharger les informations de Comic Vine - + Focus search line Ligne de recherche ciblée - + Focus comics view Focus sur la vue des bandes dessinées - + Edit shortcuts Modifier les raccourcis - + &Quit &Quitter - + Update folder Mettre à jour le dossier - + Update current folder Mettre à jour ce dossier - + Scan legacy XML metadata Analyser les métadonnées XML héritées - + Add new reading list Ajouter une nouvelle liste de lecture - + Add a new reading list to the current library Ajouter une nouvelle liste de lecture à la bibliothèque actuelle - + Remove reading list Supprimer la liste de lecture - + Remove current reading list from the library Supprimer la liste de lecture actuelle de la bibliothèque - - Add new label - Ajouter une nouvelle étiquette + + Add new label + Ajouter une nouvelle étiquette + + + + Add a new label to this library + Ajouter une nouvelle étiquette à cette bibliothèque + + + + Rename selected list + Renommer la liste sélectionnée + + + + Rename any selected labels or lists + Renommer toutes les étiquettes ou listes sélectionnées + + + + Add to... + Ajouter à... + + + + Favorites + Favoris + + + + Add selected comics to favorites list + Ajouter la bande dessinée sélectionnée à la liste des favoris + + + + + Reset rating + Réinitialiser la note + + + + LibraryWindowMenus + + + comic + comique + + + + manga + mangas + + + + western manga (left to right) + manga occidental (de gauche à droite) + + + + web comic + bande dessinée Web + + + + 4koma (top to botom) + 4koma (de haut en bas) + + + + + + + Set type + Définir le type + + + + Library + Librairie + + + + Folder + Dossier + + + + Comic + Bande dessinée + + + + Open folder... + Ouvrir le dossier... + + + + Update folder + Mettre à jour le dossier + + + + Rename folder + Renommer le dossier + + + + Rename files... + Renommer les fichiers... + + + + Organize into folders... + Organiser en dossiers... + + + + Rescan library for XML info + Réanalyser la bibliothèque pour les informations XML + + + + Set as uncompleted + Marquer comme incomplet + + + + Set as completed + Marquer comme complet + + + + Set as read + Marquer comme lu + + + + + Set as unread + Marquer comme non-lu + + + + Set custom cover + Définir une couverture personnalisée + + + + Delete custom cover + Supprimer la couverture personnalisée + + + + ListInfoView + + + 1 comic + 1 BD + + + + %1 comics + %1 BD + + + + Last day + Dernier jour + + + + Last %1 days + %1 derniers jours + + + + 1 sublist + 1 sous-liste + + + + %1 sublists + %1 sous-listes + + + + LocalComicListModel + + + file name + nom de fichier + + + + NoLibrariesWidget + + + create your first library + Créez votre première librairie + + + + You don't have any libraries yet + Vous n'avez pas encore de librairie + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <p>Vous pouvez creer une librairie dans n'importe quel dossierr, YACReaderLibrary importera les dossiers et les bandes dessinées contenus dans ce dossier. Si vous avez déjà crer des librairies, vous pouvez les ouvrir.</p><p>N'oubliez pas que vous pouvez utiliser YACReader en tant que stand alone pour lire vos bandes dessinées sur votre ordinateur.</p> + + + + add an existing one + Ajouter une librairie existante + + + + NoSearchResultsWidget + + + No results + Aucun résultat + + + + OptionsDialog + + + Appearance + Apparence + + + + Options + Possibilités + + + + Language + Langue + + + + Application language + Langue de l'application + + + + System default + Par défaut du système + + + + Tray icon settings (experimental) + Paramètres de l'icône de la barre d'état (expérimental) + + + + Close to tray + Près du plateau + + + + Start into the system tray + Commencez dans la barre d'état système + + + + Edit Comic Vine API key + Modifier la clé API Comic Vine + + + + Comic Vine API key + Clé API Comic Vine + + + + ComicInfo.xml legacy support + Prise en charge héritée de ComicInfo.xml + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + Importer des métadonnées depuis ComicInfo.xml lors de l'ajout de nouvelles bandes dessinées + + + + Consider 'recent' items added or updated since X days ago + Considérez les éléments « récents » ajoutés ou mis à jour depuis X jours + + + + Third party reader + Lecteur tiers + + + + Write {comic_file_path} where the path should go in the command + Écrivez {comic_file_path} où le chemin doit aller dans la commande + + + + Clear + Clair + + + + Update libraries at startup + Mettre à jour les bibliothèques au démarrage + + + + Try to detect changes automatically + Essayez de détecter automatiquement les changements + + + + Update libraries periodically + Mettre à jour les bibliothèques périodiquement + + + + Interval: + Intervalle: + + + + 30 minutes + 30 min + + + + 1 hour + 1 heure + + + + 2 hours + 2 heures + + + + 4 hours + 4 heures + + + + 8 hours + 8 heures + + + + 12 hours + 12 heures + + + + daily + tous les jours + + + + Update libraries at certain time + Mettre à jour les bibliothèques à un certain moment + + + + Time: + Temps: + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + AVERTISSEMENT! Lors des mises à jour de la bibliothèque, les écritures dans la base de données sont désactivées ! +Ne planifiez pas de mises à jour pendant que vous utilisez activement l'application. +Lors des mises à jour automatiques, l'application bloquera certaines actions jusqu'à ce que la mise à jour soit terminée. +Pour arrêter une mise à jour automatique, appuyez sur l'indicateur de chargement à côté du titre Bibliothèques. + + + + Modifications detection + Détection des modifications + + + + Compare the modified date of files when updating a library (not recommended) + Comparer la date de modification des fichiers lors de la mise à jour d'une bibliothèque (déconseillé) + + + + Enable background image + Activer l'image d'arrière-plan + + + + Opacity level + Niveau d'opacité + + + + Blur level + Niveau de flou + + + + Use selected comic cover as background + Utiliser la couverture de bande dessinée sélectionnée comme arrière-plan + + + + Restore defautls + Restaurer les valeurs par défaut + + + + Background + Arrière-plan + + + + Display continue reading banner + Afficher la bannière de lecture continue + + + + Display current comic banner + Afficher la bannière de bande dessinée actuelle + + + + Continue reading + Continuer la lecture + + + + Mix folders and comics + Mélanger les dossiers et les BD + + + + Start comics on a new row + Commencer les BD sur une nouvelle ligne + + + + Content + Contenu + + + + Comic Flow + Comic Flow + + + + + Libraries + Bibliothèques + + + + Grid view + Vue grille + + + + General + Général + + + + Restart is needed + Redémarrage nécessaire + + + + OrganizeFiles + + + Renamed, %1 is already in use + Renommé, %1 est déjà utilisé + + + + Missing metadata: %1 + Métadonnées manquantes : %1 + + + + %1 could not be created + %1 n'a pas pu être créé + + + + OrganizeFilesCoordinator + + + + Organize files + Organiser les fichiers + + + + This folder does not contain any comics. + Ce dossier ne contient aucune bande dessinée. + + + + This library is busy: %1 + Cette bibliothèque est occupée : %1 + + + + the library database could not be opened + la base de données de la bibliothèque n'a pas pu être ouverte + + + + the library database could not be locked for writing + la base de données de la bibliothèque n'a pas pu être verrouillée en écriture + + + + a folder entry could not be restored + une entrée de dossier n'a pas pu être restaurée + + + + a comic entry could not be updated + une entrée de bande dessinée n'a pas pu être mise à jour + + + + the library database could not be saved: %1 + la base de données de la bibliothèque n'a pas pu être enregistrée : %1 + + + + the record of the last organize run could not be read + l'enregistrement de la dernière organisation n'a pas pu être lu + + + + the folder %1 could not be created + le dossier %1 n'a pas pu être créé + + + + %n file(s) could not be moved back + + %n fichier n'a pas pu être remis en place + %n fichiers n'ont pas pu être remis en place + + + + + OrganizeFilesDialog + + Format: + Format : + + + + Organize files + Organiser les fichiers + + + + + Rename files + Renommer les fichiers + + + + Preparing the preview... + Préparation de l'aperçu... + + + + &Filename format: + &Format du nom de fichier : + + + + &Path format: + Format du &chemin : + + + + Filename format + Format du nom de fichier + + + + Path format + Format du chemin + + + + Presets + Préréglages + + + + Insert + Insérer + + + + Optional part < > + Partie facultative < > + + + + Disappears completely when the fields inside it are empty. + Disparaît complètement quand les champs qu'elle contient sont vides. + + + + Padded number {number:000} + Numéro complété par des zéros {number:000} + + + + Format help... + Aide sur le format... + + + + selected folder + dossier sélectionné + + + + library root + racine de la bibliothèque + + + + Move into + Déplacer vers + + + + Reset changes + Réinitialiser les modifications + + + + Remove selected + Retirer la sélection + + + + Show unchanged + Afficher les inchangés + + + + New name + Nouveau nom + + + + Renamed from + Ancien nom + + + + New location + Nouvel emplacement + + + + Moved from + Ancien emplacement + + + + Remove from list + Retirer de la liste + + + + Move files + Déplacer les fichiers + + + + Cancel + Annuler + + + Copy the list + Copier la liste - - Add a new label to this library - Ajouter une nouvelle étiquette à cette bibliothèque + + Undo + Revenir en arrière - - Rename selected list - Renommer la liste sélectionnée + Close + Fermer - - Rename any selected labels or lists - Renommer toutes les étiquettes ou listes sélectionnées + + Copy failure details + Copier les détails des échecs - - Add to... - Ajouter à... + + Finish + Terminer - - Favorites - Favoris + + Remove preset + Supprimer le préréglage - - Add selected comics to favorites list - Ajouter la bande dessinée sélectionnée à la liste des favoris + + Save current format as preset... + Enregistrer le format actuel comme préréglage... - - - LocalComicListModel - - file name - nom de fichier + + Reset to default format + Réinitialiser au format par défaut - - - NoLibrariesWidget - - create your first library - Créez votre première librairie + + Save preset + Enregistrer le préréglage - - You don't have any libraries yet - Vous n'avez pas encore de librairie + + Preset name: + Nom du préréglage: - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <p>Vous pouvez creer une librairie dans n'importe quel dossierr, YACReaderLibrary importera les dossiers et les bandes dessinées contenus dans ce dossier. Si vous avez déjà crer des librairies, vous pouvez les ouvrir.</p><p>N'oubliez pas que vous pouvez utiliser YACReader en tant que stand alone pour lire vos bandes dessinées sur votre ordinateur.</p> + + A filename format cannot contain "/". Use Organize files to move comics into folders. + Un format de nom de fichier ne peut pas contenir "/". Utilisez Organiser les fichiers pour déplacer des bandes dessinées dans des dossiers. - - add an existing one - Ajouter une librairie existante + + This format cannot be used: %1 + Ce format ne peut pas être utilisé : %1 - - - NoSearchResultsWidget - - No results - Aucun résultat + + new folder + nouveau dossier - - - OptionsDialog - - Appearance - Apparence + + This folder does not exist yet. It will be created. + Ce dossier n'existe pas encore. Il sera créé. - - Options - Possibilités + + file not found + fichier introuvable - - Language - Langue + + This comic is in the library but not on disk. It is skipped. + Cette bande dessinée est dans la bibliothèque mais pas sur le disque. Elle est ignorée. - - Application language - Langue de l'application + + name in use + nom déjà utilisé - - System default - Par défaut du système + + no metadata + pas de métadonnées - - Tray icon settings (experimental) - Paramètres de l'icône de la barre d'état (expérimental) + + already here + déjà ici - - Close to tray - Près du plateau + + This file is already in the right place. + Ce fichier est déjà au bon endroit. - - Start into the system tray - Commencez dans la barre d'état système + + edited + modifié + + + + %n will be renamed + + %n sera renommé + %n seront renommés + + + + + %n will move + + %n sera déplacé + %n seront déplacés + + + + + %n unchanged + + %n inchangé + %n inchangés + + + + + %n renamed + + %n renommé + %n renommés + + + + + %n removed + + %n retiré + %n retirés + + + + + %n missing + + %n introuvable + %n introuvables + + + + + %n new folder(s) + + %n nouveau dossier + %n nouveaux dossiers + + + + + %n manual change(s) kept + + %n modification manuelle conservée + %n modifications manuelles conservées + - - Edit Comic Vine API key - Modifier la clé API Comic Vine + + Nothing would be renamed with this format. + Avec ce format, rien ne serait renommé. - - Comic Vine API key - Clé API Comic Vine + + Nothing would move with this format. + Avec ce format, rien ne serait déplacé. + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + %n fichier sera renommé. Les dossiers ne changent pas. Vous pourrez revenir en arrière ensuite. + %n fichiers seront renommés. Les dossiers ne changent pas. Vous pourrez revenir en arrière ensuite. + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + %n fichier sera déplacé vers %1. Cela modifie vos fichiers sur le disque. Vous pourrez revenir en arrière ensuite. + %n fichiers seront déplacés vers %1. Cela modifie vos fichiers sur le disque. Vous pourrez revenir en arrière ensuite. + - - ComicInfo.xml legacy support - Prise en charge héritée de ComicInfo.xml + + Moving %1 of %2 +%3 + Déplacement de %1 sur %2 +%3 - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics - Importer des métadonnées depuis ComicInfo.xml lors de l'ajout de nouvelles bandes dessinées + + Updating the library... + Mise à jour de la bibliothèque... - - Consider 'recent' items added or updated since X days ago - Considérez les éléments « récents » ajoutés ou mis à jour depuis X jours + + Restored name + Nom restauré - - Third party reader - Lecteur tiers + + + Moved back from + Redéplacé depuis - - Write {comic_file_path} where the path should go in the command - Écrivez {comic_file_path} où le chemin doit aller dans la commande + + + + + Status + État - - Clear - Clair + + Final name + Nom final - - Update libraries at startup - Mettre à jour les bibliothèques au démarrage + + Previous name + Nom précédent - - Try to detect changes automatically - Essayez de détecter automatiquement les changements + + Restored location + Emplacement restauré - - Update libraries periodically - Mettre à jour les bibliothèques périodiquement + + Final location + Emplacement final - - Interval: - Intervalle: + + Previous location + Emplacement précédent - - 30 minutes - 30 min + + Restored + Restauré - - 1 hour - 1 heure + + Renamed + Renommé - - 2 hours - 2 heures + + Moved + Déplacé - - 4 hours - 4 heures + + Undo failed: %1 + Échec de l’annulation : %1 - - 8 hours - 8 heures + + Failed: %1 + Échec : %1 - - 12 hours - 12 heures + + Nothing was moved. + Rien n'a été déplacé. - - daily - tous les jours + + The record this run could be undone from could not be written, so the run did not start: %1 + L'enregistrement permettant d'annuler cette opération n'a pas pu être écrit, l'opération n'a donc pas démarré : %1 + + + + %n file(s) renamed. + + %n fichier renommé. + %n fichiers renommés. + + + + + %n file(s) moved into %1. + + %n fichier déplacé vers %1. + %n fichiers déplacés vers %1. + - - Update libraries at certain time - Mettre à jour les bibliothèques à un certain moment + + The record of this run stopped early, so the run stopped with it: %1 + L'enregistrement de cette opération s'est arrêté prématurément, l'opération s'est donc arrêtée avec lui : %1 + + + + %n file(s) were not moved. + + %n fichier n'a pas été déplacé. + %n fichiers n'ont pas été déplacés. + - - Time: - Temps: + + The library database could not be updated: %1 + La base de données de la bibliothèque n'a pas pu être mise à jour : %1 - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. - AVERTISSEMENT! Lors des mises à jour de la bibliothèque, les écritures dans la base de données sont désactivées ! -Ne planifiez pas de mises à jour pendant que vous utilisez activement l'application. -Lors des mises à jour automatiques, l'application bloquera certaines actions jusqu'à ce que la mise à jour soit terminée. -Pour arrêter une mise à jour automatique, appuyez sur l'indicateur de chargement à côté du titre Bibliothèques. + + Use Undo to move the files back, or update the library to make it match the files. + Utilisez Revenir en arrière pour remettre les fichiers en place, ou mettez la bibliothèque à jour pour qu'elle corresponde aux fichiers. + + + + %n empty folder(s) were removed. + + %n dossier vide a été supprimé. + %n dossiers vides ont été supprimés. + + + + + %n file(s) could not be moved. + + %n fichier n'a pas pu être déplacé. + %n fichiers n'ont pas pu être déplacés. + - - Modifications detection - Détection des modifications + + Moving the files back... + Remise en place des fichiers... - - Compare the modified date of files when updating a library (not recommended) - Comparer la date de modification des fichiers lors de la mise à jour d'une bibliothèque (déconseillé) + + Moving back %1 of %2 +%3 + Remise en place de %1 sur %2 +%3 - - Enable background image - Activer l'image d'arrière-plan + + Everything was moved back. + Tout a été remis en place. - - Opacity level - Niveau d'opacité + + The undo did not finish: %1 + Le retour en arrière ne s'est pas terminé : %1 - - Blur level - Niveau de flou + + Format help + Aide sur le format - - Use selected comic cover as background - Utiliser la couverture de bande dessinée sélectionnée comme arrière-plan + + Fields + Champs - - Restore defautls - Restaurer les valeurs par défaut + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + Chaque champ s'écrit entre accolades et est remplacé par les métadonnées de la bande dessinée. Le menu Insérer les liste tous. - - Background - Arrière-plan + + {series} gives %1 + {series} donne %1 - - Display continue reading banner - Afficher la bannière de lecture continue + + Optional parts + Parties facultatives - - Display current comic banner - Afficher la bannière de bande dessinée actuelle + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + Une partie écrite entre les signes < et > disparaît complètement quand tous les champs qu'elle contient sont vides. Utilisez-la pour la ponctuation qui appartient à un champ, comme des parenthèses ou un dièse en tête. Le texte au début ou à la fin d'un nom est rogné sans elle. - - Continue reading - Continuer la lecture + + {series} ({year}) with no year gives %1 + {series} ({year}) sans année donne %1 - - Comic Flow - Comic Flow + + {series}< ({year})> with no year gives %1 + {series}< ({year})> sans année donne %1 - - - Libraries - Bibliothèques + + Numbers + Numéros - - Grid view - Vue grille + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + Écrivez deux-points et quelques zéros pour compléter le numéro. Les numéros restent ainsi dans l'ordre dans un gestionnaire de fichiers. - - General - Général + + + Folders + Dossiers - - Restart is needed - Redémarrage nécessaire + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + Un format de nom de fichier ne peut pas contenir de barre oblique. Chaque bande dessinée reste dans son dossier actuel. Utilisez Organiser en dossiers pour déplacer des bandes dessinées. + + + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + Chaque partie séparée par une barre oblique devient un dossier. La dernière partie devient le nom du fichier. L'extension d'origine est toujours conservée. @@ -2388,12 +3325,12 @@ Pour arrêter une mise à jour automatique, appuyez sur l'indicateur de cha Remarques : - + Invalid cover Couverture invalide - + The image is invalid. L'image n'est pas valide. @@ -2536,6 +3473,35 @@ Pour arrêter une mise à jour automatique, appuyez sur l'indicateur de cha Listes de lecture + + ReadingListManagementCoordinator + + + Add new reading lists + Ajouter de nouvelles listes de lecture + + + + + List name: + Nom de la liste : + + + + Delete list/label + Supprimer la liste/l'étiquette + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + L'élément sélectionné sera supprimé, vos bandes dessinées ou dossiers ne seront pas supprimés de votre disque. Êtes-vous sûr? + + + + Rename list name + Renommer le nom de la liste + + RenameLibraryDialog @@ -3249,6 +4215,61 @@ Use quotes to include spaces in a value. description du volume indisponible + + SelectedComicsInfoView + + + Unknown + Inconnu + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + %1 bande(s) dessinnée(s) sélectionnée(s) + + + + Read + Lu + + + + In progress + En cours + + + + Unread + Non lus + + + + Total pages + + + + + Total size + + + + + Series + Série + + SeriesQuestion @@ -3270,53 +4291,53 @@ Use quotes to include spaces in a value. ServerConfigDialog - - + + Server connectivity Connectivité du serveur - + Scan to connect Scanner pour se connecter - + Devices on this network can reach your library at the address below. Les appareils de ce réseau peuvent accéder à votre bibliothèque à l’adresse ci-dessous. - + IP address Adresse IP - + Port Port r?seau - + Web interface Interface web - + Copy link Copier le lien - + Open web UI Ouvrir l’interface web - + Enable the server Activer le serveur - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. YACReader est disponible pour iOS et Android. Découvrez-le pour <a href='https://ios.yacreader.com'>iOS</a> ou <a href='https://android.yacreader.com'>Android</a>. @@ -3325,7 +4346,7 @@ Use quotes to include spaces in a value. Autoriser le serveur - + Set port set port Définir le port diff --git a/YACReaderLibrary/yacreaderlibrary_it.ts b/YACReaderLibrary/yacreaderlibrary_it.ts index 0f484bc54..83c45dafe 100644 --- a/YACReaderLibrary/yacreaderlibrary_it.ts +++ b/YACReaderLibrary/yacreaderlibrary_it.ts @@ -202,11 +202,22 @@ ClassicComicsView - + Hide comic flow Nascondi Comic Flow + + ComicFilesCoordinator + + Copying comics... + Sto copiando i fumetti... + + + Moving comics... + Sto muovendo i fumetti... + + ComicInfoView @@ -290,70 +301,99 @@ b/n + + ComicManagementCoordinator + + + + YACReader not found + YACReader non trovato + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + YACReader non trovato. YACReader deve essere installato nella stessa cartella di YACReaderLibrary. + + + + YACReader not found. There might be a problem with your YACReader installation. + YACReader non trovato. Potrebbe esserci un problema con l'installazione di YACReader. + + + + Error + Errore + + + + Error opening comic with third party reader. + Errore nell'apertura del fumetto con un lettore di terze parti. + + ComicModel - + no No - + yes Si - + Read Leggi - + Series Serie - + Volume Tomo - + Story Arc Arco narrativo - + Size Dimensione - + Pages Pagine - + Title Titolo - + Current Page Pagina corrente - + File Name Nome file - + Publication Date Data di pubblicazione - + Rating Valutazione @@ -381,13 +421,13 @@ Chiudi - - + + Retrieving tags for : %1 Ricezione tag per: %1 - + Looking for comic... Sto cercando il fumetto... @@ -397,34 +437,42 @@ Cerca - - - + + + Looking for volume... Sto cercando il fumetto... - - + + comic %1 of %2 - %3 Fumetto %1 di %2 - %3 - + %1 comics selected Fumetto %1 selezionato - + Error connecting to ComicVine Errore durante la connessione a ComicVine - + Retrieving volume info... Sto ricevendo le informazioni per l'abum... + + ContinueReadingGridHeader + + + Continue Reading... + Continua a leggere... + + CreateLibraryDialog @@ -468,6 +516,14 @@ Percorso non trovato + + DBHelper + + + The folder entry could not be found in the library database. + La voce della cartella non è stata trovata nel database della libreria. + + EditShortcutsDialog @@ -504,6 +560,19 @@ Questa cartella non contiene ancora fumetti + + EmptyInfoView + + + Nothing selected + Nessuna selezione + + + + Select a comic or folder to see its information. + Seleziona un fumetto o una cartella per visualizzarne le informazioni. + + EmptyLabelWidget @@ -617,27 +686,23 @@ FileComic - + + Format not supported Formato non supportato - + 7z not found 7z non trovato - + Unknown error opening the file Errore sconosciuto all'apertura del file - - Unsupported EPUB: %1 - - - - + CRC error on page (%1): some of the pages will not be displayed correctly Errore CRC alla pagina (%1): alcune pagine potrebbero non essere visualizzate correttamente @@ -645,18 +710,134 @@ FolderContentView - Continue Reading... - Continua a leggere... + Continua a leggere... + + + + FolderInfoView + + + Unknown + Sconosciuto + + + + Items + Elementi + + + + Type + Tipo + + + + Reading status + Stato di lettura + + + + Read + Leggi + + + + Unread + Non letti + + + + Collection status + Stato della raccolta + + + + Completed + Completato + + + + In progress + In corso + + + + Added + Aggiunto + + + + Updated + Aggiornato + + + + FolderManagementCoordinator + + + Add new folder + Aggiungi una nuova cartella + + + + Folder name: + Nome della cartella: GridComicsView - + Show info Mostra informazioni + + Library + Libreria + + + Folder + Cartella + + + Favorites + Favoriti + + + Recently added + Aggiunti di recente + + + + Manga + Manga + + + + Western manga + Manga occidentale + + + + Web comic + Fumetto web + + + + Yonkoma + Yonkoma + + + + Comic + Fumetto + + + + Unknown + Sconosciuto + HelpAboutDialog @@ -805,163 +986,136 @@ <p>La libreria corrente viene controllata per individuare copertine mancanti e informazioni incomplete sui fumetti.</p><p>L'operazione può richiedere diversi minuti. Puoi interromperla ed eseguirla di nuovo in seguito.</p> + + LibraryInfoView + + + Library info + Informazioni sulla biblioteca + + + + Number of folders + Numero di cartelle + + + + Number of comics + Numero di fumetti + + + + Number of read comics + Numero di fumetti letti + + + + LibraryManagementCoordinator + + + Error opening the library + Errore nell'apertura della libreria + + + + Error creating the library + Errore creando la libreria + + + + Error updating the library + Errore aggiornando la libreria + + LibraryWindow - + The selected folder doesn't contain any library. La cartella selezionata non contiene nessuna Libreria. - + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? Questa libreria è stata creata con una versione precedente di YACREaderLibrary. Deve essere aggiornata. Aggiorno ora? - - Comic - Fumetto - - - + Folder name: Nome della cartella: - + The selected folder and all its contents will be deleted from your disk. Are you sure? La cartella seleziona e tutto il suo contenuto verranno cancellati dal tuo disco. Sei sicuro? - - Error opening the library - Errore nell'apertura della libreria - - - - - YACReader not found - YACReader non trovato - - - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. C'è stato un problema cancellando le cartelle selezionate. Per favore controlla i tuoi permessi di scrittura e sii sicuro che non ci siano altre applicazioni che usano le stesse cartelle. - - - Rename list name - Rinomina la lista - Remove and delete metadata Rimuovi e cancella i Metadati - + Old library Vecchia libreria - - Set as completed - Segna come completo - - - + There was an error accessing the folder's path C'è stato un errore nell'accesso al percorso della cartella - - Library - Libreria - - - + Comics will only be deleted from the current label/list. Are you sure? I fumetti verranno cancellati dall'etichetta/lista corrente. Sei sicuro? - + This library was created with a newer version of YACReaderLibrary. Download the new version now? Questa libreria è stata creata con una verisone più recente di YACReaderLibrary. Scarico la versione aggiornata ora? - - + Moving comics... Sto muovendo i fumetti... - - + Copying comics... Sto copiando i fumetti... - + Library '%1' is no longer available. Do you want to remove it? La libreria '%1' non è più disponibile, la vuoi cancellare? - - Open folder... - Apri Cartella... - - - + Do you want remove Vuoi rimuovere - - Set as uncompleted - Segna come non completo - - - + Error in path Errore nel percorso - - Error updating the library - Errore aggiornando la libreria - - - - Folder - Cartella - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - Gli elementi selezionati verranno cancellati, i tuoi fumetti o cartella NON verranno cancellati dal tuo disco. Sei sicuro? - - - - - List name: - Nome lista: - - - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? La libreria '%1' è stata creata con una versione precedente di YACREaderLibrary. Deve essere ricreata. Lo vuoi fare ora? - + Save covers Salva Copertine - - Add new reading lists - Aggiungi una lista di lettura - - - + You are adding too many libraries. You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. @@ -974,32 +1128,29 @@ Hai probabilemnte bisogno di una sola Libreria al livello superiore, puoi poi na YACReader non ti fermerà dal creare altre librerie ma è meglio se terrai il numero di librerie basso. - - Set as read - Setta come letto - - - + Library info Informazioni sulla biblioteca - + Assign comics numbers Assegna un numero ai fumetti - + + + Please, select a folder first Per cortesia prima seleziona una cartella - + Library not available Libreria non disponibile - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. C'è un problema nel cancellare i fumetti selezionati. Per favore controlla i tuoi permessi di scrittura sui file o sulla cartella. @@ -1009,293 +1160,262 @@ YACReader non ti fermerà dal creare altre librerie ma è meglio se terrai il nu Libreria YACReader - - Error creating the library - Errore creando la libreria - - - + You are adding too many libraries. Stai aggiungendto troppe librerie. - - Update folder - Aggiorna Cartella - - - + Update needed Devi aggiornarmi - + Library name already exists Esiste già una libreria con lo stesso nome - + There is another library with the name '%1'. Esiste già una libreria con il nome '%1'. - + Delete folder Cancella Cartella - + Assign numbers starting in: Assegna numeri partendo da: - + Download new version Scarica la nuova versione - + Remove and delete metadata and backups Rimuovi ed elimina metadati e backup - + Invalid image Immagine non valida - + The selected file is not a valid image. Il file selezionato non è un'immagine valida. - + Error saving cover Errore durante il salvataggio della copertina - + There was an error saving the cover image. Si è verificato un errore durante il salvataggio dell'immagine di copertina. - + Delete comics Cancella i fumetti - - Add new folder - Aggiungi una nuova cartella - - - - Delete list/label - Cancella Lista/Etichetta - - - + + + No folder selected Nessuna cartella selezionata - + All the selected comics will be deleted from your disk. Are you sure? Tutti i fumetti selezionati saranno cancellati dal tuo disco. Sei sicuro? - + Remove comics Rimuovi i fumetti - - - Set as unread - Setta come non letto - - - + Library not found Libreria non trovata - - - - manga - Manga - - - - - - comic - comico - - - - - - web comic - fumetto web - - - - - - western manga (left to right) - manga occidentale (da sinistra a destra) - - - - + + Unable to delete Non posso cancellare - - - - 4koma (top to botom) - 4koma (dall'alto verso il basso) + + Rename or organize files + Rinomina o organizza i file - + + Set the type of the selected comics + Imposta il tipo dei fumetti selezionati + + + Search filters Filtri di ricerca - + Unread Non letti - + In progress In corso - + Highly rated Con valutazione alta - + Recently added Aggiunti di recente - + Search syntax… Sintassi di ricerca… - - - - - Set type - Imposta il tipo - - - + A repair of this library is already running (%1). Wait for it to finish. È già in corso una riparazione di questa libreria (%1). Attendere il completamento. - + The library is locked by a repair that did not finish. La libreria è bloccata da una riparazione non completata. - + The library is locked by a repair started by %1. La libreria è bloccata da una riparazione avviata da %1. - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? Se sei sicuro che non sia in corso nessun'altra riparazione, il blocco può essere rimosso. Rimuovere il blocco e continuare? - + Package operation failed - + Operazione di pacchetto non riuscita - + The covers package operation could not be completed. - + Non è stato possibile completare l'operazione con il pacchetto di copertine. - + Restore recovery failed Recupero del ripristino non riuscito - - Set custom cover - Imposta la copertina personalizzata + + Rename folder + Rinomina cartella - - Delete custom cover - Elimina la copertina personalizzata + + Invalid folder name + Nome della cartella non valido - - Error - Errore + + The folder name is empty or contains characters that are not supported. + Il nome della cartella è vuoto o contiene caratteri non supportati. - - Error opening comic with third party reader. - Errore nell'apertura del fumetto con un lettore di terze parti. + + + + Unable to rename folder + Impossibile rinominare la cartella - - + + A file or folder named '%1' already exists. + Esiste già un file o una cartella con il nome '%1'. + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. + +Folder: %1 + Non è stato possibile rinominare la cartella sul disco. Controlla il nome della cartella e i permessi di scrittura. + +Cartella: %1 + + + + The library database could not be updated. The folder rename on disk was reverted. + Non è stato possibile aggiornare il database della libreria. La rinomina della cartella sul disco è stata annullata. + + + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + Non è stato possibile aggiornare il database della libreria né annullare la rinomina della cartella sul disco. Ora la libreria deve essere aggiornata manualmente. + + + + YACReader library database (*.ydb) Database della libreria YACReader (*.ydb) - + The library database backup was created at: %1 Il backup del database della libreria è stato creato in: %1 - + Unable to create the library database backup: %1 Impossibile creare il backup del database della libreria: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? Chiudi YACReaderLibraryServer e qualsiasi altra applicazione YACReader che usa questa libreria prima del ripristino. Continuare? - + Restoring library database... Ripristino del database della libreria... - + The current library database is invalid. Restore the selected backup anyway? Il database attuale della libreria non è valido. Ripristinare comunque il backup selezionato? - - + + The library maintenance lock may be stale. Remove it and retry? Il blocco di manutenzione della libreria potrebbe essere obsoleto. Rimuoverlo e riprovare? - + Restart YACReaderLibrary before attempting recovery again. @@ -1304,71 +1424,71 @@ Restart YACReaderLibrary before attempting recovery again. Riavvia YACReaderLibrary prima di tentare nuovamente il recupero. - + The library database was restored successfully. Update the library now? Il database della libreria è stato ripristinato correttamente. Aggiornare la libreria ora? - + Library database damaged Database della libreria danneggiato - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. Il database della libreria '%1' è danneggiato, quindi gli aggiornamenti, la manutenzione e i backup normali non sono disponibili. YACReader può tentare di riparare il database. Alcuni dati danneggiati potrebbero non essere recuperabili. I backup esistenti non verranno modificati. - + Attempt repair Tenta la riparazione - + Restore a backup... Ripristina un backup... - + Repairing library database... Riparazione del database della libreria... - - - + + + Library database repair Riparazione del database della libreria - + Another maintenance operation is currently using this library. Try again after it finishes. Un'altra operazione di manutenzione sta usando questa libreria. Riprova al termine. - + The library database is already valid. Il database della libreria è già valido. - + Library database repaired Database della libreria riparato - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 Il database della libreria è stato riparato ricostruendone gli indici. L'originale danneggiato è stato conservato in: %1 - + Library database rebuilt Database della libreria ricostruito - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1379,7 +1499,7 @@ Update the library now? Aggiornare la libreria ora? - + The damaged original was preserved at: @@ -1390,12 +1510,12 @@ L'originale danneggiato è stato conservato in: %1 - + Library database repair failed Riparazione del database della libreria non riuscita - + The library database could not be repaired: %1%2 @@ -1406,42 +1526,27 @@ You can restore a backup from the Library menu or recreate the library. Puoi ripristinare un backup dal menu Libreria o ricreare la libreria. - + library? Libreria? - + Are you sure? Sei sicuro? - - Rescan library for XML info - Eseguire nuovamente la scansione della libreria per informazioni XML - - - + Upgrade failed Aggiornamento non riuscito - + There were errors during library upgrade in: Si sono verificati errori durante l'aggiornamento della libreria in: - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - YACReader non trovato. YACReader deve essere installato nella stessa cartella di YACReaderLibrary. - - - - YACReader not found. There might be a problem with your YACReader installation. - YACReader non trovato. Potrebbe esserci un problema con l'installazione di YACReader. - - - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1453,763 +1558,1596 @@ File mancanti: %3 LibraryWindowActions - + Create a new library Crea una nuova libreria - + Open an existing library Apri una libreria esistente - - + + Export comics info Esporta informazioni fumetto - - + + Import comics info Importa informazioni fumetto - + Pack covers Compatta Copertine - + Pack the covers of the selected library Compatta le copertine della libreria selezionata - + Unpack covers Scompatta le Copertine - + Unpack a catalog Scompatta un catalogo - + Update library Aggiorna Libreria - + Update current library Aggiorna la Libreria corrente - + Back up library database Esegui il backup del database della libreria - + Create a backup of the current library database Crea un backup del database attuale della libreria - + Restore library database backup Ripristina il backup del database della libreria - + Restore the current library database from a backup Ripristina il database attuale della libreria da un backup - + Repair covers and comic info Ripara copertine e informazioni dei fumetti - + Retry comics with missing covers or incomplete information Riprova i fumetti con copertine mancanti o informazioni incomplete - + Rename library Rinomina la libreria - + Rename current library Rinomina la libreria corrente - + Remove library Rimuovi la libreria - + Remove current library from your collection Rimuovi la libreria corrente dalla tua collezione - + Rescan library for XML info Eseguire nuovamente la scansione della libreria per informazioni XML - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. Cerca di trovare informazioni XML incorporate nei file dei fumetti. Devi farlo solo se la libreria è stata creata con la versione 9.8.2 o precedente o se utilizzi software di terze parti per incorporare informazioni XML nei file. - + Open library folder... Apri la cartella della libreria... - + Open the root folder of the current library Apri la cartella principale della libreria corrente - + Show library info Mostra informazioni sulla biblioteca - + Show information about the current library Mostra informazioni sulla libreria corrente - + Open current comic Apri il fumetto corrente - + Open current comic on YACReader Apri il fumetto corrente con YACReader - + Save selected covers to... Salva le copertine selezionate in... - + Save covers of the selected comics as JPG files Salva le copertine dei fumetti selezionati come file JPG - - + + Set as read Setta come letto - + Set comic as read Setta il fumetto come letto - - + + Set as unread Setta come non letto - + Set comic as unread Setta il fumetto come non letto - - + + manga Manga - + Set issue as manga Imposta il problema come manga - - + + comic comico - + Set issue as normal Imposta il problema come normale - + western manga manga occidentali - + Set issue as western manga Imposta il problema come manga occidentale - - + + web comic fumetto web - + Set issue as web comic Imposta il problema come fumetto web - - + + yonkoma Yonkoma - + Set issue as yonkoma Imposta il problema come Yonkoma - + Show/Hide marks Mostra/Nascondi - + Show or hide read marks Mostra o nascondi lo stato di lettura - + Show/Hide recent indicator Mostra/Nascondi l'indicatore recente - + Show or hide recent indicator Mostra o nascondi l'indicatore recente - - + + Fullscreen mode on/off Modalità a schermo interno on/off - + Help, About YACReader Aiuto, Crediti YACReader - + Add new folder Aggiungi una nuova cartella - + Add new folder to the current library Aggiungi una nuova cartella alla libreria corrente - + + Rename folder + Rinomina cartella + + + + Rename the current folder on disk and in the library + Rinomina la cartella corrente sul disco e nella libreria + + + Delete folder Cancella Cartella - + Delete current folder from disk Cancella la cartella corrente dal disco - + Select root node Seleziona il nodo principale - + Expand all nodes Espandi tutti i nodi - + Collapse all nodes Compatta tutti i nodi - + Show options dialog Mostra le opzioni - + Show comics server options dialog Mostra le opzioni per il server dei fumetti - - + + Change between comics views Cambia tra i modi di visualizzazione dei fumetti - + Open folder... Apri Cartella... - + + + Rename files... + Organize files + Rinomina i file... + + + + + Organize into folders... + Organizza in cartelle... + + + Set as uncompleted Segna come non completo - + Set as completed Segna come completo - + Set custom cover Imposta la copertina personalizzata - + Delete custom cover Elimina la copertina personalizzata - + western manga (left to right) manga occidentale (da sinistra a destra) - + Open containing folder... Apri la cartella dei contenuti... - Reset comic rating - Resetta la valutazione dei fumetti + Resetta la valutazione dei fumetti - + Select all comics Seleziona tutti i fumetti - + Edit Edita - + Assign current order to comics Assegna l'ordinamento corrente ai fumetti - + Update cover Aggiorna copertina - + Delete selected comics Cancella i fumetti selezionati - + Delete metadata from selected comics Elimina i metadati dai fumetti selezionati - + Download tags from Comic Vine Scarica i Tag da Comic Vine - + Focus search line Mettere a fuoco la linea di ricerca - + Focus comics view Focus sulla visualizzazione dei fumetti - + Edit shortcuts Edita scorciatoie - + &Quit &Esci - + Update folder Aggiorna Cartella - + Update current folder Aggiorna la cartella corrente - + Scan legacy XML metadata Scansione dei metadati XML legacy - + Add new reading list Aggiorna la lista di lettura - + Add a new reading list to the current library Aggiungi una lista di lettura alla libreria corrente - + Remove reading list Rimuovi la lista di lettura - + Remove current reading list from the library Rimuovi la lista di lettura dalla libreria - - Add new label - Aggiungi una nuova etichetta + + Add new label + Aggiungi una nuova etichetta + + + + Add a new label to this library + Aggiungi una nuova etichetta a questa libreria + + + + Rename selected list + Rinomina la lista selezionata + + + + Rename any selected labels or lists + Rinomina qualsiasi etichetta o lista selezionata + + + + Add to... + Aggiungi a... + + + + Favorites + Favoriti + + + + Add selected comics to favorites list + Aggiungi i fumetti selezionati alla lista dei favoriti + + + + + Reset rating + Reimposta valutazione + + + + LibraryWindowMenus + + + comic + comico + + + + manga + Manga + + + + western manga (left to right) + manga occidentale (da sinistra a destra) + + + + web comic + fumetto web + + + + 4koma (top to botom) + 4koma (dall'alto verso il basso) + + + + + + + Set type + Imposta il tipo + + + + Library + Libreria + + + + Folder + Cartella + + + + Comic + Fumetto + + + + Open folder... + Apri Cartella... + + + + Update folder + Aggiorna Cartella + + + + Rename folder + Rinomina cartella + + + + Rename files... + Rinomina i file... + + + + Organize into folders... + Organizza in cartelle... + + + + Rescan library for XML info + Eseguire nuovamente la scansione della libreria per informazioni XML + + + + Set as uncompleted + Segna come non completo + + + + Set as completed + Segna come completo + + + + Set as read + Setta come letto + + + + + Set as unread + Setta come non letto + + + + Set custom cover + Imposta la copertina personalizzata + + + + Delete custom cover + Elimina la copertina personalizzata + + + + ListInfoView + + + 1 comic + 1 fumetto + + + + %1 comics + %1 fumetti + + + + Last day + Ultimo giorno + + + + Last %1 days + Ultimi %1 giorni + + + + 1 sublist + 1 sottolista + + + + %1 sublists + %1 sottoliste + + + + LocalComicListModel + + + file name + Nome file + + + + NoLibrariesWidget + + + create your first library + Crea la tua prima libreria + + + + You don't have any libraries yet + Per ora non hai ancora nessuna libreria + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <p>Puoi creare una libreria in qualsiasi cartella, YACReader importerà tutti i fumetti e struttura da questa certella. Se hai creato una qualsiasia libreria nel passato la puoi aprire. </p><p>Non dimenticare che puoi usare YACReader come applicazione stand alone per leggere i fumetti sul tuo PC.</p> + + + + add an existing one + Aggiungine una esistente + + + + NoSearchResultsWidget + + + No results + Nessun risultato + + + + OptionsDialog + + + Restore defautls + Resetta al Default + + + + Background + Sfondo + + + + Blur level + Livello di sfumatura + + + + Enable background image + Abilita l'immagine di sfondo + + + + Options + Opzioni + + + + Comic Vine API key + API di ComicVine + + + + Edit Comic Vine API key + Edita l'API di ComicVine + + + + Opacity level + Livello di opacità + + + + General + Generale + + + + Use selected comic cover as background + Usa la cover del fumetto selezionato come sfondo + + + + Comic Flow + Comic Flow + + + + + Libraries + Librerie + + + + Grid view + Vista a Griglia + + + + Appearance + Aspetto + + + + Language + Lingua + + + + Application language + Lingua dell'applicazione + + + + System default + Predefinita del sistema + + + + Tray icon settings (experimental) + Impostazioni dell'icona nella barra delle applicazioni (sperimentale) + + + + Close to tray + Vicino al vassoio + + + + Start into the system tray + Inizia nella barra delle applicazioni + + + + ComicInfo.xml legacy support + Supporto legacy ComicInfo.xml + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + Importa metadati da ComicInfo.xml quando aggiungi nuovi fumetti + + + + Consider 'recent' items added or updated since X days ago + Considera gli elementi "recenti" aggiunti o aggiornati da X giorni fa + + + + Third party reader + Lettore di terze parti + + + + Write {comic_file_path} where the path should go in the command + Scrivi {comic_file_path} dove dovrebbe andare il percorso nel comando + + + + Clear + Cancella + + + + Update libraries at startup + Aggiorna le librerie all'avvio + + + + Try to detect changes automatically + Prova a rilevare automaticamente le modifiche + + + + Update libraries periodically + Aggiorna periodicamente le librerie + + + + Interval: + Intervallo: + + + + 30 minutes + 30 minuti + + + + 1 hour + 1 ora + + + + 2 hours + 2 ore + + + + 4 hours + 4 ore + + + + 8 hours + 8 ore + + + + 12 hours + 12 ore + + + + daily + quotidiano + + + + Update libraries at certain time + Aggiorna le librerie in determinati orari + + + + Time: + Tempo: + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + AVVERTIMENTO! Durante gli aggiornamenti della libreria le scritture sul database sono disabilitate! +Non pianificare gli aggiornamenti mentre potresti utilizzare l'app attivamente. +Durante gli aggiornamenti automatici l'app bloccherà alcune azioni fino al termine dell'aggiornamento. +Per interrompere un aggiornamento automatico, tocca l'indicatore di caricamento accanto al titolo Librerie. + + + + Modifications detection + Rilevamento delle modifiche + + + + Compare the modified date of files when updating a library (not recommended) + Confronta la data di modifica dei file durante l'aggiornamento di una libreria (non consigliato) + + + + Display continue reading banner + Visualizza il banner continua a leggere + + + + Display current comic banner + Visualizza il banner del fumetto corrente + + + + Continue reading + Continua a leggere + + + + Mix folders and comics + Mescola cartelle e fumetti + + + + Start comics on a new row + Inizia i fumetti su una nuova riga + + + + Content + Contenuto + + + + Restart is needed + Riavvio Necessario + + + + OrganizeFiles + + + Renamed, %1 is already in use + Rinominato, %1 è già in uso + + + + Missing metadata: %1 + Metadati mancanti: %1 + + + + %1 could not be created + Non è stato possibile creare %1 + + + + OrganizeFilesCoordinator + + + + Organize files + Organizza i file + + + + This folder does not contain any comics. + Questa cartella non contiene fumetti. + + + + This library is busy: %1 + Questa libreria è occupata: %1 + + + + the library database could not be opened + non è stato possibile aprire il database della libreria + + + + the library database could not be locked for writing + non è stato possibile bloccare il database della libreria per la scrittura + + + + a folder entry could not be restored + non è stato possibile ripristinare una voce di cartella + + + + a comic entry could not be updated + non è stato possibile aggiornare una voce di fumetto + + + + the library database could not be saved: %1 + non è stato possibile salvare il database della libreria: %1 + + + + the record of the last organize run could not be read + non è stato possibile leggere il registro dell'ultima organizzazione + + + + the folder %1 could not be created + non è stato possibile creare la cartella %1 + + + + %n file(s) could not be moved back + + non è stato possibile riportare indietro %n file + non è stato possibile riportare indietro %n file + + + + + OrganizeFilesDialog + + Format: + Formato: + + + + Organize files + Organizza i file + + + + + Rename files + Rinomina i file + + + + Preparing the preview... + Preparazione dell'anteprima... + + + + &Filename format: + &Formato del nome del file: + + + + &Path format: + Formato del &percorso: + + + + Filename format + Formato del nome del file + + + + Path format + Formato del percorso + + + + Presets + Preimpostazioni + + + + Insert + Inserisci + + + + Optional part < > + Parte opzionale < > + + + + Disappears completely when the fields inside it are empty. + Scompare completamente quando i campi al suo interno sono vuoti. + + + + Padded number {number:000} + Numero con zeri iniziali {number:000} + + + + Format help... + Guida al formato... + + + + selected folder + cartella selezionata + + + + library root + radice della libreria + + + + Move into + Sposta in + + + + Reset changes + Reimposta le modifiche + + + + Remove selected + Rimuovi i selezionati + + + + Show unchanged + Mostra quelli invariati + + + + New name + Nuovo nome + + + + Renamed from + Nome precedente + + + + New location + Nuova posizione + + + + Moved from + Posizione precedente + + + + Remove from list + Rimuovi dall'elenco + + + + Move files + Sposta i file + + + + Cancel + Annulla + + + Copy the list + Copia l'elenco - - Add a new label to this library - Aggiungi una nuova etichetta a questa libreria + + Undo + Ripristina - - Rename selected list - Rinomina la lista selezionata + Close + Chiudi - - Rename any selected labels or lists - Rinomina qualsiasi etichetta o lista selezionata + + Copy failure details + Copia dettagli degli errori - - Add to... - Aggiungi a... + + Finish + Fine - - Favorites - Favoriti + + Remove preset + Rimuovi preimpostazione - - Add selected comics to favorites list - Aggiungi i fumetti selezionati alla lista dei favoriti + + Save current format as preset... + Salva il formato attuale come preimpostazione... - - - LocalComicListModel - - file name - Nome file + + Reset to default format + Ripristina il formato predefinito - - - NoLibrariesWidget - - create your first library - Crea la tua prima libreria + + Save preset + Salva preimpostazione - - You don't have any libraries yet - Per ora non hai ancora nessuna libreria + + Preset name: + Nome della preimpostazione: - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <p>Puoi creare una libreria in qualsiasi cartella, YACReader importerà tutti i fumetti e struttura da questa certella. Se hai creato una qualsiasia libreria nel passato la puoi aprire. </p><p>Non dimenticare che puoi usare YACReader come applicazione stand alone per leggere i fumetti sul tuo PC.</p> + + A filename format cannot contain "/". Use Organize files to move comics into folders. + Un formato del nome del file non può contenere "/". Usa Organizza i file per spostare i fumetti nelle cartelle. - - add an existing one - Aggiungine una esistente + + This format cannot be used: %1 + Questo formato non può essere usato: %1 - - - NoSearchResultsWidget - - No results - Nessun risultato + + new folder + cartella nuova - - - OptionsDialog - - Restore defautls - Resetta al Default + + This folder does not exist yet. It will be created. + Questa cartella non esiste ancora. Verrà creata. - - Background - Sfondo + + file not found + file non trovato - - Blur level - Livello di sfumatura + + This comic is in the library but not on disk. It is skipped. + Questo fumetto è nella libreria ma non sul disco. Viene saltato. - - Enable background image - Abilita l'immagine di sfondo + + name in use + nome già in uso - - Options - Opzioni + + no metadata + senza metadati - - Comic Vine API key - API di ComicVine + + already here + già qui - - Edit Comic Vine API key - Edita l'API di ComicVine + + This file is already in the right place. + Questo file è già al posto giusto. - - Opacity level - Livello di opacità + + edited + modificato + + + + %n will be renamed + + %n sarà rinominato + %n saranno rinominati + + + + + %n will move + + %n sarà spostato + %n saranno spostati + + + + + %n unchanged + + %n invariato + %n invariati + + + + + %n renamed + + %n rinominato + %n rinominati + + + + + %n removed + + %n rimosso + %n rimossi + + + + + %n missing + + %n mancante + %n mancanti + + + + + %n new folder(s) + + %n cartella nuova + %n cartelle nuove + + + + + %n manual change(s) kept + + %n modifica manuale mantenuta + %n modifiche manuali mantenute + - - General - Generale + + Nothing would be renamed with this format. + Con questo formato non verrebbe rinominato nulla. - - Use selected comic cover as background - Usa la cover del fumetto selezionato come sfondo + + Nothing would move with this format. + Con questo formato non verrebbe spostato nulla. + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + %n file sarà rinominato. Le cartelle non cambiano. Puoi ripristinare in seguito. + %n file saranno rinominati. Le cartelle non cambiano. Puoi ripristinare in seguito. + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + %n file sarà spostato in %1. Questo modifica i tuoi file sul disco. Puoi ripristinare in seguito. + %n file saranno spostati in %1. Questo modifica i tuoi file sul disco. Puoi ripristinare in seguito. + - - Comic Flow - Comic Flow + + Moving %1 of %2 +%3 + Spostamento di %1 su %2 +%3 - - - Libraries - Librerie + + Updating the library... + Aggiornamento della libreria... - - Grid view - Vista a Griglia + + Restored name + Nome ripristinato - - Appearance - Aspetto + + + Moved back from + Spostato indietro da - - Language - Lingua + + + + + Status + Stato - - Application language - Lingua dell'applicazione + + Final name + Nome finale - - System default - Predefinita del sistema + + Previous name + Nome precedente - - Tray icon settings (experimental) - Impostazioni dell'icona nella barra delle applicazioni (sperimentale) + + Restored location + Posizione ripristinata - - Close to tray - Vicino al vassoio + + Final location + Posizione finale - - Start into the system tray - Inizia nella barra delle applicazioni + + Previous location + Posizione precedente - - ComicInfo.xml legacy support - Supporto legacy ComicInfo.xml + + Restored + Ripristinato - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics - Importa metadati da ComicInfo.xml quando aggiungi nuovi fumetti + + Renamed + Rinominato - - Consider 'recent' items added or updated since X days ago - Considera gli elementi "recenti" aggiunti o aggiornati da X giorni fa + + Moved + Spostato - - Third party reader - Lettore di terze parti + + Undo failed: %1 + Annullamento non riuscito: %1 - - Write {comic_file_path} where the path should go in the command - Scrivi {comic_file_path} dove dovrebbe andare il percorso nel comando + + Failed: %1 + Operazione non riuscita: %1 - - Clear - Cancella + + Nothing was moved. + Non è stato spostato nulla. - - Update libraries at startup - Aggiorna le librerie all'avvio + + The record this run could be undone from could not be written, so the run did not start: %1 + Non è stato possibile scrivere il registro con cui annullare questa operazione, quindi l'operazione non è iniziata: %1 + + + + %n file(s) renamed. + + %n file rinominato. + %n file rinominati. + + + + + %n file(s) moved into %1. + + %n file spostato in %1. + %n file spostati in %1. + - - Try to detect changes automatically - Prova a rilevare automaticamente le modifiche + + The record of this run stopped early, so the run stopped with it: %1 + Il registro di questa operazione si è interrotto prima della fine, quindi anche l'operazione si è fermata: %1 + + + + %n file(s) were not moved. + + %n file non è stato spostato. + %n file non sono stati spostati. + - - Update libraries periodically - Aggiorna periodicamente le librerie + + The library database could not be updated: %1 + Non è stato possibile aggiornare il database della libreria: %1 - - Interval: - Intervallo: + + Use Undo to move the files back, or update the library to make it match the files. + Usa Ripristina per riportare indietro i file, oppure aggiorna la libreria perché corrisponda ai file. + + + + %n empty folder(s) were removed. + + %n cartella vuota è stata rimossa. + %n cartelle vuote sono state rimosse. + + + + + %n file(s) could not be moved. + + Non è stato possibile spostare %n file. + Non è stato possibile spostare %n file. + - - 30 minutes - 30 minuti + + Moving the files back... + Ripristino dei file in corso... - - 1 hour - 1 ora + + Moving back %1 of %2 +%3 + Ripristino di %1 su %2 +%3 - - 2 hours - 2 ore + + Everything was moved back. + Tutto è stato riportato indietro. - - 4 hours - 4 ore + + The undo did not finish: %1 + Il ripristino non è stato completato: %1 - - 8 hours - 8 ore + + Format help + Guida al formato - - 12 hours - 12 ore + + Fields + Campi - - daily - quotidiano + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + Ogni campo si scrive tra parentesi graffe e viene sostituito dai metadati del fumetto. Il menu Inserisci li elenca tutti. - - Update libraries at certain time - Aggiorna le librerie in determinati orari + + {series} gives %1 + {series} dà %1 - - Time: - Tempo: + + Optional parts + Parti opzionali - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. - AVVERTIMENTO! Durante gli aggiornamenti della libreria le scritture sul database sono disabilitate! -Non pianificare gli aggiornamenti mentre potresti utilizzare l'app attivamente. -Durante gli aggiornamenti automatici l'app bloccherà alcune azioni fino al termine dell'aggiornamento. -Per interrompere un aggiornamento automatico, tocca l'indicatore di caricamento accanto al titolo Librerie. + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + Una parte scritta tra i segni < e > scompare completamente quando tutti i campi al suo interno sono vuoti. Usala per la punteggiatura che appartiene a un campo, come le parentesi o un cancelletto iniziale. Il testo all'inizio o alla fine di un nome viene tagliato anche senza di essa. - - Modifications detection - Rilevamento delle modifiche + + {series} ({year}) with no year gives %1 + {series} ({year}) senza anno dà %1 - - Compare the modified date of files when updating a library (not recommended) - Confronta la data di modifica dei file durante l'aggiornamento di una libreria (non consigliato) + + {series}< ({year})> with no year gives %1 + {series}< ({year})> senza anno dà %1 - - Display continue reading banner - Visualizza il banner continua a leggere + + Numbers + Numeri - - Display current comic banner - Visualizza il banner del fumetto corrente + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + Scrivi due punti e alcuni zeri per riempire il numero dell'albo. Così gli albi restano in ordine in un gestore di file. - - Continue reading - Continua a leggere + + + Folders + Cartelle - - Restart is needed - Riavvio Necessario + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + Un formato del nome del file non può contenere una barra. Ogni fumetto resta nella cartella attuale. Usa Organizza in cartelle per spostare i fumetti. + + + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + Ogni parte separata da una barra diventa una cartella. L'ultima parte diventa il nome del file. L'estensione originale viene sempre mantenuta. @@ -2380,12 +3318,12 @@ Per interrompere un aggiornamento automatico, tocca l'indicatore di caricam Note: - + Invalid cover Copertina non valida - + The image is invalid. L'immagine non è valida. @@ -2535,6 +3473,35 @@ Per interrompere un aggiornamento automatico, tocca l'indicatore di caricam Lista di lettura + + ReadingListManagementCoordinator + + + Add new reading lists + Aggiungi una lista di lettura + + + + + List name: + Nome lista: + + + + Delete list/label + Cancella Lista/Etichetta + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + Gli elementi selezionati verranno cancellati, i tuoi fumetti o cartella NON verranno cancellati dal tuo disco. Sei sicuro? + + + + Rename list name + Rinomina la lista + + RenameLibraryDialog @@ -3248,6 +4215,61 @@ Use quotes to include spaces in a value. Volumi + + SelectedComicsInfoView + + + Unknown + Sconosciuto + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + Fumetto %1 selezionato + + + + Read + Leggi + + + + In progress + In corso + + + + Unread + Non letti + + + + Total pages + + + + + Total size + + + + + Series + Serie + + SeriesQuestion @@ -3269,53 +4291,53 @@ Use quotes to include spaces in a value. ServerConfigDialog - - + + Server connectivity Connettività del server - + Scan to connect Scansiona per connetterti - + Devices on this network can reach your library at the address below. I dispositivi su questa rete possono accedere alla tua libreria all’indirizzo riportato di seguito. - + IP address Indirizzo IP - + Port Porta - + Web interface Interfaccia web - + Copy link Copia link - + Open web UI Apri interfaccia web - + Enable the server Abilita il server - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. YACReader è disponibile per iOS e Android. Scoprilo per <a href='https://ios.yacreader.com'>iOS</a> o <a href='https://android.yacreader.com'>Android</a>. @@ -3332,7 +4354,7 @@ Use quotes to include spaces in a value. Scansiona! - + Set port set port Imposta porta diff --git a/YACReaderLibrary/yacreaderlibrary_ko.ts b/YACReaderLibrary/yacreaderlibrary_ko.ts index f0f8e8376..4426dd119 100644 --- a/YACReaderLibrary/yacreaderlibrary_ko.ts +++ b/YACReaderLibrary/yacreaderlibrary_ko.ts @@ -202,11 +202,22 @@ ClassicComicsView - + Hide comic flow 만화 흐름 숨기기 + + ComicFilesCoordinator + + Copying comics... + 만화 복사 중... + + + Moving comics... + 만화 이동 중... + + ComicInfoView @@ -290,70 +301,99 @@ 흑백 + + ComicManagementCoordinator + + + + YACReader not found + YACReader를 찾을 수 없음 + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + YACReader를 찾을 수 없습니다. YACReader는 YACReaderLibrary와 같은 폴더에 설치되어야 합니다. + + + + YACReader not found. There might be a problem with your YACReader installation. + YACReader를 찾을 수 없습니다. YACReader 설치에 문제가 있을 수 있습니다. + + + + Error + 오류 + + + + Error opening comic with third party reader. + 타사 뷰어로 만화를 여는 중 오류가 발생했습니다. + + ComicModel - + yes - + no 아니오 - + Title 제목 - + File Name 파일 이름 - + Pages 페이지 - + Size 크기 - + Read 읽음 - + Current Page 현재 페이지 - + Publication Date 출판일 - + Rating 평점 - + Series 시리즈 - + Volume 볼륨 - + Story Arc 스토리 아크 @@ -386,45 +426,53 @@ 닫기 - - - + + + Looking for volume... 볼륨 검색 중... - - + + comic %1 of %2 - %3 %1 / %2 만화 - %3 - + %1 comics selected 만화 %1개 선택됨 - + Error connecting to ComicVine Comic Vine 연결 오류 - - + + Retrieving tags for : %1 태그 가져오는 중 : %1 - + Retrieving volume info... 볼륨 정보 가져오는 중... - + Looking for comic... 만화 검색 중... + + ContinueReadingGridHeader + + + Continue Reading... + 이어 읽기... + + CreateLibraryDialog @@ -468,6 +516,14 @@ 선택한 경로가 존재하지 않거나 올바르지 않습니다. 이 폴더에 쓰기 권한이 있는지 확인하세요 + + DBHelper + + + The folder entry could not be found in the library database. + 라이브러리 데이터베이스에서 폴더 항목을 찾을 수 없습니다. + + EditShortcutsDialog @@ -504,6 +560,19 @@ 이 폴더에는 아직 만화가 없습니다 + + EmptyInfoView + + + Nothing selected + 선택 항목 없음 + + + + Select a comic or folder to see its information. + 정보를 보려면 만화 또는 폴더를 선택하세요. + + EmptyLabelWidget @@ -617,46 +686,158 @@ FileComic - + 7z not found 7z를 찾을 수 없습니다 - + CRC error on page (%1): some of the pages will not be displayed correctly %1번 페이지에서 CRC 오류 발생: 일부 페이지가 올바르게 표시되지 않을 수 있습니다 - + Unknown error opening the file 파일을 여는 중 알 수 없는 오류가 발생했습니다 - + + Format not supported 지원하지 않는 형식입니다 - - - Unsupported EPUB: %1 - - FolderContentView - Continue Reading... - 이어 읽기... + 이어 읽기... + + + + FolderInfoView + + + Unknown + 알 수 없음 + + + + Items + 항목 + + + + Type + 유형 + + + + Reading status + 읽기 상태 + + + + Read + 읽음 + + + + Unread + 읽지 않음 + + + + Collection status + 컬렉션 상태 + + + + Completed + 완료 + + + + In progress + 읽는 중 + + + + Added + 추가됨 + + + + Updated + 업데이트됨 + + + + FolderManagementCoordinator + + + Add new folder + 새 폴더 추가 + + + + Folder name: + 폴더 이름: GridComicsView - + Show info 정보 보기 + + Library + 라이브러리 + + + Folder + 폴더 + + + Favorites + 즐겨찾기 + + + Recently added + 최근 추가 + + + + Manga + 망가 + + + + Western manga + 서양식 망가 + + + + Web comic + 웹툰 + + + + Yonkoma + 4컷 만화 + + + + Comic + 만화 + + + + Unknown + 알 수 없음 + HelpAboutDialog @@ -806,34 +987,50 @@ - LibraryWindow + LibraryInfoView - - Library - 라이브러리 + + Library info + 라이브러리 정보 - - Open folder... - 폴더 열기... + + Number of folders + 폴더 수 - - - - western manga (left to right) - 서양 만화 (왼쪽 → 오른쪽) + + Number of comics + 만화 수 - - - - 4koma (top to botom) - 4koma (top to botom - 4컷 (위 → 아래) + + Number of read comics + 읽은 만화 수 + + + + LibraryManagementCoordinator + + + Error opening the library + 라이브러리 열기 오류 + + + + Error creating the library + 라이브러리 생성 오류 + + + + Error updating the library + 라이브러리 업데이트 오류 + + + LibraryWindow - + Do you want remove 다음을 제거하시겠습니까: @@ -843,306 +1040,254 @@ YACReader Library - - - - manga - 망가 - - - - - - comic - 만화 - - - + Are you sure? 확실합니까? - - Rescan library for XML info - XML 정보로 라이브러리 재검색 - - - - Set as read - 읽음으로 표시 - - - - - Set as unread - 읽지 않음으로 표시 - - - - - - web comic - 웹 만화 - - - - Add new folder - 새 폴더 추가 - - - + Delete folder 폴더 삭제 - - Set as uncompleted - 미완료로 표시 - - - - Set as completed - 완료로 표시 - - - - Update folder - 폴더 업데이트 - - - - Folder - 폴더 - - - - Comic - 만화 - - - + Upgrade failed 업그레이드 실패 - + There were errors during library upgrade in: 라이브러리 업그레이드 중 오류 발생: - + Restore recovery failed 복원 복구 실패 - + Update needed 업데이트 필요 - + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? 이 라이브러리는 YACReaderLibrary의 이전 버전으로 만들어졌습니다. 업데이트가 필요합니다. 지금 업데이트하시겠습니까? - + Download new version 새 버전 내려받기 - + This library was created with a newer version of YACReaderLibrary. Download the new version now? 이 라이브러리는 YACReaderLibrary의 최신 버전으로 만들어졌습니다. 지금 새 버전을 내려받으시겠습니까? - + Library not available 라이브러리를 사용할 수 없습니다 - + Library '%1' is no longer available. Do you want to remove it? '%1' 라이브러리를 더 이상 사용할 수 없습니다. 제거하시겠습니까? - + Old library 오래된 라이브러리 - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? '%1' 라이브러리는 이전 버전의 YACReaderLibrary로 만들어졌습니다. 다시 만들어야 합니다. 지금 만드시겠습니까? - - + Copying comics... 만화 복사 중... - - + Moving comics... 만화 이동 중... - + Folder name: 폴더 이름: - + + + No folder selected 선택된 폴더 없음 - + + + Please, select a folder first 먼저 폴더를 선택하세요 - + Error in path 경로 오류 - + There was an error accessing the folder's path 폴더 경로에 접근하는 중 오류가 발생했습니다 - + The selected folder and all its contents will be deleted from your disk. Are you sure? 선택한 폴더와 그 안의 모든 내용이 디스크에서 삭제됩니다. 계속하시겠습니까? - - + + Unable to delete 삭제할 수 없음 - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. - 선택한 폴더를 삭제하는 중 문제가 발생했습니다. 쓰기 권한을 확인하고, 다른 응용 프로그램이 이 폴더나 안의 파일을 사용 중인지 확인하세요. - - - - Add new reading lists - 새 읽기 목록 추가 - - - - - List name: - 목록 이름: - - - - Delete list/label - 목록/라벨 삭제 - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - 선택한 항목이 삭제됩니다. 디스크에서 만화나 폴더는 삭제되지 않습니다. 계속하시겠습니까? + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + 선택한 폴더를 삭제하는 중 문제가 발생했습니다. 쓰기 권한을 확인하고, 다른 응용 프로그램이 이 폴더나 안의 파일을 사용하고 있지 않은지 확인하세요. - - Rename list name - 목록 이름 변경 + + Rename or organize files + 파일 이름 변경 또는 정리 - - - - - Set type - 유형 설정 + + Set the type of the selected comics + 선택한 만화의 유형 설정 - + Search filters 검색 필터 - + Unread 읽지 않음 - + In progress 읽는 중 - + Highly rated 높은 평점 - + Recently added 최근 추가 - + Search syntax… 검색 구문… - + A repair of this library is already running (%1). Wait for it to finish. 이 라이브러리에 대한 복구가 이미 진행 중입니다 (%1). 완료될 때까지 기다려 주세요. - + The library is locked by a repair that did not finish. 라이브러리가 완료되지 않은 복구에 의해 잠겨 있습니다. - + The library is locked by a repair started by %1. 라이브러리가 %1에서 시작한 복구에 의해 잠겨 있습니다. - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? 다른 복구가 실행 중이 아니라고 확신하면 잠금을 해제할 수 있습니다. 잠금을 해제하고 계속하시겠습니까? - + Package operation failed - + 패키지 작업 실패 - + The covers package operation could not be completed. - + 표지 패키지 작업을 완료할 수 없습니다. - - Set custom cover - 사용자 지정 표지 설정 + + Rename folder + 폴더 이름 바꾸기 - - Delete custom cover - 사용자 지정 표지 삭제 + + Invalid folder name + 잘못된 폴더 이름 + + + + The folder name is empty or contains characters that are not supported. + 폴더 이름이 비어 있거나 지원하지 않는 문자가 있습니다. - + + + + Unable to rename folder + 폴더 이름을 변경할 수 없음 + + + + A file or folder named '%1' already exists. + '%1'(이)라는 파일 또는 폴더가 이미 있습니다. + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. + +Folder: %1 + 디스크에서 폴더 이름을 변경할 수 없습니다. 폴더 이름과 쓰기 권한을 확인하세요. + +폴더: %1 + + + + The library database could not be updated. The folder rename on disk was reverted. + 라이브러리 데이터베이스를 업데이트할 수 없습니다. 디스크의 폴더 이름 변경을 되돌렸습니다. + + + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + 라이브러리 데이터베이스를 업데이트하지 못했고 디스크의 폴더 이름 변경도 되돌리지 못했습니다. 이제 라이브러리를 수동으로 업데이트해야 합니다. + + + Save covers 표지 저장 - + You are adding too many libraries. 라이브러리를 너무 많이 추가하고 있습니다. - + You are adding too many libraries. You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. @@ -1155,84 +1300,58 @@ YACReaderLibrary will not stop you from creating more libraries but you should k YACReaderLibrary는 라이브러리를 더 만드는 것을 막지 않지만, 라이브러리 수는 적게 유지하는 것이 좋습니다. - - - YACReader not found - YACReader를 찾을 수 없음 - - - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - YACReader를 찾을 수 없습니다. YACReader는 YACReaderLibrary와 같은 폴더에 설치되어야 합니다. - - - - YACReader not found. There might be a problem with your YACReader installation. - YACReader를 찾을 수 없습니다. YACReader 설치에 문제가 있을 수 있습니다. - - - - Error - 오류 - - - - Error opening comic with third party reader. - 타사 뷰어로 만화를 여는 중 오류가 발생했습니다. - - - + Library not found 라이브러리를 찾을 수 없음 - + The selected folder doesn't contain any library. 선택한 폴더에 라이브러리가 없습니다. - - + + YACReader library database (*.ydb) YACReader 라이브러리 데이터베이스 (*.ydb) - + The library database backup was created at: %1 라이브러리 데이터베이스 백업을 다음 위치에 만들었습니다: %1 - + Unable to create the library database backup: %1 라이브러리 데이터베이스 백업을 만들 수 없습니다: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? 복원하기 전에 YACReaderLibraryServer와 이 라이브러리를 사용하는 다른 모든 YACReader 애플리케이션을 종료하세요. 계속하시겠습니까? - + Restoring library database... 라이브러리 데이터베이스 복원 중... - + The current library database is invalid. Restore the selected backup anyway? 현재 라이브러리 데이터베이스가 유효하지 않습니다. 선택한 백업을 그래도 복원하시겠습니까? - - + + The library maintenance lock may be stale. Remove it and retry? 라이브러리 유지 관리 잠금이 오래된 것일 수 있습니다. 잠금을 제거하고 다시 시도하시겠습니까? - + Restart YACReaderLibrary before attempting recovery again. @@ -1241,71 +1360,71 @@ Restart YACReaderLibrary before attempting recovery again. 복구를 다시 시도하기 전에 YACReaderLibrary를 다시 시작하세요. - + The library database was restored successfully. Update the library now? 라이브러리 데이터베이스를 성공적으로 복원했습니다. 지금 라이브러리를 업데이트하시겠습니까? - + Library database damaged 라이브러리 데이터베이스 손상 - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. '%1' 라이브러리의 데이터베이스가 손상되어 일반 업데이트, 유지 관리 및 백업을 사용할 수 없습니다. YACReader가 데이터베이스 복구를 시도할 수 있습니다. 손상된 일부 데이터는 복구하지 못할 수 있습니다. 기존 백업은 변경되지 않습니다. - + Attempt repair 복구 시도 - + Restore a backup... 백업 복원... - + Repairing library database... 라이브러리 데이터베이스 복구 중... - - - + + + Library database repair 라이브러리 데이터베이스 복구 - + Another maintenance operation is currently using this library. Try again after it finishes. 현재 다른 유지 관리 작업에서 이 라이브러리를 사용 중입니다. 작업이 끝난 후 다시 시도하세요. - + The library database is already valid. 라이브러리 데이터베이스가 이미 유효합니다. - + Library database repaired 라이브러리 데이터베이스 복구됨 - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 인덱스를 다시 빌드하여 라이브러리 데이터베이스를 복구했습니다. 손상된 원본은 다음 위치에 보존되었습니다: %1 - + Library database rebuilt 라이브러리 데이터베이스 재구축됨 - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1316,7 +1435,7 @@ Update the library now? 지금 라이브러리를 업데이트하시겠습니까? - + The damaged original was preserved at: @@ -1327,12 +1446,12 @@ The damaged original was preserved at: %1 - + Library database repair failed 라이브러리 데이터베이스 복구 실패 - + The library database could not be repaired: %1%2 @@ -1343,12 +1462,12 @@ You can restore a backup from the Library menu or recreate the library. 라이브러리 메뉴에서 백업을 복원하거나 라이브러리를 다시 만들 수 있습니다. - + library? 라이브러리? - + Remove and delete metadata and backups 메타데이터 및 백업 제거 후 삭제 @@ -1357,92 +1476,77 @@ You can restore a backup from the Library menu or recreate the library. 제거 및 메타데이터 삭제 - + Library info 라이브러리 정보 - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. 선택한 만화를 삭제하는 중 문제가 발생했습니다. 선택한 파일이나 포함된 폴더의 쓰기 권한을 확인하세요. - + Assign comics numbers 만화에 번호 부여 - + Assign numbers starting in: 다음 번호부터 부여: - + Invalid image 잘못된 이미지 - + The selected file is not a valid image. 선택한 파일이 유효한 이미지가 아닙니다. - + Error saving cover 표지 저장 오류 - + There was an error saving the cover image. 표지 이미지를 저장하는 중 오류가 발생했습니다. - - Error creating the library - 라이브러리 생성 오류 - - - - Error updating the library - 라이브러리 업데이트 오류 - - - - Error opening the library - 라이브러리 열기 오류 - - - + Delete comics 만화 삭제 - + All the selected comics will be deleted from your disk. Are you sure? 선택한 만화가 모두 디스크에서 삭제됩니다. 확실합니까? - + Remove comics 만화 제거 - + Comics will only be deleted from the current label/list. Are you sure? 만화가 현재 라벨/목록에서만 삭제됩니다. 확실합니까? - + Library name already exists 라이브러리 이름 중복 - + There is another library with the name '%1'. '%1' 이름의 라이브러리가 이미 있습니다. - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1454,763 +1558,1580 @@ Missing files: %3 LibraryWindowActions - + Create a new library 새 라이브러리 만들기 - + Open an existing library 기존 라이브러리 열기 - - + + Export comics info 만화 정보 내보내기 - - + + Import comics info 만화 정보 가져오기 - + Pack covers 표지 묶기 - + Pack the covers of the selected library 선택한 라이브러리의 표지 묶기 - + Unpack covers 표지 풀기 - + Unpack a catalog 카탈로그 풀기 - + Update library 라이브러리 업데이트 - + Update current library 현재 라이브러리 업데이트 - + Back up library database 라이브러리 데이터베이스 백업 - + Create a backup of the current library database 현재 라이브러리 데이터베이스의 백업 만들기 - + Restore library database backup 라이브러리 데이터베이스 백업 복원 - + Restore the current library database from a backup 백업에서 현재 라이브러리 데이터베이스 복원 - + Repair covers and comic info 표지 및 만화 정보 복구 - + Retry comics with missing covers or incomplete information 표지가 없거나 정보가 불완전한 만화를 다시 처리합니다 - + Rename library 라이브러리 이름 변경 - + Rename current library 현재 라이브러리 이름 변경 - + Remove library 라이브러리 제거 - + Remove current library from your collection 내 컬렉션에서 현재 라이브러리 제거 - + Rescan library for XML info XML 정보로 라이브러리 재검색 - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. 만화 파일에 포함된 XML 정보를 찾으려고 시도합니다. 9.8.2 이하 버전으로 만든 라이브러리이거나 타사 소프트웨어로 파일에 XML 정보를 포함한 경우에만 필요합니다. - + Open library folder... 라이브러리 폴더 열기... - + Open the root folder of the current library 현재 라이브러리의 루트 폴더 열기 - + Show library info 라이브러리 정보 표시 - + Show information about the current library 현재 라이브러리에 대한 정보 표시 - + Open current comic 현재 만화 열기 - + Open current comic on YACReader YACReader에서 현재 만화 열기 - + Save selected covers to... 선택한 표지 저장... - + Save covers of the selected comics as JPG files 선택한 만화의 표지를 JPG 파일로 저장 - - + + Set as read 읽음으로 표시 - + Set comic as read 만화를 읽음으로 표시 - - + + Set as unread 읽지 않음으로 표시 - + Set comic as unread 만화를 읽지 않음으로 표시 - - + + manga 망가 - + Set issue as manga 만화를 망가로 설정 - - + + comic 만화 - + Set issue as normal 만화를 일반으로 설정 - + western manga 서양 만화 - + Set issue as western manga 만화를 서양 만화로 설정 - - + + web comic 웹 만화 - + Set issue as web comic 만화를 웹 만화로 설정 - - + + yonkoma 4컷 만화 - + Set issue as yonkoma 만화를 4컷 만화로 설정 - + Show/Hide marks 읽음 마크 표시/숨김 - + Show or hide read marks 읽음 마크를 표시하거나 숨김 - + Show/Hide recent indicator 신규 표시 표시/숨김 - + Show or hide recent indicator 신규 표시를 표시하거나 숨김 - - + + Fullscreen mode on/off 전체화면 모드 켜기/끄기 - + Help, About YACReader 도움말, YACReader 정보 - + Add new folder 새 폴더 추가 - + Add new folder to the current library 현재 라이브러리에 새 폴더 추가 - + + Rename folder + 폴더 이름 바꾸기 + + + + Rename the current folder on disk and in the library + 디스크와 라이브러리에서 현재 폴더 이름 변경 + + + Delete folder 폴더 삭제 - + Delete current folder from disk 현재 폴더를 디스크에서 삭제 - + Select root node 루트 노드 선택 - + Expand all nodes 모든 노드 펼치기 - + Collapse all nodes 모든 노드 접기 - + Show options dialog 환경설정 다이얼로그 표시 - + Show comics server options dialog 만화 서버 환경설정 다이얼로그 표시 - - + + Change between comics views 만화 보기 전환 - + Open folder... 폴더 열기... - + + + Rename files... + Organize files + 파일 이름 변경... + + + + + Organize into folders... + 폴더로 정리... + + + Set as uncompleted 미완료로 표시 - + Set as completed 완료로 표시 - + Set custom cover 사용자 지정 표지 설정 - + Delete custom cover 사용자 지정 표지 삭제 - + western manga (left to right) 서양 만화 (왼쪽 → 오른쪽) - + Open containing folder... 포함된 폴더 열기... - Reset comic rating - 만화 평점 초기화 + 만화 평점 초기화 - + Select all comics 모든 만화 선택 - + Edit 편집 - + Assign current order to comics 만화에 현재 순서 적용 - + Update cover 표지 업데이트 - + Delete selected comics 선택한 만화 삭제 - + Delete metadata from selected comics 선택한 만화에서 메타데이터 삭제 - + Download tags from Comic Vine Comic Vine에서 태그 내려받기 - + Focus search line 검색창으로 이동 - + Focus comics view 만화 보기로 이동 - + Edit shortcuts 단축키 편집 - + &Quit 끝내기(&Q) - + Update folder 폴더 업데이트 - + Update current folder 현재 폴더 업데이트 - + Scan legacy XML metadata 레거시 XML 메타데이터 스캔 - + Add new reading list 새 읽기 목록 추가 - + Add a new reading list to the current library 현재 라이브러리에 새 읽기 목록 추가 - + Remove reading list 읽기 목록 제거 - + Remove current reading list from the library 라이브러리에서 현재 읽기 목록 제거 - - Add new label - 새 라벨 추가 + + Add new label + 새 라벨 추가 + + + + Add a new label to this library + 이 라이브러리에 새 라벨 추가 + + + + Rename selected list + 선택한 목록 이름 변경 + + + + Rename any selected labels or lists + 선택한 라벨이나 목록 이름 변경 + + + + Add to... + 추가... + + + + Favorites + 즐겨찾기 + + + + Add selected comics to favorites list + 선택한 만화를 즐겨찾기 목록에 추가 + + + + + Reset rating + 평점 초기화 + + + + LibraryWindowMenus + + + comic + 만화 + + + + manga + 망가 + + + + western manga (left to right) + 서양 만화 (왼쪽 → 오른쪽) + + + + web comic + 웹 만화 + + + + 4koma (top to botom) + 4컷 (위 → 아래) + + + + + + + Set type + 유형 설정 + + + + Library + 라이브러리 + + + + Folder + 폴더 + + + + Comic + 만화 + + + + Open folder... + 폴더 열기... + + + + Update folder + 폴더 업데이트 + + + + Rename folder + 폴더 이름 바꾸기 + + + + Rename files... + 파일 이름 변경... + + + + Organize into folders... + 폴더로 정리... + + + + Rescan library for XML info + XML 정보로 라이브러리 재검색 + + + + Set as uncompleted + 미완료로 표시 + + + + Set as completed + 완료로 표시 + + + + Set as read + 읽음으로 표시 + + + + + Set as unread + 읽지 않음으로 표시 + + + + Set custom cover + 사용자 지정 표지 설정 + + + + Delete custom cover + 사용자 지정 표지 삭제 + + + + ListInfoView + + + 1 comic + 만화 1권 + + + + %1 comics + 만화 %1권 + + + + Last day + 지난 1일 + + + + Last %1 days + 지난 %1일 + + + + 1 sublist + 하위 목록 1개 + + + + %1 sublists + 하위 목록 %1개 + + + + LocalComicListModel + + + file name + 파일 이름 + + + + NoLibrariesWidget + + + You don't have any libraries yet + 아직 라이브러리가 없습니다 + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <p>아무 폴더에 라이브러리를 만들 수 있고, YACReaderLibrary가 그 폴더의 모든 만화와 하위 폴더를 가져옵니다. 이전에 만든 라이브러리가 있으면 열 수 있습니다.</p><p>YACReader는 단독 응용 프로그램으로 컴퓨터의 만화를 보는 데도 쓸 수 있습니다.</p> + + + + create your first library + 첫 라이브러리 만들기 + + + + add an existing one + 기존 라이브러리 추가 + + + + NoSearchResultsWidget + + + No results + 결과 없음 + + + + OptionsDialog + + + Language + 언어 + + + + Application language + 응용 프로그램 언어 + + + + System default + 시스템 기본값 + + + + Tray icon settings (experimental) + 트레이 아이콘 설정 (실험적) + + + + Close to tray + 트레이로 최소화 + + + + Start into the system tray + 시스템 트레이에서 시작 + + + + Edit Comic Vine API key + Comic Vine API 키 편집 + + + + Comic Vine API key + Comic Vine API 키 + + + + ComicInfo.xml legacy support + ComicInfo.xml 레거시 지원 + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + 새 만화 추가 시 ComicInfo.xml에서 메타데이터 가져오기 + + + + Consider 'recent' items added or updated since X days ago + X일 전부터 추가되거나 업데이트된 항목을 '최근'으로 간주 + + + + Third party reader + 타사 뷰어 + + + + Write {comic_file_path} where the path should go in the command + 명령어에서 경로가 들어갈 자리에 {comic_file_path}를 입력하세요 + + + + Clear + 지우기 + + + + Update libraries at startup + 시작 시 라이브러리 업데이트 + + + + Try to detect changes automatically + 변경 사항 자동 감지 시도 + + + + Update libraries periodically + 라이브러리 주기적으로 업데이트 + + + + Interval: + 간격: + + + + 30 minutes + 30분 + + + + 1 hour + 1시간 + + + + 2 hours + 2시간 + + + + 4 hours + 4시간 + + + + 8 hours + 8시간 + + + + 12 hours + 12시간 + + + + daily + 매일 + + + + Update libraries at certain time + 특정 시간에 라이브러리 업데이트 + + + + Time: + 시간: + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + 주의! 라이브러리를 업데이트하는 동안에는 데이터베이스에 기록할 수 없습니다. +앱을 적극적으로 사용 중일 때는 업데이트를 예약하지 마세요. +자동 업데이트가 진행되는 동안에는 일부 기능이 잠시 차단될 수 있습니다. +자동 업데이트를 중단하려면 라이브러리 제목 옆에 표시되는 로딩 아이콘을 눌러주세요. + + + + Modifications detection + 수정 감지 + + + + Compare the modified date of files when updating a library (not recommended) + 라이브러리 업데이트 시 파일 수정 날짜 비교 (권장하지 않음) + + + + Enable background image + 배경 이미지 사용 + + + + Opacity level + 불투명도 + + + + Blur level + 흐림 정도 + + + + Use selected comic cover as background + 선택한 만화 표지를 배경으로 사용 + + + + Restore defautls + 기본값으로 복원 + + + + Background + 배경 + + + + Display continue reading banner + 이어 읽기 배너 표시 + + + + Display current comic banner + 현재 만화 배너 표시 + + + + Continue reading + 이어 읽기 + + + + Mix folders and comics + 폴더와 만화 함께 표시 + + + + Start comics on a new row + 만화를 새 행에서 시작 + + + + Content + 콘텐츠 + + + + Comic Flow + 코믹 플로우 + + + + + Libraries + 라이브러리 + + + + Grid view + 격자 보기 + + + + General + 일반 + + + + Appearance + 외관 + + + + Options + 환경설정 + + + + Restart is needed + 재시작이 필요합니다 + + + + OrganizeFiles + + + Renamed, %1 is already in use + 이름 변경됨, %1은(는) 이미 사용 중입니다 + + + + Missing metadata: %1 + 누락된 메타데이터: %1 + + + + %1 could not be created + %1을(를) 만들 수 없습니다 + + + + OrganizeFilesCoordinator + + + + Organize files + 파일 정리 + + + + This folder does not contain any comics. + 이 폴더에는 만화가 없습니다. + + + + This library is busy: %1 + 이 라이브러리는 사용 중입니다: %1 + + + + the library database could not be opened + 라이브러리 데이터베이스를 열 수 없습니다 + + + + the library database could not be locked for writing + 쓰기용으로 라이브러리 데이터베이스를 잠글 수 없습니다 + + + + a folder entry could not be restored + 폴더 항목을 복원할 수 없습니다 + + + + a comic entry could not be updated + 만화 항목을 업데이트할 수 없습니다 + + + + the library database could not be saved: %1 + 라이브러리 데이터베이스를 저장할 수 없습니다: %1 + + + + the record of the last organize run could not be read + 마지막 정리 작업의 기록을 읽을 수 없습니다 + + + + the folder %1 could not be created + %1 폴더를 만들 수 없습니다 + + + + %n file(s) could not be moved back + + %n개 파일을 되돌리지 못했습니다 + + + + + OrganizeFilesDialog + + Format: + 형식: + + + + Organize files + 파일 정리 + + + + + Rename files + 파일 이름 변경 + + + + Preparing the preview... + 미리 보기를 준비하는 중... + + + + &Filename format: + 파일 이름 형식(&F): + + + + &Path format: + 경로 형식(&P): + + + + Filename format + 파일 이름 형식 + + + + Path format + 경로 형식 + + + + Presets + 사전 설정 + + + + Insert + 삽입 + + + + Optional part < > + 선택 부분 < > + + + + Disappears completely when the fields inside it are empty. + 안에 있는 필드가 비어 있으면 완전히 사라집니다. + + + + Padded number {number:000} + 0으로 채운 번호 {number:000} + + + + Format help... + 형식 도움말... + + + + selected folder + 선택한 폴더 + + + + library root + 라이브러리 루트 + + + + Move into + 이동 위치 + + + + Reset changes + 변경 사항 초기화 + + + + Remove selected + 선택 항목 제거 + + + + Show unchanged + 변경되지 않은 항목 표시 + + + + New name + 새 이름 + + + + Renamed from + 이전 이름 + + + + New location + 새 위치 + + + + Moved from + 이전 위치 + + + + Remove from list + 목록에서 제거 + + + + Move files + 파일 이동 + + + + Cancel + 취소 + + + Copy the list + 목록 복사 + + + + Undo + 실행 취소 - - Add a new label to this library - 이 라이브러리에 새 라벨 추가 + Close + 닫기 - - Rename selected list - 선택한 목록 이름 변경 + + Copy failure details + 실패 세부 정보 복사 - - Rename any selected labels or lists - 선택한 라벨이나 목록 이름 변경 + + Finish + 완료 - - Add to... - 추가... + + Remove preset + 사전 설정 제거 - - Favorites - 즐겨찾기 + + Save current format as preset... + 현재 형식을 사전 설정으로 저장... - - Add selected comics to favorites list - 선택한 만화를 즐겨찾기 목록에 추가 + + Reset to default format + 기본 형식으로 재설정 - - - LocalComicListModel - - file name - 파일 이름 + + Save preset + 사전 설정 저장 - - - NoLibrariesWidget - - You don't have any libraries yet - 아직 라이브러리가 없습니다 + + Preset name: + 사전 설정 이름: - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <p>아무 폴더에 라이브러리를 만들 수 있고, YACReaderLibrary가 그 폴더의 모든 만화와 하위 폴더를 가져옵니다. 이전에 만든 라이브러리가 있으면 열 수 있습니다.</p><p>YACReader는 단독 응용 프로그램으로 컴퓨터의 만화를 보는 데도 쓸 수 있습니다.</p> + + A filename format cannot contain "/". Use Organize files to move comics into folders. + 파일 이름 형식에는 "/"를 사용할 수 없습니다. 만화를 폴더로 옮기려면 파일 정리를 사용하세요. - - create your first library - 첫 라이브러리 만들기 + + This format cannot be used: %1 + 이 형식은 사용할 수 없습니다: %1 - - add an existing one - 기존 라이브러리 추가 + + new folder + 새 폴더 - - - NoSearchResultsWidget - - No results - 결과 없음 + + This folder does not exist yet. It will be created. + 이 폴더는 아직 없습니다. 새로 만듭니다. - - - OptionsDialog - - Language - 언어 + + file not found + 파일 없음 - - Application language - 응용 프로그램 언어 + + This comic is in the library but not on disk. It is skipped. + 이 만화는 라이브러리에 있지만 디스크에 없습니다. 건너뜁니다. - - System default - 시스템 기본값 + + name in use + 이름 사용 중 - - Tray icon settings (experimental) - 트레이 아이콘 설정 (실험적) + + no metadata + 메타데이터 없음 - - Close to tray - 트레이로 최소화 + + already here + 이미 여기 있음 - - Start into the system tray - 시스템 트레이에서 시작 + + This file is already in the right place. + 이 파일은 이미 올바른 위치에 있습니다. - - Edit Comic Vine API key - Comic Vine API 키 편집 + + edited + 편집됨 + + + + %n will be renamed + + %n개 이름 변경 예정 + + + + + %n will move + + %n개 이동 예정 + + + + + %n unchanged + + %n개 변경 없음 + + + + + %n renamed + + %n개 이름 변경됨 + + + + + %n removed + + %n개 제거됨 + + + + + %n missing + + %n개 없음 + + + + + %n new folder(s) + + 새 폴더 %n개 + + + + + %n manual change(s) kept + + 수동 변경 %n개 유지됨 + - - Comic Vine API key - Comic Vine API 키 + + Nothing would be renamed with this format. + 이 형식으로는 이름이 변경되는 파일이 없습니다. - - ComicInfo.xml legacy support - ComicInfo.xml 레거시 지원 + + Nothing would move with this format. + 이 형식으로는 이동하는 파일이 없습니다. + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + 파일 %n개의 이름을 변경합니다. 폴더는 바뀌지 않습니다. 나중에 실행 취소할 수 있습니다. + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + 파일 %n개를 %1(으)로 이동합니다. 디스크의 파일이 바뀝니다. 나중에 실행 취소할 수 있습니다. + - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics - 새 만화 추가 시 ComicInfo.xml에서 메타데이터 가져오기 + + Moving %1 of %2 +%3 + %2개 중 %1개 이동 중 +%3 - - Consider 'recent' items added or updated since X days ago - X일 전부터 추가되거나 업데이트된 항목을 '최근'으로 간주 + + Updating the library... + 라이브러리를 업데이트하는 중... - - Third party reader - 타사 뷰어 + + Restored name + 복원된 이름 - - Write {comic_file_path} where the path should go in the command - 명령어에서 경로가 들어갈 자리에 {comic_file_path}를 입력하세요 + + + Moved back from + 다음 위치에서 되돌림 - - Clear - 지우기 + + + + + Status + 상태 - - Update libraries at startup - 시작 시 라이브러리 업데이트 + + Final name + 최종 이름 - - Try to detect changes automatically - 변경 사항 자동 감지 시도 + + Previous name + 이전 이름 - - Update libraries periodically - 라이브러리 주기적으로 업데이트 + + Restored location + 복원된 위치 - - Interval: - 간격: + + Final location + 최종 위치 - - 30 minutes - 30분 + + Previous location + 이전 위치 - - 1 hour - 1시간 + + Restored + 복원됨 - - 2 hours - 2시간 + + Renamed + 이름 변경됨 - - 4 hours - 4시간 + + Moved + 이동됨 - - 8 hours - 8시간 + + Undo failed: %1 + 실행 취소 실패: %1 - - 12 hours - 12시간 + + Failed: %1 + 실패: %1 - - daily - 매일 + + Nothing was moved. + 이동한 항목이 없습니다. - - Update libraries at certain time - 특정 시간에 라이브러리 업데이트 + + The record this run could be undone from could not be written, so the run did not start: %1 + 이 작업을 실행 취소할 수 있는 기록을 쓰지 못해 작업을 시작하지 않았습니다: %1 + + + + %n file(s) renamed. + + 파일 %n개의 이름을 변경했습니다. + + + + + %n file(s) moved into %1. + + 파일 %n개를 %1(으)로 이동했습니다. + - - Time: - 시간: + + The record of this run stopped early, so the run stopped with it: %1 + 이 작업의 기록이 도중에 멈춰서 작업도 함께 멈췄습니다: %1 + + + + %n file(s) were not moved. + + 파일 %n개를 이동하지 않았습니다. + - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. - 주의! 라이브러리를 업데이트하는 동안에는 데이터베이스에 기록할 수 없습니다. -앱을 적극적으로 사용 중일 때는 업데이트를 예약하지 마세요. -자동 업데이트가 진행되는 동안에는 일부 기능이 잠시 차단될 수 있습니다. -자동 업데이트를 중단하려면 라이브러리 제목 옆에 표시되는 로딩 아이콘을 눌러주세요. + + The library database could not be updated: %1 + 라이브러리 데이터베이스를 업데이트할 수 없습니다: %1 - - Modifications detection - 수정 감지 + + Use Undo to move the files back, or update the library to make it match the files. + 실행 취소를 사용해 파일을 되돌리거나, 라이브러리를 업데이트해 파일과 일치시키세요. + + + + %n empty folder(s) were removed. + + 빈 폴더 %n개를 제거했습니다. + + + + + %n file(s) could not be moved. + + 파일 %n개를 이동하지 못했습니다. + - - Compare the modified date of files when updating a library (not recommended) - 라이브러리 업데이트 시 파일 수정 날짜 비교 (권장하지 않음) + + Moving the files back... + 파일을 되돌리는 중... - - Enable background image - 배경 이미지 사용 + + Moving back %1 of %2 +%3 + %2개 중 %1개 되돌리는 중 +%3 - - Opacity level - 불투명도 + + Everything was moved back. + 모두 되돌렸습니다. - - Blur level - 흐림 정도 + + The undo did not finish: %1 + 실행 취소를 완료하지 못했습니다: %1 - - Use selected comic cover as background - 선택한 만화 표지를 배경으로 사용 + + Format help + 형식 도움말 - - Restore defautls - 기본값으로 복원 + + Fields + 필드 - - Background - 배경 + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + 각 필드는 중괄호 안에 쓰며 만화의 메타데이터로 바뀝니다. 삽입 메뉴에 모든 필드가 있습니다. - - Display continue reading banner - 이어 읽기 배너 표시 + + {series} gives %1 + {series} → %1 - - Display current comic banner - 현재 만화 배너 표시 + + Optional parts + 선택 부분 - - Continue reading - 이어 읽기 + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + < 와 > 사이에 쓴 부분은 그 안의 모든 필드가 비어 있으면 완전히 사라집니다. 괄호나 앞에 붙는 번호 기호처럼 필드에 딸린 문장 부호에 사용하세요. 이름의 처음과 끝에 있는 공백은 이 부분이 없어도 잘립니다. - - Comic Flow - 코믹 플로우 + + {series} ({year}) with no year gives %1 + {series} ({year}) 연도가 없으면 %1 - - - Libraries - 라이브러리 + + {series}< ({year})> with no year gives %1 + {series}< ({year})> 연도가 없으면 %1 - - Grid view - 격자 보기 + + Numbers + 번호 - - General - 일반 + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + 콜론과 0을 몇 개 써서 호 번호를 채우세요. 그러면 파일 탐색기에서 호가 순서대로 정렬됩니다. - - Appearance - 외관 + + + Folders + 폴더 - - Options - 환경설정 + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + 파일 이름 형식에는 슬래시를 넣을 수 없습니다. 각 만화는 현재 폴더에 그대로 있습니다. 만화를 옮기려면 폴더로 정리를 사용하세요. - - Restart is needed - 재시작이 필요합니다 + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + 슬래시로 나눈 각 부분이 폴더가 됩니다. 마지막 부분이 파일 이름이 됩니다. 원래 확장자는 항상 유지됩니다. @@ -2473,12 +3394,12 @@ To stop an automatic update tap on the loading indicator next to the Libraries t 선택한 만화 정보 편집 - + Invalid cover 잘못된 표지 - + The image is invalid. 이미지가 유효하지 않습니다. @@ -2536,6 +3457,35 @@ To stop an automatic update tap on the loading indicator next to the Libraries t 읽기 목록 + + ReadingListManagementCoordinator + + + Add new reading lists + 새 읽기 목록 추가 + + + + + List name: + 목록 이름: + + + + Delete list/label + 목록/라벨 삭제 + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + 선택한 항목이 삭제됩니다. 디스크에서 만화나 폴더는 삭제되지 않습니다. 계속하시겠습니까? + + + + Rename list name + 목록 이름 변경 + + RenameLibraryDialog @@ -3249,6 +4199,61 @@ Use quotes to include spaces in a value. 볼륨 설명을 사용할 수 없음 + + SelectedComicsInfoView + + + Unknown + 알 수 없음 + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + 만화 %1개 선택됨 + + + + Read + 읽음 + + + + In progress + 읽는 중 + + + + Unread + 읽지 않음 + + + + Total pages + + + + + Total size + + + + + Series + 시리즈 + + SeriesQuestion @@ -3270,7 +4275,7 @@ Use quotes to include spaces in a value. ServerConfigDialog - + Set port set port 포트 설정 @@ -3292,53 +4297,53 @@ Use quotes to include spaces in a value. IP 주소 선택 - - + + Server connectivity 서버 연결 - + Scan to connect 스캔하여 연결 - + Devices on this network can reach your library at the address below. 이 네트워크의 기기는 아래 주소를 통해 라이브러리에 접속할 수 있습니다. - + IP address IP 주소 - + Port 포트 - + Web interface 웹 인터페이스 - + Copy link 링크 복사 - + Open web UI 웹 UI 열기 - + Enable the server 서버 활성화 - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. YACReader는 iOS와 Android에서 사용할 수 있습니다. <a href='https://ios.yacreader.com'>iOS</a> 또는 <a href='https://android.yacreader.com'>Android</a>용 앱을 만나 보세요. @@ -3765,12 +4770,12 @@ Use quotes to include spaces in a value. Release notes are not available. - + 릴리스 노트를 사용할 수 없습니다. Previous versions - + 이전 버전 diff --git a/YACReaderLibrary/yacreaderlibrary_nl.ts b/YACReaderLibrary/yacreaderlibrary_nl.ts index 6df1eaa3b..0fc1ae139 100644 --- a/YACReaderLibrary/yacreaderlibrary_nl.ts +++ b/YACReaderLibrary/yacreaderlibrary_nl.ts @@ -202,11 +202,22 @@ ClassicComicsView - + Hide comic flow Comic Flow verbergen + + ComicFilesCoordinator + + Copying comics... + Strips kopiëren... + + + Moving comics... + Strips verplaatsen... + + ComicInfoView @@ -290,70 +301,99 @@ z/w + + ComicManagementCoordinator + + + + YACReader not found + YACReader niet gevonden + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + YACReader niet gevonden. YACReader moet in dezelfde map worden geïnstalleerd als YACReaderLibrary. + + + + YACReader not found. There might be a problem with your YACReader installation. + YACReader niet gevonden. Er is mogelijk een probleem met uw YACReader-installatie. + + + + Error + Fout + + + + Error opening comic with third party reader. + Fout bij het openen van een strip met een lezer van een derde partij. + + ComicModel - + no neen - + yes Ja - + Read Gelezen - + Size Grootte(MB) - + Pages Pagina's - + Title Titel - + File Name Bestandsnaam - + Current Page Huidige pagina - + Publication Date Publicatiedatum - + Rating Beoordeling - + Series Serie - + Volume Deel - + Story Arc Verhaalboog @@ -386,45 +426,53 @@ dichtbij - - - + + + Looking for volume... Op zoek naar volumes... - - + + comic %1 of %2 - %3 strip %1 van %2 - %3 - + %1 comics selected %1 strips geselecteerd - + Error connecting to ComicVine Fout bij verbinden met ComicVine - - + + Retrieving tags for : %1 Tags ophalen voor: %1 - + Retrieving volume info... Volume-informatie ophalen... - + Looking for comic... Op zoek naar komische... + + ContinueReadingGridHeader + + + Continue Reading... + Verder lezen... + + CreateLibraryDialog @@ -468,6 +516,14 @@ Pad niet gevonden + + DBHelper + + + The folder entry could not be found in the library database. + De mapvermelding is niet gevonden in de database van de bibliotheek. + + EditShortcutsDialog @@ -504,6 +560,19 @@ Deze map bevat nog geen strips + + EmptyInfoView + + + Nothing selected + Niets geselecteerd + + + + Select a comic or folder to see its information. + Selecteer een strip of map om de informatie te bekijken. + + EmptyLabelWidget @@ -617,46 +686,158 @@ FileComic - + 7z not found 7Z Archiefbestand niet gevonden - + CRC error on page (%1): some of the pages will not be displayed correctly CRC-fout op pagina (%1): sommige pagina's worden niet correct weergegeven - + Unknown error opening the file Onbekende fout bij het openen van het bestand - + + Format not supported Formaat niet ondersteund - - - Unsupported EPUB: %1 - - FolderContentView - Continue Reading... - Verder lezen... + Verder lezen... + + + + FolderInfoView + + + Unknown + Onbekend + + + + Items + Items + + + + Type + Type + + + + Reading status + Leesstatus + + + + Read + Gelezen + + + + Unread + Ongelezen + + + + Collection status + Collectiestatus + + + + Completed + Voltooid + + + + In progress + Bezig + + + + Added + Toegevoegd + + + + Updated + Bijgewerkt + + + + FolderManagementCoordinator + + + Add new folder + Nieuwe map toevoegen + + + + Folder name: + Mapnaam: GridComicsView - + Show info Toon informatie + + Library + Bibliotheek + + + Folder + Map + + + Favorites + Favorieten + + + Recently added + Onlangs toegevoegd + + + + Manga + Manga + + + + Western manga + Westerse manga + + + + Web comic + Webcomic + + + + Yonkoma + Yonkoma + + + + Comic + Grappig + + + + Unknown + Onbekend + HelpAboutDialog @@ -805,74 +986,90 @@ <p>De huidige bibliotheek wordt gecontroleerd op ontbrekende covers en onvolledige stripinformatie.</p><p>Dit kan enkele minuten duren. Je kunt het proces stoppen en later opnieuw uitvoeren.</p> + + LibraryInfoView + + + Library info + Bibliotheekinformatie + + + + Number of folders + Aantal mappen + + + + Number of comics + Aantal strips + + + + Number of read comics + Aantal gelezen strips + + + + LibraryManagementCoordinator + + + Error opening the library + Fout bij openen Bibliotheek + + + + Error creating the library + Fout bij aanmaken Bibliotheek + + + + Error updating the library + Fout bij bijwerken Bibliotheek + + LibraryWindow - + The selected folder doesn't contain any library. De geselecteerde map bevat geen bibliotheek. - + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? Deze bibliotheek is gemaakt met een vorige versie van YACReaderLibrary. Het moet worden bijgewerkt. Nu bijwerken? - - - Error opening the library - Fout bij openen Bibliotheek - Remove and delete metadata Verwijder metagegevens - + Old library Oude Bibliotheek - - Library - Bibliotheek - - - + This library was created with a newer version of YACReaderLibrary. Download the new version now? Deze bibliotheek is gemaakt met een nieuwere versie van YACReaderLibrary. Download de nieuwe versie? - + Library '%1' is no longer available. Do you want to remove it? Bibliotheek ' %1' is niet langer beschikbaar. Wilt u het verwijderen? - - Open folder... - Map openen ... - - - + Do you want remove Wilt u verwijderen - - Error updating the library - Fout bij bijwerken Bibliotheek - - - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? Bibliotheek ' %1' is gemaakt met een oudere versie van YACReaderLibrary. Zij moet opnieuw worden aangemaakt. Wilt u de bibliotheek nu aanmaken? - - Set as read - Instellen als gelezen - - - + Library not available Bibliotheek niet beschikbaar @@ -882,401 +1079,308 @@ YACReader Bibliotheek - - Error creating the library - Fout bij aanmaken Bibliotheek - - - + Update needed Bijwerken is nodig - + Library name already exists Bibliotheek naam bestaat al - + There is another library with the name '%1'. Er is al een bibliotheek met de naam ' %1 '. - + Download new version Nieuwe versie ophalen - + Delete comics Strips verwijderen - + All the selected comics will be deleted from your disk. Are you sure? Alle geselecteerde strips worden verwijderd van uw schijf. Weet u het zeker? - - - Set as unread - Instellen als ongelezen - - - + Library not found Bibliotheek niet gevonden - - - - manga - Manga - - - - - - comic - grappig - - - - - - western manga (left to right) - westerse manga (van links naar rechts) - - - - - - 4koma (top to botom) - 4koma (top to botom - 4koma (van boven naar beneden) - - - + library? Bibliotheek? - + Are you sure? Weet u het zeker? - - Rescan library for XML info - Bibliotheek opnieuw scannen op XML-info - - - - - - web comic - web-strip - - - - Add new folder - Nieuwe map toevoegen - - - + Delete folder Map verwijderen - - Set as uncompleted - Ingesteld als onvoltooid - - - - Set as completed - Instellen als voltooid - - - - Update folder - Map bijwerken - - - - Folder - Map - - - - Comic - Grappig - - - + Upgrade failed Upgrade mislukt - + There were errors during library upgrade in: Er zijn fouten opgetreden tijdens de bibliotheekupgrade in: - - + Copying comics... Strips kopiëren... - - + Moving comics... Strips verplaatsen... - + Folder name: Mapnaam: - + + + No folder selected Geen map geselecteerd - + + + Please, select a folder first Selecteer eerst een map - + Error in path Fout in pad - + There was an error accessing the folder's path Er is een fout opgetreden bij het verkrijgen van toegang tot het pad van de map - + The selected folder and all its contents will be deleted from your disk. Are you sure? De geselecteerde map en de volledige inhoud ervan worden van uw schijf verwijderd. Weet je het zeker? - - + + Unable to delete Kan niet verwijderen - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. - Er is een probleem opgetreden bij het verwijderen van de geselecteerde mappen. Controleer of er schrijfrechten zijn en zorg ervoor dat alle toepassingen deze mappen of een van de daarin opgenomen bestanden gebruiken. - - - - Add new reading lists - Voeg nieuwe leeslijsten toe - - - - - List name: - Lijstnaam: - - - - Delete list/label - Lijst/label verwijderen - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - Het geselecteerde item wordt verwijderd, uw strips of mappen worden NIET van uw schijf verwijderd. Weet je het zeker? + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + Er is een probleem opgetreden bij het verwijderen van de geselecteerde mappen. Controleer de schrijfrechten en zorg ervoor dat geen toepassingen deze mappen of bestanden daarin gebruiken. - - Rename list name - Hernoem de lijstnaam + + Rename or organize files + Bestanden hernoemen of ordenen - - - - - Set type - Soort instellen + + Set the type of the selected comics + Het type van de geselecteerde strips instellen - + Search filters Zoekfilters - + Unread Ongelezen - + In progress Bezig - + Highly rated Hoog gewaardeerd - + Recently added Onlangs toegevoegd - + Search syntax… Zoeksyntaxis… - + A repair of this library is already running (%1). Wait for it to finish. Er wordt al een herstel van deze bibliotheek uitgevoerd (%1). Wacht tot dit is voltooid. - + The library is locked by a repair that did not finish. De bibliotheek is vergrendeld door een herstel dat niet is voltooid. - + The library is locked by a repair started by %1. De bibliotheek is vergrendeld door een herstel gestart door %1. - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? Als u zeker weet dat er geen ander herstel bezig is, kan de vergrendeling worden verwijderd. Vergrendeling verwijderen en doorgaan? - + Package operation failed - + Pakketbewerking mislukt - + The covers package operation could not be completed. - + De bewerking van het omslagpakket kon niet worden voltooid. - + Restore recovery failed Herstel na onderbroken terugzetting mislukt - - Set custom cover - Aangepaste omslag instellen + + Rename folder + Map hernoemen - - Delete custom cover - Aangepaste omslag verwijderen + + Invalid folder name + Ongeldige mapnaam - - Save covers - Bewaar hoesjes + + The folder name is empty or contains characters that are not supported. + De mapnaam is leeg of bevat tekens die niet worden ondersteund. - - You are adding too many libraries. - U voegt te veel bibliotheken toe. + + + + Unable to rename folder + Kan de map niet hernoemen - - You are adding too many libraries. + + A file or folder named '%1' already exists. + Er bestaat al een bestand of map met de naam '%1'. + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. -You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. +Folder: %1 + De map kon niet op de schijf worden hernoemd. Controleer de mapnaam en de schrijfrechten. -YACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low. - U voegt te veel bibliotheken toe. - -Je hebt waarschijnlijk maar één bibliotheek nodig in je stripmap op het hoogste niveau. Je kunt door alle submappen bladeren met behulp van het mappengedeelte in de linkerzijbalk. - -YACReaderLibrary zal u er niet van weerhouden om meer bibliotheken te creëren, maar u moet het aantal bibliotheken laag houden. +Map: %1 - - - YACReader not found - YACReader niet gevonden + + The library database could not be updated. The folder rename on disk was reverted. + De database van de bibliotheek kon niet worden bijgewerkt. Het hernoemen van de map op de schijf is teruggedraaid. - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - YACReader niet gevonden. YACReader moet in dezelfde map worden geïnstalleerd als YACReaderLibrary. + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + De database van de bibliotheek kon niet worden bijgewerkt en het hernoemen van de map op de schijf kon niet worden teruggedraaid. De bibliotheek moet nu handmatig worden bijgewerkt. - - YACReader not found. There might be a problem with your YACReader installation. - YACReader niet gevonden. Er is mogelijk een probleem met uw YACReader-installatie. + + Save covers + Bewaar hoesjes - - Error - Fout + + You are adding too many libraries. + U voegt te veel bibliotheken toe. - - Error opening comic with third party reader. - Fout bij het openen van een strip met een lezer van een derde partij. + + You are adding too many libraries. + +You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. + +YACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low. + U voegt te veel bibliotheken toe. + +Je hebt waarschijnlijk maar één bibliotheek nodig in je stripmap op het hoogste niveau. Je kunt door alle submappen bladeren met behulp van het mappengedeelte in de linkerzijbalk. + +YACReaderLibrary zal u er niet van weerhouden om meer bibliotheken te creëren, maar u moet het aantal bibliotheken laag houden. - - + + YACReader library database (*.ydb) YACReader-bibliotheekdatabase (*.ydb) - + The library database backup was created at: %1 De back-up van de bibliotheekdatabase is gemaakt in: %1 - + Unable to create the library database backup: %1 De back-up van de bibliotheekdatabase kon niet worden gemaakt: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? Sluit YACReaderLibraryServer en alle andere YACReader-programma's die deze bibliotheek gebruiken voordat je deze herstelt. Doorgaan? - + Restoring library database... Bibliotheekdatabase wordt hersteld... - + The current library database is invalid. Restore the selected backup anyway? De huidige bibliotheekdatabase is ongeldig. De geselecteerde back-up toch herstellen? - - + + The library maintenance lock may be stale. Remove it and retry? Het onderhoudsslot van de bibliotheek is mogelijk verouderd. Verwijderen en opnieuw proberen? - + Restart YACReaderLibrary before attempting recovery again. @@ -1285,71 +1389,71 @@ Restart YACReaderLibrary before attempting recovery again. Start YACReaderLibrary opnieuw voordat je nogmaals herstel probeert. - + The library database was restored successfully. Update the library now? De bibliotheekdatabase is hersteld. De bibliotheek nu bijwerken? - + Library database damaged Bibliotheekdatabase beschadigd - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. De database van bibliotheek '%1' is beschadigd. Normale updates, onderhoud en back-ups zijn daarom niet beschikbaar. YACReader kan proberen de database te herstellen. Sommige beschadigde gegevens kunnen mogelijk niet worden hersteld. Bestaande back-ups worden niet gewijzigd. - + Attempt repair Herstel proberen - + Restore a backup... Een back-up herstellen... - + Repairing library database... Bibliotheekdatabase wordt hersteld... - - - + + + Library database repair Bibliotheekdatabase herstellen - + Another maintenance operation is currently using this library. Try again after it finishes. Een andere onderhoudsbewerking gebruikt deze bibliotheek momenteel. Probeer het opnieuw wanneer die is voltooid. - + The library database is already valid. De bibliotheekdatabase is al geldig. - + Library database repaired Bibliotheekdatabase hersteld - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 De bibliotheekdatabase is hersteld door de indexen opnieuw op te bouwen. Het beschadigde origineel is bewaard in: %1 - + Library database rebuilt Bibliotheekdatabase opnieuw opgebouwd - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1360,7 +1464,7 @@ Update the library now? De bibliotheek nu bijwerken? - + The damaged original was preserved at: @@ -1371,12 +1475,12 @@ Het beschadigde origineel is bewaard in: %1 - + Library database repair failed Herstel van bibliotheekdatabase mislukt - + The library database could not be repaired: %1%2 @@ -1387,62 +1491,62 @@ You can restore a backup from the Library menu or recreate the library. Je kunt een back-up herstellen via het menu Bibliotheek of de bibliotheek opnieuw maken. - + Remove and delete metadata and backups Metagegevens en back-ups verwijderen en wissen - + Library info Bibliotheekinformatie - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. Er is een probleem opgetreden bij het verwijderen van de geselecteerde strips. Controleer of er schrijfrechten zijn voor de geselecteerde bestanden of de map waarin deze zich bevinden. - + Assign comics numbers Wijs stripnummers toe - + Assign numbers starting in: Nummers toewijzen beginnend met: - + Invalid image Ongeldige afbeelding - + The selected file is not a valid image. Het geselecteerde bestand is geen geldige afbeelding. - + Error saving cover Fout bij opslaan van dekking - + There was an error saving the cover image. Er is een fout opgetreden bij het opslaan van de omslagafbeelding. - + Remove comics Verwijder strips - + Comics will only be deleted from the current label/list. Are you sure? Strips worden alleen verwijderd van het huidige label/de huidige lijst. Weet je het zeker? - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1454,763 +1558,1596 @@ Ontbrekende bestanden: %3 LibraryWindowActions - + Create a new library Maak een nieuwe Bibliotheek - + Open an existing library Open een bestaande Bibliotheek - - + + Export comics info Strip info exporteren - - + + Import comics info Strip info Importeren - + Pack covers Inpakken strip voorbladen - + Pack the covers of the selected library Inpakken alle strip voorbladen van de geselecteerde Bibliotheek - + Unpack covers Uitpakken voorbladen - + Unpack a catalog Uitpaken van een catalogus - + Update library Bibliotheek bijwerken - + Update current library Huidige Bibliotheek bijwerken - + Back up library database Back-up van bibliotheekdatabase maken - + Create a backup of the current library database Een back-up van de huidige bibliotheekdatabase maken - + Restore library database backup Back-up van bibliotheekdatabase herstellen - + Restore the current library database from a backup De huidige bibliotheekdatabase vanuit een back-up herstellen - + Repair covers and comic info Covers en stripinformatie herstellen - + Retry comics with missing covers or incomplete information Strips met ontbrekende covers of onvolledige informatie opnieuw verwerken - + Rename library Bibliotheek hernoemen - + Rename current library Huidige Bibliotheek hernoemen - + Remove library Bibliotheek verwijderen - + Remove current library from your collection De huidige Bibliotheek verwijderen uit uw verzameling - + Rescan library for XML info Bibliotheek opnieuw scannen op XML-info - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. Probeert XML-informatie te vinden die is ingebed in stripbestanden. U hoeft dit alleen te doen als de bibliotheek is gemaakt met versie 9.8.2 of eerdere versies of als u software van derden gebruikt om XML-informatie in de bestanden in te sluiten. - + Open library folder... Bibliotheekmap openen... - + Open the root folder of the current library De hoofdmap van de huidige bibliotheek openen - + Show library info Bibliotheekinfo tonen - + Show information about the current library Toon informatie over de huidige bibliotheek - + Open current comic Huidige strip openen - + Open current comic on YACReader Huidige strip openen in YACReader - + Save selected covers to... Geselecteerde omslagen opslaan in... - + Save covers of the selected comics as JPG files Sla covers van de geselecteerde strips op als JPG-bestanden - - + + Set as read Instellen als gelezen - + Set comic as read Strip Instellen als gelezen - - + + Set as unread Instellen als ongelezen - + Set comic as unread Strip Instellen als ongelezen - - + + manga Manga - + Set issue as manga Stel het probleem in als manga - - + + comic grappig - + Set issue as normal Stel het probleem in als normaal - + western manga westerse manga - + Set issue as western manga Stel het probleem in als westerse manga - - + + web comic web-strip - + Set issue as web comic Stel het probleem in als webstrip - - + + yonkoma yokoma - + Set issue as yonkoma Stel het probleem in als yonkoma - + Show/Hide marks Toon/Verberg markeringen - + Show or hide read marks Toon of verberg leesmarkeringen - + Show/Hide recent indicator Recente indicator tonen/verbergen - + Show or hide recent indicator Toon of verberg recente indicator - - + + Fullscreen mode on/off Volledig scherm modus aan/of - + Help, About YACReader Help, Over YACReader - + Add new folder Nieuwe map toevoegen - + Add new folder to the current library Voeg een nieuwe map toe aan de huidige bibliotheek - + + Rename folder + Map hernoemen + + + + Rename the current folder on disk and in the library + De huidige map hernoemen op de schijf en in de bibliotheek + + + Delete folder Map verwijderen - + Delete current folder from disk Verwijder de huidige map van schijf - + Select root node Selecteer de hoofd categorie - + Expand all nodes Alle categorieën uitklappen - + Collapse all nodes Vouw alle knooppunten samen - + Show options dialog Toon opties dialoog - + Show comics server options dialog Toon strips-server opties dialoog - - + + Change between comics views Wisselen tussen stripweergaven - + Open folder... Map openen ... - + + + Rename files... + Organize files + Bestanden hernoemen... + + + + + Organize into folders... + In mappen ordenen... + + + Set as uncompleted Ingesteld als onvoltooid - + Set as completed Instellen als voltooid - + Set custom cover Aangepaste omslag instellen - + Delete custom cover Aangepaste omslag verwijderen - + western manga (left to right) westerse manga (van links naar rechts) - + Open containing folder... Open map ... - Reset comic rating - Stripbeoordeling opnieuw instellen + Stripbeoordeling opnieuw instellen - + Select all comics Selecteer alle strips - + Edit Bewerken - + Assign current order to comics Wijs de huidige volgorde toe aan strips - + Update cover Strip omslagen bijwerken - + Delete selected comics Geselecteerde strips verwijderen - + Delete metadata from selected comics Verwijder metadata uit geselecteerde strips - + Download tags from Comic Vine Tags downloaden van Comic Vine - + Focus search line Focus zoeklijn - + Focus comics view Focus stripweergave - + Edit shortcuts Snelkoppelingen bewerken - + &Quit &Afsluiten - + Update folder Map bijwerken - + Update current folder Werk de huidige map bij - + Scan legacy XML metadata Scan oudere XML-metagegevens - + Add new reading list Nieuwe leeslijst toevoegen - + Add a new reading list to the current library Voeg een nieuwe leeslijst toe aan de huidige bibliotheek - + Remove reading list Leeslijst verwijderen - + Remove current reading list from the library Verwijder de huidige leeslijst uit de bibliotheek - - Add new label - Nieuw etiket toevoegen + + Add new label + Nieuw etiket toevoegen + + + + Add a new label to this library + Voeg een nieuw label toe aan deze bibliotheek + + + + Rename selected list + Hernoem de geselecteerde lijst + + + + Rename any selected labels or lists + Hernoem alle geselecteerde labels of lijsten + + + + Add to... + Toevoegen aan... + + + + Favorites + Favorieten + + + + Add selected comics to favorites list + Voeg geselecteerde strips toe aan de favorietenlijst + + + + + Reset rating + Beoordeling opnieuw instellen + + + + LibraryWindowMenus + + + comic + grappig + + + + manga + Manga + + + + western manga (left to right) + westerse manga (van links naar rechts) + + + + web comic + web-strip + + + + 4koma (top to botom) + 4koma (van boven naar beneden) + + + + + + + Set type + Soort instellen + + + + Library + Bibliotheek + + + + Folder + Map + + + + Comic + Grappig + + + + Open folder... + Map openen ... + + + + Update folder + Map bijwerken + + + + Rename folder + Map hernoemen + + + + Rename files... + Bestanden hernoemen... + + + + Organize into folders... + In mappen ordenen... + + + + Rescan library for XML info + Bibliotheek opnieuw scannen op XML-info + + + + Set as uncompleted + Ingesteld als onvoltooid + + + + Set as completed + Instellen als voltooid + + + + Set as read + Instellen als gelezen + + + + + Set as unread + Instellen als ongelezen + + + + Set custom cover + Aangepaste omslag instellen + + + + Delete custom cover + Aangepaste omslag verwijderen + + + + ListInfoView + + + 1 comic + 1 strip + + + + %1 comics + %1 strips + + + + Last day + Afgelopen dag + + + + Last %1 days + Afgelopen %1 dagen + + + + 1 sublist + 1 sublijst + + + + %1 sublists + %1 sublijsten + + + + LocalComicListModel + + + file name + bestandsnaam + + + + NoLibrariesWidget + + + create your first library + Maak uw eerste bibliotheek + + + + You don't have any libraries yet + Je hebt geen nog libraries + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <P>u kunt een bibliotheek maken in een willekeurige map, YACReaderLibrary importeert alle strips en mappen uit deze map. Alle bibliotheek aangemaakt in het verleden kan je openen. < /p> <p>vergeet niet dat u YACReader kan gebruiken als stand-alone applicatie voor het lezen van de strips op de computer. < /p> + + + + add an existing one + voeg een bestaande bibliotheek toe + + + + NoSearchResultsWidget + + + No results + Geen resultaten + + + + OptionsDialog + + + Appearance + Verschijning + + + + Options + Opties + + + + Language + Taal + + + + Application language + Applicatietaal + + + + System default + Standaard van het systeem + + + + Tray icon settings (experimental) + Instellingen voor ladepictogram (experimenteel) + + + + Close to tray + Dicht bij lade + + + + Start into the system tray + Begin in het systeemvak + + + + Edit Comic Vine API key + Bewerk de Comic Vine API-sleutel + + + + Comic Vine API key + Comic Vine API-sleutel + + + + ComicInfo.xml legacy support + ComicInfo.xml verouderde ondersteuning + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + Importeer metagegevens uit ComicInfo.xml wanneer u nieuwe strips toevoegt + + + + Consider 'recent' items added or updated since X days ago + Overweeg 'recente' items die sinds X dagen geleden zijn toegevoegd of bijgewerkt + + + + Third party reader + Lezer van derden + + + + Write {comic_file_path} where the path should go in the command + Schrijf {comic_file_path} waar het pad naartoe moet in de opdracht + + + + Clear + Duidelijk + + + + Update libraries at startup + Update bibliotheken bij het opstarten + + + + Try to detect changes automatically + Probeer wijzigingen automatisch te detecteren + + + + Update libraries periodically + Update bibliotheken regelmatig + + + + Interval: + Tijdsinterval: + + + + 30 minutes + 30 minuten + + + + 1 hour + 1 uur + + + + 2 hours + 2 uur + + + + 4 hours + 4 uur + + + + 8 hours + 8 uur + + + + 12 hours + 12 uur + + + + daily + dagelijks + + + + Update libraries at certain time + Update bibliotheken op een bepaald tijdstip + + + + Time: + Tijd: + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WAARSCHUWING! Tijdens bibliotheekupdates is schrijven naar de database uitgeschakeld! +Plan geen updates terwijl u de app mogelijk actief gebruikt. +During automatic updates the app will block some of the actions until the update is finished. +Om een ​​automatische update te stoppen, tikt u op de laadindicator naast de titel van Bibliotheken. + + + + Modifications detection + Detectie van wijzigingen + + + + Compare the modified date of files when updating a library (not recommended) + Vergelijk de wijzigingsdatum van bestanden bij het updaten van een bibliotheek (niet aanbevolen) + + + + Enable background image + Achtergrondafbeelding inschakelen + + + + Opacity level + Dekkingsniveau + + + + Blur level + Vervagingsniveau + + + + Use selected comic cover as background + Gebruik geselecteerde stripomslag als achtergrond + + + + Restore defautls + Standaardwaarden herstellen + + + + Background + Achtergrond + + + + Display continue reading banner + Toon de banner voor verder lezen + + + + Display current comic banner + Toon huidige stripbanner + + + + Continue reading + Lees verder + + + + Mix folders and comics + Mappen en strips mengen + + + + Start comics on a new row + Strips op een nieuwe rij beginnen + + + + Content + Inhoud + + + + Comic Flow + Comic Flow + + + + + Libraries + Bibliotheken + + + + Grid view + Rasterweergave + + + + General + Algemeen + + + + Restart is needed + Herstart is nodig + + + + OrganizeFiles + + + Renamed, %1 is already in use + Hernoemd, %1 is al in gebruik + + + + Missing metadata: %1 + Ontbrekende metagegevens: %1 + + + + %1 could not be created + %1 kon niet worden gemaakt + + + + OrganizeFilesCoordinator + + + + Organize files + Bestanden ordenen + + + + This folder does not contain any comics. + Deze map bevat geen strips. + + + + This library is busy: %1 + Deze bibliotheek is bezig: %1 + + + + the library database could not be opened + de database van de bibliotheek kon niet worden geopend + + + + the library database could not be locked for writing + de database van de bibliotheek kon niet worden vergrendeld om te schrijven + + + + a folder entry could not be restored + een mapvermelding kon niet worden hersteld + + + + a comic entry could not be updated + een stripvermelding kon niet worden bijgewerkt + + + + the library database could not be saved: %1 + de database van de bibliotheek kon niet worden opgeslagen: %1 + + + + the record of the last organize run could not be read + het verslag van de laatste ordening kon niet worden gelezen + + + + the folder %1 could not be created + de map %1 kon niet worden gemaakt + + + + %n file(s) could not be moved back + + %n bestand kon niet worden teruggezet + %n bestanden konden niet worden teruggezet + + + + + OrganizeFilesDialog + + Format: + Formaat: + + + + Organize files + Bestanden ordenen + + + + + Rename files + Bestanden hernoemen + + + + Preparing the preview... + Voorbeeld voorbereiden... + + + + &Filename format: + &Bestandsnaamopmaak: + + + + &Path format: + &Padopmaak: + + + + Filename format + Bestandsnaamopmaak + + + + Path format + Padopmaak + + + + Presets + Voorinstellingen + + + + Insert + Invoegen + + + + Optional part < > + Optioneel deel < > + + + + Disappears completely when the fields inside it are empty. + Verdwijnt volledig wanneer de velden erin leeg zijn. + + + + Padded number {number:000} + Nummer met voorloopnullen {number:000} + + + + Format help... + Hulp bij de opmaak... + + + + selected folder + geselecteerde map + + + + library root + hoofdmap van de bibliotheek + + + + Move into + Verplaatsen naar + + + + Reset changes + Wijzigingen terugzetten + + + + Remove selected + Selectie verwijderen + + + + Show unchanged + Ongewijzigde tonen + + + + New name + Nieuwe naam + + + + Renamed from + Vorige naam + + + + New location + Nieuwe locatie + + + + Moved from + Vorige locatie + + + + Remove from list + Uit de lijst verwijderen + + + + Move files + Bestanden verplaatsen + + + + Cancel + Annuleren + + + Copy the list + De lijst kopiëren - - Add a new label to this library - Voeg een nieuw label toe aan deze bibliotheek + + Undo + Ongedaan maken - - Rename selected list - Hernoem de geselecteerde lijst + Close + Sluiten - - Rename any selected labels or lists - Hernoem alle geselecteerde labels of lijsten + + Copy failure details + Foutdetails kopiëren - - Add to... - Toevoegen aan... + + Finish + Voltooien - - Favorites - Favorieten + + Remove preset + Voorinstelling verwijderen - - Add selected comics to favorites list - Voeg geselecteerde strips toe aan de favorietenlijst + + Save current format as preset... + Huidige opmaak als voorinstelling bewaren... - - - LocalComicListModel - - file name - bestandsnaam + + Reset to default format + Standaardopmaak herstellen - - - NoLibrariesWidget - - create your first library - Maak uw eerste bibliotheek + + Save preset + Voorinstelling bewaren - - You don't have any libraries yet - Je hebt geen nog libraries + + Preset name: + Naam voorinstelling: - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <P>u kunt een bibliotheek maken in een willekeurige map, YACReaderLibrary importeert alle strips en mappen uit deze map. Alle bibliotheek aangemaakt in het verleden kan je openen. < /p> <p>vergeet niet dat u YACReader kan gebruiken als stand-alone applicatie voor het lezen van de strips op de computer. < /p> + + A filename format cannot contain "/". Use Organize files to move comics into folders. + Een bestandsnaamopmaak mag geen "/" bevatten. Gebruik Bestanden ordenen om strips naar mappen te verplaatsen. - - add an existing one - voeg een bestaande bibliotheek toe + + This format cannot be used: %1 + Deze opmaak kan niet worden gebruikt: %1 - - - NoSearchResultsWidget - - No results - Geen resultaten + + new folder + nieuwe map - - - OptionsDialog - - Appearance - Verschijning + + This folder does not exist yet. It will be created. + Deze map bestaat nog niet. Ze wordt gemaakt. - - Options - Opties + + file not found + bestand niet gevonden - - Language - Taal + + This comic is in the library but not on disk. It is skipped. + Deze strip staat in de bibliotheek, maar niet op de schijf. Ze wordt overgeslagen. - - Application language - Applicatietaal + + name in use + naam in gebruik - - System default - Standaard van het systeem + + no metadata + geen metagegevens - - Tray icon settings (experimental) - Instellingen voor ladepictogram (experimenteel) + + already here + al hier - - Close to tray - Dicht bij lade + + This file is already in the right place. + Dit bestand staat al op de juiste plek. - - Start into the system tray - Begin in het systeemvak + + edited + bewerkt + + + + %n will be renamed + + %n wordt hernoemd + %n worden hernoemd + + + + + %n will move + + %n wordt verplaatst + %n worden verplaatst + + + + + %n unchanged + + %n ongewijzigd + %n ongewijzigd + + + + + %n renamed + + %n hernoemd + %n hernoemd + + + + + %n removed + + %n verwijderd + %n verwijderd + + + + + %n missing + + %n ontbreekt + %n ontbreken + + + + + %n new folder(s) + + %n nieuwe map + %n nieuwe mappen + + + + + %n manual change(s) kept + + %n handmatige wijziging behouden + %n handmatige wijzigingen behouden + - - Edit Comic Vine API key - Bewerk de Comic Vine API-sleutel + + Nothing would be renamed with this format. + Met deze opmaak wordt niets hernoemd. - - Comic Vine API key - Comic Vine API-sleutel + + Nothing would move with this format. + Met deze opmaak wordt niets verplaatst. + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + %n bestand wordt hernoemd. De mappen veranderen niet. U kunt dit daarna ongedaan maken. + %n bestanden worden hernoemd. De mappen veranderen niet. U kunt dit daarna ongedaan maken. + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + %n bestand wordt verplaatst naar %1. Dit wijzigt uw bestanden op de schijf. U kunt dit daarna ongedaan maken. + %n bestanden worden verplaatst naar %1. Dit wijzigt uw bestanden op de schijf. U kunt dit daarna ongedaan maken. + - - ComicInfo.xml legacy support - ComicInfo.xml verouderde ondersteuning + + Moving %1 of %2 +%3 + %1 van %2 wordt verplaatst +%3 - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics - Importeer metagegevens uit ComicInfo.xml wanneer u nieuwe strips toevoegt + + Updating the library... + Bibliotheek bijwerken... - - Consider 'recent' items added or updated since X days ago - Overweeg 'recente' items die sinds X dagen geleden zijn toegevoegd of bijgewerkt + + Restored name + Herstelde naam - - Third party reader - Lezer van derden + + + Moved back from + Terugverplaatst vanuit - - Write {comic_file_path} where the path should go in the command - Schrijf {comic_file_path} waar het pad naartoe moet in de opdracht + + + + + Status + Status - - Clear - Duidelijk + + Final name + Definitieve naam - - Update libraries at startup - Update bibliotheken bij het opstarten + + Previous name + Vorige naam - - Try to detect changes automatically - Probeer wijzigingen automatisch te detecteren + + Restored location + Herstelde locatie - - Update libraries periodically - Update bibliotheken regelmatig + + Final location + Definitieve locatie - - Interval: - Tijdsinterval: + + Previous location + Vorige locatie - - 30 minutes - 30 minuten + + Restored + Hersteld - - 1 hour - 1 uur + + Renamed + Hernoemd - - 2 hours - 2 uur + + Moved + Verplaatst - - 4 hours - 4 uur + + Undo failed: %1 + Ongedaan maken mislukt: %1 - - 8 hours - 8 uur + + Failed: %1 + Mislukt: %1 - - 12 hours - 12 uur + + Nothing was moved. + Er is niets verplaatst. - - daily - dagelijks + + The record this run could be undone from could not be written, so the run did not start: %1 + Het verslag waarmee deze bewerking ongedaan gemaakt kan worden, kon niet worden geschreven. Daarom is de bewerking niet gestart: %1 + + + + %n file(s) renamed. + + %n bestand hernoemd. + %n bestanden hernoemd. + + + + + %n file(s) moved into %1. + + %n bestand verplaatst naar %1. + %n bestanden verplaatst naar %1. + - - Update libraries at certain time - Update bibliotheken op een bepaald tijdstip + + The record of this run stopped early, so the run stopped with it: %1 + Het verslag van deze bewerking is vroegtijdig gestopt, daarom is de bewerking mee gestopt: %1 + + + + %n file(s) were not moved. + + %n bestand is niet verplaatst. + %n bestanden zijn niet verplaatst. + - - Time: - Tijd: + + The library database could not be updated: %1 + De database van de bibliotheek kon niet worden bijgewerkt: %1 - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WAARSCHUWING! Tijdens bibliotheekupdates is schrijven naar de database uitgeschakeld! -Plan geen updates terwijl u de app mogelijk actief gebruikt. -During automatic updates the app will block some of the actions until the update is finished. -Om een ​​automatische update te stoppen, tikt u op de laadindicator naast de titel van Bibliotheken. + + Use Undo to move the files back, or update the library to make it match the files. + Gebruik Ongedaan maken om de bestanden terug te zetten, of werk de bibliotheek bij zodat ze bij de bestanden past. + + + + %n empty folder(s) were removed. + + %n lege map is verwijderd. + %n lege mappen zijn verwijderd. + + + + + %n file(s) could not be moved. + + %n bestand kon niet worden verplaatst. + %n bestanden konden niet worden verplaatst. + - - Modifications detection - Detectie van wijzigingen + + Moving the files back... + Bestanden worden teruggezet... - - Compare the modified date of files when updating a library (not recommended) - Vergelijk de wijzigingsdatum van bestanden bij het updaten van een bibliotheek (niet aanbevolen) + + Moving back %1 of %2 +%3 + %1 van %2 wordt teruggezet +%3 - - Enable background image - Achtergrondafbeelding inschakelen + + Everything was moved back. + Alles is teruggezet. - - Opacity level - Dekkingsniveau + + The undo did not finish: %1 + Het ongedaan maken is niet voltooid: %1 - - Blur level - Vervagingsniveau + + Format help + Hulp bij de opmaak - - Use selected comic cover as background - Gebruik geselecteerde stripomslag als achtergrond + + Fields + Velden - - Restore defautls - Standaardwaarden herstellen + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + Elk veld staat tussen accolades en wordt vervangen door de metagegevens van de strip. Het menu Invoegen toont ze allemaal. - - Background - Achtergrond + + {series} gives %1 + {series} geeft %1 - - Display continue reading banner - Toon de banner voor verder lezen + + Optional parts + Optionele delen - - Display current comic banner - Toon huidige stripbanner + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + Een deel dat tussen de tekens < en > staat, verdwijnt volledig wanneer alle velden erin leeg zijn. Gebruik het voor leestekens die bij een veld horen, zoals haakjes of een nummerteken ervoor. Tekst aan het begin of het eind van een naam wordt ook zonder dit deel afgekapt. - - Continue reading - Lees verder + + {series} ({year}) with no year gives %1 + {series} ({year}) zonder jaar geeft %1 - - Comic Flow - Comic Flow + + {series}< ({year})> with no year gives %1 + {series}< ({year})> zonder jaar geeft %1 - - - Libraries - Bibliotheken + + Numbers + Nummers - - Grid view - Rasterweergave + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + Schrijf een dubbele punt en enkele nullen om het nummer aan te vullen. Zo blijven de nummers op volgorde in een bestandsbeheerder. - - General - Algemeen + + + Folders + Mappen - - Restart is needed - Herstart is nodig + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + Een bestandsnaamopmaak mag geen schuine streep bevatten. Elke strip blijft in de huidige map. Gebruik In mappen ordenen om strips te verplaatsen. + + + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + Elk deel dat door een schuine streep wordt gescheiden, wordt een map. Het laatste deel wordt de bestandsnaam. De oorspronkelijke extensie blijft altijd behouden. @@ -2381,12 +3318,12 @@ Om een ​​automatische update te stoppen, tikt u op de laadindicator naast de Opmerkingen: - + Invalid cover Ongeldige dekking - + The image is invalid. De afbeelding is ongeldig. @@ -2536,6 +3473,35 @@ Om een ​​automatische update te stoppen, tikt u op de laadindicator naast de Leeslijsten + + ReadingListManagementCoordinator + + + Add new reading lists + Voeg nieuwe leeslijsten toe + + + + + List name: + Lijstnaam: + + + + Delete list/label + Lijst/label verwijderen + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + Het geselecteerde item wordt verwijderd, uw strips of mappen worden NIET van uw schijf verwijderd. Weet je het zeker? + + + + Rename list name + Hernoem de lijstnaam + + RenameLibraryDialog @@ -3249,6 +4215,61 @@ Use quotes to include spaces in a value. volumebeschrijving niet beschikbaar + + SelectedComicsInfoView + + + Unknown + Onbekend + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + %1 strips geselecteerd + + + + Read + Gelezen + + + + In progress + Bezig + + + + Unread + Ongelezen + + + + Total pages + + + + + Total size + + + + + Series + Serie + + SeriesQuestion @@ -3270,53 +4291,53 @@ Use quotes to include spaces in a value. ServerConfigDialog - - + + Server connectivity Serververbinding - + Scan to connect Scan om verbinding te maken - + Devices on this network can reach your library at the address below. Apparaten op dit netwerk kunnen je bibliotheek bereiken via het onderstaande adres. - + IP address IP-adres - + Port Poort - + Web interface Webinterface - + Copy link Link kopiëren - + Open web UI Webinterface openen - + Enable the server Server inschakelen - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. YACReader is beschikbaar voor iOS en Android. Ontdek de app voor <a href='https://ios.yacreader.com'>iOS</a> of <a href='https://android.yacreader.com'>Android</a>. @@ -3325,7 +4346,7 @@ Use quotes to include spaces in a value. De server instellen - + Set port set port Poort instellen diff --git a/YACReaderLibrary/yacreaderlibrary_pt.ts b/YACReaderLibrary/yacreaderlibrary_pt.ts index cd7be4386..905d6d8bd 100644 --- a/YACReaderLibrary/yacreaderlibrary_pt.ts +++ b/YACReaderLibrary/yacreaderlibrary_pt.ts @@ -202,11 +202,22 @@ ClassicComicsView - + Hide comic flow Ocultar Comic Flow + + ComicFilesCoordinator + + Copying comics... + Copiando quadrinhos... + + + Moving comics... + Quadrinhos em movimento... + + ComicInfoView @@ -290,70 +301,99 @@ p/b + + ComicManagementCoordinator + + + + YACReader not found + YACReader não encontrado + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + YACReader não encontrado. YACReader deve ser instalado na mesma pasta que YACReaderLibrary. + + + + YACReader not found. There might be a problem with your YACReader installation. + YACReader não encontrado. Pode haver um problema com a instalação do YACReader. + + + + Error + Erro + + + + Error opening comic with third party reader. + Erro ao abrir o quadrinho com leitor de terceiros. + + ComicModel - + yes sim - + no não - + Title Título - + File Name Nome do arquivo - + Pages Páginas - + Size Tamanho - + Read Ler - + Current Page Página atual - + Publication Date Data de publicação - + Rating Avaliação - + Series Série - + Volume Tomo - + Story Arc Arco de história @@ -386,45 +426,53 @@ fechar - - - + + + Looking for volume... Procurando volume... - - + + comic %1 of %2 - %3 história em quadrinhos %1 de %2 - %3 - + %1 comics selected %1 quadrinhos selecionados - + Error connecting to ComicVine Erro ao conectar-se ao ComicVine - - + + Retrieving tags for : %1 Recuperando tags para: %1 - + Retrieving volume info... Recuperando informações de volume... - + Looking for comic... Procurando quadrinhos... + + ContinueReadingGridHeader + + + Continue Reading... + Continuar a ler... + + CreateLibraryDialog @@ -468,6 +516,14 @@ O caminho selecionado não existe ou não é um caminho válido. Certifique-se de ter acesso de gravação a esta pasta + + DBHelper + + + The folder entry could not be found in the library database. + A entrada da pasta não foi encontrada no banco de dados da biblioteca. + + EditShortcutsDialog @@ -504,6 +560,19 @@ Esta pasta ainda não contém quadrinhos + + EmptyInfoView + + + Nothing selected + Nada selecionado + + + + Select a comic or folder to see its information. + Selecione um quadrinho ou uma pasta para ver suas informações. + + EmptyLabelWidget @@ -617,46 +686,158 @@ FileComic - + 7z not found 7z não encontrado - + CRC error on page (%1): some of the pages will not be displayed correctly Erro CRC na página (%1): algumas páginas não serão exibidas corretamente - + Unknown error opening the file Erro desconhecido ao abrir o arquivo - + + Format not supported Formato não suportado - - - Unsupported EPUB: %1 - - FolderContentView - Continue Reading... - Continuar a ler... + Continuar a ler... + + + + FolderInfoView + + + Unknown + Desconhecido + + + + Items + Itens + + + + Type + Tipo + + + + Reading status + Status de leitura + + + + Read + Ler + + + + Unread + Não lidos + + + + Collection status + Status da coleção + + + + Completed + Concluído + + + + In progress + Em andamento + + + + Added + Adicionado + + + + Updated + Atualizado + + + + FolderManagementCoordinator + + + Add new folder + Adicionar nova pasta + + + + Folder name: + Nome da pasta: GridComicsView - + Show info Mostrar informações + + Library + Biblioteca + + + Folder + Pasta + + + Favorites + Favoritos + + + Recently added + Adicionados recentemente + + + + Manga + Mangá + + + + Western manga + Mangá ocidental + + + + Web comic + Quadrinho da web + + + + Yonkoma + Yonkoma + + + + Comic + Quadrinhos + + + + Unknown + Desconhecido + HelpAboutDialog @@ -806,34 +987,50 @@ - LibraryWindow + LibraryInfoView - - Library - Biblioteca + + Library info + Informações da biblioteca - - Open folder... - Abrir pasta... + + Number of folders + Número de pastas - - - - western manga (left to right) - mangá ocidental (da esquerda para a direita) + + Number of comics + Número de quadrinhos - - - - 4koma (top to botom) - 4koma (top to botom - 4koma (de cima para baixo) + + Number of read comics + Número de quadrinhos lidos + + + + LibraryManagementCoordinator + + + Error opening the library + Erro ao abrir a biblioteca + + + + Error creating the library + Erro ao criar a biblioteca + + + + Error updating the library + Erro ao atualizar a biblioteca + + + LibraryWindow - + Do you want remove Você deseja remover @@ -843,306 +1040,254 @@ Biblioteca YACReader - - - - manga - mangá - - - - - - comic - cômico - - - + Are you sure? Você tem certeza? - - Rescan library for XML info - Reanalisar biblioteca para informa??es XML - - - - Set as read - Definir como lido - - - - - Set as unread - Definir como não lido - - - - - - web comic - quadrinhos da web - - - - Add new folder - Adicionar nova pasta - - - + Delete folder Excluir pasta - - Set as uncompleted - Definir como incompleto - - - - Set as completed - Definir como concluído - - - - Update folder - Atualizar pasta - - - - Folder - Pasta - - - - Comic - Quadrinhos - - - + Upgrade failed Falha na atualização - + There were errors during library upgrade in: Ocorreram erros durante a atualização da biblioteca em: - + Restore recovery failed Falha na recuperação do restauro - + Update needed Atualização necessária - + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? Esta biblioteca foi criada com uma versão anterior do YACReaderLibrary. Ele precisa ser atualizado. Atualizar agora? - + Download new version Baixe a nova versão - + This library was created with a newer version of YACReaderLibrary. Download the new version now? Esta biblioteca foi criada com uma versão mais recente do YACReaderLibrary. Baixe a nova versão agora? - + Library not available Biblioteca não disponível - + Library '%1' is no longer available. Do you want to remove it? A biblioteca '%1' não está mais disponível. Você quer removê-lo? - + Old library Biblioteca antiga - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? A biblioteca '%1' foi criada com uma versão mais antiga do YACReaderLibrary. Deve ser criado novamente. Deseja criar a biblioteca agora? - - + Copying comics... Copiando quadrinhos... - - + Moving comics... Quadrinhos em movimento... - + Folder name: Nome da pasta: - + + + No folder selected Nenhuma pasta selecionada - + + + Please, select a folder first Por favor, selecione uma pasta primeiro - + Error in path Erro no caminho - + There was an error accessing the folder's path Ocorreu um erro ao acessar o caminho da pasta - + The selected folder and all its contents will be deleted from your disk. Are you sure? A pasta selecionada e todo o seu conteúdo serão excluídos do disco. Tem certeza? - - + + Unable to delete Não foi possível excluir - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. - Ocorreu um problema ao tentar excluir as pastas selecionadas. Por favor, verifique as permissões de gravação e certifique-se de que algum aplicativo esteja usando essas pastas ou qualquer um dos arquivos contidos. - - - - Add new reading lists - Adicione novas listas de leitura - - - - - List name: - Nome da lista: - - - - Delete list/label - Excluir lista/rótulo - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - O item selecionado será excluído, seus quadrinhos ou pastas NÃO serão excluídos do disco. Tem certeza? + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + Ocorreu um problema ao tentar excluir as pastas selecionadas. Por favor, verifique as permissões de gravação e certifique-se de que nenhum aplicativo esteja usando essas pastas ou qualquer um dos arquivos contidos. - - Rename list name - Renomear nome da lista + + Rename or organize files + Renomear ou organizar arquivos - - - - - Set type - Definir tipo + + Set the type of the selected comics + Definir o tipo dos quadrinhos selecionados - + Search filters Filtros de pesquisa - + Unread Não lidos - + In progress Em andamento - + Highly rated Bem avaliados - + Recently added Adicionados recentemente - + Search syntax… Sintaxe de pesquisa… - + A repair of this library is already running (%1). Wait for it to finish. Uma reparação desta biblioteca já está em execução (%1). Aguarde a conclusão. - + The library is locked by a repair that did not finish. A biblioteca está bloqueada por uma reparação que não terminou. - + The library is locked by a repair started by %1. A biblioteca está bloqueada por uma reparação iniciada por %1. - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? Se tem certeza de que nenhuma outra reparação está em execução, o bloqueio pode ser removido. Remover o bloqueio e continuar? - + Package operation failed - + Falha na operação de pacote - + The covers package operation could not be completed. - + Não foi possível concluir a operação com o pacote de capas. - - Set custom cover - Definir capa personalizada + + Rename folder + Renomear pasta - - Delete custom cover - Excluir capa personalizada + + Invalid folder name + Nome de pasta inválido + + + + The folder name is empty or contains characters that are not supported. + O nome da pasta está vazio ou contém caracteres que não são suportados. + + + + + + Unable to rename folder + Não foi possível renomear a pasta - + + A file or folder named '%1' already exists. + Já existe um arquivo ou pasta com o nome '%1'. + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. + +Folder: %1 + Não foi possível renomear a pasta no disco. Verifique o nome da pasta e as permissões de gravação. + +Pasta: %1 + + + + The library database could not be updated. The folder rename on disk was reverted. + Não foi possível atualizar o banco de dados da biblioteca. A renomeação da pasta no disco foi revertida. + + + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + Não foi possível atualizar o banco de dados da biblioteca nem reverter a renomeação da pasta no disco. Agora a biblioteca precisa ser atualizada manualmente. + + + Save covers Salvar capas - + You are adding too many libraries. Você está adicionando muitas bibliotecas. - + You are adding too many libraries. You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. @@ -1155,84 +1300,58 @@ Você provavelmente só precisa de uma biblioteca em sua pasta de quadrinhos de YACReaderLibrary não impedirá você de criar mais bibliotecas, mas você deve manter o número de bibliotecas baixo. - - - YACReader not found - YACReader não encontrado - - - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - YACReader não encontrado. YACReader deve ser instalado na mesma pasta que YACReaderLibrary. - - - - YACReader not found. There might be a problem with your YACReader installation. - YACReader não encontrado. Pode haver um problema com a instalação do YACReader. - - - - Error - Erro - - - - Error opening comic with third party reader. - Erro ao abrir o quadrinho com leitor de terceiros. - - - + Library not found Biblioteca não encontrada - + The selected folder doesn't contain any library. A pasta selecionada não contém nenhuma biblioteca. - - + + YACReader library database (*.ydb) Base de dados da biblioteca YACReader (*.ydb) - + The library database backup was created at: %1 A cópia de segurança da base de dados da biblioteca foi criada em: %1 - + Unable to create the library database backup: %1 Não foi possível criar a cópia de segurança da base de dados da biblioteca: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? Feche o YACReaderLibraryServer e qualquer outra aplicação YACReader que esteja a usar esta biblioteca antes de restaurar. Continuar? - + Restoring library database... A restaurar a base de dados da biblioteca... - + The current library database is invalid. Restore the selected backup anyway? A base de dados atual da biblioteca não é válida. Restaurar a cópia de segurança selecionada mesmo assim? - - + + The library maintenance lock may be stale. Remove it and retry? O bloqueio de manutenção da biblioteca pode estar obsoleto. Removê-lo e tentar novamente? - + Restart YACReaderLibrary before attempting recovery again. @@ -1241,71 +1360,71 @@ Restart YACReaderLibrary before attempting recovery again. Reinicie o YACReaderLibrary antes de tentar novamente a recuperação. - + The library database was restored successfully. Update the library now? A base de dados da biblioteca foi restaurada com êxito. Atualizar a biblioteca agora? - + Library database damaged Base de dados da biblioteca danificada - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. A base de dados da biblioteca '%1' está danificada, pelo que as atualizações, a manutenção e as cópias de segurança normais não estão disponíveis. O YACReader pode tentar reparar a base de dados. Alguns dados danificados poderão não ser recuperados. As cópias de segurança existentes não serão alteradas. - + Attempt repair Tentar reparar - + Restore a backup... Restaurar uma cópia de segurança... - + Repairing library database... A reparar a base de dados da biblioteca... - - - + + + Library database repair Reparação da base de dados da biblioteca - + Another maintenance operation is currently using this library. Try again after it finishes. Outra operação de manutenção está a usar esta biblioteca. Tente novamente quando terminar. - + The library database is already valid. A base de dados da biblioteca já é válida. - + Library database repaired Base de dados da biblioteca reparada - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 A base de dados da biblioteca foi reparada através da reconstrução dos índices. O original danificado foi preservado em: %1 - + Library database rebuilt Base de dados da biblioteca reconstruída - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1316,7 +1435,7 @@ Update the library now? Atualizar a biblioteca agora? - + The damaged original was preserved at: @@ -1327,12 +1446,12 @@ O original danificado foi preservado em: %1 - + Library database repair failed Falha ao reparar a base de dados da biblioteca - + The library database could not be repaired: %1%2 @@ -1343,12 +1462,12 @@ You can restore a backup from the Library menu or recreate the library. Pode restaurar uma cópia de segurança no menu Biblioteca ou recriar a biblioteca. - + library? biblioteca? - + Remove and delete metadata and backups Remover e eliminar metadados e cópias de segurança @@ -1357,92 +1476,77 @@ Pode restaurar uma cópia de segurança no menu Biblioteca ou recriar a bibliote Remover e excluir metadados - + Library info Informações da biblioteca - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. Ocorreu um problema ao tentar excluir os quadrinhos selecionados. Por favor, verifique as permissões de gravação nos arquivos selecionados ou na pasta que os contém. - + Assign comics numbers Atribuir números de quadrinhos - + Assign numbers starting in: Atribua números começando em: - + Invalid image Imagem inválida - + The selected file is not a valid image. O arquivo selecionado não é uma imagem válida. - + Error saving cover Erro ao salvar a capa - + There was an error saving the cover image. Ocorreu um erro ao salvar a imagem da capa. - - Error creating the library - Erro ao criar a biblioteca - - - - Error updating the library - Erro ao atualizar a biblioteca - - - - Error opening the library - Erro ao abrir a biblioteca - - - + Delete comics Excluir quadrinhos - + All the selected comics will be deleted from your disk. Are you sure? Todos os quadrinhos selecionados serão excluídos do seu disco. Tem certeza? - + Remove comics Remover quadrinhos - + Comics will only be deleted from the current label/list. Are you sure? Os quadrinhos serão excluídos apenas do rótulo/lista atual. Tem certeza? - + Library name already exists O nome da biblioteca já existe - + There is another library with the name '%1'. Existe outra biblioteca com o nome '%1'. - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1454,763 +1558,1596 @@ Arquivos ausentes: %3 LibraryWindowActions - + Create a new library Criar uma nova biblioteca - + Open an existing library Abrir uma biblioteca existente - - + + Export comics info Exportar informa??es dos quadrinhos - - + + Import comics info Importar informa??es dos quadrinhos - + Pack covers Empacotar capas - + Pack the covers of the selected library Pacote de capas da biblioteca selecionada - + Unpack covers Desempacotar capas - + Unpack a catalog Desempacotar um catálogo - + Update library Atualizar biblioteca - + Update current library Atualizar biblioteca atual - + Back up library database Criar cópia de segurança da base de dados - + Create a backup of the current library database Criar uma cópia de segurança da base de dados atual da biblioteca - + Restore library database backup Restaurar cópia de segurança da base de dados - + Restore the current library database from a backup Restaurar a base de dados atual da biblioteca a partir de uma cópia de segurança - + Repair covers and comic info Reparar capas e informações dos quadrinhos - + Retry comics with missing covers or incomplete information Processar novamente quadrinhos com capas ausentes ou informações incompletas - + Rename library Renomear biblioteca - + Rename current library Renomear biblioteca atual - + Remove library Remover biblioteca - + Remove current library from your collection Remover biblioteca atual da sua coleção - + Rescan library for XML info Reanalisar biblioteca para informa??es XML - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. Tenta encontrar informações XML incorporadas em arquivos de quadrinhos. Você só precisa fazer isso se a biblioteca foi criada com versões 9.8.2 ou anteriores ou se você estiver usando software de terceiros para incorporar informações XML nos arquivos. - + Open library folder... Abrir pasta da biblioteca... - + Open the root folder of the current library Abrir a pasta raiz da biblioteca atual - + Show library info Mostrar informa??es da biblioteca - + Show information about the current library Mostrar informações sobre a biblioteca atual - + Open current comic Abrir quadrinho atual - + Open current comic on YACReader Abrir quadrinho atual no YACReader - + Save selected covers to... Salvar capas selecionadas em... - + Save covers of the selected comics as JPG files Salve as capas dos quadrinhos selecionados como arquivos JPG - - + + Set as read Definir como lido - + Set comic as read Definir quadrinhos como lidos - - + + Set as unread Definir como não lido - + Set comic as unread Definir quadrinhos como não lidos - - + + manga mangá - + Set issue as manga Definir problema como mangá - - + + comic cômico - + Set issue as normal Defina o problema como normal - + western manga mangá ocidental - + Set issue as western manga Definir problema como mangá ocidental - - + + web comic quadrinhos da web - + Set issue as web comic Definir o problema como web comic - - + + yonkoma tira yonkoma - + Set issue as yonkoma Definir problema como yonkoma - + Show/Hide marks Mostrar/ocultar marcas - + Show or hide read marks Mostrar ou ocultar marcas de leitura - + Show/Hide recent indicator Mostrar/ocultar indicador recente - + Show or hide recent indicator Mostrar ou ocultar indicador recente - - + + Fullscreen mode on/off Modo tela cheia ativado/desativado - + Help, About YACReader Ajuda, Sobre o YACReader - + Add new folder Adicionar nova pasta - + Add new folder to the current library Adicionar nova pasta à biblioteca atual - + + Rename folder + Renomear pasta + + + + Rename the current folder on disk and in the library + Renomear a pasta atual no disco e na biblioteca + + + Delete folder Excluir pasta - + Delete current folder from disk Exclua a pasta atual do disco - + Select root node Selecionar raiz - + Expand all nodes Expandir todos - + Collapse all nodes Recolher todos os nós - + Show options dialog Mostrar opções - + Show comics server options dialog Mostrar caixa de diálogo de opções do servidor de quadrinhos - - + + Change between comics views Alterar entre visualizações de quadrinhos - + Open folder... Abrir pasta... - + + + Rename files... + Organize files + Renomear arquivos... + + + + + Organize into folders... + Organizar em pastas... + + + Set as uncompleted Definir como incompleto - + Set as completed Definir como concluído - + Set custom cover Definir capa personalizada - + Delete custom cover Excluir capa personalizada - + western manga (left to right) mangá ocidental (da esquerda para a direita) - + Open containing folder... Abrir a pasta contendo... - Reset comic rating - Redefinir classificação de quadrinhos + Redefinir classificação de quadrinhos - + Select all comics Selecione todos os quadrinhos - + Edit Editar - + Assign current order to comics Atribuir ordem atual aos quadrinhos - + Update cover Atualizar capa - + Delete selected comics Excluir quadrinhos selecionados - + Delete metadata from selected comics Excluir metadados dos quadrinhos selecionados - + Download tags from Comic Vine Baixe tags do Comic Vine - + Focus search line Linha de pesquisa de foco - + Focus comics view Visualização de quadrinhos em foco - + Edit shortcuts Editar atalhos - + &Quit &Qfato - + Update folder Atualizar pasta - + Update current folder Atualizar pasta atual - + Scan legacy XML metadata Digitalize metadados XML legados - + Add new reading list Adicionar nova lista de leitura - + Add a new reading list to the current library Adicione uma nova lista de leitura à biblioteca atual - + Remove reading list Remover lista de leitura - + Remove current reading list from the library Remover lista de leitura atual da biblioteca - - Add new label - Adicionar novo rótulo + + Add new label + Adicionar novo rótulo + + + + Add a new label to this library + Adicione um novo rótulo a esta biblioteca + + + + Rename selected list + Renomear lista selecionada + + + + Rename any selected labels or lists + Renomeie quaisquer rótulos ou listas selecionados + + + + Add to... + Adicionar à... + + + + Favorites + Favoritos + + + + Add selected comics to favorites list + Adicione quadrinhos selecionados à lista de favoritos + + + + + Reset rating + Redefinir classificação + + + + LibraryWindowMenus + + + comic + cômico + + + + manga + mangá + + + + western manga (left to right) + mangá ocidental (da esquerda para a direita) + + + + web comic + quadrinhos da web + + + + 4koma (top to botom) + 4koma (de cima para baixo) + + + + + + + Set type + Definir tipo + + + + Library + Biblioteca + + + + Folder + Pasta + + + + Comic + Quadrinhos + + + + Open folder... + Abrir pasta... + + + + Update folder + Atualizar pasta + + + + Rename folder + Renomear pasta + + + + Rename files... + Renomear arquivos... + + + + Organize into folders... + Organizar em pastas... + + + + Rescan library for XML info + Reanalisar biblioteca para informa??es XML + + + + Set as uncompleted + Definir como incompleto + + + + Set as completed + Definir como concluído + + + + Set as read + Definir como lido + + + + + Set as unread + Definir como não lido + + + + Set custom cover + Definir capa personalizada + + + + Delete custom cover + Excluir capa personalizada + + + + ListInfoView + + + 1 comic + 1 quadrinho + + + + %1 comics + %1 quadrinhos + + + + Last day + Último dia + + + + Last %1 days + Últimos %1 dias + + + + 1 sublist + 1 sublista + + + + %1 sublists + %1 sublistas + + + + LocalComicListModel + + + file name + nome do arquivo + + + + NoLibrariesWidget + + + You don't have any libraries yet + Você ainda não tem nenhuma biblioteca + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <p>Você pode criar uma biblioteca em qualquer pasta, YACReaderLibrary importará todos os quadrinhos e pastas desta pasta. Se você já criou alguma biblioteca, poderá abri-la.</p><p>Não se esqueça de que você pode usar o YACReader como um aplicativo independente para ler quadrinhos em seu computador.</p> + + + + create your first library + crie sua primeira biblioteca + + + + add an existing one + adicione um existente + + + + NoSearchResultsWidget + + + No results + Nenhum resultado + + + + OptionsDialog + + + Language + Idioma + + + + Application language + Idioma do aplicativo + + + + System default + Padrão do sistema + + + + Tray icon settings (experimental) + Configurações do ícone da bandeja (experimental) + + + + Close to tray + Perto da bandeja + + + + Start into the system tray + Comece na bandeja do sistema + + + + Edit Comic Vine API key + Editar chave da API Comic Vine + + + + Comic Vine API key + Chave de API do Comic Vine + + + + ComicInfo.xml legacy support + Suporte legado ComicInfo.xml + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + Importe metadados de ComicInfo.xml ao adicionar novos quadrinhos + + + + Consider 'recent' items added or updated since X days ago + Considere itens 'recentes' adicionados ou atualizados há X dias + + + + Third party reader + Leitor de terceiros + + + + Write {comic_file_path} where the path should go in the command + Escreva {comic_file_path} onde o caminho deve ir no comando + + + + Clear + Claro + + + + Update libraries at startup + Atualizar bibliotecas na inicialização + + + + Try to detect changes automatically + Tente detectar alterações automaticamente + + + + Update libraries periodically + Atualize bibliotecas periodicamente + + + + Interval: + Intervalo: + + + + 30 minutes + 30 minutos + + + + 1 hour + 1 hora + + + + 2 hours + 2 horas + + + + 4 hours + 4 horas + + + + 8 hours + 8 horas + + + + 12 hours + 12 horas + + + + daily + diário + + + + Update libraries at certain time + Atualizar bibliotecas em determinado momento + + + + Time: + Tempo: + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + AVISO! Durante as atualizações da biblioteca, as gravações no banco de dados são desativadas! +Não agende atualizações enquanto estiver usando o aplicativo ativamente. +Durante as atualizações automáticas, o aplicativo bloqueará algumas ações até que a atualização seja concluída. +Para interromper uma atualização automática, toque no indicador de carregamento próximo ao título Bibliotecas. + + + + Modifications detection + Detecção de modificações + + + + Compare the modified date of files when updating a library (not recommended) + Compare a data de modificação dos arquivos ao atualizar uma biblioteca (não recomendado) + + + + Enable background image + Ativar imagem de fundo + + + + Opacity level + Nível de opacidade + + + + Blur level + Nível de desfoque + + + + Use selected comic cover as background + Use a capa de quadrinhos selecionada como plano de fundo + + + + Restore defautls + Restaurar padrões + + + + Background + Fundo + + + + Display continue reading banner + Exibir banner para continuar lendo + + + + Display current comic banner + Exibir banner de quadrinhos atual + + + + Continue reading + Continuar lendo + + + + Mix folders and comics + Misturar pastas e quadrinhos + + + + Start comics on a new row + Iniciar quadrinhos em uma nova linha + + + + Content + Conteúdo + + + + Comic Flow + Comic Flow + + + + + Libraries + Bibliotecas + + + + Grid view + Visualização em grade + + + + General + Em geral + + + + Appearance + Aparência + + + + Options + Opções + + + + Restart is needed + Reiniciar é necessário + + + + OrganizeFiles + + + Renamed, %1 is already in use + Renomeado, %1 já está em uso + + + + Missing metadata: %1 + Metadados ausentes: %1 + + + + %1 could not be created + Não foi possível criar %1 + + + + OrganizeFilesCoordinator + + + + Organize files + Organizar arquivos + + + + This folder does not contain any comics. + Esta pasta não contém nenhum quadrinho. + + + + This library is busy: %1 + Esta biblioteca está ocupada: %1 + + + + the library database could not be opened + não foi possível abrir o banco de dados da biblioteca + + + + the library database could not be locked for writing + não foi possível bloquear o banco de dados da biblioteca para gravação + + + + a folder entry could not be restored + não foi possível restaurar uma entrada de pasta + + + + a comic entry could not be updated + não foi possível atualizar uma entrada de quadrinho + + + + the library database could not be saved: %1 + não foi possível salvar o banco de dados da biblioteca: %1 + + + + the record of the last organize run could not be read + não foi possível ler o registro da última organização + + + + the folder %1 could not be created + não foi possível criar a pasta %1 + + + + %n file(s) could not be moved back + + não foi possível mover %n arquivo de volta + não foi possível mover %n arquivos de volta + + + + + OrganizeFilesDialog + + Format: + Formatar: + + + + Organize files + Organizar arquivos + + + + + Rename files + Renomear arquivos + + + + Preparing the preview... + Preparando a pré-visualização... + + + + &Filename format: + &Formato do nome do arquivo: + + + + &Path format: + Formato do &caminho: + + + + Filename format + Formato do nome do arquivo + + + + Path format + Formato do caminho + + + + Presets + Predefinições + + + + Insert + Inserir + + + + Optional part < > + Parte opcional < > + + + + Disappears completely when the fields inside it are empty. + Desaparece completamente quando os campos dentro dela estão vazios. + + + + Padded number {number:000} + Número com zeros {number:000} + + + + Format help... + Ajuda sobre o formato... + + + + selected folder + pasta selecionada + + + + library root + raiz da biblioteca + + + + Move into + Mover para + + + + Reset changes + Descartar as alterações + + + + Remove selected + Remover os selecionados + + + + Show unchanged + Mostrar os que não mudam + + + + New name + Novo nome + + + + Renamed from + Nome anterior + + + + New location + Novo local + + + + Moved from + Local anterior + + + + Remove from list + Remover da lista + + + + Move files + Mover os arquivos + + + + Cancel + Cancelar + + + Copy the list + Copiar a lista - - Add a new label to this library - Adicione um novo rótulo a esta biblioteca + + Undo + Desfazer - - Rename selected list - Renomear lista selecionada + Close + Fechar - - Rename any selected labels or lists - Renomeie quaisquer rótulos ou listas selecionados + + Copy failure details + Copiar detalhes das falhas - - Add to... - Adicionar à... + + Finish + Concluir - - Favorites - Favoritos + + Remove preset + Remover predefinição - - Add selected comics to favorites list - Adicione quadrinhos selecionados à lista de favoritos + + Save current format as preset... + Salvar o formato atual como predefinição... - - - LocalComicListModel - - file name - nome do arquivo + + Reset to default format + Restaurar o formato padrão - - - NoLibrariesWidget - - You don't have any libraries yet - Você ainda não tem nenhuma biblioteca + + Save preset + Salvar predefinição - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <p>Você pode criar uma biblioteca em qualquer pasta, YACReaderLibrary importará todos os quadrinhos e pastas desta pasta. Se você já criou alguma biblioteca, poderá abri-la.</p><p>Não se esqueça de que você pode usar o YACReader como um aplicativo independente para ler quadrinhos em seu computador.</p> + + Preset name: + Nome da predefinição: - - create your first library - crie sua primeira biblioteca + + A filename format cannot contain "/". Use Organize files to move comics into folders. + Um formato de nome de arquivo não pode conter "/". Use Organizar arquivos para mover quadrinhos para pastas. - - add an existing one - adicione um existente + + This format cannot be used: %1 + Este formato não pode ser usado: %1 - - - NoSearchResultsWidget - - No results - Nenhum resultado + + new folder + pasta nova - - - OptionsDialog - - Language - Idioma + + This folder does not exist yet. It will be created. + Esta pasta ainda não existe. Ela será criada. - - Application language - Idioma do aplicativo + + file not found + arquivo não encontrado - - System default - Padrão do sistema + + This comic is in the library but not on disk. It is skipped. + Este quadrinho está na biblioteca, mas não está no disco. Ele será ignorado. - - Tray icon settings (experimental) - Configurações do ícone da bandeja (experimental) + + name in use + nome em uso - - Close to tray - Perto da bandeja + + no metadata + sem metadados - - Start into the system tray - Comece na bandeja do sistema + + already here + já está aqui - - Edit Comic Vine API key - Editar chave da API Comic Vine + + This file is already in the right place. + Este arquivo já está no lugar certo. - - Comic Vine API key - Chave de API do Comic Vine + + edited + editado + + + + %n will be renamed + + %n será renomeado + %n serão renomeados + + + + + %n will move + + %n será movido + %n serão movidos + + + + + %n unchanged + + %n sem alteração + %n sem alterações + + + + + %n renamed + + %n renomeado + %n renomeados + + + + + %n removed + + %n removido + %n removidos + + + + + %n missing + + %n ausente + %n ausentes + + + + + %n new folder(s) + + %n pasta nova + %n pastas novas + + + + + %n manual change(s) kept + + %n alteração manual mantida + %n alterações manuais mantidas + - - ComicInfo.xml legacy support - Suporte legado ComicInfo.xml + + Nothing would be renamed with this format. + Com este formato, nada seria renomeado. - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics - Importe metadados de ComicInfo.xml ao adicionar novos quadrinhos + + Nothing would move with this format. + Com este formato, nada seria movido. + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + %n arquivo será renomeado. As pastas não mudam. Você pode desfazer depois. + %n arquivos serão renomeados. As pastas não mudam. Você pode desfazer depois. + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + %n arquivo será movido para %1. Isso altera seus arquivos no disco. Você pode desfazer depois. + %n arquivos serão movidos para %1. Isso altera seus arquivos no disco. Você pode desfazer depois. + - - Consider 'recent' items added or updated since X days ago - Considere itens 'recentes' adicionados ou atualizados há X dias + + Moving %1 of %2 +%3 + Movendo %1 de %2 +%3 - - Third party reader - Leitor de terceiros + + Updating the library... + Atualizando a biblioteca... - - Write {comic_file_path} where the path should go in the command - Escreva {comic_file_path} onde o caminho deve ir no comando + + Restored name + Nome restaurado - - Clear - Claro + + + Moved back from + Movido de volta de - - Update libraries at startup - Atualizar bibliotecas na inicialização + + + + + Status + Estado - - Try to detect changes automatically - Tente detectar alterações automaticamente + + Final name + Nome final - - Update libraries periodically - Atualize bibliotecas periodicamente + + Previous name + Nome anterior - - Interval: - Intervalo: + + Restored location + Localização restaurada - - 30 minutes - 30 minutos + + Final location + Localização final - - 1 hour - 1 hora + + Previous location + Localização anterior - - 2 hours - 2 horas + + Restored + Restaurado - - 4 hours - 4 horas + + Renamed + Renomeado - - 8 hours - 8 horas + + Moved + Movido - - 12 hours - 12 horas + + Undo failed: %1 + Falha ao desfazer: %1 - - daily - diário + + Failed: %1 + Falha: %1 - - Update libraries at certain time - Atualizar bibliotecas em determinado momento + + Nothing was moved. + Nada foi movido. - - Time: - Tempo: + + The record this run could be undone from could not be written, so the run did not start: %1 + Não foi possível gravar o registro que permitiria desfazer esta execução, por isso ela não começou: %1 + + + + %n file(s) renamed. + + %n arquivo renomeado. + %n arquivos renomeados. + + + + + %n file(s) moved into %1. + + %n arquivo movido para %1. + %n arquivos movidos para %1. + - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. - AVISO! Durante as atualizações da biblioteca, as gravações no banco de dados são desativadas! -Não agende atualizações enquanto estiver usando o aplicativo ativamente. -Durante as atualizações automáticas, o aplicativo bloqueará algumas ações até que a atualização seja concluída. -Para interromper uma atualização automática, toque no indicador de carregamento próximo ao título Bibliotecas. + + The record of this run stopped early, so the run stopped with it: %1 + O registro desta execução parou antes do fim, por isso a execução parou junto: %1 + + + + %n file(s) were not moved. + + %n arquivo não foi movido. + %n arquivos não foram movidos. + - - Modifications detection - Detecção de modificações + + The library database could not be updated: %1 + Não foi possível atualizar o banco de dados da biblioteca: %1 - - Compare the modified date of files when updating a library (not recommended) - Compare a data de modificação dos arquivos ao atualizar uma biblioteca (não recomendado) + + Use Undo to move the files back, or update the library to make it match the files. + Use Desfazer para mover os arquivos de volta ou atualize a biblioteca para que ela corresponda aos arquivos. + + + + %n empty folder(s) were removed. + + %n pasta vazia foi removida. + %n pastas vazias foram removidas. + + + + + %n file(s) could not be moved. + + Não foi possível mover %n arquivo. + Não foi possível mover %n arquivos. + - - Enable background image - Ativar imagem de fundo + + Moving the files back... + Movendo os arquivos de volta... - - Opacity level - Nível de opacidade + + Moving back %1 of %2 +%3 + Movendo de volta %1 de %2 +%3 - - Blur level - Nível de desfoque + + Everything was moved back. + Tudo foi movido de volta. - - Use selected comic cover as background - Use a capa de quadrinhos selecionada como plano de fundo + + The undo did not finish: %1 + A ação de desfazer não foi concluída: %1 - - Restore defautls - Restaurar padrões + + Format help + Ajuda sobre o formato - - Background - Fundo + + Fields + Campos - - Display continue reading banner - Exibir banner para continuar lendo + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + Cada campo é escrito entre chaves e é substituído pelos metadados do quadrinho. O menu Inserir lista todos eles. - - Display current comic banner - Exibir banner de quadrinhos atual + + {series} gives %1 + {series} resulta em %1 - - Continue reading - Continuar lendo + + Optional parts + Partes opcionais - - Comic Flow - Comic Flow + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + Uma parte escrita entre os sinais < e > desaparece completamente quando todos os campos dentro dela estão vazios. Use-a para a pontuação que pertence a um campo, como parênteses ou um sinal de número inicial. O texto no início ou no fim de um nome é aparado sem ela. - - - Libraries - Bibliotecas + + {series} ({year}) with no year gives %1 + {series} ({year}) sem ano resulta em %1 - - Grid view - Visualização em grade + + {series}< ({year})> with no year gives %1 + {series}< ({year})> sem ano resulta em %1 - - General - Em geral + + Numbers + Números - - Appearance - Aparência + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + Escreva dois-pontos e alguns zeros para completar o número da edição. Assim as edições ficam em ordem em um gerenciador de arquivos. - - Options - Opções + + + Folders + Pastas - - Restart is needed - Reiniciar é necessário + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + Um formato de nome de arquivo não pode conter uma barra. Cada quadrinho fica na pasta atual. Use Organizar em pastas para mover quadrinhos. + + + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + Cada parte separada por uma barra vira uma pasta. A última parte vira o nome do arquivo. A extensão original é sempre mantida. @@ -2473,12 +3410,12 @@ Para interromper uma atualização automática, toque no indicador de carregamen Edite as informações dos quadrinhos selecionados - + Invalid cover Capa inválida - + The image is invalid. A imagem é inválida. @@ -2536,6 +3473,35 @@ Para interromper uma atualização automática, toque no indicador de carregamen Listas de leitura + + ReadingListManagementCoordinator + + + Add new reading lists + Adicione novas listas de leitura + + + + + List name: + Nome da lista: + + + + Delete list/label + Excluir lista/rótulo + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + O item selecionado será excluído, seus quadrinhos ou pastas NÃO serão excluídos do disco. Tem certeza? + + + + Rename list name + Renomear nome da lista + + RenameLibraryDialog @@ -3249,6 +4215,61 @@ Use quotes to include spaces in a value. descrição do volume indisponível + + SelectedComicsInfoView + + + Unknown + Desconhecido + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + %1 quadrinhos selecionados + + + + Read + Ler + + + + In progress + Em andamento + + + + Unread + Não lidos + + + + Total pages + + + + + Total size + + + + + Series + Série + + SeriesQuestion @@ -3270,7 +4291,7 @@ Use quotes to include spaces in a value. ServerConfigDialog - + Set port set port Definir porta @@ -3292,53 +4313,53 @@ Use quotes to include spaces in a value. Escolha um endereço IP - - + + Server connectivity Conectividade do servidor - + Scan to connect Digitalize para ligar - + Devices on this network can reach your library at the address below. Os dispositivos nesta rede podem aceder à sua biblioteca através do endereço abaixo. - + IP address Endereço IP - + Port Porta - + Web interface Interface web - + Copy link Copiar ligação - + Open web UI Abrir interface web - + Enable the server Ativar o servidor - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. O YACReader está disponível para iOS e Android. Descubra-o para <a href='https://ios.yacreader.com'>iOS</a> ou <a href='https://android.yacreader.com'>Android</a>. diff --git a/YACReaderLibrary/yacreaderlibrary_ru.ts b/YACReaderLibrary/yacreaderlibrary_ru.ts index fc6cbf292..7b1a46815 100644 --- a/YACReaderLibrary/yacreaderlibrary_ru.ts +++ b/YACReaderLibrary/yacreaderlibrary_ru.ts @@ -202,11 +202,22 @@ ClassicComicsView - + Hide comic flow Скрыть Comic Flow + + ComicFilesCoordinator + + Copying comics... + Скопировать комиксы... + + + Moving comics... + Переместить комиксы... + + ComicInfoView @@ -290,70 +301,99 @@ ч/б + + ComicManagementCoordinator + + + + YACReader not found + YACReader не найден + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + YACReader не найден. YACReader должен быть установлен в ту же папку, что и YACReaderLibrary. + + + + YACReader not found. There might be a problem with your YACReader installation. + YACReader не найден. Возможно, возникла проблема с установкой YACReader. + + + + Error + Ошибка + + + + Error opening comic with third party reader. + Ошибка при открытии комикса с помощью сторонней программы чтения. + + ComicModel - + no нет - + yes да - + Read Прочитано - + Series Ряд - + Volume Объем - + Story Arc Сюжетная арка - + Size Размер - + Pages Всего страниц - + Title Заголовок - + Current Page Текущая страница - + File Name Имя файла - + Publication Date Дата публикации - + Rating Рейтинг @@ -381,13 +421,13 @@ закрыть - - + + Retrieving tags for : %1 Получение тегов для : %1 - + Looking for comic... Поиск комикса... @@ -397,34 +437,42 @@ искать - - - + + + Looking for volume... Поиск информации... - - + + comic %1 of %2 - %3 комикс %1 of %2 - %3 - + %1 comics selected %1 было выбрано - + Error connecting to ComicVine Ошибка поключения к ComicVine - + Retrieving volume info... Получение информации... + + ContinueReadingGridHeader + + + Continue Reading... + Продолжить чтение... + + CreateLibraryDialog @@ -468,6 +516,14 @@ Путь не найден + + DBHelper + + + The folder entry could not be found in the library database. + Запись о папке не найдена в базе данных библиотеки. + + EditShortcutsDialog @@ -504,6 +560,19 @@ В этой папке еще нет комиксов + + EmptyInfoView + + + Nothing selected + Ничего не выбрано + + + + Select a comic or folder to see its information. + Выберите комикс или папку, чтобы просмотреть информацию. + + EmptyLabelWidget @@ -617,27 +686,23 @@ FileComic - + + Format not supported Формат не поддерживается - + 7z not found 7z не найден - + Unknown error opening the file Неизвестная ошибка при открытии файла - - Unsupported EPUB: %1 - - - - + CRC error on page (%1): some of the pages will not be displayed correctly Ошибка контрольной суммы CRC на странице (%1): некоторые страницы будут отображаться неправильно @@ -645,18 +710,134 @@ FolderContentView - Continue Reading... - Продолжить чтение... + Продолжить чтение... + + + + FolderInfoView + + + Unknown + Неизвестно + + + + Items + Элементы + + + + Type + Тип + + + + Reading status + Статус чтения + + + + Read + Прочитано + + + + Unread + Непрочитанные + + + + Collection status + Статус коллекции + + + + Completed + Завершено + + + + In progress + В процессе + + + + Added + Добавлено + + + + Updated + Обновлено + + + + FolderManagementCoordinator + + + Add new folder + Добавить новую папку + + + + Folder name: + Имя папки: GridComicsView - + Show info Показать информацию + + Library + Библиотека + + + Folder + Папка + + + Favorites + Избранное + + + Recently added + Недавно добавленные + + + + Manga + Манга + + + + Western manga + Западная манга + + + + Web comic + Веб-комикс + + + + Yonkoma + Ёнкома + + + + Comic + Комикс + + + + Unknown + Неизвестно + HelpAboutDialog @@ -805,163 +986,136 @@ <p>Текущая библиотека проверяется на отсутствующие обложки и неполные сведения о комиксах.</p><p>Это может занять несколько минут. Процесс можно остановить и запустить снова позже.</p> + + LibraryInfoView + + + Library info + Информация о библиотеке + + + + Number of folders + Количество папок + + + + Number of comics + Количество комиксов + + + + Number of read comics + Количество прочитанных комиксов + + + + LibraryManagementCoordinator + + + Error opening the library + Ошибка открытия библиотеки + + + + Error creating the library + Ошибка создания библиотеки + + + + Error updating the library + Ошибка обновления библиотеки + + LibraryWindow - + The selected folder doesn't contain any library. Выбранная папка не содержит ни одной библиотеки. - + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? Эта библиотека была создана с предыдущей версией YACReaderLibrary. Она должна быть обновлена. Обновить сейчас? - - Comic - Комикс - - - + Folder name: Имя папки: - + The selected folder and all its contents will be deleted from your disk. Are you sure? Выбранная папка и все ее содержимое будет удалено с вашего жёсткого диска. Вы уверены? - - Error opening the library - Ошибка открытия библиотеки - - - - - YACReader not found - YACReader не найден - - - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. Возникла проблема при удалении выбранных папок. Пожалуйста, проверьте права на запись и убедитесь что другие приложения не используют эти папки или файлы. - - - Rename list name - Изменить имя списка - Remove and delete metadata Удаление метаданных - + Old library Библиотека из старой версии YACreader - - Set as completed - Отметить как завершено - - - + There was an error accessing the folder's path Ошибка доступа к пути папки - - Library - Библиотека - - - + Comics will only be deleted from the current label/list. Are you sure? Комиксы будут удалены только из выбранного списка/ярлыка. Вы уверены? - + This library was created with a newer version of YACReaderLibrary. Download the new version now? Эта библиотека была создана новой версией YACReaderLibrary. Скачать новую версию сейчас? - - + Moving comics... Переместить комиксы... - - + Copying comics... Скопировать комиксы... - + Library '%1' is no longer available. Do you want to remove it? Библиотека '%1' больше не доступна. Вы хотите удалить ее? - - Open folder... - Открыть папку... - - - + Do you want remove Вы хотите удалить библиотеку - - Set as uncompleted - Отметить как не завершено - - - + Error in path Ошибка в пути - - Error updating the library - Ошибка обновления библиотеки - - - - Folder - Папка - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - Выбранные элементы будут удалены, ваши комиксы или папки НЕ БУДУТ удалены с вашего жёсткого диска. Вы уверены? - - - - - List name: - Имя списка: - - - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? Библиотека '%1' была создана старой версией YACReaderLibrary. Она должна быть вновь создана. Вы хотите создать библиотеку сейчас? - + Save covers Сохранить обложки - - Add new reading lists - Добавить новый список чтения - - - + You are adding too many libraries. You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. @@ -974,32 +1128,29 @@ YACReaderLibrary will not stop you from creating more libraries but you should k YACReaderLibrary не помешает вам создать больше библиотек, но вы должны иметь не большое количество библиотек. - - Set as read - Отметить как прочитано - - - + Library info Информация о библиотеке - + Assign comics numbers Порядковый номер - + + + Please, select a folder first Пожалуйста, сначала выберите папку - + Library not available Библиотека не доступна - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. Возникла проблема при удалении выбранных комиксов. Пожалуйста, проверьте права на запись для выбранных файлов или содержащую их папку. @@ -1009,293 +1160,262 @@ YACReaderLibrary не помешает вам создать больше биб Библиотека YACReader - - Error creating the library - Ошибка создания библиотеки - - - + You are adding too many libraries. Вы добавляете слишком много библиотек. - - Update folder - Обновить папку - - - + Update needed Необходимо обновление - + Library name already exists Имя папки уже используется - + There is another library with the name '%1'. Уже существует другая папка с именем '%1'. - + Delete folder Удалить папку - + Assign numbers starting in: Назначить порядковый номер начиная с: - + Download new version Загрузить новую версию - + Remove and delete metadata and backups Удалить библиотеку, метаданные и резервные копии - + Invalid image Неверное изображение - + The selected file is not a valid image. Выбранный файл не является допустимым изображением. - + Error saving cover Не удалось сохранить обложку. - + There was an error saving the cover image. Не удалось сохранить изображение обложки. - + Delete comics Удалить комиксы - - Add new folder - Добавить новую папку - - - - Delete list/label - Удалить список/ярлык - - - + + + No folder selected Ни одна папка не была выбрана - + All the selected comics will be deleted from your disk. Are you sure? Все выбранные комиксы будут удалены с вашего жёсткого диска. Вы уверены? - + Remove comics Убрать комиксы - - - Set as unread - Отметить как не прочитано - - - + Library not found Библиотека не найдена - - - - manga - манга - - - - - - comic - комикс - - - - - - web comic - веб-комикс - - - - - - western manga (left to right) - западная манга (слева направо) - - - - + + Unable to delete Не удалось удалить - - - - 4koma (top to botom) - 4кома (сверху вниз) + + Rename or organize files + Переименовать или упорядочить файлы + + + + Set the type of the selected comics + Задать тип выбранных комиксов - + Search filters Фильтры поиска - + Unread Непрочитанные - + In progress В процессе - + Highly rated С высокой оценкой - + Recently added Недавно добавленные - + Search syntax… Синтаксис поиска… - - - - - Set type - Тип установки - - - + A repair of this library is already running (%1). Wait for it to finish. Восстановление этой библиотеки уже выполняется (%1). Дождитесь его завершения. - + The library is locked by a repair that did not finish. Библиотека заблокирована незавершённым восстановлением. - + The library is locked by a repair started by %1. Библиотека заблокирована восстановлением, запущенным %1. - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? Если вы уверены, что никакое другое восстановление не выполняется, блокировку можно снять. Снять блокировку и продолжить? - + Package operation failed - + Не удалось выполнить операцию с пакетом - + The covers package operation could not be completed. - + Не удалось завершить операцию с пакетом обложек. - + Restore recovery failed Не удалось восстановиться после прерванного восстановления - - Set custom cover - Установить собственную обложку + + Rename folder + Переименовать папку - - Delete custom cover - Удалить пользовательскую обложку + + Invalid folder name + Недопустимое имя папки - - Error - Ошибка + + The folder name is empty or contains characters that are not supported. + Имя папки пустое или содержит неподдерживаемые символы. - - Error opening comic with third party reader. - Ошибка при открытии комикса с помощью сторонней программы чтения. + + + + Unable to rename folder + Не удалось переименовать папку - - - YACReader library database (*.ydb) + + A file or folder named '%1' already exists. + Файл или папка с именем «%1» уже существует. + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. + +Folder: %1 + Не удалось переименовать папку на диске. Проверьте имя папки и права на запись. + +Папка: %1 + + + + The library database could not be updated. The folder rename on disk was reverted. + Не удалось обновить базу данных библиотеки. Переименование папки на диске отменено. + + + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + Не удалось обновить базу данных библиотеки, и переименование папки на диске тоже не удалось отменить. Теперь библиотеку нужно обновить вручную. + + + + + YACReader library database (*.ydb) База данных библиотеки YACReader (*.ydb) - + The library database backup was created at: %1 Резервная копия базы данных библиотеки создана здесь: %1 - + Unable to create the library database backup: %1 Не удалось создать резервную копию базы данных библиотеки: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? Перед восстановлением закройте YACReaderLibraryServer и все другие приложения YACReader, использующие эту библиотеку. Продолжить? - + Restoring library database... Восстановление базы данных библиотеки... - + The current library database is invalid. Restore the selected backup anyway? Текущая база данных библиотеки повреждена. Всё равно восстановить выбранную резервную копию? - - + + The library maintenance lock may be stale. Remove it and retry? Файл блокировки обслуживания библиотеки может быть устаревшим. Удалить его и повторить попытку? - + Restart YACReaderLibrary before attempting recovery again. @@ -1304,71 +1424,71 @@ Restart YACReaderLibrary before attempting recovery again. Перезапустите YACReaderLibrary перед следующей попыткой восстановления. - + The library database was restored successfully. Update the library now? База данных библиотеки успешно восстановлена. Обновить библиотеку сейчас? - + Library database damaged База данных библиотеки повреждена - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. База данных библиотеки «%1» повреждена, поэтому обычные обновления, обслуживание и резервное копирование недоступны. YACReader может попытаться восстановить базу данных. Некоторые повреждённые данные могут быть утрачены. Существующие резервные копии не будут изменены. - + Attempt repair Попытаться восстановить - + Restore a backup... Восстановить резервную копию... - + Repairing library database... Восстановление базы данных библиотеки... - - - + + + Library database repair Восстановление базы данных библиотеки - + Another maintenance operation is currently using this library. Try again after it finishes. Сейчас эту библиотеку использует другая операция обслуживания. Повторите попытку после её завершения. - + The library database is already valid. База данных библиотеки уже исправна. - + Library database repaired База данных библиотеки восстановлена - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 База данных библиотеки восстановлена путём перестроения индексов. Повреждённый оригинал сохранён здесь: %1 - + Library database rebuilt База данных библиотеки перестроена - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1379,7 +1499,7 @@ Update the library now? Обновить библиотеку сейчас? - + The damaged original was preserved at: @@ -1390,12 +1510,12 @@ The damaged original was preserved at: %1 - + Library database repair failed Не удалось восстановить базу данных библиотеки - + The library database could not be repaired: %1%2 @@ -1406,42 +1526,27 @@ You can restore a backup from the Library menu or recreate the library. Можно восстановить резервную копию из меню «Библиотека» или создать библиотеку заново. - + library? ? - + Are you sure? Вы уверены? - - Rescan library for XML info - Повторное сканирование библиотеки для получения информации XML - - - + Upgrade failed Обновление не удалось - + There were errors during library upgrade in: При обновлении библиотеки возникли ошибки: - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - YACReader не найден. YACReader должен быть установлен в ту же папку, что и YACReaderLibrary. - - - - YACReader not found. There might be a problem with your YACReader installation. - YACReader не найден. Возможно, возникла проблема с установкой YACReader. - - - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1453,763 +1558,1612 @@ Missing files: %3 LibraryWindowActions - + Create a new library Создать новую библиотеку - + Open an existing library Открыть существующую библиотеку - - + + Export comics info Экспортировать информацию комикса - - + + Import comics info Импортировать информацию комикса - + Pack covers Запаковать обложки - + Pack the covers of the selected library Запаковать обложки выбранной библиотеки - + Unpack covers Распаковать обложки - + Unpack a catalog Распаковать каталог - + Update library Обновить библиотеку - + Update current library Обновить эту библиотеку - + Back up library database Создать резервную копию базы данных - + Create a backup of the current library database Создать резервную копию текущей базы данных библиотеки - + Restore library database backup Восстановить резервную копию базы данных - + Restore the current library database from a backup Восстановить текущую базу данных библиотеки из резервной копии - + Repair covers and comic info Восстановить обложки и сведения о комиксах - + Retry comics with missing covers or incomplete information Повторно обработать комиксы с отсутствующими обложками или неполными сведениями - + Rename library Переименовать библиотеку - + Rename current library Переименовать эту библиотеку - + Remove library Удалить библиотеку - + Remove current library from your collection Удалить эту библиотеку из своей коллекции - + Rescan library for XML info Повторное сканирование библиотеки для получения информации XML - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. Пытается найти информацию XML, встроенную в файлы комиксов. Это необходимо делать только в том случае, если библиотека была создана с помощью версии 9.8.2 или более ранней, или если вы используете стороннее программное обеспечение для встраивания информации XML в файлы. - + Open library folder... Открыть папку библиотеки... - + Open the root folder of the current library Открыть корневую папку текущей библиотеки - + Show library info Показать информацию о библиотеке - + Show information about the current library Показать информацию о текущей библиотеке - + Open current comic Открыть выбранный комикс - + Open current comic on YACReader Открыть комикс в YACReader - + Save selected covers to... Сохранить выбранные обложки в... - + Save covers of the selected comics as JPG files Сохранить обложки выбранных комиксов как JPG файлы - - + + Set as read Отметить как прочитано - + Set comic as read Отметить комикс как прочитано - - + + Set as unread Отметить как не прочитано - + Set comic as unread Отметить комикс как не прочитано - - + + manga манга - + Set issue as manga Установить выпуск как мангу - - + + comic комикс - + Set issue as normal Установите проблему как обычно - + western manga вестерн манга - + Set issue as western manga Установить выпуск как западную мангу - - + + web comic веб-комикс - + Set issue as web comic Установить выпуск как веб-комикс - - + + yonkoma йонкома - + Set issue as yonkoma Установить проблему как йонкома - + Show/Hide marks Показать/Спрятать пометки - + Show or hide read marks Показать или спрятать отметку прочтено - + Show/Hide recent indicator Показать/скрыть индикатор последних событий - + Show or hide recent indicator Показать или скрыть недавний индикатор - - + + Fullscreen mode on/off Полноэкранный режим включить/выключить - + Help, About YACReader О программе - + Add new folder Добавить новую папку - + Add new folder to the current library Добавить новую папку в текущую библиотеку - + + Rename folder + Переименовать папку + + + + Rename the current folder on disk and in the library + Переименовать текущую папку на диске и в библиотеке + + + Delete folder Удалить папку - + Delete current folder from disk Удалить выбранную папку с жёсткого диска - + Select root node Домашняя папка - + Expand all nodes Раскрыть все папки - + Collapse all nodes Свернуть все папки - + Show options dialog Настройки - + Show comics server options dialog Настройки сервера YACReader - - + + Change between comics views Изменение внешнего вида потока комиксов - + Open folder... Открыть папку... - + + + Rename files... + Organize files + Переименовать файлы... + + + + + Organize into folders... + Разложить по папкам... + + + Set as uncompleted Отметить как не завершено - + Set as completed Отметить как завершено - + Set custom cover Установить собственную обложку - + Delete custom cover Удалить пользовательскую обложку - + western manga (left to right) западная манга (слева направо) - + Open containing folder... Открыть выбранную папку... - Reset comic rating - Сбросить рейтинг комикса + Сбросить рейтинг комикса - + Select all comics Выбрать все комиксы - + Edit Редактировать информацию - + Assign current order to comics Назначить порядковый номер - + Update cover Обновить обложки - + Delete selected comics Удалить выбранное - + Delete metadata from selected comics Удалить метаданные из выбранных комиксов - + Download tags from Comic Vine Скачать теги из Comic Vine - + Focus search line Строка поиска фокуса - + Focus comics view Просмотр комиксов в фокусе - + Edit shortcuts Редактировать горячие клавиши - + &Quit &Qкостюм - + Update folder Обновить папку - + Update current folder Обновить выбранную папку - + Scan legacy XML metadata Сканировать устаревшие метаданные XML - - Add new reading list - Создать новый список чтения + + Add new reading list + Создать новый список чтения + + + + Add a new reading list to the current library + Создать новый список чтения + + + + Remove reading list + Удалить список чтения + + + + Remove current reading list from the library + Удалить выбранный ярлык/список чтения + + + + Add new label + Создать новый ярлык + + + + Add a new label to this library + Создать новый ярлык + + + + Rename selected list + Переименовать выбранный список + + + + Rename any selected labels or lists + Переименовать выбранный ярлык/список чтения + + + + Add to... + Добавить в... + + + + Favorites + Избранное + + + + Add selected comics to favorites list + Добавить выбранные комиксы в список избранного + + + + + Reset rating + Сбросить рейтинг + + + + LibraryWindowMenus + + + comic + комикс + + + + manga + манга + + + + western manga (left to right) + западная манга (слева направо) + + + + web comic + веб-комикс + + + + 4koma (top to botom) + 4кома (сверху вниз) + + + + + + + Set type + Тип установки + + + + Library + Библиотека + + + + Folder + Папка + + + + Comic + Комикс + + + + Open folder... + Открыть папку... + + + + Update folder + Обновить папку + + + + Rename folder + Переименовать папку + + + + Rename files... + Переименовать файлы... + + + + Organize into folders... + Разложить по папкам... + + + + Rescan library for XML info + Повторное сканирование библиотеки для получения информации XML + + + + Set as uncompleted + Отметить как не завершено + + + + Set as completed + Отметить как завершено + + + + Set as read + Отметить как прочитано + + + + + Set as unread + Отметить как не прочитано + + + + Set custom cover + Установить собственную обложку + + + + Delete custom cover + Удалить пользовательскую обложку + + + + ListInfoView + + + 1 comic + 1 комикс + + + + %1 comics + %1 комиксов + + + + Last day + Последний день + + + + Last %1 days + Последние %1 дней + + + + 1 sublist + 1 вложенный список + + + + %1 sublists + %1 вложенных списков + + + + LocalComicListModel + + + file name + имя файла + + + + NoLibrariesWidget + + + create your first library + создайте свою первую библиотеку + + + + You don't have any libraries yet + У вас нет ни одной библиотеки + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <p>Вы можете создать библиотеку в любой папке, YACReaderLibrary будет импортировать все комиксы и папки из этой папки. Если вы уже ранее создавали библиотеки, их можно будет открыть.< / p > <p>Не забывайте, что Вы можете использовать YACReader в качестве отдельного приложения для чтения комиксов на вашем компьютере.</п> + + + + add an existing one + добавить уже существующую + + + + NoSearchResultsWidget + + + No results + Нет результатов + + + + OptionsDialog + + + Restore defautls + Вернуть к первоначальным значениям + + + + Background + Фоновое изображение + + + + Blur level + Уровень размытия + + + + Enable background image + Включить фоновое изображение + + + + Options + Настройки + + + + Comic Vine API key + Comic Vine API ключ + + + + Edit Comic Vine API key + Редактировать Comic Vine API ключ + + + + Opacity level + Уровень непрозрачности + + + + General + Основные + + + + Use selected comic cover as background + Обложка комикса фоновое изображение + + + + Comic Flow + Comic Flow + + + + + Libraries + Библиотеки + + + + Grid view + Фоновое изображение + + + + Appearance + Появление + + + + Language + Язык + + + + Application language + Язык приложения + + + + System default + Системный по умолчанию + + + + Tray icon settings (experimental) + Настройки значков в трее (экспериментально) + + + + Close to tray + Рядом с лотком + + + + Start into the system tray + Запустите в системном трее + + + + ComicInfo.xml legacy support + Поддержка устаревших версий ComicInfo.xml + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + Импортируйте метаданные из ComicInfo.xml при добавлении новых комиксов. + + + + Consider 'recent' items added or updated since X days ago + Учитывайте «недавние» элементы, добавленные или обновленные X дней назад. + + + + Third party reader + Сторонний читатель + + + + Write {comic_file_path} where the path should go in the command + Напишите {comic_file_path}, где должен идти путь в команде. + + + + Clear + Очистить + + + + Update libraries at startup + Обновлять библиотеки при запуске + + + + Try to detect changes automatically + Попробуйте обнаружить изменения автоматически + + + + Update libraries periodically + Периодически обновляйте библиотеки + + + + Interval: + Интервал: + + + + 30 minutes + 30 минут + + + + 1 hour + 1 час + + + + 2 hours + 2 часа + + + + 4 hours + 4 часа + + + + 8 hours + 8 часов + + + + 12 hours + 12 часов + + + + daily + ежедневно + + + + Update libraries at certain time + Обновлять библиотеки в определенное время + + + + Time: + Время: + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + ПРЕДУПРЕЖДЕНИЕ! Во время обновления библиотеки запись в базу данных отключена! +Не планируйте обновления, пока вы активно используете приложение. +Во время автоматического обновления приложение будет блокировать некоторые действия до завершения обновления. +Чтобы остановить автоматическое обновление, нажмите на индикатор загрузки рядом с названием «Библиотеки». + + + + Modifications detection + Обнаружение модификаций + + + + Compare the modified date of files when updating a library (not recommended) + Сравните дату изменения файлов при обновлении библиотеки (не рекомендуется) + + + + Display continue reading banner + Отображение баннера продолжения чтения + + + + Display current comic banner + Отображать текущий комикс-баннер + + + + Continue reading + Продолжить чтение + + + + Mix folders and comics + Смешивать папки и комиксы + + + + Start comics on a new row + Начинать комиксы с новой строки + + + + Content + Содержимое + + + + Restart is needed + Требуется перезагрузка + + + + OrganizeFiles + + + Renamed, %1 is already in use + Переименовано, имя %1 уже занято + + + + Missing metadata: %1 + Отсутствуют метаданные: %1 + + + + %1 could not be created + Не удалось создать %1 + + + + OrganizeFilesCoordinator + + + + Organize files + Упорядочить файлы + + + + This folder does not contain any comics. + В этой папке нет комиксов. + + + + This library is busy: %1 + Эта библиотека занята: %1 + + + + the library database could not be opened + не удалось открыть базу данных библиотеки + + + + the library database could not be locked for writing + не удалось заблокировать базу данных библиотеки для записи + + + + a folder entry could not be restored + не удалось восстановить запись о папке + + + + a comic entry could not be updated + не удалось обновить запись о комиксе + + + + the library database could not be saved: %1 + не удалось сохранить базу данных библиотеки: %1 + + + + the record of the last organize run could not be read + не удалось прочитать запись о последней операции упорядочивания + + + + the folder %1 could not be created + не удалось создать папку %1 + + + + %n file(s) could not be moved back + + не удалось вернуть на место %n файл + не удалось вернуть на место %n файла + не удалось вернуть на место %n файлов + + + + + OrganizeFilesDialog + + Format: + Формат: + + + + Organize files + Упорядочить файлы + + + + + Rename files + Переименовать файлы + + + + Preparing the preview... + Подготовка предварительного просмотра... + + + + &Filename format: + &Формат имени файла: + + + + &Path format: + &Формат пути: + + + + Filename format + Формат имени файла + + + + Path format + Формат пути + + + + Presets + Шаблоны + + + + Insert + Вставить + + + + Optional part < > + Необязательная часть < > + + + + Disappears completely when the fields inside it are empty. + Полностью исчезает, если поля внутри пусты. + + + + Padded number {number:000} + Номер с нулями {number:000} + + + + Format help... + Справка по формату... + + + + selected folder + выбранная папка + + + + library root + корень библиотеки + + + + Move into + Переместить в + + + + Reset changes + Сбросить изменения + + + + Remove selected + Убрать выбранные + + + + Show unchanged + Показывать без изменений + + + + New name + Новое имя + + + + Renamed from + Прежнее имя + + + + New location + Новое расположение + + + + Moved from + Прежнее расположение + + + + Remove from list + Убрать из списка - - Add a new reading list to the current library - Создать новый список чтения + + Move files + Переместить файлы - - Remove reading list - Удалить список чтения + + Cancel + Отмена - - Remove current reading list from the library - Удалить выбранный ярлык/список чтения + Copy the list + Скопировать список - - Add new label - Создать новый ярлык + + Undo + Отменить - - Add a new label to this library - Создать новый ярлык + Close + Закрыть - - Rename selected list - Переименовать выбранный список + + Copy failure details + Копировать сведения об ошибках - - Rename any selected labels or lists - Переименовать выбранный ярлык/список чтения + + Finish + Завершить - - Add to... - Добавить в... + + Remove preset + Удалить шаблон - - Favorites - Избранное + + Save current format as preset... + Сохранить текущий формат как шаблон... - - Add selected comics to favorites list - Добавить выбранные комиксы в список избранного + + Reset to default format + Вернуть формат по умолчанию - - - LocalComicListModel - - file name - имя файла + + Save preset + Сохранить шаблон - - - NoLibrariesWidget - - create your first library - создайте свою первую библиотеку + + Preset name: + Название шаблона: - - You don't have any libraries yet - У вас нет ни одной библиотеки + + A filename format cannot contain "/". Use Organize files to move comics into folders. + Формат имени файла не может содержать "/". Используйте «Упорядочить файлы», чтобы переместить комиксы в папки. - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <p>Вы можете создать библиотеку в любой папке, YACReaderLibrary будет импортировать все комиксы и папки из этой папки. Если вы уже ранее создавали библиотеки, их можно будет открыть.< / p > <p>Не забывайте, что Вы можете использовать YACReader в качестве отдельного приложения для чтения комиксов на вашем компьютере.</п> + + This format cannot be used: %1 + Этот формат нельзя использовать: %1 - - add an existing one - добавить уже существующую + + new folder + новая папка - - - NoSearchResultsWidget - - No results - Нет результатов + + This folder does not exist yet. It will be created. + Этой папки ещё нет. Она будет создана. - - - OptionsDialog - - Restore defautls - Вернуть к первоначальным значениям + + file not found + файл не найден - - Background - Фоновое изображение + + This comic is in the library but not on disk. It is skipped. + Этот комикс есть в библиотеке, но отсутствует на диске. Он пропускается. - - Blur level - Уровень размытия + + name in use + имя занято - - Enable background image - Включить фоновое изображение + + no metadata + нет метаданных - - Options - Настройки + + already here + уже здесь - - Comic Vine API key - Comic Vine API ключ + + This file is already in the right place. + Этот файл уже находится в нужном месте. - - Edit Comic Vine API key - Редактировать Comic Vine API ключ + + edited + изменено + + + + %n will be renamed + + %n будет переименован + %n будут переименованы + %n будут переименованы + + + + + %n will move + + %n будет перемещён + %n будут перемещены + %n будут перемещены + + + + + %n unchanged + + %n без изменений + %n без изменений + %n без изменений + + + + + %n renamed + + %n переименован + %n переименованы + %n переименованы + + + + + %n removed + + %n убран + %n убраны + %n убраны + + + + + %n missing + + %n отсутствует + %n отсутствуют + %n отсутствуют + + + + + %n new folder(s) + + %n новая папка + %n новые папки + %n новых папок + + + + + %n manual change(s) kept + + Сохранено %n ручное изменение + Сохранено %n ручных изменения + Сохранено %n ручных изменений + - - Opacity level - Уровень непрозрачности + + Nothing would be renamed with this format. + С этим форматом ничего не будет переименовано. - - General - Основные + + Nothing would move with this format. + С этим форматом ничего не будет перемещено. + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + Будет переименован %n файл. Папки не изменятся. Потом это можно отменить. + Будет переименовано %n файла. Папки не изменятся. Потом это можно отменить. + Будет переименовано %n файлов. Папки не изменятся. Потом это можно отменить. + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + %n файл будет перемещён в %1. Это изменит ваши файлы на диске. Потом это можно отменить. + %n файла будут перемещены в %1. Это изменит ваши файлы на диске. Потом это можно отменить. + %n файлов будут перемещены в %1. Это изменит ваши файлы на диске. Потом это можно отменить. + - - Use selected comic cover as background - Обложка комикса фоновое изображение + + Moving %1 of %2 +%3 + Перемещение %1 из %2 +%3 - - Comic Flow - Comic Flow + + Updating the library... + Обновление библиотеки... - - - Libraries - Библиотеки + + Restored name + Восстановленное имя - - Grid view - Фоновое изображение + + + Moved back from + Перемещено обратно из - - Appearance - Появление + + + + + Status + Состояние - - Language - Язык + + Final name + Итоговое имя - - Application language - Язык приложения + + Previous name + Предыдущее имя - - System default - Системный по умолчанию + + Restored location + Восстановленное расположение - - Tray icon settings (experimental) - Настройки значков в трее (экспериментально) + + Final location + Итоговое расположение - - Close to tray - Рядом с лотком + + Previous location + Предыдущее расположение - - Start into the system tray - Запустите в системном трее + + Restored + Восстановлено - - ComicInfo.xml legacy support - Поддержка устаревших версий ComicInfo.xml + + Renamed + Переименовано - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics - Импортируйте метаданные из ComicInfo.xml при добавлении новых комиксов. + + Moved + Перемещено - - Consider 'recent' items added or updated since X days ago - Учитывайте «недавние» элементы, добавленные или обновленные X дней назад. + + Undo failed: %1 + Не удалось отменить: %1 - - Third party reader - Сторонний читатель + + Failed: %1 + Ошибка: %1 - - Write {comic_file_path} where the path should go in the command - Напишите {comic_file_path}, где должен идти путь в команде. + + Nothing was moved. + Ничего не перемещено. - - Clear - Очистить + + The record this run could be undone from could not be written, so the run did not start: %1 + Не удалось записать данные, по которым эту операцию можно было бы отменить, поэтому она не началась: %1 + + + + %n file(s) renamed. + + Переименован %n файл. + Переименовано %n файла. + Переименовано %n файлов. + + + + + %n file(s) moved into %1. + + %n файл перемещён в %1. + %n файла перемещены в %1. + %n файлов перемещены в %1. + - - Update libraries at startup - Обновлять библиотеки при запуске + + The record of this run stopped early, so the run stopped with it: %1 + Запись об этой операции прервалась, поэтому операция остановилась вместе с ней: %1 + + + + %n file(s) were not moved. + + %n файл не перемещён. + %n файла не перемещены. + %n файлов не перемещены. + - - Try to detect changes automatically - Попробуйте обнаружить изменения автоматически + + The library database could not be updated: %1 + Не удалось обновить базу данных библиотеки: %1 - - Update libraries periodically - Периодически обновляйте библиотеки + + Use Undo to move the files back, or update the library to make it match the files. + Нажмите «Отменить», чтобы вернуть файлы на место, или обновите библиотеку, чтобы она соответствовала файлам. + + + + %n empty folder(s) were removed. + + Удалена %n пустая папка. + Удалены %n пустые папки. + Удалено %n пустых папок. + + + + + %n file(s) could not be moved. + + Не удалось переместить %n файл. + Не удалось переместить %n файла. + Не удалось переместить %n файлов. + - - Interval: - Интервал: + + Moving the files back... + Возврат файлов на место... - - 30 minutes - 30 минут + + Moving back %1 of %2 +%3 + Возврат %1 из %2 +%3 - - 1 hour - 1 час + + Everything was moved back. + Все файлы возвращены на место. - - 2 hours - 2 часа + + The undo did not finish: %1 + Отмена не завершилась: %1 - - 4 hours - 4 часа + + Format help + Справка по формату - - 8 hours - 8 часов + + Fields + Поля - - 12 hours - 12 часов + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + Каждое поле пишется в фигурных скобках и заменяется метаданными комикса. Все поля перечислены в меню «Вставить». - - daily - ежедневно + + {series} gives %1 + {series} даёт %1 - - Update libraries at certain time - Обновлять библиотеки в определенное время + + Optional parts + Необязательные части - - Time: - Время: + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + Часть, записанная между знаками < и >, полностью исчезает, если все поля внутри неё пусты. Используйте её для знаков, которые относятся к полю, например для скобок или знака номера перед ним. Текст в начале и в конце имени обрезается и без неё. - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. - ПРЕДУПРЕЖДЕНИЕ! Во время обновления библиотеки запись в базу данных отключена! -Не планируйте обновления, пока вы активно используете приложение. -Во время автоматического обновления приложение будет блокировать некоторые действия до завершения обновления. -Чтобы остановить автоматическое обновление, нажмите на индикатор загрузки рядом с названием «Библиотеки». + + {series} ({year}) with no year gives %1 + {series} ({year}) без года даёт %1 - - Modifications detection - Обнаружение модификаций + + {series}< ({year})> with no year gives %1 + {series}< ({year})> без года даёт %1 - - Compare the modified date of files when updating a library (not recommended) - Сравните дату изменения файлов при обновлении библиотеки (не рекомендуется) + + Numbers + Номера - - Display continue reading banner - Отображение баннера продолжения чтения + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + Поставьте двоеточие и несколько нулей, чтобы дополнить номер выпуска. Тогда выпуски останутся по порядку в файловом менеджере. - - Display current comic banner - Отображать текущий комикс-баннер + + + Folders + Папки - - Continue reading - Продолжить чтение + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + Формат имени файла не может содержать косую черту. Каждый комикс остаётся в своей папке. Чтобы переместить комиксы, используйте «Разложить по папкам». - - Restart is needed - Требуется перезагрузка + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + Каждая часть, отделённая косой чертой, становится папкой. Последняя часть становится именем файла. Исходное расширение всегда сохраняется. @@ -2380,12 +3334,12 @@ To stop an automatic update tap on the loading indicator next to the Libraries t Заметки: - + Invalid cover Неверное покрытие - + The image is invalid. Изображение недействительно. @@ -2535,6 +3489,35 @@ To stop an automatic update tap on the loading indicator next to the Libraries t Списки чтения + + ReadingListManagementCoordinator + + + Add new reading lists + Добавить новый список чтения + + + + + List name: + Имя списка: + + + + Delete list/label + Удалить список/ярлык + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + Выбранные элементы будут удалены, ваши комиксы или папки НЕ БУДУТ удалены с вашего жёсткого диска. Вы уверены? + + + + Rename list name + Изменить имя списка + + RenameLibraryDialog @@ -3248,6 +4231,61 @@ Use quotes to include spaces in a value. тома + + SelectedComicsInfoView + + + Unknown + Неизвестно + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + %1 было выбрано + + + + Read + Прочитано + + + + In progress + В процессе + + + + Unread + Непрочитанные + + + + Total pages + + + + + Total size + + + + + Series + Ряд + + SeriesQuestion @@ -3269,53 +4307,53 @@ Use quotes to include spaces in a value. ServerConfigDialog - - + + Server connectivity Подключение к серверу - + Scan to connect Отсканируйте для подключения - + Devices on this network can reach your library at the address below. Устройства в этой сети могут получить доступ к вашей библиотеке по указанному ниже адресу. - + IP address IP-адрес - + Port Порт - + Web interface Веб-интерфейс - + Copy link Копировать ссылку - + Open web UI Открыть веб-интерфейс - + Enable the server Включить сервер - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. YACReader доступен для iOS и Android. Установите его для <a href='https://ios.yacreader.com'>iOS</a> или <a href='https://android.yacreader.com'>Android</a>. @@ -3332,7 +4370,7 @@ Use quotes to include spaces in a value. Сканируйте! - + Set port set port Установить порт diff --git a/YACReaderLibrary/yacreaderlibrary_source.ts b/YACReaderLibrary/yacreaderlibrary_source.ts index d9b1cbdc8..ee7a9843f 100644 --- a/YACReaderLibrary/yacreaderlibrary_source.ts +++ b/YACReaderLibrary/yacreaderlibrary_source.ts @@ -198,7 +198,7 @@ ClassicComicsView - + Hide comic flow @@ -286,70 +286,99 @@ + + ComicManagementCoordinator + + + + YACReader not found + + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + + + + + YACReader not found. There might be a problem with your YACReader installation. + + + + + Error + + + + + Error opening comic with third party reader. + + + ComicModel - + yes - + no - + Title - + File Name - + Pages - + Size - + Read - + Current Page - + Publication Date - + Rating - + Series - + Volume - + Story Arc @@ -382,45 +411,53 @@ - - - + + + Looking for volume... - - + + comic %1 of %2 - %3 - + %1 comics selected - + Error connecting to ComicVine - - + + Retrieving tags for : %1 - + Retrieving volume info... - + Looking for comic... + + ContinueReadingGridHeader + + + Continue Reading... + + + CreateLibraryDialog @@ -464,6 +501,14 @@ + + DBHelper + + + The folder entry could not be found in the library database. + + + EditShortcutsDialog @@ -500,6 +545,19 @@ + + EmptyInfoView + + + Nothing selected + + + + + Select a comic or folder to see its information. + + + EmptyLabelWidget @@ -613,46 +671,135 @@ FileComic - + 7z not found - + CRC error on page (%1): some of the pages will not be displayed correctly - + Unknown error opening the file - + + Format not supported + + + FolderInfoView + + + Unknown + + + + + Items + + + + + Type + + + + + Reading status + + + + + Read + + + + + Unread + + + + + Collection status + + + + + Completed + + + + + In progress + + + + + Added + + - - Unsupported EPUB: %1 + + Updated - FolderContentView + FolderManagementCoordinator - - Continue Reading... + + Add new folder + + + + + Folder name: GridComicsView - + Show info + + + Manga + + + + + Western manga + + + + + Web comic + + + + + Yonkoma + + + + + Comic + + + + + Unknown + + HelpAboutDialog @@ -802,497 +949,423 @@ - LibraryWindow - - - Library - - - - - Open folder... - - + LibraryInfoView - - - - western manga (left to right) - - - - - - - 4koma (top to botom) - 4koma (top to botom - - - - - Do you want remove + + Library info - - YACReader Library + + Number of folders - - - - manga + + Number of comics - - - - comic + + Number of read comics + + + LibraryManagementCoordinator - - Are you sure? + + Error opening the library - - Rescan library for XML info + + Error creating the library - - Set as read + + Error updating the library + + + LibraryWindow - - - Set as unread + + Do you want remove - - - - web comic + + YACReader Library - - Add new folder + + Are you sure? - + Delete folder - - Set as uncompleted - - - - - Set as completed - - - - - Update folder - - - - - Folder - - - - - Comic - - - - + Upgrade failed - + There were errors during library upgrade in: - + Restore recovery failed - + Update needed - + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? - + Download new version - + This library was created with a newer version of YACReaderLibrary. Download the new version now? - + Library not available - + Library '%1' is no longer available. Do you want to remove it? - + Old library - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? - - - Copying comics... - - - - - - Moving comics... - - - - + Folder name: - + + + No folder selected - + + + Please, select a folder first - + Error in path - + There was an error accessing the folder's path - + The selected folder and all its contents will be deleted from your disk. Are you sure? - - + + Unable to delete - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. - - - - - Add new reading lists - - - - - - List name: - - - - - Delete list/label - - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. - - Rename list name + + Rename or organize files - - - - - Set type + + Set the type of the selected comics - + Search filters - + Unread - + In progress - + Highly rated - + Recently added - + Search syntax… - + A repair of this library is already running (%1). Wait for it to finish. - + The library is locked by a repair that did not finish. - + The library is locked by a repair started by %1. - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? - + Package operation failed - + The covers package operation could not be completed. - - Set custom cover + + Rename folder - - Delete custom cover + + Invalid folder name - - Save covers + + The folder name is empty or contains characters that are not supported. - - You are adding too many libraries. + + + + Unable to rename folder - - You are adding too many libraries. - -You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. + + A file or folder named '%1' already exists. + + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. -YACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low. +Folder: %1 - - - YACReader not found + + The library database could not be updated. The folder rename on disk was reverted. - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. - - YACReader not found. There might be a problem with your YACReader installation. + + Save covers - - Error + + You are adding too many libraries. - - Error opening comic with third party reader. + + You are adding too many libraries. + +You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. + +YACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low. - + Library not found - + The selected folder doesn't contain any library. - - + + YACReader library database (*.ydb) - + The library database backup was created at: %1 - + Unable to create the library database backup: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? - + Restoring library database... - + The current library database is invalid. Restore the selected backup anyway? - - + + The library maintenance lock may be stale. Remove it and retry? - + Restart YACReaderLibrary before attempting recovery again. - + The library database was restored successfully. Update the library now? - + Library database damaged - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. - + Attempt repair - + Restore a backup... - + Repairing library database... - - - + + + Library database repair - + Another maintenance operation is currently using this library. Try again after it finishes. - + The library database is already valid. - + Library database repaired - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 - + Library database rebuilt - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1300,7 +1373,7 @@ Update the library now? - + The damaged original was preserved at: @@ -1308,12 +1381,12 @@ The damaged original was preserved at: - + Library database repair failed - + The library database could not be repaired: %1%2 @@ -1321,864 +1394,1674 @@ You can restore a backup from the Library menu or recreate the library. - + library? - + Remove and delete metadata and backups - + Library info - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. - + Assign comics numbers - + Assign numbers starting in: - + Invalid image - + The selected file is not a valid image. - + Error saving cover - + There was an error saving the cover image. - - Error creating the library - - - - - Error updating the library - - - - - Error opening the library - - - - + Delete comics - + All the selected comics will be deleted from your disk. Are you sure? - + Remove comics - + Comics will only be deleted from the current label/list. Are you sure? - + Library name already exists - + There is another library with the name '%1'. - + Repaired: %1 Failed: %2 Missing files: %3 + + + Copying comics... + + + + + Moving comics... + + LibraryWindowActions - + Create a new library Criar uma nova biblioteca - + Open an existing library Abrir uma biblioteca existente - - + + Export comics info - - + + Import comics info - + Pack covers - + Pack the covers of the selected library Pacote de capas da biblioteca selecionada - + Unpack covers - + Unpack a catalog Desempacotar um catálogo - + Update library - + Update current library Atualizar biblioteca atual - + Back up library database - + Create a backup of the current library database - + Restore library database backup - + Restore the current library database from a backup - + Repair covers and comic info - + Retry comics with missing covers or incomplete information - + Rename library - + Rename current library Renomear biblioteca atual - + Remove library - + Remove current library from your collection Remover biblioteca atual da sua coleção - + Rescan library for XML info - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. - + Open library folder... - + Open the root folder of the current library - + Show library info - + Show information about the current library - + Open current comic - + Open current comic on YACReader Abrir quadrinho atual no YACReader - + Save selected covers to... - + Save covers of the selected comics as JPG files - - + + Set as read - + Set comic as read - - + + Set as unread - + Set comic as unread - - + + manga - + Set issue as manga - - + + comic - + Set issue as normal - + western manga - + Set issue as western manga - - + + web comic - + Set issue as web comic - - + + yonkoma - - Set issue as yonkoma + + Set issue as yonkoma + + + + + Show/Hide marks + + + + + Show or hide read marks + + + + + Show/Hide recent indicator + + + + + Show or hide recent indicator + + + + + + Fullscreen mode on/off + + + + + Help, About YACReader + Ajuda, Sobre o YACReader + + + + Add new folder + + + + + Add new folder to the current library + + + + + Rename folder + + + + + Rename the current folder on disk and in the library + + + + + Delete folder + + + + + Delete current folder from disk + + + + + Select root node + Selecionar raiz + + + + Expand all nodes + Expandir todos + + + + Collapse all nodes + + + + + Show options dialog + Mostrar opções + + + + Show comics server options dialog + + + + + + Change between comics views + + + + + Open folder... + + + + + + Rename files... + Organize files + + + + + + Organize into folders... + + + + + Set as uncompleted + + + + + Set as completed + + + + + Set custom cover + + + + + Delete custom cover + + + + + western manga (left to right) + + + + + Open containing folder... + Abrir a pasta contendo... + + + + Select all comics + + + + + Edit + + + + + Assign current order to comics + + + + + Update cover + + + + + Delete selected comics + + + + + Delete metadata from selected comics + + + + + Download tags from Comic Vine + + + + + Focus search line + + + + + Focus comics view + + + + + Edit shortcuts + + + + + &Quit + + + + + Update folder + + + + + Update current folder + + + + + Scan legacy XML metadata + + + + + Add new reading list + + + + + Add a new reading list to the current library + + + + + Remove reading list + + + + + Remove current reading list from the library + + + + + Add new label + + + + + Add a new label to this library + + + + + Rename selected list + + + + + Rename any selected labels or lists + + + + + Add to... + + + + + Favorites + + + + + Add selected comics to favorites list + + + + + + Reset rating + + + + + LibraryWindowMenus + + + comic + + + + + manga + + + + + western manga (left to right) + + + + + web comic + + + + + 4koma (top to botom) + + + + + + + + Set type + + + + + Library + + + + + Folder + + + + + Comic + + + + + Open folder... + + + + + Update folder + + + + + Rename folder + + + + + Rename files... + + + + + Organize into folders... + + + + + Rescan library for XML info + + + + + Set as uncompleted + + + + + Set as completed + + + + + Set as read + + + + + + Set as unread + + + + + Set custom cover + + + + + Delete custom cover + + + + + ListInfoView + + + 1 comic + + + + + %1 comics + + + + + Last day + + + + + Last %1 days + + + + + 1 sublist + + + + + %1 sublists + + + + + LocalComicListModel + + + file name + + + + + NoLibrariesWidget + + + You don't have any libraries yet + + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + + + + + create your first library + + + + + add an existing one + + + + + NoSearchResultsWidget + + + No results + + + + + OptionsDialog + + + Language + + + + + Application language + + + + + System default + + + + + Tray icon settings (experimental) + + + + + Close to tray + + + + + Start into the system tray + + + + + Edit Comic Vine API key + + + + + Comic Vine API key + + + + + ComicInfo.xml legacy support + + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + + + + + Consider 'recent' items added or updated since X days ago + + + + + Third party reader + + + + + Write {comic_file_path} where the path should go in the command + + + + + Clear + + + + + Update libraries at startup + + + + + Try to detect changes automatically + + + + + Update libraries periodically + + + + + Interval: + + + + + 30 minutes + + + + + 1 hour + + + + + 2 hours + + + + + 4 hours + + + + + 8 hours + + + + + 12 hours + + + + + daily + + + + + Update libraries at certain time + + + + + Time: + + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + + + + + Modifications detection + + + + + Compare the modified date of files when updating a library (not recommended) + + + + + Enable background image + + + + + Opacity level + + + + + Blur level + + + + + Use selected comic cover as background + + + + + Restore defautls + + + + + Background + + + + + Display continue reading banner + + + + + Display current comic banner + + + + + Continue reading + + + + + Mix folders and comics + + + + + Start comics on a new row + + + + + Content + + + + + Comic Flow + + + + + + Libraries + + + + + Grid view + + + + + General - - Show/Hide marks + + Appearance - - Show or hide read marks + + Options - - Show/Hide recent indicator + + Restart is needed + + + OrganizeFiles - - Show or hide recent indicator + + Renamed, %1 is already in use - - - Fullscreen mode on/off + + Missing metadata: %1 - - Help, About YACReader - Ajuda, Sobre o YACReader - - - - Add new folder + + %1 could not be created + + + OrganizeFilesCoordinator - - Add new folder to the current library + + + Organize files - - Delete folder + + This folder does not contain any comics. - - Delete current folder from disk + + This library is busy: %1 - - Select root node - Selecionar raiz + + the library database could not be opened + - - Expand all nodes - Expandir todos + + the library database could not be locked for writing + - - Collapse all nodes + + a folder entry could not be restored - - Show options dialog - Mostrar opções + + a comic entry could not be updated + - - Show comics server options dialog + + the library database could not be saved: %1 - - - Change between comics views + + the record of the last organize run could not be read - - Open folder... + + the folder %1 could not be created + + + %n file(s) could not be moved back + + + + + + + + OrganizeFilesDialog - - Set as uncompleted + + Organize files - - Set as completed + + + Rename files - - Set custom cover + + Preparing the preview... - - Delete custom cover + + &Filename format: - - western manga (left to right) + + &Path format: - - Open containing folder... - Abrir a pasta contendo... + + Filename format + - - Reset comic rating + + Path format - - Select all comics + + Presets - - Edit + + Insert - - Assign current order to comics + + Optional part < > - - Update cover + + Disappears completely when the fields inside it are empty. - - Delete selected comics + + Padded number {number:000} - - Delete metadata from selected comics + + Format help... - - Download tags from Comic Vine + + selected folder - - Focus search line + + library root - - Focus comics view + + Move into - - Edit shortcuts + + Reset changes - - &Quit + + Remove selected - - Update folder + + Show unchanged - - Update current folder + + New name - - Scan legacy XML metadata + + Renamed from - - Add new reading list + + New location - - Add a new reading list to the current library + + Moved from - - Remove reading list + + Remove from list - - Remove current reading list from the library + + Move files - - Add new label + + Cancel - - Add a new label to this library + + Undo - - Rename selected list + + Copy failure details - - Rename any selected labels or lists + + Finish - - Add to... + + Remove preset - - Favorites + + Save current format as preset... - - Add selected comics to favorites list + + Reset to default format - - - LocalComicListModel - - file name + + Save preset - - - NoLibrariesWidget - - You don't have any libraries yet + + Preset name: - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + + A filename format cannot contain "/". Use Organize files to move comics into folders. - - create your first library + + This format cannot be used: %1 - - add an existing one + + new folder - - - NoSearchResultsWidget - - No results + + This folder does not exist yet. It will be created. - - - OptionsDialog - - Language + + file not found - - Application language + + This comic is in the library but not on disk. It is skipped. - - System default + + name in use - - Tray icon settings (experimental) + + no metadata - - Close to tray + + already here - - Start into the system tray + + This file is already in the right place. - - Edit Comic Vine API key + + edited + + + %n will be renamed + + + + + + + + %n will move + + + + + + + + %n unchanged + + + + + + + + %n renamed + + + + + + + + %n removed + + + + + + + + %n missing + + + + + + + + %n new folder(s) + + + + + + + + %n manual change(s) kept + + + + + - - Comic Vine API key + + Nothing would be renamed with this format. - - ComicInfo.xml legacy support + + Nothing would move with this format. + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + + + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + + + + - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics + + Moving %1 of %2 +%3 - - Consider 'recent' items added or updated since X days ago + + Updating the library... - - Third party reader + + Restored name - - Write {comic_file_path} where the path should go in the command + + + Moved back from - - Clear + + + + + Status - - Update libraries at startup + + Final name - - Try to detect changes automatically + + Previous name - - Update libraries periodically + + Restored location - - Interval: + + Final location - - 30 minutes + + Previous location - - 1 hour + + Restored - - 2 hours + + Renamed - - 4 hours + + Moved - - 8 hours + + Undo failed: %1 - - 12 hours + + Failed: %1 - - daily + + Nothing was moved. - - Update libraries at certain time + + The record this run could be undone from could not be written, so the run did not start: %1 + + + %n file(s) renamed. + + + + + + + + %n file(s) moved into %1. + + + + + - - Time: + + The record of this run stopped early, so the run stopped with it: %1 + + + %n file(s) were not moved. + + + + + - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. + + The library database could not be updated: %1 - - Modifications detection + + Use Undo to move the files back, or update the library to make it match the files. + + + %n empty folder(s) were removed. + + + + + + + + %n file(s) could not be moved. + + + + + - - Compare the modified date of files when updating a library (not recommended) + + Moving the files back... - - Enable background image + + Moving back %1 of %2 +%3 - - Opacity level + + Everything was moved back. - - Blur level + + The undo did not finish: %1 - - Use selected comic cover as background + + Format help - - Restore defautls + + Fields - - Background + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. - - Display continue reading banner + + {series} gives %1 - - Display current comic banner + + Optional parts - - Continue reading + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. - - Comic Flow + + {series} ({year}) with no year gives %1 - - - Libraries + + {series}< ({year})> with no year gives %1 - - Grid view + + Numbers - - General + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. - - Appearance + + + Folders - - Options + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. - - Restart is needed + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. @@ -2442,12 +3325,12 @@ To stop an automatic update tap on the loading indicator next to the Libraries t - + Invalid cover - + The image is invalid. @@ -2505,6 +3388,35 @@ To stop an automatic update tap on the loading indicator next to the Libraries t + + ReadingListManagementCoordinator + + + Add new reading lists + + + + + + List name: + + + + + Delete list/label + + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + + + + + Rename list name + + + RenameLibraryDialog @@ -3218,6 +4130,61 @@ Use quotes to include spaces in a value. + + SelectedComicsInfoView + + + Unknown + + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + + + + + Read + + + + + In progress + + + + + Unread + + + + + Total pages + + + + + Total size + + + + + Series + + + SeriesQuestion @@ -3239,59 +4206,59 @@ Use quotes to include spaces in a value. ServerConfigDialog - - + + Server connectivity - + Scan to connect - + Devices on this network can reach your library at the address below. - + IP address - + Port - + Set port set port - + Web interface - + Copy link - + Open web UI - + Enable the server - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. diff --git a/YACReaderLibrary/yacreaderlibrary_tr.ts b/YACReaderLibrary/yacreaderlibrary_tr.ts index 686de1618..57d239283 100644 --- a/YACReaderLibrary/yacreaderlibrary_tr.ts +++ b/YACReaderLibrary/yacreaderlibrary_tr.ts @@ -202,11 +202,22 @@ ClassicComicsView - + Hide comic flow Comic Flow'u gizle + + ComicFilesCoordinator + + Copying comics... + Çizgi romanlar kopyalanıyor... + + + Moving comics... + Çizgi romanlar taşınıyor... + + ComicInfoView @@ -290,70 +301,99 @@ Karakterler + + ComicManagementCoordinator + + + + YACReader not found + YACReader bulunamadı + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + YACReader bulunamadı. YACReader, YACReaderLibrary ile aynı klasöre kurulmalıdır. + + + + YACReader not found. There might be a problem with your YACReader installation. + YACReader bulunamadı. YACReader kurulumunuzda bir sorun olabilir. + + + + Error + Hata + + + + Error opening comic with third party reader. + Çizgi roman üçüncü taraf okuyucuyla açılırken hata oluştu. + + ComicModel - + no hayır - + yes evet - + Read Oku - + Size Boyut - + Pages Sayfalar - + Title Başlık - + File Name Dosya Adı - + Current Page Geçreli Sayfa - + Publication Date Yayın Tarihi - + Rating Reyting - + Series Seri - + Volume Hacim - + Story Arc Hikaye Arkı @@ -386,45 +426,53 @@ kapat - - - + + + Looking for volume... Sayılar aranıyor... - - + + comic %1 of %2 - %3 çizgi roman %1 / %2 - %3 - + %1 comics selected %1 çizgi roman seçildi - + Error connecting to ComicVine ComicVine sitesine bağlanılırken hata - - + + Retrieving tags for : %1 %1 için etiketler alınıyor - + Retrieving volume info... Sayı bilgileri alınıyor... - + Looking for comic... Çizgi romanlar aranıyor... + + ContinueReadingGridHeader + + + Continue Reading... + Okumaya Devam Et... + + CreateLibraryDialog @@ -468,6 +516,14 @@ Dizin bulunamadı + + DBHelper + + + The folder entry could not be found in the library database. + Klasör kaydı kütüphane veritabanında bulunamadı. + + EditShortcutsDialog @@ -504,6 +560,19 @@ Bu klasör henüz çizgi roman içermiyor + + EmptyInfoView + + + Nothing selected + Hiçbir şey seçilmedi + + + + Select a comic or folder to see its information. + Bilgilerini görmek için bir çizgi roman veya klasör seçin. + + EmptyLabelWidget @@ -617,46 +686,158 @@ FileComic - + 7z not found 7z bulunamadı - + CRC error on page (%1): some of the pages will not be displayed correctly CRC hatası, sayfada (%1): bazı sayfalar düzgün görüntülenmeyecek - + Unknown error opening the file Dosya açılırken bilinmeyen hata - + + Format not supported Dosya biçimi desteklenmiyor - - - Unsupported EPUB: %1 - - FolderContentView - Continue Reading... - Okumaya Devam Et... + Okumaya Devam Et... + + + + FolderInfoView + + + Unknown + Bilinmiyor + + + + Items + Öğeler + + + + Type + Tür + + + + Reading status + Okuma durumu + + + + Read + Oku + + + + Unread + Okunmamış + + + + Collection status + Koleksiyon durumu + + + + Completed + Tamamlandı + + + + In progress + Devam eden + + + + Added + Eklendi + + + + Updated + Güncellendi + + + + FolderManagementCoordinator + + + Add new folder + Yeni klasör ekle + + + + Folder name: + Klasör adı: GridComicsView - + Show info Bilgi göster + + Library + Kütüphane + + + Folder + Klasör + + + Favorites + Favoriler + + + Recently added + Yakın zamanda eklenen + + + + Manga + Manga + + + + Western manga + Batı mangası + + + + Web comic + Web çizgi romanı + + + + Yonkoma + Yonkoma + + + + Comic + Çizgi roman + + + + Unknown + Bilinmiyor + HelpAboutDialog @@ -805,75 +986,91 @@ <p>Geçerli kitaplıkta eksik kapaklar ve tamamlanmamış çizgi roman bilgileri denetleniyor.</p><p>Bu işlem birkaç dakika sürebilir. İşlemi durdurup daha sonra yeniden çalıştırabilirsiniz.</p> + + LibraryInfoView + + + Library info + Kütüphane bilgisi + + + + Number of folders + Klasör sayısı + + + + Number of comics + Çizgi roman sayısı + + + + Number of read comics + Okunan çizgi roman sayısı + + + + LibraryManagementCoordinator + + + Error opening the library + Haa kütüphanesini aç + + + + Error creating the library + Kütüphane oluşturma sorunu + + + + Error updating the library + Kütüphane güncelleme sorunu + + LibraryWindow - + The selected folder doesn't contain any library. Seçilen dosya kütüphanede yok. - + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? Bu kütüphane YACReaderKütüphabenin bir önceki versiyonun oluşturulmuş, güncellemeye ihtiyacın var. Şimdi güncellemek ister misin ? - - - Error opening the library - Haa kütüphanesini aç - Remove and delete metadata Metadata'yı kaldır ve sil - + Old library Eski kütüphane - - Library - Kütüphane - - - + This library was created with a newer version of YACReaderLibrary. Download the new version now? Bu kütüphane YACRKütüphanenin üst bir versiyonunda oluşturulmu. Yeni versiyonu indirmek ister misiniz ? - + Library '%1' is no longer available. Do you want to remove it? Kütüphane '%1'ulaşılabilir değil. Kaldırmak ister misin? - - Open folder... - Dosyayı aç... - - - + Do you want remove Kaldırmak ister misin - - Error updating the library - Kütüphane güncelleme sorunu - - - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? Kütüphane '%1 YACRKütüphanenin eski bir sürümünde oluşturulmuş, Kütüphaneyi yeniden oluşturmak ister misin? - - Set as read - Okundu olarak işaretle - - - + Library not available Kütüphane ulaşılabilir değil @@ -883,401 +1080,308 @@ YACReader Kütüphane - - Error creating the library - Kütüphane oluşturma sorunu - - - + Update needed Güncelleme gerekli - + Library name already exists Kütüphane ismi zaten alınmış - + There is another library with the name '%1'. Bu başka bir kütüphanenin adı '%1'. - + Download new version Yeni versiyonu indir - + Delete comics Çizgi romanları sil - + All the selected comics will be deleted from your disk. Are you sure? Seçilen tüm çizgi romanlar diskten silinecek emin misin ? - - - Set as unread - Hepsini okunmadı işaretle - - - + Library not found Kütüphane bulunamadı - - - - manga - manga t?r? - - - - - - comic - komik - - - - - - western manga (left to right) - Batı mangası (soldan sağa) - - - - - - 4koma (top to botom) - 4koma (top to botom - 4koma (yukarıdan aşağıya) - - - + library? kütüphane? - + Are you sure? Emin misin? - - Rescan library for XML info - XML bilgisi için kitaplığı yeniden tarayın - - - - - - web comic - web çizgi romanı - - - - Add new folder - Yeni klasör ekle - - - + Delete folder Klasörü sil - - Set as uncompleted - Tamamlanmamış olarak ayarla - - - - Set as completed - Tamamlanmış olarak ayarla - - - - Update folder - Klasörü güncelle - - - - Folder - Klasör - - - - Comic - Çizgi roman - - - + Upgrade failed Yükseltme başarısız oldu - + There were errors during library upgrade in: Kütüphane yükseltmesi sırasında hatalar oluştu: - - + Copying comics... Çizgi romanlar kopyalanıyor... - - + Moving comics... Çizgi romanlar taşınıyor... - + Folder name: Klasör adı: - + + + No folder selected Hiçbir klasör seçilmedi - + + + Please, select a folder first Lütfen, önce bir klasör seçiniz - + Error in path Yolda hata - + There was an error accessing the folder's path Klasörün yoluna erişilirken hata oluştu - + The selected folder and all its contents will be deleted from your disk. Are you sure? Seçilen klasör ve tüm içeriği diskinizden silinecek. Emin misin? - - + + Unable to delete Silinemedi - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. - Seçili klasörleri silmeye çalışırken bir sorun oluştu. Lütfen yazma izinlerini kontrol edin ve herhangi bir uygulamanın bu klasörleri veya içerdiği dosyalardan herhangi birini kullandığından emin olun. - - - - Add new reading lists - Yeni okuma listeleri ekle - - - - - List name: - Liste adı: - - - - Delete list/label - Listeyi/Etiketi sil - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - Seçilen öğe silinecek, çizgi romanlarınız veya klasörleriniz diskinizden SİLİNMEYECEKTİR. Emin misin? + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + Seçili klasörleri silmeye çalışırken bir sorun oluştu. Lütfen yazma izinlerini kontrol edin ve hiçbir uygulamanın bu klasörleri veya içerdikleri dosyaları kullanmadığından emin olun. - - Rename list name - Listeyi yeniden adlandır + + Rename or organize files + Dosyaları yeniden adlandır veya düzenle - - - - - Set type - Türü ayarla + + Set the type of the selected comics + Seçili çizgi romanların türünü ayarla - + Search filters Arama filtreleri - + Unread Okunmamış - + In progress Devam eden - + Highly rated Yüksek puanlı - + Recently added Yakın zamanda eklenen - + Search syntax… Arama söz dizimi… - + A repair of this library is already running (%1). Wait for it to finish. Bu kütüphanenin onarımı zaten çalışıyor (%1). Bitmesini bekleyin. - + The library is locked by a repair that did not finish. Kütüphane, tamamlanmamış bir onarım tarafından kilitlendi. - + The library is locked by a repair started by %1. Kütüphane, %1 tarafından başlatılan bir onarım tarafından kilitlendi. - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? Başka bir onarımın çalışmadığından eminseniz kilit kaldırılabilir. Kilit kaldırılıp devam edilsin mi? - + Package operation failed - + Paket işlemi başarısız oldu - + The covers package operation could not be completed. - + Kapak paketi işlemi tamamlanamadı. - + Restore recovery failed Geri yükleme kurtarması başarısız oldu - - Set custom cover - Özel kapak ayarla + + Rename folder + Klasörü yeniden adlandır - - Delete custom cover - Özel kapağı sil + + Invalid folder name + Geçersiz klasör adı - - Save covers - Kapakları kaydet + + The folder name is empty or contains characters that are not supported. + Klasör adı boş veya desteklenmeyen karakterler içeriyor. - - You are adding too many libraries. - Çok fazla kütüphane ekliyorsunuz. + + + + Unable to rename folder + Klasör yeniden adlandırılamıyor - - You are adding too many libraries. + + A file or folder named '%1' already exists. + '%1' adlı bir dosya veya klasör zaten var. + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. -You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. +Folder: %1 + Klasör diskte yeniden adlandırılamadı. Lütfen klasör adını ve yazma izinlerini denetleyin. -YACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low. - Çok fazla kütüphane ekliyorsunuz. - -Muhtemelen üst düzey çizgi roman klasörünüzde yalnızca bir kütüphaneye ihtiyacınız vardır, sol kenar çubuğundaki klasörler bölümünü kullanarak herhangi bir alt klasöre göz atabilirsiniz. - -YACReaderLibrary daha fazla kütüphane oluşturmanıza engel olmaz ancak kütüphane sayısını düşük tutmalısınız. +Klasör: %1 - - - YACReader not found - YACReader bulunamadı + + The library database could not be updated. The folder rename on disk was reverted. + Kütüphane veritabanı güncellenemedi. Klasörün diskteki yeni adı geri alındı. - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - YACReader bulunamadı. YACReader, YACReaderLibrary ile aynı klasöre kurulmalıdır. + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + Kütüphane veritabanı güncellenemedi ve klasörün diskteki yeni adı geri alınamadı. Kütüphanenin şimdi elle güncellenmesi gerekiyor. - - YACReader not found. There might be a problem with your YACReader installation. - YACReader bulunamadı. YACReader kurulumunuzda bir sorun olabilir. + + Save covers + Kapakları kaydet - - Error - Hata + + You are adding too many libraries. + Çok fazla kütüphane ekliyorsunuz. - - Error opening comic with third party reader. - Çizgi roman üçüncü taraf okuyucuyla açılırken hata oluştu. + + You are adding too many libraries. + +You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. + +YACReaderLibrary will not stop you from creating more libraries but you should keep the number of libraries low. + Çok fazla kütüphane ekliyorsunuz. + +Muhtemelen üst düzey çizgi roman klasörünüzde yalnızca bir kütüphaneye ihtiyacınız vardır, sol kenar çubuğundaki klasörler bölümünü kullanarak herhangi bir alt klasöre göz atabilirsiniz. + +YACReaderLibrary daha fazla kütüphane oluşturmanıza engel olmaz ancak kütüphane sayısını düşük tutmalısınız. - - + + YACReader library database (*.ydb) YACReader kitaplık veritabanı (*.ydb) - + The library database backup was created at: %1 Kitaplık veritabanı yedeği şu konumda oluşturuldu: %1 - + Unable to create the library database backup: %1 Kitaplık veritabanı yedeği oluşturulamadı: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? Geri yüklemeden önce YACReaderLibraryServer'ı ve bu kitaplığı kullanan diğer tüm YACReader uygulamalarını kapatın. Devam edilsin mi? - + Restoring library database... Kitaplık veritabanı geri yükleniyor... - + The current library database is invalid. Restore the selected backup anyway? Geçerli kitaplık veritabanı geçersiz. Seçilen yedek yine de geri yüklensin mi? - - + + The library maintenance lock may be stale. Remove it and retry? Kitaplık bakım kilidi eski kalmış olabilir. Kaldırıp yeniden denensin mi? - + Restart YACReaderLibrary before attempting recovery again. @@ -1286,71 +1390,71 @@ Restart YACReaderLibrary before attempting recovery again. Kurtarmayı yeniden denemeden önce YACReaderLibrary'yi yeniden başlatın. - + The library database was restored successfully. Update the library now? Kitaplık veritabanı başarıyla geri yüklendi. Kitaplık şimdi güncellensin mi? - + Library database damaged Kitaplık veritabanı hasarlı - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. '%1' kitaplığının veritabanı hasarlı olduğundan normal güncellemeler, bakım ve yedeklemeler kullanılamıyor. YACReader veritabanını onarmayı deneyebilir. Bazı hasarlı veriler kurtarılamayabilir. Mevcut yedekler değiştirilmeyecektir. - + Attempt repair Onarmayı dene - + Restore a backup... Bir yedeği geri yükle... - + Repairing library database... Kitaplık veritabanı onarılıyor... - - - + + + Library database repair Kitaplık veritabanını onar - + Another maintenance operation is currently using this library. Try again after it finishes. Başka bir bakım işlemi şu anda bu kitaplığı kullanıyor. İşlem bittikten sonra yeniden deneyin. - + The library database is already valid. Kitaplık veritabanı zaten geçerli. - + Library database repaired Kitaplık veritabanı onarıldı - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 Kitaplık veritabanı dizinleri yeniden oluşturularak onarıldı. Hasarlı özgün dosya şu konumda korundu: %1 - + Library database rebuilt Kitaplık veritabanı yeniden oluşturuldu - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1361,7 +1465,7 @@ Update the library now? Kitaplık şimdi güncellensin mi? - + The damaged original was preserved at: @@ -1372,12 +1476,12 @@ Hasarlı özgün dosya şu konumda korundu: %1 - + Library database repair failed Kitaplık veritabanı onarılamadı - + The library database could not be repaired: %1%2 @@ -1388,62 +1492,62 @@ You can restore a backup from the Library menu or recreate the library. Kitaplık menüsünden bir yedeği geri yükleyebilir veya kitaplığı yeniden oluşturabilirsiniz. - + Remove and delete metadata and backups Meta verileri ve yedekleri kaldır ve sil - + Library info Kütüphane bilgisi - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. Seçilen çizgi romanlar silinmeye çalışılırken bir sorun oluştu. Lütfen seçilen dosyalarda veya klasörleri içeren yazma izinlerini kontrol edin. - + Assign comics numbers Çizgi roman numaraları ata - + Assign numbers starting in: Şunlardan başlayarak numaralar ata: - + Invalid image Geçersiz resim - + The selected file is not a valid image. Seçilen dosya geçerli bir resim değil. - + Error saving cover Kapak kaydedilirken hata oluştu - + There was an error saving the cover image. Kapak resmi kaydedilirken bir hata oluştu. - + Remove comics Çizgi romanları kaldır - + Comics will only be deleted from the current label/list. Are you sure? Çizgi romanlar yalnızca mevcut etiketten/listeden silinecektir. Emin misin? - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1455,763 +1559,1580 @@ Eksik dosyalar: %3 LibraryWindowActions - + Create a new library Yeni kütüphane oluştur - + Open an existing library Çıkış kütüphanesini aç - - + + Export comics info Çizgi roman bilgilerini göster - - + + Import comics info Çizgi roman bilgilerini çıkart - + Pack covers Paket kapakları - + Pack the covers of the selected library Kütüphanede ki kapakları paketle - + Unpack covers Kapakları aç - + Unpack a catalog Kataloğu çkart - + Update library Kütüphaneyi güncelle - + Update current library Kütüphaneyi güncelle - + Back up library database Kitaplık veritabanını yedekle - + Create a backup of the current library database Geçerli kitaplık veritabanının yedeğini oluştur - + Restore library database backup Kitaplık veritabanı yedeğini geri yükle - + Restore the current library database from a backup Geçerli kitaplık veritabanını bir yedekten geri yükle - + Repair covers and comic info Kapakları ve çizgi roman bilgilerini onar - + Retry comics with missing covers or incomplete information Kapağı eksik veya bilgileri tamamlanmamış çizgi romanları yeniden işle - + Rename library Kütüphaneyi yeniden adlandır - + Rename current library Kütüphaneyi adlandır - + Remove library Kütüphaneyi sil - + Remove current library from your collection Kütüphaneyi koleksiyonundan kaldır - + Rescan library for XML info XML bilgisi için kitaplığı yeniden tarayın - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. Komik dosyalara gömülü XML bilgilerini bulmaya çalışır. Bunu yalnızca kitaplık 9.8.2 veya önceki sürümlerle oluşturulmuşsa veya XML bilgilerini dosyalara eklemek için üçüncü taraf yazılım kullanıyorsanız yapmanız gerekir. - + Open library folder... Kütüphane klasörünü aç... - + Open the root folder of the current library Geçerli kütüphanenin kök klasörünü aç - + Show library info Kitaplık bilgilerini göster - + Show information about the current library Geçerli kitaplık hakkındaki bilgileri göster - + Open current comic Seçili çizgi romanı aç - + Open current comic on YACReader YACReader'ı geçerli çizgi roman okuyucsu seç - + Save selected covers to... Seçilen kapakları şuraya kaydet... - + Save covers of the selected comics as JPG files Seçilen çizgi romanların kapaklarını JPG dosyaları olarak kaydet - - + + Set as read Okundu olarak işaretle - + Set comic as read Çizgi romanı okundu olarak işaretle - - + + Set as unread Hepsini okunmadı işaretle - + Set comic as unread Çizgi Romanı okunmadı olarak seç - - + + manga manga t?r? - + Set issue as manga Sayıyı manga olarak ayarla - - + + comic komik - + Set issue as normal Sayıyı normal olarak ayarla - + western manga batı mangası - + Set issue as western manga Konuyu western mangası olarak ayarla - - + + web comic web çizgi romanı - + Set issue as web comic Sorunu web çizgi romanı olarak ayarla - - + + yonkoma d?rt panelli - + Set issue as yonkoma Sorunu yonkoma olarak ayarla - + Show/Hide marks Altçizgileri aç/kapa - + Show or hide read marks Okundu işaretlerini göster yada gizle - + Show/Hide recent indicator Son göstergeyi Göster/Gizle - + Show or hide recent indicator Son göstergeyi göster veya gizle - - + + Fullscreen mode on/off Tam ekran modu açık/kapalı - + Help, About YACReader Yardım, Bigli, YACReader - + Add new folder Yeni klasör ekle - + Add new folder to the current library Geçerli kitaplığa yeni klasör ekle - + + Rename folder + Klasörü yeniden adlandır + + + + Rename the current folder on disk and in the library + Geçerli klasörü diskte ve kütüphanede yeniden adlandır + + + Delete folder Klasörü sil - + Delete current folder from disk Geçerli klasörü diskten sil - + Select root node Kökü seçin - + Expand all nodes Tüm düğümleri büyüt - + Collapse all nodes Tüm düğümleri kapat - + Show options dialog Ayarları göster - + Show comics server options dialog Çizgi romanların server ayarlarını göster - - + + Change between comics views Çizgi roman görünümleri arasında değiştir - + Open folder... Dosyayı aç... - + + + Rename files... + Organize files + Dosyaları yeniden adlandır... + + + + + Organize into folders... + Klasörlere düzenle... + + + Set as uncompleted Tamamlanmamış olarak ayarla - + Set as completed Tamamlanmış olarak ayarla - + Set custom cover Özel kapak ayarla - + Delete custom cover Özel kapağı sil - + western manga (left to right) Batı mangası (soldan sağa) - + Open containing folder... Klasör açılıyor... - Reset comic rating - Çizgi roman reytingini sıfırla + Çizgi roman reytingini sıfırla - + Select all comics Tüm çizgi romanları seç - + Edit Düzenle - + Assign current order to comics Geçerli sırayı çizgi romanlara ata - + Update cover Kapağı güncelle - + Delete selected comics Seçili çizgi romanları sil - + Delete metadata from selected comics Seçilen çizgi romanlardan meta verileri sil - + Download tags from Comic Vine Etiketleri Comic Vine sitesinden indir - + Focus search line Arama satırına odaklan - + Focus comics view Çizgi roman görünümüne odaklanın - + Edit shortcuts Kısayolları düzenle - + &Quit &Çıkış - + Update folder Klasörü güncelle - + Update current folder Geçerli klasörü güncelle - + Scan legacy XML metadata Eski XML meta verilerini tarayın - + Add new reading list Yeni okuma listesi ekle - + Add a new reading list to the current library Geçerli kitaplığa yeni bir okuma listesi ekle - + Remove reading list Okuma listesini kaldır - + Remove current reading list from the library Geçerli okuma listesini kütüphaneden kaldır - - Add new label - Yeni etiket ekle + + Add new label + Yeni etiket ekle + + + + Add a new label to this library + Bu kitaplığa yeni bir etiket ekle + + + + Rename selected list + Seçilen listeyi yeniden adlandır + + + + Rename any selected labels or lists + Seçilen etiketleri ya da listeleri yeniden adlandır + + + + Add to... + Şuraya ekle... + + + + Favorites + Favoriler + + + + Add selected comics to favorites list + Seçilen çizgi romanları favoriler listesine ekle + + + + + Reset rating + Puanı sıfırla + + + + LibraryWindowMenus + + + comic + komik + + + + manga + manga t?r? + + + + western manga (left to right) + Batı mangası (soldan sağa) + + + + web comic + web çizgi romanı + + + + 4koma (top to botom) + 4koma (yukarıdan aşağıya) + + + + + + + Set type + Türü ayarla + + + + Library + Kütüphane + + + + Folder + Klasör + + + + Comic + Çizgi roman + + + + Open folder... + Dosyayı aç... + + + + Update folder + Klasörü güncelle + + + + Rename folder + Klasörü yeniden adlandır + + + + Rename files... + Dosyaları yeniden adlandır... + + + + Organize into folders... + Klasörlere düzenle... + + + + Rescan library for XML info + XML bilgisi için kitaplığı yeniden tarayın + + + + Set as uncompleted + Tamamlanmamış olarak ayarla + + + + Set as completed + Tamamlanmış olarak ayarla + + + + Set as read + Okundu olarak işaretle + + + + + Set as unread + Hepsini okunmadı işaretle + + + + Set custom cover + Özel kapak ayarla + + + + Delete custom cover + Özel kapağı sil + + + + ListInfoView + + + 1 comic + 1 çizgi roman + + + + %1 comics + %1 çizgi roman + + + + Last day + Son gün + + + + Last %1 days + Son %1 gün + + + + 1 sublist + 1 alt liste + + + + %1 sublists + %1 alt liste + + + + LocalComicListModel + + + file name + dosya adı + + + + NoLibrariesWidget + + + create your first library + İlk kütüphaneni oluştur + + + + You don't have any libraries yet + Henüz bir kütüphaneye sahip değilsin + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <p>Yeni bir kütüphane oluşturabilmeniçin kütüphane</p><p>No olvides que puedes usar YACReader como una aplicación independiente para leer los cómics en tu ordenador.</p> + + + + add an existing one + Var olan bir tane ekle + + + + NoSearchResultsWidget + + + No results + Sonuç yok + + + + OptionsDialog + + + Appearance + Dış görünüş + + + + Options + Ayarlar + + + + Language + Dil + + + + Application language + Uygulama dili + + + + System default + Sistem varsayılanı + + + + Tray icon settings (experimental) + Tepsi simgesi ayarları (deneysel) + + + + Close to tray + Tepsiyi kapat + + + + Start into the system tray + Sistem tepsisinde başlat + + + + Edit Comic Vine API key + Comic Vine API anahtarını düzenle + + + + Comic Vine API key + Comic Vine API anahtarı + + + + ComicInfo.xml legacy support + ComicInfo.xml eski desteği + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + Yeni çizgi roman eklerken meta verileri ComicInfo.xml'den içe aktarın + + + + Consider 'recent' items added or updated since X days ago + X gün öncesinden bu yana eklenen veya güncellenen 'en son' öğeleri göz önünde bulundurun + + + + Third party reader + Üçüncü taraf okuyucu + + + + Write {comic_file_path} where the path should go in the command + Komutta yolun gitmesi gereken yere {comic_file_path} yazın + + + + Clear + Temizle + + + + Update libraries at startup + Başlangıçta kitaplıkları güncelleyin + + + + Try to detect changes automatically + Değişiklikleri otomatik olarak algılamayı deneyin + + + + Update libraries periodically + Kitaplıkları düzenli aralıklarla güncelleyin + + + + Interval: + Aralık: + + + + 30 minutes + 30 dakika + + + + 1 hour + 1 saat + + + + 2 hours + 2 saat + + + + 4 hours + 4 saat + + + + 8 hours + 8 saat + + + + 12 hours + 12 saat + + + + daily + günlük + + + + Update libraries at certain time + Kitaplıkları belirli bir zamanda güncelle + + + + Time: + Zaman: + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + UYARI! Kütüphane güncellemeleri sırasında veritabanına yazma işlemi devre dışı bırakılır! +Uygulamayı aktif olarak kullanırken güncelleme planlamayın. +Otomatik güncellemeler sırasında uygulama, güncelleme bitene kadar bazı eylemleri engelleyecektir. +Otomatik güncellemeyi durdurmak için Kitaplıklar başlığının yanındaki yükleme göstergesine dokunun. + + + + Modifications detection + Değişiklik tespiti + + + + Compare the modified date of files when updating a library (not recommended) + Kitaplığı güncellerken dosyaların değiştirilme tarihini karşılaştırın (önerilmez) + + + + Enable background image + Arka plan resmini etkinleştir + + + + Opacity level + Matlık düzeyi + + + + Blur level + Bulanıklık düzeyi + + + + Use selected comic cover as background + Seçilen çizgi roman kapanığı arka plan olarak kullan + + + + Restore defautls + Varsayılanları geri yükle + + + + Background + Arka plan + + + + Display continue reading banner + Okuma devam et bannerını göster + + + + Display current comic banner + Mevcut çizgi roman banner'ını görüntüle + + + + Continue reading + Okumaya devam et + + + + Mix folders and comics + Klasörleri ve çizgi romanları karıştır + + + + Start comics on a new row + Çizgi romanları yeni bir satırda başlat + + + + Content + İçerik + + + + Comic Flow + Comic Flow + + + + + Libraries + Kütüphaneler + + + + Grid view + Izgara görünümü + + + + General + Genel + + + + Restart is needed + Yeniden başlatılmalı + + + + OrganizeFiles + + + Renamed, %1 is already in use + Yeniden adlandırıldı, %1 zaten kullanımda + + + + Missing metadata: %1 + Eksik üstveri: %1 + + + + %1 could not be created + %1 oluşturulamadı + + + + OrganizeFilesCoordinator + + + + Organize files + Dosyaları düzenle + + + + This folder does not contain any comics. + Bu klasör hiç çizgi roman içermiyor. + + + + This library is busy: %1 + Bu kütüphane meşgul: %1 + + + + the library database could not be opened + kütüphane veritabanı açılamadı + + + + the library database could not be locked for writing + kütüphane veritabanı yazma için kilitlenemedi + + + + a folder entry could not be restored + bir klasör kaydı geri yüklenemedi + + + + a comic entry could not be updated + bir çizgi roman kaydı güncellenemedi + + + + the library database could not be saved: %1 + kütüphane veritabanı kaydedilemedi: %1 + + + + the record of the last organize run could not be read + son düzenleme işleminin kaydı okunamadı + + + + the folder %1 could not be created + %1 klasörü oluşturulamadı + + + + %n file(s) could not be moved back + + %n dosya geri taşınamadı + + + + + OrganizeFilesDialog + + Format: + Formato: + + + + Organize files + Dosyaları düzenle + + + + + Rename files + Dosyaları yeniden adlandır + + + + Preparing the preview... + Önizleme hazırlanıyor... + + + + &Filename format: + &Dosya adı biçimi: + + + + &Path format: + &Yol biçimi: + + + + Filename format + Dosya adı biçimi + + + + Path format + Yol biçimi + + + + Presets + Hazır ayarlar + + + + Insert + Ekle + + + + Optional part < > + İsteğe bağlı bölüm < > + + + + Disappears completely when the fields inside it are empty. + İçindeki alanlar boşsa tümüyle kaybolur. + + + + Padded number {number:000} + Sıfırla doldurulmuş numara {number:000} + + + + Format help... + Biçim yardımı... + + + + selected folder + seçili klasör + + + + library root + kütüphane kökü + + + + Move into + Şuraya taşı + + + + Reset changes + Değişiklikleri sıfırla + + + + Remove selected + Seçilileri çıkar + + + + Show unchanged + Değişmeyenleri göster + + + + New name + Yeni ad + + + + Renamed from + Önceki ad + + + + New location + Yeni konum + + + + Moved from + Önceki konum + + + + Remove from list + Listeden çıkar + + + + Move files + Dosyaları taşı + + + + Cancel + Vazgeç + + + Copy the list + Listeyi kopyala - - Add a new label to this library - Bu kitaplığa yeni bir etiket ekle + + Undo + Geri al - - Rename selected list - Seçilen listeyi yeniden adlandır + Close + Kapat - - Rename any selected labels or lists - Seçilen etiketleri ya da listeleri yeniden adlandır + + Copy failure details + Hata ayrıntılarını kopyala - - Add to... - Şuraya ekle... + + Finish + Bitir - - Favorites - Favoriler + + Remove preset + Hazır ayarı kaldır - - Add selected comics to favorites list - Seçilen çizgi romanları favoriler listesine ekle + + Save current format as preset... + Geçerli biçimi hazır ayar olarak kaydet... - - - LocalComicListModel - - file name - dosya adı + + Reset to default format + Varsayılan biçime sıfırla - - - NoLibrariesWidget - - create your first library - İlk kütüphaneni oluştur + + Save preset + Hazır ayarı kaydet - - You don't have any libraries yet - Henüz bir kütüphaneye sahip değilsin + + Preset name: + Hazır ayar adı: - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <p>Yeni bir kütüphane oluşturabilmeniçin kütüphane</p><p>No olvides que puedes usar YACReader como una aplicación independiente para leer los cómics en tu ordenador.</p> + + A filename format cannot contain "/". Use Organize files to move comics into folders. + Bir dosya adı biçimi "/" içeremez. Çizgi romanları klasörlere taşımak için Dosyaları düzenle komutunu kullanın. - - add an existing one - Var olan bir tane ekle + + This format cannot be used: %1 + Bu biçim kullanılamaz: %1 - - - NoSearchResultsWidget - - No results - Sonuç yok + + new folder + yeni klasör - - - OptionsDialog - - Appearance - Dış görünüş + + This folder does not exist yet. It will be created. + Bu klasör henüz yok. Oluşturulacak. - - Options - Ayarlar + + file not found + dosya bulunamadı - - Language - Dil + + This comic is in the library but not on disk. It is skipped. + Bu çizgi roman kütüphanede var ama diskte yok. Atlanıyor. - - Application language - Uygulama dili + + name in use + ad kullanımda - - System default - Sistem varsayılanı + + no metadata + üstveri yok - - Tray icon settings (experimental) - Tepsi simgesi ayarları (deneysel) + + already here + zaten burada - - Close to tray - Tepsiyi kapat + + This file is already in the right place. + Bu dosya zaten doğru yerde. - - Start into the system tray - Sistem tepsisinde başlat + + edited + düzenlendi + + + + %n will be renamed + + %n yeniden adlandırılacak + + + + + %n will move + + %n taşınacak + + + + + %n unchanged + + %n değişmedi + + + + + %n renamed + + %n yeniden adlandırıldı + + + + + %n removed + + %n çıkarıldı + + + + + %n missing + + %n eksik + + + + + %n new folder(s) + + %n yeni klasör + + + + + %n manual change(s) kept + + Elle yapılan %n değişiklik korundu + - - Edit Comic Vine API key - Comic Vine API anahtarını düzenle + + Nothing would be renamed with this format. + Bu biçimle hiçbir şey yeniden adlandırılmaz. - - Comic Vine API key - Comic Vine API anahtarı + + Nothing would move with this format. + Bu biçimle hiçbir şey taşınmaz. + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + %n dosya yeniden adlandırılacak. Klasörler değişmez. Bunu sonradan geri alabilirsiniz. + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + %n dosya %1 konumuna taşınacak. Bu, diskteki dosyalarınızı değiştirir. Bunu sonradan geri alabilirsiniz. + - - ComicInfo.xml legacy support - ComicInfo.xml eski desteği + + Moving %1 of %2 +%3 + %2 dosyadan %1 taşınıyor +%3 - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics - Yeni çizgi roman eklerken meta verileri ComicInfo.xml'den içe aktarın + + Updating the library... + Kütüphane güncelleniyor... - - Consider 'recent' items added or updated since X days ago - X gün öncesinden bu yana eklenen veya güncellenen 'en son' öğeleri göz önünde bulundurun + + Restored name + Geri yüklenen ad - - Third party reader - Üçüncü taraf okuyucu + + + Moved back from + Şuradan geri taşındı - - Write {comic_file_path} where the path should go in the command - Komutta yolun gitmesi gereken yere {comic_file_path} yazın + + + + + Status + Durum - - Clear - Temizle + + Final name + Son ad - - Update libraries at startup - Başlangıçta kitaplıkları güncelleyin + + Previous name + Önceki ad - - Try to detect changes automatically - Değişiklikleri otomatik olarak algılamayı deneyin + + Restored location + Geri yüklenen konum - - Update libraries periodically - Kitaplıkları düzenli aralıklarla güncelleyin + + Final location + Son konum - - Interval: - Aralık: + + Previous location + Önceki konum - - 30 minutes - 30 dakika + + Restored + Geri yüklendi - - 1 hour - 1 saat + + Renamed + Yeniden adlandırıldı - - 2 hours - 2 saat + + Moved + Taşındı - - 4 hours - 4 saat + + Undo failed: %1 + Geri alma başarısız: %1 - - 8 hours - 8 saat + + Failed: %1 + Başarısız: %1 - - 12 hours - 12 saat + + Nothing was moved. + Hiçbir şey taşınmadı. - - daily - günlük + + The record this run could be undone from could not be written, so the run did not start: %1 + Bu işlemin geri alınmasını sağlayacak kayıt yazılamadı, bu yüzden işlem başlamadı: %1 + + + + %n file(s) renamed. + + %n dosya yeniden adlandırıldı. + + + + + %n file(s) moved into %1. + + %n dosya %1 konumuna taşındı. + - - Update libraries at certain time - Kitaplıkları belirli bir zamanda güncelle + + The record of this run stopped early, so the run stopped with it: %1 + Bu işlemin kaydı erken durdu, bu yüzden işlem de onunla birlikte durdu: %1 + + + + %n file(s) were not moved. + + %n dosya taşınmadı. + - - Time: - Zaman: + + The library database could not be updated: %1 + Kütüphane veritabanı güncellenemedi: %1 - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. - UYARI! Kütüphane güncellemeleri sırasında veritabanına yazma işlemi devre dışı bırakılır! -Uygulamayı aktif olarak kullanırken güncelleme planlamayın. -Otomatik güncellemeler sırasında uygulama, güncelleme bitene kadar bazı eylemleri engelleyecektir. -Otomatik güncellemeyi durdurmak için Kitaplıklar başlığının yanındaki yükleme göstergesine dokunun. + + Use Undo to move the files back, or update the library to make it match the files. + Dosyaları geri taşımak için Geri al'ı kullanın veya kütüphaneyi dosyalarla eşleşecek biçimde güncelleyin. + + + + %n empty folder(s) were removed. + + %n boş klasör kaldırıldı. + + + + + %n file(s) could not be moved. + + %n dosya taşınamadı. + - - Modifications detection - Değişiklik tespiti + + Moving the files back... + Dosyalar geri taşınıyor... - - Compare the modified date of files when updating a library (not recommended) - Kitaplığı güncellerken dosyaların değiştirilme tarihini karşılaştırın (önerilmez) + + Moving back %1 of %2 +%3 + %2 dosyadan %1 geri taşınıyor +%3 - - Enable background image - Arka plan resmini etkinleştir + + Everything was moved back. + Her şey geri taşındı. - - Opacity level - Matlık düzeyi + + The undo did not finish: %1 + Geri alma tamamlanmadı: %1 - - Blur level - Bulanıklık düzeyi + + Format help + Biçim yardımı - - Use selected comic cover as background - Seçilen çizgi roman kapanığı arka plan olarak kullan + + Fields + Alanlar - - Restore defautls - Varsayılanları geri yükle + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + Her alan süslü parantez içinde yazılır ve çizgi romanın üstverisiyle değiştirilir. Ekle menüsü hepsini listeler. - - Background - Arka plan + + {series} gives %1 + {series} şunu verir: %1 - - Display continue reading banner - Okuma devam et bannerını göster + + Optional parts + İsteğe bağlı bölümler - - Display current comic banner - Mevcut çizgi roman banner'ını görüntüle + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + < ve > işaretleri arasına yazılan bir bölüm, içindeki bütün alanlar boşsa tümüyle kaybolur. Bunu bir alana ait noktalama için kullanın; örneğin parantezler veya baştaki numara işareti. Bir adın başındaki ve sonundaki boşluklar bu bölüm olmadan da kırpılır. - - Continue reading - Okumaya devam et + + {series} ({year}) with no year gives %1 + {series} ({year}) yıl yoksa şunu verir: %1 - - Comic Flow - Comic Flow + + {series}< ({year})> with no year gives %1 + {series}< ({year})> yıl yoksa şunu verir: %1 - - - Libraries - Kütüphaneler + + Numbers + Numaralar - - Grid view - Izgara görünümü + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + Sayı numarasını doldurmak için iki nokta üst üste ve birkaç sıfır yazın. Böylece sayılar dosya yöneticisinde sırada kalır. - - General - Genel + + + Folders + Klasörler - - Restart is needed - Yeniden başlatılmalı + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + Bir dosya adı biçimi eğik çizgi içeremez. Her çizgi roman geçerli klasöründe kalır. Çizgi romanları taşımak için Klasörlere düzenle komutunu kullanın. + + + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + Eğik çizgiyle ayrılan her bölüm bir klasör olur. Son bölüm dosya adı olur. Özgün uzantı her zaman korunur. @@ -2432,12 +3353,12 @@ Otomatik güncellemeyi durdurmak için Kitaplıklar başlığının yanındaki y Çizgi roman bilgisini düzenle - + Invalid cover Geçersiz kapak - + The image is invalid. Resim geçersiz. @@ -2537,6 +3458,35 @@ Otomatik güncellemeyi durdurmak için Kitaplıklar başlığının yanındaki y Okuma Listeleri + + ReadingListManagementCoordinator + + + Add new reading lists + Yeni okuma listeleri ekle + + + + + List name: + Liste adı: + + + + Delete list/label + Listeyi/Etiketi sil + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + Seçilen öğe silinecek, çizgi romanlarınız veya klasörleriniz diskinizden SİLİNMEYECEKTİR. Emin misin? + + + + Rename list name + Listeyi yeniden adlandır + + RenameLibraryDialog @@ -3250,6 +4200,61 @@ Use quotes to include spaces in a value. cilt açıklaması kullanılamıyor + + SelectedComicsInfoView + + + Unknown + Bilinmiyor + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + %1 çizgi roman seçildi + + + + Read + Oku + + + + In progress + Devam eden + + + + Unread + Okunmamış + + + + Total pages + + + + + Total size + + + + + Series + Seri + + SeriesQuestion @@ -3271,53 +4276,53 @@ Use quotes to include spaces in a value. ServerConfigDialog - - + + Server connectivity Sunucu bağlantısı - + Scan to connect Bağlanmak için tarayın - + Devices on this network can reach your library at the address below. Bu ağdaki cihazlar aşağıdaki adresten kitaplığınıza erişebilir. - + IP address IP adresi - + Port Liman - + Web interface Web arayüzü - + Copy link Bağlantıyı kopyala - + Open web UI Web arayüzünü aç - + Enable the server Sunucuyu etkinleştir - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. YACReader, iOS ve Android için kullanılabilir. <a href='https://ios.yacreader.com'>iOS</a> veya <a href='https://android.yacreader.com'>Android</a> sürümünü keşfedin. @@ -3326,7 +4331,7 @@ Use quotes to include spaces in a value. erişilebilir server - + Set port set port Portu ayarla diff --git a/YACReaderLibrary/yacreaderlibrary_zh_CN.ts b/YACReaderLibrary/yacreaderlibrary_zh_CN.ts index b2ae00441..88bb3874a 100644 --- a/YACReaderLibrary/yacreaderlibrary_zh_CN.ts +++ b/YACReaderLibrary/yacreaderlibrary_zh_CN.ts @@ -202,11 +202,22 @@ ClassicComicsView - + Hide comic flow 隐藏漫画页面流 + + ComicFilesCoordinator + + Copying comics... + 复制漫画中... + + + Moving comics... + 移动漫画中... + + ComicInfoView @@ -290,70 +301,99 @@ 字效师 + + ComicManagementCoordinator + + + + YACReader not found + YACReader 未找到 + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + 未找到YACReader. YACReader应安装在与YACReaderLibrary相同的文件夹中. + + + + YACReader not found. There might be a problem with your YACReader installation. + 未找到YACReader. YACReader的安装可能有问题. + + + + Error + 错误 + + + + Error opening comic with third party reader. + 使用第三方阅读器打开漫画时出错。 + + ComicModel - + no - + yes - + Read 阅读 - + Size 大小 - + Pages 页数 - + Title 标题 - + Current Page 当前页 - + File Name 文件名 - + Rating 评分 - + Series 系列 - + Volume - + Story Arc 故事线 - + Publication Date 出版日期 @@ -381,13 +421,13 @@ 关闭 - - + + Retrieving tags for : %1 正在检索标签: %1 - + Looking for comic... 搜索漫画中... @@ -397,34 +437,42 @@ 搜索 - - - + + + Looking for volume... 搜索卷... - - + + comic %1 of %2 - %3 第 %1 本 共 %2 本 - %3 - + %1 comics selected 已选择 %1 本漫画 - + Error connecting to ComicVine ComicVine 连接时出错 - + Retrieving volume info... 正在接收卷信息... + + ContinueReadingGridHeader + + + Continue Reading... + 继续阅读... + + CreateLibraryDialog @@ -468,6 +516,14 @@ 未找到路径 + + DBHelper + + + The folder entry could not be found in the library database. + 在库数据库中找不到该文件夹的记录。 + + EditShortcutsDialog @@ -504,6 +560,19 @@ 该文件夹还没有漫画 + + EmptyInfoView + + + Nothing selected + 未选择任何内容 + + + + Select a comic or folder to see its information. + 选择漫画或文件夹以查看其信息。 + + EmptyLabelWidget @@ -617,27 +686,27 @@ FileComic - + + Format not supported 不支持的文件格式 - + 7z not found 未找到 7z - + Unknown error opening the file 打开文件时出现未知错误 - Unsupported EPUB: %1 - 不支持的 EPUB 格式:%1 + 不支持的 EPUB 格式:%1 - + CRC error on page (%1): some of the pages will not be displayed correctly 第 %1 页 CRC 校验失败: 部分页面将无法正确显示 @@ -645,18 +714,134 @@ FolderContentView - Continue Reading... - 继续阅读... + 继续阅读... + + + + FolderInfoView + + + Unknown + 未知 + + + + Items + 项目 + + + + Type + 类型 + + + + Reading status + 阅读状态 + + + + Read + 阅读 + + + + Unread + 未读 + + + + Collection status + 收藏状态 + + + + Completed + 已完成 + + + + In progress + 阅读中 + + + + Added + 已添加 + + + + Updated + 已更新 + + + + FolderManagementCoordinator + + + Add new folder + 添加新的文件夹 + + + + Folder name: + 文件夹名称: GridComicsView - + Show info 显示信息 + + Library + + + + Folder + 文件夹 + + + Favorites + 收藏夹 + + + Recently added + 最近添加 + + + + Manga + 日式漫画 + + + + Western manga + 西式漫画 + + + + Web comic + 网络漫画 + + + + Yonkoma + 四格漫画 + + + + Comic + 漫画 + + + + Unknown + 未知 + HelpAboutDialog @@ -806,230 +991,140 @@ - LibraryWindow + LibraryInfoView - - The selected folder doesn't contain any library. - 所选文件夹不包含任何库。 + + Library info + 图书馆信息 - - This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? - 此库是使用旧版本的YACReaderLibrary创建的. 它需要更新. 现在更新? + + Number of folders + 文件夹数量 - - Upgrade failed - 更新失败 + + Number of comics + 漫画数量 - - Comic - 漫画 + + Number of read comics + 已读漫画数量 + + + LibraryManagementCoordinator - - - - comic - 漫画 + + Error opening the library + 打开库时出错 - - - - manga - 日本漫画 + + Error creating the library + 创建库时出错 - - Folder name: - 文件夹名称: + + Error updating the library + 更新库时出错 + + + LibraryWindow - - The selected folder and all its contents will be deleted from your disk. Are you sure? - 所选文件夹及其所有内容将从磁盘中删除。 你确定吗? + + The selected folder doesn't contain any library. + 所选文件夹不包含任何库。 - - Rescan library for XML info - 重新扫描库的 XML 信息 + + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? + 此库是使用旧版本的YACReaderLibrary创建的. 它需要更新. 现在更新? - - Error opening the library - 打开库时出错 + + Upgrade failed + 更新失败 - - - YACReader not found - YACReader 未找到 + + Folder name: + 文件夹名称: - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. - 尝试删除所选文件夹时出现问题。 请检查写入权限,并确保没有其他应用程序在使用这些文件夹或文件。 + + The selected folder and all its contents will be deleted from your disk. Are you sure? + 所选文件夹及其所有内容将从磁盘中删除。 你确定吗? - - Rename list name - 重命名列表 + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + 尝试删除所选文件夹时出现问题。 请检查写入权限,并确保没有其他应用程序在使用这些文件夹或文件。 Remove and delete metadata 移除并删除元数据 - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - 未找到YACReader. YACReader应安装在与YACReaderLibrary相同的文件夹中. - - - + Old library 旧的库 - - Set as completed - 设为已完成 - - - + There was an error accessing the folder's path 访问文件夹的路径时出错 - - Library - - - - + Comics will only be deleted from the current label/list. Are you sure? 漫画只会从当前标签/列表中删除。 你确定吗? - + This library was created with a newer version of YACReaderLibrary. Download the new version now? 此库是使用较新版本的YACReaderLibrary创建的。 立即下载新版本? - - + Moving comics... 移动漫画中... - - + Copying comics... 复制漫画中... - + Library '%1' is no longer available. Do you want to remove it? 库 '%1' 不再可用。 你想删除它吗? - - - - web comic - 网络漫画 - - - - Open folder... - 打开文件夹... - - - - Set custom cover - 设置自定义封面 - - - - Delete custom cover - 删除自定义封面 - - - - Error - 错误 - - - - Error opening comic with third party reader. - 使用第三方阅读器打开漫画时出错。 - - - + Do you want remove 你想要删除 - - Set as uncompleted - 设为未完成 - - - + Error in path 路径错误 - - Error updating the library - 更新库时出错 - - - - Folder - 文件夹 - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - 所选项目将被删除,您的漫画或文件夹将不会从您的磁盘中删除。 你确定吗? - - - - - - western manga (left to right) - 欧美漫画(从左到右) - - - - - List name: - 列表名称: - - - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? 库 '%1' 是通过旧版本的YACReaderLibrary创建的。 必须再次创建。 你想现在创建吗? - + Save covers 保存封面 - - YACReader not found. There might be a problem with your YACReader installation. - 未找到YACReader. YACReader的安装可能有问题. - - - - Add new reading lists - 添加新的阅读列表 - - - + You are adding too many libraries. You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. @@ -1042,32 +1137,29 @@ YACReaderLibrary will not stop you from creating more libraries but you should k YACReaderLibrary不会阻止您创建更多的库,但是您应该保持较低的库数量来提升性能。 - - Set as read - 设为已读 - - - + Assign comics numbers 分配漫画编号 - + There were errors during library upgrade in: 漫画库更新时出现错误: - + + + Please, select a folder first 请先选择一个文件夹 - + Library not available 库不可用 - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. 尝试删除所选漫画时出现问题。 请检查所选文件或包含文件夹中的写入权限。 @@ -1077,166 +1169,204 @@ YACReaderLibrary不会阻止您创建更多的库,但是您应该保持较低 YACReader 库 - - Error creating the library - 创建库时出错 - - - + You are adding too many libraries. 您添加的库太多了。 - - Update folder - 更新文件夹 - - - + Update needed 需要更新 - + Library name already exists 库名已存在 - + There is another library with the name '%1'. 已存在另一个名为'%1'的库。 - + Delete folder 删除文件夹 - + Assign numbers starting in: 从以下位置开始分配编号: - + Download new version 下载新版本 - + + Rename or organize files + 重命名或整理文件 + + + + Set the type of the selected comics + 设置所选漫画的类型 + + + Search filters 搜索筛选条件 - + Unread 未读 - + In progress 阅读中 - + Highly rated 高评分 - + Recently added 最近添加 - + Search syntax… 搜索语法… - - - - - Set type - 设置类型 - - - + A repair of this library is already running (%1). Wait for it to finish. 此库的修复已在运行中(%1)。请等待其完成。 - + The library is locked by a repair that did not finish. 库已被一个未完成的修复锁定。 - + The library is locked by a repair started by %1. 库已被 %1 启动的修复锁定。 - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? 如果您确定没有其他修复正在运行,可以移除该锁定。移除锁定并继续? - + Package operation failed 打包操作失败 - + The covers package operation could not be completed. 封面包操作无法完成。 - + Restore recovery failed 恢复操作修复失败 - - + + Rename folder + 重命名文件夹 + + + + Invalid folder name + 文件夹名称无效 + + + + The folder name is empty or contains characters that are not supported. + 文件夹名称为空或包含不支持的字符。 + + + + + + Unable to rename folder + 无法重命名文件夹 + + + + A file or folder named '%1' already exists. + 名为“%1”的文件或文件夹已存在。 + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. + +Folder: %1 + 无法在磁盘上重命名该文件夹。请检查文件夹名称和写入权限。 + +文件夹:%1 + + + + The library database could not be updated. The folder rename on disk was reverted. + 无法更新库数据库。磁盘上的文件夹重命名已撤销。 + + + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + 无法更新库数据库,磁盘上的文件夹重命名也无法撤销。现在需要手动更新该库。 + + + + YACReader library database (*.ydb) YACReader 资料库数据库 (*.ydb) - + The library database backup was created at: %1 资料库数据库备份已创建于: %1 - + Unable to create the library database backup: %1 无法创建资料库数据库备份: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? 恢复前请关闭 YACReaderLibraryServer 以及正在使用此资料库的所有其他 YACReader 应用程序。是否继续? - + Restoring library database... 正在恢复资料库数据库... - + The current library database is invalid. Restore the selected backup anyway? 当前资料库数据库无效。仍要恢复所选备份吗? - - + + The library maintenance lock may be stale. Remove it and retry? 资料库维护锁可能已失效。是否移除并重试? - + Restart YACReaderLibrary before attempting recovery again. @@ -1245,71 +1375,71 @@ Restart YACReaderLibrary before attempting recovery again. 再次尝试恢复前,请重新启动 YACReaderLibrary。 - + The library database was restored successfully. Update the library now? 资料库数据库已成功恢复。是否立即更新资料库? - + Library database damaged 资料库数据库已损坏 - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. 资料库“%1”的数据库已损坏,因此无法执行常规更新、维护和备份。YACReader 可以尝试修复数据库。部分损坏的数据可能无法恢复。现有备份不会被更改。 - + Attempt repair 尝试修复 - + Restore a backup... 恢复备份... - + Repairing library database... 正在修复资料库数据库... - - - + + + Library database repair 修复资料库数据库 - + Another maintenance operation is currently using this library. Try again after it finishes. 另一个维护操作正在使用此资料库。请在其完成后重试。 - + The library database is already valid. 资料库数据库已经有效。 - + Library database repaired 资料库数据库已修复 - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 已通过重建索引修复资料库数据库。损坏的原始文件已保存在: %1 - + Library database rebuilt 资料库数据库已重建 - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1320,7 +1450,7 @@ Update the library now? 是否立即更新资料库? - + The damaged original was preserved at: @@ -1331,12 +1461,12 @@ The damaged original was preserved at: %1 - + Library database repair failed 资料库数据库修复失败 - + The library database could not be repaired: %1%2 @@ -1347,101 +1477,80 @@ You can restore a backup from the Library menu or recreate the library. 您可以从“资料库”菜单恢复备份,或重新创建资料库。 - + Remove and delete metadata and backups 移除并删除元数据和备份 - + Library info 图书馆信息 - + Invalid image 图片无效 - + The selected file is not a valid image. 所选文件不是有效图像。 - + Error saving cover 保存封面时出错 - + There was an error saving the cover image. 保存封面图像时出错。 - + Delete comics 删除漫画 - - Add new folder - 添加新的文件夹 - - - - Delete list/label - 删除 列表/标签 - - - + + + No folder selected 没有选中的文件夹 - + All the selected comics will be deleted from your disk. Are you sure? 所有选定的漫画都将从您的磁盘中删除。你确定吗? - + Remove comics 移除漫画 - - - Set as unread - 设为未读 - - - + Library not found 未找到库 - - + + Unable to delete 无法删除 - - - - 4koma (top to botom) - 四格漫画(从上到下) - - - + library? 库? - + Are you sure? 你确定吗? - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1453,759 +1562,1576 @@ Missing files: %3 LibraryWindowActions - + Create a new library 创建一个新的库 - + Open an existing library 打开现有的库 - - + + Export comics info 导出漫画信息 - - + + Import comics info 导入漫画信息 - + Pack covers 打包封面 - + Pack the covers of the selected library 打包所选库的封面 - + Unpack covers 解压封面 - + Unpack a catalog 解压目录 - + Update library 更新库 - + Update current library 更新当前库 - + Back up library database 备份资料库数据库 - + Create a backup of the current library database 创建当前资料库数据库的备份 - + Restore library database backup 恢复资料库数据库备份 - + Restore the current library database from a backup 从备份恢复当前资料库数据库 - + Repair covers and comic info 修复封面和漫画信息 - + Retry comics with missing covers or incomplete information 重新处理缺少封面或信息不完整的漫画 - + Rename library 重命名库 - + Rename current library 重命名当前库 - + Remove library 移除库 - + Remove current library from your collection 从您的集合中移除当前库 - + Rescan library for XML info 重新扫描库的 XML 信息 - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. 尝试查找漫画文件内嵌的 XML 信息。只有当创建库的 YACReaderLibrary 版本低于 9.8.2 或者使用第三方软件嵌入 XML 信息时,才需要执行该操作。 - + Open library folder... 打开库文件夹... - + Open the root folder of the current library 打开当前库的根文件夹 - + Show library info 显示图书馆信息 - + Show information about the current library 显示当前库的信息 - + Open current comic 打开当前漫画 - + Open current comic on YACReader 用YACReader打开漫画 - + Save selected covers to... 选中的封面保存到... - + Save covers of the selected comics as JPG files 保存所选的封面为jpg - - + + Set as read 设为已读 - + Set comic as read 漫画设为已读 - - + + Set as unread 设为未读 - + Set comic as unread 漫画设为未读 - - + + manga 日本漫画 - + Set issue as manga 设置为漫画 - - + + comic 漫画 - + Set issue as normal 设置漫画为 - + western manga 欧美漫画 - + Set issue as western manga 设置为欧美漫画 - - + + web comic 网络漫画 - + Set issue as web comic 设置为网络漫画 - - + + yonkoma 四格漫画 - + Set issue as yonkoma 设置为四格漫画 - + Show/Hide marks 显示/隐藏标记 - + Show or hide read marks 显示或隐藏阅读标记 - + Show/Hide recent indicator 显示/隐藏最近的指示标志 - + Show or hide recent indicator 显示或隐藏最近的指示标志 - - + + Fullscreen mode on/off 全屏模式 开/关 - + Help, About YACReader 帮助, 关于 YACReader - + Add new folder 添加新的文件夹 - + Add new folder to the current library 在当前库下添加新的文件夹 - + + Rename folder + 重命名文件夹 + + + + Rename the current folder on disk and in the library + 在磁盘和库中重命名当前文件夹 + + + Delete folder 删除文件夹 - + Delete current folder from disk 从磁盘上删除当前文件夹 - + Select root node 选择根节点 - + Expand all nodes 展开所有节点 - + Collapse all nodes 折叠所有节点 - + Show options dialog 显示选项对话框 - + Show comics server options dialog 显示漫画服务器选项对话框 - - + + Change between comics views 漫画视图之间的变化 - + Open folder... 打开文件夹... - + + + Rename files... + Organize files + 重命名文件... + + + + + Organize into folders... + 整理到文件夹... + + + Set as uncompleted 设为未完成 - + Set as completed 设为已完成 - + Set custom cover 设置自定义封面 - + Delete custom cover 删除自定义封面 - + western manga (left to right) 欧美漫画(从左到右) - + Open containing folder... 打开包含文件夹... - Reset comic rating - 重置漫画评分 + 重置漫画评分 - + Select all comics 全选漫画 - + Edit 编辑 - + Assign current order to comics 将当前序号分配给漫画 - + Update cover 更新封面 - + Delete selected comics 删除所选的漫画 - + Delete metadata from selected comics 从选定的漫画中删除元数据 - + Download tags from Comic Vine 从 Comic Vine 下载标签 - + Focus search line 聚焦于搜索行 - + Focus comics view 聚焦于漫画视图 - + Edit shortcuts 编辑快捷键 - + &Quit 退出(&Q) - + Update folder 更新文件夹 - + Update current folder 更新当前文件夹 - + Scan legacy XML metadata 扫描旧版 XML 元数据 - + Add new reading list 添加新的阅读列表 - - Add a new reading list to the current library - 在当前库添加新的阅读列表 + + Add a new reading list to the current library + 在当前库添加新的阅读列表 + + + + Remove reading list + 移除阅读列表 + + + + Remove current reading list from the library + 从当前库移除阅读列表 + + + + Add new label + 添加新标签 + + + + Add a new label to this library + 在当前库添加标签 + + + + Rename selected list + 重命名列表 + + + + Rename any selected labels or lists + 重命名任何选定的标签或列表 + + + + Add to... + 添加到... + + + + Favorites + 收藏夹 + + + + Add selected comics to favorites list + 将所选漫画添加到收藏夹列表 + + + + + Reset rating + 重置评分 + + + + LibraryWindowMenus + + + comic + 漫画 + + + + manga + 日本漫画 + + + + western manga (left to right) + 欧美漫画(从左到右) + + + + web comic + 网络漫画 + + + + 4koma (top to botom) + 四格漫画(从上到下) + + + + + + + Set type + 设置类型 + + + + Library + + + + + Folder + 文件夹 + + + + Comic + 漫画 + + + + Open folder... + 打开文件夹... + + + + Update folder + 更新文件夹 + + + + Rename folder + 重命名文件夹 + + + + Rename files... + 重命名文件... + + + + Organize into folders... + 整理到文件夹... + + + + Rescan library for XML info + 重新扫描库的 XML 信息 + + + + Set as uncompleted + 设为未完成 + + + + Set as completed + 设为已完成 + + + + Set as read + 设为已读 + + + + + Set as unread + 设为未读 + + + + Set custom cover + 设置自定义封面 + + + + Delete custom cover + 删除自定义封面 + + + + ListInfoView + + + 1 comic + 1 本漫画 + + + + %1 comics + %1 本漫画 + + + + Last day + 最近 1 天 + + + + Last %1 days + 最近 %1 天 + + + + 1 sublist + 1 个子列表 + + + + %1 sublists + %1 个子列表 + + + + LocalComicListModel + + + file name + 文件名 + + + + NoLibrariesWidget + + + create your first library + 创建你的第一个库 + + + + You don't have any libraries yet + 你还没有库 + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <p>您可以在任何文件夹中创建库,YACReaderLibrary将导入此文件夹中的所有漫画和文件夹。如果已有库,则可以打开它们。</p><p>您可以把YACReader当成独立应用来阅读电脑上的漫画。</p> + + + + add an existing one + 添加一个现有库 + + + + NoSearchResultsWidget + + + No results + 没有结果 + + + + OptionsDialog + + + Modifications detection + 修改检测 + + + + Time: + 时间: + + + + daily + 每天 + + + + Restore defautls + 恢复默认值 + + + + Close to tray + 关闭至托盘 + + + + Background + 背景 + + + + Update libraries at certain time + 定时更新库 + + + + 1 hour + 1小时 + + + + Start into the system tray + 启动至系统托盘 + + + + Display current comic banner + 显示当前漫画横幅 + + + + Continue reading + 继续阅读 + + + + Update libraries at startup + 启动时更新库 + + + + Appearance + 外观 + + + + Language + 语言 + + + + Application language + 应用程序语言 + + + + System default + 系统默认 + + + + Third party reader + 第三方阅读器 + + + + Write {comic_file_path} where the path should go in the command + 在命令中应将路径写入 {comic_file_path} + + + + Clear + 清空 + + + + 30 minutes + 30分钟 + + + + 2 hours + 2小时 + + + + 12 hours + 12小时 + + + + Blur level + 模糊 + + + + Mix folders and comics + 混合显示文件夹和漫画 + + + + Start comics on a new row + 从新行开始显示漫画 + + + + Content + 内容 + + + + Compare the modified date of files when updating a library (not recommended) + 更新库时比较文件的修改日期(不推荐) + + + + Import metadata from ComicInfo.xml when adding new comics + 添加新漫画时从 ComicInfo.xml 导入元数据 + + + + Enable background image + 启用背景图片 + + + + 4 hours + 4小时 + + + + Options + 选项 + + + + Comic Vine API key + Comic Vine API 密匙 + + + + Edit Comic Vine API key + 编辑Comic Vine API 密匙 + + + + Tray icon settings (experimental) + 托盘图标设置 (实验特性) + + + + + Libraries + + + + + 8 hours + 8小时 + + + + Try to detect changes automatically + 尝试自动检测变化 + + + + Interval: + 间隔: + + + + ComicInfo.xml legacy support + ComicInfo.xml 旧版支持 + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + 警告! 在库更新期间,将禁用对数据库的写入! +当您可能正在积极使用该应用程序时,请勿安排更新。 +在自动更新期间,应用程序将阻止某些操作,直到更新完成。 +要停止自动更新,请点击库标题旁边的加载指示器。 + + + + Opacity level + 透明度 + + + + Display continue reading banner + 显示继续阅读横幅 + + + + General + 常规 + + + + Consider 'recent' items added or updated since X days ago + 参考自 X 天前添加或更新的“最近”项目 + + + + Update libraries periodically + 定期更新库 + + + + Use selected comic cover as background + 使用选定的漫画封面做背景 + + + + Comic Flow + 漫画页面流 + + + + Grid view + 网格视图 + + + + Restart is needed + 需要重启 + + + + OrganizeFiles + + + Renamed, %1 is already in use + 已重命名,%1 已被占用 + + + + Missing metadata: %1 + 缺少元数据:%1 + + + + %1 could not be created + 无法创建 %1 + + + + OrganizeFilesCoordinator + + + + Organize files + 整理文件 + + + + This folder does not contain any comics. + 此文件夹不包含任何漫画。 + + + + This library is busy: %1 + 此库正忙:%1 + + + + the library database could not be opened + 无法打开库数据库 + + + + the library database could not be locked for writing + 无法锁定库数据库以进行写入 + + + + a folder entry could not be restored + 无法恢复某个文件夹记录 + + + + a comic entry could not be updated + 无法更新某条漫画记录 + + + + the library database could not be saved: %1 + 无法保存库数据库:%1 + + + + the record of the last organize run could not be read + 无法读取上次整理的记录 + + + + the folder %1 could not be created + 无法创建文件夹 %1 + + + + %n file(s) could not be moved back + + 有 %n 个文件无法移回 + + + + + OrganizeFilesDialog + + Format: + 格式: + + + + Organize files + 整理文件 + + + + + Rename files + 重命名文件 + + + + Preparing the preview... + 正在准备预览... + + + + &Filename format: + 文件名格式(&F): + + + + &Path format: + 路径格式(&P): + + + + Filename format + 文件名格式 + + + + Path format + 路径格式 + + + + Presets + 预设 + + + + Insert + 插入 + + + + Optional part < > + 可选部分 < > + + + + Disappears completely when the fields inside it are empty. + 当其中的字段为空时,这一部分会完全消失。 + + + + Padded number {number:000} + 补零编号 {number:000} + + + + Format help... + 格式帮助... + + + + selected folder + 所选文件夹 + + + + library root + 库根目录 + + + + Move into + 移动到 + + + + Reset changes + 重置更改 + + + + Remove selected + 移除所选项 + + + + Show unchanged + 显示未更改项 + + + + New name + 新名称 + + + + Renamed from + 原名称 + + + + New location + 新位置 + + + + Moved from + 原位置 + + + + Remove from list + 从列表中移除 + + + + Move files + 移动文件 - - Remove reading list - 移除阅读列表 + + Cancel + 取消 - - Remove current reading list from the library - 从当前库移除阅读列表 + Copy the list + 复制列表 - - Add new label - 添加新标签 + + Undo + 撤销 - - Add a new label to this library - 在当前库添加标签 + Close + 关闭 - - Rename selected list - 重命名列表 + + Copy failure details + 复制失败详细信息 - - Rename any selected labels or lists - 重命名任何选定的标签或列表 + + Finish + 完成 - - Add to... - 添加到... + + Remove preset + 删除预设 - - Favorites - 收藏夹 + + Save current format as preset... + 将当前格式另存为预设... - - Add selected comics to favorites list - 将所选漫画添加到收藏夹列表 + + Reset to default format + 重置为默认格式 - - - LocalComicListModel - - file name - 文件名 + + Save preset + 保存预设 - - - NoLibrariesWidget - - create your first library - 创建你的第一个库 + + Preset name: + 预设名称: - - You don't have any libraries yet - 你还没有库 + + A filename format cannot contain "/". Use Organize files to move comics into folders. + 文件名格式不能包含 "/"。请使用“整理文件”把漫画移动到文件夹中。 - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <p>您可以在任何文件夹中创建库,YACReaderLibrary将导入此文件夹中的所有漫画和文件夹。如果已有库,则可以打开它们。</p><p>您可以把YACReader当成独立应用来阅读电脑上的漫画。</p> + + This format cannot be used: %1 + 无法使用此格式:%1 - - add an existing one - 添加一个现有库 + + new folder + 新文件夹 - - - NoSearchResultsWidget - - No results - 没有结果 + + This folder does not exist yet. It will be created. + 此文件夹尚不存在,将会被创建。 - - - OptionsDialog - - Modifications detection - 修改检测 + + file not found + 找不到文件 - - Time: - 时间: + + This comic is in the library but not on disk. It is skipped. + 此漫画在库中,但磁盘上没有。将跳过它。 - - daily - 每天 + + name in use + 名称已被占用 - - Restore defautls - 恢复默认值 + + no metadata + 无元数据 - - Close to tray - 关闭至托盘 + + already here + 已在此处 - - Background - 背景 + + This file is already in the right place. + 此文件已在正确的位置。 - - Update libraries at certain time - 定时更新库 + + edited + 已编辑 + + + + %n will be renamed + + %n 个将被重命名 + + + + + %n will move + + %n 个将被移动 + + + + + %n unchanged + + %n 个未更改 + + + + + %n renamed + + %n 个已重命名 + + + + + %n removed + + %n 个已移除 + + + + + %n missing + + %n 个缺失 + + + + + %n new folder(s) + + %n 个新文件夹 + + + + + %n manual change(s) kept + + 已保留 %n 处手动修改 + - - 1 hour - 1小时 + + Nothing would be renamed with this format. + 使用此格式不会重命名任何文件。 - - Start into the system tray - 启动至系统托盘 + + Nothing would move with this format. + 使用此格式不会移动任何文件。 + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + 将重命名 %n 个文件。文件夹不会改变。之后可以撤销。 + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + 将把 %n 个文件移动到 %1。这会改变磁盘上的文件。之后可以撤销。 + - - Display current comic banner - 显示当前漫画横幅 + + Moving %1 of %2 +%3 + 正在移动第 %1 个,共 %2 个 +%3 - - Continue reading - 继续阅读 + + Updating the library... + 正在更新库... - - Update libraries at startup - 启动时更新库 + + Restored name + 已恢复名称 - - Appearance - 外观 + + + Moved back from + 移回自 - - Language - 语言 + + + + + Status + 状态 - - Application language - 应用程序语言 + + Final name + 最终名称 - - System default - 系统默认 + + Previous name + 原名称 - - Third party reader - 第三方阅读器 + + Restored location + 已恢复位置 - - Write {comic_file_path} where the path should go in the command - 在命令中应将路径写入 {comic_file_path} + + Final location + 最终位置 - - Clear - 清空 + + Previous location + 原位置 - - 30 minutes - 30分钟 + + Restored + 已恢复 - - 2 hours - 2小时 + + Renamed + 已重命名 - - 12 hours - 12小时 + + Moved + 已移动 - - Blur level - 模糊 + + Undo failed: %1 + 撤销失败:%1 - - Compare the modified date of files when updating a library (not recommended) - 更新库时比较文件的修改日期(不推荐) + + Failed: %1 + 失败:%1 - - Import metadata from ComicInfo.xml when adding new comics - 添加新漫画时从 ComicInfo.xml 导入元数据 + + Nothing was moved. + 没有移动任何文件。 - - Enable background image - 启用背景图片 + + The record this run could be undone from could not be written, so the run did not start: %1 + 无法写入用于撤销本次操作的记录,因此操作没有开始:%1 + + + + %n file(s) renamed. + + 已重命名 %n 个文件。 + + + + + %n file(s) moved into %1. + + 已把 %n 个文件移动到 %1。 + - - 4 hours - 4小时 + + The record of this run stopped early, so the run stopped with it: %1 + 本次操作的记录提前中断,因此操作也随之停止:%1 + + + + %n file(s) were not moved. + + 有 %n 个文件没有被移动。 + - - Options - 选项 + + The library database could not be updated: %1 + 无法更新库数据库:%1 - - Comic Vine API key - Comic Vine API 密匙 + + Use Undo to move the files back, or update the library to make it match the files. + 使用“撤销”把文件移回原处,或更新库使其与文件一致。 + + + + %n empty folder(s) were removed. + + 已移除 %n 个空文件夹。 + + + + + %n file(s) could not be moved. + + 有 %n 个文件无法移动。 + - - Edit Comic Vine API key - 编辑Comic Vine API 密匙 + + Moving the files back... + 正在把文件移回原处... - - Tray icon settings (experimental) - 托盘图标设置 (实验特性) + + Moving back %1 of %2 +%3 + 正在移回第 %1 个,共 %2 个 +%3 - - - Libraries - + + Everything was moved back. + 所有文件都已移回原处。 - - 8 hours - 8小时 + + The undo did not finish: %1 + 撤销没有完成:%1 - - Try to detect changes automatically - 尝试自动检测变化 + + Format help + 格式帮助 - - Interval: - 间隔: + + Fields + 字段 - - ComicInfo.xml legacy support - ComicInfo.xml 旧版支持 + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + 每个字段都写在花括号中,会被替换为漫画的元数据。“插入”菜单中列出了全部字段。 - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - 警告! 在库更新期间,将禁用对数据库的写入! -当您可能正在积极使用该应用程序时,请勿安排更新。 -在自动更新期间,应用程序将阻止某些操作,直到更新完成。 -要停止自动更新,请点击库标题旁边的加载指示器。 + + {series} gives %1 + {series} 得到 %1 - - Opacity level - 透明度 + + Optional parts + 可选部分 - - Display continue reading banner - 显示继续阅读横幅 + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + 写在 < 和 > 之间的部分,在其中所有字段都为空时会完全消失。请把属于某个字段的标点写在里面,例如括号或前置的井号。名称开头和结尾的文字即使不用它也会被修剪。 - - General - 常规 + + {series} ({year}) with no year gives %1 + {series} ({year}) 没有年份时得到 %1 - - Consider 'recent' items added or updated since X days ago - 参考自 X 天前添加或更新的“最近”项目 + + {series}< ({year})> with no year gives %1 + {series}< ({year})> 没有年份时得到 %1 - - Update libraries periodically - 定期更新库 + + Numbers + 编号 - - Use selected comic cover as background - 使用选定的漫画封面做背景 + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + 写一个冒号和若干个零,即可为期号补零。这样在文件管理器中各期仍按顺序排列。 - - Comic Flow - 漫画页面流 + + + Folders + 文件夹 - - Grid view - 网格视图 + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + 文件名格式不能包含斜杠。每本漫画都保留在当前文件夹中。请使用“整理到文件夹”来移动漫画。 - - Restart is needed - 需要重启 + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + 用斜杠分隔的每一部分都会变成一个文件夹。最后一部分是文件名。原有扩展名始终保留。 @@ -2263,12 +3189,12 @@ To stop an automatic update tap on the loading indicator next to the Libraries t 标签: - + Invalid cover 封面无效 - + The image is invalid. 该图像无效。 @@ -2531,6 +3457,35 @@ To stop an automatic update tap on the loading indicator next to the Libraries t 阅读列表 + + ReadingListManagementCoordinator + + + Add new reading lists + 添加新的阅读列表 + + + + + List name: + 列表名称: + + + + Delete list/label + 删除 列表/标签 + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + 所选项目将被删除,您的漫画或文件夹将不会从您的磁盘中删除。 你确定吗? + + + + Rename list name + 重命名列表 + + RenameLibraryDialog @@ -3244,6 +4199,61 @@ Use quotes to include spaces in a value. + + SelectedComicsInfoView + + + Unknown + 未知 + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + 已选择 %1 本漫画 + + + + Read + 阅读 + + + + In progress + 阅读中 + + + + Unread + 未读 + + + + Total pages + + + + + Total size + + + + + Series + 系列 + + SeriesQuestion @@ -3265,53 +4275,53 @@ Use quotes to include spaces in a value. ServerConfigDialog - - + + Server connectivity 服务器连接 - + Scan to connect 扫描以连接 - + Devices on this network can reach your library at the address below. 此网络中的设备可通过以下地址访问您的资料库。 - + IP address IP 地址 - + Port 端口 - + Web interface 网页界面 - + Copy link 复制链接 - + Open web UI 打开网页界面 - + Enable the server 启用服务器 - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. YACReader 支持 iOS 和 Android。获取 <a href='https://ios.yacreader.com'>iOS</a> 或 <a href='https://android.yacreader.com'>Android</a> 版本。 @@ -3328,7 +4338,7 @@ Use quotes to include spaces in a value. 扫一扫! - + Set port set port 设置端口 diff --git a/YACReaderLibrary/yacreaderlibrary_zh_HK.ts b/YACReaderLibrary/yacreaderlibrary_zh_HK.ts index f01829b88..4180e11af 100644 --- a/YACReaderLibrary/yacreaderlibrary_zh_HK.ts +++ b/YACReaderLibrary/yacreaderlibrary_zh_HK.ts @@ -203,11 +203,22 @@ ClassicComicsView - + Hide comic flow 隱藏 Comic Flow + + ComicFilesCoordinator + + Copying comics... + 複製漫畫中... + + + Moving comics... + 移動漫畫中... + + ComicInfoView @@ -291,70 +302,99 @@ 黑白 + + ComicManagementCoordinator + + + + YACReader not found + YACReader 未找到 + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + 未找到YACReader. YACReader應安裝在與YACReaderLibrary相同的檔夾中. + + + + YACReader not found. There might be a problem with your YACReader installation. + 未找到YACReader. YACReader的安裝可能有問題. + + + + Error + 錯誤 + + + + Error opening comic with third party reader. + 使用第三方閱讀器開啟漫畫時出錯。 + + ComicModel - + yes - + no - + Title 標題 - + File Name 檔案名 - + Pages 頁數 - + Size 大小 - + Read 閱讀 - + Current Page 當前頁 - + Publication Date 發行日期 - + Rating 評分 - + Series 系列 - + Volume 體積 - + Story Arc 故事線 @@ -387,45 +427,53 @@ 關閉 - - - + + + Looking for volume... 搜索卷... - - + + comic %1 of %2 - %3 第 %1 本 共 %2 本 - %3 - + %1 comics selected 已選擇 %1 本漫畫 - + Error connecting to ComicVine ComicVine 連接時出錯 - - + + Retrieving tags for : %1 正在檢索標籤: %1 - + Retrieving volume info... 正在接收卷資訊... - + Looking for comic... 搜索漫畫中... + + ContinueReadingGridHeader + + + Continue Reading... + 繼續閱讀... + + CreateLibraryDialog @@ -469,6 +517,14 @@ 所選路徑不存在或不是有效路徑. 確保您具有此檔夾的寫入許可權 + + DBHelper + + + The folder entry could not be found in the library database. + 在庫資料庫中找不到該檔夾的記錄。 + + EditShortcutsDialog @@ -505,6 +561,19 @@ 該資料夾還沒有漫畫 + + EmptyInfoView + + + Nothing selected + 未選取任何內容 + + + + Select a comic or folder to see its information. + 選取漫畫或資料夾以查看其資訊。 + + EmptyLabelWidget @@ -619,46 +688,158 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly 第 %1 頁 CRC 校驗失敗: 部分頁面將無法正確顯示 - + Unknown error opening the file 打開檔時出現未知錯誤 - + 7z not found 未找到 7z - + + Format not supported 不支持的檔格式 - - - Unsupported EPUB: %1 - - FolderContentView - Continue Reading... - 繼續閱讀... + 繼續閱讀... + + + + FolderInfoView + + + Unknown + 未知 + + + + Items + 項目 + + + + Type + 類型 + + + + Reading status + 閱讀狀態 + + + + Read + 閱讀 + + + + Unread + 未讀 + + + + Collection status + 收藏狀態 + + + + Completed + 已完成 + + + + In progress + 閱讀中 + + + + Added + 已加入 + + + + Updated + 已更新 + + + + FolderManagementCoordinator + + + Add new folder + 添加新的檔夾 + + + + Folder name: + 檔夾名稱: GridComicsView - + Show info 顯示資訊 + + Library + + + + Folder + 檔夾 + + + Favorites + 收藏夾 + + + Recently added + 最近新增 + + + + Manga + 日式漫畫 + + + + Western manga + 西式漫畫 + + + + Web comic + 網絡漫畫 + + + + Yonkoma + 四格漫畫 + + + + Comic + 漫畫 + + + + Unknown + 未知 + HelpAboutDialog @@ -808,282 +989,196 @@ - LibraryWindow + LibraryInfoView - - YACReader Library - YACReader 庫 + + Library info + 圖書館資訊 - - Library - + + Number of folders + 資料夾數量 - - Set as read - 設為已讀 + + Number of comics + 漫畫數量 - - - Set as unread - 設為未讀 + + Number of read comics + 已讀漫畫數量 + + + LibraryManagementCoordinator - - - - manga - 漫畫 + + Error opening the library + 打開庫時出錯 - - - - comic - 漫畫 + + Error creating the library + 創建庫時出錯 - - - - web comic - 網路漫畫 + + Error updating the library + 更新庫時出錯 + + + LibraryWindow - - - - western manga (left to right) - 西方漫畫(從左到右) + + YACReader Library + YACReader 庫 - + Library not available Library ' 庫不可用 - - Rescan library for XML info - 重新掃描庫的 XML 資訊 - - - + Delete folder 刪除檔夾 - - Open folder... - 打開檔夾... - - - - Set as uncompleted - 設為未完成 - - - - Set as completed - 設為已完成 - - - - Update folder - 更新檔夾 - - - - Folder - 檔夾 - - - - Comic - 漫畫 - - - + A repair of this library is already running (%1). Wait for it to finish. 此庫的修復已在執行中(%1)。請等待其完成。 - + The library is locked by a repair that did not finish. 此庫已被一個未完成的修復鎖定。 - + The library is locked by a repair started by %1. 此庫已被 %1 啟動的修復鎖定。 - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? 如果您確定沒有其他修復正在執行,可以移除該鎖定。移除鎖定並繼續? - + Upgrade failed 更新失敗 - + There were errors during library upgrade in: 漫畫庫更新時出現錯誤: - + Restore recovery failed 還原復原失敗 - + Update needed 需要更新 - + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? 此庫是使用舊版本的YACReaderLibrary創建的. 它需要更新. 現在更新? - + Download new version 下載新版本 - + This library was created with a newer version of YACReaderLibrary. Download the new version now? 此庫是使用較新版本的YACReaderLibrary創建的。 立即下載新版本? - + Library '%1' is no longer available. Do you want to remove it? 庫 '%1' 不再可用。 你想刪除它嗎? - + Old library 舊的庫 - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? 庫 '%1' 是通過舊版本的YACReaderLibrary創建的。 必須再次創建。 你想現在創建嗎? - - + Copying comics... 複製漫畫中... - - + Moving comics... 移動漫畫中... - + Folder name: 檔夾名稱: - + + + No folder selected 沒有選中的檔夾 - + + + Please, select a folder first 請先選擇一個檔夾 - + Error in path 路徑錯誤 - + There was an error accessing the folder's path 訪問檔夾的路徑時出錯 - + The selected folder and all its contents will be deleted from your disk. Are you sure? 所選檔夾及其所有內容將從磁片中刪除。 你確定嗎? - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. 嘗試刪除所選檔夾時出現問題。 請檢查寫入許可權,並確保沒有其他應用程式在使用這些檔夾或檔。 - - Add new reading lists - 添加新的閱讀列表 - - - - - List name: - 列表名稱: - - - - Delete list/label - 刪除 列表/標籤 - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - 所選項目將被刪除,您的漫畫或檔夾將不會從您的磁片中刪除。 你確定嗎? - - - - Rename list name - 重命名列表 - - - - - - 4koma (top to botom) - 4koma(由上至下) - - - - - - - Set type - 套裝類型 - - - - Set custom cover - 設定自訂封面 - - - - Delete custom cover - 刪除自訂封面 - - - + Save covers 保存封面 - + You are adding too many libraries. 您添加的庫太多了。 - + You are adding too many libraries. You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. @@ -1096,43 +1191,27 @@ YACReaderLibrary will not stop you from creating more libraries but you should k YACReaderLibrary不會阻止您創建更多的庫,但是您應該保持較低的庫數量來提升性能。 - - - YACReader not found - YACReader 未找到 - - - - Error - 錯誤 - - - - Error opening comic with third party reader. - 使用第三方閱讀器開啟漫畫時出錯。 - - - + Library not found 未找到庫 - + The selected folder doesn't contain any library. 所選檔夾不包含任何庫。 - + Are you sure? 你確定嗎? - + Do you want remove 你想要刪除 - + library? 庫? @@ -1141,124 +1220,165 @@ YACReaderLibrary不會阻止您創建更多的庫,但是您應該保持較低 移除並刪除元數據 - + Library info 圖書館資訊 - + Assign comics numbers 分配漫畫編號 - + Assign numbers starting in: 從以下位置開始分配編號: - - + + Unable to delete 無法刪除 - + + Rename or organize files + 重新命名或整理檔案 + + + + Set the type of the selected comics + 設定所選漫畫的類型 + + + Search filters 搜尋篩選器 - + Unread 未讀 - + In progress 閱讀中 - + Highly rated 高評分 - + Recently added 最近新增 - + Search syntax… 搜尋語法… - + Package operation failed - + 封裝作業失敗 - + The covers package operation could not be completed. - + 無法完成封面套件作業。 - - Add new folder - 添加新的檔夾 + + Rename folder + 重新命名檔夾 - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - 未找到YACReader. YACReader應安裝在與YACReaderLibrary相同的檔夾中. + + Invalid folder name + 檔夾名稱無效 - - YACReader not found. There might be a problem with your YACReader installation. - 未找到YACReader. YACReader的安裝可能有問題. + + The folder name is empty or contains characters that are not supported. + 檔夾名稱為空或包含不支援的字元。 + + + + + + Unable to rename folder + 無法重新命名檔夾 + + + + A file or folder named '%1' already exists. + 名為「%1」的檔案或檔夾已存在。 + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. + +Folder: %1 + 無法在磁碟上重新命名該檔夾。請檢查檔夾名稱與寫入權限。 + +檔夾:%1 + + + + The library database could not be updated. The folder rename on disk was reverted. + 無法更新庫資料庫。磁碟上的檔夾重新命名已復原。 + + + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + 無法更新庫資料庫,磁碟上的檔夾重新命名也無法復原。現在需要手動更新該庫。 - - + + YACReader library database (*.ydb) YACReader 漫畫庫資料庫 (*.ydb) - + The library database backup was created at: %1 漫畫庫資料庫備份已建立於: %1 - + Unable to create the library database backup: %1 無法建立漫畫庫資料庫備份: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? 還原前請關閉 YACReaderLibraryServer 及正在使用此漫畫庫的所有其他 YACReader 應用程式。是否繼續? - + Restoring library database... 正在還原漫畫庫資料庫... - + The current library database is invalid. Restore the selected backup anyway? 目前的漫畫庫資料庫無效。仍要還原所選備份嗎? - - + + The library maintenance lock may be stale. Remove it and retry? 漫畫庫維護鎖可能已失效。是否移除並重試? - + Restart YACReaderLibrary before attempting recovery again. @@ -1267,71 +1387,71 @@ Restart YACReaderLibrary before attempting recovery again. 再次嘗試復原前,請重新啟動 YACReaderLibrary。 - + The library database was restored successfully. Update the library now? 漫畫庫資料庫已成功還原。是否立即更新漫畫庫? - + Library database damaged 漫畫庫資料庫已損壞 - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. 漫畫庫「%1」的資料庫已損壞,因此無法執行一般更新、維護及備份。YACReader 可以嘗試修復資料庫。部分損壞的資料可能無法復原。現有備份不會被更改。 - + Attempt repair 嘗試修復 - + Restore a backup... 還原備份... - + Repairing library database... 正在修復漫畫庫資料庫... - - - + + + Library database repair 修復漫畫庫資料庫 - + Another maintenance operation is currently using this library. Try again after it finishes. 另一個維護操作正在使用此漫畫庫。請在操作完成後重試。 - + The library database is already valid. 漫畫庫資料庫已經有效。 - + Library database repaired 漫畫庫資料庫已修復 - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 已透過重建索引修復漫畫庫資料庫。損壞的原始檔案已保留於: %1 - + Library database rebuilt 漫畫庫資料庫已重建 - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1342,7 +1462,7 @@ Update the library now? 是否立即更新漫畫庫? - + The damaged original was preserved at: @@ -1353,12 +1473,12 @@ The damaged original was preserved at: %1 - + Library database repair failed 漫畫庫資料庫修復失敗 - + The library database could not be repaired: %1%2 @@ -1369,82 +1489,67 @@ You can restore a backup from the Library menu or recreate the library. 您可以從「漫畫庫」選單還原備份,或重新建立漫畫庫。 - + Remove and delete metadata and backups 移除並刪除中繼資料及備份 - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. 嘗試刪除所選漫畫時出現問題。 請檢查所選檔或包含檔夾中的寫入許可權。 - + Invalid image 圖片無效 - + The selected file is not a valid image. 所選檔案不是有效影像。 - + Error saving cover 儲存封面時發生錯誤 - + There was an error saving the cover image. 儲存封面圖片時發生錯誤。 - - Error creating the library - 創建庫時出錯 - - - - Error updating the library - 更新庫時出錯 - - - - Error opening the library - 打開庫時出錯 - - - + Delete comics 刪除漫畫 - + All the selected comics will be deleted from your disk. Are you sure? 所有選定的漫畫都將從您的磁片中刪除。你確定嗎? - + Remove comics 移除漫畫 - + Comics will only be deleted from the current label/list. Are you sure? 漫畫只會從當前標籤/列表中刪除。 你確定嗎? - + Library name already exists 庫名已存在 - + There is another library with the name '%1'. 已存在另一個名為'%1'的庫。 - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1456,763 +1561,1580 @@ Missing files: %3 LibraryWindowActions - + Create a new library 創建一個新的庫 - + Open an existing library 打開現有的庫 - - + + Export comics info 導出漫畫資訊 - - + + Import comics info 導入漫畫資訊 - + Pack covers 打包封面 - + Pack the covers of the selected library 打包所選庫的封面 - + Unpack covers 解壓封面 - + Unpack a catalog 解壓目錄 - + Update library 更新庫 - + Update current library 更新當前庫 - + Back up library database 備份漫畫庫資料庫 - + Create a backup of the current library database 建立目前漫畫庫資料庫的備份 - + Restore library database backup 還原漫畫庫資料庫備份 - + Restore the current library database from a backup 從備份還原目前的漫畫庫資料庫 - + Repair covers and comic info 修復封面及漫畫資訊 - + Retry comics with missing covers or incomplete information 重新處理缺少封面或資訊不完整的漫畫 - + Rename library 重命名庫 - + Rename current library 重命名當前庫 - + Remove library 移除庫 - + Remove current library from your collection 從您的集合中移除當前庫 - + Rescan library for XML info 重新掃描庫的 XML 資訊 - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. 嘗試查找漫畫檔內嵌的 XML 資訊。只有當創建庫的 YACReaderLibrary 版本低於 9.8.2 或者使用第三方軟體嵌入 XML 資訊時,才需要執行該操作。 - + Open library folder... 打開庫檔夾... - + Open the root folder of the current library 打開目前庫的根檔夾 - + Show library info 顯示圖書館資訊 - + Show information about the current library 顯示當前庫的信息 - + Open current comic 打開當前漫畫 - + Open current comic on YACReader 用YACReader打開漫畫 - + Save selected covers to... 選中的封面保存到... - + Save covers of the selected comics as JPG files 保存所選的封面為jpg - - + + Set as read 設為已讀 - + Set comic as read 漫畫設為已讀 - - + + Set as unread 設為未讀 - + Set comic as unread 漫畫設為未讀 - - + + manga 漫畫 - + Set issue as manga 將問題設定為漫畫 - - + + comic 漫畫 - + Set issue as normal 設置發行狀態為正常發行 - + western manga 西方漫畫 - + Set issue as western manga 將問題設定為西方漫畫 - - + + web comic 網路漫畫 - + Set issue as web comic 將問題設定為網路漫畫 - - + + yonkoma 四科馬 - + Set issue as yonkoma 將問題設定為 yonkoma - + Show/Hide marks 顯示/隱藏標記 - + Show or hide read marks 顯示或隱藏閱讀標記 - + Show/Hide recent indicator 顯示/隱藏最近的指標 - + Show or hide recent indicator 顯示或隱藏最近的指示器 - - + + Fullscreen mode on/off 全屏模式 開/關 - + Help, About YACReader 幫助, 關於 YACReader - + Add new folder 添加新的檔夾 - + Add new folder to the current library 在當前庫下添加新的檔夾 - + + Rename folder + 重新命名檔夾 + + + + Rename the current folder on disk and in the library + 在磁碟與庫中重新命名目前檔夾 + + + Delete folder 刪除檔夾 - + Delete current folder from disk 從磁片上刪除當前檔夾 - + Select root node 選擇根節點 - + Expand all nodes 展開所有節點 - + Collapse all nodes 折疊所有節點 - + Show options dialog 顯示選項對話框 - + Show comics server options dialog 顯示漫畫伺服器選項對話框 - - + + Change between comics views 漫畫視圖之間的變化 - + Open folder... 打開檔夾... - + + + Rename files... + Organize files + 重新命名檔案... + + + + + Organize into folders... + 整理到檔夾... + + + Set as uncompleted 設為未完成 - + Set as completed 設為已完成 - + Set custom cover 設定自訂封面 - + Delete custom cover 刪除自訂封面 - + western manga (left to right) 西方漫畫(從左到右) - + Open containing folder... 打開包含檔夾... - Reset comic rating - 重置漫畫評分 + 重置漫畫評分 - + Select all comics 全選漫畫 - + Edit 編輯 - + Assign current order to comics 將當前序號分配給漫畫 - + Update cover 更新封面 - + Delete selected comics 刪除所選的漫畫 - + Delete metadata from selected comics 從選定的漫畫中刪除元數據 - + Download tags from Comic Vine 從 Comic Vine 下載標籤 - + Focus search line 聚焦於搜索行 - + Focus comics view 聚焦於漫畫視圖 - + Edit shortcuts 編輯快捷鍵 - + &Quit 退出(&Q) - + Update folder 更新檔夾 - + Update current folder 更新當前檔夾 - + Scan legacy XML metadata 掃描舊版 XML 元數據 - + Add new reading list 添加新的閱讀列表 - + Add a new reading list to the current library 在當前庫添加新的閱讀列表 - + Remove reading list 移除閱讀列表 - + Remove current reading list from the library 從當前庫移除閱讀列表 - - Add new label - 添加新標籤 + + Add new label + 添加新標籤 + + + + Add a new label to this library + 在當前庫添加標籤 + + + + Rename selected list + 重命名列表 + + + + Rename any selected labels or lists + 重命名任何選定的標籤或列表 + + + + Add to... + 添加到... + + + + Favorites + 收藏夾 + + + + Add selected comics to favorites list + 將所選漫畫添加到收藏夾列表 + + + + + Reset rating + 重置評分 + + + + LibraryWindowMenus + + + comic + 漫畫 + + + + manga + 漫畫 + + + + western manga (left to right) + 西方漫畫(從左到右) + + + + web comic + 網路漫畫 + + + + 4koma (top to botom) + 4koma(由上至下) + + + + + + + Set type + 套裝類型 + + + + Library + + + + + Folder + 檔夾 + + + + Comic + 漫畫 + + + + Open folder... + 打開檔夾... + + + + Update folder + 更新檔夾 + + + + Rename folder + 重新命名檔夾 + + + + Rename files... + 重新命名檔案... + + + + Organize into folders... + 整理到檔夾... + + + + Rescan library for XML info + 重新掃描庫的 XML 資訊 + + + + Set as uncompleted + 設為未完成 + + + + Set as completed + 設為已完成 + + + + Set as read + 設為已讀 + + + + + Set as unread + 設為未讀 + + + + Set custom cover + 設定自訂封面 + + + + Delete custom cover + 刪除自訂封面 + + + + ListInfoView + + + 1 comic + 1 本漫畫 + + + + %1 comics + %1 本漫畫 + + + + Last day + 最近 1 天 + + + + Last %1 days + 最近 %1 天 + + + + 1 sublist + 1 個子清單 + + + + %1 sublists + %1 個子清單 + + + + LocalComicListModel + + + file name + 檔案名 + + + + NoLibrariesWidget + + + You don't have any libraries yet + 你還沒有庫 + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <p>您可以在任何檔夾中創建庫,YACReaderLibrary將導入此檔夾中的所有漫畫和文件夾。如果已有庫,則可以打開它們。</p><p>您可以把YACReader當成獨立應用來閱讀電腦上的漫畫。</p> + + + + create your first library + 創建你的第一個庫 + + + + add an existing one + 添加一個現有庫 + + + + NoSearchResultsWidget + + + No results + 沒有結果 + + + + OptionsDialog + + + Language + 語言 + + + + Application language + 應用程式語言 + + + + System default + 系統預設 + + + + Tray icon settings (experimental) + 託盤圖示設置 (實驗特性) + + + + Close to tray + 關閉至託盤 + + + + Start into the system tray + 啟動至系統託盤 + + + + Edit Comic Vine API key + 編輯Comic Vine API 密匙 + + + + Comic Vine API key + Comic Vine API 密匙 + + + + ComicInfo.xml legacy support + ComicInfo.xml 遺留支持 + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + 新增漫畫時從 ComicInfo.xml 匯入元數據 + + + + Consider 'recent' items added or updated since X days ago + 考慮自 X 天前新增或更新的「最近」項目 + + + + Third party reader + 第三方閱讀器 + + + + Write {comic_file_path} where the path should go in the command + 在命令中應將路徑寫入 {comic_file_path} + + + + Clear + 清空 + + + + Update libraries at startup + 啟動時更新庫 + + + + Try to detect changes automatically + 嘗試自動偵測變化 + + + + Update libraries periodically + 定期更新庫 + + + + Interval: + 間隔: + + + + 30 minutes + 30分鐘 + + + + 1 hour + 1小時 + + + + 2 hours + 2小時 + + + + 4 hours + 4小時 + + + + 8 hours + 8小時 + + + + 12 hours + 12小時 + + + + daily + 日常的 + + + + Update libraries at certain time + 定時更新庫 + + + + Time: + 時間: + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + 警告!在庫更新期間,將停用對資料庫的寫入! +當您可能正在積極使用應用程式時,請勿安排更新。 +在自動更新期間,應用程式將阻止某些操作,直到更新完成。 +若要停止自動更新,請點選庫標題旁的載入指示器。 + + + + Modifications detection + 修改檢測 + + + + Compare the modified date of files when updating a library (not recommended) + 更新庫時比較文件的修改日期(不建議) + + + + Enable background image + 啟用背景圖片 + + + + Opacity level + 透明度 + + + + Blur level + 模糊 + + + + Use selected comic cover as background + 使用選定的漫畫封面做背景 + + + + Restore defautls + 恢復默認值 + + + + Background + 背景 + + + + Display continue reading banner + 顯示繼續閱讀橫幅 + + + + Display current comic banner + 顯示目前漫畫橫幅 + + + + Continue reading + 繼續閱讀 + + + + Mix folders and comics + 混合顯示資料夾和漫畫 + + + + Start comics on a new row + 從新一行開始顯示漫畫 + + + + Content + 內容 + + + + Comic Flow + Comic Flow + + + + + Libraries + + + + + Grid view + 網格視圖 + + + + General + 常規 + + + + Appearance + 外貌 + + + + Options + 選項 + + + + Restart is needed + 需要重啟 + + + + OrganizeFiles + + + Renamed, %1 is already in use + 已重新命名,%1 已被使用 + + + + Missing metadata: %1 + 缺少中繼資料:%1 + + + + %1 could not be created + 無法建立 %1 + + + + OrganizeFilesCoordinator + + + + Organize files + 整理檔案 + + + + This folder does not contain any comics. + 此檔夾不包含任何漫畫。 + + + + This library is busy: %1 + 此庫忙碌中:%1 + + + + the library database could not be opened + 無法開啟庫資料庫 + + + + the library database could not be locked for writing + 無法鎖定庫資料庫以進行寫入 + + + + a folder entry could not be restored + 無法還原某個檔夾記錄 + + + + a comic entry could not be updated + 無法更新某筆漫畫記錄 + + + + the library database could not be saved: %1 + 無法儲存庫資料庫:%1 + + + + the record of the last organize run could not be read + 無法讀取上次整理的記錄 + + + + the folder %1 could not be created + 無法建立檔夾 %1 + + + + %n file(s) could not be moved back + + 有 %n 個檔案無法移回 + + + + + OrganizeFilesDialog + + Format: + 格式: + + + + Organize files + 整理檔案 + + + + + Rename files + 重新命名檔案 + + + + Preparing the preview... + 正在準備預覽... + + + + &Filename format: + 檔名格式(&F): + + + + &Path format: + 路徑格式(&P): + + + + Filename format + 檔名格式 + + + + Path format + 路徑格式 + + + + Presets + 預設組合 + + + + Insert + 插入 + + + + Optional part < > + 選用部分 < > + + + + Disappears completely when the fields inside it are empty. + 當其中的欄位為空時,這一部分會完全消失。 + + + + Padded number {number:000} + 補零編號 {number:000} + + + + Format help... + 格式說明... + + + + selected folder + 所選檔夾 + + + + library root + 庫根目錄 + + + + Move into + 移動到 + + + + Reset changes + 重設變更 + + + + Remove selected + 移除所選項目 + + + + Show unchanged + 顯示未變更項目 + + + + New name + 新名稱 + + + + Renamed from + 原名稱 + + + + New location + 新位置 + + + + Moved from + 原位置 + + + + Remove from list + 從清單中移除 + + + + Move files + 移動檔案 + + + + Cancel + 取消 + + + Copy the list + 複製清單 + + + + Undo + 復原 - - Add a new label to this library - 在當前庫添加標籤 + Close + 關閉 - - Rename selected list - 重命名列表 + + Copy failure details + 複製失敗詳細資訊 - - Rename any selected labels or lists - 重命名任何選定的標籤或列表 + + Finish + 完成 - - Add to... - 添加到... + + Remove preset + 移除預設組合 - - Favorites - 收藏夾 + + Save current format as preset... + 將目前格式保存為預設組合... - - Add selected comics to favorites list - 將所選漫畫添加到收藏夾列表 + + Reset to default format + 重設為預設格式 - - - LocalComicListModel - - file name - 檔案名 + + Save preset + 保存預設組合 - - - NoLibrariesWidget - - You don't have any libraries yet - 你還沒有庫 + + Preset name: + 預設組合名稱: - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <p>您可以在任何檔夾中創建庫,YACReaderLibrary將導入此檔夾中的所有漫畫和文件夾。如果已有庫,則可以打開它們。</p><p>您可以把YACReader當成獨立應用來閱讀電腦上的漫畫。</p> + + A filename format cannot contain "/". Use Organize files to move comics into folders. + 檔名格式不能包含 "/"。請使用「整理檔案」把漫畫移動到檔夾中。 - - create your first library - 創建你的第一個庫 + + This format cannot be used: %1 + 無法使用此格式:%1 - - add an existing one - 添加一個現有庫 + + new folder + 新檔夾 - - - NoSearchResultsWidget - - No results - 沒有結果 + + This folder does not exist yet. It will be created. + 此檔夾尚不存在,將會被建立。 - - - OptionsDialog - - Language - 語言 + + file not found + 找不到檔案 - - Application language - 應用程式語言 + + This comic is in the library but not on disk. It is skipped. + 此漫畫在庫中,但磁碟上沒有。將略過它。 - - System default - 系統預設 + + name in use + 名稱已被使用 - - Tray icon settings (experimental) - 託盤圖示設置 (實驗特性) + + no metadata + 無中繼資料 - - Close to tray - 關閉至託盤 + + already here + 已在此處 - - Start into the system tray - 啟動至系統託盤 + + This file is already in the right place. + 此檔案已在正確的位置。 - - Edit Comic Vine API key - 編輯Comic Vine API 密匙 + + edited + 已編輯 + + + + %n will be renamed + + %n 個將被重新命名 + + + + + %n will move + + %n 個將被移動 + + + + + %n unchanged + + %n 個未變更 + + + + + %n renamed + + %n 個已重新命名 + + + + + %n removed + + %n 個已移除 + + + + + %n missing + + %n 個遺失 + + + + + %n new folder(s) + + %n 個新檔夾 + + + + + %n manual change(s) kept + + 已保留 %n 處手動修改 + - - Comic Vine API key - Comic Vine API 密匙 + + Nothing would be renamed with this format. + 使用此格式不會重新命名任何檔案。 - - ComicInfo.xml legacy support - ComicInfo.xml 遺留支持 + + Nothing would move with this format. + 使用此格式不會移動任何檔案。 + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + 將重新命名 %n 個檔案。檔夾不會改變。之後可以復原。 + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + 將把 %n 個檔案移動到 %1。這會改變磁碟上的檔案。之後可以復原。 + - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics - 新增漫畫時從 ComicInfo.xml 匯入元數據 + + Moving %1 of %2 +%3 + 正在移動第 %1 個,共 %2 個 +%3 - - Consider 'recent' items added or updated since X days ago - 考慮自 X 天前新增或更新的「最近」項目 + + Updating the library... + 正在更新庫... - - Third party reader - 第三方閱讀器 + + Restored name + 已還原名稱 - - Write {comic_file_path} where the path should go in the command - 在命令中應將路徑寫入 {comic_file_path} + + + Moved back from + 移回自 - - Clear - 清空 + + + + + Status + 狀態 - - Update libraries at startup - 啟動時更新庫 + + Final name + 最終名稱 - - Try to detect changes automatically - 嘗試自動偵測變化 + + Previous name + 原名稱 - - Update libraries periodically - 定期更新庫 + + Restored location + 已還原位置 - - Interval: - 間隔: + + Final location + 最終位置 - - 30 minutes - 30分鐘 + + Previous location + 原位置 - - 1 hour - 1小時 + + Restored + 已還原 - - 2 hours - 2小時 + + Renamed + 已重新命名 - - 4 hours - 4小時 + + Moved + 已移動 - - 8 hours - 8小時 + + Undo failed: %1 + 復原失敗:%1 - - 12 hours - 12小時 + + Failed: %1 + 失敗:%1 - - daily - 日常的 + + Nothing was moved. + 沒有移動任何檔案。 - - Update libraries at certain time - 定時更新庫 + + The record this run could be undone from could not be written, so the run did not start: %1 + 無法寫入用於復原本次作業的記錄,因此作業沒有開始:%1 + + + + %n file(s) renamed. + + 已重新命名 %n 個檔案。 + + + + + %n file(s) moved into %1. + + 已把 %n 個檔案移動到 %1。 + - - Time: - 時間: + + The record of this run stopped early, so the run stopped with it: %1 + 本次作業的記錄提前中斷,因此作業也隨之停止:%1 + + + + %n file(s) were not moved. + + 有 %n 個檔案沒有被移動。 + - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. - 警告!在庫更新期間,將停用對資料庫的寫入! -當您可能正在積極使用應用程式時,請勿安排更新。 -在自動更新期間,應用程式將阻止某些操作,直到更新完成。 -若要停止自動更新,請點選庫標題旁的載入指示器。 + + The library database could not be updated: %1 + 無法更新庫資料庫:%1 - - Modifications detection - 修改檢測 + + Use Undo to move the files back, or update the library to make it match the files. + 使用「復原」把檔案移回原處,或更新庫使其與檔案一致。 + + + + %n empty folder(s) were removed. + + 已移除 %n 個空檔夾。 + + + + + %n file(s) could not be moved. + + 有 %n 個檔案無法移動。 + - - Compare the modified date of files when updating a library (not recommended) - 更新庫時比較文件的修改日期(不建議) + + Moving the files back... + 正在把檔案移回原處... - - Enable background image - 啟用背景圖片 + + Moving back %1 of %2 +%3 + 正在移回第 %1 個,共 %2 個 +%3 - - Opacity level - 透明度 + + Everything was moved back. + 所有檔案都已移回原處。 - - Blur level - 模糊 + + The undo did not finish: %1 + 復原沒有完成:%1 - - Use selected comic cover as background - 使用選定的漫畫封面做背景 + + Format help + 格式說明 - - Restore defautls - 恢復默認值 + + Fields + 欄位 - - Background - 背景 + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + 每個欄位都寫在大括號中,會被取代為漫畫的中繼資料。「插入」選單中列出了全部欄位。 - - Display continue reading banner - 顯示繼續閱讀橫幅 + + {series} gives %1 + {series} 得到 %1 - - Display current comic banner - 顯示目前漫畫橫幅 + + Optional parts + 選用部分 - - Continue reading - 繼續閱讀 + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + 寫在 < 和 > 之間的部分,在其中所有欄位都為空時會完全消失。請把屬於某個欄位的標點寫在裡面,例如括號或前置的井號。名稱開頭和結尾的文字即使不用它也會被修剪。 - - Comic Flow - Comic Flow + + {series} ({year}) with no year gives %1 + {series} ({year}) 沒有年份時得到 %1 - - - Libraries - + + {series}< ({year})> with no year gives %1 + {series}< ({year})> 沒有年份時得到 %1 - - Grid view - 網格視圖 + + Numbers + 編號 - - General - 常規 + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + 寫一個冒號和數個零,即可為期號補零。這樣在檔案管理員中各期仍按順序排列。 - - Appearance - 外貌 + + + Folders + 檔夾 - - Options - 選項 + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + 檔名格式不能包含斜線。每本漫畫都保留在目前檔夾中。請使用「整理到檔夾」來移動漫畫。 - - Restart is needed - 需要重啟 + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + 用斜線分隔的每一部分都會變成一個檔夾。最後一部分是檔名。原有副檔名一律保留。 @@ -2416,12 +3338,12 @@ To stop an automatic update tap on the loading indicator next to the Libraries t 語言(ISO): - + Invalid cover 封面無效 - + The image is invalid. 該圖像無效。 @@ -2539,6 +3461,35 @@ To stop an automatic update tap on the loading indicator next to the Libraries t 閱讀列表 + + ReadingListManagementCoordinator + + + Add new reading lists + 添加新的閱讀列表 + + + + + List name: + 列表名稱: + + + + Delete list/label + 刪除 列表/標籤 + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + 所選項目將被刪除,您的漫畫或檔夾將不會從您的磁片中刪除。 你確定嗎? + + + + Rename list name + 重命名列表 + + RenameLibraryDialog @@ -3252,6 +4203,61 @@ Use quotes to include spaces in a value. 卷描述不可用 + + SelectedComicsInfoView + + + Unknown + 未知 + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + 已選擇 %1 本漫畫 + + + + Read + 閱讀 + + + + In progress + 閱讀中 + + + + Unread + 未讀 + + + + Total pages + + + + + Total size + + + + + Series + 系列 + + SeriesQuestion @@ -3273,7 +4279,7 @@ Use quotes to include spaces in a value. ServerConfigDialog - + Set port set port 設定連接埠 @@ -3295,53 +4301,53 @@ Use quotes to include spaces in a value. 選擇IP地址 - - + + Server connectivity 伺服器連線 - + Scan to connect 掃描以連線 - + Devices on this network can reach your library at the address below. 此網絡中的裝置可透過以下地址存取你的資料庫。 - + IP address IP 地址 - + Port 端口 - + Web interface 網頁介面 - + Copy link 複製連結 - + Open web UI 開啟網頁介面 - + Enable the server 啟用伺服器 - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. YACReader 支援 iOS 及 Android。取得 <a href='https://ios.yacreader.com'>iOS</a> 或 <a href='https://android.yacreader.com'>Android</a> 版本。 diff --git a/YACReaderLibrary/yacreaderlibrary_zh_TW.ts b/YACReaderLibrary/yacreaderlibrary_zh_TW.ts index 8eae882f7..44aba9497 100644 --- a/YACReaderLibrary/yacreaderlibrary_zh_TW.ts +++ b/YACReaderLibrary/yacreaderlibrary_zh_TW.ts @@ -203,11 +203,22 @@ ClassicComicsView - + Hide comic flow 隱藏 Comic Flow + + ComicFilesCoordinator + + Copying comics... + 複製漫畫中... + + + Moving comics... + 移動漫畫中... + + ComicInfoView @@ -291,70 +302,99 @@ 黑白 + + ComicManagementCoordinator + + + + YACReader not found + YACReader 未找到 + + + + YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. + 未找到YACReader. YACReader應安裝在與YACReaderLibrary相同的檔夾中. + + + + YACReader not found. There might be a problem with your YACReader installation. + 未找到YACReader. YACReader的安裝可能有問題. + + + + Error + 錯誤 + + + + Error opening comic with third party reader. + 使用第三方閱讀器開啟漫畫時出錯。 + + ComicModel - + yes - + no - + Title 標題 - + File Name 檔案名 - + Pages 頁數 - + Size 大小 - + Read 閱讀 - + Current Page 當前頁 - + Publication Date 發行日期 - + Rating 評分 - + Series 系列 - + Volume 體積 - + Story Arc 故事線 @@ -387,45 +427,53 @@ 關閉 - - - + + + Looking for volume... 搜索卷... - - + + comic %1 of %2 - %3 第 %1 本 共 %2 本 - %3 - + %1 comics selected 已選擇 %1 本漫畫 - + Error connecting to ComicVine ComicVine 連接時出錯 - - + + Retrieving tags for : %1 正在檢索標籤: %1 - + Retrieving volume info... 正在接收卷資訊... - + Looking for comic... 搜索漫畫中... + + ContinueReadingGridHeader + + + Continue Reading... + 繼續閱讀... + + CreateLibraryDialog @@ -469,6 +517,14 @@ 所選路徑不存在或不是有效路徑. 確保您具有此檔夾的寫入許可權 + + DBHelper + + + The folder entry could not be found in the library database. + 在庫資料庫中找不到該檔夾的記錄。 + + EditShortcutsDialog @@ -505,6 +561,19 @@ 該資料夾還沒有漫畫 + + EmptyInfoView + + + Nothing selected + 未選取任何內容 + + + + Select a comic or folder to see its information. + 選取漫畫或資料夾以檢視其資訊。 + + EmptyLabelWidget @@ -619,46 +688,158 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly 第 %1 頁 CRC 校驗失敗: 部分頁面將無法正確顯示 - + Unknown error opening the file 打開檔時出現未知錯誤 - + 7z not found 未找到 7z - + + Format not supported 不支持的檔格式 - - - Unsupported EPUB: %1 - - FolderContentView - Continue Reading... - 繼續閱讀... + 繼續閱讀... + + + + FolderInfoView + + + Unknown + 未知 + + + + Items + 項目 + + + + Type + 類型 + + + + Reading status + 閱讀狀態 + + + + Read + 閱讀 + + + + Unread + 未讀 + + + + Collection status + 收藏狀態 + + + + Completed + 已完成 + + + + In progress + 閱讀中 + + + + Added + 已加入 + + + + Updated + 已更新 + + + + FolderManagementCoordinator + + + Add new folder + 添加新的檔夾 + + + + Folder name: + 檔夾名稱: GridComicsView - + Show info 顯示資訊 + + Library + + + + Folder + 檔夾 + + + Favorites + 收藏夾 + + + Recently added + 最近加入 + + + + Manga + 日式漫畫 + + + + Western manga + 西式漫畫 + + + + Web comic + 網路漫畫 + + + + Yonkoma + 四格漫畫 + + + + Comic + 漫畫 + + + + Unknown + 未知 + HelpAboutDialog @@ -808,282 +989,196 @@ - LibraryWindow + LibraryInfoView - - YACReader Library - YACReader 庫 + + Library info + 圖書館資訊 - - Library - + + Number of folders + 資料夾數量 - - Set as read - 設為已讀 + + Number of comics + 漫畫數量 - - - Set as unread - 設為未讀 + + Number of read comics + 已讀漫畫數量 + + + LibraryManagementCoordinator - - - - manga - 漫畫 + + Error opening the library + 打開庫時出錯 - - - - comic - 漫畫 + + Error creating the library + 創建庫時出錯 - - - - web comic - 網路漫畫 + + Error updating the library + 更新庫時出錯 + + + LibraryWindow - - - - western manga (left to right) - 西方漫畫(從左到右) + + YACReader Library + YACReader 庫 - + Library not available Library ' 庫不可用 - - Rescan library for XML info - 重新掃描庫的 XML 資訊 - - - + Delete folder 刪除檔夾 - - Open folder... - 打開檔夾... - - - - Set as uncompleted - 設為未完成 - - - - Set as completed - 設為已完成 - - - - Update folder - 更新檔夾 - - - - Folder - 檔夾 - - - - Comic - 漫畫 - - - + A repair of this library is already running (%1). Wait for it to finish. 此庫的修復已在執行中(%1)。請等待其完成。 - + The library is locked by a repair that did not finish. 此庫已被一個未完成的修復鎖定。 - + The library is locked by a repair started by %1. 此庫已被 %1 啟動的修復鎖定。 - + If you are sure that no other repair is running, the lock can be removed. Remove the lock and continue? 如果您確定沒有其他修復正在執行,可以移除該鎖定。移除鎖定並繼續? - + Upgrade failed 更新失敗 - + There were errors during library upgrade in: 漫畫庫更新時出現錯誤: - + Restore recovery failed 還原復原失敗 - + Update needed 需要更新 - + This library was created with a previous version of YACReaderLibrary. It needs to be updated. Update now? 此庫是使用舊版本的YACReaderLibrary創建的. 它需要更新. 現在更新? - + Download new version 下載新版本 - + This library was created with a newer version of YACReaderLibrary. Download the new version now? 此庫是使用較新版本的YACReaderLibrary創建的。 立即下載新版本? - + Library '%1' is no longer available. Do you want to remove it? 庫 '%1' 不再可用。 你想刪除它嗎? - + Old library 舊的庫 - + Library '%1' has been created with an older version of YACReaderLibrary. It must be created again. Do you want to create the library now? 庫 '%1' 是通過舊版本的YACReaderLibrary創建的。 必須再次創建。 你想現在創建嗎? - - + Copying comics... 複製漫畫中... - - + Moving comics... 移動漫畫中... - + Folder name: 檔夾名稱: - + + + No folder selected 沒有選中的檔夾 - + + + Please, select a folder first 請先選擇一個檔夾 - + Error in path 路徑錯誤 - + There was an error accessing the folder's path 訪問檔夾的路徑時出錯 - + The selected folder and all its contents will be deleted from your disk. Are you sure? 所選檔夾及其所有內容將從磁片中刪除。 你確定嗎? - - There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. + + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that no applications are using these folders or any of the contained files. + There was an issue trying to delete the selected folders. Please, check for write permissions and be sure that any applications are using these folders or any of the contained files. 嘗試刪除所選檔夾時出現問題。 請檢查寫入許可權,並確保沒有其他應用程式在使用這些檔夾或檔。 - - Add new reading lists - 添加新的閱讀列表 - - - - - List name: - 列表名稱: - - - - Delete list/label - 刪除 列表/標籤 - - - - The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? - 所選項目將被刪除,您的漫畫或檔夾將不會從您的磁片中刪除。 你確定嗎? - - - - Rename list name - 重命名列表 - - - - - - 4koma (top to botom) - 4koma(由上至下) - - - - - - - Set type - 套裝類型 - - - - Set custom cover - 設定自訂封面 - - - - Delete custom cover - 刪除自訂封面 - - - + Save covers 保存封面 - + You are adding too many libraries. 您添加的庫太多了。 - + You are adding too many libraries. You probably only need one library in your top level comics folder, you can browse any subfolders using the folders section in the left sidebar. @@ -1096,43 +1191,27 @@ YACReaderLibrary will not stop you from creating more libraries but you should k YACReaderLibrary不會阻止您創建更多的庫,但是您應該保持較低的庫數量來提升性能。 - - - YACReader not found - YACReader 未找到 - - - - Error - 錯誤 - - - - Error opening comic with third party reader. - 使用第三方閱讀器開啟漫畫時出錯。 - - - + Library not found 未找到庫 - + The selected folder doesn't contain any library. 所選檔夾不包含任何庫。 - + Are you sure? 你確定嗎? - + Do you want remove 你想要刪除 - + library? 庫? @@ -1141,124 +1220,165 @@ YACReaderLibrary不會阻止您創建更多的庫,但是您應該保持較低 移除並刪除元數據 - + Library info 圖書館資訊 - + Assign comics numbers 分配漫畫編號 - + Assign numbers starting in: 從以下位置開始分配編號: - - + + Unable to delete 無法刪除 - + + Rename or organize files + 重新命名或整理檔案 + + + + Set the type of the selected comics + 設定所選漫畫的類型 + + + Search filters 搜尋篩選條件 - + Unread 未讀 - + In progress 閱讀中 - + Highly rated 高評分 - + Recently added 最近加入 - + Search syntax… 搜尋語法… - + Package operation failed - + 封裝作業失敗 - + The covers package operation could not be completed. - + 無法完成封面套件作業。 - - Add new folder - 添加新的檔夾 + + Rename folder + 重新命名檔夾 - - YACReader not found. YACReader should be installed in the same folder as YACReaderLibrary. - 未找到YACReader. YACReader應安裝在與YACReaderLibrary相同的檔夾中. + + Invalid folder name + 檔夾名稱無效 - - YACReader not found. There might be a problem with your YACReader installation. - 未找到YACReader. YACReader的安裝可能有問題. + + The folder name is empty or contains characters that are not supported. + 檔夾名稱為空或包含不支援的字元。 + + + + + + Unable to rename folder + 無法重新命名檔夾 + + + + A file or folder named '%1' already exists. + 名為「%1」的檔案或檔夾已存在。 + + + + The folder could not be renamed on disk. Please check the folder name and write permissions. + +Folder: %1 + 無法在磁碟上重新命名該檔夾。請檢查檔夾名稱與寫入權限。 + +檔夾:%1 + + + + The library database could not be updated. The folder rename on disk was reverted. + 無法更新庫資料庫。磁碟上的檔夾重新命名已復原。 - - + + The library database could not be updated, and the folder rename on disk could not be reverted. The library now needs to be updated manually. + 無法更新庫資料庫,磁碟上的檔夾重新命名也無法復原。現在需要手動更新該庫。 + + + + YACReader library database (*.ydb) YACReader 漫畫庫資料庫 (*.ydb) - + The library database backup was created at: %1 漫畫庫資料庫備份已建立於: %1 - + Unable to create the library database backup: %1 無法建立漫畫庫資料庫備份: %1 - + Close YACReaderLibraryServer and any other YACReader application using this library before restoring. Continue? 還原前請關閉 YACReaderLibraryServer 以及正在使用此漫畫庫的所有其他 YACReader 應用程式。是否繼續? - + Restoring library database... 正在還原漫畫庫資料庫... - + The current library database is invalid. Restore the selected backup anyway? 目前的漫畫庫資料庫無效。仍要還原所選備份嗎? - - + + The library maintenance lock may be stale. Remove it and retry? 漫畫庫維護鎖可能已失效。是否移除並重試? - + Restart YACReaderLibrary before attempting recovery again. @@ -1267,71 +1387,71 @@ Restart YACReaderLibrary before attempting recovery again. 再次嘗試復原前,請重新啟動 YACReaderLibrary。 - + The library database was restored successfully. Update the library now? 漫畫庫資料庫已成功還原。是否立即更新漫畫庫? - + Library database damaged 漫畫庫資料庫已損壞 - + The database of library '%1' is damaged, so normal updates, maintenance, and backups are unavailable. YACReader can attempt to repair the database. Some damaged data may not be recoverable. Existing backups will not be changed. 漫畫庫「%1」的資料庫已損壞,因此無法執行一般更新、維護與備份。YACReader 可以嘗試修復資料庫。部分損壞的資料可能無法復原。現有備份不會被變更。 - + Attempt repair 嘗試修復 - + Restore a backup... 還原備份... - + Repairing library database... 正在修復漫畫庫資料庫... - - - + + + Library database repair 修復漫畫庫資料庫 - + Another maintenance operation is currently using this library. Try again after it finishes. 另一個維護操作正在使用此漫畫庫。請在操作完成後重試。 - + The library database is already valid. 漫畫庫資料庫已經有效。 - + Library database repaired 漫畫庫資料庫已修復 - + The library database was repaired by rebuilding its indexes. The damaged original was preserved at: %1 已透過重建索引修復漫畫庫資料庫。損壞的原始檔案已保留於: %1 - + Library database rebuilt 漫畫庫資料庫已重建 - + The library database was rebuilt successfully. The damaged original was preserved at: %1 @@ -1342,7 +1462,7 @@ Update the library now? 是否立即更新漫畫庫? - + The damaged original was preserved at: @@ -1353,12 +1473,12 @@ The damaged original was preserved at: %1 - + Library database repair failed 漫畫庫資料庫修復失敗 - + The library database could not be repaired: %1%2 @@ -1369,82 +1489,67 @@ You can restore a backup from the Library menu or recreate the library. 您可以從「漫畫庫」選單還原備份,或重新建立漫畫庫。 - + Remove and delete metadata and backups 移除並刪除中繼資料與備份 - + There was an issue trying to delete the selected comics. Please, check for write permissions in the selected files or containing folder. 嘗試刪除所選漫畫時出現問題。 請檢查所選檔或包含檔夾中的寫入許可權。 - + Invalid image 圖片無效 - + The selected file is not a valid image. 所選檔案不是有效影像。 - + Error saving cover 儲存封面時發生錯誤 - + There was an error saving the cover image. 儲存封面圖片時發生錯誤。 - - Error creating the library - 創建庫時出錯 - - - - Error updating the library - 更新庫時出錯 - - - - Error opening the library - 打開庫時出錯 - - - + Delete comics 刪除漫畫 - + All the selected comics will be deleted from your disk. Are you sure? 所有選定的漫畫都將從您的磁片中刪除。你確定嗎? - + Remove comics 移除漫畫 - + Comics will only be deleted from the current label/list. Are you sure? 漫畫只會從當前標籤/列表中刪除。 你確定嗎? - + Library name already exists 庫名已存在 - + There is another library with the name '%1'. 已存在另一個名為'%1'的庫。 - + Repaired: %1 Failed: %2 Missing files: %3 @@ -1456,763 +1561,1580 @@ Missing files: %3 LibraryWindowActions - + Create a new library 創建一個新的庫 - + Open an existing library 打開現有的庫 - - + + Export comics info 導出漫畫資訊 - - + + Import comics info 導入漫畫資訊 - + Pack covers 打包封面 - + Pack the covers of the selected library 打包所選庫的封面 - + Unpack covers 解壓封面 - + Unpack a catalog 解壓目錄 - + Update library 更新庫 - + Update current library 更新當前庫 - + Back up library database 備份漫畫庫資料庫 - + Create a backup of the current library database 建立目前漫畫庫資料庫的備份 - + Restore library database backup 還原漫畫庫資料庫備份 - + Restore the current library database from a backup 從備份還原目前的漫畫庫資料庫 - + Repair covers and comic info 修復封面與漫畫資訊 - + Retry comics with missing covers or incomplete information 重新處理缺少封面或資訊不完整的漫畫 - + Rename library 重命名庫 - + Rename current library 重命名當前庫 - + Remove library 移除庫 - + Remove current library from your collection 從您的集合中移除當前庫 - + Rescan library for XML info 重新掃描庫的 XML 資訊 - + Tries to find XML info embedded in comic files. You only need to do this if the library was created with 9.8.2 or earlier versions or if you are using third party software to embed XML info in the files. 嘗試查找漫畫檔內嵌的 XML 資訊。只有當創建庫的 YACReaderLibrary 版本低於 9.8.2 或者使用第三方軟體嵌入 XML 資訊時,才需要執行該操作。 - + Open library folder... 開啟資料庫資料夾... - + Open the root folder of the current library 開啟目前資料庫的根資料夾 - + Show library info 顯示圖書館資訊 - + Show information about the current library 顯示當前庫的信息 - + Open current comic 打開當前漫畫 - + Open current comic on YACReader 用YACReader打開漫畫 - + Save selected covers to... 選中的封面保存到... - + Save covers of the selected comics as JPG files 保存所選的封面為jpg - - + + Set as read 設為已讀 - + Set comic as read 漫畫設為已讀 - - + + Set as unread 設為未讀 - + Set comic as unread 漫畫設為未讀 - - + + manga 漫畫 - + Set issue as manga 將問題設定為漫畫 - - + + comic 漫畫 - + Set issue as normal 設置發行狀態為正常發行 - + western manga 西方漫畫 - + Set issue as western manga 將問題設定為西方漫畫 - - + + web comic 網路漫畫 - + Set issue as web comic 將問題設定為網路漫畫 - - + + yonkoma 四科馬 - + Set issue as yonkoma 將問題設定為 yonkoma - + Show/Hide marks 顯示/隱藏標記 - + Show or hide read marks 顯示或隱藏閱讀標記 - + Show/Hide recent indicator 顯示/隱藏最近的指標 - + Show or hide recent indicator 顯示或隱藏最近的指示器 - - + + Fullscreen mode on/off 全屏模式 開/關 - + Help, About YACReader 幫助, 關於 YACReader - + Add new folder 添加新的檔夾 - + Add new folder to the current library 在當前庫下添加新的檔夾 - + + Rename folder + 重新命名檔夾 + + + + Rename the current folder on disk and in the library + 在磁碟與庫中重新命名目前檔夾 + + + Delete folder 刪除檔夾 - + Delete current folder from disk 從磁片上刪除當前檔夾 - + Select root node 選擇根節點 - + Expand all nodes 展開所有節點 - + Collapse all nodes 折疊所有節點 - + Show options dialog 顯示選項對話框 - + Show comics server options dialog 顯示漫畫伺服器選項對話框 - - + + Change between comics views 漫畫視圖之間的變化 - + Open folder... 打開檔夾... - + + + Rename files... + Organize files + 重新命名檔案... + + + + + Organize into folders... + 整理到檔夾... + + + Set as uncompleted 設為未完成 - + Set as completed 設為已完成 - + Set custom cover 設定自訂封面 - + Delete custom cover 刪除自訂封面 - + western manga (left to right) 西方漫畫(從左到右) - + Open containing folder... 打開包含檔夾... - Reset comic rating - 重置漫畫評分 + 重置漫畫評分 - + Select all comics 全選漫畫 - + Edit 編輯 - + Assign current order to comics 將當前序號分配給漫畫 - + Update cover 更新封面 - + Delete selected comics 刪除所選的漫畫 - + Delete metadata from selected comics 從選定的漫畫中刪除元數據 - + Download tags from Comic Vine 從 Comic Vine 下載標籤 - + Focus search line 聚焦於搜索行 - + Focus comics view 聚焦於漫畫視圖 - + Edit shortcuts 編輯快捷鍵 - + &Quit 退出(&Q) - + Update folder 更新檔夾 - + Update current folder 更新當前檔夾 - + Scan legacy XML metadata 掃描舊版 XML 元數據 - + Add new reading list 添加新的閱讀列表 - + Add a new reading list to the current library 在當前庫添加新的閱讀列表 - + Remove reading list 移除閱讀列表 - + Remove current reading list from the library 從當前庫移除閱讀列表 - - Add new label - 添加新標籤 + + Add new label + 添加新標籤 + + + + Add a new label to this library + 在當前庫添加標籤 + + + + Rename selected list + 重命名列表 + + + + Rename any selected labels or lists + 重命名任何選定的標籤或列表 + + + + Add to... + 添加到... + + + + Favorites + 收藏夾 + + + + Add selected comics to favorites list + 將所選漫畫添加到收藏夾列表 + + + + + Reset rating + 重置評分 + + + + LibraryWindowMenus + + + comic + 漫畫 + + + + manga + 漫畫 + + + + western manga (left to right) + 西方漫畫(從左到右) + + + + web comic + 網路漫畫 + + + + 4koma (top to botom) + 4koma(由上至下) + + + + + + + Set type + 套裝類型 + + + + Library + + + + + Folder + 檔夾 + + + + Comic + 漫畫 + + + + Open folder... + 打開檔夾... + + + + Update folder + 更新檔夾 + + + + Rename folder + 重新命名檔夾 + + + + Rename files... + 重新命名檔案... + + + + Organize into folders... + 整理到檔夾... + + + + Rescan library for XML info + 重新掃描庫的 XML 資訊 + + + + Set as uncompleted + 設為未完成 + + + + Set as completed + 設為已完成 + + + + Set as read + 設為已讀 + + + + + Set as unread + 設為未讀 + + + + Set custom cover + 設定自訂封面 + + + + Delete custom cover + 刪除自訂封面 + + + + ListInfoView + + + 1 comic + 1 本漫畫 + + + + %1 comics + %1 本漫畫 + + + + Last day + 最近 1 天 + + + + Last %1 days + 最近 %1 天 + + + + 1 sublist + 1 個子清單 + + + + %1 sublists + %1 個子清單 + + + + LocalComicListModel + + + file name + 檔案名 + + + + NoLibrariesWidget + + + You don't have any libraries yet + 你還沒有庫 + + + + <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> + <p>您可以在任何檔夾中創建庫,YACReaderLibrary將導入此檔夾中的所有漫畫和文件夾。如果已有庫,則可以打開它們。</p><p>您可以把YACReader當成獨立應用來閱讀電腦上的漫畫。</p> + + + + create your first library + 創建你的第一個庫 + + + + add an existing one + 添加一個現有庫 + + + + NoSearchResultsWidget + + + No results + 沒有結果 + + + + OptionsDialog + + + Language + 語言 + + + + Application language + 應用程式語言 + + + + System default + 系統預設 + + + + Tray icon settings (experimental) + 託盤圖示設置 (實驗特性) + + + + Close to tray + 關閉至託盤 + + + + Start into the system tray + 啟動至系統託盤 + + + + Edit Comic Vine API key + 編輯Comic Vine API 密匙 + + + + Comic Vine API key + Comic Vine API 密匙 + + + + ComicInfo.xml legacy support + ComicInfo.xml 遺留支持 + + + + Import metadata from ComicInfo.xml when adding new comics + Import metada from ComicInfo.xml when adding new comics + 新增漫畫時從 ComicInfo.xml 匯入元數據 + + + + Consider 'recent' items added or updated since X days ago + 考慮自 X 天前新增或更新的「最近」項目 + + + + Third party reader + 第三方閱讀器 + + + + Write {comic_file_path} where the path should go in the command + 在命令中應將路徑寫入 {comic_file_path} + + + + Clear + 清空 + + + + Update libraries at startup + 啟動時更新庫 + + + + Try to detect changes automatically + 嘗試自動偵測變化 + + + + Update libraries periodically + 定期更新庫 + + + + Interval: + 間隔: + + + + 30 minutes + 30分鐘 + + + + 1 hour + 1小時 + + + + 2 hours + 2小時 + + + + 4 hours + 4小時 + + + + 8 hours + 8小時 + + + + 12 hours + 12小時 + + + + daily + 日常的 + + + + Update libraries at certain time + 定時更新庫 + + + + Time: + 時間: + + + + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +During automatic updates the app will block some of the actions until the update is finished. +To stop an automatic update tap on the loading indicator next to the Libraries title. + WARNING! During library updates writes to the database are disabled! +Don't schedule updates while you may be using the app actively. +To stop an automatic update tap on the loading indicator next to the Libraries title. + 警告!在庫更新期間,將停用對資料庫的寫入! +當您可能正在積極使用應用程式時,請勿安排更新。 +在自動更新期間,應用程式將阻止某些操作,直到更新完成。 +若要停止自動更新,請點選庫標題旁的載入指示器。 + + + + Modifications detection + 修改檢測 + + + + Compare the modified date of files when updating a library (not recommended) + 更新庫時比較文件的修改日期(不建議) + + + + Enable background image + 啟用背景圖片 + + + + Opacity level + 透明度 + + + + Blur level + 模糊 + + + + Use selected comic cover as background + 使用選定的漫畫封面做背景 + + + + Restore defautls + 恢復默認值 + + + + Background + 背景 + + + + Display continue reading banner + 顯示繼續閱讀橫幅 + + + + Display current comic banner + 顯示目前漫畫橫幅 + + + + Continue reading + 繼續閱讀 + + + + Mix folders and comics + 混合顯示資料夾和漫畫 + + + + Start comics on a new row + 從新的一列開始顯示漫畫 + + + + Content + 內容 + + + + Comic Flow + Comic Flow + + + + + Libraries + + + + + Grid view + 網格視圖 + + + + General + 常規 + + + + Appearance + 外貌 + + + + Options + 選項 + + + + Restart is needed + 需要重啟 + + + + OrganizeFiles + + + Renamed, %1 is already in use + 已重新命名,%1 已被使用 + + + + Missing metadata: %1 + 缺少中繼資料:%1 + + + + %1 could not be created + 無法建立 %1 + + + + OrganizeFilesCoordinator + + + + Organize files + 整理檔案 + + + + This folder does not contain any comics. + 此檔夾不包含任何漫畫。 + + + + This library is busy: %1 + 此庫忙碌中:%1 + + + + the library database could not be opened + 無法開啟庫資料庫 + + + + the library database could not be locked for writing + 無法鎖定庫資料庫以進行寫入 + + + + a folder entry could not be restored + 無法還原某個檔夾記錄 + + + + a comic entry could not be updated + 無法更新某筆漫畫記錄 + + + + the library database could not be saved: %1 + 無法儲存庫資料庫:%1 + + + + the record of the last organize run could not be read + 無法讀取上次整理的記錄 + + + + the folder %1 could not be created + 無法建立檔夾 %1 + + + + %n file(s) could not be moved back + + 有 %n 個檔案無法移回 + + + + + OrganizeFilesDialog + + Format: + 格式: + + + + Organize files + 整理檔案 + + + + + Rename files + 重新命名檔案 + + + + Preparing the preview... + 正在準備預覽... + + + + &Filename format: + 檔名格式(&F): + + + + &Path format: + 路徑格式(&P): + + + + Filename format + 檔名格式 + + + + Path format + 路徑格式 + + + + Presets + 預設組合 + + + + Insert + 插入 + + + + Optional part < > + 選用部分 < > + + + + Disappears completely when the fields inside it are empty. + 當其中的欄位為空時,這一部分會完全消失。 + + + + Padded number {number:000} + 補零編號 {number:000} + + + + Format help... + 格式說明... + + + + selected folder + 所選檔夾 + + + + library root + 庫根目錄 + + + + Move into + 移動到 + + + + Reset changes + 重設變更 + + + + Remove selected + 移除所選項目 + + + + Show unchanged + 顯示未變更項目 + + + + New name + 新名稱 + + + + Renamed from + 原名稱 + + + + New location + 新位置 + + + + Moved from + 原位置 + + + + Remove from list + 從清單中移除 + + + + Move files + 移動檔案 + + + + Cancel + 取消 + + + Copy the list + 複製清單 + + + + Undo + 復原 - - Add a new label to this library - 在當前庫添加標籤 + Close + 關閉 - - Rename selected list - 重命名列表 + + Copy failure details + 複製失敗詳細資訊 - - Rename any selected labels or lists - 重命名任何選定的標籤或列表 + + Finish + 完成 - - Add to... - 添加到... + + Remove preset + 移除預設組合 - - Favorites - 收藏夾 + + Save current format as preset... + 將目前格式保存為預設組合... - - Add selected comics to favorites list - 將所選漫畫添加到收藏夾列表 + + Reset to default format + 重設為預設格式 - - - LocalComicListModel - - file name - 檔案名 + + Save preset + 保存預設組合 - - - NoLibrariesWidget - - You don't have any libraries yet - 你還沒有庫 + + Preset name: + 預設組合名稱: - - <p>You can create a library in any folder, YACReaderLibrary will import all comics and folders from this folder. If you have created any library in the past you can open them.</p><p>Don't forget that you can use YACReader as a stand alone application for reading the comics on your computer.</p> - <p>您可以在任何檔夾中創建庫,YACReaderLibrary將導入此檔夾中的所有漫畫和文件夾。如果已有庫,則可以打開它們。</p><p>您可以把YACReader當成獨立應用來閱讀電腦上的漫畫。</p> + + A filename format cannot contain "/". Use Organize files to move comics into folders. + 檔名格式不能包含 "/"。請使用「整理檔案」把漫畫移動到檔夾中。 - - create your first library - 創建你的第一個庫 + + This format cannot be used: %1 + 無法使用此格式:%1 - - add an existing one - 添加一個現有庫 + + new folder + 新檔夾 - - - NoSearchResultsWidget - - No results - 沒有結果 + + This folder does not exist yet. It will be created. + 此檔夾尚不存在,將會被建立。 - - - OptionsDialog - - Language - 語言 + + file not found + 找不到檔案 - - Application language - 應用程式語言 + + This comic is in the library but not on disk. It is skipped. + 此漫畫在庫中,但磁碟上沒有。將略過它。 - - System default - 系統預設 + + name in use + 名稱已被使用 - - Tray icon settings (experimental) - 託盤圖示設置 (實驗特性) + + no metadata + 無中繼資料 - - Close to tray - 關閉至託盤 + + already here + 已在此處 - - Start into the system tray - 啟動至系統託盤 + + This file is already in the right place. + 此檔案已在正確的位置。 - - Edit Comic Vine API key - 編輯Comic Vine API 密匙 + + edited + 已編輯 + + + + %n will be renamed + + %n 個將被重新命名 + + + + + %n will move + + %n 個將被移動 + + + + + %n unchanged + + %n 個未變更 + + + + + %n renamed + + %n 個已重新命名 + + + + + %n removed + + %n 個已移除 + + + + + %n missing + + %n 個遺失 + + + + + %n new folder(s) + + %n 個新檔夾 + + + + + %n manual change(s) kept + + 已保留 %n 處手動修改 + - - Comic Vine API key - Comic Vine API 密匙 + + Nothing would be renamed with this format. + 使用此格式不會重新命名任何檔案。 - - ComicInfo.xml legacy support - ComicInfo.xml 遺留支持 + + Nothing would move with this format. + 使用此格式不會移動任何檔案。 + + + + %n file(s) will be renamed. The folders do not change. You can undo it afterwards. + + 將重新命名 %n 個檔案。檔夾不會改變。之後可以復原。 + + + + + %n file(s) will move into %1. This changes your files on disk. You can undo it afterwards. + + 將把 %n 個檔案移動到 %1。這會改變磁碟上的檔案。之後可以復原。 + - - Import metadata from ComicInfo.xml when adding new comics - Import metada from ComicInfo.xml when adding new comics - 新增漫畫時從 ComicInfo.xml 匯入元數據 + + Moving %1 of %2 +%3 + 正在移動第 %1 個,共 %2 個 +%3 - - Consider 'recent' items added or updated since X days ago - 考慮自 X 天前新增或更新的「最近」項目 + + Updating the library... + 正在更新庫... - - Third party reader - 第三方閱讀器 + + Restored name + 已還原名稱 - - Write {comic_file_path} where the path should go in the command - 在命令中應將路徑寫入 {comic_file_path} + + + Moved back from + 移回自 - - Clear - 清空 + + + + + Status + 狀態 - - Update libraries at startup - 啟動時更新庫 + + Final name + 最終名稱 - - Try to detect changes automatically - 嘗試自動偵測變化 + + Previous name + 原名稱 - - Update libraries periodically - 定期更新庫 + + Restored location + 已還原位置 - - Interval: - 間隔: + + Final location + 最終位置 - - 30 minutes - 30分鐘 + + Previous location + 原位置 - - 1 hour - 1小時 + + Restored + 已還原 - - 2 hours - 2小時 + + Renamed + 已重新命名 - - 4 hours - 4小時 + + Moved + 已移動 - - 8 hours - 8小時 + + Undo failed: %1 + 復原失敗:%1 - - 12 hours - 12小時 + + Failed: %1 + 失敗:%1 - - daily - 日常的 + + Nothing was moved. + 沒有移動任何檔案。 - - Update libraries at certain time - 定時更新庫 + + The record this run could be undone from could not be written, so the run did not start: %1 + 無法寫入用於復原本次作業的記錄,因此作業沒有開始:%1 + + + + %n file(s) renamed. + + 已重新命名 %n 個檔案。 + + + + + %n file(s) moved into %1. + + 已把 %n 個檔案移動到 %1。 + - - Time: - 時間: + + The record of this run stopped early, so the run stopped with it: %1 + 本次作業的記錄提前中斷,因此作業也隨之停止:%1 + + + + %n file(s) were not moved. + + 有 %n 個檔案沒有被移動。 + - - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -During automatic updates the app will block some of the actions until the update is finished. -To stop an automatic update tap on the loading indicator next to the Libraries title. - WARNING! During library updates writes to the database are disabled! -Don't schedule updates while you may be using the app actively. -To stop an automatic update tap on the loading indicator next to the Libraries title. - 警告!在庫更新期間,將停用對資料庫的寫入! -當您可能正在積極使用應用程式時,請勿安排更新。 -在自動更新期間,應用程式將阻止某些操作,直到更新完成。 -若要停止自動更新,請點選庫標題旁的載入指示器。 + + The library database could not be updated: %1 + 無法更新庫資料庫:%1 - - Modifications detection - 修改檢測 + + Use Undo to move the files back, or update the library to make it match the files. + 使用「復原」把檔案移回原處,或更新庫使其與檔案一致。 + + + + %n empty folder(s) were removed. + + 已移除 %n 個空檔夾。 + + + + + %n file(s) could not be moved. + + 有 %n 個檔案無法移動。 + - - Compare the modified date of files when updating a library (not recommended) - 更新庫時比較文件的修改日期(不建議) + + Moving the files back... + 正在把檔案移回原處... - - Enable background image - 啟用背景圖片 + + Moving back %1 of %2 +%3 + 正在移回第 %1 個,共 %2 個 +%3 - - Opacity level - 透明度 + + Everything was moved back. + 所有檔案都已移回原處。 - - Blur level - 模糊 + + The undo did not finish: %1 + 復原沒有完成:%1 - - Use selected comic cover as background - 使用選定的漫畫封面做背景 + + Format help + 格式說明 - - Restore defautls - 恢復默認值 + + Fields + 欄位 - - Background - 背景 + + Every field is written between braces and is replaced by the metadata of the comic. The Insert menu lists all of them. + 每個欄位都寫在大括號中,會被取代為漫畫的中繼資料。「插入」選單中列出了全部欄位。 - - Display continue reading banner - 顯示繼續閱讀橫幅 + + {series} gives %1 + {series} 得到 %1 - - Display current comic banner - 顯示目前漫畫橫幅 + + Optional parts + 選用部分 - - Continue reading - 繼續閱讀 + + A part written between the signs < and > disappears completely when every field inside it is empty. Use it for punctuation that belongs to a field, such as brackets or a leading number sign. Text at the start or the end of a name is trimmed without it. + 寫在 < 和 > 之間的部分,在其中所有欄位都為空時會完全消失。請把屬於某個欄位的標點寫在裡面,例如括號或前置的井號。名稱開頭和結尾的文字即使不用它也會被修剪。 - - Comic Flow - Comic Flow + + {series} ({year}) with no year gives %1 + {series} ({year}) 沒有年份時得到 %1 - - - Libraries - + + {series}< ({year})> with no year gives %1 + {series}< ({year})> 沒有年份時得到 %1 - - Grid view - 網格視圖 + + Numbers + 編號 - - General - 常規 + + Write a colon and some zeros to pad the issue number. This keeps the issues in order in a file browser. + 寫一個冒號和數個零,即可為期號補零。這樣在檔案管理員中各期仍按順序排列。 - - Appearance - 外貌 + + + Folders + 檔夾 - - Options - 選項 + + A filename format cannot contain a slash. Every comic keeps its current folder. Use Organize into folders to move comics. + 檔名格式不能包含斜線。每本漫畫都保留在目前檔夾中。請使用「整理到檔夾」來移動漫畫。 - - Restart is needed - 需要重啟 + + Each part separated by a slash becomes a folder. The last part becomes the file name. The original extension is always kept. + 用斜線分隔的每一部分都會變成一個檔夾。最後一部分是檔名。原有副檔名一律保留。 @@ -2416,12 +3338,12 @@ To stop an automatic update tap on the loading indicator next to the Libraries t 語言(ISO): - + Invalid cover 封面無效 - + The image is invalid. 該圖像無效。 @@ -2539,6 +3461,35 @@ To stop an automatic update tap on the loading indicator next to the Libraries t 閱讀列表 + + ReadingListManagementCoordinator + + + Add new reading lists + 添加新的閱讀列表 + + + + + List name: + 列表名稱: + + + + Delete list/label + 刪除 列表/標籤 + + + + The selected item will be deleted, your comics or folders will NOT be deleted from your disk. Are you sure? + 所選項目將被刪除,您的漫畫或檔夾將不會從您的磁片中刪除。 你確定嗎? + + + + Rename list name + 重命名列表 + + RenameLibraryDialog @@ -3252,6 +4203,61 @@ Use quotes to include spaces in a value. 卷描述不可用 + + SelectedComicsInfoView + + + Unknown + 未知 + + + + %1 (%2 unknown) + %1 (%n unknown) + + + + + %1 series + + + + + %1 comics selected + %n comic(s) selected + 已選擇 %1 本漫畫 + + + + Read + 閱讀 + + + + In progress + 閱讀中 + + + + Unread + 未讀 + + + + Total pages + + + + + Total size + + + + + Series + 系列 + + SeriesQuestion @@ -3273,7 +4279,7 @@ Use quotes to include spaces in a value. ServerConfigDialog - + Set port set port 設定連接埠 @@ -3295,53 +4301,53 @@ Use quotes to include spaces in a value. 選擇IP地址 - - + + Server connectivity 伺服器連線 - + Scan to connect 掃描以連線 - + Devices on this network can reach your library at the address below. 此網路中的裝置可透過以下位址存取您的資料庫。 - + IP address IP 位址 - + Port 端口 - + Web interface 網頁介面 - + Copy link 複製連結 - + Open web UI 開啟網頁介面 - + Enable the server 啟用伺服器 - + YACReader is available for iOS and Android. Discover it for <a href='https://ios.yacreader.com'>iOS</a> or <a href='https://android.yacreader.com'>Android</a>. YACReader 支援 iOS 與 Android。取得 <a href='https://ios.yacreader.com'>iOS</a> 或 <a href='https://android.yacreader.com'>Android</a> 版本。 diff --git a/YACReaderLibraryServer/console_ui_library_creator.cpp b/YACReaderLibraryServer/console_ui_library_creator.cpp index 1671c972b..ab6839889 100644 --- a/YACReaderLibraryServer/console_ui_library_creator.cpp +++ b/YACReaderLibraryServer/console_ui_library_creator.cpp @@ -6,6 +6,7 @@ #include "yacreader_libraries.h" #include +#include using namespace YACReader; @@ -212,7 +213,7 @@ int ConsoleUILibraryCreator::repairLibrary(const QString &path) << "Repaired: " << summary.repaired << std::endl << "Failed: " << summary.failed << std::endl << "Missing files: " << summary.missingFiles << std::endl; - for (const auto &failedPath : summary.failedFilePaths) { + for (const auto &failedPath : std::as_const(summary.failedFilePaths)) { std::cout << " " << failedPath.toStdString() << std::endl; } delete repairer; diff --git a/YACReaderLibraryServer/libraries_updater.cpp b/YACReaderLibraryServer/libraries_updater.cpp index b89c46b76..5b60ebb2e 100644 --- a/YACReaderLibraryServer/libraries_updater.cpp +++ b/YACReaderLibraryServer/libraries_updater.cpp @@ -16,7 +16,8 @@ void LibrariesUpdater::updateIfNeeded() libraries.load(); - for (const QString &name : libraries.getNames()) { + const auto libraryNames = libraries.getNames(); + for (const QString &name : libraryNames) { QString libraryPath = libraries.getPath(name); QString recoveryError; if (!DataBaseManagement::recoverInterruptedRestore(libraryPath, &recoveryError)) { diff --git a/YACReaderLibraryServer/main.cpp b/YACReaderLibraryServer/main.cpp index 53055e306..02588c00e 100644 --- a/YACReaderLibraryServer/main.cpp +++ b/YACReaderLibraryServer/main.cpp @@ -106,8 +106,9 @@ int main(int argc, char **argv) } if (parser.isSet("system-info")) { - auto globalInfo = YACReader::getGlobalInfo(); - for (const auto &line : globalInfo.split("\n")) { + const auto globalInfo = YACReader::getGlobalInfo(); + const auto globalInfoLines = globalInfo.split("\n"); + for (const auto &line : globalInfoLines) { qout << line << Qt::endl; } @@ -365,7 +366,8 @@ int listBackups(QCoreApplication &app, QCommandLineParser &parser, QTextStream & return 1; } - for (const auto &backup : DataBaseManagement::libraryBackups(args.at(1))) + const auto backups = DataBaseManagement::libraryBackups(args.at(1)); + for (const auto &backup : backups) qout << backup.fileName() << '\t' << backup.absoluteFilePath() << Qt::endl; return 0; } @@ -518,7 +520,8 @@ int listLibraries(QCoreApplication &app, QCommandLineParser &parser, QTextStream parser.process(app); YACReaderLibraries libraries = DBHelper::getLibraries(); - for (QString libraryName : libraries.getNames()) + const auto libraryNames = libraries.getNames(); + for (const QString &libraryName : libraryNames) qout << libraryName << " : " << libraries.getPath(libraryName) << Qt::endl; return 0; @@ -613,14 +616,15 @@ void messageHandler(QtMsgType type, const QMessageLogContext &context, const QSt void logSystemAndConfig() { QLOG_INFO() << "---------- System & configuration ----------"; - auto globalInfo = YACReader::getGlobalInfo(); - for (const auto &line : globalInfo.split("\n")) { + const auto globalInfo = YACReader::getGlobalInfo(); + const auto globalInfoLines = globalInfo.split("\n"); + for (const auto &line : globalInfoLines) { QLOG_INFO() << line; } - auto libraries = DBHelper::getLibraries().getLibraries(); + const auto libraries = DBHelper::getLibraries().getLibraries(); QLOG_INFO() << "Libraries: "; - for (auto library : libraries) { + for (const auto &library : libraries) { QLOG_INFO() << " " << library; auto access = DataBaseManagement::getDatabaseAccess(library.getPath()); QLOG_INFO() << " > STATUS: " << access; diff --git a/YACReaderLibraryServer/yacreaderlibraryserver_de.ts b/YACReaderLibraryServer/yacreaderlibraryserver_de.ts index 4091bbf16..b535caa4d 100644 --- a/YACReaderLibraryServer/yacreaderlibraryserver_de.ts +++ b/YACReaderLibraryServer/yacreaderlibraryserver_de.ts @@ -4,30 +4,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly CRC Error auf Seite (%1): Einige Seiten werden nicht korrekt dargestellt - + Unknown error opening the file Unbekannter Fehler beim Öffnen des Files - + 7z not found 7z nicht gefunden - + + Format not supported Format wird nicht unterstützt - - - Unsupported EPUB: %1 - - QCoreApplication diff --git a/YACReaderLibraryServer/yacreaderlibraryserver_es.ts b/YACReaderLibraryServer/yacreaderlibraryserver_es.ts index c661f56c3..566329d24 100644 --- a/YACReaderLibraryServer/yacreaderlibraryserver_es.ts +++ b/YACReaderLibraryServer/yacreaderlibraryserver_es.ts @@ -4,30 +4,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly Error CRC en la página (%1): algunas de las páginas no se mostrarán correctamente - + Unknown error opening the file Error desconocido abriendo el archivo - + 7z not found 7z no encontrado - + + Format not supported Formato no soportado - - - Unsupported EPUB: %1 - - QCoreApplication diff --git a/YACReaderLibraryServer/yacreaderlibraryserver_fr.ts b/YACReaderLibraryServer/yacreaderlibraryserver_fr.ts index e4b7cb86a..5260499d2 100644 --- a/YACReaderLibraryServer/yacreaderlibraryserver_fr.ts +++ b/YACReaderLibraryServer/yacreaderlibraryserver_fr.ts @@ -4,30 +4,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly Erreur CRC sur la page (%1): certaines pages ne s'afficheront pas correctement - + Unknown error opening the file Erreur inconnue lors de l'ouverture du fichier - + 7z not found 7z introuvable - + + Format not supported Format non supporté - - - Unsupported EPUB: %1 - - QCoreApplication diff --git a/YACReaderLibraryServer/yacreaderlibraryserver_ko.ts b/YACReaderLibraryServer/yacreaderlibraryserver_ko.ts index b9e9bc894..53d91b328 100644 --- a/YACReaderLibraryServer/yacreaderlibraryserver_ko.ts +++ b/YACReaderLibraryServer/yacreaderlibraryserver_ko.ts @@ -4,30 +4,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly %1번 페이지에서 CRC 오류 발생: 일부 페이지가 올바르게 표시되지 않을 수 있습니다 - + Unknown error opening the file 파일을 여는 중 알 수 없는 오류가 발생했습니다 - + 7z not found 7z를 찾을 수 없습니다 - + + Format not supported 지원하지 않는 형식입니다 - - - Unsupported EPUB: %1 - - QCoreApplication diff --git a/YACReaderLibraryServer/yacreaderlibraryserver_nl.ts b/YACReaderLibraryServer/yacreaderlibraryserver_nl.ts index 045113833..30b0741fd 100644 --- a/YACReaderLibraryServer/yacreaderlibraryserver_nl.ts +++ b/YACReaderLibraryServer/yacreaderlibraryserver_nl.ts @@ -4,30 +4,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly CRC-fout op pagina (%1): sommige pagina's worden niet correct weergegeven - + Unknown error opening the file Onbekende fout bij het openen van het bestand - + 7z not found 7Z Archiefbestand niet gevonden - + + Format not supported Formaat niet ondersteund - - - Unsupported EPUB: %1 - - QCoreApplication diff --git a/YACReaderLibraryServer/yacreaderlibraryserver_pt.ts b/YACReaderLibraryServer/yacreaderlibraryserver_pt.ts index 24df47418..3a05d96b9 100644 --- a/YACReaderLibraryServer/yacreaderlibraryserver_pt.ts +++ b/YACReaderLibraryServer/yacreaderlibraryserver_pt.ts @@ -4,30 +4,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly Erro CRC na página (%1): algumas páginas não serão exibidas corretamente - + Unknown error opening the file Erro desconhecido ao abrir o arquivo - + 7z not found 7z não encontrado - + + Format not supported Formato não suportado - - - Unsupported EPUB: %1 - - QCoreApplication diff --git a/YACReaderLibraryServer/yacreaderlibraryserver_ru.ts b/YACReaderLibraryServer/yacreaderlibraryserver_ru.ts index 81d6a2beb..6376c40bf 100644 --- a/YACReaderLibraryServer/yacreaderlibraryserver_ru.ts +++ b/YACReaderLibraryServer/yacreaderlibraryserver_ru.ts @@ -4,30 +4,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly Ошибка контрольной суммы CRC на странице (%1): некоторые страницы будут отображаться неправильно - + Unknown error opening the file Неизвестная ошибка при открытии файла - + 7z not found 7z не найден - + + Format not supported Формат не поддерживается - - - Unsupported EPUB: %1 - - QCoreApplication diff --git a/YACReaderLibraryServer/yacreaderlibraryserver_source.ts b/YACReaderLibraryServer/yacreaderlibraryserver_source.ts index 7e16d1045..90439fd09 100644 --- a/YACReaderLibraryServer/yacreaderlibraryserver_source.ts +++ b/YACReaderLibraryServer/yacreaderlibraryserver_source.ts @@ -4,30 +4,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly - + Unknown error opening the file - + 7z not found - + + Format not supported - - - Unsupported EPUB: %1 - - QCoreApplication diff --git a/YACReaderLibraryServer/yacreaderlibraryserver_tr.ts b/YACReaderLibraryServer/yacreaderlibraryserver_tr.ts index 1f82466cd..09e393ed0 100644 --- a/YACReaderLibraryServer/yacreaderlibraryserver_tr.ts +++ b/YACReaderLibraryServer/yacreaderlibraryserver_tr.ts @@ -4,30 +4,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly (%1). sayfada CRC hatası : bazı sayfalar düzgün görüntülenmeyecek - + Unknown error opening the file Dosya açılırken bilinmeyen hata - + 7z not found 7z bulunamadı - + + Format not supported Biçim desteklenmiyor - - - Unsupported EPUB: %1 - - QCoreApplication diff --git a/YACReaderLibraryServer/yacreaderlibraryserver_zh_CN.ts b/YACReaderLibraryServer/yacreaderlibraryserver_zh_CN.ts index 526cf7753..70eb8de75 100644 --- a/YACReaderLibraryServer/yacreaderlibraryserver_zh_CN.ts +++ b/YACReaderLibraryServer/yacreaderlibraryserver_zh_CN.ts @@ -4,30 +4,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly 第 %1 页 CRC 校验失败: 部分页面将无法正确显示 - + Unknown error opening the file 打开文件时出现未知错误 - + 7z not found 未找到 7z - + + Format not supported 不支持的文件格式 - - - Unsupported EPUB: %1 - - QCoreApplication diff --git a/YACReaderLibraryServer/yacreaderlibraryserver_zh_HK.ts b/YACReaderLibraryServer/yacreaderlibraryserver_zh_HK.ts index 2cd1d3d14..04b04fbd8 100644 --- a/YACReaderLibraryServer/yacreaderlibraryserver_zh_HK.ts +++ b/YACReaderLibraryServer/yacreaderlibraryserver_zh_HK.ts @@ -4,30 +4,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly 第 %1 頁 CRC 校驗失敗: 部分頁面將無法正確顯示 - + Unknown error opening the file 打開檔時出現未知錯誤 - + 7z not found 未找到 7z - + + Format not supported 不支持的檔格式 - - - Unsupported EPUB: %1 - - QCoreApplication diff --git a/YACReaderLibraryServer/yacreaderlibraryserver_zh_TW.ts b/YACReaderLibraryServer/yacreaderlibraryserver_zh_TW.ts index 873dee960..99def0eb6 100644 --- a/YACReaderLibraryServer/yacreaderlibraryserver_zh_TW.ts +++ b/YACReaderLibraryServer/yacreaderlibraryserver_zh_TW.ts @@ -4,30 +4,26 @@ FileComic - + CRC error on page (%1): some of the pages will not be displayed correctly 第 %1 頁 CRC 校驗失敗: 部分頁面將無法正確顯示 - + Unknown error opening the file 打開檔時出現未知錯誤 - + 7z not found 未找到 7z - + + Format not supported 不支持的檔格式 - - - Unsupported EPUB: %1 - - QCoreApplication diff --git a/cmake/CompilerOptions.cmake b/cmake/CompilerOptions.cmake index 429cf9954..b13cf87b6 100644 --- a/cmake/CompilerOptions.cmake +++ b/cmake/CompilerOptions.cmake @@ -2,6 +2,15 @@ # Keep this target internal so third-party code does not inherit our rules. add_library(yacreader_build_options INTERFACE) +# Link-time optimization for Release builds of YACReader-owned targets. +# Applied per-target in yacreader_apply_build_options() rather than globally, +# so third_party code keeps building with its own settings. +include(CheckIPOSupported) +check_ipo_supported(RESULT YACREADER_IPO_SUPPORTED OUTPUT YACREADER_IPO_ERROR) +if(NOT YACREADER_IPO_SUPPORTED) + message(STATUS "LTO not available, building without it: ${YACREADER_IPO_ERROR}") +endif() + target_compile_definitions(yacreader_build_options INTERFACE QT_DISABLE_DEPRECATED_UP_TO=0x060400 ) @@ -27,5 +36,9 @@ function(yacreader_apply_build_options) message(FATAL_ERROR "yacreader_apply_build_options(): unknown target '${target_name}'") endif() target_link_libraries("${target_name}" PRIVATE yacreader_build_options) + if(YACREADER_IPO_SUPPORTED) + set_property(TARGET "${target_name}" + PROPERTY INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE) + endif() endforeach() endfunction() diff --git a/common/comic.cpp b/common/comic.cpp index 2cdffc0fd..81ac21e9b 100644 --- a/common/comic.cpp +++ b/common/comic.cpp @@ -457,31 +457,8 @@ bool FileComic::isSupportedImage(const QString &fileName, const QStringList &sup YACReaderEpub::PageIndex FileComic::epubPageIndex(const QStringList &fileNames, CompressedArchive &archive) { - auto result = YACReaderEpub::readPageIndex(fileNames, [&archive](int index) { return archive.getRawDataAtIndex(index); }); - if (!result.isValid()) { - return result; - } - - QStringList pageNames; - for (const YACReaderEpub::Page &page : std::as_const(result.pages)) { - pageNames.append(page.fileName); - } - QSet supportedPageNames; - for (const QString &pageName : filter(pageNames)) { - supportedPageNames.insert(pageName); - } - - QVector supportedPages; - for (const YACReaderEpub::Page &page : std::as_const(result.pages)) { - if (supportedPageNames.contains(page.fileName)) { - supportedPages.append(page); - } - } - result.pages = std::move(supportedPages); - if (result.pages.isEmpty()) { - result.error = QStringLiteral("Package spine contains no supported image pages"); - } - return result; + const QStringList supportedExtensions = Comic::getSupportedImageLiteralFormats(); + return YACReaderEpub::readPageIndex(fileNames, [&archive](int index) { return archive.getRawDataAtIndex(index); }, [&supportedExtensions](const QString &fileName) { return isSupportedImage(fileName, supportedExtensions); }); } YACReaderEpub::ScanInfo FileComic::epubScanInfo(const QStringList &fileNames, CompressedArchive &archive, int coverPage) @@ -643,8 +620,10 @@ void FileComic::process() if (Comic::fileIsEpub(_path)) { const auto epub = epubPageIndex(archiveFileNames, archive); if (!epub.isValid()) { + // An EPUB book is not a comic, it is just a file type YACReader cannot open. + QLOG_INFO() << "Unable to open EPUB, it is not an image based comic" << _path << epub.error; moveToThread(QCoreApplication::instance()->thread()); - emit errorOpening(tr("Unsupported EPUB: %1").arg(epub.error)); + emit errorOpening(tr("Format not supported")); return; } diff --git a/common/cover_utils.cpp b/common/cover_utils.cpp index 63f35ff38..a1396e368 100644 --- a/common/cover_utils.cpp +++ b/common/cover_utils.cpp @@ -1,5 +1,8 @@ #include "cover_utils.h" +#include +#include + bool YACReader::saveCover(const QString &path, const QImage &cover) { QImage scaled; @@ -16,3 +19,16 @@ bool YACReader::saveCover(const QString &path, const QImage &cover) } return scaled.save(path, 0, 75); } + +QString YACReader::droppedImagePath(const QList &urls) +{ + if (urls.size() != 1 || !urls.constFirst().isLocalFile()) + return { }; + + const auto path = urls.constFirst().toLocalFile(); + if (!QFileInfo(path).isFile()) + return { }; + + QImageReader reader(path); + return reader.canRead() ? path : QString(); +} diff --git a/common/cover_utils.h b/common/cover_utils.h index 5e692bef6..fbbfb389f 100644 --- a/common/cover_utils.h +++ b/common/cover_utils.h @@ -2,8 +2,12 @@ #define COVER_UTILS_H #include +#include +#include +#include namespace YACReader { bool saveCover(const QString &path, const QImage &image); +QString droppedImagePath(const QList &urls); } #endif // COVER_UTILS_H diff --git a/common/epub_page_index.cpp b/common/epub_page_index.cpp index 746eb27c7..c6059ad76 100644 --- a/common/epub_page_index.cpp +++ b/common/epub_page_index.cpp @@ -7,6 +7,7 @@ #include #include +#include #include namespace { @@ -179,18 +180,68 @@ std::optional readPackage(const QByteArray &packageXml, QString &error) return package; } -std::optional imageFromWrapper(const QByteArray &document, const QString &documentPath, const QHash &archiveIndexes) +// A page of an image based comic may carry a handful of incidental characters (a page +// number, a chapter marker). Anything beyond that is real text that YACReader cannot +// render, so the document is not a picture wrapper. +constexpr int maximumIncidentalTextCharacters = 32; + +// Elements whose character data is never rendered as page text. +bool isNonRenderedSubtree(QStringView name) +{ + return name == QStringLiteral("head") || name == QStringLiteral("script") || name == QStringLiteral("style") || name == QStringLiteral("title") || name == QStringLiteral("desc") || name == QStringLiteral("metadata"); +} + +// Scanned comics sometimes carry an invisible OCR or accessibility text layer over the +// page image. It is not content the reader is expected to show. +bool isHiddenElement(const QXmlStreamAttributes &attributes) +{ + if (attributes.hasAttribute(QStringLiteral("hidden"))) { + return true; + } + const QString style = attribute(attributes, u"style").remove(' '); + return style.contains(QStringLiteral("display:none"), Qt::CaseInsensitive) || style.contains(QStringLiteral("visibility:hidden"), Qt::CaseInsensitive); +} + +int significantTextLength(QStringView text) +{ + int length = 0; + for (const QChar character : text) { + if (character.isSpace() || character.category() == QChar::Other_Format) { + continue; + } + ++length; + } + return length; +} + +struct WrapperImage { + QString path; + QString error; + + bool isValid() const { return error.isEmpty(); } +}; + +WrapperImage imageFromWrapper(const QByteArray &document, const QString &documentPath, const QHash &archiveIndexes) { HtmlEntityResolver entityResolver; QXmlStreamReader reader(document); reader.setEntityResolver(&entityResolver); QSet images; + int textLength = 0; while (!reader.atEnd()) { reader.readNext(); + if (reader.isCharacters()) { + textLength += significantTextLength(reader.text()); + continue; + } if (!reader.isStartElement()) { continue; } + if (isNonRenderedSubtree(reader.name()) || isHiddenElement(reader.attributes())) { + reader.skipCurrentElement(); + continue; + } QString reference; if (reader.name() == QStringLiteral("img")) { @@ -211,12 +262,15 @@ std::optional imageFromWrapper(const QByteArray &document, const QStrin } if (reader.hasError()) { - return std::nullopt; + return { { }, QStringLiteral("%1 is malformed: %2").arg(documentPath, reader.errorString()) }; + } + if (textLength > maximumIncidentalTextCharacters) { + return { { }, QStringLiteral("%1 contains %2 characters of text").arg(documentPath).arg(textLength) }; } if (images.size() != 1) { - return std::nullopt; + return { { }, QStringLiteral("%1 references %2 usable images").arg(documentPath).arg(images.size()) }; } - return *images.constBegin(); + return { *images.constBegin(), { } }; } struct Book { @@ -267,6 +321,14 @@ std::optional packageCoverPath(const Book &book) return std::nullopt; } +// A comic may legitimately carry a credits or copyright page among its images. A book +// whose spine is mostly made of documents YACReader cannot render is not a comic, and +// showing only the pictures it happens to contain would silently drop its content. +int toleratedNonImageSpineItems(int spineItemCount) +{ + return std::max(1, spineItemCount / 20); +} + YACReaderEpub::PageIndex pageIndexFromBook(const Book &book, const YACReaderEpub::FileReader &readFile, const YACReaderEpub::ImageFilter &acceptImage = { }) { YACReaderEpub::PageIndex result; @@ -275,14 +337,38 @@ YACReaderEpub::PageIndex pageIndexFromBook(const Book &book, const YACReaderEpub result.coverPath = *coverPath; } + int consideredItems = 0; + int nonImageItems = 0; + QString firstRejection; + const int tolerance = toleratedNonImageSpineItems(static_cast(book.package.spine.size())); + + const auto reject = [&](const QString &reason) { + ++nonImageItems; + if (firstRejection.isEmpty()) { + firstRejection = reason; + } + }; + for (const SpineItem &spineItem : book.package.spine) { + // Give up as soon as the book cannot qualify, so text books are cheap to reject. + if (nonImageItems > tolerance) { + break; + } + const auto manifestItem = book.package.manifest.constFind(spineItem.id); if (manifestItem == book.package.manifest.cend()) { + reject(QStringLiteral("spine item %1 is not in the manifest").arg(spineItem.id)); continue; } + // The navigation document is structural, not a page of the comic. + if (containsProperty(manifestItem->properties, u"nav")) { + continue; + } + ++consideredItems; const auto contentPath = resolvePath(book.packagePath, manifestItem->href); if (!contentPath) { + reject(QStringLiteral("%1 is not a valid resource path").arg(manifestItem->href)); continue; } @@ -292,24 +378,37 @@ YACReaderEpub::PageIndex pageIndexFromBook(const Book &book, const YACReaderEpub } else if (manifestItem->mediaType == QStringLiteral("application/xhtml+xml") || manifestItem->mediaType == QStringLiteral("image/svg+xml")) { const int wrapperIndex = book.archiveIndexes.value(*contentPath, -1); if (wrapperIndex < 0) { + reject(QStringLiteral("%1 is missing from the archive").arg(*contentPath)); continue; } - const auto wrapperImage = imageFromWrapper(readFile(wrapperIndex), *contentPath, book.archiveIndexes); - if (!wrapperImage) { + const WrapperImage wrapperImage = imageFromWrapper(readFile(wrapperIndex), *contentPath, book.archiveIndexes); + if (!wrapperImage.isValid()) { + reject(wrapperImage.error); continue; } - imagePath = *wrapperImage; + imagePath = wrapperImage.path; } else { + reject(QStringLiteral("%1 is not a page (%2)").arg(*contentPath, manifestItem->mediaType)); continue; } const int imageIndex = book.archiveIndexes.value(imagePath, -1); - if (imageIndex < 0 || (acceptImage && !acceptImage(imagePath))) { + if (imageIndex < 0) { + reject(QStringLiteral("%1 is missing from the archive").arg(imagePath)); + continue; + } + if (acceptImage && !acceptImage(imagePath)) { + reject(QStringLiteral("%1 is not a supported image").arg(imagePath)); continue; } result.pages.append({ imagePath, imageIndex }); } + if (nonImageItems > tolerance) { + result.pages.clear(); + result.error = QStringLiteral("EPUB is not image based: %1 of %2 checked spine items are not single image pages (%3)").arg(nonImageItems).arg(consideredItems).arg(firstRejection); + return result; + } if (result.pages.isEmpty()) { result.error = QStringLiteral("Package spine contains no usable image pages"); } @@ -320,7 +419,7 @@ YACReaderEpub::PageIndex pageIndexFromBook(const Book &book, const YACReaderEpub namespace YACReaderEpub { -PageIndex readPageIndex(const QStringList &fileNames, const FileReader &readFile) +PageIndex readPageIndex(const QStringList &fileNames, const FileReader &readFile, const ImageFilter &acceptImage) { QString error; const auto book = readBook(fileNames, readFile, error); @@ -329,7 +428,7 @@ PageIndex readPageIndex(const QStringList &fileNames, const FileReader &readFile result.error = error; return result; } - return pageIndexFromBook(*book, readFile); + return pageIndexFromBook(*book, readFile, acceptImage); } ScanInfo readScanInfo(const QStringList &fileNames, const FileReader &readFile, int coverPage, const ImageFilter &acceptImage) @@ -340,49 +439,12 @@ ScanInfo readScanInfo(const QStringList &fileNames, const FileReader &readFile, return result; } - const auto scanAllPages = [&] { - ScanInfo fullResult; - const PageIndex pages = pageIndexFromBook(*book, readFile, acceptImage); - fullResult.error = pages.error; - fullResult.pageCount = static_cast(pages.pages.size()); - if (fullResult.pageCount > 0) { - const int coverIndex = coverPage > 0 && coverPage <= fullResult.pageCount ? coverPage - 1 : 0; - fullResult.coverArchiveIndex = pages.pages.at(coverIndex).archiveIndex; - } - return fullResult; - }; - - if (!book->package.fixedLayout) { - return scanAllPages(); - } - - struct Candidate { - QString path; - bool wrapper = false; - }; - QVector candidates; - for (const SpineItem &spineItem : book->package.spine) { - const auto manifestItem = book->package.manifest.constFind(spineItem.id); - if (manifestItem == book->package.manifest.cend()) { - continue; - } - const auto contentPath = resolvePath(book->packagePath, manifestItem->href); - if (!contentPath || !book->archiveIndexes.contains(*contentPath)) { - continue; - } - - if (manifestItem->mediaType.startsWith(QStringLiteral("image/")) && manifestItem->mediaType != QStringLiteral("image/svg+xml")) { - if (!acceptImage || acceptImage(*contentPath)) { - candidates.append({ *contentPath, false }); - } - } else if (manifestItem->mediaType == QStringLiteral("application/xhtml+xml") || manifestItem->mediaType == QStringLiteral("image/svg+xml")) { - candidates.append({ *contentPath, true }); - } - } - - result.pageCount = static_cast(candidates.size()); + // The whole spine has to be walked to tell an image based comic from a book that + // merely contains images, so the reader and the library always agree on the pages. + const PageIndex pages = pageIndexFromBook(*book, readFile, acceptImage); + result.error = pages.error; + result.pageCount = static_cast(pages.pages.size()); if (result.pageCount == 0) { - result.error = QStringLiteral("Package spine contains no usable image pages"); return result; } @@ -395,17 +457,7 @@ ScanInfo readScanInfo(const QStringList &fileNames, const FileReader &readFile, } const int coverIndex = coverPage > 0 && coverPage <= result.pageCount ? coverPage - 1 : 0; - const Candidate &cover = candidates.at(coverIndex); - QString imagePath = cover.path; - if (cover.wrapper) { - const int wrapperIndex = book->archiveIndexes.value(cover.path); - const auto wrapperImage = imageFromWrapper(readFile(wrapperIndex), cover.path, book->archiveIndexes); - if (!wrapperImage || (acceptImage && !acceptImage(*wrapperImage))) { - return scanAllPages(); - } - imagePath = *wrapperImage; - } - result.coverArchiveIndex = book->archiveIndexes.value(imagePath, -1); + result.coverArchiveIndex = pages.pages.at(coverIndex).archiveIndex; return result; } diff --git a/common/epub_page_index.h b/common/epub_page_index.h index 96f7ca92f..418d21c9b 100644 --- a/common/epub_page_index.h +++ b/common/epub_page_index.h @@ -34,7 +34,7 @@ struct ScanInfo { using FileReader = std::function; using ImageFilter = std::function; -PageIndex readPageIndex(const QStringList &fileNames, const FileReader &readFile); +PageIndex readPageIndex(const QStringList &fileNames, const FileReader &readFile, const ImageFilter &acceptImage = { }); ScanInfo readScanInfo(const QStringList &fileNames, const FileReader &readFile, int coverPage, const ImageFilter &acceptImage); } diff --git a/common/rhi/yacreader_comic_flow_rhi.cpp b/common/rhi/yacreader_comic_flow_rhi.cpp index bba348df3..1b94e0075 100644 --- a/common/rhi/yacreader_comic_flow_rhi.cpp +++ b/common/rhi/yacreader_comic_flow_rhi.cpp @@ -25,6 +25,7 @@ void YACReaderComicFlow3D::setImagePaths(QStringList paths) } this->paths = paths; + loadingWindowCenter = -1; } void YACReaderComicFlow3D::updateImageData() @@ -32,6 +33,11 @@ void YACReaderComicFlow3D::updateImageData() if (worker->busy()) return; + if (loadingWindowCenter != currentSelected) { + failedImageLoads.clear(); + loadingWindowCenter = currentSelected; + } + int idx = worker->index(); if (idx >= 0 && !worker->result().isNull()) { if (!loaded[idx]) { @@ -56,6 +62,9 @@ void YACReaderComicFlow3D::updateImageData() } } + if (idx >= 0 && idx < loaded.size() && !loaded[idx]) + failedImageLoads.insert(idx); + int count = 8; switch (performance) { case low: @@ -83,11 +92,9 @@ void YACReaderComicFlow3D::updateImageData() for (int c = 0; c < 2 * count + 1; c++) { int i = indexes[c]; if ((i >= 0) && (i < numObjects)) - if (!loaded[i]) { - if (paths.size() > 0) { - QString fname = paths.at(i); - worker->generate(i, fname); - } + if (!loaded[i] && !failedImageLoads.contains(i)) { + if (!paths.isEmpty()) + worker->generate(i, paths.at(i)); delete[] indexes; return; } @@ -104,6 +111,7 @@ void YACReaderComicFlow3D::remove(int item) if (item >= 0 && item < paths.size()) { paths.removeAt(item); } + loadingWindowCenter = -1; worker->unlock(); } @@ -113,6 +121,7 @@ void YACReaderComicFlow3D::add(const QString &path, int index) worker->reset(); paths.insert(index, path); YACReaderFlow3D::add(index); + loadingWindowCenter = -1; worker->unlock(); } @@ -144,7 +153,7 @@ void YACReaderComicFlow3D::resortCovers(QList newOrder) loaded = loadedNew; marks = marksNew; images = imagesNew; - + loadingWindowCenter = -1; worker->unlock(); } @@ -189,7 +198,8 @@ ImageLoader3D::~ImageLoader3D() bool ImageLoader3D::busy() const { - return isRunning() ? working : false; + QMutexLocker locker(&mutex); + return working; } void ImageLoader3D::generate(int index, const QString &fileName) @@ -198,14 +208,16 @@ void ImageLoader3D::generate(int index, const QString &fileName) this->idx = index; this->fileName = fileName; this->img = QImage(); - mutex.unlock(); - - if (!isRunning()) - start(); - else { + this->working = true; + const bool shouldStart = !isRunning(); + if (!shouldStart) { restart = true; condition.wakeOne(); } + mutex.unlock(); + + if (shouldStart) + start(); } void ImageLoader3D::lock() @@ -233,6 +245,10 @@ void ImageLoader3D::run() this->img = image; mutex.unlock(); + QMetaObject::invokeMethod(flow, [flow = flow] { + flow->startAnimationTimer(); + }); + mutex.lock(); if (!this->restart) condition.wait(&mutex); @@ -243,5 +259,12 @@ void ImageLoader3D::run() QImage ImageLoader3D::result() { + QMutexLocker locker(&mutex); return img; } + +int ImageLoader3D::index() const +{ + QMutexLocker locker(&mutex); + return idx; +} diff --git a/common/rhi/yacreader_comic_flow_rhi.h b/common/rhi/yacreader_comic_flow_rhi.h index 61d65300e..947c02c35 100644 --- a/common/rhi/yacreader_comic_flow_rhi.h +++ b/common/rhi/yacreader_comic_flow_rhi.h @@ -4,6 +4,7 @@ #include "yacreader_flow_rhi.h" #include +#include #include class ImageLoader3D; @@ -21,6 +22,8 @@ class YACReaderComicFlow3D : public YACReaderFlow3D private: ImageLoader3D *worker; + QSet failedImageLoads; + int loadingWindowCenter = -1; protected: QList paths; @@ -38,7 +41,7 @@ class ImageLoader3D : public QThread idx = -1; fileName = ""; } - int index() const { return idx; } + int index() const; void lock(); void unlock(); QImage result(); @@ -49,7 +52,7 @@ class ImageLoader3D : public QThread void run() override; private: - QMutex mutex; + mutable QMutex mutex; QWaitCondition condition; bool restart; diff --git a/common/rhi/yacreader_flow_rhi.cpp b/common/rhi/yacreader_flow_rhi.cpp index 7db946660..695296098 100644 --- a/common/rhi/yacreader_flow_rhi.cpp +++ b/common/rhi/yacreader_flow_rhi.cpp @@ -20,6 +20,7 @@ YACReaderFlow3D::YACReaderFlow3D(QWidget *parent, struct Preset p) : QRhiWidget(parent), numObjects(0), lazyPopulateObjects(-1), + pendingCurrentIndex(-1), showMarks(true), hasBeenInitialized(false), backgroundColor(Qt::black), @@ -980,6 +981,31 @@ void YACReaderFlow3D::setCurrentIndex(int pos) viewRotateActive = 1; } +void YACReaderFlow3D::setCurrentIndexWithoutAnimation(int pos) +{ + if (pos < 0) + return; + + if (images.isEmpty() && lazyPopulateObjects > 0) { + pendingCurrentIndex = qMin(pos, lazyPopulateObjects - 1); + return; + } + + if (pos >= images.size()) + return; + + pendingCurrentIndex = -1; + currentSelected = pos; + for (auto index = 0; index < images.size(); ++index) { + calcVector(images[index].animEnd, index - currentSelected); + images[index].current = images[index].animEnd; + } + + viewRotate = 0; + cleanupAnimation(); + startAnimationTimer(); +} + void YACReaderFlow3D::updatePositions() { int count; @@ -1103,7 +1129,6 @@ void YACReaderFlow3D::populate(int n) if (hasBeenInitialized) { clear(); } - emit centerIndexChanged(0); float x = 1; float y = 1 * (700.f / 480.0f); @@ -1114,6 +1139,14 @@ void YACReaderFlow3D::populate(int n) } loaded = QVector(n, false); + + if (pendingCurrentIndex >= 0 && n > 0) { + const auto index = qMin(pendingCurrentIndex, n - 1); + setCurrentIndexWithoutAnimation(index); + emit centerIndexChanged(index); + } else { + emit centerIndexChanged(0); + } } void YACReaderFlow3D::reset() @@ -1139,6 +1172,7 @@ void YACReaderFlow3D::reset() numObjects = 0; images.clear(); + pendingCurrentIndex = -1; if (!hasBeenInitialized) lazyPopulateObjects = -1; diff --git a/common/rhi/yacreader_flow_rhi.h b/common/rhi/yacreader_flow_rhi.h index a1062bbb3..9a36597b6 100644 --- a/common/rhi/yacreader_flow_rhi.h +++ b/common/rhi/yacreader_flow_rhi.h @@ -151,6 +151,7 @@ class YACReaderFlow3D : public QRhiWidget, public ScrollManagement int numObjects; int lazyPopulateObjects; + int pendingCurrentIndex; bool showMarks; QVector loaded; QVector marks; @@ -232,6 +233,7 @@ class YACReaderFlow3D : public QRhiWidget, public ScrollManagement void showPrevious(); void showNext(); void setCurrentIndex(int pos); + void setCurrentIndexWithoutAnimation(int pos); void cleanupAnimation(); void draw(); void updatePositions(); diff --git a/common/themes/appearance_tab_widget.cpp b/common/themes/appearance_tab_widget.cpp index 4e79f9931..80d95055f 100644 --- a/common/themes/appearance_tab_widget.cpp +++ b/common/themes/appearance_tab_widget.cpp @@ -232,7 +232,8 @@ void AppearanceTabWidget::populateCombo(QComboBox *combo, if (!repository) return; - for (const auto &entry : repository->availableThemes()) { + const auto availableThemes = repository->availableThemes(); + for (const auto &entry : availableThemes) { if (variantFilter && entry.variant != *variantFilter) continue; combo->addItem(entry.displayName, entry.id); diff --git a/common/themes/theme_repository.cpp b/common/themes/theme_repository.cpp index 989219f1c..c98aa6c1a 100644 --- a/common/themes/theme_repository.cpp +++ b/common/themes/theme_repository.cpp @@ -9,6 +9,7 @@ #include #include +#include namespace { QString builtinNameFromFileName(QString fileName) @@ -131,7 +132,7 @@ bool ThemeRepository::deleteUserTheme(const QString &themeId) if (themeId.startsWith("builtin/")) return false; - for (const auto &u : userThemes) { + for (const auto &u : std::as_const(userThemes)) { if (u.id == themeId) { const bool removed = QFile::remove(u.filePath); if (removed) @@ -194,7 +195,7 @@ void ThemeRepository::scanBuiltins() return lhsName < rhsName; }); - for (const auto &fileName : builtinFiles) { + for (const auto &fileName : std::as_const(builtinFiles)) { const QString name = builtinNameFromFileName(fileName); if (name.isEmpty()) continue; diff --git a/common/yacreader_global.h b/common/yacreader_global.h index 810878628..1ffd3a1a8 100644 --- a/common/yacreader_global.h +++ b/common/yacreader_global.h @@ -19,6 +19,12 @@ class QLibrary; #define DB_VERSION "9.16.0" #define IMPORT_COMIC_INFO_XML_METADATA "IMPORT_COMIC_INFO_XML_METADATA" +#define ORGANIZE_FILES_RELATIVE_TO_ROOT "ORGANIZE_FILES_RELATIVE_TO_ROOT" +#define ORGANIZE_FILES_FILENAME_PATTERN "ORGANIZE_FILES_FILENAME_PATTERN" +#define ORGANIZE_FILES_PATH_PATTERN "ORGANIZE_FILES_PATH_PATTERN" +#define ORGANIZE_FILES_SHOW_UNCHANGED "ORGANIZE_FILES_SHOW_UNCHANGED" +#define ORGANIZE_FILES_FILENAME_PRESETS "ORGANIZE_FILES_FILENAME_PRESETS" +#define ORGANIZE_FILES_PATH_PRESETS "ORGANIZE_FILES_PATH_PRESETS" #define COMPARE_MODIFIED_DATE_ON_LIBRARY_UPDATES "COMPARE_MODIFIED_DATE_ON_LIBRARY_UPDATES" #define UPDATE_LIBRARIES_AT_STARTUP "UPDATE_LIBRARIES_AT_STARTUP" #define DETECT_CHANGES_IN_LIBRARIES_AUTOMATICALLY "DETECT_CHANGES_IN_LIBRARIES_AUTOMATICALLY" diff --git a/common/yacreader_global_gui.cpp b/common/yacreader_global_gui.cpp index f86dc449d..80c5e9d6a 100644 --- a/common/yacreader_global_gui.cpp +++ b/common/yacreader_global_gui.cpp @@ -87,7 +87,8 @@ QPixmap YACReader::hdpiPixmap(const QString &file, QSize size) QString YACReader::imageFileLoader(QWidget *parent) { QString supportedImageFormatsString; - for (const QByteArray &format : QImageReader::supportedImageFormats()) { + const auto supportedImageFormats = QImageReader::supportedImageFormats(); + for (const QByteArray &format : supportedImageFormats) { supportedImageFormatsString += QString("*.%1 ").arg(QString(format)); } @@ -108,7 +109,7 @@ QString YACReader::imagePathFromMimeData(const QMimeData *mimeData) QFileInfo fileInfo(filePath); QString extension = fileInfo.suffix().toLower(); - QList supportedFormats = QImageReader::supportedImageFormats(); + const QList supportedFormats = QImageReader::supportedImageFormats(); bool isSupported = false; for (const QByteArray &format : supportedFormats) { diff --git a/common/yacreader_global_gui.h b/common/yacreader_global_gui.h index d671b30ea..9cbd7b002 100644 --- a/common/yacreader_global_gui.h +++ b/common/yacreader_global_gui.h @@ -75,6 +75,8 @@ #define COMICS_GRID_COVER_SIZES "COMICS_GRID_COVER_SIZES" #define COMICS_GRID_SHOW_INFO "COMICS_GRID_SHOW_INFO" #define COMICS_GRID_INFO_WIDTH "COMICS_GRID_INFO_WIDTH" +#define COMICS_GRID_MIX_FOLDERS_AND_COMICS "COMICS_GRID_MIX_FOLDERS_AND_COMICS" +#define COMICS_GRID_START_COMICS_ON_NEW_ROW "COMICS_GRID_START_COMICS_ON_NEW_ROW" #define COMIC_VINE_API_KEY "COMIC_VINE_API_KEY" #define COMIC_VINE_BASE_URL "COMIC_VINE_BASE_URL" diff --git a/compileOSX.sh b/compileOSX.sh index 519624dfb..d3486fe2e 100755 --- a/compileOSX.sh +++ b/compileOSX.sh @@ -37,7 +37,7 @@ cmake -B build \ -DBUILD_NUMBER="${BUILD_NUMBER}" \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_OSX_ARCHITECTURES="${ARCHS}" \ - -DCMAKE_OSX_DEPLOYMENT_TARGET=11 + -DCMAKE_OSX_DEPLOYMENT_TARGET=12 cmake --build build --parallel diff --git a/custom_widgets/rounded_corners_dialog.cpp b/custom_widgets/rounded_corners_dialog.cpp index d6ae98abf..7bca916ac 100644 --- a/custom_widgets/rounded_corners_dialog.cpp +++ b/custom_widgets/rounded_corners_dialog.cpp @@ -25,7 +25,7 @@ QMargins marginsForEffect(const QGraphicsEffect &effect, const QSize &contentSiz YACReader::RoundedCornersDialog::RoundedCornersDialog(QWidget *parent) : QDialog(parent), m_dialogSurface(new QWidget(this)) { - setWindowFlags(windowFlags() | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint); + setWindowFlags(windowFlags() | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::NoDropShadowWindowHint); setAttribute(Qt::WA_TranslucentBackground); auto layout = new QVBoxLayout(this); diff --git a/custom_widgets/whats_new_dialog.cpp b/custom_widgets/whats_new_dialog.cpp index d67dbd6a5..4eddee35d 100644 --- a/custom_widgets/whats_new_dialog.cpp +++ b/custom_widgets/whats_new_dialog.cpp @@ -271,9 +271,7 @@ QString YACReader::WhatsNewDialog::renderHtmlDocument(const QString &content) co QString YACReader::WhatsNewDialog::renderIntro() const { - return "YACReader 10.2 adds a new basic web reader, redesigned settings dialogs, and experimental EPUB support. " - "It also brings more natural zoom controls, a better magnifying glass with an option to make it round, and more. " - "Don't forget to check the new built-in search guide so you can make the most of the search engine."; + return "YACReader 10.3 brings a much better library navigation experience!"; } QString YACReader::WhatsNewDialog::renderFooter() const diff --git a/custom_widgets/yacreader_search_line_edit.h b/custom_widgets/yacreader_search_line_edit.h index b9b195503..92c220e33 100644 --- a/custom_widgets/yacreader_search_line_edit.h +++ b/custom_widgets/yacreader_search_line_edit.h @@ -21,7 +21,7 @@ class YACReaderSearchLineEdit : public QLineEdit, protected Themable void setSearchMenu(QMenu *menu); protected: - void resizeEvent(QResizeEvent *); + void resizeEvent(QResizeEvent *) override; void applyTheme(const Theme &theme) override; signals: diff --git a/custom_widgets/yacreader_sidebar.cpp b/custom_widgets/yacreader_sidebar.cpp index a4cd113d9..55c234987 100644 --- a/custom_widgets/yacreader_sidebar.cpp +++ b/custom_widgets/yacreader_sidebar.cpp @@ -10,6 +10,8 @@ #include #include +#include + YACReaderSideBar::YACReaderSideBar(QWidget *parent) : QWidget(parent) { @@ -148,7 +150,7 @@ void YACReaderSideBar::applyTheme(const Theme &theme) foldersTitle->setTitle(applyCase(QObject::tr("Folders"))); readingListsTitle->setTitle(applyCase(QObject::tr("Reading Lists"))); - for (auto separator : separators) { + for (auto separator : std::as_const(separators)) { separator->setColor(theme.sidebar.sectionSeparatorColor); } diff --git a/custom_widgets/yacreader_sidebar.h b/custom_widgets/yacreader_sidebar.h index 82e6933e2..004b69582 100644 --- a/custom_widgets/yacreader_sidebar.h +++ b/custom_widgets/yacreader_sidebar.h @@ -36,7 +36,7 @@ class YACReaderSideBar : public QWidget, protected Themable Q_OBJECT public: explicit YACReaderSideBar(QWidget *parent = 0); - QSize sizeHint() const; + QSize sizeHint() const override; YACReaderFoldersView *foldersView; YACReaderReadingListsView *readingListsView; @@ -50,8 +50,8 @@ class YACReaderSideBar : public QWidget, protected Themable public slots: protected: - void paintEvent(QPaintEvent *); - void closeEvent(QCloseEvent *event); + void paintEvent(QPaintEvent *) override; + void closeEvent(QCloseEvent *event) override; void applyTheme(const Theme &theme) override; QSettings *settings; diff --git a/custom_widgets/yacreader_table_view.cpp b/custom_widgets/yacreader_table_view.cpp index 9d3b1bffd..51a377b6e 100644 --- a/custom_widgets/yacreader_table_view.cpp +++ b/custom_widgets/yacreader_table_view.cpp @@ -3,6 +3,7 @@ #include "QsLog.h" #include "comic_item.h" #include "comic_model.h" +#include "cover_utils.h" #include "yacreader_global_gui.h" #include @@ -121,13 +122,20 @@ void YACReaderTableView::performDrag() QLOG_DEBUG() << "performDrag"; QDrag *drag = new QDrag(this); drag->setMimeData(model()->mimeData(selectionModel()->selectedRows())); - drag->setPixmap(YACReader::hdpiPixmap(":/images/comics_view_toolbar/openInYACReader.svg", QSize(18, 18))); // TODO add better image + drag->setPixmap(theme.comicsViewToolbar.openInYACReaderIcon.pixmap(18, 18)); // TODO add better image /*Qt::DropAction dropAction =*/drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction); } void YACReaderTableView::dragEnterEvent(QDragEnterEvent *event) { + const auto imagePath = event->mimeData()->hasUrls() ? YACReader::droppedImagePath(event->mimeData()->urls()) : QString(); + if (!imagePath.isEmpty()) { + event->setDropAction(Qt::CopyAction); + event->accept(); + return; + } + QTableView::dragEnterEvent(event); if (model()->canDropMimeData(event->mimeData(), event->proposedAction(), 0, 0, QModelIndex())) @@ -137,6 +145,13 @@ void YACReaderTableView::dragEnterEvent(QDragEnterEvent *event) void YACReaderTableView::dragMoveEvent(QDragMoveEvent *event) { + const auto imagePath = event->mimeData()->hasUrls() ? YACReader::droppedImagePath(event->mimeData()->urls()) : QString(); + if (!imagePath.isEmpty() && indexAt(event->position().toPoint()).isValid()) { + event->setDropAction(Qt::CopyAction); + event->accept(); + return; + } + QTableView::dragMoveEvent(event); if (model()->canDropMimeData(event->mimeData(), event->proposedAction(), 0, 0, QModelIndex())) @@ -146,10 +161,35 @@ void YACReaderTableView::dragMoveEvent(QDragMoveEvent *event) void YACReaderTableView::dropEvent(QDropEvent *event) { - QTableView::dropEvent(event); + const auto imagePath = event->mimeData()->hasUrls() ? YACReader::droppedImagePath(event->mimeData()->urls()) : QString(); + const auto imageIndex = indexAt(event->position().toPoint()); + if (!imagePath.isEmpty() && imageIndex.isValid()) { + emit customCoverDropped(imagePath, imageIndex.siblingAtColumn(0)); + event->setDropAction(Qt::CopyAction); + event->accept(); + return; + } - if (model()->canDropMimeData(event->mimeData(), event->proposedAction(), 0, 0, QModelIndex())) - event->acceptProposedAction(); + if (!model()->canDropMimeData(event->mimeData(), event->proposedAction(), 0, 0, QModelIndex())) { + event->ignore(); + return; + } + + const QPoint position = event->position().toPoint(); + const QModelIndex destination = indexAt(position); + int destinationRow = -1; + if (destination.isValid()) { + destinationRow = destination.row(); + if (position.y() >= visualRect(destination).center().y()) + ++destinationRow; + } + + if (model()->dropMimeData(event->mimeData(), Qt::MoveAction, destinationRow, 0, QModelIndex())) { + event->setDropAction(Qt::MoveAction); + event->accept(); + } else { + event->ignore(); + } QLOG_DEBUG() << "drop on table"; } diff --git a/custom_widgets/yacreader_table_view.h b/custom_widgets/yacreader_table_view.h index 88d20b313..29d5ec090 100644 --- a/custom_widgets/yacreader_table_view.h +++ b/custom_widgets/yacreader_table_view.h @@ -21,22 +21,23 @@ class YACReaderTableView : public QTableView, protected Themable signals: void comicRated(int, QModelIndex); + void customCoverDropped(const QString &imagePath, const QModelIndex &index); public slots: void closeRatingEditor(); protected slots: - virtual void closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint); - virtual void commitData(QWidget *editor); + void closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint) override; + void commitData(QWidget *editor) override; private: - void resizeEvent(QResizeEvent *event); - void mouseMoveEvent(QMouseEvent *event); - void mousePressEvent(QMouseEvent *event); - void leaveEvent(QEvent *event); + void resizeEvent(QResizeEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; + void leaveEvent(QEvent *event) override; void performDrag(); - void dragEnterEvent(QDragEnterEvent *event); - void dragMoveEvent(QDragMoveEvent *event); - void dropEvent(QDropEvent *event); + void dragEnterEvent(QDragEnterEvent *event) override; + void dragMoveEvent(QDragMoveEvent *event) override; + void dropEvent(QDropEvent *event) override; bool editing; QModelIndex currentIndexEditing; diff --git a/custom_widgets/yacreader_titled_toolbar.cpp b/custom_widgets/yacreader_titled_toolbar.cpp index ab8e04366..0d527dbde 100644 --- a/custom_widgets/yacreader_titled_toolbar.cpp +++ b/custom_widgets/yacreader_titled_toolbar.cpp @@ -10,6 +10,8 @@ #include #include +#include + DropShadowLabel::DropShadowLabel(QWidget *parent) : QLabel(parent) { @@ -149,7 +151,7 @@ void YACReaderTitledToolBar::applyTheme(const Theme &theme) busyIndicator->setColor(sidebarTheme.busyIndicatorColor); QString qss = QString("QWidget {background-color:%1;}").arg(sidebarTheme.separatorColor.name()); - for (auto separator : separators) { + for (auto separator : std::as_const(separators)) { separator->setStyleSheet(qss); } } diff --git a/image_processing/CMakeLists.txt b/image_processing/CMakeLists.txt index 86079aa44..e567e8a71 100644 --- a/image_processing/CMakeLists.txt +++ b/image_processing/CMakeLists.txt @@ -8,3 +8,22 @@ target_include_directories(image_processing PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) yacreader_apply_build_options(image_processing) target_link_libraries(image_processing PRIVATE Qt6::Gui) + +# Raise the x86_64 baseline above the ancient default, on macOS only. +# +# lancir picks its SIMD path at compile time: __AVX__ selects 8-wide vectors, +# otherwise it falls back to 4-wide SSE2. macOS is the one platform where we +# know the oldest CPU we have to run on: our deployment target is macOS 12, and +# every Mac that can run it is Ivy Bridge or newer, so AVX is always available. +# AVX2 would need macOS 13 as the floor (the 2013 Mac Pro is Ivy Bridge, which +# has AVX but not AVX2). On Windows and Linux we have no such guarantee about +# the user's CPU, so those keep the portable baseline. +# +# -Xarch_x86_64 is self-gating: in a universal build it applies -mavx only to +# the x86_64 half, where -mavx is a valid option, and never to arm64. The +# IN_LIST check is therefore not required for correctness, only to keep clang +# from warning about an unused argument on arm64-only builds. SHELL: stops +# CMake from splitting or reordering the two tokens. +if(APPLE AND "x86_64" IN_LIST CMAKE_OSX_ARCHITECTURES) + target_compile_options(image_processing PRIVATE "SHELL:-Xarch_x86_64 -mavx") +endif() diff --git a/images/comics_view_toolbar/organize.svg b/images/comics_view_toolbar/organize.svg new file mode 100644 index 000000000..23d541e4c --- /dev/null +++ b/images/comics_view_toolbar/organize.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/release/server/docroot/css/webui.css b/release/server/docroot/css/webui.css index c1e3562f4..c75499f29 100644 --- a/release/server/docroot/css/webui.css +++ b/release/server/docroot/css/webui.css @@ -1143,6 +1143,91 @@ input[type="time"]:focus-visible { min-width: 0; } +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + padding: 0; + border: 0; + margin: -1px; + clip: rect(0 0 0 0); + white-space: nowrap; +} + +.browser-search { + display: flex; + width: min(40vw, 430px); + min-width: 220px; + height: 42px; + align-items: center; + gap: 2px; + margin-left: auto; + padding: 0 6px; + border: 1px solid var(--border); + border-radius: 11px; + background: var(--surface); + color: var(--text-muted); + transition: border-color 150ms ease, box-shadow 150ms ease; +} + +.browser-search[hidden] { + display: none; +} + +.browser-search:focus-within { + border-color: var(--accent); + box-shadow: 0 0 0 3px var(--accent-soft); +} + +.browser-search input { + min-width: 0; + height: 100%; + flex: 1; + padding: 0 5px; + border: 0; + outline: 0; + background: transparent; + color: var(--text); + font: inherit; + font-size: 13px; +} + +.browser-search input::placeholder { + color: var(--text-muted); +} + +.browser-search input::-webkit-search-cancel-button { + display: none; +} + +.browser-search-submit, +.browser-search-clear { + display: grid; + width: 32px; + height: 32px; + flex: none; + padding: 0; + border: 0; + border-radius: 8px; + background: transparent; + color: var(--text-muted); + cursor: pointer; + place-items: center; +} + +.browser-search-submit:hover, +.browser-search-clear:hover { + background: var(--surface-subtle); + color: var(--accent-strong); +} + +.browser-search-submit:focus-visible, +.browser-search-clear:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 1px; +} + .breadcrumbs { display: flex; min-width: 0; @@ -1194,6 +1279,57 @@ input[type="time"]:focus-visible { font-size: 13px; } +.continue-reading-shelf { + margin: 0 0 34px; + padding: 20px 0 22px; + border-top: 1px solid var(--border); + border-bottom: 1px solid var(--border); +} + +.continue-reading-heading { + display: flex; + position: relative; + z-index: 1; + align-items: end; + justify-content: space-between; + margin-bottom: 16px; +} + +.continue-reading-heading h3 { + margin: 0; + font-size: 19px; + letter-spacing: -0.018em; +} + +.continue-reading-list { + --continue-reading-main-width: calc(100vw - 252px); + --continue-reading-inline-padding: max(32px, calc(50vw - 714px)); + + display: grid; + width: var(--continue-reading-main-width); + overflow-x: auto; + grid-auto-columns: 142px; + grid-auto-flow: column; + align-items: start; + gap: 20px; + margin: -40px 0 -26px calc(-1 * var(--continue-reading-inline-padding)); + padding: 44px var(--continue-reading-inline-padding) 40px; + -ms-overflow-style: none; + overscroll-behavior-inline: contain; + scrollbar-width: none; + scroll-padding-inline: var(--continue-reading-inline-padding); + scroll-snap-type: inline proximity; +} + +.continue-reading-list::-webkit-scrollbar { + display: none; +} + +.continue-reading-item { + min-width: 0; + scroll-snap-align: start; +} + .browser-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(142px, 1fr)); @@ -1461,6 +1597,12 @@ input[type="time"]:focus-visible { place-items: center; } +.browser-state-search-icon { + padding: 13px; + background: var(--accent-soft); + color: var(--accent-strong); +} + .folder-state-icon { position: relative; background: var(--accent-soft); @@ -2422,6 +2564,21 @@ input[type="time"]:disabled { padding: 14px 20px; } + .browser-topbar { + flex-wrap: wrap; + } + + .browser-heading { + flex: 1; + } + + .browser-search { + width: 100%; + min-width: 0; + flex-basis: 100%; + margin-left: 0; + } + .browser-back:not([hidden]) { display: grid; } @@ -2435,6 +2592,14 @@ input[type="time"]:disabled { gap: 24px 16px; } + .continue-reading-list { + --continue-reading-main-width: 100vw; + --continue-reading-inline-padding: 20px; + + grid-auto-columns: 125px; + gap: 16px; + } + .browser-loading-grid { grid-template-columns: repeat(auto-fill, minmax(125px, 1fr)); gap: 24px 16px; diff --git a/release/server/docroot/js/webui.js b/release/server/docroot/js/webui.js index f5f4373bd..22fda522e 100644 --- a/release/server/docroot/js/webui.js +++ b/release/server/docroot/js/webui.js @@ -402,10 +402,215 @@ var breadcrumbs = document.querySelector("[data-browser-breadcrumbs]"); var pageTitle = document.querySelector("[data-browser-title]"); var browserBack = document.querySelector("[data-browser-back]"); + var searchForm = document.querySelector("[data-browser-search]"); + var searchInput = document.querySelector("[data-browser-search-input]"); + var searchClear = document.querySelector("[data-browser-search-clear]"); var navigationVersion = 0; var folderMetadataCache = {}; var browserBackAction = null; var readerCleanup = null; + var progressSyncPromise = Promise.resolve(); + var historyNavigationPending = false; + var historyTraversalPending = false; + var browserItemCollator = new Intl.Collator(undefined, { + numeric: true, + sensitivity: "base" + }); + + if ("scrollRestoration" in history) { + history.scrollRestoration = "manual"; + } + + function shouldHandleInAppLink(event) { + return event.button === 0 + && !event.metaKey + && !event.ctrlKey + && !event.shiftKey + && !event.altKey; + } + + function routesMatch(left, right) { + if (!left || !right || left.view !== right.view) { + return false; + } + if (left.view === "search") { + return left.query === right.query; + } + return String(left.itemId || "") === String(right.itemId || ""); + } + + function browserViewportTop() { + var topbar = document.querySelector(".browser-topbar"); + return topbar ? topbar.getBoundingClientRect().bottom : 0; + } + + function currentScrollAnchor(preferredCard) { + var viewportTop = browserViewportTop(); + if (preferredCard + && preferredCard.isConnected + && preferredCard.dataset.browserHistoryKey) { + return { + key: preferredCard.dataset.browserHistoryKey, + offset: preferredCard.getBoundingClientRect().top - viewportTop + }; + } + + var cards = browserRoot.querySelectorAll("[data-browser-history-key]"); + + for (var i = 0; i < cards.length; i++) { + var bounds = cards[i].getBoundingClientRect(); + if (bounds.bottom > viewportTop && bounds.top < window.innerHeight) { + return { + key: cards[i].dataset.browserHistoryKey, + offset: bounds.top - viewportTop + }; + } + } + + return null; + } + + function scrollPositionForState(state, fallbackScrollY) { + if (!state || !state.scrollAnchorKey || !Number.isFinite(state.scrollAnchorOffset)) { + return fallbackScrollY; + } + + var cards = browserRoot.querySelectorAll("[data-browser-history-key]"); + var anchor = null; + for (var i = 0; i < cards.length; i++) { + if (cards[i].dataset.browserHistoryKey === state.scrollAnchorKey) { + anchor = cards[i]; + break; + } + } + if (!anchor) { + return fallbackScrollY; + } + + var bounds = anchor.getBoundingClientRect(); + var viewportTop = browserViewportTop(); + var viewportBottomPadding = 16; + var availableHeight = Math.max(0, window.innerHeight - viewportTop - viewportBottomPadding); + var maximumVisibleOffset = Math.max(0, availableHeight - bounds.height); + var restoredOffset = Math.min( + Math.max(0, state.scrollAnchorOffset), + maximumVisibleOffset + ); + return window.scrollY + bounds.top - viewportTop - restoredOffset; + } + + function saveCurrentScrollPosition(preferredCard) { + if (historyNavigationPending) { + return; + } + + var state = history.state || routeFromLocation(); + var nextState = Object.assign({}, state, { + scrollY: window.scrollY + }); + var anchor = currentScrollAnchor(preferredCard); + if (anchor) { + nextState.scrollAnchorKey = anchor.key; + nextState.scrollAnchorOffset = anchor.offset; + } else { + delete nextState.scrollAnchorKey; + delete nextState.scrollAnchorOffset; + } + history.replaceState(nextState, "", window.location.href); + } + + function startHistoryNavigation(pushHistory, returnToCard) { + if (pushHistory) { + saveCurrentScrollPosition(returnToCard); + } + historyNavigationPending = true; + } + + function finishHistoryNavigation(state, url, pushHistory, version) { + var existingState = history.state; + var restoringExistingState = !pushHistory && routesMatch(existingState, state); + var scrollY = restoringExistingState && Number.isFinite(existingState.scrollY) + ? existingState.scrollY + : 0; + var restoredScrollY = restoringExistingState + ? scrollPositionForState(existingState, scrollY) + : 0; + var nextState = restoringExistingState + ? Object.assign({}, existingState, state, { scrollY: restoredScrollY }) + : Object.assign({}, state, { scrollY: scrollY }); + + if (pushHistory) { + history.pushState(nextState, "", url); + } else { + history.replaceState(nextState, "", url); + } + + // The destination DOM has already been built. Applying the saved offset in + // this same task prevents the browser from painting an intermediate frame + // with the document clamped to the top. + if (version === navigationVersion) { + window.scrollTo(0, restoredScrollY); + } + historyNavigationPending = false; + historyTraversalPending = false; + } + + function naturalBrowserCompare(left, right) { + return browserItemCollator.compare(String(left || ""), String(right || "")); + } + + function compareBrowserItems(left, right) { + if (left.type !== right.type) { + if (left.type === "folder") { + return -1; + } + if (right.type === "folder") { + return 1; + } + if (left.type === "comic") { + return -1; + } + if (right.type === "comic") { + return 1; + } + return 0; + } + + if (left.type === "folder") { + return naturalBrowserCompare(left.folder_name, right.folder_name); + } + + if (left.type === "comic") { + var leftHasNumber = left.universal_number !== undefined && left.universal_number !== null; + var rightHasNumber = right.universal_number !== undefined && right.universal_number !== null; + + if (leftHasNumber && rightHasNumber) { + // universal_number is a string: natural comparison supports decimals, + // suffixes and other non-integer issue identifiers used by the apps. + return naturalBrowserCompare(left.universal_number, right.universal_number); + } + if (leftHasNumber) { + return -1; + } + if (rightHasNumber) { + return 1; + } + + return naturalBrowserCompare(left.file_name, right.file_name); + } + + return 0; + } + + function sortBrowserItems(items) { + return items.map(function (item, index) { + return { item: item, index: index }; + }).sort(function (left, right) { + return compareBrowserItems(left.item, right.item) || left.index - right.index; + }).map(function (entry) { + return entry.item; + }); + } if (browserBack) { browserBack.addEventListener("click", function () { @@ -428,7 +633,15 @@ browserBack.hidden = false; browserBackAction = function () { - showFolder(String(parentFolderId), true); + var state = history.state; + if (state + && state.view === "folder" + && String(state.enteredFromFolderId || "") === String(parentFolderId)) { + saveCurrentScrollPosition(); + history.back(); + } else { + showFolder(String(parentFolderId), true); + } }; } @@ -464,6 +677,22 @@ }); } + function postJson(url, payload) { + var headers = apiHeaders("application/json"); + headers["Content-Type"] = "application/json"; + + return fetch(url, { + method: "POST", + headers: headers, + body: JSON.stringify(payload) + }).then(function (response) { + if (!response.ok) { + throw new Error("Request failed with status " + response.status); + } + return response.json(); + }); + } + function libraryUrl() { return "/webui/library/" + encodeURIComponent(libraryId); } @@ -486,6 +715,10 @@ return "/v2/library/" + encodeURIComponent(libraryId) + "/folder/" + encodeURIComponent(folderId) + "/content"; } + function continueReadingApi() { + return "/v2/library/" + encodeURIComponent(libraryId) + "/reading"; + } + function folderMetadataApi(folderId) { return "/v2/library/" + encodeURIComponent(libraryId) + "/folder/" + encodeURIComponent(folderId) + "/metadata"; } @@ -506,6 +739,10 @@ return "/v2/library/" + encodeURIComponent(libraryId) + "/comic/" + encodeURIComponent(comicId) + "/update"; } + function searchApi() { + return "/v2/library/" + encodeURIComponent(libraryId) + "/search"; + } + function apiHeaders(accept) { var headers = {}; if (accept) { @@ -590,6 +827,9 @@ link.href = part.href; if (part.action) { link.addEventListener("click", function (event) { + if (!shouldHandleInAppLink(event)) { + return; + } event.preventDefault(); part.action(); }); @@ -615,7 +855,17 @@ browserRoot.appendChild(loading); } + function showNavigationLoading() { + if (historyTraversalPending) { + browserRoot.setAttribute("aria-busy", "true"); + return; + } + showLoading(); + } + function showError(retry) { + historyNavigationPending = false; + historyTraversalPending = false; browserRoot.removeAttribute("aria-busy"); browserRoot.replaceChildren(); @@ -663,12 +913,16 @@ return image; } - function folderCard(folder) { + function folderCard(folder, containingFolderId) { var card = element("a", "browser-card folder-card"); card.href = folderUrl(String(folder.id)); + card.dataset.browserHistoryKey = "folder:" + String(folder.id); card.addEventListener("click", function (event) { + if (!shouldHandleInAppLink(event)) { + return; + } event.preventDefault(); - showFolder(String(folder.id), true); + showFolder(String(folder.id), true, containingFolderId, card); }); var cover = element("div", "browser-cover folder-cover"); @@ -692,12 +946,22 @@ return card; } - function comicCard(comic) { - var card = element("a", "browser-card comic-card"); - card.href = comicUrl(String(comic.id)); + function comicCard(comic, options) { + options = options || {}; + var comicId = String(comic.id); + var card = element("a", "browser-card comic-card" + (options.continueReading ? " continue-reading-card" : "")); + card.href = options.continueReading ? readerUrl(comicId) : comicUrl(comicId); + card.dataset.browserHistoryKey = (options.continueReading ? "continue-reading:" : "comic:") + comicId; card.addEventListener("click", function (event) { + if (!shouldHandleInAppLink(event)) { + return; + } event.preventDefault(); - showComic(String(comic.id), true); + if (options.continueReading) { + showReader(comicId, true, comic, card); + } else { + showComic(comicId, true, card); + } }); var cover = element("div", "browser-cover comic-cover"); @@ -710,7 +974,7 @@ if (comic.read) { cover.appendChild(element("span", "comic-status read", "Read")); - } else if (Number(comic.current_page) > 1) { + } else if (!options.continueReading && Number(comic.current_page) > 1) { cover.appendChild(element("span", "comic-status reading", "Page " + comic.current_page)); } @@ -726,12 +990,187 @@ var copy = element("div", "browser-card-copy"); copy.appendChild(element("div", "browser-card-title", readableComicTitle(comic))); - copy.appendChild(element("div", "browser-card-meta", numPages === 1 ? "1 page" : numPages + " pages")); + var meta = options.continueReading && currentPage > 0 && numPages > 0 + ? "Page " + currentPage + " of " + numPages + : numPages === 1 ? "1 page" : numPages + " pages"; + copy.appendChild(element("div", "browser-card-meta", meta)); card.append(cover, copy); return card; } + function continueReadingShelf(comics) { + var shelf = element("section", "continue-reading-shelf"); + shelf.setAttribute("aria-labelledby", "continue-reading-title"); + + var heading = element("div", "continue-reading-heading"); + var title = element("h3", "", "Continue reading"); + title.id = "continue-reading-title"; + heading.appendChild(title); + + var list = element("div", "continue-reading-list"); + list.setAttribute("role", "list"); + list.addEventListener("wheel", function (event) { + if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) { + return; + } + + var previousScrollLeft = list.scrollLeft; + list.scrollLeft += event.deltaY; + if (list.scrollLeft !== previousScrollLeft) { + event.preventDefault(); + } + }, { passive: false }); + comics.forEach(function (comic) { + var item = element("div", "continue-reading-item"); + item.setAttribute("role", "listitem"); + var card = comicCard(comic, { continueReading: true }); + item.appendChild(card); + list.appendChild(item); + }); + + shelf.append(heading, list); + return shelf; + } + + function setSearchValue(query) { + if (!searchInput) { + return; + } + searchInput.value = query || ""; + if (searchClear) { + searchClear.hidden = searchInput.value.length === 0; + } + } + + function setSearchVisible(visible) { + if (searchForm) { + searchForm.hidden = !visible; + } + } + + function showSearch(query, pushHistory) { + var normalizedQuery = String(query || "").trim(); + if (!normalizedQuery) { + showFolder("1", pushHistory); + return; + } + + startHistoryNavigation(pushHistory); + leaveReader(); + setSearchVisible(false); + var version = ++navigationVersion; + setSearchValue(normalizedQuery); + showNavigationLoading(); + + postJson(searchApi(), { query: normalizedQuery }).then(function (items) { + if (version !== navigationVersion) { + return; + } + + items = sortBrowserItems(items); + var folders = items.filter(function (item) { return item.type === "folder"; }); + var comics = items.filter(function (item) { return item.type === "comic"; }); + var resultCount = folders.length + comics.length; + + setPageHeading("Search"); + setBrowserBack("1"); + renderBreadcrumbs([ + { label: "Libraries", href: "/webui#libraries" }, + { + label: libraryName, + href: libraryUrl(), + action: function () { showFolder("1", true); } + }, + { label: "Search" } + ]); + + browserRoot.removeAttribute("aria-busy"); + browserRoot.replaceChildren(); + + var header = element("section", "browser-library-header search-results-header"); + header.appendChild(element("div", "section-title", "Search results")); + header.appendChild(element("h2", "", 'Results for "' + normalizedQuery + '"')); + var summary = resultCount === 1 ? "1 result" : resultCount + " results"; + var resultParts = []; + if (folders.length) { + resultParts.push(folders.length === 1 ? "1 folder" : folders.length + " folders"); + } + if (comics.length) { + resultParts.push(comics.length === 1 ? "1 comic" : comics.length + " comics"); + } + header.appendChild(element("p", "", resultParts.length ? summary + " - " + resultParts.join(" - ") : summary)); + browserRoot.appendChild(header); + + if (!resultCount) { + var empty = element("div", "browser-state compact"); + empty.appendChild(svgIcon("browser-state-icon browser-state-search-icon", '')); + empty.appendChild(element("h2", "", "No matching comics or folders")); + empty.appendChild(element("p", "", "Try a different term or use YACReader search fields such as writer:, series:, read:, or added>.")); + browserRoot.appendChild(empty); + } else { + var grid = element("div", "browser-grid"); + items.forEach(function (item) { + if (item.type === "folder") { + grid.appendChild(folderCard(item)); + } else if (item.type === "comic") { + grid.appendChild(comicCard(item)); + } + }); + browserRoot.appendChild(grid); + } + + var url = libraryUrl() + "?q=" + encodeURIComponent(normalizedQuery); + var state = { view: "search", query: normalizedQuery }; + finishHistoryNavigation(state, url, pushHistory, version); + }).catch(function () { + if (version !== navigationVersion) { + return; + } + showError(function () { + showSearch(normalizedQuery, false); + }); + }); + } + + if (searchForm && searchInput) { + searchForm.addEventListener("submit", function (event) { + event.preventDefault(); + var query = searchInput.value.trim(); + if (query) { + showSearch(query, true); + } else { + showFolder("1", true); + } + }); + + searchInput.addEventListener("input", function () { + if (searchClear) { + searchClear.hidden = searchInput.value.length === 0; + } + }); + + searchInput.addEventListener("keydown", function (event) { + if (event.key === "Escape" && searchInput.value) { + event.preventDefault(); + setSearchValue(""); + } + }); + } + + if (searchClear) { + searchClear.addEventListener("click", function () { + var route = routeFromLocation(); + setSearchValue(""); + if (route.view === "search") { + showFolder("1", true); + } + if (searchInput) { + searchInput.focus(); + } + }); + } + function getFolderMetadata(folderId) { if (folderMetadataCache[folderId]) { return Promise.resolve(folderMetadataCache[folderId]); @@ -806,21 +1245,30 @@ return parts; } - function showFolder(folderId, pushHistory) { + function showFolder(folderId, pushHistory, enteredFromFolderId, returnToCard) { + startHistoryNavigation(pushHistory, returnToCard); leaveReader(); + setSearchVisible(folderId === "1"); + if (folderId === "1") { + setSearchValue(""); + } var version = ++navigationVersion; - showLoading(); + showNavigationLoading(); Promise.all([ fetchJson(folderContentApi(folderId)), - folderTrail(folderId) + folderTrail(folderId), + folderId === "1" + ? progressSyncPromise.then(function () { return fetchJson(continueReadingApi()); }) + : Promise.resolve([]) ]).then(function (results) { if (version !== navigationVersion) { return; } - var items = results[0]; + var items = sortBrowserItems(results[0]); var trail = results[1]; + var continueReading = results[2].filter(function (item) { return item.type === "comic"; }); var folderName = trail.length ? trail[trail.length - 1].name : libraryName; var folders = items.filter(function (item) { return item.type === "folder"; }); var comics = items.filter(function (item) { return item.type === "comic"; }); @@ -850,6 +1298,10 @@ header.appendChild(element("p", "", summaryParts.join(" · ") || "No items")); browserRoot.appendChild(header); + if (continueReading.length) { + browserRoot.appendChild(continueReadingShelf(continueReading)); + } + if (!items.length) { var empty = element("div", "browser-state compact"); empty.appendChild(element("div", "browser-state-icon folder-state-icon")); @@ -860,7 +1312,7 @@ var grid = element("div", "browser-grid"); items.forEach(function (item) { if (item.type === "folder") { - grid.appendChild(folderCard(item)); + grid.appendChild(folderCard(item, folderId)); } else if (item.type === "comic") { grid.appendChild(comicCard(item)); } @@ -870,11 +1322,10 @@ var url = folderUrl(folderId); var state = { view: "folder", itemId: folderId }; - if (pushHistory) { - history.pushState(state, "", url); - } else { - history.replaceState(state, "", url); + if (pushHistory && enteredFromFolderId) { + state.enteredFromFolderId = String(enteredFromFolderId); } + finishHistoryNavigation(state, url, pushHistory, version); }).catch(function () { if (version !== navigationVersion) { return; @@ -1116,10 +1567,12 @@ return result; } - function showReader(comicId, pushHistory, existingComic) { + function showReader(comicId, pushHistory, existingComic, returnToCard) { + startHistoryNavigation(pushHistory, returnToCard); leaveReader(); + setSearchVisible(false); var version = ++navigationVersion; - showLoading(); + showNavigationLoading(); Promise.resolve(existingComic || fetchJson(comicInfoApi(comicId))).then(function (comic) { if (version !== navigationVersion) { @@ -1201,18 +1654,19 @@ function syncProgress() { if (!hasDisplayedPage || progressSynced) { - return; + return progressSyncPromise; } progressSynced = true; var headers = apiHeaders("text/plain"); headers["Content-Type"] = "text/plain; charset=utf-8"; - fetch(comicProgressApi(comicId), { + progressSyncPromise = fetch(comicProgressApi(comicId), { method: "POST", headers: headers, body: "currentPage:" + (currentPage + 1) + "\n", keepalive: true }).catch(function () { }); + return progressSyncPromise; } function cancelledPageError() { @@ -1449,11 +1903,7 @@ : false; var url = readerUrl(comicId); var state = { view: "reader", itemId: comicId, fromComicDetail: pushHistory || existingReaderState }; - if (pushHistory) { - history.pushState(state, "", url); - } else { - history.replaceState(state, "", url); - } + finishHistoryNavigation(state, url, pushHistory, version); updateNavigation(); openComicAndLoad(); @@ -1468,10 +1918,12 @@ }); } - function showComic(comicId, pushHistory) { + function showComic(comicId, pushHistory, returnToCard) { + startHistoryNavigation(pushHistory, returnToCard); leaveReader(); + setSearchVisible(false); var version = ++navigationVersion; - showLoading(); + showNavigationLoading(); fetchJson(comicInfoApi(comicId)).then(function (comic) { return Promise.all([ @@ -1698,11 +2150,7 @@ var url = comicUrl(comicId); var state = { view: "comic", itemId: comicId }; - if (pushHistory) { - history.pushState(state, "", url); - } else { - history.replaceState(state, "", url); - } + finishHistoryNavigation(state, url, pushHistory, version); }).catch(function () { if (version !== navigationVersion) { return; @@ -1714,6 +2162,10 @@ } function routeFromLocation() { + var query = new URL(window.location.href).searchParams.get("q"); + if (query && query.trim()) { + return { view: "search", query: query.trim() }; + } var escapedLibraryId = libraryId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); var match = window.location.pathname.match(new RegExp("^/webui/library/" + escapedLibraryId + "(?:/(folder|comic)/([0-9]+)(?:/(read))?)?/?$")); if (!match) { @@ -1726,8 +2178,14 @@ } window.addEventListener("popstate", function () { + historyNavigationPending = true; + historyTraversalPending = Boolean(history.state + && (history.state.scrollAnchorKey + || (Number.isFinite(history.state.scrollY) && history.state.scrollY > 0))); var route = routeFromLocation(); - if (route.view === "reader") { + if (route.view === "search") { + showSearch(route.query, false); + } else if (route.view === "reader") { showReader(route.itemId, false); } else if (route.view === "comic") { showComic(route.itemId, false); @@ -1738,7 +2196,10 @@ var initialView = document.body.dataset.browserInitialView; var initialItemId = document.body.dataset.browserInitialItemId || "1"; - if (initialView === "reader") { + var initialRoute = routeFromLocation(); + if (initialRoute.view === "search") { + showSearch(initialRoute.query, false); + } else if (initialView === "reader") { showReader(initialItemId, false); } else if (initialView === "comic") { showComic(initialItemId, false); diff --git a/shortcuts_management/shortcuts_manager.h b/shortcuts_management/shortcuts_manager.h index 865f2a08d..03ec8f163 100644 --- a/shortcuts_management/shortcuts_manager.h +++ b/shortcuts_management/shortcuts_manager.h @@ -55,7 +55,7 @@ class ShortcutsManager #define SET_AS_READ_ACTION_YL "SET_AS_READ_ACTION_YL" #define SET_AS_NON_READ_ACTION_YL "SET_AS_NON_READ_ACTION_YL" #define SET_AS_MANGA_ACTION_YL "SET_AS_MANGA_ACTION_YL" -#define SET_AS_NORMAL_ACTION_YL "SET_AS_MANGA_ACTION_YL" +#define SET_AS_NORMAL_ACTION_YL "SET_AS_NORMAL_ACTION_YL" #define SET_AS_WESTERN_MANGA_ACTION_YL "SET_AS_WESTERN_MANGA_ACTION_YL" #define SET_AS_WEB_COMIC_ACTION_YL "SET_AS_WEB_COMIC_ACTION_YL" #define SET_AS_YONKOMA_ACTION_YL "SET_AS_YONKOMA_ACTION_YL" @@ -69,6 +69,8 @@ class ShortcutsManager #define SERVER_CONFIG_ACTION_YL "SERVER_CONFIG_ACTION_YL" #define TOGGLE_COMICS_VIEW_ACTION_YL "TOGGLE_COMICS_VIEW_ACTION_YL" #define OPEN_CONTAINING_FOLDER_ACTION_YL "OPEN_CONTAINING_FOLDER_ACTION_YL" +#define RENAME_FILES_ACTION_YL "RENAME_FILES_ACTION_YL" +#define ORGANIZE_FILES_ACTION_YL "ORGANIZE_FILES_ACTION_YL" #define SET_FOLDER_AS_NOT_COMPLETED_ACTION_YL "SET_FOLDER_AS_NOT_COMPLETED_ACTION_YL" #define SET_FOLDER_AS_COMPLETED_ACTION_YL "SET_FOLDER_AS_COMPLETED_ACTION_YL" #define SET_FOLDER_AS_READ_ACTION_YL "SET_FOLDER_AS_READ_ACTION_YL" @@ -81,6 +83,8 @@ class ShortcutsManager #define SET_FOLDER_COVER_ACTION_YL "SET_FOLDER_COVER_ACTION_YL" #define DELETE_CUSTOM_FOLDER_COVER_ACTION_YL "DELETE_CUSTOM_FOLDER_COVER_ACTION_YL" #define OPEN_CONTAINING_FOLDER_COMIC_ACTION_YL "OPEN_CONTAINING_FOLDER_COMIC_ACTION_YL" +#define RENAME_COMICS_FILES_ACTION_YL "RENAME_COMICS_FILES_ACTION_YL" +#define ORGANIZE_COMICS_FILES_ACTION_YL "ORGANIZE_COMICS_FILES_ACTION_YL" #define RESET_COMIC_RATING_ACTION_YL "RESET_COMIC_RATING_ACTION_YL" #define SELECT_ALL_COMICS_ACTION_YL "SELECT_ALL_COMICS_ACTION_YL" #define EDIT_SELECTED_COMICS_ACTION_YL "EDIT_SELECTED_COMICS_ACTION_YL" diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 3ac52d8fe..39da29cb2 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -4,4 +4,8 @@ add_subdirectory(concurrent_queue_test) add_subdirectory(compressed_archive_test) add_subdirectory(continuous_view_model_test) add_subdirectory(pdf_render_size_test) +add_subdirectory(folder_rename_test) add_subdirectory(epub_page_index_test) +add_subdirectory(comic_files_manager_test) +add_subdirectory(organize_files_test) +add_subdirectory(yacreader_libraries_test) diff --git a/tests/comic_files_manager_test/CMakeLists.txt b/tests/comic_files_manager_test/CMakeLists.txt new file mode 100644 index 000000000..00554046d --- /dev/null +++ b/tests/comic_files_manager_test/CMakeLists.txt @@ -0,0 +1,11 @@ +qt_add_executable(comic_files_manager_test + main.cpp +) +yacreader_apply_build_options(comic_files_manager_test) +target_link_libraries(comic_files_manager_test PRIVATE + Qt6::Core + Qt6::Test + library_common +) + +add_test(NAME comic_files_manager_test COMMAND comic_files_manager_test) diff --git a/tests/comic_files_manager_test/main.cpp b/tests/comic_files_manager_test/main.cpp new file mode 100644 index 000000000..01698ba5b --- /dev/null +++ b/tests/comic_files_manager_test/main.cpp @@ -0,0 +1,70 @@ +#include "comic_files_manager.h" + +#include +#include +#include +#include + +class ComicFilesManagerTest : public QObject +{ + Q_OBJECT + +private slots: + void copiesComicAndReportsDestinationFolder(); + void movesComicAndRemovesSource(); +}; + +namespace { +QString createSourceComic(QTemporaryDir &temporaryDir, const QString &name) +{ + const QString path = temporaryDir.filePath(name); + QFile file(path); + if (!file.open(QIODevice::WriteOnly) || file.write("comic") == -1) + return QString(); + return path; +} +} + +void ComicFilesManagerTest::copiesComicAndReportsDestinationFolder() +{ + QTemporaryDir temporaryDir; + QVERIFY(temporaryDir.isValid()); + const QString source = createSourceComic(temporaryDir, QStringLiteral("source.cbz")); + QVERIFY(!source.isEmpty()); + + ComicFilesManager manager; + QSignalSpy successSpy(&manager, &ComicFilesManager::success); + QSignalSpy finishedSpy(&manager, &ComicFilesManager::finished); + manager.copyComicsTo({ { source, QStringLiteral("Series") } }, temporaryDir.filePath(QStringLiteral("destination")), 42); + + manager.process(); + + QCOMPARE(successSpy.count(), 1); + QCOMPARE(successSpy.first().first().toULongLong(), 42ULL); + QCOMPARE(finishedSpy.count(), 1); + QVERIFY(QFile::exists(source)); + QVERIFY(QFile::exists(temporaryDir.filePath(QStringLiteral("destination/Series/source.cbz")))); +} + +void ComicFilesManagerTest::movesComicAndRemovesSource() +{ + QTemporaryDir temporaryDir; + QVERIFY(temporaryDir.isValid()); + const QString source = createSourceComic(temporaryDir, QStringLiteral("source.cbz")); + QVERIFY(!source.isEmpty()); + + ComicFilesManager manager; + QSignalSpy successSpy(&manager, &ComicFilesManager::success); + manager.moveComicsTo({ { source, QString() } }, temporaryDir.filePath(QStringLiteral("destination")), 84); + + manager.process(); + + QCOMPARE(successSpy.count(), 1); + QCOMPARE(successSpy.first().first().toULongLong(), 84ULL); + QVERIFY(!QFile::exists(source)); + QVERIFY(QFile::exists(temporaryDir.filePath(QStringLiteral("destination/source.cbz")))); +} + +QTEST_GUILESS_MAIN(ComicFilesManagerTest) + +#include "main.moc" diff --git a/tests/concurrent_queue_test/concurrent_queue_test.cpp b/tests/concurrent_queue_test/concurrent_queue_test.cpp index ee187df93..178d5388f 100644 --- a/tests/concurrent_queue_test/concurrent_queue_test.cpp +++ b/tests/concurrent_queue_test/concurrent_queue_test.cpp @@ -636,7 +636,7 @@ void ConcurrentQueueTest::waitAllFromMultipleThreads() std::vector waitingThreads; waitingThreads.reserve(waitingThreadCount - 1); for (int id = 1; id < waitingThreadCount; ++id) { - waitingThreads.emplace_back([=, &queue] { + waitingThreads.emplace_back([=, &queue, this] { waitAndPrint(queue, QueueControlMessagePrinter(total, id, queueThreadCount)); }); } diff --git a/tests/epub_page_index_test/main.cpp b/tests/epub_page_index_test/main.cpp index 6d5b0684e..43999afa3 100644 --- a/tests/epub_page_index_test/main.cpp +++ b/tests/epub_page_index_test/main.cpp @@ -19,6 +19,12 @@ private slots: void skipsBrokenSpineItems(); void rejectsWrappersWithMultipleImages(); void rejectsPathsOutsideTheArchive(); + void rejectsIllustratedTextBooks(); + void rejectsPagesWithBodyText(); + void ignoresStyleScriptAndHiddenText(); + void ignoresNavigationDocuments(); + void toleratesAFewNonImagePages(); + void scanInfoMatchesThePageIndex(); }; namespace { @@ -28,6 +34,12 @@ YACReaderEpub::PageIndex readIndex(const QStringList &fileNames, const QHash &files, int coverPage = 1) +{ + return YACReaderEpub::readScanInfo( + fileNames, [&](int index) { return files.value(fileNames.at(index)); }, coverPage, { }); +} + QByteArray containerXml() { return R"( @@ -213,6 +225,184 @@ void EpubPageIndexTest::rejectsPathsOutsideTheArchive() QVERIFY(result.error.contains("no usable image pages")); } +void EpubPageIndexTest::rejectsIllustratedTextBooks() +{ + // A novel whose chapters happen to open with an illustration is not a comic. + QString manifest; + QString spine; + QHash files { { "META-INF/container.xml", containerXml() } }; + for (int chapter = 0; chapter < 10; ++chapter) { + manifest += QString(R"()").arg(chapter); + spine += QString(R"()").arg(chapter); + files.insert(QString("OEBPS/chapters/ch%1.xhtml").arg(chapter), + QString(R"( +

It was the best of times, it was the worst of times, it was the age of wisdom.

+ )") + .arg(chapter) + .toUtf8()); + files.insert(QString("OEBPS/images/ch%1.jpg").arg(chapter), "illustration"); + } + files.insert("OEBPS/content.opf", QString(R"(%1%2)").arg(manifest, spine).toUtf8()); + const QStringList fileNames = files.keys(); + + const auto result = readIndex(fileNames, files); + + QVERIFY(!result.isValid()); + QVERIFY2(result.error.contains("not image based"), qPrintable(result.error)); + QVERIFY(result.pages.isEmpty()); +} + +void EpubPageIndexTest::rejectsPagesWithBodyText() +{ + const QHash files { + { "META-INF/container.xml", containerXml() }, + { "OEBPS/content.opf", R"( + + + + + + )" }, + { "OEBPS/one.xhtml", R"(

A paragraph of real text that the reader would silently drop.

)" }, + { "OEBPS/two.xhtml", R"(

Another paragraph of real text that would go missing.

)" }, + { "OEBPS/three.xhtml", R"()" }, + { "OEBPS/one.jpg", "one" }, + { "OEBPS/two.jpg", "two" }, + { "OEBPS/three.jpg", "three" }, + }; + const QStringList fileNames = files.keys(); + + const auto result = readIndex(fileNames, files); + + QVERIFY(!result.isValid()); + QVERIFY2(result.error.contains("characters of text"), qPrintable(result.error)); +} + +void EpubPageIndexTest::ignoresStyleScriptAndHiddenText() +{ + const QHash files { + { "META-INF/container.xml", containerXml() }, + { "OEBPS/content.opf", R"( + + )" }, + { "OEBPS/page.xhtml", R"( + + Page 1 of the comic + + + + + + + + )" }, + { "OEBPS/images/page.jpg", "page" }, + }; + const QStringList fileNames = files.keys(); + + const auto result = readIndex(fileNames, files); + + QVERIFY2(result.isValid(), qPrintable(result.error)); + QCOMPARE(result.pages.constFirst().fileName, QString("OEBPS/images/page.jpg")); +} + +void EpubPageIndexTest::ignoresNavigationDocuments() +{ + // The nav document is structural: it must neither become a page nor spend the + // tolerance that a real credits page needs. + const QHash files { + { "META-INF/container.xml", containerXml() }, + { "OEBPS/content.opf", R"( + + + + + + + )" }, + { "OEBPS/nav.xhtml", R"()" }, + { "OEBPS/credits.xhtml", R"(

Script, art and lettering by someone. All rights reserved.

)" }, + { "OEBPS/one.xhtml", R"()" }, + { "OEBPS/two.xhtml", R"()" }, + { "OEBPS/one.jpg", "one" }, + { "OEBPS/two.jpg", "two" }, + }; + const QStringList fileNames = files.keys(); + + const auto result = readIndex(fileNames, files); + + QVERIFY2(result.isValid(), qPrintable(result.error)); + QCOMPARE(result.pages.size(), 2); + QCOMPARE(result.pages.at(0).fileName, QString("OEBPS/one.jpg")); + QCOMPARE(result.pages.at(1).fileName, QString("OEBPS/two.jpg")); +} + +void EpubPageIndexTest::toleratesAFewNonImagePages() +{ + QString manifest = R"()"; + QString spine = R"()"; + QHash files { + { "META-INF/container.xml", containerXml() }, + { "OEBPS/credits.xhtml", R"(

Script, art and lettering by someone. All rights reserved.

)" }, + }; + for (int page = 0; page < 20; ++page) { + manifest += QString(R"()").arg(page); + spine += QString(R"()").arg(page); + files.insert(QString("OEBPS/images/p%1.jpg").arg(page), "page"); + } + files.insert("OEBPS/content.opf", QString(R"(%1%2)").arg(manifest, spine).toUtf8()); + const QStringList fileNames = files.keys(); + + const auto result = readIndex(fileNames, files); + + QVERIFY2(result.isValid(), qPrintable(result.error)); + QCOMPARE(result.pages.size(), 20); +} + +void EpubPageIndexTest::scanInfoMatchesThePageIndex() +{ + const QHash comic { + { "META-INF/container.xml", containerXml() }, + { "OEBPS/content.opf", R"( + pre-paginated + + + + )" }, + { "OEBPS/one.xhtml", R"()" }, + { "OEBPS/two.xhtml", R"()" }, + { "OEBPS/one.jpg", "one" }, + { "OEBPS/two.jpg", "two" }, + }; + const QStringList comicNames = comic.keys(); + + const auto comicScan = readScan(comicNames, comic); + + QVERIFY2(comicScan.isValid(), qPrintable(comicScan.error)); + QCOMPARE(comicScan.pageCount, static_cast(readIndex(comicNames, comic).pages.size())); + QCOMPARE(comicScan.coverArchiveIndex, static_cast(comicNames.indexOf(QString("OEBPS/one.jpg")))); + + // A fixed layout book made of text pages used to be counted page by page. + const QHash textBook { + { "META-INF/container.xml", containerXml() }, + { "OEBPS/content.opf", R"( + pre-paginated + + + + )" }, + { "OEBPS/one.xhtml", R"(

A chapter

Page after page of prose with no pictures at all.

)" }, + { "OEBPS/two.xhtml", R"(

More prose, still with nothing for the reader to show.

)" }, + }; + const QStringList textBookNames = textBook.keys(); + + const auto textBookScan = readScan(textBookNames, textBook); + + QVERIFY(!textBookScan.isValid()); + QCOMPARE(textBookScan.pageCount, 0); + QCOMPARE(textBookScan.coverArchiveIndex, -1); +} + QTEST_GUILESS_MAIN(EpubPageIndexTest) #include "main.moc" diff --git a/tests/folder_rename_test/CMakeLists.txt b/tests/folder_rename_test/CMakeLists.txt new file mode 100644 index 000000000..40933e115 --- /dev/null +++ b/tests/folder_rename_test/CMakeLists.txt @@ -0,0 +1,13 @@ +qt_add_executable(folder_rename_test + main.cpp +) +yacreader_apply_build_options(folder_rename_test) +target_link_libraries(folder_rename_test PRIVATE + Qt6::Core + Qt6::Sql + Qt6::Test + db_helper + library_common +) + +add_test(NAME folder_rename_test COMMAND folder_rename_test) diff --git a/tests/folder_rename_test/main.cpp b/tests/folder_rename_test/main.cpp new file mode 100644 index 000000000..6934b0701 --- /dev/null +++ b/tests/folder_rename_test/main.cpp @@ -0,0 +1,130 @@ +#include "db_helper.h" + +#include +#include +#include + +class FolderRenameTest : public QObject +{ + Q_OBJECT + +private slots: + void rewritesOnlyTheRenamedFolderTree(); + void treatsSqlWildcardCharactersLiterally(); + void missingFolderLeavesPathsUntouched(); +}; + +namespace { +QSqlDatabase createDatabase(const QString &connectionName) +{ + auto db = QSqlDatabase::addDatabase("QSQLITE", connectionName); + db.setDatabaseName(":memory:"); + db.open(); + + QSqlQuery query(db); + query.exec("CREATE TABLE folder (id INTEGER PRIMARY KEY, parentId INTEGER, name TEXT, path TEXT, finished BOOLEAN, completed BOOLEAN, added INTEGER, updated INTEGER)"); + query.exec("CREATE TABLE comic (id INTEGER PRIMARY KEY, parentId INTEGER, path TEXT)"); + query.exec("INSERT INTO folder VALUES (2, 1, 'Folder1', '/Folder1', 1, 0, 123, 456)"); + query.exec("INSERT INTO folder VALUES (3, 2, 'subfolder', '/Folder1/subfolder', 0, 1, 234, 567)"); + query.exec("INSERT INTO folder VALUES (4, 3, 'Folder1', '/Folder1/subfolder/Folder1', 0, 1, 345, 678)"); + query.exec("INSERT INTO folder VALUES (5, 1, 'Folder10', '/Folder10', 0, 1, 456, 789)"); + query.exec("INSERT INTO folder VALUES (6, 1, 'Folder1 Backup', '/Folder1 Backup', 0, 1, 567, 890)"); + query.exec("INSERT INTO folder VALUES (7, 1, 'Other', '/Other', 0, 1, 678, 901)"); + query.exec("INSERT INTO folder VALUES (8, 7, 'Folder1', '/Other/Folder1', 0, 1, 789, 012)"); + query.exec("INSERT INTO folder VALUES (9, 1, 'Folder1Backup', '/Folder1Backup', 0, 1, 890, 123)"); + query.exec("INSERT INTO folder VALUES (20, 1, 'Series_100%', '/Series_100%', 0, 1, 901, 234)"); + query.exec("INSERT INTO folder VALUES (21, 1, 'SeriesX100A', '/SeriesX100A', 0, 1, 012, 345)"); + query.exec("INSERT INTO comic VALUES (10, 4, '/Folder1/subfolder/Folder1/comic.cbz')"); + query.exec("INSERT INTO comic VALUES (11, 5, '/Folder10/comic.cbz')"); + query.exec("INSERT INTO comic VALUES (12, 6, '/Folder1 Backup/comic.cbz')"); + query.exec("INSERT INTO comic VALUES (13, 8, '/Other/Folder1/comic.cbz')"); + query.exec("INSERT INTO comic VALUES (14, 1, '/Folder1.cbz')"); + query.exec("INSERT INTO comic VALUES (15, 2, '/Folder1/direct.cbz')"); + query.exec("INSERT INTO comic VALUES (20, 20, '/Series_100%/comic.cbz')"); + query.exec("INSERT INTO comic VALUES (21, 21, '/SeriesX100A/comic.cbz')"); + return db; +} + +QString value(QSqlDatabase &db, const QString &table, int id, const QString &column) +{ + QSqlQuery query(db); + query.prepare(QString("SELECT %1 FROM %2 WHERE id = :id").arg(column, table)); + query.bindValue(":id", id); + query.exec(); + query.next(); + return query.value(0).toString(); +} +} + +void FolderRenameTest::rewritesOnlyTheRenamedFolderTree() +{ + const QString connectionName = "folderRenameSuccess"; + { + auto db = createDatabase(connectionName); + QVERIFY(db.transaction()); + QString error; + QVERIFY2(DBHelper::renameFolder(2, "Folder2", "/Folder1", "/Folder2", db, &error), qPrintable(error)); + QVERIFY(db.commit()); + + QCOMPARE(value(db, "folder", 2, "name"), QString("Folder2")); + QCOMPARE(value(db, "folder", 2, "path"), QString("/Folder2")); + QCOMPARE(value(db, "folder", 2, "finished"), QString("1")); + QCOMPARE(value(db, "folder", 2, "completed"), QString("0")); + QCOMPARE(value(db, "folder", 2, "added"), QString("123")); + QCOMPARE(value(db, "folder", 2, "updated"), QString("456")); + QCOMPARE(value(db, "folder", 3, "path"), QString("/Folder2/subfolder")); + QCOMPARE(value(db, "folder", 4, "path"), QString("/Folder2/subfolder/Folder1")); + QCOMPARE(value(db, "comic", 10, "path"), QString("/Folder2/subfolder/Folder1/comic.cbz")); + QCOMPARE(value(db, "comic", 15, "path"), QString("/Folder2/direct.cbz")); + + QCOMPARE(value(db, "folder", 5, "path"), QString("/Folder10")); + QCOMPARE(value(db, "comic", 11, "path"), QString("/Folder10/comic.cbz")); + QCOMPARE(value(db, "folder", 6, "path"), QString("/Folder1 Backup")); + QCOMPARE(value(db, "comic", 12, "path"), QString("/Folder1 Backup/comic.cbz")); + QCOMPARE(value(db, "folder", 8, "path"), QString("/Other/Folder1")); + QCOMPARE(value(db, "comic", 13, "path"), QString("/Other/Folder1/comic.cbz")); + QCOMPARE(value(db, "folder", 9, "path"), QString("/Folder1Backup")); + QCOMPARE(value(db, "comic", 14, "path"), QString("/Folder1.cbz")); + } + QSqlDatabase::removeDatabase(connectionName); +} + +void FolderRenameTest::treatsSqlWildcardCharactersLiterally() +{ + const QString connectionName = "folderRenameWildcards"; + { + auto db = createDatabase(connectionName); + QVERIFY(db.transaction()); + QString error; + QVERIFY2(DBHelper::renameFolder(20, "Renamed", "/Series_100%", "/Renamed", db, &error), qPrintable(error)); + QVERIFY(db.commit()); + + QCOMPARE(value(db, "folder", 20, "path"), QString("/Renamed")); + QCOMPARE(value(db, "comic", 20, "path"), QString("/Renamed/comic.cbz")); + QCOMPARE(value(db, "folder", 21, "path"), QString("/SeriesX100A")); + QCOMPARE(value(db, "comic", 21, "path"), QString("/SeriesX100A/comic.cbz")); + } + QSqlDatabase::removeDatabase(connectionName); +} + +void FolderRenameTest::missingFolderLeavesPathsUntouched() +{ + const QString connectionName = "folderRenameMissing"; + { + auto db = createDatabase(connectionName); + QVERIFY(db.transaction()); + QString error; + QVERIFY(!DBHelper::renameFolder(99, "Folder2", "/Folder1", "/Folder2", db, &error)); + QVERIFY(!error.isEmpty()); + QVERIFY(db.rollback()); + + QCOMPARE(value(db, "folder", 2, "path"), QString("/Folder1")); + QCOMPARE(value(db, "folder", 3, "path"), QString("/Folder1/subfolder")); + QCOMPARE(value(db, "comic", 10, "path"), QString("/Folder1/subfolder/Folder1/comic.cbz")); + } + QSqlDatabase::removeDatabase(connectionName); +} + +QTEST_GUILESS_MAIN(FolderRenameTest) + +#include "main.moc" diff --git a/tests/organize_files_test/CMakeLists.txt b/tests/organize_files_test/CMakeLists.txt new file mode 100644 index 000000000..e0b4f55b1 --- /dev/null +++ b/tests/organize_files_test/CMakeLists.txt @@ -0,0 +1,20 @@ +qt_add_executable(organize_files_test + main.cpp + ${CMAKE_SOURCE_DIR}/YACReaderLibrary/organize_files/organize_files_plan.cpp + ${CMAKE_SOURCE_DIR}/YACReaderLibrary/organize_files/organize_files_journal.cpp + ${CMAKE_SOURCE_DIR}/YACReaderLibrary/organize_files/organize_files_worker.cpp +) +yacreader_apply_build_options(organize_files_test) +target_include_directories(organize_files_test PRIVATE + ${CMAKE_SOURCE_DIR}/YACReaderLibrary + ${CMAKE_SOURCE_DIR}/YACReaderLibrary/organize_files +) +target_link_libraries(organize_files_test PRIVATE + Qt6::Core + Qt6::Sql + Qt6::Test + db_helper + library_common +) + +add_test(NAME organize_files_test COMMAND organize_files_test) diff --git a/tests/organize_files_test/main.cpp b/tests/organize_files_test/main.cpp new file mode 100644 index 000000000..cef380a25 --- /dev/null +++ b/tests/organize_files_test/main.cpp @@ -0,0 +1,978 @@ +#include "db_helper.h" +#include "organize_files_journal.h" +#include "organize_files_plan.h" +#include "organize_files_worker.h" + +#include +#include +#include +#include +#include + +#include + +using namespace OrganizeFiles; + +class OrganizeFilesTest : public QObject +{ + Q_OBJECT + +private slots: + void substitutesEveryToken(); + void readsTheYearAndTheMonthFromTheDateColumn(); + void keepsPunctuationOutOfEmptyOptionalGroups(); + void padsOnlyTheLeadingDigits(); + void reportsInvalidTokens(); + void sanitizesSegments(); + void resolvesCollisionsAgainstDiskAndPlan(); + void freesTheNameOfAFileThatMovesAway(); + void keepsOverridesAndExclusions(); + void renameModeKeepsEveryFileInItsFolder(); + void rejectsSeparatorsInAFilenamePattern(); + void claimsThePathOfAnExcludedComic(); + void renamesWhenOnlyTheCaseChanges(); + void adoptsTheOnDiskCasingOfExistingFolders(); + void mergesPlannedFolderCasingsIntoOne(); + void ordersMovesSoNothingIsOverwritten(); + void removesOnlyEmptyDirectoriesInsideTheBase(); + void sweepsCreatedDirectoriesWhenAMoveFails(); + void undoRemovesOnlyTheDirectoriesTheRunCreated(); + void movesComicRowWithoutLosingCuration(); + void keepsAFolderThatStillHoldsAComic(); + void createsFolderRowsInheritingTheType(); + void removesOnlyEmptyCreatedFolderRows(); + void journalRoundTrip(); + void journalCarriesTheFolderRowsItRemoved(); + void undoPutsTheDatabaseBackExactlyAsItWas(); +}; + +namespace { + +ComicEntry spiderMan() +{ + ComicEntry entry; + entry.comicId = 1; + entry.sourceAbsolute = QStringLiteral("/library/Unsorted/asm42.cbz"); + entry.baseName = QStringLiteral("asm42"); + entry.extension = QStringLiteral(".cbz"); + entry.publisher = QStringLiteral("Marvel"); + entry.imprint = QStringLiteral("Epic"); + entry.series = QStringLiteral("The Amazing Spider-Man"); + entry.volume = QStringLiteral("1"); + entry.number = QStringLiteral("42"); + entry.count = QStringLiteral("100"); + entry.title = QStringLiteral("The Sinister Six"); + entry.year = QStringLiteral("2018"); + entry.month = QStringLiteral("07"); + entry.storyArc = QStringLiteral("Sinister War"); + entry.arcNumber = QStringLiteral("2"); + entry.writer = QStringLiteral("Dan Slott"); + return entry; +} + +ComicEntry bareScan() +{ + ComicEntry entry; + entry.comicId = 2; + entry.sourceAbsolute = QStringLiteral("/library/Unsorted/scan001.cbz"); + entry.baseName = QStringLiteral("scan001"); + entry.extension = QStringLiteral(".cbz"); + return entry; +} + +QSqlDatabase createDatabase(const QString &connectionName) +{ + auto db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), connectionName); + db.setDatabaseName(QStringLiteral(":memory:")); + db.open(); + + QSqlQuery query(db); + query.exec("PRAGMA foreign_keys = ON"); + query.exec("CREATE TABLE folder (id INTEGER PRIMARY KEY, parentId INTEGER NOT NULL, name TEXT NOT NULL, path TEXT NOT NULL, " + "finished BOOLEAN DEFAULT 0, completed BOOLEAN DEFAULT 1, numChildren INTEGER, firstChildHash TEXT, customImage TEXT, " + "manga BOOLEAN DEFAULT 0, type INTEGER DEFAULT 0, added INTEGER, updated INTEGER, " + "FOREIGN KEY(parentId) REFERENCES folder(id) ON DELETE CASCADE)"); + query.exec("CREATE TABLE comic_info (id INTEGER PRIMARY KEY, hash TEXT, added INTEGER)"); + query.exec("CREATE TABLE comic (id INTEGER PRIMARY KEY, parentId INTEGER NOT NULL, comicInfoId INTEGER NOT NULL, fileName TEXT NOT NULL, path TEXT, " + "FOREIGN KEY(parentId) REFERENCES folder(id) ON DELETE CASCADE, FOREIGN KEY(comicInfoId) REFERENCES comic_info(id))"); + query.exec("CREATE TABLE label (id INTEGER PRIMARY KEY, name TEXT, ordering INTEGER, color INTEGER)"); + query.exec("CREATE TABLE comic_label (id INTEGER PRIMARY KEY, label_id INTEGER, comic_id INTEGER, ordering INTEGER, " + "FOREIGN KEY(comic_id) REFERENCES comic(id) ON DELETE CASCADE)"); + query.exec("CREATE TABLE comic_reading_list (id INTEGER PRIMARY KEY, reading_list_id INTEGER, comic_id INTEGER, ordering INTEGER, " + "FOREIGN KEY(comic_id) REFERENCES comic(id) ON DELETE CASCADE)"); + + query.exec("INSERT INTO folder VALUES (1, 1, 'root', '/', 0, 1, NULL, NULL, NULL, 0, 1, 100, 100)"); + // customImage and type are the folder state that an undo has to bring back. They + // only survive if the row comes back with the same id. + query.exec("INSERT INTO folder VALUES (2, 1, 'Unsorted', '/Unsorted', 0, 1, NULL, NULL, 'cover.jpg', 0, 3, 200, 200)"); + query.exec("INSERT INTO comic_info VALUES (1, 'hash1', 500)"); + query.exec("INSERT INTO comic VALUES (10, 2, 1, 'asm42.cbz', '/Unsorted/asm42.cbz')"); + query.exec("INSERT INTO label VALUES (1, 'To read', 0, 0)"); + query.exec("INSERT INTO comic_label VALUES (1, 1, 10, 0)"); + query.exec("INSERT INTO comic_reading_list VALUES (1, 1, 10, 0)"); + + return db; +} + +void writeFile(const QString &path) +{ + QDir().mkpath(QFileInfo(path).absolutePath()); + QFile file(path); + file.open(QIODevice::WriteOnly); + file.write("x"); + file.close(); +} + +} + +void OrganizeFilesTest::substitutesEveryToken() +{ + const auto entry = spiderMan(); + + QCOMPARE(buildRelativePath(QStringLiteral("{publisher}/{series}/{number} {title}"), entry), + QStringLiteral("Marvel/The Amazing Spider-Man/42 The Sinister Six.cbz")); + QCOMPARE(buildRelativePath(QStringLiteral("{imprint}/{volume}/{count}/{year}/{month}"), entry), + QStringLiteral("Epic/1/100/2018/07.cbz")); + QCOMPARE(buildRelativePath(QStringLiteral("{storyArc} {arcNumber}/{writer}/{filename}"), entry), + QStringLiteral("Sinister War 2/Dan Slott/asm42.cbz")); +} + +void OrganizeFilesTest::readsTheYearAndTheMonthFromTheDateColumn() +{ + ComicEntry entry; + + applyPublicationDate(entry, QStringLiteral("1/7/2018")); + QCOMPARE(entry.year, QStringLiteral("2018")); + QCOMPARE(entry.month, QStringLiteral("07")); + + // Comic Vine pads its components, ComicInfo.xml does not. + ComicEntry padded; + applyPublicationDate(padded, QStringLiteral("01/07/2018")); + QCOMPARE(padded.year, entry.year); + QCOMPARE(padded.month, entry.month); + + // A missing year is stored as a 0, which is not a year. + ComicEntry monthOnly; + applyPublicationDate(monthOnly, QStringLiteral("1/7/0")); + QVERIFY(monthOnly.year.isEmpty()); + QCOMPARE(monthOnly.month, QStringLiteral("07")); + + // A missing month is stored as a 1, so it cannot be told apart from + // January. Comics with only a year get {month} 01. + ComicEntry yearOnly; + applyPublicationDate(yearOnly, QStringLiteral("1/1/2018")); + QCOMPARE(yearOnly.year, QStringLiteral("2018")); + QCOMPARE(yearOnly.month, QStringLiteral("01")); + + for (const auto &date : { QString(), QStringLiteral("2018"), QStringLiteral("//"), QStringLiteral("1/13/2018") }) { + ComicEntry rejected; + applyPublicationDate(rejected, date); + QVERIFY2(rejected.month.isEmpty(), qPrintable(date)); + } + + // The tokens are the ones an empty optional group drops. + ComicEntry undated; + undated.baseName = QStringLiteral("scan001"); + undated.extension = QStringLiteral(".cbz"); + undated.series = QStringLiteral("Series"); + applyPublicationDate(undated, QStringLiteral("1/1/0")); + QCOMPARE(buildRelativePath(QStringLiteral("{series}< ({year})>"), undated), + QStringLiteral("Series.cbz")); +} + +void OrganizeFilesTest::keepsPunctuationOutOfEmptyOptionalGroups() +{ + const auto entry = bareScan(); + + QStringList fallbacks; + QCOMPARE(buildRelativePath(QStringLiteral("{series}< ({year})>/<#{number}>< - {title}>"), entry, &fallbacks), + QStringLiteral("Unknown Series/scan001.cbz")); + + QCOMPARE(buildRelativePath(QStringLiteral("{publisher}/{series}"), entry), + QStringLiteral("Unknown Publisher/Unknown Series.cbz")); + + QVERIFY(!fallbacks.isEmpty()); + + const auto complete = spiderMan(); + QCOMPARE(buildRelativePath(QStringLiteral("{series}< ({year})>/<#{number}>< - {title}>"), complete), + QStringLiteral("The Amazing Spider-Man (2018)/#42 - The Sinister Six.cbz")); + + QCOMPARE(buildRelativePath(QStringLiteral("{publisher}/<{imprint}/>{series}"), complete), + QStringLiteral("Marvel/Epic/The Amazing Spider-Man.cbz")); + QCOMPARE(buildRelativePath(QStringLiteral("{publisher}/<{imprint}/>{series}"), entry), + QStringLiteral("Unknown Publisher/Unknown Series.cbz")); +} + +void OrganizeFilesTest::padsOnlyTheLeadingDigits() +{ + QCOMPARE(padNumber(QStringLiteral("42"), 3), QStringLiteral("042")); + QCOMPARE(padNumber(QStringLiteral("42AU"), 4), QStringLiteral("0042AU")); + QCOMPARE(padNumber(QStringLiteral("AU42"), 4), QStringLiteral("AU42")); + QCOMPARE(padNumber(QStringLiteral("1234"), 3), QStringLiteral("1234")); + + QCOMPARE(buildRelativePath(QStringLiteral("{number:000}"), spiderMan()), QStringLiteral("042.cbz")); +} + +void OrganizeFilesTest::reportsInvalidTokens() +{ + QVERIFY(invalidTokens(QStringLiteral("{series}/{number:000}")).isEmpty()); + QCOMPARE(invalidTokens(QStringLiteral("{series}/{penciller}")), QStringList { QStringLiteral("{penciller}") }); + QCOMPARE(invalidTokens(QStringLiteral("{title:000}")), QStringList { QStringLiteral("{title:000}") }); + QVERIFY(!invalidTokens(QStringLiteral("{series")).isEmpty()); + QVERIFY(!invalidTokens(QStringLiteral("{series}<({year})")).isEmpty()); +} + +void OrganizeFilesTest::sanitizesSegments() +{ + QCOMPARE(sanitizeSegment(QStringLiteral("a/b:c*d")), QStringLiteral("a_b_c_d")); + QCOMPARE(sanitizeSegment(QStringLiteral("trailing dots...")), QStringLiteral("trailing dots")); + QCOMPARE(sanitizeSegment(QStringLiteral(" spaced out ")), QStringLiteral("spaced out")); + QCOMPARE(sanitizeSegment(QStringLiteral("- leading dash")), QStringLiteral("leading dash")); + QCOMPARE(sanitizeSegment(QStringLiteral("NUL")), QStringLiteral("NUL_")); + QCOMPARE(sanitizeSegment(QStringLiteral("com1.cbz")), QStringLiteral("com1.cbz_")); + QCOMPARE(sanitizeSegment(QStringLiteral("Console")), QStringLiteral("Console")); +} + +void OrganizeFilesTest::resolvesCollisionsAgainstDiskAndPlan() +{ + QTemporaryDir temporary; + const QString base = temporary.path(); + + writeFile(base + QStringLiteral("/Marvel/Series/001.cbz")); + + ComicEntry first; + first.comicId = 1; + first.sourceAbsolute = base + QStringLiteral("/in/a.cbz"); + first.extension = QStringLiteral(".cbz"); + first.baseName = QStringLiteral("a"); + first.publisher = QStringLiteral("Marvel"); + first.series = QStringLiteral("Series"); + first.number = QStringLiteral("1"); + + ComicEntry second = first; + second.comicId = 2; + second.sourceAbsolute = base + QStringLiteral("/in/b.cbz"); + second.baseName = QStringLiteral("b"); + + writeFile(first.sourceAbsolute); + writeFile(second.sourceAbsolute); + + PlanBuilder builder({ first, second }, base, Mode::Organize); + const auto moves = builder.build(QStringLiteral("{publisher}/{series}/{number:000}"), { }); + + QCOMPARE(moves.size(), 2); + QCOMPARE(moves.at(0).destinationRelative, QStringLiteral("Marvel/Series/001 (1).cbz")); + QCOMPARE(moves.at(0).status, PlannedMove::Status::Renamed); + QCOMPARE(moves.at(1).destinationRelative, QStringLiteral("Marvel/Series/001 (2).cbz")); + QCOMPARE(moves.at(1).status, PlannedMove::Status::Renamed); +} + +void OrganizeFilesTest::freesTheNameOfAFileThatMovesAway() +{ + QTemporaryDir temporary; + const QString base = temporary.path(); + + ComicEntry mover; + mover.comicId = 1; + mover.sourceAbsolute = base + QStringLiteral("/Series/001.cbz"); + mover.extension = QStringLiteral(".cbz"); + mover.baseName = QStringLiteral("001"); + mover.series = QStringLiteral("Series"); + mover.number = QStringLiteral("1"); + writeFile(mover.sourceAbsolute); + + PlanBuilder builder({ mover }, base, Mode::Organize); + const auto moves = builder.build(QStringLiteral("{series}/{number:000}"), { }); + + QCOMPARE(moves.size(), 1); + QCOMPARE(moves.at(0).status, PlannedMove::Status::Unchanged); + QCOMPARE(moves.at(0).destinationRelative, QStringLiteral("Series/001.cbz")); +} + +void OrganizeFilesTest::keepsOverridesAndExclusions() +{ + QTemporaryDir temporary; + const QString base = temporary.path(); + + auto entry = spiderMan(); + entry.sourceAbsolute = base + QStringLiteral("/in/asm42.cbz"); + writeFile(entry.sourceAbsolute); + + Overrides overrides; + overrides[entry.sourceAbsolute].destinationRelative = QStringLiteral("Renamed/By hand.cbz"); + + PlanBuilder builder({ entry }, base, Mode::Organize); + + auto moves = builder.build(QStringLiteral("{publisher}/{series}/{number:000}"), overrides); + QCOMPARE(moves.at(0).destinationRelative, QStringLiteral("Renamed/By hand.cbz")); + + moves = builder.build(QStringLiteral("{series}/{filename}"), overrides); + QCOMPARE(moves.at(0).destinationRelative, QStringLiteral("Renamed/By hand.cbz")); + + overrides[entry.sourceAbsolute].excluded = true; + moves = builder.build(QStringLiteral("{series}/{filename}"), overrides); + QCOMPARE(moves.at(0).status, PlannedMove::Status::Excluded); +} + +void OrganizeFilesTest::renameModeKeepsEveryFileInItsFolder() +{ + QTemporaryDir temporary; + const QString base = temporary.path(); + + ComicEntry deep; + deep.comicId = 1; + deep.sourceAbsolute = base + QStringLiteral("/3x3 ojos/scans/raw01.cbz"); + deep.baseName = QStringLiteral("raw01"); + deep.extension = QStringLiteral(".cbz"); + deep.series = QStringLiteral("3x3 Eyes"); + deep.number = QStringLiteral("1"); + writeFile(deep.sourceAbsolute); + + ComicEntry atBase; + atBase.comicId = 2; + atBase.sourceAbsolute = base + QStringLiteral("/loose.cbz"); + atBase.baseName = QStringLiteral("loose"); + atBase.extension = QStringLiteral(".cbz"); + atBase.series = QStringLiteral("Loose"); + atBase.number = QStringLiteral("7"); + writeFile(atBase.sourceAbsolute); + + PlanBuilder builder({ deep, atBase }, base, Mode::Rename); + const auto moves = builder.build(QStringLiteral("{series}< #{number:000}>"), { }); + + QCOMPARE(moves.size(), 2); + + // The folder structure is untouched; only the file name changes. + QCOMPARE(moves.at(0).destinationRelative, QStringLiteral("3x3 ojos/scans/3x3 Eyes #001.cbz")); + + // A comic already sitting in the base gets no empty leading segment. + QCOMPARE(moves.at(1).destinationRelative, QStringLiteral("Loose #007.cbz")); + + for (const auto &move : moves) + QCOMPARE(QFileInfo(move.destinationRelative).path(), QFileInfo(QDir(base).relativeFilePath(move.sourceAbsolute)).path()); +} + +void OrganizeFilesTest::rejectsSeparatorsInAFilenamePattern() +{ + QVERIFY(patternCreatesFolders(QStringLiteral("{series}/{number:000}"))); + QVERIFY(!patternCreatesFolders(QStringLiteral("{series} #{number:000}"))); + + QVERIFY(!patternCreatesFolders(defaultPattern(Mode::Rename))); + QVERIFY(patternCreatesFolders(defaultPattern(Mode::Organize))); + + for (const auto &preset : presets(Mode::Rename)) { + QVERIFY2(!patternCreatesFolders(preset.second), qPrintable(preset.second)); + QVERIFY2(invalidTokens(preset.second).isEmpty(), qPrintable(preset.second)); + } + + for (const auto &preset : presets(Mode::Organize)) + QVERIFY2(invalidTokens(preset.second).isEmpty(), qPrintable(preset.second)); + + QVERIFY(!knownTokens().contains(QStringLiteral("folder"))); + QVERIFY(invalidTokens(defaultPattern(Mode::Rename)).isEmpty()); + QVERIFY(invalidTokens(defaultPattern(Mode::Organize)).isEmpty()); +} + +void OrganizeFilesTest::claimsThePathOfAnExcludedComic() +{ + QTemporaryDir temporary; + const QString base = temporary.path(); + + // The excluded comic already sits on the path the pattern gives the other one. + // It never moves, so the other one cannot have that path. + ComicEntry staying; + staying.comicId = 1; + staying.sourceAbsolute = QDir::cleanPath(base + QStringLiteral("/Series/001.cbz")); + staying.baseName = QStringLiteral("001"); + staying.extension = QStringLiteral(".cbz"); + staying.series = QStringLiteral("Series"); + staying.number = QStringLiteral("1"); + + ComicEntry moving; + moving.comicId = 2; + moving.sourceAbsolute = QDir::cleanPath(base + QStringLiteral("/Unsorted/loose.cbz")); + moving.baseName = QStringLiteral("loose"); + moving.extension = QStringLiteral(".cbz"); + moving.series = QStringLiteral("Series"); + moving.number = QStringLiteral("1"); + + writeFile(staying.sourceAbsolute); + writeFile(moving.sourceAbsolute); + + Overrides overrides; + overrides[staying.sourceAbsolute].excluded = true; + + PlanBuilder builder({ staying, moving }, base, Mode::Organize); + const auto moves = builder.build(QStringLiteral("{series}/{number:000}"), overrides); + + QCOMPARE(moves.size(), 2); + QCOMPARE(moves.at(0).status, PlannedMove::Status::Excluded); + QCOMPARE(moves.at(1).status, PlannedMove::Status::Renamed); + QCOMPARE(moves.at(1).destinationRelative, QStringLiteral("Series/001 (1).cbz")); + + // The same has to hold when the entries arrive the other way round. The old + // single pass made the answer depend on the order of the list. + PlanBuilder reversed({ moving, staying }, base, Mode::Organize); + const auto reversedMoves = reversed.build(QStringLiteral("{series}/{number:000}"), overrides); + + QCOMPARE(reversedMoves.size(), 2); + QCOMPARE(reversedMoves.at(0).status, PlannedMove::Status::Renamed); + QCOMPARE(reversedMoves.at(0).destinationRelative, QStringLiteral("Series/001 (1).cbz")); + QCOMPARE(reversedMoves.at(1).status, PlannedMove::Status::Excluded); +} + +void OrganizeFilesTest::renamesWhenOnlyTheCaseChanges() +{ + QTemporaryDir temporary; + const QString base = temporary.path(); + + ComicEntry entry; + entry.comicId = 1; + entry.sourceAbsolute = QDir::cleanPath(base + QStringLiteral("/Series/spider-man 001.cbz")); + entry.baseName = QStringLiteral("spider-man 001"); + entry.extension = QStringLiteral(".cbz"); + entry.series = QStringLiteral("Spider-Man"); + entry.number = QStringLiteral("001"); + + writeFile(entry.sourceAbsolute); + + PlanBuilder builder({ entry }, base, Mode::Rename); + const auto moves = builder.build(QStringLiteral("{series} {number}"), Overrides()); + + QCOMPARE(moves.size(), 1); + // Folded paths would call this unchanged on Windows and macOS, and fixing + // capitalisation is a normal reason to rename. + QCOMPARE(moves.at(0).status, PlannedMove::Status::Move); + QCOMPARE(moves.at(0).destinationRelative, QStringLiteral("Series/Spider-Man 001.cbz")); + + // And the move itself has to go through, which a plain rename cannot do on a + // file system that ignores case. + QString reason; + const QString destination = QDir::cleanPath(base + QStringLiteral("/Series/Spider-Man 001.cbz")); + QVERIFY2(OrganizeFiles::moveFile(entry.sourceAbsolute, destination, &reason), qPrintable(reason)); + QCOMPARE(QDir(base + QStringLiteral("/Series")).entryList(QDir::Files), QStringList { QStringLiteral("Spider-Man 001.cbz") }); +} + +void OrganizeFilesTest::adoptsTheOnDiskCasingOfExistingFolders() +{ + QTemporaryDir temporary; + const QString base = QDir::cleanPath(temporary.path()); + + // The destination folder already exists on disk with a different casing. + // mkpath() cannot re-case it, so the files will land in "marvel" whatever the + // pattern says, and the plan and the database have to say the same. + writeFile(base + QStringLiteral("/marvel/existing.cbz")); + + ComicEntry entry; + entry.comicId = 1; + entry.sourceAbsolute = QDir::cleanPath(base + QStringLiteral("/Unsorted/a.cbz")); + entry.baseName = QStringLiteral("a"); + entry.extension = QStringLiteral(".cbz"); + entry.publisher = QStringLiteral("Marvel"); + entry.number = QStringLiteral("1"); + writeFile(entry.sourceAbsolute); + + PlanBuilder builder({ entry }, base, Mode::Organize); + const auto moves = builder.build(QStringLiteral("{publisher}/{number:000}"), { }); + + QCOMPARE(moves.size(), 1); +#if defined(Q_OS_WIN) || defined(Q_OS_MACOS) + QCOMPARE(moves.at(0).destinationRelative, QStringLiteral("marvel/001.cbz")); +#else + // On a case-sensitive file system "Marvel" really is a different directory. + QCOMPARE(moves.at(0).destinationRelative, QStringLiteral("Marvel/001.cbz")); +#endif +} + +void OrganizeFilesTest::mergesPlannedFolderCasingsIntoOne() +{ + QTemporaryDir temporary; + const QString base = QDir::cleanPath(temporary.path()); + + // Two casings of one new folder. On disk the second mkpath() is a no-op, so + // only one directory appears, with the casing of whichever move ran first. The + // plan has to agree with itself, or the database gets two folder rows for one + // directory and the next update deletes one of them, comics included. + ComicEntry first; + first.comicId = 1; + first.sourceAbsolute = QDir::cleanPath(base + QStringLiteral("/in/a.cbz")); + first.baseName = QStringLiteral("a"); + first.extension = QStringLiteral(".cbz"); + first.publisher = QStringLiteral("Marvel"); + first.number = QStringLiteral("1"); + + ComicEntry second = first; + second.comicId = 2; + second.sourceAbsolute = QDir::cleanPath(base + QStringLiteral("/in/b.cbz")); + second.baseName = QStringLiteral("b"); + second.publisher = QStringLiteral("MARVEL"); + second.number = QStringLiteral("2"); + + writeFile(first.sourceAbsolute); + writeFile(second.sourceAbsolute); + + PlanBuilder builder({ first, second }, base, Mode::Organize); + const auto moves = builder.build(QStringLiteral("{publisher}/{number:000}"), { }); + + QCOMPARE(moves.size(), 2); + QCOMPARE(moves.at(0).destinationRelative, QStringLiteral("Marvel/001.cbz")); +#if defined(Q_OS_WIN) || defined(Q_OS_MACOS) + // The first appearance in the plan decides the casing. + QCOMPARE(moves.at(1).destinationRelative, QStringLiteral("Marvel/002.cbz")); +#else + QCOMPARE(moves.at(1).destinationRelative, QStringLiteral("MARVEL/002.cbz")); +#endif +} + +void OrganizeFilesTest::ordersMovesSoNothingIsOverwritten() +{ + using OrganizeFiles::FileMove; + + // A chain: the second move has to free /b before the first can take it. + const QList chain { + { 1, QStringLiteral("/a.cbz"), QStringLiteral("/b.cbz") }, + { 2, QStringLiteral("/b.cbz"), QStringLiteral("/c.cbz") } + }; + + const auto orderedChain = OrganizeFiles::orderMoves(chain); + QCOMPARE(orderedChain.size(), 2); + QCOMPARE(orderedChain.at(0).move.comicId, 2ull); + QCOMPARE(orderedChain.at(1).move.comicId, 1ull); + QVERIFY(!orderedChain.at(0).viaTemporary); + QVERIFY(!orderedChain.at(1).viaTemporary); + + // A swap cannot be ordered at all, so one file is parked under a temporary name + // first. The parking move has to come first, or nothing else can proceed. + const QList swap { + { 1, QStringLiteral("/a.cbz"), QStringLiteral("/b.cbz") }, + { 2, QStringLiteral("/b.cbz"), QStringLiteral("/a.cbz") } + }; + + const auto orderedSwap = OrganizeFiles::orderMoves(swap); + QCOMPARE(orderedSwap.size(), 2); + QVERIFY(orderedSwap.at(0).viaTemporary); + QVERIFY(!orderedSwap.at(1).viaTemporary); + QCOMPARE(orderedSwap.at(1).move.comicId, 2ull); + + // Moves that have nothing to do with each other keep their order. + const QList independent { + { 1, QStringLiteral("/a.cbz"), QStringLiteral("/x.cbz") }, + { 2, QStringLiteral("/b.cbz"), QStringLiteral("/y.cbz") } + }; + + const auto orderedIndependent = OrganizeFiles::orderMoves(independent); + QCOMPARE(orderedIndependent.size(), 2); + QCOMPARE(orderedIndependent.at(0).move.comicId, 1ull); + QCOMPARE(orderedIndependent.at(1).move.comicId, 2ull); +} + +void OrganizeFilesTest::removesOnlyEmptyDirectoriesInsideTheBase() +{ + QTemporaryDir temporary; + const QString root = QDir::cleanPath(temporary.path()); + const QString base = root + QStringLiteral("/base"); + + QDir().mkpath(base + QStringLiteral("/empty/deeper")); + QDir().mkpath(base + QStringLiteral("/kept")); + QDir().mkpath(root + QStringLiteral("/outside")); + writeFile(base + QStringLiteral("/kept/still here.cbz")); + + const auto removed = OrganizeFiles::removeEmptyDirectories( + { base + QStringLiteral("/empty/deeper"), base + QStringLiteral("/kept"), root + QStringLiteral("/outside") }, + base); + + // The empty branch goes, and the walk up stops at the base. + QVERIFY(!QDir(base + QStringLiteral("/empty/deeper")).exists()); + QVERIFY(!QDir(base + QStringLiteral("/empty")).exists()); + QCOMPARE(removed.size(), 2); + + QVERIFY(QDir(base).exists()); + QVERIFY(QDir(base + QStringLiteral("/kept")).exists()); + // Outside the base is none of this operation's business, even when it is empty. + QVERIFY(QDir(root + QStringLiteral("/outside")).exists()); +} + +void OrganizeFilesTest::sweepsCreatedDirectoriesWhenAMoveFails() +{ + QTemporaryDir temporary; + const QString library = QDir::cleanPath(temporary.path()); + + // The first move fails: its source does not exist. The directory created for + // it must not survive the run, or a library update right after would find a + // folder the database knows nothing about. + OrganizeFiles::FileMove failing; + failing.comicId = 1; + failing.source = library + QStringLiteral("/Unsorted/missing.cbz"); + failing.destination = library + QStringLiteral("/Marvel/Series/001.cbz"); + + OrganizeFiles::FileMove moving; + moving.comicId = 2; + moving.source = library + QStringLiteral("/Unsorted/real.cbz"); + moving.destination = library + QStringLiteral("/DC/002.cbz"); + writeFile(moving.source); + + MoveWorker worker(library, library, { failing, moving }, true); + worker.process(); + + QCOMPARE(worker.completedMoves().size(), 1); + QCOMPARE(worker.failures().size(), 1); + + // The created-and-unused branch is gone, the used one holds the file. + QVERIFY(!QDir(library + QStringLiteral("/Marvel")).exists()); + QVERIFY(QFileInfo::exists(library + QStringLiteral("/DC/002.cbz"))); + + // The emptied source directory was cleaned up as usual. + QVERIFY(!QDir(library + QStringLiteral("/Unsorted")).exists()); +} + +void OrganizeFilesTest::undoRemovesOnlyTheDirectoriesTheRunCreated() +{ + QTemporaryDir temporary; + const QString base = QDir::cleanPath(temporary.path()); + + // The run created Marvel and Marvel/Spider-Man. It did not create Existing: that + // folder was already there, empty, and the run only put a file in it. + QDir().mkpath(base + QStringLiteral("/Marvel/Spider-Man")); + QDir().mkpath(base + QStringLiteral("/Existing")); + QDir().mkpath(base + QStringLiteral("/Marvel/Kept")); + writeFile(base + QStringLiteral("/Marvel/Kept/other.cbz")); + + const auto removed = OrganizeFiles::removeCreatedDirectories( + { base + QStringLiteral("/Marvel"), base + QStringLiteral("/Marvel/Spider-Man") }); + + QVERIFY(!QDir(base + QStringLiteral("/Marvel/Spider-Man")).exists()); + QCOMPARE(removed.size(), 1); + + // Marvel still holds Kept, so it stays, and so does everything under it. + QVERIFY(QDir(base + QStringLiteral("/Marvel")).exists()); + QVERIFY(QDir(base + QStringLiteral("/Marvel/Kept")).exists()); + + // The folder that was there before the run is empty again, and it is still not + // this operation's to delete. + QVERIFY(QDir(base + QStringLiteral("/Existing")).exists()); +} + +void OrganizeFilesTest::movesComicRowWithoutLosingCuration() +{ + const QString connectionName = QStringLiteral("organize_move"); + { + auto db = createDatabase(connectionName); + + const auto parentId = DBHelper::ensureFolderPath(QStringLiteral("/Marvel/The Amazing Spider-Man"), db); + QVERIFY(parentId > 1); + QVERIFY(DBHelper::moveComic(10, parentId, QStringLiteral("042.cbz"), + QStringLiteral("/Marvel/The Amazing Spider-Man/042.cbz"), db)); + + QSqlQuery query(db); + query.exec("SELECT parentId, fileName, path FROM comic WHERE id = 10"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toULongLong(), parentId); + QCOMPARE(query.value(1).toString(), QStringLiteral("042.cbz")); + QCOMPARE(query.value(2).toString(), QStringLiteral("/Marvel/The Amazing Spider-Man/042.cbz")); + + query.exec("SELECT COUNT(*) FROM comic_label WHERE comic_id = 10"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 1); + + query.exec("SELECT COUNT(*) FROM comic_reading_list WHERE comic_id = 10"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 1); + + // /Unsorted is empty now that the comic moved out, so the row goes. + QList removed; + DBHelper::removeEmptyFolderPaths({ QStringLiteral("/Unsorted") }, db, &removed); + QCOMPARE(removed.size(), 1); + + query.exec("SELECT COUNT(*) FROM folder WHERE path = '/Unsorted'"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 0); + + // Checked again after the folder row is gone. The cascade runs from folder + // to comic and from comic to the curation tables, so this is the assertion + // that says the cleanup did not reach the comic. + query.exec("SELECT COUNT(*) FROM comic WHERE id = 10"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 1); + + query.exec("SELECT COUNT(*) FROM comic_label WHERE comic_id = 10"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 1); + + query.exec("SELECT COUNT(*) FROM comic_reading_list WHERE comic_id = 10"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 1); + } + QSqlDatabase::removeDatabase(connectionName); +} + +void OrganizeFilesTest::keepsAFolderThatStillHoldsAComic() +{ + const QString connectionName = QStringLiteral("organize_keep_folder"); + { + auto db = createDatabase(connectionName); + + // Comic 11 is in the library but not on disk, so the plan skips it. Its row + // still lives in /Unsorted. When comic 10 moves out, the directory on disk + // is empty, but the folder row is not. + QSqlQuery seed(db); + seed.exec("INSERT INTO comic_info VALUES (2, 'hash2', 600)"); + seed.exec("INSERT INTO comic VALUES (11, 2, 2, 'gone.cbz', '/Unsorted/gone.cbz')"); + seed.exec("INSERT INTO comic_label VALUES (2, 1, 11, 0)"); + + const auto parentId = DBHelper::ensureFolderPath(QStringLiteral("/Marvel"), db); + QVERIFY(DBHelper::moveComic(10, parentId, QStringLiteral("042.cbz"), QStringLiteral("/Marvel/042.cbz"), db)); + + QList removed; + DBHelper::removeEmptyFolderPaths({ QStringLiteral("/Unsorted") }, db, &removed); + + QVERIFY(removed.isEmpty()); + + QSqlQuery query(db); + query.exec("SELECT COUNT(*) FROM folder WHERE path = '/Unsorted'"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 1); + + // The whole point: the skipped comic and its label are still there. + query.exec("SELECT COUNT(*) FROM comic WHERE id = 11"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 1); + + query.exec("SELECT COUNT(*) FROM comic_label WHERE comic_id = 11"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 1); + } + QSqlDatabase::removeDatabase(connectionName); +} + +void OrganizeFilesTest::createsFolderRowsInheritingTheType() +{ + const QString connectionName = QStringLiteral("organize_folders"); + { + auto db = createDatabase(connectionName); + + QList created; + const auto parentId = DBHelper::ensureFolderPath(QStringLiteral("/Manga/Series"), db, &created); + QCOMPARE(created.size(), 2); + + QSqlQuery query(db); + query.exec("SELECT type, path FROM folder WHERE id = " + QString::number(parentId)); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 1); + QCOMPARE(query.value(1).toString(), QStringLiteral("/Manga/Series")); + + QList createdAgain; + QCOMPARE(DBHelper::ensureFolderPath(QStringLiteral("/Manga/Series"), db, &createdAgain), parentId); + QVERIFY(createdAgain.isEmpty()); + + DBHelper::moveComic(10, parentId, QStringLiteral("a.cbz"), QStringLiteral("/Manga/Series/a.cbz"), db); + DBHelper::syncFolderAddedFromContents({ parentId }, db); + + query.exec("SELECT added FROM folder WHERE id = " + QString::number(parentId)); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toLongLong(), 500); + } + QSqlDatabase::removeDatabase(connectionName); +} + +void OrganizeFilesTest::removesOnlyEmptyCreatedFolderRows() +{ + const QString connectionName = QStringLiteral("organize_created_rows"); + { + auto db = createDatabase(connectionName); + + // The run created /Marvel and /Marvel/Series and moved the comic in. + QList created; + const auto parentId = DBHelper::ensureFolderPath(QStringLiteral("/Marvel/Series"), db, &created); + QCOMPARE(created.size(), 2); + QVERIFY(DBHelper::moveComic(10, parentId, QStringLiteral("042.cbz"), QStringLiteral("/Marvel/Series/042.cbz"), db)); + + // While the comic is inside, the rows are not empty and must stay, even + // when they are asked for by id. + QList reversed = created; + std::reverse(reversed.begin(), reversed.end()); + DBHelper::removeEmptyFolderRows(reversed, db); + + QSqlQuery query(db); + query.exec("SELECT COUNT(*) FROM folder WHERE path LIKE '/Marvel%'"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 2); + + // The undo moves the comic back. Now the created rows are empty, and the + // undo deletes exactly them, children first. + QVERIFY(DBHelper::moveComic(10, 2, QStringLiteral("asm42.cbz"), QStringLiteral("/Unsorted/asm42.cbz"), db)); + DBHelper::removeEmptyFolderRows(reversed, db); + + query.exec("SELECT COUNT(*) FROM folder WHERE path LIKE '/Marvel%'"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 0); + + // The folders that were there before the run are untouched. + query.exec("SELECT COUNT(*) FROM folder"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 2); + } + QSqlDatabase::removeDatabase(connectionName); +} + +void OrganizeFilesTest::journalRoundTrip() +{ + QTemporaryDir temporary; + const QString library = temporary.path(); + + Journal journal(library); + QVERIFY(journal.begin(library)); + journal.appendMove(10, library + QStringLiteral("/Unsorted/asm42.cbz"), library + QStringLiteral("/Marvel/042.cbz")); + journal.appendRemovedDirectory(library + QStringLiteral("/Unsorted")); + journal.finish(); + + JournalData data; + QVERIFY(Journal::read(library, journal.filePath(), &data)); + QVERIFY(data.complete); + QCOMPARE(data.moves.size(), 1); + QCOMPARE(data.moves.at(0).comicId, 10ull); + QCOMPARE(data.moves.at(0).from, QStringLiteral("/Unsorted/asm42.cbz")); + QCOMPARE(data.moves.at(0).to, QStringLiteral("/Marvel/042.cbz")); + QCOMPARE(data.removedDirectories, QStringList { QStringLiteral("/Unsorted") }); + QCOMPARE(absoluteFromRelative(library, data.moves.at(0).to), QDir::cleanPath(library + QStringLiteral("/Marvel/042.cbz"))); + + QCOMPARE(Journal::latestPath(library), journal.filePath()); +} + +void OrganizeFilesTest::journalCarriesTheFolderRowsItRemoved() +{ + QTemporaryDir temporary; + const QString library = temporary.path(); + + QString journalPath; + + { + Journal journal(library); + QVERIFY(journal.begin(library)); + journal.appendMove(10, library + QStringLiteral("/Unsorted/asm42.cbz"), library + QStringLiteral("/Marvel/042.cbz")); + journal.finish(); + journalPath = journal.filePath(); + } + + // The database work runs after the files have moved and the journal is closed, + // so it has to be able to add to the same record. + { + Journal journal(library); + QVERIFY(journal.reopen(journalPath)); + + QVariantMap row; + row.insert(QStringLiteral("id"), 2); + row.insert(QStringLiteral("parentId"), 1); + row.insert(QStringLiteral("name"), QStringLiteral("Unsorted")); + row.insert(QStringLiteral("path"), QStringLiteral("/Unsorted")); + row.insert(QStringLiteral("type"), 3); + row.insert(QStringLiteral("customImage"), QStringLiteral("cover.jpg")); + + journal.appendRemovedFolder(row); + journal.appendCreatedFolder(7); + journal.appendCreatedFolder(8); + journal.finish(); + } + + JournalData data; + QVERIFY(Journal::read(library, journalPath, &data)); + + QCOMPARE(data.moves.size(), 1); + QCOMPARE(data.removedFolders.size(), 1); + + // The created rows come back in creation order, so an undo can reverse the + // list and delete children before parents. + QCOMPARE(data.createdFolders, (QList { 7, 8 })); + + const auto row = data.removedFolders.at(0); + // The id has to survive the round trip through JSON as an integer, because it + // goes straight back into an INTEGER PRIMARY KEY. + QCOMPARE(row.value(QStringLiteral("id")).toULongLong(), 2ull); + QCOMPARE(row.value(QStringLiteral("path")).toString(), QStringLiteral("/Unsorted")); + QCOMPARE(row.value(QStringLiteral("type")).toInt(), 3); + QCOMPARE(row.value(QStringLiteral("customImage")).toString(), QStringLiteral("cover.jpg")); +} + +void OrganizeFilesTest::undoPutsTheDatabaseBackExactlyAsItWas() +{ + QTemporaryDir temporary; + const QString library = temporary.path(); + + const QString connectionName = QStringLiteral("organize_undo"); + { + auto db = createDatabase(connectionName); + + const auto readFolder = [&db](const QString &path) { + QSqlQuery query(db); + query.prepare("SELECT id, parentId, name, path, type, customImage, added FROM folder WHERE path = :path"); + query.bindValue(":path", path); + query.exec(); + QVariantList values; + if (query.next()) { + for (int i = 0; i < 7; ++i) + values << query.value(i); + } + return values; + }; + + const auto before = readFolder(QStringLiteral("/Unsorted")); + QCOMPARE(before.size(), 7); + + // The run: the comic moves out and the folder it left is deleted. + const auto destinationId = DBHelper::ensureFolderPath(QStringLiteral("/Marvel/The Amazing Spider-Man"), db); + QVERIFY(DBHelper::moveComic(10, destinationId, QStringLiteral("042.cbz"), + QStringLiteral("/Marvel/The Amazing Spider-Man/042.cbz"), db)); + + QList removedFolders; + DBHelper::removeEmptyFolderPaths({ QStringLiteral("/Unsorted") }, db, &removedFolders); + QCOMPARE(removedFolders.size(), 1); + QVERIFY(readFolder(QStringLiteral("/Unsorted")).isEmpty()); + + // The record goes through the journal, exactly as it does in a real run, so + // the JSON round trip is part of what is being tested here. + Journal journal(library); + QVERIFY(journal.begin(library)); + for (const auto &row : removedFolders) + journal.appendRemovedFolder(row); + journal.finish(); + + JournalData data; + QVERIFY(Journal::read(library, journal.filePath(), &data)); + QCOMPARE(data.removedFolders.size(), 1); + + // The undo. + QVERIFY(DBHelper::restoreFolderRows(data.removedFolders, db)); + + QList created; + const auto restoredId = DBHelper::ensureFolderPath(QStringLiteral("/Unsorted"), db, &created); + // Nothing new was created: the original row is back, so the path resolves to + // it. A new row would mean a new id, and the custom cover for this folder is + // stored under the old one. + QVERIFY(created.isEmpty()); + QCOMPARE(restoredId, before.at(0).toULongLong()); + + QVERIFY(DBHelper::moveComic(10, restoredId, QStringLiteral("asm42.cbz"), QStringLiteral("/Unsorted/asm42.cbz"), db)); + + const auto after = readFolder(QStringLiteral("/Unsorted")); + QCOMPARE(after, before); + + QSqlQuery query(db); + query.exec("SELECT parentId, fileName, path FROM comic WHERE id = 10"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toULongLong(), before.at(0).toULongLong()); + QCOMPARE(query.value(1).toString(), QStringLiteral("asm42.cbz")); + QCOMPARE(query.value(2).toString(), QStringLiteral("/Unsorted/asm42.cbz")); + + query.exec("SELECT COUNT(*) FROM comic_label WHERE comic_id = 10"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 1); + + query.exec("SELECT COUNT(*) FROM comic_reading_list WHERE comic_id = 10"); + QVERIFY(query.next()); + QCOMPARE(query.value(0).toInt(), 1); + } + QSqlDatabase::removeDatabase(connectionName); +} + +QTEST_GUILESS_MAIN(OrganizeFilesTest) + +#include "main.moc" diff --git a/tests/yacreader_libraries_test/CMakeLists.txt b/tests/yacreader_libraries_test/CMakeLists.txt new file mode 100644 index 000000000..e19ebd02a --- /dev/null +++ b/tests/yacreader_libraries_test/CMakeLists.txt @@ -0,0 +1,11 @@ +qt_add_executable(yacreader_libraries_test + main.cpp +) +yacreader_apply_build_options(yacreader_libraries_test) +target_link_libraries(yacreader_libraries_test PRIVATE + Qt6::Core + Qt6::Test + library_common +) + +add_test(NAME yacreader_libraries_test COMMAND yacreader_libraries_test) diff --git a/tests/yacreader_libraries_test/main.cpp b/tests/yacreader_libraries_test/main.cpp new file mode 100644 index 000000000..2e8bc0f68 --- /dev/null +++ b/tests/yacreader_libraries_test/main.cpp @@ -0,0 +1,64 @@ +#include "yacreader_libraries.h" + +#include +#include +#include + +class YACReaderLibrariesTest : public QObject +{ + Q_OBJECT + +private slots: + void renamePreservesLibraryIdentityAndPath(); + void removingUnknownLibraryDoesNothing(); +}; + +void YACReaderLibrariesTest::renamePreservesLibraryIdentityAndPath() +{ + QTemporaryDir temporaryDirectory; + QVERIFY(temporaryDirectory.isValid()); + + const auto comicsPath = temporaryDirectory.filePath("comics"); + const auto mangaPath = temporaryDirectory.filePath("manga"); + QVERIFY(QDir().mkpath(QDir(comicsPath).filePath(".yacreaderlibrary"))); + QVERIFY(QDir().mkpath(QDir(mangaPath).filePath(".yacreaderlibrary"))); + + YACReaderLibraries libraries; + libraries.addLibrary("Comics", comicsPath); + libraries.addLibrary("Manga", mangaPath); + + const auto comicsId = libraries.getUuid("Comics"); + const auto comicsLegacyId = libraries.getId("Comics"); + const auto mangaId = libraries.getUuid("Manga"); + const auto mangaLegacyId = libraries.getId("Manga"); + + libraries.rename("Comics", "Renamed Comics"); + + QCOMPARE(libraries.getPath("Renamed Comics"), comicsPath); + QCOMPARE(libraries.getUuid("Renamed Comics"), comicsId); + QCOMPARE(libraries.getId("Renamed Comics"), comicsLegacyId); + QCOMPARE(libraries.getPath("Manga"), mangaPath); + QCOMPARE(libraries.getUuid("Manga"), mangaId); + QCOMPARE(libraries.getId("Manga"), mangaLegacyId); +} + +void YACReaderLibrariesTest::removingUnknownLibraryDoesNothing() +{ + QTemporaryDir temporaryDirectory; + QVERIFY(temporaryDirectory.isValid()); + + const auto libraryPath = temporaryDirectory.filePath("library"); + QVERIFY(QDir().mkpath(QDir(libraryPath).filePath(".yacreaderlibrary"))); + + YACReaderLibraries libraries; + libraries.addLibrary("Library", libraryPath); + + libraries.remove("Missing"); + + QCOMPARE(libraries.getNames(), QList { "Library" }); + QCOMPARE(libraries.getPath("Library"), libraryPath); +} + +QTEST_GUILESS_MAIN(YACReaderLibrariesTest) + +#include "main.moc"