Skip to content

Commit 9b5f7f4

Browse files
committed
Animated titles: Source/imports cleanup
1 parent 465f463 commit 9b5f7f4

File tree

4 files changed

+58
-100
lines changed

4 files changed

+58
-100
lines changed

src/windows/animated_title.py

+2-12
Original file line numberDiff line numberDiff line change
@@ -26,26 +26,16 @@
2626
along with OpenShot Library. If not, see <http://www.gnu.org/licenses/>.
2727
"""
2828

29-
import sys
3029
import os
31-
import time
3230
import uuid
33-
import shutil
34-
import subprocess
35-
import re
36-
import math
3731

38-
from PyQt5.QtCore import *
39-
from PyQt5.QtGui import QIcon, QStandardItemModel, QStandardItem
40-
from PyQt5.QtWidgets import *
41-
from PyQt5 import uic
32+
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QPushButton
4233

43-
from classes import info, metrics, ui_util, settings, qt_types, updates
34+
from classes import info, ui_util, metrics
4435
from classes.app import get_app
4536
from classes.logger import log
4637
from windows.views.blender_listview import BlenderListView
4738

48-
import json
4939

5040
class AnimatedTitle(QDialog):
5141
""" Animated Title Dialog """

src/windows/models/blender_model.py

+36-55
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,14 @@
2929

3030
# Try to get the security-patched XML functions from defusedxml
3131
try:
32-
from defusedxml import minidom as xml
32+
from defusedxml import minidom as xml
3333
except ImportError:
34-
from xml.dom import minidom as xml
34+
from xml.dom import minidom as xml
3535

3636
from PyQt5.QtCore import Qt, QSize
37-
from PyQt5.QtGui import *
38-
from PyQt5.QtWidgets import QMessageBox
39-
import openshot # Python module for libopenshot (required video editing module installed separately)
37+
from PyQt5.QtGui import QIcon, QPixmap, QStandardItem, QStandardItemModel
38+
39+
import openshot
4040

4141
from classes import info
4242
from classes.logger import log
@@ -46,11 +46,8 @@
4646
class BlenderModel():
4747
def update_model(self, clear=True):
4848
log.info("updating effects model.")
49-
app = get_app()
5049

51-
# Get window to check filters
52-
win = app.window
53-
_ = app._tr
50+
_ = self.app._tr
5451

5552
# Clear all items
5653
if clear:
@@ -60,25 +57,24 @@ def update_model(self, clear=True):
6057
# Add Headers
6158
self.model.setHorizontalHeaderLabels([_("Thumb"), _("Name")])
6259

63-
# get a list of files in the OpenShot /effects directory
64-
effects_dir = os.path.join(info.PATH, "blender")
65-
icons_dir = os.path.join(effects_dir, "icons")
66-
67-
for file in sorted(os.listdir(effects_dir)):
68-
if os.path.isfile(os.path.join(effects_dir, file)) and ".xml" in file:
69-
# Split path
70-
path = os.path.join(effects_dir, file)
60+
# get a list of files in the application blender directory
61+
blender_dir = os.path.join(info.PATH, "blender")
62+
icons_dir = os.path.join(blender_dir, "icons")
7163

64+
for file in sorted(os.listdir(blender_dir)):
65+
path = os.path.join(blender_dir, file)
66+
if path in self.model_paths:
67+
continue
68+
if os.path.isfile(path) and ".xml" in file:
7269
# load xml effect file
7370
xmldoc = xml.parse(path)
7471

75-
# Get all attributes
72+
# Get column data for model
7673
title = xmldoc.getElementsByTagName("title")[0].childNodes[0].data
77-
description = xmldoc.getElementsByTagName("description")[0].childNodes[0].data
7874
icon_name = xmldoc.getElementsByTagName("icon")[0].childNodes[0].data
7975
icon_path = os.path.join(icons_dir, icon_name)
80-
category = xmldoc.getElementsByTagName("category")[0].childNodes[0].data
8176
service = xmldoc.getElementsByTagName("service")[0].childNodes[0].data
77+
xmldoc.unlink()
8278

8379
# Check for thumbnail path (in build-in cache)
8480
thumb_path = os.path.join(info.IMAGES_PATH, "cache", "blender_{}".format(icon_name))
@@ -95,66 +91,51 @@ def update_model(self, clear=True):
9591
# Reload this reader
9692
clip = openshot.Clip(icon_path)
9793
reader = clip.Reader()
98-
99-
# Open reader
10094
reader.Open()
10195

102-
# Determine scale of thumbnail
103-
scale = 95.0 / reader.info.width
104-
10596
# Save thumbnail
106-
reader.GetFrame(0).Thumbnail(thumb_path, 98, 64, "", "",
107-
"#000", False, "png", 85, 0.0)
97+
reader.GetFrame(0).Thumbnail(
98+
thumb_path, 98, 64, "", "",
99+
"#000", False, "png", 85, 0.0)
108100
reader.Close()
109-
110-
except:
111-
# Handle exception
112-
log.info('Invalid blender image file: %s' % icon_path)
113-
msg = QMessageBox()
114-
msg.setText(_("{} is not a valid image file.".format(icon_path)))
115-
msg.exec_()
101+
except Exception:
102+
log.info('Invalid blender image file: %s', icon_path)
116103
continue
117104

118105
row = []
119-
106+
flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
120107
# Append thumbnail
121-
col = QStandardItem()
122-
icon_pixmap = QPixmap(thumb_path)
123-
scaled_pixmap = icon_pixmap.scaled(QSize(93, 62), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
124-
col.setIcon(QIcon(scaled_pixmap))
125-
col.setText(self.app._tr(title))
108+
col = QStandardItem(self.app._tr(title))
109+
icon_pixmap = QPixmap(thumb_path).scaled(
110+
QSize(93, 62), Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
111+
col.setIcon(QIcon(icon_pixmap))
126112
col.setToolTip(self.app._tr(title))
127-
col.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
113+
col.setFlags(flags)
128114
row.append(col)
129115

130116
# Append Name
131-
col = QStandardItem("Name")
117+
col = QStandardItem(self.app._tr(title))
132118
col.setData(self.app._tr(title), Qt.DisplayRole)
133-
col.setText(self.app._tr(title))
134-
col.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
119+
col.setFlags(flags)
135120
row.append(col)
136121

137122
# Append Path
138-
col = QStandardItem("Path")
123+
col = QStandardItem(path)
139124
col.setData(path, Qt.DisplayRole)
140-
col.setText(path)
141-
col.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
125+
col.setFlags(flags)
142126
row.append(col)
143127

144128
# Append Service
145-
col = QStandardItem("Service")
129+
col = QStandardItem(service)
146130
col.setData(service, Qt.DisplayRole)
147-
col.setText(service)
148-
col.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
131+
col.setFlags(flags)
149132
row.append(col)
150133

151-
# Append ROW to MODEL (if does not already exist in model)
152-
if path not in self.model_paths:
153-
self.model.appendRow(row)
154-
self.model_paths[path] = path
134+
self.model.appendRow(row)
135+
self.model_paths[path] = path
155136

156137
# Process events in QT (to keep the interface responsive)
157-
app.processEvents()
138+
self.app.processEvents()
158139

159140
def __init__(self, *args):
160141

src/windows/views/blender_listview.py

+20-32
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import sys
3232
import re
3333
import functools
34+
import shlex
3435

3536
# Try to get the security-patched XML functions from defusedxml
3637
try:
@@ -66,10 +67,7 @@ def currentChanged(self, selected, deselected):
6667
# Get translation object
6768
_ = self.app._tr
6869

69-
# Clear existing settings
7070
self.win.clear_effect_controls()
71-
72-
# Get animation details
7371
animation = self.get_animation_details()
7472
self.selected_template = animation.get("service")
7573

@@ -83,17 +81,15 @@ def currentChanged(self, selected, deselected):
8381

8482
# Loop through params
8583
for param in animation.get("params", []):
86-
log.info('Using parameter %s: %s' % (param["name"], param["title"]))
84+
log.debug('Using parameter %s: %s' % (param["name"], param["title"]))
8785

8886
# Is Hidden Param?
89-
if param["name"] == "start_frame" or param["name"] == "end_frame":
87+
if param["name"] in ["start_frame", "end_frame"]:
9088
# add value to dictionary
9189
self.params[param["name"]] = int(param["default"])
92-
93-
# skip to next param without rendering the controls
90+
# skip to next param without rendering a control
9491
continue
9592

96-
# Create Label
9793
widget = None
9894
label = QLabel()
9995
label.setText(_(param["title"]))
@@ -162,15 +158,13 @@ def currentChanged(self, selected, deselected):
162158
)
163159

164160
# Add normal values
165-
box_index = 0
166-
for k, v in sorted(param["values"].items()):
161+
for i, (k, v) in enumerate(sorted(param["values"].items())):
167162
# add dropdown item
168163
widget.addItem(_(k), v)
169164

170165
# select dropdown (if default)
171166
if v == param["default"]:
172-
widget.setCurrentIndex(box_index)
173-
box_index = box_index + 1
167+
widget.setCurrentIndex(i)
174168

175169
if not param["values"]:
176170
widget.addItem(_("No Files Found"), "")
@@ -193,10 +187,7 @@ def currentChanged(self, selected, deselected):
193187
elif (label):
194188
self.win.settingsContainer.layout().addRow(label)
195189

196-
# Enable interface
197190
self.enable_interface()
198-
199-
# Init slider values
200191
self.init_slider_values()
201192

202193
def spinner_value_changed(self, param, value):
@@ -393,7 +384,7 @@ def get_animation_details(self):
393384
)
394385
])
395386
except (TypeError, AttributeError) as ex:
396-
log.warn("XML parser: {}".format(ex))
387+
log.warn("XML parser: %s", ex)
397388
pass
398389

399390
# Append param object to list
@@ -439,8 +430,10 @@ def get_project_params(self, is_preview=True):
439430
project_params["alpha_mode"] = 1
440431
project_params["horizon_color"] = (0.57, 0.57, 0.57)
441432
project_params["animation"] = True
442-
project_params["output_path"] = os.path.join(info.BLENDER_PATH, self.unique_folder_name,
443-
self.params["file_name"])
433+
project_params["output_path"] = os.path.join(
434+
info.BLENDER_PATH,
435+
self.unique_folder_name,
436+
self.params["file_name"])
444437

445438
# return the dictionary
446439
return project_params
@@ -487,17 +480,13 @@ def inject_params(self, path, frame=None):
487480

488481
# prepare string to inject
489482
user_params = "\n#BEGIN INJECTING PARAMS\n"
490-
for k, v in self.params.items():
491-
if type(v) == int or type(v) == float or type(v) == list or type(v) == bool:
492-
user_params += "params['{}'] = {}\n".format(k, v)
493-
if type(v) == str:
494-
user_params += "params['{}'] = u'{}'\n".format(k, v.replace("'", r"\'"))
495-
496-
for k, v in self.get_project_params(is_preview).items():
497-
if type(v) == int or type(v) == float or type(v) == list or type(v) == bool:
483+
param_data = self.params.items()
484+
param_data.update(self.get_project_params(is_preview))
485+
for k, v in param_data.items():
486+
if isinstance(v, (int, float, list, bool)):
498487
user_params += "params['{}'] = {}\n".format(k, v)
499-
if type(v) == str:
500-
user_params += "params['{}'] = u'{}'\n".format(k, v.replace("'", r"\'").replace("\\", "\\\\"))
488+
if isinstance(v, str):
489+
user_params += "params['{}'] = '{}'\n".format(k, v.replace("'", r"\'").replace("\\", "\\\\"))
501490
user_params += "#END INJECTING PARAMS\n"
502491

503492
# Insert the single frame number to render for preview
@@ -577,13 +566,12 @@ def Render(self, frame=None):
577566
Q_ARG(int, int(frame or 0))
578567
)
579568

580-
def __init__(self, *args):
581-
# Invoke parent init
569+
def __init__(self, parent, *args):
570+
# Invoke base class init
582571
super().__init__(*args)
583572

584-
# Get a reference to the window object
573+
self.win = parent
585574
self.app = get_app()
586-
self.win = args[0]
587575

588576
# Get Model data
589577
self.blender_model = BlenderModel()

src/windows/views/files_treeview.py

-1
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,6 @@ def __init__(self, model, *args):
225225
self.setSelectionBehavior(QAbstractItemView.SelectRows)
226226
self.setSelectionModel(self.files_model.selection_model)
227227

228-
# Keep track of mouse press start position to determine when to start drag
229228
self.setAcceptDrops(True)
230229
self.setDragEnabled(True)
231230
self.setDropIndicatorShown(True)

0 commit comments

Comments
 (0)