package com.widgetworkbench.cheerpj; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Window; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JSplitPane; import javax.swing.SwingUtilities; /** * Optional, unsigned compatibility bridge for the iTAC Workplace running in * CheerpJ's virtual Swing desktop. No vendor classes are modified. * * Window reports deliberately do not contain window titles or component text: * those may contain sensitive MES data. Only classes and geometry are reported. */ public final class WorkplaceResizeBridge { private static final String FRAME_NAME = "com.itac.mes.suite.presentation.MesSuiteFrame"; private static final String PANEL_NAME = "com.itac.mes.gui.suite.MesSuitePanel"; private WorkplaceResizeBridge() { } private static volatile boolean monitorActive; private static volatile Thread monitorThread; private static volatile int monitorWidth; private static volatile int monitorHeight; private static volatile String monitorMode = "off"; /** * Starts exactly one Java-owned AWT/window monitor. IMPORTANT: all subsequent * monitor calls happen on a native Java Thread, NOT through CheerpJ Library * Mode. That prevents simultaneous JavaScript-to-Java invocations while * cheerpjRunMain() is executing. * * @return 1 = started, 2 = already running */ public static synchronized int startRuntimeMonitor(int width, int height, String mode) { if (!validSize(width, height)) throw new IllegalArgumentException("invalid viewport"); if (!("off".equals(mode) || "diagnose".equals(mode) || "rescue".equals(mode))) throw new IllegalArgumentException("invalid window mode"); monitorWidth = width; monitorHeight = height; monitorMode = mode; if (monitorThread != null && monitorThread.isAlive()) return 2; monitorActive = true; final Thread worker = new Thread(new Runnable() { @Override public void run() { String lastSnapshot = null; boolean mainFrameSized = false; int reportedErrorCount = 0; while (monitorActive) { try { final int width = monitorWidth; final int height = monitorHeight; final String mode = monitorMode; // The main frame does not exist at startup. Retry until // first detected; do not continuously move user windows. if (!mainFrameSized) { if (resize(width, height) > 0) { mainFrameSized = true; System.out.println("[WidgetWorkbench/WindowGeometry] MAIN_FRAME_RESIZE " + width + "x" + height); } } if (!"off".equals(mode)) { if ("rescue".equals(mode)) { final String rescue = rescueOffscreenDialogs(width, height); if (rescue.startsWith("RESCUE moved=") && !rescue.startsWith("RESCUE moved=0")) System.out.println("[WidgetWorkbench/WindowGeometry] " + rescue); } final String snapshot = diagnoseWindows(width, height); if (!snapshot.equals(lastSnapshot)) { lastSnapshot = snapshot; System.out.println("[WidgetWorkbench/WindowGeometry]\n" + snapshot); } } Thread.sleep(2000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); break; } catch (Throwable ex) { // Diagnostics MUST NOT abort the vendor application or // repeatedly flood logs when the AWT implementation fails. if (reportedErrorCount++ < 3) System.out.println( "[WidgetWorkbench/WindowGeometry] MONITOR_ERROR " + ex.getClass().getName()); try { Thread.sleep(3000); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); break; } } } monitorActive = false; } }, "WidgetWorkbench-WindowMonitor"); worker.setDaemon(true); monitorThread = worker; worker.start(); return 1; } /** For isolated Java regression tests; not called by the active JS runner. */ public static synchronized void stopRuntimeMonitor() { monitorActive = false; Thread worker = monitorThread; if (worker != null) worker.interrupt(); monitorThread = null; } /** Resize only the main Workplace frame (not its owned dialogs). */ public static int resize(final int width, final int height) { if (!validSize(width, height)) return 0; int matches = 0; for (final Frame frame : Frame.getFrames()) { if (!(frame instanceof JFrame) || !FRAME_NAME.equals(frame.getClass().getName())) continue; final JFrame window = (JFrame) frame; final Container content = window.getContentPane(); if (content == null || !PANEL_NAME.equals(content.getClass().getName())) continue; matches++; final Runnable action = new Runnable() { @Override public void run() { if (!window.isDisplayable()) return; window.setSize(width, height); window.setLocation(0, 0); content.invalidate(); window.validate(); window.repaint(); } }; if (SwingUtilities.isEventDispatchThread()) action.run(); else SwingUtilities.invokeLater(action); } return matches; } /** Existing main-window resize diagnostics (kept for compatibility). */ public static String diagnose() { return onEdt(new Snapshot() { @Override public String get() { StringBuilder sb = new StringBuilder(); int count = 0; for (Frame frame : Frame.getFrames()) { if (!(frame instanceof JFrame) || !FRAME_NAME.equals(frame.getClass().getName())) continue; JFrame window = (JFrame) frame; Container panel = window.getContentPane(); if (panel == null || !PANEL_NAME.equals(panel.getClass().getName())) continue; count++; appendSize(sb, "frame", window); appendSize(sb, "MesSuitePanel", panel); JSplitPane split = findSplit(panel); if (split == null) sb.append("split: not yet mounted; "); else { appendSize(sb, "split", split); sb.append("dividerPx=").append(split.getDividerLocation()).append("; "); } } if (count == 0) sb.append("Workplace window not found"); return sb.toString(); } }); } /** * Read-only snapshot of the virtual desktop and ALL AWT top-level windows, * including invisible/not-yet-displayed JDialogs. Safe for periodic polling. * The viewport represents the actual CheerpJ HTML display in CSS pixels. */ public static String diagnoseWindows(final int width, final int height) { if (!validSize(width, height)) return "WINDOWS INVALID_VIEWPORT"; return onEdt(new Snapshot() { @Override public String get() { final Rectangle viewport = new Rectangle(0, 0, width, height); final StringBuilder out = new StringBuilder(2048); out.append("viewport=").append(rect(viewport)); out.append(" headless=").append(GraphicsEnvironment.isHeadless()).append('\n'); try { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] devices = ge.getScreenDevices(); Dimension toolkit = Toolkit.getDefaultToolkit().getScreenSize(); out.append("toolkitScreen=").append(toolkit.width).append('x').append(toolkit.height).append('\n'); out.append("virtualScreens=").append(devices.length).append('\n'); for (int i = 0; i < devices.length && i < 8; i++) { GraphicsConfiguration gc = devices[i].getDefaultConfiguration(); out.append(" screen[").append(i).append("]=") .append(gc == null ? "no configuration" : rect(gc.getBounds())) .append('\n'); } } catch (RuntimeException | LinkageError ex) { out.append("virtualScreens=unavailable(").append(ex.getClass().getSimpleName()).append(")\n"); } final Window[] windows = Window.getWindows(); int dialogs = 0, visibleDialogs = 0, outsideDialogs = 0; for (Window w : windows) { if (w instanceof JDialog) { dialogs++; if (w.isVisible()) visibleDialogs++; if (w.isVisible() && isOutside(w.getBounds(), viewport)) outsideDialogs++; } } out.append("windows=").append(windows.length) .append(" dialogs=").append(dialogs) .append(" visibleDialogs=").append(visibleDialogs) .append(" offscreenDialogs=").append(outsideDialogs).append('\n'); for (int i = 0; i < windows.length && i < 80; i++) { Window w = windows[i]; Rectangle b = w.getBounds(); out.append('[').append(i).append("] ") .append(w.getClass().getName()) .append(" bounds=").append(rect(b)) .append(" visible=").append(w.isVisible()) .append(" showing=").append(w.isShowing()) .append(" displayable=").append(w.isDisplayable()) .append(" active=").append(w.isActive()) .append(" focused=").append(w.isFocused()) .append(" outsideViewport=").append(b.width > 0 && b.height > 0 && isOutside(b, viewport)); Window owner = w.getOwner(); if (owner != null) out.append(" owner=").append(owner.getClass().getName()); if (w instanceof Dialog) out.append(" modal=").append(((Dialog) w).isModal()); out.append('\n'); } if (windows.length > 80) out.append("... additional windows omitted\n"); return out.toString(); } }); } /** * Opt-in recovery, NOT an authentication workaround. Reposition only visible * Swing dialogs which are almost entirely outside the virtual display. * Never resize dialogs, move the main frame, or move invisible dialogs. */ public static String rescueOffscreenDialogs(final int width, final int height) { if (!validSize(width, height)) return "WINDOWS INVALID_VIEWPORT"; return onEdt(new Snapshot() { @Override public String get() { Rectangle viewport = new Rectangle(0, 0, width, height); int visible = 0, moved = 0; for (Window window : Window.getWindows()) { if (!(window instanceof JDialog) || !window.isVisible() || !window.isDisplayable()) continue; visible++; Rectangle before = window.getBounds(); if (!isOutside(before, viewport)) continue; // An oversized dialog is positioned at zero rather than // resized, avoiding changes to vendor-controlled content. int newX = Math.max(0, (width - before.width) / 2); int newY = Math.max(0, (height - before.height) / 2); window.setLocation(newX, newY); moved++; } return "RESCUE moved=" + moved + " visibleDialogs=" + visible; } }); } private static boolean validSize(int width, int height) { return width >= 200 && height >= 150 && width <= 16000 && height <= 16000; } static boolean isOutside(Rectangle bounds, Rectangle viewport) { if (bounds.width <= 0 || bounds.height <= 0) return true; Rectangle intersection = bounds.intersection(viewport); int minWidth = Math.min(48, Math.max(1, bounds.width / 5)); int minHeight = Math.min(40, Math.max(1, bounds.height / 5)); return intersection.width < minWidth || intersection.height < minHeight; } private static String rect(Rectangle r) { return r.x + "," + r.y + " " + r.width + "x" + r.height; } private interface Snapshot { String get(); } private static String onEdt(final Snapshot action) { if (SwingUtilities.isEventDispatchThread()) { try { return action.get(); } catch (RuntimeException | LinkageError ex) { return "WINDOWS ERROR " + ex.getClass().getSimpleName(); } } // An iTAC modal UI may be busy or its event dispatch may have thrown. // Do NOT wait indefinitely for the EDT from CheerpJ's library thread. FutureTask task = new FutureTask(new Callable() { @Override public String call() { try { return action.get(); } catch (RuntimeException | LinkageError ex) { return "WINDOWS ERROR " + ex.getClass().getSimpleName(); } } }); SwingUtilities.invokeLater(task); try { return task.get(1500, TimeUnit.MILLISECONDS); } catch (TimeoutException ex) { task.cancel(false); return "WINDOWS EDT_BUSY (snapshot timed out after 1500ms)"; } catch (InterruptedException ex) { task.cancel(false); Thread.currentThread().interrupt(); return "WINDOWS interrupted"; } catch (Exception ex) { return "WINDOWS invocation error: " + ex.getClass().getSimpleName(); } } private static void appendSize(StringBuilder sb, String title, Component c) { Dimension preferred = c.getPreferredSize(); Dimension minimum = c.getMinimumSize(); Dimension actual = c.getSize(); sb.append(title).append('=').append(actual.width).append('x').append(actual.height) .append(" pref=").append(preferred.width).append('x').append(preferred.height) .append(" min=").append(minimum.width).append('x').append(minimum.height).append("; "); } private static JSplitPane findSplit(Container parent) { for (Component child : parent.getComponents()) { if (child instanceof JSplitPane) return (JSplitPane) child; if (child instanceof Container) { JSplitPane found = findSplit((Container) child); if (found != null) return found; } } return null; } }