Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved DPI Scaling on Windows and Fixed related Bugs #2155

Open
wants to merge 107 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 92 commits
Commits
Show all changes
107 commits
Select commit Hold shift + click to select a range
184d5d4
Fixed bug in call of SetProcessDpiAwarenessContext
proneon267 Oct 15, 2023
986804f
Added a changelog.
proneon267 Oct 15, 2023
5967db9
Fixed winforms scaling bugs.
proneon267 Oct 16, 2023
a9f740b
Updated changelog.
proneon267 Oct 16, 2023
c1bdf9d
Added event handler to detect dpi change when live.
proneon267 Oct 18, 2023
196bf77
Merge branch 'patch-20' of https://github.com/proneon267/toga into pa…
proneon267 Oct 18, 2023
29a55d3
Merge branch 'main' into patch-20
proneon267 Oct 18, 2023
ff23b17
Empty commit for CI/CD
proneon267 Oct 18, 2023
afccfc6
Updated changelog
proneon267 Oct 18, 2023
94dce84
Added support for font scaling based on DPI change
proneon267 Oct 21, 2023
65c6bd7
Empty commit
proneon267 Oct 21, 2023
21d1f56
Miscellaneous fixes
proneon267 Oct 21, 2023
fcfe409
Merge branch 'beeware:main' into patch-20
proneon267 Oct 21, 2023
0129035
Merge branch 'beeware:main' into patch-20
proneon267 Oct 23, 2023
ebd1c29
Fixed Hwnd Related Bugs.
proneon267 Oct 23, 2023
4e4addc
Fixed menubar clipping bug.
proneon267 Oct 23, 2023
7aeeb7c
Miscellaneous fixes
proneon267 Oct 23, 2023
0ff2ec6
Empty commit for CI
proneon267 Oct 23, 2023
1012ac5
Merge branch 'beeware:main' into patch-20
proneon267 Oct 25, 2023
1393b7d
Empty commit for CI
proneon267 Oct 26, 2023
796db51
Added Support for Scaling Stack Trace Dialogs.
proneon267 Oct 27, 2023
ec7617d
Miscellaneous fixes
proneon267 Oct 27, 2023
a4ff196
Miscellaneous fixes
proneon267 Oct 27, 2023
9e3685a
Miscellaneous fixes
proneon267 Oct 27, 2023
20b6793
Merge branch 'main' into patch-20
proneon267 Nov 1, 2023
4619553
Merge branch 'main' into patch-20
proneon267 Nov 3, 2023
6f8019c
Empty commit for CI
proneon267 Nov 3, 2023
407156e
Added support for scaling window toolbar
proneon267 Nov 3, 2023
550839c
Added tests
proneon267 Nov 5, 2023
392487a
Miscellaneous fixes
proneon267 Nov 5, 2023
2d59078
Fixed tests
proneon267 Nov 6, 2023
d54bc4d
Merge branch 'beeware:main' into patch-20
proneon267 Nov 7, 2023
c45aa2e
Modified scaling code
proneon267 Nov 7, 2023
1714095
Merge branch 'patch-20' of https://github.com/proneon267/toga into pa…
proneon267 Nov 7, 2023
5c512cb
Fixed Stack Trace Dialog Scaling issues
proneon267 Nov 9, 2023
cbdc69a
Miscellaneous Fixes
proneon267 Nov 9, 2023
2ae714f
Merge branch 'main' into patch-20
proneon267 Nov 9, 2023
a285a53
Merge branch 'patch-20' of https://github.com/proneon267/toga into HEAD
proneon267 Nov 9, 2023
c5fb1b0
Miscellaneous Fixes
proneon267 Nov 9, 2023
469f287
Merge branch 'main' into patch-20
proneon267 Nov 9, 2023
9929c3a
Merge branch 'patch-20' of https://github.com/proneon267/toga into HEAD
proneon267 Nov 9, 2023
ab754c2
Merge branch 'main' into patch-20
proneon267 Nov 9, 2023
a670a2a
Miscellaneous Fixes
proneon267 Nov 9, 2023
eeeeaa3
Merge branch 'patch-20' of https://github.com/proneon267/toga into dp…
proneon267 Nov 9, 2023
d2e5948
Fixed tests
proneon267 Nov 9, 2023
6aa68d7
Empty commit for CI
proneon267 Nov 9, 2023
083d9da
Added scaling support for moving between screens.
proneon267 Nov 9, 2023
f1ddd6f
Empty commit for CI
proneon267 Nov 9, 2023
0325388
Empty commit for CI
proneon267 Nov 9, 2023
7527b39
Miscellaneous Fixes
proneon267 Nov 11, 2023
4b7791b
Miscellaneous Fixes
proneon267 Nov 11, 2023
995819b
Merge branch 'beeware:main' into patch-20
proneon267 Nov 11, 2023
8c422e8
Miscellaneous Fixes
proneon267 Nov 11, 2023
0eb366a
Merge branch 'main' into patch-20
proneon267 Nov 12, 2023
c7b2f19
Merge branch 'beeware:main' into patch-20
proneon267 Nov 14, 2023
30b088b
Merge branch 'beeware:main' into patch-20
proneon267 Nov 15, 2023
3e7bdea
Merge branch 'main' into patch-20
proneon267 Nov 25, 2023
ee76a14
Miscellaneous Fixes
proneon267 Nov 29, 2023
d92d929
Miscellaneous Fixes
proneon267 Nov 29, 2023
48cd2bf
Merge branch 'beeware:main' into patch-20
proneon267 Dec 2, 2023
0a9e732
Merge branch 'beeware:main' into patch-20
proneon267 Dec 10, 2023
de079fa
Merge branch 'main' into patch-20
proneon267 Dec 17, 2023
81a04ae
Miscellaneous Fixes
proneon267 Dec 17, 2023
279458f
Merge branch 'beeware:main' into patch-20
proneon267 Dec 18, 2023
2e16e16
Merge branch 'beeware:main' into patch-20
proneon267 Dec 22, 2023
acf13d3
Miscellaneous Fixes
proneon267 Dec 22, 2023
c97df03
Merge branch 'beeware:main' into patch-20
proneon267 Jan 13, 2024
b8db567
Merge branch 'beeware:main' into patch-20
proneon267 Jan 14, 2024
4086055
Merge branch 'beeware:main' into patch-20
proneon267 Jan 17, 2024
85bcb6b
Merge branch 'beeware:main' into patch-20
proneon267 Jan 17, 2024
4d77f3f
Merge branch 'beeware:main' into patch-20
proneon267 Jan 20, 2024
7842aff
Empty commit for CI
proneon267 Jan 21, 2024
4f4f988
Merge branch 'beeware:main' into patch-20
proneon267 Jan 25, 2024
c529e5f
Merge branch 'beeware:main' into patch-20
proneon267 Feb 3, 2024
46eb4a9
Misc Fixes
proneon267 Feb 3, 2024
3090935
Removed dialog scaling
proneon267 Feb 6, 2024
a99b83a
Misc Fixes
proneon267 Feb 6, 2024
71d06b5
Misc Fixes
proneon267 Feb 6, 2024
fd718a2
Merge branch 'beeware:main' into patch-20
proneon267 Feb 9, 2024
d0b7f0e
Corrected windows implementation
proneon267 Feb 10, 2024
6ceb39d
Updated to latest main branch
proneon267 Feb 11, 2024
03062b9
Corrected winforms screens dpi scaling
proneon267 Feb 11, 2024
69f83cc
Corrected winforms tests_backend to detect dpi scale
proneon267 Feb 11, 2024
65e6144
Corrected winforms dpi scaling
proneon267 Feb 11, 2024
b6451f5
Corrected winforms tests_backend dpi scaling
proneon267 Feb 11, 2024
8cf5eef
Corrected winforms tests_backend dpi scaling
proneon267 Feb 11, 2024
6a0b6d7
Empty commit for CI
proneon267 Feb 11, 2024
18bc25d
Empty commit for CI
proneon267 Feb 11, 2024
87c88af
Merge branch 'main' into patch-20
proneon267 Mar 21, 2024
6713490
updated to latest main branch
proneon267 Mar 21, 2024
c873366
updated to latest main branch
proneon267 Mar 21, 2024
fac093d
Merge branch 'beeware:main' into patch-20
proneon267 Apr 2, 2024
3084c42
Merge remote-tracking branch 'remotes/origin/main' into patch-20
mhsmith Apr 3, 2024
31e54c9
Fix StackTraceDialog scaling
mhsmith Apr 3, 2024
c793d64
Fix various scaling bugs
mhsmith Apr 4, 2024
c44fef0
Merge branch 'beeware:main' into patch-20
proneon267 Apr 14, 2024
64221ab
Fixed reported dpi scaling bugs
proneon267 Apr 14, 2024
12a70d1
Fixed tests
proneon267 Apr 15, 2024
2cd6213
Empty commit for CI
proneon267 Apr 15, 2024
7c8a9b8
Empty commit for CI
proneon267 Apr 15, 2024
69054c1
Fixed remaining errors
proneon267 Apr 26, 2024
5e58f35
Fixed test
proneon267 Apr 28, 2024
ae20798
Merge branch 'main' into patch-20
proneon267 May 7, 2024
ff6223c
Modified DPI change test
proneon267 May 15, 2024
1313d7e
Fixed DPI change test
proneon267 May 15, 2024
a53a820
Merge branch 'beeware:main' into patch-20
proneon267 May 15, 2024
f3db6ff
Merge branch 'beeware:main' into patch-20
proneon267 Jun 1, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/2155.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DPI scaling on Windows is now improved and related bugs are fixed.
4 changes: 2 additions & 2 deletions iOS/tests_backend/probe.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import asyncio

