TeaSpeak-Client/modules/core/url-preview/index.ts

104 lines
3.2 KiB
TypeScript
Raw Normal View History

2019-06-26 16:09:01 -04:00
import * as electron from "electron";
import * as path from "path";
2019-06-30 11:24:10 -04:00
import * as winmgr from "../window";
2019-06-26 16:09:01 -04:00
2019-08-21 04:00:27 -04:00
let global_window: electron.BrowserWindow;
let global_window_promise: Promise<void>;
export async function close() {
while(global_window_promise) {
try {
await global_window_promise;
break;
} catch(error) {} /* error will be already logged */
}
if(global_window) {
global_window.close();
global_window = undefined;
global_window_promise = undefined;
}
}
2019-06-30 11:24:10 -04:00
export async function open_preview(url: string) {
2019-08-21 04:00:27 -04:00
while(global_window_promise) {
try {
await global_window_promise;
break;
} catch(error) {} /* error will be already logged */
}
if(!global_window) {
global_window_promise = (async () => {
global_window = new electron.BrowserWindow({
webPreferences: {
nodeIntegration: true,
webviewTag: true
},
center: true,
show: false,
});
global_window.setMenuBarVisibility(false);
global_window.setMenu(null);
global_window.loadFile(path.join(__dirname, "html", "index.html")).then(() => {
//global_window.webContents.openDevTools();
});
global_window.on('close', event => {
global_window = undefined;
});
try {
await winmgr.apply_bounds('url-preview', global_window);
winmgr.track_bounds('url-preview', global_window);
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject("timeout"), 5000);
global_window.on('ready-to-show', () => {
clearTimeout(timeout);
resolve();
});
});
} catch(error) {
console.warn("Failed to initialize preview window. Dont show preview! Error: %o", error);
throw "failed to initialize";
}
global_window.show();
})();
try {
await global_window_promise;
} catch(error) {
console.log("Failed to create preview window! Error: %o", error);
try {
global_window.close();
} finally {
global_window = undefined;
}
global_window_promise = undefined;
return;
}
}
global_window.webContents.send('preview', url);
if(!global_window.isFocused())
global_window.focus();
2019-06-26 16:09:01 -04:00
}
electron.ipcMain.on('preview-action', (event, args) => {
const sender: electron.WebContents = event.sender;
if(!args || !args.action) {
console.warn("Received preview action without a valid action type!");
return;
}
if(args.action === "open-url") {
console.log("Opening " +args.url);
electron.shell.openExternal(args.url, {
activate: true
});
const browser = electron.BrowserWindow.fromWebContents(sender);
if(!browser)
console.warn("Failed to find browser handle");
else
browser.close();
}
});