Pamatovat filtry ve formuláři a přidat jejich reset (#84) (#85)

* Pamatovat filtry ve formuláři a přidat jejich reset (#84)

Filtrační dialog si do konce běhu QGIS pamatuje poslední filtry
potvrzené tlačítkem OK, zvlášť pro akce, lokality a samostatné
nálezy. Storno ani odmítnuté obrácené rozmezí uložený stav nemění.

- tlačítko „Obnovit výchozí“ vrátí formulář do výchozího stavu
  (bbox zapnutý, PIAN se třemi úrovněmi); uložený stav změní až OK
- tlačítko ✕ u každého výběru vymaže jen tento filtr
- upozornění nahoře hlásí obnovené filtry a jejich počet
- kódy, které po aktualizaci heslářů zmizely, se zahodí; popisky
  se skládají z aktuálních heslářů
- výchozí hodnoty jsou definované na jednom místě, PIAN už není
  natvrdo v setup_picker()
- smoke test, README a changelog v2.2.0

OpenSpec: openspec/changes/add-filter-memory-and-reset/
Připraveno s pomocí AI (implementace subagent, revize a ověření
Claude), ručně zkontrolovat v QGIS.

* Křížek vrací filtr do výchozího stavu, oznámení bez ikony (#84)

Úpravy po ručním testu v QGIS:
- ✕ u výběru vrací filtr do jeho výchozího stavu; u PIAN – přesnost
  obnoví tři předvolené úrovně, místo aby výběr vymazal. Tlačítko je
  aktivní, jen když se výběr od výchozího liší. PIAN bez omezení jde
  dál nastavit odškrtnutím všech úrovní ve výběru.
- oznámení o obnovených filtrech bez úvodního „ℹ“

Spec, design, tasks, README, changelog a smoke test upraveny.
Připraveno s pomocí AI.

* Archivovat OpenSpec změnu add-filter-memory-and-reset (#84)

Ruční test v QGIS (akce) zapsán k úkolu 4.3, změna archivována
do openspec/changes/archive/2026-10-02-add-filter-memory-and-reset/.
Připraveno s pomocí AI.

* Upřesnit záznam ručního testu u úkolu 4.3 (#84)

Vzhled i funkce ověřeny u všech tří typů dat, poslední oprava
(✕ u PIAN, oznámení) jen u akcí.
Připraveno s pomocí AI.
This commit is contained in:
david-spacil authored and GitHub committed 2026-10-02 19:04:53 +02:00
1 parent 6e95973296
commit 46fd8da045
9 files changed
+975 -23

No files matched your search

@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-02
@@ -0,0 +1,172 @@
# Design
## Context
See proposal.md – Why. Current state of `amcr_viewer/amcr_dialog.py`
(branch `version/v2.2.0`):
- `AmcrViewer.run_download()` builds a new `AmcrFilterDialog(typ_dat)` for
every opening (`amcr_viewer.py`), without a parent.
- Form state is spread over:
- `self.selection_cache` – 19 keys, each a list of codelist codes; the
picker's read-only `QLineEdit` text is only set inside the nested
`open_dialog()` closure in `setup_picker()`, which keeps no reference
to the line edit.
- checkboxes `chk_bbox` (default checked), `chk_posevidence`,
`chk_proj_akce` (events only), `chk_komponenty` (events and sites);
- `self.date_ranges` – `(api_field, name, date_from, date_to)` with
nullable `QgsDateEdit`s (`clear()` is the only correct way to empty
them, see `_date_edit`).
- The one non-empty default, *PIAN – přesnost* = `HES-000861/862/863`, is
hard-coded inside `setup_picker()` together with its display text.
- Codelists are module-level dicts in `amcr_codelists.py` mapping
**label → code**; `refresh_globals()` updates them in place after
*Aktualizovat hesláře*, so the dialog always sees the current values.
- `tests/smoke_test.py` already builds the dialog offscreen for all three
data types and checks `get_filters()` for date ranges.
## Goals / Non-Goals
**Goals:**
- One snapshot format that describes the whole form, used for remember,
restore, defaults and "is it default?" comparison.
- No change in `get_filters()` / `get_bbox()` / `get_komponenty()` output
for the same form state.
**Non-Goals:**
- Persisting to `QgsSettings` or the project (variants B and C of #84).
- Remembering the window size or scroll position.
## Decisions
### Snapshot = plain dict kept at module level in `amcr_dialog.py`
`_REMEMBERED_STATE: dict[str, dict]` keyed by `typ_dat`. The snapshot is
```python
{
"codes": {cache_key: [code, ...], ...}, # only pickers of this typ
"checks": {"bbox": bool, "posevidence": bool, ...},
"dates": {api_field: (iso_from | None, iso_to | None), ...},
}
```
Dates are stored as ISO strings (or `None` for an empty picker), never as
`QDate`, so a stored value can never turn an empty picker into "today".
- *Why module level, not on `AmcrViewer`:* `run_download()` stays
untouched and the smoke test can exercise remember/restore just by
creating dialogs. QGIS (and Plugin Reloader) re-imports the plugin
package on reload, which drops the dict – that matches the "QGIS run
only" requirement.
- *Alternative – keep one dialog instance per type and only `hide()` it:*
rejected. Restoring would be free, but Cancel would then keep the
cancelled edits (the requirement says it must not), and long-lived
dialogs would hold stale codelist references after an update.
- *Alternative – pass state in/out through `AmcrViewer`:* works, but adds
plumbing in two files for no behavioural gain.
### Defaults defined once
A module-level `DEFAULT_CODES = {"pian_presnost": ["HES-000861",
"HES-000862", "HES-000863"]}` and `DEFAULT_CHECKS = {"bbox": True}`
replace the hard-coded block in `setup_picker()`. `_default_state()`
builds a full snapshot for the dialog's `typ_dat` from them. It is used
by the constructor (no remembered state), the reset button and the
"differs from defaults" comparison – one definition, three users.
### Pickers keep a handle to their widgets
`setup_picker()` registers each picker in `self.pickers[cache_key] =
(data_source, display_field, clear_btn)`. A single
`_set_picker(cache_key, codes)` sets `selection_cache`, rebuilds the
display text from the current codelist (inverted `code → label`, sorted
like the selection dialog), drops unknown codes and enables/disables the
clear button. `open_dialog()`, restore, reset and clear all go through
it, so the display text can never disagree with the cache.
Display text is rebuilt from codes rather than stored, so a label renamed
by a codelist update shows its new name, and a removed code disappears
(spec: *Restored values follow the current codelists*).
### Remember only in `accept()` after validation
`accept()` already returns early on a reversed date range; the snapshot is
taken just before `super().accept()`. `reject()` is not overridden.
### Reset button
`QDialogButtonBox.StandardButton.RestoreDefaults` with Czech text
*Obnovit výchozí* (the standard button would otherwise show the Qt
translation of "Restore Defaults", which depends on the installed Qt
translations). Clicking applies `_default_state()` to the form and hides
the notice; `_REMEMBERED_STATE` is untouched until OK.
The button box already holds *Aktualizovat hesláře* in `ActionRole`; the
reset button sits next to it on the left, OK/Cancel stay on the right.
### Per-picker clear button
A narrow `QToolButton` with text `✕` next to *Vybrat…*. It calls
`_set_picker(cache_key, DEFAULT_CODES.get(cache_key, []))` – it returns
the filter to its default, which is empty for every picker except
*pian_presnost* (its three pre-selected levels). The tooltip is
*Vymazat výběr* for an empty default and *Vrátit výchozí výběr* for
*pian_presnost*. `_set_picker()` enables the button only while the
current codes differ from the default (compared order-insensitively, so
a reordered default still counts as the default); on a fresh dialog the
PIAN button is therefore disabled. For `pian_presnost`, empty means the
filter is not sent (current `get_filters()` behaviour for an empty
list) – this matches the spec.
Changed after the user's manual test in QGIS: the ✕ on *PIAN – přesnost*
emptied the picker, but the user expected it to restore the default
three levels, so the button now returns each filter to its default
instead of always emptying it.
Checkboxes and date pickers do not get their own clear button: a
checkbox is one click, and `QgsDateEdit` with `setAllowNull(True)`
already has its own clear control.
### Notice about restored filters
A `QLabel` above the bbox checkbox, styled like the existing component
warning (neutral info colours), hidden by default. Shown in the
constructor only when a remembered state exists **and** differs from
`_default_state()`. Text: *Načteny filtry z minulého hledání (aktivní
filtry: N).* (changed after the user's manual test in QGIS: the leading
"ℹ " was removed). N counts form items that differ from the default –
one per picker, checkbox and date row (a date row counts once even
with both bounds set). Hidden again on reset; not updated live on
every edit (it describes what was loaded, not the current form).
### Qt5/Qt6
`QToolButton` from `qgis.PyQt.QtWidgets`; all enums fully scoped
(`QDialogButtonBox.StandardButton.RestoreDefaults`,
`QDialogButtonBox.ButtonRole.ResetRole`); no `exec_()`.
## Risks / Trade-offs
- [Forgotten filter gives a suspiciously small result] → notice at the top
with a count; reset is one click.
- [Restored bbox restriction with a different map extent] → bbox is a
checkbox, the extent itself is read at download time as today; nothing
extent-specific is stored.
- [Codelist update removes a selected code] → dropped silently on
restore. Considered warning about it; not done, because the picker text
already shows what is selected and the case is rare.
- [Plugin reload during development keeps the old dict] → only if the
package is not re-imported; both QGIS and Plugin Reloader do re-import.
## Verification
- Smoke test (offline, `qgis/qgis:ltr` and `qgis/qgis:stable`): OK →
reopen restores codes/checks/dates and `get_filters()` is equal; Cancel
keeps the previous state; reset + OK equals a fresh dialog; clear drops
one key from `get_filters()`; unknown code is dropped; notice visible
only for non-default state; types do not share state.
- Manual test in QGIS 3.44 and QGIS 4: the scenarios from the spec, plus
*Aktualizovat hesláře* between two openings.
@@ -0,0 +1,72 @@
# Proposal
## Why
The filter dialog (`AmcrFilterDialog`) is created from scratch every time
the user opens it, so every selection is lost after each download. Refining
a query ("same area, add one more period") means re-entering every picker
and date by hand. There is also no quick way back to the default state once
many filters are set (issue #84).
## What Changes
- The filter dialog remembers the last confirmed filters **per data type**
(Fieldwork events, Sites, Individual finds) for the rest of the QGIS
run. Reopening the dialog for the same data type restores all pickers,
checkboxes and date ranges. Nothing is written to disk; after a QGIS
restart (or a plugin reload) the dialog starts from the defaults again.
- State is remembered only when the dialog is confirmed with OK (after the
existing date-range validation passes). *Cancel* leaves the remembered
state unchanged.
- A new *Obnovit výchozí* button (`RestoreDefaults` role) in the button
row resets the whole form to its **defaults**, not to an empty form:
*Omezit vyhledávání rozsahem okna* checked, *PIAN – přesnost* with its
three pre-selected levels, everything else empty. The reset is applied
to the form only; the remembered state changes only on OK.
- When the dialog opens with restored filters that differ from the
defaults, a notice at the top says so and how many filters are active,
so a forgotten filter further down the scrollable form is not missed.
- Each picker gets a small clear button (✕) that returns that single
filter to its **default** (empty for almost all pickers, the three
pre-selected accuracy levels for *PIAN – přesnost*); it is available
only while the filter differs from that default. "No PIAN
restriction" is still reachable by unchecking all levels in the
selection dialog.
- Restored codes that are no longer in the current codelists (after
*Aktualizovat hesláře*) are dropped, and picker texts are rebuilt from
the current codelist labels.
- README (section 3.3) and the v2.2.0 changelog entry in `metadata.txt`
describe the new behaviour.
Out of scope:
- Persisting filters across QGIS restarts (`QgsSettings`) or in the QGIS
project – considered in issue #84 as variants B and C, not chosen.
- Sharing filter values between data types.
## Capabilities
### New Capabilities
- `filter-dialog`: state of the filter dialog between openings – remembered
filters per data type, reset to defaults, clearing a single filter and
the notice about restored filters.
### Modified Capabilities
<!-- none – openspec/specs/ is not maintained (change-tracked) -->
## Impact
- Code: `amcr_viewer/amcr_dialog.py` (state capture/restore, defaults in
one place, reset button, per-picker clear button, notice);
`tests/smoke_test.py` (offline cases for restore, cancel, reset, clear
and dropped codes). `amcr_viewer/amcr_viewer.py` is not expected to
change – `run_download` keeps creating the dialog as today.
- No change to the digiarchiv API requests: `get_filters()`, `get_bbox()`
and `get_komponenty()` keep their output for the same form state.
- No change to layer attributes or stored settings (`QSettings` is not
touched).
- Target branch `version/v2.2.0` (unreleased): the change joins the v2.2.0
changelog entry, no separate version bump.
- Qt5/Qt6 rules from `AGENTS.md` apply; no new dependencies.
@@ -0,0 +1,111 @@
# Spec Delta
## Purpose
Keeps the filter dialog's selections between openings within one QGIS run,
so a query can be refined without re-entering it, and gives quick ways back
to the default state.
## ADDED Requirements
### Requirement: Confirmed filters are remembered per data type
When the user confirms the filter dialog with OK, the plugin SHALL remember
the whole form state (all pickers, checkboxes and date ranges) for that
data type, and SHALL restore it the next time the dialog for the same data
type is opened within the same QGIS run. Each data type (Fieldwork events,
Sites, Individual finds) SHALL have its own remembered state.
#### Scenario: Reopening after a download
- **GIVEN** the user opened the Fieldwork events dialog, selected a region and a period, set a start-date range and confirmed with OK
- **WHEN** the user opens the Fieldwork events dialog again
- **THEN** the same region, period and date range are selected and confirming without changes sends the same filters as before
#### Scenario: Data types do not share state
- **GIVEN** filters were confirmed in the Fieldwork events dialog
- **WHEN** the user opens the Sites dialog for the first time
- **THEN** the Sites dialog shows its defaults
#### Scenario: Cancel keeps the previous state
- **GIVEN** a remembered state exists for a data type
- **WHEN** the user changes filters and closes the dialog with Cancel
- **THEN** reopening the dialog shows the remembered state, not the cancelled changes
#### Scenario: Rejected date range is not remembered
- **WHEN** the user confirms a reversed date range and the dialog refuses it
- **THEN** the remembered state is unchanged
### Requirement: Remembered state lives only for the QGIS run
The remembered filters SHALL NOT be written to disk, QGIS settings or the
project; after QGIS is restarted or the plugin is reloaded, every dialog
SHALL open with its defaults.
#### Scenario: QGIS restart
- **GIVEN** filters were confirmed in a previous QGIS run
- **WHEN** the user opens the dialog after restarting QGIS
- **THEN** the dialog shows its defaults
### Requirement: Reset restores the defaults
The filter dialog SHALL offer a reset action that returns every field of
the form to its default: the map-extent restriction checked, *PIAN –
přesnost* with its three pre-selected accuracy levels (where the data type
has it), and every other filter empty. The reset SHALL change only the
form; the remembered state SHALL change only when the dialog is then
confirmed with OK.
#### Scenario: Reset and confirm
- **GIVEN** several filters are set
- **WHEN** the user resets the form and confirms with OK
- **THEN** the sent filters equal those of a dialog opened for the first time, and reopening shows the defaults
#### Scenario: Reset and cancel
- **GIVEN** a remembered state exists
- **WHEN** the user resets the form and closes the dialog with Cancel
- **THEN** reopening the dialog shows the remembered state
### Requirement: A single filter can be returned to its default
Each codelist filter SHALL offer a per-picker action that returns only
that filter to its default value (empty, or the three pre-selected
accuracy levels for *PIAN – přesnost*). The action SHALL be available
only while the filter differs from its default. Returning *PIAN –
přesnost* to its default SHALL restore the three pre-selected accuracy
levels; a completely empty *PIAN – přesnost* (no restriction) SHALL
remain reachable by unchecking all levels in the picker's selection
dialog.
#### Scenario: Clearing one picker
- **GIVEN** a region and a period are selected
- **WHEN** the user clears the region filter
- **THEN** the region filter shows nothing selected, the period stays selected and the region parameter is not sent
#### Scenario: Returning PIAN to its default
- **GIVEN** a Fieldwork events dialog is open with *PIAN – přesnost* at its default three accuracy levels
- **WHEN** the user changes the PIAN selection (for example clears it)
- **THEN** the picker's clear action becomes available and, when used, restores exactly the three pre-selected accuracy levels
- **WHEN** the user unchecks all levels in the *PIAN – přesnost* selection dialog instead
- **THEN** no accuracy restriction is sent
### Requirement: Restored filters are announced
When the dialog opens with a restored state that differs from the
defaults, it SHALL show a notice at the top of the form stating that
filters from the previous search were restored and how many filters
differ from the defaults. The notice SHALL disappear once the form is
reset to the defaults.
#### Scenario: Notice after reopening
- **GIVEN** a region and a period were confirmed
- **WHEN** the dialog is reopened
- **THEN** a notice at the top says filters were restored and that 2 filters are active
#### Scenario: No notice for defaults
- **WHEN** the dialog opens with no remembered state, or with a remembered state equal to the defaults
- **THEN** no notice is shown
### Requirement: Restored values follow the current codelists
When restoring, the plugin SHALL drop selected codes that are no longer
present in the current codelists and SHALL display the remaining
selections with their current codelist labels.
#### Scenario: Code removed by a codelist update
- **GIVEN** a confirmed selection contains a code that a later codelist update removed
- **WHEN** the dialog is reopened
- **THEN** that code is not selected and not sent, and the other selected values remain
@@ -0,0 +1,82 @@
# Tasks
## 1. Form state in one place
- [x] 1.1 In `amcr_viewer/amcr_dialog.py` add `DEFAULT_CODES` /
`DEFAULT_CHECKS` and `_default_state()`; remove the hard-coded
`pian_presnost` block from `setup_picker()` and apply the default
through the new path. Verify: smoke test case "filtrační dialogy"
still passes and a fresh `akce`/`lokalita` dialog still sends
`f_pian_presnost` with the three codes (assert in the new test 1.4)
- [x] 1.2 Register pickers in `self.pickers` and add `_set_picker()`
(cache + display text rebuilt from the current codelist, unknown codes
dropped, clear-button state); route `open_dialog()` through it.
Verify: `python3 tests/check_sources.py`, `ruff check .`
- [x] 1.3 Add `_snapshot()` / `_apply_state()` covering codes, checkboxes
and date ranges (ISO strings or `None`; empty picker via `clear()`).
Verify: smoke test round-trip – snapshot → apply on a fresh dialog →
equal `get_filters()`, `get_bbox()`, `get_komponenty()`
- [x] 1.4 Extend `tests/smoke_test.py` with an offline case for 1.1–1.3
(defaults incl. PIAN, round-trip for all three data types, unknown code
dropped). Verify: smoke test passes in `qgis/qgis:ltr` and
`qgis/qgis:stable`
## 2. Remember, reset, clear, notice
- [x] 2.1 Module-level `_REMEMBERED_STATE` keyed by `typ_dat`; store the
snapshot in `accept()` after the date-range check, restore in the
constructor. Verify (smoke test): OK → reopen restores; Cancel keeps
the previous state; reversed range refused → state unchanged; another
data type starts from defaults
- [x] 2.2 *Obnovit výchozí* button
(`QDialogButtonBox.StandardButton.RestoreDefaults`, Czech text) that
applies `_default_state()` to the form only. Verify (smoke test): reset
+ OK equals a fresh dialog; reset + Cancel keeps the remembered state
- [x] 2.3 `✕` button (`QToolButton`, tooltip *Vymazat výběr*, or
*Vrátit výchozí výběr* for a picker with a non-empty default) per
picker that returns that filter to its default, enabled only while it
differs from the default. Verify (smoke test): clearing one picker
removes only its key from `get_filters()`; the PIAN `✕` is disabled
on a fresh dialog, enabled after a change and restores the three
default levels
- [x] 2.4 Notice label at the top, shown only when a restored state
differs from defaults, with the count of differing items; hidden on
reset. Verify (smoke test): hidden for a fresh dialog and for a
remembered default state, visible with the right count otherwise
- [x] 2.5 Reset `_REMEMBERED_STATE` between smoke-test cases (in
`try/finally`) so cases stay independent; verify by running the smoke
test twice in one container
## 3. Documentation and version
- [x] 3.1 README section 3.3: remembered filters per data type for the
QGIS run, *Obnovit výchozí*, `✕` per filter, the notice; adjust the
PIAN default note (reset restores it, `✕` clears it). Verify by reading
the section against the spec
- [x] 3.2 Add bullets to the existing v2.2.0 entry of `changelog=` in
`amcr_viewer/metadata.txt` (branch `version/v2.2.0` is unreleased, so
no new version; `CITATION.cff` already says 2.2.0). Verify:
`python3 tests/check_version_bump.py` (or the CI package job) passes
## 4. Final verification
- [x] 4.1 Run the AGENTS.md check set: `tests/check_sources.py`, bandit,
detect-secrets `--all-files`, `flake8 --isolated amcr_viewer/`,
`ruff check .`, `pyqgis4-checker` (log contains only the header), smoke
test in `qgis/qgis:ltr` and `qgis/qgis:stable`; delete
`amcr_viewer/__pycache__` afterwards
- [x] 4.2 `openspec validate add-filter-memory-and-reset --strict` passes
- [x] 4.3 Manual test in QGIS 3.44 and QGIS 4 (user): spec scenarios –
reopen after a download, Cancel, reset + OK / Cancel, `✕` on one
picker and on PIAN, notice text, separate state per data type,
*Aktualizovat hesláře* between two openings, defaults after a QGIS
restart
- User: look and function verified on Fieldwork events, Sites and
Individual finds; everything worked except two points – the notice
started with an odd "ℹ" and `✕` on PIAN emptied it instead of
restoring the default. Both fixed (commit d5e520d); the fix was
re-tested by the user on Fieldwork events, for Sites and Individual
finds it is covered by the smoke test.
- [x] 4.4 Archive before merge:
`openspec archive add-filter-memory-and-reset --skip-specs` in the same
PR