import toga
from toga_iOS.libs import NSRunLoop, UIScreen
from toga_iOS.libs import NSRunLoop


class BaseProbe:
Expand All @@ -21,5 +21,5 @@ async def redraw(self, message=None, delay=0):

def assert_image_size(self, image_size, size, screen):
# Retina displays render images at a higher resolution than their reported size.
scale = int(UIScreen.mainScreen.scale)
scale = int(screen._impl.native.scale)
assert image_size == (size[0] * scale, size[1] * scale)
124 changes: 124 additions & 0 deletions testbed/tests/app/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,3 +587,127 @@ async def test_screens(app, app_probe):
# Check that the origin of every other screen is not "0,0"
origins_not_zero = all(screen.origin != (0, 0) for screen in app.screens[1:])
assert origins_not_zero is True


# This test is windows specific
if toga.platform.current_platform == "windows":
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pytest.mark.skipif is a cleaner way of doing this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. Thanks!


async def test_system_dpi_change(
monkeypatch, app, app_probe, main_window, main_window_probe
):
# For restoring original behavior after completion of test.
original_values = dict()
# --------------------------------- Set up for testing ---------------------------------
# For toolbar
main_window.toolbar.add(app.cmd1, app.cmd2)

# ----------------------- Setup Mock values for testing -----------------------
# For main_window
original_values["main_window_update_scale"] = main_window._impl.update_scale
main_window_update_scale_mock = Mock()
monkeypatch.setattr(
main_window._impl, "update_scale", main_window_update_scale_mock
)
original_values["main_window_resize_content"] = main_window._impl.resize_content
main_window_resize_content_mock = Mock()
monkeypatch.setattr(
main_window._impl, "resize_content", main_window_resize_content_mock
)

