-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
3363 lines (3021 loc) · 121 KB
/
Copy pathscript.js
File metadata and controls
3363 lines (3021 loc) · 121 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
/* Dildows 7 - main script.
Bootstraps and wires together all managers: AppManager, WindowManager,
TaskbarManager, DesktopManager, and StartMenuManager. */
'use strict';
/* Central registry of every launchable application.
Each entry provides the window title, taskbar icon class, default size,
and the <template> ID whose content is cloned into the window body.
fixedSize: true disables resize handles and the maximize button.
aliasOf: redirects a key to another entry (e.g. 'pictures' → 'computer'). */
const APP_REGISTRY = {
aboutme: { title: 'About Me', icon: 'icon-aboutme', width: 760, height: 540, template: 'content-aboutme' },
computer: { title: 'Computer', icon: 'icon-computer', width: 700, height: 460, template: 'content-computer' },
notepad: { title: 'Untitled - Notepad', icon: 'icon-notepad', width: 520, height: 440, template: 'content-notepad' },
calculator: { title: 'Calculator', icon: 'icon-calculator', width: 280, height: 380, template: 'content-calculator', fixedSize: true },
paint: { title: 'untitled - Paint', icon: 'icon-paint', width: 760, height: 540, template: 'content-paint' },
ie: { title: 'Dildows Internet Explorer', icon: 'icon-ie', width: 760, height: 540, template: 'content-ie' },
mediaplayer: { title: 'Windows Media Player', icon: 'icon-mediaplayer', width: 360, height: 480, template: 'content-mediaplayer' },
recyclebin: { title: 'Recycle Bin', icon: 'icon-recyclebin', width: 560, height: 400, template: 'content-recyclebin' },
games: { title: 'Games', icon: 'icon-games', width: 480, height: 320, template: 'content-games' },
solitaire: { title: 'Solitaire', icon: 'icon-solitaire', width: 680, height: 560, template: 'content-solitaire' },
minesweeper: { title: 'Minesweeper', icon: 'icon-minesweeper', width: 340, height: 460, template: 'content-minesweeper', fixedSize: true },
chesstitans: { title: 'Chess Titans', icon: 'icon-chess', width: 460, height: 480, template: 'content-chesstitans' },
doom: { title: 'DOOM', icon: 'icon-doom', width: 680, height: 500, template: 'content-doom' },
controlpanel: { title: 'Control Panel', icon: 'icon-computer', width: 600, height: 420, template: 'content-controlpanel' },
devices: { title: 'Devices and Printers',icon: 'icon-computer', width: 560, height: 380, template: 'content-devices' },
help: { title: 'Windows Help and Support', icon: 'icon-ie', width: 560, height: 440, template: 'content-help' },
pictures: { aliasOf: 'computer' },
'aboutme-docs': { aliasOf: 'computer' },
};
/* ── Utilities ───────────────────────────────────────────── */
function clamp(val, min, max) { return Math.max(min, Math.min(max, val)); }
function uid(prefix) { return prefix + '-' + Math.random().toString(36).slice(2, 9); }
/* ── SoundManager ────────────────────────────────────────── *
* Thin wrapper around <audio> elements defined in index.html.
* Each method resets currentTime so rapid repeats always play from the start.
* Errors (e.g. missing file, autoplay policy) are swallowed silently. */
class SoundManager {
_play(id) {
const el = document.getElementById(id);
if (!el) return;
try {
el.currentTime = 0;
el.play().catch(() => {});
} catch (e) {}
}
click() { this._play('snd-click'); }
open() { this._play('snd-open'); }
close() { this._play('snd-close'); }
error() { this._play('snd-error'); }
startup() { this._play('snd-boot'); }
}
const Sound = new SoundManager();
/* ── DesktopManager ──────────────────────────────────────── *
* Manages desktop icons: double-click to launch, drag to reposition
* with Windows-7-accurate grid snapping, rubber-band multi-select,
* multi-icon drag, right-click context menus, and icon view modes.
*
* Grid system:
* - Icons snap to a virtual grid cell (GRID_W × GRID_H).
* - Each icon occupies exactly one cell; no two icons share a cell.
* - On drop, the nearest free cell is chosen (like real Windows 7).
* - Multi-selected icons maintain their relative cell offsets when dragged.
*/
class DesktopManager {
constructor(appManager) {
this.appManager = appManager;
this.desktopEl = document.getElementById('desktop');
this.iconsEl = document.getElementById('desktop-icons');
this.selectionBox = document.getElementById('selection-box');
this.desktopMenu = document.getElementById('desktop-context-menu');
this.iconMenu = document.getElementById('icon-context-menu');
this.selecting = false;
this.selectStart = { x: 0, y: 0 };
this.activeIconForMenu = null;
// Grid cell dimensions (px) — must match icon slot size
this.GRID_W = 90;
this.GRID_H = 94;
this.GRID_PAD_X = 10; // desktop left/top padding
this.GRID_PAD_Y = 10;
this.TASKBAR_H = 40;
// Map<iconEl, {col, row}> — current grid position of each icon
this.iconPositions = new Map();
this._initGrid();
this._bind();
}
/* ── Grid helpers ──────────────────────────────────────── */
_cols() {
return Math.max(1, Math.floor((window.innerWidth - this.GRID_PAD_X) / this.GRID_W));
}
_rows() {
return Math.max(1, Math.floor((window.innerHeight - this.TASKBAR_H - this.GRID_PAD_Y) / this.GRID_H));
}
/** Convert pixel position (top-left of icon) → nearest grid cell {col, row} */
_pxToCell(x, y) {
const col = Math.round((x - this.GRID_PAD_X) / this.GRID_W);
const row = Math.round((y - this.GRID_PAD_Y) / this.GRID_H);
return { col: Math.max(0, col), row: Math.max(0, row) };
}
/** Convert grid cell → pixel position (top-left of icon's bounding cell) */
_cellToPx(col, row) {
return {
x: this.GRID_PAD_X + col * this.GRID_W,
y: this.GRID_PAD_Y + row * this.GRID_H,
};
}
/** Set an icon's screen position based on its grid cell. */
_placeIcon(icon, col, row) {
const { x, y } = this._cellToPx(col, row);
icon.style.position = 'absolute';
icon.style.left = x + 'px';
icon.style.top = y + 'px';
this.iconPositions.set(icon, { col, row });
}
/** Returns a Set of "col,row" strings for all currently occupied cells,
* optionally excluding a set of icon elements. */
_occupiedCells(excludeIcons = new Set()) {
const occupied = new Set();
this.iconPositions.forEach((pos, icon) => {
if (!excludeIcons.has(icon)) occupied.add(`${pos.col},${pos.row}`);
});
return occupied;
}
/** Find the nearest free cell to (targetCol, targetRow), scanning outward. */
_nearestFreeCell(targetCol, targetRow, occupied) {
const cols = this._cols();
const rows = this._rows();
// BFS-style outward spiral search
for (let radius = 0; radius <= Math.max(cols, rows); radius++) {
for (let dc = -radius; dc <= radius; dc++) {
for (let dr = -radius; dr <= radius; dr++) {
if (Math.abs(dc) !== radius && Math.abs(dr) !== radius) continue;
const c = targetCol + dc;
const r = targetRow + dr;
if (c < 0 || r < 0 || c >= cols || r >= rows) continue;
if (!occupied.has(`${c},${r}`)) return { col: c, row: r };
}
}
}
return { col: targetCol, row: targetRow }; // fallback
}
/** Place all icons initially in a column-first grid layout. */
_initGrid() {
// Switch the icons container to absolute positioning mode
this.iconsEl.style.position = 'absolute';
this.iconsEl.style.inset = '0';
this.iconsEl.style.display = 'block';
this.iconsEl.style.width = '100%';
this.iconsEl.style.height = `calc(100% - ${this.TASKBAR_H}px)`;
const icons = Array.from(this.iconsEl.querySelectorAll('.desktop-icon'));
const rows = this._rows();
icons.forEach((icon, i) => {
const col = Math.floor(i / rows);
const row = i % rows;
this._placeIcon(icon, col, row);
});
}
/* ── Event binding ─────────────────────────────────────── */
_bind() {
this.iconsEl.querySelectorAll('.desktop-icon').forEach(icon => this._bindIcon(icon));
// Rubber-band selection on bare desktop
this.desktopEl.addEventListener('mousedown', (e) => {
const onDesktop = e.target === this.desktopEl || e.target === this.iconsEl || e.target.id === 'windows-container' || e.target.classList.contains('background');
if (!onDesktop) return;
this._closeAllContextMenus();
this._deselectAll();
this.selecting = true;
const rect = this.desktopEl.getBoundingClientRect();
this.selectStart = { x: e.clientX - rect.left, y: e.clientY - rect.top };
this.selectionBox.style.left = this.selectStart.x + 'px';
this.selectionBox.style.top = this.selectStart.y + 'px';
this.selectionBox.style.width = '0px';
this.selectionBox.style.height = '0px';
this.selectionBox.style.display = 'block';
});
document.addEventListener('mousemove', (e) => {
if (!this.selecting) return;
const rect = this.desktopEl.getBoundingClientRect();
const curX = e.clientX - rect.left;
const curY = e.clientY - rect.top;
const left = Math.min(curX, this.selectStart.x);
const top = Math.min(curY, this.selectStart.y);
const w = Math.abs(curX - this.selectStart.x);
const h = Math.abs(curY - this.selectStart.y);
this.selectionBox.style.left = left + 'px';
this.selectionBox.style.top = top + 'px';
this.selectionBox.style.width = w + 'px';
this.selectionBox.style.height = h + 'px';
// Hit-test against absolute icon positions
this.iconsEl.querySelectorAll('.desktop-icon').forEach(icon => {
const iLeft = parseInt(icon.style.left, 10) || 0;
const iTop = parseInt(icon.style.top, 10) || 0;
const iRight = iLeft + icon.offsetWidth;
const iBottom = iTop + icon.offsetHeight;
const overlap = !(iRight < left || iLeft > left + w || iBottom < top || iTop > top + h);
icon.classList.toggle('selected', overlap);
});
});
document.addEventListener('mouseup', () => {
if (this.selecting) {
this.selecting = false;
this.selectionBox.style.display = 'none';
}
});
this.desktopEl.addEventListener('contextmenu', (e) => {
if (e.target === this.desktopEl || e.target === this.iconsEl || e.target.id === 'windows-container') {
e.preventDefault();
this._closeAllContextMenus();
this._openContextMenu(this.desktopMenu, e.clientX, e.clientY);
}
});
this.desktopMenu.addEventListener('click', (e) => {
const item = e.target.closest('.context-item');
if (!item) return;
this._handleDesktopMenuAction(item.dataset.action);
this._closeAllContextMenus();
});
this.iconMenu.addEventListener('click', (e) => {
const item = e.target.closest('.context-item');
if (!item) return;
this._handleIconMenuAction(item.dataset.action);
this._closeAllContextMenus();
});
document.addEventListener('click', (e) => {
if (!e.target.closest('.context-menu')) this._closeAllContextMenus();
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') this._closeAllContextMenus();
});
}
_bindIcon(icon) {
let lastClick = 0;
icon.addEventListener('dragstart', (e) => e.preventDefault());
icon.addEventListener('mousedown', (e) => {
e.stopPropagation();
// Selection logic
if (e.ctrlKey) {
icon.classList.toggle('selected');
} else if (!icon.classList.contains('selected')) {
this._deselectAll();
icon.classList.add('selected');
}
// If already selected and multi-selected, keep group
const selectedIcons = Array.from(this.iconsEl.querySelectorAll('.desktop-icon.selected'));
const startX = e.clientX;
const startY = e.clientY;
let isDragging = false;
const DRAG_THRESHOLD = 4;
// Record each icon's starting pixel position and cell, and cursor offset from the primary icon
const primaryRect = icon.getBoundingClientRect();
const parentRect = this.desktopEl.getBoundingClientRect();
const cursorOffsetX = startX - primaryRect.left;
const cursorOffsetY = startY - primaryRect.top;
// Snapshot start positions (px) for all dragged icons
const startPositions = selectedIcons.map(ic => ({
icon: ic,
startLeft: parseInt(ic.style.left, 10) || 0,
startTop: parseInt(ic.style.top, 10) || 0,
cell: this.iconPositions.get(ic) || { col: 0, row: 0 },
}));
// Primary icon's start position
const primaryStart = startPositions.find(s => s.icon === icon) || startPositions[0];
// Ghost overlay for multi-drag preview
let ghostEls = [];
const moveHandler = (ev) => {
const dx = ev.clientX - startX;
const dy = ev.clientY - startY;
if (!isDragging && Math.hypot(dx, dy) < DRAG_THRESHOLD) return;
if (!isDragging) {
isDragging = true;
// Create semi-transparent ghost copies for all dragged icons
selectedIcons.forEach(ic => {
const ghost = ic.cloneNode(true);
ghost.style.opacity = '0.55';
ghost.style.pointerEvents = 'none';
ghost.style.position = 'absolute';
ghost.style.zIndex = '9998';
ghost.classList.add('icon-ghost');
this.iconsEl.appendChild(ghost);
ghostEls.push({ ghost, icon: ic });
});
selectedIcons.forEach(ic => { ic.style.opacity = '0.25'; });
}
// Move ghosts
ghostEls.forEach(({ ghost, icon: ic }) => {
const sp = startPositions.find(s => s.icon === ic);
let nx = sp.startLeft + dx;
let ny = sp.startTop + dy;
// clamp to desktop area
nx = Math.max(0, Math.min(nx, window.innerWidth - 90));
ny = Math.max(0, Math.min(ny, window.innerHeight - this.TASKBAR_H - 94));
ghost.style.left = nx + 'px';
ghost.style.top = ny + 'px';
});
};
const upHandler = () => {
document.removeEventListener('mousemove', moveHandler);
document.removeEventListener('mouseup', upHandler);
// Cleanup ghosts
ghostEls.forEach(({ ghost }) => ghost.remove());
ghostEls = [];
selectedIcons.forEach(ic => { ic.style.opacity = ''; });
if (!isDragging) {
// Click / double-click
const now = Date.now();
if (now - lastClick < 400) this._launchFromIcon(icon);
lastClick = now;
return;
}
// ── Snap all dragged icons to grid ──────────────────────
const dx = e.clientX - startX; // stale after mouseup — use last ev
// We need to recompute from ghost final positions
const excluded = new Set(selectedIcons);
const occupied = this._occupiedCells(excluded);
// Compute desired target cell for the primary icon based on cursor
const primaryGhost = ghostEls.length ? null : null; // ghosts removed already
// Use start + delta approach: reconstruct from last mousemove via stored ghost positions
// Since ghosts are removed, compute from startPositions + accumulated dx/dy
// We can get dx from last moveHandler — store it in closure
// Actually we need the last ev position; use a stored ref:
const lastEv = { clientX: e._lastClientX || startX, clientY: e._lastClientY || startY };
// Better: track last mouse position in a ref
const finalDx = (DesktopManager._lastMouseX || startX) - startX;
const finalDy = (DesktopManager._lastMouseY || startY) - startY;
// For each selected icon, compute its desired pixel pos and snap it
// Process in order to avoid cell conflicts
const assignments = [];
startPositions.forEach(sp => {
const desiredX = sp.startLeft + finalDx;
const desiredY = sp.startTop + finalDy;
const desired = this._pxToCell(desiredX, desiredY);
// Clamp to grid bounds
desired.col = Math.max(0, Math.min(desired.col, this._cols() - 1));
desired.row = Math.max(0, Math.min(desired.row, this._rows() - 1));
// Find nearest free cell (considering already-assigned ones this drop)
const allOccupied = new Set([...occupied, ...assignments.map(a => `${a.col},${a.row}`)]);
const free = this._nearestFreeCell(desired.col, desired.row, allOccupied);
assignments.push({ icon: sp.icon, col: free.col, row: free.row });
});
assignments.forEach(({ icon: ic, col, row }) => {
this._placeIcon(ic, col, row);
});
};
document.addEventListener('mousemove', moveHandler);
document.addEventListener('mouseup', upHandler);
});
icon.addEventListener('keydown', (e) => {
if (e.key === 'Enter') this._launchFromIcon(icon);
});
icon.addEventListener('contextmenu', (e) => {
e.preventDefault();
e.stopPropagation();
if (!icon.classList.contains('selected')) {
this._deselectAll();
icon.classList.add('selected');
}
this.activeIconForMenu = icon;
this._closeAllContextMenus();
this._openContextMenu(this.iconMenu, e.clientX, e.clientY);
});
}
_launchFromIcon(icon) {
const app = icon.dataset.app;
Sound.click();
this.appManager.launch(app);
}
_deselectAll() {
this.iconsEl.querySelectorAll('.desktop-icon.selected').forEach(i => i.classList.remove('selected'));
}
_openContextMenu(menu, x, y) {
menu.style.left = x + 'px';
menu.style.top = y + 'px';
menu.classList.add('open');
requestAnimationFrame(() => {
const rect = menu.getBoundingClientRect();
if (rect.right > window.innerWidth) menu.style.left = (window.innerWidth - rect.width - 6) + 'px';
if (rect.bottom > window.innerHeight - 40) menu.style.top = (window.innerHeight - rect.height - 46) + 'px';
});
}
_closeAllContextMenus() {
document.querySelectorAll('.context-menu').forEach(m => m.classList.remove('open'));
}
_handleDesktopMenuAction(action) {
switch (action) {
case 'view-large': this._setIconSize('large'); break;
case 'view-medium': this._setIconSize('medium'); break;
case 'view-small': this._setIconSize('small'); break;
case 'refresh': this._refreshAnim(); break;
case 'new-textdoc': this.appManager.launch('notepad'); break;
case 'new-folder': DialogManager.info('New Folder', 'A new folder has been created on the desktop.'); break;
case 'personalize': DialogManager.info('Personalize', 'Personalization settings are not available in this demo.'); break;
default: break;
}
}
_setIconSize(size) {
this.iconsEl.classList.remove('icons-small', 'icons-medium');
if (size === 'small') {
this.GRID_W = 80; this.GRID_H = 60;
this.iconsEl.classList.add('icons-small');
} else if (size === 'medium') {
this.GRID_W = 84; this.GRID_H = 78;
this.iconsEl.classList.add('icons-medium');
} else {
this.GRID_W = 90; this.GRID_H = 94;
}
// Re-snap all icons to grid with new cell size
const icons = Array.from(this.iconsEl.querySelectorAll('.desktop-icon:not(.icon-ghost)'));
const rows = this._rows();
icons.forEach((icon, i) => {
const col = Math.floor(i / rows);
const row = i % rows;
this._placeIcon(icon, col, row);
});
}
_handleIconMenuAction(action) {
if (!this.activeIconForMenu) return;
const icon = this.activeIconForMenu;
switch (action) {
case 'open': this._launchFromIcon(icon); break;
case 'delete': DialogManager.confirm('Delete Shortcut', `Are you sure you want to delete '${icon.querySelector('.icon-label').textContent}'?`, () => {
icon.style.opacity = '0.3';
setTimeout(() => { icon.style.opacity = ''; }, 600);
});
break;
case 'rename': DialogManager.info('Rename', 'Renaming is disabled for system icons in this demo.'); break;
case 'properties': DialogManager.info(icon.querySelector('.icon-label').textContent + ' Properties', 'Type: Application\nLocation: Desktop'); break;
default: break;
}
}
_refreshAnim() {
this.desktopEl.style.transition = 'filter 0.15s ease';
this.desktopEl.style.filter = 'brightness(1.15)';
setTimeout(() => { this.desktopEl.style.filter = ''; }, 150);
}
}
// Track global mouse position for drag-end snapping
document.addEventListener('mousemove', (e) => {
DesktopManager._lastMouseX = e.clientX;
DesktopManager._lastMouseY = e.clientY;
});
/* ── WindowManager ───────────────────────────────────────── *
* Handles the full lifecycle of every app window:
* - Creation from <template>, cascaded positioning, z-index stacking
* - Title-bar drag with Aero Snap (left/right/maximize zones)
* - Edge/corner resize with min-size enforcement
* - Minimize, maximize/restore, snap, close (with media cleanup) */
class WindowManager {
constructor(taskbarManager) {
this.container = document.getElementById('windows-container');
this.windows = new Map();
this.zCounter = 100;
this.activeId = null;
this.taskbarManager = taskbarManager;
this.cascadeOffset = 0;
}
createWindow(appKey, config, contentEl) {
const id = uid('win');
const tpl = document.getElementById('tpl-window');
const node = tpl.content.firstElementChild.cloneNode(true);
node.dataset.app = appKey;
node.dataset.winId = id;
const titleBar = node.querySelector('.title-bar');
const titleText = titleBar.querySelector('.title-bar-text');
const controls = titleBar.querySelector('.title-bar-controls');
titleText.textContent = config.title;
const iconSpan = document.createElement('span');
iconSpan.className = 'window-icon ' + config.icon;
iconSpan.style.cssText = 'display:inline-block;width:20px;height:20px;margin-right:6px;background-size:contain;background-repeat:no-repeat;background-position:center;';
titleText.prepend(iconSpan);
const body = node.querySelector('.window-body-content');
body.innerHTML = '';
body.appendChild(contentEl);
const TASKBAR_H = 40;
const w = config.width || 600;
const h = config.height || 420;
const visibleCount = Array.from(this.windows.values()).filter(wd => !wd.minimized).length;
const offsetAmount = (visibleCount * 28) % 140;
const maxLeft = Math.max(20, window.innerWidth - w - 20);
const maxTop = Math.max(20, window.innerHeight - TASKBAR_H - h - 10);
const left = Math.min(40 + offsetAmount, maxLeft);
const top = Math.min(36 + offsetAmount, maxTop);
node.style.width = w + 'px';
node.style.height = h + 'px';
node.style.left = left + 'px';
node.style.top = top + 'px';
node.style.position = 'absolute';
node.style.margin = '0';
if (config.fixedSize) {
node.querySelectorAll('.resize-handle').forEach(h => h.style.display = 'none');
controls.querySelector('.Maximize').style.display = 'none';
}
this.container.appendChild(node);
const winData = {
id, el: node, app: appKey, config,
minimized: false, maximized: false,
prevRect: null, snapped: null,
onClose: null,
_cleanupDoom: null,
_cleanupFunctions: []
};
this.windows.set(id, winData);
this._bindWindowChrome(winData);
this._bindDrag(winData);
if (!config.fixedSize) this._bindResize(winData);
this.focus(id);
this.taskbarManager.addApp(winData);
Sound.open();
return winData;
}
_bindWindowChrome(winData) {
const { el, id } = winData;
el.addEventListener('mousedown', () => this.focus(id));
el.querySelector('.Close').addEventListener('click', (e) => {
e.stopPropagation();
this.close(id);
});
el.querySelector('.Minimize').addEventListener('click', (e) => {
e.stopPropagation();
this.minimize(id);
});
el.querySelector('.Maximize').addEventListener('click', (e) => {
e.stopPropagation();
this.toggleMaximize(id);
});
el.querySelector('.title-bar').addEventListener('dblclick', (e) => {
if (e.target.closest('.button')) return;
this.toggleMaximize(id);
});
}
_bindDrag(winData) {
const { el, id } = winData;
const titlebar = el.querySelector('.title-bar');
let dragging = false, offsetX = 0, offsetY = 0;
let snapPreviewEl = this._getSnapPreviewEl();
titlebar.addEventListener('mousedown', (e) => {
if (e.target.closest('.button')) return;
this.focus(id);
const wd = this.windows.get(id);
if (wd.maximized) {
const ratioX = (e.clientX) / window.innerWidth;
this.toggleMaximize(id, true);
const rect = el.getBoundingClientRect();
el.style.left = clamp(e.clientX - rect.width * ratioX, 0, window.innerWidth - rect.width) + 'px';
el.style.top = '4px';
const newRect = el.getBoundingClientRect();
offsetX = e.clientX - newRect.left;
offsetY = e.clientY - newRect.top;
dragging = true;
el.classList.add('dragging');
} else {
dragging = true;
const rect = el.getBoundingClientRect();
offsetX = e.clientX - rect.left;
offsetY = e.clientY - rect.top;
el.classList.add('dragging');
}
const moveHandler = (ev) => {
if (!dragging) return;
let x = ev.clientX - offsetX;
let y = ev.clientY - offsetY;
const TASKBAR_H = 40;
const maxY = window.innerHeight - TASKBAR_H - 10;
y = Math.max(0, Math.min(y, maxY));
x = clamp(x, -el.offsetWidth + 80, window.innerWidth - 80);
el.style.left = x + 'px';
el.style.top = y + 'px';
const SNAP_MARGIN = 18;
let snapZone = null;
if (ev.clientX <= SNAP_MARGIN) snapZone = 'left';
else if (ev.clientX >= window.innerWidth - SNAP_MARGIN) snapZone = 'right';
else if (ev.clientY <= SNAP_MARGIN) snapZone = 'maximize';
this._showSnapPreview(snapPreviewEl, snapZone);
winData._pendingSnap = snapZone;
};
const upHandler = () => {
dragging = false;
el.classList.remove('dragging');
document.removeEventListener('mousemove', moveHandler);
document.removeEventListener('mouseup', upHandler);
this._hideSnapPreview(snapPreviewEl);
if (winData._pendingSnap === 'left') this.snap(id, 'left');
else if (winData._pendingSnap === 'right') this.snap(id, 'right');
else if (winData._pendingSnap === 'maximize') this.toggleMaximize(id, false, true);
winData._pendingSnap = null;
};
document.addEventListener('mousemove', moveHandler);
document.addEventListener('mouseup', upHandler);
});
}
_getSnapPreviewEl() {
let el = document.getElementById('snap-preview-global');
if (!el) {
el = document.createElement('div');
el.id = 'snap-preview-global';
el.className = 'snap-preview';
document.getElementById('desktop').appendChild(el);
}
return el;
}
_showSnapPreview(el, zone) {
if (!zone) { el.style.display = 'none'; return; }
el.style.display = 'block';
if (zone === 'left') { el.style.left = '0'; el.style.top = '0'; el.style.width = '50%'; el.style.height = 'calc(100% - 40px)'; }
else if (zone === 'right') { el.style.left = '50%'; el.style.top = '0'; el.style.width = '50%'; el.style.height = 'calc(100% - 40px)'; }
else if (zone === 'maximize') { el.style.left = '0'; el.style.top = '0'; el.style.width = '100%'; el.style.height = 'calc(100% - 40px)'; }
}
_hideSnapPreview(el) { el.style.display = 'none'; }
snap(id, side) {
const wd = this.windows.get(id);
if (!wd) return;
const el = wd.el;
if (!wd.prevRect) {
wd.prevRect = { left: el.style.left, top: el.style.top, width: el.style.width, height: el.style.height };
}
el.classList.remove('maximized');
el.classList.remove('snapped-left', 'snapped-right');
const h = window.innerHeight - 40;
if (side === 'left') {
el.style.left = '0px'; el.style.top = '0px';
el.style.width = (window.innerWidth / 2) + 'px'; el.style.height = h + 'px';
el.classList.add('snapped-left');
wd.snapped = 'left';
} else {
el.style.left = (window.innerWidth / 2) + 'px'; el.style.top = '0px';
el.style.width = (window.innerWidth / 2) + 'px'; el.style.height = h + 'px';
el.classList.add('snapped-right');
wd.snapped = 'right';
}
}
_bindResize(winData) {
const { el, id } = winData;
const handles = el.querySelectorAll('.resize-handle');
handles.forEach(handle => {
handle.addEventListener('mousedown', (e) => {
e.preventDefault();
e.stopPropagation();
this.focus(id);
const wd = this.windows.get(id);
if (wd.maximized) return;
let dir = '';
for (const cls of handle.classList) {
if (cls.startsWith('resize-') && cls !== 'resize-handle') {
dir = cls.replace('resize-', '');
break;
}
}
if (!dir) return;
const startX = e.clientX;
const startY = e.clientY;
const rect = el.getBoundingClientRect();
const initial = {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
right: rect.right,
bottom: rect.bottom
};
const MIN_W = 280;
const MIN_H = 160;
const TASKBAR_H = 40;
const moveHandler = (ev) => {
const dx = ev.clientX - startX;
const dy = ev.clientY - startY;
let newLeft = initial.left;
let newTop = initial.top;
let newWidth = initial.width;
let newHeight = initial.height;
// East handle: anchor the left edge, stretch the right side.
if (dir.includes('e')) {
newWidth = Math.max(MIN_W, initial.width + dx);
}
// West handle: anchor the right edge, move the left side.
if (dir.includes('w')) {
const rawLeft = initial.left + dx;
newLeft = Math.min(rawLeft, initial.right - MIN_W); // clamp so width >= MIN_W
newLeft = Math.max(0, newLeft); // keep on-screen
newWidth = initial.right - newLeft;
}
// South handle: anchor the top edge, stretch the bottom.
if (dir.includes('s')) {
const maxH = window.innerHeight - TASKBAR_H - initial.top;
newHeight = Math.min(Math.max(MIN_H, initial.height + dy), maxH);
}
// North handle: anchor the bottom edge, move the top side.
if (dir.includes('n')) {
const rawTop = initial.top + dy;
newTop = Math.min(rawTop, initial.bottom - MIN_H); // clamp so height >= MIN_H
newTop = Math.max(0, newTop); // keep on-screen
newHeight = initial.bottom - newTop;
}
el.style.left = newLeft + 'px';
el.style.top = newTop + 'px';
el.style.width = newWidth + 'px';
el.style.height = newHeight + 'px';
};
const upHandler = () => {
document.removeEventListener('mousemove', moveHandler);
document.removeEventListener('mouseup', upHandler);
};
document.addEventListener('mousemove', moveHandler);
document.addEventListener('mouseup', upHandler);
});
});
}
focus(id) {
if (this.activeId === id) {
const wd = this.windows.get(id);
if (wd) { wd.el.classList.add('active'); }
return;
}
this.windows.forEach((wd, wid) => {
wd.el.classList.toggle('active', wid === id);
});
const wd = this.windows.get(id);
if (wd) {
this.zCounter += 1;
wd.el.style.zIndex = this.zCounter;
if (wd.minimized) this._restore(wd);
}
this.activeId = id;
this.taskbarManager.setActive(id);
}
minimize(id) {
const wd = this.windows.get(id);
if (!wd) return;
wd.minimized = true;
wd.el.classList.add('minimized');
Sound.click();
if (this.activeId === id) {
this.activeId = null;
this.taskbarManager.setActive(null);
}
this.taskbarManager.setMinimized(id, true);
}
_restore(wd) {
wd.minimized = false;
wd.el.classList.remove('minimized');
this.taskbarManager.setMinimized(wd.id, false);
}
toggleFromTaskbar(id) {
const wd = this.windows.get(id);
if (!wd) return;
if (wd.minimized) {
this.focus(id);
} else if (this.activeId === id) {
this.minimize(id);
} else {
this.focus(id);
}
}
toggleMaximize(id, forceRestore, forceMaximize) {
const wd = this.windows.get(id);
if (!wd || wd.config.fixedSize) return;
const el = wd.el;
if (forceRestore || (wd.maximized && !forceMaximize)) {
wd.maximized = false;
el.classList.remove('maximized', 'snapped-left', 'snapped-right');
if (wd.prevRect) {
el.style.left = wd.prevRect.left;
el.style.top = wd.prevRect.top;
el.style.width = wd.prevRect.width;
el.style.height = wd.prevRect.height;
}
wd.snapped = null;
} else {
if (!wd.prevRect) {
wd.prevRect = { left: el.style.left, top: el.style.top, width: el.style.width, height: el.style.height };
}
wd.maximized = true;
el.classList.remove('snapped-left', 'snapped-right');
el.classList.add('maximized');
el.style.left = '0px';
el.style.top = '0px';
el.style.width = '100%';
el.style.height = 'calc(100% - 40px)';
wd.snapped = null;
}
this.focus(id);
}
close(id) {
const wd = this.windows.get(id);
if (!wd) return;
// Run registered DOOM cleanup (AudioContext, canvas, DOS instance) before DOM removal.
if (wd._cleanupDoom) {
try {
wd._cleanupDoom();
} catch (e) {
console.warn('DOOM cleanup error:', e);
}
wd._cleanupDoom = null;
}
if (wd._cleanupFunctions && wd._cleanupFunctions.length > 0) {
wd._cleanupFunctions.forEach(fn => {
try {
fn();
} catch (e) {
console.warn('Cleanup function error:', e);
}
});
wd._cleanupFunctions = [];
}
if (wd.onClose) {
try {
wd.onClose();
} catch (e) {
console.warn('onClose error:', e);
}
wd.onClose = null;
}
try {
const iframes = wd.el.querySelectorAll('iframe');
iframes.forEach(iframe => {
try {
if (iframe.contentWindow) {
if (iframe.contentWindow.stop) {
try { iframe.contentWindow.stop(); } catch (e) {}
}
try {
if (iframe.contentWindow.AudioContext) {
const ctx = iframe.contentWindow.AudioContext;
if (ctx && ctx.close) {
try { ctx.close(); } catch (e) {}
}
}
} catch (e) {}
}
} catch (e) {}
iframe.src = 'about:blank';
iframe.remove();
});
const audios = wd.el.querySelectorAll('audio');
audios.forEach(audio => {
try {
audio.pause();
audio.src = '';
audio.load();
} catch (e) {}
audio.remove();
});
const videos = wd.el.querySelectorAll('video');
videos.forEach(video => {
try {
video.pause();
video.src = '';
video.load();
} catch (e) {}
video.remove();
});
const canvases = wd.el.querySelectorAll('canvas');
canvases.forEach(canvas => {
try {
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
if (gl) {
gl.getExtension('WEBGL_lose_context')?.loseContext();
}
} catch (e) {}
canvas.remove();
});
const worklets = wd.el.querySelectorAll('audio-worklet');
worklets.forEach(w => w.remove());
} catch (e) {
console.warn('Element cleanup error:', e);
}
try {
const allElements = wd.el.querySelectorAll('*');
allElements.forEach(el => {
try {
const clone = el.cloneNode(false);
el.parentNode?.replaceChild(clone, el);
} catch (e) {}
});
} catch (e) {}
Sound.close();
wd.el.classList.add('closing');
setTimeout(() => {
try {
while (wd.el.firstChild) {
try {