This commit is contained in:
Tjark Müller 2023-05-10 15:23:51 +02:00
commit 03fda7e79e
168 changed files with 35051 additions and 5929 deletions

4
.gitignore vendored
View File

@ -83,4 +83,6 @@ typings/
# ignore generated contents-
/doc/out/*
**/thumbnails
**/thumbnail.png
**/thumbnail.png
/site/dist
/site/__pycache__

13
bin/browser.sh Normal file
View File

@ -0,0 +1,13 @@
#!/bin/bash
if [ "$1" = "dist" ]
then
if [ -z "$2" ]
then
npm run package-all
else
npm run package-app-$2
fi
else
electron . ./lib/index.html
fi

289
browser/browser.html Normal file
View File

@ -0,0 +1,289 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
html {
height: 100%;
width: 100%;
margin: 0px;
}
::-webkit-scrollbar { display: none; }
body {
margin: 0px;
padding: 0px;
width: 100%;
height: 100%;
font-family: sans-serif;
font-size: 22pt;
-webkit-tap-highlight-color: #ccc;
background-color: #DDD;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-hyphens: auto;
hyphens: auto;
/* https://davidwalsh.name/font-smoothing */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-app-region: drag;
}
header {
position: absolute;
width: 100%;
height: 24px;
}
#progressBar {
position: absolute;
background-color: rgb(165, 165, 196);
width: 0%;
height: 24px;
}
#info {
width: 100%;
margin: 3px;
font-size: 16px;
position: absolute;
text-align:center;
}
</style>
<title>
Browser
</title>
</head>
<body style="width: 100%; height: 100%; -webkit-app-region: no-drag">
<header id="header" style="-webkit-app-region: drag">
<div id="progressBar"></div>
<span id="info">Minimal Header</span>
</header>
<main></main>
</body>
<script>
const { ipcRenderer } = require("electron")
let urls = new Set()
let favicons = new Set()
let progress = 0
info.innerHTML = window.location.href
function notify(url) {
if (urls.has(url)) return
console.log(url)
//header.innerHTML += `<p>${url}</p>`
urls.add(url)
}
let colorExtractorCanvas = document.createElement('canvas')
let colorExtractorContext = colorExtractorCanvas.getContext('2d')
let colorExtractorImage = document.createElement('img')
function getColor(url, callback) {
colorExtractorImage.onload = function (e) {
let w = colorExtractorImage.width
let h = colorExtractorImage.height
colorExtractorCanvas.width = w
colorExtractorCanvas.height = h
let offset = Math.max(1, Math.round(0.00032 * w * h))
colorExtractorContext.drawImage(colorExtractorImage, 0, 0, w, h)
let data = colorExtractorContext.getImageData(0, 0, w, h).data
let pixels = {}
let d, add, sum
for (let i = 0; i < data.length; i += 4 * offset) {
d = Math.round(data[i] / 5) * 5 + ',' + Math.round(data[i + 1] / 5) * 5 + ',' + Math.round(data[i + 2] / 5) * 5
add = 1
sum = data[i] + data[i + 1] + data[i + 2]
// very dark or light pixels shouldn't be counted as heavily
if (sum < 310) {
add = 0.35
}
if (sum < 50) {
add = 0.01
}
if (data[i] > 210 || data[i + 1] > 210 || data[i + 2] > 210) {
add = 0.5 - (0.0001 * sum)
}
if (pixels[d]) {
pixels[d] = pixels[d] + add
} else {
pixels[d] = add
}
}
// find the largest pixel set
let largestPixelSet = null
let ct = 0
for (let k in pixels) {
if (k === '255,255,255' || k === '0,0,0') {
pixels[k] *= 0.05
}
if (pixels[k] > ct) {
largestPixelSet = k
ct = pixels[k]
}
}
let res = largestPixelSet.split(',')
for (let i = 0; i < res.length; i++) {
res[i] = parseInt(res[i])
}
callback(res)
}
colorExtractorImage.src = url
}
function getTextColor(bgColor) {
let output = runNetwork(bgColor)
if (output.black > 0.5) {
return 'black'
}
return 'white'
}
var runNetwork = function anonymous(input) {
var net = {
'layers': [{
'r': {},
'g': {},
'b': {}
}, {
'0': {
'bias': 14.176907520571566,
'weights': {
'r': -3.2764240497480652,
'g': -16.90247884718719,
'b': -2.9976364179397814
}
},
'1': {
'bias': 9.086071102351246,
'weights': {
'r': -4.327474143397604,
'g': -15.780660155750773,
'b': 2.879230202567851
}
},
'2': {
'bias': 22.274487339773476,
'weights': {
'r': -3.5830205067960965,
'g': -25.498384261673618,
'b': -6.998329189107962
}
}
}, {
'black': {
'bias': 17.873962570788997,
'weights': {
'0': -15.542217788633987,
'1': -13.377152708685674,
'2': -24.52215186113144
}
}
}],
'outputLookup': true,
'inputLookup': true
}
for (var i = 1; i < net.layers.length; i++) {
var layer = net.layers[i]
var output = {}
for (var id in layer) {
var node = layer[id]
var sum = node.bias
for (var iid in node.weights) {
sum += node.weights[iid] * input[iid]
}
output[id] = (1 / (1 + Math.exp(-sum)))
}
input = output
}
return output
}
function applyColors(backgroundColor, foregroundColor) {
console.log("applyColors", backgroundColor, foregroundColor)
progressBar.style.backgroundColor = backgroundColor
info.style.color = foregroundColor
}
ipcRenderer.on('title', (sender, title) => {
info.innerHTML = title
})
ipcRenderer.on('favicons', (sender, urls) => {
console.log("favicons event", urls)
for (let url of urls) {
if (!favicons.has(url)) {
getColor(url, c => {
let cr = 'rgb(' + c[0] + ',' + c[1] + ',' + c[2] + ')'
let obj = {
r: c[0] / 255,
g: c[1] / 255,
b: c[2] / 255
}
let textclr = getTextColor(obj)
applyColors(cr, textclr)
})
}
favicons.add(url)
}
})
ipcRenderer.on('progress', (sender, amount) => {
console.log("progress event", amount)
if (amount > progress) {
progress = Math.min(amount, 1)
}
progressBar.style.width = Math.round(progress * 100) + '%'
})
ipcRenderer.on('did-start-loading', (sender, url) => {
console.log('did-start-loading', url)
})
ipcRenderer.on('did-get-response-details', (sender, info) => {
let {
status, newURL, originalURL,
httpResponseCode,
requestMethod,
referrer,
headers,
resourceType
} = info
notify(newURL)
notify(originalURL)
//console.log('did-get-response-details', info)
})
ipcRenderer.on('did-get-redirect-request', (sender, info) => {
let { oldURL,
newURL,
isMainFrame,
httpResponseCode,
requestMethod,
referrer,
headers
} = info
notify(newURL)
notify(oldURL)
//console.log('did-get-response-details', info)
})
ipcRenderer.on('did-stop-loading', (sender, info) => {
//console.log('did-stop-loading', info)
})
</script>
</html>

