Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

Support rotated monitors in Desktop Duplication HyperGlass

jokwa13531944c8c031d
diff --git a/crates/rf-win/src/glass/capture.rs b/crates/rf-win/src/glass/capture.rs
index 4342247a..76ba8de2 100644
--- a/crates/rf-win/src/glass/capture.rs
+++ b/crates/rf-win/src/glass/capture.rs
@@ -14,7 +14,10 @@ use std::ffi::c_void;
use crossbeam_channel::Receiver;
use windows::Win32::Foundation::{E_ACCESSDENIED, HANDLE, LUID, RECT};
use windows::Win32::Graphics::Direct3D11::{D3D11_TEXTURE2D_DESC, ID3D11Texture2D};
-use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_MODE_ROTATION_IDENTITY, DXGI_MODE_ROTATION_UNSPECIFIED};
+use windows::Win32::Graphics::Dxgi::Common::{
+ DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_MODE_ROTATION, DXGI_MODE_ROTATION_ROTATE90, DXGI_MODE_ROTATION_ROTATE180,
+ DXGI_MODE_ROTATION_ROTATE270,
+};
use windows::Win32::Graphics::Dxgi::{
CreateDXGIFactory1, DXGI_ERROR_ACCESS_LOST, DXGI_ERROR_DEVICE_HUNG, DXGI_ERROR_DEVICE_REMOVED, DXGI_ERROR_DEVICE_RESET,
DXGI_ERROR_DRIVER_INTERNAL_ERROR, DXGI_ERROR_NOT_FOUND, DXGI_ERROR_WAIT_TIMEOUT, DXGI_OUTDUPL_FRAME_INFO, DXGI_OUTDUPL_MOVE_RECT, IDXGIAdapter1, IDXGIFactory1,
@@ -26,7 +29,7 @@ use windows::Win32::System::StationsAndDesktops::{
use windows::core::Interface;
use super::Cmd;
-use super::gpu::{Gpu, Source};
+use super::gpu::{Gpu, Rotation, Source};
use super::rest::Pace;
use super::wgc::{Exclusion, Power, SessionMonitor};
@@ -48,7 +51,6 @@ pub(super) struct Located {
pub adapter: IDXGIAdapter1,
pub output: IDXGIOutput,
pub rect: RECT,
- pub rotated: bool,
}
/// The adapter and output a monitor is attached to. A new factory every time: an old one does not see monitors that came later.
@@ -60,8 +62,7 @@ pub(super) unsafe fn locate(hmon: isize) -> R<Located> {
while let Ok(output) = adapter.EnumOutputs(o) {
let d = output.GetDesc()?;
if d.Monitor.0 as isize == hmon {
- let rotated = d.Rotation != DXGI_MODE_ROTATION_IDENTITY && d.Rotation != DXGI_MODE_ROTATION_UNSPECIFIED;
- return Ok(Located { adapter, output, rect: d.DesktopCoordinates, rotated });
+ return Ok(Located { adapter, output, rect: d.DesktopCoordinates });
}
o += 1;
}
@@ -70,6 +71,28 @@ pub(super) unsafe fn locate(hmon: isize) -> R<Located> {
Err(DXGI_ERROR_NOT_FOUND.into())
}
+fn rotation_from_dxgi(r: DXGI_MODE_ROTATION) -> Rotation {
+ if r == DXGI_MODE_ROTATION_ROTATE90 {
+ Rotation::Deg90
+ } else if r == DXGI_MODE_ROTATION_ROTATE180 {
+ Rotation::Deg180
+ } else if r == DXGI_MODE_ROTATION_ROTATE270 {
+ Rotation::Deg270
+ } else {
+ Rotation::Identity
+ }
+}
+
+/// Maps a dirty/move rectangle from panel scanout coordinates (`tex_w x tex_h`) into upright desktop coordinates.
+pub(super) fn unrotate_rect(r: RECT, rot: Rotation, tex_w: i32, tex_h: i32) -> RECT {
+ match rot {
+ Rotation::Identity => r,
+ Rotation::Deg90 => RECT { left: tex_h - r.bottom, top: r.left, right: tex_h - r.top, bottom: r.right },
+ Rotation::Deg180 => RECT { left: tex_w - r.right, top: tex_h - r.bottom, right: tex_w - r.left, bottom: tex_h - r.top },
+ Rotation::Deg270 => RECT { left: r.top, top: tex_w - r.right, right: r.bottom, bottom: tex_w - r.left },
+ }
+}
+
/// Whether the desktop that takes the user's input is the normal one. On the lock screen, the Ctrl+Alt+Del screen and a UAC prompt it is
/// Winlogon's: a process of the user cannot open it, and Desktop Duplication answers ACCESS_LOST or E_ACCESSDENIED for as long as it
/// stays. That is a pause, not a failure: a PC that was locked for a minute must come back with its glass.
@@ -379,6 +402,7 @@ pub(super) struct DupMonitor {
output: IDXGIOutput,
dup: Option<IDXGIOutputDuplication>,
pub mirror: Option<Source>,
+ rotation: Rotation,
/// The mirror holds a picture of the desktop.
pub has_image: bool,
broken_since: Option<Instant>,
@@ -402,7 +426,7 @@ pub(super) fn gap_left(last: Option<Instant>, gap: Duration, now: Instant) -> Op
}
impl DupMonitor {
- /// Checks that the monitor can be mirrored on the glass device (`luid`): same adapter, not rotated. The duplication itself is made
+ /// Checks that the monitor can be mirrored on the glass device (`luid`): same adapter. The duplication itself is made
/// on the first `pump`, and again whenever it was lost.
unsafe fn open(hmon: isize, luid: LUID) -> Result<DupMonitor, String> {
let l = locate(hmon).map_err(|e| format!("the monitor is not among the DXGI outputs: {e}"))?;
@@ -410,15 +434,13 @@ impl DupMonitor {
if al.LowPart != luid.LowPart || al.HighPart != luid.HighPart {
return Err("the monitor is attached to another graphics adapter than the one the glass is drawn on".into());
}
- if l.rotated {
- return Err("the monitor is rotated, which the glass does not handle".into());
- }
Ok(DupMonitor {
hmon,
rect: l.rect,
output: l.output,
dup: None,
mirror: None,
+ rotation: Rotation::Identity,
has_image: false,
broken_since: None,
fresh: false,
@@ -478,9 +500,6 @@ impl DupMonitor {
Ok(l) => {
self.output = l.output;
self.rect = l.rect;
- if l.rotated {
- return Err(MonError::Monitor("the monitor is rotated, which the glass does not handle".into()));
- }
}
Err(e) => return self.broken(format!("the monitor is gone from the DXGI outputs: {e}"), now, false),
}
@@ -497,13 +516,13 @@ impl DupMonitor {
if dd.DesktopImageInSystemMemory.as_bool() {
return Err(MonError::Monitor("the desktop image is in system memory (a software or remote display), which the glass cannot read".into()));
}
- if dd.Rotation != DXGI_MODE_ROTATION_IDENTITY && dd.Rotation != DXGI_MODE_ROTATION_UNSPECIFIED {
- return Err(MonError::Monitor("the duplicated output is rotated, which the glass does not handle".into()));
- }
+ let rot = rotation_from_dxgi(dd.Rotation);
+ self.rotation = rot;
let (mw, mh) = (dd.ModeDesc.Width, dd.ModeDesc.Height);
- if self.mirror.as_ref().is_none_or(|m| (m.w, m.h) != (mw, mh)) {
+ if self.mirror.as_ref().is_none_or(|m| (m.w, m.h, m.rotation) != (mw, mh, rot)) {
match Source::new(g, mw, mh, None) {
- Ok(s) => {
+ Ok(mut s) => {
+ s.rotation = rot;
self.mirror = Some(s);
self.has_image = false;
}
@@ -551,7 +570,10 @@ impl DupMonitor {
if hdr != mirror_hdr {
let made = if hdr { Source::new_hdr(g, mw, mh, sdr_white_level(&self.output)) } else { Source::new(g, mw, mh, None) };
match made {
- Ok(m) => self.mirror = Some(m),
+ Ok(mut m) => {
+ m.rotation = self.rotation;
+ self.mirror = Some(m);
+ }
Err(e) => bad = Some(format!("the mirror for this desktop's colour format could not be made: {e}")),
}
}
@@ -573,7 +595,13 @@ impl DupMonitor {
}
drop(res);
// where it changed: only while the frame is still held, and only for a frame that became the picture
- let dirty = dup_dirty(image, whole, info.AccumulatedFrames, || frame_dirty(&dup, &info));
+ let dirty = match dup_dirty(image, whole, info.AccumulatedFrames, || frame_dirty(&dup, &info)) {
+ Dirty::Rects(rs) if self.rotation != Rotation::Identity => {
+ let (tw, th) = self.mirror.as_ref().map_or((0, 0), |m| (m.w as i32, m.h as i32));
+ Dirty::Rects(rs.into_iter().map(|r| unrotate_rect(r, self.rotation, tw, th)).collect())
+ }
+ other => other,
+ };
let _ = dup.ReleaseFrame();
self.last_taken = Some(Instant::now());
if let Some(why) = bad {
@@ -617,4 +645,13 @@ mod tests {
// no picture: nothing changed
assert!(matches!(dup_dirty(false, false, 5, || panic!("not read")), Dirty::Rects(r) if r.is_empty()));
}
+
+ #[test]
+ fn dirty_rects_unrotate_from_panel_to_desktop_coordinates() {
+ let r = RECT { left: 10, top: 20, right: 30, bottom: 50 };
+ assert_eq!(unrotate_rect(r, Rotation::Identity, 1920, 1080), r);
+ assert_eq!(unrotate_rect(r, Rotation::Deg90, 1920, 1080), RECT { left: 1030, top: 10, right: 1060, bottom: 30 });
+ assert_eq!(unrotate_rect(r, Rotation::Deg180, 1920, 1080), RECT { left: 1890, top: 1030, right: 1910, bottom: 1060 });
+ assert_eq!(unrotate_rect(r, Rotation::Deg270, 1920, 1080), RECT { left: 20, top: 1890, right: 50, bottom: 1910 });
+ }
}
diff --git a/crates/rf-win/src/glass/glass.hlsl b/crates/rf-win/src/glass/glass.hlsl
index 57beae10..d1cc5c1d 100644
--- a/crates/rf-win/src/glass/glass.hlsl
+++ b/crates/rf-win/src/glass/glass.hlsl
@@ -111,9 +111,17 @@ float4 VSMain(uint id : SV_VertexID) : SV_Position
}
// Pass 1: copy the window rectangle (plus margin) out of the source. The clamp sampler repeats the edge pixels where the region sticks out.
+// uPass.x carries the source's DXGI rotation (0 = identity, 1 = 90 CW, 2 = 180, 3 = 270 CW); uReg is in upright desktop px.
float4 PSCrop(float4 pos : SV_Position) : SV_Target
{
- float4 c = tA.SampleLevel(sLin, (uReg.xy + pos.xy) / uReg.zw, 0);
+ float2 uv = (uReg.xy + pos.xy) / uReg.zw;
+ if (uPass.x > 2.5)
+ uv = float2(1.0 - uv.y, uv.x);
+ else if (uPass.x > 1.5)
+ uv = float2(1.0 - uv.x, 1.0 - uv.y);
+ else if (uPass.x > 0.5)
+ uv = float2(uv.y, 1.0 - uv.x);
+ float4 c = tA.SampleLevel(sLin, uv, 0);
// An HDR desktop (uOpt.z = 1): half floats, linear scRGB where 1.0 is 80 nits. SDR white (uOpt.w, the monitor's "SDR content
// brightness" over 80 nits) becomes 1, brighter is clipped, and the result is sRGB encoded: the picture an 8 bit desktop holds.
if (uOpt.z > 0.5)
diff --git a/crates/rf-win/src/glass/gpu.rs b/crates/rf-win/src/glass/gpu.rs
index 88d3bcde..d8674864 100644
--- a/crates/rf-win/src/glass/gpu.rs
+++ b/crates/rf-win/src/glass/gpu.rs
@@ -575,7 +575,7 @@ impl Renderer {
// Textures
// ---------------------------------------------------------------------------------------------------------------------------------
-unsafe fn tex2d(g: &Gpu, w: u32, h: u32, mips: u32, fmt: DXGI_FORMAT, bind: u32) -> R<ID3D11Texture2D> {
+pub(super) unsafe fn tex2d(g: &Gpu, w: u32, h: u32, mips: u32, fmt: DXGI_FORMAT, bind: u32) -> R<ID3D11Texture2D> {
let mut t = None;
g.dev.CreateTexture2D(
&D3D11_TEXTURE2D_DESC {
@@ -596,7 +596,7 @@ unsafe fn tex2d(g: &Gpu, w: u32, h: u32, mips: u32, fmt: DXGI_FORMAT, bind: u32)
t.ok_or_else(fail)
}
-unsafe fn rtv_mip(g: &Gpu, t: &ID3D11Texture2D, fmt: DXGI_FORMAT, mip: u32) -> R<ID3D11RenderTargetView> {
+pub(super) unsafe fn rtv_mip(g: &Gpu, t: &ID3D11Texture2D, fmt: DXGI_FORMAT, mip: u32) -> R<ID3D11RenderTargetView> {
let mut v = None;
g.dev.CreateRenderTargetView(
t,
@@ -630,6 +630,31 @@ unsafe fn srv_mip(g: &Gpu, t: &ID3D11Texture2D, fmt: DXGI_FORMAT, mip: u32, coun
v.ok_or_else(fail)
}
+/// Display orientation of a duplicated desktop texture (`DXGI_MODE_ROTATION`).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(super) enum Rotation {
+ #[default]
+ Identity,
+ Deg90,
+ Deg180,
+ Deg270,
+}
+
+impl Rotation {
+ pub(super) fn code(self) -> f32 {
+ match self {
+ Rotation::Identity => 0.0,
+ Rotation::Deg90 => 1.0,
+ Rotation::Deg180 => 2.0,
+ Rotation::Deg270 => 3.0,
+ }
+ }
+
+ pub(super) fn swaps_axes(self) -> bool {
+ matches!(self, Rotation::Deg90 | Rotation::Deg270)
+ }
+}
+
/// A BGRA8 texture the glass reads (the mirror of a monitor, or a picture the caller gave). `data` is tightly packed BGRA.
pub(super) struct Source {
pub tex: ID3D11Texture2D,
@@ -639,6 +664,7 @@ pub(super) struct Source {
/// An HDR desktop's picture (half floats, linear scRGB): the SDR white level over 80 nits, which the crop pass divides by before
/// it encodes sRGB. `None`: an 8 bit sRGB picture.
pub hdr: Option<f32>,
+ pub rotation: Rotation,
}
impl Source {
@@ -648,29 +674,35 @@ impl Source {
g.ctx.UpdateSubresource(&tex, 0, None, d.as_ptr() as *const c_void, w * 4, 0);
}
let srv = srv_mip(g, &tex, DXGI_FORMAT_B8G8R8A8_UNORM, 0, 1)?;
- Ok(Source { tex, srv, w, h, hdr: None })
+ Ok(Source { tex, srv, w, h, hdr: None, rotation: Rotation::Identity })
}
/// A mirror for an HDR desktop: the duplicated frames are copied in as they come (FP16), and the crop pass tone maps them.
pub(super) unsafe fn new_hdr(g: &Gpu, w: u32, h: u32, sdr_white: f32) -> R<Source> {
let tex = tex2d(g, w, h, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D11_BIND_SHADER_RESOURCE.0 as u32)?;
let srv = srv_mip(g, &tex, DXGI_FORMAT_R16G16B16A16_FLOAT, 0, 1)?;
- Ok(Source { tex, srv, w, h, hdr: Some(sdr_white) })
+ Ok(Source { tex, srv, w, h, hdr: Some(sdr_white), rotation: Rotation::Identity })
+ }
+
+ /// Upright desktop dimensions in pixels (swapped when rotated 90 or 270 degrees).
+ pub(super) fn desktop_size(&self) -> (u32, u32) {
+ if self.rotation.swaps_axes() { (self.h, self.w) } else { (self.w, self.h) }
}
}
-/// The crop pass's word for a source: `opt[2]` 1 for an HDR picture, `opt[3]` its SDR white level over 80 nits.
-fn mark_source(opt: &mut [f32; 4], src: &Source) {
+/// The crop pass's words for a source: `opt[2..4]` for HDR tone mapping, `pass[0]` for source rotation.
+fn mark_source(cb: &mut Cb, src: &Source) {
match src.hdr {
Some(white) => {
- opt[2] = 1.0;
- opt[3] = white;
+ cb.opt[2] = 1.0;
+ cb.opt[3] = white;
}
None => {
- opt[2] = 0.0;
- opt[3] = 1.0;
+ cb.opt[2] = 0.0;
+ cb.opt[3] = 1.0;
}
}
+ cb.pass[0] = src.rotation.code();
}
/// The backdrop of one glass: the part of the source around the glass (its rectangle plus the padding), copied out and followed by
@@ -832,7 +864,7 @@ impl Prepared {
/// A draw for a backdrop that is still the one `prep` last put into the region (only the lenses moved): the constant buffer, without
/// the copy and the pyramid passes.
pub(super) fn reuse(region: &Region, src: &Source, geo: &Geometry, look: &Look) -> Prepared {
- Prepared { cb: make_cb(geo, look, (src.w, src.h), region, false) }
+ Prepared { cb: make_cb(geo, look, src.desktop_size(), region, false) }
}
/// Passes 1 and 2: copy the glass rectangle plus padding out of the source, then build the blur pyramid.
@@ -858,16 +890,17 @@ pub(super) fn other_monitor_crop(origin: (i32, i32), pad: u32, region: (u32, u32
/// monitors had glass on one half only, and the backdrop jumped to the other monitor's when the window's middle crossed over). `extra`
/// are those pictures with their top left minus this monitor's, desktop px.
pub(super) unsafe fn prep_with(r: &Renderer, region: &Region, src: &Source, extra: &[(&Source, (i32, i32))], geo: &Geometry, look: &Look, check: bool) -> Prepared {
- let mut cb = make_cb(geo, look, (src.w, src.h), region, check);
- mark_source(&mut cb.opt, src);
+ let mut cb = make_cb(geo, look, src.desktop_size(), region, check);
+ mark_source(&mut cb, src);
r.pass(&r.ps_crop, &region.rtv[0], region.w, region.h, &src.srv, &cb);
if !extra.is_empty() {
let c = &r.g.ctx;
for (other, delta) in extra {
- let Some((reg, [x0, y0, x1, y1])) = other_monitor_crop(geo.origin, region.pad, (region.w, region.h), *delta, (other.w, other.h)) else { continue };
+ let (ow, oh) = other.desktop_size();
+ let Some((reg, [x0, y0, x1, y1])) = other_monitor_crop(geo.origin, region.pad, (region.w, region.h), *delta, (ow, oh)) else { continue };
let mut ocb = cb;
- ocb.reg = [reg[0], reg[1], other.w as f32, other.h as f32];
- mark_source(&mut ocb.opt, other);
+ ocb.reg = [reg[0], reg[1], ow as f32, oh as f32];
+ mark_source(&mut ocb, other);
c.RSSetState(&r.scissor);
c.RSSetScissorRects(Some(&[RECT { left: x0 as i32, top: y0 as i32, right: x1 as i32, bottom: y1 as i32 }]));
r.pass(&r.ps_crop, &region.rtv[0], region.w, region.h, &other.srv, &ocb);
@@ -894,7 +927,7 @@ pub(super) unsafe fn glass_pass(r: &Renderer, region: &Region, p: &Prepared, geo
// ---------------------------------------------------------------------------------------------------------------------------------
/// Copy a whole texture into a staging texture and return the bytes, `bpp` bytes per pixel, tightly packed.
-unsafe fn readback(g: &Gpu, tex: &ID3D11Texture2D, w: u32, h: u32, bpp: u32) -> R<Vec<u8>> {
+pub(super) unsafe fn readback(g: &Gpu, tex: &ID3D11Texture2D, w: u32, h: u32, bpp: u32) -> R<Vec<u8>> {
let mut d = D3D11_TEXTURE2D_DESC::default();
tex.GetDesc(&mut d);
d.Usage = D3D11_USAGE_STAGING;
diff --git a/crates/rf-win/src/glass/tests.rs b/crates/rf-win/src/glass/tests.rs
index 3d91c3fd..6bbd4765 100644
--- a/crates/rf-win/src/glass/tests.rs
+++ b/crates/rf-win/src/glass/tests.rs
@@ -376,6 +376,57 @@ fn an_hdr_backdrop_reads_as_the_sdr_picture_it_shows() {
});
}
+#[test]
+fn rotated_source_crops_into_upright_region_for_all_orientations() {
+ if !can_draw() {
+ return;
+ }
+ // Asymmetric 2x2 panel texture (160x120): TL=red, TR=green, BL=blue, BR=white in panel coords.
+ let (tw, th) = (160u32, 120u32);
+ let data = picture(tw, th, |x, y| match (x < tw / 2, y < th / 2) {
+ (true, true) => [255, 0, 0],
+ (false, true) => [0, 255, 0],
+ (true, false) => [0, 0, 255],
+ (false, false) => [255, 255, 255],
+ });
+ let look = bare_optics();
+ with_renderer(true, |r| unsafe {
+ let check = |rot: super::gpu::Rotation, sample_at: (i32, i32), want_rgb: [u8; 3]| {
+ let mut src = Source::new(&r.g, tw, th, Some(&data)).expect("source");
+ src.rotation = rot;
+ let (dw, dh) = src.desktop_size();
+ let geo = Geometry { w: 40, h: 40, origin: sample_at, scale: 1.0, radius_px: 0.0, cut_corners: false, shape: None, shadow: None };
+ let region = Region::new(&r.g, geo.w, geo.h, 8).expect("region");
+ let prepared = prep(r, &region, &src, &geo, &look, false);
+ let target = super::gpu::tex2d(
+ &r.g,
+ geo.w,
+ geo.h,
+ 1,
+ windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM,
+ (windows::Win32::Graphics::Direct3D11::D3D11_BIND_RENDER_TARGET.0 | windows::Win32::Graphics::Direct3D11::D3D11_BIND_SHADER_RESOURCE.0) as u32,
+ )
+ .expect("target");
+ let rtv = super::gpu::rtv_mip(&r.g, &target, windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM, 0).expect("rtv");
+ super::gpu::glass_pass(r, &region, &prepared, &geo, &rtv);
+ let out = super::gpu::readback(&r.g, &target, geo.w, geo.h, 4).expect("readback");
+ let off = (20 * geo.w as usize + 20) * 4;
+ let got = [out[off + 2], out[off + 1], out[off]];
+ assert!(
+ (got[0] as i32 - want_rgb[0] as i32).abs() < 20
+ && (got[1] as i32 - want_rgb[1] as i32).abs() < 20
+ && (got[2] as i32 - want_rgb[2] as i32).abs() < 20,
+ "rot={rot:?} desktop=({dw}x{dh}) at={sample_at:?} got={got:?} want={want_rgb:?}"
+ );
+ };
+ // Desktop TL of 90 CW = panel BL (blue); desktop TL of 180 = panel BR (white); desktop TL of 270 CW = panel TR (green).
+ check(super::gpu::Rotation::Identity, (10, 10), [255, 0, 0]);
+ check(super::gpu::Rotation::Deg90, (10, 10), [0, 0, 255]);
+ check(super::gpu::Rotation::Deg180, (10, 10), [255, 255, 255]);
+ check(super::gpu::Rotation::Deg270, (10, 10), [0, 255, 0]);
+ });
+}
+
/// The value the app reads: unknown until the engine has measured, only for a window the app still holds, gone with the glass.
#[test]
fn the_brightness_is_unknown_until_measured_and_goes_with_the_glass() {