Files
spark/src/client/spark/view/Extensions/WindowExtensions.cs
T

316 lines
17 KiB
C#

using mbts.ui.native;
using mbts.ui.shell;
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
namespace mbts.ui {
static class WindowExtensions {
static readonly bool _ensure_onscreen_with_work_area_rect = config.Configuration.get<bts.config.toggles.EnsureOnScreenWithWorkAreaRect>().Enabled;
public static Rect bounds(this Window window) {
return new Rect(window.Left, window.Top, window.ActualWidth, window.ActualHeight);
}
public static double Bottom(this Window window) => window.Top + window.ActualHeight;
public static double Right(this Window window) => window.Left + window.ActualWidth;
public static async void set_position(this Window window, WindowPosition position) {
if (position != null) {
window.Left = position.left;
window.Top = position.top;
if (position.height > 0) { window.Height = position.height; }
if (position.width > 0) { window.Width = position.width; }
}
window.ensure_onscreen();
// After we set the window position we yield before settings the Maximized state
// Otherwise - (I think because since the underlying HWND hasn't been created yet)
// The window maximizes on the primary screen instead of the screen that the above settings
// would indicate.
if (position != null) {
await System.Threading.Tasks.Task.Yield();
window.WindowState = position.is_maximized ? System.Windows.WindowState.Maximized : System.Windows.WindowState.Normal;
}
}
public static void center_in_parent(this Window window, System.Windows.Forms.Control parent) {
System.Drawing.Point parent_position = parent.PointToScreen(System.Drawing.Point.Empty);
System.Drawing.Size parent_size = parent.Size;
int left_position = (parent_position.X) + (parent_size.Width / 2) - ((int)window.Width / 2);
int top_position = (parent_position.Y) + (parent_size.Height / 2) - ((int)window.Height / 2);
var window_position = window.get_position();
window_position.left = left_position;
window_position.top = top_position;
window.set_position(window_position);
}
public static void ensure_within_area(this Window window, Rect area) {
// Left (x)
double left_diff = window.Left - area.Left;
if (left_diff < 0) {
// window is left of the area; move the left to [relative] x=0
window.Left = area.Left;
} else {
double right_diff = window.Right() - area.Right;
if (right_diff > 0) {
// Excess width should hang out of the right (bc we live in a society that reads left to right).
window.Left -= Math.Min(left_diff, right_diff);
}
}
// Top (y)
double top_diff = window.Top - area.Top;
if (top_diff < 0) {
// window is above the area; move the top to [relative] y=0
window.Top = area.Top;
} else {
double bottom_diff = window.Bottom() - area.Bottom;
if (bottom_diff > 0) {
// Excess height should hang out of the bottom (bc we live in a society that reads top to bottom).
window.Top -= Math.Min(top_diff, bottom_diff);
}
}
}
public static async void ensure_onscreen(this Window window) {
// From MSDN:
// The virtual screen is the bounding rectangle of all display monitors.The VirtualScreenWidth and VirtualScreenHeight metrics are the width and height of the virtual screen.
// Jake: Note that there seems to be some strangeness associated with mixed dpi and what is returned by SystemParameters
// When a single 4k monitor is attached, the Height: 1440 and Width: 2560 are respectively scaled accoring to the system
// scaling parameters (the original 4k monitor is Height 2160 and Width 3840 with 150% scaling).
// When attaching a 1680 x 1050 monitor to the left of this monitor, in portrait mode, the results are a bit unclear.
//
// -------------------
// | | |
// | 2 | |
// | | 1 |
// ----| |
// | |
// ---------------
//
// 2 is 1050 x 1680 (portrait)
// 1 is 3840 x 2160 (landscape, 150% scaling)
//
// VirtualScreenTop: 0
// VirtualScreenLeft: -1050
// VirtualScreenHeight: 1680
// VirtualScreenWidth: 3610
//
// VirtualScreenHeight is what perplexes me; I'd expect the bounding rectangle to *still* yield a
// Height of 1440.
//
// Ergo, I think the code below to make sure the window appears on some screen is mostly right
// but may not behave correctly in mixed dpi environments
// first, we make sure the window (and it's entirety) is within the bounds of our screen
// is our window above the top of our screen
if (window.Top < SystemParameters.VirtualScreenTop) { window.Top = SystemParameters.VirtualScreenTop; }
// is our window off to the left of our screen?
if (window.Left < SystemParameters.VirtualScreenLeft) { window.Left = SystemParameters.VirtualScreenLeft; }
// now, is the position of the bottom edge our of window off the screen, if so, adjust by window height
if (window.Top + window.Height > SystemParameters.VirtualScreenTop + SystemParameters.VirtualScreenHeight) {
window.Top = SystemParameters.VirtualScreenHeight + SystemParameters.VirtualScreenTop - window.Height;
}
// now, is the position of the right edge our of our window off the screen, if so adjust by window width
if (window.Left + window.Width > SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth) {
window.Left = SystemParameters.VirtualScreenWidth + SystemParameters.VirtualScreenLeft - window.Width;
}
// Check that we aren't overlapped with the task bar - snap to the current monitors work area
if (!window.Topmost) {
var hwnd = window.hwnd();
if (hwnd == IntPtr.Zero) {
// If the window is null await the SourceInitialized then try again
await window.FromEvent<object, EventArgs>("SourceInitialized");
hwnd = window.hwnd();
}
if (hwnd != IntPtr.Zero) {
// grab the current screen's info
var hmonitor = NativeMethods.MonitorFromWindow(hwnd, NativeMethods.MONITOR_DEFAULTONNEAREST);
if (hmonitor != IntPtr.Zero) {
MONITORINFO minfo = new MONITORINFO();
minfo.cbSize = Marshal.SizeOf(minfo);
if (NativeMethods.GetMonitorInfo(hmonitor, ref minfo)) {
if (!_ensure_onscreen_with_work_area_rect) {
var work_area_rect = new Rect(minfo.rcWork.Left, minfo.rcWork.Top, minfo.rcWork.Width, minfo.rcWork.Height);
var transform = get_transform_from_device(window);
work_area_rect.Transform(transform);
window.ensure_within_area(work_area_rect);
return;
}
// if the screen and workarea upper left and lower right coords are the same, there is no
// taskbar on this screen
var no_taskbar_on_screen = (minfo.rcMonitor.Top == minfo.rcWork.Top && minfo.rcMonitor.Left == minfo.rcWork.Left &&
minfo.rcMonitor.Bottom == minfo.rcWork.Bottom && minfo.rcMonitor.Right == minfo.rcWork.Right);
if (!no_taskbar_on_screen) {
// there is a taskbar somewhere, let's figure out where
Rect task_bar_rect = new Rect();
var left_docked_width = Math.Abs((Math.Abs(minfo.rcMonitor.Left) - Math.Abs(minfo.rcWork.Left)));
var top_docked_height = Math.Abs((Math.Abs(minfo.rcMonitor.Top) - Math.Abs(minfo.rcWork.Top)));
var right_docked_width = ((minfo.rcMonitor.Width - left_docked_width) - minfo.rcWork.Width);
var bottom_docked_height = ((minfo.rcMonitor.Height - top_docked_height) - minfo.rcWork.Height);
if ((left_docked_width > 0)) {
// docked on left
task_bar_rect.X = minfo.rcMonitor.Left;
task_bar_rect.Y = minfo.rcMonitor.Top;
task_bar_rect.Width = left_docked_width;
task_bar_rect.Height = minfo.rcMonitor.Height;
} else if ((right_docked_width > 0)) {
// docked on right
task_bar_rect.X = minfo.rcWork.Right;
task_bar_rect.Y = minfo.rcMonitor.Top;
task_bar_rect.Width = right_docked_width;
task_bar_rect.Height = minfo.rcMonitor.Height;
} else if ((top_docked_height > 0)) {
// docked on top
task_bar_rect.X = minfo.rcWork.Left;
task_bar_rect.Y = minfo.rcMonitor.Top;
task_bar_rect.Width = minfo.rcWork.Width;
task_bar_rect.Height = top_docked_height;
} else if ((bottom_docked_height > 0)) {
// docked on bottom
task_bar_rect.X = minfo.rcWork.Left;
task_bar_rect.Y = minfo.rcWork.Bottom;
task_bar_rect.Width = minfo.rcWork.Width;
task_bar_rect.Height = bottom_docked_height;
}
// we now have our taskbar real coordinates/pixels
// need to convert them to WPF cooredinates/pixels
var transform = get_transform_from_device(window);
task_bar_rect = Rect.Transform(task_bar_rect, transform);
// our source window is already in WPF pixels, so no conversion
Rect source_window_rect = new Rect(window.Left, window.Top, window.ActualWidth, window.ActualHeight);
// use counter just in case something goes awry (don't risk entering an infinite loop)
int counter = 0;
while (source_window_rect.IntersectsWith(task_bar_rect) && counter++ < 4) {
// we have some kind of intersection, let's figure out what kind
var intersection = Rect.Intersect(task_bar_rect, source_window_rect);
const double error_margin = 0.00005;
int nudge_direction = 0;
if ((source_window_rect.Width - intersection.Width) > error_margin) {
// 1 = task bar on left, so nudge right
// -1 = task on right, so nuedge left
nudge_direction = (task_bar_rect.Left == 0) ? 1 : -1;
window.Left = source_window_rect.Left + nudge_direction * intersection.Width;
}
if ((source_window_rect.Height - intersection.Height) > error_margin) {
// 1 = task bar on top, so nudge down
// -1 = task on bottom, so nuedge up
nudge_direction = (task_bar_rect.Top == 0) ? 1 : -1;
window.Top = source_window_rect.Top + nudge_direction * intersection.Height;
}
// update the rect w/ the new window position to see if we have to go another round
source_window_rect = new Rect(window.Left, window.Top, window.ActualWidth, window.ActualHeight);
}
}
}
}
}
}
}
public static WindowPosition get_position(this Window window) {
// Save the 'restored' position of this window
WINDOWPLACEMENT pl = new WINDOWPLACEMENT();
var hwnd = window.hwnd();
if (hwnd == IntPtr.Zero || window.WindowState == System.Windows.WindowState.Normal) {
// If the window is closing it might not have an HWND backing
// Remote desktop also seems to do strange things with the Window. Try to use the normal window position whenever possible
return new WindowPosition() {
left = (int)window.Left,
top = (int)window.Top,
width = (int)window.Width,
height = (int)window.Height,
is_maximized = window.WindowState == System.Windows.WindowState.Maximized,
always_on_top = window.Topmost
};
}
// GetWindowPlacement gets the correct size even for minimized windows
NativeMethods.GetWindowPlacement(window.hwnd(), ref pl);
Point p_size = transform_from_device(window, pl.NormalPosition.Width, pl.NormalPosition.Height);
return new WindowPosition() {
left = (int)window.Left,
top = (int)window.Top,
width = (int)p_size.X,
height = (int)p_size.Y,
is_maximized = window.WindowState == System.Windows.WindowState.Maximized,
always_on_top = window.Topmost,
};
}
public static void FlashWindow(this Window window) {
WindowInteropHelper h = new WindowInteropHelper(window);
native.NativeMethods.FlashWindow(h.Handle);
}
public static IntPtr hwnd(this Window window) {
return new WindowInteropHelper(window).Handle;
}
private static Lazy<Matrix> _screen_transform = new Lazy<Matrix>(get_default_transform, System.Threading.LazyThreadSafetyMode.PublicationOnly);
private static Matrix get_default_transform() {
Matrix m = Matrix.Identity;
Application.Current.Dispatcher.Invoke(() => {
var window = Application.Current.MainWindow;
var psrc = PresentationSource.FromVisual(window);
m = psrc != null ? psrc.CompositionTarget.TransformFromDevice : m;
}, System.Windows.Threading.DispatcherPriority.Send);
return m;
}
private static Point transform_from_device(System.Windows.Media.Visual v, double x, double y) {
// In a high dpi setting the Win32 screen coordinates are different from the WPF screen coordinates.
/// this function transforms from "device" to WPF coordinates
Point p = new Point(x, y);
var psrc = PresentationSource.FromVisual(v);
if (psrc != null) {
return psrc.CompositionTarget.TransformFromDevice.Transform(p);
}
return _screen_transform.Value.Transform(p);
}
private static Matrix get_transform_from_device(Visual v) {
var psrc = PresentationSource.FromVisual(v);
if (psrc != null) {
return psrc.CompositionTarget.TransformFromDevice;
}
return Matrix.Identity;
}
public static void move_to_mouse(this Window window, int off_x = 0, int off_y = 0) {
Win32Point wpt;
NativeMethods.GetCursorPos(out wpt);
Point p = transform_from_device(window, wpt.x, wpt.y);
window.Left = p.X + off_x;
window.Top = p.Y + off_y;
window.ensure_onscreen();
}
public static IDisposable Show(this Window window, int off_x = int.MinValue, int off_y = int.MinValue, bool dispose_vm_on_close = false) {
window.move_to_mouse(off_x, off_y);
if (dispose_vm_on_close) window.Closed += (s, e) => (window.DataContext as IDisposable)?.Dispose();
if (off_x != int.MinValue && off_y != int.MinValue) window.move_to_mouse(off_x, off_y);
else window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
window.Show();
return Disposable.Create(() => {
// not very elegant, but safe and effective
if (window != null) {
try { window.Close(); } catch { }
}
});
}
}
}