Add compatible DataGrid, filter editors, themes and JDBC example
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package de.neitzel.fx.example.grid;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.h2.jdbcx.JdbcConnectionPool;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
class DemoResourcesTest {
|
||||
@Test
|
||||
void independentCleanupContinuesAndPreservesFailures() {
|
||||
var attempts = new ArrayList<String>();
|
||||
var first = new java.sql.SQLException("anchor close");
|
||||
var second = new IllegalStateException("pool close");
|
||||
var failure =
|
||||
assertThrows(
|
||||
IllegalStateException.class,
|
||||
() ->
|
||||
DemoResources.closeAll(
|
||||
() -> {
|
||||
attempts.add("anchor");
|
||||
throw first;
|
||||
},
|
||||
() -> {
|
||||
attempts.add("pool");
|
||||
throw second;
|
||||
},
|
||||
() -> attempts.add("executor")));
|
||||
assertEquals(List.of("anchor", "pool", "executor"), attempts);
|
||||
assertSame(first, failure.getCause());
|
||||
assertArrayEquals(new Throwable[] {second}, failure.getSuppressed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInitialBorrowStillReleasesOwnedExecutor() {
|
||||
var pool = JdbcConnectionPool.create("jdbc:h2:mem:closed_" + UUID.randomUUID(), "sa", "");
|
||||
var workers = Executors.newSingleThreadExecutor();
|
||||
pool.dispose();
|
||||
try {
|
||||
assertThrows(Exception.class, () -> new ProductCatalog(10, pool, workers));
|
||||
assertTrue(workers.isShutdown());
|
||||
} finally {
|
||||
workers.shutdown();
|
||||
pool.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,585 @@
|
||||
package de.neitzel.fx.example.grid;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import de.neitzel.grid.*;
|
||||
import de.neitzel.grid.jdbc.*;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.math.*;
|
||||
import java.nio.file.*;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
class JdbcProductTest {
|
||||
static ProductCatalog catalog;
|
||||
|
||||
@BeforeAll
|
||||
static void start() throws Exception {
|
||||
catalog = new ProductCatalog(10000);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stop() {
|
||||
catalog.close();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void reset() throws Exception {
|
||||
catalog.reset();
|
||||
}
|
||||
|
||||
static PageResult<Long, Product> result(GridSource<Long, Product> source, GridQuery q)
|
||||
throws Exception {
|
||||
return source.query(q, new QueryOptions(1000, true))
|
||||
.result()
|
||||
.toCompletableFuture()
|
||||
.get(20, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
static GridQuery query(List<FilterCondition> filters, List<SortKey> sort, PageRequest page) {
|
||||
return new GridQuery(filters, sort, page);
|
||||
}
|
||||
|
||||
void parity(List<FilterCondition> filters, List<SortKey> sort, PageRequest page)
|
||||
throws Exception {
|
||||
var q = query(filters, sort, page);
|
||||
assertEquals(result(catalog.memory, q), result(catalog.jdbc, q), q.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyOperatorAndUnicodeExactChecklistAndOrderingAgree() throws Exception {
|
||||
for (var op : TextFilter.Operator.values())
|
||||
for (boolean sensitive : List.of(false, true))
|
||||
for (String text :
|
||||
List.of(
|
||||
"Alpha",
|
||||
"a",
|
||||
"%",
|
||||
"_",
|
||||
"!",
|
||||
"İ",
|
||||
"ß",
|
||||
"ss",
|
||||
"😀",
|
||||
"é",
|
||||
"e\u0301",
|
||||
"' OR 1=1 --"))
|
||||
parity(
|
||||
List.of(new TextFilter("name", op, text, sensitive)),
|
||||
List.of(new SortKey("name", SortKey.Direction.ASCENDING)),
|
||||
new PageRequest.All());
|
||||
parity(
|
||||
List.of(new TextFilter("name", TextFilter.Operator.EQUALS, "", true)),
|
||||
List.of(),
|
||||
new PageRequest.All());
|
||||
for (var op : NumericFilter.Operator.values())
|
||||
for (String col : List.of("quantity", "price"))
|
||||
parity(
|
||||
List.of(
|
||||
new NumericFilter(
|
||||
col,
|
||||
op,
|
||||
new BigDecimal("1.0"),
|
||||
op == NumericFilter.Operator.RANGE
|
||||
? new BigDecimal("20.00")
|
||||
: null)),
|
||||
List.of(),
|
||||
new PageRequest.All());
|
||||
for (String col : List.of("name", "category", "quantity", "price"))
|
||||
for (boolean missing : List.of(true, false))
|
||||
parity(
|
||||
List.of(new MissingFilter(col, missing)),
|
||||
List.of(),
|
||||
new PageRequest.Paged(0, 50));
|
||||
for (boolean missing : List.of(true, false)) {
|
||||
parity(
|
||||
List.of(
|
||||
new ValueFilter(
|
||||
"name",
|
||||
Set.of(
|
||||
new FilterValue.Text("Alpha"),
|
||||
new FilterValue.Text("a%b")),
|
||||
missing)),
|
||||
List.of(),
|
||||
new PageRequest.All());
|
||||
parity(
|
||||
List.of(new ValueFilter("name", Set.of(), missing)),
|
||||
List.of(),
|
||||
new PageRequest.All());
|
||||
parity(
|
||||
List.of(
|
||||
new ValueFilter(
|
||||
"quantity", Set.of(new FilterValue.IntegerValue(1)), missing)),
|
||||
List.of(),
|
||||
new PageRequest.All());
|
||||
parity(
|
||||
List.of(
|
||||
new ValueFilter(
|
||||
"price",
|
||||
Set.of(new FilterValue.Decimal(new BigDecimal("1.0"))),
|
||||
missing)),
|
||||
List.of(),
|
||||
new PageRequest.All());
|
||||
}
|
||||
for (String col : List.of("name", "category", "quantity", "price"))
|
||||
for (var dir : SortKey.Direction.values())
|
||||
parity(List.of(), List.of(new SortKey(col, dir)), new PageRequest.All());
|
||||
parity(
|
||||
List.of(
|
||||
new TextFilter("name", TextFilter.Operator.CONTAINS, "product", false),
|
||||
new NumericFilter(
|
||||
"price", NumericFilter.Operator.LESS, new BigDecimal("10"), null)),
|
||||
List.of(
|
||||
new SortKey("category", SortKey.Direction.DESCENDING),
|
||||
new SortKey("price", SortKey.Direction.ASCENDING)),
|
||||
new PageRequest.Paged(3, 25));
|
||||
for (int page : List.of(0, 1, 199, 200, 999))
|
||||
parity(List.of(), List.of(), new PageRequest.Paged(page, 50));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedAndInvalidSemanticsFailBeforeBorrowing() throws Exception {
|
||||
var tracking = new Tracking(catalog.database);
|
||||
var source = source(tracking, ProductCatalog::read);
|
||||
for (FilterCondition invalid :
|
||||
List.of(
|
||||
new LocalNameLength("name"),
|
||||
new TextFilter("price", TextFilter.Operator.EQUALS, "1", true),
|
||||
new NumericFilter(
|
||||
"quantity",
|
||||
NumericFilter.Operator.EQUALS,
|
||||
new BigDecimal("1.1"),
|
||||
null),
|
||||
new NumericFilter(
|
||||
"price",
|
||||
NumericFilter.Operator.EQUALS,
|
||||
new BigDecimal("1.001"),
|
||||
null),
|
||||
new NumericFilter(
|
||||
"price",
|
||||
NumericFilter.Operator.EQUALS,
|
||||
new BigDecimal("10000000000"),
|
||||
null),
|
||||
new ValueFilter("quantity", Set.of(new FilterValue.Text("1")), false),
|
||||
new MissingFilter("not_mapped", true))) {
|
||||
assertThrows(RuntimeException.class, () -> source.validateFilter(invalid));
|
||||
assertThrows(
|
||||
ExecutionException.class,
|
||||
() ->
|
||||
result(
|
||||
source,
|
||||
query(
|
||||
List.of(invalid),
|
||||
List.of(),
|
||||
new PageRequest.Paged(0, 50))));
|
||||
}
|
||||
assertEquals(0, tracking.opened.get());
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> JdbcColumn.text("bad", "name; DROP TABLE products", "key"));
|
||||
assertEquals(
|
||||
2,
|
||||
result(
|
||||
catalog.memory,
|
||||
query(
|
||||
List.of(
|
||||
new ValueFilter(
|
||||
"name",
|
||||
Set.of(
|
||||
new FilterValue.Text("Alpha"),
|
||||
new FilterValue.Text("alpha")),
|
||||
false)),
|
||||
List.of(),
|
||||
new PageRequest.All()))
|
||||
.rows()
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void snapshotContainsCountAndRowsDespiteConcurrentWriter() throws Exception {
|
||||
var tracking = new Tracking(catalog.database);
|
||||
tracking.afterCount =
|
||||
() -> {
|
||||
try (var connection = catalog.database.getConnection()) {
|
||||
ProductCatalog.insert(
|
||||
connection,
|
||||
List.of(
|
||||
new Product(
|
||||
10001,
|
||||
"Concurrent",
|
||||
"Office",
|
||||
1L,
|
||||
new BigDecimal("1.00"))));
|
||||
}
|
||||
};
|
||||
var page =
|
||||
result(
|
||||
source(tracking, ProductCatalog::read),
|
||||
query(List.of(), List.of(), new PageRequest.All()));
|
||||
assertEquals(10000, page.total().orElseThrow());
|
||||
assertEquals(10000, page.rows().size());
|
||||
assertEquals(
|
||||
10001,
|
||||
result(catalog.jdbc, query(List.of(), List.of(), new PageRequest.All()))
|
||||
.rows()
|
||||
.size());
|
||||
tracking.assertReleased();
|
||||
assertEquals(1, tracking.opened.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void allWarningClosesResourcesAndRecountsOnApproval() throws Exception {
|
||||
var tracking = new Tracking(catalog.database);
|
||||
var source = source(tracking, ProductCatalog::read);
|
||||
var q = query(List.of(), List.of(), new PageRequest.All());
|
||||
var error =
|
||||
assertThrows(
|
||||
ExecutionException.class,
|
||||
() ->
|
||||
source.query(q, new QueryOptions(9999, false))
|
||||
.result()
|
||||
.toCompletableFuture()
|
||||
.get());
|
||||
assertInstanceOf(AllRowsConfirmationRequired.class, error.getCause());
|
||||
assertEquals(0, tracking.rowQueries.get());
|
||||
tracking.assertReleased();
|
||||
catalog.insert();
|
||||
var page =
|
||||
source.query(q, new QueryOptions(9999, true)).result().toCompletableFuture().get();
|
||||
assertEquals(10001, page.rows().size());
|
||||
tracking.assertReleased();
|
||||
assertEquals(
|
||||
10001,
|
||||
source.query(q, new QueryOptions(10001, false))
|
||||
.result()
|
||||
.toCompletableFuture()
|
||||
.get()
|
||||
.rows()
|
||||
.size());
|
||||
var small =
|
||||
query(
|
||||
List.of(
|
||||
new NumericFilter(
|
||||
"id",
|
||||
NumericFilter.Operator.LESS_OR_EQUAL,
|
||||
new BigDecimal("1000"),
|
||||
null)),
|
||||
List.of(),
|
||||
new PageRequest.All());
|
||||
assertEquals(
|
||||
1000,
|
||||
source.query(small, QueryOptions.defaults())
|
||||
.result()
|
||||
.toCompletableFuture()
|
||||
.get()
|
||||
.rows()
|
||||
.size());
|
||||
var above =
|
||||
query(
|
||||
List.of(
|
||||
new NumericFilter(
|
||||
"id",
|
||||
NumericFilter.Operator.LESS_OR_EQUAL,
|
||||
new BigDecimal("1001"),
|
||||
null)),
|
||||
List.of(),
|
||||
new PageRequest.All());
|
||||
assertInstanceOf(
|
||||
AllRowsConfirmationRequired.class,
|
||||
assertThrows(
|
||||
ExecutionException.class,
|
||||
() ->
|
||||
source.query(above, QueryOptions.defaults())
|
||||
.result()
|
||||
.toCompletableFuture()
|
||||
.get())
|
||||
.getCause());
|
||||
tracking.assertReleased();
|
||||
}
|
||||
|
||||
@Test
|
||||
void failuresCancellationAndExecutorRejectionReleaseResources() throws Exception {
|
||||
var tracking = new Tracking(catalog.database);
|
||||
var source =
|
||||
source(
|
||||
tracking,
|
||||
rs -> {
|
||||
throw new SQLException("Injected mapper failure");
|
||||
});
|
||||
assertThrows(
|
||||
ExecutionException.class,
|
||||
() -> result(source, query(List.of(), List.of(), new PageRequest.Paged(0, 50))));
|
||||
tracking.assertReleased();
|
||||
var entered = new CountDownLatch(1);
|
||||
var release = new CountDownLatch(1);
|
||||
var blocking =
|
||||
source(
|
||||
tracking,
|
||||
rs -> {
|
||||
entered.countDown();
|
||||
try {
|
||||
if (!release.await(5, TimeUnit.SECONDS))
|
||||
throw new SQLException("test timed out");
|
||||
} catch (InterruptedException e) {
|
||||
throw new SQLException(e);
|
||||
}
|
||||
return ProductCatalog.read(rs);
|
||||
});
|
||||
var execution = blocking.query(query(List.of(), List.of(), new PageRequest.Paged(0, 50)));
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
execution.cancel();
|
||||
release.countDown();
|
||||
assertThrows(
|
||||
CancellationException.class, () -> execution.result().toCompletableFuture().join());
|
||||
long limit = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
||||
while (tracking.closed.get() < tracking.opened.get() && System.nanoTime() < limit)
|
||||
Thread.sleep(10);
|
||||
tracking.assertReleased();
|
||||
assertTrue(tracking.cancels.get() > 0);
|
||||
var rejected =
|
||||
new JdbcGridSource<Long, Product>(
|
||||
tracking.proxy(),
|
||||
r -> {
|
||||
throw new RejectedExecutionException("closed executor");
|
||||
},
|
||||
JdbcDialect.h2(),
|
||||
"products",
|
||||
"id",
|
||||
ProductCatalog.jdbcColumns(),
|
||||
ProductCatalog::read,
|
||||
250,
|
||||
3);
|
||||
int before = tracking.opened.get();
|
||||
assertThrows(
|
||||
ExecutionException.class,
|
||||
() -> result(rejected, query(List.of(), List.of(), new PageRequest.Paged(0, 50))));
|
||||
assertEquals(before, tracking.opened.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void queuedCancellationAndUnqualifiedCollationAreRejected() throws Exception {
|
||||
var tracking = new Tracking(catalog.database);
|
||||
var queued = new java.util.ArrayList<Runnable>();
|
||||
var source =
|
||||
new JdbcGridSource<Long, Product>(
|
||||
tracking.proxy(),
|
||||
queued::add,
|
||||
JdbcDialect.h2(),
|
||||
"products",
|
||||
"id",
|
||||
ProductCatalog.jdbcColumns(),
|
||||
ProductCatalog::read,
|
||||
250,
|
||||
3);
|
||||
var execution = source.query(query(List.of(), List.of(), new PageRequest.Paged(0, 50)));
|
||||
execution.cancel();
|
||||
queued.removeFirst().run();
|
||||
assertEquals(0, tracking.opened.get());
|
||||
var other =
|
||||
org.h2.jdbcx.JdbcConnectionPool.create(
|
||||
"jdbc:h2:mem:collated_" + UUID.randomUUID(), "sa", "");
|
||||
try (var anchor = other.getConnection()) {
|
||||
try (var statement = anchor.createStatement()) {
|
||||
statement.execute("SET COLLATION ENGLISH");
|
||||
}
|
||||
var unqualified =
|
||||
new JdbcGridSource<Long, Product>(
|
||||
other,
|
||||
Runnable::run,
|
||||
JdbcDialect.h2(),
|
||||
"products",
|
||||
"id",
|
||||
ProductCatalog.jdbcColumns(),
|
||||
ProductCatalog::read,
|
||||
250,
|
||||
3);
|
||||
var error =
|
||||
assertThrows(
|
||||
ExecutionException.class,
|
||||
() ->
|
||||
result(
|
||||
unqualified,
|
||||
query(
|
||||
List.of(),
|
||||
List.of(),
|
||||
new PageRequest.Paged(0, 50))));
|
||||
assertTrue(error.getCause().getMessage().contains("collation"));
|
||||
} finally {
|
||||
other.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void mutationKeysAndTimings() throws Exception {
|
||||
catalog.insert();
|
||||
parity(
|
||||
List.of(
|
||||
new TextFilter(
|
||||
"name", TextFilter.Operator.EQUALS, "INSERTED 10001", false)),
|
||||
List.of(),
|
||||
new PageRequest.All());
|
||||
catalog.delete(10001);
|
||||
parity(List.of(), List.of(), new PageRequest.Paged(199, 50));
|
||||
var lines = new ArrayList<String>();
|
||||
lines.add(
|
||||
"10,000 immutable Product rows; source materialization only, excludes FX"
|
||||
+ " Components; single observed run, no performance guarantee.");
|
||||
for (var source : List.of(catalog.memory, catalog.jdbc))
|
||||
for (PageRequest page :
|
||||
List.of(
|
||||
new PageRequest.Paged(0, 50),
|
||||
new PageRequest.Paged(199, 50),
|
||||
new PageRequest.All())) {
|
||||
long before = System.nanoTime();
|
||||
var response =
|
||||
result(
|
||||
source,
|
||||
query(
|
||||
List.of(),
|
||||
List.of(new SortKey("name", SortKey.Direction.ASCENDING)),
|
||||
page));
|
||||
lines.add(
|
||||
source.filterExecutionId()
|
||||
+ " "
|
||||
+ page
|
||||
+ " rows="
|
||||
+ response.rows().size()
|
||||
+ " durationMs="
|
||||
+ (System.nanoTime() - before) / 1_000_000.0);
|
||||
}
|
||||
Path path = Path.of("target/jdbc-evidence");
|
||||
Files.createDirectories(path);
|
||||
Files.write(path.resolve("timings.txt"), lines);
|
||||
}
|
||||
|
||||
JdbcGridSource<Long, Product> source(
|
||||
Tracking tracking, JdbcGridSource.RowMapper<Long, Product> mapper) {
|
||||
return new JdbcGridSource<>(
|
||||
tracking.proxy(),
|
||||
catalog.workers,
|
||||
JdbcDialect.h2(),
|
||||
"products",
|
||||
"id",
|
||||
ProductCatalog.jdbcColumns(),
|
||||
mapper,
|
||||
250,
|
||||
3);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface SqlAction {
|
||||
void run() throws SQLException;
|
||||
}
|
||||
|
||||
static final class Tracking {
|
||||
final DataSource target;
|
||||
final AtomicInteger opened = new AtomicInteger(),
|
||||
closed = new AtomicInteger(),
|
||||
statements = new AtomicInteger(),
|
||||
results = new AtomicInteger(),
|
||||
rowQueries = new AtomicInteger(),
|
||||
cancels = new AtomicInteger();
|
||||
final List<Throwable> problems = new CopyOnWriteArrayList<>();
|
||||
SqlAction afterCount = () -> {};
|
||||
|
||||
Tracking(DataSource target) {
|
||||
this.target = target;
|
||||
}
|
||||
|
||||
DataSource proxy() {
|
||||
return wrap(
|
||||
DataSource.class,
|
||||
target,
|
||||
(object, method, args) -> {
|
||||
Object value = invoke(target, method, args);
|
||||
if (method.getName().equals("getConnection")) {
|
||||
opened.incrementAndGet();
|
||||
return connection((Connection) value);
|
||||
}
|
||||
return value;
|
||||
});
|
||||
}
|
||||
|
||||
Connection connection(Connection c) throws SQLException {
|
||||
int original = c.getTransactionIsolation();
|
||||
boolean auto = c.getAutoCommit();
|
||||
return wrap(
|
||||
Connection.class,
|
||||
c,
|
||||
(object, method, args) -> {
|
||||
if (method.getName().equals("close")) {
|
||||
try {
|
||||
assertEquals(auto, c.getAutoCommit());
|
||||
assertEquals(original, c.getTransactionIsolation());
|
||||
} catch (Throwable problem) {
|
||||
problems.add(problem);
|
||||
}
|
||||
closed.incrementAndGet();
|
||||
}
|
||||
Object value = invoke(c, method, args);
|
||||
if (value instanceof PreparedStatement s)
|
||||
return statement(s, (String) args[0]);
|
||||
return value;
|
||||
});
|
||||
}
|
||||
|
||||
PreparedStatement statement(PreparedStatement s, String sql) {
|
||||
statements.incrementAndGet();
|
||||
boolean count = sql.startsWith("SELECT COUNT");
|
||||
if (sql.startsWith("SELECT id")) rowQueries.incrementAndGet();
|
||||
return wrap(
|
||||
PreparedStatement.class,
|
||||
s,
|
||||
(object, method, args) -> {
|
||||
if (method.getName().equals("close")) statements.decrementAndGet();
|
||||
if (method.getName().equals("cancel")) cancels.incrementAndGet();
|
||||
if (method.getName().equals("executeQuery")
|
||||
&& !sql.contains("INFORMATION_SCHEMA"))
|
||||
assertEquals(3, s.getQueryTimeout());
|
||||
Object value = invoke(s, method, args);
|
||||
if (value instanceof ResultSet rs) {
|
||||
results.incrementAndGet();
|
||||
return wrap(
|
||||
ResultSet.class,
|
||||
rs,
|
||||
(o, m, a) -> {
|
||||
Object answer = invoke(rs, m, a);
|
||||
if (m.getName().equals("close")) {
|
||||
results.decrementAndGet();
|
||||
if (count) afterCount.run();
|
||||
}
|
||||
return answer;
|
||||
});
|
||||
}
|
||||
return value;
|
||||
});
|
||||
}
|
||||
|
||||
void assertReleased() {
|
||||
assertEquals(opened.get(), closed.get());
|
||||
assertEquals(0, statements.get());
|
||||
assertEquals(0, results.get());
|
||||
assertTrue(problems.isEmpty(), problems.toString());
|
||||
}
|
||||
|
||||
static Object invoke(Object object, Method method, Object[] args) throws Throwable {
|
||||
try {
|
||||
return method.invoke(object, args);
|
||||
} catch (InvocationTargetException e) {
|
||||
throw e.getCause();
|
||||
}
|
||||
}
|
||||
|
||||
static <T> T wrap(Class<T> type, T target, InvocationHandler handler) {
|
||||
return type.cast(
|
||||
Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, handler));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
package de.neitzel.fx.example.grid;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import de.neitzel.fx.grid.filter.*;
|
||||
import de.neitzel.grid.*;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
class ProductGridDemoTest {
|
||||
static final Queue<Throwable> uncaught = new ConcurrentLinkedQueue<>();
|
||||
ProductCatalog catalog;
|
||||
ProductGridDemo demo;
|
||||
Stage stage;
|
||||
Path setup;
|
||||
Thread.UncaughtExceptionHandler previous;
|
||||
|
||||
@BeforeAll
|
||||
static void startup() throws Exception {
|
||||
var ready = new CountDownLatch(1);
|
||||
try {
|
||||
Platform.startup(ready::countDown);
|
||||
} catch (IllegalStateException already) {
|
||||
ready.countDown();
|
||||
}
|
||||
assertTrue(ready.await(10, TimeUnit.SECONDS));
|
||||
fx(() -> Platform.setImplicitExit(false));
|
||||
}
|
||||
|
||||
static void fx(Runnable work) throws Exception {
|
||||
var f = new FutureTask<Void>(work, null);
|
||||
Platform.runLater(f);
|
||||
f.get(90, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void open() throws Exception {
|
||||
catalog = new ProductCatalog(10000);
|
||||
setup = Files.createTempDirectory("grid-demo-test").resolve("setup.json");
|
||||
fx(
|
||||
() -> {
|
||||
previous = Thread.currentThread().getUncaughtExceptionHandler();
|
||||
Thread.currentThread().setUncaughtExceptionHandler((t, e) -> uncaught.add(e));
|
||||
demo = new ProductGridDemo(catalog, setup);
|
||||
stage = new Stage();
|
||||
var scene = new Scene(demo, 1120, 820);
|
||||
demo.install(scene);
|
||||
stage.setScene(scene);
|
||||
stage.show();
|
||||
});
|
||||
ready();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() throws Exception {
|
||||
fx(
|
||||
() -> {
|
||||
demo.close();
|
||||
stage.close();
|
||||
Thread.currentThread().setUncaughtExceptionHandler(previous);
|
||||
});
|
||||
catalog.close();
|
||||
Files.deleteIfExists(setup);
|
||||
Files.deleteIfExists(setup.getParent());
|
||||
assertTrue(uncaught.isEmpty(), uncaught.toString());
|
||||
uncaught.clear();
|
||||
}
|
||||
|
||||
void await(BooleanSupplier condition) throws Exception {
|
||||
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(45);
|
||||
var value = new AtomicBoolean();
|
||||
while (System.nanoTime() < until) {
|
||||
fx(() -> value.set(condition.getAsBoolean()));
|
||||
if (value.get()) return;
|
||||
Thread.sleep(20);
|
||||
}
|
||||
fail("Timed out waiting for demo state");
|
||||
}
|
||||
|
||||
void ready() throws Exception {
|
||||
await(() -> demo.grid.stateProperty().get().phase() == GridCoordinator.Phase.READY);
|
||||
}
|
||||
|
||||
void click(String label) {
|
||||
Button button =
|
||||
(Button)
|
||||
demo.lookupAll(".button").stream()
|
||||
.filter(n -> n instanceof Button b && b.getText().equals(label))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
button.fire();
|
||||
}
|
||||
|
||||
@Test
|
||||
void fxmlFieldsAlignWithHeadersAfterCssAndReorder() throws Exception {
|
||||
fx(
|
||||
() -> {
|
||||
for (String theme : List.of("light", "dark", "high-contrast")) {
|
||||
demo.themePicker.setValue(theme);
|
||||
demo.grid.setColumnOrder(
|
||||
List.of("price", "id", "name", "category", "quantity"));
|
||||
demo.grid.setColumnWidth("name", new ColumnWidth.Explicit(400));
|
||||
demo.applyCss();
|
||||
demo.layout();
|
||||
var row = (javafx.scene.layout.HBox) demo.grid.lookup(".result-row");
|
||||
assertEquals(javafx.geometry.Insets.EMPTY, row.getPadding());
|
||||
var headers =
|
||||
demo.grid.lookupAll(".column-cell").stream()
|
||||
.sorted(
|
||||
java.util.Comparator.comparingDouble(
|
||||
n ->
|
||||
n.localToScene(n.getBoundsInLocal())
|
||||
.getMinX()))
|
||||
.toList();
|
||||
assertEquals(5, headers.size());
|
||||
for (int index = 0; index < headers.size(); index++) {
|
||||
var field = row.getChildren().get(index);
|
||||
assertEquals(
|
||||
headers.get(index)
|
||||
.localToScene(headers.get(index).getBoundsInLocal())
|
||||
.getMinX(),
|
||||
field.localToScene(field.getBoundsInLocal()).getMinX(),
|
||||
.1);
|
||||
assertEquals(
|
||||
headers.get(index).getBoundsInLocal().getWidth(),
|
||||
field.getBoundsInLocal().getWidth(),
|
||||
.1);
|
||||
assertEquals(4, ((Label) field).getPadding().getLeft(), .1);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void currentPageChecklistKeepsExactOriginalValues() throws Exception {
|
||||
var root = new AtomicReference<javafx.scene.Parent>();
|
||||
fx(
|
||||
() -> {
|
||||
var opener =
|
||||
(Button)
|
||||
demo.lookupAll(".filter-button").stream()
|
||||
.filter(
|
||||
n ->
|
||||
"Filter Name"
|
||||
.equals(n.getAccessibleText()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
opener.fire();
|
||||
var window =
|
||||
javafx.stage.Window.getWindows().stream()
|
||||
.filter(
|
||||
w ->
|
||||
w != stage
|
||||
&& w.getScene()
|
||||
.getRoot()
|
||||
.lookup("#mode")
|
||||
!= null)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
root.set(window.getScene().getRoot());
|
||||
});
|
||||
// Select the mode by its displayed name without assuming the internal list ordering.
|
||||
fx(
|
||||
() -> {
|
||||
var box = (ComboBox<?>) root.get().lookup("#mode");
|
||||
box.getSelectionModel().select(box.getItems().indexOf("Checklist"));
|
||||
});
|
||||
await(
|
||||
() ->
|
||||
root.get().lookupAll(".check-box").stream()
|
||||
.anyMatch(
|
||||
n ->
|
||||
n instanceof CheckBox b
|
||||
&& "Alpha".equals(b.getText())));
|
||||
fx(
|
||||
() -> {
|
||||
assertTrue(
|
||||
((Label) root.get().lookup("#scope"))
|
||||
.getText()
|
||||
.contains("Current page"));
|
||||
var choices =
|
||||
root.get().lookupAll(".check-box").stream()
|
||||
.map(n -> (CheckBox) n)
|
||||
.toList();
|
||||
assertTrue(choices.stream().anyMatch(b -> "alpha".equals(b.getText())));
|
||||
choices.stream()
|
||||
.filter(b -> "Alpha".equals(b.getText()))
|
||||
.findFirst()
|
||||
.orElseThrow()
|
||||
.fire();
|
||||
((Button)
|
||||
root.get().lookupAll(".button").stream()
|
||||
.filter(
|
||||
n ->
|
||||
n instanceof Button b
|
||||
&& "OK".equals(b.getText()))
|
||||
.findFirst()
|
||||
.orElseThrow())
|
||||
.fire();
|
||||
});
|
||||
ready();
|
||||
fx(
|
||||
() ->
|
||||
assertEquals(
|
||||
List.of("Alpha"),
|
||||
demo.grid.stateProperty().get().result().rows().stream()
|
||||
.map(r -> r.model().name())
|
||||
.toList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void actualFxmlEditorsSourceSwitchSetupThemesAndCapabilityErrors() throws Exception {
|
||||
fx(
|
||||
() -> {
|
||||
var context =
|
||||
new FilterEditorContext(
|
||||
"price",
|
||||
FilterColumn.number(Locale.ROOT, false, null, null),
|
||||
null,
|
||||
List.of(),
|
||||
FilterColumn.Checklist.DISABLED);
|
||||
var editor = PricePresetEditor.load(context);
|
||||
assertEquals(
|
||||
new NumericFilter(
|
||||
"price",
|
||||
NumericFilter.Operator.LESS_OR_EQUAL,
|
||||
new BigDecimal("10.00"),
|
||||
null),
|
||||
editor.draft());
|
||||
TextField field = (TextField) editor.view().lookup("#maximum");
|
||||
field.setText("1.001");
|
||||
assertFalse(editor.validationMessageProperty().get().isEmpty());
|
||||
field.setText("1.0");
|
||||
catalog.jdbc.validateFilter(editor.draft());
|
||||
demo.grid.setFilters(List.of(editor.draft()));
|
||||
editor.close();
|
||||
});
|
||||
ready();
|
||||
fx(
|
||||
() -> {
|
||||
assertTrue(
|
||||
demo.grid.stateProperty().get().result().rows().stream()
|
||||
.allMatch(
|
||||
r -> r.model().price().compareTo(BigDecimal.ONE) <= 0));
|
||||
demo.grid.select(1L);
|
||||
demo.grid.setColumnOrder(
|
||||
List.of("price", "id", "name", "category", "quantity"));
|
||||
demo.grid.setColumnWidth("name", new ColumnWidth.Explicit(400));
|
||||
try {
|
||||
demo.save();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
demo.themePicker.setValue("dark");
|
||||
demo.grid.setFilters(List.of());
|
||||
});
|
||||
ready();
|
||||
fx(() -> demo.restoreLegacy());
|
||||
ready();
|
||||
fx(
|
||||
() -> {
|
||||
assertEquals(2, demo.grid.snapshotSetup().definitionVersion());
|
||||
assertTrue(
|
||||
demo.grid.stateProperty().get().result().rows().stream()
|
||||
.allMatch(r -> "Office".equals(r.model().category())));
|
||||
demo.restore();
|
||||
});
|
||||
ready();
|
||||
fx(
|
||||
() -> {
|
||||
assertEquals("price", demo.grid.snapshotSetup().columns().getFirst().id());
|
||||
assertEquals(1, demo.grid.snapshotSetup().filters().size());
|
||||
demo.sourcePicker.setValue("Memory");
|
||||
});
|
||||
ready();
|
||||
fx(
|
||||
() -> {
|
||||
click("Memory-only filter");
|
||||
});
|
||||
ready();
|
||||
fx(
|
||||
() -> {
|
||||
assertTrue(
|
||||
demo.grid.stateProperty().get().result().rows().stream()
|
||||
.allMatch(r -> r.model().name().length() <= 5));
|
||||
demo.sourcePicker.setValue("JDBC / H2");
|
||||
});
|
||||
await(() -> demo.grid.stateProperty().get().phase() == GridCoordinator.Phase.ERROR);
|
||||
fx(
|
||||
() -> {
|
||||
assertTrue(
|
||||
demo.grid
|
||||
.stateProperty()
|
||||
.get()
|
||||
.error()
|
||||
.getMessage()
|
||||
.contains("does not support"));
|
||||
click("Clear filters");
|
||||
});
|
||||
ready();
|
||||
fx(() -> demo.sourcePicker.setValue("Memory"));
|
||||
ready();
|
||||
fx(() -> demo.sourcePicker.setValue("JDBC / H2"));
|
||||
ready();
|
||||
fx(
|
||||
() -> {
|
||||
demo.themePicker.setValue("high-contrast");
|
||||
stage.getScene().getRoot().applyCss();
|
||||
stage.getScene().getRoot().layout();
|
||||
var image = demo.snapshot(null, null);
|
||||
var buffered =
|
||||
new BufferedImage(
|
||||
(int) image.getWidth(),
|
||||
(int) image.getHeight(),
|
||||
BufferedImage.TYPE_INT_ARGB);
|
||||
for (int y = 0; y < buffered.getHeight(); y++)
|
||||
for (int x = 0; x < buffered.getWidth(); x++)
|
||||
buffered.setRGB(x, y, image.getPixelReader().getArgb(x, y));
|
||||
try {
|
||||
Files.createDirectories(Path.of("target/jdbc-evidence"));
|
||||
ImageIO.write(
|
||||
buffered, "png", Path.of("target/jdbc-evidence/demo.png").toFile());
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void lateSuccessFailureRetryAndDisappearingPage() throws Exception {
|
||||
fx(() -> click("Late success then failure"));
|
||||
await(() -> demo.grid.stateProperty().get().phase() == GridCoordinator.Phase.ERROR);
|
||||
Thread.sleep(2800);
|
||||
fx(
|
||||
() -> {
|
||||
assertEquals(
|
||||
GridCoordinator.Phase.ERROR, demo.grid.stateProperty().get().phase());
|
||||
demo.grid.retry();
|
||||
});
|
||||
ready();
|
||||
fx(() -> click("Late failure then success"));
|
||||
ready();
|
||||
Thread.sleep(2800);
|
||||
fx(
|
||||
() -> {
|
||||
assertEquals(
|
||||
GridCoordinator.Phase.READY, demo.grid.stateProperty().get().phase());
|
||||
assertTrue(demo.diagnostics.getText().contains("obsolete completion"));
|
||||
demo.grid.last();
|
||||
});
|
||||
ready();
|
||||
fx(
|
||||
() -> {
|
||||
assertEquals(
|
||||
199,
|
||||
((PageRequest.Paged) demo.grid.stateProperty().get().displayed().page())
|
||||
.pageIndex());
|
||||
click("Delete displayed page");
|
||||
});
|
||||
await(
|
||||
() ->
|
||||
demo.grid.stateProperty().get().phase() == GridCoordinator.Phase.READY
|
||||
&& demo.grid.stateProperty().get().result().total().orElseThrow()
|
||||
== 9950);
|
||||
fx(
|
||||
() ->
|
||||
assertEquals(
|
||||
198,
|
||||
((PageRequest.Paged)
|
||||
demo.grid.stateProperty().get().displayed().page())
|
||||
.pageIndex()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allCancellationSupersessionRestorationAndFullMaterialization() throws Exception {
|
||||
var decision = new CompletableFuture<Boolean>();
|
||||
var asked = new AtomicLong();
|
||||
fx(
|
||||
() -> {
|
||||
demo.grid.setAllConfirmation(
|
||||
(q, count) -> {
|
||||
asked.set(count);
|
||||
return decision;
|
||||
});
|
||||
demo.grid.showAll();
|
||||
});
|
||||
await(() -> asked.get() == 10000);
|
||||
assertEquals(
|
||||
1,
|
||||
catalog.database.getActiveConnections(),
|
||||
"Only application anchor remains while awaiting person");
|
||||
fx(() -> decision.complete(false));
|
||||
ready();
|
||||
fx(() -> assertInstanceOf(PageRequest.Paged.class, demo.grid.snapshotSetup().page()));
|
||||
var obsolete = new CompletableFuture<Boolean>();
|
||||
asked.set(0);
|
||||
fx(
|
||||
() -> {
|
||||
demo.grid.setAllConfirmation(
|
||||
(q, count) -> {
|
||||
asked.set(count);
|
||||
return obsolete;
|
||||
});
|
||||
demo.grid.showAll();
|
||||
});
|
||||
await(() -> asked.get() == 10000);
|
||||
fx(
|
||||
() ->
|
||||
demo.grid.setFilters(
|
||||
List.of(
|
||||
new NumericFilter(
|
||||
"id",
|
||||
NumericFilter.Operator.LESS_OR_EQUAL,
|
||||
new BigDecimal("25"),
|
||||
null))));
|
||||
ready();
|
||||
fx(() -> obsolete.complete(true));
|
||||
ready();
|
||||
fx(() -> assertEquals(25, demo.grid.stateProperty().get().result().rows().size()));
|
||||
fx(
|
||||
() -> {
|
||||
demo.grid.setPageSize(50);
|
||||
demo.grid.setFilters(List.of());
|
||||
});
|
||||
ready();
|
||||
// One measured, explicitly approved All load of real FXML Components (not virtualization).
|
||||
long before = System.nanoTime();
|
||||
var approvals = new AtomicInteger();
|
||||
fx(
|
||||
() -> {
|
||||
demo.grid.setAllConfirmation(
|
||||
(q, count) -> {
|
||||
approvals.incrementAndGet();
|
||||
return CompletableFuture.completedFuture(true);
|
||||
});
|
||||
demo.grid.showAll();
|
||||
});
|
||||
ready();
|
||||
long elapsed = (System.nanoTime() - before) / 1_000_000;
|
||||
fx(
|
||||
() -> {
|
||||
assertEquals(10000, demo.grid.stateProperty().get().result().rows().size());
|
||||
assertInstanceOf(PageRequest.All.class, demo.grid.snapshotSetup().page());
|
||||
try {
|
||||
demo.save();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
demo.grid.setPageSize(50);
|
||||
});
|
||||
ready();
|
||||
asked.set(0);
|
||||
var restoreDecision = new CompletableFuture<Boolean>();
|
||||
fx(
|
||||
() -> {
|
||||
demo.grid.setAllConfirmation(
|
||||
(q, count) -> {
|
||||
asked.set(count);
|
||||
return restoreDecision;
|
||||
});
|
||||
demo.restore();
|
||||
});
|
||||
await(() -> asked.get() == 10000);
|
||||
fx(() -> restoreDecision.complete(false));
|
||||
ready();
|
||||
fx(() -> assertInstanceOf(PageRequest.Paged.class, demo.grid.snapshotSetup().page()));
|
||||
assertEquals(1, approvals.get());
|
||||
Files.createDirectories(Path.of("target/jdbc-evidence"));
|
||||
Files.writeString(
|
||||
Path.of("target/jdbc-evidence/fx-materialization.txt"),
|
||||
"10,000 H2 rows as fresh FXML Components; count/approval/fetch/publication"
|
||||
+ " elapsedMs="
|
||||
+ elapsed
|
||||
+ "; includes UI materialization, no virtualization. Single observed"
|
||||
+ " run.\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
package de.neitzel.fx.example.theme;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.css.PseudoClass;
|
||||
import javafx.scene.*;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.image.*;
|
||||
import javafx.scene.layout.*;
|
||||
import javafx.scene.paint.*;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
class ThemeGalleryTest {
|
||||
private static final java.util.Queue<Throwable> uncaught =
|
||||
new java.util.concurrent.ConcurrentLinkedQueue<>();
|
||||
private static Thread.UncaughtExceptionHandler previousHandler;
|
||||
|
||||
@BeforeEach
|
||||
void captureFxErrors() throws Exception {
|
||||
fx(
|
||||
() -> {
|
||||
previousHandler = Thread.currentThread().getUncaughtExceptionHandler();
|
||||
Thread.currentThread()
|
||||
.setUncaughtExceptionHandler((thread, error) -> uncaught.add(error));
|
||||
});
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void verifyFxErrors() throws Exception {
|
||||
fx(() -> Thread.currentThread().setUncaughtExceptionHandler(previousHandler));
|
||||
var errors = new java.util.ArrayList<>(uncaught);
|
||||
uncaught.clear();
|
||||
assertTrue(errors.isEmpty(), "Uncaught FX errors: " + errors);
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
static void start() throws Exception {
|
||||
CountDownLatch ready = new CountDownLatch(1);
|
||||
try {
|
||||
Platform.startup(ready::countDown);
|
||||
} catch (IllegalStateException e) {
|
||||
ready.countDown();
|
||||
}
|
||||
assertTrue(ready.await(10, TimeUnit.SECONDS));
|
||||
fx(() -> Platform.setImplicitExit(false));
|
||||
}
|
||||
|
||||
static void fx(Runnable code) throws Exception {
|
||||
var task = new FutureTask<Void>(code, null);
|
||||
Platform.runLater(task);
|
||||
task.get(15, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
static double luminance(Color c) {
|
||||
return .2126 * linear(c.getRed())
|
||||
+ .7152 * linear(c.getGreen())
|
||||
+ .0722 * linear(c.getBlue());
|
||||
}
|
||||
|
||||
static double linear(double c) {
|
||||
return c <= .04045 ? c / 12.92 : Math.pow((c + .055) / 1.055, 2.4);
|
||||
}
|
||||
|
||||
static double contrast(Color a, Color b) {
|
||||
double x = luminance(a), y = luminance(b);
|
||||
return (Math.max(x, y) + .05) / (Math.min(x, y) + .05);
|
||||
}
|
||||
|
||||
static Color background(Node node) {
|
||||
for (Node current = node; current != null; current = current.getParent())
|
||||
if (current instanceof Region r && r.getBackground() != null)
|
||||
for (int i = r.getBackground().getFills().size() - 1; i >= 0; i--) {
|
||||
Paint p = r.getBackground().getFills().get(i).getFill();
|
||||
if (p instanceof Color c && c.getOpacity() == 1) return c;
|
||||
}
|
||||
throw new AssertionError("No opaque resolved background for " + node);
|
||||
}
|
||||
|
||||
static void measure(
|
||||
String theme,
|
||||
String name,
|
||||
Paint foreground,
|
||||
Node node,
|
||||
double target,
|
||||
List<String> report) {
|
||||
assertInstanceOf(Color.class, foreground);
|
||||
Color fg = (Color) foreground, bg = background(node);
|
||||
double ratio = contrast(fg, bg);
|
||||
report.add(
|
||||
theme
|
||||
+ " | "
|
||||
+ name
|
||||
+ " | "
|
||||
+ fg
|
||||
+ " | "
|
||||
+ bg
|
||||
+ " | "
|
||||
+ String.format(Locale.ROOT, "%.2f", ratio));
|
||||
assertTrue(ratio >= target, theme + " " + name + " contrast " + ratio + " < " + target);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvedStateContrastStableGeometryAndThemeSwitchingPreserveGridState() throws Exception {
|
||||
var ref = new AtomicReference<ThemeGallery>();
|
||||
var window = new AtomicReference<Stage>();
|
||||
fx(
|
||||
() -> {
|
||||
var gallery = new ThemeGallery();
|
||||
ref.set(gallery);
|
||||
Stage stage = new Stage();
|
||||
window.set(stage);
|
||||
Scene scene = new Scene(gallery, 920, 900);
|
||||
gallery.install(scene);
|
||||
stage.setScene(scene);
|
||||
stage.show();
|
||||
});
|
||||
for (int i = 0; i < 5; i++) fx(() -> {});
|
||||
List<String> report = new ArrayList<>();
|
||||
try {
|
||||
fx(
|
||||
() -> {
|
||||
var g = ref.get();
|
||||
var selected = g.grid.selectedKeyProperty().get();
|
||||
var query = g.grid.stateProperty().get().displayed();
|
||||
g.draft.setText("Unfinished draft");
|
||||
g.grid.setColumnWidth(
|
||||
"name", new de.neitzel.grid.ColumnWidth.Explicit(475));
|
||||
double[] normalSize = new double[2];
|
||||
for (String theme : List.of("light", "dark", "high-contrast")) {
|
||||
assertTrue(g.themes.select(theme));
|
||||
g.hovered.pseudoClassStateChanged(
|
||||
PseudoClass.getPseudoClass("hover"), true);
|
||||
g.focused.pseudoClassStateChanged(
|
||||
PseudoClass.getPseudoClass("focused"), true);
|
||||
g.applyCss();
|
||||
g.layout();
|
||||
double target = theme.equals("high-contrast") ? 7 : 4.5;
|
||||
for (var button : List.of(g.normal, g.hovered, g.focused, g.disabled))
|
||||
measure(
|
||||
theme,
|
||||
button.getText(),
|
||||
button.getTextFill(),
|
||||
button,
|
||||
target,
|
||||
report);
|
||||
measure(
|
||||
theme,
|
||||
"invalid",
|
||||
g.invalid.lookupAll(".text").stream()
|
||||
.filter(
|
||||
n ->
|
||||
n instanceof javafx.scene.text.Text t
|
||||
&& t.getText()
|
||||
.equals(
|
||||
g.invalid
|
||||
.getText()))
|
||||
.map(n -> ((javafx.scene.text.Text) n).getFill())
|
||||
.findFirst()
|
||||
.orElseThrow(),
|
||||
g.invalid,
|
||||
target,
|
||||
report);
|
||||
measure(theme, "error", g.error.getTextFill(), g.error, target, report);
|
||||
measure(
|
||||
theme,
|
||||
"warning",
|
||||
g.warning.getTextFill(),
|
||||
g.warning,
|
||||
target,
|
||||
report);
|
||||
var focus =
|
||||
(Color)
|
||||
g.focused
|
||||
.getBorder()
|
||||
.getStrokes()
|
||||
.getFirst()
|
||||
.getTopStroke();
|
||||
double focusRatio = contrast(focus, background(g.focused));
|
||||
report.add(
|
||||
theme
|
||||
+ " | focus border | "
|
||||
+ focus
|
||||
+ " | "
|
||||
+ background(g.focused)
|
||||
+ " | "
|
||||
+ focusRatio);
|
||||
assertTrue(focusRatio >= 3);
|
||||
var box = (Region) g.lookup(".check-box .box");
|
||||
measure(
|
||||
theme,
|
||||
"checkbox boundary",
|
||||
box.getBorder().getStrokes().getFirst().getTopStroke(),
|
||||
box,
|
||||
3,
|
||||
report);
|
||||
var icon = (javafx.scene.shape.SVGPath) g.grid.lookup(".filter-icon");
|
||||
measure(theme, "filter icon", icon.getFill(), icon, 3, report);
|
||||
var filterButton = (Button) g.grid.lookup(".filter-button");
|
||||
assertTrue(filterButton.getAccessibleText().contains("active"));
|
||||
assertFalse(filterButton.getText().isBlank());
|
||||
var cells =
|
||||
g.standard.lookupAll(".table-cell").stream()
|
||||
.filter(
|
||||
n ->
|
||||
n instanceof TableCell<?, ?> cell
|
||||
&& cell.getText() != null
|
||||
&& cell.getText()
|
||||
.startsWith("REMOVE"))
|
||||
.toList();
|
||||
assertEquals(1, cells.size());
|
||||
var cell = (TableCell<?, ?>) cells.getFirst();
|
||||
measure(
|
||||
theme,
|
||||
"selected TableView",
|
||||
cell.getTextFill(),
|
||||
cell,
|
||||
target,
|
||||
report);
|
||||
var selectedLabel =
|
||||
(Label) g.grid.lookup(".result-row:selected .label");
|
||||
assertNotNull(selectedLabel);
|
||||
measure(
|
||||
theme,
|
||||
"selected DataGrid",
|
||||
selectedLabel.getTextFill(),
|
||||
selectedLabel,
|
||||
target,
|
||||
report);
|
||||
selectedLabel.getParent().setDisable(true);
|
||||
g.applyCss();
|
||||
measure(
|
||||
theme,
|
||||
"selected disabled row",
|
||||
selectedLabel.getTextFill(),
|
||||
selectedLabel,
|
||||
target,
|
||||
report);
|
||||
selectedLabel.getParent().setDisable(false);
|
||||
g.applyCss();
|
||||
assertEquals(selected, g.grid.selectedKeyProperty().get());
|
||||
assertEquals(query, g.grid.stateProperty().get().displayed());
|
||||
assertEquals(
|
||||
475, ((Region) g.grid.lookup(".column-cell")).getWidth(), .01);
|
||||
assertEquals("Unfinished draft", g.draft.getText());
|
||||
if (theme.equals("light")) {
|
||||
normalSize[0] = g.normal.getWidth();
|
||||
normalSize[1] = g.normal.getHeight();
|
||||
} else {
|
||||
assertEquals(normalSize[0], g.normal.getWidth(), .01);
|
||||
assertEquals(normalSize[1], g.normal.getHeight(), .01);
|
||||
}
|
||||
try {
|
||||
Path output = Path.of("target/theme-gallery");
|
||||
Files.createDirectories(output);
|
||||
WritableImage shot = g.snapshot(null, null);
|
||||
BufferedImage image =
|
||||
new BufferedImage(
|
||||
(int) shot.getWidth(),
|
||||
(int) shot.getHeight(),
|
||||
BufferedImage.TYPE_INT_ARGB);
|
||||
for (int y = 0; y < image.getHeight(); y++)
|
||||
for (int x = 0; x < image.getWidth(); x++)
|
||||
image.setRGB(x, y, shot.getPixelReader().getArgb(x, y));
|
||||
ImageIO.write(
|
||||
image, "png", output.resolve(theme + ".png").toFile());
|
||||
} catch (java.io.IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
fx(
|
||||
() -> {
|
||||
ref.get().close();
|
||||
window.get().close();
|
||||
});
|
||||
Path output = Path.of("target/theme-gallery");
|
||||
Files.createDirectories(output);
|
||||
Files.write(output.resolve("contrast.txt"), report);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void popupDialogAndFloatingWindowResolvedTextMeetThemeTargets() throws Exception {
|
||||
List<String> report = new ArrayList<>();
|
||||
fx(
|
||||
() -> {
|
||||
var manager = new de.neitzel.fx.theme.ThemeManager();
|
||||
Stage owner = new Stage();
|
||||
Button opener = new Button("Open filter");
|
||||
owner.setScene(new Scene(new VBox(opener), 500, 400));
|
||||
manager.register(owner.getScene());
|
||||
owner.show();
|
||||
var editor =
|
||||
de.neitzel.fx.grid.filter.BuiltInFilterEditor.load(
|
||||
new de.neitzel.fx.grid.filter.FilterEditorContext(
|
||||
"x",
|
||||
de.neitzel.fx.grid.filter.FilterColumn.text(),
|
||||
new de.neitzel.grid.TextFilter(
|
||||
"x",
|
||||
de.neitzel.grid.TextFilter.Operator.EQUALS,
|
||||
"Typed draft",
|
||||
false),
|
||||
List.of(),
|
||||
de.neitzel.fx.grid.filter.FilterColumn.Checklist
|
||||
.DISABLED));
|
||||
var popup =
|
||||
new de.neitzel.fx.grid.filter.FilterPopup(
|
||||
opener,
|
||||
editor,
|
||||
de.neitzel.fx.grid.filter.FilterPopup.Options.defaults(),
|
||||
c -> {},
|
||||
c -> {});
|
||||
popup.show();
|
||||
try {
|
||||
for (String theme : List.of("light", "dark", "high-contrast")) {
|
||||
manager.select(theme);
|
||||
editor.view().applyCss();
|
||||
editor.view().layout();
|
||||
var input = (TextField) editor.view().lookup("#operand");
|
||||
var text =
|
||||
input.lookupAll(".text").stream()
|
||||
.filter(
|
||||
n ->
|
||||
n instanceof javafx.scene.text.Text t
|
||||
&& t.getText()
|
||||
.equals("Typed draft"))
|
||||
.map(n -> (javafx.scene.text.Text) n)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
measure(
|
||||
theme,
|
||||
"popup draft",
|
||||
text.getFill(),
|
||||
input,
|
||||
theme.equals("high-contrast") ? 7 : 4.5,
|
||||
report);
|
||||
assertTrue(popup.isOpen());
|
||||
assertEquals("Typed draft", input.getText());
|
||||
snapshot(editor.view().getScene().getRoot(), theme + "-popup");
|
||||
}
|
||||
popup.close();
|
||||
Alert dialog = new Alert(Alert.AlertType.INFORMATION);
|
||||
dialog.initOwner(owner);
|
||||
Label content = new Label("Dialog content remains readable");
|
||||
dialog.getDialogPane().setContent(content);
|
||||
dialog.show();
|
||||
try {
|
||||
for (String theme : List.of("light", "dark", "high-contrast")) {
|
||||
manager.select(theme);
|
||||
dialog.getDialogPane().applyCss();
|
||||
dialog.getDialogPane().layout();
|
||||
measure(
|
||||
theme,
|
||||
"dialog",
|
||||
content.getTextFill(),
|
||||
content,
|
||||
theme.equals("high-contrast") ? 7 : 4.5,
|
||||
report);
|
||||
}
|
||||
} finally {
|
||||
dialog.close();
|
||||
}
|
||||
Stage floating = new Stage();
|
||||
floating.initOwner(owner);
|
||||
Label label = new Label("Floating editor");
|
||||
floating.setScene(
|
||||
new Scene(
|
||||
new VBox(label, new TextField("Unfinished edit")),
|
||||
400,
|
||||
150));
|
||||
floating.show();
|
||||
try {
|
||||
for (String theme : List.of("light", "dark", "high-contrast")) {
|
||||
manager.select(theme);
|
||||
floating.getScene().getRoot().applyCss();
|
||||
measure(
|
||||
theme,
|
||||
"floating",
|
||||
label.getTextFill(),
|
||||
label,
|
||||
theme.equals("high-contrast") ? 7 : 4.5,
|
||||
report);
|
||||
}
|
||||
} finally {
|
||||
floating.close();
|
||||
}
|
||||
} finally {
|
||||
popup.close();
|
||||
owner.close();
|
||||
manager.close();
|
||||
}
|
||||
});
|
||||
Path output = Path.of("target/theme-gallery");
|
||||
Files.createDirectories(output);
|
||||
Files.write(output.resolve("window-contrast.txt"), report);
|
||||
}
|
||||
|
||||
static void snapshot(Parent root, String name) {
|
||||
try {
|
||||
Path output = Path.of("target/theme-gallery");
|
||||
Files.createDirectories(output);
|
||||
WritableImage shot = root.snapshot(null, null);
|
||||
BufferedImage image =
|
||||
new BufferedImage(
|
||||
(int) shot.getWidth(),
|
||||
(int) shot.getHeight(),
|
||||
BufferedImage.TYPE_INT_ARGB);
|
||||
for (int y = 0; y < image.getHeight(); y++)
|
||||
for (int x = 0; x < image.getWidth(); x++)
|
||||
image.setRGB(x, y, shot.getPixelReader().getArgb(x, y));
|
||||
ImageIO.write(image, "png", output.resolve(name + ".png").toFile());
|
||||
} catch (java.io.IOException error) {
|
||||
throw new RuntimeException(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user