refactor: background.js

master
qier222 4 years ago
parent de4315707b
commit 11844e22fe

@ -7,131 +7,112 @@ import { initIpcMain } from "./electron/ipcMain.js";
import { createMenu } from "./electron/menu"; import { createMenu } from "./electron/menu";
import { createTouchBar } from "./electron/touchBar"; import { createTouchBar } from "./electron/touchBar";
import { createDockMenu } from "./electron/dockMenu"; import { createDockMenu } from "./electron/dockMenu";
import { createTray } from "./electron/tray.js";
import { autoUpdater } from "electron-updater"; import { autoUpdater } from "electron-updater";
import express from "express"; import express from "express";
import expressProxy from "express-http-proxy"; import expressProxy from "express-http-proxy";
import Store from "electron-store"; import Store from "electron-store";
const store = new Store({ class Background {
constructor() {
this.window = null;
this.store = new Store({
windowWidth: { windowWidth: {
width: { type: "number", default: 1440 }, width: { type: "number", default: 1440 },
height: { type: "number", default: 840 }, height: { type: "number", default: 840 },
}, },
}); });
this.neteaseMusicAPI = null;
this.expressApp = null;
this.willQuitApp = process.platform === "darwin" ? false : true;
this.init();
}
const isDevelopment = process.env.NODE_ENV !== "production"; init() {
console.log("initializing");
// Keep a global reference of the window object, if you don't, the window will // Make sure the app is singleton.
// be closed automatically when the JavaScript object is garbage collected. if (!app.requestSingleInstanceLock()) return app.quit();
let win;
// eslint-disable-next-line no-unused-vars
let tray;
let willQuitApp = false; // start netease music api
this.neteaseMusicAPI = startNeteaseMusicApi();
// ipcMain // create Express app
initIpcMain(win); this.createExpressApp();
// Scheme must be registered before the app is ready // init ipcMain
protocol.registerSchemesAsPrivileged([ initIpcMain(this.window);
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: "app", privileges: { secure: true, standard: true } }, { scheme: "app", privileges: { secure: true, standard: true } },
]); ]);
function createWindow() { // handle app events
win = new BrowserWindow({ this.handleAppEvents();
width: store.get("window.width"), }
height: store.get("window.height"),
titleBarStyle: "hiddenInset",
webPreferences: {
webSecurity: false,
nodeIntegration: true,
},
});
win.setMenuBarVisibility(false);
if (process.platform !== "darwin") { async initDevtools() {
tray = createTray(win); // Install Vue Devtools extension
try {
await installExtension(VUEJS_DEVTOOLS);
} catch (e) {
console.error("Vue Devtools failed to install:", e.toString());
} }
if (process.env.WEBPACK_DEV_SERVER_URL) { // Exit cleanly on request from parent process in development mode.
// Load the url of the dev server if in development mode if (process.platform === "win32") {
win.loadURL(process.env.WEBPACK_DEV_SERVER_URL); process.on("message", (data) => {
if (!process.env.IS_TEST) win.webContents.openDevTools(); if (data === "graceful-exit") {
app.quit();
}
});
} else { } else {
createProtocol("app"); process.on("SIGTERM", () => {
// win.loadURL("app://./index.html"); app.quit();
});
}
}
createExpressApp() {
console.log("creating express app");
const expressApp = express(); const expressApp = express();
expressApp.use("/", express.static(__dirname + "/")); expressApp.use("/", express.static(__dirname + "/"));
expressApp.use("/api", expressProxy("http://127.0.0.1:10754")); expressApp.use("/api", expressProxy("http://127.0.0.1:10754"));
expressApp.listen(27232); this.expressApp = expressApp.listen(27232);
win.loadURL("http://localhost:27232");
} }
win.webContents.on("new-window", function (e, url) { createWindow() {
e.preventDefault(); console.log("creating app window");
shell.openExternal(url);
}); this.window = new BrowserWindow({
win.on("close", (e) => { width: this.store.get("window.width") | 1440,
if (willQuitApp) { height: this.store.get("window.height") | 840,
/* the user tried to quit the app */ titleBarStyle: "hiddenInset",
win = null; webPreferences: {
} else { webSecurity: false,
/* the user only tried to close the window */ nodeIntegration: true,
e.preventDefault(); },
win.hide();
}
});
// win.on("closed", () => {
// win = null;
// });
win.on("resize", () => {
let { height, width } = win.getBounds();
store.set("window", { height, width });
}); });
return win;
}
// Quit when all windows are closed. // hide menu bar on Microsoft Windows and Linux
app.on("window-all-closed", () => { this.window.setMenuBarVisibility(false);
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== "darwin") {
// app.quit();
}
});
app.on("activate", () => { if (process.env.WEBPACK_DEV_SERVER_URL) {
// On macOS it's common to re-create a window in the app when the // Load the url of the dev server if in development mode
// dock icon is clicked and there are no other windows open. this.window.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
if (win === null) { if (!process.env.IS_TEST) this.window.webContents.openDevTools();
createWindow();
} else { } else {
win.show(); createProtocol("app");
this.window.loadURL("http://localhost:27232");
}
} }
});
/**
* 'before-quit' is emitted when Electron receives the signal to exit and wants to start closing windows
*/
app.on("before-quit", () => (willQuitApp = true));
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
// start netease music api
startNeteaseMusicApi();
// check for update checkForUpdates() {
const log = require("electron-log");
log.transports.file.level = "debug";
autoUpdater.logger = log;
autoUpdater.checkForUpdatesAndNotify(); autoUpdater.checkForUpdatesAndNotify();
if (process.platform === "darwin") { const showNewVersionMessage = (info) => {
autoUpdater.on("update-available", (info) => {
log.debug(info);
dialog dialog
.showMessageBox({ .showMessageBox({
title: "发现新版本 v" + info.version, title: "发现新版本 v" + info.version,
@ -148,53 +129,99 @@ app.on("ready", async () => {
); );
} }
}); });
};
if (process.platform === "darwin") {
autoUpdater.on("update-available", (info) => {
showNewVersionMessage(info);
}); });
} }
}
// Install Vue Devtools extension handleWindowEvents() {
if (isDevelopment && !process.env.IS_TEST) { this.window.once("ready-to-show", () => {
try { console.log("windows ready-to-show event");
await installExtension(VUEJS_DEVTOOLS); this.window.show();
} catch (e) { });
console.error("Vue Devtools failed to install:", e.toString());
this.window.on("close", (e) => {
console.log("windows close event");
if (this.willQuitApp) {
/* the user tried to quit the app */
this.window = null;
app.quit();
} else {
/* the user only tried to close the window */
e.preventDefault();
this.window.hide();
} }
});
this.window.on("resize", () => {
let { height, width } = this.window.getBounds();
this.store.set("window", { height, width });
});
this.window.webContents.on("new-window", function (e, url) {
e.preventDefault();
shell.openExternal(url);
});
}
handleAppEvents() {
app.on("ready", async () => {
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
console.log("app ready event");
// for development
if (process.env.NODE_ENV !== "production") {
this.initDevtools();
} }
// create window // create window
createWindow(); this.createWindow();
win.once("ready-to-show", () => { this.handleWindowEvents();
win.show();
}); // check for updates
this.checkForUpdates();
// create menu // create menu
createMenu(win); createMenu(this.window);
// create dock menu for macOS // create dock menu for macOS
app.dock.setMenu(createDockMenu(win)); app.dock.setMenu(createDockMenu(this.window));
// create touchbar // create touch bar
win.setTouchBar(createTouchBar(win)); this.window.setTouchBar(createTouchBar(this.window));
}); });
// Exit cleanly on request from parent process in development mode. app.on("activate", () => {
if (isDevelopment) { // On macOS it's common to re-create a window in the app when the
if (process.platform === "win32") { // dock icon is clicked and there are no other windows open.
process.on("message", (data) => { console.log("app activate event");
if (data === "graceful-exit") { if (this.window === null) {
app.quit(); this.createWindow();
} else {
this.window.show();
} }
}); });
} else {
process.on("SIGTERM", () => { app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit(); app.quit();
});
} }
} });
app.on("before-quit", () => {
this.willQuitApp = true;
});
// Make sure the app is singleton. app.on("quit", () => {
function initialize() { this.expressApp.close();
const shouldQuit = !app.requestSingleInstanceLock(); });
if (shouldQuit) return app.quit(); }
} }
initialize(); new Background();

@ -1,35 +0,0 @@
/* global __static */
import path from "path";
import { app, nativeImage, Tray, Menu } from "electron";
export function createTray(win) {
let icon = nativeImage
.createFromPath(path.join(__static, "img/icons/menu@88.png"))
.resize({
height: 20,
width: 20,
});
let tray = new Tray(icon);
tray.on("click", () => {
if (win && win.isVisible()) {
win.hide();
} else {
win.show();
}
});
tray.on("right-click", () => {
const contextMenu = Menu.buildFromTemplate([
{
label: "Quit",
click: () => {
app.exit();
},
},
]);
tray.popUpContextMenu(contextMenu);
});
return tray;
}
Loading…
Cancel
Save