49
browser/carlo.js Normal file
View File

@ -0,0 +1,49 @@
const carlo = require('carlo');
const fse = require('fs-extra');
const urlExists = require('url-exists');
// command line arguments
let path = 'index.html'
process.argv.forEach((value, index, array) => {
if (index === 2) {
path = value
}
});
(async () => {
// Launch the browser.
const opts = {}
// Set path to custom chrome
const chrome = `${__dirname}/../chrome/chrome.exe`
if (fse.pathExistsSync(chrome)) {
opts.executablePath = chrome
}
// Launch app
const app = await carlo.launch(opts)
// Terminate Node.js process on app window closing.
app.on('exit', () => process.exit())
// Tell carlo where your web files are located.
app.serveFolder(`${__dirname}/../`)
// Check if URL exists
urlExists('https://localhost:8443', async (error, exists) => {
if (exists) {
console.info('Serve files via server')
app.serveOrigin('https://localhost:8443') // Optional
} else {
console.info('Serve files from file system')
}
// Expose 'env' function in the web environment.
await app.exposeFunction('env', _ => process.env)
// Navigate to the main page of your app.
console.info('Starting carlo with', path)
await app.load(path)
})
})()

24
browser/i18n.js Normal file
View File

@ -0,0 +1,24 @@
const path = require('path')
const electron = require('electron')
const fs = require('fs')
let loadedLanguage
let app = electron.app ? electron.app : electron.remote.app
module.exports = i18n
function i18n() {
if (fs.existsSync(path.join(__dirname, 'i18n', app.getLocale() + '.js'))) {
loadedLanguage = JSON.parse(fs.readFileSync(path.join(__dirname, 'i18n', app.getLocale() + '.js'), 'utf8'))
}
else {
loadedLanguage = JSON.parse(fs.readFileSync(path.join(__dirname, 'i18n', 'en.js'), 'utf8'))
}
}
i18n.prototype.__ = function(phrase) {
let translation = loadedLanguage[phrase]
if (translation === undefined) {
translation = phrase
}
return translation
}

61
browser/i18n/de.js Normal file
View File

