misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
The drop target is a plain pop-up window too: no black band across its top (#208) (#231)
Ahmed Nefzaouie303c6d8da8d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ffe0a2f4..0bb28187 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -563,13 +563,15 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, seeon its own, with the file still open, and renaming the finished file failed. The connections arenow told to stop and waited for, when a download completes and when it is stopped or fails, sonone of them outlives it. A stopped download's last writes are also in its saved progress now.-- **Menus without a black band across their top**+- **Menus and the drop target without a black band across their top**([#208](https://github.com/anefzaoui/misterdownloadmanager/issues/208)): on a Windows 11Insider build (22635), every menu and submenu showed a black band a title bar tall across itstop and a thin one down its left side, its items moved down by as much and its last ones cut- off. A menu's window had a title bar's style, hidden by MDM, and something on that build placed- the menu's picture where the title bar would have ended. Menus are now plain pop-up windows, as- Windows' own menus are, with nothing above their items to take for a title bar.+ off; so did the drop target (Tasks → Show drop target), its icon moved down. Each of these+ windows had a title bar's style, hidden by MDM, and something on that build placed the window's+ picture where the title bar would have ended. Menus and the drop target are now plain pop-up+ windows, as Windows' own menus are, with nothing above their contents to take for a title bar;+ every window of MDM without a title bar is made one the same way.- **A window closed with its title bar's × no longer turns black first**([#207](https://github.com/anefzaoui/misterdownloadmanager/issues/207)): every dialog and theprogress window turned black for a moment when closed with the × or Alt+F4, rather than withdiff --git a/ROADMAP.md b/ROADMAP.mdindex 28b53951..561fde32 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -281,9 +281,10 @@ Everything below ships together, in one release, as version 0.3.0.### Bugs being looked into-- 🔍 Menus with a black band across their top on a Windows 11 Insider build- ([#208](https://github.com/anefzaoui/misterdownloadmanager/issues/208)): menus are now plain- pop-up windows, as Windows' own are; a test build is with the reporter+- 🔍 Menus and the drop target with a black band across their top on a Windows 11 Insider build+ ([#208](https://github.com/anefzaoui/misterdownloadmanager/issues/208)): menus are plain pop-up+ windows now, as Windows' own are, and the reporter confirmed them fixed; the drop target is one+ too, its test build is with the reporter- 🔍 A freeze of the window on start ([#57](https://github.com/anefzaoui/misterdownloadmanager/issues/57)):most likely a computer busy just after start; freeze reports now measure it, so the next one says- 🔍 A crash on Linux as Download File Info opensdiff --git a/crates/app/src/app.rs b/crates/app/src/app.rsindex 2339c7be..9a800da2 100644--- a/crates/app/src/app.rs+++ b/crates/app/src/app.rs@@ -1683,6 +1683,13 @@ impl App {}// The main window into the tray, as closing it does (tests and #72's measurements)."tray" => self.hide_to_tray(ctx),+ // Off-screen test copies: the drop target's menu, as a right-click on it opens it+ // (#208's checks; a posted click has no pointer position by the time it is seen).+ "drop-target-menu" if crate::offscreen() => {+ if let Some(at) = self.drop_target.as_ref().map(|d| d.center()) {+ self.drop_target_menu(at, ctx);+ }+ }// The main window minimized, not to the tray (tests of #162)."minimized" => ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true)),// Off-screen test copies: the interface zoomed (`zoom:1.5`) while running, as a@@ -6248,13 +6255,7 @@ impl App {match ev {Event::Drop(s) => self.dropped(vec![s], ctx),Event::ShowMain => self.show_window(ctx),- Event::Context(screen) => {- // Popups take a point in the main window.- let origin = ctx- .input(|i| i.viewport().inner_rect)- .map_or(Pos2::ZERO, |r| r.min);- self.open_popup(Popup::DropTarget, screen - origin.to_vec2());- }+ Event::Context(screen) => self.drop_target_menu(screen, ctx),Event::Moved(p) => {self.settings.drop_target_pos = Some((p.x.round() as i32, p.y.round() as i32));self.dirty = true;@@ -6263,6 +6264,15 @@ impl App {}}+ /// The drop target's menu at `screen` (a point on the screen, logical points).+ fn drop_target_menu(&mut self, screen: Pos2, ctx: &egui::Context) {+ // Popups take a point in the main window.+ let origin = ctx+ .input(|i| i.viewport().inner_rect)+ .map_or(Pos2::ZERO, |r| r.min);+ self.open_popup(Popup::DropTarget, screen - origin.to_vec2());+ }+/// Tasks → Export: every download's address, as an IDM export file or plain text.fn export(&mut self, ef2: bool) {let (ext, name) = if ef2 {diff --git a/crates/app/src/chrome.rs b/crates/app/src/chrome.rsindex a54f06f6..13044c47 100644--- a/crates/app/src/chrome.rs+++ b/crates/app/src/chrome.rs@@ -791,6 +791,70 @@ fn menu_size<C>(vec2(38.0 + widest + if has_sub { 48.0 } else { 30.0 }, h + 6.0)}+/// How a borderless window of ours looks and takes the pointer ([`style_popup`]).+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum PopupLook {+ /// A menu: never activated (the main window keeps the focus), small rounded corners and+ /// the menu's border, no open animation.+ Menu,+ /// A small floating window (the drop target): activated as any window, rounded corners.+ Floating,+}++/// The builder of every borderless window of ours (a menu, the drop target): no title bar, not+/// resizable, no taskbar button, always on top. On Windows it is created hidden: its first pass+/// makes it a plain popup ([`style_popup`]) and [`show_popup`] shows it then.+pub fn popup_viewport(title: &str) -> egui::ViewportBuilder {+ egui::ViewportBuilder::default()+ .with_title(title)+ .with_decorations(false)+ .with_resizable(false)+ .with_taskbar(false)+ .with_always_on_top()+ // Hidden until styled, then shown (show_popup).+ .with_visible(!cfg!(windows))+}++/// Call first in the pass of a borderless window titled `title` (made with [`popup_viewport`]),+/// before anything is drawn in it. On Windows it becomes a plain popup window, its client the+/// whole window (win32::popup_window): winit's borderless windows keep a caption style, which+/// on a Windows 11 Insider build (22635) put a black band a title bar tall across the top of+/// every menu and of the drop target, their picture moved down by as much (#208). Styled in+/// the window's own pass: its frame changes, and a picture drawn before that was lost with the+/// old frame (black until something made it draw again). True on the pass that styled it: show+/// it then ([`show_popup`]). Elsewhere nothing to do (false).+#[cfg_attr(not(windows), allow(unused_variables))]+pub fn style_popup(title: &str, look: PopupLook) -> bool {+ #[cfg(windows)]+ {+ use crate::win32::Popup;+ let kind = match look {+ PopupLook::Menu => Popup::Menu {+ border: u32::from_le_bytes([+ POPUP_BORDER().r(),+ POPUP_BORDER().g(),+ POPUP_BORDER().b(),+ 0,+ ]),+ },+ PopupLook::Floating => Popup::Floating,+ };+ crate::win32::popup_window(title, kind)+ }+ #[cfg(not(windows))]+ false+}++/// Show the borderless window `vid` [`style_popup`] just styled (from its parent's pass).+pub fn show_popup(ctx: &egui::Context, vid: egui::ViewportId) {+ ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::Visible(true));+ // The command is carried out on the window's next frame: a menu opened from the keyboard+ // (Shift+F10, the Menu key) or a screen reader moves no pointer to bring one, and stayed+ // hidden (#113).+ ctx.request_repaint_of(vid);+ ctx.request_repaint();+}+/// Place a menu of `size` at screen point `at`, flipped to stay inside the monitor's work area:/// up (or left) of the point, or for a submenu (`parent`: the parent menu's screen rect) to the/// parent's left side. In a right-to-left interface `at` is the menu's top-right: it opens to@@ -856,15 +920,8 @@ fn popup_level<C: Clone>(.and_then(|(a, b)| if depth == 0 { a } else { b });let screen = Rect::from_min_size(place_menu(at, size, parent), size);let title = format!("misterdownloadmanager menu {depth}"); // not translated: an id- let builder = egui::ViewportBuilder::default()- .with_title(title.clone())- .with_decorations(false)- .with_resizable(false)- .with_taskbar(false)- .with_always_on_top()+ let builder = popup_viewport(&title).with_active(false)- // Hidden until styled (no open animation, no activation), then shown below.- .with_visible(!cfg!(windows)).with_position(screen.min).with_inner_size(size);let open_sub = if depth == 0 {@@ -878,24 +935,10 @@ fn popup_level<C: Clone>(let parent_vid = ctx.viewport_id();// Set when this pass made the new (hidden) window a menu window: shown below. (Elsewhere a// menu's window is created visible.)- #[cfg_attr(not(windows), allow(unused_mut))]let mut styled = false;ctx.show_viewport_immediate(vid, builder, |ui, _| {- // Made a menu window (win32::menu_window) in its own pass, before anything is drawn in- // it: its frame changes (#208), and a picture drawn before that was lost with the old- // frame, so the menu showed black until something made it draw again.- #[cfg(windows)]- {- styled = crate::win32::menu_window(- &title,- u32::from_le_bytes([- POPUP_BORDER().r(),- POPUP_BORDER().g(),- POPUP_BORDER().b(),- 0,- ]),- );- }+ // Made a menu window in its own pass, before anything is drawn in it (style_popup).+ styled = style_popup(&title, PopupLook::Menu);// What happens in this window, for popup() and keyboard(), which run in the parent's// pass: they must not ask egui about a menu window by its id, which creates one when it// isn't open (a submenu, mostly): an untitled copy of the main window, opened and closed@@ -921,7 +964,7 @@ fn popup_level<C: Clone>(// arrow on the left pointing left.let _surface = winui::Surface::enter(o.x, o.x + w);let rtl = winui::rtl();- // Body; Windows 11 rounds the window and draws the border and shadow (menu_window).+ // Body; Windows 11 rounds the window and draws the border and shadow (style_popup).fill(&painter,o.x,@@ -1161,12 +1204,7 @@ fn popup_level<C: Clone>(}});if styled {- ctx.send_viewport_cmd_to(vid, egui::ViewportCommand::Visible(true));- // The command is carried out on the menu's next frame: a menu opened from the keyboard- // (Shift+F10, the Menu key) or a screen reader moves no pointer to bring one, and stayed- // hidden (#113).- ctx.request_repaint_of(vid);- ctx.request_repaint();+ show_popup(ctx, vid);}if let Some((i, slot_y)) = sub_at&& let MenuEntry::Sub(_, _, children) = &entries[i]diff --git a/crates/app/src/droptarget.rs b/crates/app/src/droptarget.rsindex 3b130090..9bca3c91 100644--- a/crates/app/src/droptarget.rs+++ b/crates/app/src/droptarget.rs@@ -8,7 +8,7 @@use std::sync::mpsc::{Receiver, Sender, channel};use std::sync::{Arc, atomic::AtomicBool, atomic::Ordering};-use egui::{Pos2, ViewportBuilder, ViewportCommand, ViewportId, pos2, vec2};+use egui::{Pos2, ViewportCommand, ViewportId, pos2, vec2};/// The window's title (its OLE target is found by it).const TITLE: &str = "Mister Download Manager drop target"; // not translated: an id@@ -81,6 +81,9 @@ impl Drops {pub struct DropTarget {drops: Drops,pos: Pos2,+ /// MDM_TEST_DROP's link was dropped (once).+ #[cfg(windows)]+ test_dropped: bool,}impl DropTarget {@@ -88,6 +91,8 @@ impl DropTarget {DropTarget {drops: Drops::default(),pos: pos.unwrap_or(pos2(200.0, 200.0)),+ #[cfg(windows)]+ test_dropped: false,}}@@ -98,19 +103,31 @@ impl DropTarget {.into_iter().map(Event::Drop).collect();- let builder = ViewportBuilder::default()- .with_title(TITLE)- .with_decorations(false)- .with_resizable(false)- .with_taskbar(false)- .with_always_on_top()+ // Off-screen test copies: MDM_TEST_DROP=<link> is dropped on the box once, through its+ // OLE drop target, as a browser drops one (#208's checks: it still takes links as a+ // popup window). Taken at the next poll, as a real drop is.+ #[cfg(windows)]+ if !self.test_dropped+ && let Some(ole) = &self.drops.ole+ && crate::offscreen()+ && let Ok(link) = std::env::var("MDM_TEST_DROP")+ {+ self.test_dropped = true;+ ole.test_drop(&link);+ }+ // A borderless window as menus are (a plain popup on Windows, #208).+ let builder = crate::chrome::popup_viewport(TITLE)// Windows: our own OLE target takes links and files; elsewhere winit's own// (files only: macOS and Linux hand links over no other way here)..with_drag_and_drop(!cfg!(windows)).with_position(self.pos).with_inner_size(vec2(SIZE, SIZE));let over = self.drops.over();- ctx.show_viewport_immediate(ViewportId::from_hash_of("drop-target"), builder, |ui, _| {+ let vid = ViewportId::from_hash_of("drop-target");+ let mut styled = false;+ ctx.show_viewport_immediate(vid, builder, |ui, _| {+ // Styled in its own pass, before anything is drawn in it.+ styled = crate::chrome::style_popup(TITLE, crate::chrome::PopupLook::Floating);let rect = ui.max_rect();let p = ui.painter();let (fill, edge) = if over {@@ -175,6 +192,15 @@ impl DropTarget {events.push(Event::Moved(r.min));}});+ if styled {+ crate::chrome::show_popup(ctx, vid);+ }events}++ /// The middle of the box (screen, logical points): where a right-click opens its menu in+ /// the off-screen checks (`/show drop-target-menu`).+ pub fn center(&self) -> Pos2 {+ self.pos + vec2(SIZE, SIZE) / 2.0+ }}diff --git a/crates/app/src/win32.rs b/crates/app/src/win32.rsindex 1ad75846..d9d928aa 100644--- a/crates/app/src/win32.rs+++ b/crates/app/src/win32.rs@@ -699,14 +699,33 @@ pub fn main_minimize_to_tray(ctx: &egui::Context, enabled: bool) -> bool {})}-/// A menu window's style: a plain popup, as Win32's own menus are, without the caption, frame-/// and caption buttons winit gives every borderless window (it keeps WS_CAPTION and hides the-/// frame in WM_NCCALCSIZE). With a caption style, whatever lays the window out by its styles-/// rather than by our WM_NCCALCSIZE puts the client a caption lower and a frame to the right:-/// on a Windows 11 Insider build (22635) each menu showed a black band a caption tall across-/// its top and its items moved down by as much (#208). Without one, every reading agrees: the-/// client is the whole window.-pub(crate) fn menu_style(style: u32) -> u32 {+/// What a borderless window of ours is, for [`popup_window`]: every one is a plain popup+/// ([`popup_style`], #208); they differ in how they take the pointer and how they look.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Popup {+ /// A menu (chrome.rs): never activated, so the main window keeps the focus and the+ /// keyboard; Windows 11's small rounded corners and a 1 px border in this colour+ /// (0x00BBGGRR); no window-open animation (menus just appear).+ Menu { border: u32 },+ /// A small floating window (the drop target, droptarget.rs): activated when clicked, as+ /// any window; Windows 11's rounded corners, border and shadow, as it had with its caption+ /// style.+ Floating,+}++/// The subclass of every borderless window of ours ([`popup_proc`]): its id, and its data's+/// flag for a window never activated (a menu).+const POPUP_SUBCLASS: usize = 0x3e1;+const POPUP_NO_ACTIVATE: usize = 1;++/// A borderless window's style: a plain popup, as Win32's own menus are, without the caption,+/// frame and caption buttons winit gives every borderless window (it keeps WS_CAPTION and hides+/// the frame in WM_NCCALCSIZE). With a caption style, whatever lays the window out by its+/// styles rather than by our WM_NCCALCSIZE puts the client a caption lower and a frame to the+/// right: on a Windows 11 Insider build (22635) each menu, and the drop target, showed a black+/// band a caption tall across its top and its picture moved down by as much (#208). Without+/// one, every reading agrees: the client is the whole window.+pub(crate) fn popup_style(style: u32) -> u32 {use windows_sys::Win32::UI::WindowsAndMessaging::{WS_CAPTION, WS_MAXIMIZEBOX, WS_MINIMIZEBOX, WS_POPUP, WS_SYSMENU,};@@ -714,83 +733,200 @@ pub(crate) fn menu_style(style: u32) -> u32 {| WS_POPUP}+/// The extended styles a borderless window keeps: no taskbar button or Alt+Tab entry (a tool+/// window, without the app window style winit gives every window, which asks for a button),+/// and a menu is never activated.+fn popup_ex_style(ex: u32, no_activate: bool) -> u32 {+ use windows_sys::Win32::UI::WindowsAndMessaging::{+ WS_EX_APPWINDOW, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,+ };+ (ex & !WS_EX_APPWINDOW) | WS_EX_TOOLWINDOW | if no_activate { WS_EX_NOACTIVATE } else { 0 }+}+#[cfg(test)]-mod menu_style_tests {+mod popup_style_tests {use super::*;use windows_sys::Win32::Foundation::RECT;use windows_sys::Win32::UI::WindowsAndMessaging::{- AdjustWindowRectEx, WS_CLIPCHILDREN, WS_CLIPSIBLINGS, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,- WS_EX_TOPMOST, WS_POPUP, WS_VISIBLE,+ AdjustWindowRectEx, WS_CLIPCHILDREN, WS_CLIPSIBLINGS, WS_EX_APPWINDOW, WS_EX_NOACTIVATE,+ WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP, WS_VISIBLE,};- /// winit's borderless window as it creates a menu (style 0x16CB0000: a caption, system- /// menu, minimize and maximize boxes) and the extended styles menu_window gives it.- const WINIT_MENU: u32 = 0x16CB_0000;+ /// winit's borderless window as it creates a menu or the drop target (style 0x16CB0000: a+ /// caption, system menu, minimize and maximize boxes), and the extended styles+ /// popup_window gives a menu and the drop target (always on top, a window edge).+ const WINIT_BORDERLESS: u32 = 0x16CB_0000;const MENU_EX: u32 = 0x0804_0198;+ const DROP_TARGET_EX: u32 = 0x0000_0198;- fn frame(style: u32, ex: u32) -> [i32; 4] {+ /// The frame (left, top, right, bottom) the styles alone put round a `w` × `h` client: what+ /// a reader of the styles, rather than of our WM_NCCALCSIZE, takes for it.+ fn frame(style: u32, ex: u32, w: i32, h: i32) -> [i32; 4] {let mut rc = RECT {left: 0,top: 0,- right: 279,- bottom: 275,+ right: w,+ bottom: h,};// SAFETY: plain computation on a local rectangle.unsafe { AdjustWindowRectEx(&mut rc, style, 0, ex) };- [-rc.left, -rc.top, rc.right - 279, rc.bottom - 275]+ [-rc.left, -rc.top, rc.right - w, rc.bottom - h]}#[test]fn a_menu_window_is_a_popup_whose_client_is_all_of_it() {// As created, the styles alone give it a caption and a frame: what a reader of the// styles (rather than of our WM_NCCALCSIZE) took for its client on build 22635 (#208).- assert_ne!(frame(WINIT_MENU, MENU_EX), [0, 0, 0, 0]);- let style = menu_style(WINIT_MENU);+ assert_ne!(frame(WINIT_BORDERLESS, MENU_EX, 279, 275), [0, 0, 0, 0]);+ let style = popup_style(WINIT_BORDERLESS);assert_eq!(style,WS_POPUP | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);// As a popup, no reading of its styles finds a frame (at any scale: none to scale).- assert_eq!(frame(style, MENU_EX), [0, 0, 0, 0]);+ assert_eq!(frame(style, MENU_EX, 279, 275), [0, 0, 0, 0]);// Applied again (winit setting its styles once more), nothing changes.- assert_eq!(menu_style(style), style);+ assert_eq!(popup_style(style), style);}#[test]- fn a_menu_window_keeps_its_extended_styles() {- // winit's own extended styles for it, without ours: they come back.- let winit_ex = WS_EX_TOPMOST | 0x0000_0100 | 0x0000_0010;- let ex = menu_ex_style(winit_ex);- assert_eq!(ex & WS_EX_NOACTIVATE, WS_EX_NOACTIVATE);- assert_eq!(ex & WS_EX_TOOLWINDOW, WS_EX_TOOLWINDOW);- assert_eq!(ex & WS_EX_TOPMOST, WS_EX_TOPMOST);+ fn the_drop_target_is_a_popup_whose_client_is_all_of_it() {+ // The black band left on build 22635 once menus were fixed (#208): a caption about+ // 26 px tall over the 56 px box, its picture moved down by as much.+ let [_, top, _, _] = frame(WINIT_BORDERLESS, 0x0004_0118, 56, 56);+ assert!(top > 20, "a caption's height above its client: {top}");+ let style = popup_style(WINIT_BORDERLESS);+ assert_eq!(+ style,+ WS_POPUP | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN+ );+ // As winit makes it (always on top, a window edge, files accepted, an app window).+ let ex = popup_ex_style(0x0004_0118, false);+ assert_eq!(ex, DROP_TARGET_EX);+ assert_eq!(frame(style, ex, 56, 56), [0, 0, 0, 0]);+ assert_eq!(popup_style(style), style);}-}-/// The extended styles a menu window keeps: never activated, no taskbar button or Alt+Tab entry.-fn menu_ex_style(ex: u32) -> u32 {- use windows_sys::Win32::UI::WindowsAndMessaging::{WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW};- ex | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW+ #[test]+ fn a_popup_keeps_its_extended_styles() {+ // winit's own extended styles for it (always on top, a window edge, files accepted,+ // an app window), without ours: they come back, but for the app window's.+ let winit_ex = WS_EX_TOPMOST | 0x0000_0100 | 0x0000_0010 | WS_EX_APPWINDOW;+ let menu = popup_ex_style(winit_ex, true);+ assert_eq!(menu & WS_EX_APPWINDOW, 0);+ assert_eq!(menu & WS_EX_NOACTIVATE, WS_EX_NOACTIVATE);+ assert_eq!(menu & WS_EX_TOOLWINDOW, WS_EX_TOOLWINDOW);+ assert_eq!(menu & WS_EX_TOPMOST, WS_EX_TOPMOST);+ // The drop target is activated as any window (a click on it, a drag), but has no+ // taskbar button either; an off-screen test copy's never-activate stays.+ let floating = popup_ex_style(winit_ex, false);+ assert_eq!(floating & WS_EX_NOACTIVATE, 0);+ assert_eq!(floating & WS_EX_TOOLWINDOW, WS_EX_TOOLWINDOW);+ assert_eq!(floating & WS_EX_TOPMOST, WS_EX_TOPMOST);+ assert_eq!(+ popup_ex_style(winit_ex | WS_EX_NOACTIVATE, false) & WS_EX_NOACTIVATE,+ WS_EX_NOACTIVATE+ );+ }++ /// A real (hidden, off-screen) window with winit's borderless styles, made a popup by+ /// popup_window: plain popup styles, its client the whole window, and both kept when its+ /// styles are set again (winit does on every change of its flags).+ #[test]+ fn popup_window_makes_a_real_window_a_popup_and_keeps_it_one() {+ use windows_sys::Win32::UI::WindowsAndMessaging::{+ CreateWindowExW, DestroyWindow, GetClientRect, GetWindowRect, WS_CAPTION,+ };+ for (n, kind) in [+ Popup::Floating,+ Popup::Menu {+ border: 0x00ff_0000,+ },+ ]+ .into_iter()+ .enumerate()+ {+ let title = format!("mdm popup test {n} {}", std::process::id());+ let wide: Vec<u16> = title.encode_utf16().chain(Some(0)).collect();+ let class: Vec<u16> = "STATIC\0".encode_utf16().collect();+ // SAFETY: a hidden window of the system's STATIC class on this thread, destroyed+ // below; the strings are NUL-terminated.+ let hwnd = unsafe {+ CreateWindowExW(+ 0x0000_0108,+ class.as_ptr(),+ wide.as_ptr(),+ WINIT_BORDERLESS & !WS_VISIBLE,+ -20000,+ -20000,+ 56,+ 56,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ std::ptr::null(),+ )+ };+ assert!(!hwnd.is_null());+ assert!(popup_window(&title, kind), "applied once");+ assert!(!popup_window(&title, kind), "only once");+ // SAFETY: our own window; plain queries and style changes, as winit's.+ unsafe {+ let style = GetWindowLongPtrW(hwnd, GWL_STYLE) as u32;+ assert_eq!(style & WS_CAPTION, 0);+ assert_ne!(style & WS_POPUP, 0);+ // winit setting its caption style again: the subclass keeps the popup's.+ SetWindowLongPtrW(hwnd, GWL_STYLE, (style | WS_CAPTION) as isize);+ assert_eq!(GetWindowLongPtrW(hwnd, GWL_STYLE) as u32, style);+ let ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE) as u32;+ SetWindowLongPtrW(hwnd, GWL_EXSTYLE, 0x0000_0108);+ assert_eq!(GetWindowLongPtrW(hwnd, GWL_EXSTYLE) as u32, ex);+ assert_eq!(+ ex & WS_EX_NOACTIVATE != 0,+ matches!(kind, Popup::Menu { .. })+ );+ // Its size as the drop target's (a window with a caption style can't be made+ // that narrow: a popup can), then its client is the whole window.+ SetWindowPos(+ hwnd,+ std::ptr::null_mut(),+ 0,+ 0,+ 56,+ 56,+ SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE,+ );+ let (mut w, mut c): (RECT, RECT) = (zeroed(), zeroed());+ GetWindowRect(hwnd, &mut w);+ GetClientRect(hwnd, &mut c);+ assert_eq!([w.right - w.left, w.bottom - w.top], [56, 56]);+ assert_eq!([c.left, c.top, c.right, c.bottom], [0, 0, 56, 56]);+ DestroyWindow(hwnd);+ }+ }+ }}-/// Menu windows answer mouse-activation with "don't activate": clicking an item must not take-/// focus from the main window (which would close the menu before the click completes). They-/// keep their popup styles when winit sets the styles again (it does on every change of its-/// window flags, showing the window included), and their client is the whole window, with no-/// frame (winit's borderless frame moves the client a pixel down, for a shadow drawn round a-/// caption style, which a popup has no need of).-unsafe extern "system" fn menu_proc(+/// Every borderless window of ours: it keeps its popup styles when winit sets the styles again+/// (it does on every change of its window flags, showing the window included), and its client+/// is the whole window, with no frame (winit's borderless frame moves the client a pixel down,+/// for a shadow drawn round a caption style, which a popup has no need of). A menu's (`data`+/// has [`POPUP_NO_ACTIVATE`]) answers mouse-activation with "don't activate": clicking an item+/// must not take focus from the main window (which would close the menu before the click+/// completes).+unsafe extern "system" fn popup_proc(hwnd: HWND,msg: u32,wparam: WPARAM,lparam: LPARAM,_id: usize,- _data: usize,+ data: usize,) -> LRESULT {use windows_sys::Win32::UI::WindowsAndMessaging::{STYLESTRUCT, WM_STYLECHANGING};const WM_MOUSEACTIVATE: u32 = 0x0021;const MA_NOACTIVATE: LRESULT = 3;- if msg == WM_MOUSEACTIVATE {+ let no_activate = data & POPUP_NO_ACTIVATE != 0;+ if msg == WM_MOUSEACTIVATE && no_activate {return MA_NOACTIVATE;}if msg == WM_STYLECHANGING && lparam != 0 {@@ -798,8 +934,8 @@ unsafe extern "system" fn menu_proc(// styleNew the window may alter (Win32 contract).let s = unsafe { &mut *(lparam as *mut STYLESTRUCT) };match wparam as i32 {- GWL_STYLE => s.styleNew = menu_style(s.styleNew),- GWL_EXSTYLE => s.styleNew = menu_ex_style(s.styleNew),+ GWL_STYLE => s.styleNew = popup_style(s.styleNew),+ GWL_EXSTYLE => s.styleNew = popup_ex_style(s.styleNew, no_activate),_ => {}}return 0;@@ -812,38 +948,48 @@ unsafe extern "system" fn menu_proc(unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) }}-/// Make our borderless window titled `title` behave and look like a Win32 menu popup: never-/// activated (the main window keeps focus and keyboard), no taskbar entry, Windows 11's small-/// rounded corners, shadow and a 1 px border in `border` (0x00BBGGRR), and no window-open-/// animation (menus just appear); a plain popup window whose client is all of it-/// ([`menu_style`], #208). Cheap to call every frame: returns true only on the call that applied-/// it — the window is created hidden and should be shown then.-pub fn menu_window(title: &str, border: u32) -> bool {+/// Make our borderless window titled `title` a plain popup window whose client is all of it+/// ([`popup_style`], #208), with no taskbar entry, and the rest of what `kind` says. Every+/// borderless window of ours comes here (chrome.rs's `popup_viewport` and `style_popup`). Call+/// it in the window's own pass, before anything is drawn in it: its frame changes, and a+/// picture drawn before that is lost with the old frame (black until something makes it draw+/// again). Cheap to call every frame: returns true only on the call that applied it; the window+/// is created hidden and should be shown then.+pub fn popup_window(title: &str, kind: Popup) -> bool {use windows_sys::Win32::Graphics::Dwm::{DWMWA_BORDER_COLOR, DWMWA_TRANSITIONS_FORCEDISABLED, DWMWA_WINDOW_CORNER_PREFERENCE,- DWMWCP_ROUNDSMALL, DwmSetWindowAttribute,+ DWMWCP_ROUND, DWMWCP_ROUNDSMALL, DwmSetWindowAttribute,};- use windows_sys::Win32::UI::WindowsAndMessaging::{SWP_NOSIZE, WS_EX_NOACTIVATE};+ use windows_sys::Win32::UI::WindowsAndMessaging::{GetPropW, SWP_NOSIZE, SetPropW};let Some(hwnd) = find_own_window(title) else {return false;};+ let no_activate = matches!(kind, Popup::Menu { .. });+ // SAFETY: our own window, on its thread; the subclass proc lives as long as the program;+ // the DWM attributes are read from locals during the calls.unsafe {- let ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE) as u32;- if ex & WS_EX_NOACTIVATE != 0 {+ // Done once (comctl32 5.8, which MDM links, has no GetWindowSubclass to ask by).+ let done: Vec<u16> = "MDM.popup\0".encode_utf16().collect();+ if !GetPropW(hwnd, done.as_ptr()).is_null() {return false;}- let off: i32 = 1;- DwmSetWindowAttribute(- hwnd,- DWMWA_TRANSITIONS_FORCEDISABLED as u32,- &off as *const i32 as *const c_void,- size_of::<i32>() as u32,- );+ SetPropW(hwnd, done.as_ptr(), 1usize as _);+ if let Popup::Menu { .. } = kind {+ let off: i32 = 1;+ DwmSetWindowAttribute(+ hwnd,+ DWMWA_TRANSITIONS_FORCEDISABLED as u32,+ &off as *const i32 as *const c_void,+ size_of::<i32>() as u32,+ );+ }// The subclass first: it keeps the styles below when winit sets its own again.- SetWindowSubclass(hwnd, Some(menu_proc), 0x3e1, 0);- SetWindowLongPtrW(hwnd, GWL_EXSTYLE, menu_ex_style(ex) as isize);+ let data = if no_activate { POPUP_NO_ACTIVATE } else { 0 };+ SetWindowSubclass(hwnd, Some(popup_proc), POPUP_SUBCLASS, data);+ let ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE) as u32;+ SetWindowLongPtrW(hwnd, GWL_EXSTYLE, popup_ex_style(ex, no_activate) as isize);let style = GetWindowLongPtrW(hwnd, GWL_STYLE) as u32;- SetWindowLongPtrW(hwnd, GWL_STYLE, menu_style(style) as isize);+ SetWindowLongPtrW(hwnd, GWL_STYLE, popup_style(style) as isize);// The frame measured again (WM_NCCALCSIZE): no caption, the client the whole window.SetWindowPos(hwnd,@@ -854,19 +1000,25 @@ pub fn menu_window(title: &str, border: u32) -> bool {0,SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE,);- let corner = DWMWCP_ROUNDSMALL;+ // Windows 11 rounds a window with a caption style by itself, not a popup: asked for.+ let corner = match kind {+ Popup::Menu { .. } => DWMWCP_ROUNDSMALL,+ Popup::Floating => DWMWCP_ROUND,+ };DwmSetWindowAttribute(hwnd,DWMWA_WINDOW_CORNER_PREFERENCE as u32,&corner as *const _ as *const c_void,size_of::<i32>() as u32,);- DwmSetWindowAttribute(- hwnd,- DWMWA_BORDER_COLOR as u32,- &border as *const u32 as *const c_void,- size_of::<u32>() as u32,- );+ if let Popup::Menu { border } = kind {+ DwmSetWindowAttribute(+ hwnd,+ DWMWA_BORDER_COLOR as u32,+ &border as *const u32 as *const c_void,+ size_of::<u32>() as u32,+ );+ }}true}@@ -2228,6 +2380,118 @@ pub mod ole {}Some(Registration { hwnd, target })}++ /// Off-screen test copies only (MDM_TEST_DROP, droptarget.rs): `text` dropped on the+ /// window as a browser drops a link, without a mouse: a data object holding it as+ /// "UniformResourceLocatorW" goes to the drop target OLE has registered for the window+ /// (DragEnter, then Drop), as OLE's drag loop hands it. False when the window holds no+ /// registration of ours.+ pub fn test_drop(&self, text: &str) -> bool {+ use windows_sys::Win32::UI::WindowsAndMessaging::GetPropW;+ // OLE keeps the target registered for a window in this property of it (in the+ // process that registered it: the target itself).+ let prop: Vec<u16> = "OleDropTargetInterface\0".encode_utf16().collect();+ // SAFETY: a property read on our own window.+ let registered = unsafe { GetPropW(self.hwnd, prop.as_ptr()) };+ if registered != self.target.cast() {+ tracing::warn!("test drop: the window holds no drop target of ours");+ return false;+ }+ let data = Box::into_raw(Box::new(TestData {+ vtbl: &TEST_DATA_VTBL,+ text: text.encode_utf16().chain(Some(0)).collect(),+ }));+ let target = registered as *mut Target;+ let mut effect = DROPEFFECT_COPY;+ // SAFETY: our live target, called through its vtable as OLE does, with a data+ // object that lives until both calls return.+ unsafe {+ let pt = PointL { x: 0, y: 0 };+ ((*target).vtbl.drag_enter)(target, data.cast(), 0, pt, &mut effect);+ let pt = PointL { x: 0, y: 0 };+ ((*target).vtbl.drop)(target, data.cast(), 0, pt, &mut effect);+ std::mem::drop(Box::from_raw(data));+ }+ tracing::info!("test drop: {text} (effect {effect})");+ effect == DROPEFFECT_COPY+ }+ }++ /// The data object of [`Registration::test_drop`]: its text as a link (or plain text), in+ /// memory the receiver frees (ReleaseStgMedium).+ #[repr(C)]+ struct TestData {+ vtbl: &'static TestDataVtbl,+ text: Vec<u16>,+ }++ /// IDataObject's vtable up to GetData, all the receiver calls.+ #[repr(C)]+ struct TestDataVtbl {+ query_interface:+ unsafe extern "system" fn(*mut c_void, *const Guid, *mut *mut c_void) -> HResult,+ add_ref: unsafe extern "system" fn(*mut c_void) -> u32,+ release: unsafe extern "system" fn(*mut c_void) -> u32,+ get_data:+ unsafe extern "system" fn(*mut TestData, *const FormatEtc, *mut StgMedium) -> HResult,+ }++ static TEST_DATA_VTBL: TestDataVtbl = TestDataVtbl {+ query_interface: test_data_query,+ add_ref: test_data_ref,+ release: test_data_ref,+ get_data: test_data_get,+ };++ unsafe extern "system" fn test_data_query(+ _this: *mut c_void,+ _iid: *const Guid,+ out: *mut *mut c_void,+ ) -> HResult {+ // SAFETY: `out` is the caller's.+ unsafe { *out = std::ptr::null_mut() };+ E_NOINTERFACE+ }++ /// Owned by test_drop for the calls: no counting.+ unsafe extern "system" fn test_data_ref(_this: *mut c_void) -> u32 {+ 1+ }++ unsafe extern "system" fn test_data_get(+ this: *mut TestData,+ fmt: *const FormatEtc,+ out: *mut StgMedium,+ ) -> HResult {+ const DV_E_FORMATETC: HResult = 0x8004_0064_u32 as i32;+ const GMEM_MOVEABLE: u32 = 2;+ #[link(name = "kernel32")]+ unsafe extern "system" {+ fn GlobalAlloc(flags: u32, bytes: usize) -> *mut c_void;+ }+ // SAFETY: valid pointers for the call; the memory is filled within its size and handed+ // to the caller, who releases it.+ unsafe {+ let name: Vec<u16> = "UniformResourceLocatorW\0".encode_utf16().collect();+ let url_format = RegisterClipboardFormatW(name.as_ptr()) as u16;+ if (*fmt).cf != url_format && (*fmt).cf != CF_UNICODETEXT {+ return DV_E_FORMATETC;+ }+ let text = &(*this).text;+ let h = GlobalAlloc(GMEM_MOVEABLE, text.len() * 2);+ let p = GlobalLock(h) as *mut u16;+ if p.is_null() {+ return DV_E_FORMATETC;+ }+ std::ptr::copy_nonoverlapping(text.as_ptr(), p, text.len());+ GlobalUnlock(h);+ *out = StgMedium {+ tymed: TYMED_HGLOBAL,+ handle: h,+ unk_for_release: std::ptr::null_mut(),+ };+ }+ S_OK}impl Drop for Registration {