-
Notifications
You must be signed in to change notification settings - Fork 8
/
happ-ui-controller.js
375 lines (328 loc) · 11.6 KB
/
happ-ui-controller.js
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
const { BrowserView, dialog, protocol, session, ipcMain, shell } = require('electron')
const { ncp } = require('ncp')
const fs = require('fs')
const path = require('path')
const conductor = require('./conductor.js')
const url = require('url')
const HAPP_SCHEME = 'holoscape-happ'
function UIinfoFile(){
return path.join(conductor.rootConfigPath(), 'UIs.json')
}
function loadUIinfo() {
if(!fs.existsSync(UIinfoFile())) {
return {}
} else {
return JSON.parse(fs.readFileSync(UIinfoFile()))
}
}
function sanitizeUINameForScheme(name) {
name = name.split('_').join('-')
name = name.split(' ').join('-')
name = name.toLowerCase()
return name
}
function setupWindowDevProduction(window) {
if(process.env.DEV) {
window.webContents.openDevTools()
} else {
window.setMenu(null)
window.removeMenu()
}
}
const happProtocolCallback = (request, callback) => {
console.log(`HAPP SCHEME: got request for file ${request.url}`)
const url = request.url.substr(HAPP_SCHEME.length+1)
console.log('URL:', url)
const urlPath = path.normalize(url)
console.log('urlPath:', urlPath)
const happDir = urlPath.split('/')[1]
console.log('happDir:', happDir)
const uiRootDir = path.join(conductor.rootConfigPath(), 'UIs', happDir)
let absoluteFilePath
const base = `${HAPP_SCHEME}://${happDir}`
if(request.url.startsWith(base) && request.url.length > base.length+1){
const url = request.url.substr(base.length)
if(url.startsWith(__dirname)) {
absoluteFilePath = url
} else {
if(url.endsWith('_dna_connections.json')) {
absoluteFilePath = path.join(conductor.rootConfigPath(), 'UIs', `${happDir}-interface.json`)
} else {
let filePath = path.normalize(url)
filePath = filePath.split("#")[0]
filePath = filePath.split("?")[0]
if(filePath == "/") {
filePath = "/index.html"
}
absoluteFilePath = path.join(uiRootDir, filePath)
}
}
} else {
absoluteFilePath = path.join(uiRootDir, 'index.html')
}
console.log('Redirecting to:', absoluteFilePath)
callback({ path: absoluteFilePath })
}
/// This controller is managing all the custom hApp UIs that can be installed.
/// It stores a list of all installed UIs with their installation directory and
/// potentially set zome interface in `installedUIs`, which gets persisted
/// to UIInfoFile().
///
/// It looks like this:
/// ```js
/// installedUIs = {
/// 'basic-chat': {
/// installDir: '/home/lucksus/.config/Holoscape/UIs/basic-chat',
/// interface: 'basic-chat-interface'
/// }
/// }
/// ```
///
/// When a hApp UI is shown for the first time, `showHideUi(name)` calls `createUI(name)`
/// which creates a separate BrowserWindow for that UI. All existing BrowserWindows are
/// stored in `runningUIs`.
///
/// In order to make a web UI that was build to be hosted by an HTTP server work inside
/// these browser windows served from file-system, we are registering a custom URI scheme per UI
/// in the format of 'happ-<name>' where any URL 'happ-<name>://<resource>` will be redirected
/// to the `installDir` of that hApp UI.
class HappUiController {
installedUIs = {};
runningUIs = {};
holoscape;
mainWindow;
activeUI;
constructor(hs) {
this.holoscape = hs
this.installedUIs = loadUIinfo()
ipcMain.on('request-activate-happ-window', (event, args) => {
let name = args.uiToActivate
if(this.installedUIs[name]) {
console.log(`${args.requester} requested to show another UI: ${name}`)
this.showAndRiseUI(args.uiToActivate, args.location)
} else {
console.log(`${args.requester} requested to show non-existant UI: ${name}`)
}
})
ipcMain.on('show-developer-tools', (event, uiName) => {
console.log("got show dev tools:", uiName)
let happView = this.runningUIs[uiName]
if(happView) {
happView.webContents.openDevTools()
}
})
console.log('Registering file protocol:', HAPP_SCHEME)
protocol.registerFileProtocol(HAPP_SCHEME, happProtocolCallback, (error) => {
if(error) throw error
})
}
setMainWindow(mainWindow) {
this.mainWindow = mainWindow
this.mainWindow.on('resize', () => {
if(this.activeUI && this.runningUIs[this.activeUI]) {
this.showView(this.runningUIs[this.activeUI])
}
})
}
createUiMenuTemplate() {
let menuTemplate = []
for(let uiName in this.installedUIs) {
let visible = false
// if(this.runningUIs[uiName] && this.runningUIs[uiName].isVisible()) {
// visible = true
// }
menuTemplate.push({
label: uiName,
//click: ()=>this.showHideUI(uiName),
type: 'checkbox',
checked: visible
})
}
return menuTemplate
}
saveUIinfo() {
fs.writeFileSync(UIinfoFile(), JSON.stringify(this.installedUIs))
}
installUI() {
let sourcePath = dialog.showOpenDialogSync({
title: 'Holoscape',
message: 'Install a web UI directory as hApp',
properties: ['openDirectory'],
})
if(!sourcePath) return
sourcePath = sourcePath[0]
this.installUIFromPath(sourcePath, path.basename(sourcePath))
}
installUIFromPath(sourcePath, name) {
let UIsDir = path.join(conductor.rootConfigPath(), 'UIs')
let installDir = path.join(UIsDir, sanitizeUINameForScheme(name))
if(fs.existsSync(installDir)) {
dialog.showErrorBox('Holoscape', 'UI with name '+name+' already installed!')
return
}
if(!fs.existsSync(UIsDir)) {
fs.mkdirSync(UIsDir)
}
const that = this
return new Promise((resolve, reject) => {
ncp(sourcePath, installDir, (err) => {
//if(err) reject(err)
//else
resolve()
})
})
.then(() => {
that.installedUIs[name] = {installDir}
that.saveUIinfo()
that.holoscape.updateTrayMenu()
that.holoscape.notifyNewHapp(name, that.installedUIs[name])
})
.catch((err) => {
dialog.showErrorBox('Holoscape', JSON.stringify(err))
})
}
getInstalledUIs() {
return this.installedUIs
}
async setUiInterface(uiName, interfaceId) {
console.log('Setting ui interface:',uiName, interfaceId)
this.installedUIs[uiName].interface = interfaceId
this.saveUIinfo()
let interfaces = await global.conductor_call('admin/interface/list')()
let interfaceConfig = interfaces.find((i) => i.id == interfaceId)
const dnaInterfaceConfig = {dna_interface: interfaceConfig}
const sanitizedUiName = sanitizeUINameForScheme(uiName)
const filePath = path.join(conductor.rootConfigPath(), 'UIs', `${sanitizedUiName}-interface.json`)
fs.writeFileSync(filePath, JSON.stringify(dnaInterfaceConfig))
const window = this.runningUIs[uiName]
if(window) {
window.reload()
}
}
async createUI(name) {
console.log('Creating UI for', name)
if(!this.installedUIs[name]){
console.error('Tried to open unknown UI', name)
return
}
if(this.runningUIs[name]) {
console.log('Already have UI for', name, '. Showing...')
this.runningUIs[name].show()
return
}
const partition = `persist:${name}`
const ses = session.fromPartition(partition)
const uiRootDir = this.installedUIs[name].installDir
const uiSubDir = path.basename(uiRootDir)
const protocolError = await new Promise((resolve, reject) => {
ses.protocol.registerFileProtocol(HAPP_SCHEME, happProtocolCallback, (error) => {
if (error) reject('Failed to register protocol '+error)
else resolve()
})
})
if(protocolError) {
console.error('Could not register custom hApp protocol in session: ', protocolError)
return
}
let view = new BrowserView({
webPreferences: {
nodeIntegration: true,
title: name,
partition,
preload: path.join(__dirname, 'happ-ui-preload.js')
},
})
this.mainWindow.addBrowserView(view)
view.uiName = name
const windowURL = `${HAPP_SCHEME}://${uiSubDir}/`
console.log('Created view. Loading', windowURL)
view.webContents.loadURL(windowURL)
// Open <a href='' target='_blank'> with default system browser
view.webContents.on("new-window", function (event, url) {
event.preventDefault()
shell.openExternal(url)
})
//setupWindowDevProduction(view)
let holoscape = this.holoscape
view.on('close', (event) => {
if(!holoscape.quitting) event.preventDefault();
view.hide();
holoscape.updateTrayMenu()
})
this.runningUIs[name] = view
}
showView(view) {
let mainWindowBounds = this.mainWindow.getBounds()
view.setBounds({x: 300, y: 0, width: mainWindowBounds.width-300, height: mainWindowBounds.height-66})
}
hideView(view) {
view.setBounds({x: -200, y: 0, width: 100, height: 100})
}
showHappUi(name) {
let view = this.runningUIs[name]
if(!view) {
this.createUI(name).then(() => {
view = this.runningUIs[name]
this.showView(view)
})
} else {
this.showView(view)
}
for(let viewName in this.runningUIs) {
if(viewName != name) {
let view = this.runningUIs[viewName]
this.hideView(view)
}
}
this.activeUI = name
}
hideAllHappUis() {
for(let viewName in this.runningUIs) {
this.hideView(this.runningUIs[viewName])
}
}
async ensureWindowFor(name) {
if(!this.runningUIs[name]) {
await this.createUI(name)
}
return this.runningUIs[name]
}
async showAndRiseUI(name, location) {
this.ensureWindowFor(name).then((window)=>{
this.hideAllHappUis()
this.showHappUi(name)
this.holoscape.notifyUiActivated(name)
console.log(window)
const uiRootDir = this.installedUIs[name].installDir
const uiSubDir = path.basename(uiRootDir)
if(location){
window.loadURL(url.format({
pathname: path.join(uiSubDir, './index.html'),
protocol: HAPP_SCHEME,
slashes: true,
hash: location
}))
console.log(`Opening ${name} at ${location}`)
} else {
console.log(`Reloading ${name}`)
window.loadURL(url.format({
pathname: path.join(uiSubDir, './index.html'),
protocol: HAPP_SCHEME,
slashes: true,
hash: '/'
}))
}
}).catch(err => {
console.log('showAndRiseUI error')
console.log(err)
})
}
}
module.exports = {
HappUiController,
UIinfoFile,
loadUIinfo,
sanitizeUINameForScheme,
HAPP_SCHEME,
setupWindowDevProduction,
}