This is an automated email from the ASF dual-hosted git repository.

mattcasters pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/hop.git


The following commit(s) were added to refs/heads/main by this push:
     new 1120df572d Terminal: pass size to the PTY, HiDPI font on Linux, CJK 
font fallbac… (#9185)
1120df572d is described below

commit 1120df572d0b5a41fef6f806d6cde384b7d26859
Author: Bart Maertens <[email protected]>
AuthorDate: Tue Nov 3 09:24:51 2026 +0100

    Terminal: pass size to the PTY, HiDPI font on Linux, CJK font fallbac… 
(#9185)
    
    * Terminal: pass size to the PTY, HiDPI font on Linux, CJK font fallback, 
close tabs cleanly, JediTerm 3.76, fixes #7210
    
    * fix remarks
    
    ---------
    
    Co-authored-by: Hans Van Akelyen <[email protected]>
---
 assemblies/static/src/main/resources/LICENSE       |   4 +-
 ui/pom.xml                                         |   2 +-
 .../hop/ui/hopgui/terminal/JediTerminalWidget.java | 249 ++++++++++++++-------
 .../hop/ui/hopgui/terminal/TerminalFonts.java      | 170 ++++++++++++++
 .../hop/ui/hopgui/terminal/TerminalFontsTest.java  | 180 +++++++++++++++
 5 files changed, 527 insertions(+), 78 deletions(-)

diff --git a/assemblies/static/src/main/resources/LICENSE 
b/assemblies/static/src/main/resources/LICENSE
index 6fa098345a..8ca9c2b87b 100644
--- a/assemblies/static/src/main/resources/LICENSE
+++ b/assemblies/static/src/main/resources/LICENSE
@@ -1750,10 +1750,10 @@ This product bundles jctools-core 3.1.0, which is 
available under a
 This product bundles jdom2 2.0.6.1, which is available under a
 "Apache 2.0" license. For details, see LICENSE.
 
-This product bundles jediterm-core 3.57, which is available under a
+This product bundles jediterm-core 3.76, which is available under a
 "Apache 2.0" license. For details, see LICENSE.
 
-This product bundles jediterm-ui 3.57, which is available under a
+This product bundles jediterm-ui 3.76, which is available under a
 "Apache 2.0" license. For details, see LICENSE.
 
 This product bundles jempbox 1.8.17, which is available under a
diff --git a/ui/pom.xml b/ui/pom.xml
index c2149ab191..95c9ba5a2f 100644
--- a/ui/pom.xml
+++ b/ui/pom.xml
@@ -30,7 +30,7 @@
 
     <properties>
         <assembly_package-phase>none</assembly_package-phase>
-        <jediterm.version>3.57</jediterm.version>
+        <jediterm.version>3.76</jediterm.version>
         <pty4j.version>0.14.0</pty4j.version>
         <xmlgraphics-commons.version>2.11</xmlgraphics-commons.version>
     </properties>
diff --git 
a/ui/src/main/java/org/apache/hop/ui/hopgui/terminal/JediTerminalWidget.java 
b/ui/src/main/java/org/apache/hop/ui/hopgui/terminal/JediTerminalWidget.java
index 30416c3295..cc42882344 100644
--- a/ui/src/main/java/org/apache/hop/ui/hopgui/terminal/JediTerminalWidget.java
+++ b/ui/src/main/java/org/apache/hop/ui/hopgui/terminal/JediTerminalWidget.java
@@ -17,19 +17,26 @@
 
 package org.apache.hop.ui.hopgui.terminal;
 
+import com.jediterm.core.util.TermSize;
+import com.jediterm.terminal.ProcessTtyConnector;
 import com.jediterm.terminal.TerminalColor;
 import com.jediterm.terminal.TextStyle;
-import com.jediterm.terminal.TtyConnector;
+import com.jediterm.terminal.TtyConnectorResizeStrategy;
+import com.jediterm.terminal.TtyConnectorResizeStrategyProvider;
+import com.jediterm.terminal.model.StyleState;
+import com.jediterm.terminal.model.TerminalTextBuffer;
 import com.jediterm.terminal.ui.JediTermWidget;
 import com.jediterm.terminal.ui.TerminalPanel;
 import com.jediterm.terminal.ui.settings.DefaultSettingsProvider;
+import com.jediterm.terminal.ui.settings.SettingsProvider;
 import com.pty4j.PtyProcess;
 import com.pty4j.PtyProcessBuilder;
 import com.pty4j.WinSize;
+import java.awt.Font;
 import java.awt.Frame;
+import java.awt.GraphicsConfiguration;
+import java.awt.GraphicsEnvironment;
 import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
 import java.nio.charset.StandardCharsets;
 import java.util.HashMap;
 import java.util.Map;
@@ -49,6 +56,8 @@ import org.eclipse.swt.layout.FormAttachment;
 import org.eclipse.swt.layout.FormData;
 import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Shell;
 
 /** JediTerm-based terminal widget using SWT-AWT bridge for embedding AWT 
components in SWT. */
 public class JediTerminalWidget implements ITerminalWidget {
@@ -61,6 +70,12 @@ public class JediTerminalWidget implements ITerminalWidget {
   /** Font scale percent (100 = base size). Mutable so toolbar +/- can update 
all tabs. */
   private final AtomicInteger fontScalePercent = new AtomicInteger(100);
 
+  /**
+   * Makes up for the desktop scale AWT does not follow on Linux. Set on the 
SWT thread, read by the
+   * settings provider on the AWT thread.
+   */
+  private volatile float hiDpiFontScale = 1.0f;
+
   private Composite bridgeComposite;
   private Frame awtFrame;
   private JediTermWidget jediTermWidget;
@@ -113,6 +128,8 @@ public class JediTerminalWidget implements ITerminalWidget {
           if (bridgeComposite.isDisposed() || awtFrame == null) {
             return;
           }
+          // the tab now has its place on a monitor
+          updateHiDpiFontScale();
           try {
             Rectangle rect = bridgeComposite.getClientArea();
             java.awt.EventQueue.invokeLater(
@@ -131,10 +148,32 @@ public class JediTerminalWidget implements 
ITerminalWidget {
           }
         });
 
+    // Moved to a monitor with another scale
+    Shell shell = bridgeComposite.getShell();
+    Listener shellMoved = event -> updateHiDpiFontScale();
+    shell.addListener(SWT.Move, shellMoved);
+    bridgeComposite.addListener(
+        SWT.Dispose,
+        event -> {
+          if (!shell.isDisposed()) {
+            shell.removeListener(SWT.Move, shellMoved);
+          }
+        });
+    hiDpiFontScale = computeHiDpiFontScale();
+
     // Create JediTerm widget with Hop dark mode support
     boolean isDarkMode = PropsUi.getInstance().isDarkMode();
     DefaultSettingsProvider settings = createHopSettingsProvider(isDarkMode, 
display);
-    jediTermWidget = new JediTermWidget(settings);
+    jediTermWidget =
+        new JediTermWidget(settings) {
+          @Override
+          protected TerminalPanel createTerminalPanel(
+              SettingsProvider settingsProvider,
+              StyleState styleState,
+              TerminalTextBuffer terminalTextBuffer) {
+            return new FallbackFontTerminalPanel(settingsProvider, 
terminalTextBuffer, styleState);
+          }
+        };
     awtFrame.add(jediTermWidget);
 
     awtFrame.setVisible(true);
@@ -205,6 +244,57 @@ public class JediTerminalWidget implements ITerminalWidget 
{
     }
   }
 
+  /**
+   * On Linux, SWT follows the desktop scale but AWT does not, so on a HiDPI 
screen the terminal
+   * font comes out smaller than the rest of Hop. Return the factor that makes 
up the difference,
+   * see {@link TerminalFonts#hiDpiScale(int, int, double)}. On Windows and 
macOS AWT scales itself,
+   * so the factor is 1.
+   */
+  private float computeHiDpiFontScale() {
+    if (!Const.isLinux() || bridgeComposite.isDisposed()) {
+      return 1.0f;
+    }
+    try {
+      // the configuration of the embedded frame once it has one: the screen 
the terminal is on
+      GraphicsConfiguration configuration =
+          awtFrame == null ? null : awtFrame.getGraphicsConfiguration();
+      if (configuration == null) {
+        configuration =
+            GraphicsEnvironment.getLocalGraphicsEnvironment()
+                .getDefaultScreenDevice()
+                .getDefaultConfiguration();
+      }
+      double awtScale = configuration.getDefaultTransform().getScaleX();
+      int swtZoom = bridgeComposite.getMonitor().getZoom();
+      int swtDpi = bridgeComposite.getDisplay().getDPI().x;
+      float scale = TerminalFonts.hiDpiScale(swtZoom, swtDpi, awtScale);
+      if (Math.abs(scale - hiDpiFontScale) > 0.01f) {
+        log.logDetailed(
+            "JediTerm: SWT zoom "
+                + swtZoom
+                + "%, SWT DPI "
+                + swtDpi
+                + ", AWT scale "
+                + awtScale
+                + ", font scale "
+                + scale);
+      }
+      return scale;
+    } catch (Exception e) {
+      log.logDebug("Could not determine HiDPI font scale: " + e.getMessage());
+      return 1.0f;
+    }
+  }
+
+  /** Recompute the HiDPI font scale, and redraw the terminal when it changed. 
*/
+  private void updateHiDpiFontScale() {
+    float scale = computeHiDpiFontScale();
+    if (Math.abs(scale - hiDpiFontScale) > 0.01f) {
+      hiDpiFontScale = scale;
+      reinitFont();
+    }
+  }
+
   /**
    * Create SettingsProvider with Hop theme and fixed-width font; font size 
uses fontScalePercent.
    */
@@ -229,23 +319,24 @@ public class JediTerminalWidget implements 
ITerminalWidget {
 
     return new DefaultSettingsProvider() {
       private int computeFontSize() {
-        return Math.round(baseFontHeight * (fontScalePercent.get() / 100f) * 
systemPropScale);
+        return Math.round(
+            baseFontHeight * (fontScalePercent.get() / 100f) * systemPropScale 
* hiDpiFontScale);
       }
 
       @Override
       public TerminalColor getDefaultBackground() {
         if (Const.isWindows() && !isDarkMode) {
           // Windows light mode: PowerShell blue background
-          return new TerminalColor(1, 36, 86);
+          return TerminalColor.rgb(1, 36, 86);
         } else if (Const.isWindows() && isDarkMode) {
           // Windows dark mode: dark gray background
-          return new TerminalColor(43, 43, 43);
+          return TerminalColor.rgb(43, 43, 43);
         } else if (isDarkMode) {
           // Mac/Linux dark mode: dark gray background
-          return new TerminalColor(43, 43, 43);
+          return TerminalColor.rgb(43, 43, 43);
         } else {
           // Mac/Linux light mode: white background
-          return new TerminalColor(255, 255, 255);
+          return TerminalColor.rgb(255, 255, 255);
         }
       }
 
@@ -253,16 +344,16 @@ public class JediTerminalWidget implements 
ITerminalWidget {
       public TerminalColor getDefaultForeground() {
         if (Const.isWindows() && !isDarkMode) {
           // Windows light mode: PowerShell gray foreground
-          return new TerminalColor(204, 204, 204);
+          return TerminalColor.rgb(204, 204, 204);
         } else if (Const.isWindows() && isDarkMode) {
           // Windows dark mode: light gray foreground
-          return new TerminalColor(187, 187, 187);
+          return TerminalColor.rgb(187, 187, 187);
         } else if (isDarkMode) {
           // Mac/Linux dark mode: light gray foreground
-          return new TerminalColor(187, 187, 187);
+          return TerminalColor.rgb(187, 187, 187);
         } else {
           // Mac/Linux light mode: black foreground
-          return new TerminalColor(0, 0, 0);
+          return TerminalColor.rgb(0, 0, 0);
         }
       }
 
@@ -278,15 +369,15 @@ public class JediTerminalWidget implements 
ITerminalWidget {
 
       @Override
       public TextStyle getFoundPatternColor() {
-        TerminalColor bg = new TerminalColor(255, 255, 0);
-        TerminalColor fg = new TerminalColor(0, 0, 0);
+        TerminalColor bg = TerminalColor.rgb(255, 255, 0);
+        TerminalColor fg = TerminalColor.rgb(0, 0, 0);
         return new TextStyle(fg, bg);
       }
 
       @Override
       public TextStyle getHyperlinkColor() {
         TerminalColor linkColor =
-            isDarkMode ? new TerminalColor(96, 161, 255) : new 
TerminalColor(0, 0, 238);
+            isDarkMode ? TerminalColor.rgb(96, 161, 255) : 
TerminalColor.rgb(0, 0, 238);
         return new TextStyle(linkColor, null);
       }
 
@@ -306,11 +397,15 @@ public class JediTerminalWidget implements 
ITerminalWidget {
   public void setFontScalePercent(int percent) {
     int clamped = Math.clamp(percent, 50, 200);
     fontScalePercent.set(clamped);
+    reinitFont();
+  }
+
+  private void reinitFont() {
     if (jediTermWidget == null) {
       return;
     }
-    // The DefaultSettingsProvider already reads fontScalePercent via 
computeFontSize(),
-    // so updating the AtomicInteger is enough for the provider. We now need 
to tell
+    // The DefaultSettingsProvider already reads fontScalePercent and 
hiDpiFontScale via
+    // computeFontSize(), so updating those is enough for the provider. We now 
need to tell
     // TerminalPanel to re-read the font from the provider and recalculate its 
character
     // grid. TerminalPanel.reinitFontAndResize() does exactly that but is 
protected,
     // so we call it via reflection.
@@ -402,19 +497,16 @@ public class JediTerminalWidget implements 
ITerminalWidget {
         bridgeComposite.dispose();
       }
 
-      // Clean up PTY in background thread
+      // Clean up in a background thread. close() (not stop()) also closes the 
connector, which
+      // destroys the shell, and shuts down JediTerm's executor threads and 
repaint timer.
       final JediTermWidget termWidget = jediTermWidget;
-      final Pty4JTtyConnector connector = ttyConnector;
       final PtyProcess process = ptyProcess;
 
       new Thread(
               () -> {
                 try {
                   if (termWidget != null) {
-                    termWidget.stop();
-                  }
-                  if (connector != null) {
-                    connector.close();
+                    termWidget.close();
                   }
                   if (process != null && process.isAlive()) {
                     process.destroy();
@@ -461,74 +553,81 @@ public class JediTerminalWidget implements 
ITerminalWidget {
     return workingDirectory;
   }
 
-  /** Adapter connecting Pty4J to JediTerm's TtyConnector */
-  private static class Pty4JTtyConnector implements TtyConnector {
+  /**
+   * TerminalPanel that falls back to another installed font for characters 
the terminal font cannot
+   * draw. On Linux, Java's logical Monospaced font leaves out the fallback 
fonts fontconfig would
+   * use, so CJK and similar characters otherwise render as empty boxes.
+   */
+  private static class FallbackFontTerminalPanel extends TerminalPanel {
 
-    private final PtyProcess ptyProcess;
-    private final InputStream inputStream;
-    private final OutputStream outputStream;
+    /** The fallback fonts at the size and style they are drawn in. Only used 
on the AWT thread. */
+    private final Map<DerivedFontKey, Font> derivedFonts = new HashMap<>();
 
-    public Pty4JTtyConnector(PtyProcess ptyProcess) {
-      this.ptyProcess = ptyProcess;
-      this.inputStream = ptyProcess.getInputStream();
-      this.outputStream = ptyProcess.getOutputStream();
-    }
+    private record DerivedFontKey(Font fallback, int style, float size) {}
 
-    public boolean init() {
-      return true;
+    FallbackFontTerminalPanel(
+        SettingsProvider settingsProvider,
+        TerminalTextBuffer terminalTextBuffer,
+        StyleState styleState) {
+      super(settingsProvider, terminalTextBuffer, styleState);
     }
 
-    public void close() {
-      try {
-        if (ptyProcess != null && ptyProcess.isAlive()) {
-          ptyProcess.destroy();
-        }
-      } catch (Exception e) {
-        log.logError("Error closing Pty4J connector", e);
+    @Override
+    protected Font getFontToDisplay(char[] text, int start, int end, TextStyle 
style) {
+      Font font = super.getFontToDisplay(text, start, end, style);
+      if (font.canDisplayUpTo(text, start, end) == -1) {
+        return font;
       }
+      return TerminalFonts.INSTANCE
+          .fallbackFor(text, start, end, this::repaint)
+          .map(
+              fallback ->
+                  derivedFonts.computeIfAbsent(
+                      new DerivedFontKey(fallback, font.getStyle(), 
font.getSize2D()),
+                      key -> key.fallback().deriveFont(key.style(), 
key.size())))
+          .orElse(font);
     }
+  }
 
-    public String getName() {
-      return "Pty4J Connector";
-    }
-
-    public int read(char[] buf, int offset, int length) throws IOException {
-      byte[] bytes = new byte[length];
-      int bytesRead = inputStream.read(bytes, 0, length);
-      if (bytesRead > 0) {
-        String str = new String(bytes, 0, bytesRead, StandardCharsets.UTF_8);
-        char[] chars = str.toCharArray();
-        System.arraycopy(chars, 0, buf, offset, Math.min(chars.length, 
length));
-        return chars.length;
-      }
-      return bytesRead;
-    }
-
-    public void write(byte[] bytes) throws IOException {
-      outputStream.write(bytes);
-      outputStream.flush();
-    }
+  /**
+   * Adapter connecting Pty4J to JediTerm's TtyConnector. ProcessTtyConnector 
decodes the output
+   * with a stateful reader, so multi-byte characters split across reads stay 
intact.
+   */
+  private static class Pty4JTtyConnector extends ProcessTtyConnector
+      implements TtyConnectorResizeStrategyProvider {
 
-    public boolean isConnected() {
-      return ptyProcess != null && ptyProcess.isAlive();
-    }
+    private final PtyProcess ptyProcess;
 
-    public void write(String string) throws IOException {
-      write(string.getBytes(StandardCharsets.UTF_8));
+    public Pty4JTtyConnector(PtyProcess ptyProcess) {
+      super(ptyProcess, StandardCharsets.UTF_8);
+      this.ptyProcess = ptyProcess;
     }
 
-    public int waitFor() throws InterruptedException {
-      return ptyProcess.waitFor();
+    @Override
+    public String getName() {
+      return "Pty4J Connector";
     }
 
-    public boolean ready() throws IOException {
-      return inputStream.available() > 0;
+    /**
+     * Pass the terminal size on to the PTY so the shell wraps lines at the 
visible width. JediTerm
+     * only calls this overload; its default implementation throws.
+     */
+    /**
+     * Windows ConPTY may redraw the screen buffer on a resize. Arriving on a 
buffer that was just
+     * resized, that pushes lines into the scrollback, so JediTerm resizes it 
a little later.
+     */
+    @Override
+    public TtyConnectorResizeStrategy getResizeStrategy() {
+      return Const.isWindows()
+          ? TtyConnectorResizeStrategy.POSTPONED
+          : TtyConnectorResizeStrategy.IMMEDIATE;
     }
 
-    public void resize(int cols, int rows) {
-      if (ptyProcess != null && ptyProcess.isAlive()) {
+    @Override
+    public void resize(TermSize termSize) {
+      if (ptyProcess.isAlive()) {
         try {
-          ptyProcess.setWinSize(new WinSize(cols, rows));
+          ptyProcess.setWinSize(new WinSize(termSize.getColumns(), 
termSize.getRows()));
         } catch (Exception e) {
           log.logError("Error resizing PTY", e);
         }
diff --git 
a/ui/src/main/java/org/apache/hop/ui/hopgui/terminal/TerminalFonts.java 
b/ui/src/main/java/org/apache/hop/ui/hopgui/terminal/TerminalFonts.java
new file mode 100644
index 0000000000..b597e17a58
--- /dev/null
+++ b/ui/src/main/java/org/apache/hop/ui/hopgui/terminal/TerminalFonts.java
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hop.ui.hopgui.terminal;
+
+import java.awt.Font;
+import java.awt.GraphicsEnvironment;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+/** Font size and font fallback of the JediTerm terminal. */
+final class TerminalFonts {
+
+  /** The resolution AWT and SWT treat as a scale of 1. */
+  static final float BASE_DPI = 96f;
+
+  /** Java's logical fonts: the terminal font is one of them, so they make 
poor fallbacks. */
+  private static final Set<String> LOGICAL_FAMILIES =
+      Set.of("dialog", "dialoginput", "monospaced", "serif", "sansserif");
+
+  /** The fonts that worked most recently, tried before any scan. */
+  private static final int RECENT_FONTS = 8;
+
+  /** Shared by every terminal tab. */
+  static final TerminalFonts INSTANCE =
+      new TerminalFonts(
+          () -> 
GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(),
+          family -> new Font(family, Font.PLAIN, 1),
+          Executors.newSingleThreadExecutor(
+              runnable -> {
+                Thread thread = new Thread(runnable, 
"hop-terminal-font-fallback");
+                thread.setDaemon(true);
+                return thread;
+              }));
+
+  private final Supplier<String[]> families;
+  private final Function<String, Font> fontOfFamily;
+  private final Executor scanner;
+
+  /** The fallback per grapheme cluster; empty when no installed font can draw 
the cluster. */
+  private final Map<String, Optional<Font>> byCluster = new 
ConcurrentHashMap<>();
+
+  private final Set<String> scanning = ConcurrentHashMap.newKeySet();
+  private final List<Font> recent = new CopyOnWriteArrayList<>();
+
+  TerminalFonts(
+      Supplier<String[]> families, Function<String, Font> fontOfFamily, 
Executor scanner) {
+    this.families = families;
+    this.fontOfFamily = fontOfFamily;
+    this.scanner = scanner;
+  }
+
+  /**
+   * The factor by which the AWT terminal font has to grow to match the rest 
of Hop on Linux. SWT
+   * follows the desktop scale in two ways: the GDK scale factor (the monitor 
zoom) and the font
+   * resolution of the session ({@code Xft.dpi}, the GNOME text scaling 
factor), which only shows in
+   * the DPI. AWT follows neither, apart from its own scale. GTK4 reports a 
fixed 96 DPI, so the
+   * zoom still counts.
+   *
+   * @param swtZoom the zoom of the monitor in percent
+   * @param swtDpi the horizontal DPI of the SWT display
+   * @param awtScale the scale of the AWT graphics configuration
+   */
+  static float hiDpiScale(int swtZoom, int swtDpi, double awtScale) {
+    float swtScale = Math.max(swtZoom / 100f, swtDpi / BASE_DPI);
+    if (swtScale <= 0f || Float.isNaN(swtScale)) {
+      swtScale = 1f;
+    }
+    double scale = awtScale > 0 ? awtScale : 1.0;
+    return (float) (swtScale / scale);
+  }
+
+  /**
+   * An installed font that draws the grapheme cluster {@code text[start, 
end)}, which the terminal
+   * font cannot draw. A font that worked for an earlier cluster is tried 
first: one font usually
+   * covers a whole script. Otherwise the installed fonts are scanned in the 
background, never on
+   * the paint thread, and {@code onFound} is called once a font is found, to 
repaint.
+   *
+   * @return the font, or empty while the scan runs or when no installed font 
draws the cluster
+   */
+  Optional<Font> fallbackFor(char[] text, int start, int end, Runnable 
onFound) {
+    String cluster = new String(text, start, end - start);
+    Optional<Font> known = byCluster.get(cluster);
+    if (known != null) {
+      return known;
+    }
+    for (Font font : recent) {
+      if (font.canDisplayUpTo(cluster) == -1) {
+        Optional<Font> found = Optional.of(font);
+        byCluster.put(cluster, found);
+        return found;
+      }
+    }
+    if (scanning.add(cluster)) {
+      scanner.execute(
+          () -> {
+            try {
+              Optional<Font> found = scan(cluster);
+              found.ifPresent(this::remember);
+              byCluster.put(cluster, found);
+              if (found.isPresent()) {
+                onFound.run();
+              }
+            } finally {
+              scanning.remove(cluster);
+            }
+          });
+    }
+    return Optional.empty();
+  }
+
+  /**
+   * The first installed font that draws the cluster: a monospaced one if 
there is one, then any
+   * other, and Java's logical fonts last.
+   */
+  private Optional<Font> scan(String cluster) {
+    Font other = null;
+    Font logical = null;
+    for (String family : families.get()) {
+      Font candidate = fontOfFamily.apply(family);
+      if (candidate.canDisplayUpTo(cluster) != -1) {
+        continue;
+      }
+      String name = family.toLowerCase(Locale.ROOT);
+      if (LOGICAL_FAMILIES.contains(name)) {
+        if (logical == null) {
+          logical = candidate;
+        }
+      } else if (name.contains("mono")) {
+        return Optional.of(candidate);
+      } else if (other == null) {
+        other = candidate;
+      }
+    }
+    return Optional.ofNullable(other != null ? other : logical);
+  }
+
+  private void remember(Font font) {
+    if (recent.contains(font)) {
+      return;
+    }
+    recent.add(0, font);
+    while (recent.size() > RECENT_FONTS) {
+      recent.remove(recent.size() - 1);
+    }
+  }
+}
diff --git 
a/ui/src/test/java/org/apache/hop/ui/hopgui/terminal/TerminalFontsTest.java 
b/ui/src/test/java/org/apache/hop/ui/hopgui/terminal/TerminalFontsTest.java
new file mode 100644
index 0000000000..4d8be55154
--- /dev/null
+++ b/ui/src/test/java/org/apache/hop/ui/hopgui/terminal/TerminalFontsTest.java
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hop.ui.hopgui.terminal;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.awt.Font;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.junit.jupiter.api.Test;
+
+class TerminalFontsTest {
+
+  /** The installed fonts of the test, each with the characters it can draw. */
+  private final Map<String, String> installed = new LinkedHashMap<>();
+
+  private final AtomicInteger scans = new AtomicInteger();
+  private final AtomicInteger repaints = new AtomicInteger();
+  private final List<Runnable> pendingScans = new ArrayList<>();
+
+  private final TerminalFonts fonts =
+      new TerminalFonts(
+          () -> {
+            scans.incrementAndGet();
+            return installed.keySet().toArray(new String[0]);
+          },
+          family -> font(family, installed.get(family)),
+          pendingScans::add);
+
+  @Test
+  void theScaleFollowsTheZoomAndTheFontResolutionOfTheDesktop() {
+    assertEquals(1.0f, TerminalFonts.hiDpiScale(100, 96, 1.0));
+    // Xft.dpi 192 or a GNOME text scaling factor of 2, with a GDK scale 
factor of 1
+    assertEquals(2.0f, TerminalFonts.hiDpiScale(100, 192, 1.0));
+    // GDK_SCALE=2, or GTK4, which reports 96 DPI
+    assertEquals(2.0f, TerminalFonts.hiDpiScale(200, 96, 1.0));
+    // AWT scales by itself as well
+    assertEquals(1.0f, TerminalFonts.hiDpiScale(200, 192, 2.0));
+    // AWT scales more than SWT: the font has to shrink, not stay at its size
+    assertEquals(0.5f, TerminalFonts.hiDpiScale(100, 96, 2.0));
+    // nonsense from the platform does not break the font
+    assertEquals(1.0f, TerminalFonts.hiDpiScale(0, 0, 0));
+  }
+
+  @Test
+  void theFontsAreScannedOffThePaintThreadAndTheTerminalIsRepainted() {
+    installed.put("CJK Mono", "中");
+
+    assertEquals(Optional.empty(), fallbackFor("中"), "found on the paint 
thread");
+    assertEquals(0, scans.get());
+
+    runPendingScans();
+    assertEquals(1, repaints.get());
+    assertEquals("CJK Mono", fallbackFor("中").orElseThrow().getName());
+  }
+
+  @Test
+  void aClusterIsScannedOnceWhileItsScanIsPending() {
+    installed.put("CJK Mono", "中");
+    fallbackFor("中");
+    fallbackFor("中");
+    assertEquals(1, pendingScans.size());
+  }
+
+  @Test
+  void aClusterNoFontCanDrawDoesNotHideItsBaseCharacter() {
+    installed.put("CJK Mono", "中");
+
+    // an ideograph with a variation selector no installed font has
+    fallbackFor("中️");
+    runPendingScans();
+    assertEquals(Optional.empty(), fallbackFor("中️"));
+
+    fallbackFor("中");
+    runPendingScans();
+    assertEquals("CJK Mono", fallbackFor("中").orElseThrow().getName());
+  }
+
+  @Test
+  void theFontThatWorkedIsTriedBeforeScanningAgain() {
+    installed.put("Other", "x");
+    installed.put("CJK Mono", "中文字");
+    fallbackFor("中");
+    runPendingScans();
+
+    // the next ideograph of the same script is found at once, without a scan
+    assertEquals("CJK Mono", fallbackFor("文").orElseThrow().getName());
+    assertEquals(1, scans.get());
+  }
+
+  @Test
+  void aClusterNoFontCanDrawIsScannedOnlyOnce() {
+    installed.put("CJK Mono", "中");
+    fallbackFor("☃");
+    runPendingScans();
+    fallbackFor("☃");
+    fallbackFor("☃");
+    assertTrue(pendingScans.isEmpty());
+    assertEquals(1, scans.get());
+    assertEquals(0, repaints.get());
+  }
+
+  @Test
+  void aMonospacedFontIsPreferredOverLogicalAndProportionalFonts() {
+    installed.put("Monospaced", "中");
+    installed.put("Dialog", "中");
+    installed.put("Noto Sans CJK", "中");
+    installed.put("Noto Sans Mono CJK", "中");
+    assertEquals("Noto Sans Mono CJK", scanFor("中"));
+
+    installed.remove("Noto Sans Mono CJK");
+    assertEquals("Noto Sans CJK", scanFor("文中"), "a real font beats a logical 
one");
+  }
+
+  @Test
+  void aLogicalFontIsTheLastResort() {
+    installed.put("Dialog", "中");
+    assertEquals("Dialog", scanFor("中"));
+  }
+
+  private String scanFor(String cluster) {
+    TerminalFonts fresh =
+        new TerminalFonts(
+            () -> installed.keySet().toArray(new String[0]),
+            family -> font(family, installed.get(family) + cluster),
+            Runnable::run);
+    char[] text = cluster.toCharArray();
+    fresh.fallbackFor(text, 0, text.length, () -> {});
+    return fresh.fallbackFor(text, 0, text.length, () -> 
{}).orElseThrow().getName();
+  }
+
+  private Optional<Font> fallbackFor(String cluster) {
+    // the cluster sits in the middle of a line, as when the terminal draws it
+    char[] line = ("ab" + cluster + "cd").toCharArray();
+    return fonts.fallbackFor(line, 2, 2 + cluster.length(), 
repaints::incrementAndGet);
+  }
+
+  private void runPendingScans() {
+    List<Runnable> scansToRun = new ArrayList<>(pendingScans);
+    pendingScans.clear();
+    scansToRun.forEach(Runnable::run);
+    assertFalse(scansToRun.isEmpty(), "no scan was started");
+  }
+
+  /** A font that draws exactly the given characters. */
+  private static Font font(String family, String drawable) {
+    return new Font(family, Font.PLAIN, 1) {
+      @Override
+      public int canDisplayUpTo(String text) {
+        for (int i = 0; i < text.length(); i++) {
+          if (drawable.indexOf(text.charAt(i)) < 0) {
+            return i;
+          }
+        }
+        return -1;
+      }
+    };
+  }
+}

Reply via email to