/
main-window.js
6771 lines (5762 loc) · 206 KB
/
main-window.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 {ipcRenderer, shell, remote, nativeImage, clipboard} = require('electron')
const { app } = require('electron').remote
const child_process = require('child_process')
const fs = require('fs-extra')
const os = require('os')
const dns = require('dns')
const path = require('path')
const menu = require('../menu')
const util = require('../utils/index')
const Color = require('color-js')
const chokidar = require('chokidar')
const plist = require('plist')
const R = require('ramda')
const CAF = require('caf')
const isDev = require('electron-is-dev')
const { getInitialStateRenderer } = require('electron-redux')
const configureStore = require('../shared/store/configureStore')
const observeStore = require('../shared/helpers/observeStore')
const StoryboarderSketchPane = require('./storyboarder-sketch-pane')
const { SketchPane } = require('alchemancy')
const SketchPaneUtil = require('alchemancy').util
const undoStack = require('../undo-stack')
const Toolbar = require('./toolbar')
const tooltips = require('./tooltips')
const ContextMenu = require('./context-menu')
const ColorPicker = require('./color-picker')
const PomodoroTimerView = require('./pomodoro-timer-view')
const Transport = require('./transport')
const notifications = require('./notifications')
const NotificationData = require('../../data/messages.json')
const Guides = require('./guides')
const OnionSkin = require('./onion-skin')
const Sonifier = require('./sonifier/index')
const LayersEditor = require('./layers-editor')
const DiagnosticsView = require('./diagnostics-view')
const sfx = require('../wonderunit-sound')
const keytracker = require('../utils/keytracker')
const createIsCommandPressed = keytracker.createIsCommandPressed
const SceneTimelineView = require('./scene-timeline-view')
const storyTips = new(require('./story-tips'))(sfx, notifications)
const exporter = require('./exporter')
const exporterCommon = require('../exporters/common')
const exporterCopyProject = require('../exporters/copy-project')
const exporterArchive = require('../exporters/archive')
const exporterWeb = require('../exporters/web')
const exporterPsd = require('../exporters/psd')
const importerPsd = require('../importers/psd')
const sceneSettingsView = require('./scene-settings-view')
const boardModel = require('../models/board')
const FileHelper = require('../files/file-helper')
const ShotTemplateSystem = require('../shot-template-system')
const StsSidebar = require('./sts-sidebar')
const AudioPlayback = require('./audio-playback')
const AudioFileControlView = require('./audio-file-control-view')
const pkg = require('../../../package.json')
const sharedObj = remote.getGlobal('sharedObj')
const store = configureStore(getInitialStateRenderer(), 'renderer')
window.$r = { store } // for debugging, e.g.: $r.store.getStore()
const isCommandPressed = createIsCommandPressed(store)
const prefsModule = require('electron').remote.require('./prefs')
prefsModule.init(path.join(app.getPath('userData'), 'pref.json'))
// we're gradually migrating prefs to a reducer
// we read any 2.0 toolbar related prefs into the toolbar reducer manually
// NOTE this is async so preferences will be invalid until main IPC dispatches back to renderers
if (prefsModule.getPrefs().toolbar) {
store.dispatch({
type: 'TOOLBAR_MERGE_FROM_PREFERENCES', payload: prefsModule.getPrefs()
})
}
const CanvasRecorder = require('../recording/canvas-recorder')
const moment = require('moment')
let isRecording = false
let isRecordingStarted = false
let canvasRecorder
let boardFilename // absolute path to .storyboarder
let boardPath
let boardData
let currentBoard = 0
let scriptFilePath // .fountain/.fdx, only used for multi-scene projects
let scriptData
let locations
let characters
let boardSettings
let currentPath
let currentScene = 0
let boardFileDirty = false
let boardFileDirtyTimer
let recordingToBoardIndex = undefined
let watcher // for chokidar
const ALLOWED_AUDIO_FILE_EXTENSIONS = [
'wav',
'mp3',
'm4a',
'mp4'
]
let imageFileDirtyTimer
let isSavingImageFile = false // lock for saveImageFile
let drawIdleTimer
let isEditMode = false
let editModeTimer
let enableEditModeDelay = 750 // msecs
let periodicDragUpdateTimer
let periodicDragUpdatePeriod = 30 // msecs
let mouseDragStartX
let textInputMode = false
let textInputAllowAdvance = false
let viewMode = 0
let selections = new Set()
let thumbnailCursor = {
visible: false,
x: 0,
el: null
}
let lastPointer = { x: null, y: null }
let toolbar
let contextMenu
let colorPicker
let transport
let guides
let onionSkin
let layersEditor
let pomodoroTimerView
let shotTemplateSystem
let audioPlayback
let audioFileControlView
let sceneTimelineView
let timelineModeControlView
let storyboarderSketchPane
let exportWebWindow
let dragMode = false
let preventDragMode = false
let dragPoint
let dragTarget
let scrollPoint
// CAF cancel tokens for async functions
let cancelTokens = {}
const msecsToFrames = value => Math.round(value / 1000 * boardData.fps)
const framesToMsecs = value => Math.round(value / boardData.fps * 1000)
// TODO better name than etags?
// TODO store in boardData instead, but exclude from JSON?
// TODO use mtime trick like we do for layers and posterframes?
// cache buster for thumbnails
let etags = {}
const setEtag = absoluteFilePath => { etags[absoluteFilePath] = Date.now() }
const getEtag = absoluteFilePath => etags[absoluteFilePath] || '0'
const cacheKey = filepath => {
try {
// file exists, cache based on mtime
return fs.statSync(filepath).mtimeMs
} catch (err) {
// file not found, cache buster based on current time
return Date.now()
}
}
let srcByUid = {} // TODO review, was used for setThumbnailDisplayAsPending, do we still need it?
let shouldRenderThumbnailDrawer = true
// analytics.event('Application', 'open', filename)
// flag set after we've warned about FPS at least once since this window opened
let hasWarnedOnceAboutFps = false
remote.getCurrentWindow().on('focus', () => {
menu.setMenu()
// HACK update to reflect current value
audioPlayback && audioPlayback.setEnableAudition(audioPlayback.enableAudition)
})
///////////////////////////////////////////////////////////////
// Loading / Init Operations
///////////////////////////////////////////////////////////////
const load = async (event, args) => {
try {
if (args[1]) {
log({ type: 'progress', message: 'Loading Project with Script' })
console.log("LOADING SCRIPT FILE", args[0])
ipcRenderer.send('analyticsEvent', 'Application', 'open script', args[0])
scriptFilePath = args[0]
// there is scriptData - the window opening is a script type
scriptData = args[1]
locations = args[2]
characters = args[3]
boardSettings = args[4]
currentPath = args[5]
await updateSceneFromScript()
store.dispatch({
type: 'SCENE_FILE_LOADED',
payload: { path: boardFilename }
})
} else {
log({ type: 'progress', message: 'Loading Project File' })
// if not, its just a simple single boarder file
boardFilename = args[0]
boardPath = boardFilename.split(path.sep)
boardPath.pop()
boardPath = boardPath.join(path.sep)
console.log(' BOARD PATH: ', boardFilename)
try {
boardData = JSON.parse(fs.readFileSync(boardFilename))
ipcRenderer.send('analyticsEvent', 'Application', 'open', boardFilename, boardData.boards.length)
store.dispatch({
type: 'SCENE_FILE_LOADED',
payload: { path: boardFilename }
})
} catch (error) {
throw new Error(`Could not read file ${path.basename(boardFilename)}. The file may be inaccessible or corrupt.\nError: ${error.message}`)
}
}
migrateScene()
await loadBoardUI()
await updateBoardUI()
verifyScene()
log({ type: 'progress', message: 'Preparing to display' })
resize()
// storyboarderSketchPane.resize()
await new Promise(resolve => setTimeout(resolve, 50)) // wait for the DOM to catch up to avoid FOUC
ipcRenderer.send('workspaceReady')
let win = remote.getCurrentWindow()
win.webContents.addListener('before-input-event', (event, input) => {
// TODO need a different fix for dev tools, which doesn't have before-input-event
// see: https://github.com/wonderunit/storyboarder/issues/1202
//
//
// intercept some key commands
//
// TODO avoid key doubling where Menu still tries to send the command
// see: https://github.com/wonderunit/storyboarder/issues/1206
//
// construct a unique set of keys including the one JUST intercepted
let pressedKeys = [...new Set([...keytracker.pressed(), input.key])]
//
// intercept: New Board (IPC: newBoard)
if (isCommandPressed('menu:boards:new-board', pressedKeys)) {
// keyDown triggers newBoard
if (input.type == 'keyDown') {
// sanity check
if (!textInputMode) {
// manually construct a new board
newBoard()
.then(index => {
// go to the board
gotoBoard(index)
// report
ipcRenderer.send('analyticsEvent', 'Board', 'new')
})
.catch(err => console.error(err))
}
}
// keyUp AND keyDown cause menu to be ignored and key to be trapped
win.webContents.setIgnoreMenuShortcuts(true)
event.preventDefault()
return
}
// intercept: Change Tool (IPC: setTool)
// e.g.: '1'-'6' shouldn't flash the menu
for (let [command, toolName] of [
['menu:tools:light-pencil', 'light-pencil'],
['menu:tools:brush', 'brush'],
['menu:tools:tone', 'tone'],
['menu:tools:pencil', 'pencil'],
['menu:tools:pen', 'pen'],
['menu:tools:note-pen', 'note-pen'],
['menu:tools:eraser', 'eraser']
]) {
if (isCommandPressed(command, pressedKeys)) {
if (input.type == 'keyDown' &&
!textInputMode &&
!storyboarderSketchPane.getIsDrawingOrStabilizing()
) {
store.dispatch({
type: 'TOOLBAR_TOOL_CHANGE',
payload: toolName,
meta: { scope: 'local' }
})
}
win.webContents.setIgnoreMenuShortcuts(true)
event.preventDefault()
return
}
}
// if we're in text input mode, and have not pressed Control or Meta
if (textInputMode && !(input.control || input.meta)) {
// ignore any key that might trigger the menu
win.webContents.setIgnoreMenuShortcuts(true)
} else {
// otherwise, allow it through
win.webContents.setIgnoreMenuShortcuts(false)
}
})
} catch (error) {
console.error(error)
// DEBUG show current window
if (isDev) {
remote.getCurrentWindow().show()
remote.getCurrentWebContents().openDevTools()
}
log({ type: 'error', message: error.message })
remote.dialog.showMessageBox({
type: 'error',
message: error.message
})
// TODO add a cancel button to loading view when a fatal error occurs?
}
}
ipcRenderer.on('load', load)
let toggleNewShot = () => {
storeUndoStateForScene(true)
boardData.boards[currentBoard].newShot = !boardData.boards[currentBoard].newShot
sfx.playEffect(boardData.boards[currentBoard].newShot ? 'on' : 'off')
document.querySelector('input[name="newShot"]').checked = boardData.boards[currentBoard].newShot
markBoardFileDirty()
renderThumbnailDrawer()
storeUndoStateForScene()
}
const commentOnLineMileage = (miles) => {
let message = []
let otherMessages
switch (miles) {
// REMOVED TO LIMIT NOTIFICATIONS
// case 0.01:
// otherMessages = [
// "Yes!!! The first stroke. I remember my first stroke – fondly.",
// "I can tell this one is going to be good!",
// "What are you drawing?",
// "Let's make this one better than the last one.",
// "What's happening in this point of the story?",
// "Here we go again!",
// "Let's do this!",
// "I wish I could draw as good as that.",
// ]
// message.push(otherMessages[Math.floor(Math.random()*otherMessages.length)])
// break
// case 1:
// otherMessages = [
// "Looking great!!!",
// "Absolutely fantastic!",
// "You're like a regular Picaso.",
// "Hey - this looks great. And to think I doubted you.",
// "This is way better than your last board!",
// "Hooray! A great start.",
// "I can see great form in this one.",
// "There is so much potential with this drawing!",
// "Imagine when your friends see this.",
// "Let's keep the line miles to a minimum.",
// ]
// message.push(otherMessages[Math.floor(Math.random()*otherMessages.length)])
// sfx.playEffect('tool-pencil')
// break
case 5:
message.push('5 line miles.')
otherMessages = [
"You should be done with your rough drawing.",
"You got the basic form down?",
"Are you sure this is the layout you want?",
"Let's get to cleaning this up!",
"Such great composition!",
"Oh. Now I can see what you're going for.",
"Let's wrap this one up.",
"Beautiful.",
"You make me proud.",
]
message.push(otherMessages[Math.floor(Math.random()*otherMessages.length)])
sfx.playEffect('tool-light-pencil')
break
case 8:
message.push('8 line miles.')
otherMessages = [
"Let's finish this up!",
"Are you done yet?",
"We have so many other boards to do still...",
"Yes.. Very close to done.",
"Can we move on to the next drawing and come back to this one?",
"I think you need to pee.",
"Is it finished?",
"Yeah.. I'm gonna need you to come in this weekend and finish the rest of these boards.",
"Wrap it up!",
]
message.push(otherMessages[Math.floor(Math.random()*otherMessages.length)])
sfx.playEffect('tool-brush')
break
case 10:
message.push('10 miles!')
otherMessages = [
"Let's finish this up!",
"Are you done yet?",
"Alright, I think this one is done.",
"Yes.. Very close to done. Actually, looks done to me.",
"Let's move on.",
"Remember, you're not making the next Moner Lisa.",
"Who do you think you are, Picaso?",
"Looks great! But let's not make it too great.",
"Sweet!",
]
message.push(otherMessages[Math.floor(Math.random()*otherMessages.length)])
sfx.positive()
break
case 20:
message.push('20 miles!!!')
otherMessages = [
"This is done. Let's move on.",
"Woot. You're finished!",
"You're taking too long.",
"Come on buddy... put the pen down.",
"You know you're not burning that many more calories working this hard on this board.",
"YESSSS!!! BEAUTIFUL!!!!",
"I LOVE IT!!!!",
"How did you learn to draw so well?",
]
message.push(otherMessages[Math.floor(Math.random()*otherMessages.length)])
sfx.negative()
break
case 50:
message.push('50 miles!!!')
otherMessages = [
"Uhh.. I fell asleep. What did I miss?",
"Are you painting the sixteen chapel or something?",
"I'm waiting for your paint to dry.",
"Come on buddy... put the pen down. Let's go for a walk.",
"Why don't you tweet this masterpiece out?",
"Hey. This is like some sort of torture.",
"I thought it looked nice an hour ago.",
"How about starting a new board?",
]
message.push(otherMessages[Math.floor(Math.random()*otherMessages.length)])
sfx.negative()
break
case 100:
message.push('100 miles!!!')
otherMessages = [
"Nope!!! I'm going to delete this board if you keep drawing. Just kidding. Or am I?",
"I FEEL ASLEEP.",
"Wake me up when you need me.",
"Dude. You remember you are storyboarding.",
"Let's go for a walk.",
"How many boards do we have left?",
"I thought it looked nice 2 hours ago.",
"How about starting a new board?",
"Post this one to twitter, it's a f*cking masterpiece.",
]
message.push(otherMessages[Math.floor(Math.random()*otherMessages.length)])
sfx.error()
break
case 200:
message.push('200 miles!!!')
otherMessages = [
"Now you're just fucking with me.",
"I FEEL ASLEEP.",
"You haven't worked your wrist out this hard since you were 13.",
"I think your pen is going to break.",
]
message.push(otherMessages[Math.floor(Math.random()*otherMessages.length)])
sfx.error()
break
case 300:
message.push('300 miles!!!')
otherMessages = [
"I quit.",
"Imagine what I'll say at 1000 miles.",
"I'm going home.",
"I hate you.",
]
message.push(otherMessages[Math.floor(Math.random()*otherMessages.length)])
sfx.error()
break
case 500:
message.push('500 miles!!!')
otherMessages = [
"So close to 1000!!!",
]
message.push(otherMessages[Math.floor(Math.random()*otherMessages.length)])
sfx.error()
break
case 1000:
message.push('1000 miles!!!')
otherMessages = [
"Great job. :/ See ya.",
]
message.push(otherMessages[Math.floor(Math.random()*otherMessages.length)])
sfx.error()
setTimeout(()=> {window.close()}, 5000);
break
}
notifications.notify({message: message.join(' '), timing: 10})
}
// TODO this is really similar to verifyScene, but verifyScene requires the UI to be ready (for notifications)
const migrateScene = () => {
let boardImagesPath = path.join(boardPath, 'images')
// if at least one board.url file exists, consider this an old project
let needsMigration = false
for (let board of boardData.boards) {
if (fs.existsSync(path.join(boardImagesPath, board.url))) {
if (!(board.layers && board.layers.fill)) {
// needs to be migrated
needsMigration = true
break
}
}
}
if (!needsMigration) return false
// is this scene itself a migrated backup?
let foldername = path.dirname(boardFilename)
// does the basename end with `-backup`?
let foldernameContainsStringBackup = foldername.match(/-backup$/i) != null
// is this a backup folder alongside the original?
let calculatedOriginalFilename = foldername.replace(/-backup$/i, '')
let isAlongside = fs.existsSync(calculatedOriginalFilename)
if (foldernameContainsStringBackup && isAlongside) {
// we don't need to migrate
remote.dialog.showMessageBox({
message: "This appears to be a backup of a scene created with an older version of Storyboarder. It will not be migrated. Some layers won’t appear correctly in this version of Storyboarder."
})
return false
}
// make a backup
let src = boardFilename
let dst = path.join(path.dirname(boardFilename), '..',
path.basename(boardFilename, path.extname(boardFilename)) + '-backup')
if (fs.existsSync(dst)) {
remote.dialog.showMessageBox({
type: 'error',
message: `Tried to migrate scene to new Storyboarder format but a backup already exists.\n\n${dst}\n\nPlease move or rename the backup folder and retry.`
})
window.close()
throw new Error('Could not migrate')
return false
}
fs.ensureDirSync(dst)
console.log('Preparing to migrate scene to new Storyboarder layers format')
console.log('Making a backup before migrating …')
exporterCopyProject.copyProject(
src,
dst,
{
// copy board url main images
copyBoardUrlMainImages: true,
// ignore missing files, like posterframes or thumbnails
ignoreMissing: true
})
// upgrade to the 1.6 layers format
// see: https://github.com/wonderunit/storyboarder/issues/1160
for (let board of boardData.boards) {
// if a file exists for the board.url, we haven't migrated yet
if (fs.existsSync(path.join(boardImagesPath, board.url))) {
// catch edge case where fill layer already exists
if (board.layers && board.layers.fill) {
console.warn('Found an old main layer but fill already exists')
remote.dialog.showMessageBox({
type: 'error',
message: 'Error while migrating board: fill layer already exists'
})
} else {
// ensure board.layers exists
if (!board.layers) {
board.layers = {}
}
// move main layer to fill layer
let filename = boardModel.boardFilenameForLayer(board, 'fill')
console.log(`Moving ${board.url} to new fill layer ${filename}`)
fs.moveSync(path.join(boardImagesPath, board.url), path.join(boardImagesPath, filename))
board.layers.fill = {
url: filename
}
markBoardFileDirty()
}
}
}
}
// NOTE we assume that all resources (board data and images) are saved BEFORE calling verifyScene
const verifyScene = () => {
// find all used files
const flatten = arr => Array.prototype.concat(...arr)
const pngFiles = flatten(boardData.boards.map(board => ([
...boardModel.boardOrderedLayerFilenames(board).filenames,
boardModel.boardFilenameForThumbnail(board)
])))
//
//
// PNG: notify about any missing PNG file, create it
//
let missing = []
for (let filename of pngFiles) {
if (!fs.existsSync(path.join(boardPath, 'images', filename))) {
missing.push(filename)
}
}
if (missing.length) {
let message = `[WARNING] This scene is missing the following file(s):\n\n${missing.join('\n')}\n\n` +
`This is probably not your fault, but is a bug caused by previous releases of Storyboarder.`
notifications.notify({ message, timing: 60 })
// create placeholder image
let size = boardModel.boardFileImageSize(boardData)
let context = createSizedContext(size)
let canvas = context.canvas
let imageData = canvas.toDataURL()
for (let filename of missing) {
console.log('saving placeholder', filename)
saveDataURLtoFile(imageData, filename)
}
notifications.notify({ message: 'We’ved added placeholder files for any missing image(s). ' +
'You should not see this warning again for this scene.', timing: 60 })
}
//
//
// PSD: notify about any missing PSD file, and unlink
//
for (let board of boardData.boards) {
if (board.link) {
if (!fs.existsSync(path.join(boardPath, 'images', board.link))) {
let message = `[WARNING] This scene is missing the linked file ${board.link}. ` +
`It will be unlinked.`
notifications.notify({ message, timing: 60 })
delete board.link
markBoardFileDirty()
}
}
}
}
const loadBoardUI = async () => {
log({ type: 'progress', message: 'Loading User Interface' })
let size = boardModel.boardFileImageSize(boardData)
shotTemplateSystem = new ShotTemplateSystem({ width: size[0], height: size[1] })
if (!SketchPane.canInitialize()) {
remote.dialog.showMessageBox({
type: 'error',
message: 'Sorry, Storyboarder is not supported on your device because WebGL could not be initialized.'
})
window.close()
return
}
storyboarderSketchPane = new StoryboarderSketchPane(
document.getElementById('storyboarder-sketch-pane'),
size,
store
)
await storyboarderSketchPane.load()
window.addEventListener('resize', () => {
resize()
// storyboarderSketchPane.resize()
})
window.ondragover = () => { return false }
window.ondragleave = () => { return false }
window.ondragend = () => { return false }
window.ondrop = e => {
e.preventDefault()
if (!e || !e.dataTransfer || !e.dataTransfer.files || !e.dataTransfer.files.length) {
return
}
let files = e.dataTransfer.files
for (let file of files) {
if (path.extname(file.name).match(/\.aif*/)) {
notifications.notify({ message: `Whoops! Sorry, Storyboarder can’t read AIFF files (yet).`, timing: 5 })
return
}
let hasRecognizedExtension = ALLOWED_AUDIO_FILE_EXTENSIONS.includes(path.extname(file.name).replace('.', ''))
if (
hasRecognizedExtension &&
audioPlayback.supportsType(file.name)
) {
notifications.notify({ message: `Copying audio file\n${file.name}`, timing: 5 })
audioFileControlView.onSelectFile(file.path)
return
}
}
let hasStoryboarderFile = false
let filepaths = []
for (let file of files) {
if (file.name.indexOf(".storyboarder") > -1) {
hasStoryboarderFile = true
// force load
ipcRenderer.send('openFile', file.path)
break
} else {
filepaths.push(file.path)
}
}
if (!hasStoryboarderFile) {
insertNewBoardsWithFiles(filepaths)
}
}
storyboarderSketchPane.on('addToUndoStack', layerIndices => {
clearTimeout(drawIdleTimer)
storeUndoStateForImage(true, layerIndices)
})
storyboarderSketchPane.on('markDirty', layerIndices => {
storeUndoStateForImage(false, layerIndices)
markImageFileDirty(layerIndices)
// TODO performance pass. this is slow!
// see: https://github.com/wonderunit/storyboarder/issues/1193
if (isRecording) {
// grab full-size image from current sketchpane (in memory)
let pixels = storyboarderSketchPane.sketchPane.extractThumbnailPixels(
storyboarderSketchPane.sketchPane.width,
storyboarderSketchPane.sketchPane.height,
storyboarderSketchPane.visibleLayersIndices
)
// un-premultiply
SketchPaneUtil.arrayPostDivide(pixels)
// send as a canvas
canvasRecorder.capture([
SketchPaneUtil.pixelsToCanvas(
pixels,
storyboarderSketchPane.sketchPane.width,
storyboarderSketchPane.sketchPane.height
)
])
if (!isRecordingStarted) isRecordingStarted = true
}
drawIdleTimer = setTimeout(onDrawIdle, 500)
})
// storyboarderSketchPane.on('pointerdown', () => {
// clearTimeout(drawIdleTimer)
// })
storyboarderSketchPane.on('lineMileage', value =>
addToLineMileage(value))
let sketchPaneEl = document.querySelector('#storyboarder-sketch-pane')
let captionEl = document.createElement('div')
captionEl.id = 'canvas-caption'
sketchPaneEl.appendChild(captionEl)
for (var item of document.querySelectorAll('#board-metadata input:not(.layers-ui-reference-opacity), textarea')) {
item.addEventListener('focus', (e)=> {
textInputMode = true
textInputAllowAdvance = false
switch (e.target.name) {
case 'duration':
case 'frames':
textInputAllowAdvance = true
break
}
})
item.addEventListener('blur', (e)=> {
textInputMode = false
textInputAllowAdvance = false
})
item.addEventListener('change', (e)=> {
switch (e.target.name) {
case 'newShot':
boardData.boards[currentBoard].newShot = e.target.checked
sfx.playEffect(e.target.checked ? 'on' : 'off')
markBoardFileDirty()
textInputMode = false
break
case 'dialogue':
renderCaption()
break
}
renderThumbnailDrawer()
})
item.addEventListener('input', e => {
switch (e.target.name) {
case 'duration':
// if we can't parse the value as a number (e.g.: empty string),
// set to undefined
// which will render as the scene's default duration
let newDuration = isNaN(parseInt(e.target.value, 10))
? undefined
: e.target.value
// set the new duration value
for (let index of selections) {
boardData.boards[index].duration = newDuration
}
// update the `frames` view
document.querySelector('input[name="frames"]').value = msecsToFrames(boardModel.boardDuration(boardData, boardData.boards[currentBoard]))
renderThumbnailDrawer()
renderMarkerPosition()
break
case 'frames':
let newFrames = isNaN(parseInt(e.target.value, 10))
? undefined
: e.target.value
for (let index of selections) {
boardData.boards[index].duration = newFrames != null
? framesToMsecs(newFrames)
: undefined
}
// update the `duration` view
document.querySelector('input[name="duration"]').value = newFrames != null
? framesToMsecs(newFrames)
: ''
renderThumbnailDrawer()
renderMarkerPosition()
break
case 'dialogue':
boardData.boards[currentBoard].dialogue = (e.target.value)
break
case 'action':
boardData.boards[currentBoard].action = (e.target.value)
break
case 'notes':
boardData.boards[currentBoard].notes = (e.target.value)
break
}
markBoardFileDirty()
})
}
document.querySelector('#thumbnail-container').addEventListener('pointerdown', (e)=>{
if (e.pointerType == 'pen' || e.pointerType == 'mouse') {
dragTarget = document.querySelector('#thumbnail-container')
dragTarget.style.overflow = 'hidden'
dragTarget.style.scrollBehavior = 'unset'
dragMode = true
dragPoint = [e.pageX, e.pageY]
scrollPoint = [dragTarget.scrollLeft, dragTarget.scrollTop]
mouseDragStartX = e.clientX
periodicDragUpdate()
}
})
document.querySelector('.board-metadata-container').addEventListener('pointerdown', (e)=>{
if (e.pointerType == 'pen' || e.pointerType == 'mouse') {
dragTarget = document.querySelector('.board-metadata-container')
dragTarget.style.overflow = 'hidden'
dragTarget.style.scrollBehavior = 'unset'
dragMode = true
dragPoint = [e.pageX, e.pageY]
scrollPoint = [dragTarget.scrollLeft, dragTarget.scrollTop]
}
})
// toggle scroll-indicator visibility based on scroll position
const renderScrollIndicator = () => {
let target = document.querySelector('.board-metadata-container')
let el = document.querySelector('#board-metadata .scroll-indicator')
if (target.offsetHeight + target.scrollTop === target.scrollHeight) {
el.style.opacity = 0
} else {
el.style.opacity = 1.0
}
}
document.querySelector('.board-metadata-container').addEventListener('scroll', () => renderScrollIndicator())
document.querySelector('#board-metadata .scroll-indicator').addEventListener('click', e => {
let el = document.querySelector('.board-metadata-container')
el.scrollTo({
top: el.scrollHeight,
behavior: 'smooth'
})
})
window.addEventListener('resize', () => renderScrollIndicator())
renderScrollIndicator() // initialize
for (var item of document.querySelectorAll('.board-metadata-container input, .board-metadata-container textarea')) {
item.addEventListener('pointerdown', (e)=>{
preventDragMode = true
dragTarget = document.querySelector('.board-metadata-container')
dragTarget.style.scrollBehavior = 'smooth'
})
}
document.querySelector('#suggested-dialogue-duration').addEventListener('pointerdown', (e)=>{
let board = boardData.boards[currentBoard]
board.duration = e.target.dataset.duration
renderMetaData()
})
// for (var item of document.querySelectorAll('.thumbnail')) {
// item.classList.remove('active')
// }
const getActiveLayerFilePath = () => {
let board = boardData.boards[currentBoard]
let state = store.getState()
if (state.toolbar.activeTool !== 'eraser') {
let filename = boardModel.boardFilenameForLayer(board, state.toolbar.tools[state.toolbar.activeTool].defaultLayerName)
let filepath = path.join(boardPath, 'images', filename)
try {
if (fs.statSync(filepath).isFile()) {
return filepath
}
} catch (err) {
if (err.code !== 'ENOENT') {
throw err
}
}
}
}
document.querySelector('#show-in-finder-button').addEventListener('pointerdown', event => {
let filepath = getActiveLayerFilePath()
if (filepath) {
console.log('revealing', filepath)
shell.showItemInFolder(filepath)
} else {
// TODO find the first existing layer? see: https://github.com/wonderunit/storyboarder/issues/1173
// e.g.: `eraser`, or a layer image that hasn't save yet
console.log('could not find image file for current layer')
// uncomment to warn artist first
// remote.dialog.showMessageBox({