From 091f271aa11a18e6d7d05eb2887d95b9a6447946 Mon Sep 17 00:00:00 2001 From: Rene Hopf Date: Thu, 12 Nov 2026 01:44:31 +0100 Subject: [PATCH 1/3] HiDPI: scale the Tk GUIs, the G-code preview and PyVCP On a HiDPI desktop the X server (or XWayland with native scaling) reports an ordinary 96 dpi screen and announces the scale only through the Xft.dpi resource, e.g. 192 for 200 %. Tk's text follows Xft.dpi, but nothing else did: widget sizes, borders, sliders and scrollbars, fixed window sizes, images, the preview's lines, DRO text and icons, and PyVCP's drawn widgets all came out at their 96 dpi size. Tk: - tcl/hidpi.tcl reads Xft.dpi (LINUXCNC_UI_SCALE overrides it, 1 disables), sets tk scaling and scales the pixel defaults of the Tk and BWidget widgets through the option database, below ~/.Xresources and a program's own settings. It also offers scale and scale_image for programs' own pixel sizes and images. - linuxcnc.tcl turns it on when Tk is loaded, so the Tcl tools get it; halshow, emccalib and halconfig, which load Tk after it, call it themselves. nf.init_hidpi() does the same for Python Tk programs. - pickconfig, halshow (window, sidebar, tree rows, watch canvas) and the splash screen scale their own pixel sizes and images; AXIS scales its toolbar and other icons. - linuxcnctop's name column and the vismach window scale. Preview: - glcanon_gl.set_line_scale() widens every line the preview draws, and build_atlas() takes a scale for the DRO font; the DRO's home/limit icons and offsets follow the font's scale. - AXIS sets both from the Tk factor. gremlin follows the GTK window's scale factor, checked every frame. PyVCP: - Panels scale their XML pixel sizes, line widths and images, embedded in AXIS or run standalone. Point-size fonts are left alone, as Tk already scales them. At 96 dpi, or without Xft.dpi as under Xvfb, the factor is 1 and nothing changes. --- lib/python/glnav.py | 7 +- lib/python/nf.py.in | 10 ++ lib/python/pyvcp_widgets.py | 99 +++++++++---- lib/python/rs274/glcanon_gl.py | 62 ++++++-- lib/python/rs274/glcanon_scene.py | 24 +-- lib/python/vcpparse.py | 2 + lib/python/vismach.py | 6 +- share/axis/tcl/support.tcl | 3 + src/emc/usr_intf/axis/scripts/axis.py | 10 +- src/emc/usr_intf/axis/scripts/linuxcnctop.py | 10 +- src/emc/usr_intf/gremlin/gremlin.py | 26 +++- tcl/bin/emccalib.tcl | 3 + tcl/bin/halconfig.tcl | 3 + tcl/bin/halshow.tcl | 52 +++++-- tcl/bin/pickconfig.tcl | 4 +- tcl/bin/popimage | 6 +- tcl/hidpi.tcl | 146 +++++++++++++++++++ tcl/linuxcnc.tcl.in | 11 +- 18 files changed, 402 insertions(+), 82 deletions(-) create mode 100644 tcl/hidpi.tcl diff --git a/lib/python/glnav.py b/lib/python/glnav.py index 478a0d666c8..ff8dfa6da9a 100644 --- a/lib/python/glnav.py +++ b/lib/python/glnav.py @@ -2,7 +2,7 @@ import numpy as np -def use_pango_font(font, start, count, will_call_prepost=False): +def use_pango_font(font, start, count, will_call_prepost=False, scale=1.0): """Build a glyph-atlas font for the OpenGL 3.3 core overlay renderer. Signature preserved for callers (axis.py, gremlin.py, qt5_graphics.py): @@ -10,9 +10,12 @@ def use_pango_font(font, start, count, will_call_prepost=False): ``rs274.glcanon_gl.GlyphAtlas`` (a texture atlas + overlay shader) instead of a per-glyph display-list base; consumers pass it through get_font_info() to the shared overlay pass, which draws text as textured quads. + + ``scale`` multiplies the font size, for HiDPI displays where the GL + surface is in device pixels but Pango assumes 96 dpi. """ from rs274 import glcanon_gl - atlas = glcanon_gl.build_atlas(font, start, count) + atlas = glcanon_gl.build_atlas(font, start, count, scale) return atlas, atlas.char_width, atlas.line_space diff --git a/lib/python/nf.py.in b/lib/python/nf.py.in index f2467613532..fac078e3390 100644 --- a/lib/python/nf.py.in +++ b/lib/python/nf.py.in @@ -112,7 +112,17 @@ tcl_libdir = os.path.join(SHARE, "tcl") def source_lib_tcl(r, f): r.tk.call("source", os.path.join(tcl_libdir, f)) +def init_hidpi(r): + """Scale Tk to the desktop's HiDPI factor (Xft.dpi) - tk scaling and the + pixel defaults of the Tk widgets, see tcl/hidpi.tcl - and return the + factor (1.0 when unscaled). Call before creating widgets. Safe to call + again: later calls only return the factor.""" + if not r.tk.call("info", "commands", "linuxcnc::hidpi::init"): + r.tk.call("source", os.path.join(EMC2_TCL_DIR, "hidpi.tcl")) + return float(r.tk.call("linuxcnc::hidpi::init")) + def start(r): + init_hidpi(r) r.tk.call("set", "imagedir", os.path.join(SHARE, "images")) r.tk.call("lappend", "auto_path", os.path.join(tcl_libdir, "bwidget")) r.tk.call("lappend", "auto_path", "/usr/lib") diff --git a/lib/python/pyvcp_widgets.py b/lib/python/pyvcp_widgets.py index ea9ee969346..ea9256b77f9 100644 --- a/lib/python/pyvcp_widgets.py +++ b/lib/python/pyvcp_widgets.py @@ -54,6 +54,31 @@ import bwidget import time +# HiDPI scale factor (1.0 = 96 dpi). Sizes in the panel XML, and the fixed +# sizes below, are 96 dpi pixels; _px() turns them into screen pixels. Fonts +# given in points need no scaling: Tk's Xft font code already follows the +# desktop scale. Set by init_hidpi(), which vcpparse.create_vcp() calls. +_scale = 1.0 + +def init_hidpi(master): + """Load LinuxCNC's Tk HiDPI support into ``master``'s interpreter (if + the host program, e.g. AXIS, has not already) and take its factor.""" + global _scale + try: + import nf + _scale = nf.init_hidpi(master) + except Exception as e: + print("pyvcp: HiDPI scaling unavailable:", e, file=sys.stderr) + _scale = 1.0 + +def _px(v): + """A 96 dpi pixel size in screen pixels.""" + return v * _scale + +def _ipx(v): + """_px() rounded, for options Tk wants as whole pixels.""" + return int(round(v * _scale)) + # ------------------------------------------- @@ -118,6 +143,7 @@ def __init__(self,root,pycomp,halpin=None,halparam=None,param_pin=0,size=200,cpr text=None,initval=0,resolution=0.1, \ **kw): + size=_px(size) pad=size/10 self.counts = int(round(initval/resolution)) @@ -128,7 +154,7 @@ def __init__(self,root,pycomp,halpin=None,halparam=None,param_pin=0,size=200,cpr Canvas.__init__(self,root,width=size,height=size) pad2=pad-size/15 - self.circle2=self.create_oval(pad2,pad2,size-pad2,size-pad2,width=3)# edge circle + self.circle2=self.create_oval(pad2,pad2,size-pad2,size-pad2,width=_px(3))# edge circle self.itemconfig(self.circle2,fill=edgecolor,activefill=edgecolor) self.circle=self.create_oval(pad,pad,size-pad,size-pad) # dial circle @@ -153,8 +179,8 @@ def __init__(self,root,pycomp,halpin=None,halparam=None,param_pin=0,size=200,cpr self.mid+(self.r*1)*math.sin(self.alfa), \ self.mid+(self.r*1.1)*math.cos(self.alfa), \ self.mid+(self.r*1.1)*math.sin(self.alfa)) - self.itemconfig(self.line,arrow="last",arrowshape=(10,10,10)) - self.itemconfig(self.line,width=10) + self.itemconfig(self.line,arrow="last",arrowshape=(_px(10),_px(10),_px(10))) + self.itemconfig(self.line,width=_px(10)) #TJP items get rendered in order of creation, so the knob will be behind these texts #TJP the font can be described with pixel size by using negative value @@ -324,10 +350,10 @@ def draw_ticks(self,cpr): starty=self.mid+self.r*math.sin((n+i)*self.d_alfa) if i == 0: length = 1.15 - width = 2 + width = _px(2) else: length = 1.1 - width = 1 + width = _px(1) stopx=self.mid+length*self.r*math.cos((n+i)*self.d_alfa) stopy=self.mid+length*self.r*math.sin((n+i)*self.d_alfa) self.create_line(startx,starty,stopx,stopy,width=width) @@ -366,8 +392,11 @@ class pyvcp_meter(Canvas): # FIXME: logarithmic scale option n=0 def __init__(self,root,pycomp,halpin=None, size=200,text=None,subtext=None,min_=0,max_=100,majorscale=None, minorscale=None,region1=None,region2=None,region3=None,**kw): + # fonts are in points, sized from the unscaled size (see _scale) + self.font_size = size + size = _px(size) self.size = size - self.pad=10 + self.pad=_px(10) Canvas.__init__(self,root,width=size,height=size) self.halpin=halpin self.min_=min_ @@ -375,7 +404,7 @@ def __init__(self,root,pycomp,halpin=None, size=200,text=None,subtext=None,min_= range_=2.5 self.min_alfa=-math.pi/2-range_ self.max_alfa=-math.pi/2+range_ - self.circle=self.create_oval(self.pad,self.pad,size-self.pad,size-self.pad, width=2) + self.circle=self.create_oval(self.pad,self.pad,size-self.pad,size-self.pad, width=_px(2)) self.itemconfig(self.circle,fill="white") self.mid=size/2 self.r=(size-2*self.pad)/2 @@ -388,15 +417,15 @@ def __init__(self,root,pycomp,halpin=None, size=200,text=None,subtext=None,min_= self.majorscale=float((self.max_-self.min_)/10) else: self.majorscale=majorscale - if text!=None: t=self.create_text([self.mid,self.mid-size/12],font="Arial %d bold" % (size/10),text=text) - if subtext!=None: t=self.create_text([self.mid,self.mid+size/12],font="Arial %d" % (size/30+5),text=subtext) + if text!=None: t=self.create_text([self.mid,self.mid-size/12],font="Arial %d bold" % (self.font_size/10),text=text) + if subtext!=None: t=self.create_text([self.mid,self.mid+size/12],font="Arial %d" % (self.font_size/30+5),text=subtext) if region1!=None: self.draw_region(region1) if region2!=None: self.draw_region(region2) if region3!=None: self.draw_region(region3) self.draw_ticks() self.line = self.create_line([self.mid,self.mid, self.mid+self.r*math.cos(self.alfa), self.mid+self.r*math.sin(self.alfa)],fill="red", arrow="last", arrowshape=(0.9*self.r,self.r,self.r/20)) - self.itemconfig(self.line,width=3) + self.itemconfig(self.line,width=_px(3)) # create the hal pin if halpin == None: @@ -447,8 +476,8 @@ def draw_ticks(self): xy1 = self.p2c(1,alfa) xy2 = self.p2c(0.85,alfa) xytext = self.p2c(0.75,alfa) - self.create_text(xytext,font="Arial %d" % (self.size/30+5), text="%g" % value) - self.create_line(xy1, xy2, width=2) + self.create_text(xytext,font="Arial %d" % (self.font_size/30+5), text="%g" % value) + self.create_line(xy1, xy2, width=_px(2)) value = value + self.majorscale #minor ticks value = self.min_ @@ -458,7 +487,7 @@ def draw_ticks(self): alfa = self.value2angle(value) xy1 = self.p2c(1,alfa) xy2 = self.p2c(0.9,alfa) - self.create_line(xy1, xy2) + self.create_line(xy1, xy2, width=_px(1)) value = value + self.minorscale # ------------------------------------------- @@ -489,13 +518,14 @@ class pyvcp_jogwheel(Canvas): def __init__(self,root,pycomp,halpin=None,text=None,clear_pin=0,scale_pin=0, fillcolor="lightgrey",bgcolor="lightgrey",size=200,cpr=40,**kw): + size=_px(size) pad=size/10 self.count=0 self.scale=0.0 self.drotxt=0.0 Canvas.__init__(self,root,width=size,height=size) pad2=pad-size/15 - self.circle2=self.create_oval(pad2,pad2,size-pad2,size-pad2,width=3)# edge circle + self.circle2=self.create_oval(pad2,pad2,size-pad2,size-pad2,width=_px(3))# edge circle self.circle=self.create_oval(pad,pad,size-pad,size-pad) self.itemconfig(self.circle,fill=bgcolor,activefill=fillcolor) self.mid=size/2 @@ -513,8 +543,8 @@ def __init__(self,root,pycomp,halpin=None,text=None,clear_pin=0,scale_pin=0, self.mid+(self.r*1)*math.sin(self.alfa), \ self.mid+(self.r*1.1)*math.cos(self.alfa), \ self.mid+(self.r*1.1)*math.sin(self.alfa)) - self.itemconfig(self.line,arrow="last",arrowshape=(10,10,10)) - self.itemconfig(self.line,width=8) + self.itemconfig(self.line,arrow="last",arrowshape=(_px(10),_px(10),_px(10))) + self.itemconfig(self.line,width=_px(8)) #TJP items get rendered in order of creation, so the knob will be behind these texts #TJP the font can be described with pixel size by using negative value @@ -651,7 +681,7 @@ def draw_ticks(self,cpr): starty=self.mid+self.r*math.sin(n*self.d_alfa) stopx=self.mid+1.15*self.r*math.cos(n*self.d_alfa) stopy=self.mid+1.15*self.r*math.sin(n*self.d_alfa) - self.create_line([startx,starty,stopx,stopy]) + self.create_line([startx,starty,stopx,stopy],width=_px(1)) def update(self,pycomp): if self.scale_pin: @@ -675,7 +705,7 @@ def update(self,pycomp): class pyvcp_radiobutton(Frame): n=0 def __init__(self,master,pycomp,halpin=None,initval=0,orient=None,choices=[],**kw): - f=Frame.__init__(self,master,bd=2,relief=GROOVE) + f=Frame.__init__(self,master,bd=_ipx(2),relief=GROOVE) self.v = IntVar() self.v.set(1) self.choices=choices @@ -1244,10 +1274,10 @@ def __init__(self,master,pycomp,fillcolor="green",bgcolor="grey", range3=None,format='3.1f', canvas_width=200, canvas_height=50, bar_height=30, bar_width=150,**kw): - self.cw=canvas_width - self.ch=canvas_height - self.bh=bar_height - self.bw=bar_width + self.cw=_px(canvas_width) + self.ch=_px(canvas_height) + self.bh=_px(bar_height) + self.bw=_px(bar_width) #self.cw=200 # canvas width #self.ch=50 # canvas height #self.bh=30 # bar height @@ -1271,21 +1301,23 @@ def __init__(self,master,pycomp,fillcolor="green",bgcolor="grey", pycomp[self.halpin] = self.value # the border - border=self.create_rectangle(self.pad,1,self.pad+self.bw,self.bh) + border=self.create_rectangle(self.pad,_px(1),self.pad+self.bw,self.bh, + width=_px(1)) self.itemconfig(border,fill=bgcolor) # the bar tmp=self.bar_coords() start=tmp[0] end=tmp[1] - self.bar=self.create_rectangle(start,2,end,self.bh-1) + self.bar=self.create_rectangle(start,_px(2),end,self.bh-_px(1), + width=_px(1)) # default fill unless overridden self.itemconfig(self.bar,fill=fillcolor) # start text - start_text=self.create_text(self.pad,self.bh+10,text=str(self.startval) ) + start_text=self.create_text(self.pad,self.bh+_px(10),text=str(self.startval) ) #end text - end_text=self.create_text(self.pad+self.bw,self.bh+10,text=str(self.endval) ) + end_text=self.create_text(self.pad+self.bw,self.bh+_px(10),text=str(self.endval) ) # value text self.val_text=self.create_text(self.pad+self.bw/2, self.bh/2,text=str(self.value) ) @@ -1346,8 +1378,8 @@ def update(self,pycomp): tmp=self.bar_coords() start=tmp[0] end=tmp[1] - self.coords(self.bar, start, 2, - end, self.bh-1) + self.coords(self.bar, start, _px(2), + end, self.bh-_px(1)) @@ -1367,12 +1399,13 @@ class pyvcp_led(Canvas): n=0 def __init__(self,master,pycomp, halpin=None,disable_pin=False, off_color="red",on_color="green",disabled_color="gray80",size=20,**kw): + size=_px(size) Canvas.__init__(self,master,width=size,height=size,bd=0) self.off_color=off_color self.on_color=on_color self.disabled_color=disabled_color self.disable_pin = disable_pin - self.oh=self.create_oval(1,1,size,size) + self.oh=self.create_oval(_px(1),_px(1),size,size,width=_px(1)) self.state = 0 self.itemconfig(self.oh,fill=off_color) if halpin == None: @@ -1417,12 +1450,14 @@ class pyvcp_rectled(Canvas): n=0 def __init__(self,master,pycomp, halpin=None,disable_pin=False, off_color="red",on_color="green",disabled_color="gray80",height=10,width=30,**kw): - Canvas.__init__(self,master,width=width,height=height,bd=2) + width=_px(width) + height=_px(height) + Canvas.__init__(self,master,width=width,height=height,bd=_ipx(2)) self.off_color=off_color self.on_color=on_color self.disabled_color=disabled_color self.disable_pin = disable_pin - self.oh=self.create_rectangle(1,1,width,height) + self.oh=self.create_rectangle(_px(1),_px(1),width,height,width=_px(1)) self.state=0 self.itemconfig(self.oh,fill=off_color) if halpin == None: @@ -1785,6 +1820,8 @@ class pyvcp_image(_pyvcp_dummy): all_images = {} def __init__(self, master, pycomp, name, **kw): self.all_images[name] = PhotoImage(name, kw, master) + if _scale != 1.0: + master.tk.call("linuxcnc::hidpi::scale_image", name) class _pyvcp_image(Label): def __init__(self, master, pycomp, images, halpin=None, **kw): diff --git a/lib/python/rs274/glcanon_gl.py b/lib/python/rs274/glcanon_gl.py index aab7dcdbed0..3191f0adeef 100644 --- a/lib/python/rs274/glcanon_gl.py +++ b/lib/python/rs274/glcanon_gl.py @@ -454,6 +454,24 @@ def _try_line_width(w: float) -> bool: #: clamp - see :func:`pending_line_expansion`. _REQUESTED_LINE_WIDTH: float = 1.0 +#: Multiplier applied to every width the scene asks for, so lines keep their +#: apparent thickness on a HiDPI display, where the GL drawable is in device +#: pixels (2 at 200 %). Set once by the GUI through :func:`set_line_scale`. +_LINE_SCALE: float = 1.0 + + +def set_line_scale(scale: float) -> None: + """Scale all line widths by ``scale`` (HiDPI). 1.0 leaves them as asked. + + Discards the width probe, since the widths to probe change with it. + """ + global _LINE_SCALE, _MAX_LINE_WIDTH + scale = max(1.0, float(scale)) + if scale == _LINE_SCALE: + return + _LINE_SCALE = scale + _MAX_LINE_WIDTH = None + #: The context ``_MAX_LINE_WIDTH`` was probed in, or None for "not yet probed". #: The verdict describes a context, not a process - see :func:`_context_token`. _LINE_WIDTH_CONTEXT: int | None = None @@ -531,7 +549,8 @@ def set_line_width(width: float) -> None: context; it does not decide a width. """ global _MAX_LINE_WIDTH, _REQUESTED_LINE_WIDTH, _LINE_WIDTH_CONTEXT - _REQUESTED_LINE_WIDTH = max(1.0, float(width)) + width = max(1.0, float(width)) * _LINE_SCALE + _REQUESTED_LINE_WIDTH = width token = _context_token() # Only a *change* discards. Starting from None adopts the current context # without touching the verdict, so a test that forces _MAX_LINE_WIDTH to @@ -540,9 +559,10 @@ def set_line_width(width: float) -> None: _MAX_LINE_WIDTH = None _LINE_WIDTH_CONTEXT = token if _MAX_LINE_WIDTH is None: - _MAX_LINE_WIDTH = 3.0 if _try_line_width(3.0) else 1.0 - _warn_if_range_disagrees(_MAX_LINE_WIDTH) - w = max(1.0, min(float(width), _MAX_LINE_WIDTH)) + probe = 3.0 * _LINE_SCALE + _MAX_LINE_WIDTH = probe if _try_line_width(probe) else 1.0 + _warn_if_range_disagrees(_MAX_LINE_WIDTH, probe) + w = max(1.0, min(width, _MAX_LINE_WIDTH)) if not _try_line_width(w) and w != 1.0: _MAX_LINE_WIDTH = 1.0 _try_line_width(1.0) @@ -553,7 +573,7 @@ def set_line_width(width: float) -> None: _RANGE_DISAGREEMENT_SEEN: set[int] = set() -def _warn_if_range_disagrees(granted: float) -> None: +def _warn_if_range_disagrees(granted: float, probe: float = 3.0) -> None: """Record, once per context, a probe that refuses a width the reported range covers. @@ -566,21 +586,21 @@ def _warn_if_range_disagrees(granted: float) -> None: ``v3d``, every honest refusal too: it reports ``[1, 1]``, so there is nothing to disagree about. """ - if granted >= 3.0: + if granted >= probe: return reported = _gl_floats(GL_ALIASED_LINE_WIDTH_RANGE, 2, (1.0, 1.0))[1] - if reported < 3.0: + if reported < probe: return token = _context_token() if token in _RANGE_DISAGREEMENT_SEEN: return _RANGE_DISAGREEMENT_SEEN.add(token) log.warning( - "preview: driver refused glLineWidth(3.0) though " + "preview: driver refused glLineWidth(%.1f) though " "GL_ALIASED_LINE_WIDTH_RANGE reports a maximum of %.1f; " "wide lines will be drawn at %.1f. A forward-compatible context " "does this by design; anything else means the width probe read an " - "error it did not cause.", reported, granted) + "error it did not cause.", probe, reported, granted) def pending_line_expansion() -> float: @@ -2871,6 +2891,11 @@ class GlyphAtlas: pixel coordinate space (origin bottom-left), matching the legacy overlay. """ + #: The HiDPI factor the font was rasterised at (see :func:`build_atlas`); + #: overlay elements drawn next to its text, such as the DRO's home and + #: limit icons, scale by it too. + scale: float = 1.0 + def __init__(self, char_width: int, line_space: int, descent: int) -> None: self.char_width = char_width @@ -2989,14 +3014,16 @@ def _icon_texture(self, key: Any, data: Sequence[int], w: int, return tex def draw_icon(self, key: Any, data: Sequence[int], x: float, y: float, - w: int, h: int, color: Color, screen: Screen) -> None: - """Draw a 1-bit icon as a textured quad with its bottom-left at (x, y). + w: int, h: int, color: Color, screen: Screen, + scale: float = 1.0) -> None: + """Draw a 1-bit ``w`` x ``h`` icon as a textured quad with its + bottom-left at (x, y), enlarged ``scale`` times (HiDPI). Matches the legacy ``glBitmap(w, h, ...)`` placement: the texture is stored bottom-up, so screen-bottom (y) samples the first data row. """ tex = self._icon_texture(key, data, w, h) - verts = _quad(x, y, x + w, y + h, 0.0, 0.0, 1.0, 1.0) + verts = _quad(x, y, x + w * scale, y + h * scale, 0.0, 0.0, 1.0, 1.0) self._draw_array(verts, color, True, screen, texture=tex) def delete(self) -> None: @@ -3022,9 +3049,12 @@ def _quad(x0: float, y0: float, x1: float, y1: float, u0: float, v0: float, ] -def build_atlas(font: str, start: int, count: int) -> GlyphAtlas: +def build_atlas(font: str, start: int, count: int, + scale: float = 1.0) -> GlyphAtlas: """Rasterise glyphs ``start..start+count`` of ``font`` into a GlyphAtlas. + ``scale`` multiplies the font's size (HiDPI: Pango assumes 96 dpi). + Mirrors glnav.use_pango_font's Pango/Cairo setup so metrics match, but packs the glyphs into one GL_R8 texture instead of per-glyph display lists. Returns the GlyphAtlas. @@ -3037,6 +3067,11 @@ def build_atlas(font: str, start: int, count: int) -> GlyphAtlas: import cairo font_desc = Pango.FontDescription(font) + if scale != 1.0: + if font_desc.get_size_is_absolute(): + font_desc.set_absolute_size(font_desc.get_size() * scale) + else: + font_desc.set_size(int(font_desc.get_size() * scale)) surface = cairo.ImageSurface(cairo.FORMAT_A8, 256, 256) context = cairo.Context(surface) pango_context = PangoCairo.create_context(context) @@ -3089,6 +3124,7 @@ def build_atlas(font: str, start: int, count: int) -> GlyphAtlas: atlas = np.zeros((atlas_h, atlas_w), dtype=np.uint8) result = GlyphAtlas(char_width, line_space, descent) + result.scale = scale for i in range(count): cp = start + i glyph, w, h, adv = bitmaps[cp] diff --git a/lib/python/rs274/glcanon_scene.py b/lib/python/rs274/glcanon_scene.py index 66a491ed2bc..0ff9d6ebacb 100644 --- a/lib/python/rs274/glcanon_scene.py +++ b/lib/python/rs274/glcanon_scene.py @@ -51,7 +51,7 @@ GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA, GL_TRIANGLES, GL_TRUE, glBindVertexArray, glBlendColor, glBlendFunc, glDepthFunc, glDepthMask, glDisable, glEnable, - glLineWidth, glUseProgram) + glUseProgram) import gcode import glnav @@ -745,6 +745,8 @@ def apply_baseline(self) -> None: glDepthMask(GL_TRUE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) + # 1.0 times the HiDPI line scale (set_line_scale); plain 1 otherwise. + set_line_width(1.0) def draw(self, ctx: FrameContext) -> None: debug = SCENE_DEBUG @@ -1644,7 +1646,7 @@ def scope(self, ctx: FrameContext) -> Iterator[None]: with super().scope(ctx), ctx.mv.push(): tool_offset = ctx.to_internal_units(ctx.stat.tool_offset)[:3] ctx.mv.translate(*[-pos for pos in tool_offset]) - glLineWidth(1) + set_line_width(1.0) yield def draw(self, ctx: FrameContext) -> None: @@ -2018,10 +2020,12 @@ def show_icon(self, idx: int, icon: array.array) -> None: # Textured-quad replacement for the legacy # glBitmap(13, 16, xorig=0, yorig=3, xmove=17, ...): draw at the running # pen offset down by the 3px y origin, then advance the pen 17px as - # glBitmap advanced the raster position after each icon. - self._atlas.draw_icon(id(icon), icon, self._pen_x, self._pen_y - 3, - 13, 16, self._fg, self._screen) - self._pen_x += 17 + # glBitmap advanced the raster position after each icon. All of it in + # 96 dpi pixels, times the HiDPI factor the DRO font was built with. + sc = self._atlas.scale + self._atlas.draw_icon(id(icon), icon, self._pen_x, self._pen_y - 3 * sc, + 13, 16, self._fg, self._screen, scale=sc) + self._pen_x += 17 * sc def draw(self, ctx: FrameContext) -> None: limit, homed, posstrs, droposstrs = ctx.posstrs() @@ -2044,16 +2048,16 @@ def draw(self, ctx: FrameContext) -> None: # to (1-overlay_alpha), matching the legacy GL_ONE/GL_CONSTANT_ALPHA. bg = ctx.colors['overlay_background'] top = ctx.height - bottom = top - 8 - linespace*len(posstrs) - atlas.draw_quad(0, bottom, pixel_width+42, top, + bottom = top - 8 * atlas.scale - linespace*len(posstrs) + atlas.draw_quad(0, bottom, pixel_width + 42 * atlas.scale, top, (bg[0], bg[1], bg[2], ctx.colors['overlay_alpha']), screen) maxlen = 0 - ypos -= linespace+5 + ypos -= linespace + 5 * atlas.scale self.reset_icons() - stringstart_xpos = 15 + stringstart_xpos = 15 * atlas.scale #----------------------------------------------------------------------- if ctx.show_offsets: thestring = droposstrs else: thestring = posstrs diff --git a/lib/python/vcpparse.py b/lib/python/vcpparse.py index 24c4a360fda..9f00666aa17 100644 --- a/lib/python/vcpparse.py +++ b/lib/python/vcpparse.py @@ -175,6 +175,8 @@ def create_vcp(master, comp = None, compname="pyvcp"): reload(pyvcp_widgets) global pyvcp0, pycomp pyvcp0 = master + # Scale to the desktop's HiDPI factor; before any widget is created. + pyvcp_widgets.init_hidpi(master) if comp is None: try: comp = hal.component(compname) diff --git a/lib/python/vismach.py b/lib/python/vismach.py index 7fd37958fcf..6249934570e 100644 --- a/lib/python/vismach.py +++ b/lib/python/vismach.py @@ -1540,8 +1540,12 @@ def draw(self): def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0): app = tkinter.Tk() + import nf + hidpi = nf.init_hidpi(app) - t = O(app, double=1, depth=1) + # Togl's default 400x400 is in device pixels; scale it for HiDPI. + t = O(app, double=1, depth=1, + width=int(round(400 * hidpi)), height=int(round(400 * hidpi))) # set which axes to rotate around if rotation_vectors: t.rotation_vectors = rotation_vectors # we want to be able to see the model from all angles diff --git a/share/axis/tcl/support.tcl b/share/axis/tcl/support.tcl index 6402ee0439f..a7fe3d7dab0 100644 --- a/share/axis/tcl/support.tcl +++ b/share/axis/tcl/support.tcl @@ -59,6 +59,9 @@ proc load_image { name {img ""}} { if {[lsearch [image names] $img] != -1} { return $img } set file [find_image $name] image create photo $img -file $file + if {[info commands linuxcnc::hidpi::scale_image] ne ""} { + linuxcnc::hidpi::scale_image $img + } return $img } diff --git a/src/emc/usr_intf/axis/scripts/axis.py b/src/emc/usr_intf/axis/scripts/axis.py index 53192ad3048..ab900a7ac85 100755 --- a/src/emc/usr_intf/axis/scripts/axis.py +++ b/src/emc/usr_intf/axis/scripts/axis.py @@ -147,8 +147,12 @@ def key_released(ev): os.system("xhost -SI:localuser:gdm -SI:localuser:root > /dev/null 2>&1") root_window = Tkinter.Tk(className="Axis") tkdar.enable(root_window) # Set detectable key repeat -dpi_value = root_window.winfo_fpixels('1i') -root_window.tk.call('tk', 'scaling', '-displayof', '.', dpi_value / 72.0) +# Scale to the desktop's HiDPI factor (Xft.dpi): sets tk scaling and the +# pixel defaults of Tk widgets. Must run before any widget is created. +hidpi_factor = nf.init_hidpi(root_window) +# The preview is drawn in device pixels: widen its lines by the same factor. +from rs274 import glcanon_gl +glcanon_gl.set_line_scale(hidpi_factor) root_window.withdraw() nf.start(root_window) nf.makecommand(root_window, "_", _) @@ -4003,7 +4007,7 @@ def get_coordinate_font(large): if coordinate_font not in font_cache: font_cache[coordinate_font] = \ - glnav.use_pango_font(coordinate_font, 0, 128) + glnav.use_pango_font(coordinate_font, 0, 128, scale=hidpi_factor) fontbase, coordinate_charwidth, coordinate_linespace = \ font_cache[coordinate_font] diff --git a/src/emc/usr_intf/axis/scripts/linuxcnctop.py b/src/emc/usr_intf/axis/scripts/linuxcnctop.py index 69c82944b1f..04cbfe86755 100644 --- a/src/emc/usr_intf/axis/scripts/linuxcnctop.py +++ b/src/emc/usr_intf/axis/scripts/linuxcnctop.py @@ -123,19 +123,23 @@ def gui(): from _tkinter import TclError root = tkinter.Tk(className="LinuxCNCTop") + import nf + hidpi = nf.init_hidpi(root) + # width of the name column, in 96 dpi pixels times the HiDPI factor + col = int(round(150 * hidpi)) rs274.options.install(root) root.title(_("LinuxCNC Status")) t = tkinter.Text(wrap="word") sb = tkinter.Scrollbar(command=t.yview) t.configure(yscrollcommand=sb.set) - t.configure(tabs=150) + t.configure(tabs=col) base_font = t.tk.call("set", "BASE_FONT") fixed_font = t.tk.call("set", "FIXED_FONT") t.tag_configure("key", foreground="blue", font=base_font) - t.tag_configure("value", foreground="black", font=fixed_font, lmargin1=150, lmargin2=150) - t.tag_configure("changedvalue", foreground="black", background="red", font=fixed_font, lmargin1=150, lmargin2=150) + t.tag_configure("value", foreground="black", font=fixed_font, lmargin1=col, lmargin2=col) + t.tag_configure("changedvalue", foreground="black", background="red", font=fixed_font, lmargin1=col, lmargin2=col) t.tag_configure("sel", foreground="white") t.tag_raise("sel") t.bind("", "break") diff --git a/src/emc/usr_intf/gremlin/gremlin.py b/src/emc/usr_intf/gremlin/gremlin.py index 296cb244902..b013e4e0430 100755 --- a/src/emc/usr_intf/gremlin/gremlin.py +++ b/src/emc/usr_intf/gremlin/gremlin.py @@ -55,6 +55,7 @@ import glnav import rs274.glcanon +import rs274.glcanon_gl import rs274.interpret from rs274.program_time import MachineLimits, ProgramTime, format_seconds import linuxcnc @@ -279,6 +280,7 @@ def reshape(self, widget, width, height): def render(self, area=None, context=None): if not self.initialised: return True + self.update_hidpi() if self.perspective: self.redraw_perspective() else: self.redraw_ortho() @@ -345,15 +347,33 @@ def realize(self, widget): return self._current_file = None - self.font_base, width, linespace = glnav.use_pango_font('monospace 16', 0, 128) - self.font_linespace = linespace - self.font_charwidth = width + self._font_scale = None + self.update_hidpi() rs274.glcanon.GlCanonDraw.realize(self) self.swapbuffers() if s.file: self.load() + def update_hidpi(self): + """Follow the window's scale factor (HiDPI): the GL framebuffer is in + device pixels, so line widths, the overlay font and its icons are + scaled by it. Checked every frame, since the factor changes when the + window moves to a screen with a different scale. Needs the context. + """ + scale = self.get_scale_factor() + rs274.glcanon_gl.set_line_scale(scale) + if scale == self._font_scale: + return + old = getattr(self, 'font_base', None) + self.font_base, width, linespace = glnav.use_pango_font( + 'monospace 16', 0, 128, scale=scale) + self.font_linespace = linespace + self.font_charwidth = width + self._font_scale = scale + if old is not None and hasattr(old, 'delete'): + old.delete() + def set_current_view(self): if self.current_view not in ['p', 'x', 'y', 'y2', 'z', 'z2']: return diff --git a/tcl/bin/emccalib.tcl b/tcl/bin/emccalib.tcl index c856e9e5d03..1ef9984326f 100755 --- a/tcl/bin/emccalib.tcl +++ b/tcl/bin/emccalib.tcl @@ -30,6 +30,9 @@ eval emc_init $argv source [file join $::env(HALLIB_DIR) hal_procs_lib.tcl] package require BWidget +# Tk is loaded only now when started from tclsh; scale to the desktop's HiDPI +# factor (no-op if linuxcnc.tcl already did it). +linuxcnc::hidpi::init # add a few default characteristics to the display foreach class { Button Checkbutton Entry Label Listbox Menu Menubutton \ diff --git a/tcl/bin/halconfig.tcl b/tcl/bin/halconfig.tcl index 6a80605fb56..f283e125bf0 100755 --- a/tcl/bin/halconfig.tcl +++ b/tcl/bin/halconfig.tcl @@ -31,6 +31,9 @@ source [file join [file dirname [info script]] .. linuxcnc.tcl] eval emc_init $argv package require BWidget +# Tk is loaded only now when started from tclsh; scale to the desktop's HiDPI +# factor (no-op if linuxcnc.tcl already did it). +linuxcnc::hidpi::init #----------open channel to halcmd ---------- diff --git a/tcl/bin/halshow.tcl b/tcl/bin/halshow.tcl index 3b7cd81e5c6..466cf812398 100755 --- a/tcl/bin/halshow.tcl +++ b/tcl/bin/halshow.tcl @@ -22,6 +22,9 @@ source [file join [file dirname [info script]] .. linuxcnc.tcl] source [file join [file dirname [info script]] cbutton.tcl] package require BWidget +# Tk is loaded only now when started from tclsh; scale to the desktop's HiDPI +# factor (no-op if linuxcnc.tcl already did it). +linuxcnc::hidpi::init # add a few default characteristics to the display foreach class { Button Checkbutton Entry Label Listbox Menu Menubutton \ @@ -135,15 +138,18 @@ image create photo preferencesIcon -data { YII= } wm iconphoto . -default applicationIcon -set masterwidth 700 -set masterheight 475 +linuxcnc::hidpi::scale_image preferencesIcon +# pixel size scaled to the desktop's HiDPI factor +proc px {n} { linuxcnc::hidpi::scale $n } +set masterwidth [px 700] +set masterheight [px 475] # set fixed size for configuration display and center set xmax [winfo screenwidth .] set ymax [winfo screenheight .] set x [expr ($xmax - $masterwidth ) / 2 ] set y [expr ($ymax - $masterheight ) / 2] wm geometry . "${masterwidth}x${masterheight}+$x+$y" -wm minsize . 230 240 +wm minsize . [px 230] [px 240] # save settings after switching to another window bind . {saveIni} @@ -325,7 +331,7 @@ set bh [button $fh.top.bh -borderwidth 0 -text » -padx 4 -pady 1] pack $bh -side right bind $bh [list hideListview true] # preferences button -set bp [checkbutton $fh.top.bpref -image preferencesIcon -indicatoron false -variable ::bp_state -borderwidth 0 -height 20 -width 20] +set bp [checkbutton $fh.top.bpref -image preferencesIcon -indicatoron false -variable ::bp_state -borderwidth 0 -height [px 20] -width [px 20]] pack $bp -side right -pady 0 bind $bp { if {$::bp_state} { @@ -359,19 +365,19 @@ bind $fe { bind $fe {refreshHAL} # frame to show tree -set ::fs [frame $::rightf.fs -borderwidth 1 -relief raised -width 24] +set ::fs [frame $::rightf.fs -borderwidth 1 -relief raised -width [px 24]] set bs [button $::fs.bs -borderwidth 0 -text « -padx 5 -pady 0] pack $bs -side top bind $bs [list showListview] # add canvas to create rotated text -set clbl [canvas $::fs.clbl -width 20] +set clbl [canvas $::fs.clbl -width [px 20]] pack $clbl -$clbl create text 10 5 -angle 90 -anchor e -text [msgcat::mc "Tree View"] -font [list "" 10] +$clbl create text [px 10] [px 5] -angle 90 -anchor e -text [msgcat::mc "Tree View"] -font [list "" 10] proc hideListview {resizeWindow} { - place $::fs -width 24 -relheight 1.0 + place $::fs -width [px 24] -relheight 1.0 pack forget $::nb - place $::nb -anchor ne -relx 1.0 -relwidth 1.0 -width -33 -relheight 1.0 + place $::nb -anchor ne -relx 1.0 -relwidth 1.0 -width -[px 33] -relheight 1.0 placeFrames 0 if {$resizeWindow} { set ::old_w_leftf [winfo width $::leftf] @@ -384,7 +390,7 @@ proc hideListview {resizeWindow} { } } -set ::old_w_leftf 160 +set ::old_w_leftf [px 160] proc showListview {} { place forget $::fs place configure $::nb -relwidth 1.0 -width 0 @@ -413,6 +419,9 @@ proc scaleFrames {} { # build the tree widgets left side set ::treew [Tree $::tf.t -width 10 -yscrollcommand "sSlide $::tf" ] +# row height from the font, so rows do not overlap with large or scaled fonts +$::treew configure -deltay [font metrics [[listbox .fontprobe] cget -font] -linespace] +destroy .fontprobe set str $::tf.sc scrollbar $str -orient vert -command "$::treew yview" pack $str -side right -fill y @@ -882,10 +891,28 @@ set ::watchlist "" set ::watchlist_len 0 set ::watchstring "" set ::col1_width 100 +# Everything in the watch canvas is laid out in 96 dpi pixels; the items of +# each row are then scaled to the desktop's HiDPI factor (scaleNewItems). +# Text is not affected by canvas scaling, its font already has the right size. +proc lastCanvasItem {} { + return [lindex [$::cisp find all] end] +} +proc scaleNewItems {last} { + set f [linuxcnc::hidpi::factor] + if {$f == 1.0} { return } + foreach id [$::cisp find all] { + if {$last eq "" || $id > $last} { + $::cisp scale $id 0 0 $f $f + } + } +} + proc watchHAL {which} { if {$which == "zzz"} { + set last [lastCanvasItem] $::cisp create text 40 [expr 1 * 20 + 12] -anchor w -tag firstmessage\ -text [msgcat::mc "<-- Select a Leaf. Click on its name."] + scaleNewItems $last set ::watchlist "" set ::watchstring "" return @@ -954,9 +981,11 @@ proc watchHAL {which} { set labelcolor blue3 } + set last [lastCanvasItem] $::cisp create text $::col1_width [expr $i * 20 + 13] -text $label \ -anchor w -tag $label -fill $labelcolor - set canvaswidth [winfo width $::cisp] + # in unscaled units, see scaleNewItems + set canvaswidth [expr {[winfo width $::cisp] / [linuxcnc::hidpi::factor]}] if {$type == "bit" || $type == "bool"} { $::cisp create oval 10 [expr $i * 20 + 5] 25 [expr $i * 20 + 20] \ -fill lightgray -tag oval$i @@ -1003,6 +1032,7 @@ proc watchHAL {which} { } if {$i > 1} {$::cisp create line 10 [expr $i * 20 + 3] [expr $canvaswidth - 52] \ [expr $i * 20 + 3] -fill grey70} + scaleNewItems $last $::cisp bind $label [list popupmenu_watch $vartype $label $i $writable $which %X %Y] $::cisp configure -scrollregion [$::cisp bbox all] $::cisp yview moveto 1.0 diff --git a/tcl/bin/pickconfig.tcl b/tcl/bin/pickconfig.tcl index d8057d45d30..847bef8a65a 100755 --- a/tcl/bin/pickconfig.tcl +++ b/tcl/bin/pickconfig.tcl @@ -382,8 +382,8 @@ set top [frame .main -borderwidth 0 -relief flat ] pack $logo -side left -anchor nw pack $top -side left -expand yes -fill both -wm geo . 780x480 -wm minsize . 780 480 +wm geo . [linuxcnc::hidpi::scale 780]x[linuxcnc::hidpi::scale 480] +wm minsize . [linuxcnc::hidpi::scale 780] [linuxcnc::hidpi::scale 480] proc SW { args } { set res [eval ScrolledWindow $args] diff --git a/tcl/bin/popimage b/tcl/bin/popimage index 58acd23585d..2f1dcace171 100755 --- a/tcl/bin/popimage +++ b/tcl/bin/popimage @@ -31,6 +31,9 @@ if {$argc < 1} { } load [file join [file dirname [info script]] .. linuxcnc.so] +# Scale to the desktop's HiDPI factor (see hidpi.tcl). +source [file join [file dirname [info script]] .. hidpi.tcl] +linuxcnc::hidpi::init . configure -borderwidth 0 -highlightthickness 0 @@ -56,11 +59,12 @@ if {[catch {image create photo -file $img} image]} { exit } +linuxcnc::hidpi::scale_image $image set w [image width $image] set h [image height $image] canvas .c -width $w -height $h -borderwidth 0 -highlightthickness 0 .c create image 0 0 -anchor nw -image $image -.c create text 4 [expr $h-4] -anchor sw \ +.c create text [linuxcnc::hidpi::scale 4] [expr {$h-[linuxcnc::hidpi::scale 4]}] -anchor sw \ -text $env(LINUXCNCVERSION) -fill white -font {Helvetica 18} pack .c diff --git a/tcl/hidpi.tcl b/tcl/hidpi.tcl new file mode 100644 index 00000000000..a2e3cc55070 --- /dev/null +++ b/tcl/hidpi.tcl @@ -0,0 +1,146 @@ +# HiDPI support for LinuxCNC's Tk programs. +# +# Tk 8.6 has no notion of a desktop scale factor. On a HiDPI desktop the +# X server (or XWayland with native scaling) reports an ordinary 96 dpi screen +# and announces the real scale only through the Xft.dpi resource, e.g. 192 +# for 200%. Text already follows Xft.dpi, because Tk's Xft font code applies +# it, but everything Tk measures in pixels does not: widget defaults such as +# slider and scrollbar sizes, fixed window sizes and images all come out at +# their 96 dpi size. +# +# Source this file right after Tk is initialised and call +# linuxcnc::hidpi::init +# Then use [linuxcnc::hidpi::scale] for pixel sizes the program sets itself, +# and linuxcnc::hidpi::scale_image for images. +# +# The scale can be forced with the LINUXCNC_UI_SCALE environment variable +# (e.g. LINUXCNC_UI_SCALE=1.5); LINUXCNC_UI_SCALE=1 disables scaling. + +namespace eval linuxcnc::hidpi { + variable factor 1.0 + variable initialised 0 +} + +# Desktop scale relative to 96 dpi, rounded to a quarter step. +proc linuxcnc::hidpi::detect {} { + if {[info exists ::env(LINUXCNC_UI_SCALE)] + && [string is double -strict $::env(LINUXCNC_UI_SCALE)] + && $::env(LINUXCNC_UI_SCALE) > 0} { + return [expr {double($::env(LINUXCNC_UI_SCALE))}] + } + set dpi 96.0 + if {![catch {exec xrdb -query} res]} { + foreach line [split $res \n] { + if {[regexp {^Xft\.dpi:\s*([0-9.]+)} $line -> d] && $d > 0} { + set dpi $d + } + } + } + set f [expr {round($dpi / 96.0 * 4) / 4.0}] + if {$f < 1.0} { set f 1.0 } + return $f +} + +proc linuxcnc::hidpi::init {} { + variable factor + variable initialised + if {$initialised} { return $factor } + set initialised 1 + set factor [detect] + + # Sizes given in screen units (points, mm, inches) - many Tk defaults, + # e.g. button padding - follow tk scaling. + tk scaling [expr {$factor * 96.0 / 72.0}] + + if {$factor == 1.0} { return $factor } + + # Pixel defaults of the classic widgets. startupFile priority: above + # widgetDefault, which BWidget uses for its own pixel defaults when it is + # loaded later, but below ~/.Xresources (userDefault) and a program's own + # "option add" (interactive) or explicit widget options. + # Only options whose built-in default is non-zero are listed, per class: + # a blanket *borderWidth would also give frames and labels a border. + foreach {pattern px} { + *Scale.width 15 + *Scale.sliderLength 30 + *Scale.length 100 + *Scrollbar.width 11 + *Scrollbar.elementBorderWidth 1 + *selectBorderWidth 1 + *activeBorderWidth 1 + *insertWidth 2 + *Button.borderWidth 2 + *Checkbutton.borderWidth 2 + *Radiobutton.borderWidth 2 + *Menubutton.borderWidth 2 + *Scale.borderWidth 2 + *Scrollbar.borderWidth 1 + *Entry.borderWidth 1 + *Spinbox.borderWidth 1 + *Listbox.borderWidth 1 + *Text.borderWidth 1 + *Menu.borderWidth 1 + *Button.highlightThickness 1 + *Checkbutton.highlightThickness 1 + *Radiobutton.highlightThickness 1 + *Scale.highlightThickness 1 + *Entry.highlightThickness 1 + *Spinbox.highlightThickness 1 + *Listbox.highlightThickness 1 + *Text.highlightThickness 1 + *Tree.deltax 10 + *Tree.padX 20 + } { + option add $pattern [scale $px] startupFile + } + + # ttk widgets size their arrows, sliders and indicators in pixels. + catch { + foreach theme [ttk::style theme names] { + ttk::style theme settings $theme { + ttk::style configure . -arrowsize [scale 12] \ + -sliderthickness [scale 15] -sliderlength [scale 30] \ + -indicatordiameter [scale 12] -indicatorsize [scale 12] \ + -gripcount [scale 5] + } + } + } + return $factor +} + +# The current scale factor (1.0 when unscaled). +proc linuxcnc::hidpi::factor {} { + variable factor + return $factor +} + +# Scale a pixel size. +proc linuxcnc::hidpi::scale {px} { + variable factor + return [expr {int(round($px * $factor))}] +} + +# Scale a photo image in place to the current factor. Integer factors are +# exact pixel doubling; others are approximated as zoom/subsample in halves +# (e.g. 1.5 = zoom 3, subsample 2). +proc linuxcnc::hidpi::scale_image {img} { + variable factor + if {$factor == 1.0 || [image type $img] ne "photo"} { return $img } + set zoom [expr {int(round($factor * 2))}] + set sub 2 + if {$zoom % 2 == 0} { set zoom [expr {$zoom / 2}]; set sub 1 } + set tmp [image create photo] + $tmp copy $img + $img blank + $img configure -width 0 -height 0 + if {$sub == 1} { + $img copy $tmp -zoom $zoom + } else { + set big [image create photo] + $big copy $tmp -zoom $zoom + $img copy $big -subsample $sub + image delete $big + } + image delete $tmp + return $img +} diff --git a/tcl/linuxcnc.tcl.in b/tcl/linuxcnc.tcl.in index 10ab7d8e0ec..c2471e66bfd 100644 --- a/tcl/linuxcnc.tcl.in +++ b/tcl/linuxcnc.tcl.in @@ -52,15 +52,22 @@ proc linuxcnc::image_search i { set paths "$::linuxcnc::IMAGEDIR $::linuxcnc::HOME $::linuxcnc::HOME/etc/linuxcnc /etc/linuxcnc ." foreach f $paths { if [file exists $f/$i] { - return [image create photo -file $f/$i] + return [hidpi::scale_image [image create photo -file $f/$i]] } if [file exists $f/$i.gif] { - return [image create photo -file $f/$i.gif] + return [hidpi::scale_image [image create photo -file $f/$i.gif]] } } error "image $i is not available" } +# Scale Tk programs to the desktop's HiDPI factor (see hidpi.tcl). Only when +# Tk is loaded: tclsh scripts source this file too. +source [file join [file dirname [info script]] hidpi.tcl] +if {[info commands tk] ne ""} { + linuxcnc::hidpi::init +} + load [file join [file dirname [info script]] linuxcnc[info sharedlibextension]] # Arrange to load hal.so when the 'hal' command is requested From 45836d6c3c7d37b1c122d38407b28ea9e1726c1d Mon Sep 17 00:00:00 2001 From: Rene Hopf Date: Thu, 12 Nov 2026 15:21:42 +0100 Subject: [PATCH 2/3] hidpi: leave tk scaling alone Tk's Xft code turns a pixel font into points with tk scaling and Xft then applies Xft.dpi, so setting tk scaling to factor*96/72 halved every pixel font (ngcgui's {Helvetica -10 bold}, tkbackplot, lh_chart) compared to master. Text is now left entirely to Xft.dpi, as on master; the Button padX/padY defaults, which are in screen units and relied on tk scaling, go into the option database with the other pixel defaults. This also means nothing is changed at factor 1 any more. - ttk -gripcount is a number of lines, not pixels: don't scale it. - Guard the namespace variables so that re-sourcing linuxcnc.tcl (as rs274.options.install does) keeps the state of an earlier init. - Document that LINUXCNC_UI_SCALE scales sizes, images and lines but not text, which follows Xft.dpi. --- lib/python/nf.py.in | 4 ++-- src/emc/usr_intf/axis/scripts/axis.py | 4 ++-- tcl/hidpi.tcl | 30 +++++++++++++++++++-------- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/lib/python/nf.py.in b/lib/python/nf.py.in index fac078e3390..9256f5b01dc 100644 --- a/lib/python/nf.py.in +++ b/lib/python/nf.py.in @@ -113,8 +113,8 @@ def source_lib_tcl(r, f): r.tk.call("source", os.path.join(tcl_libdir, f)) def init_hidpi(r): - """Scale Tk to the desktop's HiDPI factor (Xft.dpi) - tk scaling and the - pixel defaults of the Tk widgets, see tcl/hidpi.tcl - and return the + """Scale Tk to the desktop's HiDPI factor (Xft.dpi) - the pixel defaults + of the Tk widgets, see tcl/hidpi.tcl - and return the factor (1.0 when unscaled). Call before creating widgets. Safe to call again: later calls only return the factor.""" if not r.tk.call("info", "commands", "linuxcnc::hidpi::init"): diff --git a/src/emc/usr_intf/axis/scripts/axis.py b/src/emc/usr_intf/axis/scripts/axis.py index ab900a7ac85..8fbc6923847 100755 --- a/src/emc/usr_intf/axis/scripts/axis.py +++ b/src/emc/usr_intf/axis/scripts/axis.py @@ -147,8 +147,8 @@ def key_released(ev): os.system("xhost -SI:localuser:gdm -SI:localuser:root > /dev/null 2>&1") root_window = Tkinter.Tk(className="Axis") tkdar.enable(root_window) # Set detectable key repeat -# Scale to the desktop's HiDPI factor (Xft.dpi): sets tk scaling and the -# pixel defaults of Tk widgets. Must run before any widget is created. +# Scale to the desktop's HiDPI factor (Xft.dpi): sets the pixel defaults of +# Tk widgets. Must run before any widget is created. hidpi_factor = nf.init_hidpi(root_window) # The preview is drawn in device pixels: widen its lines by the same factor. from rs274 import glcanon_gl diff --git a/tcl/hidpi.tcl b/tcl/hidpi.tcl index a2e3cc55070..a59b129bb59 100644 --- a/tcl/hidpi.tcl +++ b/tcl/hidpi.tcl @@ -8,17 +8,27 @@ # slider and scrollbar sizes, fixed window sizes and images all come out at # their 96 dpi size. # +# tk scaling is left alone. Tk's Xft code turns a pixel font (e.g. +# {Helvetica -10}) into points with tk scaling and Xft then applies Xft.dpi, +# so changing it would shrink every pixel font. Text is left entirely to +# Xft.dpi; the factor only goes into the option database and the helpers +# below. +# # Source this file right after Tk is initialised and call # linuxcnc::hidpi::init # Then use [linuxcnc::hidpi::scale] for pixel sizes the program sets itself, # and linuxcnc::hidpi::scale_image for images. # # The scale can be forced with the LINUXCNC_UI_SCALE environment variable -# (e.g. LINUXCNC_UI_SCALE=1.5); LINUXCNC_UI_SCALE=1 disables scaling. +# (e.g. LINUXCNC_UI_SCALE=1.5); LINUXCNC_UI_SCALE=1 disables scaling. It +# scales widget sizes, images and lines only: text still follows Xft.dpi, +# which cannot be changed from Tcl. +# Guarded, so that sourcing this file again (linuxcnc.tcl is re-sourced by +# some programs) keeps the state of an earlier init. namespace eval linuxcnc::hidpi { - variable factor 1.0 - variable initialised 0 + if {![info exists factor]} { variable factor 1.0 } + if {![info exists initialised]} { variable initialised 0 } } # Desktop scale relative to 96 dpi, rounded to a quarter step. @@ -47,11 +57,6 @@ proc linuxcnc::hidpi::init {} { if {$initialised} { return $factor } set initialised 1 set factor [detect] - - # Sizes given in screen units (points, mm, inches) - many Tk defaults, - # e.g. button padding - follow tk scaling. - tk scaling [expr {$factor * 96.0 / 72.0}] - if {$factor == 1.0} { return $factor } # Pixel defaults of the classic widgets. startupFile priority: above @@ -93,6 +98,13 @@ proc linuxcnc::hidpi::init {} { } { option add $pattern [scale $px] startupFile } + # Defaults given in screen units, which would follow tk scaling. + foreach {pattern dist} { + *Button.padX 3m + *Button.padY 1m + } { + option add $pattern [scale [winfo fpixels . $dist]] startupFile + } # ttk widgets size their arrows, sliders and indicators in pixels. catch { @@ -101,7 +113,7 @@ proc linuxcnc::hidpi::init {} { ttk::style configure . -arrowsize [scale 12] \ -sliderthickness [scale 15] -sliderlength [scale 30] \ -indicatordiameter [scale 12] -indicatorsize [scale 12] \ - -gripcount [scale 5] + -gripcount 5 } } } From 57b860ec6855294aa3489d1733d8aed711fa8aaf Mon Sep 17 00:00:00 2001 From: Rene Hopf Date: Thu, 12 Nov 2026 15:29:53 +0100 Subject: [PATCH 3/3] pyvcp: size the dial and jogwheel pixel fonts from the unscaled size Their text uses a pixel font sized from the dial, which is now in screen pixels. With tk scaling left alone Tk's Xft code scales pixel fonts by Xft.dpi already, so the text came out at twice its size on a 200 % desktop. Size it from the 96 dpi size, as the meter does for its point fonts. --- lib/python/pyvcp_widgets.py | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/lib/python/pyvcp_widgets.py b/lib/python/pyvcp_widgets.py index ea9256b77f9..cccd0e4d06a 100644 --- a/lib/python/pyvcp_widgets.py +++ b/lib/python/pyvcp_widgets.py @@ -56,8 +56,9 @@ # HiDPI scale factor (1.0 = 96 dpi). Sizes in the panel XML, and the fixed # sizes below, are 96 dpi pixels; _px() turns them into screen pixels. Fonts -# given in points need no scaling: Tk's Xft font code already follows the -# desktop scale. Set by init_hidpi(), which vcpparse.create_vcp() calls. +# need no scaling, in points or in pixels: Tk's Xft font code already follows +# the desktop scale, so a pixel font must be sized from the unscaled size. +# Set by init_hidpi(), which vcpparse.create_vcp() calls. _scale = 1.0 def init_hidpi(master): @@ -185,17 +186,19 @@ def __init__(self,root,pycomp,halpin=None,halparam=None,param_pin=0,size=200,cpr #TJP items get rendered in order of creation, so the knob will be behind these texts #TJP the font can be described with pixel size by using negative value self.txtroom=int(size/6) + # pixel font, from the unscaled size (see _scale) + self.txtfont=('Arial',-int(round(self.txtroom/_scale))) # a title, if the user has supplied one if text!=None: self.title=self.create_text([self.mid,self.mid-self.txtroom], - text=text,font=('Arial',-self.txtroom)) + text=text,font=self.txtfont) # the output - self.dro=self.create_text([self.mid,self.mid],font=('Arial',-self.txtroom)) + self.dro=self.create_text([self.mid,self.mid],font=self.txtfont) self.update_dro() # the scale self.delta=self.create_text([self.mid,self.mid+self.txtroom], - text='x '+ str(self.funit),font=('Arial',-self.txtroom)) + text='x '+ str(self.funit),font=self.txtfont) self.bind('',self.wheel_up) # untested no wheel mouse @@ -550,18 +553,20 @@ def __init__(self,root,pycomp,halpin=None,text=None,clear_pin=0,scale_pin=0, #TJP the font can be described with pixel size by using negative value self.txtroom=int(size/10) + # pixel font, from the unscaled size (see _scale) + self.txtfont=('Arial',-int(round(self.txtroom/_scale))) # a title, if the user has supplied one if text!=None: self.title=self.create_text([self.mid,self.mid-self.txtroom], - text=text,font=('Arial',-self.txtroom)) + text=text,font=self.txtfont) # the output if clear_pin!=0: self.dro=self.create_text([self.mid,self.mid], - text=str(self.drotxt),font=('Arial',-self.txtroom)) + text=str(self.drotxt),font=self.txtfont) # the scale if scale_pin!=0: self.jogscale=self.create_text([self.mid,self.mid+self.txtroom], - text='x '+ str(self.scale),font=('Arial',-self.txtroom)) + text='x '+ str(self.scale),font=self.txtfont) self.bind('',self.wheel_up) self.bind('',self.wheel_down)