window1 = toga.Window("Test Window 1")
window1.content = toga.Box()
window1_probe = window_probe(app, window1)
window1.show()
await window1_probe.wait_for_window("Extra windows added")

# For window1
original_values["window1_update_scale"] = window1._impl.update_scale
window1_update_scale_mock = Mock()
monkeypatch.setattr(window1._impl, "update_scale", window1_update_scale_mock)
original_values["window1_resize_content"] = window1._impl.resize_content
window1_resize_content_mock = Mock()
monkeypatch.setattr(
window1._impl, "resize_content", window1_resize_content_mock
)
original_values["window1_update_toolbar_font_scale"] = (
window1._impl.update_toolbar_font_scale
)
window1_update_toolbar_font_scale_mock = Mock()
monkeypatch.setattr(
window1._impl,
"update_toolbar_font_scale",
window1_update_toolbar_font_scale_mock,
)
# -----------------------------------------------------------------------------
# Explicitly set the dpi_scale for testing
for window in app.windows:
window._impl._dpi_scale = 1.5
# --------------------------------------------------------------------------------------
await main_window_probe.redraw(
"Triggering DPI change event for testing property changes"
)
app_probe.trigger_dpi_change_event()

# Test out properties which should change on dpi change
main_window._impl.update_scale.assert_called_once()
window1._impl.update_scale.assert_called_once()
assert main_window_probe.has_toolbar()
app_probe.assert_main_window_toolbar_font_scale_updated()
assert not window1_probe.has_toolbar()
window1._impl.update_toolbar_font_scale.assert_not_called()
app_probe.assert_main_window_menubar_font_scale_updated()
assert not hasattr(window1._impl, "update_menubar_font_scale")
app_probe.assert_main_window_widgets_font_scale_updated()
main_window._impl.resize_content.assert_called_once()
window1._impl.resize_content.assert_called_once()