@ -0,0 +1,61 @@
{
"edit": "Bearbeiten",
"undo": "Widerrufen",
"redo": "Wiederholen",
"cut": "Ausschneiden",
"copy": "Kopieren",
"paste": "Einsetzen",
"pasteandmatchstyle": "Einsetzen und Stil anpassen",
"delete": "Löschen",
"selectall": "Alles auswählen",
"view": "Darstellung",
"reload": "Seite neu laden",
"forcereload": "Cache löschen und Seite neu laden",
"resetzoom": "Originalgröße",
"zoomin": "Vergrößern",
"zoomout": "Verkleinern",
"togglefullscreen": "Vollbildmodus umschalten",
"minimalpad": "Minimal-Pad",
"multiuserbrowser": "Mehrbenutzer-Browser",
"history": "Verlauf",
"back": "Zurück",
"forward": "Vorwärts",
"home": "Startseite",
"recentlyvisited": "Kürzlich besucht",
"bookmarks": "Lesezeichen",
"localfilesystem": "Lokales Dateisystem",
"testframes": "Testseiten",
"develop": "Entwickler",
"toggledevelopertools": "Webinformationen umschalten",
"openprocessmonitor": "Prozessmonitor öffnen",
"selectfolder": "Datenverzeichnis auswählen...",
"selectfolder.noadmin.ok": "OK",
"selectfolder.noadmin.message": "Keine ausreichenden Berechtigungen",
"selectfolder.noadmin.detail": "Um das Datenverzeichnis zu ändern, muss der IWM Browser mit Administrator-Berechtigungen gestartet werden.",
"selectfolder.warning.next": "Weiter",
"selectfolder.warning.cancel": "Abbrechen",
"selectfolder.warning.message": "Datenverzeichnis vorhanden",
"selectfolder.warning.detail": "Ihr IWM Browser besitzt bereits ein (verlinktes) Datenverzeichnis. Wenn Sie fortfahren, wird das alte Verzeichnis gesichert und ein neues wird erstellt.",
"selectfolder.select.title": "Datenverzeichnis wählen",
"selectfolder.select.buttonLabel": "Auswählen",
"selectfolder.samefolder.ok": "OK",
"selectfolder.samefolder.message": "Ungültiges Datenverzeichnis",
"selectfolder.samefolder.detail.same": "Das alte Datenverzeichnis darf nicht als neues Verzeichnis ausgewählt werden.",
"selectfolder.samefolder.detail.within": "Das neue Datenverzeichnis darf sich nicht innerhalb des alten Verzeichnisses befinden.",
"selectfolder.info.ok": "OK",
"selectfolder.info.message": "Link auf Datenverzeichnis erstellt",
"selectfolder.info.detail": "Der IWM Browser verwendet nun den Ordner \"${0}\" als neues Datenverzeichnis.",
"startserver": "Starte Server",
"stopserver": "Stoppe Server",
"runloadtests": "Starte Ladetests",
"window": "Fenster",
"close": "Fenster schließen",
"minimize": "Im Dock ablegen",
"zoom": "Zoomen",
"front": "Alle nach vorne bringen",
"screenshot": "Bildschirmfoto erstellen",
"help": "Hilfe",
"iwm": "Leibniz-Institut für Wissensmedien",
"about": "Über IWM Browser",
"quit": "IWM Browser beenden"
}

61
browser/i18n/en.js Normal file
View File

@ -0,0 +1,61 @@
{
"edit": "Edit",
"undo": "Undo",
"redo": "Redo",
"cut": "Cut",
"copy": "Copy",
"paste": "Paste",
"pasteandmatchstyle": "Paste and Match Style",
"delete": "Delete",
"selectall": "Select all",
"view": "View",
"reload": "Reload",
"forcereload": "Force Reload",
"resetzoom": "Actual size",
"zoomin": "Zoom in",
"zoomout": "Zoom out",
"togglefullscreen": "Toggle Full Screen",
"minimalpad": "Minimal Pad",
"multiuserbrowser": "Multi-User Browser",
"history": "History",
"back": "Back",
"forward": "Forward",
"home": "Home",
"recentlyvisited": "Recently Visited",
"bookmarks": "Bookmarks",
"localfilesystem": "Local Filesystem",
"testframes": "Test Frames",
"develop": "Develop",
"toggledevelopertools": "Toggle Developer Tools",
"openprocessmonitor": "Open Process Monitor",
"selectfolder": "Select data folder...",
"selectfolder.noadmin.ok": "OK",
"selectfolder.noadmin.message": "Insufficient permissions",
"selectfolder.noadmin.detail": "To change the data directory, the IWM Browser must be started with administrator privileges.",
"selectfolder.warning.next": "Next",
"selectfolder.warning.cancel": "Cancel",
"selectfolder.warning.message": "Data folder exists",
"selectfolder.warning.detail": "Your IWM Browser already has a (linked) data directory. If you continue, the old directory is backed up and a new one is created.",
"selectfolder.select.title": "Select data folder",
"selectfolder.select.buttonLabel": "Select",
"selectfolder.samefolder.ok": "OK",
"selectfolder.samefolder.message": "Invalid data folder",
"selectfolder.samefolder.detail.same": "The old data directory cannot be selected as the new directory.",
"selectfolder.samefolder.detail.within": "The new data directory cannot be inside the old directory.",
"selectfolder.info.ok": "OK",
"selectfolder.info.message": "Created link to data folder",
"selectfolder.info.detail": "The IWM Browser now uses the folder \"${0}\" as the new data folder.",
"startserver": "Start Server",
"stopserver": "Stop Server",
"runloadtests": "Run Load Tests",
"window": "Window",
"close": "Close",
"minimize": "Minimize",
"zoom": "Zoom",
"front": "Bring All to Front",
"screenshot": "Make Screenshot",
"help": "Help",
"iwm": "Leibniz-Institut für Wissensmedien",
"about": "About IWM Browser",
"quit": "Quit IWM Browser"
}

