forked from marktext/marktext
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.js
More file actions
623 lines (538 loc) · 18.3 KB
/
file.js
File metadata and controls
623 lines (538 loc) · 18.3 KB
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
import fs from 'fs-extra'
import path from 'path'
import { BrowserWindow, app, dialog, ipcMain, shell } from 'electron'
import log from 'electron-log'
import { isDirectory, isFile, exists } from 'common/filesystem'
import { MARKDOWN_EXTENSIONS, isMarkdownFile } from 'common/filesystem/paths'
import { checkUpdates, userSetting } from './marktext'
import { showTabBar } from './view'
import { COMMANDS } from '../../commands'
import { EXTENSION_HASN, PANDOC_EXTENSIONS, URL_REG } from '../../config'
import { normalizeAndResolvePath, writeFile } from '../../filesystem'
import { writeMarkdownFile } from '../../filesystem/markdown'
import { getPath, getRecommendTitleFromMarkdownString } from '../../utils'
import pandoc from '../../utils/pandoc'
// TODO(refactor): "save" and "save as" should be moved to the editor window (editor.js) and
// the renderer should communicate only with the editor window for file relevant stuff.
// E.g. "mt::save-tabs" --> "mt::window-save-tabs$wid:<windowId>"
const getExportExtensionFilter = type => {
if (type === 'pdf') {
return [{
name: 'Portable Document Format',
extensions: ['pdf']
}]
} else if (type === 'styledHtml') {
return [{
name: 'Hypertext Markup Language',
extensions: ['html']
}]
}
// Allow all extensions.
return undefined
}
const getPdfPageOptions = options => {
if (!options) {
return {}
}
const { pageSize, pageSizeWidth, pageSizeHeight, isLandscape } = options
if (pageSize === 'custom' && pageSizeWidth && pageSizeHeight) {
return {
// Note: mm to microns
pageSize: { height: pageSizeHeight * 1000, width: pageSizeWidth * 1000 },
landscape: !!isLandscape
}
} else {
return { pageSize, landscape: !!isLandscape }
}
}
// Handle the export response from renderer process.
const handleResponseForExport = async (e, { type, content, pathname, title, pageOptions }) => {
const win = BrowserWindow.fromWebContents(e.sender)
const extension = EXTENSION_HASN[type]
const dirname = pathname ? path.dirname(pathname) : getPath('documents')
let nakedFilename = pathname ? path.basename(pathname, '.md') : title
if (!nakedFilename) {
nakedFilename = 'Untitled'
}
const defaultPath = path.join(dirname, `${nakedFilename}${extension}`)
const { filePath, canceled } = await dialog.showSaveDialog(win, {
defaultPath,
filters: getExportExtensionFilter(type)
})
if (filePath && !canceled) {
try {
if (type === 'pdf') {
const options = { printBackground: true }
Object.assign(options, getPdfPageOptions(pageOptions))
const data = await win.webContents.printToPDF(options)
removePrintServiceFromWindow(win)
await writeFile(filePath, data, extension, 'binary')
} else {
if (!content) {
throw new Error('No HTML content found.')
}
await writeFile(filePath, content, extension, 'utf8')
}
win.webContents.send('mt::export-success', { type, filePath })
} catch (err) {
log.error('Error while exporting:', err)
const ERROR_MSG = err.message || `Error happened when export ${filePath}`
win.webContents.send('mt::show-notification', {
title: 'Export failure',
type: 'error',
message: ERROR_MSG
})
}
} else {
// User canceled save dialog
if (type === 'pdf') {
removePrintServiceFromWindow(win)
}
}
}
const handleResponseForPrint = e => {
const win = BrowserWindow.fromWebContents(e.sender)
win.webContents.print({ printBackground: true }, () => {
removePrintServiceFromWindow(win)
})
}
const handleResponseForSave = async (e, { id, filename, markdown, pathname, options, defaultPath }) => {
const win = BrowserWindow.fromWebContents(e.sender)
let recommendFilename = getRecommendTitleFromMarkdownString(markdown)
if (!recommendFilename) {
recommendFilename = filename || 'Untitled'
}
// If the file doesn't exist on disk add it to the recently used documents later
// and execute file from filesystem watcher for a short time. The file may exists
// on disk nevertheless but is already tracked by MarkText.
const alreadyExistOnDisk = !!pathname
let filePath = pathname
if (!filePath) {
const { filePath: dialogPath, canceled } = await dialog.showSaveDialog(win, {
defaultPath: path.join(defaultPath || getPath('documents'), `${recommendFilename}.md`)
})
if (dialogPath && !canceled) {
filePath = dialogPath
}
}
// Save dialog canceled by user - no error.
if (!filePath) {
return Promise.resolve()
}
filePath = path.resolve(filePath)
const extension = path.extname(filePath) || '.md'
filePath = !filePath.endsWith(extension) ? filePath += extension : filePath
return writeMarkdownFile(filePath, markdown, options, win)
.then(() => {
if (!alreadyExistOnDisk) {
ipcMain.emit('window-add-file-path', win.id, filePath)
ipcMain.emit('menu-add-recently-used', filePath)
const filename = path.basename(filePath)
win.webContents.send('mt::set-pathname', { id, pathname: filePath, filename })
} else {
ipcMain.emit('window-file-saved', win.id, filePath)
win.webContents.send('mt::tab-saved', id)
}
return id
})
.catch(err => {
log.error('Error while saving:', err)
win.webContents.send('mt::tab-save-failure', id, err.message)
})
}
const showUnsavedFilesMessage = async (win, files) => {
const { response } = await dialog.showMessageBox(win, {
type: 'warning',
buttons: ['Save', 'Cancel', 'Don\'t save'],
defaultId: 0,
message: `Do you want to save the changes you made to ${files.length} ${files.length === 1 ? 'file' : 'files'}?\n\n${files.map(f => f.filename).join('\n')}`,
detail: 'Your changes will be lost if you don\'t save them.',
cancelId: 1,
noLink: true
})
switch (response) {
case 2:
return { needSave: false }
case 0:
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ needSave: true })
})
})
default:
return null
}
}
const noticePandocNotFound = win => {
return win.webContents.send('mt::pandoc-not-exists', {
title: 'Import Warning',
type: 'warning',
message: 'Install pandoc before you want to import files.',
time: 10000
})
}
const openPandocFile = async (windowId, pathname) => {
try {
const converter = pandoc(pathname, 'markdown')
const data = await converter()
ipcMain.emit('app-open-markdown-by-id', windowId, data)
} catch (err) {
log.error('Error while converting file:', err)
}
}
const removePrintServiceFromWindow = win => {
// remove print service content and restore GUI
win.webContents.send('mt::print-service-clearup')
}
// --- events -----------------------------------
ipcMain.on('mt::save-tabs', (e, unsavedFiles) => {
Promise.all(unsavedFiles.map(file => handleResponseForSave(e, file)))
.catch(log.error)
})
ipcMain.on('mt::save-and-close-tabs', async (e, unsavedFiles) => {
const win = BrowserWindow.fromWebContents(e.sender)
const userResult = await showUnsavedFilesMessage(win, unsavedFiles)
if (!userResult) {
return
}
const { needSave } = userResult
if (needSave) {
Promise.all(unsavedFiles.map(file => handleResponseForSave(e, file)))
.then(arr => {
const tabIds = arr.filter(id => id != null)
win.webContents.send('mt::force-close-tabs-by-id', tabIds)
})
.catch(err => {
log.error('Error while save all:', err)
})
} else {
const tabIds = unsavedFiles.map(f => f.id)
win.webContents.send('mt::force-close-tabs-by-id', tabIds)
}
})
ipcMain.on('mt::response-file-save-as', async (e, { id, filename, markdown, pathname, options, defaultPath }) => {
const win = BrowserWindow.fromWebContents(e.sender)
let recommendFilename = getRecommendTitleFromMarkdownString(markdown)
if (!recommendFilename) {
recommendFilename = filename || 'Untitled'
}
// If the file doesn't exist on disk add it to the recently used documents later
// and execute file from filesystem watcher for a short time. The file may exists
// on disk nevertheless but is already tracked by MarkText.
const alreadyExistOnDisk = !!pathname
let { filePath, canceled } = await dialog.showSaveDialog(win, {
defaultPath: pathname || path.join(defaultPath || getPath('documents'), `${recommendFilename}.md`)
})
if (filePath && !canceled) {
filePath = path.resolve(filePath)
writeMarkdownFile(filePath, markdown, options, win)
.then(() => {
if (!alreadyExistOnDisk) {
ipcMain.emit('window-add-file-path', win.id, filePath)
ipcMain.emit('menu-add-recently-used', filePath)
const filename = path.basename(filePath)
win.webContents.send('mt::set-pathname', { id, pathname: filePath, filename })
} else if (pathname !== filePath) {
// Update window file list and watcher.
ipcMain.emit('window-change-file-path', win.id, filePath, pathname)
const filename = path.basename(filePath)
win.webContents.send('mt::set-pathname', { id, pathname: filePath, filename })
} else {
ipcMain.emit('window-file-saved', win.id, filePath)
win.webContents.send('mt::tab-saved', id)
}
})
.catch(err => {
log.error('Error while save as:', err)
win.webContents.send('mt::tab-save-failure', id, err.message)
})
}
})
ipcMain.on('mt::close-window-confirm', async (e, unsavedFiles) => {
const win = BrowserWindow.fromWebContents(e.sender)
const userResult = await showUnsavedFilesMessage(win, unsavedFiles)
if (!userResult) {
return
}
const { needSave } = userResult
if (needSave) {
Promise.all(unsavedFiles.map(file => handleResponseForSave(e, file)))
.then(() => {
ipcMain.emit('window-close-by-id', win.id)
})
.catch(err => {
log.error('Error while saving before quit:', err)
// Notify user about the problem.
dialog.showMessageBox(win, {
type: 'error',
buttons: ['Close', 'Keep It Open'],
message: 'Failure while saving files',
detail: err.message
})
.then(({ response }) => {
if (win.id && response === 0) {
ipcMain.emit('window-close-by-id', win.id)
}
})
})
} else {
ipcMain.emit('window-close-by-id', win.id)
}
})
ipcMain.on('mt::response-file-save', handleResponseForSave)
ipcMain.on('mt::response-export', handleResponseForExport)
ipcMain.on('mt::response-print', handleResponseForPrint)
ipcMain.on('mt::window::drop', async (e, fileList) => {
const win = BrowserWindow.fromWebContents(e.sender)
for (const file of fileList) {
if (isMarkdownFile(file)) {
openFileOrFolder(win, file)
continue
}
// Try to import the file
if (PANDOC_EXTENSIONS.some(ext => file.endsWith(ext))) {
const existsPandoc = pandoc.exists()
if (!existsPandoc) {
noticePandocNotFound(win)
} else {
openPandocFile(win.id, file)
}
break
}
}
})
ipcMain.on('mt::rename', async (e, { id, pathname, newPathname }) => {
if (pathname === newPathname) return
const win = BrowserWindow.fromWebContents(e.sender)
const doRename = () => {
fs.rename(pathname, newPathname, err => {
if (err) {
log.error(`mt::rename: Cannot rename "${pathname}" to "${newPathname}".\n${err.stack}`)
return
}
ipcMain.emit('window-change-file-path', win.id, newPathname, pathname)
e.sender.send('mt::set-pathname', {
id,
pathname: newPathname,
filename: path.basename(newPathname)
})
})
}
if (!await exists(newPathname)) {
doRename()
} else {
const { response } = await dialog.showMessageBox(win, {
type: 'warning',
buttons: ['Replace', 'Cancel'],
defaultId: 1,
message: `The file "${path.basename(newPathname)}" already exists. Do you want to replace it?`,
cancelId: 1,
noLink: true
})
if (response === 0) {
doRename()
}
}
})
ipcMain.on('mt::response-file-move-to', async (e, { id, pathname }) => {
const win = BrowserWindow.fromWebContents(e.sender)
const { filePath, canceled } = await dialog.showSaveDialog(win, {
buttonLabel: 'Move to',
nameFieldLabel: 'Filename:',
defaultPath: pathname
})
if (filePath && !canceled) {
fs.rename(pathname, filePath, err => {
if (err) {
log.error(`mt::rename: Cannot rename "${pathname}" to "${filePath}".\n${err.stack}`)
return
}
ipcMain.emit('window-change-file-path', win.id, filePath, pathname)
e.sender.send('mt::set-pathname', { id, pathname: filePath, filename: path.basename(filePath) })
})
}
})
ipcMain.on('mt::ask-for-open-project-in-sidebar', async e => {
const win = BrowserWindow.fromWebContents(e.sender)
const { filePaths } = await dialog.showOpenDialog(win, {
properties: ['openDirectory', 'createDirectory']
})
if (filePaths && filePaths[0]) {
const resolvedPath = normalizeAndResolvePath(filePaths[0])
ipcMain.emit('app-open-directory-by-id', win.id, resolvedPath, true)
}
})
ipcMain.on('mt::format-link-click', (e, { data, dirname }) => {
if (!data || (!data.href && !data.text)) {
return
}
const urlCandidate = data.href || data.text
if (URL_REG.test(urlCandidate)) {
shell.openExternal(urlCandidate)
return
} else if (/^[a-z0-9]+:\/\//i.test(urlCandidate)) {
// Prevent other URLs.
return
}
const href = data.href
if (!href) {
return
}
let pathname = null
if (path.isAbsolute(href)) {
pathname = href
} else if (dirname && !path.isAbsolute(href)) {
pathname = path.join(dirname, href)
}
if (pathname) {
pathname = path.normalize(pathname)
if (isMarkdownFile(pathname)) {
const win = BrowserWindow.fromWebContents(e.sender)
openFileOrFolder(win, pathname)
} else {
shell.openPath(pathname)
}
}
})
// --- commands -------------------------------------
ipcMain.on('mt::cmd-open-file', e => {
const win = BrowserWindow.fromWebContents(e.sender)
openFile(win)
})
ipcMain.on('mt::cmd-new-editor-window', () => {
newEditorWindow()
})
ipcMain.on('mt::cmd-open-folder', e => {
const win = BrowserWindow.fromWebContents(e.sender)
openFolder(win)
})
ipcMain.on('mt::cmd-close-window', e => {
const win = BrowserWindow.fromWebContents(e.sender)
win.close()
})
ipcMain.on('mt::cmd-import-file', e => {
const win = BrowserWindow.fromWebContents(e.sender)
importFile(win)
})
// --- menu -------------------------------------
export const exportFile = (win, type) => {
if (win && win.webContents) {
win.webContents.send('mt::show-export-dialog', type)
}
}
export const importFile = async win => {
const existsPandoc = pandoc.exists()
if (!existsPandoc) {
return noticePandocNotFound(win)
}
const { filePaths } = await dialog.showOpenDialog(win, {
properties: ['openFile'],
filters: [{
name: 'All Files',
extensions: PANDOC_EXTENSIONS
}]
})
if (filePaths && filePaths[0]) {
openPandocFile(win.id, filePaths[0])
}
}
export const printDocument = win => {
if (win) {
win.webContents.send('mt::show-export-dialog', 'print')
}
}
export const openFile = async win => {
const { filePaths } = await dialog.showOpenDialog(win, {
properties: ['openFile', 'multiSelections'],
filters: [{
name: 'Markdown document',
extensions: MARKDOWN_EXTENSIONS
}]
})
if (Array.isArray(filePaths) && filePaths.length > 0) {
ipcMain.emit('app-open-files-by-id', win.id, filePaths)
}
}
export const openFolder = async win => {
const { filePaths } = await dialog.showOpenDialog(win, {
properties: ['openDirectory', 'createDirectory']
})
if (filePaths && filePaths[0]) {
openFileOrFolder(win, filePaths[0])
}
}
export const openFileOrFolder = (win, pathname) => {
const resolvedPath = normalizeAndResolvePath(pathname)
if (isFile(resolvedPath)) {
ipcMain.emit('app-open-file-by-id', win.id, resolvedPath)
} else if (isDirectory(resolvedPath)) {
ipcMain.emit('app-open-directory-by-id', win.id, resolvedPath)
} else {
console.error(`[ERROR] Cannot open unknown file: "${resolvedPath}"`)
}
}
export const newBlankTab = win => {
if (win && win.webContents) {
win.webContents.send('mt::new-untitled-tab')
showTabBar(win)
}
}
export const newEditorWindow = () => {
ipcMain.emit('app-create-editor-window')
}
export const closeTab = win => {
if (win && win.webContents) {
win.webContents.send('mt::editor-close-tab')
}
}
export const closeWindow = win => {
if (win) {
win.close()
}
}
export const save = win => {
if (win && win.webContents) {
win.webContents.send('mt::editor-ask-file-save')
}
}
export const saveAs = win => {
if (win && win.webContents) {
win.webContents.send('mt::editor-ask-file-save-as')
}
}
export const autoSave = (menuItem, browserWindow) => {
const { checked } = menuItem
ipcMain.emit('set-user-preference', { autoSave: checked })
}
export const moveTo = win => {
if (win && win.webContents) {
win.webContents.send('mt::editor-move-file')
}
}
export const rename = win => {
if (win && win.webContents) {
win.webContents.send('mt::editor-rename-file')
}
}
export const clearRecentlyUsed = () => {
ipcMain.emit('menu-clear-recently-used')
}
// --- Commands -------------------------------------------------------------
export const loadFileCommands = commandManager => {
commandManager.add(COMMANDS.FILE_CHECK_UPDATE, checkUpdates)
commandManager.add(COMMANDS.FILE_CLOSE_TAB, closeTab)
commandManager.add(COMMANDS.FILE_CLOSE_WINDOW, closeWindow)
commandManager.add(COMMANDS.FILE_EXPORT_FILE, exportFile)
commandManager.add(COMMANDS.FILE_IMPORT_FILE, importFile)
commandManager.add(COMMANDS.FILE_MOVE_FILE, moveTo)
commandManager.add(COMMANDS.FILE_NEW_FILE, newEditorWindow)
commandManager.add(COMMANDS.FILE_NEW_TAB, newBlankTab)
commandManager.add(COMMANDS.FILE_OPEN_FILE, openFile)
commandManager.add(COMMANDS.FILE_OPEN_FOLDER, openFolder)
commandManager.add(COMMANDS.FILE_PREFERENCES, userSetting)
commandManager.add(COMMANDS.FILE_PRINT, printDocument)
commandManager.add(COMMANDS.FILE_QUIT, app.quit)
commandManager.add(COMMANDS.FILE_RENAME_FILE, rename)
commandManager.add(COMMANDS.FILE_SAVE, save)
commandManager.add(COMMANDS.FILE_SAVE_AS, saveAs)
}