1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
use crate::platform::window::WindowId;
use crate::platform::event::{Event, MouseButton};
use super::OsBackend;
use std::collections::HashMap;
use std::time::Instant;
// Static counter for all windows to use
static mut COUNTER: i32 = 0;
#[cfg(windows)]
use windows::{
core::PCWSTR,
Win32::Foundation::*,
Win32::UI::WindowsAndMessaging::*,
Win32::Graphics::Gdi::*,
Win32::System::LibraryLoader::GetModuleHandleW,
};
pub struct WindowsBackend {
next_window_id: usize,
windows: HashMap<WindowId, Win32Window>,
start_time: Instant,
running: bool,
}
struct Win32Window {
window_id: WindowId,
#[cfg(windows)]
hwnd: HWND,
width: u32,
height: u32,
dpi_factor: f32,
title: String,
}
impl WindowsBackend {
pub fn new() -> Self {
Self {
next_window_id: 1,
windows: HashMap::new(),
start_time: Instant::now(),
running: false,
}
}
#[cfg(windows)]
fn register_window_class(&self) -> u16 {
unsafe {
let h_instance = GetModuleHandleW(None).unwrap();
// Use a static class name to avoid issues with string lifetime
let class_name = "mixWindowClass";
let class_name_w: Vec<u16> = class_name.encode_utf16().chain(std::iter::once(0)).collect();
// We'll just try to register the class and handle any errors
let wc = WNDCLASSEXW {
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
style: CS_HREDRAW | CS_VREDRAW | CS_OWNDC,
lpfnWndProc: Some(Self::wnd_proc),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: h_instance.into(),
hIcon: HICON(0),
hCursor: LoadCursorW(None, IDC_ARROW).unwrap(),
hbrBackground: HBRUSH(COLOR_WINDOW.0 as isize),
lpszMenuName: PCWSTR::null(),
lpszClassName: PCWSTR(class_name_w.as_ptr()),
hIconSm: HICON(0),
};
// Try to register the class
let class_atom = RegisterClassExW(&wc);
if class_atom == 0 {
let error = GetLastError();
// If the class is already registered, that's fine
if error.0 == 1410 { // ERROR_CLASS_ALREADY_EXISTS
return 1; // Return a non-zero value to indicate success
}
panic!("Failed to register window class: error code {}", error.0);
}
class_atom
}
}
#[cfg(windows)]
unsafe extern "system" fn wnd_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
match msg {
WM_DESTROY => {
PostQuitMessage(0);
LRESULT(0)
},
WM_PAINT => {
let mut ps = PAINTSTRUCT::default();
let hdc = BeginPaint(hwnd, &mut ps);
// Fill the window with a light blue background
let brush = CreateSolidBrush(COLORREF(0x00FFFFCC)); // Light yellow (BGR format)
let _ = FillRect(hdc, &ps.rcPaint, brush);
let _ = DeleteObject(brush);
// Draw a button
let pen = CreatePen(PS_SOLID, 2, COLORREF(0x00004CAF)); // Green (BGR format)
let old_pen = SelectObject(hdc, pen);
let button_brush = CreateSolidBrush(COLORREF(0x00004CAF)); // Green (BGR format)
let old_brush = SelectObject(hdc, button_brush);
let _ = Rectangle(hdc, 300, 300, 500, 380);
// Draw button text
SetBkMode(hdc, TRANSPARENT);
SetTextColor(hdc, COLORREF(0x00FFFFFF)); // White (BGR format)
let text = "Increment";
let text_w: Vec<u16> = text.encode_utf16().collect();
let _ = TextOutW(hdc, 350, 330, &text_w);
// Draw a label
SetTextColor(hdc, COLORREF(0x00F32196)); // Blue (BGR format)
let text = "Hello, mix!";
let text_w: Vec<u16> = text.encode_utf16().collect();
let _ = TextOutW(hdc, 300, 100, &text_w);
// Draw a counter label
SetTextColor(hdc, COLORREF(0x00000000)); // Black (BGR format)
// Use the static counter
let text = format!("Counter: {}", COUNTER);
let text_w: Vec<u16> = text.encode_utf16().collect();
let _ = TextOutW(hdc, 300, 200, &text_w);
SelectObject(hdc, old_brush);
SelectObject(hdc, old_pen);
let _ = DeleteObject(pen);
let _ = DeleteObject(button_brush);
let _ = EndPaint(hwnd, &ps);
LRESULT(0)
},
_ => DefWindowProcW(hwnd, msg, wparam, lparam),
}
}
}
impl OsBackend for WindowsBackend {
fn init(&mut self) {
#[cfg(windows)]
{
self.register_window_class();
}
}
fn create_window(&mut self, title: &str, width: u32, height: u32) -> WindowId {
let window_id = WindowId(self.next_window_id);
self.next_window_id += 1;
#[cfg(windows)]
{
unsafe {
let h_instance = GetModuleHandleW(None).unwrap();
let class_name = "mixWindowClass";
let class_name_w: Vec<u16> = class_name.encode_utf16().chain(std::iter::once(0)).collect();
let title_w: Vec<u16> = title.encode_utf16().chain(std::iter::once(0)).collect();
let style = WS_OVERLAPPEDWINDOW;
// Calculate the window size based on the client area size
let mut rect = RECT {
left: 0,
top: 0,
right: width as i32,
bottom: height as i32,
};
let _ = AdjustWindowRect(&mut rect, style, FALSE);
// Make sure we have a valid window class
let _ = self.register_window_class();
let hwnd = CreateWindowExW(
WINDOW_EX_STYLE(0),
PCWSTR(class_name_w.as_ptr()),
PCWSTR(title_w.as_ptr()),
style,
CW_USEDEFAULT,
CW_USEDEFAULT,
rect.right - rect.left,
rect.bottom - rect.top,
None,
None,
h_instance,
None,
);
if hwnd.0 == 0 {
let error = GetLastError();
panic!("Failed to create window: error code {}", error.0);
}
// No need to store a pointer to self anymore
let win32_window = Win32Window {
window_id,
hwnd,
width,
height,
dpi_factor: 1.0,
title: title.to_string(),
};
self.windows.insert(window_id, win32_window);
// Show the window
let _ = ShowWindow(hwnd, SW_SHOW);
let _ = UpdateWindow(hwnd);
}
}
#[cfg(not(windows))]
{
let win32_window = Win32Window {
window_id,
width,
height,
dpi_factor: 1.0,
title: title.to_string(),
};
self.windows.insert(window_id, win32_window);
}
window_id
}
fn process_events(&mut self) -> Vec<Event> {
let mut events = Vec::new();
#[cfg(windows)]
{
unsafe {
let mut msg = MSG::default();
while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
match msg.message {
WM_QUIT => {
self.running = false;
events.push(Event::Shutdown);
},
WM_SIZE => {
// Find the window that was resized
for (window_id, window) in &mut self.windows {
if window.hwnd == msg.hwnd {
let width = (msg.lParam.0 & 0xFFFF) as u32;
let height = ((msg.lParam.0 >> 16) & 0xFFFF) as u32;
window.width = width;
window.height = height;
events.push(Event::WindowResize {
window_id: *window_id,
width: width as f32,
height: height as f32,
dpi_factor: window.dpi_factor,
});
break;
}
}
},
WM_CLOSE => {
// Find the window that was closed
for (window_id, window) in &self.windows {
if window.hwnd == msg.hwnd {
events.push(Event::WindowClose {
window_id: *window_id,
});
break;
}
}
},
WM_LBUTTONDOWN => {
let x = (msg.lParam.0 & 0xFFFF) as f32;
let y = ((msg.lParam.0 >> 16) & 0xFFFF) as f32;
// Check if the click is on the button
if x >= 300.0 && x <= 500.0 && y >= 300.0 && y <= 380.0 {
// Increment the static counter
unsafe {
COUNTER += 1;
}
// Invalidate the window to trigger a redraw
let _ = InvalidateRect(msg.hwnd, None, FALSE);
}
// Find the window
for (window_id, _) in &self.windows {
if msg.hwnd == msg.hwnd {
events.push(Event::MouseDown {
window_id: *window_id,
x,
y,
button: MouseButton::Left,
});
break;
}
}
},
WM_LBUTTONUP => {
let x = (msg.lParam.0 & 0xFFFF) as f32;
let y = ((msg.lParam.0 >> 16) & 0xFFFF) as f32;
// Find the window
for (window_id, _) in &self.windows {
if msg.hwnd == msg.hwnd {
events.push(Event::MouseUp {
window_id: *window_id,
x,
y,
button: MouseButton::Left,
});
break;
}
}
},
WM_MOUSEMOVE => {
let x = (msg.lParam.0 & 0xFFFF) as f32;
let y = ((msg.lParam.0 >> 16) & 0xFFFF) as f32;
// Find the window
for (window_id, _) in &self.windows {
if msg.hwnd == msg.hwnd {
events.push(Event::MouseMove {
window_id: *window_id,
x,
y,
});
break;
}
}
},
_ => {}
}
}
}
}
events
}
fn render(&mut self) {
#[cfg(windows)]
{
for (_, window) in &self.windows {
unsafe {
// Invalidate the window to trigger a WM_PAINT message
let _ = InvalidateRect(window.hwnd, None, FALSE);
let _ = UpdateWindow(window.hwnd);
}
}
}
}
fn shutdown(&mut self) {
#[cfg(windows)]
{
for (_, window) in &self.windows {
unsafe {
let _ = DestroyWindow(window.hwnd);
}
}
}
}
}