-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesktop-items.js
More file actions
658 lines (592 loc) · 20.3 KB
/
desktop-items.js
File metadata and controls
658 lines (592 loc) · 20.3 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
(function(window) {
'use strict';
const DESKTOP_ITEMS_STORAGE_KEY = 'desktopItems_win9x_v1';
const DESKTOP_ICON_POSITIONS_KEY = 'desktopIconPositions_win9x_style_v2';
const SYSTEM_SHORTCUTS_INITIALIZED_KEY = 'desktopSystemShortcutsInitialized_win9x_v2';
const NEW_MENU_TYPES = ['folder', 'shortcut', 'textDocument', 'bitmapImage', 'waveSound'];
const STATIC_DESKTOP_APPS = [
{ appId: 'recycleBin', name: 'Recycle Bin', icon: './recycle_bin_empty-0.png' },
];
const SYSTEM_SHORTCUTS = [
{ id: 'system-shortcut-network-neighborhood', targetAppId: 'networkExplorer', name: 'Network Neighborhood', icon: './network_normal_two_pcs-0.png' },
{ id: 'system-shortcut-notepad', targetAppId: 'notepad', name: 'Notepad', icon: './notepad-0.png' },
{ id: 'system-shortcut-calculator', targetAppId: 'calculator', name: 'Calculator', icon: './calculator-0.png' },
{ id: 'system-shortcut-internet-browser', targetAppId: 'internetBrowser', name: 'Internet Browser', icon: './search_web-0.png' },
{ id: 'system-shortcut-internet-explorer', targetAppId: 'internetExplorer', name: 'Internet Explorer', icon: './msie2-0.png' },
{ id: 'system-shortcut-netscape-navigator', targetAppId: 'netscapeNavigator', name: 'Netscape Navigator', icon: './n2-2.png' },
{ id: 'system-shortcut-payment-tool', targetAppId: 'paymentTool', name: 'BrowserBox HQ', icon: './tree-0.png' },
];
const TYPE_REGISTRY = {
folder: {
label: 'Folder',
defaultName: 'New Folder',
icon: './directory_closed_cool-0.png',
createInitialData: () => ({}),
open: (item) => {
if (window.Win9xSystem && typeof window.Win9xSystem.openApplication === 'function') {
void window.Win9xSystem.openApplication('folderViewer', {
folderId: item.id,
});
}
},
},
shortcut: {
label: 'Shortcut',
defaultName: 'New Shortcut',
icon: './file_win_shortcut-0.png',
createInitialData: () => ({ targetUrl: 'https://browserbox.io' }),
open: (item) => {
if (window.Win9xSystem && typeof window.Win9xSystem.openApplication === 'function') {
if (typeof item.targetAppId === 'string' && item.targetAppId.trim()) {
void window.Win9xSystem.openApplication(item.targetAppId.trim());
} else {
void window.Win9xSystem.openApplication('internetExplorer', {
navigateToUrl: item.targetUrl || 'https://browserbox.io',
});
}
}
},
},
textDocument: {
label: 'Text Document',
defaultName: 'New Text Document.txt',
icon: './document-0.png',
createInitialData: () => ({ content: '' }),
open: (item) => {
if (window.Win9xSystem && typeof window.Win9xSystem.openApplication === 'function') {
void window.Win9xSystem.openApplication('notepad', {
virtualFileId: item.id,
virtualFileName: item.name,
virtualFileContent: typeof item.content === 'string' ? item.content : '',
});
}
},
},
bitmapImage: {
label: 'Bitmap Image',
defaultName: 'New Bitmap Image.bmp',
icon: './paint_file-2.png',
createInitialData: () => ({
dataUrl: createDefaultBitmapDataUrl(),
mimeType: 'image/bmp',
}),
open: (item) => {
if (window.Win9xSystem && typeof window.Win9xSystem.openApplication === 'function') {
void window.Win9xSystem.openApplication('imageViewer', {
imageUrl: typeof item.dataUrl === 'string' ? item.dataUrl : '',
fileName: item.name || 'Bitmap Image',
});
}
},
},
waveSound: {
label: 'Wave Sound',
defaultName: 'New Wave Sound.wav',
icon: './loudspeaker_wave-0.png',
createInitialData: () => ({
dataUrl: createDefaultWaveDataUrl(),
mimeType: 'audio/wav',
}),
open: (item) => {
if (window.Win9xSystem && typeof window.Win9xSystem.openApplication === 'function') {
void window.Win9xSystem.openApplication('wavePlayer', {
audioUrl: typeof item.dataUrl === 'string' ? item.dataUrl : '',
fileName: item.name || 'Wave Sound',
});
}
},
},
};
let desktopItems = [];
function emitItemsChanged(action, payload = null) {
try {
window.dispatchEvent(new CustomEvent('win9x:desktop-items-changed', {
detail: { action, payload },
}));
} catch (error) {
console.error('DesktopItems: failed to emit change event:', error);
}
}
function createDefaultBitmapDataUrl() {
const canvas = document.createElement('canvas');
canvas.width = 32;
canvas.height = 32;
const context = canvas.getContext('2d');
if (!context) {
return '';
}
context.fillStyle = '#d0d0d0';
context.fillRect(0, 0, 32, 32);
context.fillStyle = '#b0b0b0';
context.fillRect(0, 0, 16, 16);
context.fillRect(16, 16, 16, 16);
context.strokeStyle = '#707070';
context.strokeRect(0.5, 0.5, 31, 31);
context.fillStyle = '#204a87';
context.fillRect(7, 10, 18, 12);
context.fillStyle = '#ffffff';
context.font = 'bold 8px sans-serif';
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillText('BMP', 16, 16);
return canvas.toDataURL('image/png');
}
function createDefaultWaveDataUrl() {
const sampleRate = 8000;
const durationSeconds = 0.12;
const sampleCount = Math.floor(sampleRate * durationSeconds);
const dataSize = sampleCount * 2;
const buffer = new ArrayBuffer(44 + dataSize);
const view = new DataView(buffer);
function writeAscii(offset, text) {
for (let i = 0; i < text.length; i += 1) {
view.setUint8(offset + i, text.charCodeAt(i));
}
}
writeAscii(0, 'RIFF');
view.setUint32(4, 36 + dataSize, true);
writeAscii(8, 'WAVE');
writeAscii(12, 'fmt ');
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
view.setUint16(22, 1, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, sampleRate * 2, true);
view.setUint16(32, 2, true);
view.setUint16(34, 16, true);
writeAscii(36, 'data');
view.setUint32(40, dataSize, true);
const frequency = 660;
for (let i = 0; i < sampleCount; i += 1) {
const time = i / sampleRate;
const envelope = Math.max(0, 1 - (i / sampleCount));
const sample = Math.sin(2 * Math.PI * frequency * time) * 0.35 * envelope;
const clamped = Math.max(-1, Math.min(1, sample));
view.setInt16(44 + (i * 2), Math.round(clamped * 32767), true);
}
let binary = '';
const bytes = new Uint8Array(buffer);
for (let i = 0; i < bytes.length; i += 1) {
binary += String.fromCharCode(bytes[i]);
}
return `data:audio/wav;base64,${window.btoa(binary)}`;
}
function generateItemId() {
return `item-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 9)}`;
}
function normalizeParentId(parentId) {
return typeof parentId === 'string' && parentId.trim()
? parentId.trim()
: null;
}
function loadItems() {
try {
const raw = localStorage.getItem(DESKTOP_ITEMS_STORAGE_KEY);
if (!raw) {
desktopItems = [];
return;
}
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) {
desktopItems = [];
return;
}
desktopItems = parsed
.filter((item) => (
item &&
typeof item.id === 'string' &&
typeof item.type === 'string' &&
typeof item.name === 'string' &&
TYPE_REGISTRY[item.type]
))
.map((item) => ({
...item,
parentId: normalizeParentId(item.parentId),
}));
} catch (error) {
console.error('DesktopItems: failed to load from storage:', error);
desktopItems = [];
}
}
function saveItems() {
try {
localStorage.setItem(DESKTOP_ITEMS_STORAGE_KEY, JSON.stringify(desktopItems));
} catch (error) {
console.error('DesktopItems: failed to save to storage:', error);
}
}
function migrateLegacyBuiltInPositionsToShortcuts(shortcutsToCreate) {
if (!Array.isArray(shortcutsToCreate) || shortcutsToCreate.length === 0) {
return;
}
try {
const raw = localStorage.getItem(DESKTOP_ICON_POSITIONS_KEY);
if (!raw) {
return;
}
const positions = JSON.parse(raw);
if (!positions || typeof positions !== 'object') {
return;
}
let changed = false;
shortcutsToCreate.forEach((shortcutSpec) => {
const legacyKey = shortcutSpec.targetAppId;
const nextKey = `item:${shortcutSpec.id}`;
if (!legacyKey || positions[nextKey] || !positions[legacyKey]) {
return;
}
positions[nextKey] = positions[legacyKey];
delete positions[legacyKey];
changed = true;
});
if (changed) {
localStorage.setItem(DESKTOP_ICON_POSITIONS_KEY, JSON.stringify(positions));
}
} catch (error) {
console.error('DesktopItems: failed to migrate legacy icon positions:', error);
}
}
function ensureSystemShortcutsInitialized() {
const alreadyInitialized = localStorage.getItem(SYSTEM_SHORTCUTS_INITIALIZED_KEY) === '1';
if (alreadyInitialized) {
return;
}
const existingById = new Set(desktopItems.map((item) => item.id));
const existingByTargetAppId = new Set(
desktopItems
.filter((item) => item && item.type === 'shortcut' && typeof item.targetAppId === 'string')
.map((item) => item.targetAppId.trim())
.filter(Boolean)
);
const shortcutsToCreate = [];
const now = Date.now();
let changed = false;
SYSTEM_SHORTCUTS.forEach((shortcutSpec, index) => {
const targetAppId = (shortcutSpec.targetAppId || '').trim();
if (!targetAppId) {
return;
}
if (existingById.has(shortcutSpec.id) || existingByTargetAppId.has(targetAppId)) {
return;
}
const createdShortcut = {
id: shortcutSpec.id,
type: 'shortcut',
name: getUniqueName(shortcutSpec.name),
icon: shortcutSpec.icon,
parentId: null,
createdAt: now + index,
targetAppId,
targetUrl: '',
isSystemShortcut: true,
};
desktopItems.push(createdShortcut);
existingById.add(shortcutSpec.id);
existingByTargetAppId.add(targetAppId);
shortcutsToCreate.push(shortcutSpec);
changed = true;
});
migrateLegacyBuiltInPositionsToShortcuts(shortcutsToCreate);
if (changed) {
saveItems();
}
try {
localStorage.setItem(SYSTEM_SHORTCUTS_INITIALIZED_KEY, '1');
} catch (error) {
console.error('DesktopItems: failed to persist shortcut initialization state:', error);
}
}
function syncSystemShortcutMetadata() {
const byTargetAppId = new Map(
SYSTEM_SHORTCUTS
.filter((shortcutSpec) => shortcutSpec && typeof shortcutSpec.targetAppId === 'string')
.map((shortcutSpec) => [shortcutSpec.targetAppId.trim(), shortcutSpec])
);
let changed = false;
desktopItems.forEach((item) => {
if (!item || item.type !== 'shortcut' || typeof item.targetAppId !== 'string') {
return;
}
const shortcutSpec = byTargetAppId.get(item.targetAppId.trim());
if (!shortcutSpec) {
return;
}
if (item.isSystemShortcut !== true) {
item.isSystemShortcut = true;
changed = true;
}
if (typeof shortcutSpec.name === 'string' && item.name !== shortcutSpec.name) {
item.name = shortcutSpec.name;
changed = true;
}
if (typeof shortcutSpec.icon === 'string' && item.icon !== shortcutSpec.icon) {
item.icon = shortcutSpec.icon;
changed = true;
}
});
if (changed) {
saveItems();
}
}
function getUniqueName(baseName, excludeId = null) {
const normalized = new Set(
desktopItems
.filter((item) => item.id !== excludeId)
.map((item) => item.name.trim().toLowerCase())
);
if (!normalized.has(baseName.trim().toLowerCase())) {
return baseName;
}
let suffix = 2;
let candidate = `${baseName} (${suffix})`;
while (normalized.has(candidate.trim().toLowerCase())) {
suffix += 1;
candidate = `${baseName} (${suffix})`;
}
return candidate;
}
function createDesktopIconElement(item) {
const iconEl = document.createElement('div');
iconEl.className = 'desktop-icon';
if (item.kind === 'static-app') {
iconEl.dataset.appId = item.appId;
} else {
iconEl.dataset.desktopItemId = item.id;
iconEl.dataset.itemType = item.type;
if (item.type === 'shortcut' && typeof item.targetAppId === 'string' && item.targetAppId.trim()) {
const targetAppId = item.targetAppId.trim();
iconEl.dataset.targetAppId = targetAppId;
iconEl.dataset.appId = targetAppId;
}
}
const img = document.createElement('img');
img.src = item.icon || TYPE_REGISTRY[item.type]?.icon || './html-0.png';
img.alt = item.name;
iconEl.appendChild(img);
const label = document.createElement('span');
label.textContent = item.name;
iconEl.appendChild(label);
return iconEl;
}
function renderDesktopItems() {
const desktop = document.getElementById('desktop');
if (!desktop) return;
desktop.querySelectorAll('.desktop-icon').forEach((el) => el.remove());
STATIC_DESKTOP_APPS.forEach((appEntry) => {
desktop.appendChild(createDesktopIconElement({
kind: 'static-app',
appId: appEntry.appId,
name: appEntry.name,
icon: appEntry.icon,
}));
});
desktopItems.filter((item) => item.parentId === null).forEach((item) => {
desktop.appendChild(createDesktopIconElement({
kind: 'dynamic',
...item,
}));
});
if (window.Win9xDesktopUtils && typeof window.Win9xDesktopUtils.refreshIconStateAndListeners === 'function') {
window.Win9xDesktopUtils.refreshIconStateAndListeners();
}
}
function selectItemIcon(itemId) {
const iconEl = document.querySelector(`.desktop-icon[data-desktop-item-id="${itemId}"]`);
if (!iconEl) return;
if (window.Win9xDesktopUtils && typeof window.Win9xDesktopUtils.clearSelection === 'function') {
window.Win9xDesktopUtils.clearSelection();
}
if (window.Win9xDesktopUtils && typeof window.Win9xDesktopUtils.selectIcon === 'function') {
window.Win9xDesktopUtils.selectIcon(iconEl, true);
}
}
function createItem(type, options = {}) {
const def = TYPE_REGISTRY[type];
if (!def) {
throw new Error(`Unsupported desktop item type: ${type}`);
}
const item = {
id: generateItemId(),
type,
name: getUniqueName((options.name || def.defaultName || def.label).trim()),
icon: def.icon,
parentId: normalizeParentId(options.parentId),
createdAt: Date.now(),
...(typeof def.createInitialData === 'function' ? def.createInitialData(options) : {}),
...(options && typeof options === 'object' ? options : {}),
};
item.parentId = normalizeParentId(item.parentId);
desktopItems.push(item);
saveItems();
renderDesktopItems();
emitItemsChanged('create', { id: item.id, type: item.type, parentId: item.parentId });
requestAnimationFrame(() => selectItemIcon(item.id));
return item;
}
function getItemById(itemId) {
return desktopItems.find((item) => item.id === itemId) || null;
}
function openItem(itemId) {
const item = getItemById(itemId);
if (!item) return false;
const def = TYPE_REGISTRY[item.type];
if (!def || typeof def.open !== 'function') return false;
def.open(item);
return true;
}
function updateTextDocumentContent(itemId, content, fileName = null) {
const item = getItemById(itemId);
if (!item || item.type !== 'textDocument') {
return false;
}
item.content = typeof content === 'string' ? content : '';
if (typeof fileName === 'string' && fileName.trim()) {
item.name = getUniqueName(fileName.trim(), item.id);
}
saveItems();
renderDesktopItems();
emitItemsChanged('update', { id: item.id, type: item.type });
return true;
}
function deleteItem(itemId) {
const target = getItemById(itemId);
if (!target) {
return null;
}
const idsToDelete = new Set([itemId]);
const queue = [itemId];
while (queue.length > 0) {
const currentId = queue.shift();
desktopItems.forEach((item) => {
if (item.parentId === currentId && !idsToDelete.has(item.id)) {
idsToDelete.add(item.id);
queue.push(item.id);
}
});
}
const removedItems = [];
desktopItems = desktopItems.filter((item) => {
if (idsToDelete.has(item.id)) {
removedItems.push(item);
return false;
}
return true;
});
saveItems();
try {
const rawPositions = localStorage.getItem(DESKTOP_ICON_POSITIONS_KEY);
if (rawPositions) {
const positions = JSON.parse(rawPositions);
if (positions && typeof positions === 'object') {
removedItems.forEach((removedItem) => {
const storageKey = `item:${removedItem.id}`;
if (positions[storageKey]) delete positions[storageKey];
});
localStorage.setItem(DESKTOP_ICON_POSITIONS_KEY, JSON.stringify(positions));
}
}
} catch (error) {
console.error('DesktopItems: failed to remove icon position for deleted item:', error);
}
renderDesktopItems();
emitItemsChanged('delete', { id: itemId, deletedIds: Array.from(idsToDelete) });
return target;
}
function getItemsByParentId(parentId = null) {
const normalizedParentId = normalizeParentId(parentId);
return desktopItems.filter((item) => item.parentId === normalizedParentId);
}
function moveItem(itemId, nextParentId = null) {
const item = getItemById(itemId);
if (!item) {
return false;
}
const normalizedParentId = normalizeParentId(nextParentId);
if (normalizedParentId === item.id) {
return false;
}
if (normalizedParentId !== null) {
const nextParent = getItemById(normalizedParentId);
if (!nextParent || nextParent.type !== 'folder') {
return false;
}
}
let ancestorId = normalizedParentId;
while (ancestorId !== null) {
if (ancestorId === item.id) {
return false;
}
const ancestor = getItemById(ancestorId);
ancestorId = ancestor ? normalizeParentId(ancestor.parentId) : null;
}
item.parentId = normalizedParentId;
saveItems();
renderDesktopItems();
emitItemsChanged('move', { id: item.id, parentId: normalizedParentId });
return true;
}
function renameItem(itemId, nextName) {
const item = getItemById(itemId);
if (!item) {
return null;
}
const trimmedName = typeof nextName === 'string' ? nextName.trim() : '';
if (!trimmedName) {
return item.name;
}
const finalName = getUniqueName(trimmedName, item.id);
if (finalName === item.name) {
return item.name;
}
item.name = finalName;
saveItems();
const iconLabel = document.querySelector(`.desktop-icon[data-desktop-item-id="${item.id}"] span`);
if (iconLabel) {
iconLabel.textContent = item.name;
} else {
renderDesktopItems();
}
emitItemsChanged('rename', { id: item.id, name: item.name });
return item.name;
}
function getNewMenuEntries() {
return NEW_MENU_TYPES
.filter((type) => TYPE_REGISTRY[type])
.map((type) => {
const def = TYPE_REGISTRY[type];
return {
id: `new-${type}`,
label: def.label,
icon: def.icon,
enabled: true,
action: () => {
createItem(type);
},
};
});
}
function initDesktopItems() {
loadItems();
ensureSystemShortcutsInitialized();
syncSystemShortcutMetadata();
renderDesktopItems();
}
window.Win9xDesktopItems = {
createItem,
getItemById,
getItems: () => [...desktopItems],
getItemsByParentId,
getNewMenuEntries,
openItem,
deleteItem,
moveItem,
renameItem,
renderDesktopItems,
updateTextDocumentContent,
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initDesktopItems);
} else {
initDesktopItems();
}
})(window);