-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
329 lines (288 loc) · 9.86 KB
/
Copy pathmain.js
File metadata and controls
329 lines (288 loc) · 9.86 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
// main.js - Electron's Main Process Script
const { app, BrowserWindow, screen, Tray, Menu, ipcMain, dialog } = require("electron");
const path = require("path");
const fs = require("fs");
const { attach, detach, reset } = require("electron-as-wallpaper");
let mainWindow; // Declare mainWindow globally to prevent garbage collection
let settingsWindow = null;
let tray = null;
// Where we persist the widget's last position
const configPath = path.join(app.getPath("userData"), "window-position.json");
// Where we persist font + gradient color settings
const settingsPath = path.join(app.getPath("userData"), "widget-settings.json");
const DEFAULT_SETTINGS = {
font: "Anurati",
gradientStart: "#ffffff",
gradientEnd: "#ffffff",
gradientAngle: 90,
// Set when the user browses a font file from their own device instead of
// picking one of the built-in presets. customFontName is what gets used
// as the CSS font-family; customFontDataUrl is the actual font data
// (embedded as base64) so it works without relying on the original file
// still being at that path on future launches.
customFontName: null,
customFontDataUrl: null,
};
function loadSettings() {
try {
const raw = fs.readFileSync(settingsPath, "utf-8");
return { ...DEFAULT_SETTINGS, ...JSON.parse(raw) };
} catch (err) {
// No saved settings yet, or file is corrupt/missing — use defaults.
return { ...DEFAULT_SETTINGS };
}
}
function saveSettingsToDisk(settings) {
try {
fs.writeFileSync(settingsPath, JSON.stringify(settings));
} catch (err) {
console.error("Failed to save settings:", err);
}
}
let currentSettings = loadSettings();
function getSavedPosition() {
try {
const raw = fs.readFileSync(configPath, "utf-8");
const pos = JSON.parse(raw);
if (typeof pos.x === "number" && typeof pos.y === "number") {
return pos;
}
} catch (err) {
// No saved position yet, or file is corrupt/missing — that's fine.
}
return null;
}
function savePosition() {
if (!mainWindow) return;
const [x, y] = mainWindow.getPosition();
try {
fs.writeFileSync(configPath, JSON.stringify({ x, y }));
} catch (err) {
console.error("Failed to save window position:", err);
}
}
function createWindow() {
// Get the primary display's work area size
const primaryDisplay = screen.getPrimaryDisplay();
const { width, height } = primaryDisplay.workAreaSize;
// Calculate the default Y position (top of screen)
const yPosition = Math.round(height * 0);
// Use the saved position if we have one, otherwise fall back to the default
const saved = getSavedPosition();
const startX = saved ? saved.x : Math.round((width + 100) / 2);
const startY = saved ? saved.y : yPosition;
// Create the browser window.
mainWindow = new BrowserWindow({
width: 700, // Adjust width as needed for your clock
height: 350, // Adjust height as needed for your clock
x: startX,
y: startY,
transparent: true, // Make the window background transparent
frame: false, // Remove the window frame (title bar, minimize/maximize/close buttons)
resizable: false, // Prevent resizing
alwaysOnTop: false, // Not needed — attach() below pins it into the desktop layer directly
skipTaskbar: true, // Hide the app from the taskbar/dock
focusable: true, // Must be true so the window can be dragged
webPreferences: {
preload: path.join(__dirname, "preload.js"), // Recommended for security
nodeIntegration: false, // Keep nodeIntegration false for security
contextIsolation: true, // Keep contextIsolation true for security
},
});
// Load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, "index.html"));
// NOTE: We no longer call setIgnoreMouseEvents(true) — that made the
// window click-through and unmovable. Now the widget can be clicked
// and dragged directly (drag region is defined in index.html's CSS).
// Reparent the widget into Windows' hidden "WorkerW" layer — the same
// layer that sits between your wallpaper and desktop icons, and the
// same trick Rainmeter uses. This makes the widget permanently part of
// the desktop: it never covers other app windows, and other app windows
// never cover it — switching apps has zero effect on it.
//
// forwardMouseInput/forwardKeyboardInput are left off so the widget stays
// draggable and the font picker stays clickable. Turn them on if you'd
// rather have clicks pass straight through to your desktop icons.
//
// WorkerW can occasionally not exist yet when the app launches (e.g.
// right after login, or right after explorer.exe restarts). If attach()
// fails, retry a few times with a short delay instead of crashing.
attachWithRetry();
function attachWithRetry(attemptsLeft = 5) {
Promise.resolve()
.then(() =>
attach(mainWindow, {
transparent: true,
forwardMouseInput: false,
forwardKeyboardInput: false,
})
)
.catch((err) => {
if (attemptsLeft > 0) {
setTimeout(() => attachWithRetry(attemptsLeft - 1), 1000);
} else {
console.error(
"Could not attach widget to desktop after several attempts:",
err
);
}
});
}
// Save the new position any time the widget is moved
mainWindow.on("moved", savePosition);
// Optional: Open the DevTools. Uncomment for debugging.
// mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on("closed", () => {
mainWindow = null;
});
}
function cleanupWallpaper() {
try {
reset();
} catch (err) {
// Nothing to reset — that's fine.
}
}
function createSettingsWindow() {
// Only ever have one settings window open at a time
if (settingsWindow) {
settingsWindow.focus();
return;
}
settingsWindow = new BrowserWindow({
width: 380,
height: 480,
resizable: false,
title: "Atomic Clock Settings",
autoHideMenuBar: true,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: false,
contextIsolation: true,
},
});
settingsWindow.setMenu(null);
settingsWindow.loadFile(path.join(__dirname, "settings.html"));
settingsWindow.on("closed", () => {
settingsWindow = null;
});
}
// Renderer (settings.html) asks for the current settings when it opens
ipcMain.handle("get-settings", () => currentSettings);
// Opens a native file picker so the user can choose any .ttf/.otf font
// file on their device. The chosen font is read and embedded as a base64
// data URL so it keeps working even if the original file is later moved,
// renamed, or deleted.
ipcMain.handle("browse-font", async () => {
const result = await dialog.showOpenDialog({
title: "Choose a font file",
filters: [{ name: "Fonts", extensions: ["ttf", "otf"] }],
properties: ["openFile"],
});
if (result.canceled || result.filePaths.length === 0) {
return null;
}
const filePath = result.filePaths[0];
const ext = path.extname(filePath).slice(1).toLowerCase();
const format = ext === "ttf" ? "truetype" : "opentype";
try {
const buffer = fs.readFileSync(filePath);
const base64 = buffer.toString("base64");
return {
fontName: path.basename(filePath, path.extname(filePath)),
dataUrl: `data:font/${format};base64,${base64}`,
};
} catch (err) {
console.error("Failed to read chosen font file:", err);
return null;
}
});
// Renderer (settings.html) saves new settings — persist them, then push
// the update live to the widget window so it applies instantly
ipcMain.handle("save-settings", (_event, newSettings) => {
currentSettings = { ...DEFAULT_SETTINGS, ...newSettings };
saveSettingsToDisk(currentSettings);
if (mainWindow) {
mainWindow.webContents.send("settings-changed", currentSettings);
}
return true;
});
function createTray() {
const iconPath = path.join(__dirname, "build", "icon.ico");
let icon = iconPath;
// Validate the icon file before handing it to Tray — an empty/corrupt/
// missing .ico file used to crash tray creation entirely (which is why
// the tray icon appeared to be "missing" even though the real problem
// was this failing silently as an unhandled rejection).
try {
const stats = fs.statSync(iconPath);
if (stats.size === 0) {
throw new Error("icon.ico is empty");
}
} catch (err) {
console.error(
`Tray icon problem (${err.message}). Falling back to a blank icon — replace build/icon.ico with a valid .ico file.`
);
icon = require("electron").nativeImage.createEmpty();
}
tray = new Tray(icon);
const contextMenu = Menu.buildFromTemplate([
{
label: "Settings...",
click: () => {
createSettingsWindow();
},
},
{
label: "Reset Position",
click: () => {
try {
fs.unlinkSync(configPath);
} catch (err) {
// no saved file, nothing to remove
}
if (mainWindow) {
const primaryDisplay = screen.getPrimaryDisplay();
const { width, height } = primaryDisplay.workAreaSize;
mainWindow.setPosition(
Math.round((width + 100) / 2),
Math.round(height * 0)
);
}
},
},
{
label: "Quit Clock",
click: () => {
app.quit();
},
},
]);
tray.setToolTip("Desktop Clock");
tray.setContextMenu(contextMenu);
}
app.disableHardwareAcceleration();
app.whenReady().then(() => {
createWindow();
createTray();
// Add this block to enable auto-launch at startup
app.setLoginItemSettings({
openAtLogin: true,
path: process.execPath,
args: [],
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("before-quit", () => {
cleanupWallpaper();
});