# Test if widget.refresh is called once on each widget
for window in app.windows:
for widget in window.widgets:
original_values[id(widget)] = widget.refresh
monkeypatch.setattr(widget, "refresh", Mock())

await main_window_probe.redraw(
"Triggering DPI change event for testing widget refresh calls"
)
app_probe.trigger_dpi_change_event()

for window in app.windows:
for widget in main_window.widgets:
widget.refresh.assert_called_once()

# Restore original state
for window in app.windows:
for widget in window.widgets:
monkeypatch.setattr(widget, "refresh", original_values[id(widget)])
monkeypatch.setattr(
window1._impl,
"update_toolbar_font_scale",
original_values["window1_update_toolbar_font_scale"],
)
monkeypatch.setattr(
window1._impl, "resize_content", original_values["window1_resize_content"]
)
monkeypatch.setattr(
window1._impl, "update_scale", original_values["window1_update_scale"]
)
monkeypatch.setattr(
main_window._impl,
"resize_content",
original_values["main_window_resize_content"],
)
monkeypatch.setattr(
main_window._impl,
"update_scale",
original_values["main_window_update_scale"],
)

# Restore original state
for window in app.windows:
window._impl._dpi_scale = 1.0
await main_window_probe.redraw(
"Triggering DPI change event for restoring original state"
)
app_probe.trigger_dpi_change_event()
main_window.toolbar.clear()
window1.close()
87 changes: 59 additions & 28 deletions winforms/src/toga_winforms/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
import re
import sys
import threading
from ctypes import windll
from ctypes import c_void_p, windll, wintypes

import System.Windows.Forms as WinForms
from Microsoft.Win32 import SystemEvents
from System import Environment, Threading
from System.ComponentModel import InvalidEnumArgumentException
from System.Drawing import Font as WinFont
from System.Media import SystemSounds
from System.Net import SecurityProtocolType, ServicePointManager
from System.Windows.Threading import Dispatcher
Expand All @@ -19,10 +21,20 @@
from .libs.proactor import WinformsProactorEventLoop
from .libs.wrapper import WeakrefCallable
from .screens import Screen as ScreenImpl
from .widgets.base import Scalable
from .window import Window


class MainWindow(Window):
def update_menubar_font_scale(self):
# Directly using self.native.MainMenuStrip.Font instead of
# original_menubar_font makes the menubar font to not scale down.
self.native.MainMenuStrip.Font = WinFont(
self.original_menubar_font.FontFamily,
self.scale_font(self.original_menubar_font.Size),
self.original_menubar_font.Style,
)

def winforms_FormClosing(self, sender, event):
# Differentiate between the handling that occurs when the user
# requests the app to exit, and the actual application exiting.
Expand Down Expand Up @@ -68,9 +80,40 @@ def print_stack_trace(stack_trace_line): # pragma: no cover
print(py_exc.Message)


class App:
class App(Scalable):
_MAIN_WINDOW_CLASS = MainWindow

# These are required for properly setting up DPI mode
WinForms.Application.EnableVisualStyles()
WinForms.Application.SetCompatibleTextRenderingDefault(False)

# ------------------- Set the DPI Awareness mode for the process -------------------
# This needs to be done at the earliest and doing this in __init__() or
# in create() doesn't work
mhsmith marked this conversation as resolved.
Show resolved Hide resolved
#
# Check the version of windows and make sure we are setting the DPI mode
# with the most up to date API
mhsmith marked this conversation as resolved.
Show resolved Hide resolved
# Windows Versioning Check Sources : https://www.lifewire.com/windows-version-numbers-2625171
# and https://docs.microsoft.com/en-us/windows/release-information/
win_version = Environment.OSVersion.Version
# Represents Windows 10 Build 1703 and beyond which should use
# SetProcessDpiAwarenessContext(-4) for DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
# Valid values: https://learn.microsoft.com/en-us/windows/win32/hidpi/dpi-awareness-context
if (win_version.Major > 10) or (
win_version.Major == 10 and win_version.Build >= 15063
):
windll.user32.SetProcessDpiAwarenessContext.restype = wintypes.BOOL
windll.user32.SetProcessDpiAwarenessContext.argtypes = [c_void_p]
# SetProcessDpiAwarenessContext returns False(0) on Failure
if windll.user32.SetProcessDpiAwarenessContext(-4) == 0: # pragma: no cover
print("WARNING: Failed to set the DPI Awareness mode for the app.")
else: # pragma: no cover
print(
"WARNING: Your Windows version doesn't support DPI Awareness setting. "
"We recommend you upgrade to at least Windows 10 Build 1703."
)
# ----------------------------------------------------------------------------------