578
browser/main.js Normal file
View File

@ -0,0 +1,578 @@
/* globals require, __dirname, process */
/*eslint no-console: ["error", { allow: ["log"] }]*/
const { app, BrowserWindow, BrowserView, ipcMain, dialog, shell } = require('electron')
const electronLocalshortcut = require('electron-localshortcut')
//const electron = require('electron')
const os = require('os')
const fs = require('fs')
const path = require('path')
const { URL } = require('url')
const Store = require('./store.js')
const { prettyPrint } = require('html')
// Use this constant to start the application in kiosk-mode or in development mode
const DEVELOPMENT = true
// true: Dev-Tools are open
// false (KIOSK-Mode): No application switcher, no menu, no taskbar (or dock on a mac), shortcuts are working
global.multiUserMode = true
global.errorCount = 0
global.stopTestsOnError = false
global.jsonData = { value: null }
// UO: Experimental feature using Native Windows
global.useBrowserView = false
global.useMinimalPad = true
global.menu = null
global.observeTraffic = false
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
let browsers = new Map() // url: BrowserWindow
const store = new Store({
// We'll call our data file 'user-preferences'
configName: 'user-preferences',
defaults: {
url: `file://${__dirname}/index.html`,
devTools: DEVELOPMENT,
multiUserBrowser: true
}
})
function createWindow() {
if (global.observeTraffic) {
const {session} = require('electron')
session.defaultSession.webRequest.onCompleted((details) => {
console.log("onCompleted", details.url)
})
}
let { screen } = require('electron')
let bounds = store.get('storedBounds')
? store.get('storedBounds')
: screen.getPrimaryDisplay().bounds
// let displays = screen.getAllDisplays()
// let externalDisplay = null
// externalDisplay = displays[displays.length-1]
// const {width, height} =displays[displays.length-1].workAreaSize
// externalDisplay = displays[0]
// const {width, height} =displays[0].workAreaSize
win = new BrowserWindow({
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: bounds.height,
fullscreenable: true,
fullscreen: !DEVELOPMENT,
title: 'IWM Browser',
show: false,
kiosk: !DEVELOPMENT,
acceptFirstMouse: true,
webPreferences: {
webSecurity: false,
allowRunningInsecureContent: true,
nodeIntegration: true,
webviewTag: true,
nativeWindowOpen: true,
devTools: true,
preload: path.join(__dirname, './preload.js')
},
icon: path.join(__dirname, 'assets/icons/png/64x64.png')
})
module.exports.win = win
let url = store.get('url')
if (process.argv.length > 2) {
let path = process.argv[2]
url = `file://${__dirname}/../${path}`
console.log('Using process.argv[2]', url)
}
console.log('Using', url)
win.maximize()
// BAD: All other methods don't work (like ensureFileSync, fileExists...)
try {
let settings = require('./settings.json')
console.log('Using settings', `file://${__dirname}/${settings.url}`)
win.loadURL(`file://${__dirname}/${settings.url}`)
} catch (ex) {
win.loadURL(url)
}
const { webContents } = win
//
// if (process.platform === 'win32' && win.isKiosk()) {
// webContents.on('did-finish-load', function() {
// webContents.executeJavaScript('document.body.style.cursor = "none";')
// })
// }
// Add the app menu
let menu = require('./menu.js')
global.menu = menu
// Add global shortcuts
// Esc quits the app
electronLocalshortcut.register('Esc', () => {
app.quit()
})
// Command (Mac) or Control (Win) + K toggles the Kiosk mode
electronLocalshortcut.register('CommandOrControl+K', () => {
if (win) {
win.setKiosk(!win.isKiosk())
}
})
// Show if its ready.
win.once('ready-to-show', () => {
webContents.send('preparePads')
win.show()
})
// Clear cache
webContents.session.clearCache(() => console.log('Cache cleared'))
// Open dev tools when in development mode
if (store.get('devTools')) {
webContents.openDevTools({ mode: 'right' })
} else {
webContents.closeDevTools()
}
webContents.on('devtools-opened', () => {
store.set('devTools', true)
})
webContents.on('devtools-closed', () => {
store.set('devTools', false)
})
webContents.on('did-navigate', (event, url) => {
menu.setHistoryStatus()
})
/* UO: At this point we have no access to the event or link position*/
webContents.on('new-window', (event, url, frameName, disposition, options, additionalFeatures) => {
console.log('new-window', global.multiUserMode)
if (global.multiUserMode) {
event.preventDefault()
webContents.send('newPad', url, options.x, options.y)
}
})
// WORKAROUND: On windows, if the app was set to fullscreen, the menubar is not hidden
if (win.isKiosk()) {
win.setMenuBarVisibility(false)
}
win.on('focus', event => {
menu.focus()
})
win.on('blur', event => {
menu.blur()
})
win.on('enter-full-screen', () => {
win.setMenuBarVisibility(false)
})
win.on('leave-full-screen', () => {
win.setMenuBarVisibility(true)
})
win.on('enter-html-full-screen', () => {
win.setMenuBarVisibility(false)
})
win.on('leave-html-full-screen', () => {
win.setMenuBarVisibility(true)
})
win.on('close', () => {
store.set('storedBounds', win.getBounds())
})
// Emitted when the window is closed.
win.on('closed', () => {
app.quit()
})
}
// When work makes progress, show the progress bar
function onProgress(progress) {
// Use values 0 to 1, or -1 to hide the progress bar
try {
win.setProgressBar(progress || -1) // Progress bar works on all platforms
} catch (e) {
if (DEVELOPMENT) console.log(e.message)
}
}
function trySend(target, ...args) {
try {
target.send(...args)
} catch (e) {
if (DEVELOPMENT) console.log(e.message)
}
}
function openBrowserView(url, x, y) {
const useMinBrowser = false // Change this to switch between Min and a custom browser
const minURL = 'file:///Users/uo/devel/min/index.html'
const browserURL = `file://${__dirname}/browser.html`
let width = 640
let height = 1200
let [winWidth, winHeight] = win.getSize()
if (x + width > winWidth) {
x = winWidth - width
}
if (y + height > winHeight) {
y = winHeight - height
}
console.log('open browser view')
let browser = new BrowserWindow({
x,
y,
width,
height,
minWidth: 320,
minHeight: 350,
titleBarStyle: useMinBrowser ? 'hidden-inset' : 'hidden',
frame: process.platform !== 'win32'
})
let browserContents = browser.webContents
browser.setAlwaysOnTop(true)
if (useMinBrowser) {
browserContents.on('did-finish-load', event => {
console.log('did-finish-load', browserContents.getURL())
browserContents.executeJavaScript(
'Object.values(window.webviews.elementMap).map(obj => obj.src)',
result => {
console.log(
'window.webviews',
result,
url,
result.indexOf(url)
)
if (result.indexOf(url) == -1) {
console.log('Adding tab')
browserContents.send('addTab', { url })
}
}
)
})
browser.loadURL(minURL)
} else {
console.log('Loading', browserURL)
browser.loadURL(browserURL)
let view = new BrowserView({
webPreferences: {
nodeIntegration: false,
devTools: true
}
})
//browserContents.openDevTools({mode: 'right'})
browser.setBrowserView(view)
view.setBounds({ x: 0, y: 24, width: width, height: height - 24 })
view.setAutoResize({ width: true, height: true })
let viewContents = view.webContents
let progress = 0
viewContents.on('page-title-set', event => {
console.log('page-title-set', event)
})
viewContents.on('page-favicon-updated', (event, favicons) => {
//console.log("page-favicon-updated", event, favicons)
trySend(browserContents, 'favicons', favicons)
})
viewContents.on('did-start-loading', event => {
onProgress(0)
trySend(browserContents, 'progress', 0)
trySend(browserContents, 'did-start-loading')
//let senderURL = event.sender.getURL() || url
//console.log('did-start-loading', senderURL)
})
viewContents.on(
'did-get-response-details',
(
event,
status,
newURL,
originalURL,
httpResponseCode,
requestMethod,
referrer,
headers,
resourceType
) => {
trySend(browserContents, 'did-get-response-details', {
status,
newURL,
originalURL,
httpResponseCode,
requestMethod,
referrer,
headers,
resourceType
})
progress += 0.01
onProgress(progress)
trySend(browserContents, 'progress', progress)
//console.log('did-get-response-details', newURL)
}
)
viewContents.on(
'did-get-redirect-request',
(
event,
oldURL,
newURL,
isMainFrame,
httpResponseCode,
requestMethod,
referrer,
headers
) => {
trySend(browserContents, 'did-get-redirect-request', {
oldURL,
newURL,
isMainFrame,
httpResponseCode,
requestMethod,
referrer,
headers
})
//console.log('did-get-redirect-request', newURL)
}
)
viewContents.on('did-stop-loading', event => {
//console.log('did-stop-loading', event.sender.getURL())
trySend(browserContents, 'did-stop-loading')
})
viewContents.on('did-finish-load', event => {
//console.log('did-finish-load', event.sender.getURL())
progress = 1
onProgress(progress)
trySend(browserContents, 'progress', progress)
})
viewContents.on('dom-ready', event => {
if (progress < 0.5) {
progress = 0.5
onProgress(progress)
trySend(browserContents, 'progress', progress)
}
viewContents.executeJavaScript('document.title', result => {
trySend(browserContents, 'title', result)
})
//console.log('dom-ready', event.sender.getURL())
})
viewContents.on('new-window', function (event, url) {
event.preventDefault()
console.log('new-window')
openBrowserView(url, x, y)
})
viewContents.loadURL(url)
}
browsers.set(url, browser)
browser.on('closed', e => {
for (let [url, browser] of browsers.entries()) {
if (browser == e.sender) {
browsers.delete(url)
console.log('removed browser view', url)
}
}
})
}
// UO: Experimental call. Opens a Min Browser window or a limited window with a browser view
ipcMain.on('loadBrowserView', (e, opts = {}) => {
let { url, x, y } = opts
openBrowserView(url, x, y)
})
ipcMain.on('multiUserMode', (e, opts = {}) => {
global.multiUserMode = opts
})
ipcMain.on('padContainerLoaded', e => {
win.webContents.send('padContainerAvailable')
})
ipcMain.on('createScreenshot', (e, opts = {}) => {
opts = Object.assign(
{},
{
name: `iwmbrowser-${new Date()
.toISOString()
.replace(/:/g, '-')}.png`,
path: os.tmpdir()
},
opts
)
win.webContents.capturePage(image => {
if (image) {
let file = path.join(opts.path, opts.name)
fs.writeFile(file, image.toPNG(), err => {
if (err) {
//throw err
} else {
console.log(`Screenshot saved: ${file}`)
}
})
}
})
})
ipcMain.on('directoryListing', (e, opts = {}) => {
let { directory, files, folders } = opts
console.log("directoryListing", opts)
try {
let listing = fs.readdirSync(directory)
let result = { directory, files: [], folders: [] }
for (let name of listing) {
if (name.startsWith('.'))
continue
let fullPath = path.join(directory, name)
let stat = fs.lstatSync(fullPath)
if (files && stat.isFile()) {
if (typeof files == 'string' && !files.endsWith(files))
continue
result.files.push(name)
}
if (folders && stat.isDirectory())
result.folders.push(name)
}
e.sender.send('directoryListing', result)
} catch (err) {
let args = { directory, errorMessage: err.message}
e.sender.send('directoryListingError', args)
}
})
ipcMain.on('createTextfile', (e, opts = {}) => {
opts = Object.assign(
{},
{
name: `iwmbrowser-${new Date()
.toISOString()
.replace(/:/g, '-')}.txt`,
path: os.tmpdir(),
text: ''
},
opts
)
let file = path.join(opts.path, opts.name)
fs.writeFile(file, opts.text, err => {
if (err) {
//throw err
} else {
console.log(`Textfile saved: ${file}`)
}
})
})
ipcMain.on('error', e => {
console.log('Received error notification')
global.errorCount += 1
})
ipcMain.on('openExternal', (e, url=null) => {
console.log('Received openExternal', url)
if (url) {
shell.openExternal(url)
}
})
ipcMain.on('save', (e, opts = {}) => {
let { url, html, saveAs, action } = opts
// url must absolute URL
let urlObj = new URL(url)
let pathname = urlObj.pathname
if (saveAs) {
pathname = dialog.showSaveDialog(win, { title: 'Save as:', defaultPath: pathname })
if (typeof pathname == 'undefined')
return
}
try {
console.log("Saving", pathname, action)
html = prettyPrint(html, { indent_size: 4 });
fs.writeFileSync(pathname, html, 'utf-8')
if (saveAs) {
let normalized = pathname.replace(/\\/g, '/')
e.sender.send('savedAs', {url: `file://${normalized}`, action})
}
}
catch (e) {
console.warn('Failed to save the file', pathname)
e.sender.send('saveFailed', pathname)
}
})
// 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', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// 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(
'select-client-certificate',
(event, webContents, url, list, callback) => {
console.log('select-client-certificate', url, list)
event.preventDefault()
ipc.once('client-certificate-selected', (event, item) => {
console.log('selected:', item)
callback(item)
})
mainWindow.webContents.send('select-client-certificate', list)
}
)
app.on(
'certificate-error',
(event, webContents, url, error, certificate, callback) => {
console.log('certificate-error', url)
event.preventDefault()
const result = true // TODO: do real validation here
callback(result)
}
)
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})
module.exports = {
store: store
}

