| 1 |
import ctypes |
| 2 |
import logging |
| 3 |
import os |
| 4 |
import signal |
| 5 |
import sys |
| 6 |
import tempfile |
| 7 |
import threading |
| 8 |
import winreg |
| 9 |
from ctypes import windll, wintypes |
| 10 |
from platform import machine |
| 11 |
from threading import Event, Semaphore |
| 12 |
|
| 13 |
try: |
| 14 |
import clr |
| 15 |
except Exception: |
| 16 |
os.environ['PYTHONNET_RUNTIME'] = 'coreclr' |
| 17 |
import clr |
| 18 |
|
| 19 |
from webview import FileDialog, _state, settings, windows |
| 20 |
from webview.guilib import forced_gui_ |
| 21 |
from webview.menu import Menu, MenuAction, MenuSeparator |
| 22 |
from webview.platforms import win32 |
| 23 |
from webview.screen import Screen |
| 24 |
from webview.util import inject_base_uri, parse_file_type |
| 25 |
from webview.window import FixPoint |
| 26 |
|
| 27 |
clr.AddReference('System.Windows.Forms') |
| 28 |
clr.AddReference('System.Collections') |
| 29 |
clr.AddReference('System.Threading') |
| 30 |
clr.AddReference('System.Reflection') |
| 31 |
|
| 32 |
import System.Windows.Forms as WinForms # noqa: E402 |
| 33 |
from Microsoft.Win32 import SystemEvents # noqa: E402 |
| 34 |
from System import Array, Environment, Func, Int32, IntPtr, Object, Type, UInt32 # noqa: E402 |
| 35 |
from System.Drawing import Color, ColorTranslator, Icon, Point, Size, SizeF # noqa: E402 |
| 36 |
from System.Reflection import Assembly, BindingFlags # noqa: E402 |
| 37 |
from System.Threading import ApartmentState, Thread, ThreadStart # noqa: E402 |
| 38 |
|
| 39 |
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) |
| 40 |
logger = logging.getLogger('pywebview') |
| 41 |
cache_dir = None |
| 42 |
_sigint_received = False |
| 43 |
|
| 44 |
|
| 45 |
def _sigint_handler(signum, frame): |
| 46 |
""" |
| 47 |
Handler for SIGINT signal (Ctrl+C). |
| 48 |
|
| 49 |
Sets a flag that's checked by the timer in the GUI thread. This is necessary because |
| 50 |
the signal handler runs in the main thread, but Application.Exit() must be called |
| 51 |
from the GUI thread. The timer in create_window() checks this flag periodically and |
| 52 |
exits the application when it's set. |
| 53 |
""" |
| 54 |
global _sigint_received |
| 55 |
_sigint_received = True |
| 56 |
|
| 57 |
|
| 58 |
def _is_new_version(current_version: str, new_version: str) -> bool: |
| 59 |
new_range = new_version.split('.') |
| 60 |
cur_range = current_version.split('.') |
| 61 |
for index, _ in enumerate(new_range): |
| 62 |
if len(cur_range) > index: |
| 63 |
return int(new_range[index]) >= int(cur_range[index]) |
| 64 |
|
| 65 |
return False |
| 66 |
|
| 67 |
|
| 68 |
def _is_chromium(): |
| 69 |
if settings['WEBVIEW2_RUNTIME_PATH']: |
| 70 |
return True |
| 71 |
|
| 72 |
def edge_build(key_type, key, description=''): |
| 73 |
try: |
| 74 |
if machine() == 'x86' or key_type == 'HKEY_CURRENT_USER': |
| 75 |
path = rf'Microsoft\EdgeUpdate\Clients\{key}' |
| 76 |
else: |
| 77 |
path = rf'WOW6432Node\Microsoft\EdgeUpdate\Clients\{key}' |
| 78 |
|
| 79 |
with winreg.OpenKey(getattr(winreg, key_type), rf'SOFTWARE\{path}') as windows_key: |
| 80 |
build, _ = winreg.QueryValueEx(windows_key, 'pv') |
| 81 |
return str(build) |
| 82 |
|
| 83 |
except Exception: |
| 84 |
pass |
| 85 |
|
| 86 |
return '0' |
| 87 |
|
| 88 |
try: |
| 89 |
net_key = winreg.OpenKey( |
| 90 |
winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full' |
| 91 |
) |
| 92 |
version, _ = winreg.QueryValueEx(net_key, 'Release') |
| 93 |
|
| 94 |
if version < 394802: # .NET 4.6.2 |
| 95 |
return False |
| 96 |
|
| 97 |
build_versions = [ |
| 98 |
{ |
| 99 |
'key': '{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}', |
| 100 |
'description': 'Microsoft Edge WebView2 Runtime', |
| 101 |
}, # runtime |
| 102 |
{ |
| 103 |
'key': '{2CD8A007-E189-409D-A2C8-9AF4EF3C72AA}', |
| 104 |
'description': 'Microsoft Edge WebView2 Beta', |
| 105 |
}, # beta |
| 106 |
{ |
| 107 |
'key': '{0D50BFEC-CD6A-4F9A-964C-C7416E3ACB10}', |
| 108 |
'description': 'Microsoft Edge WebView2 Developer', |
| 109 |
}, # dev |
| 110 |
{ |
| 111 |
'key': '{65C35B14-6C1D-4122-AC46-7148CC9D6497}', |
| 112 |
'description': 'Microsoft Edge WebView2 Canary', |
| 113 |
}, # canary |
| 114 |
] |
| 115 |
|
| 116 |
for item in build_versions: |
| 117 |
for key_type in ('HKEY_CURRENT_USER', 'HKEY_LOCAL_MACHINE'): |
| 118 |
build = edge_build(key_type, item['key'], item['description']) |
| 119 |
if _is_new_version('86.0.622.0', build): # Webview2 86.0.622.0 |
| 120 |
return True |
| 121 |
|
| 122 |
except Exception as e: |
| 123 |
logger.exception(e) |
| 124 |
finally: |
| 125 |
winreg.CloseKey(net_key) |
| 126 |
|
| 127 |
return False |
| 128 |
|
| 129 |
|
| 130 |
is_cef = forced_gui_ == 'cef' |
| 131 |
is_chromium = not is_cef and _is_chromium() and forced_gui_ != 'mshtml' |
| 132 |
|
| 133 |
if is_cef: |
| 134 |
from . import cef as CEF |
| 135 |
|
| 136 |
IWebBrowserInterop = object |
| 137 |
|
| 138 |
logger.debug('Using WinForms / CEF') |
| 139 |
renderer = 'cef' |
| 140 |
elif is_chromium: |
| 141 |
from . import edgechromium as Chromium |
| 142 |
|
| 143 |
IWebBrowserInterop = object |
| 144 |
|
| 145 |
logger.debug('Using WinForms / Chromium') |
| 146 |
renderer = 'edgechromium' |
| 147 |
else: |
| 148 |
from . import mshtml as IE |
| 149 |
|
| 150 |
logger.warning( |
| 151 |
'MSHTML is deprecated. See https://pywebview.flowrl.com/guide/web_engine.html on details how to use Edge Chromium' |
| 152 |
) |
| 153 |
logger.debug('Using WinForms / MSHTML') |
| 154 |
IE._set_ie_mode() |
| 155 |
renderer = 'mshtml' |
| 156 |
|
| 157 |
|
| 158 |
def DwmSetWindowAttribute(hwnd, attr, value, size=4): |
| 159 |
DwmSetWindowAttribute = ctypes.windll.dwmapi.DwmSetWindowAttribute |
| 160 |
DwmSetWindowAttribute.argtypes = [ |
| 161 |
wintypes.HWND, |
| 162 |
wintypes.DWORD, |
| 163 |
ctypes.c_void_p, |
| 164 |
wintypes.DWORD, |
| 165 |
] |
| 166 |
return DwmSetWindowAttribute(hwnd, attr, ctypes.byref(ctypes.c_int(value)), size) |
| 167 |
|
| 168 |
|
| 169 |
def ExtendFrameIntoClientArea(hwnd): |
| 170 |
class _MARGINS(ctypes.Structure): |
| 171 |
_fields_ = [ |
| 172 |
('cxLeftWidth', ctypes.c_int), |
| 173 |
('cxRightWidth', ctypes.c_int), |
| 174 |
('cyTopHeight', ctypes.c_int), |
| 175 |
('cyBottomHeight', ctypes.c_int), |
| 176 |
] |
| 177 |
|
| 178 |
DwmExtendFrameIntoClientArea = ctypes.windll.dwmapi.DwmExtendFrameIntoClientArea |
| 179 |
m = _MARGINS() |
| 180 |
m.cxLeftWidth = 1 |
| 181 |
m.cxRightWidth = 1 |
| 182 |
m.cyTopHeight = 1 |
| 183 |
m.cyBottomHeight = 1 |
| 184 |
return DwmExtendFrameIntoClientArea(hwnd, ctypes.byref(m)) |
| 185 |
|
| 186 |
|
| 187 |
class BrowserView: |
| 188 |
instances = {} |
| 189 |
|
| 190 |
class BrowserForm(WinForms.Form): |
| 191 |
def __init__(self, window, cache_dir): |
| 192 |
super().__init__() |
| 193 |
self.uid = window.uid |
| 194 |
self.pywebview_window = window |
| 195 |
self.pywebview_window.native = self |
| 196 |
self.real_url = None |
| 197 |
self.Text = window.title |
| 198 |
# Store initial window size as logical pixels, will be converted later |
| 199 |
self._initial_width = window.initial_width |
| 200 |
self._initial_height = window.initial_height |
| 201 |
|
| 202 |
self.AutoScaleDimensions = SizeF(96.0, 96.0) |
| 203 |
self.AutoScaleMode = WinForms.AutoScaleMode.Dpi |
| 204 |
hwnd = self.Handle.ToInt32() |
| 205 |
|
| 206 |
# Set the initial size now that we have a window handle and can get DPI |
| 207 |
# Size and MinimumSize need to be in physical pixels |
| 208 |
scale = self._scale |
| 209 |
self.Size = Size(int(window.initial_width * scale), int(window.initial_height * scale)) |
| 210 |
self.MinimumSize = Size( |
| 211 |
int(window.min_size[0] * scale), int(window.min_size[1] * scale) |
| 212 |
) |
| 213 |
|
| 214 |
if window.initial_x is not None and window.initial_y is not None: |
| 215 |
self.StartPosition = WinForms.FormStartPosition.Manual |
| 216 |
# Convert logical pixel coordinates to physical for WinForms |
| 217 |
self.Location = Point( |
| 218 |
int(window.initial_x * scale), |
| 219 |
int(window.initial_y * scale), |
| 220 |
) |
| 221 |
elif window.screen: |
| 222 |
self.StartPosition = WinForms.FormStartPosition.Manual |
| 223 |
# Screen coordinates are in logical pixels, center the window |
| 224 |
# Calculate center position in logical pixels first, then convert to physical |
| 225 |
logical_x = window.screen.x + (window.screen.width - window.initial_width) // 2 |
| 226 |
logical_y = window.screen.y + (window.screen.height - window.initial_height) // 2 |
| 227 |
self.Location = Point(int(logical_x * scale), int(logical_y * scale)) |
| 228 |
else: |
| 229 |
self.StartPosition = WinForms.FormStartPosition.CenterScreen |
| 230 |
|
| 231 |
if not window.resizable: |
| 232 |
self.FormBorderStyle = WinForms.FormBorderStyle.FixedSingle |
| 233 |
self.MaximizeBox = False |
| 234 |
|
| 235 |
if window.maximized: |
| 236 |
self.WindowState = WinForms.FormWindowState.Maximized |
| 237 |
elif window.minimized: |
| 238 |
self.WindowState = WinForms.FormWindowState.Minimized |
| 239 |
|
| 240 |
self.old_state = self.WindowState |
| 241 |
|
| 242 |
# Application icon |
| 243 |
if _state['icon'] and os.path.isfile(_state['icon']): |
| 244 |
self.Icon = Icon(_state['icon']) |
| 245 |
else: |
| 246 |
handle = kernel32.GetModuleHandleW(None) |
| 247 |
icon_handle = windll.shell32.ExtractIconW(handle, sys.executable, 0) |
| 248 |
|
| 249 |
if icon_handle != 0: |
| 250 |
self.Icon = Icon.FromHandle(IntPtr.op_Explicit(Int32(icon_handle))).Clone() |
| 251 |
windll.user32.DestroyIcon(icon_handle) |
| 252 |
|
| 253 |
self.closed = window.events.closed |
| 254 |
self.closing = window.events.closing |
| 255 |
self.shown = window.events.shown |
| 256 |
self.loaded = window.events.loaded |
| 257 |
self.url = window.real_url |
| 258 |
self.TopMost = window.on_top |
| 259 |
|
| 260 |
self.is_fullscreen = False |
| 261 |
if window.fullscreen: |
| 262 |
self.toggle_fullscreen() |
| 263 |
|
| 264 |
if window.shadow and not window.transparent: |
| 265 |
# Should do this before set frameless |
| 266 |
ExtendFrameIntoClientArea(hwnd) |
| 267 |
DwmSetWindowAttribute(hwnd, 2, 2, 4) |
| 268 |
|
| 269 |
if window.frameless: |
| 270 |
self.frameless = window.frameless |
| 271 |
self.FormBorderStyle = getattr(WinForms.FormBorderStyle, 'None') |
| 272 |
|
| 273 |
if window.menu or _state['menu']: |
| 274 |
self.set_window_menu(window.menu or _state['menu']) |
| 275 |
|
| 276 |
if is_cef: |
| 277 |
self.browser = None |
| 278 |
CEF.create_browser(window, hwnd, BrowserView.alert, self) |
| 279 |
elif is_chromium: |
| 280 |
self.browser = Chromium.EdgeChrome(self, window, cache_dir) |
| 281 |
self.webview = self.browser.webview |
| 282 |
else: |
| 283 |
self.browser = IE.MSHTML(self, window, BrowserView.alert) |
| 284 |
self.webview = self.browser.webview |
| 285 |
|
| 286 |
if ( |
| 287 |
window.transparent and self.browser |
| 288 |
): # window transparency is supported only with EdgeChromium |
| 289 |
self.SetStyle(WinForms.ControlStyles.SupportsTransparentBackColor, True) |
| 290 |
self.browser.DefaultBackgroundColor = Color.Transparent |
| 291 |
else: |
| 292 |
self.BackColor = ColorTranslator.FromHtml(window.background_color) |
| 293 |
|
| 294 |
if not window.focus: |
| 295 |
windll.user32.SetWindowLongW( |
| 296 |
self.Handle.ToInt32(), |
| 297 |
-20, |
| 298 |
windll.user32.GetWindowLongW(self.Handle.ToInt32(), -20) | 0x8000000, |
| 299 |
) |
| 300 |
|
| 301 |
self.Activated += self.on_activated |
| 302 |
self.Shown += self.on_shown |
| 303 |
self.FormClosed += self.on_close |
| 304 |
self.FormClosing += self.on_closing |
| 305 |
self.Resize += self.on_resize |
| 306 |
self.Move += self.on_move |
| 307 |
|
| 308 |
self.localization = window.localization |
| 309 |
|
| 310 |
self.update_title_bar_theme() |
| 311 |
SystemEvents.UserPreferenceChanged += self.on_system_theme_changed |
| 312 |
|
| 313 |
def __str__(self): |
| 314 |
return f'<System.Windows.Forms object with {self.Handle} handle>' |
| 315 |
|
| 316 |
@property |
| 317 |
def _scale(self): |
| 318 |
"""Logical-to-physical pixel scale for the monitor this window is on.""" |
| 319 |
if is_chromium: |
| 320 |
try: |
| 321 |
# Use per-window DPI for accurate multi-monitor support |
| 322 |
return windll.user32.GetDpiForWindow(self.Handle.ToInt32()) / 96 |
| 323 |
except Exception as e: |
| 324 |
logger.warning(f'Failed to get DPI for window: {e}') |
| 325 |
return 1.0 |
| 326 |
else: |
| 327 |
# MSHTML doesn't need scaling |
| 328 |
return 1.0 |
| 329 |
|
| 330 |
def on_system_theme_changed(self, sender, e): |
| 331 |
self.update_title_bar_theme() |
| 332 |
|
| 333 |
def update_title_bar_theme(self): |
| 334 |
if self.is_dark_theme(): |
| 335 |
DwmSetWindowAttribute(self.Handle.ToInt32(), 20, 1) |
| 336 |
DwmSetWindowAttribute(self.Handle.ToInt32(), 38, 2) |
| 337 |
else: |
| 338 |
DwmSetWindowAttribute(self.Handle.ToInt32(), 20, 0) |
| 339 |
DwmSetWindowAttribute(self.Handle.ToInt32(), 38, 1) |
| 340 |
|
| 341 |
def is_dark_theme(self): |
| 342 |
try: |
| 343 |
personalize_key = winreg.OpenKey( |
| 344 |
winreg.HKEY_CURRENT_USER, |
| 345 |
r'Software\Microsoft\Windows\CurrentVersion\Themes\Personalize', |
| 346 |
0, |
| 347 |
winreg.KEY_READ, |
| 348 |
) |
| 349 |
system_theme, _ = winreg.QueryValueEx(personalize_key, 'AppsUseLightTheme') |
| 350 |
winreg.CloseKey(personalize_key) |
| 351 |
if system_theme == 0: |
| 352 |
return True |
| 353 |
else: |
| 354 |
return False |
| 355 |
except Exception as e: |
| 356 |
logger.debug(f'Error while getting system theme: {e}') |
| 357 |
return None |
| 358 |
|
| 359 |
def on_activated(self, *_): |
| 360 |
if not self.pywebview_window.focus: |
| 361 |
windll.user32.SetWindowLongW( |
| 362 |
self.Handle.ToInt32(), |
| 363 |
-20, |
| 364 |
windll.user32.GetWindowLongW(self.Handle.ToInt32(), -20) | 0x8000000, |
| 365 |
) |
| 366 |
|
| 367 |
def on_shown(self, *_): |
| 368 |
if not is_cef: |
| 369 |
self.shown.set() |
| 370 |
self.browser.webview.Focus() |
| 371 |
|
| 372 |
def on_close(self, *_): |
| 373 |
def _shutdown(): |
| 374 |
if is_cef: |
| 375 |
CEF.shutdown() |
| 376 |
elif is_chromium: |
| 377 |
self.hide() |
| 378 |
self.browser.clear_user_data() |
| 379 |
|
| 380 |
WinForms.Application.Exit() |
| 381 |
|
| 382 |
if not is_cef: |
| 383 |
# stop waiting for JS result |
| 384 |
self.browser.js_result_semaphore.release() |
| 385 |
|
| 386 |
if is_cef: |
| 387 |
CEF.close_window(self.uid) |
| 388 |
|
| 389 |
del BrowserView.instances[self.uid] |
| 390 |
|
| 391 |
# during tests windows is empty for some reason. no idea why. |
| 392 |
if self.pywebview_window in windows: |
| 393 |
windows.remove(self.pywebview_window) |
| 394 |
|
| 395 |
self.closed.set() |
| 396 |
|
| 397 |
if len(BrowserView.instances) == 0: |
| 398 |
self.Invoke(Func[Type](_shutdown)) |
| 399 |
|
| 400 |
def on_closing(self, sender, args): |
| 401 |
should_cancel = self.closing.set() |
| 402 |
if should_cancel: |
| 403 |
args.Cancel = True |
| 404 |
|
| 405 |
if not args.Cancel: |
| 406 |
if self.pywebview_window.confirm_close: |
| 407 |
result = WinForms.MessageBox.Show( |
| 408 |
self.localization['global.quitConfirmation'], |
| 409 |
self.Text, |
| 410 |
WinForms.MessageBoxButtons.OKCancel, |
| 411 |
WinForms.MessageBoxIcon.Asterisk, |
| 412 |
) |
| 413 |
|
| 414 |
if result == WinForms.DialogResult.Cancel: |
| 415 |
args.Cancel = True |
| 416 |
|
| 417 |
def on_resize(self, sender, args): |
| 418 |
if self.WindowState == WinForms.FormWindowState.Maximized: |
| 419 |
self.pywebview_window.events.maximized.set() |
| 420 |
|
| 421 |
if self.WindowState == WinForms.FormWindowState.Minimized: |
| 422 |
self.pywebview_window.events.minimized.set() |
| 423 |
|
| 424 |
if self.WindowState == WinForms.FormWindowState.Normal and self.old_state in ( |
| 425 |
WinForms.FormWindowState.Minimized, |
| 426 |
WinForms.FormWindowState.Maximized, |
| 427 |
): |
| 428 |
self.pywebview_window.events.restored.set() |
| 429 |
|
| 430 |
self.old_state = self.WindowState |
| 431 |
|
| 432 |
if is_cef: |
| 433 |
CEF.resize(self.Width, self.Height, self.uid) |
| 434 |
|
| 435 |
# Convert physical pixel dimensions to logical pixels for the API |
| 436 |
scale = self._scale |
| 437 |
self.pywebview_window.events.resized.set( |
| 438 |
int(self.Width / scale), int(self.Height / scale) |
| 439 |
) |
| 440 |
|
| 441 |
def on_move(self, sender, args): |
| 442 |
# Convert physical pixel location to logical pixels for the API |
| 443 |
scale = self._scale |
| 444 |
self.pywebview_window.events.moved.set( |
| 445 |
int(self.Location.X / scale), |
| 446 |
int(self.Location.Y / scale), |
| 447 |
) |
| 448 |
|
| 449 |
def evaluate_js(self, script, parse_json): |
| 450 |
result = self.browser.evaluate_js(script, parse_json) |
| 451 |
return result |
| 452 |
|
| 453 |
def clear_cookies(self): |
| 454 |
def _clear_cookies(): |
| 455 |
self.browser.clear_cookies() |
| 456 |
|
| 457 |
if not is_chromium: |
| 458 |
logger.error('clear_cookies() is not implemented for this platform') |
| 459 |
return |
| 460 |
|
| 461 |
self.Invoke(Func[Type](_clear_cookies)) |
| 462 |
|
| 463 |
def get_cookies(self): |
| 464 |
def _get_cookies(): |
| 465 |
self.browser.get_cookies(cookies, semaphore) |
| 466 |
|
| 467 |
cookies = [] |
| 468 |
if not is_chromium: |
| 469 |
logger.error('get_cookies() is not implemented for this platform') |
| 470 |
return cookies |
| 471 |
|
| 472 |
semaphore = Semaphore(0) |
| 473 |
|
| 474 |
self.Invoke(Func[Type](_get_cookies)) |
| 475 |
semaphore.acquire() |
| 476 |
|
| 477 |
return cookies |
| 478 |
|
| 479 |
def load_html(self, content, base_uri): |
| 480 |
def _load_html(): |
| 481 |
self.browser.load_html(content, base_uri) |
| 482 |
|
| 483 |
self.Invoke(Func[Type](_load_html)) |
| 484 |
|
| 485 |
def load_url(self, url): |
| 486 |
def _load_url(): |
| 487 |
self.browser.load_url(url) |
| 488 |
|
| 489 |
self.Invoke(Func[Type](_load_url)) |
| 490 |
|
| 491 |
def hide(self): |
| 492 |
self.Invoke(Func[Type](self.Hide)) |
| 493 |
|
| 494 |
def show(self): |
| 495 |
def _show(): |
| 496 |
self.Show() |
| 497 |
self.Activate() |
| 498 |
|
| 499 |
if self.InvokeRequired: |
| 500 |
self.Invoke(Func[Type](_show)) |
| 501 |
else: |
| 502 |
_show() |
| 503 |
|
| 504 |
def set_window_menu(self, menu_list): |
| 505 |
def _set_window_menu(): |
| 506 |
def create_action_item(menu_line_item): |
| 507 |
action_item = WinForms.ToolStripMenuItem(menu_line_item.title) |
| 508 |
# Don't run action function on main thread |
| 509 |
action_item.Click += ( |
| 510 |
lambda _, __, menu_line_item=menu_line_item: threading.Thread( |
| 511 |
target=menu_line_item.function |
| 512 |
).start() |
| 513 |
) |
| 514 |
return action_item |
| 515 |
|
| 516 |
def create_submenu(title, line_items, supermenu=None): |
| 517 |
m = WinForms.ToolStripMenuItem(title) |
| 518 |
for menu_line_item in line_items: |
| 519 |
if isinstance(menu_line_item, MenuSeparator): |
| 520 |
m.DropDownItems.Add(WinForms.ToolStripSeparator()) |
| 521 |
continue |
| 522 |
elif isinstance(menu_line_item, MenuAction): |
| 523 |
m.DropDownItems.Add(create_action_item(menu_line_item)) |
| 524 |
elif isinstance(menu_line_item, Menu): |
| 525 |
create_submenu(menu_line_item.title, menu_line_item.items, m) |
| 526 |
|
| 527 |
if supermenu: |
| 528 |
supermenu.DropDownItems.Add(m) |
| 529 |
|
| 530 |
return m |
| 531 |
|
| 532 |
top_level_menu = WinForms.MenuStrip() |
| 533 |
|
| 534 |
for menu in menu_list: |
| 535 |
# Ignore '__app__' menus (macOS-only feature) |
| 536 |
if isinstance(menu, Menu) and menu.title == '__app__': |
| 537 |
continue |
| 538 |
if isinstance(menu, Menu): |
| 539 |
top_level_menu.Items.Add(create_submenu(menu.title, menu.items)) |
| 540 |
elif isinstance(menu, MenuAction): |
| 541 |
top_level_menu.Items.Add(create_action_item(menu)) |
| 542 |
|
| 543 |
self.Controls.Add(top_level_menu) |
| 544 |
|
| 545 |
if self.InvokeRequired: |
| 546 |
self.Invoke(Func[Type](_set_window_menu)) |
| 547 |
else: |
| 548 |
_set_window_menu() |
| 549 |
|
| 550 |
def toggle_fullscreen(self): |
| 551 |
def _toggle(): |
| 552 |
if not self.is_fullscreen: |
| 553 |
self.old_size = self.Size |
| 554 |
self.old_state = self.WindowState |
| 555 |
self.old_style = self.FormBorderStyle |
| 556 |
self.old_location = self.Location |
| 557 |
self.old_screen = WinForms.Screen.FromControl(self) |
| 558 |
self.FormBorderStyle = getattr(WinForms.FormBorderStyle, 'None') |
| 559 |
self.Bounds = WinForms.Screen.FromControl(self).Bounds |
| 560 |
self.WindowState = WinForms.FormWindowState.Maximized |
| 561 |
self.is_fullscreen = True |
| 562 |
windll.user32.SetWindowPos( |
| 563 |
self.Handle.ToInt32(), |
| 564 |
None, |
| 565 |
self.old_screen.Bounds.X, |
| 566 |
self.old_screen.Bounds.Y, |
| 567 |
self.old_screen.Bounds.Width, |
| 568 |
self.old_screen.Bounds.Height, |
| 569 |
64, |
| 570 |
) |
| 571 |
# disable window rounding |
| 572 |
DwmSetWindowAttribute(self.Handle.ToInt32(), 33, 1) |
| 573 |
# hide window border |
| 574 |
DwmSetWindowAttribute(self.Handle.ToInt32(), 34, 0xFFFFFFFE) |
| 575 |
else: |
| 576 |
self.WindowState = WinForms.FormWindowState.Normal |
| 577 |
self.FormBorderStyle = self.old_style |
| 578 |
self.is_fullscreen = False |
| 579 |
valid_location = any( |
| 580 |
screen == self.old_screen for screen in WinForms.Screen.AllScreens |
| 581 |
) |
| 582 |
|
| 583 |
if not valid_location: |
| 584 |
self.Size = self.old_size |
| 585 |
self.CenterToScreen() |
| 586 |
else: |
| 587 |
self.Location = self.old_location |
| 588 |
self.Size = self.old_size |
| 589 |
|
| 590 |
# enable window rounding |
| 591 |
DwmSetWindowAttribute(self.Handle.ToInt32(), 33, 0) |
| 592 |
# show window border |
| 593 |
DwmSetWindowAttribute(self.Handle.ToInt32(), 34, 0xFFFFFFFF) |
| 594 |
|
| 595 |
if self.InvokeRequired: |
| 596 |
self.Invoke(Func[Type](_toggle)) |
| 597 |
else: |
| 598 |
_toggle() |
| 599 |
|
| 600 |
def resize(self, width, height, fix_point): |
| 601 |
# Input width/height are in logical pixels, need to convert to physical |
| 602 |
scale = self._scale |
| 603 |
phys_width = int(width * scale) |
| 604 |
phys_height = int(height * scale) |
| 605 |
|
| 606 |
# Location is already in physical pixels |
| 607 |
x = self.Location.X |
| 608 |
y = self.Location.Y |
| 609 |
|
| 610 |
if fix_point & FixPoint.EAST: |
| 611 |
x = x + self.Width - phys_width |
| 612 |
|
| 613 |
if fix_point & FixPoint.SOUTH: |
| 614 |
y = y + self.Height - phys_height |
| 615 |
|
| 616 |
windll.user32.SetWindowPos( |
| 617 |
self.Handle.ToInt32(), None, x, y, phys_width, phys_height, 64 |
| 618 |
) |
| 619 |
|
| 620 |
def move(self, x, y): |
| 621 |
# Input x/y are in logical pixels, need to convert to physical |
| 622 |
SWP_NOSIZE = 0x0001 # Retains the current size |
| 623 |
SWP_NOZORDER = 0x0004 # Retains the current Z order |
| 624 |
SWP_SHOWWINDOW = 0x0040 # Displays the window |
| 625 |
|
| 626 |
scale = self._scale |
| 627 |
if scale != 1: |
| 628 |
# Convert logical pixels to physical pixels |
| 629 |
x_phys = int(x * scale) |
| 630 |
y_phys = int(y * scale) |
| 631 |
else: |
| 632 |
x_phys = int(x) |
| 633 |
y_phys = int(y) |
| 634 |
|
| 635 |
windll.user32.SetWindowPos( |
| 636 |
self.Handle.ToInt32(), |
| 637 |
None, |
| 638 |
x_phys, |
| 639 |
y_phys, |
| 640 |
None, |
| 641 |
None, |
| 642 |
SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW, |
| 643 |
) |
| 644 |
|
| 645 |
def maximize(self): |
| 646 |
def _maximize(): |
| 647 |
self.WindowState = WinForms.FormWindowState.Maximized |
| 648 |
|
| 649 |
self.Invoke(Func[Type](_maximize)) |
| 650 |
|
| 651 |
def minimize(self): |
| 652 |
def _minimize(): |
| 653 |
self.WindowState = WinForms.FormWindowState.Minimized |
| 654 |
|
| 655 |
self.Invoke(Func[Type](_minimize)) |
| 656 |
|
| 657 |
def restore(self): |
| 658 |
def _restore(): |
| 659 |
self.WindowState = WinForms.FormWindowState.Normal |
| 660 |
|
| 661 |
self.Invoke(Func[Type](_restore)) |
| 662 |
|
| 663 |
@staticmethod |
| 664 |
def alert(message): |
| 665 |
WinForms.MessageBox.Show(str(message)) |
| 666 |
|
| 667 |
|
| 668 |
class OpenFolderDialog: |
| 669 |
foldersFilter = 'Folders|\n' |
| 670 |
flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic |
| 671 |
windowsFormsAssembly = Assembly.LoadWithPartialName('System.Windows.Forms') |
| 672 |
iFileDialogType = windowsFormsAssembly.GetType( |
| 673 |
'System.Windows.Forms.FileDialogNative+IFileDialog' |
| 674 |
) |
| 675 |
OpenFileDialogType = windowsFormsAssembly.GetType('System.Windows.Forms.OpenFileDialog') |
| 676 |
FileDialogType = windowsFormsAssembly.GetType('System.Windows.Forms.FileDialog') |
| 677 |
createVistaDialogMethodInfo = OpenFileDialogType.GetMethod('CreateVistaDialog', flags) |
| 678 |
onBeforeVistaDialogMethodInfo = OpenFileDialogType.GetMethod('OnBeforeVistaDialog', flags) |
| 679 |
getOptionsMethodInfo = FileDialogType.GetMethod('GetOptions', flags) |
| 680 |
setOptionsMethodInfo = iFileDialogType.GetMethod('SetOptions', flags) |
| 681 |
fosPickFoldersBitFlag = ( |
| 682 |
windowsFormsAssembly.GetType('System.Windows.Forms.FileDialogNative+FOS') |
| 683 |
.GetField('FOS_PICKFOLDERS') |
| 684 |
.GetValue(None) |
| 685 |
) |
| 686 |
|
| 687 |
vistaDialogEventsConstructorInfo = windowsFormsAssembly.GetType( |
| 688 |
'System.Windows.Forms.FileDialog+VistaDialogEvents' |
| 689 |
).GetConstructor(flags, None, [FileDialogType], []) |
| 690 |
adviseMethodInfo = iFileDialogType.GetMethod('Advise') |
| 691 |
unadviseMethodInfo = iFileDialogType.GetMethod('Unadvise') |
| 692 |
showMethodInfo = iFileDialogType.GetMethod('Show') |
| 693 |
|
| 694 |
@classmethod |
| 695 |
def show(cls, parent=None, initialDirectory=None, allow_multiple=False, title=None): |
| 696 |
openFileDialog = WinForms.OpenFileDialog() |
| 697 |
openFileDialog.InitialDirectory = initialDirectory |
| 698 |
openFileDialog.Title = title |
| 699 |
openFileDialog.Filter = OpenFolderDialog.foldersFilter |
| 700 |
openFileDialog.AddExtension = False |
| 701 |
openFileDialog.CheckFileExists = False |
| 702 |
openFileDialog.DereferenceLinks = True |
| 703 |
openFileDialog.Multiselect = allow_multiple |
| 704 |
openFileDialog.RestoreDirectory = True |
| 705 |
|
| 706 |
iFileDialog = OpenFolderDialog.createVistaDialogMethodInfo.Invoke(openFileDialog, []) |
| 707 |
OpenFolderDialog.onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, [iFileDialog]) |
| 708 |
options = OpenFolderDialog.getOptionsMethodInfo.Invoke(openFileDialog, []) |
| 709 |
options = options.op_BitwiseOr(OpenFolderDialog.fosPickFoldersBitFlag) |
| 710 |
OpenFolderDialog.setOptionsMethodInfo.Invoke(iFileDialog, [options]) |
| 711 |
adviseParametersWithOutputConnectionToken = Array[Object]( |
| 712 |
[ |
| 713 |
OpenFolderDialog.vistaDialogEventsConstructorInfo.Invoke([openFileDialog]), |
| 714 |
UInt32(0), |
| 715 |
] |
| 716 |
) |
| 717 |
OpenFolderDialog.adviseMethodInfo.Invoke( |
| 718 |
iFileDialog, adviseParametersWithOutputConnectionToken |
| 719 |
) |
| 720 |
dwCookie = adviseParametersWithOutputConnectionToken.GetValue(1) |
| 721 |
try: |
| 722 |
result = OpenFolderDialog.showMethodInfo.Invoke( |
| 723 |
iFileDialog, [parent.Handle if parent else None] |
| 724 |
) |
| 725 |
if result == 0: |
| 726 |
return tuple(openFileDialog.FileNames) |
| 727 |
|
| 728 |
return None |
| 729 |
|
| 730 |
finally: |
| 731 |
OpenFolderDialog.unadviseMethodInfo.Invoke(iFileDialog, [UInt32(dwCookie)]) |
| 732 |
|
| 733 |
|
| 734 |
_main_window_created = Event() |
| 735 |
_main_window_created.clear() |
| 736 |
|
| 737 |
_already_set_up_app = False |
| 738 |
|
| 739 |
|
| 740 |
def init_storage(): |
| 741 |
global cache_dir |
| 742 |
|
| 743 |
if not _state['private_mode'] or _state['storage_path']: |
| 744 |
try: |
| 745 |
data_folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) |
| 746 |
|
| 747 |
if not os.access(data_folder, os.W_OK): |
| 748 |
data_folder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) |
| 749 |
|
| 750 |
cache_dir = _state['storage_path'] or os.path.join(data_folder, 'pywebview') |
| 751 |
|
| 752 |
if not os.path.exists(cache_dir): |
| 753 |
os.makedirs(cache_dir) |
| 754 |
except Exception: |
| 755 |
logger.exception(f'Cache directory {cache_dir} creation failed') |
| 756 |
else: |
| 757 |
cache_dir = tempfile.TemporaryDirectory().name |
| 758 |
|
| 759 |
|
| 760 |
def setup_app(): |
| 761 |
# MUST be called before create_window |
| 762 |
global _already_set_up_app |
| 763 |
if _already_set_up_app: |
| 764 |
return |
| 765 |
|
| 766 |
WinForms.Application.EnableVisualStyles() |
| 767 |
WinForms.Application.SetCompatibleTextRenderingDefault(False) |
| 768 |
_already_set_up_app = True |
| 769 |
|
| 770 |
|
| 771 |
def create_window(window): |
| 772 |
def create(): |
| 773 |
browser = BrowserView.BrowserForm(window, cache_dir) |
| 774 |
BrowserView.instances[window.uid] = browser |
| 775 |
window.events.before_show.set() |
| 776 |
|
| 777 |
if window.hidden: |
| 778 |
browser.Opacity = 0 |
| 779 |
browser.Show() |
| 780 |
browser.Hide() |
| 781 |
browser.Opacity = 1 |
| 782 |
elif window.transparent and is_chromium: |
| 783 |
# hack to make transparent window work |
| 784 |
# window is started hidden and shown on Navigating event. |
| 785 |
# no idea why this works |
| 786 |
browser.Show() |
| 787 |
browser.Hide() |
| 788 |
else: |
| 789 |
browser.Show() |
| 790 |
|
| 791 |
_main_window_created.set() |
| 792 |
|
| 793 |
if window.uid == 'master': |
| 794 |
|
| 795 |
def timer_tick(sender, e): |
| 796 |
# Check if SIGINT was received and exit from GUI thread |
| 797 |
global _sigint_received |
| 798 |
if _sigint_received: |
| 799 |
app.Exit() |
| 800 |
|
| 801 |
# Create a timer to periodically allow the Python interpreter to run |
| 802 |
# This enables the signal handler to be called even when the WinForms event loop is running |
| 803 |
timer = WinForms.Timer() |
| 804 |
timer.Interval = 500 # 500ms |
| 805 |
timer.Tick += timer_tick |
| 806 |
timer.Start() |
| 807 |
|
| 808 |
app.Run() |
| 809 |
|
| 810 |
app = WinForms.Application |
| 811 |
|
| 812 |
if window.uid == 'master': |
| 813 |
# Set up Ctrl+C handler in main thread (before starting GUI thread) |
| 814 |
signal.signal(signal.SIGINT, _sigint_handler) |
| 815 |
|
| 816 |
if is_chromium: |
| 817 |
init_storage() |
| 818 |
|
| 819 |
if sys.getwindowsversion().major >= 6: |
| 820 |
windll.user32.SetProcessDPIAware() |
| 821 |
|
| 822 |
if is_cef: |
| 823 |
CEF.init(window, cache_dir) |
| 824 |
|
| 825 |
thread = Thread(ThreadStart(create)) |
| 826 |
thread.SetApartmentState(ApartmentState.STA) |
| 827 |
thread.Start() |
| 828 |
|
| 829 |
# Don't use thread.Join() as it blocks the main thread indefinitely, |
| 830 |
# preventing signal handlers from being processed. Instead, periodically |
| 831 |
# check if the thread is still alive, which allows the Python interpreter |
| 832 |
# to process pending signals (like SIGINT from Ctrl+C) |
| 833 |
while thread.IsAlive: |
| 834 |
thread.Join(500) |
| 835 |
|
| 836 |
else: |
| 837 |
_main_window_created.wait() |
| 838 |
i = list(BrowserView.instances.values())[0] # arbitrary instance |
| 839 |
i.Invoke(Func[Type](create)) |
| 840 |
|
| 841 |
|
| 842 |
def set_title(title, uid): |
| 843 |
def _set_title(): |
| 844 |
i.Text = title |
| 845 |
|
| 846 |
i = BrowserView.instances.get(uid) |
| 847 |
|
| 848 |
if not i: |
| 849 |
return |
| 850 |
elif i.InvokeRequired: |
| 851 |
i.Invoke(Func[Type](_set_title)) |
| 852 |
else: |
| 853 |
_set_title() |
| 854 |
|
| 855 |
|
| 856 |
def create_confirmation_dialog(title, message, uid): |
| 857 |
i = BrowserView.instances.get(uid) |
| 858 |
|
| 859 |
if not i: |
| 860 |
return |
| 861 |
|
| 862 |
result = WinForms.MessageBox.Show(message, title, WinForms.MessageBoxButtons.OKCancel) |
| 863 |
return result == WinForms.DialogResult.OK |
| 864 |
|
| 865 |
|
| 866 |
def create_file_dialog(dialog_type, directory, allow_multiple, save_filename, file_types, uid): |
| 867 |
i = BrowserView.instances.get(uid) |
| 868 |
|
| 869 |
if not i: |
| 870 |
return |
| 871 |
|
| 872 |
if not directory: |
| 873 |
directory = os.environ['HOMEPATH'] |
| 874 |
|
| 875 |
try: |
| 876 |
if dialog_type == FileDialog.FOLDER: |
| 877 |
file_path = OpenFolderDialog.show(i, directory, allow_multiple) |
| 878 |
|
| 879 |
elif dialog_type == FileDialog.OPEN: |
| 880 |
dialog = WinForms.OpenFileDialog() |
| 881 |
|
| 882 |
dialog.Multiselect = allow_multiple |
| 883 |
dialog.InitialDirectory = directory |
| 884 |
|
| 885 |
if len(file_types) > 0: |
| 886 |
dialog.Filter = '|'.join( |
| 887 |
['{0} ({1})|{1}'.format(*parse_file_type(f)) for f in file_types] |
| 888 |
) |
| 889 |
else: |
| 890 |
dialog.Filter = i.localization['windows.fileFilter.allFiles'] + ' (*.*)|*.*' |
| 891 |
dialog.RestoreDirectory = True |
| 892 |
|
| 893 |
result = dialog.ShowDialog(i) |
| 894 |
if result == WinForms.DialogResult.OK: |
| 895 |
file_path = tuple(dialog.FileNames) |
| 896 |
else: |
| 897 |
file_path = None |
| 898 |
|
| 899 |
elif dialog_type == FileDialog.SAVE: |
| 900 |
dialog = WinForms.SaveFileDialog() |
| 901 |
if len(file_types) > 0: |
| 902 |
dialog.Filter = '|'.join( |
| 903 |
['{0} ({1})|{1}'.format(*parse_file_type(f)) for f in file_types] |
| 904 |
) |
| 905 |
else: |
| 906 |
dialog.Filter = i.localization['windows.fileFilter.allFiles'] + ' (*.*)|*.*' |
| 907 |
dialog.InitialDirectory = directory |
| 908 |
dialog.RestoreDirectory = True |
| 909 |
dialog.FileName = save_filename |
| 910 |
|
| 911 |
result = dialog.ShowDialog(i) |
| 912 |
if result == WinForms.DialogResult.OK: |
| 913 |
file_path = (dialog.FileName,) |
| 914 |
else: |
| 915 |
file_path = None |
| 916 |
|
| 917 |
return file_path |
| 918 |
except Exception as e: |
| 919 |
logger.exception(f'Error invoking {dialog_type} dialog: {e}') |
| 920 |
return None |
| 921 |
|
| 922 |
|
| 923 |
def clear_cookies(uid): |
| 924 |
if is_cef: |
| 925 |
CEF.clear_cookies(uid) |
| 926 |
i = BrowserView.instances.get(uid) |
| 927 |
|
| 928 |
if i: |
| 929 |
i.clear_cookies() |
| 930 |
|
| 931 |
|
| 932 |
def get_cookies(uid): |
| 933 |
if is_cef: |
| 934 |
return CEF.get_cookies(uid) |
| 935 |
i = BrowserView.instances.get(uid) |
| 936 |
|
| 937 |
if i: |
| 938 |
return i.get_cookies() |
| 939 |
|
| 940 |
|
| 941 |
def get_current_url(uid): |
| 942 |
if is_cef: |
| 943 |
return CEF.get_current_url(uid) |
| 944 |
|
| 945 |
i = BrowserView.instances.get(uid) |
| 946 |
if i: |
| 947 |
return i.browser.url |
| 948 |
|
| 949 |
|
| 950 |
def load_url(url, uid): |
| 951 |
i = BrowserView.instances.get(uid) |
| 952 |
if not i: |
| 953 |
return |
| 954 |
|
| 955 |
if is_cef: |
| 956 |
CEF.load_url(url, uid) |
| 957 |
else: |
| 958 |
i.load_url(url) |
| 959 |
|
| 960 |
|
| 961 |
def load_html(content, base_uri, uid): |
| 962 |
i = BrowserView.instances.get(uid) |
| 963 |
|
| 964 |
if is_cef: |
| 965 |
CEF.load_html(inject_base_uri(content, base_uri), uid) |
| 966 |
elif i: |
| 967 |
i.load_html(content, base_uri) |
| 968 |
|
| 969 |
|
| 970 |
def get_active_window(): |
| 971 |
active_window = None |
| 972 |
try: |
| 973 |
active_window = WinForms.Form.ActiveForm |
| 974 |
except Exception: |
| 975 |
return None |
| 976 |
|
| 977 |
if active_window: |
| 978 |
for uid, browser_view_instance in BrowserView.instances.items(): |
| 979 |
if browser_view_instance.Handle == active_window.Handle: |
| 980 |
return browser_view_instance.pywebview_window |
| 981 |
|
| 982 |
return None |
| 983 |
|
| 984 |
|
| 985 |
def show(uid): |
| 986 |
i = BrowserView.instances.get(uid) |
| 987 |
if i: |
| 988 |
i.show() |
| 989 |
|
| 990 |
|
| 991 |
def hide(uid): |
| 992 |
i = BrowserView.instances.get(uid) |
| 993 |
if i: |
| 994 |
i.hide() |
| 995 |
|
| 996 |
|
| 997 |
def toggle_fullscreen(uid): |
| 998 |
i = BrowserView.instances.get(uid) |
| 999 |
if i: |
| 1000 |
i.toggle_fullscreen() |
| 1001 |
|
| 1002 |
|
| 1003 |
def set_on_top(uid, on_top): |
| 1004 |
i = BrowserView.instances.get(uid) |
| 1005 |
if i: |
| 1006 |
i.TopMost = on_top |
| 1007 |
|
| 1008 |
|
| 1009 |
def resize(width, height, uid, fix_point): |
| 1010 |
i = BrowserView.instances.get(uid) |
| 1011 |
if i: |
| 1012 |
i.resize(width, height, fix_point) |
| 1013 |
|
| 1014 |
|
| 1015 |
def move(x, y, uid): |
| 1016 |
i = BrowserView.instances.get(uid) |
| 1017 |
if i: |
| 1018 |
i.move(x, y) |
| 1019 |
|
| 1020 |
|
| 1021 |
def maximize(uid): |
| 1022 |
i = BrowserView.instances.get(uid) |
| 1023 |
if i: |
| 1024 |
i.maximize() |
| 1025 |
|
| 1026 |
|
| 1027 |
def minimize(uid): |
| 1028 |
i = BrowserView.instances.get(uid) |
| 1029 |
if i: |
| 1030 |
i.minimize() |
| 1031 |
|
| 1032 |
|
| 1033 |
def restore(uid): |
| 1034 |
i = BrowserView.instances.get(uid) |
| 1035 |
if i: |
| 1036 |
i.restore() |
| 1037 |
|
| 1038 |
|
| 1039 |
def destroy_window(uid): |
| 1040 |
def _close(): |
| 1041 |
i.Close() |
| 1042 |
|
| 1043 |
i = BrowserView.instances.get(uid) |
| 1044 |
if not i: |
| 1045 |
return |
| 1046 |
|
| 1047 |
i.Invoke(Func[Type](_close)) |
| 1048 |
if not is_cef: |
| 1049 |
i.browser.js_result_semaphore.release() |
| 1050 |
|
| 1051 |
|
| 1052 |
def evaluate_js(script, uid, parse_json, result_id=None): |
| 1053 |
if is_cef: |
| 1054 |
return CEF.evaluate_js(script, result_id, parse_json, uid) |
| 1055 |
|
| 1056 |
i = BrowserView.instances.get(uid) |
| 1057 |
if i: |
| 1058 |
return i.evaluate_js(script, parse_json) |
| 1059 |
|
| 1060 |
|
| 1061 |
def get_position(uid): |
| 1062 |
i = BrowserView.instances.get(uid) |
| 1063 |
if i: |
| 1064 |
# Convert physical pixel position to logical pixels |
| 1065 |
scale = i._scale |
| 1066 |
return int(i.Left / scale), int(i.Top / scale) |
| 1067 |
|
| 1068 |
|
| 1069 |
def get_size(uid): |
| 1070 |
i = BrowserView.instances.get(uid) |
| 1071 |
if i: |
| 1072 |
# Size is in physical pixels, convert to logical pixels |
| 1073 |
size = i.Size |
| 1074 |
scale = i._scale |
| 1075 |
return int(size.Width / scale), int(size.Height / scale) |
| 1076 |
|
| 1077 |
|
| 1078 |
def get_screens(): |
| 1079 |
"""Get all screens with coordinates in logical pixels.""" |
| 1080 |
screens = [] |
| 1081 |
|
| 1082 |
for s in WinForms.Screen.AllScreens: |
| 1083 |
# Get logical size from Bounds (already DPI-aware scaled due to SetProcessDPIAware) |
| 1084 |
logical_width = s.Bounds.Width |
| 1085 |
logical_height = s.Bounds.Height |
| 1086 |
|
| 1087 |
# Get scale factor by comparing physical vs logical resolution |
| 1088 |
scale = win32.get_screen_scale(s.DeviceName, logical_width, logical_height) |
| 1089 |
|
| 1090 |
# Bounds are already in logical pixels due to SetProcessDPIAware |
| 1091 |
screens.append( |
| 1092 |
Screen( |
| 1093 |
s.Bounds.X, |
| 1094 |
s.Bounds.Y, |
| 1095 |
logical_width, |
| 1096 |
logical_height, |
| 1097 |
s.WorkingArea, |
| 1098 |
scale, |
| 1099 |
) |
| 1100 |
) |
| 1101 |
|
| 1102 |
return screens |
| 1103 |
|
| 1104 |
|
| 1105 |
def add_tls_cert(_): |
| 1106 |
return |