def __init__(self, interface):
self.interface = interface
self.interface._impl = self
Expand All @@ -97,32 +140,10 @@ def create(self):
self.app_context = WinForms.ApplicationContext()
self.app_dispatcher = Dispatcher.CurrentDispatcher

# Check the version of windows and make sure we are setting the DPI mode
# with the most up to date API
# Windows Versioning Check Sources : https://www.lifewire.com/windows-version-numbers-2625171
# and https://docs.microsoft.com/en-us/windows/release-information/
win_version = Environment.OSVersion.Version
if win_version.Major >= 6: # Checks for Windows Vista or later
# Represents Windows 8.1 up to Windows 10 before Build 1703 which should use
# SetProcessDpiAwareness(True)
if (win_version.Major == 6 and win_version.Minor == 3) or (
win_version.Major == 10 and win_version.Build < 15063
): # pragma: no cover
windll.shcore.SetProcessDpiAwareness(True)
print(
"WARNING: Your Windows version doesn't support DPI-independent rendering. "
"We recommend you upgrade to at least Windows 10 Build 1703."
)
# Represents Windows 10 Build 1703 and beyond which should use
# SetProcessDpiAwarenessContext(-2)
elif win_version.Major == 10 and win_version.Build >= 15063:
windll.user32.SetProcessDpiAwarenessContext(-2)
# Any other version of windows should use SetProcessDPIAware()
else: # pragma: no cover
windll.user32.SetProcessDPIAware()

self.native.EnableVisualStyles()
self.native.SetCompatibleTextRenderingDefault(False)
# Register the DisplaySettingsChanged event handler
SystemEvents.DisplaySettingsChanged += WeakrefCallable(
self.winforms_DisplaySettingsChanged
)

# Ensure that TLS1.2 and TLS1.3 are enabled for HTTPS connections.
# For some reason, some Windows installs have these protocols
Expand Down Expand Up @@ -150,6 +171,14 @@ def create(self):
self.create_menus()
self.interface.main_window._impl.set_app(self)

######################################################################
# Native event handlers
######################################################################

def winforms_DisplaySettingsChanged(self, sender, event):
for window in self.interface.windows:
window._impl.update_window_dpi_changed()

######################################################################
# Commands and menus
######################################################################
Expand Down Expand Up @@ -257,6 +286,8 @@ def create_menus(self):
cmd._impl.native.append(item)
submenu.DropDownItems.Add(item)

# Required for font scaling on DPI changes
window.original_menubar_font = menubar.Font
window.resize_content()

######################################################################
Expand Down
1 change: 0 additions & 1 deletion winforms/src/toga_winforms/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

class Container(Scalable):
def __init__(self, native_parent):
self.init_scale(native_parent)
self.native_parent = native_parent
self.native_width = self.native_height = 0
self.content = None
Expand Down
20 changes: 14 additions & 6 deletions winforms/src/toga_winforms/screens.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@

from toga.screens import Screen as ScreenInterface

from .widgets.base import Scalable

class Screen:

class Screen(Scalable):
_instances = {}

def __new__(cls, native):
Expand All @@ -30,17 +32,23 @@ def get_name(self):
return name.split("\\")[-1]

def get_origin(self):
return self.native.Bounds.X, self.native.Bounds.Y
return (
self.scale_out(self.native.Bounds.X),
self.scale_out(self.native.Bounds.Y),
)

def get_size(self):
return self.native.Bounds.Width, self.native.Bounds.Height
return (
self.scale_out(self.native.Bounds.Width),
self.scale_out(self.native.Bounds.Height),
)

def get_image_data(self):
bitmap = Bitmap(*self.get_size())
bitmap = Bitmap(*map(self.scale_in, self.get_size()))
graphics = Graphics.FromImage(bitmap)
source_point = Point(*self.get_origin())
source_point = Point(*map(self.scale_in, self.get_origin()))
destination_point = Point(0, 0)
copy_size = Size(*self.get_size())
copy_size = Size(*map(self.scale_in, self.get_size()))
graphics.CopyFromScreen(source_point, destination_point, copy_size)
stream = MemoryStream()
bitmap.Save(stream, Imaging.ImageFormat.Png)
Expand Down