Skip to content

misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux

fix(ui): smooth Windows text while retaining pixel alignment (#329)

awishtodiexz587b53db5aec
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 38353e56..9d036f6d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
- **YouTube's look-up failing with "Requested format is not available"** ([#352](https://github.com/anefzaoui/misterdownloadmanager/issues/352)): signed-in cookies make yt-dlp use only YouTube's players that need a JavaScript runtime, and without one no video is left. The page is now looked up again without the cookies, and lists its qualities.
- **Download video offering only the sound, with no reason given** ([#351](https://github.com/anefzaoui/misterdownloadmanager/issues/351)): when a page's better videos need ffmpeg and it isn't installed, the window now says so.
- Adding a link again after its finished file was moved or deleted starts a new download, instead of asking about a duplicate that isn't there ([#342](https://github.com/anefzaoui/misterdownloadmanager/issues/342)).
+- **Sharp, evenly spaced text on Windows:** letters no longer run together or drift apart. English and other Latin, Greek and Cyrillic text is drawn the way Windows draws its own classic controls, with each letter's shape and width fitted together; every other script uses hinting suited to anti-aliased rendering ([#323](https://github.com/anefzaoui/misterdownloadmanager/issues/323), [#334](https://github.com/anefzaoui/misterdownloadmanager/issues/334)).
## [0.5.1] - 2026-11-08
diff --git a/Cargo.lock b/Cargo.lock
index 1b20e946..6bad846c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4479,6 +4479,7 @@ dependencies = [
"unicode-segmentation",
"url",
"wgpu",
+ "windows 0.62.2",
"windows-sys 0.61.2",
"winit",
"winresource",
diff --git a/ROADMAP.md b/ROADMAP.md
index d1c8a0c0..bce43069 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -30,6 +30,9 @@ Everything below ships together, in version 0.5.0.
- ✅ **View → Interface size**: every window larger, 100 % to 200 %, with Ctrl + / Ctrl − / Ctrl 0
as in a browser; a window larger than the screen scrolls. Sharper text on Windows (part of
[#262](https://github.com/anefzaoui/misterdownloadmanager/issues/262))
+- ✅ Windows: sharp, evenly spaced text at every interface size: letters no longer run together
+ or drift apart ([#323](https://github.com/anefzaoui/misterdownloadmanager/issues/323),
+ [#334](https://github.com/anefzaoui/misterdownloadmanager/issues/334))
- ✅ Linux: Update now asks the package manager which package MDM is; a copy installed by
another package manager (pacman) is left to the system's updates, with a plain message
- ✅ Linux: the .deb and .rpm install the browsers' host files for everyone and remove them on
diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml
index 0ec7c113..b1fcf392 100644
--- a/crates/app/Cargo.toml
+++ b/crates/app/Cargo.toml
@@ -76,6 +76,10 @@ wgpu = { version = "30.0", default-features = false, features = ["dx12", "wgsl"]
# Drag the downloaded file out of Download complete (OLE drag and drop).
drag = "2.1.1"
raw-window-handle = "0.6"
+# Latin, Greek and Cyrillic text drawn by DirectWrite as Windows' classic controls draw it
+# (win32.rs `text_rasterizer`): its COM interfaces, which windows-sys doesn't have. The windows
+# 0.62 wgpu-hal already builds.
+windows = { version = "0.62", default-features = false, features = ["Win32_Graphics_DirectWrite"] }
# The notification-area icon and its menu (tray.rs).
[target.'cfg(not(target_os = "linux"))'.dependencies]
diff --git a/crates/app/src/theme.rs b/crates/app/src/theme.rs
index c8f67f4b..b3d0f80c 100644
--- a/crates/app/src/theme.rs
+++ b/crates/app/src/theme.rs
@@ -513,6 +513,8 @@ pub fn interface_fonts(ctx: &egui::Context) {
}
fn load_fonts(ctx: &egui::Context, all: bool) {
+ #[cfg(windows)]
+ classic_text(ctx);
let code = crate::i18n::code().to_owned();
let mut loaded = LOADED.lock().unwrap();
// Only the script fonts depend on the language: rebuild when that set changes.
@@ -603,18 +605,42 @@ fn fonts(ctx: &egui::Context, code: &str, all: bool) {
text_styles(ctx);
}
-/// Windows' fonts drawn as sharp as Windows draws them (#262): each glyph grid-fitted across too
-/// (the fonts' own hinting, as Windows runs it for its grey text), and started on a whole pixel.
-/// egui hints only up and down by default and places glyphs at quarter pixels, which left the
-/// upright strokes of Segoe UI and Tahoma two pixels wide and grey at 9 pt: text read as blurred,
-/// most at 100 % and 125 %. Letters keep their unhinted advances, so a word can show a pixel more
-/// or less between two letters. Linux's and macOS's fonts keep egui's default (often unhinted
-/// fonts; a Mac's screen is dense enough).
+/// Latin, Greek and Cyrillic text drawn the way Windows' classic controls draw it (#262, #323,
+/// #334), by DirectWrite ([`crate::win32::text_rasterizer`]): the fonts' shapes and, with them,
+/// whole-pixel widths, so a letter's width and the place it is drawn for finally agree. That
+/// disagreement is what glued some letters together and pushed others apart. Set again when the
+/// interface's direction changes: a right-to-left line needs its brackets mirrored by the shaper.
+#[cfg(windows)]
+fn classic_text(ctx: &egui::Context) {
+ use std::sync::atomic::{AtomicI8, Ordering};
+ static RTL: AtomicI8 = AtomicI8::new(-1);
+ let rtl = crate::i18n::rtl();
+ if RTL.swap(i8::from(rtl), Ordering::Relaxed) != i8::from(rtl) {
+ ctx.set_glyph_rasterizers(
+ crate::win32::text_rasterizer(font_dir(), rtl)
+ .into_iter()
+ .collect(),
+ );
+ }
+}
+
+/// The text [`classic_text`] leaves to egui (Arabic, Hebrew, Indic, Thai, CJK; marks clustered
+/// with their letter), fitted to whole pixels (#262) with hinting for egui's anti-aliased output.
+/// Mono hinting targets black-and-white bitmaps: at small sizes it can distort curves and make
+/// diagonals jagged. Smooth hinting keeps those outlines suited to coverage rendering, while
+/// allowing horizontal grid-fitting so upright strokes stay sharp. Keep whole-pixel glyph origins
+/// and the shaper's advances, so this changes neither layout nor the interface size. Linux and
+/// macOS keep egui's defaults.
#[cfg(windows)]
fn sharp_text(defs: &mut egui::FontDefinitions) {
for data in defs.font_data.values_mut() {
let data = std::sync::Arc::make_mut(data);
- data.tweak.hinting_target = egui::epaint::text::HintingTarget::Mono;
+ data.tweak.hinting_target =
+ egui::epaint::text::HintingTarget::Smooth(egui::epaint::text::SmoothHinting {
+ light: false,
+ symmetric_rendering: false,
+ preserve_linear_metrics: false,
+ });
data.tweak.subpixel_binning = Some(false);
}
}
diff --git a/crates/app/src/win32.rs b/crates/app/src/win32.rs
index 6518fb7c..46772ade 100644
--- a/crates/app/src/win32.rs
+++ b/crates/app/src/win32.rs
@@ -4394,3 +4394,320 @@ pub fn keep_awake(reason: Option<&str>) -> bool {
*held = Some(h as isize);
true
}
+
+/// Latin, Greek and Cyrillic text as Windows' classic controls draw it, in grey (#262, #323,
+/// #334): each letter's shape and width come from the font's own hinting for this size, through
+/// DirectWrite's GDI-classic mode. Before, egui placed letters by their unhinted widths rounded
+/// to whole pixels while the letters themselves were fitted to pixels: the two disagreed by up to
+/// a pixel, so letters touched in one place ("download") and stood apart in another ("Resum e").
+///
+/// `None` from DirectWrite's factory or a font's file keeps egui's rasterizer. A cluster it isn't
+/// for ([`classic_char`]) is left to egui too, which shapes it. The rasterizer is told the
+/// interface's direction: a bracket in a right-to-left line is mirrored by the shaper, so those
+/// stay with egui there.
+pub fn text_rasterizer(
+ font_dir: std::path::PathBuf,
+ rtl: bool,
+) -> Option<egui::epaint::text::GlyphRasterizer> {
+ let glyphs = classic_text::Glyphs::new(font_dir)
+ .map_err(|e| tracing::warn!("text: DirectWrite unavailable, egui draws the text ({e})"))
+ .ok()?;
+ let glyphs = std::sync::Mutex::new(glyphs);
+ Some(
+ egui::epaint::text::GlyphRasterizer::new(
+ "mdm::win32::classic_text",
+ move |req: &egui::epaint::text::GlyphRasterizerRequest<'_>| {
+ glyphs.lock().ok()?.glyph(req, rtl)
+ },
+ )
+ .with_priority(egui::epaint::text::FontPriority::Highest),
+ )
+}
+
+/// Does [`text_rasterizer`] draw this character? One code point that needs no shaping: Latin,
+/// Greek and Cyrillic letters, digits and punctuation. Scripts whose letters change shape (Arabic,
+/// Indic, ...) and the invisible marks are left to egui and its shaper; so are the brackets of a
+/// right-to-left line, which the shaper mirrors.
+fn classic_char(c: char, rtl: bool) -> bool {
+ if rtl
+ && matches!(
+ c,
+ '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>' | '«' | '»' | '‹' | '›'
+ )
+ {
+ return false;
+ }
+ matches!(c,
+ ' '..='~'
+ | '\u{A0}'..='\u{AC}' // Latin-1, without the soft hyphen
+ | '\u{AE}'..='\u{2AF}' // Latin Extended and IPA
+ | '\u{370}'..='\u{3FF}' // Greek
+ | '\u{400}'..='\u{52F}' // Cyrillic
+ | '\u{1E00}'..='\u{1EFF}' // Vietnamese and other precomposed Latin
+ | '\u{2010}'..='\u{2027}' // dashes, quotes, bullets, ellipsis
+ | '\u{2030}'..='\u{205E}' // per mille, primes, guillemets
+ | '\u{20A0}'..='\u{20BF}' // currency
+ )
+}
+
+/// The font file of a family `theme.rs` sets up (Segoe UI leads the two built-in ones).
+fn classic_font_file(family: &egui::FontFamily) -> Option<&'static str> {
+ match family {
+ egui::FontFamily::Proportional | egui::FontFamily::Monospace => Some("segoeui.ttf"),
+ egui::FontFamily::Name(name) => match &**name {
+ "tahoma" => Some("tahoma.ttf"),
+ "tahoma-bold" => Some("tahomabd.ttf"),
+ "arial-bold" => Some("arialbd.ttf"),
+ _ => None,
+ },
+ }
+}
+
+mod classic_text {
+ use std::collections::HashMap;
+ use std::os::windows::ffi::OsStrExt as _;
+ use std::path::PathBuf;
+
+ use egui::epaint::text::{GlyphBitmap, GlyphRasterizerRequest, RasterizedGlyph};
+ use egui::epaint::{Color32, ColorImage};
+ use windows::Win32::Graphics::DirectWrite::{
+ DWRITE_FACTORY_TYPE_SHARED, DWRITE_FONT_FACE_TYPE_TRUETYPE, DWRITE_FONT_METRICS,
+ DWRITE_FONT_SIMULATIONS_NONE, DWRITE_GLYPH_METRICS, DWRITE_GLYPH_OFFSET, DWRITE_GLYPH_RUN,
+ DWRITE_GRID_FIT_MODE_ENABLED, DWRITE_MEASURING_MODE_GDI_CLASSIC,
+ DWRITE_RENDERING_MODE_GDI_CLASSIC, DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE,
+ DWRITE_TEXTURE_ALIASED_1x1, DWriteCreateFactory, IDWriteFactory2, IDWriteFontFace,
+ };
+
+ pub struct Glyphs {
+ factory: IDWriteFactory2,
+ dir: PathBuf,
+ /// The font files opened so far; `None` for one DirectWrite can't use.
+ faces: HashMap<&'static str, Option<IDWriteFontFace>>,
+ }
+
+ // SAFETY: DirectWrite's shared factory and the objects it makes are free-threaded
+ // (documented thread-safe); `Glyphs` is only used behind a Mutex.
+ unsafe impl Send for Glyphs {}
+
+ impl Glyphs {
+ pub fn new(dir: PathBuf) -> windows::core::Result<Glyphs> {
+ // SAFETY: a plain COM call.
+ let factory: IDWriteFactory2 =
+ unsafe { DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)? };
+ Ok(Glyphs {
+ factory,
+ dir,
+ faces: HashMap::new(),
+ })
+ }
+
+ fn face(&mut self, file: &'static str) -> Option<IDWriteFontFace> {
+ let (factory, dir) = (&self.factory, &self.dir);
+ self.faces
+ .entry(file)
+ .or_insert_with(|| {
+ let path: Vec<u16> = dir
+ .join(file)
+ .as_os_str()
+ .encode_wide()
+ .chain([0])
+ .collect();
+ // SAFETY: `path` is NUL-terminated and outlives the calls; plain COM calls.
+ unsafe {
+ let font = factory
+ .CreateFontFileReference(windows::core::PCWSTR(path.as_ptr()), None)
+ .ok()?;
+ factory
+ .CreateFontFace(
+ DWRITE_FONT_FACE_TYPE_TRUETYPE,
+ &[Some(font)],
+ 0,
+ DWRITE_FONT_SIMULATIONS_NONE,
+ )
+ .ok()
+ }
+ })
+ .clone()
+ }
+
+ pub fn glyph(
+ &mut self,
+ req: &GlyphRasterizerRequest<'_>,
+ rtl: bool,
+ ) -> Option<RasterizedGlyph> {
+ let mut chars = req.cluster.chars();
+ let ch = chars.next()?;
+ if chars.next().is_some() || !super::classic_char(ch, rtl) {
+ return None;
+ }
+ if req.font_size_px.is_nan() || req.font_size_px < 1.0 {
+ return None;
+ }
+ let face = self.face(super::classic_font_file(req.family)?)?;
+ // GDI's sizes are whole pixels.
+ let em = req.font_size_px.round();
+ let mut id = 0u16;
+ let mut metrics = DWRITE_GLYPH_METRICS::default();
+ let mut font = DWRITE_FONT_METRICS::default();
+ // SAFETY: each pointer is to one element, the count given.
+ unsafe {
+ face.GetGlyphIndices(&(ch as u32), 1, &mut id).ok()?;
+ if id == 0 {
+ return None;
+ }
+ face.GetGdiCompatibleGlyphMetrics(
+ em,
+ 1.0,
+ None,
+ false,
+ &id,
+ 1,
+ &mut metrics,
+ false,
+ )
+ .ok()?;
+ face.GetMetrics(&mut font);
+ }
+ let advance_px =
+ (metrics.advanceWidth as f32 * em / f32::from(font.designUnitsPerEm)).round();
+ let bitmap = self.draw(face, id, em).unwrap_or(GlyphBitmap {
+ // A space: egui still wants a bitmap to carry the advance.
+ image: ColorImage::new([1, 1], vec![Color32::TRANSPARENT]),
+ offset_px: egui::vec2(0.0, 0.0),
+ is_color: false,
+ });
+ Some(RasterizedGlyph { bitmap, advance_px })
+ }
+
+ /// The glyph in grey, placed from its origin; `None` when it has no ink.
+ fn draw(&self, face: IDWriteFontFace, id: u16, em: f32) -> Option<GlyphBitmap> {
+ let (ids, advances, offsets) = ([id], [0f32], [DWRITE_GLYPH_OFFSET::default()]);
+ let run = DWRITE_GLYPH_RUN {
+ fontFace: std::mem::ManuallyDrop::new(Some(face)),
+ fontEmSize: em,
+ glyphCount: 1,
+ glyphIndices: ids.as_ptr(),
+ glyphAdvances: advances.as_ptr(),
+ glyphOffsets: offsets.as_ptr(),
+ isSideways: false.into(),
+ bidiLevel: 0,
+ };
+ // SAFETY: `run` and the arrays it points to live through the calls; the texture
+ // buffer is exactly the bounds' size.
+ let drawn = unsafe {
+ self.factory
+ .CreateGlyphRunAnalysis(
+ &run,
+ None,
+ DWRITE_RENDERING_MODE_GDI_CLASSIC,
+ DWRITE_MEASURING_MODE_GDI_CLASSIC,
+ DWRITE_GRID_FIT_MODE_ENABLED,
+ DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE,
+ 0.0,
+ 0.0,
+ )
+ .and_then(|a| {
+ let r = a.GetAlphaTextureBounds(DWRITE_TEXTURE_ALIASED_1x1)?;
+ let w = (r.right - r.left).max(0) as usize;
+ let h = (r.bottom - r.top).max(0) as usize;
+ let mut coverage = vec![0u8; w * h];
+ if w > 0 && h > 0 {
+ a.CreateAlphaTexture(DWRITE_TEXTURE_ALIASED_1x1, &r, &mut coverage)?;
+ }
+ Ok((r, w, h, coverage))
+ })
+ };
+ drop(std::mem::ManuallyDrop::into_inner(run.fontFace));
+ let (r, w, h, coverage) = drawn.ok()?;
+ if w == 0 || h == 0 {
+ return None;
+ }
+ // White with alpha, premultiplied (`GlyphBitmap`).
+ let pixels = coverage
+ .into_iter()
+ .map(|a| Color32::from_rgba_premultiplied(a, a, a, a))
+ .collect();
+ Some(GlyphBitmap {
+ image: ColorImage::new([w, h], pixels),
+ offset_px: egui::vec2(r.left as f32, r.top as f32),
+ is_color: false,
+ })
+ }
+ }
+}
+
+#[cfg(test)]
+mod classic_text_tests {
+ use egui::FontFamily;
+ use egui::epaint::text::GlyphRasterizerRequest;
+
+ fn glyphs() -> super::classic_text::Glyphs {
+ let dir = std::env::var_os("WINDIR")
+ .map(|w| std::path::PathBuf::from(w).join("Fonts"))
+ .unwrap();
+ super::classic_text::Glyphs::new(dir).unwrap()
+ }
+
+ fn req<'a>(cluster: &'a str, family: &'a FontFamily, size: f32) -> GlyphRasterizerRequest<'a> {
+ GlyphRasterizerRequest {
+ cluster,
+ family,
+ font_size_px: size,
+ subpixel_offset_px: 0.0,
+ }
+ }
+
+ /// #334: every letter gets a whole pixel width, and is drawn within it: the two can't drift
+ /// apart any more. The letters of the words the report names, at the sizes of 100 % to 200 %.
+ #[test]
+ fn letters_have_whole_pixel_advances_and_stay_inside_them() {
+ let mut g = glyphs();
+ for family in [FontFamily::Proportional, FontFamily::Name("tahoma".into())] {
+ for size in [11.0, 12.0, 13.2, 15.0, 16.5, 18.0, 24.0] {
+ for ch in "downloadefaultakeDRsum".chars() {
+ let text = ch.to_string();
+ let glyph = g.glyph(&req(&text, &family, size), false).unwrap();
+ assert_eq!(glyph.advance_px.fract(), 0.0, "{ch} at {size}");
+ assert!(glyph.advance_px >= 1.0, "{ch} at {size}");
+ let right = glyph.bitmap.offset_px.x + glyph.bitmap.image.size[0] as f32;
+ assert!(
+ right <= glyph.advance_px + 1.0,
+ "{ch} at {size}: ink ends at {right}, advance {}",
+ glyph.advance_px
+ );
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn a_space_keeps_its_advance() {
+ let mut g = glyphs();
+ let s = g
+ .glyph(&req(" ", &FontFamily::Proportional, 12.0), false)
+ .unwrap();
+ assert!(s.advance_px > 0.0);
+ }
+
+ #[test]
+ fn what_needs_shaping_stays_with_egui() {
+ let mut g = glyphs();
+ let f = FontFamily::Proportional;
+ for not in [
+ "\u{62a}",
+ "\u{5d0}",
+ "\u{93e}",
+ "\u{e14}",
+ "e\u{301}",
+ "\u{1F600}",
+ ] {
+ assert!(g.glyph(&req(not, &f, 12.0), false).is_none(), "{not:?}");
+ }
+ // A bracket is mirrored by the shaper in a right-to-left line, only.
+ assert!(g.glyph(&req("(", &f, 12.0), false).is_some());
+ assert!(g.glyph(&req("(", &f, 12.0), true).is_none());
+ // A family it isn't told about stays with egui.
+ let other = FontFamily::Name("other".into());
+ assert!(g.glyph(&req("a", &other, 12.0), false).is_none());
+ }
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 128d00b1..3e8fe09b 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -66,7 +66,10 @@ toolbar, key and IPC commands into actions. Each dialog is its own module and re
`Outcome` (open, closed, done with a value). Windows-only calls are confined to `win32.rs` and
their Linux and macOS counterparts to `unix.rs` (starting with the session, the browsers' host,
sounds, show in folder, the crash handler); every other file is safe, portable Rust. Fonts come from the system:
-Windows' Fonts folder, macOS's system fonts, fontconfig on Linux (`theme.rs`).
+Windows' Fonts folder, macOS's system fonts, fontconfig on Linux (`theme.rs`). On Windows, Latin,
+Greek and Cyrillic text is drawn by DirectWrite in GDI-classic mode (`win32.rs`, through egui's
+glyph rasterizer hook), so each letter's hinted shape and whole-pixel width come together; other
+scripts are shaped and drawn by egui.
### Themes