vektaview 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. vektaview-0.1.0/LICENSE +21 -0
  2. vektaview-0.1.0/PKG-INFO +48 -0
  3. vektaview-0.1.0/README.md +27 -0
  4. vektaview-0.1.0/pyproject.toml +35 -0
  5. vektaview-0.1.0/setup.cfg +4 -0
  6. vektaview-0.1.0/src/vektaview/__init__.py +19 -0
  7. vektaview-0.1.0/src/vektaview/_context.py +14 -0
  8. vektaview-0.1.0/src/vektaview/_frame.py +38 -0
  9. vektaview-0.1.0/src/vektaview/_icon.py +107 -0
  10. vektaview-0.1.0/src/vektaview/_native.py +205 -0
  11. vektaview-0.1.0/src/vektaview/_png.py +18 -0
  12. vektaview-0.1.0/src/vektaview/_text.py +168 -0
  13. vektaview-0.1.0/src/vektaview/_widget_paint.py +260 -0
  14. vektaview-0.1.0/src/vektaview/_win32.py +87 -0
  15. vektaview-0.1.0/src/vektaview/assets/logo.png +0 -0
  16. vektaview-0.1.0/src/vektaview/behavior.py +103 -0
  17. vektaview-0.1.0/src/vektaview/canvas.py +54 -0
  18. vektaview-0.1.0/src/vektaview/colors.py +36 -0
  19. vektaview-0.1.0/src/vektaview/errors.py +6 -0
  20. vektaview-0.1.0/src/vektaview/functions.py +96 -0
  21. vektaview-0.1.0/src/vektaview/objects.py +535 -0
  22. vektaview-0.1.0/src/vektaview/painter.py +964 -0
  23. vektaview-0.1.0/src/vektaview/sections.py +47 -0
  24. vektaview-0.1.0/src/vektaview/systems.py +213 -0
  25. vektaview-0.1.0/src/vektaview/trace.py +80 -0
  26. vektaview-0.1.0/src/vektaview/widgets.py +395 -0
  27. vektaview-0.1.0/src/vektaview/window.py +561 -0
  28. vektaview-0.1.0/src/vektaview.egg-info/PKG-INFO +48 -0
  29. vektaview-0.1.0/src/vektaview.egg-info/SOURCES.txt +30 -0
  30. vektaview-0.1.0/src/vektaview.egg-info/dependency_links.txt +1 -0
  31. vektaview-0.1.0/src/vektaview.egg-info/requires.txt +2 -0
  32. vektaview-0.1.0/src/vektaview.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Guillaume Latreille
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.4
2
+ Name: vektaview
3
+ Version: 0.1.0
4
+ Summary: A small Python library for drawing live, interactive vector graphics and plots in a native Windows window.
5
+ Author: Guillaume Latreille
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/boooperdooop/VektaView
8
+ Project-URL: Issues, https://github.com/boooperdooop/VektaView/issues
9
+ Keywords: visualization,simulation,plotting,windows
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Education
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering :: Visualization
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy
19
+ Requires-Dist: Pillow
20
+ Dynamic: license-file
21
+
22
+ # VektaView
23
+
24
+ A small Python library for live, interactive vector graphics and plots in a native Windows window.
25
+
26
+ ## Install
27
+
28
+ ```
29
+ pip install vektaview
30
+ ```
31
+
32
+ Requires Windows and Python 3.10 or newer.
33
+
34
+ ## Quick start
35
+
36
+ ```python
37
+ import vektaview as vv
38
+
39
+ window = vv.Window(title="Hello", width=900, height=600, theme="dark")
40
+ # ... create objects, widgets and behaviours here ...
41
+ vv.run()
42
+ ```
43
+
44
+ See the `examples/` folder for complete scenes.
45
+
46
+ ## License
47
+
48
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,27 @@
1
+ # VektaView
2
+
3
+ A small Python library for live, interactive vector graphics and plots in a native Windows window.
4
+
5
+ ## Install
6
+
7
+ ```
8
+ pip install vektaview
9
+ ```
10
+
11
+ Requires Windows and Python 3.10 or newer.
12
+
13
+ ## Quick start
14
+
15
+ ```python
16
+ import vektaview as vv
17
+
18
+ window = vv.Window(title="Hello", width=900, height=600, theme="dark")
19
+ # ... create objects, widgets and behaviours here ...
20
+ vv.run()
21
+ ```
22
+
23
+ See the `examples/` folder for complete scenes.
24
+
25
+ ## License
26
+
27
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "vektaview"
7
+ dynamic = ["version"]
8
+ description = "A small Python library for drawing live, interactive vector graphics and plots in a native Windows window."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Guillaume Latreille"}]
14
+ keywords = ["visualization", "simulation", "plotting", "windows"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Education",
18
+ "Operating System :: Microsoft :: Windows",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Scientific/Engineering :: Visualization",
21
+ ]
22
+ dependencies = ["numpy", "Pillow"]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/boooperdooop/VektaView"
26
+ Issues = "https://github.com/boooperdooop/VektaView/issues"
27
+
28
+ [tool.setuptools.dynamic]
29
+ version = { attr = "vektaview.__version__" }
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src"]
33
+
34
+ [tool.setuptools.package-data]
35
+ vektaview = ["assets/*.png", "py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,19 @@
1
+ """VektaView: interactive, animated visualizations of mathematics and physics in one desktop window."""
2
+ from .errors import Error
3
+ from .window import Window
4
+ from .systems import Axes, NumberPlane, Grid
5
+ from .objects import Dot, Circle, Ellipse, Rectangle, Polygon, Line, Arrow, Vector, Arc, Text, Label, Box
6
+ from .trace import Trace
7
+ from .sections import Section
8
+ from .functions import ParametricFunction, FunctionGraph
9
+ from .widgets import Slider, Input, Button, Checkbox, Dropdown, Readout, Playback
10
+ from .behavior import on_change, every_frame, run, play, pause, step, restart, save_image
11
+
12
+ __version__ = "0.1.0"
13
+ __all__ = [
14
+ "Error", "Window", "Axes", "NumberPlane", "Grid", "Section",
15
+ "Dot", "Circle", "Ellipse", "Rectangle", "Polygon", "Line", "Arrow", "Vector", "Arc", "Text", "Label", "Box",
16
+ "Trace", "ParametricFunction", "FunctionGraph",
17
+ "Slider", "Input", "Button", "Checkbox", "Dropdown", "Readout", "Playback",
18
+ "on_change", "every_frame", "run", "play", "pause", "step", "restart", "save_image",
19
+ ]
@@ -0,0 +1,14 @@
1
+ from .errors import fail
2
+
3
+ _current = None
4
+
5
+
6
+ def set_current(window):
7
+ global _current
8
+ _current = window
9
+
10
+
11
+ def current(who="Object"):
12
+ if _current is None:
13
+ fail(who, "no window exists", "create one first with vv.Window(...)")
14
+ return _current
@@ -0,0 +1,38 @@
1
+ """Dark-gray title bar for every VektaView window, set through the Desktop Window Manager (DWM).
2
+
3
+ The title-bar, title-text and border colours need Windows 11 (build 22000 or later); on older Windows those calls fail
4
+ quietly and the system colours stay. Dark mode (light caption buttons on a dark bar) also works on Windows 10.
5
+ """
6
+ import ctypes as ct
7
+
8
+ FRAME_COLOR = (32, 32, 32) # title bar and border: dark gray (#202020)
9
+ FRAME_TEXT_COLOR = (235, 235, 235) # title text
10
+
11
+ DWMWA_USE_IMMERSIVE_DARK_MODE_OLD = 19 # Windows 10 before 20H1
12
+ DWMWA_USE_IMMERSIVE_DARK_MODE = 20
13
+ DWMWA_BORDER_COLOR, DWMWA_CAPTION_COLOR, DWMWA_TEXT_COLOR = 34, 35, 36
14
+
15
+
16
+ def colorref(rgb):
17
+ """(r, g, b) -> Windows COLORREF, 0x00BBGGRR."""
18
+ r, g, b = (int(v) & 255 for v in rgb[:3])
19
+ return (b << 16) | (g << 8) | r
20
+
21
+
22
+ def _set(hwnd, attribute, value):
23
+ try:
24
+ fn = ct.WinDLL("dwmapi").DwmSetWindowAttribute
25
+ fn.argtypes = [ct.c_void_p, ct.c_uint32, ct.c_void_p, ct.c_uint32]
26
+ fn.restype = ct.c_long
27
+ v = ct.c_uint32(value)
28
+ return fn(hwnd, attribute, ct.byref(v), ct.sizeof(v)) == 0
29
+ except (AttributeError, OSError):
30
+ return False
31
+
32
+
33
+ def apply_default_frame(hwnd):
34
+ """Dark-gray title bar and border, light title text, dark caption buttons. Safe to call on any Windows version."""
35
+ _set(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE, 1) or _set(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE_OLD, 1)
36
+ _set(hwnd, DWMWA_CAPTION_COLOR, colorref(FRAME_COLOR))
37
+ _set(hwnd, DWMWA_TEXT_COLOR, colorref(FRAME_TEXT_COLOR))
38
+ _set(hwnd, DWMWA_BORDER_COLOR, colorref(FRAME_COLOR))
@@ -0,0 +1,107 @@
1
+ """Window icon (title bar, taskbar, Alt+Tab) from the packaged logo, or from any image file you pass."""
2
+ import ctypes as ct
3
+ from ctypes import wintypes as wt
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+ WM_SETICON, ICON_SMALL, ICON_BIG = 0x0080, 0, 1
9
+ SM_CXICON, SM_CXSMICON = 11, 49
10
+ LOGO = Path(__file__).parent / "assets" / "logo.png" # shipped inside the package (see pyproject package-data)
11
+
12
+
13
+ def load_image(path):
14
+ """Read any image Pillow understands and return a square RGBA array ready to be scaled into icons.
15
+
16
+ - An image without transparency (for example a JPG) gets its white outer background removed.
17
+ - Transparent or white margins are trimmed, then the logo is centred on a square with a small border.
18
+ """
19
+ from PIL import Image, ImageDraw
20
+ im = Image.open(path).convert("RGBA")
21
+ if im.getchannel("A").getextrema()[0] == 255: # opaque: knock out the background from the corners
22
+ w, h = im.size
23
+ for corner in ((0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)):
24
+ if sum(im.getpixel(corner)[:3]) > 700: # near white
25
+ ImageDraw.floodfill(im, corner, (255, 255, 255, 0), thresh=60)
26
+ box = im.getchannel("A").point(lambda a: 255 if a > 8 else 0).getbbox()
27
+ if box:
28
+ im = im.crop(box)
29
+ side = int(round(max(im.size) * 1.08))
30
+ square = Image.new("RGBA", (side, side), (0, 0, 0, 0))
31
+ square.paste(im, ((side - im.width) // 2, (side - im.height) // 2))
32
+ return np.asarray(square, np.uint8)
33
+
34
+
35
+ def resized(rgba, size):
36
+ from PIL import Image
37
+ return np.asarray(Image.fromarray(rgba, "RGBA").resize((size, size), Image.LANCZOS), np.uint8)
38
+
39
+
40
+ class _BITMAPINFOHEADER(ct.Structure):
41
+ _fields_ = [("biSize", wt.DWORD), ("biWidth", wt.LONG), ("biHeight", wt.LONG), ("biPlanes", wt.WORD),
42
+ ("biBitCount", wt.WORD), ("biCompression", wt.DWORD), ("biSizeImage", wt.DWORD),
43
+ ("biXPelsPerMeter", wt.LONG), ("biYPelsPerMeter", wt.LONG), ("biClrUsed", wt.DWORD),
44
+ ("biClrImportant", wt.DWORD)]
45
+
46
+
47
+ class _ICONINFO(ct.Structure):
48
+ _fields_ = [("fIcon", wt.BOOL), ("xHotspot", wt.DWORD), ("yHotspot", wt.DWORD),
49
+ ("hbmMask", wt.HBITMAP), ("hbmColor", wt.HBITMAP)]
50
+
51
+
52
+ def _apis():
53
+ user32, gdi32 = ct.WinDLL("user32", use_last_error=True), ct.WinDLL("gdi32", use_last_error=True)
54
+ user32.GetDC.argtypes, user32.GetDC.restype = [wt.HWND], wt.HDC
55
+ user32.ReleaseDC.argtypes = [wt.HWND, wt.HDC]
56
+ user32.CreateIconIndirect.argtypes, user32.CreateIconIndirect.restype = [ct.POINTER(_ICONINFO)], wt.HICON
57
+ user32.SendMessageW.argtypes, user32.SendMessageW.restype = [wt.HWND, wt.UINT, wt.WPARAM, ct.c_ssize_t], ct.c_ssize_t
58
+ user32.GetSystemMetrics.argtypes = [ct.c_int]
59
+ gdi32.CreateDIBSection.argtypes = [wt.HDC, ct.c_void_p, wt.UINT, ct.POINTER(ct.c_void_p), wt.HANDLE, wt.DWORD]
60
+ gdi32.CreateDIBSection.restype = wt.HBITMAP
61
+ gdi32.CreateBitmap.argtypes = [ct.c_int, ct.c_int, wt.UINT, wt.UINT, ct.c_void_p]
62
+ gdi32.CreateBitmap.restype = wt.HBITMAP
63
+ gdi32.DeleteObject.argtypes = [wt.HGDIOBJ]
64
+ return user32, gdi32
65
+
66
+
67
+ def _hicon(user32, gdi32, rgba):
68
+ h, w = rgba.shape[:2]
69
+ bmi = _BITMAPINFOHEADER(ct.sizeof(_BITMAPINFOHEADER), w, -h, 1, 32, 0, 0, 0, 0, 0, 0) # top-down 32-bit BGRA
70
+ bits = ct.c_void_p()
71
+ dc = user32.GetDC(None)
72
+ color = gdi32.CreateDIBSection(dc, ct.byref(bmi), 0, ct.byref(bits), None, 0)
73
+ user32.ReleaseDC(None, dc)
74
+ bgra = np.ascontiguousarray(rgba[..., [2, 1, 0, 3]])
75
+ ct.memmove(bits, bgra.ctypes.data, bgra.nbytes)
76
+ mask = gdi32.CreateBitmap(w, h, 1, 1, ct.create_string_buffer(((w + 15) // 16 * 2) * h)) # ignored: the colour bitmap has alpha
77
+ handle = user32.CreateIconIndirect(ct.byref(_ICONINFO(True, 0, 0, mask, color)))
78
+ gdi32.DeleteObject(color)
79
+ gdi32.DeleteObject(mask)
80
+ return handle
81
+
82
+
83
+ def set_window_icon(hwnd, source=None):
84
+ """Give the window an icon: `source` is an image path, or None for the packaged logo. Returns True on success."""
85
+ try:
86
+ path = Path(source) if source else LOGO
87
+ if not path.is_file():
88
+ return False
89
+ base = load_image(path)
90
+ user32, gdi32 = _apis()
91
+ small, big = user32.GetSystemMetrics(SM_CXSMICON), user32.GetSystemMetrics(SM_CXICON) # DPI-aware sizes
92
+ for kind, size in ((ICON_SMALL, small), (ICON_BIG, big)): # small first, then big
93
+ handle = _hicon(user32, gdi32, resized(base, size))
94
+ if not handle:
95
+ return False
96
+ user32.SendMessageW(hwnd, WM_SETICON, kind, handle)
97
+ return True
98
+ except (AttributeError, OSError):
99
+ return False
100
+
101
+
102
+ def set_taskbar_identity(app_id="VektaView.App"):
103
+ """Without its own identity, a window run by python.exe is grouped under Python's taskbar icon."""
104
+ try:
105
+ ct.windll.shell32.SetCurrentProcessExplicitAppUserModelID(app_id)
106
+ except (AttributeError, OSError):
107
+ pass
@@ -0,0 +1,205 @@
1
+ import ctypes as ct
2
+ from ctypes import wintypes as wt
3
+ from . import _win32 as w
4
+
5
+ _windows = {}
6
+ _class_registered = False
7
+ CLASS_NAME = "VektaViewWindow"
8
+
9
+ WM_ENTERSIZEMOVE, WM_EXITSIZEMOVE, WM_TIMER, WM_MOUSEWHEEL = 0x0231, 0x0232, 0x0113, 0x020A
10
+ SETTLE_TIMER = 1
11
+ SETTLE_MS = 150 # re-render at full quality when the mouse pauses this long; None = only on release
12
+
13
+ w.user32.SetTimer.argtypes = [wt.HWND, ct.c_size_t, wt.UINT, ct.c_void_p]
14
+ w.user32.SetTimer.restype = ct.c_size_t
15
+ w.user32.KillTimer.argtypes = [wt.HWND, ct.c_size_t]
16
+
17
+ _user32 = ct.WinDLL("user32", use_last_error=True)
18
+ _user32.ScreenToClient.argtypes = [wt.HWND, ct.POINTER(wt.POINT)]
19
+ _gdi32 = ct.WinDLL("gdi32", use_last_error=True)
20
+ _gdi32.SetStretchBltMode.argtypes = [wt.HDC, ct.c_int]
21
+ _gdi32.StretchDIBits.argtypes = [wt.HDC, ct.c_int, ct.c_int, ct.c_int, ct.c_int, ct.c_int, ct.c_int,
22
+ ct.c_int, ct.c_int, ct.c_void_p, ct.c_void_p, wt.UINT, wt.DWORD]
23
+
24
+
25
+ class _BMIH(ct.Structure):
26
+ _fields_ = [("biSize", wt.DWORD), ("biWidth", wt.LONG), ("biHeight", wt.LONG), ("biPlanes", wt.WORD),
27
+ ("biBitCount", wt.WORD), ("biCompression", wt.DWORD), ("biSizeImage", wt.DWORD),
28
+ ("biXPelsPerMeter", wt.LONG), ("biYPelsPerMeter", wt.LONG),
29
+ ("biClrUsed", wt.DWORD), ("biClrImportant", wt.DWORD)]
30
+
31
+
32
+ def _wndproc(hwnd, msg, wparam, lparam):
33
+ win = _windows.get(hwnd)
34
+ if win is not None:
35
+ if msg == w.WM_ERASEBKGND:
36
+ return 1
37
+ if msg == w.WM_SIZE:
38
+ win._width, win._height = lparam & 0xFFFF, (lparam >> 16) & 0xFFFF
39
+ if win._live:
40
+ if SETTLE_MS:
41
+ w.user32.SetTimer(hwnd, SETTLE_TIMER, SETTLE_MS, None) # restarts the countdown
42
+ w.user32.InvalidateRect(hwnd, None, False)
43
+ else:
44
+ win._apply_size()
45
+ return 0
46
+ if msg == WM_ENTERSIZEMOVE:
47
+ win._live = True
48
+ return 0
49
+ if msg == WM_EXITSIZEMOVE:
50
+ win._live = False
51
+ w.user32.KillTimer(hwnd, SETTLE_TIMER)
52
+ win._apply_size()
53
+ return 0
54
+ if msg == WM_TIMER and wparam == SETTLE_TIMER:
55
+ w.user32.KillTimer(hwnd, SETTLE_TIMER)
56
+ win._apply_size() # full render while the mouse is paused, still dragging
57
+ return 0
58
+ if msg == w.WM_PAINT:
59
+ draft = win._live and win.on_draft and (win._width, win._height) != win._applied
60
+ ps = w.PAINTSTRUCT()
61
+ hdc = w.user32.BeginPaint(hwnd, ct.byref(ps))
62
+ callback = win.on_draft if draft else win.on_paint
63
+ if callback:
64
+ callback(hdc)
65
+ w.user32.EndPaint(hwnd, ct.byref(ps))
66
+ return 0
67
+ if msg == w.WM_CLOSE:
68
+ if win.on_close is None or win.on_close() is not False:
69
+ w.user32.DestroyWindow(hwnd)
70
+ return 0
71
+ if msg == w.WM_DESTROY:
72
+ _windows.pop(hwnd, None)
73
+ win._hwnd = None
74
+ w.user32.PostQuitMessage(0)
75
+ return 0
76
+ if msg in (w.WM_MOUSEMOVE, w.WM_LBUTTONDOWN, w.WM_LBUTTONUP):
77
+ x = ct.c_short(lparam & 0xFFFF).value
78
+ y = ct.c_short((lparam >> 16) & 0xFFFF).value
79
+ kind = {w.WM_MOUSEMOVE: "move", w.WM_LBUTTONDOWN: "down", w.WM_LBUTTONUP: "up"}[msg]
80
+ if msg == w.WM_LBUTTONDOWN:
81
+ w.user32.SetCapture(hwnd) # keep receiving events while dragging outside the window
82
+ elif msg == w.WM_LBUTTONUP:
83
+ w.user32.ReleaseCapture()
84
+ if win.on_mouse:
85
+ win.on_mouse(kind, x, y)
86
+ return 0
87
+ if msg == WM_MOUSEWHEEL:
88
+ if win.on_wheel:
89
+ pt = wt.POINT(ct.c_short(lparam & 0xFFFF).value, ct.c_short((lparam >> 16) & 0xFFFF).value) # screen coordinates
90
+ _user32.ScreenToClient(hwnd, ct.byref(pt))
91
+ notches = ct.c_short((wparam >> 16) & 0xFFFF).value / 120.0 # +1 per notch away from the user
92
+ win.on_wheel(pt.x, pt.y, notches)
93
+ return 0
94
+ if msg == w.WM_CHAR:
95
+ if win.on_char:
96
+ win.on_char(wparam)
97
+ return 0
98
+ return w.user32.DefWindowProcW(hwnd, msg, wparam, lparam)
99
+
100
+
101
+ _WNDPROC_REF = w.WNDPROC(_wndproc) # module-level: must outlive every window
102
+
103
+
104
+ def _register_class():
105
+ global _class_registered
106
+ if _class_registered:
107
+ return
108
+ wc = w.WNDCLASSEXW()
109
+ wc.cbSize = ct.sizeof(w.WNDCLASSEXW)
110
+ wc.style = w.CS_HREDRAW | w.CS_VREDRAW | w.CS_OWNDC
111
+ wc.lpfnWndProc = _WNDPROC_REF
112
+ wc.hInstance = w.kernel32.GetModuleHandleW(None)
113
+ wc.hCursor = w.user32.LoadCursorW(None, w.IDC_ARROW)
114
+ wc.hbrBackground = ct.cast(w.COLOR_WINDOW + 1, wt.HBRUSH)
115
+ wc.lpszClassName = CLASS_NAME
116
+ if not w.user32.RegisterClassExW(ct.byref(wc)):
117
+ raise ct.WinError(ct.get_last_error())
118
+ _class_registered = True
119
+
120
+
121
+ class NativeWindow:
122
+ """Thin wrapper over one Win32 window. Knows nothing about objects or widgets."""
123
+
124
+ def __init__(self, title="VektaView", width=800, height=600):
125
+ """width and height are the size of the drawable (client) area in DIP."""
126
+ self.on_close = self.on_resize = self.on_paint = None
127
+ self.on_mouse = self.on_char = self.on_wheel = None
128
+
129
+ w.user32.SetProcessDPIAware() # must run before any window exists
130
+ try:
131
+ self.scale = max(1.0, w.user32.GetDpiForSystem() / 96.0) # device pixels per DIP
132
+ except (AttributeError, OSError): # Windows older than 10 (1607)
133
+ self.scale = 1.0
134
+ self._width, self._height = round(width * self.scale), round(height * self.scale)
135
+
136
+ rect = wt.RECT(0, 0, self._width, self._height) # client size in device pixels
137
+ w.user32.AdjustWindowRectEx(ct.byref(rect), w.WS_OVERLAPPEDWINDOW, False, 0)
138
+ outer_w, outer_h = rect.right - rect.left, rect.bottom - rect.top
139
+
140
+ self.on_draft = None
141
+ self._live = False
142
+ self._applied = (self._width, self._height)
143
+
144
+ _register_class()
145
+ self._hwnd = w.user32.CreateWindowExW(
146
+ 0, CLASS_NAME, title, w.WS_OVERLAPPEDWINDOW, w.CW_USEDEFAULT, w.CW_USEDEFAULT,
147
+ outer_w, outer_h, None, None, w.kernel32.GetModuleHandleW(None), None)
148
+ if not self._hwnd:
149
+ raise ct.WinError(ct.get_last_error())
150
+ _windows[self._hwnd] = self
151
+
152
+ @property
153
+ def is_open(self):
154
+ return self._hwnd is not None
155
+
156
+ @property
157
+ def is_minimized(self):
158
+ return bool(self.is_open and w.user32.IsIconic(self._hwnd))
159
+
160
+ def show(self):
161
+ w.user32.ShowWindow(self._hwnd, w.SW_SHOWNORMAL)
162
+ w.user32.UpdateWindow(self._hwnd)
163
+
164
+ def minimize(self): w.user32.ShowWindow(self._hwnd, w.SW_MINIMIZE)
165
+ def maximize(self): w.user32.ShowWindow(self._hwnd, w.SW_MAXIMIZE)
166
+ def restore(self): w.user32.ShowWindow(self._hwnd, w.SW_RESTORE)
167
+
168
+ def close(self):
169
+ if self.is_open:
170
+ w.user32.DestroyWindow(self._hwnd)
171
+
172
+ def set_title(self, text):
173
+ w.user32.SetWindowTextW(self._hwnd, text)
174
+
175
+ def invalidate(self):
176
+ if self.is_open:
177
+ w.user32.InvalidateRect(self._hwnd, None, False)
178
+
179
+ def present(self, hdc, canvas):
180
+ w.blit_bgra(hdc, canvas.buffer)
181
+
182
+ def pump(self):
183
+ msg = wt.MSG()
184
+ while w.user32.PeekMessageW(ct.byref(msg), None, 0, 0, w.PM_REMOVE):
185
+ if msg.message == w.WM_QUIT:
186
+ return False
187
+ w.user32.TranslateMessage(ct.byref(msg))
188
+ w.user32.DispatchMessageW(ct.byref(msg))
189
+ return True
190
+
191
+ def _apply_size(self):
192
+ """Tell the application the final client size, then repaint at full quality."""
193
+ self._applied = (self._width, self._height)
194
+ if self.on_resize:
195
+ self.on_resize(*self._applied)
196
+ self.invalidate()
197
+
198
+ def present_stretched(self, hdc, canvas):
199
+ """Cheap draft: stretch the last rendered frame to the current client size."""
200
+ buf = canvas.buffer
201
+ h, wd = buf.shape[:2]
202
+ bmi = _BMIH(ct.sizeof(_BMIH), wd, -h, 1, 32, 0, 0, 0, 0, 0, 0) # negative height = top-down
203
+ _gdi32.SetStretchBltMode(hdc, 3) # COLORONCOLOR: fastest
204
+ _gdi32.StretchDIBits(hdc, 0, 0, self._width, self._height, 0, 0, wd, h,
205
+ buf.ctypes.data_as(ct.c_void_p), ct.byref(bmi), 0, 0x00CC0020)
@@ -0,0 +1,18 @@
1
+ import struct
2
+ import zlib
3
+
4
+
5
+ def write_png(path, rgba):
6
+ h, w = rgba.shape[:2]
7
+ raw = b"".join(b"\x00" + rgba[y].tobytes() for y in range(h))
8
+
9
+ def chunk(tag, data):
10
+ body = tag + data
11
+ return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF)
12
+
13
+ png = (b"\x89PNG\r\n\x1a\n"
14
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
15
+ + chunk(b"IDAT", zlib.compress(raw, 6))
16
+ + chunk(b"IEND", b""))
17
+ with open(path, "wb") as f:
18
+ f.write(png)