-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.js
1179 lines (1139 loc) · 32.3 KB
/
main.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const {
app,
clipboard,
Menu,
BrowserWindow,
dialog,
shell,
ipcMain,
} = require("electron");
const EventEmitter = require("events");
const crypto = require("crypto");
const request = require("electron-request");
const path = require("path");
const os = require("os");
const cp = require("child_process");
const portfinder = require("portfinder");
const prompt = require("electron-prompt");
const fs = require("fs");
const { unlink } = require("fs/promises");
const util = require("util");
const execFile = util.promisify(cp.execFile);
const mkdir = util.promisify(fs.mkdir);
require("update-electron-app")({
updateInterval: "1 hour",
});
const RANDOM_SECRET = crypto.randomBytes(32).toString("hex");
// 'SQLite format 3\0':
const SQLITE_HEADER = Buffer.from("53514c69746520666f726d6174203300", "hex");
const minPackageVersions = {
datasette: "0.59",
"datasette-app-support": "0.11.8",
"datasette-vega": "0.6.2",
"datasette-cluster-map": "0.17.1",
"datasette-pretty-json": "0.2.1",
"datasette-edit-schema": "0.4",
"datasette-configure-fts": "1.1",
"datasette-leaflet": "0.2.2",
};
let enableDebugMenu = !!process.env.DEBUGMENU;
function configureWindow(window) {
window.webContents.on("will-navigate", function (event, reqUrl) {
// Links to external sites should open in system browser
let requestedHost = new URL(reqUrl).host;
let currentHost = new URL(window.webContents.getURL()).host;
if (requestedHost && requestedHost != currentHost) {
event.preventDefault();
shell.openExternal(reqUrl);
}
});
window.webContents.on("did-fail-load", (event) => {
window.loadFile("did-fail-load.html");
});
window.webContents.on("did-navigate", (event, reqUrl) => {
// Update back/forward button enable status
let menu = Menu.getApplicationMenu();
if (!menu) {
return;
}
let backItem = menu.getMenuItemById("back-item");
let forwardItem = menu.getMenuItemById("forward-item");
if (backItem) {
backItem.enabled = window.webContents.canGoBack();
}
if (forwardItem) {
forwardItem.enabled = window.webContents.canGoForward();
}
});
}
class DatasetteServer {
constructor(app, port) {
this.app = app;
this.port = port;
this.process = null;
this.apiToken = crypto.randomBytes(32).toString("hex");
this.logEmitter = new EventEmitter();
this.cappedServerLog = [];
this.cappedProcessLog = [];
this.accessControl = "localhost";
this.cap = 1000;
}
on(event, listener) {
this.logEmitter.on(event, listener);
}
async openFile(filepath) {
const first16 = await firstBytes(filepath, 16);
let endpoint;
let errorMessage;
if (first16.equals(SQLITE_HEADER)) {
endpoint = "/-/open-database-file";
errorMessage = "Error opening database file";
} else {
endpoint = "/-/open-csv-file";
errorMessage = "Error opening CSV file";
}
const response = await this.apiRequest(endpoint, {
path: filepath,
});
const responseJson = await response.json();
if (!responseJson.ok) {
console.log(responseJson);
dialog.showMessageBox({
type: "error",
message: errorMessage,
detail: responseJson.error,
});
} else {
setTimeout(() => {
this.openPath(responseJson.path);
});
}
}
async about() {
const response = await request(
`http://localhost:${this.port}/-/versions.json`
);
const data = await response.json();
return [
"An open source multi-tool for exploring and publishing data",
"",
`Datasette: ${data.datasette.version}`,
`Python: ${data.python.version}`,
`SQLite: ${data.sqlite.version}`,
].join("\n");
}
async setAccessControl(accessControl) {
if (accessControl == this.accessControl) {
return;
}
this.accessControl = accessControl;
await this.startOrRestart();
}
serverLog(message, type) {
if (!message) {
return;
}
type ||= "stdout";
const item = {
message: message.replace("INFO: ", ""),
type,
ts: new Date(),
};
this.cappedServerLog.push(item);
this.logEmitter.emit("serverLog", item);
this.cappedServerLog = this.cappedServerLog.slice(-this.cap);
}
processLog(item) {
this.cappedProcessLog.push(item);
this.logEmitter.emit("processLog", item);
this.cappedProcessLog = this.cappedProcessLog.slice(-this.cap);
}
serverArgs() {
const args = [
"--port",
this.port,
"--version-note",
"xyz-for-datasette-app",
"--setting",
"sql_time_limit_ms",
"10000",
"--setting",
"max_returned_rows",
"2000",
"--setting",
"facet_time_limit_ms",
"3000",
"--setting",
"max_csv_mb",
"0",
];
if (this.accessControl == "network") {
args.push("--host", "0.0.0.0");
}
return args;
}
serverEnv() {
return {
DATASETTE_API_TOKEN: this.apiToken,
DATASETTE_SECRET: RANDOM_SECRET,
DATASETTE_DEFAULT_PLUGINS: Object.keys(minPackageVersions).join(" "),
};
}
async startOrRestart() {
const venv_dir = await this.ensureVenv();
await this.ensurePackagesInstalled();
const datasette_bin = path.join(venv_dir, "bin", "datasette");
let backupPath = null;
if (this.process) {
// Dump temporary to restore later
backupPath = path.join(
app.getPath("temp"),
`backup-${crypto.randomBytes(8).toString("hex")}.db`
);
await this.apiRequest("/-/dump-temporary-to-file", { path: backupPath });
this.process.kill();
}
return new Promise((resolve, reject) => {
let process;
try {
process = cp.spawn(datasette_bin, this.serverArgs(), {
env: this.serverEnv(),
});
} catch (e) {
reject(e);
}
this.process = process;
process.stderr.on("data", async (data) => {
if (/Uvicorn running/.test(data)) {
serverHasStarted = true;
if (backupPath) {
await this.apiRequest("/-/restore-temporary-from-file", {
path: backupPath,
});
await unlink(backupPath);
}
resolve(`http://localhost:${this.port}/`);
}
for (const line of data.toString().split("\n")) {
this.serverLog(line, "stderr");
}
});
process.stdout.on("data", (data) => {
for (const line of data.toString().split("\n")) {
this.serverLog(line);
}
});
process.on("error", (err) => {
console.error("Failed to start datasette", err);
this.app.quit();
reject();
});
});
}
shutdown() {
this.process.kill();
}
async apiRequest(path, body) {
return await request(`http://localhost:${this.port}${path}`, {
method: "POST",
body: JSON.stringify(body),
headers: {
Authorization: `Bearer ${this.apiToken}`,
},
});
}
async execCommand(command, args) {
return new Promise((resolve, reject) => {
// Use spawn() not execFile() so we can tail stdout/stderr
console.log(command, args);
// I tried process.hrtime() here but consistently got a
// "Cannot access 'process' before initialization" error
const start = new Date().valueOf(); // millisecond timestamp
const process = cp.spawn(command, args);
const collectedErr = [];
this.processLog({
type: "start",
command,
args,
});
process.stderr.on("data", async (data) => {
for (const line of data.toString().split("\n")) {
this.processLog({
type: "stderr",
command,
args,
stderr: line.trim(),
});
collectedErr.push(line.trim());
}
});
process.stdout.on("data", (data) => {
for (const line of data.toString().split("\n")) {
this.processLog({
type: "stdout",
command,
args,
stdout: line.trim(),
});
}
});
process.on("error", (err) => {
this.processLog({
type: "error",
command,
args,
error: err.toString(),
});
reject(err);
});
process.on("exit", (err) => {
let duration_ms = new Date().valueOf() - start;
this.processLog({
type: "end",
command,
args,
duration: duration_ms,
});
if (process.exitCode == 0) {
resolve(process);
} else {
reject(collectedErr.join("\n"));
}
});
});
}
async installPlugin(plugin) {
const pip_binary = path.join(
process.env.HOME,
".datasette-app",
"venv",
"bin",
"pip"
);
await this.execCommand(pip_binary, [
"install",
plugin,
"--disable-pip-version-check",
]);
}
async uninstallPlugin(plugin) {
const pip_binary = path.join(
process.env.HOME,
".datasette-app",
"venv",
"bin",
"pip"
);
await this.execCommand(pip_binary, [
"uninstall",
plugin,
"--disable-pip-version-check",
"-y",
]);
}
async packageVersions() {
const venv_dir = await this.ensureVenv();
const pip_path = path.join(venv_dir, "bin", "pip");
const versionsProcess = await execFile(pip_path, [
"list",
"--format",
"json",
]);
const versions = {};
for (const item of JSON.parse(versionsProcess.stdout)) {
versions[item.name] = item.version;
}
return versions;
}
async ensureVenv() {
const datasette_app_dir = path.join(process.env.HOME, ".datasette-app");
const venv_dir = path.join(datasette_app_dir, "venv");
if (!fs.existsSync(datasette_app_dir)) {
await mkdir(datasette_app_dir);
}
let shouldCreateVenv = true;
if (fs.existsSync(venv_dir)) {
// Check Python interpreter still works, using
// ~/.datasette-app/venv/bin/python3.9 --version
// See https://github.com/simonw/datasette-app/issues/89
const venv_python = path.join(venv_dir, "bin", "python3.9");
try {
await this.execCommand(venv_python, ["--version"]);
shouldCreateVenv = false;
} catch (e) {
fs.rmdirSync(venv_dir, { recursive: true });
}
}
if (shouldCreateVenv) {
await this.execCommand(findPython(), ["-m", "venv", venv_dir]);
}
return venv_dir;
}
async ensurePackagesInstalled() {
const venv_dir = await this.ensureVenv();
// Anything need installing or upgrading?
const needsInstall = [];
for (const [name, requiredVersion] of Object.entries(minPackageVersions)) {
needsInstall.push(`${name}>=${requiredVersion}`);
}
const pip_path = path.join(venv_dir, "bin", "pip");
try {
await this.execCommand(
pip_path,
["install"].concat(needsInstall).concat(["--disable-pip-version-check"])
);
} catch (e) {
dialog.showMessageBox({
type: "error",
message: "Error running pip",
detail: e.toString(),
});
}
await new Promise((resolve) => setTimeout(resolve, 500));
}
openPath(path, opts) {
path = path || "/";
opts = opts || {};
const loadUrlOpts = {
extraHeaders: `authorization: Bearer ${this.apiToken}`,
method: "POST",
postData: [
{
type: "rawData",
bytes: Buffer.from(JSON.stringify({ redirect: path })),
},
],
};
if (
BrowserWindow.getAllWindows().length == 1 &&
(opts.forceMainWindow ||
new URL(BrowserWindow.getAllWindows()[0].webContents.getURL())
.pathname == "/")
) {
// Re-use the single existing window
BrowserWindow.getAllWindows()[0].webContents.loadURL(
`http://localhost:${this.port}/-/auth-app-user`,
loadUrlOpts
);
} else {
// Open a new window
let newWindow = new BrowserWindow({
...windowOpts(),
...{ show: false },
});
newWindow.loadURL(
`http://localhost:${this.port}/-/auth-app-user`,
loadUrlOpts
);
newWindow.once("ready-to-show", () => {
newWindow.show();
});
configureWindow(newWindow);
}
}
}
function findPython() {
const possibilities = [
// In packaged app
path.join(process.resourcesPath, "python", "bin", "python3.9"),
// In development
path.join(__dirname, "python", "bin", "python3.9"),
];
for (const path of possibilities) {
if (fs.existsSync(path)) {
return path;
}
}
console.log("Could not find python3, checked", possibilities);
app.quit();
}
function windowOpts(extraOpts) {
extraOpts = extraOpts || {};
let opts = {
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, extraOpts.preload || "preload.js"),
sandbox: false,
},
};
if (BrowserWindow.getFocusedWindow()) {
const pos = BrowserWindow.getFocusedWindow().getPosition();
opts.x = pos[0] + 22;
opts.y = pos[1] + 22;
}
return opts;
}
let datasette = null;
function createLoadingWindow() {
let mainWindow = new BrowserWindow({
show: false,
...windowOpts(),
});
mainWindow.loadFile("loading.html");
mainWindow.once("ready-to-show", () => {
mainWindow.show();
for (const item of datasette.cappedProcessLog) {
mainWindow.webContents.send("processLog", item);
}
datasette.on("processLog", (item) => {
!mainWindow.isDestroyed() &&
mainWindow.webContents.send("processLog", item);
});
});
configureWindow(mainWindow);
return mainWindow;
}
async function importCsvFromUrl(url, tableName) {
const response = await datasette.apiRequest("/-/open-csv-from-url", {
url: url,
table_name: tableName,
});
const responseJson = await response.json();
if (!responseJson.ok) {
console.log(responseJson);
dialog.showMessageBox({
type: "error",
message: "Error loading CSV file",
detail: responseJson.error,
});
} else {
setTimeout(() => {
datasette.openPath(responseJson.path);
}, 500);
}
}
async function initializeApp() {
/* We don't use openPath here because we want to control the transition from the
loading.html page to the index page once the server has started up */
createLoadingWindow();
let freePort = null;
try {
freePort = await portfinder.getPortPromise({ port: 8001 });
} catch (err) {
console.error("Failed to obtain a port", err);
app.quit();
}
// Start Python Datasette process (if one is not yet running)
if (!datasette) {
datasette = new DatasetteServer(app, freePort);
}
datasette.on("serverLog", (item) => {
console.log(item);
});
await datasette.startOrRestart();
datasette.openPath("/", {
forceMainWindow: true,
});
if (filepathOnOpen) {
await datasette.openFile(filepathOnOpen);
filepathOnOpen = null;
}
app.on("will-quit", () => {
datasette.shutdown();
});
ipcMain.on("install-plugin", async (event, pluginName) => {
try {
await datasette.installPlugin(pluginName);
await datasette.startOrRestart();
dialog.showMessageBoxSync({
type: "info",
message: "Plugin installed",
detail: `${pluginName} is now ready to use`,
});
event.reply("plugin-installed", pluginName);
} catch (error) {
dialog.showMessageBoxSync({
type: "error",
message: "Plugin installation error",
detail: error.toString(),
});
}
});
ipcMain.on("uninstall-plugin", async (event, pluginName) => {
try {
await datasette.uninstallPlugin(pluginName);
await datasette.startOrRestart();
dialog.showMessageBoxSync({
type: "info",
message: "Plugin uninstalled",
detail: `${pluginName} has been removed`,
});
event.reply("plugin-uninstalled", pluginName);
} catch (error) {
dialog.showMessageBoxSync({
type: "error",
message: "Error uninstalling plugin",
detail: error.toString(),
});
}
});
ipcMain.on("import-csv-from-url", async (event, info) => {
await importCsvFromUrl(info.url, info.tableName);
});
ipcMain.on("import-csv", async (event, database) => {
let selectedFiles = dialog.showOpenDialogSync({
properties: ["openFile"],
});
if (!selectedFiles) {
return;
}
let pathToOpen = null;
const response = await datasette.apiRequest("/-/import-csv-file", {
path: selectedFiles[0],
database: database,
});
const responseJson = await response.json();
if (!responseJson.ok) {
console.log(responseJson);
dialog.showMessageBox({
type: "error",
message: "Error importing CSV file",
detail: responseJson.error,
});
} else {
pathToOpen = responseJson.path;
}
setTimeout(() => {
datasette.openPath(pathToOpen);
}, 500);
event.reply("csv-imported", database);
});
let menuTemplate = buildMenu();
var menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
}
function buildMenu() {
const homeItem = {
label: "Home",
click() {
let window = BrowserWindow.getFocusedWindow();
if (window) {
window.webContents.loadURL(`http://localhost:${datasette.port}/`);
}
},
};
const backItem = {
label: "Back",
id: "back-item",
accelerator: "CommandOrControl+[",
click() {
let window = BrowserWindow.getFocusedWindow();
if (window) {
window.webContents.goBack();
}
},
enabled: false,
};
const forwardItem = {
label: "Forward",
id: "forward-item",
accelerator: "CommandOrControl+]",
click() {
let window = BrowserWindow.getFocusedWindow();
if (window) {
window.webContents.goForward();
}
},
enabled: false,
};
app.on("browser-window-focus", (event, window) => {
forwardItem.enabled = window.webContents.canGoForward();
backItem.enabled = window.webContents.canGoBack();
});
function buildNetworkChanged(setting) {
return async function () {
await datasette.setAccessControl(setting);
Menu.setApplicationMenu(Menu.buildFromTemplate(buildMenu()));
};
}
const onlyMyComputer = {
label: "Only my computer",
type: "radio",
checked: datasette.accessControl == "localhost",
click: buildNetworkChanged("localhost"),
};
const anyoneOnNetwork = {
label: "Anyone on my networks",
type: "radio",
checked: datasette.accessControl == "network",
click: buildNetworkChanged("network"),
};
// Gather IPv4 addresses
const ips = new Set();
for (const [key, networkIps] of Object.entries(os.networkInterfaces())) {
networkIps.forEach((details) => {
const ip = details.address;
if (details.family == "IPv4" && ip != "127.0.0.1") {
ips.add(ip);
}
});
}
const accessControlItems = [
onlyMyComputer,
anyoneOnNetwork,
{ type: "separator" },
{
label: "Open in Browser",
click() {
shell.openExternal(`http://localhost:${datasette.port}/`);
},
},
];
if (datasette.accessControl == "network") {
for (let ip of ips) {
accessControlItems.push({
label: `Copy http://${ip}:${datasette.port}/`,
click() {
clipboard.writeText(`http://${ip}:${datasette.port}/`);
},
});
}
}
const menuTemplate = [
{
label: "Menu",
submenu: [
{
label: "About Datasette",
async click() {
let buttons = ["Visit datasette.io", "OK"];
if (!enableDebugMenu) {
buttons.push("Enable Debug Menu");
}
dialog
.showMessageBox({
type: "info",
message: `Datasette Desktop ${app.getVersion()}`,
detail: await datasette.about(),
buttons: buttons,
})
.then((click) => {
console.log(click);
if (click.response == 0) {
shell.openExternal("https://datasette.io/");
}
if (click.response == 2) {
enableDebugMenu = true;
Menu.setApplicationMenu(Menu.buildFromTemplate(buildMenu()));
}
});
},
},
{ type: "separator" },
{
role: "quit",
},
],
},
{
label: "File",
submenu: [
{
label: "New Window",
accelerator: "CommandOrControl+N",
click() {
let newWindow = new BrowserWindow({
...windowOpts(),
...{ show: false },
});
newWindow.loadURL(`http://localhost:${datasette.port}`);
newWindow.once("ready-to-show", () => {
newWindow.show();
});
configureWindow(newWindow);
},
},
{ type: "separator" },
{
label: "Open Recent",
role: "recentdocuments",
submenu: [
{ label: "Clear Recent Items", role: "clearrecentdocuments" },
],
},
{ type: "separator" },
{
label: "Open CSV…",
accelerator: "CommandOrControl+O",
click: async () => {
let selectedFiles = dialog.showOpenDialogSync({
properties: ["openFile", "multiSelections"],
});
if (!selectedFiles) {
return;
}
let pathToOpen = null;
for (const filepath of selectedFiles) {
app.addRecentDocument(filepath);
const response = await datasette.apiRequest("/-/open-csv-file", {
path: filepath,
});
const responseJson = await response.json();
if (!responseJson.ok) {
console.log(responseJson);
dialog.showMessageBox({
type: "error",
message: "Error opening CSV file",
detail: responseJson.error,
});
} else {
pathToOpen = responseJson.path;
}
}
setTimeout(() => {
datasette.openPath(pathToOpen);
}, 500);
},
},
{
label: "Open CSV from URL…",
click: async () => {
prompt({
title: "Open CSV from URL",
label: "URL:",
type: "input",
alwaysOnTop: true,
})
.then(async (url) => {
if (url !== null) {
await importCsvFromUrl(url);
}
})
.catch(console.error);
},
},
{ type: "separator" },
{
label: "Open Database…",
accelerator: "CommandOrControl+D",
click: async () => {
let selectedFiles = dialog.showOpenDialogSync({
properties: ["openFile", "multiSelections"],
});
if (!selectedFiles) {
return;
}
let pathToOpen = null;
for (const filepath of selectedFiles) {
const response = await datasette.apiRequest(
"/-/open-database-file",
{ path: filepath }
);
const responseJson = await response.json();
if (!responseJson.ok) {
console.log(responseJson);
dialog.showMessageBox({
type: "error",
message: "Error opening database file",
detail: responseJson.error,
});
} else {
app.addRecentDocument(filepath);
pathToOpen = responseJson.path;
}
}
setTimeout(() => {
datasette.openPath(pathToOpen);
}, 500);
},
},
{
label: "New Empty Database…",
accelerator: "CommandOrControl+Shift+N",
click: async () => {
const filepath = dialog.showSaveDialogSync({
defaultPath: "database.db",
title: "Create Empty Database",
});
if (!filepath) {
return;
}
const response = await datasette.apiRequest(
"/-/new-empty-database-file",
{ path: filepath }
);
const responseJson = await response.json();
if (!responseJson.ok) {
console.log(responseJson);
dialog.showMessageBox({
type: "error",
title: "Datasette",
message: responseJson.error,
});
} else {
datasette.openPath(responseJson.path);
}
},
},
{ type: "separator" },
{
label: "Access Control",
submenu: accessControlItems,
},
{ type: "separator" },
{
role: "close",
},
],
},
{ role: "editMenu" },
{
label: "Navigate",
submenu: [
homeItem,
backItem,
forwardItem,
{
label: "Reload Current Page",
accelerator: "CommandOrControl+R",
click() {
let window = BrowserWindow.getFocusedWindow();
if (window) {
window.webContents.reload();
}
},
},
],
},
{
label: "Plugins",
submenu: [
{
label: "Install and Manage Plugins…",
click() {
datasette.openPath(
"/plugin_directory/plugins?_sort_desc=stargazers_count&_facet=installed&_facet=upgrade"
);
},
},
{
label: "About Datasette Plugins",
click() {
shell.openExternal("https://datasette.io/plugins");
},
},
],
},
{
role: "help",
submenu: [
{
label: "Learn More",
click: async () => {
await shell.openExternal("https://datasette.io/");
},
},
],
},
];
if (enableDebugMenu) {
const enableChromiumDevTools = !!BrowserWindow.getAllWindows().length;
menuTemplate.push({
label: "Debug",
submenu: [
{
label: "Open Chromium DevTools",
enabled: enableChromiumDevTools,
click() {
(
BrowserWindow.getFocusedWindow() ||
BrowserWindow.getAllWindows()[0]
).webContents.openDevTools();
},
},
{ type: "separator" },
{
label: "Show Server Log",
click() {
/* Is it open already? */
let browserWindow = null;
let existing = BrowserWindow.getAllWindows().filter((bw) =>
bw.webContents.getURL().endsWith("/server-log.html")
);
if (existing.length) {
browserWindow = existing[0];
browserWindow.focus();
} else {
browserWindow = new BrowserWindow(
windowOpts({
preload: "server-log-preload.js",
})
);
browserWindow.loadFile("server-log.html");
datasette.on("serverLog", (item) => {
!browserWindow.isDestroyed() &&
browserWindow.webContents.send("serverLog", item);