629
browser/menu.js Normal file
View File

@ -0,0 +1,629 @@
/* globals require, process */
/*eslint no-console: ["error", { allow: ["log", "error"] }] */
const { Menu, app, shell, dialog } = require('electron')
const fs = require('fs')
const fse = require('fs-extra')
const os = require('os')
const path = require('path')
const { openProcessManager } = require('electron-process-manager')
const main = require('./main.js')
let { thumbnail } = require('./utils.js')
const loadTests = require('./test.js')
const i18n = new (require('./i18n.js'))()
function selectURL(url) {
url = url.replace(/\\/g, '/')
console.log('selectURL', url)
main.win.loadURL(url)
main.store.set('url', url)
}
function findItems(key, value) {
let items = []
for (let i = 0; i < menu.items.length; i++) {
for (let j = 0; j < menu.items[i].submenu.items.length; j++) {
let item = menu.items[i].submenu.items[j]
if (item[key] === value) {
items.push(item)
}
}
}
return items
}
function findItem(key, value) {
return findItems(key, value)[0]
}
function toggleBookmarks(bookmark) {
let items = findItems('class', 'bookmark')
for (let i = 0; i < items.length; i++) {
items[i].checked = false
}
bookmark.checked = true
}
function checkBookmark(url) {
let items = findItems('url', url)
if (items.length === 1) {
toggleBookmarks(items[0])
}
}
function setHistoryStatus() {
const historyBack = findItem('id', 'history-back')
historyBack.enabled = main.win.webContents.canGoBack()
const historyForward = findItem('id', 'history-forward')
historyForward.enabled = main.win.webContents.canGoForward()
}
function showSelectDataFolderDialog(focusedWindow) {
dialog.showOpenDialog(
{
title: i18n.__('selectfolder.select.title'),
buttonLabel: i18n.__('selectfolder.select.buttonLabel'),
properties: ['openDirectory', 'createDirectory', 'noResolveAliases', 'treatPackageAsDirectory']
},
(filePaths) => {
if (filePaths && filePaths.length === 1) {
const varPath = path.join(__dirname, '../var')
// Check if the same folder was used
if (filePaths[0].startsWith(varPath)) {
const same = filePaths[0] === varPath
dialog.showMessageBox(
{
type: 'error',
icon: path.join(__dirname, '../assets/icons/png/512x512-empty.png'),
buttons: [i18n.__('selectfolder.samefolder.ok')],
defaultId: 0,
message: i18n.__('selectfolder.samefolder.message'),
detail: same
? i18n.__('selectfolder.samefolder.detail.same')
: i18n.__('selectfolder.samefolder.detail.within'),
cancelId: 0
},
(response) => {
showSelectDataFolderDialog(focusedWindow)
}
)
} else {
// Backup
if (fse.pathExistsSync(varPath)) {
const varPathBackup = findNextVarFolder()
// Rename old var folder or link
fse.renameSync(varPath, varPathBackup)
} else {
// BUG: Workaround because pathExistsSync return false on existing symbolic links with a missing target
fse.removeSync(varPath)
}
// Add new symlink
main.store.set('dataFolder', filePaths[0])
fs.symlinkSync(filePaths[0], varPath, 'dir')
dialog.showMessageBox(
{
type: 'info',
icon: path.join(__dirname, '../assets/icons/png/link.png'),
buttons: [i18n.__('selectfolder.info.ok')],
defaultId: 0,
message: i18n.__('selectfolder.info.message'),
detail: i18n.__('selectfolder.info.detail').replace(/\$\{0\}/, filePaths[0]),
cancelId: 0
},
(response) => {
if (focusedWindow) focusedWindow.reload()
}
)
}
}
}
)
}
function findNextVarFolder() {
let exists = true
let counter = 0
while (exists) {
counter++
exists = fse.pathExistsSync(path.join(__dirname, `../var${counter}`))
}
return path.join(__dirname, `../var${counter}`)
}
function showFolderBrowser(focusedWindow) {
const varPath = path.join(__dirname, '../var')
const varPathExists = fse.pathExistsSync(varPath)
if (varPathExists) {
dialog.showMessageBox(
{
type: 'warning',
icon: path.join(__dirname, '../assets/icons/png/512x512-empty.png'),
buttons: [i18n.__('selectfolder.warning.next'), i18n.__('selectfolder.warning.cancel')],
defaultId: 1,
message: i18n.__('selectfolder.warning.message'),
detail: i18n.__('selectfolder.warning.detail'),
cancelId: 1
},
(response) => {
if (response === 0) {
showSelectDataFolderDialog(focusedWindow)
}
}
)
} else {
showSelectDataFolderDialog(focusedWindow)
}
}
const template = [
{
label: i18n.__('edit'),
submenu: [
{
role: 'undo',
label: i18n.__('undo')
},
{
role: 'redo',
label: i18n.__('redo')
},
{
type: 'separator'
},
{
role: 'cut',
label: i18n.__('cut')
},
{
role: 'copy',
label: i18n.__('copy')
},
{
role: 'paste',
label: i18n.__('paste')
},
{
role: 'pasteandmatchstyle',
label: i18n.__('pasteandmatchstyle')
},
{
role: 'delete',
label: i18n.__('delete')
},
{
role: 'selectall',
label: i18n.__('selectall')
}
]
},
{
label: i18n.__('view'),
submenu: [
{
label: i18n.__('reload'),
accelerator: 'CmdOrCtrl+R',
click(item, focusedWindow) {
if (focusedWindow) {
focusedWindow.webContents.setVisualZoomLevelLimits(1, 1)
focusedWindow.reload()
}
}
},
{
id: 'forcereload',
label: i18n.__('forcereload'),
accelerator: 'CmdOrCtrl+Shift+R',
click(item, focusedWindow) {
if (focusedWindow) {
focusedWindow.webContents.session.clearCache(() => console.log('Cache cleared'))
focusedWindow.webContents.setVisualZoomLevelLimits(1, 1)
focusedWindow.reload()
}
}
},
{
type: 'separator'
},
{
role: 'resetzoom',
label: i18n.__('resetzoom')
},
{
role: 'zoomin',
label: i18n.__('zoomin')
},
{
role: 'zoomout',
label: i18n.__('zoomout')
},
{
type: 'separator'
},
{
id: 'togglefullscreen',
label: i18n.__('togglefullscreen'),
accelerator: process.platform === 'darwin' ? 'Cmd+Ctrl+F' : 'F11',
click(item, focusedWindow) {
if (focusedWindow) {
focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
}
}
},
{
type: 'separator'
},
{
label: i18n.__('multiuserbrowser'),
accelerator: 'CmdOrCtrl+M',
type: 'checkbox',
checked: true,
click(item, focusedWindow) {
if (focusedWindow) {
main.store.set('multiUserBrowser', item.checked)
global.multiUserMode = item.checked
}
}
},
{
label: i18n.__('minimalpad'),
accelerator: 'CmdOrCtrl+p',
type: 'checkbox',
checked: true,
click(item, focusedWindow) {
if (focusedWindow) {
main.store.set('minimalPad', item.checked)
global.useMinimalPad = item.checked
}
}
}
]
},
{
label: i18n.__('history'),
submenu: [
{
id: 'history-back',
label: i18n.__('back'),
accelerator: 'CmdOrCtrl+Left',
click(item, focusedWindow) {
main.win.webContents.goBack()
}
},
{
id: 'history-forward',
label: i18n.__('forward'),
accelerator: 'CmdOrCtrl+Right',
click(item, focusedWindow) {
main.win.webContents.goForward()
}
},
{
label: i18n.__('home'),
accelerator: 'CmdOrCtrl+Up',
click(item, focusedWindow) {
main.win.webContents.goToIndex(0)
}
},
{
type: 'separator'
},
{
label: i18n.__('recentlyvisited'),
enabled: false
}
]
},
{
label: i18n.__('bookmarks'),
submenu: [
{
label: i18n.__('localfilesystem'),
class: 'bookmark',
type: 'checkbox',
url: `file://${__dirname}/../index.html`,
accelerator: 'CmdOrCtrl+L',
click(item, focusedWindow) {
selectURL(item.url)
toggleBookmarks(item)
}
},
{
label: i18n.__('testframes'),
class: 'bookmark',
type: 'checkbox',
url: `file://${__dirname}/../index.html?test`,
accelerator: 'CmdOrCtrl+T',
click(item, focusedWindow) {
selectURL(item.url)
toggleBookmarks(item)
}
},
{
type: 'separator'
},
{
id: 'localhost',
label: 'https://localhost:8443',
class: 'bookmark',
type: 'checkbox',
enabled: false,
url: 'https://localhost:8443/index.html',
click(item, focusedWindow) {
selectURL(item.url)
toggleBookmarks(item)
}
},
{
id: 'localhost',
label: 'https://localhost:3000',
class: 'bookmark',
type: 'checkbox',
enabled: true,
url: 'https://localhost:3000/index.html',
click(item, focusedWindow) {
selectURL(item.url)
toggleBookmarks(item)
}
},
// {
// label: 'http://tornado.iwm-kmrc.de:8000',
// class: 'bookmark',
// type: 'checkbox',
// url: 'http://tornado.iwm-kmrc.de:8000/index.html',
// click(item, focusedWindow) {
// selectURL(item.url)
// toggleBookmarks(item)
// }
// },
{
label: 'http://rousseau.iwm-kmrc.de/index.html',
class: 'bookmark',
type: 'checkbox',
url: 'http://rousseau.iwm-kmrc.de/index.html',
click(item, focusedWindow) {
selectURL(item.url)
toggleBookmarks(item)
}
}
]
},
{
label: i18n.__('develop'),
submenu: [
{
id: 'toggledevelopertools',
label: i18n.__('toggledevelopertools'),
accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
click(item, focusedWindow) {
if (focusedWindow) focusedWindow.webContents.toggleDevTools()
}
},
{
label: i18n.__('openprocessmonitor'),
accelerator: process.platform === 'darwin' ? 'Alt+Command+P' : 'Ctrl+Shift+P',
click(item, focusedWindow) {
openProcessManager()
}
},
{
type: 'separator'
},
{
label: i18n.__('selectfolder'),
accelerator: process.platform === 'darwin' ? 'Alt+Command+D' : 'Ctrl+Shift+D',
click(item, focusedWindow) {
if (process.platform === 'win32') {
var exec = require('child_process').exec
exec('NET SESSION', function (err, so, se) {
const admin = se.length === 0 ? true : false
if (admin) {
showFolderBrowser(focusedWindow)
} else {
dialog.showMessageBox({
type: 'error',
icon: path.join(__dirname, '../assets/icons/png/512x512-empty.png'),
buttons: [i18n.__('selectfolder.noadmin.ok')],
message: i18n.__('selectfolder.noadmin.message'),
detail: i18n.__('selectfolder.noadmin.detail')
})
}
})