-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
2980 lines (2705 loc) · 260 KB
/
index.html
File metadata and controls
2980 lines (2705 loc) · 260 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simplex OS</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="simplex_os_desktop_style_B.css" id="main-stylesheet">
<style>
/* CSS for Blinking Glow Features */
:root {
--window-glow-blink-speed: 1.5s; /* Default speed for window glow */
--start-button-glow-blink-speed: 1.5s; /* Default speed for start button glow */
}
/* Active Window Blinking Glow */
@keyframes windowBlinkGlowAnimation {
0%, 100% { box-shadow: 0 0 0px var(--_glow-color, transparent); }
50% { box-shadow: 0 0 20px 5px var(--_glow-color, transparent); }
}
body.window-glow-active .window.active {
--_glow-color: var(--window-active-border-color-custom, var(--window-active-border-color-default-dark)); /* Adapts to theme */
animation: windowBlinkGlowAnimation var(--window-glow-blink-speed) infinite;
}
/* Start Button Blinking Glow */
@keyframes startButtonGlowAnimation {
0%, 100% { box-shadow: 0 0 0px transparent; }
50% { box-shadow: 0 0 15px 3px var(--_start-button-glow-color, var(--accent-primary)); }
}
#start-button.blinking-glow-enabled {
--_start-button-glow-color: var(--start-button-bg, var(--start-button-bg-dark)); /* Uses current start button bg */
animation: startButtonGlowAnimation var(--start-button-glow-blink-speed) infinite;
}
/* Desktop Icon Visibility */
#desktop.icons-hidden .desktop-icon {
opacity: 0;
transform: scale(0.8);
pointer-events: none;
visibility: hidden;
}
/* Ensure transition for opacity/transform on desktop icons if not already present */
#desktop .desktop-icon {
transition: background-color 0.1s ease, opacity 0.3s ease-out, transform 0.3s ease-out, visibility 0s 0.3s;
}
body.animations-disabled #desktop .desktop-icon,
body.animations-disabled #desktop.icons-hidden .desktop-icon {
transition: none !important;
}
body.animations-disabled #desktop.icons-hidden .desktop-icon {
display: none; /* Fallback for no animations */
}
/* Styles for Collapsible Settings Sections */
.settings-section h3.settings-section-toggle {
cursor: pointer;
display: flex;
justify-content: space-between;
align-items: center;
user-select: none; /* Prevent text selection on toggle click */
padding: 10px 0; /* Add some padding to make the click target larger if h3 itself had less padding */
margin-bottom: 0; /* h3's default margin-bottom will be handled by settings-section-content */
}
.settings-section h3.settings-section-toggle .collapse-icon {
transition: transform 0.2s ease-in-out;
font-size: 0.8em;
margin-left: 10px;
}
.settings-section.collapsed h3.settings-section-toggle .collapse-icon {
transform: rotate(-90deg);
}
.settings-section .settings-section-content {
max-height: 2000px; /* Sufficiently large height for content */
overflow: hidden;
transition: max-height 0.3s ease-in-out, opacity 0.3s ease-in-out, padding-top 0.3s ease-in-out, margin-top 0.3s ease-in-out;
opacity: 1;
margin-top: 18px; /* Replaces old h3 margin-bottom */
}
.settings-section.collapsed .settings-section-content {
max-height: 0;
opacity: 0;
margin-top: 0;
padding-top: 0; /* If content had padding */
pointer-events: none;
}
body.animations-disabled .settings-section .settings-section-content,
body.animations-disabled .settings-section.collapsed .settings-section-content {
display: none;
}
/* --- START: Styles for OS Dialog Buttons --- */
#os-dialog-actions {
display: flex;
justify-content: flex-end; /* Aligns buttons to the right */
gap: 10px;
padding-top: 20px;
margin-top: 15px;
border-top: 1px solid var(--border-secondary, #444);
}
#os-dialog-actions button {
background-color: var(--bg-tertiary, #3a3a3a);
color: var(--text-primary, #f0f0f0);
border: 1px solid var(--border-primary, #555);
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
font-size: 0.9em;
font-weight: 500;
min-width: 80px;
text-align: center;
transition: background-color 0.15s ease, border-color 0.15s ease, filter 0.15s ease;
}
#os-dialog-actions button:hover {
background-color: var(--taskbar-button-hover, #4a4a4a);
border-color: var(--border-secondary, #777);
}
/* Style for the primary action button (e.g., OK, Save, Confirm) */
#os-dialog-actions button.primary,
#os-dialog-actions button.success {
background-color: var(--accent-primary, #0078D4);
color: var(--text-secondary, #ffffff);
border-color: var(--accent-primary, #0078D4);
font-weight: bold;
}
#os-dialog-actions button.primary:hover,
#os-dialog-actions button.success:hover {
background-color: var(--accent-primary, #0078D4); /* Keep base color */
filter: brightness(1.2); /* Make it glow slightly on hover */
}
/* Style for the dangerous action button (e.g., Delete, Reset) */
#os-dialog-actions button.danger {
background-color: var(--accent-danger, #D32F2F);
color: var(--text-secondary, #ffffff);
border-color: var(--accent-danger, #D32F2F);
font-weight: bold;
}
#os-dialog-actions button.danger:hover {
background-color: var(--accent-danger, #D32F2F);
filter: brightness(1.2);
}
/* --- END: Styles for OS Dialog Buttons --- */
</style>
</head>
<body>
<div id="desktop"></div>
<div id="taskbar"> <button id="start-button"><i class="fa-solid fa-bars"></i> Start</button> <div id="taskbar-apps"></div> <div id="system-tray"><span id="clock"></span></div> </div>
<div id="start-menu" class="hidden">
<div id="start-menu-search-bar">
<i class="fa-solid fa-search"></i>
<input type="search" id="app-search-input" placeholder="Search for apps...">
</div>
<ul id="app-list"></ul>
</div>
<div id="taskbar-clock-popup"> <div class="popup-time">--:--:--</div> <div class="popup-date">---</div> </div>
<div id="lock-screen-overlay" class="hidden"></div>
<div id="welcome-screen-overlay" class="hidden"></div>
<div id="custom-context-menu" class="hidden"></div>
<div id="os-dialog-overlay" class="hidden">
<div id="os-dialog-box" class="os-dialog">
<h3 id="os-dialog-title"></h3>
<div id="os-dialog-content"></div>
<div id="os-dialog-actions"></div>
</div>
</div>
<input type="file" id="app-file-input" style="display:none;" accept=".js">
<input type="file" id="image-file-input" style="display:none;" accept="image/*">
<input type="file" id="wallpaper-file-input" style="display:none;" accept="image/*">
<input type="file" id="media-file-input" style="display:none;" accept="audio/*,video/*,.mkv,.avi,.mov,.flac,.mp3,.mp4,.ogg,.wav">
<input type="file" id="custom-css-file-input" style="display:none;" accept=".css">
<!-- Hidden file input specifically for the image widget -->
<input type="file" id="widget-image-file-input" style="display:none;" accept="image/*">
<script>
document.addEventListener('DOMContentLoaded', () => {
// --- Element References ---
const desktop = document.getElementById('desktop');
const taskbar = document.getElementById('taskbar');
const taskbarApps = document.getElementById('taskbar-apps');
const startButton = document.getElementById('start-button');
const startMenu = document.getElementById('start-menu');
const appList = document.getElementById('app-list');
const appSearchInput = document.getElementById('app-search-input');
const appFileInput = document.getElementById('app-file-input');
const clockElement = document.getElementById('clock');
const taskbarClockPopup = document.getElementById('taskbar-clock-popup');
const imageFileInput = document.getElementById('image-file-input');
const wallpaperFileInput = document.getElementById('wallpaper-file-input');
const mediaFileInput = document.getElementById('media-file-input');
const customCSSFileInput = document.getElementById('custom-css-file-input');
const widgetImageFileInput = document.getElementById('widget-image-file-input'); // Ref for image widget
const mainStylesheetLink = document.getElementById('main-stylesheet');
let lockScreenOverlay = document.getElementById('lock-screen-overlay');
let passwordSetupScreen;
let loginScreen;
let welcomeScreenOverlay = document.getElementById('welcome-screen-overlay');
let customContextMenu = document.getElementById('custom-context-menu');
// --- OS Dialog System Elements ---
const osDialogOverlay = document.getElementById('os-dialog-overlay');
const osDialogBox = document.getElementById('os-dialog-box');
const osDialogTitle = document.getElementById('os-dialog-title');
const osDialogContent = document.getElementById('os-dialog-content');
const osDialogActions = document.getElementById('os-dialog-actions');
// --- State Variables ---
let openWindows = {};
let nextZIndex = 10;
let activeWindowId = null;
let desktopShortcuts = [];
let osLocked = true;
let desktopIconsVisible = true;
let desktopIconArrangement = 'row';
let desktopWidgets = {}; // For widget instances
let nextWidgetZIndex = 5;
// --- Touch/Tap Interaction Variables ---
let lastTapTime = 0;
let lastTapTarget = null;
const DOUBLE_TAP_THRESHOLD = 300; // milliseconds for double tap
let longPressTimer = null;
const LONG_PRESS_DURATION = 700; // milliseconds for long press
let touchStartX = 0;
let touchStartY = 0;
const LONG_PRESS_MOVE_THRESHOLD = 10; // pixels a touch can move and still be a long press
// --- Storage Keys ---
const INSTALLED_APPS_STORAGE_KEY = 'simplexos_installed_apps_v2';
const DESKTOP_SHORTCUTS_KEY = 'simplexos_desktop_shortcuts_v1';
const BG_COLOR1_KEY = 'simplexos_bg_color1_v1';
const BG_COLOR2_KEY = 'simplexos_bg_color2_v1';
const WALLPAPER_KEY = 'simplexos_wallpaper_v1';
const STARTMENU_VIEW_KEY = 'simplexos_startmenu_view_v1';
const ANIMATIONS_DISABLED_KEY = 'simplexos_animations_disabled_v1';
const NOTES_STORAGE_KEY = 'simplexos_notes_app_data_v1';
const ICON_COLOR_KEY = 'simplexos_icon_color_v1';
const START_BUTTON_BG_KEY = 'simplexos_start_button_bg_v1';
const START_MENU_ICON_COLOR_KEY = 'simplexos_start_menu_icon_color_v1';
const WINDOW_ACTIVE_BORDER_COLOR_KEY = 'simplexos_window_active_border_color_v1';
const PASSWORD_HASH_KEY = 'simplexos_password_hash_v1';
const PASSWORD_SETUP_SKIPPED_KEY = 'simplexos_password_setup_skipped_v1';
const WELCOME_SCREEN_SHOWN_KEY = 'simplexos_welcome_screen_shown_v1';
const CONTEXT_MENU_ENABLED_KEY = 'simplexos_context_menu_enabled_v1';
const WINDOW_GLOW_ENABLED_KEY = 'simplexos_window_glow_enabled_v1';
const WINDOW_GLOW_SPEED_KEY = 'simplexos_window_glow_speed_v1';
const CUSTOM_CSS_CONTENT_KEY = 'simplexos_custom_css_content_v1';
const CUSTOM_CSS_FILENAME_KEY = 'simplexos_custom_css_filename_v1';
const START_BUTTON_GLOW_ENABLED_KEY = 'simplexos_start_button_glow_enabled_v1';
const DESKTOP_ICONS_VISIBLE_KEY = 'simplexos_desktop_icons_visible_v1';
const DESKTOP_ICON_ARRANGEMENT_KEY = 'simplexos_desktop_icon_arrangement_v1';
// --- Storage Keys ---
// ... (other keys)
const TASKBAR_COLOR_KEY = 'simplexos_taskbar_color_v1';
const APP_LIBRARY_GUIDE_SHOWN_KEY = 'simplexos_app_library_guide_shown_v1'; // <-- ADD THIS LINE
const DESKTOP_WIDGETS_KEY = 'simplexos_desktop_widgets_v1';
// ... (other keys)
const WIDGET_DATA_PREFIX = 'simplexos_widget_data_';
const THEME_STYLESHEET_KEY = 'simplexos_theme_stylesheet_v1';
// --- Default Values ---
let DEFAULT_BG_COLOR1;
let DEFAULT_BG_COLOR2;
const DEFAULT_STARTMENU_VIEW = 'list';
const DEFAULT_WALLPAPERS = [
'desktop_wallpapers/default_w_1.jpg', 'desktop_wallpapers/default_w_2.jpg',
'desktop_wallpapers/default_w_3.jpg', 'desktop_wallpapers/default_w_4.jpg',
'desktop_wallpapers/default_w_5.jpg',
];
let DEFAULT_ICON_COLOR_DARK;
let DEFAULT_START_BUTTON_BG_DARK;
let DEFAULT_START_MENU_ICON_COLOR_DARK;
let DEFAULT_WINDOW_ACTIVE_BORDER_DARK;
let DEFAULT_BORDER_PRIMARY_DARK;
let DEFAULT_BORDER_SECONDARY_DARK;
let DEFAULT_TASKBAR_BG_DARK;
const DEFAULT_DESKTOP_ICONS_VISIBLE = true;
const DEFAULT_DESKTOP_ICON_ARRANGEMENT = 'row';
const AVAILABLE_THEMES = {
'simplex_os_desktop_style_B.css': 'Simplex Dark (Default)',
'simplex_os_theme_light.css': 'Simplex Light',
'simplex_os_theme_futuristic.css': 'Futuristic World',
'simplex_os_theme_hacker.css': 'Hacker Terminal',
'simplex_os_theme_solar.css': 'Solar Power',
'simplex_os_theme_ancient.css': 'Ancient Myths',
'simplex_os_theme_valentine.css': 'Saint Valentine',
};
const DEFAULT_THEME_STYLESHEET = 'simplex_os_desktop_style_B.css';
// --- Widget Definitions ---
const widgets = {
'digitalClock': {
name: 'Digital Clock',
defaultSize: { width: 290, height: 180 },
init: (contentEl, instanceId) => {
contentEl.classList.add('digital-clock-widget');
contentEl.innerHTML = `
<div class="digital-time" id="digital-time-${instanceId}"></div>
<div class="digital-date" id="digital-date-${instanceId}"></div>`;
const timeEl = contentEl.querySelector(`#digital-time-${instanceId}`);
const dateEl = contentEl.querySelector(`#digital-date-${instanceId}`);
function updateClock() {
const now = new Date();
if (timeEl) timeEl.textContent = now.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', second:'2-digit'});
if (dateEl) dateEl.textContent = now.toLocaleDateString(undefined, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
}
updateClock();
const intervalId = setInterval(updateClock, 1000);
if (desktopWidgets[instanceId]) {
desktopWidgets[instanceId].cleanup = () => clearInterval(intervalId);
}
}
},
'quickNote': {
name: 'Quick Note',
defaultSize: { width: 200, height: 200 },
init: (contentEl, instanceId) => {
const storageKey = `${WIDGET_DATA_PREFIX}${instanceId}`;
contentEl.classList.add('quick-note-widget');
contentEl.innerHTML = `<textarea placeholder="Type something..."></textarea>`;
const textarea = contentEl.querySelector('textarea');
const savedContent = localStorage.getItem(storageKey);
if (savedContent) textarea.value = savedContent;
textarea.addEventListener('input', () => {
localStorage.setItem(storageKey, textarea.value);
});
}
},
'imageFrame': {
name: 'Image Frame',
defaultSize: { width: 180, height: 180 },
init: (contentEl, instanceId) => {
const storageKey = `${WIDGET_DATA_PREFIX}${instanceId}`;
contentEl.classList.add('image-frame-widget');
contentEl.innerHTML = `
<div class="placeholder" id="placeholder-${instanceId}"><i class="fa-solid fa-image"></i><span>Click to add image</span></div>
<img id="image-${instanceId}" class="hidden" />
`;
const placeholder = contentEl.querySelector(`#placeholder-${instanceId}`);
const imageEl = contentEl.querySelector(`#image-${instanceId}`);
const loadImage = (dataUrl) => {
if(dataUrl) {
imageEl.src = dataUrl;
imageEl.classList.remove('hidden');
placeholder.classList.add('hidden');
}
};
const savedImage = localStorage.getItem(storageKey);
if (savedImage) loadImage(savedImage);
const selectImage = () => {
widgetImageFileInput.onchange = (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (readEvent) => {
const dataUrl = readEvent.target.result;
localStorage.setItem(storageKey, dataUrl);
loadImage(dataUrl);
};
reader.readAsDataURL(file);
}
widgetImageFileInput.value = ''; // Reset for next selection
};
widgetImageFileInput.click();
};
placeholder.onclick = selectImage;
imageEl.onclick = selectImage; // Allow changing the image
}
},
'todoList': {
name: 'To-Do List',
defaultSize: { width: 250, height: 300 },
init: (contentEl, instanceId) => {
const storageKey = `${WIDGET_DATA_PREFIX}${instanceId}`;
contentEl.classList.add('todo-list-widget');
contentEl.innerHTML = `
<input type="text" id="todo-input-${instanceId}" placeholder="Add a task and press Enter...">
<ul id="todo-list-${instanceId}"></ul>
`;
const input = contentEl.querySelector(`#todo-input-${instanceId}`);
const list = contentEl.querySelector(`#todo-list-${instanceId}`);
let todos = JSON.parse(localStorage.getItem(storageKey)) || [];
const saveTodos = () => {
localStorage.setItem(storageKey, JSON.stringify(todos));
};
const renderTodos = () => {
list.innerHTML = '';
todos.forEach((todo, index) => {
const li = document.createElement('li');
li.className = todo.completed ? 'completed' : '';
li.innerHTML = `<span>${todo.text}</span><button class="delete-btn" data-index="${index}"><i class="fa-solid fa-xmark"></i></button>`;
li.querySelector('span').onclick = () => {
todos[index].completed = !todos[index].completed;
saveTodos();
renderTodos();
};
li.querySelector('.delete-btn').onclick = (e) => {
e.stopPropagation();
todos.splice(index, 1);
saveTodos();
renderTodos();
};
list.appendChild(li);
});
};
input.onkeypress = (e) => {
if (e.key === 'Enter' && input.value.trim() !== '') {
if (todos.length >= 32) {
showOSAlert('The To-Do list can hold a maximum of 32 items.', 'List Full');
return;
}
todos.push({ text: input.value.trim(), completed: false });
input.value = '';
saveTodos();
renderTodos();
}
};
renderTodos();
}
},
'miniCalculator': {
name: 'Mini Calculator',
defaultSize: { width: 180, height: 250 },
init: (contentEl, instanceId) => {
contentEl.classList.add('mini-calc-widget');
contentEl.innerHTML = `
<div class="display" id="calc-display-${instanceId}">0</div>
<div class="buttons">
<button data-val="C" class="special">C</button><button class="operator" data-val="/">/</button><button class="operator" data-val="*">*</button><button class="operator" data-val="-">-</button>
<button data-val="7">7</button><button data-val="8">8</button><button data-val="9">9</button><button class="operator tall" data-val="+">+</button>
<button data-val="4">4</button><button data-val="5">5</button><button data-val="6">6</button>
<button data-val="1">1</button><button data-val="2">2</button><button data-val="3">3</button><button class="tall" data-val="=">=</button>
<button data-val="0" class="wide">0</button><button data-val=".">.</button>
</div>
`;
const display = contentEl.querySelector(`#calc-display-${instanceId}`);
const operators = contentEl.querySelectorAll('.buttons .operator');
let currentValue = '0';
let operator = null;
let previousValue = null;
let waitingForOperand = false;
const clearActiveOperator = () => operators.forEach(op => op.classList.remove('active'));
contentEl.querySelector('.buttons').addEventListener('click', (e) => {
if (e.target.tagName !== 'BUTTON') return;
const value = e.target.dataset.val;
const isOperator = e.target.classList.contains('operator');
if ('0123456789'.includes(value)) {
if (waitingForOperand) {
currentValue = value;
waitingForOperand = false;
} else {
currentValue = currentValue === '0' ? value : currentValue + value;
}
clearActiveOperator();
} else if (value === '.') {
if (!currentValue.includes('.')) currentValue += '.';
} else if (isOperator) {
if (operator && !waitingForOperand) calculate();
previousValue = currentValue;
operator = value;
waitingForOperand = true;
clearActiveOperator();
e.target.classList.add('active');
} else if (value === '=') {
calculate();
clearActiveOperator();
} else if (value === 'C') {
currentValue = '0'; operator = null; previousValue = null; waitingForOperand = false;
clearActiveOperator();
}
display.textContent = currentValue.length > 9 ? parseFloat(currentValue).toExponential(3) : currentValue;
});
function calculate() {
if (operator === null || waitingForOperand) return;
const prev = parseFloat(previousValue);
const curr = parseFloat(currentValue);
let result = 0;
if (operator === '+') result = prev + curr;
else if (operator === '-') result = prev - curr;
else if (operator === '*') result = prev * curr;
else if (operator === '/') result = prev / curr;
currentValue = String(result);
operator = null;
previousValue = null;
waitingForOperand = false;
}
}
}
};
// --- OS Dialog System ---
function showOSDialog(options) {
return new Promise((resolve) => {
osDialogTitle.textContent = options.title || 'Message';
osDialogContent.innerHTML = ''; // Clear previous content
if (options.htmlContent) {
osDialogContent.innerHTML = options.htmlContent;
} else {
const messagePara = document.createElement('p');
messagePara.textContent = options.message || '';
osDialogContent.appendChild(messagePara);
}
let inputField = null;
if (options.type === 'prompt') {
inputField = document.createElement('input');
inputField.type = options.inputType || 'text';
inputField.value = options.defaultValue || '';
osDialogContent.appendChild(inputField);
}
osDialogActions.innerHTML = '';
const closeDialog = (value) => {
osDialogOverlay.classList.add('hidden');
resolve(value);
};
options.buttons.forEach(btnConfig => {
const button = document.createElement('button');
button.textContent = btnConfig.label;
button.className = btnConfig.class || '';
button.onclick = () => {
let value = btnConfig.value;
if (options.type === 'prompt' && (value === true || value === undefined)) {
value = inputField.value;
}
closeDialog(value);
};
osDialogActions.appendChild(button);
});
osDialogOverlay.classList.remove('hidden');
// Focus the most logical element
const primaryButton = osDialogActions.querySelector('button.primary') || osDialogActions.querySelector('button.danger') || osDialogActions.querySelector('button');
if (inputField) {
setTimeout(() => inputField.focus(), 50);
} else if (primaryButton) {
setTimeout(() => primaryButton.focus(), 50);
}
});
}
function showOSAlert(message, title = 'Alert') {
return showOSDialog({
title: title,
message: message,
type: 'alert',
buttons: [{ label: 'OK', value: true, class: 'primary' }]
});
}
function showOSConfirm(message, title = 'Confirm') {
return showOSDialog({
title: title,
message: message,
type: 'confirm',
buttons: [
{ label: 'Cancel', value: false },
{ label: 'OK', value: true, class: 'primary' }
]
});
}
function showOSConfirmDanger(message, title = 'Confirm Action') {
return showOSDialog({
title: title,
message: message,
type: 'confirm',
buttons: [
{ label: 'Cancel', value: false },
{ label: 'Confirm', value: true, class: 'danger' }
]
});
}
function showOSPrompt(message, title = 'Input', defaultValue = '', inputType = 'text') {
return showOSDialog({
title: title,
message: message,
type: 'prompt',
inputType: inputType,
defaultValue: defaultValue,
buttons: [
{ label: 'Cancel', value: null },
{ label: 'OK', value: true, class: 'primary' }
]
});
}
function showAddWidgetDialog() {
let listHtml = '<ul class="os-dialog-selection-list">';
const widgetIcons = {
'digitalClock': 'fa-hourglass-half',
'quickNote': 'fa-note-sticky',
'systemMonitor': 'fa-microchip',
'imageFrame': 'fa-image',
'todoList': 'fa-list-check',
'miniCalculator': 'fa-calculator'
};
for (const type in widgets) {
const iconClass = widgetIcons[type] || 'fa-puzzle-piece';
listHtml += `<li data-widget-type="${type}"><i class="fa-solid ${iconClass}"></i> ${widgets[type].name}</li>`;
}
listHtml += '</ul>';
showOSDialog({
title: 'Add Widget',
htmlContent: listHtml,
buttons: [{ label: 'Cancel', value: null }]
});
const listElement = osDialogOverlay.querySelector('.os-dialog-selection-list');
if (listElement) {
listElement.addEventListener('click', (e) => {
const li = e.target.closest('li[data-widget-type]');
if (li) {
const widgetType = li.dataset.widgetType;
createWidget(widgetType);
// Manually close the dialog
osDialogOverlay.classList.add('hidden');
}
});
}
}
// --- Helper: Get Icon HTML ---
function getIconHtml(appConfig, size = 'large') {
const iconContent = appConfig.icon || '<i class="fa-solid fa-puzzle-piece"></i>';
const imgSize = size === 'small' ? '16' : '32';
const fontSize = size === 'small' ? '1.1em' : '28px';
const containerSize = size === 'small' ? '1.2em' : '32px';
if (appConfig.iconPath && appConfig.iconPath.toLowerCase().endsWith('.svg')) {
return `<img src="${appConfig.iconPath}" alt="${appConfig.name}" width="${imgSize}" height="${imgSize}">`;
} else if (appConfig.iconPath) {
return `<span class="icon" style="font-size: ${fontSize}; width: ${containerSize}; height: ${containerSize};">${appConfig.iconPath}</span>`;
} else if (typeof iconContent === 'string' && iconContent.trim().toLowerCase().startsWith('<svg')) { // <-- ADD THIS CONDITION
return `<span class="icon" style="font-size: ${fontSize}; width: ${containerSize}; height: ${containerSize};">${iconContent}</span>`;
} else if (typeof iconContent === 'string' && iconContent.startsWith('<i')) {
return `<span class="icon" style="font-size: ${fontSize}; width: ${containerSize}; height: ${containerSize};">${iconContent}</span>`;
} else if (typeof iconContent === 'string' && (iconContent.includes('/') || iconContent.startsWith('data:image'))) {
return `<img src="${iconContent}" alt="${appConfig.name}" width="${imgSize}" height="${imgSize}">`;
} else {
return `<span class="icon" style="font-size: ${fontSize}; width: ${containerSize}; height: ${containerSize};"><i class="fa-solid fa-puzzle-piece"></i></span>`;
}
}
// --- Application Definitions ---
let apps = {
// -----------------------------------------------------------------------------
// --- Calculator App ---
// -----------------------------------------------------------------------------
'Calculator': { name: 'Calculator', icon: '<i class="fa-solid fa-calculator"></i>', isCustom: false, init: (contentEl, windowId) => {
contentEl.style.padding = '0';
contentEl.innerHTML = `<div class="calculator-app"><div class="calculator"><div class="display" id="calc-display-${windowId}"><span class="pending-operator" id="calc-op-${windowId}"></span><span class="main-display">0</span></div><button class="special" data-value="clear">AC</button><button class="special" data-value="negate">+/-</button><button class="special" data-value="%">%</button><button class="operator" data-value="/">÷</button><button data-value="7">7</button><button data-value="8">8</button><button data-value="9">9</button><button class="operator" data-value="*">×</button><button data-value="4">4</button><button data-value="5">5</button><button data-value="6">6</button><button class="operator" data-value="-">−</button><button data-value="1">1</button><button data-value="2">2</button><button data-value="3">3</button><button class="operator" data-value="+">+</button><button data-value="0">0</button><button data-value=".">.</button><button class="operator" data-value="=">=</button></div></div>`;
const display = contentEl.querySelector(`#calc-display-${windowId} .main-display`); const opIndicator = contentEl.querySelector(`#calc-op-${windowId}`); const calcContainer = contentEl.querySelector('.calculator'); let currentValue = '0', previousValue = null, operator = null, waitingForOperand = false;
function updateDisplay() { let formattedValue = currentValue; try { if (formattedValue !== 'Error' && formattedValue !== 'Infinity' && formattedValue !== '-Infinity') { const num = parseFloat(formattedValue); if (!isNaN(num)) { if (Math.abs(num) > 1e15 || (Math.abs(num) < 1e-9 && num !== 0)) formattedValue = num.toExponential(6); else if (formattedValue.length > 15) { formattedValue = String(num); if(formattedValue.length > 15) formattedValue = num.toPrecision(10); }}}} catch {} display.textContent = formattedValue; const clearButton = calcContainer.querySelector('button[data-value="clear"]'); if (clearButton) clearButton.textContent = (currentValue === '0' || waitingForOperand) && previousValue === null ? 'AC' : 'C'; opIndicator.textContent = operator && waitingForOperand && operator !== '=' ? operator : ''; }
function calculate(val1, val2, op) { const num1 = parseFloat(val1); const num2 = parseFloat(val2); if (isNaN(num1) || isNaN(num2)) return 'Error'; switch(op) { case '+': return num1 + num2; case '-': return num1 - num2; case '*': return num1 * num2; case '/': return num2 === 0 ? 'Error' : num1 / num2; default: return num2; } }
calcContainer.addEventListener('click', (e) => { if (e.target.tagName !== 'BUTTON') return; const value = e.target.dataset.value; const type = e.target.classList.contains('operator') ? 'operator' : e.target.classList.contains('special') ? 'special' : 'number'; if (value === 'clear') { if (currentValue !== '0' && !waitingForOperand && calcContainer.querySelector('button[data-value="clear"]').textContent === 'C') currentValue = '0'; else { currentValue = '0'; previousValue = null; operator = null; waitingForOperand = false; } } else if (value === 'negate') { if (currentValue !== '0' && currentValue !== 'Error') currentValue = String(parseFloat(currentValue) * -1); } else if (value === '%') { if (currentValue !== 'Error') { currentValue = String(parseFloat(currentValue) / 100); waitingForOperand = false; } } else if (value === '.') { if (currentValue === 'Error') return; if (waitingForOperand) { currentValue = '0.'; waitingForOperand = false; } else if (!currentValue.includes('.')) currentValue += '.'; } else if (type === 'number') { if (currentValue === 'Error') return; if (waitingForOperand || currentValue === '0') { currentValue = value; waitingForOperand = false; } else { if (currentValue.length < 15) currentValue += value; } } else if (type === 'operator') { if (currentValue === 'Error' && value !== '=') { currentValue = '0'; previousValue = null; operator = null; waitingForOperand = false; } if (value === '=') { if (operator && previousValue !== null) { const result = calculate(previousValue, currentValue, operator); currentValue = String(result); previousValue = null; operator = null; waitingForOperand = true; } } else { if (operator && previousValue !== null && !waitingForOperand) { const result = calculate(previousValue, currentValue, operator); currentValue = String(result); previousValue = currentValue; } else { previousValue = currentValue; } operator = value; waitingForOperand = true; } } if (currentValue.length > 18 && !currentValue.includes('e') && currentValue !== 'Error') currentValue = 'Error'; updateDisplay(); calcContainer.querySelectorAll('.operator').forEach(btn => btn.classList.remove('active')); if (operator && waitingForOperand && operator !== '=') { const opButton = calcContainer.querySelector(`button[data-value="${CSS.escape(operator)}"]`); if (opButton) opButton.classList.add('active'); } }); updateDisplay();
} },
// -----------------------------------------------------------------------------
// --- TextPad App (Enhanced with Font Selection) ---
// -----------------------------------------------------------------------------
'TextPad': { name: 'Text Pad', icon: '<i class="fa-regular fa-file-lines"></i>', isCustom: false, init: (contentEl, windowId) => {
contentEl.style.padding = '0'; contentEl.style.overflow = 'hidden';
// Added font family selector to the toolbar
contentEl.innerHTML = `<div class="textpad-app">
<div class="textpad-toolbar">
<button id="textpad-save-${windowId}" title="Save As..."><i class="fa-solid fa-save"></i> Save</button>
<div class="separator"></div>
<label for="textpad-font-family-${windowId}" style="margin: 0 4px 0 8px; font-size: 0.9em;">Font:</label>
<select id="textpad-font-family-${windowId}" title="Change Font Family" style="padding: 4px 6px; border-radius: 3px; border: 1px solid var(--border-primary); background-color: var(--paint-toolbar-button-bg); color: var(--paint-toolbar-text); cursor: pointer; max-width: 150px; font-size: 0.9em;"></select>
<div class="font-size-controls" style="margin-left: auto; display: flex; align-items: center; gap: 4px;"> <!-- Ensured flex for alignment -->
<span style="font-size: 0.9em;">Size:</span>
<button id="textpad-font-dec-${windowId}" title="Decrease Font Size"><i class="fa-solid fa-minus"></i></button>
<span id="textpad-font-size-indicator-${windowId}" style="font-size: 0.9em; min-width: 30px; text-align: center;">16px</span>
<button id="textpad-font-inc-${windowId}" title="Increase Font Size"><i class="fa-solid fa-plus"></i></button>
</div>
</div>
<div class="textpad-content"><textarea id="textpad-textarea-${windowId}" spellcheck="false" placeholder="Start typing..."></textarea></div>
</div>`;
const textarea = contentEl.querySelector(`#textpad-textarea-${windowId}`);
const saveButton = contentEl.querySelector(`#textpad-save-${windowId}`);
const fontIncButton = contentEl.querySelector(`#textpad-font-inc-${windowId}`);
const fontDecButton = contentEl.querySelector(`#textpad-font-dec-${windowId}`);
const fontSizeIndicator = contentEl.querySelector(`#textpad-font-size-indicator-${windowId}`);
const fontFamilySelect = contentEl.querySelector(`#textpad-font-family-${windowId}`);
const TEXTPAD_STYLE_KEY = 'textpad_style_v1';
const FONT_FAMILIES = [
{ name: "System UI", value: "-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif" },
{ name: "Arial", value: "Arial, Helvetica, sans-serif" },
{ name: "Verdana", value: "Verdana, Geneva, sans-serif" },
{ name: "Tahoma", value: "Tahoma, Geneva, sans-serif" },
{ name: "Times New Roman", value: "\"Times New Roman\", Times, serif" },
{ name: "Georgia", value: "Georgia, serif" },
{ name: "Courier New", value: "\"Courier New\", Courier, monospace" },
{ name: "Lucida Console", value: "\"Lucida Console\", Monaco, monospace" },
{ name: "Monospace", value: "monospace" } // Default fallback
];
const DEFAULT_TEXTPAD_FONT_FAMILY = "monospace"; // Actual initial default for editor
const DEFAULT_TEXTPAD_FONT_SIZE = 16;
// Populate font family select
FONT_FAMILIES.forEach(font => {
const option = document.createElement('option');
option.value = font.value;
option.textContent = font.name;
fontFamilySelect.appendChild(option);
});
let currentStyle = {
fontFamily: DEFAULT_TEXTPAD_FONT_FAMILY,
fontSize: DEFAULT_TEXTPAD_FONT_SIZE
};
function loadStyle() {
const storedStyle = localStorage.getItem(TEXTPAD_STYLE_KEY);
if (storedStyle) {
try {
const parsedStyle = JSON.parse(storedStyle);
currentStyle.fontFamily = parsedStyle.fontFamily || DEFAULT_TEXTPAD_FONT_FAMILY;
currentStyle.fontSize = parseInt(parsedStyle.fontSize, 10) || DEFAULT_TEXTPAD_FONT_SIZE;
if (!FONT_FAMILIES.some(f => f.value === currentStyle.fontFamily)) { // Ensure font is valid
currentStyle.fontFamily = DEFAULT_TEXTPAD_FONT_FAMILY;
}
} catch (e) {
console.error("Error parsing TextPad style from localStorage", e);
currentStyle.fontFamily = DEFAULT_TEXTPAD_FONT_FAMILY;
currentStyle.fontSize = DEFAULT_TEXTPAD_FONT_SIZE;
}
}
applyStyle();
}
function saveStyle() {
try {
localStorage.setItem(TEXTPAD_STYLE_KEY, JSON.stringify(currentStyle));
} catch (e) {
console.error("Error saving TextPad style to localStorage", e);
if (window.showOSAlert) { // Check if showOSAlert is available
window.showOSAlert("Could not save TextPad style settings. Browser storage might be full.", "Save Error");
}
}
}
function applyStyle() {
textarea.style.fontFamily = currentStyle.fontFamily;
textarea.style.fontSize = `${currentStyle.fontSize}px`;
fontSizeIndicator.textContent = `${currentStyle.fontSize}px`;
fontFamilySelect.value = currentStyle.fontFamily;
}
fontIncButton.addEventListener('click', () => {
currentStyle.fontSize = Math.min(72, currentStyle.fontSize + 2);
applyStyle();
saveStyle();
});
fontDecButton.addEventListener('click', () => {
currentStyle.fontSize = Math.max(8, currentStyle.fontSize - 2);
applyStyle();
saveStyle();
});
fontFamilySelect.addEventListener('change', () => {
currentStyle.fontFamily = fontFamilySelect.value;
applyStyle();
saveStyle();
});
saveButton.addEventListener('click', async () => {
const textContent = textarea.value;
const defaultFilename = "textpad_content.txt";
const filename = await showOSDialog({ // Assuming showOSDialog is globally available
title: 'Save Text File', message: 'Save file as:', type: 'prompt', defaultValue: defaultFilename,
buttons: [ { label: 'Cancel', value: null }, { label: 'Save', value: true, class: 'success' } ]
});
if (filename === null || filename.trim() === "") return;
const blob = new Blob([textContent], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a'); a.href = url; a.download = filename.endsWith('.txt') ? filename : filename + '.txt';
a.style.display = 'none'; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url);
});
// Load and apply initial style
loadStyle();
} },
// -----------------------------------------------------------------------------
// --- Paint App (New) ---
// -----------------------------------------------------------------------------
'Paint': {
name: 'Paint',
icon: '<i class="fa-solid fa-paintbrush"></i>',
isCustom: false,
init: (contentEl, windowId) => {
contentEl.style.padding = '0';
contentEl.style.overflow = 'hidden';
contentEl.innerHTML = `
<div class="paint-app-container">
<div class="paint-toolbar top-toolbar">
<button id="save-paint-${windowId}" title="Save Image"><i class="fa-solid fa-save"></i> Save</button>
<button id="resize-canvas-${windowId}" title="Resize Canvas"><i class="fa-solid fa-arrows-up-down-left-right"></i> Resize</button>
<button id="clear-canvas-${windowId}" title="Clear Canvas"><i class="fa-solid fa-trash-can"></i> Clear</button>
<div class="separator"></div>
<button id="undo-${windowId}" title="Undo (Ctrl+Z)" disabled><i class="fa-solid fa-undo"></i></button>
<button id="redo-${windowId}" title="Redo (Ctrl+Y)" disabled><i class="fa-solid fa-redo"></i></button>
<div class="separator"></div>
<!-- Brush Tools -->
<button class="tool active" data-tool="pencil" title="Pencil (Round)"><i class="fa-solid fa-pencil"></i></button>
<button class="tool" data-tool="pixelBrush" title="Pixel Brush (Square)"><i class="fa-solid fa-vector-square"></i></button>
<button class="tool" data-tool="sprayBrush" title="Spray Brush"><i class="fa-solid fa-spray-can-sparkles"></i></button>
<button class="tool" data-tool="patternBrush" title="Pattern Brush"><i class="fa-solid fa-border-all"></i></button>
<button class="tool" data-tool="crayonBrush" title="Crayon Brush"><i class="fa-solid fa-palette"></i></button>
<button class="tool" data-tool="markerBrush" title="Marker Brush"><i class="fa-solid fa-highlighter"></i></button>
<div class="separator"></div>
<button class="tool" data-tool="eraser" title="Eraser"><i class="fa-solid fa-eraser"></i></button>
<button class="tool" data-tool="fill" title="Fill Bucket"><i class="fa-solid fa-fill-drip"></i></button>
<div class="separator"></div>
<!-- Shape Tools -->
<button class="tool" data-tool="line" title="Line"><i class="fa-solid fa-minus"></i></button>
<button class="tool" data-tool="rect" title="Rectangle"><i class="fa-regular fa-square"></i></button>
<button class="tool" data-tool="circle" title="Circle"><i class="fa-regular fa-circle"></i></button>
<input type="checkbox" id="fill-shape-${windowId}" class="tool-option-toggle">
<label for="fill-shape-${windowId}" title="Fill Shape"><i class="fa-solid fa-fill"></i> Fill</label>
<div class="separator"></div>
<!-- Color and Size -->
<label for="color-${windowId}">Color:</label>
<input type="color" id="color-${windowId}" value="#000000">
<label for="size-${windowId}">Size:</label>
<input type="range" id="size-${windowId}" min="1" max="50" value="5">
<span class="size-indicator" id="size-indicator-${windowId}">5</span>
</div>
<div class="paint-main-content">
<div class="paint-canvas-area" id="canvas-area-${windowId}">
<canvas id="canvas-${windowId}" class="paint-canvas"></canvas>
<canvas id="overlay-canvas-${windowId}" class="paint-overlay-canvas"></canvas>
</div>
<div class="paint-color-palette" id="color-palette-${windowId}"></div>
</div>
</div>`;
const canvas = contentEl.querySelector(`#canvas-${windowId}`);
const ctx = canvas.getContext('2d', { willReadFrequently: true });
const overlayCanvas = contentEl.querySelector(`#overlay-canvas-${windowId}`);
const overlayCtx = overlayCanvas.getContext('2d');
const toolbar = contentEl.querySelector('.top-toolbar');
const colorPalette = contentEl.querySelector(`#color-palette-${windowId}`);
const sizeSlider = contentEl.querySelector(`#size-${windowId}`);
const colorPicker = contentEl.querySelector(`#color-${windowId}`);
const sizeIndicator = contentEl.querySelector(`#size-indicator-${windowId}`);
const fillShapeCheckbox = contentEl.querySelector(`#fill-shape-${windowId}`);
const undoButton = contentEl.querySelector(`#undo-${windowId}`);
const redoButton = contentEl.querySelector(`#redo-${windowId}`);
let isDrawing = false, isDrawingShape = false;
let currentTool = 'pencil', currentColor = '#000000', currentSize = 5;
let lastX, lastY, startX, startY;
let isFillingShapes = false;
let canvasWidth = 500, canvasHeight = 400;
let history = [], historyIndex = -1;
function initialize() {
setupColorPalette();
setCanvasSize(canvasWidth, canvasHeight, false);
saveState();
updateUndoRedoButtons();
setActiveTool('pencil');
canvas.addEventListener('mousedown', handlePaintStart);
canvas.addEventListener('mousemove', handlePaintMove);
canvas.addEventListener('mouseup', handlePaintEnd);
canvas.addEventListener('mouseleave', handlePaintLeave);
toolbar.addEventListener('click', handleToolbarClick);
fillShapeCheckbox.addEventListener('change', (e) => { isFillingShapes = e.target.checked; });
colorPicker.addEventListener('input', (e) => { setColor(e.target.value); });
sizeSlider.addEventListener('input', (e) => { currentSize = e.target.value; sizeIndicator.textContent = currentSize; });
colorPalette.addEventListener('click', handlePaletteClick);
const windowEl = openWindows[windowId]?.element;
if (windowEl) {
const handleKeyDown = (e) => {
if (e.ctrlKey || e.metaKey) {
if (e.key === 'z') { e.preventDefault(); undo(); }
else if (e.key === 'y') { e.preventDefault(); redo(); }
}
};
windowEl.addEventListener('keydown', handleKeyDown);
if (openWindows[windowId]) {
openWindows[windowId].cleanup = () => { windowEl.removeEventListener('keydown', handleKeyDown); };
}
}
}
function saveState() {
if (historyIndex < history.length - 1) history.splice(historyIndex + 1);
history.push(canvas.toDataURL());
historyIndex++;
if (history.length > 30) { history.shift(); historyIndex--; }
updateUndoRedoButtons();
}
function undo() { if (historyIndex > 0) { historyIndex--; restoreState(); } }
function redo() { if (historyIndex < history.length - 1) { historyIndex++; restoreState(); } }
function restoreState() {
const img = new Image();
img.onload = () => { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0); };
img.src = history[historyIndex];
updateUndoRedoButtons();
}
function updateUndoRedoButtons() {
undoButton.disabled = historyIndex <= 0;
redoButton.disabled = historyIndex >= history.length - 1;
}
function setCanvasSize(width, height, preserveContent = true) {
let tempCanvas = null;
if (preserveContent && canvas.width > 0) {
tempCanvas = document.createElement('canvas');
tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
tempCanvas.getContext('2d').drawImage(canvas, 0, 0);
}
canvasWidth = width; canvasHeight = height;
canvas.width = canvasWidth; canvas.height = canvasHeight;
overlayCanvas.width = canvasWidth; overlayCanvas.height = canvasHeight;
const bg = getComputedStyle(document.documentElement).getPropertyValue('--paint-canvas-bg-dark').trim() || '#ffffff';
ctx.fillStyle = bg; ctx.fillRect(0, 0, canvas.width, canvas.height);
if (tempCanvas) ctx.drawImage(tempCanvas, 0, 0);
}
async function promptForCanvasSize() {
const newWidth = await showOSPrompt('Enter new canvas width (px):', 'Resize Canvas', canvasWidth);
if (newWidth === null || isNaN(newWidth) || newWidth <= 0) return;
const newHeight = await showOSPrompt('Enter new canvas height (px):', 'Resize Canvas', canvasHeight);
if (newHeight === null || isNaN(newHeight) || newHeight <= 0) return;
setCanvasSize(parseInt(newWidth), parseInt(newHeight), true);
saveState();
}
function handlePaintStart(e) {
e.preventDefault(); // <-- FIX: Prevents the browser from dragging the canvas
isDrawing = true;
const pos = getMousePos(e);
[startX, lastX] = [pos.x, pos.x];
[startY, lastY] = [pos.y, pos.y];
ctx.lineWidth = currentSize; ctx.strokeStyle = currentColor;
ctx.fillStyle = currentColor; ctx.lineJoin = 'round';
ctx.globalCompositeOperation = (currentTool === 'eraser') ? 'destination-out' : 'source-over';