-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbwm.rs
More file actions
1225 lines (1088 loc) · 50.8 KB
/
bwm.rs
File metadata and controls
1225 lines (1088 loc) · 50.8 KB
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Breenix Window Manager (bwm) — Pure Compositor + Input Router
//!
//! Discovers Breengel client windows registered via the kernel window buffer API,
//! composites them onto the screen with GPU acceleration (VirGL), and routes
//! keyboard/mouse input to the focused window via kernel ring buffers.
//!
//! BWM does NOT spawn child processes or emulate terminals. Those responsibilities
//! belong to init (process spawning) and bterm (terminal emulation).
use std::process;
use libbreenix::graphics::{self, WindowInputEvent, input_event_type};
use libbreenix::io;
use libbreenix::signal;
use libbreenix::types::Fd;
use libgfx::bitmap_font;
use libgfx::color::Color;
use libgfx::framebuf::FrameBuf;
// ─── Constants ───────────────────────────────────────────────────────────────
/// Title bar height in pixels
const TITLE_BAR_HEIGHT: usize = 32;
/// Window border/shadow width
const BORDER_WIDTH: usize = 2;
/// Noto Sans Mono 16px cell dimensions for title bar text.
const CELL_W: usize = 7;
const CELL_H: usize = 18;
/// Top taskbar height
const TASKBAR_HEIGHT: usize = 28;
/// Bottom app bar height
const APPBAR_HEIGHT: usize = 36;
/// Chrome button size (close/minimize)
const CHROME_BTN_SIZE: usize = 20;
/// Padding between chrome buttons
const CHROME_BTN_PAD: usize = 4;
/// Space reserved in title bar for chrome buttons
const CHROME_RESERVED: usize = 52;
// Colors
const TITLE_FOCUSED_BG: Color = Color::rgb(40, 100, 220);
const TITLE_UNFOCUSED_BG: Color = Color::rgb(45, 50, 65);
const TITLE_TEXT: Color = Color::rgb(160, 165, 175);
const TITLE_FOCUSED_TEXT: Color = Color::rgb(255, 255, 255);
const WIN_BORDER_COLOR: Color = Color::rgb(50, 55, 70);
const WIN_BORDER_FOCUSED: Color = Color::rgb(60, 130, 255);
const CONTENT_BG: Color = Color::rgb(20, 25, 40);
// Taskbar/Appbar colors
const TASKBAR_BG: Color = Color::rgb(20, 22, 30);
const TASKBAR_TEXT: Color = Color::rgb(180, 185, 195);
const APPBAR_BG: Color = Color::rgb(25, 28, 38);
const APPBAR_BORDER: Color = Color::rgb(50, 55, 70);
const APPBAR_BTN_BG: Color = Color::rgb(40, 45, 60);
const APPBAR_BTN_FOCUSED: Color = Color::rgb(40, 100, 220);
const APPBAR_BTN_MINIMIZED: Color = Color::rgb(30, 33, 45);
const APPBAR_BTN_TEXT: Color = Color::rgb(160, 165, 175);
// Chrome button colors
const CLOSE_BTN_BG: Color = Color::rgb(200, 50, 50);
const CLOSE_BTN_TEXT: Color = Color::rgb(255, 255, 255);
const MINIMIZE_BTN_BG: Color = Color::rgb(80, 85, 100);
const MINIMIZE_BTN_TEXT: Color = Color::rgb(255, 255, 255);
// ─── Input Parser ────────────────────────────────────────────────────────────
// Parses stdin bytes (keyboard input) into InputEvents that BWM can either
// handle internally (F-key focus switching) or route to the focused client
// window as WindowInputEvents.
struct InputParser {
state: InputState,
esc_buf: [u8; 8],
esc_len: usize,
}
#[derive(Clone, Copy, PartialEq)]
enum InputState { Normal, Escape, CsiOrSS3 }
enum InputEvent {
/// A regular key press: ascii byte + modifiers (bit 1 = ctrl)
Key { ascii: u8, keycode: u16, modifiers: u16 },
/// F1..F5 for BWM-internal focus switching
FunctionKey(u8),
}
impl InputParser {
fn new() -> Self { Self { state: InputState::Normal, esc_buf: [0; 8], esc_len: 0 } }
fn feed(&mut self, byte: u8) -> Option<InputEvent> {
match self.state {
InputState::Normal => {
if byte == 0x1b { self.state = InputState::Escape; self.esc_len = 0; None }
else { Some(Self::byte_to_key_event(byte)) }
}
InputState::Escape => {
if byte == b'[' || byte == b'O' {
self.state = InputState::CsiOrSS3; self.esc_buf[0] = byte; self.esc_len = 1; None
} else { self.state = InputState::Normal; Some(Self::byte_to_key_event(byte)) }
}
InputState::CsiOrSS3 => {
if self.esc_len < 7 { self.esc_buf[self.esc_len] = byte; self.esc_len += 1; }
if byte >= 0x40 && byte <= 0x7e { self.state = InputState::Normal; self.decode_escape() }
else { None }
}
}
}
/// Convert a raw stdin byte into a Key event with appropriate keycode/modifiers.
fn byte_to_key_event(byte: u8) -> InputEvent {
match byte {
// Enter (before Ctrl range since 0x0D falls in 0x01..=0x1A)
0x0D => InputEvent::Key { ascii: 13, keycode: 0x28, modifiers: 0 },
// Backspace (0x08 falls in Ctrl range; 0x7F does not)
0x08 | 0x7F => InputEvent::Key { ascii: 8, keycode: 0x2A, modifiers: 0 },
// Tab (0x09 falls in Ctrl range)
0x09 => InputEvent::Key { ascii: 9, keycode: 0x2B, modifiers: 0 },
// Ctrl+A through Ctrl+Z (0x01..0x1A), excluding Enter/Backspace/Tab matched above
0x01..=0x1A => InputEvent::Key {
ascii: byte,
keycode: byte as u16, // raw control code
modifiers: 0x02, // ctrl bit
},
// Printable ASCII + space
_ => InputEvent::Key { ascii: byte, keycode: byte as u16, modifiers: 0 },
}
}
fn decode_escape(&self) -> Option<InputEvent> {
if self.esc_len < 2 { return None; }
let final_byte = self.esc_buf[self.esc_len - 1];
if self.esc_buf[0] == b'[' {
match final_byte {
// Arrow keys -> Key events with USB HID keycodes
b'A' => return Some(InputEvent::Key { ascii: 0, keycode: 0x52, modifiers: 0 }), // Up
b'B' => return Some(InputEvent::Key { ascii: 0, keycode: 0x51, modifiers: 0 }), // Down
b'C' => return Some(InputEvent::Key { ascii: 0, keycode: 0x4F, modifiers: 0 }), // Right
b'D' => return Some(InputEvent::Key { ascii: 0, keycode: 0x50, modifiers: 0 }), // Left
b'~' if self.esc_len >= 3 => {
let _num = self.esc_buf[1] - b'0';
if self.esc_len == 3 { if _num == 1 { return Some(InputEvent::FunctionKey(1)); } }
else if self.esc_len == 4 {
let num2 = (self.esc_buf[1] - b'0') * 10 + (self.esc_buf[2] - b'0');
match num2 {
11 => return Some(InputEvent::FunctionKey(1)),
12 => return Some(InputEvent::FunctionKey(2)),
13 => return Some(InputEvent::FunctionKey(3)),
14 => return Some(InputEvent::FunctionKey(4)),
15 => return Some(InputEvent::FunctionKey(5)),
_ => {}
}
}
}
_ => {}
}
} else if self.esc_buf[0] == b'O' {
match final_byte {
b'P' => return Some(InputEvent::FunctionKey(1)),
b'Q' => return Some(InputEvent::FunctionKey(2)),
b'R' => return Some(InputEvent::FunctionKey(3)),
b'S' => return Some(InputEvent::FunctionKey(4)),
_ => {}
}
}
None
}
}
// ─── Window ─────────────────────────────────────────────────────────────────
struct Window {
x: i32,
y: i32,
width: usize,
height: usize,
title: [u8; 32],
title_len: usize,
window_id: u32,
owner_pid: u32,
minimized: bool,
/// Stable ordering for appbar (assigned at discovery time, never changes)
creation_order: u32,
/// Direct-mapped pointer to client window's pixel buffer (read-only, MAP_SHARED)
mapped_ptr: *const u32,
/// Client window buffer width (from map_window_buffer)
mapped_w: u32,
/// Client window buffer height (from map_window_buffer)
mapped_h: u32,
}
impl Window {
fn content_x(&self) -> i32 { self.x + BORDER_WIDTH as i32 }
fn content_y(&self) -> i32 { self.y + TITLE_BAR_HEIGHT as i32 + BORDER_WIDTH as i32 }
fn content_width(&self) -> usize { self.width.saturating_sub(BORDER_WIDTH * 2) }
fn content_height(&self) -> usize { self.height.saturating_sub(TITLE_BAR_HEIGHT + BORDER_WIDTH * 2) }
fn total_height(&self) -> usize { self.height }
fn hit_title(&self, mx: i32, my: i32) -> bool {
mx >= self.x && mx < self.x + self.width as i32
&& my >= self.y && my < self.y + TITLE_BAR_HEIGHT as i32
}
fn hit_any(&self, mx: i32, my: i32) -> bool {
mx >= self.x && mx < self.x + self.width as i32
&& my >= self.y && my < self.y + self.total_height() as i32
}
fn hit_content(&self, mx: i32, my: i32) -> bool {
mx >= self.content_x() && mx < self.content_x() + self.content_width() as i32
&& my >= self.content_y() && my < self.content_y() + self.content_height() as i32
}
fn bounds(&self) -> (i32, i32, i32, i32) {
(self.x, self.y, self.x + self.width as i32, self.y + self.total_height() as i32)
}
fn close_btn_rect(&self) -> (i32, i32, usize, usize) {
let bx = self.x + self.width as i32 - BORDER_WIDTH as i32
- CHROME_BTN_PAD as i32 - CHROME_BTN_SIZE as i32;
let by = self.y + BORDER_WIDTH as i32
+ ((TITLE_BAR_HEIGHT - BORDER_WIDTH - CHROME_BTN_SIZE) / 2) as i32;
(bx, by, CHROME_BTN_SIZE, CHROME_BTN_SIZE)
}
fn minimize_btn_rect(&self) -> (i32, i32, usize, usize) {
let (cx, cy, _, _) = self.close_btn_rect();
(cx - CHROME_BTN_PAD as i32 - CHROME_BTN_SIZE as i32, cy, CHROME_BTN_SIZE, CHROME_BTN_SIZE)
}
fn hit_close_button(&self, mx: i32, my: i32) -> bool {
let (bx, by, bw, bh) = self.close_btn_rect();
mx >= bx && mx < bx + bw as i32 && my >= by && my < by + bh as i32
}
fn hit_minimize_button(&self, mx: i32, my: i32) -> bool {
let (bx, by, bw, bh) = self.minimize_btn_rect();
mx >= bx && mx < bx + bw as i32 && my >= by && my < by + bh as i32
}
}
fn rects_overlap(a: (i32, i32, i32, i32), b: (i32, i32, i32, i32)) -> bool {
a.0 < b.2 && a.2 > b.0 && a.1 < b.3 && a.3 > b.1
}
// ─── Drawing Helpers ─────────────────────────────────────────────────────────
fn fill_rect(fb: &mut FrameBuf, x: i32, y: i32, w: usize, h: usize, color: Color) {
for dy in 0..h as i32 {
let py = y + dy;
if py < 0 || py >= fb.height as i32 { continue; }
for dx in 0..w as i32 {
let px = x + dx;
if px < 0 || px >= fb.width as i32 { continue; }
fb.put_pixel(px as usize, py as usize, color);
}
}
}
fn draw_text_at(fb: &mut FrameBuf, text: &[u8], x: i32, y: i32, color: Color) {
if y < 0 || y >= fb.height as i32 { return; }
for (i, &ch) in text.iter().enumerate() {
let px = x + (i as i32) * CELL_W as i32;
if px < 0 || px + CELL_W as i32 > fb.width as i32 { continue; }
bitmap_font::draw_char(fb, ch as char, px as usize, y as usize, color);
}
}
/// Draw a floating window frame (border + title bar + chrome buttons + content bg)
fn draw_window_frame(fb: &mut FrameBuf, win: &Window, focused: bool) {
let border_color = if focused { WIN_BORDER_FOCUSED } else { WIN_BORDER_COLOR };
let title_bg = if focused { TITLE_FOCUSED_BG } else { TITLE_UNFOCUSED_BG };
let title_fg = if focused { TITLE_FOCUSED_TEXT } else { TITLE_TEXT };
let bw = BORDER_WIDTH;
let shadow = Color::rgb(8, 10, 18);
fill_rect(fb, win.x + 3, win.y + 3, win.width, win.total_height(), shadow);
fill_rect(fb, win.x, win.y, win.width, win.total_height(), border_color);
fill_rect(fb, win.x + bw as i32, win.y + bw as i32,
win.width - bw * 2, TITLE_BAR_HEIGHT - bw, title_bg);
// Title text (truncated to not overlap chrome buttons)
let max_title_w = win.width.saturating_sub(bw * 2 + 8 + CHROME_RESERVED);
let max_chars = max_title_w / CELL_W;
let text_len = win.title_len.min(max_chars);
let text_y = win.y + bw as i32 + ((TITLE_BAR_HEIGHT - bw - CELL_H) / 2) as i32;
draw_text_at(fb, &win.title[..text_len], win.x + 8, text_y, title_fg);
// Close button (rightmost in title bar)
let (cbx, cby, cbw, cbh) = win.close_btn_rect();
fill_rect(fb, cbx, cby, cbw, cbh, CLOSE_BTN_BG);
let cx = cbx + (cbw as i32 - CELL_W as i32) / 2;
let cy = cby + (cbh as i32 - CELL_H as i32) / 2;
draw_text_at(fb, b"x", cx, cy, CLOSE_BTN_TEXT);
// Minimize button (left of close)
let (mbx, mby, mbw, mbh) = win.minimize_btn_rect();
fill_rect(fb, mbx, mby, mbw, mbh, MINIMIZE_BTN_BG);
let mx = mbx + (mbw as i32 - CELL_W as i32) / 2;
let my = mby + (mbh as i32 - CELL_H as i32) / 2;
draw_text_at(fb, b"-", mx, my, MINIMIZE_BTN_TEXT);
fill_rect(fb, win.content_x(), win.content_y(),
win.content_width(), win.content_height(), CONTENT_BG);
}
/// Paint the decorative desktop background — gradient with grid
fn paint_background(fb: &mut FrameBuf) {
let w = fb.width;
let h = fb.height;
for y in 0..h {
for x in 0..w {
let t = (y * 255 / h) as u8;
let r = 12u8.saturating_add(t / 12);
let g = 16u8.saturating_add(t / 20);
let b = 38u8.saturating_add(t / 6);
let grid = (x % 64 == 0 || y % 64 == 0) as u8;
let r2 = r.saturating_add(grid * 6);
let g2 = g.saturating_add(grid * 8);
let b2 = b.saturating_add(grid * 12);
fb.put_pixel(x, y, Color::rgb(r2, g2, b2));
}
}
}
// ─── Taskbar & App Bar ──────────────────────────────────────────────────────
/// US Eastern Time offset from UTC in seconds.
/// DST (EDT, UTC-4) runs from 2nd Sunday of March to 1st Sunday of November.
/// Standard (EST, UTC-5) applies the rest of the year.
fn eastern_offset_secs(utc_secs: i64) -> i64 {
// Compute day-of-year, month, day-of-week from Unix timestamp
let days = (utc_secs / 86400) as i64;
// Compute year/month/day
let mut y = 1970i64;
let mut rem = days;
loop {
let ydays = if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) { 366 } else { 365 };
if rem < ydays { break; }
rem -= ydays;
y += 1;
}
let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
let mdays: [i64; 12] = [31, if leap {29} else {28}, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let mut month = 0u8;
for i in 0..12 {
if rem < mdays[i] { month = i as u8 + 1; break; }
rem -= mdays[i];
}
let day = rem as u8 + 1;
// 2nd Sunday of March: find first Sunday in March, add 7
// 1st Sunday of November: find first Sunday in November
// Check month boundaries for DST transitions
// DST starts: 2nd Sunday of March at 2:00 AM EST (7:00 AM UTC)
// DST ends: 1st Sunday of November at 2:00 AM EDT (6:00 AM UTC)
let hour_utc = ((utc_secs % 86400) / 3600) as u8;
// March: find day-of-week of March 1
let jan1_dow = {
let mut d = 0i64;
for yr in 1970..y {
d += if yr % 4 == 0 && (yr % 100 != 0 || yr % 400 == 0) { 366 } else { 365 };
}
((d % 7 + 4) % 7) as u8 // 0=Sun
};
// Day of week of March 1 = (jan1_dow + 31 + feb_days) % 7
let feb = if leap { 29 } else { 28 };
let mar1_dow = (jan1_dow + 31 + feb) % 7;
let dst_start_day = if mar1_dow == 0 { 8u8 } else { (14 - mar1_dow + 1) as u8 }; // 2nd Sunday
// Day of week of Nov 1
let days_to_nov1: u16 = [31u16, feb as u16, 31, 30, 31, 30, 31, 31, 30, 31].iter().sum();
let nov1_dow = (jan1_dow as u16 + days_to_nov1) % 7;
let dst_end_day = if nov1_dow == 0 { 1u8 } else { 7 - nov1_dow as u8 + 1 };
let is_dst = match month {
1..=2 => false,
4..=10 => true,
3 => day > dst_start_day || (day == dst_start_day && hour_utc >= 7),
11 => day < dst_end_day || (day == dst_end_day && hour_utc < 6),
12 => false,
_ => false,
};
if is_dst { -4 * 3600 } else { -5 * 3600 }
}
fn format_clock(utc_secs: i64, buf: &mut [u8; 11]) {
let offset = eastern_offset_secs(utc_secs);
let local = utc_secs + offset;
// Handle day wrap
let t = ((local % 86400) + 86400) % 86400;
let s = (t % 60) as u8;
let m = ((t / 60) % 60) as u8;
let h = ((t / 3600) % 24) as u8;
buf[0] = b'0' + h / 10;
buf[1] = b'0' + h % 10;
buf[2] = b':';
buf[3] = b'0' + m / 10;
buf[4] = b'0' + m % 10;
buf[5] = b':';
buf[6] = b'0' + s / 10;
buf[7] = b'0' + s % 10;
buf[8] = b' ';
buf[9] = b'E';
buf[10] = b'T';
}
fn draw_taskbar(fb: &mut FrameBuf, clock_text: &[u8]) {
let w = fb.width;
fill_rect(fb, 0, 0, w, TASKBAR_HEIGHT, TASKBAR_BG);
// "Breenix" label on the left
let label_y = ((TASKBAR_HEIGHT - CELL_H) / 2 + 1) as i32;
draw_text_at(fb, b"Breenix", 8, label_y, TASKBAR_TEXT);
// Clock on the right
if !clock_text.is_empty() {
let clock_x = w as i32 - (clock_text.len() as i32 * CELL_W as i32) - 8;
draw_text_at(fb, clock_text, clock_x, label_y, TASKBAR_TEXT);
}
}
fn appbar_button_width(title_len: usize) -> usize {
let text_w = title_len * CELL_W + 16;
text_w.max(60).min(180)
}
/// Build indices sorted by creation_order (stable appbar layout).
fn sorted_by_creation(windows: &[Window]) -> ([usize; 16], usize) {
let n = windows.len().min(16);
let mut idx = [0usize; 16];
for i in 0..n { idx[i] = i; }
// Insertion sort (at most 16 elements)
for i in 1..n {
let mut j = i;
while j > 0 && windows[idx[j]].creation_order < windows[idx[j - 1]].creation_order {
idx.swap(j, j - 1);
j -= 1;
}
}
(idx, n)
}
fn draw_appbar(fb: &mut FrameBuf, windows: &[Window], focused_win: usize) {
let screen_h = fb.height;
let screen_w = fb.width;
let bar_y = (screen_h - APPBAR_HEIGHT) as i32;
// Background
fill_rect(fb, 0, bar_y, screen_w, APPBAR_HEIGHT, APPBAR_BG);
// 1px top border
fill_rect(fb, 0, bar_y, screen_w, 1, APPBAR_BORDER);
// Window buttons in stable creation order
let (sorted, n) = sorted_by_creation(windows);
let mut btn_x: i32 = 4;
let btn_h: usize = APPBAR_HEIGHT - 8;
let btn_y = bar_y + 4;
for k in 0..n {
let i = sorted[k];
let win = &windows[i];
let btn_w = appbar_button_width(win.title_len);
let bg = if i == focused_win && !win.minimized {
APPBAR_BTN_FOCUSED
} else if win.minimized {
APPBAR_BTN_MINIMIZED
} else {
APPBAR_BTN_BG
};
fill_rect(fb, btn_x, btn_y, btn_w, btn_h, bg);
// Title text (truncated to fit button)
let max_chars = (btn_w.saturating_sub(12)) / CELL_W;
let text_len = win.title_len.min(max_chars);
let text_y = btn_y + ((btn_h - CELL_H) / 2 + 1) as i32;
draw_text_at(fb, &win.title[..text_len], btn_x + 6, text_y, APPBAR_BTN_TEXT);
btn_x += btn_w as i32 + 2;
if btn_x >= screen_w as i32 - 4 { break; }
}
}
fn appbar_hit_test(windows: &[Window], screen_w: usize, screen_h: usize, mx: i32, my: i32) -> Option<usize> {
let bar_y = (screen_h - APPBAR_HEIGHT) as i32;
if my < bar_y || my >= screen_h as i32 { return None; }
let (sorted, n) = sorted_by_creation(windows);
let mut btn_x: i32 = 4;
let btn_h = (APPBAR_HEIGHT - 8) as i32;
let btn_y = bar_y + 4;
for k in 0..n {
let i = sorted[k];
let btn_w = appbar_button_width(windows[i].title_len) as i32;
if mx >= btn_x && mx < btn_x + btn_w
&& my >= btn_y && my < btn_y + btn_h
{
return Some(i); // Returns the actual Vec index, not the sorted position
}
btn_x += btn_w + 2;
if btn_x >= screen_w as i32 - 4 { break; }
}
None
}
fn next_visible_window(windows: &[Window], current: usize) -> usize {
for i in (0..windows.len()).rev() {
if !windows[i].minimized {
return i;
}
}
current
}
// ─── Input Routing ──────────────────────────────────────────────────────────
fn route_keyboard_to_focused(windows: &[Window], focused_win: usize, event: &WindowInputEvent) {
if focused_win < windows.len() && windows[focused_win].window_id != 0 {
let _ = graphics::write_window_input(windows[focused_win].window_id, event);
}
}
fn send_focus_event(windows: &[Window], win_idx: usize, event_type: u16) {
if win_idx < windows.len() && windows[win_idx].window_id != 0 {
let event = WindowInputEvent {
event_type,
keycode: 0, mouse_x: 0, mouse_y: 0, modifiers: 0, _pad: 0,
};
let _ = graphics::write_window_input(windows[win_idx].window_id, &event);
}
}
fn route_mouse_button_to_focused(
windows: &[Window], focused_win: usize,
button: u16, pressed: bool, win_local_x: i16, win_local_y: i16,
) {
if focused_win < windows.len() && windows[focused_win].window_id != 0 {
let event = WindowInputEvent {
event_type: input_event_type::MOUSE_BUTTON,
keycode: button,
mouse_x: win_local_x,
mouse_y: win_local_y,
modifiers: 0,
_pad: if pressed { 1 } else { 0 },
};
let _ = graphics::write_window_input(windows[focused_win].window_id, &event);
}
}
fn route_mouse_move_to_focused(
windows: &[Window], focused_win: usize,
win_local_x: i16, win_local_y: i16,
) {
if focused_win < windows.len() && windows[focused_win].window_id != 0 {
let event = WindowInputEvent {
event_type: input_event_type::MOUSE_MOVE,
keycode: 0,
mouse_x: win_local_x, mouse_y: win_local_y,
modifiers: 0, _pad: 0,
};
let _ = graphics::write_window_input(windows[focused_win].window_id, &event);
}
}
// ─── Window Discovery ───────────────────────────────────────────────────────
fn discover_windows(windows: &mut Vec<Window>, screen_w: usize, screen_h: usize, next_order: &mut u32) -> bool {
let mut win_infos = [graphics::WindowInfo {
buffer_id: 0, owner_pid: 0, width: 0, height: 0,
x: 0, y: 0, title_len: 0, title: [0; 64],
}; 16];
let count = match graphics::list_windows(&mut win_infos) {
Ok(c) => c as usize,
Err(_) => return false,
};
let before = windows.len();
windows.retain(|w| {
win_infos[..count].iter().any(|info| info.buffer_id == w.window_id)
});
let removed = before > windows.len();
let mut added = false;
for i in 0..count {
let info = &win_infos[i];
if info.buffer_id == 0 { continue; }
if windows.iter().any(|w| w.window_id == info.buffer_id) { continue; }
let n = windows.len();
let usable_h = screen_h.saturating_sub(TASKBAR_HEIGHT + APPBAR_HEIGHT);
let cascade_x = 30 + (n as i32 * 50) % ((screen_w as i32 - 500).max(100));
let cascade_y = TASKBAR_HEIGHT as i32 + 10
+ (n as i32 * 50) % ((usable_h as i32 - 500).max(100));
let total_w = info.width as usize + BORDER_WIDTH * 2;
let total_h = info.height as usize + TITLE_BAR_HEIGHT + BORDER_WIDTH * 2;
let mut title = [0u8; 32];
let title_len = (info.title_len as usize).min(32);
title[..title_len].copy_from_slice(&info.title[..title_len]);
print!("[bwm] Discovered window '{}' (id={}, {}x{}) at ({},{})\n",
core::str::from_utf8(&title[..title_len]).unwrap_or("?"),
info.buffer_id, info.width, info.height, cascade_x, cascade_y);
// Map client window buffer into our address space for zero-copy reads
let (map_ptr, map_w, map_h) = match graphics::map_window_buffer(info.buffer_id) {
Ok(result) => result,
Err(_) => {
print!("[bwm] WARNING: failed to map window {} buffer\n", info.buffer_id);
(core::ptr::null(), 0, 0)
}
};
let order = *next_order;
*next_order += 1;
windows.push(Window {
x: cascade_x, y: cascade_y, width: total_w, height: total_h,
title, title_len, window_id: info.buffer_id,
owner_pid: info.owner_pid,
minimized: false,
creation_order: order,
mapped_ptr: map_ptr, mapped_w: map_w, mapped_h: map_h,
});
added = true;
}
removed || added
}
// ─── Client Pixel Blitting ──────────────────────────────────────────────────
/// Core pixel blit — direct u32 writes to compositor buffer for speed.
/// Bypasses FrameBuf::put_pixel which does per-pixel bounds checking + color conversion.
fn blit_pixels_to_fb(fb: &mut FrameBuf, win: &Window, src: &[u32], w: usize, h: usize) {
let cx = win.content_x();
let cy = win.content_y();
let cw = win.content_width();
let ch = win.content_height();
let pw = w.min(cw);
let ph = h.min(ch);
let fb_w = fb.width;
let fb_h = fb.height;
// Get raw u32 pointer to compositor buffer
let fb_ptr = fb.raw_ptr() as *mut u32;
for row in 0..ph {
let py = (cy + row as i32) as usize;
if py >= fb_h { continue; }
let dst_row_start = py * fb_w;
let src_row_start = row * w;
let x_start = cx.max(0) as usize;
let x_end = ((cx + pw as i32) as usize).min(fb_w);
let src_offset = if cx < 0 { (-cx) as usize } else { 0 };
if x_start >= x_end { continue; }
let count = x_end - x_start;
let si = src_row_start + src_offset;
if si + count > src.len() { continue; }
unsafe {
core::ptr::copy_nonoverlapping(
src.as_ptr().add(si),
fb_ptr.add(dst_row_start + x_start),
count,
);
}
}
}
/// Check if a window has new pixels and blit from mapped memory to compositor.
/// Skips pixels covered by higher-z windows (occluders) so no z-repair is needed.
/// Returns true if new data was available.
fn blit_client_pixels(fb: &mut FrameBuf, win: &Window,
occluders: &[(i32, i32, i32, i32)]) -> bool {
if win.mapped_ptr.is_null() || win.mapped_w == 0 || win.mapped_h == 0 {
return false;
}
let dirty = graphics::check_window_dirty(win.window_id).unwrap_or(false);
if !dirty { return false; }
if occluders.is_empty() {
blit_mapped_pixels(fb, win);
return true;
}
// Occluded blit: for each row, skip pixels covered by higher windows.
let w = win.mapped_w as usize;
let h = win.mapped_h as usize;
let src = unsafe { core::slice::from_raw_parts(win.mapped_ptr, w * h) };
let cx = win.content_x();
let cy = win.content_y();
let cw = win.content_width().min(w);
let ch = win.content_height().min(h);
let fb_w = fb.width;
let fb_h = fb.height;
let fb_ptr = fb.raw_ptr() as *mut u32;
for row in 0..ch {
let py = cy + row as i32;
if py < 0 || py >= fb_h as i32 { continue; }
let row_x_start = cx.max(0) as usize;
let row_x_end = ((cx + cw as i32) as usize).min(fb_w);
if row_x_start >= row_x_end { continue; }
// Build visible spans by subtracting occluder columns from the full row
let mut spans = [(0usize, 0usize); 8];
let mut n_spans = 1;
spans[0] = (row_x_start, row_x_end);
for &(ox0, oy0, ox1, oy1) in occluders {
if py < oy0 || py >= oy1 { continue; }
let os = ox0.max(0) as usize;
let oe = ox1.max(0) as usize;
let mut new_spans = [(0usize, 0usize); 8];
let mut nc = 0;
for k in 0..n_spans {
let (sx, ex) = spans[k];
if sx >= ex { continue; }
if oe <= sx || os >= ex {
if nc < 8 { new_spans[nc] = (sx, ex); nc += 1; }
} else {
if sx < os && nc < 8 { new_spans[nc] = (sx, os); nc += 1; }
if ex > oe && nc < 8 { new_spans[nc] = (oe, ex); nc += 1; }
}
}
spans = new_spans;
n_spans = nc;
}
let src_row = row * w;
let src_col_base = if cx < 0 { (-cx) as usize } else { 0 };
for k in 0..n_spans {
let (sx, ex) = spans[k];
if sx >= ex { continue; }
let count = ex - sx;
let si = src_row + src_col_base + (sx - row_x_start);
if si + count > w * h { continue; }
unsafe {
core::ptr::copy_nonoverlapping(
src.as_ptr().add(si),
fb_ptr.add(py as usize * fb_w + sx),
count,
);
}
}
}
true
}
/// Blit a window's pixels from its mapped memory to the compositor buffer.
fn blit_mapped_pixels(fb: &mut FrameBuf, win: &Window) {
if win.mapped_ptr.is_null() { return; }
let w = win.mapped_w as usize;
let h = win.mapped_h as usize;
let pixel_count = w * h;
let src = unsafe { core::slice::from_raw_parts(win.mapped_ptr, pixel_count) };
blit_pixels_to_fb(fb, win, src, w, h);
}
/// Redraw all windows in z-order (index 0 = bottom), plus taskbar and app bar.
/// Reads directly from mapped memory (zero-copy from client window pages).
fn redraw_all_windows(fb: &mut FrameBuf, windows: &[Window], focused_win: usize, clock_text: &[u8]) {
draw_taskbar(fb, clock_text);
for i in 0..windows.len() {
if windows[i].minimized { continue; }
draw_window_frame(fb, &windows[i], i == focused_win);
if windows[i].window_id != 0 {
blit_mapped_pixels(fb, &windows[i]);
}
}
draw_appbar(fb, windows, focused_win);
}
// ─── Main ────────────────────────────────────────────────────────────────────
fn main() {
print!("[bwm] Breenix Window Manager starting...\n");
if let Err(e) = graphics::take_over_display() {
print!("[bwm] WARNING: take_over_display failed: {}\n", e);
}
let info = {
let mut result = None;
for attempt in 0..10 {
match graphics::fbinfo() {
Ok(info) => { result = Some(info); break; }
Err(_) if attempt < 9 => {
let _ = libbreenix::time::nanosleep(&libbreenix::types::Timespec { tv_sec: 0, tv_nsec: 10_000_000 });
}
Err(e) => { print!("[bwm] ERROR: fbinfo failed: {}\n", e); process::exit(1); }
}
}
result.unwrap()
};
let screen_w = info.width as usize;
let screen_h = info.height as usize;
let bpp = info.bytes_per_pixel as usize;
let gpu_compositing = {
let test_pixel: [u32; 1] = [0xFF000000];
graphics::virgl_composite(&test_pixel, 1, 1).is_ok()
};
if !gpu_compositing {
print!("[bwm] ERROR: GPU compositing required\n");
process::exit(1);
}
print!("[bwm] GPU compositing mode (VirGL), display: {}x{}\n", screen_w, screen_h);
// Try to map COMPOSITE_TEX directly into our address space.
// If successful, all pixel writes go straight to GPU texture backing (zero-copy).
let (composite_buf, direct_mapped) = match graphics::map_compositor_texture() {
Ok((ptr, tex_w, tex_h)) => {
let mapped_w = tex_w as usize;
let mapped_h = tex_h as usize;
print!("[bwm] Direct compositor mapping: {}x{} at {:p}\n", mapped_w, mapped_h, ptr);
let buf = unsafe { core::slice::from_raw_parts_mut(ptr, mapped_w * mapped_h) };
(buf, true)
}
Err(_) => {
print!("[bwm] Fallback: heap-allocated compositor buffer\n");
// Leak a Vec to get a &'static mut slice — BWM runs for the lifetime of the OS
let v = vec![0u32; screen_w * screen_h];
let leaked = v.leak();
(leaked as &mut [u32], false)
}
};
let mut fb = unsafe {
FrameBuf::from_raw(
composite_buf.as_mut_ptr() as *mut u8,
screen_w, screen_h, screen_w * bpp, bpp, info.is_bgr(),
)
};
// Paint decorative background and cache it for fast restoration
paint_background(&mut fb);
let bg_cache = composite_buf.to_vec();
// Enter raw mode on stdin
let mut orig_termios = libbreenix::termios::Termios::default();
let _ = libbreenix::termios::tcgetattr(Fd::from_raw(0), &mut orig_termios);
let mut raw = orig_termios;
libbreenix::termios::cfmakeraw(&mut raw);
let _ = libbreenix::termios::tcsetattr(Fd::from_raw(0), libbreenix::termios::TCSANOW, &raw);
let mut windows: Vec<Window> = Vec::new();
let mut focused_win: usize = 0;
let mut input_parser = InputParser::new();
let mut mouse_x: i32 = 0;
let mut mouse_y: i32 = 0;
let mut prev_buttons: u32 = 0;
let mut dragging: Option<(usize, i32, i32)> = None;
let mut full_redraw = true;
let mut content_dirty = false;
// Clock state
let mut last_clock_sec: i64 = -1;
let mut clock_text = [0u8; 11];
format_clock(0, &mut clock_text);
let mut next_creation_order: u32 = 0;
// Initial composite
if direct_mapped {
// Data is already in COMPOSITE_TEX — just tell kernel to upload + display
let _ = graphics::virgl_composite_windows_rect(&[], 0, 0, 1, 0, 0, screen_w as u32, screen_h as u32);
} else {
let _ = graphics::virgl_composite_windows(&composite_buf, screen_w as u32, screen_h as u32, true);
}
let mut read_buf = [0u8; 512];
let mut poll_fds = [io::PollFd { fd: 0, events: io::poll_events::POLLIN as i16, revents: 0 }];
// Performance tracing
let mut perf_frame: u64 = 0;
let mut perf_total_ns: u64 = 0;
let mut perf_composites: u64 = 0;
let mut perf_waits: u64 = 0;
fn mono_ns() -> u64 {
let ts = libbreenix::time::now_monotonic().unwrap_or_default();
(ts.tv_sec as u64) * 1_000_000_000 + (ts.tv_nsec as u64)
}
// Registry generation tracking for compositor_wait
let mut registry_gen: u32 = 0;
// Initial window discovery (before entering event loop)
if discover_windows(&mut windows, screen_w, screen_h, &mut next_creation_order) {
focused_win = next_visible_window(&windows, 0);
composite_buf.copy_from_slice(&bg_cache);
redraw_all_windows(&mut fb, &windows, focused_win, &clock_text);
full_redraw = true;
}
loop {
// ── 0. Block until something needs compositing ──
// compositor_wait blocks in the kernel until: window dirty, mouse moved,
// registry changed, or timeout. Replaces the old poll+sleep_ms(2) pattern.
// 16ms timeout ensures keyboard input via stdin is checked at least ~60Hz.
let (ready, new_reg_gen) = graphics::compositor_wait(16, registry_gen).unwrap_or((0, registry_gen));
registry_gen = new_reg_gen;
perf_waits += 1;
let t0 = mono_ns();
// ── 1. Discover new/removed client windows (only when registry changed) ──
if ready & graphics::COMPOSITOR_READY_REGISTRY != 0 {
if discover_windows(&mut windows, screen_w, screen_h, &mut next_creation_order) {
// New windows are pushed to end of Vec (top of z-order).
// Always focus the topmost visible window so appbar selection
// matches the visually foregrounded window.
focused_win = next_visible_window(&windows, 0);
composite_buf.copy_from_slice(&bg_cache);
redraw_all_windows(&mut fb, &windows, focused_win, &clock_text);
full_redraw = true;
}
}
// ── 2. Poll stdin (non-blocking) — keyboard arrives via stdin, not kernel events ──
poll_fds[0].revents = 0;
let _ = io::poll(&mut poll_fds, 0);
// ── 3. Process keyboard input ──
if poll_fds[0].revents & io::poll_events::POLLIN as i16 != 0 {
if let Ok(n) = io::read(Fd::from_raw(0), &mut read_buf) {
for i in 0..n {
if let Some(event) = input_parser.feed(read_buf[i]) {
match event {
InputEvent::FunctionKey(k) if (k as usize) <= windows.len() => {
let new_focus = (k - 1) as usize;
if new_focus < windows.len() && new_focus != focused_win {
send_focus_event(&windows, focused_win, input_event_type::FOCUS_LOST);
focused_win = new_focus;
send_focus_event(&windows, focused_win, input_event_type::FOCUS_GAINED);
composite_buf.copy_from_slice(&bg_cache);
redraw_all_windows(&mut fb, &windows, focused_win, &clock_text);
full_redraw = true;
}
}
InputEvent::Key { ascii, keycode, modifiers } => {
if !windows.is_empty() {
let win_event = WindowInputEvent {
event_type: input_event_type::KEY_PRESS,
keycode,
mouse_x: ascii as i16,
mouse_y: 0,
modifiers,
_pad: 0,
};
route_keyboard_to_focused(&windows, focused_win, &win_event);
}
}
_ => {}
}
}
}
}
}
// ── 4. Process mouse input (only when mouse changed) ──
if ready & graphics::COMPOSITOR_READY_MOUSE != 0 {
if let Ok((mx, my, buttons)) = graphics::mouse_state() {
let new_mx = mx as i32;
let new_my = my as i32;
let mouse_moved = new_mx != mouse_x || new_my != mouse_y;
if mouse_moved {
mouse_x = new_mx;
mouse_y = new_my;
if let Some((win_idx, off_x, off_y)) = dragging {
let new_x = mouse_x - off_x;
// Clamp drag to stay below taskbar
let new_y = (mouse_y - off_y).max(TASKBAR_HEIGHT as i32);
if new_x != windows[win_idx].x || new_y != windows[win_idx].y {
windows[win_idx].x = new_x;
windows[win_idx].y = new_y;
composite_buf.copy_from_slice(&bg_cache);
redraw_all_windows(&mut fb, &windows, focused_win, &clock_text);
full_redraw = true;
}
} else if !windows.is_empty() && focused_win < windows.len()
&& !windows[focused_win].minimized
&& windows[focused_win].hit_content(mouse_x, mouse_y)
{
let local_x = (mouse_x - windows[focused_win].content_x()) as i16;
let local_y = (mouse_y - windows[focused_win].content_y()) as i16;
route_mouse_move_to_focused(&windows, focused_win, local_x, local_y);