Release NeitzelLib 1.0.2 with saved HTML viewing and row selection
Supply default selection colors through the row container’s user-agent stylesheet so JavaFX can style large result sets within the existing materialization test timeout.
This commit is contained in:
@@ -34,7 +34,7 @@ domain or usable under a license compatible with this project's license.
|
|||||||
### core
|
### core
|
||||||
|
|
||||||
Core utilities, including [foreground desktop observations](core/docs/foreground-detection.md)
|
Core utilities, including [foreground desktop observations](core/docs/foreground-detection.md)
|
||||||
using JNA for optional native desktop integration, and [native application configuration folders](core/docs/application-directories.md).
|
using JNA for optional native desktop integration, and [native application configuration folders](core/docs/application-directories.md). Use [ImageScaler.fitOpaque](core/docs/image-fitting.md) to fit images within bounds and composite transparent pixels onto a background.
|
||||||
|
|
||||||
### encryption
|
### encryption
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ Optional mapped JDBC DataGrid source, initially qualified with H2. See [data-gri
|
|||||||
|
|
||||||
### fx
|
### fx
|
||||||
|
|
||||||
JavaFX docking, standalone bars and optional MVVM bindings from FXML views to ordinary Java models. Docking works with plain JavaFX and standard FXMLLoader without initializing MVVM. See [fx/README.md](fx/README.md) and the [docking guide](fx/docs/docking.md).
|
JavaFX docking, saved HTML/SingleFile viewing, standalone bars and optional MVVM bindings from FXML views to ordinary Java models. Docking works with plain JavaFX and standard FXMLLoader without initializing MVVM. See [fx/README.md](fx/README.md) and the [docking guide](fx/docs/docking.md).
|
||||||
|
|
||||||
### injection
|
### injection
|
||||||
|
|
||||||
@@ -64,20 +64,19 @@ Person desk that shows how to use `fx` and `injection`. Build with `./mvnw -pl f
|
|||||||
|
|
||||||
### gson
|
### gson
|
||||||
|
|
||||||
TypeAdapter for gson.
|
Gson configuration and type adapters, plus JSON storage for versioned DataGrid setups. See the [Gson guide](gson/README.md).
|
||||||
|
|
||||||
### log4j
|
### log4j
|
||||||
|
|
||||||
Stuff for log4j (Version 1). Please use log4j2 if you want to use log4j! (Or log with slf4j as I do in all other
|
Configuration helpers for legacy Log4j 1 applications.
|
||||||
modules!)
|
|
||||||
|
|
||||||
### net
|
### net
|
||||||
|
|
||||||
Some network stuff using javax.mail as dependency.
|
IMAP account monitoring, new-message events and message utilities built on JavaMail.
|
||||||
|
|
||||||
### quarkus
|
### quarkus
|
||||||
|
|
||||||
Some additions for quarkus that might be useful.
|
Request filters and route logging for Quarkus applications.
|
||||||
|
|
||||||
## Start a JavaFX project
|
## Start a JavaFX project
|
||||||
|
|
||||||
@@ -85,10 +84,16 @@ The [complete quick start](fx/docs/quick-start.md) includes local installation,
|
|||||||
|
|
||||||
Build with Java 25. Maven wrapper version is 3.9.11; the project requires Maven 3.9.11 or later. Surefire fails the build if tests fail.
|
Build with Java 25. Maven wrapper version is 3.9.11; the project requires Maven 3.9.11 or later. Surefire fails the build if tests fail.
|
||||||
|
|
||||||
|
## Changes in 1.0.2
|
||||||
|
|
||||||
|
- Display saved HTML and SingleFile archives offline with [HtmlViewer](fx/docs/html-viewer.md). Each viewer can grant external image access for its current document.
|
||||||
|
- Configure single, multiple or disabled [DataGrid row selection](fx/docs/data-grid.md). Applications can track selected keys across pages and access the selected rows on the current page.
|
||||||
|
- Offer prefix suggestions with `AutoCompleteTextField`, removable tags with `TagChip`, and dismissible toolbars with `ToolBarPane`. See the [FXML control reference](fx/docs/fxml-controls.md).
|
||||||
|
- Give each window a [platform menu bar](fx/docs/bars.md#window-menus), including floating docking windows. Use [message catalogs](fx/docs/i18n.md) to translate FXML and Java controls and offer a language menu.
|
||||||
|
|
||||||
## Use a release from Maven
|
## Use a release from Maven
|
||||||
|
|
||||||
The main branch builds `1.0.2-SNAPSHOT`. For the published `1.0.1` release,
|
To use release `1.0.2`, add the Gitea registry to the consuming project's POM and use the release
|
||||||
add the Gitea registry to the consuming project's POM and use the release
|
|
||||||
version for the module you need:
|
version for the module you need:
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
@@ -103,7 +108,7 @@ version for the module you need:
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>fx</artifactId>
|
<artifactId>fx</artifactId>
|
||||||
<version>1.0.1</version>
|
<version>1.0.2</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -71,9 +71,7 @@ detection is working. No compositor extensions or bridges are installed.
|
|||||||
## Tests and observed evidence
|
## Tests and observed evidence
|
||||||
|
|
||||||
Public capability/lifecycle tests run with `mvn -pl core
|
Public capability/lifecycle tests run with `mvn -pl core
|
||||||
-Dtest=ForegroundDetectorTest -Dmaven.test.failure.ignore=false test`. The parent
|
-Dtest=ForegroundDetectorTest test`. Surefire fails the build when a test fails.
|
||||||
project otherwise permits ignored test failures, so use that override when
|
|
||||||
verifying acceptance.
|
|
||||||
|
|
||||||
Native opt-in smoke check: add `-Ddesktop.native.tests=true` in a graphical
|
Native opt-in smoke check: add `-Ddesktop.native.tests=true` in a graphical
|
||||||
session with an identifiable external application foreground. It validates focus
|
session with an identifiable external application foreground. It validates focus
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0.2-SNAPSHOT</version>
|
<version>1.0.2</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>core</artifactId>
|
<artifactId>core</artifactId>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.2-SNAPSHOT</version></parent>
|
<modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.2</version></parent>
|
||||||
<artifactId>data-grid-jdbc</artifactId><description>Optional mapped JDBC grid source</description>
|
<artifactId>data-grid-jdbc</artifactId><description>Optional mapped JDBC grid source</description>
|
||||||
<dependencies><dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
|
<dependencies><dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
|
||||||
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.5.252</version><scope>test</scope></dependency></dependencies></project>
|
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.5.252</version><scope>test</scope></dependency></dependencies></project>
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.2-SNAPSHOT</version></parent>
|
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.2</version></parent>
|
||||||
<artifactId>data-grid</artifactId>
|
<artifactId>data-grid</artifactId>
|
||||||
<description>Toolkit-independent filter, query and grid setup contracts</description>
|
<description>Toolkit-independent filter, query and grid setup contracts</description>
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0.2-SNAPSHOT</version>
|
<version>1.0.2</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>encryption</artifactId>
|
<artifactId>encryption</artifactId>
|
||||||
|
|||||||
@@ -30,12 +30,12 @@ From the NeitzelLib root with JDK 25:
|
|||||||
./mvnw -f fx-example/pom.xml javafx:run
|
./mvnw -f fx-example/pom.xml javafx:run
|
||||||
```
|
```
|
||||||
|
|
||||||
The first command installs local `1.0.2-SNAPSHOT` artifacts; the second runs only the application module. Do not combine `javafx:run` with `-am`, since the parent has no JavaFX launcher. See the [quick start](../fx/docs/quick-start.md) for test reports.
|
The first command installs local `1.0.2` artifacts; the second runs only the application module. Do not combine `javafx:run` with `-am`, since the parent has no JavaFX launcher. See the [quick start](../fx/docs/quick-start.md) for test reports.
|
||||||
|
|
||||||
The packaged alternative, after `package` or `install`, is:
|
The packaged alternative, after `package` or `install`, is:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
java -jar fx-example/target/fx-example-1.0.2-SNAPSHOT.jar
|
java -jar fx-example/target/fx-example-1.0.2.jar
|
||||||
```
|
```
|
||||||
|
|
||||||
Keep the adjacent `target/libs` directory with the JAR: the manifest refers to those copied runtime dependencies. A desktop session is required. This example has no `module-info.java`; it is a classpath application.
|
Keep the adjacent `target/libs` directory with the JAR: the manifest refers to those copied runtime dependencies. A desktop session is required. This example has no `module-info.java`; it is a classpath application.
|
||||||
@@ -108,7 +108,7 @@ Inspect Surefire XML reports for test totals, failures and skips. JavaFX tests n
|
|||||||
|
|
||||||
## Open the example in NeitzelFXDesigner
|
## Open the example in NeitzelFXDesigner
|
||||||
|
|
||||||
The repository root includes `neitzel-fx-designer.json` with the `person-desk` context. It selects `fx-example`, classpath launch, the `designer-preview` Maven profile, the local runtime key `java21`, and `de.neitzel.fx.example.preview.DeskPreviewProvider`. Configure your own JDK path for that key; machine paths are not part of the shared project configuration.
|
The repository root includes `neitzel-fx-designer.json` with the `person-desk` context. It selects `fx-example`, classpath launch, the `designer-preview` Maven profile, the local runtime key `java25`, and `de.neitzel.fx.example.preview.DeskPreviewProvider`. Configure your own JDK path for that key; machine paths are not part of the shared project configuration.
|
||||||
|
|
||||||
The optional profile adds the Designer preview API only to the test source set, compiles `src/designer/java`, includes its resources, and produces Model metadata for Person, Address and Note. It does not add a runtime dependency to the ordinary application, replace its handwritten PersonViewModel, or generate a default ViewModel registry.
|
The optional profile adds the Designer preview API only to the test source set, compiles `src/designer/java`, includes its resources, and produces Model metadata for Person, Address and Note. It does not add a runtime dependency to the ordinary application, replace its handwritten PersonViewModel, or generate a default ViewModel registry.
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ From the repository root with JDK 25, build without installing runtime artifacts
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
./mvnw -pl fx-example -am package -DskipTests
|
./mvnw -pl fx-example -am package -DskipTests
|
||||||
java -cp 'fx-example/target/fx-example-1.0.2-SNAPSHOT.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
|
java -cp 'fx-example/target/fx-example-1.0.2.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
|
||||||
```
|
```
|
||||||
|
|
||||||
The default catalog has 10,000 products. Both backends use identical stable IDs, names, categories, quantities and DECIMAL(12,2) prices. Fixtures include duplicate sort values, nulls, empty text, mixed case, Unicode, apostrophes and literal SQL wildcard characters. One `ProductCatalog` service maintains original text and Locale.ROOT comparison keys together on insertion/reset. Mutations run on application workers and explicitly refresh the grid; browsing is read-only.
|
The default catalog has 10,000 products. Both backends use identical stable IDs, names, categories, quantities and DECIMAL(12,2) prices. Fixtures include duplicate sort values, nulls, empty text, mixed case, Unicode, apostrophes and literal SQL wildcard characters. One `ProductCatalog` service maintains original text and Locale.ROOT comparison keys together on insertion/reset. Mutations run on application workers and explicitly refresh the grid; browsing is read-only.
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
After the reactor `verify` or `package` build, from the repository root (no local artifact install required):
|
After the reactor `verify` or `package` build, from the repository root (no local artifact install required):
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
java -cp 'fx-example/target/fx-example-1.0.2-SNAPSHOT.jar:fx-example/target/libs/*' \
|
java -cp 'fx-example/target/fx-example-1.0.2.jar:fx-example/target/libs/*' \
|
||||||
de.neitzel.fx.example.theme.ThemeGalleryMain
|
de.neitzel.fx.example.theme.ThemeGalleryMain
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0.2-SNAPSHOT</version>
|
<version>1.0.2</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>fx-example</artifactId>
|
<artifactId>fx-example</artifactId>
|
||||||
|
|||||||
+3
-1
@@ -10,6 +10,7 @@
|
|||||||
- [Walk through the person desk](../fx-example/README.md).
|
- [Walk through the person desk](../fx-example/README.md).
|
||||||
- This page is the detailed FXML and runtime reference.
|
- This page is the detailed FXML and runtime reference.
|
||||||
- [Generated ViewModel classes and registries](docs/generated-viewmodels.md).
|
- [Generated ViewModel classes and registries](docs/generated-viewmodels.md).
|
||||||
|
- [Saved HTML and SingleFile viewing](docs/html-viewer.md).
|
||||||
- [Bounded integer spinners](docs/integer-spinners.md) and [system tray support](docs/tray-support.md).
|
- [Bounded integer spinners](docs/integer-spinners.md) and [system tray support](docs/tray-support.md).
|
||||||
- [Standalone toolbar and status bar](docs/bars.md), usable without MVVM.
|
- [Standalone toolbar and status bar](docs/bars.md), usable without MVVM.
|
||||||
- [Docking: opening, moving and activating live contents](docs/docking.md), with ordinary Java/FXML startup examples.
|
- [Docking: opening, moving and activating live contents](docs/docking.md), with ordinary Java/FXML startup examples.
|
||||||
@@ -55,9 +56,10 @@ These are the versions configured by this source snapshot, not a promise of comp
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| JDK | Java 25 | Select a matching JDK for compilation and launch |
|
| JDK | Java 25 | Select a matching JDK for compilation and launch |
|
||||||
| Maven | Minimum 3.9.11; wrapper 3.9.11 | Use the wrapper or an installed Maven |
|
| Maven | Minimum 3.9.11; wrapper 3.9.11 | Use the wrapper or an installed Maven |
|
||||||
| Library | `de.neitzel.lib:fx:1.0.1` | Use the Gitea Maven registry or install the local reactor |
|
| Library | `de.neitzel.lib:fx:1.0.2` | Use the Gitea Maven registry or install the local reactor |
|
||||||
| Internal modules | `fx` directly depends on `core`, `injection` and toolkit-independent `data-grid` | Resolved transitively through Maven |
|
| Internal modules | `fx` directly depends on `core`, `injection` and toolkit-independent `data-grid` | Resolved transitively through Maven |
|
||||||
| JavaFX | 27.0.1: base, graphics, controls, FXML and web | Resolved transitively; deployment still needs platform-native artifacts |
|
| JavaFX | 27.0.1: base, graphics, controls, FXML and web | Resolved transitively; deployment still needs platform-native artifacts |
|
||||||
|
| Saved HTML | jsoup 1.23.2, ph-css 8.2.3, TwelveMonkeys WebP 3.15.3 | Resolved transitively by `fx`; no separate application setup |
|
||||||
| Injection scanning | Reflections 0.10.2 | Brought by `injection` |
|
| Injection scanning | Reflections 0.10.2 | Brought by `injection` |
|
||||||
| Injection annotations | `jakarta.inject-api` 2.0.1 | Use Jakarta annotations, not `javax.inject` |
|
| Injection annotations | `jakarta.inject-api` 2.0.1 | Use Jakarta annotations, not `javax.inject` |
|
||||||
| Logging | SLF4J API 2.0.20 | Choose one logging backend; the example uses `slf4j-simple` 2.0.20 at runtime |
|
| Logging | SLF4J API 2.0.20 | Choose one logging backend; the example uses `slf4j-simple` 2.0.20 at runtime |
|
||||||
|
|||||||
@@ -30,7 +30,10 @@ Use `de.neitzel.grid` for shared models/source types and `de.neitzel.fx.view` fo
|
|||||||
- Header clicks alternate ascending/descending sort for that mapped column; `setSort(null)` clears user sorting. Sorting/filter/page-size changes request the first page (All remains All with fresh consent checks).
|
- Header clicks alternate ascending/descending sort for that mapped column; `setSort(null)` clears user sorting. Sorting/filter/page-size changes request the first page (All remains All with fresh consent checks).
|
||||||
- `setFilters`, `setSort`, `setPageRequest`, `setSource`, `load`, `refresh`, and `retry` delegate to the coordinator; returned rows are never locally filtered again.
|
- `setFilters`, `setSort`, `setPageRequest`, `setSource`, `load`, `refresh`, and `retry` delegate to the coordinator; returned rows are never locally filtered again.
|
||||||
- `stateProperty` exposes requested versus displayed query, result, phase and error. Loading/failed rows stay visible but disabled; selected loaded data becomes unavailable while those rows are stale. Query/navigation controls remain usable.
|
- `stateProperty` exposes requested versus displayed query, result, phase and error. Loading/failed rows stay visible but disabled; selected loaded data becomes unavailable while those rows are stale. Query/navigation controls remain usable.
|
||||||
- `selectedKeyProperty` retains an off-page identity. `selectedElementProperty` exposes only current displayed selected data. A successfully replaced source clears selection. `confirmedDeleted(key)` clears that key and refreshes; absence from a page alone does not imply deletion.
|
- `selectionMode` is configurable in Java or FXML: `NONE`, `SINGLE` (default), or `MULTIPLE`, using `RowSelectionMode`. Changing to NONE clears selection; changing to SINGLE keeps the lead key. Selection mode is application configuration and is not persisted in saved setups.
|
||||||
|
- `selectedKeysProperty` is a read-only observable list retaining off-page identities. `selectedElementsProperty` contains selected models only while their rows are visible and interactive. `selectedKeyProperty` / `selectedElementProperty` expose the lead key/model for compatibility. Single-item actions should require exactly one selected key and one loaded element.
|
||||||
|
- `select(key)` replaces selection (`null` clears); `selectKeys(keys)` replaces a multiple selection, with the last key as lead. Click replaces, Ctrl/Cmd-click toggles, Shift-click selects a range in visible grouped order, Ctrl/Cmd-Shift-click adds a range. Arrow/Home/End keys move through visible rows; Shift extends, Ctrl/Cmd moves focus, Space selects, Ctrl/Cmd-Space toggles, Ctrl/Cmd-A selects visible rows, Escape clears. Embedded editors keep their own keys. Rows have default selection colors even without an application theme.
|
||||||
|
- A successfully replaced source clears all selection. `confirmedDeleted(key)` removes only that key and refreshes; absence from a page alone does not imply deletion. Collapsed groups retain their keys but expose no actionable elements for hidden rows.
|
||||||
- Empty results disable navigation. Unknown totals are displayed as unknown and disable Last. A disappeared page receives one bounded correction; subsequent invalidation becomes an error with Retry.
|
- Empty results disable navigation. Unknown totals are displayed as unknown and disable Last. A disappeared page receives one bounded correction; subsequent invalidation becomes an error with Retry.
|
||||||
|
|
||||||
## Guards, warnings and supersession
|
## Guards, warnings and supersession
|
||||||
|
|||||||
@@ -6,10 +6,11 @@ context. The optional `ViewLoader` applies NeitzelLib binding declarations.
|
|||||||
|
|
||||||
| Control | FXML configuration | Data and lifetime |
|
| Control | FXML configuration | Data and lifetime |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `de.neitzel.fx.view.DataGrid` | Columns, typed attributes, widths, filters, grouping, page size and setup identity | Bind `items` or `source`; explicitly load after configuration, close with the view |
|
| `de.neitzel.fx.view.DataGrid` | Columns, typed attributes, widths, filters, grouping, page size, `selectionMode` and setup identity | Bind `items` or `source`; explicitly load after configuration, close with the view |
|
||||||
| `de.neitzel.fx.view.Table` | `collection`, `row`, `Column` declarations | Existing ViewLoader collection/Component rows and `selection` binding |
|
| `de.neitzel.fx.view.Table` | `collection`, `row`, `Column` declarations | Existing ViewLoader collection/Component rows and `selection` binding |
|
||||||
| `de.neitzel.fx.control.StatusBar` | `leftItems`, `rightItems` containing ordinary Nodes | Bind the properties of the contained controls |
|
| `de.neitzel.fx.control.StatusBar` | `leftItems`, `rightItems` containing ordinary Nodes | Bind the properties of the contained controls |
|
||||||
| `de.neitzel.fx.control.AutoCompleteTextField` | Standard TextField attributes and a `suggestions` list of strings | Type a prefix, use arrow keys and Enter or select with the mouse. Selecting emits the normal text-field action |
|
| `de.neitzel.fx.control.AutoCompleteTextField` | Standard TextField attributes and a `suggestions` list of strings | Type a prefix, use arrow keys and Enter or select with the mouse. Selecting emits the normal text-field action |
|
||||||
|
| `de.neitzel.fx.control.HtmlViewer` | `mediaButtonVisible`, `mediaLoadText`, `mediaReloadText`, `mediaTooltipText`, `noExternalMediaText` | Explicit `load` / `loadHtml` / `display`; call `close()` when disposed. See [HTML viewer](html-viewer.md) |
|
||||||
| `de.neitzel.fx.control.TagChip` | `text`, `removable` (false by default), `onRemove` | The action handler owns removing the tag from its model |
|
| `de.neitzel.fx.control.TagChip` | `text`, `removable` (false by default), `onRemove` | The action handler owns removing the tag from its model |
|
||||||
| `de.neitzel.fx.docking.DockPane` | `initialLayout`, `DockLayout`, group/split definitions | Attach a DockingManager to open application-owned content |
|
| `de.neitzel.fx.docking.DockPane` | `initialLayout`, `DockLayout`, group/split definitions | Attach a DockingManager to open application-owned content |
|
||||||
| `de.neitzel.fx.control.NonNegativeIntegerSpinner` | `minimum`, `maximum`, `initialValue` constructor attributes | Bind writable `number`, which shares the value factory's property |
|
| `de.neitzel.fx.control.NonNegativeIntegerSpinner` | `minimum`, `maximum`, `initialValue` constructor attributes | Bind writable `number`, which shares the value factory's property |
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# Saved HTML viewer
|
||||||
|
|
||||||
|
`de.neitzel.fx.control.HtmlViewer` displays local HTML and SingleFile exports.
|
||||||
|
It preserves saved CSS, classes, inline styles, embedded fonts and background
|
||||||
|
images. SVGs are rendered as isolated images; embedded WebP is converted to PNG
|
||||||
|
in memory for WebView. Files are never rewritten. The control needs ordinary
|
||||||
|
JavaFX only, with no MVVM or injection initialization.
|
||||||
|
|
||||||
|
```java
|
||||||
|
// In Application.start(Stage stage):
|
||||||
|
var viewer = new HtmlViewer();
|
||||||
|
stage.setScene(new Scene(viewer, 900, 600));
|
||||||
|
stage.setOnHidden(event -> viewer.close());
|
||||||
|
stage.show();
|
||||||
|
viewer.load(Path.of("saved-page.html"));
|
||||||
|
```
|
||||||
|
|
||||||
|
`load(Path)` and `loadHtml(String)` prepare content on an owned virtual thread.
|
||||||
|
`loadHtml(String, URI)` additionally accepts an HTTP(S) source address for relative
|
||||||
|
images. It never fetches that address. A saved `<base href>` takes precedence.
|
||||||
|
Input is limited to 32 MiB (UTF-8 bytes for strings). File loads detect the saved encoding.
|
||||||
|
WebP conversion is bounded to 16 megapixels per image and a 64 MiB encoded-image
|
||||||
|
budget per preparation. Invalid or oversized images keep their original data.
|
||||||
|
|
||||||
|
For applications that already prepare documents in the background, use
|
||||||
|
`HtmlDocument.read(Path)` or `HtmlDocument.parse(String[, URI])` off the FX thread,
|
||||||
|
then `viewer.display(document)` on the FX thread. A prepared document is immutable
|
||||||
|
and may be shared between viewers; permissions are never shared with it.
|
||||||
|
|
||||||
|
All viewer operations and property access belong on the FX thread.
|
||||||
|
`loadingProperty()` covers preparation and browser loading; `errorProperty()`
|
||||||
|
reports the current preparation/rendering failure. A progress indicator and error
|
||||||
|
message are included. New loads cancel pending work and discard stale results.
|
||||||
|
`clear()` releases the current content and leaves the viewer reusable. `close()`
|
||||||
|
also cancels pending work, is idempotent, and makes future loads fail.
|
||||||
|
|
||||||
|
## External images
|
||||||
|
|
||||||
|
Each displayed document starts offline. The included **Load external media**
|
||||||
|
button calls `loadExternalImages()`, which explicitly allows HTTP(S) images only
|
||||||
|
for that viewer and document. The same permission covers CSS background images.
|
||||||
|
`externalImagesAvailableProperty()` indicates detected external image addresses;
|
||||||
|
`externalImagesAllowedProperty()` reports whether permission was granted.
|
||||||
|
Loading or displaying another document, clearing, or closing revokes permission.
|
||||||
|
No permission is stored in configuration or in the source file.
|
||||||
|
|
||||||
|
JavaScript, embedded webpages, external stylesheets, external fonts and navigation
|
||||||
|
remain disabled. Embedded SVG is rendered in
|
||||||
|
[SVG secure image mode](https://www.w3.org/TR/SVG/latest/conform.html), rather than
|
||||||
|
as active SVG markup. The document CSP is also applied to saved CSS that the CSS
|
||||||
|
parser does not understand. This is a saved-document viewer; pages that require
|
||||||
|
JavaScript or missing source images cannot be reconstructed.
|
||||||
|
|
||||||
|
Set `mediaButtonVisible=false` if the application supplies its own action.
|
||||||
|
Bind that action to availability/loading and call `loadExternalImages()` on click.
|
||||||
|
Applications still own document tabs, archive paths, metadata, search text, and
|
||||||
|
opening files in external applications.
|
||||||
|
|
||||||
|
## FXML and translations
|
||||||
|
|
||||||
|
Construction performs no file or network I/O. Ordinary `FXMLLoader` can create
|
||||||
|
an idle viewer; the controller explicitly loads its document afterward.
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<?import de.neitzel.fx.control.HtmlViewer?>
|
||||||
|
<HtmlViewer xmlns:fx="http://javafx.com/fxml/1" fx:id="article"
|
||||||
|
mediaButtonVisible="true"
|
||||||
|
mediaLoadText="Externe Medien laden"
|
||||||
|
mediaReloadText="Externe Medien erneut laden"
|
||||||
|
mediaTooltipText="Lädt Bilder nur für diese Ansicht und kontaktiert deren Server."
|
||||||
|
noExternalMediaText="Keine auflösbaren externen Bildadressen gefunden."/>
|
||||||
|
```
|
||||||
|
|
||||||
|
The four text attributes also expose writable StringProperties for ordinary
|
||||||
|
binding or live `Messages.observable(...)` translations. Style classes are
|
||||||
|
`html-viewer` on the root and `html-viewer-media-load` on its action button.
|
||||||
|
|
||||||
|
The tests cover SVG/CSS/WebP rendering through WebView snapshot pixels, offline
|
||||||
|
opening, per-viewer grants, replacement/close, loopback network requests, error
|
||||||
|
handling, and ordinary FXML loading. They require a graphical JavaFX session.
|
||||||
@@ -1,19 +1,19 @@
|
|||||||
# Your first JavaFX application
|
# Your first JavaFX application
|
||||||
|
|
||||||
This walkthrough creates a complete Maven project with one editable name and a label that follows it. It uses Java 25, JavaFX 27.0.1 and NeitzelLib 1.0.1. The source build below uses the matching release tag.
|
This walkthrough creates a complete Maven project with one editable name and a label that follows it. It uses Java 25, JavaFX 27.0.1 and NeitzelLib 1.0.2. The source build below uses the matching release tag.
|
||||||
|
|
||||||
## Prepare the library
|
## Prepare the library
|
||||||
|
|
||||||
Install a JDK 25. Use the library's Maven wrapper (3.9.11), or a separate Maven installation version 3.9.11 or newer. Check `java -version` and `./mvnw -version` before building; on macOS, select the JDK with `export JAVA_HOME=$(/usr/libexec/java_home -v 25)` if necessary.
|
Install a JDK 25. Use the library's Maven wrapper (3.9.11), or a separate Maven installation version 3.9.11 or newer. Check `java -version` and `./mvnw -version` before building; on macOS, select the JDK with `export JAVA_HOME=$(/usr/libexec/java_home -v 25)` if necessary.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone --branch v1.0.1 https://gitea.neitzel.de/konrad/NeitzelLib.git
|
git clone --branch v1.0.2 https://gitea.neitzel.de/konrad/NeitzelLib.git
|
||||||
cd NeitzelLib
|
cd NeitzelLib
|
||||||
./mvnw -pl fx-example -am install
|
./mvnw -pl fx-example -am install
|
||||||
./mvnw -f fx-example/pom.xml javafx:run
|
./mvnw -f fx-example/pom.xml javafx:run
|
||||||
```
|
```
|
||||||
|
|
||||||
The `install` command installs the parent POM, `core`, `injection` and `fx` into your local Maven repository and builds the example. Surefire fails the build when a test fails. The XML reports show which tests ran. The `javafx:run` command opens the [person desk example](../../fx-example/README.md). Run `javafx:run` only on the example POM, not with `-am`: the reactor parent is not a JavaFX application.
|
The `install` command installs the parent POM, `core`, `data-grid`, `injection` and `fx` into your local Maven repository and builds the example. Surefire fails the build when a test fails. The XML reports show which tests ran. The `javafx:run` command opens the [person desk example](../../fx-example/README.md). Run `javafx:run` only on the example POM, not with `-am`: the reactor parent is not a JavaFX application.
|
||||||
|
|
||||||
Check test results after the build (requires Python 3):
|
Check test results after the build (requires Python 3):
|
||||||
|
|
||||||
@@ -66,7 +66,7 @@ hello-fx/
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>fx</artifactId>
|
<artifactId>fx</artifactId>
|
||||||
<version>1.0.1</version>
|
<version>1.0.2</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
@@ -190,7 +190,7 @@ For a named-module application, see the [module and lifecycle notes](architectur
|
|||||||
|
|
||||||
| Symptom | Check |
|
| Symptom | Check |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Maven cannot resolve `de.neitzel.lib:fx:1.0.1` or its parent | Install the library reactor first; use the same Maven local repository for both projects. For direct downloads, see the [Maven repository setup](../../README.md#use-a-release-from-maven). |
|
| Maven cannot resolve `de.neitzel.lib:fx:1.0.2` or its parent | Install the library reactor first; use the same Maven local repository for both projects. For direct downloads, see the [Maven repository setup](../../README.md#use-a-release-from-maven). |
|
||||||
| `No plugin found for prefix 'javafx'` | Invoke the example POM directly, or use the complete application POM above. Do not invoke the goal on the library reactor parent. |
|
| `No plugin found for prefix 'javafx'` | Invoke the example POM directly, or use the complete application POM above. Do not invoke the goal on the library reactor parent. |
|
||||||
| JavaFX runtime/native library failure | Check the JDK version, architecture and JavaFX dependencies actually resolved; avoid mixing native artifacts from different platforms or JavaFX versions. |
|
| JavaFX runtime/native library failure | Check the JDK version, architecture and JavaFX dependencies actually resolved; avoid mixing native artifacts from different platforms or JavaFX versions. |
|
||||||
| `getResource(...)` returns null | The FXML belongs under `src/main/resources` in the matching package; verify it was copied to `target/classes`. Resource names are case-sensitive. |
|
| `getResource(...)` returns null | The FXML belongs under `src/main/resources` in the matching package; verify it was copied to `target/classes`. Resource names are case-sensitive. |
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ The renderer preserves supplied row order and does no local filtering, sorting,
|
|||||||
`setColumnOrder` validates complete stable-ID membership and fixed positions before updating headers and fields. `setColumnWidth` accepts default/explicit intent; it returns the clamped applied width so the coordinator can report adjustments. Row roots must have zero padding (put padding inside mapped fields). Rows use zero inter-field spacing to align with result headers; action controls keep their intrinsic size. The result integration now also supplies native resize/reorder and grouping support
|
`setColumnOrder` validates complete stable-ID membership and fixed positions before updating headers and fields. `setColumnWidth` accepts default/explicit intent; it returns the clamped applied width so the coordinator can report adjustments. Row roots must have zero padding (put padding inside mapped fields). Rows use zero inter-field spacing to align with result headers; action controls keep their intrinsic size. The result integration now also supplies native resize/reorder and grouping support
|
||||||
when composed by DataGrid; the stable programmatic operations remain available. Header requests can be delegated through `setOnSortRequest`; the renderer never sorts locally.
|
when composed by DataGrid; the stable programmatic operations remain available. Header requests can be delegated through `setOnSortRequest`; the renderer never sorts locally.
|
||||||
|
|
||||||
`select(key)` retains an off-page key; the read-only loaded selected element becomes null until that key returns. Row clicks and blank-body clicks update this separate result selection. The old `Table.selectionProperty()` remains the legacy path and is not the result-mode selection API.
|
`setSelectionMode(RowSelectionMode.NONE/SINGLE/MULTIPLE)` configures selection (default SINGLE). `select(key)` replaces selection; `selectKeys(keys)` supports multiple identities, including off-page keys. `selectedKeysProperty()` and `selectedElementsProperty()` expose unmodifiable observable lists; loaded elements include only visible interactive rows. The singular properties expose the lead. `deselect(key)` removes one identity. See [DataGrid selection](data-grid.md) for mouse and keyboard gestures. Row clicks and blank-body clicks update this separate result selection. The old `Table.selectionProperty()` remains the legacy path and is not the result-mode selection API.
|
||||||
|
|
||||||
`close()` is idempotent, removes rows/handlers and disposes row resources. Disposal failures do not undo an already published page; observe `disposalFailureProperty()` to surface them. Explicit close is necessary; attaching/removing a Table from a Scene does not infer application ownership.
|
`close()` is idempotent, removes rows/handlers and disposes row resources. Disposal failures do not undo an already published page; observe `disposalFailureProperty()` to surface them. Explicit close is necessary; attaching/removing a Table from a Scene does not infer application ownership.
|
||||||
|
|
||||||
|
|||||||
+18
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0.2-SNAPSHOT</version>
|
<version>1.0.2</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>fx</artifactId>
|
<artifactId>fx</artifactId>
|
||||||
@@ -43,6 +43,23 @@
|
|||||||
<artifactId>javafx-web</artifactId>
|
<artifactId>javafx-web</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Saved HTML rendering -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jsoup</groupId>
|
||||||
|
<artifactId>jsoup</artifactId>
|
||||||
|
<version>1.23.2</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.helger</groupId>
|
||||||
|
<artifactId>ph-css</artifactId>
|
||||||
|
<version>8.2.3</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.twelvemonkeys.imageio</groupId>
|
||||||
|
<artifactId>imageio-webp</artifactId>
|
||||||
|
<version>3.15.3</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- NeitzelLib dependencies -->
|
<!-- NeitzelLib dependencies -->
|
||||||
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
|
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import javax.imageio.ImageIO;
|
||||||
|
import javax.imageio.stream.MemoryCacheImageInputStream;
|
||||||
|
|
||||||
|
/** WebView does not decode WebP. Convert embedded images once per preparation, without changing the file. */
|
||||||
|
final class EmbeddedImages {
|
||||||
|
private static final Pattern WEBP = Pattern.compile("data:image/webp;base64,[A-Za-z0-9+/=]+", Pattern.CASE_INSENSITIVE);
|
||||||
|
private static final long MAX_PIXELS = 16 * 1024 * 1024;
|
||||||
|
private final Map<String, String> converted = new HashMap<>();
|
||||||
|
private int remainingBytes = 64 * 1024 * 1024;
|
||||||
|
|
||||||
|
String adapt(String value) {
|
||||||
|
if (Thread.currentThread().isInterrupted()) throw new java.util.concurrent.CancellationException();
|
||||||
|
return WEBP.matcher(value).replaceAll(match -> java.util.regex.Matcher.quoteReplacement(
|
||||||
|
converted.computeIfAbsent(match.group(), this::png)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String png(String value) {
|
||||||
|
if (remainingBytes <= 0) return value;
|
||||||
|
try (var input = new MemoryCacheImageInputStream(new ByteArrayInputStream(
|
||||||
|
Base64.getDecoder().decode(value.substring(value.indexOf(',') + 1))))) {
|
||||||
|
var readers = ImageIO.getImageReaders(input);
|
||||||
|
if (!readers.hasNext()) return value;
|
||||||
|
var reader = readers.next();
|
||||||
|
try {
|
||||||
|
reader.setInput(input, true, true);
|
||||||
|
if ((long) reader.getWidth(0) * reader.getHeight(0) > MAX_PIXELS) return value;
|
||||||
|
var image = reader.read(0);
|
||||||
|
var output = new ByteArrayOutputStream();
|
||||||
|
if (!ImageIO.write(image, "png", output)) return value;
|
||||||
|
if ((long) output.size() * 4 / 3 > remainingBytes) return value;
|
||||||
|
remainingBytes -= (output.size() + 2) / 3 * 4;
|
||||||
|
return "data:image/png;base64," + Base64.getEncoder().encodeToString(output.toByteArray());
|
||||||
|
} finally { reader.dispose(); }
|
||||||
|
} catch (IOException | IllegalArgumentException invalid) { return value; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Objects;
|
||||||
|
import org.jsoup.Jsoup;
|
||||||
|
|
||||||
|
/** Immutable prepared HTML, shareable between viewers without sharing external-image permission.
|
||||||
|
* Preparation performs no network requests and may be expensive; call it off the FX thread.
|
||||||
|
*/
|
||||||
|
@lombok.RequiredArgsConstructor(access = lombok.AccessLevel.PACKAGE)
|
||||||
|
public final class HtmlDocument {
|
||||||
|
private static final int MAX_BYTES = 32 * 1024 * 1024;
|
||||||
|
private final String offlineHtml;
|
||||||
|
private final String externalImagesHtml;
|
||||||
|
private final boolean hasExternalImages;
|
||||||
|
|
||||||
|
/** Reads at most 32 MiB, detects the saved character encoding, and never modifies the file. */
|
||||||
|
public static HtmlDocument read(Path file) throws IOException {
|
||||||
|
Objects.requireNonNull(file, "file");
|
||||||
|
try (var input = Files.newInputStream(file)) {
|
||||||
|
byte[] bytes = input.readNBytes(MAX_BYTES + 1);
|
||||||
|
if (bytes.length > MAX_BYTES) throw new IOException("HTML exceeds the 32 MiB preview limit.");
|
||||||
|
return HtmlPresentation.prepare(Jsoup.parse(new ByteArrayInputStream(bytes), null, ""));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static HtmlDocument parse(String html) { return parse(html, null); }
|
||||||
|
|
||||||
|
/** An optional HTTP(S) source address resolves relative images; it is never fetched. */
|
||||||
|
public static HtmlDocument parse(String html, URI source) {
|
||||||
|
Objects.requireNonNull(html, "html");
|
||||||
|
if (source != null && httpUri(source.toString()) == null) {
|
||||||
|
throw new IllegalArgumentException("HTML source must be an HTTP(S) address.");
|
||||||
|
}
|
||||||
|
if (html.length() > MAX_BYTES || html.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) {
|
||||||
|
throw new IllegalArgumentException("HTML exceeds the 32 MiB preview limit.");
|
||||||
|
}
|
||||||
|
return HtmlPresentation.prepare(Jsoup.parse(html, source == null ? "" : source.toASCIIString()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasExternalImages() { return hasExternalImages; }
|
||||||
|
String offlineHtml() { return offlineHtml; }
|
||||||
|
String externalImagesHtml() { return externalImagesHtml; }
|
||||||
|
|
||||||
|
static URI imageUri(String value, URI base) {
|
||||||
|
if (value.isBlank()) return null;
|
||||||
|
try {
|
||||||
|
URI uri = new URI(value.startsWith("//") ? "https:" + value : value);
|
||||||
|
if (!uri.isAbsolute() && base != null) uri = base.resolve(uri);
|
||||||
|
return httpUri(uri.toString());
|
||||||
|
} catch (URISyntaxException invalid) { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
static URI httpUri(String value) {
|
||||||
|
try {
|
||||||
|
URI uri = new URI(value.strip());
|
||||||
|
return uri.getHost() != null && ("https".equalsIgnoreCase(uri.getScheme()) || "http".equalsIgnoreCase(uri.getScheme()))
|
||||||
|
? uri : null;
|
||||||
|
} catch (URISyntaxException invalid) { return null; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import com.helger.css.decl.CSSDeclaration;
|
||||||
|
import com.helger.css.decl.CSSExpressionMemberTermURI;
|
||||||
|
import com.helger.css.decl.CSSFontFaceRule;
|
||||||
|
import com.helger.css.decl.ICSSTopLevelRule;
|
||||||
|
import com.helger.css.decl.visit.CSSVisitor;
|
||||||
|
import com.helger.css.decl.visit.DefaultCSSUrlVisitor;
|
||||||
|
import com.helger.css.reader.CSSReader;
|
||||||
|
import com.helger.css.reader.CSSReaderSettings;
|
||||||
|
import com.helger.css.reader.errorhandler.CollectingCSSParseErrorHandler;
|
||||||
|
import com.helger.css.handler.DoNothingCSSParseExceptionCallback;
|
||||||
|
import com.helger.css.writer.CSSWriter;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import org.jsoup.nodes.DataNode;
|
||||||
|
import org.jsoup.nodes.Document;
|
||||||
|
import org.jsoup.safety.Cleaner;
|
||||||
|
import org.jsoup.safety.Safelist;
|
||||||
|
|
||||||
|
/** Presentation preserves saved CSS; text indexing deliberately uses the simpler reader markup. */
|
||||||
|
final class HtmlPresentation {
|
||||||
|
private static final Safelist SAFE = Safelist.relaxed()
|
||||||
|
.addTags("div", "main", "header", "footer", "nav", "aside", "section", "article", "figure",
|
||||||
|
"figcaption", "small", "mark", "s", "style", "picture", "details", "summary", "time",
|
||||||
|
"form", "fieldset", "legend", "label", "input", "button", "select", "option")
|
||||||
|
.addAttributes(":all", "class", "id", "style", "hidden", "dir", "lang")
|
||||||
|
.addAttributes("input", "type", "value", "placeholder", "checked", "disabled")
|
||||||
|
.addAttributes("button", "type", "disabled")
|
||||||
|
.addAttributes("option", "value", "selected")
|
||||||
|
.addAttributes("style", "media", "type")
|
||||||
|
.removeAttributes("a", "href")
|
||||||
|
.addProtocols("img", "src", "data");
|
||||||
|
private static final Pattern IMAGE = Pattern.compile(
|
||||||
|
"data:image/(?:png|jpeg|gif|webp|svg\\+xml)(?:;[^,]*)?,.+", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
|
||||||
|
|
||||||
|
static HtmlDocument prepare(Document source) {
|
||||||
|
checkCancelled();
|
||||||
|
var images = new EmbeddedImages();
|
||||||
|
for (var style : source.select("style")) {
|
||||||
|
String css = images.adapt(style.data());
|
||||||
|
style.empty().appendChild(new DataNode(css));
|
||||||
|
}
|
||||||
|
for (var element : source.select("[style]")) element.attr("style", images.adapt(element.attr("style")));
|
||||||
|
var baseElement = source.selectFirst("base[href]");
|
||||||
|
URI base = HtmlDocument.httpUri(baseElement == null ? source.baseUri() : baseElement.attr("href"));
|
||||||
|
// Export inline SVG as an isolated image too, keeping page logos and icons without active SVG DOM.
|
||||||
|
for (var svg : source.select("svg").stream()
|
||||||
|
.filter(svg -> svg.parents().stream().noneMatch(parent -> parent.tagName().equals("svg"))).toList()) {
|
||||||
|
svg.attr("xmlns", "http://www.w3.org/2000/svg");
|
||||||
|
var image = new org.jsoup.nodes.Element("img");
|
||||||
|
image.attributes().addAll(svg.attributes());
|
||||||
|
image.attr("src", "data:image/svg+xml;base64," + Base64.getEncoder()
|
||||||
|
.encodeToString(svg.outerHtml().getBytes(StandardCharsets.UTF_8)));
|
||||||
|
svg.replaceWith(image);
|
||||||
|
}
|
||||||
|
source.select("script, template, noscript, iframe, object, embed, link, meta, base").remove();
|
||||||
|
// Cleaner handles the body only. Keep saved styles in their original order, ahead of body styles.
|
||||||
|
var headStyles = source.head().select("style").stream().map(style -> style.clone()).toList();
|
||||||
|
// Embedded SVG remains an image, never active inline SVG markup (SVG secure image mode).
|
||||||
|
for (var image : source.select("img[src]")) {
|
||||||
|
String value = images.adapt(image.attr("src").strip());
|
||||||
|
image.attr("src", value);
|
||||||
|
if (IMAGE.matcher(value).matches()) continue;
|
||||||
|
var remote = HtmlDocument.imageUri(value, base);
|
||||||
|
if (remote == null) image.removeAttr("src");
|
||||||
|
else image.attr("src", remote.toASCIIString());
|
||||||
|
}
|
||||||
|
var safelist = new Safelist(SAFE);
|
||||||
|
for (var element : source.getAllElements()) {
|
||||||
|
checkCancelled();
|
||||||
|
// Saved custom-element wrappers are inert with JavaScript disabled, but their CSS still matters.
|
||||||
|
if (element.tagName().contains("-")) safelist.addTags(element.tagName());
|
||||||
|
for (var attribute : element.attributes()) {
|
||||||
|
if (presentationAttribute(attribute.getKey())) safelist.addAttributes(":all", attribute.getKey());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var clean = new Cleaner(safelist).clean(source);
|
||||||
|
copyAttributes(source.selectFirst("html"), clean.selectFirst("html"));
|
||||||
|
copyAttributes(source.body(), clean.body());
|
||||||
|
clean.title(source.title());
|
||||||
|
for (var style : headStyles) {
|
||||||
|
var saved = clean.head().appendElement("style");
|
||||||
|
if (style.hasAttr("media")) saved.attr("media", style.attr("media"));
|
||||||
|
saved.appendChild(new DataNode(style.data()));
|
||||||
|
}
|
||||||
|
var online = render(clean.clone(), base, true);
|
||||||
|
var offline = render(clean, base, false);
|
||||||
|
return new HtmlDocument(offline.html(), online.html(), online.external());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void copyAttributes(org.jsoup.nodes.Element source, org.jsoup.nodes.Element target) {
|
||||||
|
for (String name : new String[]{"class", "id", "style", "hidden", "dir", "lang"}) {
|
||||||
|
if (source.hasAttr(name)) target.attr(name, source.attr(name));
|
||||||
|
}
|
||||||
|
for (var attribute : source.attributes()) {
|
||||||
|
if (presentationAttribute(attribute.getKey())) target.attr(attribute.getKey(), attribute.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean presentationAttribute(String name) {
|
||||||
|
return name.startsWith("data-") || name.startsWith("aria-") || name.equals("role");
|
||||||
|
}
|
||||||
|
|
||||||
|
private record Rendered(String html, boolean external) {}
|
||||||
|
|
||||||
|
private static Rendered render(Document document, URI base, boolean externalImages) {
|
||||||
|
boolean[] external = {false};
|
||||||
|
for (var image : document.select("img[src]")) {
|
||||||
|
if (HtmlDocument.httpUri(image.attr("src")) != null) {
|
||||||
|
external[0] = true;
|
||||||
|
if (!externalImages) image.removeAttr("src");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (var style : document.select("style")) {
|
||||||
|
String saved = style.data();
|
||||||
|
style.empty().appendChild(new DataNode(css(saved, base, externalImages, external)));
|
||||||
|
}
|
||||||
|
for (var element : document.select("[style]")) {
|
||||||
|
// Parse an attribute as a rule, so URL handling is identical for both kinds of saved CSS.
|
||||||
|
String sheet = css("x{" + element.attr("style") + "}", base, externalImages, external);
|
||||||
|
int start = sheet.indexOf('{'), end = sheet.lastIndexOf('}');
|
||||||
|
element.attr("style", start >= 0 && end > start ? sheet.substring(start + 1, end) : "");
|
||||||
|
}
|
||||||
|
document.head().prependElement("meta").attr("http-equiv", "Content-Security-Policy")
|
||||||
|
.attr("content", policy(externalImages));
|
||||||
|
document.head().prependElement("meta").attr("charset", "UTF-8");
|
||||||
|
document.head().appendElement("meta").attr("name", "viewport").attr("content", "width=device-width, initial-scale=1");
|
||||||
|
document.outputSettings().prettyPrint(false);
|
||||||
|
return new Rendered("<!doctype html>" + document.outerHtml(), external[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String css(String source, URI base, boolean allowExternal, boolean[] external) {
|
||||||
|
checkCancelled();
|
||||||
|
var errors = new CollectingCSSParseErrorHandler();
|
||||||
|
var settings = new CSSReaderSettings().setCustomErrorHandler(errors)
|
||||||
|
.setCustomExceptionHandler(new DoNothingCSSParseExceptionCallback());
|
||||||
|
var sheet = CSSReader.readFromStringReader(source, settings);
|
||||||
|
// Keep unsupported author CSS: the document CSP still enforces the resource boundary.
|
||||||
|
if (sheet == null || errors.hasParseErrors()) return source;
|
||||||
|
sheet.removeAllImportRules();
|
||||||
|
CSSVisitor.visitCSSUrl(sheet, new DefaultCSSUrlVisitor() {
|
||||||
|
@Override public void onUrlDeclaration(ICSSTopLevelRule rule, CSSDeclaration declaration,
|
||||||
|
CSSExpressionMemberTermURI term) {
|
||||||
|
String value = term.getURIString();
|
||||||
|
if (value.regionMatches(true, 0, "data:", 0, 5) || value.startsWith("#")) return;
|
||||||
|
URI remote = HtmlDocument.imageUri(value, base);
|
||||||
|
boolean image = !(rule instanceof CSSFontFaceRule);
|
||||||
|
if (remote != null && image) external[0] = true;
|
||||||
|
term.setURIString(remote != null && image && allowExternal ? remote.toASCIIString() : "data:,");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// A stylesheet's escaped strings must not terminate its HTML raw-text container.
|
||||||
|
return new CSSWriter().getCSSAsString(sheet).replaceAll("(?i)</style", "<\\\\/style");
|
||||||
|
}
|
||||||
|
|
||||||
|
static String policy(boolean externalImages) {
|
||||||
|
return "default-src 'none'; img-src data:" + (externalImages ? " https: http:" : "")
|
||||||
|
+ "; style-src 'unsafe-inline'; font-src data:; script-src 'none'; frame-src 'none';"
|
||||||
|
+ " object-src 'none'; connect-src 'none'; form-action 'none'; base-uri 'none'";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void checkCancelled() {
|
||||||
|
if (Thread.currentThread().isInterrupted()) throw new java.util.concurrent.CancellationException();
|
||||||
|
}
|
||||||
|
|
||||||
|
private HtmlPresentation() {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Objects;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.beans.binding.Bindings;
|
||||||
|
import javafx.beans.property.*;
|
||||||
|
import javafx.concurrent.Task;
|
||||||
|
import javafx.concurrent.Worker;
|
||||||
|
import javafx.geometry.Insets;
|
||||||
|
import javafx.scene.control.Button;
|
||||||
|
import javafx.scene.control.Label;
|
||||||
|
import javafx.scene.control.ProgressIndicator;
|
||||||
|
import javafx.scene.control.Tooltip;
|
||||||
|
import javafx.scene.layout.BorderPane;
|
||||||
|
import javafx.scene.layout.HBox;
|
||||||
|
import javafx.scene.layout.StackPane;
|
||||||
|
import javafx.scene.web.WebView;
|
||||||
|
|
||||||
|
/** Saved HTML viewer with offline defaults, isolated SVG images and per-document image permission.
|
||||||
|
* All instance methods must be called on the FX thread. Constructing the control performs no I/O.
|
||||||
|
* Loading a replacement, clearing or closing cancels pending work and revokes permission.
|
||||||
|
*/
|
||||||
|
public final class HtmlViewer extends BorderPane implements AutoCloseable {
|
||||||
|
private final WebView browser = new WebView();
|
||||||
|
private final ReadOnlyBooleanWrapper preparing = new ReadOnlyBooleanWrapper();
|
||||||
|
private final ReadOnlyBooleanWrapper loading = new ReadOnlyBooleanWrapper(this, "loading");
|
||||||
|
private final ReadOnlyObjectWrapper<Throwable> error = new ReadOnlyObjectWrapper<>(this, "error");
|
||||||
|
private final ReadOnlyBooleanWrapper externalImagesAvailable = new ReadOnlyBooleanWrapper(this, "externalImagesAvailable");
|
||||||
|
private final ReadOnlyBooleanWrapper externalImagesAllowed = new ReadOnlyBooleanWrapper(this, "externalImagesAllowed");
|
||||||
|
private final BooleanProperty mediaButtonVisible = new SimpleBooleanProperty(this, "mediaButtonVisible", true);
|
||||||
|
private final StringProperty mediaLoadText = new SimpleStringProperty(this, "mediaLoadText", "Load external media");
|
||||||
|
private final StringProperty mediaReloadText = new SimpleStringProperty(this, "mediaReloadText", "Reload external media");
|
||||||
|
private final StringProperty mediaTooltipText = new SimpleStringProperty(this, "mediaTooltipText", "Loads external images for this viewer only and contacts their servers.");
|
||||||
|
private final StringProperty noExternalMediaText = new SimpleStringProperty(this, "noExternalMediaText", "No resolvable external image addresses found.");
|
||||||
|
private HtmlDocument document;
|
||||||
|
private Task<HtmlDocument> pending;
|
||||||
|
private long generation;
|
||||||
|
private boolean closed;
|
||||||
|
|
||||||
|
public HtmlViewer() {
|
||||||
|
getStyleClass().add("html-viewer");
|
||||||
|
browser.setContextMenuEnabled(false);
|
||||||
|
browser.getEngine().setJavaScriptEnabled(false);
|
||||||
|
loading.bind(preparing.or(browser.getEngine().getLoadWorker().runningProperty()));
|
||||||
|
browser.getEngine().getLoadWorker().stateProperty().addListener((property, old, state) -> {
|
||||||
|
if (state == Worker.State.FAILED && !preparing.get() && !closed) {
|
||||||
|
error.set(browser.getEngine().getLoadWorker().getException());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
var media = new Button();
|
||||||
|
media.getStyleClass().add("html-viewer-media-load");
|
||||||
|
media.textProperty().bind(Bindings.when(externalImagesAllowed).then(mediaReloadText).otherwise(mediaLoadText));
|
||||||
|
media.disableProperty().bind(loading.or(externalImagesAvailable.not()));
|
||||||
|
var tooltip = new Tooltip();
|
||||||
|
tooltip.textProperty().bind(Bindings.when(externalImagesAvailable).then(mediaTooltipText).otherwise(noExternalMediaText));
|
||||||
|
media.setTooltip(tooltip);
|
||||||
|
media.setOnAction(event -> loadExternalImages());
|
||||||
|
var toolbar = new HBox(media);
|
||||||
|
toolbar.setPadding(new Insets(8, 10, 5, 10));
|
||||||
|
toolbar.visibleProperty().bind(mediaButtonVisible);
|
||||||
|
toolbar.managedProperty().bind(mediaButtonVisible);
|
||||||
|
setTop(toolbar);
|
||||||
|
var progress = new ProgressIndicator();
|
||||||
|
progress.setMaxSize(36, 36);
|
||||||
|
progress.visibleProperty().bind(loading);
|
||||||
|
progress.managedProperty().bind(loading);
|
||||||
|
var failure = new Label();
|
||||||
|
failure.setWrapText(true);
|
||||||
|
failure.textProperty().bind(error.map(problem -> Objects.toString(problem.getMessage(), problem.getClass().getSimpleName())));
|
||||||
|
failure.visibleProperty().bind(error.isNotNull());
|
||||||
|
failure.managedProperty().bind(failure.visibleProperty());
|
||||||
|
setCenter(new StackPane(browser, progress, failure));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Prepare a file on an owned virtual thread, then display it offline. */
|
||||||
|
public void load(Path file) {
|
||||||
|
Objects.requireNonNull(file, "file");
|
||||||
|
prepare(() -> HtmlDocument.read(file));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void loadHtml(String html) { loadHtml(html, null); }
|
||||||
|
|
||||||
|
/** Prepare HTML off the FX thread; source is an optional HTTP(S) base, never a URL to fetch. */
|
||||||
|
public void loadHtml(String html, URI source) {
|
||||||
|
Objects.requireNonNull(html, "html");
|
||||||
|
prepare(() -> HtmlDocument.parse(html, source));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Display an immutable document already prepared by the caller. Permission starts revoked. */
|
||||||
|
public void display(HtmlDocument value) {
|
||||||
|
requireOpen();
|
||||||
|
Objects.requireNonNull(value, "document");
|
||||||
|
clear();
|
||||||
|
show(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void show(HtmlDocument value) {
|
||||||
|
document = value;
|
||||||
|
externalImagesAvailable.set(value.hasExternalImages());
|
||||||
|
browser.getEngine().loadContent(value.offlineHtml());
|
||||||
|
}
|
||||||
|
|
||||||
|
@FunctionalInterface private interface Preparation { HtmlDocument run() throws Exception; }
|
||||||
|
|
||||||
|
private void prepare(Preparation work) {
|
||||||
|
requireOpen();
|
||||||
|
clear();
|
||||||
|
long request = generation;
|
||||||
|
preparing.set(true);
|
||||||
|
var task = new Task<HtmlDocument>() {
|
||||||
|
@Override protected HtmlDocument call() throws Exception { return work.run(); }
|
||||||
|
};
|
||||||
|
pending = task;
|
||||||
|
task.setOnSucceeded(event -> {
|
||||||
|
if (closed || request != generation) return;
|
||||||
|
pending = null;
|
||||||
|
show(task.getValue());
|
||||||
|
preparing.set(false);
|
||||||
|
});
|
||||||
|
task.setOnFailed(event -> {
|
||||||
|
if (closed || request != generation) return;
|
||||||
|
pending = null;
|
||||||
|
error.set(task.getException());
|
||||||
|
preparing.set(false);
|
||||||
|
});
|
||||||
|
Thread.ofVirtual().name("html-viewer-prepare").start(task);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Explicitly grants HTTP(S) image requests for the currently displayed document only. */
|
||||||
|
public void loadExternalImages() {
|
||||||
|
requireOpen();
|
||||||
|
if (document == null || !externalImagesAvailable.get()) return;
|
||||||
|
error.set(null);
|
||||||
|
externalImagesAllowed.set(true);
|
||||||
|
browser.getEngine().loadContent(document.externalImagesHtml());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void clear() {
|
||||||
|
requireOpen();
|
||||||
|
generation++;
|
||||||
|
if (pending != null) { pending.cancel(true); pending = null; }
|
||||||
|
preparing.set(false);
|
||||||
|
document = null;
|
||||||
|
externalImagesAvailable.set(false);
|
||||||
|
externalImagesAllowed.set(false);
|
||||||
|
error.set(null);
|
||||||
|
browser.getEngine().getLoadWorker().cancel();
|
||||||
|
browser.getEngine().load(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void close() {
|
||||||
|
requireFxThread();
|
||||||
|
if (closed) return;
|
||||||
|
clear();
|
||||||
|
closed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireOpen() {
|
||||||
|
requireFxThread();
|
||||||
|
if (closed) throw new IllegalStateException("HtmlViewer is closed.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void requireFxThread() {
|
||||||
|
if (!Platform.isFxApplicationThread()) throw new IllegalStateException("HtmlViewer requires the JavaFX application thread.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public ReadOnlyBooleanProperty loadingProperty() { return loading.getReadOnlyProperty(); }
|
||||||
|
public boolean isLoading() { return loading.get(); }
|
||||||
|
public ReadOnlyObjectProperty<Throwable> errorProperty() { return error.getReadOnlyProperty(); }
|
||||||
|
public Throwable getError() { return error.get(); }
|
||||||
|
public ReadOnlyBooleanProperty externalImagesAvailableProperty() { return externalImagesAvailable.getReadOnlyProperty(); }
|
||||||
|
public boolean isExternalImagesAvailable() { return externalImagesAvailable.get(); }
|
||||||
|
public ReadOnlyBooleanProperty externalImagesAllowedProperty() { return externalImagesAllowed.getReadOnlyProperty(); }
|
||||||
|
public boolean isExternalImagesAllowed() { return externalImagesAllowed.get(); }
|
||||||
|
public BooleanProperty mediaButtonVisibleProperty() { return mediaButtonVisible; }
|
||||||
|
public boolean isMediaButtonVisible() { return mediaButtonVisible.get(); }
|
||||||
|
public void setMediaButtonVisible(boolean value) { mediaButtonVisible.set(value); }
|
||||||
|
public StringProperty mediaLoadTextProperty() { return mediaLoadText; }
|
||||||
|
public String getMediaLoadText() { return mediaLoadText.get(); }
|
||||||
|
public void setMediaLoadText(String value) { mediaLoadText.set(value); }
|
||||||
|
public StringProperty mediaReloadTextProperty() { return mediaReloadText; }
|
||||||
|
public String getMediaReloadText() { return mediaReloadText.get(); }
|
||||||
|
public void setMediaReloadText(String value) { mediaReloadText.set(value); }
|
||||||
|
public StringProperty mediaTooltipTextProperty() { return mediaTooltipText; }
|
||||||
|
public String getMediaTooltipText() { return mediaTooltipText.get(); }
|
||||||
|
public void setMediaTooltipText(String value) { mediaTooltipText.set(value); }
|
||||||
|
public StringProperty noExternalMediaTextProperty() { return noExternalMediaText; }
|
||||||
|
public String getNoExternalMediaText() { return noExternalMediaText.get(); }
|
||||||
|
public void setNoExternalMediaText(String value) { noExternalMediaText.set(value); }
|
||||||
|
}
|
||||||
@@ -88,11 +88,26 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
private final DataGridDeclaration<K, T> declaration = new DataGridDeclaration<>(this);
|
private final DataGridDeclaration<K, T> declaration = new DataGridDeclaration<>(this);
|
||||||
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
|
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
|
||||||
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
|
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
|
||||||
|
private final ReadOnlyListWrapper<K> selectedKeys = new ReadOnlyListWrapper<>(
|
||||||
|
FXCollections.emptyObservableList());
|
||||||
|
private final ReadOnlyListWrapper<T> selectedElements = new ReadOnlyListWrapper<>(
|
||||||
|
FXCollections.emptyObservableList());
|
||||||
|
private final ObjectProperty<RowSelectionMode> selectionMode =
|
||||||
|
new SimpleObjectProperty<>(this, "selectionMode", RowSelectionMode.SINGLE) {
|
||||||
|
@Override public void set(RowSelectionMode value) {
|
||||||
|
requireFx();
|
||||||
|
if (closed) throw new IllegalStateException("Grid is closed");
|
||||||
|
super.set(Objects.requireNonNull(value));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/** Creates a query-free FXML control. Columns are visible before a source is attached. */
|
/** Creates a query-free FXML control. Columns are visible before a source is attached. */
|
||||||
public DataGrid() {
|
public DataGrid() {
|
||||||
requireFx();
|
requireFx();
|
||||||
getStyleClass().add("data-grid");
|
getStyleClass().add("data-grid");
|
||||||
|
selectionMode.addListener((property, old, mode) -> {
|
||||||
|
if (renderer != null) renderer.setSelectionMode(mode);
|
||||||
|
});
|
||||||
setSpacing(8);
|
setSpacing(8);
|
||||||
getChildren().addAll(declaration.preview(), status);
|
getChildren().addAll(declaration.preview(), status);
|
||||||
}
|
}
|
||||||
@@ -258,6 +273,9 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
new PageRequest.Paged(
|
new PageRequest.Paged(
|
||||||
0, Math.min(50, source.capabilities().maximumPageSize())));
|
0, Math.min(50, source.capabilities().maximumPageSize())));
|
||||||
renderer = table.openResults(columns, rowFactory);
|
renderer = table.openResults(columns, rowFactory);
|
||||||
|
renderer.setSelectionMode(getSelectionMode());
|
||||||
|
selectedKeys.bind(renderer.selectedKeysProperty());
|
||||||
|
selectedElements.bind(renderer.selectedElementsProperty());
|
||||||
renderer.enableColumnSeparators();
|
renderer.enableColumnSeparators();
|
||||||
selectedKey.bind(renderer.selectedKeyProperty());
|
selectedKey.bind(renderer.selectedKeyProperty());
|
||||||
selectedElement.bind(renderer.selectedElementProperty());
|
selectedElement.bind(renderer.selectedElementProperty());
|
||||||
@@ -351,6 +369,21 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
return selectedElement.getReadOnlyProperty();
|
return selectedElement.getReadOnlyProperty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ObjectProperty<RowSelectionMode> selectionModeProperty() { return selectionMode; }
|
||||||
|
|
||||||
|
public RowSelectionMode getSelectionMode() { return selectionMode.get(); }
|
||||||
|
|
||||||
|
public void setSelectionMode(RowSelectionMode mode) { selectionMode.set(mode); }
|
||||||
|
|
||||||
|
public ReadOnlyListProperty<K> selectedKeysProperty() { return selectedKeys.getReadOnlyProperty(); }
|
||||||
|
|
||||||
|
public ReadOnlyListProperty<T> selectedElementsProperty() { return selectedElements.getReadOnlyProperty(); }
|
||||||
|
|
||||||
|
public void selectKeys(Collection<? extends K> keys) {
|
||||||
|
check();
|
||||||
|
renderer.selectKeys(keys);
|
||||||
|
}
|
||||||
|
|
||||||
public void select(K key) {
|
public void select(K key) {
|
||||||
check();
|
check();
|
||||||
renderer.select(key);
|
renderer.select(key);
|
||||||
@@ -358,7 +391,7 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
|
|
||||||
public void confirmedDeleted(K key) {
|
public void confirmedDeleted(K key) {
|
||||||
check();
|
check();
|
||||||
if (Objects.equals(key, selectedKeyProperty().get())) renderer.select(null);
|
renderer.deselect(key);
|
||||||
refresh();
|
refresh();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1229,6 +1262,10 @@ public final class DataGrid<K, T> extends VBox implements AutoCloseable {
|
|||||||
if (renderer != null) renderer.close();
|
if (renderer != null) renderer.close();
|
||||||
selectedKey.unbind();
|
selectedKey.unbind();
|
||||||
selectedElement.unbind();
|
selectedElement.unbind();
|
||||||
|
selectedKeys.unbind();
|
||||||
|
selectedElements.unbind();
|
||||||
|
selectedKeys.set(FXCollections.emptyObservableList());
|
||||||
|
selectedElements.set(FXCollections.emptyObservableList());
|
||||||
selectedKey.set(null);
|
selectedKey.set(null);
|
||||||
selectedElement.set(null);
|
selectedElement.set(null);
|
||||||
getChildren().clear();
|
getChildren().clear();
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
/** Configures row selection independently of querying and saved grid layouts. */
|
||||||
|
public enum RowSelectionMode {
|
||||||
|
NONE, SINGLE, MULTIPLE
|
||||||
|
}
|
||||||
@@ -137,7 +137,15 @@ public class Table extends VBox {
|
|||||||
/**
|
/**
|
||||||
* The Rows currently showing.
|
* The Rows currently showing.
|
||||||
*/
|
*/
|
||||||
private final VBox body = new VBox();
|
private final VBox body = new VBox() {
|
||||||
|
private static final String SELECTION_CSS =
|
||||||
|
Table.class.getResource("result-selection.css").toExternalForm();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getUserAgentStylesheet() {
|
||||||
|
return SELECTION_CSS;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The column popup.
|
* The column popup.
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import de.neitzel.grid.*;
|
|||||||
|
|
||||||
import javafx.application.Platform;
|
import javafx.application.Platform;
|
||||||
import javafx.beans.property.*;
|
import javafx.beans.property.*;
|
||||||
|
import javafx.collections.*;
|
||||||
import javafx.event.EventHandler;
|
import javafx.event.EventHandler;
|
||||||
import javafx.scene.Node;
|
import javafx.scene.Node;
|
||||||
import javafx.scene.control.Button;
|
import javafx.scene.control.Button;
|
||||||
@@ -11,6 +12,8 @@ import javafx.scene.control.Label;
|
|||||||
import javafx.scene.control.Tooltip;
|
import javafx.scene.control.Tooltip;
|
||||||
import javafx.scene.input.MouseButton;
|
import javafx.scene.input.MouseButton;
|
||||||
import javafx.scene.input.MouseEvent;
|
import javafx.scene.input.MouseEvent;
|
||||||
|
import javafx.scene.input.KeyEvent;
|
||||||
|
import javafx.scene.input.KeyCode;
|
||||||
import javafx.scene.layout.HBox;
|
import javafx.scene.layout.HBox;
|
||||||
import javafx.scene.layout.Region;
|
import javafx.scene.layout.Region;
|
||||||
import javafx.scene.layout.VBox;
|
import javafx.scene.layout.VBox;
|
||||||
@@ -35,6 +38,14 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
private List<Entry<K, T>> entries = List.of();
|
private List<Entry<K, T>> entries = List.of();
|
||||||
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
|
private final ReadOnlyObjectWrapper<K> selectedKey = new ReadOnlyObjectWrapper<>();
|
||||||
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
|
private final ReadOnlyObjectWrapper<T> selectedElement = new ReadOnlyObjectWrapper<>();
|
||||||
|
private final ObservableList<K> selectedKeys = FXCollections.observableArrayList();
|
||||||
|
private final ObservableList<T> selectedElements = FXCollections.observableArrayList();
|
||||||
|
private final ReadOnlyListWrapper<K> keysView = new ReadOnlyListWrapper<>(
|
||||||
|
FXCollections.unmodifiableObservableList(selectedKeys));
|
||||||
|
private final ReadOnlyListWrapper<T> elementsView = new ReadOnlyListWrapper<>(
|
||||||
|
FXCollections.unmodifiableObservableList(selectedElements));
|
||||||
|
private RowSelectionMode selectionMode = RowSelectionMode.SINGLE;
|
||||||
|
private K anchor;
|
||||||
private final ReadOnlyObjectWrapper<RuntimeException> disposalFailure =
|
private final ReadOnlyObjectWrapper<RuntimeException> disposalFailure =
|
||||||
new ReadOnlyObjectWrapper<>();
|
new ReadOnlyObjectWrapper<>();
|
||||||
private boolean closed;
|
private boolean closed;
|
||||||
@@ -59,7 +70,8 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
private final ResultHeaderGestures gestures;
|
private final ResultHeaderGestures gestures;
|
||||||
private final ResultScrollAlignment scrollAlignment;
|
private final ResultScrollAlignment scrollAlignment;
|
||||||
|
|
||||||
private record Entry<K, T>(GridRow<K, T> row, ResultRow view, EventHandler<MouseEvent> click) {}
|
private record Entry<K, T>(GridRow<K, T> row, ResultRow view,
|
||||||
|
EventHandler<MouseEvent> click, EventHandler<KeyEvent> key) {}
|
||||||
|
|
||||||
TableResults(
|
TableResults(
|
||||||
HBox header,
|
HBox header,
|
||||||
@@ -104,6 +116,20 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
return selectedElement.getReadOnlyProperty();
|
return selectedElement.getReadOnlyProperty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ReadOnlyListProperty<K> selectedKeysProperty() { return keysView.getReadOnlyProperty(); }
|
||||||
|
|
||||||
|
/** Only selected models currently visible and interactive are actionable. */
|
||||||
|
public ReadOnlyListProperty<T> selectedElementsProperty() { return elementsView.getReadOnlyProperty(); }
|
||||||
|
|
||||||
|
public RowSelectionMode getSelectionMode() { return selectionMode; }
|
||||||
|
|
||||||
|
public void setSelectionMode(RowSelectionMode mode) {
|
||||||
|
checkOpen();
|
||||||
|
selectionMode = Objects.requireNonNull(mode);
|
||||||
|
if (mode == RowSelectionMode.NONE) select(null);
|
||||||
|
else if (mode == RowSelectionMode.SINGLE && selectedKeys.size() > 1) select(selectedKey.get());
|
||||||
|
}
|
||||||
|
|
||||||
/** Cleanup failures are exposed separately: they do not roll back an already published page. */
|
/** Cleanup failures are exposed separately: they do not roll back an already published page. */
|
||||||
public ReadOnlyObjectProperty<RuntimeException> disposalFailureProperty() {
|
public ReadOnlyObjectProperty<RuntimeException> disposalFailureProperty() {
|
||||||
return disposalFailure.getReadOnlyProperty();
|
return disposalFailure.getReadOnlyProperty();
|
||||||
@@ -193,10 +219,81 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
/** Retains an off-page key while exposing no loaded selected element. */
|
/** Retains an off-page key while exposing no loaded selected element. */
|
||||||
public void select(K key) {
|
public void select(K key) {
|
||||||
checkOpen();
|
checkOpen();
|
||||||
selectedKey.set(key);
|
selectKeys(key == null ? List.of() : List.of(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replaces selection, retaining off-page identities. The last key is the lead. */
|
||||||
|
public void selectKeys(Collection<? extends K> keys) {
|
||||||
|
checkOpen();
|
||||||
|
var next = new LinkedHashSet<K>();
|
||||||
|
keys.forEach(key -> next.add(Objects.requireNonNull(key)));
|
||||||
|
if (selectionMode == RowSelectionMode.NONE) next.clear();
|
||||||
|
if (selectionMode == RowSelectionMode.SINGLE && next.size() > 1)
|
||||||
|
throw new IllegalArgumentException("Multiple selection is disabled");
|
||||||
|
selectedKeys.setAll(next);
|
||||||
|
selectedKey.set(next.isEmpty() ? null : next.getLast());
|
||||||
|
anchor = selectedKey.get();
|
||||||
markSelection();
|
markSelection();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void deselect(K key) {
|
||||||
|
checkOpen();
|
||||||
|
var remaining = new ArrayList<>(selectedKeys);
|
||||||
|
remaining.remove(key);
|
||||||
|
selectKeys(remaining);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<K> visibleKeys() {
|
||||||
|
var byRoot = new IdentityHashMap<Node, K>();
|
||||||
|
entries.forEach(e -> byRoot.put(e.view().root(), e.row().key()));
|
||||||
|
return body.getChildren().stream().filter(byRoot::containsKey).map(byRoot::get).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void choose(K key, boolean shortcut, boolean shift) {
|
||||||
|
if (!rowsInteractive || selectionMode == RowSelectionMode.NONE) return;
|
||||||
|
if (selectionMode == RowSelectionMode.SINGLE) { select(key); return; }
|
||||||
|
K previousAnchor = anchor;
|
||||||
|
var next = new LinkedHashSet<K>();
|
||||||
|
if (shortcut) next.addAll(selectedKeys);
|
||||||
|
var visible = visibleKeys();
|
||||||
|
int start = visible.indexOf(anchor), end = visible.indexOf(key);
|
||||||
|
if (shift && start >= 0 && end >= 0) {
|
||||||
|
next.addAll(visible.subList(Math.min(start, end), Math.max(start, end) + 1));
|
||||||
|
next.remove(key);
|
||||||
|
next.add(key);
|
||||||
|
} else if (!shortcut || !next.remove(key)) next.add(key);
|
||||||
|
selectKeys(next);
|
||||||
|
anchor = shift && previousAnchor != null ? previousAnchor : key;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void keyPressed(K key, KeyEvent event) {
|
||||||
|
// Embedded editors retain their own keyboard behavior.
|
||||||
|
if (event.getTarget() != event.getSource() || !rowsInteractive
|
||||||
|
|| selectionMode == RowSelectionMode.NONE) return;
|
||||||
|
var visible = visibleKeys();
|
||||||
|
int index = visible.indexOf(key);
|
||||||
|
if (event.getCode() == KeyCode.A && event.isShortcutDown()
|
||||||
|
&& selectionMode == RowSelectionMode.MULTIPLE) selectKeys(visible);
|
||||||
|
else if (event.getCode() == KeyCode.ESCAPE) select(null);
|
||||||
|
else if (event.getCode() == KeyCode.SPACE) choose(key, event.isShortcutDown(), event.isShiftDown());
|
||||||
|
else {
|
||||||
|
int next = switch (event.getCode()) {
|
||||||
|
case UP -> Math.max(0, index - 1);
|
||||||
|
case DOWN -> Math.min(visible.size() - 1, index + 1);
|
||||||
|
case HOME -> 0;
|
||||||
|
case END -> visible.size() - 1;
|
||||||
|
default -> -1;
|
||||||
|
};
|
||||||
|
if (next < 0 || visible.isEmpty()) return;
|
||||||
|
K target = visible.get(next);
|
||||||
|
if (!event.isShortcutDown() || event.isShiftDown())
|
||||||
|
choose(target, event.isShortcutDown(), event.isShiftDown());
|
||||||
|
entries.stream().filter(e -> Objects.equals(e.row().key(), target))
|
||||||
|
.findFirst().ifPresent(e -> e.view().root().requestFocus());
|
||||||
|
}
|
||||||
|
event.consume();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stages fresh rows before replacing the visible page; failed construction preserves the old
|
* Stages fresh rows before replacing the visible page; failed construction preserves the old
|
||||||
* page.
|
* page.
|
||||||
@@ -258,13 +355,20 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
"Row factory must create detached fresh rows");
|
"Row factory must create detached fresh rows");
|
||||||
EventHandler<MouseEvent> click =
|
EventHandler<MouseEvent> click =
|
||||||
e -> {
|
e -> {
|
||||||
if (e.getButton() == MouseButton.PRIMARY) select(row.key());
|
if (e.getButton() == MouseButton.PRIMARY)
|
||||||
|
choose(row.key(), e.isShortcutDown(), e.isShiftDown());
|
||||||
|
if (e.getButton() == MouseButton.PRIMARY
|
||||||
|
&& (e.getTarget() == view.root() || e.getTarget() instanceof Label))
|
||||||
|
view.root().requestFocus();
|
||||||
};
|
};
|
||||||
next.add(new Entry<>(row, view, click));
|
EventHandler<KeyEvent> key = e -> keyPressed(row.key(), e);
|
||||||
|
next.add(new Entry<>(row, view, click, key));
|
||||||
validateRow(view);
|
validateRow(view);
|
||||||
view.root().getStyleClass().add("result-row");
|
view.root().getStyleClass().add("result-row");
|
||||||
layoutRow(view, nextOrder, preparedWidths);
|
layoutRow(view, nextOrder, preparedWidths);
|
||||||
view.root().addEventHandler(MouseEvent.MOUSE_CLICKED, click);
|
view.root().addEventHandler(MouseEvent.MOUSE_CLICKED, click);
|
||||||
|
view.root().setFocusTraversable(true);
|
||||||
|
view.root().addEventHandler(KeyEvent.KEY_PRESSED, key);
|
||||||
}
|
}
|
||||||
} catch (RuntimeException failure) {
|
} catch (RuntimeException failure) {
|
||||||
release(next);
|
release(next);
|
||||||
@@ -445,8 +549,10 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
|
|
||||||
private void markSelection() {
|
private void markSelection() {
|
||||||
T loaded = null;
|
T loaded = null;
|
||||||
|
List<T> actionable = new ArrayList<>();
|
||||||
|
Set<K> keys = new HashSet<>(selectedKeys);
|
||||||
for (var e : entries) {
|
for (var e : entries) {
|
||||||
boolean selected = Objects.equals(selectedKey.get(), e.row().key());
|
boolean selected = keys.contains(e.row().key());
|
||||||
e.view()
|
e.view()
|
||||||
.root()
|
.root()
|
||||||
.pseudoClassStateChanged(
|
.pseudoClassStateChanged(
|
||||||
@@ -454,10 +560,14 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
e.view().root().getStyleClass().remove("selected");
|
e.view().root().getStyleClass().remove("selected");
|
||||||
if (selected) {
|
if (selected) {
|
||||||
e.view().root().getStyleClass().add("selected");
|
e.view().root().getStyleClass().add("selected");
|
||||||
if (e.view().root().getParent() == body) loaded = e.row().model();
|
if (rowsInteractive && e.view().root().getParent() == body) {
|
||||||
|
actionable.add(e.row().model());
|
||||||
|
if (Objects.equals(selectedKey.get(), e.row().key())) loaded = e.row().model();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
selectedElement.set(rowsInteractive ? loaded : null);
|
selectedElement.set(rowsInteractive ? loaded : null);
|
||||||
|
selectedElements.setAll(actionable);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setOnLayoutCommitted(Runnable handler) {
|
public void setOnLayoutCommitted(Runnable handler) {
|
||||||
@@ -774,6 +884,7 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
RuntimeException aggregate = null;
|
RuntimeException aggregate = null;
|
||||||
for (var e : retired) {
|
for (var e : retired) {
|
||||||
e.view().root().removeEventHandler(MouseEvent.MOUSE_CLICKED, e.click());
|
e.view().root().removeEventHandler(MouseEvent.MOUSE_CLICKED, e.click());
|
||||||
|
e.view().root().removeEventHandler(KeyEvent.KEY_PRESSED, e.key());
|
||||||
try {
|
try {
|
||||||
e.view().dispose().run();
|
e.view().dispose().run();
|
||||||
} catch (RuntimeException failure) {
|
} catch (RuntimeException failure) {
|
||||||
@@ -806,6 +917,9 @@ public final class TableResults<K, T> implements AutoCloseable {
|
|||||||
body.setOnMouseClicked(null);
|
body.setOnMouseClicked(null);
|
||||||
selectedKey.set(null);
|
selectedKey.set(null);
|
||||||
selectedElement.set(null);
|
selectedElement.set(null);
|
||||||
|
selectedKeys.clear();
|
||||||
|
selectedElements.clear();
|
||||||
|
anchor = null;
|
||||||
captured = GroupProjection.capture(List.of(), List.of());
|
captured = GroupProjection.capture(List.of(), List.of());
|
||||||
groupTree = List.of();
|
groupTree = List.of();
|
||||||
disclosure.clear();
|
disclosure.clear();
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
.result-row:selected { -fx-background-color: -fx-selection-bar; }
|
||||||
|
.result-row:selected .label { -fx-text-fill: -fx-selection-bar-text; }
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import org.jsoup.Jsoup;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class HtmlDocumentTest {
|
||||||
|
@TempDir Path temporary;
|
||||||
|
|
||||||
|
@Test void stringSourceResolvesRelativeImagesWithoutFetchingItsAddress() {
|
||||||
|
var document = HtmlDocument.parse("<img src='../image.png'>", java.net.URI.create("https://example.test/path/page.html"));
|
||||||
|
assertTrue(document.hasExternalImages());
|
||||||
|
assertEquals("https://example.test/image.png", Jsoup.parse(document.externalImagesHtml()).selectFirst("img").attr("src"));
|
||||||
|
assertFalse(Jsoup.parse(document.offlineHtml()).selectFirst("img").hasAttr("src"));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> HtmlDocument.parse("<p>Text</p>", java.net.URI.create("file:///tmp/page.html")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void resolvesOnlyWebImagesAndKeepsOfflineIndexingAndOriginalFileUnchanged() throws Exception {
|
||||||
|
String source = """
|
||||||
|
<base href="https://example.test/folder/page.html"><title>Example</title>
|
||||||
|
<script src="https://example.test/script"></script><iframe src="https://example.test/frame"></iframe>
|
||||||
|
<img src="picture.png" onerror="alert(1)"><img src="//cdn.example.test/image.jpg">
|
||||||
|
<img src="file:///etc/passwd"><img src="javascript:alert(1)">
|
||||||
|
<img src="data:image/svg+xml;base64,PHN2Zz4="><img src="data:image/png;base64,YWJj">
|
||||||
|
<a href="https://example.test/link">Text</a>
|
||||||
|
""";
|
||||||
|
var file = Files.writeString(temporary.resolve("page.html"), source);
|
||||||
|
var preview = HtmlDocument.read(file);
|
||||||
|
assertTrue(preview.hasExternalImages());
|
||||||
|
var online = Jsoup.parse(preview.externalImagesHtml());
|
||||||
|
assertEquals(java.util.List.of("https://example.test/folder/picture.png", "https://cdn.example.test/image.jpg",
|
||||||
|
"data:image/svg+xml;base64,PHN2Zz4=", "data:image/png;base64,YWJj"), online.select("img[src]").eachAttr("src"));
|
||||||
|
assertTrue(online.select("script,iframe,base,[onerror],a[href]").isEmpty());
|
||||||
|
assertEquals(java.util.List.of("data:image/svg+xml;base64,PHN2Zz4=", "data:image/png;base64,YWJj"),
|
||||||
|
Jsoup.parse(preview.offlineHtml()).select("img[src]").eachAttr("src"));
|
||||||
|
assertEquals(source, Files.readString(file));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void relativeImagesWithoutWebBaseRemainUnavailable() throws Exception {
|
||||||
|
var file = Files.writeString(temporary.resolve("local.html"), "<img src='local.png'><img src='file:///tmp/local.png'>");
|
||||||
|
var preview = HtmlDocument.read(file);
|
||||||
|
assertFalse(preview.hasExternalImages());
|
||||||
|
assertTrue(Jsoup.parse(preview.externalImagesHtml()).select("img[src]").isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void keepsSavedLayoutAndEmbeddedBackgroundsWhileGatingRemoteImages() throws Exception {
|
||||||
|
String svg = "data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E";
|
||||||
|
var file = Files.writeString(temporary.resolve("saved.html"), """
|
||||||
|
<html class="saved"><head><base href="https://example.test/path/">
|
||||||
|
<style>@import 'https://example.test/track.css';
|
||||||
|
.hero { width: 120px; background-image:url("%s"); }
|
||||||
|
@media (min-width: 200px) { .remote {background: url('../background.png')} }
|
||||||
|
@font-face {font-family: saved;src:url('https://example.test/font.woff2')}
|
||||||
|
</style></head><body class="page" style="margin:0">
|
||||||
|
<div class="hero" style="height:80px;background-image:url('%s')">Article</div>
|
||||||
|
<svg onload="alert(1)"></svg><script>alert(1)</script>
|
||||||
|
</body></html>
|
||||||
|
""".formatted(svg, svg.replace("'", "%27")));
|
||||||
|
var preview = HtmlDocument.read(file);
|
||||||
|
assertTrue(preview.hasExternalImages(), "CSS backgrounds must enable the per-tab media button");
|
||||||
|
var offline = Jsoup.parse(preview.offlineHtml());
|
||||||
|
var online = Jsoup.parse(preview.externalImagesHtml());
|
||||||
|
assertEquals("saved", offline.selectFirst("html").className());
|
||||||
|
assertEquals("page", offline.body().className());
|
||||||
|
assertTrue(offline.selectFirst(".hero").attr("style").contains("data:image/svg+xml"));
|
||||||
|
assertTrue(offline.selectFirst("style").data().contains("data:image/svg+xml"));
|
||||||
|
assertFalse(offline.selectFirst("style").data().contains("background.png"));
|
||||||
|
assertTrue(online.selectFirst("style").data().contains("https://example.test/background.png"));
|
||||||
|
assertFalse(online.selectFirst("style").data().contains("track.css"));
|
||||||
|
assertFalse(online.selectFirst("style").data().contains("https://example.test/font.woff2"));
|
||||||
|
assertTrue(offline.select("script,iframe,svg,link,base,[onload]").isEmpty());
|
||||||
|
assertTrue(offline.selectFirst("meta[http-equiv]").attr("content").contains("img-src data:;"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void preservesCustomWrappersAndCssThatTheParserDoesNotUnderstand() throws Exception {
|
||||||
|
String css = ".before {color: blue} @supports selector(:focus-visible) {.after {color:red}}";
|
||||||
|
var file = Files.writeString(temporary.resolve("modern.html"), "<html data-theme='light'><style>" + css
|
||||||
|
+ "</style><body><a-menu data-open='false' aria-hidden='true' class='menu'>Text</a-menu></body></html>");
|
||||||
|
var document = Jsoup.parse(HtmlDocument.read(file).offlineHtml());
|
||||||
|
assertEquals(css, document.selectFirst("style").data());
|
||||||
|
assertEquals("false", document.selectFirst("a-menu").attr("data-open"));
|
||||||
|
assertEquals("true", document.selectFirst("a-menu").attr("aria-hidden"));
|
||||||
|
assertEquals("light", document.selectFirst("html").attr("data-theme"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void aBrokenEmbeddedWebpDoesNotPreventOpeningTheDocument() throws Exception {
|
||||||
|
var file = Files.writeString(temporary.resolve("broken.html"), "<img src='data:image/webp;base64,abcde'><p>Readable text</p>");
|
||||||
|
assertTrue(HtmlDocument.read(file).offlineHtml().contains("Readable text"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
package de.neitzel.fx.control;
|
||||||
|
|
||||||
|
import com.sun.net.httpserver.HttpServer;
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.concurrent.atomic.*;
|
||||||
|
import java.util.function.BooleanSupplier;
|
||||||
|
import javax.imageio.ImageIO;
|
||||||
|
import javafx.application.Platform;
|
||||||
|
import javafx.concurrent.Worker;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.layout.VBox;
|
||||||
|
import javafx.scene.web.WebView;
|
||||||
|
import javafx.stage.Stage;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class HtmlViewerTest {
|
||||||
|
@TempDir Path temporary;
|
||||||
|
@BeforeAll static void toolkit() throws Exception {
|
||||||
|
var started = new CountDownLatch(1);
|
||||||
|
try { Platform.startup(started::countDown); }
|
||||||
|
catch (IllegalStateException running) { started.countDown(); }
|
||||||
|
assertTrue(started.await(10, TimeUnit.SECONDS));
|
||||||
|
fx(() -> Platform.setImplicitExit(false));
|
||||||
|
}
|
||||||
|
private static void fx(Runnable action) throws Exception {
|
||||||
|
var task = new FutureTask<Void>(action, null);
|
||||||
|
Platform.runLater(task); task.get(10, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
private static void await(BooleanSupplier condition) throws Exception {
|
||||||
|
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15);
|
||||||
|
var matched = new AtomicBoolean();
|
||||||
|
while (System.nanoTime() < deadline) {
|
||||||
|
fx(() -> matched.set(condition.getAsBoolean()));
|
||||||
|
if (matched.get()) return;
|
||||||
|
Thread.sleep(20);
|
||||||
|
}
|
||||||
|
fail("Timed out waiting for HTML load");
|
||||||
|
}
|
||||||
|
private static WebView browser(HtmlViewer pane) { return (WebView) pane.lookup("WebView"); }
|
||||||
|
private static boolean loaded(HtmlViewer pane) {
|
||||||
|
return browser(pane).getEngine().getLoadWorker().getState() == Worker.State.SUCCEEDED;
|
||||||
|
}
|
||||||
|
private static String imageSource(HtmlViewer pane) {
|
||||||
|
return browser(pane).getEngine().getDocument().getElementsByTagName("img").item(0)
|
||||||
|
.getAttributes().getNamedItem("src") == null ? "" : browser(pane).getEngine().getDocument()
|
||||||
|
.getElementsByTagName("img").item(0).getAttributes().getNamedItem("src").getNodeValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static HtmlViewer viewer(HtmlDocument document) {
|
||||||
|
var viewer = new HtmlViewer(); viewer.display(document); return viewer;
|
||||||
|
}
|
||||||
|
private static javafx.scene.control.Button media(HtmlViewer viewer) {
|
||||||
|
return (javafx.scene.control.Button) viewer.lookup(".html-viewer-media-load");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void ordinaryFxmlConstructsAnIdleLocalizableControl() throws Exception {
|
||||||
|
fx(() -> {
|
||||||
|
var loader = new javafx.fxml.FXMLLoader();
|
||||||
|
String fxml = """
|
||||||
|
<?import de.neitzel.fx.control.HtmlViewer?>
|
||||||
|
<HtmlViewer xmlns:fx="http://javafx.com/fxml/1" mediaButtonVisible="false"
|
||||||
|
mediaLoadText="Bilder laden" mediaReloadText="Erneut laden"
|
||||||
|
mediaTooltipText="Nur diese Ansicht" noExternalMediaText="Keine externen Bilder"/>
|
||||||
|
""";
|
||||||
|
try {
|
||||||
|
HtmlViewer viewer = loader.load(new java.io.ByteArrayInputStream(fxml.getBytes(StandardCharsets.UTF_8)));
|
||||||
|
try {
|
||||||
|
assertFalse(viewer.isLoading()); assertNull(viewer.getError());
|
||||||
|
assertFalse(viewer.isExternalImagesAvailable()); assertFalse(viewer.isExternalImagesAllowed());
|
||||||
|
assertFalse(viewer.isMediaButtonVisible()); assertFalse(viewer.getTop().isManaged());
|
||||||
|
assertEquals("Bilder laden", media(viewer).getText());
|
||||||
|
assertEquals("Keine externen Bilder", media(viewer).getTooltip().getText());
|
||||||
|
viewer.setMediaLoadText("Load images");
|
||||||
|
assertEquals("Load images", media(viewer).getText());
|
||||||
|
} finally { viewer.close(); }
|
||||||
|
} catch (java.io.IOException failure) { throw new RuntimeException(failure); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void asynchronousFailureReplacementAndCloseDoNotPublishStaleContent() throws Exception {
|
||||||
|
var ref = new AtomicReference<HtmlViewer>();
|
||||||
|
fx(() -> { ref.set(new HtmlViewer()); ref.get().load(temporary.resolve("missing.html")); });
|
||||||
|
try {
|
||||||
|
await(() -> !ref.get().isLoading() && ref.get().getError() != null);
|
||||||
|
fx(() -> {
|
||||||
|
assertInstanceOf(java.io.IOException.class, ref.get().getError());
|
||||||
|
ref.get().loadHtml("<p>Stale preparation</p>");
|
||||||
|
assertTrue(ref.get().isLoading());
|
||||||
|
ref.get().display(HtmlDocument.parse("<p>Current document</p>"));
|
||||||
|
});
|
||||||
|
await(() -> !ref.get().isLoading() && loaded(ref.get()));
|
||||||
|
fx(() -> {
|
||||||
|
assertNull(ref.get().getError());
|
||||||
|
assertEquals("Current document", browser(ref.get()).getEngine().getDocument().getElementsByTagName("p").item(0).getTextContent());
|
||||||
|
ref.get().clear();
|
||||||
|
assertFalse(ref.get().isExternalImagesAvailable()); assertFalse(ref.get().isExternalImagesAllowed());
|
||||||
|
ref.get().loadHtml("<p>Pending on close</p>");
|
||||||
|
ref.get().close();
|
||||||
|
assertFalse(ref.get().isLoading());
|
||||||
|
assertThrows(IllegalStateException.class, () -> ref.get().loadHtml("<p>Closed</p>"));
|
||||||
|
});
|
||||||
|
for (int i = 0; i < 4; i++) fx(() -> {});
|
||||||
|
fx(() -> {
|
||||||
|
assertFalse(ref.get().isLoading()); assertNull(ref.get().getError());
|
||||||
|
assertFalse(ref.get().isExternalImagesAvailable());
|
||||||
|
});
|
||||||
|
} finally { fx(() -> ref.get().close()); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void displaysEmbeddedSvgAndStylesheetAndInlineBackgroundImages() throws Exception {
|
||||||
|
String red = svg("red"), blue = svg("blue"), green = svg("lime");
|
||||||
|
var file = Files.writeString(temporary.resolve("embedded.html"), """
|
||||||
|
<style>body{margin:0;background:white}img,.tile{width:40px;height:40px;display:block}
|
||||||
|
.tile{background-image:url('%s')}</style>
|
||||||
|
<img src="%s"><div class="tile"></div>
|
||||||
|
<div style="width:40px;height:40px;background-image:url('%s')"></div>
|
||||||
|
<img src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4TBUAAAAvJ8AJAAcQ/Y/+B4CE8P+8GtH/1AAA">
|
||||||
|
<div style="width:40px;height:40px;background-image:url('data:image/webp;base64,UklGRiIAAABXRUJQVlA4TBUAAAAvJ8AJAAcQ/Y/+B4CE8P+8GtH/1AAA')"></div>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><rect width="40" height="40" fill="blue"/></svg>
|
||||||
|
""".formatted(blue, red, green));
|
||||||
|
var preview = HtmlDocument.read(file);
|
||||||
|
assertFalse(preview.hasExternalImages());
|
||||||
|
var pane = new AtomicReference<HtmlViewer>(); var stage = new AtomicReference<Stage>();
|
||||||
|
try {
|
||||||
|
fx(() -> {
|
||||||
|
pane.set(viewer(preview));
|
||||||
|
var window = new Stage(); stage.set(window);
|
||||||
|
window.setScene(new Scene(pane.get(), 240, 300)); window.show();
|
||||||
|
assertTrue(media(pane.get()).isDisabled());
|
||||||
|
});
|
||||||
|
await(() -> loaded(pane.get()));
|
||||||
|
// Snapshot pixels exercise the actual WebKit SVG decoder and CSS layout, with JavaScript disabled.
|
||||||
|
await(() -> {
|
||||||
|
var pixels = browser(pane.get()).snapshot(null, null).getPixelReader();
|
||||||
|
return pixels.getColor(20, 20).getRed() > .9 && pixels.getColor(20, 20).getGreen() < .1
|
||||||
|
&& pixels.getColor(20, 60).getBlue() > .9 && pixels.getColor(20, 60).getRed() < .1
|
||||||
|
&& pixels.getColor(20, 100).getGreen() > .9 && pixels.getColor(20, 100).getRed() < .1
|
||||||
|
&& pixels.getColor(20, 140).getRed() > .9 && pixels.getColor(20, 140).getGreen() < .1
|
||||||
|
&& pixels.getColor(20, 180).getRed() > .9 && pixels.getColor(20, 180).getGreen() < .1
|
||||||
|
&& pixels.getColor(20, 220).getBlue() > .9 && pixels.getColor(20, 220).getRed() < .1;
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fx(() -> { if (pane.get() != null) pane.get().close(); if (stage.get() != null) stage.get().hide(); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String svg(String color) {
|
||||||
|
return "data:image/svg+xml," + URLEncoder.encode("<svg xmlns='http://www.w3.org/2000/svg' width='40' height='40'>"
|
||||||
|
+ "<rect width='40' height='40' fill='" + color + "'/></svg>", StandardCharsets.UTF_8).replace("+", "%20");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void networkImagesRequireExplicitPermissionPerViewAndReopeningStartsOffline() throws Exception {
|
||||||
|
var images = new AtomicInteger(); var forbidden = new AtomicInteger();
|
||||||
|
var bytes = new ByteArrayOutputStream();
|
||||||
|
ImageIO.write(new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB), "png", bytes);
|
||||||
|
var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||||
|
server.createContext("/image.png", exchange -> {
|
||||||
|
images.incrementAndGet();
|
||||||
|
exchange.getResponseHeaders().set("Content-Type", "image/png");
|
||||||
|
exchange.getResponseHeaders().set("Cache-Control", "no-store");
|
||||||
|
exchange.sendResponseHeaders(200, bytes.size());
|
||||||
|
try (var output = exchange.getResponseBody()) { output.write(bytes.toByteArray()); }
|
||||||
|
});
|
||||||
|
server.createContext("/forbidden", exchange -> {
|
||||||
|
forbidden.incrementAndGet(); exchange.sendResponseHeaders(204, -1); exchange.close();
|
||||||
|
});
|
||||||
|
server.createContext("/background.png", exchange -> {
|
||||||
|
images.incrementAndGet();
|
||||||
|
exchange.getResponseHeaders().set("Content-Type", "image/png");
|
||||||
|
exchange.getResponseHeaders().set("Cache-Control", "no-store");
|
||||||
|
exchange.sendResponseHeaders(200, bytes.size());
|
||||||
|
try (var output = exchange.getResponseBody()) { output.write(bytes.toByteArray()); }
|
||||||
|
});
|
||||||
|
server.start();
|
||||||
|
String base = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||||
|
var first = new AtomicReference<HtmlViewer>(); var second = new AtomicReference<HtmlViewer>();
|
||||||
|
var reopened = new AtomicReference<HtmlViewer>(); var stage = new AtomicReference<Stage>();
|
||||||
|
try {
|
||||||
|
var file = Files.writeString(temporary.resolve("page.html"), "<img src='" + base + "/image.png'>"
|
||||||
|
+ "<script src='" + base + "/forbidden'></script><iframe src='" + base + "/forbidden'></iframe>"
|
||||||
|
+ "<style>@import '" + base + "/forbidden'; @font-face{font-family:evil;src:url('" + base + "/forbidden')}"
|
||||||
|
+ ".remote{width:40px;height:40px;background-image:url('" + base + "/background.png')}</style>"
|
||||||
|
+ "<div class='remote'>Background</div><img src=\"data:image/svg+xml,"
|
||||||
|
+ URLEncoder.encode("<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'>"
|
||||||
|
+ "<script href='" + base + "/forbidden'/><image href='" + base + "/forbidden'/></svg>",
|
||||||
|
StandardCharsets.UTF_8).replace("+", "%20") + "\">");
|
||||||
|
var preview = HtmlDocument.read(file);
|
||||||
|
fx(() -> {
|
||||||
|
first.set(viewer(preview)); second.set(viewer(preview));
|
||||||
|
var window = new Stage(); stage.set(window);
|
||||||
|
window.setScene(new Scene(new VBox(first.get(), second.get()), 600, 600)); window.show();
|
||||||
|
});
|
||||||
|
await(() -> loaded(first.get()) && loaded(second.get()));
|
||||||
|
assertEquals(0, images.get(), "Opening HTML must never fetch remote images");
|
||||||
|
fx(() -> {
|
||||||
|
assertEquals("", imageSource(first.get())); assertEquals("", imageSource(second.get()));
|
||||||
|
media(first.get()).fire();
|
||||||
|
});
|
||||||
|
await(() -> images.get() == 2 && loaded(first.get()));
|
||||||
|
fx(() -> {
|
||||||
|
assertEquals(base + "/image.png", imageSource(first.get()));
|
||||||
|
assertEquals("", imageSource(second.get()), "Permission must not spread to another tab");
|
||||||
|
assertFalse(browser(first.get()).getEngine().isJavaScriptEnabled());
|
||||||
|
assertFalse(browser(second.get()).getEngine().isJavaScriptEnabled());
|
||||||
|
assertTrue(first.get().isExternalImagesAllowed());
|
||||||
|
first.get().display(HtmlDocument.parse("<p>Replacement</p>"));
|
||||||
|
assertFalse(first.get().isExternalImagesAllowed(), "Replacing the document revokes permission");
|
||||||
|
assertFalse(first.get().isExternalImagesAvailable());
|
||||||
|
first.get().close();
|
||||||
|
reopened.set(viewer(preview));
|
||||||
|
((VBox) stage.get().getScene().getRoot()).getChildren().set(0, reopened.get());
|
||||||
|
});
|
||||||
|
await(() -> loaded(reopened.get()));
|
||||||
|
fx(() -> assertEquals("", imageSource(reopened.get())));
|
||||||
|
assertEquals(2, images.get(), "Reopening must require a fresh grant");
|
||||||
|
assertEquals(0, forbidden.get(), "Scripts and embedded pages must never load");
|
||||||
|
} finally {
|
||||||
|
fx(() -> {
|
||||||
|
if (first.get() != null) first.get().close();
|
||||||
|
if (second.get() != null) second.get().close();
|
||||||
|
if (reopened.get() != null) reopened.get().close();
|
||||||
|
if (stage.get() != null) stage.get().hide();
|
||||||
|
});
|
||||||
|
server.stop(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package de.neitzel.fx.view;
|
||||||
|
|
||||||
|
import de.neitzel.grid.GridRow;
|
||||||
|
import javafx.scene.Scene;
|
||||||
|
import javafx.scene.control.Label;
|
||||||
|
import javafx.scene.input.*;
|
||||||
|
import javafx.scene.layout.HBox;
|
||||||
|
import org.junit.jupiter.api.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class RowSelectionTest {
|
||||||
|
@BeforeAll static void toolkit() throws Exception { DataGridTest.start(); }
|
||||||
|
|
||||||
|
private static MouseEvent click(boolean shortcut, boolean shift) {
|
||||||
|
boolean mac = System.getProperty("os.name").startsWith("Mac");
|
||||||
|
return new MouseEvent(MouseEvent.MOUSE_CLICKED, 1, 1, 1, 1, MouseButton.PRIMARY, 1,
|
||||||
|
shift, shortcut && !mac, false, shortcut && mac,
|
||||||
|
false, false, false, false, false, true, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void mouseModifiersModesAndVisibleHighlight() throws Exception {
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
var roots = new ArrayList<HBox>();
|
||||||
|
var table = new Table();
|
||||||
|
var renderer = table.<Integer, String>openResults(TableResultsTest.columns(), s -> {
|
||||||
|
var row = TableResultsTest.row(s, new AtomicInteger());
|
||||||
|
roots.add(row.root());
|
||||||
|
return row;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
renderer.show(List.of(new GridRow<>(1, "A"), new GridRow<>(2, "B"),
|
||||||
|
new GridRow<>(3, "C"), new GridRow<>(4, "D")));
|
||||||
|
assertEquals(RowSelectionMode.SINGLE, renderer.getSelectionMode());
|
||||||
|
roots.get(0).fireEvent(click(false, false));
|
||||||
|
roots.get(2).fireEvent(click(true, false));
|
||||||
|
assertEquals(List.of(3), renderer.selectedKeysProperty());
|
||||||
|
renderer.setSelectionMode(RowSelectionMode.MULTIPLE);
|
||||||
|
roots.get(0).fireEvent(click(false, false));
|
||||||
|
roots.get(2).fireEvent(click(true, false));
|
||||||
|
assertEquals(List.of(1, 3), renderer.selectedKeysProperty());
|
||||||
|
roots.get(3).fireEvent(click(false, true));
|
||||||
|
assertEquals(List.of(3, 4), renderer.selectedKeysProperty());
|
||||||
|
roots.get(1).fireEvent(click(true, true));
|
||||||
|
assertEquals(Set.of(2, 3, 4), new HashSet<>(renderer.selectedKeysProperty()));
|
||||||
|
roots.get(2).fireEvent(click(true, false));
|
||||||
|
assertEquals(List.of(4, 2), renderer.selectedKeysProperty());
|
||||||
|
assertEquals("B", renderer.selectedElementProperty().get());
|
||||||
|
assertEquals(List.of("B", "D"), renderer.selectedElementsProperty());
|
||||||
|
assertThrows(UnsupportedOperationException.class,
|
||||||
|
() -> renderer.selectedKeysProperty().clear());
|
||||||
|
new Scene(table);
|
||||||
|
table.applyCss();
|
||||||
|
assertNotNull(roots.get(1).getBackground(), "Default selection is visibly styled");
|
||||||
|
assertTrue(roots.get(1).getPseudoClassStates().stream()
|
||||||
|
.anyMatch(p -> p.getPseudoClassName().equals("selected")));
|
||||||
|
renderer.setSelectionMode(RowSelectionMode.SINGLE);
|
||||||
|
assertEquals(List.of(2), renderer.selectedKeysProperty());
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> renderer.selectKeys(List.of(1, 2)));
|
||||||
|
renderer.setSelectionMode(RowSelectionMode.NONE);
|
||||||
|
roots.get(0).fireEvent(click(false, false));
|
||||||
|
renderer.select(1);
|
||||||
|
assertTrue(renderer.selectedKeysProperty().isEmpty());
|
||||||
|
assertNull(renderer.selectedElementProperty().get());
|
||||||
|
} finally { renderer.close(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void keyboardAndChildEditorAndRetainedIdentities() throws Exception {
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
var roots = new ArrayList<HBox>();
|
||||||
|
var renderer = new Table().<Integer, String>openResults(TableResultsTest.columns(), s -> {
|
||||||
|
var row = TableResultsTest.row(s, new AtomicInteger());
|
||||||
|
roots.add(row.root());
|
||||||
|
return row;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
renderer.setSelectionMode(RowSelectionMode.MULTIPLE);
|
||||||
|
renderer.show(List.of(new GridRow<>(1, "A"), new GridRow<>(2, "B")));
|
||||||
|
renderer.select(1);
|
||||||
|
roots.getFirst().fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.DOWN,
|
||||||
|
true, false, false, false));
|
||||||
|
assertEquals(List.of(1, 2), renderer.selectedKeysProperty());
|
||||||
|
((Label) roots.getFirst().getChildren().getFirst()).fireEvent(
|
||||||
|
new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.ESCAPE,
|
||||||
|
false, false, false, false));
|
||||||
|
assertEquals(List.of(1, 2), renderer.selectedKeysProperty(), "Child keys are left alone");
|
||||||
|
renderer.setRowsInteractive(false);
|
||||||
|
assertTrue(renderer.selectedElementsProperty().isEmpty());
|
||||||
|
assertEquals(List.of(1, 2), renderer.selectedKeysProperty());
|
||||||
|
renderer.show(List.of(new GridRow<>(2, "new B")));
|
||||||
|
renderer.setRowsInteractive(true);
|
||||||
|
assertEquals(List.of("new B"), renderer.selectedElementsProperty());
|
||||||
|
renderer.deselect(1);
|
||||||
|
assertEquals(List.of(2), renderer.selectedKeysProperty());
|
||||||
|
roots.getLast().fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.ESCAPE,
|
||||||
|
false, false, false, false));
|
||||||
|
assertTrue(renderer.selectedKeysProperty().isEmpty());
|
||||||
|
} finally { renderer.close(); }
|
||||||
|
assertTrue(renderer.selectedElementsProperty().isEmpty());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void fxmlSelectionModeAndCoordinatorSelection() throws Exception {
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
try {
|
||||||
|
DataGrid<?, ?> declarative = new javafx.fxml.FXMLLoader().load(
|
||||||
|
new java.io.ByteArrayInputStream(("<?import de.neitzel.fx.view.DataGrid?>"
|
||||||
|
+ "<DataGrid selectionMode=\"NONE\"/>").getBytes(java.nio.charset.StandardCharsets.UTF_8)));
|
||||||
|
assertEquals(RowSelectionMode.NONE, declarative.getSelectionMode());
|
||||||
|
declarative.close();
|
||||||
|
} catch (java.io.IOException e) { throw new java.io.UncheckedIOException(e); }
|
||||||
|
});
|
||||||
|
var reference = new java.util.concurrent.atomic.AtomicReference<DataGrid<Long, DataGridTest.Item>>();
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
var grid = DataGridTest.grid(List.of(new DataGridTest.Item(1, "A"),
|
||||||
|
new DataGridTest.Item(2, "B")), new AtomicInteger());
|
||||||
|
reference.set(grid);
|
||||||
|
grid.setSelectionMode(RowSelectionMode.MULTIPLE);
|
||||||
|
grid.refresh();
|
||||||
|
});
|
||||||
|
DataGridTest.drain();
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
var grid = reference.get();
|
||||||
|
try {
|
||||||
|
grid.selectKeys(List.of(1L, 2L));
|
||||||
|
assertEquals(2, grid.selectedElementsProperty().size());
|
||||||
|
grid.confirmedDeleted(1L);
|
||||||
|
assertEquals(List.of(2L), grid.selectedKeysProperty());
|
||||||
|
grid.setSelectionMode(RowSelectionMode.NONE);
|
||||||
|
assertTrue(grid.selectedKeysProperty().isEmpty());
|
||||||
|
} finally { grid.close(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void rangesFollowVisibleGroupOrderAndCollapsedRowsAreNotActionable() throws Exception {
|
||||||
|
DataGridTest.fx(() -> {
|
||||||
|
var roots = new ArrayList<HBox>();
|
||||||
|
var renderer = new Table().<Integer, String>openResults(TableResultsTest.columns(), s -> {
|
||||||
|
var row = TableResultsTest.row(s, new AtomicInteger());
|
||||||
|
roots.add(row.root());
|
||||||
|
return row;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
renderer.setSelectionMode(RowSelectionMode.MULTIPLE);
|
||||||
|
renderer.configureGrouping(List.of(de.neitzel.grid.GroupColumn.<String>text(
|
||||||
|
"name", s -> s.substring(0, 1))), true, List.of("name"), false, 100);
|
||||||
|
renderer.show(List.of(new GridRow<>(1, "A1"), new GridRow<>(2, "B1"), new GridRow<>(3, "A2")));
|
||||||
|
roots.get(0).fireEvent(click(false, false));
|
||||||
|
roots.get(1).fireEvent(click(false, true));
|
||||||
|
assertEquals(List.of(1, 3, 2), renderer.selectedKeysProperty());
|
||||||
|
renderer.setExpanded(new de.neitzel.grid.GroupPath(List.of(
|
||||||
|
new de.neitzel.grid.GroupPath.Segment("name", new de.neitzel.grid.FilterValue.Text("A")))), false);
|
||||||
|
assertEquals(List.of("B1"), renderer.selectedElementsProperty());
|
||||||
|
assertEquals(3, renderer.selectedKeysProperty().size());
|
||||||
|
} finally { renderer.close(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0.2-SNAPSHOT</version>
|
<version>1.0.2</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>gson</artifactId>
|
<artifactId>gson</artifactId>
|
||||||
|
|||||||
+2
-2
@@ -8,13 +8,13 @@ The worked example is the person desk in `fx-example`, package `de.neitzel.fx.ex
|
|||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
Depend on the module. It brings Reflections 0.10.2 and `jakarta.inject-api` 2.0.1 (plus shared logging dependencies). The parent artifact is `de.neitzel.lib:neitzellib:1.0`. Java 25.
|
Depend on the module. It brings Reflections 0.10.2 and `jakarta.inject-api` 2.0.1 (plus shared logging dependencies). The parent artifact is `de.neitzel.lib:neitzellib:1.0.2`. Java 25.
|
||||||
|
|
||||||
```xml
|
```xml
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>injection</artifactId>
|
<artifactId>injection</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0.2</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0.2-SNAPSHOT</version>
|
<version>1.0.2</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>injection</artifactId>
|
<artifactId>injection</artifactId>
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0.2-SNAPSHOT</version>
|
<version>1.0.2</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>log4j</artifactId>
|
<artifactId>log4j</artifactId>
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0.2-SNAPSHOT</version>
|
<version>1.0.2</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>net</artifactId>
|
<artifactId>net</artifactId>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0.2-SNAPSHOT</version>
|
<version>1.0.2</version>
|
||||||
|
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>de.neitzel.lib</groupId>
|
<groupId>de.neitzel.lib</groupId>
|
||||||
<artifactId>neitzellib</artifactId>
|
<artifactId>neitzellib</artifactId>
|
||||||
<version>1.0.2-SNAPSHOT</version>
|
<version>1.0.2</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>quarkus</artifactId>
|
<artifactId>quarkus</artifactId>
|
||||||
|
|||||||
Reference in New Issue
Block a user