-
Notifications
You must be signed in to change notification settings - Fork 512
/
main_window.py
3264 lines (2685 loc) · 128 KB
/
main_window.py
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
"""
@file
@brief This file loads the main window (i.e. the primary user-interface)
@author Noah Figg <eggmunkee@hotmail.com>
@author Jonathan Thomas <jonathan@openshot.org>
@author Olivier Girard <olivier@openshot.org>
@section LICENSE
Copyright (c) 2008-2018 OpenShot Studios, LLC
(http://www.openshotstudios.com). This file is part of
OpenShot Video Editor (http://www.openshot.org), an open-source project
dedicated to delivering high quality video editing and animation solutions
to the world.
OpenShot Video Editor is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenShot Video Editor is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with OpenShot Library. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import shutil
import webbrowser
import functools
from time import sleep
from uuid import uuid4
import json
import openshot # Python module for libopenshot (required video editing module installed separately)
from PyQt5.QtCore import (
Qt, pyqtSignal, pyqtSlot, QCoreApplication, PYQT_VERSION_STR,
QTimer, QDateTime, QFileInfo, QUrl,
)
from PyQt5.QtGui import QIcon, QCursor, QKeySequence, QTextCursor
from PyQt5.QtWidgets import (
QMainWindow, QWidget, QDockWidget,
QMessageBox, QDialog, QFileDialog, QInputDialog,
QAction, QActionGroup, QSizePolicy,
QStatusBar, QToolBar, QToolButton,
QLineEdit, QComboBox, QTextEdit
)
from classes import exceptions, info, qt_types, sentry, ui_util, updates
from classes.app import get_app
from classes.exporters.edl import export_edl
from classes.exporters.final_cut_pro import export_xml
from classes.importers.edl import import_edl
from classes.importers.final_cut_pro import import_xml
from classes.logger import log
from classes.metrics import track_metric_session, track_metric_screen
from classes.query import File, Clip, Transition, Marker, Track, Effect
from classes.thumbnail import httpThumbnailServerThread
from classes.time_parts import secondsToTimecode
from classes.timeline import TimelineSync
from classes.version import get_current_Version
from windows.models.effects_model import EffectsModel
from windows.models.emoji_model import EmojisModel
from windows.models.files_model import FilesModel
from windows.models.transition_model import TransitionsModel
from windows.preview_thread import PreviewParent
from windows.video_widget import VideoWidget
from windows.views.effects_listview import EffectsListView
from windows.views.effects_treeview import EffectsTreeView
from windows.views.emojis_listview import EmojisListView
from windows.views.files_listview import FilesListView
from windows.views.files_treeview import FilesTreeView
from windows.views.properties_tableview import PropertiesTableView, SelectionLabel
from windows.views.webview import TimelineWebView
from windows.views.transitions_listview import TransitionsListView
from windows.views.transitions_treeview import TransitionsTreeView
from windows.views.tutorial import TutorialManager
class MainWindow(updates.UpdateWatcher, QMainWindow):
""" This class contains the logic for the main window widget """
# Path to ui file
ui_path = os.path.join(info.PATH, 'windows', 'ui', 'main-window.ui')
previewFrameSignal = pyqtSignal(int)
refreshFrameSignal = pyqtSignal()
refreshFilesSignal = pyqtSignal()
refreshTransitionsSignal = pyqtSignal()
refreshEffectsSignal = pyqtSignal()
LoadFileSignal = pyqtSignal(str)
PlaySignal = pyqtSignal()
PauseSignal = pyqtSignal()
StopSignal = pyqtSignal()
SeekSignal = pyqtSignal(int)
SpeedSignal = pyqtSignal(float)
RecoverBackup = pyqtSignal()
FoundVersionSignal = pyqtSignal(str)
TransformSignal = pyqtSignal(str)
KeyFrameTransformSignal = pyqtSignal(str, str)
SelectRegionSignal = pyqtSignal(str)
MaxSizeChanged = pyqtSignal(object)
InsertKeyframe = pyqtSignal(object)
OpenProjectSignal = pyqtSignal(str)
ThumbnailUpdated = pyqtSignal(str)
FileUpdated = pyqtSignal(str)
CaptionTextUpdated = pyqtSignal(str, object)
CaptionTextLoaded = pyqtSignal(str, object)
TimelineZoom = pyqtSignal(float) # Signal to zoom into timeline from zoom slider
TimelineScrolled = pyqtSignal(list) # Scrollbar changed signal from timeline
TimelineResize = pyqtSignal() # Timeline length changed signal from timeline
TimelineScroll = pyqtSignal(float) # Signal to force scroll timeline to specific point
TimelineCenter = pyqtSignal() # Signal to force center scroll on playhead
SelectionAdded = pyqtSignal(str, str, bool) # Signal to add a selection
SelectionRemoved = pyqtSignal(str, str) # Signal to remove a selection
SelectionChanged = pyqtSignal() # Signal after selections have been changed (added/removed)
SetKeyframeFilter = pyqtSignal(str) # Signal to only show keyframes for the selected property
# Docks are closable, movable and floatable
docks_frozen = False
# Save window settings on close
def closeEvent(self, event):
app = get_app()
# Some window managers handels dragging of the modal messages incorrectly if other windows are open
# Hide tutorial window first
self.tutorial_manager.hide_dialog()
# Prompt user to save (if needed)
if app.project.needs_save():
log.info('Prompt user to save project')
# Translate object
_ = app._tr
# Handle exception
ret = QMessageBox.question(
self,
_("Unsaved Changes"),
_("Save changes to project before closing?"),
QMessageBox.Cancel | QMessageBox.No | QMessageBox.Yes)
if ret == QMessageBox.Yes:
# Save project
self.actionSave_trigger()
event.accept()
elif ret == QMessageBox.Cancel:
# Show tutorial again, if any
self.tutorial_manager.re_show_dialog()
# User canceled prompt - don't quit
event.ignore()
return
# Log the exit routine
log.info('---------------- Shutting down -----------------')
# Close any tutorial dialogs
self.tutorial_manager.exit_manager()
# Save settings
self.save_settings()
# Track end of session
track_metric_session(False)
# Disable video caching
openshot.Settings.Instance().ENABLE_PLAYBACK_CACHING = False
# Stop threads
self.StopSignal.emit()
# Stop thumbnail server thread
self.http_server_thread.kill()
# Stop ZMQ polling thread
get_app().logger_libopenshot.kill()
# Process any queued events
QCoreApplication.processEvents()
# Stop preview thread (and wait for it to end)
self.preview_thread.player.CloseAudioDevice()
self.preview_thread.kill()
self.videoPreview.deleteLater()
self.videoPreview = None
self.preview_parent.Stop()
# Clean-up Timeline
if self.timeline_sync and self.timeline_sync.timeline:
# Clear all clips & close all readers
self.timeline_sync.timeline.Close()
self.timeline_sync.timeline.Clear()
del self.timeline_sync.timeline
# Destroy lock file
self.destroy_lock_file()
def recover_backup(self):
"""Recover the backup file (if any)"""
log.info("recover_backup")
# Check for backup.osp file
if os.path.exists(info.BACKUP_FILE):
# Load recovery project
log.info("Recovering backup file: %s" % info.BACKUP_FILE)
self.open_project(info.BACKUP_FILE, clear_thumbnails=False)
# Clear the file_path (which is set by saving the project)
project = get_app().project
project.current_filepath = None
project.has_unsaved_changes = True
# Set Window title
self.SetWindowTitle()
# Show message to user
msg = QMessageBox()
_ = get_app()._tr
msg.setWindowTitle(_("Backup Recovered"))
msg.setText(_("Your most recent unsaved project has been recovered."))
msg.exec_()
else:
# No backup project found
# Load a blank project (to propagate the default settings)
get_app().project.load("")
self.actionUndo.setEnabled(False)
self.actionRedo.setEnabled(False)
self.actionClearHistory.setEnabled(False)
self.SetWindowTitle()
def create_lock_file(self):
"""Create a lock file"""
lock_path = os.path.join(info.USER_PATH, ".lock")
# Check if it already exists
if os.path.exists(lock_path):
last_log_line = exceptions.libopenshot_crash_recovery() or "No Log Detected"
log.error(f"Unhandled crash detected: {last_log_line}")
self.destroy_lock_file()
else:
# Normal startup, clear thumbnails
self.clear_temporary_files()
# Reset Sentry component (it can be temporarily changed to libopenshot during
# the call to libopenshot_crash_recovery above)
sentry.set_tag("component", "openshot-qt")
# Write lock file (try a few times if failure)
lock_value = str(uuid4())
for attempt in range(5):
try:
# Create lock file
with open(lock_path, 'w') as f:
f.write(lock_value)
log.debug("Wrote value %s to lock file %s", lock_value, lock_path)
break
except OSError:
log.debug("Failed to write lock file (attempt: %d)", attempt, exc_info=1)
sleep(0.25)
def destroy_lock_file(self):
"""Destroy the lock file"""
lock_path = os.path.join(info.USER_PATH, ".lock")
# Remove file (try a few times if failure)
for attempt in range(5):
try:
os.remove(lock_path)
log.debug("Removed lock file {}".format(lock_path))
break
except FileNotFoundError:
break
except OSError:
log.debug('Failed to destroy lock file (attempt: %s)' % attempt, exc_info=1)
sleep(0.25)
def actionNew_trigger(self):
app = get_app()
_ = app._tr # Get translation function
# Do we have unsaved changes?
if app.project.needs_save():
ret = QMessageBox.question(
self,
_("Unsaved Changes"),
_("Save changes to project first?"),
QMessageBox.Cancel | QMessageBox.No | QMessageBox.Yes)
if ret == QMessageBox.Yes:
# Save project
self.actionSave_trigger()
elif ret == QMessageBox.Cancel:
# User canceled prompt
return
# Disable video caching
openshot.Settings.Instance().ENABLE_PLAYBACK_CACHING = False
# Stop preview thread
self.SpeedSignal.emit(0)
self.PauseSignal.emit()
# Reset selections
self.clearSelections()
# Process all events
QCoreApplication.processEvents()
# Clear any previous thumbnails
self.clear_temporary_files()
# clear data and start new project
app.project.load("")
app.updates.reset()
self.updateStatusChanged(False, False)
# Refresh files views
self.refreshFilesSignal.emit()
log.info("New Project created.")
# Set Window title
self.SetWindowTitle()
# Seek to frame 0
self.SeekSignal.emit(1)
# Update max size (for fast previews)
self.MaxSizeChanged.emit(self.videoPreview.size())
# Enable video caching
openshot.Settings.Instance().ENABLE_PLAYBACK_CACHING = True
def actionAnimatedTitle_trigger(self):
# show dialog
from windows.animated_title import AnimatedTitle
win = AnimatedTitle()
# Run the dialog event loop - blocking interaction on this window during that time
result = win.exec_()
if result == QDialog.Accepted:
log.info('animated title add confirmed')
else:
log.info('animated title add cancelled')
def actionAnimation_trigger(self):
# show dialog
from windows.animation import Animation
win = Animation()
# Run the dialog event loop - blocking interaction on this window during that time
result = win.exec_()
if result == QDialog.Accepted:
log.info('animation confirmed')
else:
log.info('animation cancelled')
def actionTitle_trigger(self):
# show dialog
from windows.title_editor import TitleEditor
win = TitleEditor()
# Run the dialog event loop - blocking interaction on this window during that time
win.exec_()
def actionEditTitle_trigger(self):
# Loop through selected files (set 1 selected file if more than 1)
for f in self.selected_files():
if f.data.get("path").endswith(".svg"):
file_path = f.data.get("path")
file_id = f.id
break
if not file_path:
return
# show dialog for editing title
from windows.title_editor import TitleEditor
win = TitleEditor(edit_file_path=file_path)
# Run the dialog event loop - blocking interaction on this window during that time
win.exec_()
# Update file thumbnail
self.FileUpdated.emit(file_id)
# Force update of clips
for c in Clip.filter(file_id=file_id):
# update clip
c.data["reader"]["path"] = file_path
c.save()
# Emit thumbnail update signal (to update timeline thumb image)
self.ThumbnailUpdated.emit(c.id)
# Update preview
self.refreshFrameSignal.emit()
def actionClearAllCache_trigger(self):
""" Clear all timeline cache - deep clear """
self.timeline_sync.timeline.ClearAllCache(True)
def actionDuplicateTitle_trigger(self):
file_path = None
# Loop through selected files (set 1 selected file if more than 1)
for f in self.selected_files():
if f.data.get("path").endswith(".svg"):
file_path = f.data.get("path")
break
if not file_path:
return
# show dialog for editing title
from windows.title_editor import TitleEditor
win = TitleEditor(edit_file_path=file_path, duplicate=True)
# Run the dialog event loop - blocking interaction on this window during that time
return win.exec_()
def actionClearWaveformData_trigger(self):
"""Clear audio data from current project"""
files = File.filter()
for file in files:
if "audio_data" in file.data.get("ui", {}):
file_path = file.data.get("path")
log.debug("File %s has audio data. Deleting it." % os.path.split(file_path)[1])
del file.data["ui"]["audio_data"]
file.save()
clips = Clip.filter()
for clip in clips:
if "audio_data" in clip.data.get("ui", {}):
log.debug("Clip %s has audio data. Deleting it." % clip.id)
del clip.data["ui"]["audio_data"]
clip.save()
get_app().window.actionClearWaveformData.setEnabled(False)
def actionClearHistory_trigger(self):
"""Clear history for current project"""
project = get_app().project
project.has_unsaved_changes = True
get_app().updates.reset()
log.info('History cleared')
def save_project(self, file_path):
""" Save a project to a file path, and refresh the screen """
app = get_app()
_ = app._tr # Get translation function
try:
# Update history in project data
s = app.get_settings()
app.updates.save_history(app.project, s.get("history-limit"))
# Save project to file
app.project.save(file_path)
# Set Window title
self.SetWindowTitle()
# Load recent projects again
self.load_recent_menu()
log.info("Saved project %s", file_path)
except Exception as ex:
log.error("Couldn't save project %s", file_path, exc_info=1)
QMessageBox.warning(self, _("Error Saving Project"), str(ex))
def open_project(self, file_path, clear_thumbnails=True):
""" Open a project from a file path, and refresh the screen """
app = get_app()
settings = app.get_settings()
# Set default load-project path to this path.
settings.setDefaultPath(settings.actionType.LOAD, file_path)
_ = app._tr # Get translation function
# First check for empty file_path (probably user cancellation)
if not file_path:
# Ignore the request
return
# Disable video caching
openshot.Settings.Instance().ENABLE_PLAYBACK_CACHING = False
# Stop preview thread
self.SpeedSignal.emit(0)
self.PauseSignal.emit()
# Reset selections
self.clearSelections()
# Process all events
QCoreApplication.processEvents()
# Do we have unsaved changes?
if app.project.needs_save():
ret = QMessageBox.question(
self,
_("Unsaved Changes"),
_("Save changes to project first?"),
QMessageBox.Cancel | QMessageBox.No | QMessageBox.Yes)
if ret == QMessageBox.Yes:
# Save project
self.actionSave.trigger()
elif ret == QMessageBox.Cancel:
# User canceled prompt
return
# Set cursor to waiting
app.setOverrideCursor(QCursor(Qt.WaitCursor))
try:
if os.path.exists(file_path):
# Clear any previous thumbnails
if clear_thumbnails:
self.clear_temporary_files()
# Load project file
app.project.load(file_path, clear_thumbnails)
# Set Window title
self.SetWindowTitle()
# Reset undo/redo history
app.updates.reset()
app.updates.load_history(app.project)
# Refresh files views
self.refreshFilesSignal.emit()
# Refresh thumbnail
self.refreshFrameSignal.emit()
# Update max size (for fast previews)
self.MaxSizeChanged.emit(self.videoPreview.size())
# Load recent projects again
self.load_recent_menu()
log.info("Loaded project {}".format(file_path))
else:
log.info("File not found at {}".format(file_path))
self.statusBar.showMessage(
_("Project %s is missing (it may have been moved or deleted). "
"It has been removed from the Recent Projects menu." % file_path),
5000)
self.remove_recent_project(file_path)
self.load_recent_menu()
# Ensure that playhead, preview thread, and cache all agree that
# Frame 1 is being previewed
self.preview_thread.player.Seek(1)
self.movePlayhead(1)
except Exception as ex:
log.error("Couldn't open project %s.", file_path, exc_info=1)
QMessageBox.warning(self, _("Error Opening Project"), str(ex))
# Enable video caching
openshot.Settings.Instance().ENABLE_PLAYBACK_CACHING = True
# Restore normal cursor
app.restoreOverrideCursor()
def clear_temporary_files(self):
"""Clear all user thumbnails"""
for temp_dir in [
info.get_default_path("THUMBNAIL_PATH"),
info.get_default_path("BLENDER_PATH"),
info.get_default_path("TITLE_PATH"),
]:
try:
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
log.info("Cleared temporary files: %s", temp_dir)
os.mkdir(temp_dir)
except Exception:
log.warning("Failed to clear %s", temp_dir, exc_info=1)
# Clear any backups
if os.path.exists(info.BACKUP_FILE):
try:
# Remove backup file
os.unlink(info.BACKUP_FILE)
log.info("Cleared backup: %s", info.BACKUP_FILE)
except Exception:
log.warning("Could not delete backup file %s",
info.BACKUP_FILE, exc_info=1)
def actionOpen_trigger(self):
app = get_app()
_ = app._tr
s = app.get_settings()
recommended_folder = s.getDefaultPath(s.actionType.LOAD)
# Do we have unsaved changes?
if app.project.needs_save():
ret = QMessageBox.question(
self,
_("Unsaved Changes"),
_("Save changes to project first?"),
QMessageBox.Cancel | QMessageBox.No | QMessageBox.Yes)
if ret == QMessageBox.Yes:
# Save project
self.actionSave_trigger()
elif ret == QMessageBox.Cancel:
# User canceled prompt
return
# Prompt for open project file
file_path = QFileDialog.getOpenFileName(
self,
_("Open Project..."),
recommended_folder,
_("OpenShot Project (*.osp)"))[0]
if file_path:
# Load project file
self.OpenProjectSignal.emit(file_path)
def actionSave_trigger(self):
app = get_app()
s = app.get_settings()
_ = app._tr
# Get current filepath if any, otherwise ask user
file_path = app.project.current_filepath
if not file_path:
recommended_folder = s.getDefaultPath(s.actionType.SAVE)
recommended_path = os.path.join(
recommended_folder,
_("Untitled Project") + ".osp"
)
file_path = QFileDialog.getSaveFileName(
self,
_("Save Project..."),
recommended_path,
_("OpenShot Project (*.osp)"))[0]
if file_path:
s.setDefaultPath(s.actionType.SAVE, file_path)
# Append .osp if needed
if not file_path.endswith(".osp"):
file_path = "%s.osp" % file_path
# Save project
self.save_project(file_path)
def auto_save_project(self):
"""Auto save the project"""
import time
app = get_app()
s = app.get_settings()
# Get current filepath (if any)
file_path = app.project.current_filepath
if not app.project.needs_save():
return
if file_path:
# A Real project file exists
# Append .osp if needed
if not file_path.endswith(".osp"):
file_path = "%s.osp" % file_path
folder_path, file_name = os.path.split(file_path)
file_name, file_ext = os.path.splitext(file_name)
# Make copy of unsaved project file in 'recovery' folder
recover_path_with_timestamp = os.path.join(
info.RECOVERY_PATH, "%d-%s.osp" % (int(time.time()), file_name))
if os.path.exists(file_path):
shutil.copy(file_path, recover_path_with_timestamp)
else:
log.warning(
"Existing project *.osp file not found during recovery process: %s",
file_path)
# Find any recovery file older than X auto-saves
old_backup_files = []
backup_file_count = 0
for backup_filename in reversed(sorted(os.listdir(info.RECOVERY_PATH))):
if ".osp" in backup_filename:
backup_file_count += 1
if backup_file_count > s.get("recovery-limit"):
old_backup_files.append(os.path.join(info.RECOVERY_PATH, backup_filename))
# Delete recovery files which are 'too old'
for backup_filepath in old_backup_files:
os.unlink(backup_filepath)
# Save project
log.info("Auto save project file: %s", file_path)
self.save_project(file_path)
# Remove backup.osp (if any)
if os.path.exists(info.BACKUP_FILE):
# Delete backup.osp since we just saved the actual project
os.unlink(info.BACKUP_FILE)
else:
# No saved project found
log.info("Creating backup of project file: %s", info.BACKUP_FILE)
app.project.save(info.BACKUP_FILE, backup_only=True)
def actionSaveAs_trigger(self):
app = get_app()
s = app.get_settings()
_ = app._tr
project_file_path = app.project.current_filepath
if project_file_path:
recommended_file_name = os.path.basename(project_file_path)
else:
recommended_file_name = "%s.osp" % _("Untitled Project")
recommended_folder = s.getDefaultPath(s.actionType.SAVE)
recommended_path = os.path.join(
recommended_folder,
recommended_file_name
)
file_path = QFileDialog.getSaveFileName(
self,
_("Save Project As..."),
recommended_path,
_("OpenShot Project (*.osp)"))[0]
if file_path:
s.setDefaultPath(s.actionType.SAVE, file_path)
# Append .osp if needed
if ".osp" not in file_path:
file_path = "%s.osp" % file_path
# Save new project
self.save_project(file_path)
def actionImportFiles_trigger(self):
app = get_app()
s = app.get_settings()
_ = app._tr
recommended_path = s.getDefaultPath(s.actionType.IMPORT)
fd = QFileDialog()
fd.setDirectory(recommended_path)
qurl_list = fd.getOpenFileUrls(
self,
_("Import Files...")
)[0]
# Set cursor to waiting
app.setOverrideCursor(QCursor(Qt.WaitCursor))
try:
# Import list of files
self.files_model.process_urls(qurl_list)
# Refresh files views
self.refreshFilesSignal.emit()
finally:
# Restore cursor
app.restoreOverrideCursor()
def invalidImage(self, filename=None):
""" Show a popup when an image file can't be loaded """
if not filename:
return
# Translations
_ = get_app()._tr
# Show message to user
QMessageBox.warning(
self,
None,
_("%s is not a valid video, audio, or image file.") % filename,
QMessageBox.Ok
)
def promptImageSequence(self, filename=None):
""" Ask the user whether to import an image sequence """
if not filename:
return False
# Get translations
app = get_app()
_ = app._tr
# Process the event queue first, since we've been ignoring input
app.processEvents()
# Display prompt dialog
ret = QMessageBox.question(
self,
_("Import Image Sequence"),
_("Would you like to import %s as an image sequence?") % filename,
QMessageBox.No | QMessageBox.Yes
)
return ret == QMessageBox.Yes
def actionAdd_to_Timeline_trigger(self, checked=False):
# Loop through selected files
files = self.selected_files()
# Bail if nothing's selected
if not files:
return
# Get current position of playhead
fps = get_app().project.get("fps")
fps_float = float(fps["num"]) / float(fps["den"])
pos = (self.preview_thread.player.Position() - 1) / fps_float
# show window
from windows.add_to_timeline import AddToTimeline
win = AddToTimeline(files, pos)
# Run the dialog event loop - blocking interaction on this window during this time
result = win.exec_()
if result == QDialog.Accepted:
log.info('confirmed')
else:
log.info('canceled')
def actionExportVideo_trigger(self, checked=True):
# show window
from windows.export import Export
win = Export()
# Run the dialog event loop - blocking interaction on this window during this time
result = win.exec_()
if result == QDialog.Accepted:
log.info('Export Video add confirmed')
else:
log.info('Export Video add cancelled')
def actionExportEDL_trigger(self, checked=True):
"""Export EDL File"""
export_edl()
def actionExportFCPXML_trigger(self, checked=True):
"""Export XML (Final Cut Pro) File"""
export_xml()
def actionImportEDL_trigger(self, checked=True):
"""Import EDL File"""
import_edl()
def actionImportFCPXML_trigger(self, checked=True):
"""Import XML (Final Cut Pro) File"""
import_xml()
def actionUndo_trigger(self, checked=True):
log.info('actionUndo_trigger')
get_app().updates.undo()
# Update the preview
self.refreshFrameSignal.emit()
def actionRedo_trigger(self, checked=True):
log.info('actionRedo_trigger')
get_app().updates.redo()
# Update the preview
self.refreshFrameSignal.emit()
def actionPreferences_trigger(self, checked=True):
log.debug("Showing preferences dialog")
# Stop preview thread
self.SpeedSignal.emit(0)
self.PauseSignal.emit()
# Set cursor to waiting
get_app().setOverrideCursor(QCursor(Qt.WaitCursor))
# Show dialog
from windows.preferences import Preferences
win = Preferences()
# Run the dialog event loop - blocking interaction on this window during this time
result = win.exec_()
if result == QDialog.Accepted:
log.info('Preferences add confirmed')
else:
log.info('Preferences add cancelled')
# Save settings
s = get_app().get_settings()
s.save()
# Restore normal cursor
get_app().restoreOverrideCursor()
def actionFilesShowAll_trigger(self, checked=True):
self.refreshFilesSignal.emit()
def actionFilesShowVideo_trigger(self, checked=True):
self.refreshFilesSignal.emit()
def actionFilesShowAudio_trigger(self, checked=True):
self.refreshFilesSignal.emit()
def actionFilesShowImage_trigger(self, checked=True):
self.refreshFilesSignal.emit()
def actionTransitionsShowAll_trigger(self, checked=True):
self.refreshTransitionsSignal.emit()
def actionTransitionsShowCommon_trigger(self, checked=True):
self.refreshTransitionsSignal.emit()
def actionEffectsShowAll_trigger(self, checked=True):
self.refreshEffectsSignal.emit()
def actionEffectsShowVideo_trigger(self, checked=True):
self.refreshEffectsSignal.emit()
def actionEffectsShowAudio_trigger(self, checked=True):
self.refreshEffectsSignal.emit()
def actionHelpContents_trigger(self, checked=True):
try:
webbrowser.open("https://www.openshot.org/%suser-guide/?app-menu" % info.website_language(), new=1)
except Exception:
QMessageBox.information(self, "Error !", "Unable to open the online help")
log.error("Unable to open the Help Contents", exc_info=1)
def actionAbout_trigger(self, checked=True):
"""Show about dialog"""
from windows.about import About
win = About()
# Run the dialog event loop - blocking interaction on this window during this time
win.exec_()
def actionReportBug_trigger(self, checked=True):
try:
webbrowser.open("https://www.openshot.org/%sissues/new/?app-menu" % info.website_language(), new=1)
except Exception:
QMessageBox.information(self, "Error !", "Unable to open the Bug Report GitHub Issues web page")
log.error("Unable to open the Bug Report page", exc_info=1)
def actionAskQuestion_trigger(self, checked=True):
try:
webbrowser.open("https://www.reddit.com/r/OpenShot/", new=1)
except Exception:
QMessageBox.information(self, "Error !", "Unable to open the official OpenShot subreddit web page")
log.error("Unable to open the subreddit page", exc_info=1)
def actionTranslate_trigger(self, checked=True):
try:
webbrowser.open("https://translations.launchpad.net/openshot/2.0", new=1)
except Exception:
QMessageBox.information(self, "Error !", "Unable to open the Translation web page")
log.error("Unable to open the translation page", exc_info=1)
def actionDonate_trigger(self, checked=True):
try:
webbrowser.open("https://www.openshot.org/%sdonate/?app-menu" % info.website_language(), new=1)
except Exception:
QMessageBox.information(self, "Error !", "Unable to open the Donate web page")
log.error("Unable to open the donation page", exc_info=1)
def actionUpdate_trigger(self, checked=True):
try:
webbrowser.open("https://www.openshot.org/%sdownload/?app-toolbar" % info.website_language(), new=1)
except Exception:
QMessageBox.information(self, "Error !", "Unable to open the Download web page")
log.error("Unable to open the download page", exc_info=1)
def should_play(self, requested_speed=0):
"""Determine if we should start playback, based on the current frame
and the total number of frames in our timeline clips. For example,
if we are at the end of our last clip, and the user clicks play, we
do not want to start playback."""
# Get max frame (based on last clip) and current frame
max_frame = get_app().window.timeline_sync.timeline.GetMaxFrame()
current_frame = self.preview_thread.current_frame
if current_frame is not None:
next_frame = current_frame + requested_speed
return next_frame <= max_frame and next_frame > 0
return False
def actionPlay_trigger(self):
"""Toggle play/pause on video preview"""
player = self.preview_thread.player
if player.Mode() == openshot.PLAYBACK_PAUSED:
# Start playback
if self.should_play():
max_frame = get_app().window.timeline_sync.timeline.GetMaxFrame()
self.PlaySignal.emit()
else:
# Pause playback
self.PauseSignal.emit()
def actionPreview_File_trigger(self, checked=True):
""" Preview the selected media file """
log.info('actionPreview_File_trigger')
# Loop through selected files (set 1 selected file if more than 1)
f = self.files_model.current_file()