[pitivi] autopep8 WORKS, let's just use it!
- From: Thibault Saunier <tsaunier src gnome org>
- To: commits-list gnome org
- Cc:
- Subject: [pitivi] autopep8 WORKS, let's just use it!
- Date: Sat, 15 Nov 2014 10:32:28 +0000 (UTC)
commit 01295e53bfc157feaad3cc347c758e1b12f752e3
Author: Thibault Saunier <tsaunier gnome org>
Date: Thu Sep 25 12:41:35 2014 +0200
autopep8 WORKS, let's just use it!
https://bugzilla.gnome.org/show_bug.cgi?id=739251
pitivi/application.py | 28 ++-
pitivi/autoaligner.py | 34 ++-
pitivi/check.py | 14 +-
pitivi/clipproperties.py | 70 ++++--
pitivi/dialogs/clipmediaprops.py | 7 +-
pitivi/dialogs/depsmanager.py | 7 +-
pitivi/dialogs/filelisterrordialog.py | 8 +-
pitivi/dialogs/prefs.py | 65 +++--
pitivi/dialogs/startupwizard.py | 12 +-
pitivi/effects.py | 51 +++--
pitivi/mainwindow.py | 292 ++++++++++++--------
pitivi/mediafilespreviewer.py | 60 +++--
pitivi/medialibrary.py | 181 ++++++++-----
pitivi/preset.py | 9 +-
pitivi/project.py | 160 +++++++----
pitivi/render.py | 227 ++++++++++------
pitivi/settings.py | 12 +-
pitivi/tabsmanager.py | 46 ++--
pitivi/timeline/controls.py | 10 +-
pitivi/timeline/elements.py | 156 +++++++----
pitivi/timeline/layer.py | 65 +++--
pitivi/timeline/previewers.py | 107 +++++---
pitivi/timeline/ruler.py | 36 ++-
pitivi/timeline/timeline.py | 201 +++++++++-----
pitivi/titleeditor.py | 54 +++--
pitivi/transitions.py | 60 +++--
pitivi/undo/effect.py | 20 +-
pitivi/undo/timeline.py | 39 ++-
pitivi/undo/undo.py | 24 ++-
pitivi/utils/extract.py | 12 +-
pitivi/utils/loggable.py | 58 +++--
pitivi/utils/misc.py | 3 +-
pitivi/utils/pipeline.py | 48 +++-
pitivi/utils/ripple_update_group.py | 3 +-
pitivi/utils/system.py | 47 ++--
pitivi/utils/threads.py | 2 +
pitivi/utils/ui.py | 22 +-
pitivi/utils/widgets.py | 97 +++++---
pitivi/viewer.py | 142 ++++++----
tests/common.py | 3 +-
tests/dogtail_scripts/common.py | 96 +++++---
tests/dogtail_scripts/test_clipproperties.py | 83 ++++--
.../dogtail_scripts/test_dialogs_clipmediaprops.py | 22 +-
tests/dogtail_scripts/test_dialogs_prefs.py | 18 +-
.../dogtail_scripts/test_dialogs_startupwizard.py | 1 +
tests/dogtail_scripts/test_effects.py | 27 ++-
tests/dogtail_scripts/test_medialibrary.py | 15 +-
tests/dogtail_scripts/test_project.py | 123 ++++++---
tests/dogtail_scripts/test_timeline.py | 72 ++++--
tests/runtests.py | 5 +-
tests/test_application.py | 10 +-
tests/test_check.py | 3 +-
tests/test_clipproperties.py | 42 ++-
tests/test_log.py | 2 +-
tests/test_mainwindow.py | 6 +-
tests/test_prefs.py | 87 +++---
tests/test_preset.py | 34 ++-
tests/test_project.py | 31 ++-
tests/test_projectsettings.py | 6 +-
tests/test_system.py | 17 +-
tests/test_undo.py | 8 +-
tests/test_undo_timeline.py | 1 +
tests/test_utils.py | 6 +-
win32/setup.py | 107 ++++----
64 files changed, 2085 insertions(+), 1229 deletions(-)
---
diff --git a/pitivi/application.py b/pitivi/application.py
index 24444c8..c7144b8 100644
--- a/pitivi/application.py
+++ b/pitivi/application.py
@@ -46,6 +46,7 @@ import pitivi.utils.loggable as log
class Pitivi(Gtk.Application, Loggable):
+
"""
Pitivi's application.
@@ -82,7 +83,8 @@ class Pitivi(Gtk.Application, Loggable):
uri = quote_uri(os.environ['PITIVI_SCENARIO_FILE'])
else:
cache_dir = get_dir(os.path.join(xdg_cache_home(), "scenarios"))
- uri = os.path.join(cache_dir, str(time.strftime("%Y%m%d-%H%M%S")) + ".scenario")
+ uri = os.path.join(
+ cache_dir, str(time.strftime("%Y%m%d-%H%M%S")) + ".scenario")
uri = quote_uri(uri)
self._first_action = True
self.log_file = open(path_from_uri(uri), "w")
@@ -98,7 +100,8 @@ class Pitivi(Gtk.Application, Loggable):
def write_action(self, structure):
if self._first_action:
- self.log_file.write("description, seek=true, handles-states=true\n")
+ self.log_file.write(
+ "description, seek=true, handles-states=true\n")
self._first_action = False
self.log_file.write(structure.to_string() + "\n")
@@ -106,7 +109,8 @@ class Pitivi(Gtk.Application, Loggable):
def _startupCb(self, unused_app):
# Init logging as early as possible so we can log startup code
- enable_color = not os.environ.get('PITIVI_DEBUG_NO_COLOR', '0') in ('', '1')
+ enable_color = not os.environ.get(
+ 'PITIVI_DEBUG_NO_COLOR', '0') in ('', '1')
# Let's show a human-readable Pitivi debug output by default, and only
# show a crazy unreadable mess when surrounded by gst debug statements.
enable_crack_output = "GST_DEBUG" in os.environ
@@ -125,7 +129,8 @@ class Pitivi(Gtk.Application, Loggable):
self.timeline_log_observer = TimelineLogObserver(self.action_log)
self.project_log_observer = ProjectLogObserver(self.action_log)
- self.project_manager.connect("new-project-loaded", self._newProjectLoaded)
+ self.project_manager.connect(
+ "new-project-loaded", self._newProjectLoaded)
self.project_manager.connect("project-closed", self._projectClosed)
self._createActions()
@@ -179,7 +184,8 @@ class Pitivi(Gtk.Application, Loggable):
assert giofiles
self.createMainWindow()
if len(giofiles) > 1:
- self.warning("Can open only one project file at a time. Ignoring the rest!")
+ self.warning(
+ "Can open only one project file at a time. Ignoring the rest!")
project_file = giofiles[0]
self.project_manager.loadProject(quote_uri(project_file.get_uri()))
return True
@@ -194,7 +200,8 @@ class Pitivi(Gtk.Application, Loggable):
self.debug("shutting down")
# Refuse to close if we are not done with the current project.
if not self.project_manager.closeRunningProject():
- self.warning("Not closing since running project doesn't want to close")
+ self.warning(
+ "Not closing since running project doesn't want to close")
return False
if self.welcome_wizard:
self.welcome_wizard.hide()
@@ -245,12 +252,15 @@ class Pitivi(Gtk.Application, Loggable):
self.info("Latest software version is %s", current_version)
VERSION_split = [int(i) for i in VERSION.split(".")]
- current_version_split = [int(i) for i in current_version.split(".")]
+ current_version_split = [int(i)
+ for i in current_version.split(".")]
if VERSION_split > current_version_split:
status = "CURRENT"
- self.info("Running version %s, which is newer than the latest known version. Considering it
as the latest current version.", VERSION)
+ self.info(
+ "Running version %s, which is newer than the latest known version. Considering it as the
latest current version.", VERSION)
elif status is "UNSUPPORTED":
- self.warning("Using an outdated version of Pitivi (%s)", VERSION)
+ self.warning(
+ "Using an outdated version of Pitivi (%s)", VERSION)
self._version_information["current"] = current_version
self._version_information["status"] = status
diff --git a/pitivi/autoaligner.py b/pitivi/autoaligner.py
index f986237..3932ffa 100644
--- a/pitivi/autoaligner.py
+++ b/pitivi/autoaligner.py
@@ -213,12 +213,13 @@ def affinealign(reference, targets, max_drift=0.02):
for t in targets:
t -= numpy.mean(t)
ft = numpy.fft.rfft(t, L2)
- #fxcorr is the FFT'd cross-correlation with the reference blocks
+ # fxcorr is the FFT'd cross-correlation with the reference blocks
fxcorr_blocks = numpy.zeros((L2 / 2 + 1, num_blocks),
dtype=numpy.complex)
for i in range(num_blocks):
fxcorr_blocks[:, i] = ft * freference_blocks[:, i]
- fxcorr_blocks[:, i] /= numpy.sqrt(numpy.sum(fxcorr_blocks[:, i] ** 2))
+ fxcorr_blocks[:, i] /= numpy.sqrt(
+ numpy.sum(fxcorr_blocks[:, i] ** 2))
del ft
# At this point xcorr_blocks would show a distinct bright line, nearly
# orthogonal to time, indicating where each of these blocks found their
@@ -253,16 +254,17 @@ def affinealign(reference, targets, max_drift=0.02):
halfautocorr[-1:2, -1:2] = 0 # NEEDS TUNING
# Normalize each column (appears to be necessary)
for i in range(2 * num_blocks):
- halfautocorr[:, i] /= numpy.sqrt(numpy.sum(halfautocorr[:, i] ** 2))
- #from matplotlib.pyplot import imshow,show
- #imshow(halfautocorr,interpolation='nearest',aspect='auto');show()
+ halfautocorr[:, i] /= numpy.sqrt(
+ numpy.sum(halfautocorr[:, i] ** 2))
+ # from matplotlib.pyplot import imshow,show
+ # imshow(halfautocorr,interpolation='nearest',aspect='auto');show()
drift = _findslope(halfautocorr) / bspace
del halfautocorr
- #inverse transform and shift everything into alignment
+ # inverse transform and shift everything into alignment
xcorr_blocks = numpy.fft.irfft(fxcorr_blocks, None, 0)
del fxcorr_blocks
- #TODO: see if phase ramps are worthwhile here
+ # TODO: see if phase ramps are worthwhile here
for i in range(num_blocks):
blockcenter = i * bspace + bsize / 2
shift = int(blockcenter * drift)
@@ -275,16 +277,16 @@ def affinealign(reference, targets, max_drift=0.02):
xcorr_blocks[-shift:, i] = xcorr_blocks[:shift, i].copy()
xcorr_blocks[:-shift, i] = temp
- #from matplotlib.pyplot import imshow,show
- #imshow(xcorr_blocks,interpolation='nearest',aspect='auto');show()
+ # from matplotlib.pyplot import imshow,show
+ # imshow(xcorr_blocks,interpolation='nearest',aspect='auto');show()
# xcorr is the drift-compensated cross-correlation
xcorr = numpy.sum(xcorr_blocks, axis=1)
del xcorr_blocks
offset = numpy.argmax(xcorr)
- #from matplotlib.pyplot import plot,show
- #plot(xcorr);show()
+ # from matplotlib.pyplot import plot,show
+ # plot(xcorr);show()
del xcorr
if offset >= len(t):
offset -= L2
@@ -576,13 +578,15 @@ class AutoAligner(Loggable):
for clip, audiotrack in pairs:
# blocksize is the number of samples per block
blocksize = audiotrack.stream.rate // self.BLOCKRATE
- extractee = EnvelopeExtractee(blocksize, self._envelopeCb, clip)
+ extractee = EnvelopeExtractee(
+ blocksize, self._envelopeCb, clip)
# numsamples is the total number of samples in the track,
# which is used by progress_aggregator to determine
# the percent completion.
numsamples = ((audiotrack.duration / Gst.SECOND) *
audiotrack.stream.rate)
- extractee.addWatcher(progress_aggregator.getPortionCB(numsamples))
+ extractee.addWatcher(
+ progress_aggregator.getPortionCB(numsamples))
self._extraction_stack.append((audiotrack, extractee))
# After we return, start the extraction cycle.
# This GLib.idle_add call should not be necessary;
@@ -647,13 +651,15 @@ class AutoAligner(Loggable):
class AlignmentProgressDialog:
+
""" Dialog indicating the progress of the auto-alignment process.
Code derived from L{RenderingProgressDialog}, but greatly simplified
(read-only, no buttons)."""
def __init__(self, app):
self.builder = Gtk.Builder()
- self.builder.add_from_file(os.path.join(configure.get_ui_dir(), "alignmentprogress.ui"))
+ self.builder.add_from_file(
+ os.path.join(configure.get_ui_dir(), "alignmentprogress.ui"))
self.builder.connect_signals(self)
self.window = self.builder.get_object("align-progress")
diff --git a/pitivi/check.py b/pitivi/check.py
index be9df14..c4f40c7 100644
--- a/pitivi/check.py
+++ b/pitivi/check.py
@@ -49,6 +49,7 @@ def _string_to_list(version):
class Dependency(object):
+
"""
This abstract class represents a module or component requirement.
@param modulename: The string allowing for import or lookup of the component.
@@ -57,6 +58,7 @@ class Dependency(object):
@param additional_message: A string that will be displayed to the user to further
explain the purpose of the missing component.
"""
+
def __init__(self, modulename, version_required_string, additional_message=None):
self.version_required_string = version_required_string
self.modulename = modulename
@@ -120,6 +122,7 @@ class Dependency(object):
class GIDependency(Dependency):
+
def _try_importing_component(self):
try:
__import__("gi.repository." + self.modulename)
@@ -133,6 +136,7 @@ class GIDependency(Dependency):
class ClassicDependency(Dependency):
+
def _try_importing_component(self):
try:
__import__(self.modulename)
@@ -146,10 +150,12 @@ class ClassicDependency(Dependency):
class GstPluginDependency(Dependency):
+
"""
Don't call check on its instances before actually checking
Gst is importable.
"""
+
def _try_importing_component(self):
try:
from gi.repository import Gst
@@ -166,16 +172,19 @@ class GstPluginDependency(Dependency):
class GstDependency(GIDependency):
+
def _format_version(self, module):
return list(module.version())
class GtkOrClutterDependency(GIDependency):
+
def _format_version(self, module):
return [module.MAJOR_VERSION, module.MINOR_VERSION, module.MICRO_VERSION]
class CairoDependency(ClassicDependency):
+
def __init__(self, version_required_string):
ClassicDependency.__init__(self, "cairo", version_required_string)
@@ -207,7 +216,8 @@ def check_requirements():
dependency.check()
if not dependency.satisfied:
if hard_dependencies_satisfied:
- print((_("ERROR - The following hard dependencies are unmet:")))
+ print(
+ (_("ERROR - The following hard dependencies are unmet:")))
print("==================================================")
print(dependency)
hard_dependencies_satisfied = False
@@ -229,7 +239,7 @@ def check_requirements():
if not _check_audiosinks():
print((_("Could not create audio output sink. "
- "Make sure you have a valid one (pulsesink, alsasink or osssink).")))
+ "Make sure you have a valid one (pulsesink, alsasink or osssink).")))
return False
return True
diff --git a/pitivi/clipproperties.py b/pitivi/clipproperties.py
index 674550e..b3bb286 100644
--- a/pitivi/clipproperties.py
+++ b/pitivi/clipproperties.py
@@ -49,6 +49,7 @@ from pitivi.effects import AUDIO_EFFECT, VIDEO_EFFECT, HIDDEN_EFFECTS, \
class ClipPropertiesError(Exception):
+
"""Base Exception for errors happening in L{ClipProperties}s or L{EffectProperties}s"""
pass
@@ -56,15 +57,16 @@ class ClipPropertiesError(Exception):
def compare_type(track, effect_type):
if (track.get_property("track_type") == GES.TrackType.AUDIO
- and effect_type == AUDIO_EFFECT):
+ and effect_type == AUDIO_EFFECT):
return True
elif (track.get_property("track_type") == GES.TrackType.VIDEO
- and effect_type == VIDEO_EFFECT):
+ and effect_type == VIDEO_EFFECT):
return True
return False
class ClipProperties(Gtk.ScrolledWindow, Loggable):
+
"""
Widget for configuring the selected clip.
@@ -99,14 +101,16 @@ class ClipProperties(Gtk.ScrolledWindow, Loggable):
# vbox.pack_start(self.transformation_expander, False, True, 0)
effects_properties_manager = EffectsPropertiesManager(app)
- self.effect_expander = EffectProperties(app, effects_properties_manager, self)
+ self.effect_expander = EffectProperties(
+ app, effects_properties_manager, self)
self.effect_expander.set_vexpand(False)
vbox.pack_start(self.effect_expander, True, True, 0)
def _setProject(self, project):
self._project = project
if project:
- self.effect_expander._connectTimelineSelection(self.app.gui.timeline_ui.timeline)
+ self.effect_expander._connectTimelineSelection(
+ self.app.gui.timeline_ui.timeline)
# Transformation boxed DISABLED
# if self.transformation_expander:
# self.transformation_expander.timeline = self.app.gui.timeline_ui.timeline
@@ -138,6 +142,7 @@ class ClipProperties(Gtk.ScrolledWindow, Loggable):
class EffectProperties(Gtk.Expander, Loggable):
+
"""
Widget for viewing and configuring effects
@@ -165,7 +170,8 @@ class EffectProperties(Gtk.Expander, Loggable):
# The toolbar that will go between the list of effects and properties
self._toolbar = Gtk.Toolbar()
- self._toolbar.get_style_context().add_class(Gtk.STYLE_CLASS_INLINE_TOOLBAR)
+ self._toolbar.get_style_context().add_class(
+ Gtk.STYLE_CLASS_INLINE_TOOLBAR)
self._toolbar.set_icon_size(Gtk.IconSize.SMALL_TOOLBAR)
removeEffectButton = Gtk.ToolButton()
removeEffectButton.set_icon_name("list-remove-symbolic")
@@ -173,7 +179,8 @@ class EffectProperties(Gtk.Expander, Loggable):
removeEffectButton.set_is_important(True)
self._toolbar.insert(removeEffectButton, 0)
- # Treeview to display a list of effects (checkbox, effect type and name)
+ # Treeview to display a list of effects (checkbox, effect type and
+ # name)
self.treeview_scrollwin = Gtk.ScrolledWindow()
self.treeview_scrollwin.set_policy(Gtk.PolicyType.NEVER,
Gtk.PolicyType.AUTOMATIC)
@@ -203,7 +210,7 @@ class EffectProperties(Gtk.Expander, Loggable):
activatedcell.props.xpad = PADDING
activatedcell.connect("toggled", self._effectActiveToggleCb)
activatedcol = self.treeview.insert_column_with_attributes(-1,
- _("Active"), activatedcell, active=COL_ACTIVATED)
+ _("Active"), activatedcell,
active=COL_ACTIVATED)
typecol = Gtk.TreeViewColumn(_("Type"))
typecol.set_spacing(SPACING)
@@ -242,7 +249,8 @@ class EffectProperties(Gtk.Expander, Loggable):
self._vcontent = Gtk.VPaned()
self._table = Gtk.Table(n_rows=3, n_columns=1, homogeneous=False)
self._table.attach(self.treeview_scrollwin, 0, 1, 0, 1)
- self._table.attach(self._toolbar, 0, 1, 2, 3, yoptions=Gtk.AttachOptions.FILL)
+ self._table.attach(
+ self._toolbar, 0, 1, 2, 3, yoptions=Gtk.AttachOptions.FILL)
self._vcontent.pack1(self._table, resize=True, shrink=False)
self.add(self._vcontent)
self._vcontent.show()
@@ -259,7 +267,8 @@ class EffectProperties(Gtk.Expander, Loggable):
self.treeview.connect("query-tooltip", self._treeViewQueryTooltipCb)
self._vcontent.connect("notify", self._vcontentNotifyCb)
removeEffectButton.connect("clicked", self._removeEffectCb)
- self.app.project_manager.connect("new-project-loaded", self._newProjectLoadedCb)
+ self.app.project_manager.connect(
+ "new-project-loaded", self._newProjectLoadedCb)
self.connect('notify::expanded', self._expandedCb)
self.connected = False
@@ -278,10 +287,12 @@ class EffectProperties(Gtk.Expander, Loggable):
def _setTimeline(self, timeline):
if self.connected:
- self._timeline.selection.disconnect_by_func(self._selectionChangedCb)
+ self._timeline.selection.disconnect_by_func(
+ self._selectionChangedCb)
self._timeline = timeline
if timeline:
- self._timeline.selection.connect("selection-changed", self._selectionChangedCb)
+ self._timeline.selection.connect(
+ "selection-changed", self._selectionChangedCb)
self.connected = bool(timeline)
timeline = property(_getTimeline, _setTimeline)
@@ -338,7 +349,8 @@ class EffectProperties(Gtk.Expander, Loggable):
def addEffectToClip(self, clip, factory_name, priority=None):
"""Adds the specified effect if it can be applied to the clip."""
model = self.treeview.get_model()
- media_type = self.app.effects.getFactoryFromName(factory_name).media_type
+ media_type = self.app.effects.getFactoryFromName(
+ factory_name).media_type
for track_element in clip.get_children(False):
track_type = track_element.get_track_type()
if track_type == GES.TrackType.AUDIO and media_type == AUDIO_EFFECT or \
@@ -364,11 +376,13 @@ class EffectProperties(Gtk.Expander, Loggable):
self.addEffectToClip(clip, factory_name)
def _dragMotionCb(self, unused_tree_view, unused_drag_context, unused_x, unused_y, unused_timestamp):
- self.debug("Something is being dragged in the clip properties' effects list")
+ self.debug(
+ "Something is being dragged in the clip properties' effects list")
self.drag_highlight()
def _dragLeaveCb(self, unused_tree_view, unused_drag_context, unused_timestamp):
- self.info("The item being dragged has left the clip properties' effects list")
+ self.info(
+ "The item being dragged has left the clip properties' effects list")
self.drag_unhighlight()
def _dragDataReceivedCb(self, treeview, drag_context, x, y, selection_data, unused_info, timestamp):
@@ -402,7 +416,8 @@ class EffectProperties(Gtk.Expander, Loggable):
if dest_row:
drop_path, drop_pos = dest_row
drop_index = drop_path.get_indices()[0]
- drop_index = self.calculateEffectPriority(source_index, drop_index, drop_pos)
+ drop_index = self.calculateEffectPriority(
+ source_index, drop_index, drop_pos)
else:
# This should happen when dragging after the last row.
drop_index = len(model) - 1
@@ -455,13 +470,15 @@ class EffectProperties(Gtk.Expander, Loggable):
self.updateAll()
def _treeViewQueryTooltipCb(self, view, x, y, keyboard_mode, tooltip):
- is_row, x, y, model, path, tree_iter = view.get_tooltip_context(x, y, keyboard_mode)
+ is_row, x, y, model, path, tree_iter = view.get_tooltip_context(
+ x, y, keyboard_mode)
if not is_row:
return False
view.set_tooltip_row(tooltip, path)
description = self.storemodel.get_value(tree_iter, COL_DESC_TEXT)
- bin_description = self.storemodel.get_value(tree_iter, COL_BIN_DESCRIPTION_TEXT)
+ bin_description = self.storemodel.get_value(
+ tree_iter, COL_BIN_DESCRIPTION_TEXT)
tooltip.set_text("%s\n%s" % (bin_description, description))
return True
@@ -495,7 +512,8 @@ class EffectProperties(Gtk.Expander, Loggable):
elif track_type == GES.TrackType.VIDEO:
to_append.append("Video")
to_append.append(effect.props.bin_description)
- effect_factory = self.app.effects.getFactoryFromName(effect.props.bin_description)
+ effect_factory = self.app.effects.getFactoryFromName(
+ effect.props.bin_description)
to_append.append(effect_factory.human_name)
to_append.append(asset.description)
to_append.append(effect)
@@ -540,15 +558,18 @@ class EffectProperties(Gtk.Expander, Loggable):
def _showEffectConfigurationWidget(self, effect):
self._removeEffectConfigurationWidget()
- self._effect_config_ui = self.effects_properties_manager.getEffectConfigurationUI(effect)
+ self._effect_config_ui = self.effects_properties_manager.getEffectConfigurationUI(
+ effect)
if not self._effect_config_ui:
return
- self._vcontent.pack2(self._effect_config_ui, resize=False, shrink=False)
+ self._vcontent.pack2(
+ self._effect_config_ui, resize=False, shrink=False)
self._vcontent.set_position(int(self._config_ui_h_pos))
self._effect_config_ui.show_all()
class TransformationProperties(Gtk.Expander):
+
"""
Widget for viewing and configuring speed
"""
@@ -671,7 +692,8 @@ class TransformationProperties(Gtk.Expander):
if not effect:
effect = GES.Effect.new(bin_description=name)
self._selected_clip.add(effect)
- tracks = self.app.project_manager.current_project.timeline.get_tracks()
+ tracks = self.app.project_manager.current_project.timeline.get_tracks(
+ )
effect = self._findEffect(name)
# disable the effect on default
a = self.effect.get_gnlobject()
@@ -692,7 +714,8 @@ class TransformationProperties(Gtk.Expander):
self.show()
if self.get_expanded():
- self.effect = self._findOrCreateEffect("frei0r-filter-scale0tilt")
+ self.effect = self._findOrCreateEffect(
+ "frei0r-filter-scale0tilt")
self._updateSpinButtons()
else:
if self._selected_clip:
@@ -715,6 +738,7 @@ class TransformationProperties(Gtk.Expander):
def _setTimeline(self, timeline):
self._timeline = timeline
if timeline:
- self._timeline.selection.connect('selection-changed', self._selectionChangedCb)
+ self._timeline.selection.connect(
+ 'selection-changed', self._selectionChangedCb)
timeline = property(_getTimeline, _setTimeline)
diff --git a/pitivi/dialogs/clipmediaprops.py b/pitivi/dialogs/clipmediaprops.py
index 4cfdab5..6079539 100644
--- a/pitivi/dialogs/clipmediaprops.py
+++ b/pitivi/dialogs/clipmediaprops.py
@@ -31,6 +31,7 @@ from pitivi.utils.ui import frame_rates, audio_rates, \
class ClipMediaPropsDialog(object):
+
"""
Displays the properties of an asset, and allows applying them to a project.
@@ -53,7 +54,8 @@ class ClipMediaPropsDialog(object):
self.dialog = builder.get_object("Import Settings")
# Checkbuttons (with their own labels) in the first table column:
self.size_checkbutton = builder.get_object("size_checkbutton")
- self.framerate_checkbutton = builder.get_object("framerate_checkbutton")
+ self.framerate_checkbutton = builder.get_object(
+ "framerate_checkbutton")
self.PAR_checkbutton = builder.get_object("PAR_checkbutton")
self.channels_checkbutton = builder.get_object("channels_checkbutton")
self.samplerate_checkbutton = builder.get_object("samplerate_checkbtn")
@@ -109,7 +111,8 @@ class ClipMediaPropsDialog(object):
# Translators: a label showing an invalid framerate value
self.frame_rate.set_text(_("invalid (%s fps)" % foo))
self.framerate_checkbutton.set_active(False)
- # For consistency, insensitize the checkbox AND value labels
+ # For consistency, insensitize the checkbox AND value
+ # labels
self.framerate_checkbutton.set_sensitive(False)
self.frame_rate.set_sensitive(False)
diff --git a/pitivi/dialogs/depsmanager.py b/pitivi/dialogs/depsmanager.py
index c5e6995..d8d6dbc 100644
--- a/pitivi/dialogs/depsmanager.py
+++ b/pitivi/dialogs/depsmanager.py
@@ -30,6 +30,7 @@ from pitivi.check import missing_soft_deps
class DepsManager(object):
+
"""Display a dialog listing missing soft dependencies.
The sane way to query and install is by using PackageKit's InstallResource()
"""
@@ -37,7 +38,8 @@ class DepsManager(object):
def __init__(self, app, parent_window=None):
self.app = app
self.builder = Gtk.Builder()
- self.builder.add_from_file(os.path.join(get_ui_dir(), "depsmanager.ui"))
+ self.builder.add_from_file(
+ os.path.join(get_ui_dir(), "depsmanager.ui"))
self.builder.connect_signals(self)
self.window = self.builder.get_object("window1")
self.window.set_modal(True)
@@ -92,7 +94,8 @@ class DepsManager(object):
"""
label_contents = ""
for depname, dep in missing_soft_deps.items():
- label_contents += "• %s (%s)\n" % (dep.modulename, dep.additional_message)
+ label_contents += "• %s (%s)\n" % (
+ dep.modulename, dep.additional_message)
self.builder.get_object("pkg_list").set_text(label_contents)
def show(self):
diff --git a/pitivi/dialogs/filelisterrordialog.py b/pitivi/dialogs/filelisterrordialog.py
index fb08d94..ddfe56e 100644
--- a/pitivi/dialogs/filelisterrordialog.py
+++ b/pitivi/dialogs/filelisterrordialog.py
@@ -37,6 +37,7 @@ from pitivi.utils.loggable import Loggable
class FileListErrorDialog(GObject.Object, Loggable):
+
""" Dialog box for showing errors in a list of files """
__gsignals__ = {
@@ -48,7 +49,7 @@ class FileListErrorDialog(GObject.Object, Loggable):
Loggable.__init__(self)
self.builder = Gtk.Builder()
self.builder.add_from_file(os.path.join(get_ui_dir(),
- "filelisterrordialog.ui"))
+ "filelisterrordialog.ui"))
self.builder.connect_signals(self)
self.window = self.builder.get_object("filelisterrordialog")
@@ -95,7 +96,8 @@ class FileListErrorDialog(GObject.Object, Loggable):
if extra:
end = textbuffer.get_end_iter()
- textbuffer.insert_with_tags(end, _("Extra information:") + " ", boldtag)
+ textbuffer.insert_with_tags(
+ end, _("Extra information:") + " ", boldtag)
end = textbuffer.get_end_iter()
textbuffer.insert(end, "%s\n" % extra)
@@ -115,7 +117,7 @@ class FileListErrorDialog(GObject.Object, Loggable):
"""Destroy internal window"""
self.window.destroy()
- ## Callbacks from glade
+ # Callbacks from glade
def _closeCb(self, unused_dialog):
"""Emit the close signal"""
diff --git a/pitivi/dialogs/prefs.py b/pitivi/dialogs/prefs.py
index acc515b..1c69426 100644
--- a/pitivi/dialogs/prefs.py
+++ b/pitivi/dialogs/prefs.py
@@ -36,17 +36,18 @@ from gettext import gettext as _
GlobalSettings.addConfigSection("user-interface")
GlobalSettings.addConfigOption('prefsDialogWidth',
- section="user-interface",
- key="prefs-dialog-width",
- default=600)
+ section="user-interface",
+ key="prefs-dialog-width",
+ default=600)
GlobalSettings.addConfigOption('prefsDialogHeight',
- section="user-interface",
- key="prefs-dialog-height",
- default=400)
+ section="user-interface",
+ key="prefs-dialog-height",
+ default=400)
class PreferencesDialog(object):
+
"""
This dialog displays preferences for pitivi.
"""
@@ -85,11 +86,11 @@ class PreferencesDialog(object):
"""Run the internal dialog"""
self.dialog.run()
-## Public API
+# Public API
@classmethod
def addPreference(cls, attrname, label, description, section=None,
- widget_class=None, **args):
+ widget_class=None, **args):
"""
Add a user preference. The preferences dialog will try
to guess the appropriate widget to use based on the type of the
@@ -108,7 +109,7 @@ class PreferencesDialog(object):
"""
if not section:
section = "General"
- if not section in cls.prefs:
+ if section not in cls.prefs:
cls.prefs[section] = {}
cls.prefs[section][attrname] = (label, description, widget_class, args)
@@ -128,11 +129,11 @@ class PreferencesDialog(object):
@type section: C{str}
"""
cls.addPreference(attrname, label, description, section,
- ptvWidgets.PathWidget)
+ ptvWidgets.PathWidget)
@classmethod
def addNumericPreference(cls, attrname, label, description, section=None,
- upper=None, lower=None):
+ upper=None, lower=None):
"""
Add an auto-generated user preference that will show up as either a
Gtk.SpinButton or an horizontal Gtk.Scale, depending whether both the
@@ -152,7 +153,7 @@ class PreferencesDialog(object):
@type lower: C{number}
"""
cls.addPreference(attrname, label, description, section,
- ptvWidgets.NumericWidget, upper=upper, lower=lower)
+ ptvWidgets.NumericWidget, upper=upper, lower=lower)
@classmethod
def addTextPreference(cls, attrname, label, description, section=None, matches=None):
@@ -171,7 +172,7 @@ class PreferencesDialog(object):
@type section: C{str}
"""
cls.addPreference(attrname, label, description, section,
- ptvWidgets.TextWidget, matches=matches)
+ ptvWidgets.TextWidget, matches=matches)
@classmethod
def addChoicePreference(cls, attrname, label, description, choices, section=None):
@@ -192,7 +193,7 @@ class PreferencesDialog(object):
@type section: C{str}
"""
cls.addPreference(attrname, label, description, section,
- ptvWidgets.ChoiceWidget, choices=choices)
+ ptvWidgets.ChoiceWidget, choices=choices)
@classmethod
def addTogglePreference(cls, attrname, label, description, section=None):
@@ -210,7 +211,7 @@ class PreferencesDialog(object):
@type section: C{str}
"""
cls.addPreference(attrname, label, description, section,
- ptvWidgets.ToggleWidget)
+ ptvWidgets.ToggleWidget)
@classmethod
def addColorPreference(cls, attrname, label, description, section=None, value_type=int):
@@ -230,7 +231,7 @@ class PreferencesDialog(object):
@type section: C{str}
"""
cls.addPreference(attrname, label, description, section,
- ptvWidgets.ColorWidget, value_type=value_type)
+ ptvWidgets.ColorWidget, value_type=value_type)
@classmethod
def addFontPreference(cls, attrname, label, description, section=None):
@@ -248,9 +249,9 @@ class PreferencesDialog(object):
@type section: C{str}
"""
cls.addPreference(attrname, label, description, section,
- ptvWidgets.FontWidget)
+ ptvWidgets.FontWidget)
-## Implementation
+# Implementation
def __fillContents(self):
for section in sorted(self.prefs):
options = self.prefs[section]
@@ -266,7 +267,8 @@ class PreferencesDialog(object):
label, description, widget_class, args = options[attrname]
widget = widget_class(**args)
widget.setWidgetValue(getattr(self.settings, attrname))
- widget.connectValueChanged(self._valueChanged, widget, attrname)
+ widget.connectValueChanged(
+ self._valueChanged, widget, attrname)
self.widgets[attrname] = widget
if isinstance(widget, ptvWidgets.ToggleWidget):
# Don't add a semicolon for checkbuttons
@@ -274,7 +276,8 @@ class PreferencesDialog(object):
else:
label_widget = Gtk.Label(label=_(label) + ":")
icon = Gtk.Image()
- icon.set_from_icon_name("edit-clear-all-symbolic", Gtk.IconSize.MENU)
+ icon.set_from_icon_name(
+ "edit-clear-all-symbolic", Gtk.IconSize.MENU)
revert = Gtk.Button()
revert.add(icon)
revert.set_tooltip_text(_("Reset to default value"))
@@ -295,13 +298,16 @@ class PreferencesDialog(object):
# Avoid the separating the label from the checkbox
widget.set_label(label.get_text())
widgets.attach(widget, 0, 2, y, y + 1, yoptions=0)
- widgets.attach(revert, 2, 3, y, y + 1, xoptions=0, yoptions=0)
+ widgets.attach(
+ revert, 2, 3, y, y + 1, xoptions=0, yoptions=0)
else:
label.set_alignment(1.0, 0.5)
label.set_tooltip_text(description)
- widgets.attach(label, 0, 1, y, y + 1, xoptions=Gtk.AttachOptions.FILL, yoptions=0)
+ widgets.attach(
+ label, 0, 1, y, y + 1, xoptions=Gtk.AttachOptions.FILL, yoptions=0)
widgets.attach(widget, 1, 2, y, y + 1, yoptions=0)
- widgets.attach(revert, 2, 3, y, y + 1, xoptions=0, yoptions=0)
+ widgets.attach(
+ revert, 2, 3, y, y + 1, xoptions=0, yoptions=0)
label.show()
widget.set_tooltip_text(description)
widget.show()
@@ -324,7 +330,7 @@ class PreferencesDialog(object):
def _clearHistory(self):
# Disable missing docstring
- #pylint: disable=C0111
+ # pylint: disable=C0111
self.original_values = {}
self.revert_button.set_sensitive(False)
@@ -359,13 +365,13 @@ class PreferencesDialog(object):
def _acceptButtonCb(self, unused_button):
# Disable missing docstring
- #pylint: disable=C0111
+ # pylint: disable=C0111
self._clearHistory()
self.dialog.hide()
def _valueChanged(self, unused_fake_widget, real_widget, attrname):
# Disable missing docstring
- #pylint: disable=C0111
+ # pylint: disable=C0111
value = getattr(self.settings, attrname)
if attrname not in self.original_values:
self.original_values[attrname] = value
@@ -379,18 +385,19 @@ class PreferencesDialog(object):
setattr(self.settings, attrname, value)
# adjust controls as appropriate
- self.resets[attrname].set_sensitive(not self.settings.isDefault(attrname))
+ self.resets[attrname].set_sensitive(
+ not self.settings.isDefault(attrname))
self.factory_settings.set_sensitive(True)
def _configureCb(self, unused_widget, event):
# Disable missing docstring
- #pylint: disable=C0111
+ # pylint: disable=C0111
self.settings.prefsDialogWidth = event.width
self.settings.prefsDialogHeight = event.height
def _canReset(self):
# Disable missing docstring
- #pylint: disable=C0111
+ # pylint: disable=C0111
for section in self.prefs.values():
for attrname in section:
if not self.settings.isDefault(attrname):
diff --git a/pitivi/dialogs/startupwizard.py b/pitivi/dialogs/startupwizard.py
index ba1d7c6..0a71caf 100644
--- a/pitivi/dialogs/startupwizard.py
+++ b/pitivi/dialogs/startupwizard.py
@@ -34,6 +34,7 @@ from pitivi.utils.misc import show_user_manual
class StartUpWizard(object):
+
"""A Wizard displaying recent projects.
Allows the user to:
@@ -57,7 +58,8 @@ class StartUpWizard(object):
def __init__(self, app):
self.app = app
self.builder = Gtk.Builder()
- self.builder.add_from_file(os.path.join(get_ui_dir(), "startupwizard.ui"))
+ self.builder.add_from_file(
+ os.path.join(get_ui_dir(), "startupwizard.ui"))
self.builder.connect_signals(self)
self.window = self.builder.get_object("window1")
@@ -69,7 +71,8 @@ class StartUpWizard(object):
_filter.set_name(_("Projects"))
for asset in GES.list_assets(GES.Formatter):
- _filter.add_pattern('*.' + asset.get_meta(GES.META_FORMATTER_EXTENSION))
+ _filter.add_pattern(
+ '*.' + asset.get_meta(GES.META_FORMATTER_EXTENSION))
self.recent_chooser.add_filter(_filter)
@@ -89,7 +92,8 @@ class StartUpWizard(object):
if self.app.getLatest():
self._appVersionInfoReceivedCb(self.app, None)
else:
- self.app.connect("version-info-received", self._appVersionInfoReceivedCb)
+ self.app.connect(
+ "version-info-received", self._appVersionInfoReceivedCb)
def _newProjectCb(self, unused_button):
"""Handle a click on the New (Project) button."""
@@ -136,7 +140,7 @@ class StartUpWizard(object):
self.window.hide()
def _projectFailedCb(self, unused_project_manager, unused_uri,
- unused_exception):
+ unused_exception):
"""Handle the failure of a project open operation."""
self.show()
diff --git a/pitivi/effects.py b/pitivi/effects.py
index a93d7d1..d1f9e14 100644
--- a/pitivi/effects.py
+++ b/pitivi/effects.py
@@ -132,8 +132,8 @@ BLACKLISTED_EFFECTS = ["colorconvert", "coglogoinsert", "festival",
"alphacolor", "cogcolorspace", "videodetect",
"navigationtest", "videoanalyse"]
-#FIXME Check if this is still true with GES
-#We should unblacklist it when #650985 is solved
+# FIXME Check if this is still true with GES
+# We should unblacklist it when #650985 is solved
BLACKLISTED_PLUGINS = ["ldaspa"]
ICON_WIDTH = 48 + 2 * 6 # 48 pixels, plus a margin on each side
@@ -154,6 +154,7 @@ class EffectFactory(object):
class EffectsManager(object):
+
"""
Groups effects.
"""
@@ -177,7 +178,7 @@ class EffectsManager(object):
name = element_factory.get_name()
if ("Effect" in klass and name not in BLACKLISTED_EFFECTS
- and not [bplug for bplug in BLACKLISTED_PLUGINS if bplug in name]):
+ and not [bplug for bplug in BLACKLISTED_PLUGINS if bplug in name]):
media_type = None
if "Audio" in klass:
@@ -193,8 +194,10 @@ class EffectsManager(object):
effect = EffectFactory(name,
media_type,
- categories=self._getEffectCategories(name),
- human_name=self._getEffectName(element_factory),
+ categories=self._getEffectCategories(
+ name),
+ human_name=self._getEffectName(
+ element_factory),
description=self._getEffectDescripton(element_factory))
self._addEffectToDic(name, effect)
@@ -300,7 +303,7 @@ class EffectsManager(object):
return icon
-#----------------------- UI classes to manage effects -------------------------#
+# ----------------------- UI classes to manage effects -------------------------#
HIDDEN_EFFECTS = ["frei0r-filter-scale0tilt"]
GlobalSettings.addConfigSection('effect-library')
@@ -315,6 +318,7 @@ GlobalSettings.addConfigSection('effect-library')
class EffectListWidget(Gtk.VBox, Loggable):
+
""" Widget for listing effects """
def __init__(self, instance, unused_uiman):
@@ -337,7 +341,8 @@ class EffectListWidget(Gtk.VBox, Loggable):
self.searchEntry = builder.get_object("search_entry")
# Store
- self.storemodel = Gtk.ListStore(str, str, int, object, object, str, GdkPixbuf.Pixbuf)
+ self.storemodel = Gtk.ListStore(
+ str, str, int, object, object, str, GdkPixbuf.Pixbuf)
self.view = Gtk.TreeView(model=self.storemodel)
self.view.props.headers_visible = False
@@ -366,13 +371,15 @@ class EffectListWidget(Gtk.VBox, Loggable):
text_cell.props.xpad = 6
text_cell.set_property("ellipsize", Pango.EllipsizeMode.END)
text_col.pack_start(text_cell, True)
- text_col.set_cell_data_func(text_cell, self.view_description_cell_data_func, None)
+ text_col.set_cell_data_func(
+ text_cell, self.view_description_cell_data_func, None)
self.view.append_column(icon_col)
self.view.append_column(text_col)
# Make the treeview a drag source which provides effects.
- self.view.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, [EFFECT_TARGET_ENTRY],
Gdk.DragAction.COPY)
+ self.view.enable_model_drag_source(
+ Gdk.ModifierType.BUTTON1_MASK, [EFFECT_TARGET_ENTRY], Gdk.DragAction.COPY)
self.view.connect("button-press-event", self._buttonPressEventCb)
self.view.connect("select-cursor-row", self._enterPressEventCb)
@@ -420,7 +427,8 @@ class EffectListWidget(Gtk.VBox, Loggable):
effect_factory,
name,
self.app.effects.getEffectIcon(name)])
- self.storemodel.set_sort_column_id(COL_NAME_TEXT, Gtk.SortType.ASCENDING)
+ self.storemodel.set_sort_column_id(
+ COL_NAME_TEXT, Gtk.SortType.ASCENDING)
def populate_categories_widget(self):
self.categoriesWidget.get_model().clear()
@@ -454,7 +462,8 @@ class EffectListWidget(Gtk.VBox, Loggable):
def _enterPressEventCb(self, unused_view, unused_event=None):
factory_name = self.getSelectedEffectFactoryName()
if factory_name is not None:
- self.app.gui.clipconfig.effect_expander.addEffectToCurrentSelection(factory_name)
+ self.app.gui.clipconfig.effect_expander.addEffectToCurrentSelection(
+ factory_name)
def _buttonPressEventCb(self, view, event):
chain_up = True
@@ -464,7 +473,8 @@ class EffectListWidget(Gtk.VBox, Loggable):
elif event.type == getattr(Gdk.EventType, '2BUTTON_PRESS'):
factory_name = self.getSelectedEffectFactoryName()
if factory_name is not None:
- self.app.gui.clipconfig.effect_expander.addEffectToCurrentSelection(factory_name)
+ self.app.gui.clipconfig.effect_expander.addEffectToCurrentSelection(
+ factory_name)
else:
chain_up = not self._rowUnderMouseSelected(view, event)
@@ -529,9 +539,11 @@ PROPS_TO_IGNORE = ['name', 'qos', 'silent', 'message']
class EffectsPropertiesManager:
+
"""
@type app: L{Pitivi}
"""
+
def __init__(self, app):
self.cache_dict = {}
self._current_effect_setting_ui = None
@@ -549,11 +561,11 @@ class EffectsPropertiesManager:
# Here we should handle special effects configuration UI
effect_settings_widget = GstElementSettingsWidget()
effect_settings_widget.setElement(effect, ignore=PROPS_TO_IGNORE,
- default_btn=True, use_element_props=True)
+ default_btn=True, use_element_props=True)
scrolled_window = Gtk.ScrolledWindow()
scrolled_window.add_with_viewport(effect_settings_widget)
scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC,
- Gtk.PolicyType.AUTOMATIC)
+ Gtk.PolicyType.AUTOMATIC)
self.cache_dict[effect] = scrolled_window
self._connectAllWidgetCallbacks(effect_settings_widget, effect)
self._postConfiguration(effect, effect_settings_widget)
@@ -561,7 +573,8 @@ class EffectsPropertiesManager:
self._current_effect_setting_ui = self._getUiToSetEffect(effect)
element = self._current_effect_setting_ui.element
for prop in element.list_children_properties():
- self._current_element_values[prop.name] = element.get_child_property(prop.name)
+ self._current_element_values[
+ prop.name] = element.get_child_property(prop.name)
return self.cache_dict[effect]
@@ -580,7 +593,8 @@ class EffectsPropertiesManager:
def _getUiToSetEffect(self, effect):
""" Permit to get the widget to set the effect and not its container """
if type(self.cache_dict[effect]) is Gtk.ScrolledWindow:
- effect_set_ui = self.cache_dict[effect].get_children()[0].get_children()[0]
+ effect_set_ui = self.cache_dict[
+ effect].get_children()[0].get_children()[0]
else:
effect_set_ui = self.cache_dict[effect]
return effect_set_ui
@@ -595,13 +609,14 @@ class EffectsPropertiesManager:
def _onValueChangedCb(self, unused_widget, dynamic, prop):
value = dynamic.getWidgetValue()
- #FIXME Workaround in order to make aspectratiocrop working
+ # FIXME Workaround in order to make aspectratiocrop working
if isinstance(value, Gst.Fraction):
value = Gst.Fraction(int(value.num), int(value.denom))
if value != self._current_element_values.get(prop.name):
self.action_log.begin("Effect property change")
- self._current_effect_setting_ui.element.set_child_property(prop.name, value)
+ self._current_effect_setting_ui.element.set_child_property(
+ prop.name, value)
self.action_log.commit()
self.app.project_manager.current_project.pipeline.flushSeek()
diff --git a/pitivi/mainwindow.py b/pitivi/mainwindow.py
index 1b8f8ff..c8396f7 100644
--- a/pitivi/mainwindow.py
+++ b/pitivi/mainwindow.py
@@ -54,79 +54,82 @@ from pitivi.viewer import ViewerContainer
GlobalSettings.addConfigSection("main-window")
GlobalSettings.addConfigOption('mainWindowHPanePosition',
- section="main-window",
- key="hpane-position",
- type_=int)
+ section="main-window",
+ key="hpane-position",
+ type_=int)
GlobalSettings.addConfigOption('mainWindowMainHPanePosition',
- section="main-window",
- key="main-hpane-position",
- type_=int)
+ section="main-window",
+ key="main-hpane-position",
+ type_=int)
GlobalSettings.addConfigOption('mainWindowVPanePosition',
- section="main-window",
- key="vpane-position",
- type_=int)
+ section="main-window",
+ key="vpane-position",
+ type_=int)
GlobalSettings.addConfigOption('mainWindowX',
- section="main-window",
- key="X", default=0, type_=int)
+ section="main-window",
+ key="X", default=0, type_=int)
GlobalSettings.addConfigOption('mainWindowY',
- section="main-window",
- key="Y", default=0, type_=int)
+ section="main-window",
+ key="Y", default=0, type_=int)
GlobalSettings.addConfigOption('mainWindowWidth',
- section="main-window",
- key="width", default=-1, type_=int)
+ section="main-window",
+ key="width", default=-1, type_=int)
GlobalSettings.addConfigOption('mainWindowHeight',
- section="main-window",
- key="height", default=-1, type_=int)
+ section="main-window",
+ key="height", default=-1, type_=int)
GlobalSettings.addConfigOption('lastProjectFolder',
- section="main-window",
- key="last-folder",
- environment="PITIVI_PROJECT_FOLDER",
- default=os.path.expanduser("~"))
+ section="main-window",
+ key="last-folder",
+ environment="PITIVI_PROJECT_FOLDER",
+ default=os.path.expanduser("~"))
GlobalSettings.addConfigSection('export')
GlobalSettings.addConfigOption('lastExportFolder',
- section='export',
- key="last-export-folder",
- environment="PITIVI_EXPORT_FOLDER",
- default=os.path.expanduser("~"))
+ section='export',
+ key="last-export-folder",
+ environment="PITIVI_EXPORT_FOLDER",
+ default=os.path.expanduser("~"))
GlobalSettings.addConfigOption('elementSettingsDialogWidth',
- section='export',
- key='element-settings-dialog-width',
- default=620)
+ section='export',
+ key='element-settings-dialog-width',
+ default=620)
GlobalSettings.addConfigOption('elementSettingsDialogHeight',
- section='export',
- key='element-settings-dialog-height',
- default=460)
+ section='export',
+ key='element-settings-dialog-height',
+ default=460)
GlobalSettings.addConfigSection("effect-configuration")
GlobalSettings.addConfigOption('effectVPanedPosition',
- section='effect-configuration',
- key='effect-vpaned-position',
- type_=int)
+ section='effect-configuration',
+ key='effect-vpaned-position',
+ type_=int)
GlobalSettings.addConfigSection("version")
GlobalSettings.addConfigOption('displayCounter',
- section='version',
- key='info-displayed-counter',
- default=0)
+ section='version',
+ key='info-displayed-counter',
+ default=0)
GlobalSettings.addConfigOption('lastCurrentVersion',
- section='version',
- key='last-current-version',
- default='')
+ section='version',
+ key='last-current-version',
+ default='')
GlobalSettings.addConfigOption('timelineAutoRipple',
- section='user-interface',
- key='timeline-autoripple',
- default=False)
+ section='user-interface',
+ key='timeline-autoripple',
+ default=False)
class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
+
"""
Pitivi's main window.
@cvar app: The application object
@type app: L{Pitivi}
"""
+
def __init__(self, app):
gtksettings = Gtk.Settings.get_default()
gtksettings.set_property("gtk-application-prefer-dark-theme", True)
- # Pulseaudio "role" (http://0pointer.de/blog/projects/tagging-audio.htm)
+ # Pulseaudio "role"
+ # (http://0pointer.de/blog/projects/tagging-audio.htm)
os.environ["PULSE_PROP_media.role"] = "production"
os.environ["PULSE_PROP_application.icon_name"] = "pitivi"
@@ -150,13 +153,18 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
self._missingUriOnLoading = False
pm = self.app.project_manager
- pm.connect("new-project-loading", self._projectManagerNewProjectLoadingCb)
- pm.connect("new-project-loaded", self._projectManagerNewProjectLoadedCb)
- pm.connect("new-project-failed", self._projectManagerNewProjectFailedCb)
- pm.connect("save-project-failed", self._projectManagerSaveProjectFailedCb)
+ pm.connect("new-project-loading",
+ self._projectManagerNewProjectLoadingCb)
+ pm.connect("new-project-loaded",
+ self._projectManagerNewProjectLoadedCb)
+ pm.connect("new-project-failed",
+ self._projectManagerNewProjectFailedCb)
+ pm.connect("save-project-failed",
+ self._projectManagerSaveProjectFailedCb)
pm.connect("project-saved", self._projectManagerProjectSavedCb)
pm.connect("closing-project", self._projectManagerClosingProjectCb)
- pm.connect("reverting-to-saved", self._projectManagerRevertingToSavedCb)
+ pm.connect("reverting-to-saved",
+ self._projectManagerRevertingToSavedCb)
pm.connect("project-closed", self._projectManagerProjectClosedCb)
pm.connect("missing-uri", self._projectManagerMissingUriCb)
@@ -249,7 +257,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
# Main "toolbar" (using client-side window decorations with HeaderBar)
self._headerbar = Gtk.HeaderBar()
self._create_headerbar_buttons()
- self.builder.add_from_file(os.path.join(get_ui_dir(), "mainmenubutton.ui"))
+ self.builder.add_from_file(
+ os.path.join(get_ui_dir(), "mainmenubutton.ui"))
# FIXME : see https://bugzilla.gnome.org/show_bug.cgi?id=729263
self.builder.connect_signals_full(self._builderConnectCb, self)
@@ -283,8 +292,10 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
self.main_tabs = BaseTabs(self.app)
self.medialibrary = MediaLibraryWidget(self.app, self.uimanager)
self.effectlist = EffectListWidget(self.app, self.uimanager)
- self.main_tabs.append_page(self.medialibrary, Gtk.Label(label=_("Media Library")))
- self.main_tabs.append_page(self.effectlist, Gtk.Label(label=_("Effect Library")))
+ self.main_tabs.append_page(
+ self.medialibrary, Gtk.Label(label=_("Media Library")))
+ self.main_tabs.append_page(
+ self.effectlist, Gtk.Label(label=_("Effect Library")))
self.medialibrary.connect('play', self._mediaLibraryPlayCb)
self.medialibrary.show()
self.effectlist.show()
@@ -294,10 +305,14 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
self.clipconfig = ClipProperties(self.app)
self.trans_list = TransitionsListWidget(self.app)
self.title_editor = TitleEditor(self.app)
- self.context_tabs.append_page(self.clipconfig, Gtk.Label(label=_("Clip")))
- self.context_tabs.append_page(self.trans_list, Gtk.Label(label=_("Transition")))
- self.context_tabs.append_page(self.title_editor.widget, Gtk.Label(label=_("Title")))
- self.context_tabs.connect("switch-page", self.title_editor.tabSwitchedCb)
+ self.context_tabs.append_page(
+ self.clipconfig, Gtk.Label(label=_("Clip")))
+ self.context_tabs.append_page(
+ self.trans_list, Gtk.Label(label=_("Transition")))
+ self.context_tabs.append_page(
+ self.title_editor.widget, Gtk.Label(label=_("Title")))
+ self.context_tabs.connect(
+ "switch-page", self.title_editor.tabSwitchedCb)
# Show by default the Title tab, as the Clip and Transition tabs
# are useful only when a clip or transition is selected, but
# the Title tab allows adding titles.
@@ -317,7 +332,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
self.timeline_ui.setProjectManager(self.app.project_manager)
self.vpaned.pack2(self.timeline_ui, resize=True, shrink=False)
- self.timeline_ui.timeline.selection.connect("selection-changed",
self.title_editor.selectionChangedCb)
+ self.timeline_ui.timeline.selection.connect(
+ "selection-changed", self.title_editor.selectionChangedCb)
# Enable our shortcuts for HeaderBar buttons and menu items:
self._set_keyboard_shortcuts()
@@ -398,28 +414,33 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
self.timeline_ui.grab_focus()
def _create_headerbar_buttons(self):
- self.undo_button = Gtk.Button.new_from_icon_name("edit-undo-symbolic", Gtk.IconSize.LARGE_TOOLBAR)
+ self.undo_button = Gtk.Button.new_from_icon_name(
+ "edit-undo-symbolic", Gtk.IconSize.LARGE_TOOLBAR)
self.undo_button.set_always_show_image(True)
self.undo_button.set_label(_("Undo"))
self.undo_button.set_action_name("app.undo")
- self.redo_button = Gtk.Button.new_from_icon_name("edit-redo-symbolic", Gtk.IconSize.LARGE_TOOLBAR)
+ self.redo_button = Gtk.Button.new_from_icon_name(
+ "edit-redo-symbolic", Gtk.IconSize.LARGE_TOOLBAR)
self.redo_button.set_always_show_image(True)
self.redo_button.set_label(_("Redo"))
self.redo_button.set_action_name("app.redo")
separator = Gtk.Separator()
- self.save_button = Gtk.Button.new_from_icon_name("document-save", Gtk.IconSize.LARGE_TOOLBAR)
+ self.save_button = Gtk.Button.new_from_icon_name(
+ "document-save", Gtk.IconSize.LARGE_TOOLBAR)
self.save_button.set_always_show_image(True)
self.save_button.set_label(_("Save"))
- render_icon = Gtk.Image.new_from_file(os.path.join(get_pixmap_dir(), "pitivi-render-24.png"))
+ render_icon = Gtk.Image.new_from_file(
+ os.path.join(get_pixmap_dir(), "pitivi-render-24.png"))
self.render_button = Gtk.Button()
self.render_button.set_image(render_icon)
self.render_button.set_always_show_image(True)
self.render_button.set_label(_("Render"))
- self.render_button.set_tooltip_text(_("Export your project as a finished movie"))
+ self.render_button.set_tooltip_text(
+ _("Export your project as a finished movie"))
self.render_button.set_sensitive(False) # The only one we have to set.
self.render_button.connect("clicked", self._renderCb)
@@ -471,7 +492,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
self.app.add_accelerator("F10", "win.menu_button", None)
def showProjectStatus(self):
- dirty = self.app.project_manager.current_project.hasUnsavedModifications()
+ dirty = self.app.project_manager.current_project.hasUnsavedModifications(
+ )
self.save_action.set_enabled(dirty)
if self.app.project_manager.current_project.uri:
self._menubutton_items["menu_revert_to_saved"].set_sensitive(dirty)
@@ -498,8 +520,10 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
return False
def _saveWindowSettings(self):
- self.settings.mainWindowHPanePosition = self.secondhpaned.get_position()
- self.settings.mainWindowMainHPanePosition = self.mainhpaned.get_position()
+ self.settings.mainWindowHPanePosition = self.secondhpaned.get_position(
+ )
+ self.settings.mainWindowMainHPanePosition = self.mainhpaned.get_position(
+ )
self.settings.mainWindowVPanePosition = self.vpaned.get_position()
def _mediaLibraryPlayCb(self, unused_medialibrary, asset):
@@ -526,7 +550,7 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
self.timeline_ui.purgeObject(asset.get_id())
def _builderConnectCb(self, builder, gobject, signal_name, handler_name,
- connect_object, flags, user_data):
+ connect_object, flags, user_data):
id_ = gobject.connect(signal_name, getattr(self, handler_name))
self.builder_handler_ids.append((gobject, id_))
@@ -559,7 +583,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
uri = self._showExportDialog(self.app.project_manager.current_project)
result = None
if uri:
- result = self.app.project_manager.exportProject(self.app.project_manager.current_project, uri)
+ result = self.app.project_manager.exportProject(
+ self.app.project_manager.current_project, uri)
if not result:
self.log("Project couldn't be exported")
@@ -570,7 +595,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
def showProjectSettingsDialog(self):
from pitivi.project import ProjectSettingsDialog
- ProjectSettingsDialog(self, self.app.project_manager.current_project).window.run()
+ ProjectSettingsDialog(
+ self, self.app.project_manager.current_project).window.run()
self.updateTitle()
def _menuCb(self, unused_action, unused_param):
@@ -612,16 +638,18 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
"Alessandro Decina <alessandro decina collabora co uk>",
"Brandon Lewis <brandon_lewis berkeley edu>",
"",
- # Translators: this paragraph is to be translated, the list of contributors is shown
dynamically as a clickable link below it
+ # Translators: this paragraph is to be translated, the list
+ # of contributors is shown dynamically as a clickable link
+ # below it
_("Contributors:\n" +
- "A handwritten list here would...\n" +
- "• be too long,\n" +
- "• be frequently outdated,\n" +
- "• not show their relative merit.\n\n" +
- "Out of respect for our contributors, we point you instead to:\n"),
+ "A handwritten list here would...\n" +
+ "• be too long,\n" +
+ "• be frequently outdated,\n" +
+ "• not show their relative merit.\n\n" +
+ "Out of respect for our contributors, we point you instead to:\n"),
# Translators: keep the %s at the end of the 1st line
_("The list of contributors on Ohloh %s\n" +
- "Or you can run: git shortlog -s -n")
+ "Or you can run: git shortlog -s -n")
% "http://ohloh.net/p/pitivi/contributors", ]
abt.set_authors(authors)
translators = _("translator-credits")
@@ -644,20 +672,23 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
return # The user has not made a decision, don't do anything
chooser = Gtk.FileChooserDialog(title=_("Open File..."),
- transient_for=self,
- action=Gtk.FileChooserAction.OPEN)
+ transient_for=self,
+ action=Gtk.FileChooserAction.OPEN)
chooser.add_buttons(_("Cancel"), Gtk.ResponseType.CANCEL,
_("Open"), Gtk.ResponseType.OK)
chooser.set_default_response(Gtk.ResponseType.OK)
chooser.set_select_multiple(False)
- # TODO: Remove this set_current_folder call when GTK bug 683999 is fixed
+ # TODO: Remove this set_current_folder call when GTK bug 683999 is
+ # fixed
chooser.set_current_folder(self.settings.lastProjectFolder)
formatter_assets = GES.list_assets(GES.Formatter)
- formatter_assets.sort(key=lambda x: - x.get_meta(GES.META_FORMATTER_RANK))
+ formatter_assets.sort(
+ key=lambda x: - x.get_meta(GES.META_FORMATTER_RANK))
for format_ in formatter_assets:
filt = Gtk.FileFilter()
filt.set_name(format_.get_meta(GES.META_DESCRIPTION))
- filt.add_pattern("*%s" % format_.get_meta(GES.META_FORMATTER_EXTENSION))
+ filt.add_pattern("*%s" %
+ format_.get_meta(GES.META_FORMATTER_EXTENSION))
chooser.add_filter(filt)
default = Gtk.FileFilter()
default.set_name(_("All supported formats"))
@@ -668,7 +699,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
if response == Gtk.ResponseType.OK:
self.app.project_manager.loadProject(chooser.get_uri())
else:
- self.info("User cancelled loading a new project, but no other project is currently active.
Resetting")
+ self.info(
+ "User cancelled loading a new project, but no other project is currently active. Resetting")
self.app.project_manager.newBlankProject()
chooser.destroy()
return True
@@ -695,7 +727,7 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
self.log("A new project is loaded")
self._connectToProject(project)
project.timeline.connect("notify::duration",
- self._timelineDurationChangedCb)
+ self._timelineDurationChangedCb)
project.pipeline.activatePositionListener()
self._setProject(project)
@@ -724,10 +756,10 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
def _projectManagerSaveProjectFailedCb(self, unused_project_manager, uri, exception=None):
project_filename = unquote(uri.split("/")[-1])
dialog = Gtk.MessageDialog(transient_for=self,
- modal=True,
- message_type=Gtk.MessageType.ERROR,
- buttons=Gtk.ButtonsType.OK,
- text=_('Unable to save project "%s"') % project_filename)
+ modal=True,
+ message_type=Gtk.MessageType.ERROR,
+ buttons=Gtk.ButtonsType.OK,
+ text=_('Unable to save project "%s"') % project_filename)
if exception:
dialog.set_property("secondary-use-markup", True)
dialog.set_property("secondary-text", unquote(str(exception)))
@@ -767,7 +799,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
_("Cancel"), Gtk.ResponseType.CANCEL,
save, Gtk.ResponseType.YES)
# Even though we set the title to an empty string when creating dialog,
- # seems we really have to do it once more so it doesn't show "pitivi"...
+ # seems we really have to do it once more so it doesn't show
+ # "pitivi"...
dialog.set_resizable(False)
dialog.set_default_response(Gtk.ResponseType.CANCEL)
dialog.get_accessible().set_name("unsaved changes dialog")
@@ -787,14 +820,15 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
if project.uri:
path = unquote(project.uri).split("file://")[1]
- last_saved = max(os.path.getmtime(path), project_manager.time_loaded)
+ last_saved = max(
+ os.path.getmtime(path), project_manager.time_loaded)
time_delta = time() - last_saved
secondary.props.label = _("If you don't save, "
- "the changes from the last %s will be lost."
- % beautify_time_delta(time_delta))
+ "the changes from the last %s will be lost."
+ % beautify_time_delta(time_delta))
else:
secondary.props.label = _("If you don't save, "
- "your changes will be lost.")
+ "your changes will be lost.")
# put the text in a vbox
vbox = Gtk.VBox(homogeneous=False, spacing=SPACING * 2)
@@ -802,7 +836,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
vbox.pack_start(secondary, True, True, 0)
# make the [[image] text] hbox
- image = Gtk.Image.new_from_icon_name("dialog-question", Gtk.IconSize.DIALOG)
+ image = Gtk.Image.new_from_icon_name(
+ "dialog-question", Gtk.IconSize.DIALOG)
hbox = Gtk.HBox(homogeneous=False, spacing=SPACING * 2)
hbox.pack_start(image, False, True, 0)
hbox.pack_start(vbox, True, True, 0)
@@ -843,7 +878,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
self.info("Project closed - clearing the media library and timeline")
self.medialibrary.storemodel.clear()
self._disconnectFromProject(self.app.project_manager.current_project)
- self.app.project_manager.current_project.timeline.disconnect_by_func(self._timelineDurationChangedCb)
+ self.app.project_manager.current_project.timeline.disconnect_by_func(
+ self._timelineDurationChangedCb)
self.timeline_ui.setProject(None)
self.clipconfig.timeline = None
self.render_button.set_sensitive(False)
@@ -852,15 +888,15 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
def _projectManagerRevertingToSavedCb(self, unused_project_manager, unused_project):
if self.app.project_manager.current_project.hasUnsavedModifications():
dialog = Gtk.MessageDialog(transient_for=self,
- modal=True,
- message_type=Gtk.MessageType.WARNING,
- buttons=Gtk.ButtonsType.NONE,
- text=_("Revert to saved project version?"))
+ modal=True,
+ message_type=Gtk.MessageType.WARNING,
+ buttons=Gtk.ButtonsType.NONE,
+ text=_("Revert to saved project version?"))
dialog.add_buttons(Gtk.STOCK_CANCEL, Gtk.ResponseType.NO,
- Gtk.STOCK_REVERT_TO_SAVED, Gtk.ResponseType.YES)
+ Gtk.STOCK_REVERT_TO_SAVED, Gtk.ResponseType.YES)
dialog.set_resizable(False)
dialog.set_property("secondary-text",
- _("This will reload the current project. All unsaved changes will be lost."))
+ _("This will reload the current project. All unsaved changes will be lost."))
dialog.set_default_response(Gtk.ResponseType.NO)
dialog.set_transient_for(self)
response = dialog.run()
@@ -882,7 +918,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
dialog.run()
dialog.destroy()
- def _projectManagerMissingUriCb(self, unused_project_manager, unused_project,
+ def _projectManagerMissingUriCb(
+ self, unused_project_manager, unused_project,
unused_error, asset):
self._missingUriOnLoading = True
uri = asset.get_id()
@@ -945,7 +982,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
# add it inside the filter string.
unused_filename, extension = os.path.splitext(uri)
filter_ = Gtk.FileFilter()
- # Translators: this is a format filter in a filechooser. Ex: "AVI files"
+ # Translators: this is a format filter in a filechooser. Ex: "AVI
+ # files"
filter_.set_name(_("%s files" % extension))
filter_.add_pattern("*%s" % extension.lower())
filter_.add_pattern("*%s" % extension.upper())
@@ -965,7 +1003,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
if response == Gtk.ResponseType.OK:
self.log("User chose a new URI for the missing file")
new_uri = chooser.get_uri()
- self.app.project_manager.current_project.setModificationState(False)
+ self.app.project_manager.current_project.setModificationState(
+ False)
else:
# Even if the user clicks Cancel, the discoverer keeps trying to
# import the rest of the clips...
@@ -975,20 +1014,24 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
# TODO: bugs #661059, 609136
attempted_uri = self.app.project_manager.current_project.uri
reason = _('No replacement file was provided for "<i>%s</i>".\n\n'
- 'Pitivi does not currently support partial projects.'
- % info_name(asset))
+ 'Pitivi does not currently support partial projects.'
+ % info_name(asset))
# Put an end to the async signals spamming us with dialogs:
- self.app.project_manager.disconnect_by_func(self._projectManagerMissingUriCb)
+ self.app.project_manager.disconnect_by_func(
+ self._projectManagerMissingUriCb)
# Don't overlap the file chooser with our error dialog
- # The chooser will be destroyed further below, so let's hide it now.
+ # The chooser will be destroyed further below, so let's hide it
+ # now.
dialog.hide()
# Reset projectManager and disconnect all the signals:
- self.app.project_manager.newBlankProject(ignore_unsaved_changes=True)
+ self.app.project_manager.newBlankProject(
+ ignore_unsaved_changes=True)
# Force the project load to fail:
# This will show an error using _projectManagerNewProjectFailedCb
# You have to do this *after* successfully creating a blank project,
# or the startupwizard will still be connected to that signal too.
- self.app.project_manager.emit("new-project-failed", attempted_uri, reason)
+ self.app.project_manager.emit(
+ "new-project-failed", attempted_uri, reason)
dialog.destroy()
return new_uri
@@ -998,11 +1041,13 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
# medialibrary.connect("missing-plugins", self._sourceListMissingPluginsCb)
project.connect("asset-removed", self._mediaLibrarySourceRemovedCb)
project.connect("project-changed", self._projectChangedCb)
- project.connect("rendering-settings-changed", self._renderingSettingsChangedCb)
+ project.connect(
+ "rendering-settings-changed", self._renderingSettingsChangedCb)
# Missing Plugins Support
- def _sourceListMissingPluginsCb(self, unused_project, unused_uri, unused_factory,
+ def _sourceListMissingPluginsCb(
+ self, unused_project, unused_uri, unused_factory,
details, unused_descriptions, missingPluginsCallback):
res = self._installPlugins(details, missingPluginsCallback)
return res
@@ -1012,7 +1057,7 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
context.set_xid(self.window.xid)
res = GstPbutils.install_plugins_async(details, context,
- missingPluginsCallback)
+ missingPluginsCallback)
return res
# Pitivi current project callbacks
@@ -1032,7 +1077,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
# When loading the first project, the signal has never been
# connected before.
pass
- project.connect("rendering-settings-changed", self._renderingSettingsChangedCb)
+ project.connect(
+ "rendering-settings-changed", self._renderingSettingsChangedCb)
self.viewer.setPipeline(project.pipeline)
self.app.timeline_log_observer.setPipeline(project.pipeline)
@@ -1088,9 +1134,11 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
asset_extension = asset.get_meta(GES.META_FORMATTER_EXTENSION)
if not project.name:
- chooser.set_current_name(_("Untitled") + "." + asset_extension + "_tar")
+ chooser.set_current_name(
+ _("Untitled") + "." + asset_extension + "_tar")
else:
- chooser.set_current_name(project.name + "." + asset_extension + "_tar")
+ chooser.set_current_name(
+ project.name + "." + asset_extension + "_tar")
filt = Gtk.FileFilter()
filt.set_name(_("Tar archive"))
@@ -1120,8 +1168,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
self.log("Save URI requested")
chooser = Gtk.FileChooserDialog(title=_("Save As..."),
- transient_for=self,
- action=Gtk.FileChooserAction.SAVE)
+ transient_for=self,
+ action=Gtk.FileChooserAction.SAVE)
chooser.add_buttons(_("Cancel"), Gtk.ResponseType.CANCEL,
_("Save"), Gtk.ResponseType.OK)
chooser.set_default_response(Gtk.ResponseType.OK)
@@ -1133,7 +1181,7 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
chooser.set_select_multiple(False)
chooser.set_current_name(_("Untitled") + "." +
- asset.get_meta(GES.META_FORMATTER_EXTENSION))
+ asset.get_meta(GES.META_FORMATTER_EXTENSION))
chooser.set_current_folder(self.settings.lastProjectFolder)
chooser.props.do_overwrite_confirmation = True
@@ -1166,7 +1214,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
foo = self._showSaveScreenshotDialog()
if foo:
path, mime = foo[0], foo[1]
- self.app.project_manager.current_project.pipeline.save_thumbnail(-1, -1, mime, path)
+ self.app.project_manager.current_project.pipeline.save_thumbnail(
+ -1, -1, mime, path)
def _showSaveScreenshotDialog(self):
"""
@@ -1196,7 +1245,8 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
chosen_format = formats.get(chooser.get_filter().get_name())
chosen_ext = chosen_format[1][0]
chosen_mime = chosen_format[0]
- uri = os.path.join(chooser.get_current_folder(), chooser.get_filename())
+ uri = os.path.join(
+ chooser.get_current_folder(), chooser.get_filename())
ret = [uri + "." + chosen_ext, chosen_mime]
else:
ret = None
@@ -1221,6 +1271,7 @@ class PitiviMainWindow(Gtk.ApplicationWindow, Loggable):
class PreviewAssetWindow(Gtk.Window):
+
"""
Window for previewing a video or audio asset.
@@ -1258,7 +1309,8 @@ class PreviewAssetWindow(Gtk.Window):
self.show()
self._previewer.play()
- # Hack so that we really really force the "utility" window to be focused
+ # Hack so that we really really force the "utility" window to be
+ # focused
self.present()
def _calculatePreviewWindowSize(self):
diff --git a/pitivi/mediafilespreviewer.py b/pitivi/mediafilespreviewer.py
index bdabff3..86fb741 100644
--- a/pitivi/mediafilespreviewer.py
+++ b/pitivi/mediafilespreviewer.py
@@ -43,17 +43,17 @@ PREVIEW_HEIGHT = 100
GlobalSettings.addConfigSection('filechooser-preview')
GlobalSettings.addConfigOption('FCEnablePreview',
- section='filechooser-preview',
- key='do-preview-on-clip-import',
- default=True)
+ section='filechooser-preview',
+ key='do-preview-on-clip-import',
+ default=True)
GlobalSettings.addConfigOption('FCpreviewWidth',
- section='filechooser-preview',
- key='video-preview-width',
- default=PREVIEW_WIDTH)
+ section='filechooser-preview',
+ key='video-preview-width',
+ default=PREVIEW_WIDTH)
GlobalSettings.addConfigOption('FCpreviewHeight',
- section='filechooser-preview',
- key='video-preview-height',
- default=PREVIEW_HEIGHT)
+ section='filechooser-preview',
+ key='video-preview-height',
+ default=PREVIEW_HEIGHT)
acceptable_tags = [
Gst.TAG_ALBUM_ARTIST,
@@ -69,6 +69,7 @@ acceptable_tags = [
class PreviewWidget(Gtk.Grid, Loggable):
+
"""
Widget for displaying a GStreamer sink with playback controls.
@@ -116,7 +117,8 @@ class PreviewWidget(Gtk.Grid, Loggable):
# An image for images and audio
self.preview_image = Gtk.Image()
- self.preview_image.set_size_request(self.settings.FCpreviewWidth, self.settings.FCpreviewHeight)
+ self.preview_image.set_size_request(
+ self.settings.FCpreviewWidth, self.settings.FCpreviewHeight)
self.preview_image.show()
self.attach(self.preview_image, 0, 1, 1, 1)
@@ -223,13 +225,16 @@ class PreviewWidget(Gtk.Grid, Loggable):
if video.is_image():
self.current_preview_type = 'image'
self.preview_video.hide()
- pixbuf = GdkPixbuf.Pixbuf.new_from_file(Gst.uri_get_location(uri))
+ pixbuf = GdkPixbuf.Pixbuf.new_from_file(
+ Gst.uri_get_location(uri))
pixbuf_w = pixbuf.get_width()
pixbuf_h = pixbuf.get_height()
w, h = self.__get_best_size(pixbuf_w, pixbuf_h)
- pixbuf = pixbuf.scale_simple(w, h, GdkPixbuf.InterpType.NEAREST)
+ pixbuf = pixbuf.scale_simple(
+ w, h, GdkPixbuf.InterpType.NEAREST)
self.preview_image.set_from_pixbuf(pixbuf)
- self.preview_image.set_size_request(self.settings.FCpreviewWidth,
self.settings.FCpreviewHeight)
+ self.preview_image.set_size_request(
+ self.settings.FCpreviewWidth, self.settings.FCpreviewHeight)
self.preview_image.show()
self.bbox.show()
self.play_button.hide()
@@ -242,11 +247,13 @@ class PreviewWidget(Gtk.Grid, Loggable):
self.player.setClipUri(self.current_selected_uri)
self.player.setState(Gst.State.PAUSED)
self.pos_adj.props.upper = duration
- video_width = (video.get_par_num() / video.get_par_denom()) * video.get_width()
+ video_width = (
+ video.get_par_num() / video.get_par_denom()) * video.get_width()
video_height = video.get_height()
w, h = self.__get_best_size(video_width, video_height)
self.preview_video.set_size_request(w, h)
- self.preview_video.setDisplayAspectRatio(float(video_width) / video_height)
+ self.preview_video.setDisplayAspectRatio(
+ float(video_width) / video_height)
self.preview_video.show()
self.bbox.show()
self.play_button.show()
@@ -254,7 +261,8 @@ class PreviewWidget(Gtk.Grid, Loggable):
self.b_zoom_in.show()
self.b_zoom_out.show()
self.description = "\n".join([
- _("<b>Resolution</b>: %d×%d") % (video_width, video_height),
+ _("<b>Resolution</b>: %d×%d") % (
+ video_width, video_height),
_("<b>Duration</b>: %s") % pretty_duration])
else:
self.current_preview_type = 'audio'
@@ -266,7 +274,8 @@ class PreviewWidget(Gtk.Grid, Loggable):
audio = audio[0]
self.pos_adj.props.upper = duration
- self.preview_image.set_from_icon_name("audio-x-generic", Gtk.IconSize.DIALOG)
+ self.preview_image.set_from_icon_name(
+ "audio-x-generic", Gtk.IconSize.DIALOG)
self.preview_image.show()
self.preview_image.set_size_request(PREVIEW_WIDTH, PREVIEW_HEIGHT)
self.description = "\n".join([
@@ -393,8 +402,10 @@ class PreviewWidget(Gtk.Grid, Loggable):
h *= 0.8
if (w, h) < self.original_dims:
(w, h) = self.original_dims
- pixbuf = GdkPixbuf.Pixbuf.new_from_file(Gst.uri_get_location(self.current_selected_uri))
- pixbuf = pixbuf.scale_simple(int(w), int(h), GdkPixbuf.InterpType.BILINEAR)
+ pixbuf = GdkPixbuf.Pixbuf.new_from_file(
+ Gst.uri_get_location(self.current_selected_uri))
+ pixbuf = pixbuf.scale_simple(
+ int(w), int(h), GdkPixbuf.InterpType.BILINEAR)
w = max(w, self.settings.FCpreviewWidth)
h = max(h, self.settings.FCpreviewHeight)
@@ -428,17 +439,18 @@ class PreviewWidget(Gtk.Grid, Loggable):
keys.sort()
text = self.description + "\n\n"
for key in keys:
- text = text + "<b>" + key.capitalize() + "</b>: " + self.tags[key] + "\n"
+ text = text + "<b>" + \
+ key.capitalize() + "</b>: " + self.tags[key] + "\n"
self.l_tags.set_markup(text)
def _on_b_details_clicked_cb(self, unused_button):
mess = self.preview_cache_errors.get(self.current_selected_uri, None)
if mess is not None:
dialog = Gtk.MessageDialog(transient_for=None,
- modal=True,
- message_type=Gtk.MessageType.WARNING,
- buttons=Gtk.ButtonsType.OK,
- text=str(mess))
+ modal=True,
+ message_type=Gtk.MessageType.WARNING,
+ buttons=Gtk.ButtonsType.OK,
+ text=str(mess))
dialog.set_icon_name("pitivi")
dialog.set_title(_("Error while analyzing a file"))
dialog.run()
diff --git a/pitivi/medialibrary.py b/pitivi/medialibrary.py
index 09cf00c..cc5843e 100644
--- a/pitivi/medialibrary.py
+++ b/pitivi/medialibrary.py
@@ -60,19 +60,19 @@ SHOW_ICONVIEW = 2
GlobalSettings.addConfigSection('clip-library')
GlobalSettings.addConfigOption('lastImportFolder',
- section='clip-library',
- key='last-folder',
- environment='PITIVI_IMPORT_FOLDER',
- default=os.path.expanduser("~"))
+ section='clip-library',
+ key='last-folder',
+ environment='PITIVI_IMPORT_FOLDER',
+ default=os.path.expanduser("~"))
GlobalSettings.addConfigOption('closeImportDialog',
- section='clip-library',
- key='close-import-dialog-after-import',
- default=True)
+ section='clip-library',
+ key='close-import-dialog-after-import',
+ default=True)
GlobalSettings.addConfigOption('lastClipView',
- section='clip-library',
- key='last-clip-view',
- type_=int,
- default=SHOW_ICONVIEW)
+ section='clip-library',
+ key='last-clip-view',
+ type_=int,
+ default=SHOW_ICONVIEW)
STORE_MODEL_STRUCTURE = (
GdkPixbuf.Pixbuf, GdkPixbuf.Pixbuf,
@@ -98,7 +98,8 @@ ui = '''
# http://en.wikipedia.org/wiki/Comparison_of_container_formats and
# http://en.wikipedia.org/wiki/List_of_file_formats#Video
# ...and looking at the contents of /usr/share/mime
-SUPPORTED_FILE_FORMATS = {"video": ("3gpp", "3gpp2", "dv", "mp2t", "mp4", "mpeg", "ogg", "quicktime",
"webm", "x-flv", "x-matroska", "x-mng", "x-ms-asf", "x-msvideo", "x-ms-wmp", "x-ms-wmv", "x-ogm+ogg",
"x-theora+ogg"),
+SUPPORTED_FILE_FORMATS = {
+ "video": ("3gpp", "3gpp2", "dv", "mp2t", "mp4", "mpeg", "ogg", "quicktime", "webm", "x-flv",
"x-matroska", "x-mng", "x-ms-asf", "x-msvideo", "x-ms-wmp", "x-ms-wmv", "x-ogm+ogg", "x-theora+ogg"),
"application": ("mxf",),
# Don't forget audio formats
"audio": ("aac", "ac3", "basic", "flac", "mp2", "mp4", "mpeg", "ogg", "opus", "webm", "x-adpcm",
"x-aifc", "x-aiff", "x-aiffc", "x-ape", "x-flac+ogg", "x-m4b", "x-matroska", "x-ms-asx", "x-ms-wma",
"x-speex", "x-speex+ogg", "x-vorbis+ogg", "x-wav"),
@@ -109,11 +110,12 @@ OTHER_KNOWN_FORMATS = ("video/mp2t",)
class MediaLibraryWidget(Gtk.VBox, Loggable):
+
""" Widget for listing sources """
__gsignals__ = {
'play': (GObject.SignalFlags.RUN_LAST, None,
- (GObject.TYPE_PYOBJECT,))}
+ (GObject.TYPE_PYOBJECT,))}
def __init__(self, app, uiman):
Gtk.VBox.__init__(self)
@@ -147,21 +149,26 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
# Store
self.storemodel = Gtk.ListStore(*STORE_MODEL_STRUCTURE)
- self.storemodel.set_sort_func(COL_URI, MediaLibraryWidget.compare_basename)
+ self.storemodel.set_sort_func(
+ COL_URI, MediaLibraryWidget.compare_basename)
# Prefer to sort the media library elements by URI
# rather than show them randomly.
self.storemodel.set_sort_column_id(COL_URI, Gtk.SortType.ASCENDING)
# Scrolled Windows
self.treeview_scrollwin = Gtk.ScrolledWindow()
- self.treeview_scrollwin.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
+ self.treeview_scrollwin.set_policy(
+ Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
self.treeview_scrollwin.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
- self.treeview_scrollwin.get_accessible().set_name("media_listview_scrollwindow")
+ self.treeview_scrollwin.get_accessible().set_name(
+ "media_listview_scrollwindow")
self.iconview_scrollwin = Gtk.ScrolledWindow()
- self.iconview_scrollwin.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
+ self.iconview_scrollwin.set_policy(
+ Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
self.iconview_scrollwin.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
- self.iconview_scrollwin.get_accessible().set_name("media_iconview_scrollwindow")
+ self.iconview_scrollwin.get_accessible().set_name(
+ "media_iconview_scrollwindow")
# import sources dialogbox
self._importDialog = None
@@ -169,14 +176,17 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
# Filtering model for the search box.
# Use this instead of using self.storemodel directly
self.modelFilter = self.storemodel.filter_new()
- self.modelFilter.set_visible_func(self._setRowVisible, data=searchEntry)
+ self.modelFilter.set_visible_func(
+ self._setRowVisible, data=searchEntry)
# TreeView
# Displays icon, name, type, length
self.treeview = Gtk.TreeView(model=self.modelFilter)
self.treeview_scrollwin.add(self.treeview)
- self.treeview.connect("button-press-event", self._treeViewButtonPressEventCb)
- self.treeview.connect("button-release-event", self._treeViewButtonReleaseEventCb)
+ self.treeview.connect(
+ "button-press-event", self._treeViewButtonPressEventCb)
+ self.treeview.connect(
+ "button-release-event", self._treeViewButtonReleaseEventCb)
self.treeview.connect("row-activated", self._itemOrRowActivatedCb)
self.treeview.set_headers_visible(False)
self.treeview.set_property("search_column", COL_SEARCH_TEXT)
@@ -215,10 +225,13 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
# IconView
self.iconview = Gtk.IconView(model=self.modelFilter)
self.iconview_scrollwin.add(self.iconview)
- self.iconview.connect("button-press-event", self._iconViewButtonPressEventCb)
- self.iconview.connect("button-release-event", self._iconViewButtonReleaseEventCb)
+ self.iconview.connect(
+ "button-press-event", self._iconViewButtonPressEventCb)
+ self.iconview.connect(
+ "button-release-event", self._iconViewButtonReleaseEventCb)
self.iconview.connect("item-activated", self._itemOrRowActivatedCb)
- self.iconview.connect("selection-changed", self._viewSelectionChangedCb)
+ self.iconview.connect(
+ "selection-changed", self._viewSelectionChangedCb)
self.iconview.set_item_orientation(Gtk.Orientation.VERTICAL)
self.iconview.set_property("has_tooltip", True)
self.iconview.set_tooltip_column(COL_INFOTEXT)
@@ -249,7 +262,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
# Connect to project. We must remove and reset the callbacks when
# changing project.
project_manager = self.app.project_manager
- project_manager.connect("new-project-created", self._newProjectCreatedCb)
+ project_manager.connect(
+ "new-project-created", self._newProjectCreatedCb)
project_manager.connect("new-project-loaded", self._newProjectLoadedCb)
project_manager.connect("new-project-failed", self._newProjectFailedCb)
@@ -260,8 +274,10 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
self.drag_dest_add_uri_targets()
self.connect("drag_data_received", self._dndDataReceivedCb)
- self._setup_view_for_drag_and_drop(self.treeview, [FILESOURCE_TARGET_ENTRY])
- self._setup_view_for_drag_and_drop(self.iconview, [FILESOURCE_TARGET_ENTRY])
+ self._setup_view_for_drag_and_drop(
+ self.treeview, [FILESOURCE_TARGET_ENTRY])
+ self._setup_view_for_drag_and_drop(
+ self.iconview, [FILESOURCE_TARGET_ENTRY])
# Hack so that the views have the same method as self
self.treeview.getSelectedItems = self.getSelectedItems
@@ -269,10 +285,10 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
# Keyboard shortcuts for some items in the gtkbuilder file
selection_actions = (
("RemoveSources", Gtk.STOCK_DELETE, _("_Remove from Project"),
- "<Control>Delete", None, self._removeSourcesCb),
+ "<Control>Delete", None, self._removeSourcesCb),
("InsertEnd", Gtk.STOCK_COPY, _("Insert at _End of Timeline"),
- "Insert", None, self._insertEndCb),
+ "Insert", None, self._insertEndCb),
)
self.selection_actions = Gtk.ActionGroup(name="medialibraryselection")
self.selection_actions.add_actions(selection_actions)
@@ -333,7 +349,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
def _setup_view_for_drag_and_drop(self, view, target_entries):
view.drag_source_set(0, [], Gdk.DragAction.COPY)
- view.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, target_entries, Gdk.DragAction.COPY)
+ view.enable_model_drag_source(
+ Gdk.ModifierType.BUTTON1_MASK, target_entries, Gdk.DragAction.COPY)
view.drag_source_set_target_list([])
view.drag_source_add_uri_targets()
view.drag_source_add_text_targets()
@@ -386,7 +403,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
# empty except clause is bad but load_icon raises Gio.Error.
# Right, *gio*.
if alternate:
- icon = GdkPixbuf.Pixbuf.new_from_file(os.path.join(pixdir, alternate))
+ icon = GdkPixbuf.Pixbuf.new_from_file(
+ os.path.join(pixdir, alternate))
else:
icon = icontheme.load_icon("dialog-question", size, 0)
return icon
@@ -443,8 +461,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
close_after = Gtk.CheckButton(label=_("Close after importing files"))
close_after.set_active(self.app.settings.closeImportDialog)
- self._importDialog = Gtk.FileChooserDialog(title=dialogtitle, transient_for=None,
- action=chooser_action)
+ self._importDialog = Gtk.FileChooserDialog(
+ title=dialogtitle, transient_for=None, action=chooser_action)
self._importDialog.set_icon_name("pitivi")
self._importDialog.add_buttons(_("Cancel"), Gtk.ResponseType.CANCEL,
@@ -454,12 +472,14 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
self._importDialog.set_select_multiple(True)
self._importDialog.set_modal(True)
self._importDialog.set_transient_for(self.app.gui)
- self._importDialog.set_current_folder(self.app.settings.lastImportFolder)
+ self._importDialog.set_current_folder(
+ self.app.settings.lastImportFolder)
self._importDialog.connect('response', self._dialogBoxResponseCb)
previewer = PreviewWidget(self.app.settings)
self._importDialog.set_preview_widget(previewer)
self._importDialog.set_use_preview_label(False)
- self._importDialog.connect('update-preview', previewer.add_preview_request)
+ self._importDialog.connect(
+ 'update-preview', previewer.add_preview_request)
# Filter for the "known good" formats by default
filt_supported = Gtk.FileFilter()
filt_known = Gtk.FileFilter()
@@ -489,7 +509,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
# the actual # of the clip we're processing), but there is no offset
# in the progressbar itself (to reflect the process being incomplete).
current_clip_iter = self.app.project_manager.current_project.nb_imported_files
- total_clips = self.app.project_manager.current_project.nb_remaining_file_to_import +
current_clip_iter
+ total_clips = self.app.project_manager.current_project.nb_remaining_file_to_import + \
+ current_clip_iter
progressbar_text = (_("Importing clip %(current_clip)d of %(total)d") %
{"current_clip": current_clip_iter + 1,
@@ -498,7 +519,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
if current_clip_iter == 0:
self._progressbar.set_fraction(0.0)
elif total_clips != 0:
- self._progressbar.set_fraction(current_clip_iter / float(total_clips))
+ self._progressbar.set_fraction(
+ current_clip_iter / float(total_clips))
def _getThumbnailInDir(self, dir, hash):
"""
@@ -512,7 +534,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
path_128 = dir + "normal/" + hash + ".png"
interpolation = GdkPixbuf.InterpType.BILINEAR
- # First, try the 128 version since that's the native resolution we want:
+ # First, try the 128 version since that's the native resolution we
+ # want:
try:
thumb_128 = GdkPixbuf.Pixbuf.new_from_file(path_128)
w, h = thumb_128.get_width(), thumb_128.get_height()
@@ -537,8 +560,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
# seems to be the proper/reliable way in a GNOME context
asset_file = Gio.file_new_for_uri(uri)
info = asset_file.query_info(attributes="standard::*",
- flags=Gio.FileQueryInfoFlags.NONE,
- cancellable=None)
+ flags=Gio.FileQueryInfoFlags.NONE,
+ cancellable=None)
mime = Gio.content_type_get_mime_type(info.get_content_type())
mtime = os.path.getmtime(path_from_uri(uri))
if not self.thumbnailer.can_thumbnail(uri, mime, mtime):
@@ -549,18 +572,21 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
self.debug("Thumbnailer failed thumbnailing %s", uri)
return None
self.thumbnailer.save_thumbnail(pixbuf_128, uri, mtime)
- pixbuf_64 = pixbuf_128.scale_simple(64, 64, GdkPixbuf.InterpType.BILINEAR)
+ pixbuf_64 = pixbuf_128.scale_simple(
+ 64, 64, GdkPixbuf.InterpType.BILINEAR)
return pixbuf_128, pixbuf_64
def _addAsset(self, asset):
- # 128 is the normal size for thumbnails, but for *icons* it looks insane
+ # 128 is the normal size for thumbnails, but for *icons* it looks
+ # insane
LARGE_SIZE = 96
info = asset.get_info()
# The code below tries to read existing thumbnails from the freedesktop
# thumbnails directory (~/.thumbnails). The filenames are simply
# the file URI hashed with md5, so we can retrieve them easily.
- video_streams = [i for i in info.get_stream_list() if isinstance(i, DiscovererVideoInfo)]
+ video_streams = [
+ i for i in info.get_stream_list() if isinstance(i, DiscovererVideoInfo)]
if len(video_streams) > 0:
# From the freedesktop spec: "if the environment variable
# $XDG_CACHE_HOME is set and not blank then the directory
@@ -571,24 +597,30 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
thumbnail_hash = md5(quoted_uri.encode()).hexdigest()
try:
thumb_dir = os.environ['XDG_CACHE_HOME']
- thumb_64, thumb_128 = self._getThumbnailInDir(thumb_dir, thumbnail_hash)
+ thumb_64, thumb_128 = self._getThumbnailInDir(
+ thumb_dir, thumbnail_hash)
except KeyError:
thumb_64, thumb_128 = (None, None)
if thumb_64 is None:
thumb_dir = os.path.expanduser("~/.cache/thumbnails/")
- thumb_64, thumb_128 = self._getThumbnailInDir(thumb_dir, thumbnail_hash)
+ thumb_64, thumb_128 = self._getThumbnailInDir(
+ thumb_dir, thumbnail_hash)
if thumb_64 is None:
thumb_dir = os.path.expanduser("~/.thumbnails/")
- thumb_64, thumb_128 = self._getThumbnailInDir(thumb_dir, thumbnail_hash)
+ thumb_64, thumb_128 = self._getThumbnailInDir(
+ thumb_dir, thumbnail_hash)
if thumb_64 is None:
if asset.is_image():
thumb_64 = self._getIcon("image-x-generic")
- thumb_128 = self._getIcon("image-x-generic", None, LARGE_SIZE)
+ thumb_128 = self._getIcon(
+ "image-x-generic", None, LARGE_SIZE)
else:
thumb_64 = self._getIcon("video-x-generic")
- thumb_128 = self._getIcon("video-x-generic", None, LARGE_SIZE)
+ thumb_128 = self._getIcon(
+ "video-x-generic", None, LARGE_SIZE)
# TODO ideally gst discoverer should create missing thumbnails.
- self.log("Missing a thumbnail for %s, queuing", path_from_uri(quoted_uri))
+ self.log(
+ "Missing a thumbnail for %s, queuing", path_from_uri(quoted_uri))
self._missing_thumbs.append(quoted_uri)
else:
thumb_64 = self._getIcon("audio-x-generic")
@@ -620,7 +652,7 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
# medialibrary callbacks
def _assetAddedCb(self, unused_project, asset,
- unused_current_clip_iter=None, unused_total_clips=None):
+ unused_current_clip_iter=None, unused_total_clips=None):
""" a file was added to the medialibrary """
if isinstance(asset, GES.UriClipAsset):
self._updateProgressbar()
@@ -652,7 +684,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
self._progressbar.show()
def _sourcesStoppedImportingCb(self, unused_project):
- self.debug("Importing took %.3f seconds", time.time() - self.import_start_time)
+ self.debug("Importing took %.3f seconds",
+ time.time() - self.import_start_time)
self.flush_pending_rows()
self._progressbar.hide()
if self._errors:
@@ -674,7 +707,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
self._missing_thumbs = []
if missing_thumbs:
self.info("Generating missing thumbnails: %d", len(missing_thumbs))
- self._thumbs_process = threading.Thread(target=MediaLibraryWidget._generateThumbnailsThread,
args=(self, missing_thumbs))
+ self._thumbs_process = threading.Thread(
+ target=MediaLibraryWidget._generateThumbnailsThread, args=(self, missing_thumbs))
self._thumbs_process.start()
def _generateThumbnailsThread(self, missing_thumbs):
@@ -696,7 +730,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
break
if not found:
# Can happen if the user removed the asset in the meanwhile.
- self.log("%s needed a thumbnail, but vanished from storemodel", uri)
+ self.log(
+ "%s needed a thumbnail, but vanished from storemodel", uri)
# Error Dialog Box callbacks
@@ -733,7 +768,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
paths = self.getSelectedPaths()
if not paths:
return
- # use row references so we don't have to care if a path has been removed
+ # use row references so we don't have to care if a path has been
+ # removed
rows = []
for path in paths:
row = Gtk.TreeRowReference.new(model, path)
@@ -758,7 +794,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
"""
Select, in the media library, unused sources in the project.
"""
- assets = self.app.project_manager.current_project.list_assets(GES.UriClip)
+ assets = self.app.project_manager.current_project.list_assets(
+ GES.UriClip)
unused_sources_uris = []
model = self.treeview.get_model()
@@ -799,7 +836,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
# Only use the first item.
path = paths[0]
asset = self.storemodel[path][COL_ASSET]
- dialog = ClipMediaPropsDialog(self.app.project_manager.current_project, asset)
+ dialog = ClipMediaPropsDialog(
+ self.app.project_manager.current_project, asset)
dialog.dialog.set_transient_for(self.app.gui)
dialog.run()
@@ -852,7 +890,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
selection = view.get_selected_items()
return view.path_is_selected(path) and len(selection)
else:
- raise RuntimeError("Unknown media library view type: %s" % type(view))
+ raise RuntimeError(
+ "Unknown media library view type: %s" % type(view))
return False
@@ -866,7 +905,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
def _viewGetPathAtPos(self, event):
if self.clip_view == SHOW_TREEVIEW:
- pathinfo = self.treeview.get_path_at_pos(int(event.x), int(event.y))
+ pathinfo = self.treeview.get_path_at_pos(
+ int(event.x), int(event.y))
return pathinfo[0]
elif self.clip_view == SHOW_ICONVIEW:
return self.iconview.get_path_at_pos(int(event.x), int(event.y))
@@ -917,7 +957,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
def _treeViewButtonReleaseEventCb(self, unused_treeview, event):
ts = self.treeview.get_selection()
- state = event.get_state() & (Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
+ state = event.get_state() & (
+ Gdk.ModifierType.CONTROL_MASK | Gdk.ModifierType.SHIFT_MASK)
path = self.treeview.get_path_at_pos(event.x, event.y)
if not state and not self.dragged:
@@ -959,7 +1000,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
for path in self._draggedPaths:
self.iconview.select_path(path)
- self.iconview_cursor_pos = self.iconview.get_path_at_pos(event.x, event.y)
+ self.iconview_cursor_pos = self.iconview.get_path_at_pos(
+ event.x, event.y)
return True
@@ -968,7 +1010,8 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
shift_mask = event.get_state() & Gdk.ModifierType.SHIFT_MASK
modifier_active = control_mask or shift_mask
if not modifier_active and self.iconview_cursor_pos:
- current_cursor_pos = self.iconview.get_path_at_pos(event.x, event.y)
+ current_cursor_pos = self.iconview.get_path_at_pos(
+ event.x, event.y)
if current_cursor_pos == self.iconview_cursor_pos:
if iconview.path_is_selected(current_cursor_pos):
@@ -1000,13 +1043,15 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
if self.app.project_manager.current_project:
self.app.project_manager.current_project.addUris(uris)
else:
- self.warning("Adding uris to project, but the project has changed in the meantime")
+ self.warning(
+ "Adding uris to project, but the project has changed in the meantime")
return False
# Drag and Drop
def _dndDataReceivedCb(self, unused_widget, unused_context, unused_x,
unused_y, selection, targettype, unused_time):
- self.debug("targettype: %d, selection.data: %r", targettype, selection.get_data())
+ self.debug("targettype: %d, selection.data: %r",
+ targettype, selection.get_data())
directories = []
filenames = []
@@ -1027,10 +1072,12 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
else:
self.warning("Unusable file: %s, %s", raw_uri, path)
else:
- self.fixme("Importing remote files is not implemented: %s", raw_uri)
+ self.fixme(
+ "Importing remote files is not implemented: %s", raw_uri)
if directories:
- # Recursively import from folders that were dragged into the library
+ # Recursively import from folders that were dragged into the
+ # library
self.app.threads.addThread(PathWalker, directories, self._addUris)
if filenames:
self.app.project_manager.current_project.addUris(filenames)
@@ -1078,7 +1125,7 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
return [self.modelFilter[path][COL_URI]
for path in self._draggedPaths]
return [self.modelFilter[path][COL_URI]
- for path in self.getSelectedPaths()]
+ for path in self.getSelectedPaths()]
def getSelectedAssets(self):
""" Returns a list of selected items URIs """
@@ -1086,4 +1133,4 @@ class MediaLibraryWidget(Gtk.VBox, Loggable):
return [self.modelFilter[path][COL_ASSET]
for path in self._draggedPaths]
return [self.modelFilter[path][COL_ASSET]
- for path in self.getSelectedPaths()]
+ for path in self.getSelectedPaths()]
diff --git a/pitivi/preset.py b/pitivi/preset.py
index f3d8be9..60d1e94 100644
--- a/pitivi/preset.py
+++ b/pitivi/preset.py
@@ -35,11 +35,13 @@ from pitivi.utils import system
class DuplicatePresetNameException(Exception):
+
"""Raised when an operation would result in a duplicated preset name."""
pass
class PresetManager(object):
+
"""Abstract class for storing a list of presets.
Subclasses must provide a filename attribute.
@@ -232,7 +234,8 @@ class PresetManager(object):
def removePreset(self, name):
try:
- os.remove(self.presets[name]["filepath"]) # Deletes json file if exists
+ # Deletes json file if exists
+ os.remove(self.presets[name]["filepath"])
except KeyError:
# Trying to remove a preset that has not actually been saved
return
@@ -382,8 +385,8 @@ class RenderPresetManager(PresetManager):
cached_encs = CachedEncoderList()
if (acodec not in [fact.get_name() for fact in cached_encs.aencoders]
- or vcodec not in [fact.get_name() for fact in cached_encs.vencoders]
- or container not in [fact.get_name() for fact in cached_encs.muxers]):
+ or vcodec not in [fact.get_name() for fact in cached_encs.vencoders]
+ or container not in [fact.get_name() for fact in cached_encs.muxers]):
return
try:
diff --git a/pitivi/project.py b/pitivi/project.py
index 526eacd..24da94a 100644
--- a/pitivi/project.py
+++ b/pitivi/project.py
@@ -62,6 +62,7 @@ DEFAULT_AUDIO_ENCODER = "vorbisenc"
class AssetRemovedAction(UndoableAction):
+
def __init__(self, project, asset):
UndoableAction.__init__(self)
self.project = project
@@ -82,6 +83,7 @@ class AssetRemovedAction(UndoableAction):
class AssetAddedAction(UndoableAction):
+
def __init__(self, project, asset):
UndoableAction.__init__(self)
self.project = project
@@ -159,6 +161,7 @@ class ProjectLogObserver(UndoableAction):
class ProjectManager(GObject.Object, Loggable):
+
"""
@type app: L{Pitivi}
@type current_project: L{Project}
@@ -203,7 +206,8 @@ class ProjectManager(GObject.Object, Loggable):
use_backup = False
try:
time_diff = os.path.getmtime(backup_path) - os.path.getmtime(path)
- self.debug('Backup file is %d secs newer: %s', time_diff, backup_path)
+ self.debug(
+ 'Backup file is %d secs newer: %s', time_diff, backup_path)
except OSError:
self.debug('Backup file does not exist: %s', backup_path)
except UnicodeEncodeError:
@@ -230,13 +234,14 @@ class ProjectManager(GObject.Object, Loggable):
if self.current_project.createTimeline():
self.emit("new-project-created", self.current_project)
- self.current_project.connect("project-changed", self._projectChangedCb)
+ self.current_project.connect(
+ "project-changed", self._projectChangedCb)
return True
else:
self.emit("new-project-failed", uri,
_('This might be due to a bug or an unsupported project file format. '
- 'If you were trying to add a media file to your project, '
- 'use the "Import" button instead.'))
+ 'If you were trying to add a media file to your project, '
+ 'use the "Import" button instead.'))
self.newBlankProject(ignore_unsaved_changes=True)
return False
@@ -250,7 +255,8 @@ class ProjectManager(GObject.Object, Loggable):
dialog.add_buttons(_("Ignore backup"), Gtk.ResponseType.REJECT,
_("Restore from backup"), Gtk.ResponseType.YES)
# Even though we set the title to an empty string when creating dialog,
- # seems we really have to do it once more so it doesn't show "pitivi"...
+ # seems we really have to do it once more so it doesn't show
+ # "pitivi"...
dialog.set_title("")
dialog.set_icon_name("pitivi")
dialog.set_transient_for(self.app.gui)
@@ -274,7 +280,8 @@ class ProjectManager(GObject.Object, Loggable):
vbox.pack_start(primary, True, True, 0)
# make the [[image] text] hbox
- image = Gtk.Image.new_from_icon_name("dialog-question", Gtk.IconSize.DIALOG)
+ image = Gtk.Image.new_from_icon_name(
+ "dialog-question", Gtk.IconSize.DIALOG)
hbox = Gtk.HBox(homogeneous=False, spacing=SPACING * 2)
hbox.pack_start(image, False, True, 0)
hbox.pack_start(vbox, True, True, 0)
@@ -309,7 +316,8 @@ class ProjectManager(GObject.Object, Loggable):
GES will default to GES.XmlFormatter.
"""
if self.disable_save is True and (backup is True or uri is None):
- self.log("Read-only mode is enforced and no new URI was specified, ignoring save request")
+ self.log(
+ "Read-only mode is enforced and no new URI was specified, ignoring save request")
return False
if backup:
@@ -340,7 +348,9 @@ class ProjectManager(GObject.Object, Loggable):
# "overwrite" is always True: our GTK filechooser save dialogs are
# set to always ask the user on our behalf about overwriting, so
# if saveProject is actually called, that means overwriting is OK.
- saved = self.current_project.save(self.current_project.timeline, uri, formatter_type,
overwrite=True)
+ saved = self.current_project.save(
+ self.current_project.timeline, uri,
+ formatter_type, overwrite=True)
except Exception as e:
saved = False
self.emit("save-project-failed", uri, e)
@@ -397,7 +407,8 @@ class ProjectManager(GObject.Object, Loggable):
# add all sources
for source in sources:
path = path_from_uri(source.get_id())
- tar.add(path, os.path.join(top, os.path.relpath(path, common)))
+ tar.add(
+ path, os.path.join(top, os.path.relpath(path, common)))
tar.close()
# This catches errors with tarring; the GUI already shows errors while
# saving projects (ex: permissions), so probably no GUI needed here.
@@ -407,8 +418,10 @@ class ProjectManager(GObject.Object, Loggable):
self.error(e)
tar_file = path_from_uri(uri)
if os.path.isfile(tar_file):
- renamed = os.path.splitext(tar_file)[0] + " (CORRUPT)" + "." + project_extension + "_tar"
- self.warning('An error occurred, will save the tarball as "%s"' % renamed)
+ renamed = os.path.splitext(tar_file)[
+ 0] + " (CORRUPT)" + "." + project_extension + "_tar"
+ self.warning(
+ 'An error occurred, will save the tarball as "%s"' % renamed)
os.rename(tar_file, renamed)
else:
everything_ok = True
@@ -437,12 +450,14 @@ class ProjectManager(GObject.Object, Loggable):
""" close the current project """
if self.current_project is None:
- self.warning("Trying to close a project that was already closed/didn't exist")
+ self.warning(
+ "Trying to close a project that was already closed/didn't exist")
return True
self.info("closing running project %s", self.current_project.uri)
if not self.emit("closing-project", self.current_project):
- self.warning("Could not close project - this could be because there were unsaved changes and the
user cancelled when prompted about them")
+ self.warning(
+ "Could not close project - this could be because there were unsaved changes and the user
cancelled when prompted about them")
return False
self.emit("project-closed", self.current_project)
@@ -452,7 +467,8 @@ class ProjectManager(GObject.Object, Loggable):
try:
self.current_project.disconnect_by_function(self._projectChangedCb)
except Exception:
- self.debug("Tried disconnecting signals, but they were not connected")
+ self.debug(
+ "Tried disconnecting signals, but they were not connected")
self._cleanBackup(self.current_project.uri)
self.current_project.release()
self.current_project = None
@@ -517,7 +533,8 @@ class ProjectManager(GObject.Object, Loggable):
if self._backup_lock == 0:
self._backup_lock = 10
- GLib.timeout_add_seconds(self._backup_lock, self._saveBackupCb, project, uri)
+ GLib.timeout_add_seconds(
+ self._backup_lock, self._saveBackupCb, project, uri)
else:
if self._backup_lock < 60:
self._backup_lock += 5
@@ -560,6 +577,7 @@ class ProjectManager(GObject.Object, Loggable):
class Project(Loggable, GES.Project):
+
"""
The base class for Pitivi projects
@@ -620,24 +638,24 @@ class Project(Loggable, GES.Project):
container_profile = \
GstPbutils.EncodingContainerProfile.new("pitivi-profile",
_("Pitivi encoding profile"),
- Gst.Caps("application/ogg"),
+ Gst.Caps(
+ "application/ogg"),
None)
- # Create video profile (We use the same default seetings as the project settings)
- video_profile = GstPbutils.EncodingVideoProfile.new(Gst.Caps("video/x-theora"),
- None,
- Gst.Caps("video/x-raw"),
- 0)
-
- # Create audio profile (We use the same default seetings as the project settings)
- audio_profile = GstPbutils.EncodingAudioProfile.new(Gst.Caps("audio/x-vorbis"),
- None,
- Gst.Caps("audio/x-raw"),
- 0)
+ # Create video profile (We use the same default seetings as the project
+ # settings)
+ video_profile = GstPbutils.EncodingVideoProfile.new(
+ Gst.Caps("video/x-theora"), None, Gst.Caps("video/x-raw"), 0)
+
+ # Create audio profile (We use the same default seetings as the project
+ # settings)
+ audio_profile = GstPbutils.EncodingAudioProfile.new(
+ Gst.Caps("audio/x-vorbis"), None, Gst.Caps("audio/x-raw"), 0)
container_profile.add_profile(video_profile)
container_profile.add_profile(audio_profile)
# Keep a reference to those profiles
- # FIXME We should handle the case we have more than 1 audio and 1 video profiles
+ # FIXME We should handle the case we have more than 1 audio and 1 video
+ # profiles
self.container_profile = container_profile
self.audio_profile = audio_profile
self.video_profile = video_profile
@@ -774,7 +792,8 @@ class Project(Loggable, GES.Project):
@videopar.setter
def videopar(self, value):
if self.set_video_restriction_value("pixel-aspect-ratio", value):
- self._emitChange("rendering-settings-changed", "pixel-aspect-ratio", value)
+ self._emitChange(
+ "rendering-settings-changed", "pixel-aspect-ratio", value)
@property
def audiochannels(self):
@@ -878,7 +897,7 @@ class Project(Loggable, GES.Project):
self.nb_imported_files += 1
assets = self.get_loading_assets()
self.nb_remaining_file_to_import = len([asset for asset in assets if
- GObject.type_is_a(asset.get_extractable_type(), GES.UriClip)])
+ GObject.type_is_a(asset.get_extractable_type(),
GES.UriClip)])
if self.nb_remaining_file_to_import == 0:
self.nb_imported_files = 0
# We do not take into account asset comming from project
@@ -911,28 +930,33 @@ class Project(Loggable, GES.Project):
# The encoding profile might have been reset from the
# Project file, we just take it as our
self.container_profile = container_profile
- self.muxer = self._getElementFactoryName(encoders.muxers, container_profile)
+ self.muxer = self._getElementFactoryName(
+ encoders.muxers, container_profile)
if self.muxer is None:
self.muxer = DEFAULT_MUXER
for profile in container_profile.get_profiles():
if isinstance(profile, GstPbutils.EncodingVideoProfile):
self.video_profile = profile
if self.video_profile.get_restriction() is None:
- self.video_profile.set_restriction(Gst.Caps("video/x-raw"))
+ self.video_profile.set_restriction(
+ Gst.Caps("video/x-raw"))
self._ensureVideoRestrictions()
- self.vencoder = self._getElementFactoryName(encoders.vencoders, profile)
+ self.vencoder = self._getElementFactoryName(
+ encoders.vencoders, profile)
elif isinstance(profile, GstPbutils.EncodingAudioProfile):
self.audio_profile = profile
if self.audio_profile.get_restriction() is None:
- self.audio_profile.set_restriction(Gst.Caps("audio/x-raw"))
+ self.audio_profile.set_restriction(
+ Gst.Caps("audio/x-raw"))
self._ensureAudioRestrictions()
- self.aencoder = self._getElementFactoryName(encoders.aencoders, profile)
+ self.aencoder = self._getElementFactoryName(
+ encoders.aencoders, profile)
else:
self.warning("We do not handle profile: %s" % profile)
# ------------------------------------------ #
- # Our API #
+ # Our API #
# ------------------------------------------ #
def _commit(self):
"""
@@ -1088,7 +1112,7 @@ class Project(Loggable, GES.Project):
self._acodecsettings_cache[self.aencoder] = value
# ------------------------------------------ #
- # Private methods #
+ # Private methods #
# ------------------------------------------ #
def _ensureTracks(self):
@@ -1139,7 +1163,8 @@ class Project(Loggable, GES.Project):
return profile.get_preset_name()
factories = Gst.ElementFactory.list_filter(elements,
- Gst.Caps(profile.get_format()),
+ Gst.Caps(
+ profile.get_format()),
Gst.PadDirection.SRC,
False)
if factories:
@@ -1149,7 +1174,7 @@ class Project(Loggable, GES.Project):
def _calculateNbLoadingAssets(self):
nb_remaining_file_to_import = len([asset for asset in self.get_loading_assets() if
- GObject.type_is_a(asset.get_extractable_type(), GES.UriClip)])
+ GObject.type_is_a(asset.get_extractable_type(), GES.UriClip)])
if self.nb_remaining_file_to_import == 0 and nb_remaining_file_to_import:
self.nb_remaining_file_to_import = nb_remaining_file_to_import
self._emitChange("start-importing")
@@ -1174,7 +1199,8 @@ class ProjectSettingsDialog():
Initialize the static parts of the UI and set up various shortcuts
"""
self.builder = Gtk.Builder()
- self.builder.add_from_file(os.path.join(get_ui_dir(), "projectsettings.ui"))
+ self.builder.add_from_file(
+ os.path.join(get_ui_dir(), "projectsettings.ui"))
self.builder.connect_signals(self)
getObj = self.builder.get_object
@@ -1208,8 +1234,10 @@ class ProjectSettingsDialog():
# Set the shading style in the contextual toolbars below presets
video_presets_toolbar = getObj("video_presets_toolbar")
audio_presets_toolbar = getObj("audio_presets_toolbar")
- video_presets_toolbar.get_style_context().add_class(Gtk.STYLE_CLASS_INLINE_TOOLBAR)
- audio_presets_toolbar.get_style_context().add_class(Gtk.STYLE_CLASS_INLINE_TOOLBAR)
+ video_presets_toolbar.get_style_context().add_class(
+ Gtk.STYLE_CLASS_INLINE_TOOLBAR)
+ audio_presets_toolbar.get_style_context().add_class(
+ Gtk.STYLE_CLASS_INLINE_TOOLBAR)
def _setupUiConstraints(self):
"""
@@ -1274,7 +1302,8 @@ class ProjectSettingsDialog():
edge_func=self.updateWidth)
# keep framereate text field and combo in sync
- self.wg.addBiEdge(self.frame_rate_combo, self.frame_rate_fraction_widget)
+ self.wg.addBiEdge(
+ self.frame_rate_combo, self.frame_rate_fraction_widget)
# keep dar text field and combo in sync
self.wg.addEdge(self.dar_combo, self.dar_fraction_widget,
@@ -1334,16 +1363,21 @@ class ProjectSettingsDialog():
# Bind the widgets in the Video tab to the Video Presets Manager.
self.bindSpinbutton(self.video_presets, "width", self.width_spinbutton)
- self.bindSpinbutton(self.video_presets, "height", self.height_spinbutton)
- self.bindFractionWidget(self.video_presets, "frame-rate", self.frame_rate_fraction_widget)
+ self.bindSpinbutton(
+ self.video_presets, "height", self.height_spinbutton)
+ self.bindFractionWidget(
+ self.video_presets, "frame-rate", self.frame_rate_fraction_widget)
self.bindPar(self.video_presets)
# Bind the widgets in the Audio tab to the Audio Presets Manager.
self.bindCombo(self.audio_presets, "channels", self.channels_combo)
- self.bindCombo(self.audio_presets, "sample-rate", self.sample_rate_combo)
+ self.bindCombo(
+ self.audio_presets, "sample-rate", self.sample_rate_combo)
- self.wg.addEdge(self.par_fraction_widget, self.save_video_preset_button)
- self.wg.addEdge(self.frame_rate_fraction_widget, self.save_video_preset_button)
+ self.wg.addEdge(
+ self.par_fraction_widget, self.save_video_preset_button)
+ self.wg.addEdge(
+ self.frame_rate_fraction_widget, self.save_video_preset_button)
self.wg.addEdge(self.width_spinbutton, self.save_video_preset_button)
self.wg.addEdge(self.height_spinbutton, self.save_video_preset_button)
@@ -1357,7 +1391,8 @@ class ProjectSettingsDialog():
self.select_par_radiobutton.props.active = True
self.par_fraction_widget.setWidgetValue(value)
- mgr.bindWidget("par", updatePar, self.par_fraction_widget.getWidgetValue)
+ mgr.bindWidget(
+ "par", updatePar, self.par_fraction_widget.getWidgetValue)
def bindFractionWidget(self, mgr, name, widget):
mgr.bindWidget(name, widget.setWidgetValue, widget.getWidgetValue)
@@ -1390,9 +1425,11 @@ class ProjectSettingsDialog():
treeview.props.headers_visible = False
model = mgr.getModel()
treeview.set_model(model)
- model.connect("row-inserted", self._newPresetCb, column, renderer, treeview)
+ model.connect(
+ "row-inserted", self._newPresetCb, column, renderer, treeview)
renderer.connect("edited", self._presetNameEditedCb, mgr)
- renderer.connect("editing-started", self._presetNameEditingStartedCb, mgr)
+ renderer.connect(
+ "editing-started", self._presetNameEditingStartedCb, mgr)
treeview.get_selection().connect("changed", self._presetChangedCb, mgr,
update_buttons_func)
treeview.connect("focus-out-event", self._treeviewDefocusedCb, mgr)
@@ -1548,8 +1585,10 @@ class ProjectSettingsDialog():
self.remove_audio_preset_button.set_sensitive(can_remove)
def _updateVideoPresetButtons(self):
- self.save_video_preset_button.set_sensitive(self.video_presets.isSaveButtonSensitive())
- self.remove_video_preset_button.set_sensitive(self.video_presets.isRemoveButtonSensitive())
+ self.save_video_preset_button.set_sensitive(
+ self.video_presets.isSaveButtonSensitive())
+ self.remove_video_preset_button.set_sensitive(
+ self.video_presets.isRemoveButtonSensitive())
def _updateAudioSaveButton(self, unused_in, button):
button.set_sensitive(self.audio_presets.isSaveButtonSensitive())
@@ -1582,16 +1621,20 @@ class ProjectSettingsDialog():
self.par_fraction_widget.setWidgetValue(dar * (1 / sar))
def updateDarFromCombo(self):
- self.dar_fraction_widget.setWidgetValue(get_combo_value(self.dar_combo))
+ self.dar_fraction_widget.setWidgetValue(
+ get_combo_value(self.dar_combo))
def updateDarFromFractionWidget(self):
- set_combo_value(self.dar_combo, self.dar_fraction_widget.getWidgetValue())
+ set_combo_value(
+ self.dar_combo, self.dar_fraction_widget.getWidgetValue())
def updateParFromCombo(self):
- self.par_fraction_widget.setWidgetValue(get_combo_value(self.par_combo))
+ self.par_fraction_widget.setWidgetValue(
+ get_combo_value(self.par_combo))
def updateParFromFractionWidget(self):
- set_combo_value(self.par_combo, self.par_fraction_widget.getWidgetValue())
+ set_combo_value(
+ self.par_combo, self.par_fraction_widget.getWidgetValue())
def updateUI(self):
@@ -1626,7 +1669,8 @@ class ProjectSettingsDialog():
self.project.videowidth = int(self.width_spinbutton.get_value())
self.project.videoheight = int(self.height_spinbutton.get_value())
self.project.videopar = self.par_fraction_widget.getWidgetValue()
- self.project.videorate = self.frame_rate_fraction_widget.getWidgetValue()
+ self.project.videorate = self.frame_rate_fraction_widget.getWidgetValue(
+ )
self.project.audiochannels = get_combo_value(self.channels_combo)
self.project.audiorate = get_combo_value(self.sample_rate_combo)
diff --git a/pitivi/render.py b/pitivi/render.py
index a010494..ac1c608 100644
--- a/pitivi/render.py
+++ b/pitivi/render.py
@@ -48,6 +48,7 @@ from pitivi.utils.widgets import GstElementSettingsDialog
class CachedEncoderList(object):
+
"""
Registry of avalaible Muxer/Audio encoder/Video Encoder. And
avalaible combinations of those.
@@ -72,8 +73,10 @@ class CachedEncoderList(object):
Otherwise, create one.
"""
if not cls._instance:
- cls._instance = super(CachedEncoderList, cls).__new__(cls, *args, **kwargs)
- Gst.Registry.get().connect("feature-added", cls._instance._registryFeatureAddedCb)
+ cls._instance = super(
+ CachedEncoderList, cls).__new__(cls, *args, **kwargs)
+ Gst.Registry.get().connect(
+ "feature-added", cls._instance._registryFeatureAddedCb)
cls._instance._buildEncoders()
cls._instance._buildCombinations()
return cls._instance
@@ -81,8 +84,9 @@ class CachedEncoderList(object):
def _buildEncoders(self):
self.aencoders = []
self.vencoders = []
- self.muxers = Gst.ElementFactory.list_get_elements(Gst.ELEMENT_FACTORY_TYPE_MUXER,
- Gst.Rank.SECONDARY)
+ self.muxers = Gst.ElementFactory.list_get_elements(
+ Gst.ELEMENT_FACTORY_TYPE_MUXER,
+ Gst.Rank.SECONDARY)
for fact in Gst.ElementFactory.list_get_elements(
Gst.ELEMENT_FACTORY_TYPE_ENCODER, Gst.Rank.SECONDARY):
@@ -103,8 +107,10 @@ class CachedEncoderList(object):
# only include muxers with audio and video
if aencs and vencs:
- self.audio_combination[mux] = sorted(aencs, key=lambda x: - x.get_rank())
- self.video_combination[mux] = sorted(vencs, key=lambda x: - x.get_rank())
+ self.audio_combination[mux] = sorted(
+ aencs, key=lambda x: - x.get_rank())
+ self.video_combination[mux] = sorted(
+ vencs, key=lambda x: - x.get_rank())
else:
useless_muxers.add(muxer)
@@ -116,7 +122,7 @@ class CachedEncoderList(object):
res = []
if muxsinkcaps == []:
muxsinkcaps = [x.get_caps() for x in muxer.get_static_pad_templates()
- if x.direction == Gst.PadDirection.SINK]
+ if x.direction == Gst.PadDirection.SINK]
for encoder in encoders:
for tpl in encoder.get_static_pad_templates():
if tpl.direction == Gst.PadDirection.SRC:
@@ -161,9 +167,9 @@ def beautify_factoryname(factory):
# only replace lowercase versions of "format", "video", "audio"
# otherwise they might be part of a trademark name
words_to_remove = ["Muxer", "muxer", "Encoder", "encoder",
- "format", "video", "audio", "instead",
- # Incorrect naming for Sorenson Spark:
- "Flash Video (FLV) /", ]
+ "format", "video", "audio", "instead",
+ # Incorrect naming for Sorenson Spark:
+ "Flash Video (FLV) /", ]
words_to_replace = [["version ", "v"], ["Microsoft", "MS"], ]
name = factory.get_longname()
for word in words_to_remove:
@@ -235,24 +241,29 @@ class RenderingProgressDialog(GObject.Object):
self.app = app
self.main_render_dialog = parent
self.builder = Gtk.Builder()
- self.builder.add_from_file(os.path.join(configure.get_ui_dir(), "renderingprogress.ui"))
+ self.builder.add_from_file(
+ os.path.join(configure.get_ui_dir(), "renderingprogress.ui"))
self.builder.connect_signals(self)
self.window = self.builder.get_object("render-progress")
self.table1 = self.builder.get_object("table1")
self.progressbar = self.builder.get_object("progressbar")
self.play_pause_button = self.builder.get_object("play_pause_button")
- self.play_rendered_file_button = self.builder.get_object("play_rendered_file_button")
+ self.play_rendered_file_button = self.builder.get_object(
+ "play_rendered_file_button")
self.close_button = self.builder.get_object("close_button")
self.cancel_button = self.builder.get_object("cancel_button")
- self._filesize_est_label = self.builder.get_object("estimated_filesize_label")
- self._filesize_est_value_label = self.builder.get_object("estimated_filesize_value_label")
+ self._filesize_est_label = self.builder.get_object(
+ "estimated_filesize_label")
+ self._filesize_est_value_label = self.builder.get_object(
+ "estimated_filesize_value_label")
# Parent the dialog with mainwindow, since renderingdialog is hidden.
# It allows this dialog to properly minimize together with mainwindow
self.window.set_transient_for(self.app.gui)
# UI widgets
- self.window.set_icon_from_file(configure.get_pixmap_dir() + "/pitivi-render-16.png")
+ self.window.set_icon_from_file(
+ configure.get_pixmap_dir() + "/pitivi-render-16.png")
# We will only show the close/play buttons when the render is done:
self.play_rendered_file_button.hide()
@@ -260,7 +271,8 @@ class RenderingProgressDialog(GObject.Object):
def updatePosition(self, fraction):
self.progressbar.set_fraction(fraction)
- self.window.set_title(_("Rendering — %d%% complete") % int(100 * fraction))
+ self.window.set_title(
+ _("Rendering — %d%% complete") % int(100 * fraction))
def updateProgressbarETA(self, time_estimation):
# Translators: this string indicates the estimated time
@@ -301,6 +313,7 @@ class RenderingProgressDialog(GObject.Object):
class RenderDialog(Loggable):
+
"""Render dialog box.
@ivar preferred_aencoder: The last audio encoder selected by the user.
@@ -365,13 +378,15 @@ class RenderDialog(Loggable):
self._displayRenderSettings()
self.window.connect("delete-event", self._deleteEventCb)
- self.project.connect("rendering-settings-changed", self._settingsChanged)
+ self.project.connect(
+ "rendering-settings-changed", self._settingsChanged)
# Monitor changes
self.wg = RippleUpdateGroup()
self.wg.addVertex(self.frame_rate_combo, signal="changed")
- self.wg.addVertex(self.save_render_preset_button, update_func=self._updateRenderSaveButton)
+ self.wg.addVertex(
+ self.save_render_preset_button, update_func=self._updateRenderSaveButton)
self.wg.addVertex(self.channels_combo, signal="changed")
self.wg.addVertex(self.sample_rate_combo, signal="changed")
self.wg.addVertex(self.muxercombobox, signal="changed")
@@ -386,21 +401,26 @@ class RenderDialog(Loggable):
self._updateRenderPresetButtons)
self.wg.addEdge(self.frame_rate_combo, self.save_render_preset_button)
- self.wg.addEdge(self.audio_encoder_combo, self.save_render_preset_button)
- self.wg.addEdge(self.video_encoder_combo, self.save_render_preset_button)
+ self.wg.addEdge(
+ self.audio_encoder_combo, self.save_render_preset_button)
+ self.wg.addEdge(
+ self.video_encoder_combo, self.save_render_preset_button)
self.wg.addEdge(self.muxercombobox, self.save_render_preset_button)
self.wg.addEdge(self.channels_combo, self.save_render_preset_button)
self.wg.addEdge(self.sample_rate_combo, self.save_render_preset_button)
- self._infobarForPresetManager = {self.render_presets: self.render_preset_infobar}
+ self._infobarForPresetManager = {
+ self.render_presets: self.render_preset_infobar}
# Bind widgets to RenderPresetsManager
self.bindCombo(self.render_presets, "channels", self.channels_combo)
- self.bindCombo(self.render_presets, "sample-rate", self.sample_rate_combo)
+ self.bindCombo(
+ self.render_presets, "sample-rate", self.sample_rate_combo)
self.bindCombo(self.render_presets, "acodec", self.audio_encoder_combo)
self.bindCombo(self.render_presets, "vcodec", self.video_encoder_combo)
self.bindCombo(self.render_presets, "container", self.muxercombobox)
- self.bindCombo(self.render_presets, "frame-rate", self.frame_rate_combo)
+ self.bindCombo(
+ self.render_presets, "frame-rate", self.frame_rate_combo)
self.bindHeight(self.render_presets)
self.bindWidth(self.render_presets)
@@ -422,33 +442,33 @@ class RenderDialog(Loggable):
def bindCombo(self, mgr, name, widget):
if name == "container":
mgr.bindWidget(name,
- lambda x: self.muxer_setter(widget, x),
- lambda: get_combo_value(widget).get_name())
+ lambda x: self.muxer_setter(widget, x),
+ lambda: get_combo_value(widget).get_name())
elif name == "acodec":
mgr.bindWidget(name,
- lambda x: self.acodec_setter(widget, x),
- lambda: get_combo_value(widget).get_name())
+ lambda x: self.acodec_setter(widget, x),
+ lambda: get_combo_value(widget).get_name())
elif name == "vcodec":
mgr.bindWidget(name,
- lambda x: self.vcodec_setter(widget, x),
- lambda: get_combo_value(widget).get_name())
+ lambda x: self.vcodec_setter(widget, x),
+ lambda: get_combo_value(widget).get_name())
elif name == "sample-rate":
mgr.bindWidget(name,
- lambda x: self.sample_rate_setter(widget, x),
- lambda: get_combo_value(widget))
+ lambda x: self.sample_rate_setter(widget, x),
+ lambda: get_combo_value(widget))
elif name == "channels":
mgr.bindWidget(name,
- lambda x: self.channels_setter(widget, x),
- lambda: get_combo_value(widget))
+ lambda x: self.channels_setter(widget, x),
+ lambda: get_combo_value(widget))
elif name == "frame-rate":
mgr.bindWidget(name,
- lambda x: self.framerate_setter(widget, x),
- lambda: get_combo_value(widget))
+ lambda x: self.framerate_setter(widget, x),
+ lambda: get_combo_value(widget))
def muxer_setter(self, widget, value):
set_combo_value(widget, Gst.ElementFactory.find(value))
@@ -490,13 +510,13 @@ class RenderDialog(Loggable):
def bindHeight(self, mgr):
mgr.bindWidget("height",
- lambda x: setattr(self.project, "videoheight", x),
- lambda: 0)
+ lambda x: setattr(self.project, "videoheight", x),
+ lambda: 0)
def bindWidth(self, mgr):
mgr.bindWidget("width",
- lambda x: setattr(self.project, "videowidth", x),
- lambda: 0)
+ lambda x: setattr(self.project, "videowidth", x),
+ lambda: 0)
def _fillPresetsTreeview(self, treeview, mgr, update_buttons_func):
"""Set up the specified treeview to display the specified presets.
@@ -516,11 +536,13 @@ class RenderDialog(Loggable):
treeview.props.headers_visible = False
model = mgr.getModel()
treeview.set_model(model)
- model.connect("row-inserted", self._newPresetCb, column, renderer, treeview)
+ model.connect(
+ "row-inserted", self._newPresetCb, column, renderer, treeview)
renderer.connect("edited", self._presetNameEditedCb, mgr)
- renderer.connect("editing-started", self._presetNameEditingStartedCb, mgr)
+ renderer.connect(
+ "editing-started", self._presetNameEditingStartedCb, mgr)
treeview.get_selection().connect("changed", self._presetChangedCb,
- mgr, update_buttons_func)
+ mgr, update_buttons_func)
treeview.connect("focus-out-event", self._treeviewDefocusedCb, mgr)
def _newPresetCb(self, unused_model, path, unused_iter_, column, renderer, treeview):
@@ -594,7 +616,7 @@ class RenderDialog(Loggable):
"vcodec": get_combo_value(self.video_encoder_combo).get_name(),
"container": get_combo_value(self.muxercombobox).get_name(),
"frame-rate": Gst.Fraction(int(get_combo_value(self.frame_rate_combo).num),
- int(get_combo_value(self.frame_rate_combo).denom)),
+ int(get_combo_value(self.frame_rate_combo).denom)),
"height": 0,
"width": 0})
@@ -633,16 +655,21 @@ class RenderDialog(Loggable):
def _createUi(self):
builder = Gtk.Builder()
- builder.add_from_file(os.path.join(configure.get_ui_dir(), "renderingdialog.ui"))
+ builder.add_from_file(
+ os.path.join(configure.get_ui_dir(), "renderingdialog.ui"))
builder.connect_signals(self)
self.window = builder.get_object("render-dialog")
self.selected_only_button = builder.get_object("selected_only_button")
- self.video_output_checkbutton = builder.get_object("video_output_checkbutton")
- self.audio_output_checkbutton = builder.get_object("audio_output_checkbutton")
+ self.video_output_checkbutton = builder.get_object(
+ "video_output_checkbutton")
+ self.audio_output_checkbutton = builder.get_object(
+ "audio_output_checkbutton")
self.render_button = builder.get_object("render_button")
- self.video_settings_button = builder.get_object("video_settings_button")
- self.audio_settings_button = builder.get_object("audio_settings_button")
+ self.video_settings_button = builder.get_object(
+ "video_settings_button")
+ self.audio_settings_button = builder.get_object(
+ "audio_settings_button")
self.frame_rate_combo = builder.get_object("frame_rate_combo")
self.scale_spinbutton = builder.get_object("scale_spinbutton")
self.channels_combo = builder.get_object("channels_combo")
@@ -653,10 +680,14 @@ class RenderDialog(Loggable):
self.filebutton = builder.get_object("filebutton")
self.fileentry = builder.get_object("fileentry")
self.resolution_label = builder.get_object("resolution_label")
- self.render_preset_treeview = builder.get_object("render_preset_treeview")
- self.save_render_preset_button = builder.get_object("save_render_preset_button")
- self.remove_render_preset_button = builder.get_object("remove_render_preset_button")
- self.render_preset_infobar = builder.get_object("render-preset-infobar")
+ self.render_preset_treeview = builder.get_object(
+ "render_preset_treeview")
+ self.save_render_preset_button = builder.get_object(
+ "save_render_preset_button")
+ self.remove_render_preset_button = builder.get_object(
+ "remove_render_preset_button")
+ self.render_preset_infobar = builder.get_object(
+ "render-preset-infobar")
icon = os.path.join(configure.get_pixmap_dir(), "pitivi-render-16.png")
self.window.set_icon_from_file(icon)
@@ -664,7 +695,8 @@ class RenderDialog(Loggable):
# Set the shading style in the toolbar below presets
presets_toolbar = builder.get_object("render_presets_toolbar")
- presets_toolbar.get_style_context().add_class(Gtk.STYLE_CLASS_INLINE_TOOLBAR)
+ presets_toolbar.get_style_context().add_class(
+ Gtk.STYLE_CLASS_INLINE_TOOLBAR)
def _settingsChanged(self, unused_project, unused_key, unused_value):
self.updateResolution()
@@ -694,7 +726,7 @@ class RenderDialog(Loggable):
# Muxer settings
# note: this will trigger an update of the codec comboboxes
set_combo_value(self.muxercombobox,
- Gst.ElementFactory.find(self.project.muxer))
+ Gst.ElementFactory.find(self.project.muxer))
def _checkForExistingFile(self, *unused_args):
"""
@@ -732,7 +764,8 @@ class RenderDialog(Loggable):
current_filesize = os.stat(path_from_uri(self.outfile)).st_size
length = self.app.project_manager.current_project.timeline.props.duration
- estimated_size = float(current_filesize * float(length) / self.current_position)
+ estimated_size = float(
+ current_filesize * float(length) / self.current_position)
# Now let's make it human-readable (instead of octets).
# If it's in the giga range (10⁹) instead of mega (10⁶), use 2 decimals
if estimated_size > 10e8:
@@ -756,14 +789,18 @@ class RenderDialog(Loggable):
def updateAvailableEncoders(self):
"""Update the encoder comboboxes to show the available encoders."""
encoders = CachedEncoderList()
- vencoder_model = factorylist(encoders.video_combination[self.project.muxer])
+ vencoder_model = factorylist(
+ encoders.video_combination[self.project.muxer])
self.video_encoder_combo.set_model(vencoder_model)
- aencoder_model = factorylist(encoders.audio_combination[self.project.muxer])
+ aencoder_model = factorylist(
+ encoders.audio_combination[self.project.muxer])
self.audio_encoder_combo.set_model(aencoder_model)
- self._updateEncoderCombo(self.video_encoder_combo, self.preferred_vencoder)
- self._updateEncoderCombo(self.audio_encoder_combo, self.preferred_aencoder)
+ self._updateEncoderCombo(
+ self.video_encoder_combo, self.preferred_vencoder)
+ self._updateEncoderCombo(
+ self.audio_encoder_combo, self.preferred_aencoder)
def _updateEncoderCombo(self, encoder_combo, preferred_encoder):
"""Select the specified encoder for the specified encoder combo."""
@@ -788,19 +825,20 @@ class RenderDialog(Loggable):
"""
properties = getattr(self.project, settings_attr)
self.dialog = GstElementSettingsDialog(factory, properties=properties,
- parent_window=self.window, isControllable=False)
- self.dialog.ok_btn.connect("clicked", self._okButtonClickedCb, settings_attr)
+ parent_window=self.window, isControllable=False)
+ self.dialog.ok_btn.connect(
+ "clicked", self._okButtonClickedCb, settings_attr)
def _showRenderErrorDialog(self, error, details):
primary_message = _("Sorry, something didn’t work right.")
secondary_message = _("An error occured while trying to render your "
- "project. You might want to check our troubleshooting guide or "
- "file a bug report. See the details below for some basic "
- "information that may help identify the problem.")
+ "project. You might want to check our troubleshooting guide or "
+ "file a bug report. See the details below for some basic "
+ "information that may help identify the problem.")
dialog = Gtk.MessageDialog(transient_for=self.window, modal=True,
- message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK,
- text=primary_message)
+ message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK,
+ text=primary_message)
dialog.set_property("secondary-text", secondary_message)
expander = Gtk.Expander()
@@ -820,7 +858,8 @@ class RenderDialog(Loggable):
# FIXME: https://github.com/pitivi/gst-editing-services/issues/23
self._pipeline.set_mode(GES.PipelineFlags.RENDER)
encodebin = self._pipeline.get_by_name("internal-encodebin")
- self._gstSigId[encodebin] = encodebin.connect("element-added", self._elementAddedCb)
+ self._gstSigId[encodebin] = encodebin.connect(
+ "element-added", self._elementAddedCb)
self._pipeline.set_state(Gst.State.PLAYING)
self._is_rendering = True
self._time_started = time.time()
@@ -841,12 +880,15 @@ class RenderDialog(Loggable):
self._pipeline.set_mode(GES.PipelineFlags.FULL_PREVIEW)
def _pauseRender(self, unused_progress):
- self._rendering_is_paused = self.progress.play_pause_button.get_active()
+ self._rendering_is_paused = self.progress.play_pause_button.get_active(
+ )
if self._rendering_is_paused:
self._last_timestamp_when_pausing = time.time()
else:
- self._time_spent_paused += time.time() - self._last_timestamp_when_pausing
- self.debug("Resuming render after %d seconds in pause", self._time_spent_paused)
+ self._time_spent_paused += time.time(
+ ) - self._last_timestamp_when_pausing
+ self.debug(
+ "Resuming render after %d seconds in pause", self._time_spent_paused)
self.app.project_manager.current_project.pipeline.togglePlayback()
def _destroyProgressWindow(self):
@@ -860,7 +902,8 @@ class RenderDialog(Loggable):
obj.disconnect(id)
self._gstSigId = {}
try:
- self.app.project_manager.current_project.pipeline.disconnect_by_func(self._updatePositionCb)
+ self.app.project_manager.current_project.pipeline.disconnect_by_func(
+ self._updatePositionCb)
except TypeError:
# The render was successful, so this was already disconnected
pass
@@ -891,7 +934,8 @@ class RenderDialog(Loggable):
self.outfile = os.path.join(self.filebutton.get_uri(),
self.fileentry.get_text())
self.progress = RenderingProgressDialog(self.app, self)
- self.window.hide() # Hide the rendering settings dialog while rendering
+ # Hide the rendering settings dialog while rendering
+ self.window.hide()
encoder_string = self.project.vencoder
try:
@@ -906,12 +950,14 @@ class RenderDialog(Loggable):
caps = Gst.Caps.from_string(struct.get_caps().to_string())
fixed = caps.fixate()
fmt = fixed.get_structure(0).get_value("format")
- self.project.video_profile.get_restriction()[0]["format"] = fmt
+ self.project.video_profile.get_restriction()[
+ 0]["format"] = fmt
self._factory_formats[encoder_string] = fmt
break
self.project.set_rendering(True)
- self._pipeline.set_render_settings(self.outfile, self.project.container_profile)
+ self._pipeline.set_render_settings(
+ self.outfile, self.project.container_profile)
self.startAction()
self.progress.window.show()
self.progress.connect("cancel", self._cancelRender)
@@ -919,10 +965,12 @@ class RenderDialog(Loggable):
bus = self._pipeline.get_bus()
bus.add_signal_watch()
self._gstSigId[bus] = bus.connect('message', self._busMessageCb)
- self.app.project_manager.current_project.pipeline.connect("position", self._updatePositionCb)
+ self.app.project_manager.current_project.pipeline.connect(
+ "position", self._updatePositionCb)
# Force writing the config now, or the path will be reset
# if the user opens the rendering dialog again
- self.app.settings.lastExportFolder = self.filebutton.get_current_folder()
+ self.app.settings.lastExportFolder = self.filebutton.get_current_folder(
+ )
self.app.settings.storeSettings()
def _closeButtonClickedCb(self, unused_button):
@@ -936,14 +984,16 @@ class RenderDialog(Loggable):
def _containerContextHelpClickedCb(self, unused_button):
show_user_manual("codecscontainers")
- # -- Periodic (timer) callbacks --
+ # Periodic (timer) callbacks
def _updateTimeEstimateCb(self):
if self._rendering_is_paused:
return True # Do nothing until we resume rendering
elif self._is_rendering:
- timediff = time.time() - self._time_started - self._time_spent_paused
+ timediff = time.time() - \
+ self._time_started - self._time_spent_paused
length = self.app.project_manager.current_project.timeline.props.duration
- totaltime = (timediff * float(length) / float(self.current_position)) - timediff
+ totaltime = (timediff * float(length) /
+ float(self.current_position)) - timediff
time_estimate = beautify_ETA(int(totaltime * Gst.SECOND))
if time_estimate:
self.progress.updateProgressbarETA(time_estimate)
@@ -966,7 +1016,7 @@ class RenderDialog(Loggable):
self._filesizeEstimateTimer = None
return False # Stop the timer
- # -- GStreamer callbacks --
+ # GStreamer callbacks
def _busMessageCb(self, unused_bus, message):
if message.type == Gst.MessageType.EOS: # Render complete
self.debug("got EOS message, render complete")
@@ -975,8 +1025,10 @@ class RenderDialog(Loggable):
self.progress.window.set_title(_("Render complete"))
self.progress.setFilesizeEstimate(None)
if not self.progress.window.is_active():
- notification = _('"%s" has finished rendering.' % self.fileentry.get_text())
- self.notification = self.app.system.desktopMessage(_("Render complete"), notification,
"pitivi")
+ notification = _(
+ '"%s" has finished rendering.' % self.fileentry.get_text())
+ self.notification = self.app.system.desktopMessage(
+ _("Render complete"), notification, "pitivi")
self._maybePlayFinishedSound()
self.progress.play_rendered_file_button.show()
self.progress.close_button.show()
@@ -996,7 +1048,8 @@ class RenderDialog(Loggable):
state_really_changed = pending == Gst.State.VOID_PENDING
if state_really_changed:
if state == Gst.State.PLAYING:
- self.debug("Rendering started/resumed, inhibiting sleep")
+ self.debug(
+ "Rendering started/resumed, inhibiting sleep")
self.system.inhibitSleep(RenderDialog.INHIBIT_REASON)
else:
self.system.uninhibitSleep(RenderDialog.INHIBIT_REASON)
@@ -1021,11 +1074,13 @@ class RenderDialog(Loggable):
if timediff < 6:
self.progress.progressbar.set_text(_("Estimating..."))
else:
- self._timeEstimateTimer = GLib.timeout_add_seconds(3, self._updateTimeEstimateCb)
+ self._timeEstimateTimer = GLib.timeout_add_seconds(
+ 3, self._updateTimeEstimateCb)
# Filesize is trickier and needs more time to be meaningful:
if not self._filesizeEstimateTimer and (fraction > 0.33 or timediff > 180):
- self._filesizeEstimateTimer = GLib.timeout_add_seconds(5, self._updateFilesizeEstimateCb)
+ self._filesizeEstimateTimer = GLib.timeout_add_seconds(
+ 5, self._updateFilesizeEstimateCb)
def _elementAddedCb(self, unused_bin, element):
"""
@@ -1043,7 +1098,7 @@ class RenderDialog(Loggable):
element.set_property(propname, value)
self.debug("Setting %s to %s", propname, value)
- # -- Settings changed callbacks --
+ # Settings changed callbacks
def _scaleSpinbuttonChangedCb(self, unused_button):
render_scale = self.scale_spinbutton.get_value()
self.project.render_scale = render_scale
diff --git a/pitivi/settings.py b/pitivi/settings.py
index e3a5af4..84a524f 100644
--- a/pitivi/settings.py
+++ b/pitivi/settings.py
@@ -99,6 +99,7 @@ class ConfigError(Exception):
class Notification(object):
+
"""A descriptor to help with the implementation of signals"""
def __init__(self, attrname):
@@ -118,6 +119,7 @@ class Notification(object):
class GlobalSettings(GObject.Object):
+
"""
Pitivi app settings.
@@ -289,19 +291,21 @@ class GlobalSettings(GObject.Object):
@type notify: C{boolean}
"""
if section and section not in cls.options:
- raise ConfigError("You must add the section \"%s\" first." % section)
+ raise ConfigError(
+ "You must add the section \"%s\" first." % section)
if key and not section:
- raise ConfigError("You must specify a section for key \"%s\"" % key)
+ raise ConfigError(
+ "You must specify a section for key \"%s\"" % key)
if section and key in cls.options[section]:
raise ConfigError("Option \"%s\" is already in use.")
if hasattr(cls, attrname):
raise ConfigError("Settings attribute \"%s\" is already in use.")
if environment and environment in cls.environment:
raise ConfigError("Settings environment varaible \"%s\" is"
- "already in use.")
+ "already in use.")
if not type_ and default is None:
raise ConfigError("Settings attribute \"%s\" has must have a"
- " type or a default." % attrname)
+ " type or a default." % attrname)
if not type_:
type_ = type(default)
if notify:
diff --git a/pitivi/tabsmanager.py b/pitivi/tabsmanager.py
index 958fc59..cebe63f 100644
--- a/pitivi/tabsmanager.py
+++ b/pitivi/tabsmanager.py
@@ -26,9 +26,11 @@ from pitivi.settings import GlobalSettings
class BaseTabs(Gtk.Notebook):
+
"""
@type app: Pitivi
"""
+
def __init__(self, app):
Gtk.Notebook.__init__(self)
self.set_border_width(SPACING)
@@ -48,7 +50,8 @@ class BaseTabs(Gtk.Notebook):
docked = getattr(self.settings, child_name + "docked")
if docked is False:
self.createWindow(child, created_by_signal=False)
- # Wait till the tab or floating window is ready before showing contents:
+ # Wait till the tab or floating window is ready before showing
+ # contents:
child.show()
def _set_child_properties(self, child, label):
@@ -58,7 +61,7 @@ class BaseTabs(Gtk.Notebook):
label.props.xalign = 0.0
def _detachedComponentWindowDestroyCb(self, window, child,
- original_position, child_name):
+ original_position, child_name):
notebook = window.get_child()
position = notebook.page_num(child)
notebook.remove_page(position)
@@ -104,9 +107,12 @@ class BaseTabs(Gtk.Notebook):
window.add(notebook)
window.show_all()
window.move(x, y)
- window.connect("configure-event", self._detachedComponentWindowConfiguredCb, child_name)
- window.connect("destroy", self._detachedComponentWindowDestroyCb, child,
- original_position, child_name)
+ window.connect(
+ "configure-event", self._detachedComponentWindowConfiguredCb,
+ child_name)
+ window.connect(
+ "destroy", self._detachedComponentWindowDestroyCb, child,
+ original_position, child_name)
if not created_by_signal:
# Delete the tab from the original notebook (since it was not
@@ -137,24 +143,24 @@ class BaseTabs(Gtk.Notebook):
"""
GlobalSettings.addConfigSection(child_name)
GlobalSettings.addConfigOption(child_name + "docked",
- section=child_name,
- key="docked",
- default=True)
+ section=child_name,
+ key="docked",
+ default=True)
GlobalSettings.addConfigOption(child_name + "width",
- section=child_name,
- key="width",
- default=320)
+ section=child_name,
+ key="width",
+ default=320)
GlobalSettings.addConfigOption(child_name + "height",
- section=child_name,
- key="height",
- default=400)
+ section=child_name,
+ key="height",
+ default=400)
GlobalSettings.addConfigOption(child_name + "x",
- section=child_name,
- key="x",
- default=0)
+ section=child_name,
+ key="x",
+ default=0)
GlobalSettings.addConfigOption(child_name + "y",
- section=child_name,
- key="y",
- default=0)
+ section=child_name,
+ key="y",
+ default=0)
GlobalSettings.readSettingSectionFromFile(self.settings, child_name)
diff --git a/pitivi/timeline/controls.py b/pitivi/timeline/controls.py
index 1f2f4c8..e443bad 100644
--- a/pitivi/timeline/controls.py
+++ b/pitivi/timeline/controls.py
@@ -29,6 +29,7 @@ from pitivi.utils.ui import EXPANDED_SIZE, SPACING, CONTROL_WIDTH
class ControlActor(GtkClutter.Actor):
+
def __init__(self, container, widget, layer, is_audio):
GtkClutter.Actor.__init__(self)
@@ -104,7 +105,8 @@ class ControlContainer(Clutter.ScrollActor):
def _setTrackControlPosition(self, control):
y = control.layer.get_priority() * (EXPANDED_SIZE + SPACING) + SPACING
if control.is_audio:
- y += len(self.timeline.bTimeline.get_layers()) * (EXPANDED_SIZE + SPACING)
+ y += len(self.timeline.bTimeline.get_layers()) * \
+ (EXPANDED_SIZE + SPACING)
control.set_position(0, y)
@@ -124,7 +126,8 @@ class ControlContainer(Clutter.ScrollActor):
movedLayer = control.layer
priority = movedLayer.get_priority()
- movedLayer.props.priority = 999 # Don't put 1000 layers or this breaks !
+ # Don't put 1000 layers or this breaks !
+ movedLayer.props.priority = 999
if priority > target:
for layer in self.timeline.bTimeline.get_layers():
@@ -172,5 +175,6 @@ class ControlContainer(Clutter.ScrollActor):
self.remove_child(control)
self.trackControls.remove(control.widget)
- self.controlActors = [elem for elem in self.controlActors if elem.layer != layer]
+ self.controlActors = [
+ elem for elem in self.controlActors if elem.layer != layer]
self._reorderLayerActors()
diff --git a/pitivi/timeline/elements.py b/pitivi/timeline/elements.py
index 7e4b41b..4d72fa3 100644
--- a/pitivi/timeline/elements.py
+++ b/pitivi/timeline/elements.py
@@ -58,12 +58,14 @@ DRAG_RIGHT_HANDLEBAR_CURSOR = Gdk.Cursor.new(Gdk.CursorType.RIGHT_SIDE)
class Ghostclip(Clutter.Actor):
+
"""
The concept of a ghostclip is to represent future actions without
actually moving GESClips. They are created when the user wants
to change a clip of layer, and when the user does a drag and drop
from the media library.
"""
+
def __init__(self, track_type, bElement=None):
Clutter.Actor.__init__(self)
self.track_type = track_type
@@ -112,7 +114,8 @@ class Ghostclip(Clutter.Actor):
# We would be moving to an existing layer.
elif self.priority < self.nbrLayers:
self.set_size(self.props.width, EXPANDED_SIZE)
- self.props.y = self.priority * (EXPANDED_SIZE + SPACING) + SPACING
+ self.props.y = self.priority * \
+ (EXPANDED_SIZE + SPACING) + SPACING
if self.track_type == GES.TrackType.AUDIO:
self.props.y += self.nbrLayers * (EXPANDED_SIZE + SPACING)
self.props.visible = True
@@ -126,6 +129,7 @@ class Ghostclip(Clutter.Actor):
class TrimHandle(Clutter.Texture):
+
def __init__(self, timelineElement, isLeft):
Clutter.Texture.__init__(self)
@@ -133,7 +137,8 @@ class TrimHandle(Clutter.Texture):
self.timelineElement = weakref.proxy(timelineElement)
self.dragAction = Clutter.DragAction()
- self.set_from_file(os.path.join(configure.get_pixmap_dir(), "trimbar-normal.png"))
+ self.set_from_file(
+ os.path.join(configure.get_pixmap_dir(), "trimbar-normal.png"))
self.set_size(-1, EXPANDED_SIZE)
self.hide()
self.set_reactive(True)
@@ -155,7 +160,7 @@ class TrimHandle(Clutter.Texture):
self.timelineElement.disconnect_by_func(self._elementEnterEventCb)
self.timelineElement.disconnect_by_func(self._elementLeaveEventCb)
- #Callbacks
+ # Callbacks
def _enterEventCb(self, unused_actor, unused_event):
self.timelineElement.set_reactive(False)
@@ -163,24 +168,30 @@ class TrimHandle(Clutter.Texture):
elem.set_reactive(False)
self.set_reactive(True)
- self.set_from_file(os.path.join(configure.get_pixmap_dir(), "trimbar-focused.png"))
+ self.set_from_file(
+ os.path.join(configure.get_pixmap_dir(), "trimbar-focused.png"))
if self.isLeft:
-
self.timelineElement.timeline._container.embed.get_window().set_cursor(DRAG_LEFT_HANDLEBAR_CURSOR)
+ self.timelineElement.timeline._container.embed.get_window().set_cursor(
+ DRAG_LEFT_HANDLEBAR_CURSOR)
else:
-
self.timelineElement.timeline._container.embed.get_window().set_cursor(DRAG_RIGHT_HANDLEBAR_CURSOR)
+ self.timelineElement.timeline._container.embed.get_window().set_cursor(
+ DRAG_RIGHT_HANDLEBAR_CURSOR)
def _leaveEventCb(self, unused_actor, event):
self.timelineElement.set_reactive(True)
children = self.timelineElement.get_children()
- other_actor = self.timelineElement.timeline._container.stage.get_actor_at_pos(Clutter.PickMode.ALL,
event.x, event.y)
+ other_actor = self.timelineElement.timeline._container.stage.get_actor_at_pos(
+ Clutter.PickMode.ALL, event.x, event.y)
if other_actor not in children:
self.timelineElement.hideHandles()
for elem in children:
elem.set_reactive(True)
- self.set_from_file(os.path.join(configure.get_pixmap_dir(), "trimbar-normal.png"))
- self.timelineElement.timeline._container.embed.get_window().set_cursor(NORMAL_CURSOR)
+ self.set_from_file(
+ os.path.join(configure.get_pixmap_dir(), "trimbar-normal.png"))
+ self.timelineElement.timeline._container.embed.get_window().set_cursor(
+ NORMAL_CURSOR)
def _elementEnterEventCb(self, unused_actor, unused_event):
self.show()
@@ -196,7 +207,8 @@ class TrimHandle(Clutter.Texture):
if self.isLeft:
edge = GES.Edge.EDGE_START
- self._dragBeginStart = self.timelineElement.bElement.get_parent().get_start()
+ self._dragBeginStart = self.timelineElement.bElement.get_parent(
+ ).get_start()
else:
edge = GES.Edge.EDGE_END
self._dragBeginStart = self.timelineElement.bElement.get_parent().get_duration() + \
@@ -218,8 +230,10 @@ class TrimHandle(Clutter.Texture):
delta_x = coords[0] - self.dragBeginStartX
new_start = self._dragBeginStart + Zoomable.pixelToNs(delta_x)
- self._context.setMode(self.timelineElement.timeline._container.getEditionMode(isAHandle=True))
- self._context.editTo(new_start,
self.timelineElement.bElement.get_parent().get_layer().get_priority())
+ self._context.setMode(
+ self.timelineElement.timeline._container.getEditionMode(isAHandle=True))
+ self._context.editTo(
+ new_start, self.timelineElement.bElement.get_parent().get_layer().get_priority())
return False
def _dragEndCb(self, unused_action, unused_actor, unused_event_x, unused_event_y, unused_modifiers):
@@ -230,19 +244,24 @@ class TrimHandle(Clutter.Texture):
for elem in self.timelineElement.get_children():
elem.set_reactive(True)
- self.set_from_file(os.path.join(configure.get_pixmap_dir(), "trimbar-normal.png"))
- self.timelineElement.timeline._container.embed.get_window().set_cursor(NORMAL_CURSOR)
+ self.set_from_file(
+ os.path.join(configure.get_pixmap_dir(), "trimbar-normal.png"))
+ self.timelineElement.timeline._container.embed.get_window().set_cursor(
+ NORMAL_CURSOR)
def clipTrimCb(self, unused_TrimStartContext, tl_obj, position):
# While a clip is being trimmed, ask the viewer to preview it
- self.timelineElement.timeline._container.app.gui.viewer.clipTrimPreview(tl_obj, position)
+ self.timelineElement.timeline._container.app.gui.viewer.clipTrimPreview(
+ tl_obj, position)
def clipTrimFinishedCb(self, unused_TrimStartContext):
# When a clip has finished trimming, tell the viewer to reset itself
- self.timelineElement.timeline._container.app.gui.viewer.clipTrimPreviewFinished()
+ self.timelineElement.timeline._container.app.gui.viewer.clipTrimPreviewFinished(
+ )
class TimelineElement(Clutter.Actor, Zoomable):
+
"""
@ivar bElement: the backend element.
@type bElement: GES.TrackElement
@@ -323,7 +342,8 @@ class TimelineElement(Clutter.Actor, Zoomable):
self.props.height = height
self.preview.set_size(max(width - 2, 1), max(height - 2, 1))
if self.rightHandle:
- self.rightHandle.set_position(width - self.rightHandle.props.width, 0)
+ self.rightHandle.set_position(
+ width - self.rightHandle.props.width, 0)
if ease:
self.background.restore_easing_state()
@@ -339,7 +359,8 @@ class TimelineElement(Clutter.Actor, Zoomable):
def removeKeyframe(self, kf):
self.source.unset(kf.value.timestamp)
- self.keyframes = sorted(self.keyframes, key=lambda keyframe: keyframe.value.timestamp)
+ self.keyframes = sorted(
+ self.keyframes, key=lambda keyframe: keyframe.value.timestamp)
self.updateKeyframes()
def showKeyframes(self, element, propname, isDefault=False):
@@ -378,7 +399,8 @@ class TimelineElement(Clutter.Actor, Zoomable):
self.drawLines()
def setKeyframePosition(self, keyframe, value):
- x = self.nsToPixel(value.timestamp - self.bElement.props.in_point) - KEYFRAME_SIZE / 2
+ x = self.nsToPixel(
+ value.timestamp - self.bElement.props.in_point) - KEYFRAME_SIZE / 2
y = EXPANDED_SIZE - (value.value * EXPANDED_SIZE) - KEYFRAME_SIZE / 2
keyframe.set_position(x, y)
@@ -407,9 +429,11 @@ class TimelineElement(Clutter.Actor, Zoomable):
values = self.source.get_all()
if len(values) < 2 and self.bElement.props.duration > 0:
self.source.unset_all()
- val = float(self.prop.default_value) / (self.prop.maximum - self.prop.minimum)
+ val = float(self.prop.default_value) / \
+ (self.prop.maximum - self.prop.minimum)
self.source.set(self.bElement.props.in_point, val)
- self.source.set(self.bElement.props.duration + self.bElement.props.in_point, val)
+ self.source.set(
+ self.bElement.props.duration + self.bElement.props.in_point, val)
for keyframe in self.keyframes:
self.remove_child(keyframe)
@@ -486,7 +510,8 @@ class TimelineElement(Clutter.Actor, Zoomable):
self.lines.append(line)
self.insert_child_above(line, self._linesMarker)
- adj = self.nsToPixel(keyframe.value.timestamp - lastKeyframe.value.timestamp)
+ adj = self.nsToPixel(
+ keyframe.value.timestamp - lastKeyframe.value.timestamp)
opp = (lastKeyframe.value.value - keyframe.value.value) * EXPANDED_SIZE
hyp = math.sqrt(adj ** 2 + opp ** 2)
if hyp < 1:
@@ -497,8 +522,10 @@ class TimelineElement(Clutter.Actor, Zoomable):
line.props.width = hyp
line.props.height = KEYFRAME_SIZE
line.props.rotation_angle_z = math.degrees(math.asin(sinX))
- line.props.x = self.nsToPixel(lastKeyframe.value.timestamp - self.bElement.props.in_point)
- line.props.y = EXPANDED_SIZE - (EXPANDED_SIZE * lastKeyframe.value.value) - KEYFRAME_SIZE / 2
+ line.props.x = self.nsToPixel(
+ lastKeyframe.value.timestamp - self.bElement.props.in_point)
+ line.props.y = EXPANDED_SIZE - \
+ (EXPANDED_SIZE * lastKeyframe.value.value) - KEYFRAME_SIZE / 2
line.canvas.invalidate()
def _createGhostclip(self):
@@ -524,7 +551,8 @@ class TimelineElement(Clutter.Actor, Zoomable):
return previewer
if isinstance(self.bElement, GES.VideoUriSource):
return VideoPreviewer(self.bElement, self.timeline)
- # TODO: GES.AudioTransition, GES.VideoTransition, GES.ImageSource, GES.TitleSource
+ # TODO: GES.AudioTransition, GES.VideoTransition, GES.ImageSource,
+ # GES.TitleSource
return Clutter.Actor()
def _createMarquee(self):
@@ -540,7 +568,8 @@ class TimelineElement(Clutter.Actor, Zoomable):
self.dragAction.connect("drag-progress", self._dragProgressCb)
self.dragAction.connect("drag-begin", self._dragBeginCb)
self.dragAction.connect("drag-end", self._dragEndCb)
- self.bElement.selected.connect("selected-changed", self._selectedChangedCb)
+ self.bElement.selected.connect(
+ "selected-changed", self._selectedChangedCb)
self.bElement.connect("notify::duration", self._durationChangedCb)
self.bElement.connect("notify::in-point", self._inpointChangedCb)
# We gotta go low-level cause Clutter.ClickAction["clicked"]
@@ -592,6 +621,7 @@ class TimelineElement(Clutter.Actor, Zoomable):
class Gradient(Clutter.Actor):
+
def __init__(self, rb, gb, bb, re, ge, be):
"""
Creates a rectangle with a gradient. The first three parameters
@@ -618,9 +648,11 @@ class Gradient(Clutter.Actor):
class Line(Clutter.Actor):
+
"""
A cairo line used for keyframe curves.
"""
+
def __init__(self, timelineElement, keyframe, lastKeyframe):
Clutter.Actor.__init__(self)
self.timelineElement = weakref.proxy(timelineElement)
@@ -658,7 +690,8 @@ class Line(Clutter.Actor):
cr.paint()
cr.set_operator(cairo.OPERATOR_OVER)
- # The "height budget" to draw line components = the tallest component...
+ # The "height budget" to draw line components = the tallest
+ # component...
_max_height = KEYFRAME_SIZE
# While normally all three lines would have an equal height,
@@ -686,14 +719,16 @@ class Line(Clutter.Actor):
cr.stroke()
def transposeXY(self, x, y):
- x -= self.timelineElement.props.x + CONTROL_WIDTH - self.timelineElement.timeline._scroll_point.x
+ x -= self.timelineElement.props.x + CONTROL_WIDTH - \
+ self.timelineElement.timeline._scroll_point.x
x += Zoomable.nsToPixel(self.timelineElement.bElement.props.in_point)
y -= self.timelineElement.props.y
return x, y
def _ungrab(self):
self.timelineElement.set_reactive(True)
- self.timelineElement.timeline._container.embed.get_window().set_cursor(NORMAL_CURSOR)
+ self.timelineElement.timeline._container.embed.get_window().set_cursor(
+ NORMAL_CURSOR)
def _clickedCb(self, unused_actor, event):
if self.gotDragged:
@@ -716,7 +751,8 @@ class Line(Clutter.Actor):
def _enterEventCb(self, unused_actor, unused_event):
self.timelineElement.set_reactive(False)
- self.timelineElement.timeline._container.embed.get_window().set_cursor(DRAG_CURSOR)
+ self.timelineElement.timeline._container.embed.get_window().set_cursor(
+ DRAG_CURSOR)
def _leaveEventCb(self, unused_actor, unused_event):
self._ungrab()
@@ -750,6 +786,7 @@ class Line(Clutter.Actor):
class KeyframeMenu(GtkClutter.Actor):
+
def __init__(self, keyframe):
GtkClutter.Actor.__init__(self)
self.keyframe = keyframe
@@ -778,6 +815,7 @@ class KeyframeMenu(GtkClutter.Actor):
class Keyframe(Clutter.Actor):
+
"""
@ivar has_changeable_time: if False, it means this is an edge keyframe.
@type has_changeable_time: bool
@@ -810,13 +848,15 @@ class Keyframe(Clutter.Actor):
def createMenu(self):
self.menu = KeyframeMenu(self)
- self.timelineElement.timeline._container.stage.connect("button-press-event", self._stageClickedCb)
+ self.timelineElement.timeline._container.stage.connect(
+ "button-press-event", self._stageClickedCb)
self.timelineElement.timeline.add_child(self.menu)
def _unselect(self):
self.timelineElement.set_reactive(True)
self.set_background_color(KEYFRAME_NORMAL_COLOR)
- self.timelineElement.timeline._container.embed.get_window().set_cursor(NORMAL_CURSOR)
+ self.timelineElement.timeline._container.embed.get_window().set_cursor(
+ NORMAL_CURSOR)
def remove(self):
# Can't remove edge keyframes !
@@ -828,7 +868,8 @@ class Keyframe(Clutter.Actor):
self.timelineElement.removeKeyframe(self)
def _stageClickedCb(self, stage, event):
- actor = stage.get_actor_at_pos(Clutter.PickMode.REACTIVE, event.x, event.y)
+ actor = stage.get_actor_at_pos(
+ Clutter.PickMode.REACTIVE, event.x, event.y)
if actor != self.menu:
self.menu.hide()
@@ -843,7 +884,8 @@ class Keyframe(Clutter.Actor):
def _enterEventCb(self, unused_actor, unused_event):
self.timelineElement.set_reactive(False)
self.set_background_color(KEYFRAME_SELECTED_COLOR)
- self.timelineElement.timeline._container.embed.get_window().set_cursor(DRAG_CURSOR)
+ self.timelineElement.timeline._container.embed.get_window().set_cursor(
+ DRAG_CURSOR)
def _leaveEventCb(self, unused_actor, unused_event):
self._unselect()
@@ -862,7 +904,8 @@ class Keyframe(Clutter.Actor):
def endDrag(self):
if not self.dragProgressed and not self.line:
timeline = self.timelineElement.timeline
- self.menu.set_position(self.timelineElement.props.x + self.props.x + 10,
self.timelineElement.props.y + self.props.y + 10)
+ self.menu.set_position(
+ self.timelineElement.props.x + self.props.x + 10, self.timelineElement.props.y +
self.props.y + 10)
self.menu.show()
self.line = None
@@ -872,7 +915,8 @@ class Keyframe(Clutter.Actor):
newValue = self.valueStart - (delta_y / EXPANDED_SIZE)
# Don't overlap first and last keyframes.
- newTs = min(max(newTs, self.inpoint + 1), self.duration + self.inpoint - 1)
+ newTs = min(max(newTs, self.inpoint + 1),
+ self.duration + self.inpoint - 1)
newValue = min(max(newValue, 0.0), 1.0)
@@ -888,12 +932,15 @@ class Keyframe(Clutter.Actor):
self.timelineElement.setKeyframePosition(self, self.value)
# Resort the keyframes list each time. Should be cheap as there should never be too much
keyframes,
- # if optimization is needed, check if resorting is needed, should not be in 99 % of the cases.
- self.timelineElement.keyframes = sorted(self.timelineElement.keyframes, key=lambda keyframe:
keyframe.value.timestamp)
+ # if optimization is needed, check if resorting is needed, should
+ # not be in 99 % of the cases.
+ self.timelineElement.keyframes = sorted(
+ self.timelineElement.keyframes, key=lambda keyframe: keyframe.value.timestamp)
self.timelineElement.drawLines(self.line)
# This will update the viewer. nifty.
if not self.line:
- self.timelineElement.timeline._container.seekInPosition(newTs + self.start)
+ self.timelineElement.timeline._container.seekInPosition(
+ newTs + self.start)
def _dragBeginCb(self, unused_action, unused_actor, event_x, event_y, unused_modifiers):
self.dragProgressed = False
@@ -914,6 +961,7 @@ class Keyframe(Clutter.Actor):
class URISourceElement(TimelineElement):
+
def __init__(self, bElement, timeline):
TimelineElement.__init__(self, bElement, timeline)
self.gotDragged = False
@@ -953,19 +1001,22 @@ class URISourceElement(TimelineElement):
# Callbacks
def _clickedCb(self, unused_action, unused_actor):
- #TODO : Let's be more specific, masks etc ..
+ # TODO : Let's be more specific, masks etc ..
mode = SELECT
if self.timeline._container._controlMask:
if not self.bElement.selected:
mode = SELECT_ADD
- self.timeline.current_group.add(self.bElement.get_toplevel_parent())
+ self.timeline.current_group.add(
+ self.bElement.get_toplevel_parent())
else:
- self.timeline.current_group.remove(self.bElement.get_toplevel_parent())
+ self.timeline.current_group.remove(
+ self.bElement.get_toplevel_parent())
mode = UNSELECT
elif not self.bElement.selected:
GES.Container.ungroup(self.timeline.current_group, False)
self.timeline.current_group = GES.Group()
- self.timeline.current_group.add(self.bElement.get_toplevel_parent())
+ self.timeline.current_group.add(
+ self.bElement.get_toplevel_parent())
self.timeline._container.gui.switchContextTab(self.bElement)
children = self.bElement.get_toplevel_parent().get_children(True)
@@ -982,7 +1033,8 @@ class URISourceElement(TimelineElement):
self.gotDragged = False
mode = self.timeline._container.getEditionMode()
- # This can't change during a drag, so we can safely compute it now for drag events.
+ # This can't change during a drag, so we can safely compute it now for
+ # drag events.
nbrLayers = len(self.timeline.bTimeline.get_layers())
self.brother = self.timeline.findBrother(self.bElement)
self._dragBeginStart = self.bElement.get_start()
@@ -1020,16 +1072,20 @@ class URISourceElement(TimelineElement):
priority = self._getLayerForY(y)
new_start = self._dragBeginStart + self.pixelToNs(delta_x)
- self.ghostclip.props.x = max(0, self.nsToPixel(self._dragBeginStart) + delta_x)
+ self.ghostclip.props.x = max(
+ 0, self.nsToPixel(self._dragBeginStart) + delta_x)
self.ghostclip.update(priority, y, False)
if self.brother:
- self.brother.ghostclip.props.x = max(0, self.nsToPixel(self._dragBeginStart) + delta_x)
+ self.brother.ghostclip.props.x = max(
+ 0, self.nsToPixel(self._dragBeginStart) + delta_x)
self.brother.ghostclip.update(priority, y, True)
if not self.ghostclip.props.visible:
- self._context.editTo(new_start, self.bElement.get_parent().get_layer().get_priority())
+ self._context.editTo(
+ new_start, self.bElement.get_parent().get_layer().get_priority())
else:
- self._context.editTo(self._dragBeginStart, self.bElement.get_parent().get_layer().get_priority())
+ self._context.editTo(
+ self._dragBeginStart, self.bElement.get_parent().get_layer().get_priority())
self.timeline._updateSize(self.ghostclip)
return False
@@ -1038,7 +1094,8 @@ class URISourceElement(TimelineElement):
coords = self.dragAction.get_motion_coords()
delta_x = coords[0] - self.dragBeginStartX
new_start = self._dragBeginStart + self.pixelToNs(delta_x)
- priority = self._getLayerForY(coords[1] + self.timeline._container.point.y)
+ priority = self._getLayerForY(
+ coords[1] + self.timeline._container.point.y)
priority = min(priority, len(self.timeline.bTimeline.get_layers()))
priority = max(0, priority)
@@ -1067,6 +1124,7 @@ class URISourceElement(TimelineElement):
class TransitionElement(TimelineElement):
+
def __init__(self, bElement, timeline):
TimelineElement.__init__(self, bElement, timeline)
self.isDragged = True
diff --git a/pitivi/timeline/layer.py b/pitivi/timeline/layer.py
index df4e767..3d3919d 100644
--- a/pitivi/timeline/layer.py
+++ b/pitivi/timeline/layer.py
@@ -33,6 +33,7 @@ from pitivi.utils.ui import LAYER_CONTROL_TARGET_ENTRY
# TODO GTK3 port to GtkGrid
class BaseLayerControl(Gtk.VBox, Loggable):
+
"""
Base Layer control classes
"""
@@ -51,10 +52,12 @@ class BaseLayerControl(Gtk.VBox, Loggable):
context = self.get_style_context()
# get the default color for the current theme
- self.UNSELECTED_COLOR = context.get_background_color(Gtk.StateFlags.NORMAL)
+ self.UNSELECTED_COLOR = context.get_background_color(
+ Gtk.StateFlags.NORMAL)
# use base instead of bg colors so that we get the lighter color
# that is used for list items in TreeView.
- self.SELECTED_COLOR = context.get_background_color(Gtk.StateFlags.SELECTED)
+ self.SELECTED_COLOR = context.get_background_color(
+ Gtk.StateFlags.SELECTED)
table = Gtk.Table(n_rows=2, n_columns=2)
table.set_border_width(2)
@@ -82,8 +85,10 @@ class BaseLayerControl(Gtk.VBox, Loggable):
# Name entry
self.name_entry = Gtk.Entry()
- self.name_entry.set_tooltip_text(_("Set a personalized name for this layer"))
- self.name_entry.set_property("primary-icon-name", icon_mapping[layer_type])
+ self.name_entry.set_tooltip_text(
+ _("Set a personalized name for this layer"))
+ self.name_entry.set_property(
+ "primary-icon-name", icon_mapping[layer_type])
self.name_entry.connect("button_press_event", self._buttonPressCb)
# self.name_entry.drag_dest_unset()
self.name_entry.set_sensitive(False)
@@ -91,10 +96,11 @@ class BaseLayerControl(Gtk.VBox, Loggable):
# 'Solo' toggle button
self.solo_button = Gtk.ToggleButton()
self.solo_button.set_tooltip_markup(_("<b>Solo mode</b>\n"
- "Other non-soloed layers will be disabled as long as "
- "this is enabled."))
+ "Other non-soloed layers will be disabled as long as "
+ "this is enabled."))
solo_image = Gtk.Image()
- solo_image.set_from_icon_name("avatar-default-symbolic", Gtk.IconSize.MENU)
+ solo_image.set_from_icon_name(
+ "avatar-default-symbolic", Gtk.IconSize.MENU)
self.solo_button.add(solo_image)
self.solo_button.connect("toggled", self._soloToggledCb)
self.solo_button.set_relief(Gtk.ReliefStyle.NONE)
@@ -106,7 +112,7 @@ class BaseLayerControl(Gtk.VBox, Loggable):
visible_option.set_active(True)
visible_option.set_sensitive(False)
visible_option.set_tooltip_markup(_("<b>Enable or disable this layer</b>\n"
- "Disabled layers will not play nor render."))
+ "Disabled layers will not play nor render."))
# Upper bar
upper = Gtk.HBox()
@@ -133,7 +139,8 @@ class BaseLayerControl(Gtk.VBox, Loggable):
self.layer_down.connect("activate", self._moveLayerCb, 1)
self.layer_first = Gtk.MenuItem.new_with_label(_("Move layer to top"))
self.layer_first.connect("activate", self._moveLayerCb, -2)
- self.layer_last = Gtk.MenuItem.new_with_label(_("Move layer to bottom"))
+ self.layer_last = Gtk.MenuItem.new_with_label(
+ _("Move layer to bottom"))
self.layer_last.connect("activate", self._moveLayerCb, 2)
self.popup.append(self.layer_first)
@@ -197,11 +204,15 @@ class BaseLayerControl(Gtk.VBox, Loggable):
Called when the selection state changes
"""
if self.selected:
- self.eventbox.override_background_color(Gtk.StateType.NORMAL, self.SELECTED_COLOR)
- self.name_entry.override_background_color(Gtk.StateType.NORMAL, self.SELECTED_COLOR)
+ self.eventbox.override_background_color(
+ Gtk.StateType.NORMAL, self.SELECTED_COLOR)
+ self.name_entry.override_background_color(
+ Gtk.StateType.NORMAL, self.SELECTED_COLOR)
else:
- self.eventbox.override_background_color(Gtk.StateType.NORMAL, self.UNSELECTED_COLOR)
- self.name_entry.override_background_color(Gtk.StateType.NORMAL, self.UNSELECTED_COLOR)
+ self.eventbox.override_background_color(
+ Gtk.StateType.NORMAL, self.UNSELECTED_COLOR)
+ self.name_entry.override_background_color(
+ Gtk.StateType.NORMAL, self.UNSELECTED_COLOR)
# continue GTK signal propagation
return True
@@ -267,12 +278,15 @@ class BaseLayerControl(Gtk.VBox, Loggable):
Used for visual drag'n'drop feedback
"""
if highlighted:
- self.sep.override_background_color(Gtk.StateType.NORMAL, self.SELECTED_COLOR)
+ self.sep.override_background_color(
+ Gtk.StateType.NORMAL, self.SELECTED_COLOR)
else:
- self.sep.override_background_color(Gtk.StateType.NORMAL, self.UNSELECTED_COLOR)
+ self.sep.override_background_color(
+ Gtk.StateType.NORMAL, self.UNSELECTED_COLOR)
class VideoLayerControl(BaseLayerControl):
+
"""
Layer control class for video layers
"""
@@ -280,13 +294,16 @@ class VideoLayerControl(BaseLayerControl):
__gtype_name__ = 'VideoLayerControl'
def __init__(self, control_container, layer, app):
- BaseLayerControl.__init__(self, control_container, layer, GES.TrackType.VIDEO, app)
+ BaseLayerControl.__init__(
+ self, control_container, layer, GES.TrackType.VIDEO, app)
opacity = Gtk.Label(label=_("Opacity:"))
# Opacity scale
- opacity_adjust = Gtk.Adjustment(value=100, upper=100, step_increment=5, page_increment=10)
- opacity_scale = Gtk.Scale.new(Gtk.Orientation.HORIZONTAL, adjustment=opacity_adjust)
+ opacity_adjust = Gtk.Adjustment(
+ value=100, upper=100, step_increment=5, page_increment=10)
+ opacity_scale = Gtk.Scale.new(
+ Gtk.Orientation.HORIZONTAL, adjustment=opacity_adjust)
opacity_scale.set_value_pos(Gtk.PositionType.LEFT)
opacity_scale.set_digits(0)
opacity_scale.set_tooltip_text(_("Change video opacity"))
@@ -297,6 +314,7 @@ class VideoLayerControl(BaseLayerControl):
class AudioLayerControl(BaseLayerControl):
+
"""
Layer control class for audio layers
"""
@@ -304,15 +322,18 @@ class AudioLayerControl(BaseLayerControl):
__gtype_name__ = 'AudioLayerControl'
def __init__(self, control_container, layer, app):
- BaseLayerControl.__init__(self, control_container, layer, GES.TrackType.AUDIO, app)
+ BaseLayerControl.__init__(
+ self, control_container, layer, GES.TrackType.AUDIO, app)
volume = Gtk.Label(label=_("Vol:"))
volume_button = Gtk.VolumeButton(size=Gtk.IconSize.MENU)
panning = Gtk.Label(label=_("Pan:"))
# Volume scale
- panning_adjust = Gtk.Adjustment(value=0, lower=-100, upper=100, step_increment=5, page_increment=10)
- panning_scale = Gtk.Scale.new(Gtk.Orientation.HORIZONTAL, adjustment=panning_adjust)
+ panning_adjust = Gtk.Adjustment(
+ value=0, lower=-100, upper=100, step_increment=5, page_increment=10)
+ panning_scale = Gtk.Scale.new(
+ Gtk.Orientation.HORIZONTAL, adjustment=panning_adjust)
panning_scale.set_value_pos(Gtk.PositionType.LEFT)
panning_scale.set_digits(0)
panning_scale.set_tooltip_text(_("Change audio panning"))
@@ -325,6 +346,7 @@ class AudioLayerControl(BaseLayerControl):
class TwoStateButton(Gtk.Button):
+
"""
Button with two states and according labels/images
"""
@@ -354,6 +376,7 @@ class TwoStateButton(Gtk.Button):
class SpacedSeparator(Gtk.EventBox):
+
"""
A Separator with vertical spacing
diff --git a/pitivi/timeline/previewers.py b/pitivi/timeline/previewers.py
index bff2401..4f1ff2a 100644
--- a/pitivi/timeline/previewers.py
+++ b/pitivi/timeline/previewers.py
@@ -59,7 +59,9 @@ THUMBNAILS_CPU_USAGE = 20
THUMB_MARGIN_PX = 3
WAVEFORM_UPDATE_INTERVAL = timedelta(microseconds=500000)
-MARGIN = 500 # For the waveforms, ensures we always have a little extra surface when scrolling while
playing.
+# For the waveforms, ensures we always have a little extra surface when
+# scrolling while playing.
+MARGIN = 500
PREVIEW_GENERATOR_SIGNALS = {
"done": (GObject.SIGNAL_RUN_LAST, None, ()),
@@ -75,9 +77,11 @@ is prefixed with a little b, example : bTimeline
class PreviewGeneratorManager():
+
"""
Manage the execution of PreviewGenerators
"""
+
def __init__(self):
# The current PreviewGenerator per GES.TrackType.
self._cpipeline = {}
@@ -117,6 +121,7 @@ class PreviewGeneratorManager():
class PreviewGenerator(object):
+
"""
Interface to be implemented by classes that generate previews
It is need to implement it so PreviewGeneratorManager can manage
@@ -166,7 +171,8 @@ class VideoPreviewer(Clutter.ScrollActor, PreviewGenerator, Zoomable, Loggable):
# Variables related to the timeline objects
self.timeline = timeline
self.bElement = bElement
- self.uri = quote_uri(bElement.props.uri) # Guard against malformed URIs
+ # Guard against malformed URIs
+ self.uri = quote_uri(bElement.props.uri)
self.duration = bElement.props.duration
# Variables related to thumbnailing
@@ -260,15 +266,21 @@ class VideoPreviewer(Clutter.ScrollActor, PreviewGenerator, Zoomable, Loggable):
usage_percent = self.cpu_usage_tracker.usage()
if usage_percent < THUMBNAILS_CPU_USAGE:
self.interval *= 0.9
- self.log('Thumbnailing sped up (+10%%) to a %.1f ms interval for "%s"' % (self.interval,
filename_from_uri(self.uri)))
+ self.log(
+ 'Thumbnailing sped up (+10%%) to a %.1f ms interval for "%s"' %
+ (self.interval, filename_from_uri(self.uri)))
else:
self.interval *= 1.1
- self.log('Thumbnailing slowed down (-10%%) to a %.1f ms interval for "%s"' % (self.interval,
filename_from_uri(self.uri)))
+ self.log(
+ 'Thumbnailing slowed down (-10%%) to a %.1f ms interval for "%s"' %
+ (self.interval, filename_from_uri(self.uri)))
self.cpu_usage_tracker.reset()
- self._thumb_cb_id = GLib.timeout_add(self.interval, self._create_next_thumb)
+ self._thumb_cb_id = GLib.timeout_add(
+ self.interval, self._create_next_thumb)
def _startThumbnailingWhenIdle(self):
- self.debug('Waiting for UI to become idle for: %s', filename_from_uri(self.uri))
+ self.debug(
+ 'Waiting for UI to become idle for: %s', filename_from_uri(self.uri))
GLib.idle_add(self._startThumbnailing, priority=GLib.PRIORITY_LOW)
def _startThumbnailing(self):
@@ -277,7 +289,8 @@ class VideoPreviewer(Clutter.ScrollActor, PreviewGenerator, Zoomable, Loggable):
# removed from the timeline after the PreviewGeneratorManager
# started this job.
return
- self.debug('Now generating thumbnails for: %s', filename_from_uri(self.uri))
+ self.debug(
+ 'Now generating thumbnails for: %s', filename_from_uri(self.uri))
query_success, duration = self.pipeline.query_duration(Gst.Format.TIME)
if not query_success or duration == -1:
self.debug("Could not determine duration of: %s", self.uri)
@@ -336,10 +349,12 @@ class VideoPreviewer(Clutter.ScrollActor, PreviewGenerator, Zoomable, Loggable):
return False # Stop the timer
def _get_thumb_duration(self):
- thumb_duration_tmp = Zoomable.pixelToNs(self.thumb_width + THUMB_MARGIN_PX)
+ thumb_duration_tmp = Zoomable.pixelToNs(
+ self.thumb_width + THUMB_MARGIN_PX)
# quantize thumb length to thumb_period
thumb_duration = quantize(thumb_duration_tmp, self.thumb_period)
- # make sure that the thumb duration after the quantization isn't smaller than before
+ # make sure that the thumb duration after the quantization isn't
+ # smaller than before
if thumb_duration < thumb_duration_tmp:
thumb_duration += self.thumb_period
# make sure that we don't show thumbnails more often than thumb_period
@@ -360,13 +375,15 @@ class VideoPreviewer(Clutter.ScrollActor, PreviewGenerator, Zoomable, Loggable):
for current_time in range(element_left, element_right, thumb_duration):
thumb = Thumbnail(self.thumb_width, self.thumb_height)
- thumb.set_position(Zoomable.nsToPixel(current_time), THUMB_MARGIN_PX)
+ thumb.set_position(
+ Zoomable.nsToPixel(current_time), THUMB_MARGIN_PX)
self.add_child(thumb)
self.thumbs[current_time] = thumb
if current_time in self.thumb_cache:
gdkpixbuf = self.thumb_cache[current_time]
if self._allAnimated or current_time not in old_thumbs:
- self.thumbs[current_time].set_from_gdkpixbuf_animated(gdkpixbuf)
+ self.thumbs[
+ current_time].set_from_gdkpixbuf_animated(gdkpixbuf)
else:
self.thumbs[current_time].set_from_gdkpixbuf(gdkpixbuf)
else:
@@ -537,6 +554,7 @@ class VideoPreviewer(Clutter.ScrollActor, PreviewGenerator, Zoomable, Loggable):
class Thumbnail(Clutter.Actor):
+
def __init__(self, width, height):
Clutter.Actor.__init__(self)
image = Clutter.Image.new()
@@ -619,7 +637,8 @@ class ThumbnailCache(Loggable):
return pixbuf
def __setitem__(self, key, value):
- success, jpeg = value.save_to_bufferv("jpeg", ["quality", None], ["90"])
+ success, jpeg = value.save_to_bufferv(
+ "jpeg", ["quality", None], ["90"])
if not success:
self.warning("JPEG compression failed")
return
@@ -629,18 +648,21 @@ class ThumbnailCache(Loggable):
self._cur.execute("INSERT INTO Thumbs VALUES (?,?)", (key, blob,))
def commit(self):
- self.debug('Saving thumbnail cache file to disk for: %s', self._filename)
+ self.debug(
+ 'Saving thumbnail cache file to disk for: %s', self._filename)
self._db.commit()
self.log("Saved thumbnail cache file: %s" % self._filehash)
class PipelineCpuAdapter(Loggable):
+
"""
This pipeline manager will modulate the rate of the provided pipeline.
It is the responsibility of the caller to set the sync of the sink to True,
disable QOS and provide a pipeline with a rate of 1.0.
Doing otherwise would be cheating. Cheating is bad.
"""
+
def __init__(self, pipeline):
Loggable.__init__(self)
self.pipeline = pipeline
@@ -679,12 +701,14 @@ class PipelineCpuAdapter(Loggable):
if not self.ready:
self.ready = True
self.pipeline.set_state(Gst.State.READY)
- res, self.lastPos = self.pipeline.query_position(Gst.Format.TIME)
+ res, self.lastPos = self.pipeline.query_position(
+ Gst.Format.TIME)
return True
if self.rate > 0.0:
self.rate *= 0.9
- self.log('Pipeline rate slowed down (-10%%) to %.3f' % self.rate)
+ self.log(
+ 'Pipeline rate slowed down (-10%%) to %.3f' % self.rate)
else:
self.rate *= 1.1
self.log('Pipeline rate sped up (+10%%) to %.3f' % self.rate)
@@ -692,8 +716,10 @@ class PipelineCpuAdapter(Loggable):
if not self.ready:
res, position = self.pipeline.query_position(Gst.Format.TIME)
else:
- if self.rate > 0.5: # This to avoid going back and forth from READY to PAUSED
- self.pipeline.set_state(Gst.State.PAUSED) # The message handler will unset ready and seek
correctly.
+ # This to avoid going back and forth from READY to PAUSED
+ if self.rate > 0.5:
+ # The message handler will unset ready and seek correctly.
+ self.pipeline.set_state(Gst.State.PAUSED)
return True
self.pipeline.set_state(Gst.State.PAUSED)
@@ -727,6 +753,7 @@ class PipelineCpuAdapter(Loggable):
class AudioPreviewer(Clutter.Actor, PreviewGenerator, Zoomable, Loggable):
+
"""
Audio previewer based on the results from the "level" gstreamer element.
"""
@@ -742,11 +769,13 @@ class AudioPreviewer(Clutter.Actor, PreviewGenerator, Zoomable, Loggable):
self.pipeline = None
self.discovered = False
self.bElement = bElement
- self._uri = quote_uri(bElement.props.uri) # Guard against malformed URIs
+ # Guard against malformed URIs
+ self._uri = quote_uri(bElement.props.uri)
self.timeline = timeline
self.actors = []
- self.set_content_scaling_filters(Clutter.ScalingFilter.NEAREST, Clutter.ScalingFilter.NEAREST)
+ self.set_content_scaling_filters(
+ Clutter.ScalingFilter.NEAREST, Clutter.ScalingFilter.NEAREST)
self.canvas = Clutter.Canvas()
self.set_content(self.canvas)
self.width = 0
@@ -764,7 +793,8 @@ class AudioPreviewer(Clutter.Actor, PreviewGenerator, Zoomable, Loggable):
self._callback_id = 0
def startLevelsDiscoveryWhenIdle(self):
- self.debug('Waiting for UI to become idle for: %s', filename_from_uri(self._uri))
+ self.debug('Waiting for UI to become idle for: %s',
+ filename_from_uri(self._uri))
GLib.idle_add(self._startLevelsDiscovery, priority=GLib.PRIORITY_LOW)
def _startLevelsDiscovery(self):
@@ -781,9 +811,11 @@ class AudioPreviewer(Clutter.Actor, PreviewGenerator, Zoomable, Loggable):
self._launchPipeline()
def _launchPipeline(self):
- self.debug('Now generating waveforms for: %s', filename_from_uri(self._uri))
+ self.debug(
+ 'Now generating waveforms for: %s', filename_from_uri(self._uri))
self.peaks = None
- self.pipeline = Gst.parse_launch("uridecodebin name=decode uri=" + self._uri + " ! audioconvert !
level name=wavelevel interval=10000000 post-messages=true ! fakesink qos=false name=faked")
+ self.pipeline = Gst.parse_launch("uridecodebin name=decode uri=" + self._uri +
+ " ! audioconvert ! level name=wavelevel interval=10000000
post-messages=true ! fakesink qos=false name=faked")
faked = self.pipeline.get_by_name("faked")
faked.props.sync = True
self._wavelevel = self.pipeline.get_by_name("wavelevel")
@@ -792,7 +824,8 @@ class AudioPreviewer(Clutter.Actor, PreviewGenerator, Zoomable, Loggable):
bus = self.pipeline.get_bus()
bus.add_signal_watch()
- self.nSamples = self.bElement.get_parent().get_asset().get_duration() / 10000000
+ self.nSamples = self.bElement.get_parent(
+ ).get_asset().get_duration() / 10000000
bus.connect("message", self._busMessageCb)
self.becomeControlled()
@@ -805,14 +838,16 @@ class AudioPreviewer(Clutter.Actor, PreviewGenerator, Zoomable, Loggable):
def _maybeUpdate(self):
if self.discovered:
- self.log('Checking if the waveform for "%s" needs to be redrawn' % self._uri)
+ self.log('Checking if the waveform for "%s" needs to be redrawn' %
+ self._uri)
if self.lastUpdate is None or datetime.now() - self.lastUpdate > WAVEFORM_UPDATE_INTERVAL:
# Last update was long ago or never.
self._compute_geometry()
else:
if self._callback_id:
GLib.source_remove(self._callback_id)
- self._callback_id = GLib.timeout_add(500, self._compute_geometry)
+ self._callback_id = GLib.timeout_add(
+ 500, self._compute_geometry)
def _compute_geometry(self):
self._callback_id = 0
@@ -821,25 +856,31 @@ class AudioPreviewer(Clutter.Actor, PreviewGenerator, Zoomable, Loggable):
width_px = self.nsToPixel(self.bElement.props.duration)
if width_px <= 0:
return
- start = self.timeline.get_scroll_point().x - self.nsToPixel(self.bElement.props.start)
+ start = self.timeline.get_scroll_point().x - self.nsToPixel(
+ self.bElement.props.start)
start = max(0, start)
# Take into account the timeline width, to avoid building
# huge clips when the timeline is zoomed in a lot.
- timeline_width = self.timeline._container.get_allocation().width - CONTROL_WIDTH
+ timeline_width = self.timeline._container.get_allocation(
+ ).width - CONTROL_WIDTH
end = min(width_px,
self.timeline.get_scroll_point().x + timeline_width + MARGIN)
self.width = int(end - start)
- if self.width < 0: # We've been called at a moment where size was updated but not scroll_point.
+ # We've been called at a moment where size was updated but not
+ # scroll_point.
+ if self.width < 0:
return
# We need to take duration and inpoint into account.
asset_duration = self.bElement.get_parent().get_asset().get_duration()
if self.bElement.props.duration:
- nbSamples = self.nbSamples / (float(asset_duration) / float(self.bElement.props.duration))
+ nbSamples = self.nbSamples / \
+ (float(asset_duration) / float(self.bElement.props.duration))
else:
nbSamples = self.nbSamples
if self.bElement.props.in_point:
- startOffsetSamples = self.nbSamples / (float(asset_duration) /
float(self.bElement.props.in_point))
+ startOffsetSamples = self.nbSamples / \
+ (float(asset_duration) / float(self.bElement.props.in_point))
else:
startOffsetSamples = 0
@@ -854,7 +895,8 @@ class AudioPreviewer(Clutter.Actor, PreviewGenerator, Zoomable, Loggable):
def _prepareSamples(self):
# Let's go mono.
if len(self.peaks) > 1:
- samples = (numpy.array(self.peaks[0]) + numpy.array(self.peaks[1])) / 2
+ samples = (
+ numpy.array(self.peaks[0]) + numpy.array(self.peaks[1])) / 2
else:
samples = numpy.array(self.peaks[0])
@@ -955,7 +997,8 @@ class AudioPreviewer(Clutter.Actor, PreviewGenerator, Zoomable, Loggable):
if self.surface:
self.surface.finish()
- self.surface = renderer.fill_surface(self.samples[self.start:self.end], int(self.width),
int(EXPANDED_SIZE))
+ self.surface = renderer.fill_surface(
+ self.samples[self.start:self.end], int(self.width), int(EXPANDED_SIZE))
context.set_operator(cairo.OPERATOR_OVER)
context.set_source_surface(self.surface, 0, 0)
diff --git a/pitivi/timeline/ruler.py b/pitivi/timeline/ruler.py
index c07cf73..ca8492a 100644
--- a/pitivi/timeline/ruler.py
+++ b/pitivi/timeline/ruler.py
@@ -57,6 +57,7 @@ SMALL_FONT_SIZE = 11
class ScaleRuler(Gtk.DrawingArea, Zoomable, Loggable):
+
"""
Widget for displaying the ruler.
@@ -70,7 +71,7 @@ class ScaleRuler(Gtk.DrawingArea, Zoomable, Loggable):
"motion-notify-event": "override",
"scroll-event": "override",
"seek": (GObject.SignalFlags.RUN_LAST, None,
- [GObject.TYPE_UINT64])
+ [GObject.TYPE_UINT64])
}
def __init__(self, timeline, hadj):
@@ -85,13 +86,14 @@ class ScaleRuler(Gtk.DrawingArea, Zoomable, Loggable):
self.connect("focus-out-event", self._focusOutCb)
self.timeline = timeline
- self._background_color = timeline.get_style_context().lookup_color('theme_bg_color')[1]
+ self._background_color = timeline.get_style_context().lookup_color(
+ 'theme_bg_color')[1]
self._seeker = Seeker()
self.hadj = hadj
hadj.connect("value-changed", self._hadjValueChangedCb)
self.add_events(Gdk.EventMask.POINTER_MOTION_MASK |
- Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK |
- Gdk.EventMask.SCROLL_MASK)
+ Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK |
+ Gdk.EventMask.SCROLL_MASK)
self.pixbuf = None
@@ -230,10 +232,10 @@ class ScaleRuler(Gtk.DrawingArea, Zoomable, Loggable):
else:
# No modifier key held down, just scroll
if (event.scroll.direction == Gdk.ScrollDirection.UP
- or event.scroll.direction == Gdk.ScrollDirection.LEFT):
+ or event.scroll.direction == Gdk.ScrollDirection.LEFT):
self.timeline.scroll_left()
elif (event.scroll.direction == Gdk.ScrollDirection.DOWN
- or event.scroll.direction == Gdk.ScrollDirection.RIGHT):
+ or event.scroll.direction == Gdk.ScrollDirection.RIGHT):
self.timeline.scroll_right()
def setProjectFrameRate(self, rate):
@@ -242,7 +244,8 @@ class ScaleRuler(Gtk.DrawingArea, Zoomable, Loggable):
"""
self.frame_rate = rate
self.ns_per_frame = float(1 / self.frame_rate) * Gst.SECOND
- self.scales = (float(2 / rate), float(5 / rate), float(10 / rate)) + SCALES
+ self.scales = (float(2 / rate), float(
+ 5 / rate), float(10 / rate)) + SCALES
# Drawing methods
@@ -255,8 +258,10 @@ class ScaleRuler(Gtk.DrawingArea, Zoomable, Loggable):
context.fill()
offset = int(self.nsToPixel(Gst.CLOCK_TIME_NONE)) - self.pixbuf_offset
if offset > 0:
- set_cairo_color(context, style.get_background_color(Gtk.StateFlags.ACTIVE))
- context.rectangle(0, 0, int(offset), context.get_target().get_height())
+ set_cairo_color(
+ context, style.get_background_color(Gtk.StateFlags.ACTIVE))
+ context.rectangle(
+ 0, 0, int(offset), context.get_target().get_height())
context.fill()
def drawRuler(self, context):
@@ -276,7 +281,9 @@ class ScaleRuler(Gtk.DrawingArea, Zoomable, Loggable):
spacing = scale * zoom
if spacing >= textwidth * 1.5:
return spacing, scale
- raise Exception("Failed to find an interval size for textwidth:%s, zoomratio:%s" % (textwidth,
Zoomable.zoomratio))
+ raise Exception(
+ "Failed to find an interval size for textwidth:%s, zoomratio:%s" %
+ (textwidth, Zoomable.zoomratio))
def drawTicks(self, context, offset, spacing):
for count_per_interval, height_ratio in TICK_TYPES:
@@ -370,13 +377,16 @@ class ScaleRuler(Gtk.DrawingArea, Zoomable, Loggable):
states = [style.get_background_color(Gtk.StateFlags.ACTIVE),
style.get_background_color(Gtk.StateFlags.SELECTED)]
- frame_num = int(self.pixelToNs(self.pixbuf_offset) * float(self.frame_rate) / Gst.SECOND)
+ frame_num = int(
+ self.pixelToNs(self.pixbuf_offset) * float(self.frame_rate) / Gst.SECOND)
paintpos = self.pixbuf_offset - offset
max_pos = context.get_target().get_width() + self.pixbuf_offset
while paintpos < max_pos:
- paintpos = self.nsToPixel(1 / float(self.frame_rate) * Gst.SECOND * frame_num)
+ paintpos = self.nsToPixel(
+ 1 / float(self.frame_rate) * Gst.SECOND * frame_num)
set_cairo_color(context, states[(frame_num + 1) % 2])
- context.rectangle(0.5 + paintpos - self.pixbuf_offset, y, frame_width, height)
+ context.rectangle(
+ 0.5 + paintpos - self.pixbuf_offset, y, frame_width, height)
context.fill()
frame_num += 1
diff --git a/pitivi/timeline/timeline.py b/pitivi/timeline/timeline.py
index 79ffd7c..67a1410 100644
--- a/pitivi/timeline/timeline.py
+++ b/pitivi/timeline/timeline.py
@@ -48,29 +48,30 @@ from pitivi.utils.widgets import ZoomBox
GlobalSettings.addConfigOption('edgeSnapDeadband',
- section="user-interface",
- key="edge-snap-deadband",
- default=5,
- notify=True)
+ section="user-interface",
+ key="edge-snap-deadband",
+ default=5,
+ notify=True)
PreferencesDialog.addNumericPreference('edgeSnapDeadband',
- section=_("Behavior"),
- label=_("Snap distance"),
- description=_("Threshold (in pixels) at which two clips will snap together "
- "when dragging or trimming."),
- lower=0)
+ section=_("Behavior"),
+ label=_("Snap distance"),
+ description=_("Threshold (in pixels) at which two clips will snap
together "
+ "when dragging or trimming."),
+ lower=0)
GlobalSettings.addConfigOption('imageClipLength',
- section="user-interface",
- key="image-clip-length",
- default=1000,
- notify=True)
+ section="user-interface",
+ key="image-clip-length",
+ default=1000,
+ notify=True)
PreferencesDialog.addNumericPreference('imageClipLength',
- section=_("Behavior"),
- label=_("Image clip duration"),
- description=_("Default clip length (in miliseconds) of images when inserting on the timeline."),
- lower=1)
+ section=_("Behavior"),
+ label=_("Image clip duration"),
+ description=_(
+ "Default clip length (in miliseconds) of images when inserting on
the timeline."),
+ lower=1)
# Colors
TIMELINE_BACKGROUND_COLOR = Clutter.Color.new(31, 30, 33, 255)
@@ -86,6 +87,7 @@ is prefixed with a little b, example : bTimeline
class TimelineStage(Clutter.ScrollActor, Zoomable, Loggable):
+
"""
The timeline view showing the clips.
"""
@@ -116,7 +118,8 @@ class TimelineStage(Clutter.ScrollActor, Zoomable, Loggable):
# The first marker added as a child is the furthest and
# the latest added marker is the closest to the viewer.
- # All the audio, video, image, title clips are placed above this marker.
+ # All the audio, video, image, title clips are placed above this
+ # marker.
self._clips_marker = Clutter.Actor()
self.add_child(self._clips_marker)
# All the transition clips are placed above this marker.
@@ -252,7 +255,8 @@ class TimelineStage(Clutter.ScrollActor, Zoomable, Loggable):
layer = self._getLayerForGhostClip(ghostclip)
if ghostclip.asset.is_image():
- clip_duration = self._settings.imageClipLength * Gst.SECOND / 1000.0
+ clip_duration = self._settings.imageClipLength * \
+ Gst.SECOND / 1000.0
else:
clip_duration = ghostclip.asset.get_duration()
@@ -354,7 +358,8 @@ class TimelineStage(Clutter.ScrollActor, Zoomable, Loggable):
ghostclip.setNbrLayers(len(self.bTimeline.get_layers()))
if asset.is_image():
- clip_duration = self._settings.imageClipLength * Gst.SECOND / 1000.0
+ clip_duration = self._settings.imageClipLength * \
+ Gst.SECOND / 1000.0
else:
clip_duration = asset.get_duration()
@@ -378,7 +383,8 @@ class TimelineStage(Clutter.ScrollActor, Zoomable, Loggable):
self.lastPosition = position
def _updatePlayHead(self):
- height = len(self.bTimeline.get_layers()) * (EXPANDED_SIZE + SPACING) * 2
+ height = len(self.bTimeline.get_layers()) * \
+ (EXPANDED_SIZE + SPACING) * 2
self.playhead.set_size(PLAYHEAD_WIDTH, height)
self._movePlayhead(self.lastPosition)
@@ -418,9 +424,12 @@ class TimelineStage(Clutter.ScrollActor, Zoomable, Loggable):
return
bElement.connect("notify::start", self._elementStartChangedCb, element)
- bElement.connect("notify::duration", self._elementDurationChangedCb, element)
- bElement.connect("notify::in-point", self._elementInPointChangedCb, element)
- bElement.connect("notify::priority", self._elementPriorityChangedCb, element)
+ bElement.connect(
+ "notify::duration", self._elementDurationChangedCb, element)
+ bElement.connect(
+ "notify::in-point", self._elementInPointChangedCb, element)
+ bElement.connect(
+ "notify::priority", self._elementPriorityChangedCb, element)
self.elements.append(element)
@@ -467,7 +476,8 @@ class TimelineStage(Clutter.ScrollActor, Zoomable, Loggable):
y = 0
if track_type == GES.TrackType.AUDIO:
y = len(self.bTimeline.get_layers()) * (EXPANDED_SIZE + SPACING)
- y += bElement.get_parent().get_layer().get_priority() * (EXPANDED_SIZE + SPACING) + SPACING
+ y += bElement.get_parent().get_layer().get_priority() * \
+ (EXPANDED_SIZE + SPACING) + SPACING
element.save_easing_state()
element.props.y = y
@@ -476,11 +486,14 @@ class TimelineStage(Clutter.ScrollActor, Zoomable, Loggable):
def _updateSize(self, ghostclip=None):
self.save_easing_state()
self.set_easing_duration(0)
- self.props.width = self.nsToPixel(self.bTimeline.get_duration()) + CONTROL_WIDTH
+ self.props.width = self.nsToPixel(
+ self.bTimeline.get_duration()) + CONTROL_WIDTH
if ghostclip is not None:
- ghostEnd = ghostclip.props.x + ghostclip.props.width + CONTROL_WIDTH
+ ghostEnd = ghostclip.props.x + \
+ ghostclip.props.width + CONTROL_WIDTH
self.props.width = max(ghostEnd, self.props.width)
- self.props.height = (len(self.bTimeline.get_layers()) + 1) * (EXPANDED_SIZE + SPACING) * 2 + SPACING
+ self.props.height = (len(self.bTimeline.get_layers()) + 1) * \
+ (EXPANDED_SIZE + SPACING) * 2 + SPACING
self.restore_easing_state()
self._container.vadj.props.upper = self.props.height
self._container.updateHScrollAdjustments()
@@ -581,7 +594,8 @@ class TimelineStage(Clutter.ScrollActor, Zoomable, Loggable):
if position == 0:
self._snapEndedCb()
else:
- height = len(self.bTimeline.get_layers()) * (EXPANDED_SIZE + SPACING) * 2
+ height = len(self.bTimeline.get_layers()) * \
+ (EXPANDED_SIZE + SPACING) * 2
self._snap_indicator.props.height = height
self._snap_indicator.props.x = Zoomable.nsToPixel(position)
self._snap_indicator.props.visible = True
@@ -602,7 +616,8 @@ class TimelineStage(Clutter.ScrollActor, Zoomable, Loggable):
def _trackAddedCb(self, unused_timeline, track):
self._connectTrack(track)
- self._container.app.project_manager.current_project.update_restriction_caps()
+ self._container.app.project_manager.current_project.update_restriction_caps(
+ )
def _trackRemovedCb(self, unused_timeline, track):
self._disconnectTrack(track)
@@ -638,9 +653,11 @@ class TimelineStage(Clutter.ScrollActor, Zoomable, Loggable):
class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
+
"""
Container for zoom box, ruler, timeline, scrollbars and toolbar.
"""
+
def __init__(self, gui, instance, ui_manager):
Zoomable.__init__(self)
Gtk.Grid.__init__(self)
@@ -660,7 +677,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
self._project = None
self.bTimeline = None
- self.ui_manager.add_ui_from_file(os.path.join(get_ui_dir(), "timelinecontainer.xml"))
+ self.ui_manager.add_ui_from_file(
+ os.path.join(get_ui_dir(), "timelinecontainer.xml"))
self._createActions()
self._createUi()
@@ -689,14 +707,16 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
# We need to snapshot this value, because we only do the zoom fit at the
# end of clip insertion, but inserting multiple clips eventually changes
- # the value of self.zoomed_fitted as clips get progressively inserted...
+ # the value of self.zoomed_fitted as clips get progressively
+ # inserted...
zoom_was_fitted = self.zoomed_fitted
for asset in assets:
if isinstance(asset, GES.TitleClip):
clip_duration = asset.get_duration()
elif asset.is_image():
- clip_duration = self._settings.imageClipLength * Gst.SECOND / 1000.0
+ clip_duration = self._settings.imageClipLength * \
+ Gst.SECOND / 1000.0
else:
clip_duration = asset.get_duration()
@@ -710,7 +730,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
if zoom_was_fitted:
self._setBestZoomRatio()
else:
- self.scrollToPixel(Zoomable.nsToPixel(self.bTimeline.props.duration))
+ self.scrollToPixel(
+ Zoomable.nsToPixel(self.bTimeline.props.duration))
self.app.action_log.commit()
self.bTimeline.commit()
@@ -730,8 +751,10 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
self._projectmanager = projectmanager
if projectmanager is not None:
- projectmanager.connect("new-project-created", self._projectCreatedCb)
- projectmanager.connect("new-project-loaded", self._projectChangedCb)
+ projectmanager.connect(
+ "new-project-created", self._projectCreatedCb)
+ projectmanager.connect(
+ "new-project-loaded", self._projectChangedCb)
def updateHScrollAdjustments(self):
"""
@@ -743,7 +766,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
else:
contents_size = Zoomable.nsToPixel(self.bTimeline.props.duration)
- end_padding = CONTROL_WIDTH * 2 # Provide some space for clip insertion at the end
+ # Provide some space for clip insertion at the end
+ end_padding = CONTROL_WIDTH * 2
self.hadj.props.lower = 0
self.hadj.props.upper = contents_size + end_padding
@@ -785,7 +809,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
self.bTimeline = None
self.timeline.setProject(self._project)
- self.timeline.selection.connect("selection-changed", self._selectionChangedCb)
+ self.timeline.selection.connect(
+ "selection-changed", self._selectionChangedCb)
def getEditionMode(self, isAHandle=False):
if self._shiftMask or self._autoripple_active:
@@ -833,8 +858,10 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
self.stage.add_child(self.timeline)
self.timeline.connect("button-press-event", self._timelineClickedCb)
- self.timeline.connect("button-release-event", self._timelineClickReleasedCb)
- # FIXME: Connect to the stage of the embed instead, see
https://bugzilla.gnome.org/show_bug.cgi?id=697522
+ self.timeline.connect(
+ "button-release-event", self._timelineClickReleasedCb)
+ # FIXME: Connect to the stage of the embed instead, see
+ # https://bugzilla.gnome.org/show_bug.cgi?id=697522
self.embed.connect("scroll-event", self._scrollEventCb)
self.connect("key-press-event", self._keyPressEventCb)
@@ -869,16 +896,21 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
toolbar.set_style(Gtk.ToolbarStyle.ICONS)
toolbar.get_accessible().set_name("timeline toolbar")
- alter_style_class(".%s" % Gtk.STYLE_CLASS_INLINE_TOOLBAR, toolbar, "padding-left: %dpx;
border-width: 0px; background: alpha (@base_color, 0.0);" % (SPACING / 2))
- alter_style_class(".%s.trough" % Gtk.STYLE_CLASS_SCROLLBAR, self._vscrollbar, "border: alpha
(@base_color, 0.0); background: alpha (@base_color, 0.0);")
- alter_style_class(".%s.trough" % Gtk.STYLE_CLASS_SCROLLBAR, self._hscrollbar, "border: alpha
(@base_color, 0.0); background: alpha (@base_color, 0.0);")
+ alter_style_class(".%s" % Gtk.STYLE_CLASS_INLINE_TOOLBAR, toolbar,
+ "padding-left: %dpx; border-width: 0px; background: alpha (@base_color, 0.0);" %
(SPACING / 2))
+ alter_style_class(
+ ".%s.trough" % Gtk.STYLE_CLASS_SCROLLBAR, self._vscrollbar,
+ "border: alpha (@base_color, 0.0); background: alpha (@base_color, 0.0);")
+ alter_style_class(
+ ".%s.trough" % Gtk.STYLE_CLASS_SCROLLBAR, self._hscrollbar,
+ "border: alpha (@base_color, 0.0); background: alpha (@base_color, 0.0);")
# Toggle/pushbuttons like the "gapless mode" ones are special, it seems
# you can't insert them as normal "actions", so we create them here:
gapless_mode_button = Gtk.ToggleToolButton()
gapless_mode_button.set_stock_id("pitivi-gapless")
gapless_mode_button.set_tooltip_markup(_("Toggle gapless mode\n"
- "When enabled, adjacent clips automatically move to fill gaps."))
+ "When enabled, adjacent clips automatically move to fill
gaps."))
toolbar.add(gapless_mode_button)
# Restore the state of the timeline's "gapless" mode:
self._autoripple_active = self._settings.timelineAutoRipple
@@ -957,7 +989,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
Sets up the GtkActions. This allows managing the sensitivity of widgets
to the mouse and keyboard shortcuts.
"""
- # TODO: use GAction + GActionGroup (Gio.SimpleAction + Gio.SimpleActionGroup)
+ # TODO: use GAction + GActionGroup (Gio.SimpleAction +
+ # Gio.SimpleActionGroup)
# Action list items can vary in size (1-6 items). The first one is the
# name, and it is the only mandatory option. All the other options are
@@ -970,49 +1003,49 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
zoom_fit_tooltip = _("Zoom Fit")
actions = (
("ZoomIn", Gtk.STOCK_ZOOM_IN, None,
- "<Control>plus", zoom_in_tooltip, self._zoomInCb),
+ "<Control>plus", zoom_in_tooltip, self._zoomInCb),
("ZoomOut", Gtk.STOCK_ZOOM_OUT, None,
- "<Control>minus", zoom_out_tooltip, self._zoomOutCb),
+ "<Control>minus", zoom_out_tooltip, self._zoomOutCb),
("ZoomFit", Gtk.STOCK_ZOOM_FIT, None,
- "<Control>0", zoom_fit_tooltip, self._zoomFitCb),
+ "<Control>0", zoom_fit_tooltip, self._zoomFitCb),
# Alternate keyboard shortcuts to the actions above
("ControlEqualAccel", Gtk.STOCK_ZOOM_IN, None,
- "<Control>equal", zoom_in_tooltip, self._zoomInCb),
+ "<Control>equal", zoom_in_tooltip, self._zoomInCb),
("ControlKPAddAccel", Gtk.STOCK_ZOOM_IN, None,
- "<Control>KP_Add", zoom_in_tooltip, self._zoomInCb),
+ "<Control>KP_Add", zoom_in_tooltip, self._zoomInCb),
("ControlKPSubtractAccel", Gtk.STOCK_ZOOM_OUT, None,
- "<Control>KP_Subtract", zoom_out_tooltip, self._zoomOutCb),
+ "<Control>KP_Subtract", zoom_out_tooltip, self._zoomOutCb),
)
selection_actions = (
("DeleteObj", Gtk.STOCK_DELETE, None,
- "Delete", _("Delete Selected"), self._deleteSelected),
+ "Delete", _("Delete Selected"), self._deleteSelected),
("UngroupObj", "pitivi-ungroup", _("Ungroup"),
- "<Shift><Control>G", _("Ungroup clips"), self._ungroupSelected),
+ "<Shift><Control>G", _("Ungroup clips"), self._ungroupSelected),
# Translators: This is an action, the title of a button
("GroupObj", "pitivi-group", _("Group"),
- "<Control>G", _("Group clips"), self._groupSelected),
+ "<Control>G", _("Group clips"), self._groupSelected),
("AlignObj", "pitivi-align", _("Align"),
- "<Shift><Control>A", _("Align clips based on their soundtracks"), self._alignSelected),
+ "<Shift><Control>A", _("Align clips based on their soundtracks"), self._alignSelected),
)
playhead_actions = (
("PlayPause", Gtk.STOCK_MEDIA_PLAY, None,
- "space", _("Start Playback"), self._playPauseCb),
+ "space", _("Start Playback"), self._playPauseCb),
("Split", "pitivi-split", _("Split"),
- "S", _("Split clip at playhead position"), self._splitCb),
+ "S", _("Split clip at playhead position"), self._splitCb),
("Keyframe", "pitivi-keyframe", _("Add a Keyframe"),
- "K", _("Add a keyframe"), self._keyframeCb),
+ "K", _("Add a keyframe"), self._keyframeCb),
)
actiongroup = Gtk.ActionGroup(name="timelinepermanent")
@@ -1052,7 +1085,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
# last second of the timeline will be in view.
timeline_duration = duration + Gst.SECOND - 1
timeline_duration_s = int(timeline_duration / Gst.SECOND)
- self.debug("Adjusting zoom for a timeline duration of %s secs", timeline_duration_s)
+ self.debug(
+ "Adjusting zoom for a timeline duration of %s secs", timeline_duration_s)
ideal_zoom_ratio = float(ruler_width) / timeline_duration_s
nearest_zoom_level = Zoomable.computeZoomLevel(ideal_zoom_ratio)
@@ -1061,11 +1095,13 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
if not allow_zoom_in:
# For example when the user zoomed out and is adding clips
# to the timeline, zooming in would be confusing.
- self.log("Zoom not changed because the entire timeline is already visible")
+ self.log(
+ "Zoom not changed because the entire timeline is already visible")
return
Zoomable.setZoomLevel(nearest_zoom_level)
- self.bTimeline.set_snapping_distance(Zoomable.pixelToNs(self._settings.edgeSnapDeadband))
+ self.bTimeline.set_snapping_distance(
+ Zoomable.pixelToNs(self._settings.edgeSnapDeadband))
# Only do this at the very end, after updating the other widgets.
self.log("Setting 'zoomed_fitted' to True")
@@ -1074,26 +1110,30 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
def scroll_left(self):
# This method can be a callback for our events, or called by ruler.py
self._hscrollbar.set_value(self._hscrollbar.get_value() -
- self.hadj.props.page_size ** (2.0 / 3.0))
+ self.hadj.props.page_size ** (2.0 / 3.0))
def scroll_right(self):
# This method can be a callback for our events, or called by ruler.py
self._hscrollbar.set_value(self._hscrollbar.get_value() +
- self.hadj.props.page_size ** (2.0 / 3.0))
+ self.hadj.props.page_size ** (2.0 / 3.0))
def scroll_up(self):
self._vscrollbar.set_value(self._vscrollbar.get_value() -
- self.vadj.props.page_size ** (2.0 / 3.0))
+ self.vadj.props.page_size ** (2.0 / 3.0))
def scroll_down(self):
self._vscrollbar.set_value(self._vscrollbar.get_value() +
- self.vadj.props.page_size ** (2.0 / 3.0))
+ self.vadj.props.page_size ** (2.0 / 3.0))
def _scrollToPixel(self, x):
if x > self.hadj.props.upper:
- self.warning("Position %s is bigger than the hscrollbar's upper bound (%s) - is the position
really in pixels?" % (x, self.hadj.props.upper))
+ self.warning(
+ "Position %s is bigger than the hscrollbar's upper bound (%s) - is the position really in
pixels?" %
+ (x, self.hadj.props.upper))
elif x < self.hadj.props.lower:
- self.warning("Position %s is smaller than the hscrollbar's lower bound (%s)" % (x,
self.hadj.props.lower))
+ self.warning(
+ "Position %s is smaller than the hscrollbar's lower bound (%s)" %
+ (x, self.hadj.props.lower))
if self._project and self._project.pipeline.getState() != Gst.State.PLAYING:
self.timeline.save_easing_state()
@@ -1179,7 +1219,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
def _alignSelected(self, unused_action):
if not self.bTimeline:
- self.error("Trying to use the autoalign feature with an empty timeline")
+ self.error(
+ "Trying to use the autoalign feature with an empty timeline")
return
progress_dialog = AlignmentProgressDialog(self.app)
@@ -1261,7 +1302,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
def zoomChanged(self):
if self.bTimeline:
# zoomChanged might be called various times before the UI is ready
- self.bTimeline.set_snapping_distance(Zoomable.pixelToNs(self._settings.edgeSnapDeadband))
+ self.bTimeline.set_snapping_distance(
+ Zoomable.pixelToNs(self._settings.edgeSnapDeadband))
self.updateHScrollAdjustments()
@@ -1275,7 +1317,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
elif event.keyval == Gdk.KEY_Control_L:
self._controlMask = True
- # Now the second (independent) part: framestepping and seeking shortcuts
+ # Now the second (independent) part: framestepping and seeking
+ # shortcuts
if event.keyval == Gdk.KEY_Left:
if self._shiftMask:
self._seeker.seekRelative(0 - Gst.SECOND)
@@ -1307,7 +1350,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
def _timelineClickReleasedCb(self, unused_timeline, event):
if self.app and self.timeline.allowSeek is True:
- position = self.pixelToNs(event.x - CONTROL_WIDTH + self.timeline._scroll_point.x)
+ position = self.pixelToNs(
+ event.x - CONTROL_WIDTH + self.timeline._scroll_point.x)
self._seeker.seek(position)
self.timeline.allowSeek = True
@@ -1333,7 +1377,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
def _snapDistanceChangedCb(self, unused_settings):
if self.bTimeline:
- self.bTimeline.set_snapping_distance(Zoomable.pixelToNs(self._settings.edgeSnapDeadband))
+ self.bTimeline.set_snapping_distance(
+ Zoomable.pixelToNs(self._settings.edgeSnapDeadband))
def _projectChangedCb(self, unused_app, project, unused_fully_loaded):
"""
@@ -1357,7 +1402,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
if self._project:
self._project.disconnect_by_func(self._renderingSettingsChangedCb)
try:
- self.timeline._pipeline.disconnect_by_func(self.timeline.positionCb)
+ self.timeline._pipeline.disconnect_by_func(
+ self.timeline.positionCb)
except AttributeError:
pass
except TypeError:
@@ -1461,7 +1507,8 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
self.timeline.removeGhostClips()
def _dragDropCb(self, widget, context, x, y, timestamp):
- # Same as in insertEnd: this value changes during insertion, snapshot it
+ # Same as in insertEnd: this value changes during insertion, snapshot
+ # it
zoom_was_fitted = self.zoomed_fitted
target = widget.drag_dest_find_target(context, None)
@@ -1483,11 +1530,13 @@ class TimelineContainer(Gtk.Grid, Zoomable, Loggable):
margin = min(x, 50)
self.scrollToPixel(x - margin)
elif target.name() == "pitivi/effect":
- actor = self.stage.get_actor_at_pos(Clutter.PickMode.REACTIVE, x, y)
+ actor = self.stage.get_actor_at_pos(
+ Clutter.PickMode.REACTIVE, x, y)
bElement = actor.bElement
clip = bElement.get_parent()
factory_name = self.dropData
- self.app.gui.clipconfig.effect_expander.addEffectToClip(clip, factory_name)
+ self.app.gui.clipconfig.effect_expander.addEffectToClip(
+ clip, factory_name)
return True
def _dragDataReceivedCb(self, widget, drag_context, unused_x, unused_y, selection_data, unused_info,
timestamp):
diff --git a/pitivi/titleeditor.py b/pitivi/titleeditor.py
index 34097b1..3336867 100644
--- a/pitivi/titleeditor.py
+++ b/pitivi/titleeditor.py
@@ -42,6 +42,7 @@ BACKGROUND_DEFAULT_COLOR = 0x00000000 # Transparent
class TitleEditor(Loggable):
+
"""
Widget for configuring the selected title.
@@ -85,16 +86,16 @@ class TitleEditor(Loggable):
self.settings[setting] = builder.get_object(setting)
for n, en in list({_("Custom"): "position",
- _("Top"): "top",
- _("Center"): "center",
- _("Bottom"): "bottom",
- _("Baseline"): "baseline"}.items()):
+ _("Top"): "top",
+ _("Center"): "center",
+ _("Bottom"): "bottom",
+ _("Baseline"): "baseline"}.items()):
self.settings["valignment"].append(en, n)
for n, en in list({_("Custom"): "position",
- _("Left"): "left",
- _("Center"): "center",
- _("Right"): "right"}.items()):
+ _("Left"): "left",
+ _("Center"): "center",
+ _("Right"): "right"}.items()):
self.settings["halignment"].append(en, n)
self._deactivate()
@@ -107,7 +108,8 @@ class TitleEditor(Loggable):
def _frontTextColorButtonCb(self, widget):
color = gdk_rgba_to_argb(widget.get_rgba())
self.debug("Setting title foreground color to %x", color)
- # TODO: Use set_text_color when we work with TitleSources instead of TitleClips
+ # TODO: Use set_text_color when we work with TitleSources instead of
+ # TitleClips
self.source.set_color(color)
self.seeker.flush()
@@ -145,16 +147,20 @@ class TitleEditor(Loggable):
# FIXME: sometimes we get a TextOverlay/TitleSource
# without a valid text property. This should not happen.
source_text = ""
- self.warning('Source did not have a text property, setting it to "" to avoid pango choking up on
None')
+ self.warning(
+ 'Source did not have a text property, setting it to "" to avoid pango choking up on None')
self.log("Title text set to %s", source_text)
self.textbuffer.set_text(source_text)
self.settings['xpos'].set_value(self.source.get_xpos())
self.settings['ypos'].set_value(self.source.get_ypos())
- self.settings['valignment'].set_active_id(self.source.get_valignment().value_name)
- self.settings['halignment'].set_active_id(self.source.get_halignment().value_name)
+ self.settings['valignment'].set_active_id(
+ self.source.get_valignment().value_name)
+ self.settings['halignment'].set_active_id(
+ self.source.get_halignment().value_name)
- font_desc = Pango.FontDescription.from_string(self.source.get_font_desc())
+ font_desc = Pango.FontDescription.from_string(
+ self.source.get_font_desc())
self.font_button.set_font_desc(font_desc)
color = argb_to_gdk_rgba(self.source.get_text_color())
@@ -186,11 +192,15 @@ class TitleEditor(Loggable):
for name, obj in list(self.settings.items()):
if obj == updated_obj:
if name == "valignment":
- self.source.set_valignment(getattr(GES.TextVAlign, obj.get_active_id().upper()))
- self.settings["ypos"].set_visible(obj.get_active_id() == "position")
+ self.source.set_valignment(
+ getattr(GES.TextVAlign, obj.get_active_id().upper()))
+ self.settings["ypos"].set_visible(
+ obj.get_active_id() == "position")
elif name == "halignment":
- self.source.set_halignment(getattr(GES.TextHAlign, obj.get_active_id().upper()))
- self.settings["xpos"].set_visible(obj.get_active_id() == "position")
+ self.source.set_halignment(
+ getattr(GES.TextHAlign, obj.get_active_id().upper()))
+ self.settings["xpos"].set_visible(
+ obj.get_active_id() == "position")
elif name == "xpos":
self.settings["halignment"].set_active_id("position")
self.source.set_xpos(obj.get_value())
@@ -235,9 +245,12 @@ class TitleEditor(Loggable):
def _connect_signals(self):
if not self._signals_connected:
- self.app.gui.viewer.target.connect("motion-notify-event", self.drag_notify_event)
- self.app.gui.viewer.target.connect("button-press-event", self.drag_press_event)
- self.app.gui.viewer.target.connect("button-release-event", self.drag_release_event)
+ self.app.gui.viewer.target.connect(
+ "motion-notify-event", self.drag_notify_event)
+ self.app.gui.viewer.target.connect(
+ "button-press-event", self.drag_press_event)
+ self.app.gui.viewer.target.connect(
+ "button-release-event", self.drag_release_event)
self._signals_connected = True
def _disconnect_signals(self):
@@ -253,7 +266,8 @@ class TitleEditor(Loggable):
self._drag_events = [(event.x, event.y)]
# Update drag by drag event change, but not too often
self.timeout = GLib.timeout_add(100, self.drag_update_event)
- # If drag goes out for 0.3 second, and do not come back, consider drag end
+ # If drag goes out for 0.3 second, and do not come back, consider
+ # drag end
self._drag_updated = True
self.timeout = GLib.timeout_add(1000, self.drag_possible_end_event)
diff --git a/pitivi/transitions.py b/pitivi/transitions.py
index f58fbb9..9c4b162 100644
--- a/pitivi/transitions.py
+++ b/pitivi/transitions.py
@@ -42,6 +42,7 @@ from pitivi.utils.ui import SPACING
class TransitionsListWidget(Gtk.VBox, Loggable):
+
"""
Widget for configuring the selected transition.
@@ -58,30 +59,37 @@ class TransitionsListWidget(Gtk.VBox, Loggable):
icon_theme = Gtk.IconTheme.get_default()
self._question_icon = icon_theme.load_icon("dialog-question", 48, 0)
- #Tooltip handling
+ # Tooltip handling
self._current_transition_name = None
self._current_tooltip_icon = None
- #Searchbox
+ # Searchbox
self.searchbar = Gtk.HBox()
- self.searchbar.set_border_width(3) # Prevents being flush against the notebook
+ # Prevents being flush against the notebook
+ self.searchbar.set_border_width(3)
self.searchEntry = Gtk.Entry()
- self.searchEntry.set_icon_from_icon_name(Gtk.EntryIconPosition.SECONDARY, "edit-clear-symbolic")
+ self.searchEntry.set_icon_from_icon_name(
+ Gtk.EntryIconPosition.SECONDARY, "edit-clear-symbolic")
self.searchEntry.set_placeholder_text(_("Search..."))
self.searchbar.pack_end(self.searchEntry, True, True, 0)
self.props_widgets = Gtk.VBox()
borderTable = Gtk.Table(n_rows=2, n_columns=3)
- self.border_mode_normal = Gtk.RadioButton(group=None, label=_("Normal"))
- self.border_mode_loop = Gtk.RadioButton(group=self.border_mode_normal, label=_("Loop"))
+ self.border_mode_normal = Gtk.RadioButton(
+ group=None, label=_("Normal"))
+ self.border_mode_loop = Gtk.RadioButton(
+ group=self.border_mode_normal, label=_("Loop"))
self.border_mode_normal.set_active(True)
self.borderScale = Gtk.Scale.new(Gtk.Orientation.HORIZONTAL, None)
self.borderScale.set_draw_value(False)
- borderTable.attach(self.border_mode_normal, 0, 1, 0, 1, xoptions=Gtk.AttachOptions.FILL,
yoptions=Gtk.AttachOptions.FILL)
- borderTable.attach(self.border_mode_loop, 1, 2, 0, 1, xoptions=Gtk.AttachOptions.FILL,
yoptions=Gtk.AttachOptions.FILL)
- # The ypadding is a hack to make the slider widget align with the radiobuttons.
+ borderTable.attach(self.border_mode_normal, 0, 1, 0, 1,
+ xoptions=Gtk.AttachOptions.FILL, yoptions=Gtk.AttachOptions.FILL)
+ borderTable.attach(self.border_mode_loop, 1, 2, 0, 1,
+ xoptions=Gtk.AttachOptions.FILL, yoptions=Gtk.AttachOptions.FILL)
+ # The ypadding is a hack to make the slider widget align with the
+ # radiobuttons.
borderTable.attach(self.borderScale, 2, 3, 0, 2, ypadding=SPACING * 2)
self.invert_checkbox = Gtk.CheckButton(label=_("Reverse direction"))
@@ -110,12 +118,12 @@ class TransitionsListWidget(Gtk.VBox, Loggable):
# FIXME: the "never" horizontal scroll policy in GTK2 messes up iconview
# Re-enable this when we switch to GTK3
# See also http://python.6.n6.nabble.com/Cannot-shrink-width-of-scrolled-textview-tp1945060.html
- #self.iconview_scrollwin.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
+ # self.iconview_scrollwin.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
self.iconview = Gtk.IconView(model=self.storemodel)
self.iconview.set_pixbuf_column(COL_ICON)
# We don't show text because we have a searchbar and the names are ugly
- #self.iconview.set_text_column(COL_NAME_TEXT)
+ # self.iconview.set_text_column(COL_NAME_TEXT)
self.iconview.set_item_width(48 + 10)
self.iconview_scrollwin.add(self.iconview)
self.iconview.set_property("has_tooltip", True)
@@ -156,7 +164,8 @@ class TransitionsListWidget(Gtk.VBox, Loggable):
# The user clicked between icons
return False
- self.debug("New transition type selected: %s", transition_asset.get_id())
+ self.debug(
+ "New transition type selected: %s", transition_asset.get_id())
if transition_asset.get_id() == "crossfade":
self.props_widgets.set_sensitive(False)
else:
@@ -187,14 +196,18 @@ class TransitionsListWidget(Gtk.VBox, Loggable):
if widget == self.border_mode_loop:
self.borderScale.set_range(50000, 500000)
self.borderScale.clear_marks()
- self.borderScale.add_mark(50000, Gtk.PositionType.BOTTOM, _("Slow"))
- self.borderScale.add_mark(200000, Gtk.PositionType.BOTTOM, _("Fast"))
- self.borderScale.add_mark(500000, Gtk.PositionType.BOTTOM, _("Epileptic"))
+ self.borderScale.add_mark(
+ 50000, Gtk.PositionType.BOTTOM, _("Slow"))
+ self.borderScale.add_mark(
+ 200000, Gtk.PositionType.BOTTOM, _("Fast"))
+ self.borderScale.add_mark(
+ 500000, Gtk.PositionType.BOTTOM, _("Epileptic"))
else:
self.borderScale.set_range(0, 25000)
self.borderScale.clear_marks()
self.borderScale.add_mark(0, Gtk.PositionType.BOTTOM, _("Sharp"))
- self.borderScale.add_mark(25000, Gtk.PositionType.BOTTOM, _("Smooth"))
+ self.borderScale.add_mark(
+ 25000, Gtk.PositionType.BOTTOM, _("Smooth"))
def _searchEntryChangedCb(self, unused_entry):
self.modelFilter.refilter()
@@ -211,7 +224,8 @@ class TransitionsListWidget(Gtk.VBox, Loggable):
pass
finally:
self.selectTransition(element.get_asset())
- self.iconview.connect("button-release-event", self._transitionSelectedCb)
+ self.iconview.connect(
+ "button-release-event", self._transitionSelectedCb)
def _borderChangedCb(self, element, unused_prop):
"""
@@ -249,13 +263,15 @@ class TransitionsListWidget(Gtk.VBox, Loggable):
trans_asset.icon = self._getIcon(trans_asset.get_id())
self.storemodel.append([trans_asset,
str(trans_asset.get_id()),
- str(trans_asset.get_meta(GES.META_DESCRIPTION)),
+ str(trans_asset.get_meta(
+ GES.META_DESCRIPTION)),
trans_asset.icon])
# Now that the UI is fully ready, enable searching
self.modelFilter.set_visible_func(self._setRowVisible, data=None)
# Alphabetical/name sorting instead of based on the ID number
- self.storemodel.set_sort_column_id(COL_NAME_TEXT, Gtk.SortType.ASCENDING)
+ self.storemodel.set_sort_column_id(
+ COL_NAME_TEXT, Gtk.SortType.ASCENDING)
def activate(self, element):
"""
@@ -320,13 +336,15 @@ class TransitionsListWidget(Gtk.VBox, Loggable):
name = transition_nick + ".png"
icon = None
try:
- icon = GdkPixbuf.Pixbuf.new_from_file(os.path.join(self._pixdir, name))
+ icon = GdkPixbuf.Pixbuf.new_from_file(
+ os.path.join(self._pixdir, name))
except:
icon = self._question_icon
return icon
def _queryTooltipCb(self, view, x, y, keyboard_mode, tooltip):
- is_row, x, y, model, path, iter_ = view.get_tooltip_context(x, y, keyboard_mode)
+ is_row, x, y, model, path, iter_ = view.get_tooltip_context(
+ x, y, keyboard_mode)
if not is_row:
return False
diff --git a/pitivi/undo/effect.py b/pitivi/undo/effect.py
index 613f2b7..3b423d9 100644
--- a/pitivi/undo/effect.py
+++ b/pitivi/undo/effect.py
@@ -28,6 +28,7 @@ from pitivi.effects import PROPS_TO_IGNORE
class EffectPropertyChanged(UndoableAction):
+
def __init__(self, effect, property_name, old_value, new_value):
UndoableAction.__init__(self)
self.effect = effect
@@ -47,9 +48,11 @@ class EffectPropertyChanged(UndoableAction):
# FIXME We should refactor pitivi.undo.PropertyChangeTracker so we can use it as
# a baseclass here!
class EffectGstElementPropertyChangeTracker:
+
"""
Track effect configuration changes in its list of control effects
"""
+
def __init__(self, action_log):
self._tracked_effects = {}
self.action_log = action_log
@@ -74,7 +77,8 @@ class EffectGstElementPropertyChangeTracker:
def _propertyChangedCb(self, effect, unused_gstelement, pspec):
old_value = self._tracked_effects[effect][pspec.name]
new_value = effect.get_child_property(pspec.name)[1]
- action = EffectPropertyChanged(effect, pspec.name, old_value, new_value)
+ action = EffectPropertyChanged(
+ effect, pspec.name, old_value, new_value)
self._tracked_effects[effect][pspec.name] = new_value
self.action_log.push(action)
@@ -87,6 +91,7 @@ class EffectAdded(UndoableAction):
# doing again. We have to keep all EffectPropertyChanged object that refers
# to the Effect when undoing so we reset theirs effect when
# doing it again. The way of doing it is the same with EffectRemoved
+
def __init__(self, clip, effect, properties_watcher):
UndoableAction.__init__(self)
self.clip = clip
@@ -108,9 +113,9 @@ class EffectAdded(UndoableAction):
def undo(self):
props = self.effect.list_children_properties()
self.effect_props = [(prop.name, self.effect.get_child_property(prop.name)[1])
- for prop in props
- if prop.flags & GObject.PARAM_WRITABLE
- and prop.name not in PROPS_TO_IGNORE]
+ for prop in props
+ if prop.flags & GObject.PARAM_WRITABLE
+ and prop.name not in PROPS_TO_IGNORE]
self.clip.remove(self.effect)
self._props_changed =\
self._properties_watcher.getPropChangedFromEffect(self.effect)
@@ -120,6 +125,7 @@ class EffectAdded(UndoableAction):
class EffectRemoved(UndoableAction):
+
def __init__(self, clip, effect, properties_watcher):
UndoableAction.__init__(self)
self.effect = effect
@@ -133,9 +139,9 @@ class EffectRemoved(UndoableAction):
def do(self):
props = self.effect.list_children_properties()
self.effect_props = [(prop.name, self.effect.get_child_property(prop.name)[1])
- for prop in props
- if prop.flags & GObject.PARAM_WRITABLE
- and prop.name not in PROPS_TO_IGNORE]
+ for prop in props
+ if prop.flags & GObject.PARAM_WRITABLE
+ and prop.name not in PROPS_TO_IGNORE]
self.clip.remove(self.effect)
diff --git a/pitivi/undo/timeline.py b/pitivi/undo/timeline.py
index 0c1203b..d1af68f 100644
--- a/pitivi/undo/timeline.py
+++ b/pitivi/undo/timeline.py
@@ -49,7 +49,8 @@ class ClipPropertyChangeTracker(PropertyChangeTracker):
for property_name, property_value in properties.items():
old_value = self.properties[property_name]
if old_value != property_value:
- self._propertyChangedCb(self.obj, property_value, property_name)
+ self._propertyChangedCb(
+ self.obj, property_value, property_name)
class KeyframeChangeTracker(GObject.Object):
@@ -90,7 +91,8 @@ class KeyframeChangeTracker(GObject.Object):
old_snapshot = self.keyframes[keyframe]
new_snapshot = self._getKeyframeSnapshot(keyframe)
self.keyframes[keyframe] = new_snapshot
- self.emit("keyframe-moved", interpolator, keyframe, old_snapshot, new_snapshot)
+ self.emit("keyframe-moved", interpolator,
+ keyframe, old_snapshot, new_snapshot)
def _getKeyframeSnapshot(self, keyframe):
return (keyframe.mode, keyframe.time, keyframe.value)
@@ -106,11 +108,13 @@ class ClipPropertyChanged(UndoableAction):
self.new_value = new_value
def do(self):
- self.clip.set_property(self.property_name.replace("-", "_"), self.new_value)
+ self.clip.set_property(
+ self.property_name.replace("-", "_"), self.new_value)
self._done()
def undo(self):
- self.clip.set_property(self.property_name.replace("-", "_"), self.old_value)
+ self.clip.set_property(
+ self.property_name.replace("-", "_"), self.old_value)
self._undone()
@@ -165,6 +169,7 @@ class ClipRemoved(UndoableAction):
class LayerAdded(UndoableAction):
+
def __init__(self, timeline, layer):
self.timeline = timeline
self.layer = layer
@@ -182,6 +187,7 @@ class LayerAdded(UndoableAction):
class LayerRemoved(UndoableAction):
+
def __init__(self, timeline, layer):
self.timeline = timeline
self.layer = layer
@@ -227,7 +233,7 @@ class InterpolatorKeyframeRemoved(UndoableAction):
def undo(self):
self.track_element.newKeyframe(self.keyframe.time,
- self.keyframe.value, self.keyframe.mode)
+ self.keyframe.value, self.keyframe.mode)
self._done()
@@ -284,7 +290,8 @@ class TimelineLogObserver(object):
self.log = log
self.clip_property_trackers = {}
self.interpolator_keyframe_trackers = {}
- self.effect_properties_tracker = EffectGstElementPropertyChangeTracker(log)
+ self.effect_properties_tracker = EffectGstElementPropertyChangeTracker(
+ log)
self._pipeline = None
def setPipeline(self, pipeline):
@@ -333,7 +340,8 @@ class TimelineLogObserver(object):
attr_name = "last-%s" % property_name
last_value = clip.get_property(property_name)
setattr(tracker, attr_name, last_value)
- tracker.connect("monitored-property-changed", self._clipPropertyChangedCb)
+ tracker.connect(
+ "monitored-property-changed", self._clipPropertyChangedCb)
self.clip_property_trackers[clip] = tracker
clip.connect("child-added", self._clipTrackElementAddedCb)
@@ -359,8 +367,10 @@ class TimelineLogObserver(object):
# self._disconnectFromInterpolator(interpolator)
def _connectToInterpolator(self, interpolator):
- interpolator.connect("keyframe-added", self._interpolatorKeyframeAddedCb)
- interpolator.connect("keyframe-removed", self._interpolatorKeyframeRemovedCb)
+ interpolator.connect(
+ "keyframe-added", self._interpolatorKeyframeAddedCb)
+ interpolator.connect(
+ "keyframe-removed", self._interpolatorKeyframeRemovedCb)
tracker = KeyframeChangeTracker()
tracker.connectToObject(interpolator)
tracker.connect("keyframe-moved", self._interpolatorKeyframeMovedCb)
@@ -382,12 +392,12 @@ class TimelineLogObserver(object):
self.log.push(action)
def _clipPropertyChangedCb(self, tracker, clip,
- property_name, old_value, new_value):
+ property_name, old_value, new_value):
attr_name = "last-%s" % property_name
new_value = clip.get_property(property_name)
old_value = getattr(tracker, attr_name)
action = self.timelinePropertyChangedAction(clip, property_name,
- old_value, new_value)
+ old_value, new_value)
setattr(tracker, attr_name, new_value)
self.log.push(action)
@@ -411,7 +421,8 @@ class TimelineLogObserver(object):
self.log.push(action)
def _interpolatorKeyframeRemovedCb(self, track_element, keyframe, old_value=None):
- action = self.interpolatorKeyframeRemovedAction(track_element, keyframe)
+ action = self.interpolatorKeyframeRemovedAction(
+ track_element, keyframe)
self.log.push(action)
def _trackElementActiveChangedCb(self, track_element, active, add_effect_action):
@@ -422,9 +433,9 @@ class TimelineLogObserver(object):
self.log.push(action)
def _interpolatorKeyframeMovedCb(self, tracker, track_element,
- keyframe, old_snapshot, new_snapshot):
+ keyframe, old_snapshot, new_snapshot):
action = self.interpolatorKeyframeChangedAction(track_element,
- keyframe, old_snapshot, new_snapshot)
+ keyframe, old_snapshot, new_snapshot)
self.log.push(action)
def _layerAddedCb(self, timeline, layer):
diff --git a/pitivi/undo/undo.py b/pitivi/undo/undo.py
index e9f21db..0f933b7 100644
--- a/pitivi/undo/undo.py
+++ b/pitivi/undo/undo.py
@@ -31,16 +31,19 @@ from pitivi.utils.loggable import Loggable
class UndoError(Exception):
+
""" Any exception related to the undo/redo feature."""
pass
class UndoWrongStateError(UndoError):
+
""" Exception related to the current state of the undo/redo stack. """
pass
class UndoableAction(GObject.Object):
+
"""
An action that can be undone.
In other words, when your object's state changes, create an UndoableAction
@@ -76,6 +79,7 @@ class UndoableAction(GObject.Object):
class UndoableActionStack(UndoableAction):
+
"""
Simply a stack of UndoableAction objects.
"""
@@ -118,6 +122,7 @@ class UndoableActionStack(UndoableAction):
class UndoableActionLog(GObject.Object, Loggable):
+
"""
This is the "master" class that handles all the undo/redo system. There is
only one instance of it in Pitivi: application.py's "action_log" property.
@@ -152,7 +157,8 @@ class UndoableActionLog(GObject.Object, Loggable):
stack = UndoableActionStack(action_group_name)
nested = self._stackIsNested(stack)
self.stacks.append(stack)
- self.debug("begin action group %s, nested %s", stack.action_group_name, nested)
+ self.debug("begin action group %s, nested %s",
+ stack.action_group_name, nested)
self.emit("begin", stack, nested)
def push(self, action):
@@ -175,7 +181,8 @@ class UndoableActionLog(GObject.Object, Loggable):
return
stack.push(action)
- self.debug("push action %s in action group %s", action, stack.action_group_name)
+ self.debug("push action %s in action group %s",
+ action, stack.action_group_name)
self.emit("push", stack, action)
def rollback(self):
@@ -188,7 +195,8 @@ class UndoableActionLog(GObject.Object, Loggable):
if stack is None:
return
nested = self._stackIsNested(stack)
- self.debug("rollback action group %s, nested %s", stack.action_group_name, nested)
+ self.debug("rollback action group %s, nested %s",
+ stack.action_group_name, nested)
self.emit("rollback", stack, nested)
stack.undo()
@@ -210,7 +218,8 @@ class UndoableActionLog(GObject.Object, Loggable):
if self.redo_stacks:
self.redo_stacks = []
- self.debug("commit action group %s nested %s", stack.action_group_name, nested)
+ self.debug("commit action group %s nested %s",
+ stack.action_group_name, nested)
self.emit("commit", stack, nested)
def undo(self):
@@ -277,6 +286,7 @@ class UndoableActionLog(GObject.Object, Loggable):
class PropertyChangeTracker(GObject.Object):
+
"""
BaseClass to track a class property, Used for undo/redo
"""
@@ -306,7 +316,8 @@ class PropertyChangeTracker(GObject.Object):
def _takeCurrentSnapshot(cls, obj):
properties = {}
for property_name in cls.property_names:
- properties[property_name] = obj.get_property(property_name.replace("-", "_"))
+ properties[property_name] = obj.get_property(
+ property_name.replace("-", "_"))
return properties
@@ -317,4 +328,5 @@ class PropertyChangeTracker(GObject.Object):
def _propertyChangedCb(self, object, property_value, property_name):
old_value = self.properties[property_name]
self.properties[property_name] = property_value
- self.emit("monitored-property-changed", object, property_name, old_value, property_value)
+ self.emit("monitored-property-changed", object,
+ property_name, old_value, property_value)
diff --git a/pitivi/utils/extract.py b/pitivi/utils/extract.py
index 738b764..2d411dd 100644
--- a/pitivi/utils/extract.py
+++ b/pitivi/utils/extract.py
@@ -30,8 +30,8 @@ Code derived from ui/previewer.py.
from gi.repository import Gst
from collections import deque
-#from pitivi.elements.singledecodebin import SingleDecodeBin
-#from pitivi.elements.extractionsink import ExtractionSink
+# from pitivi.elements.singledecodebin import SingleDecodeBin
+# from pitivi.elements.extractionsink import ExtractionSink
from pitivi.utils.loggable import Loggable
@@ -216,10 +216,10 @@ class RandomAccessAudioExtractor(RandomAccessExtractor):
self.debug("processing segment with timestamp=%i and duration=%i",
timestamp, duration)
res = self.audioPipeline.seek(1.0,
- Gst.Format.TIME,
- Gst.SeekFlags.FLUSH | Gst.SeekFlags.ACCURATE,
- Gst.SeekType.SET, timestamp,
- Gst.SeekType.SET, timestamp + duration)
+ Gst.Format.TIME,
+ Gst.SeekFlags.FLUSH | Gst.SeekFlags.ACCURATE,
+ Gst.SeekType.SET, timestamp,
+ Gst.SeekType.SET, timestamp + duration)
if not res:
self.warning("seek failed %s", timestamp)
self.audioPipeline.set_state(Gst.State.PLAYING)
diff --git a/pitivi/utils/loggable.py b/pitivi/utils/loggable.py
index f4f9a9f..a01e8e3 100644
--- a/pitivi/utils/loggable.py
+++ b/pitivi/utils/loggable.py
@@ -72,6 +72,7 @@ _LEVEL_NAMES = ['ERROR', 'WARN', 'FIXME', 'INFO', 'DEBUG', 'LOG']
class TerminalController:
+
"""
A class that can be used to portably generate formatted output to
a terminal.
@@ -200,7 +201,8 @@ class TerminalController:
if set_bg_ansi:
for i, color in zip(list(range(len(self._ANSICOLORS))),
self._ANSICOLORS):
- setattr(self, 'BG_' + color, curses.tparm(set_bg_ansi, i) or b'')
+ setattr(
+ self, 'BG_' + color, curses.tparm(set_bg_ansi, i) or b'')
def _tigetstr(self, cap_name):
# String capabilities can include "delays" of the form "$<2>".
@@ -225,12 +227,13 @@ class TerminalController:
else:
return getattr(self, s[2:-1])
-#######################################################################
+#
# Example use case: progress bar
-#######################################################################
+#
class ProgressBar:
+
"""
A 3-line progress bar, which looks like::
@@ -358,7 +361,7 @@ def getCategoryLevel(category):
if it wasn't registered yet.
"""
global _categories
- if not category in _categories:
+ if category not in _categories:
registerCategory(category)
return _categories[category]
@@ -626,19 +629,20 @@ def stderrHandler(level, object, category, file, line, message):
# show a bazillion of debug details that are not relevant to Pitivi.
if not _enableCrackOutput:
safeprintf(sys.stderr, '%s %-8s %-17s %-2s %s %s\n',
- getFormattedLevelName(level), time.strftime("%H:%M:%S"),
- category, "", message, where)
+ getFormattedLevelName(level), time.strftime("%H:%M:%S"),
+ category, "", message, where)
else:
o = ""
if object:
o = '"' + object + '"'
# level pid object cat time
# 5 + 1 + 7 + 1 + 32 + 1 + 17 + 1 + 15 == 80
- safeprintf(sys.stderr, '%s [%5d] [0x%12x] %-32s %-17s %-15s %-4s %s %s\n',
- getFormattedLevelName(level), os.getpid(),
- threading.current_thread().ident,
- o[:32], category, time.strftime("%b %d %H:%M:%S"), "",
- message, where)
+ safeprintf(
+ sys.stderr, '%s [%5d] [0x%12x] %-32s %-17s %-15s %-4s %s %s\n',
+ getFormattedLevelName(level), os.getpid(),
+ threading.current_thread().ident,
+ o[:32], category, time.strftime("%b %d %H:%M:%S"), "",
+ message, where)
sys.stderr.flush()
@@ -655,18 +659,18 @@ def _preformatLevels(enableColorOutput):
if type(t.BOLD) == bytes:
formatter = lambda level: ''.join(
(t.BOLD.decode(), getattr(t, COLORS[level]).decode(),
- logLevelName(level), t.NORMAL.decode()))
+ logLevelName(level), t.NORMAL.decode()))
else:
formatter = lambda level: ''.join(
(t.BOLD, getattr(t, COLORS[level]),
- logLevelName(level), t.NORMAL))
+ logLevelName(level), t.NORMAL))
else:
formatter = lambda level: logLevelName(level)
for level in ERROR, WARN, FIXME, INFO, DEBUG, LOG:
_FORMATTED_LEVELS.append(formatter(level))
-### "public" useful API
+# "public" useful API
# setup functions
@@ -848,7 +852,7 @@ def getExceptionMessage(exception, frame=-1, filename=None):
stack = traceback.extract_tb(sys.exc_info()[2])
if filename:
stack = [f for f in stack if f[0].find(filename) > -1]
- #import code; code.interact(local=locals())
+ # import code; code.interact(local=locals())
(filename, line, func, text) = stack[frame]
filename = scrubFilename(filename)
exc = exception.__class__.__name__
@@ -923,6 +927,7 @@ def outputToFiles(stdout=None, stderr=None):
class BaseLoggable(object):
+
"""
Base class for objects that want to be able to log messages with
different level of severity. The levels are, in order from least
@@ -954,37 +959,43 @@ class BaseLoggable(object):
"""Log an error. By default this will also raise an exception."""
if _canShortcutLogging(self.logCategory, ERROR):
return
- errorObject(self.logObjectName(), self.logCategory, *self.logFunction(*args))
+ errorObject(self.logObjectName(),
+ self.logCategory, *self.logFunction(*args))
def warning(self, *args):
"""Log a warning. Used for non-fatal problems."""
if _canShortcutLogging(self.logCategory, WARN):
return
- warningObject(self.logObjectName(), self.logCategory, *self.logFunction(*args))
+ warningObject(
+ self.logObjectName(), self.logCategory, *self.logFunction(*args))
def fixme(self, *args):
"""Log a fixme. Used for FIXMEs ."""
if _canShortcutLogging(self.logCategory, FIXME):
return
- fixmeObject(self.logObjectName(), self.logCategory, *self.logFunction(*args))
+ fixmeObject(self.logObjectName(),
+ self.logCategory, *self.logFunction(*args))
def info(self, *args):
"""Log an informational message. Used for normal operation."""
if _canShortcutLogging(self.logCategory, INFO):
return
- infoObject(self.logObjectName(), self.logCategory, *self.logFunction(*args))
+ infoObject(self.logObjectName(),
+ self.logCategory, *self.logFunction(*args))
def debug(self, *args):
"""Log a debug message. Used for debugging."""
if _canShortcutLogging(self.logCategory, DEBUG):
return
- debugObject(self.logObjectName(), self.logCategory, *self.logFunction(*args))
+ debugObject(self.logObjectName(),
+ self.logCategory, *self.logFunction(*args))
def log(self, *args):
"""Log a log message. Used for debugging recurring events."""
if _canShortcutLogging(self.logCategory, LOG):
return
- logObject(self.logObjectName(), self.logCategory, *self.logFunction(*args))
+ logObject(self.logObjectName(),
+ self.logCategory, *self.logFunction(*args))
def doLog(self, level, where, format, *args, **kwargs):
"""
@@ -1008,7 +1019,7 @@ class BaseLoggable(object):
return {}
args = self.logFunction(*args)
return doLog(level, self.logObjectName(), self.logCategory,
- format, args, where=where, **kwargs)
+ format, args, where=where, **kwargs)
def logFunction(self, *args):
"""Overridable log function. Default just returns passed message."""
@@ -1028,6 +1039,7 @@ class BaseLoggable(object):
class Loggable(BaseLoggable):
+
def __init__(self, logCategory=None):
if logCategory:
self.logCategory = logCategory
@@ -1044,4 +1056,4 @@ class Loggable(BaseLoggable):
if _canShortcutLogging(self.logCategory, ERROR):
return
doLog(ERROR, self.logObjectName(), self.logCategory,
- format, self.logFunction(*args), where=-2)
+ format, self.logFunction(*args), where=-2)
diff --git a/pitivi/utils/misc.py b/pitivi/utils/misc.py
index 704c65c..b383413 100644
--- a/pitivi/utils/misc.py
+++ b/pitivi/utils/misc.py
@@ -147,6 +147,7 @@ def quote_uri(uri):
class PathWalker(Thread):
+
"""
Thread for recursively searching in a list of directories
"""
@@ -169,7 +170,7 @@ class PathWalker(Thread):
uris = []
for afile in files:
uris.append(quote_uri("file://%s" %
- os.path.join(path, afile)))
+ os.path.join(path, afile)))
if uris:
GLib.idle_add(self.callback, uris)
diff --git a/pitivi/utils/pipeline.py b/pitivi/utils/pipeline.py
index 7592fe1..8c0fa05 100644
--- a/pitivi/utils/pipeline.py
+++ b/pitivi/utils/pipeline.py
@@ -52,6 +52,7 @@ class PipelineError(Exception):
class Seeker(GObject.Object, Loggable):
+
"""
The Seeker is a singleton helper class to do various seeking
operations in the pipeline.
@@ -91,7 +92,8 @@ class Seeker(GObject.Object, Loggable):
if self.pending_seek_id is None:
if on_idle:
- self.pending_seek_id = self._scheduleSeek(self.timeout, self._seekTimeoutCb)
+ self.pending_seek_id = self._scheduleSeek(
+ self.timeout, self._seekTimeoutCb)
else:
self._seekTimeoutCb()
else:
@@ -101,7 +103,8 @@ class Seeker(GObject.Object, Loggable):
if self.pending_seek_id is None:
self._time = int(time)
if on_idle:
- self.pending_seek_id = self._scheduleSeek(self.timeout, self._seekTimeoutCb, relative=True)
+ self.pending_seek_id = self._scheduleSeek(
+ self.timeout, self._seekTimeoutCb, relative=True)
else:
self._seekTimeoutCb(relative=True)
@@ -144,6 +147,7 @@ class Seeker(GObject.Object, Loggable):
class SimplePipeline(GObject.Object, Loggable):
+
"""
The Pipeline is only responsible for:
- State changes
@@ -224,7 +228,8 @@ class SimplePipeline(GObject.Object, Loggable):
if res == Gst.StateChangeReturn.FAILURE:
# reset to NULL
self._pipeline.set_state(Gst.State.NULL)
- raise PipelineError("Failure changing state of the Gst.Pipeline to %r, currently reset to NULL"
% state)
+ raise PipelineError(
+ "Failure changing state of the Gst.Pipeline to %r, currently reset to NULL" % state)
def getState(self):
"""
@@ -236,8 +241,10 @@ class SimplePipeline(GObject.Object, Loggable):
@return: The current state.
@rtype: C{State}
"""
- change, state, pending = self._pipeline.get_state(timeout=0) # No timeout
- self.debug("change: %r, state: %r, pending: %r", change, state, pending)
+ # No timeout
+ change, state, pending = self._pipeline.get_state(timeout=0)
+ self.debug(
+ "change: %r, state: %r, pending: %r", change, state, pending)
return state
def play(self):
@@ -357,7 +364,8 @@ class SimplePipeline(GObject.Object, Loggable):
# i.e. it does NOT check for current state
if listen:
if self._listening and self._listeningSigId == 0:
- self._listeningSigId = GLib.timeout_add(self._listeningInterval,
+ self._listeningSigId = GLib.timeout_add(
+ self._listeningInterval,
self._positionListenerCb)
elif self._listeningSigId != 0:
GLib.source_remove(self._listeningSigId)
@@ -416,7 +424,8 @@ class SimplePipeline(GObject.Object, Loggable):
prev, new, pending = message.parse_state_changed()
if message.src == self._pipeline:
- self.debug("Pipeline change state prev: %r, new: %r, pending: %r", prev, new, pending)
+ self.debug(
+ "Pipeline change state prev: %r, new: %r, pending: %r", prev, new, pending)
emit_state_change = pending == Gst.State.VOID_PENDING
if prev == Gst.State.READY and new == Gst.State.PAUSED:
@@ -430,7 +439,8 @@ class SimplePipeline(GObject.Object, Loggable):
if self.pendingRecovery:
self.simple_seek(self.lastPosition)
self.pendingRecovery = False
- self.info("Seeked back to the last position after pipeline recovery")
+ self.info(
+ "Seeked back to the last position after pipeline recovery")
elif prev == Gst.State.PAUSED and new == Gst.State.PLAYING:
self._listenToPosition(True)
elif prev == Gst.State.PLAYING and new == Gst.State.PAUSED:
@@ -462,7 +472,8 @@ class SimplePipeline(GObject.Object, Loggable):
def _recover(self):
if self._attempted_recoveries > MAX_RECOVERIES:
- self.warning("Pipeline error detected multiple times in a row, not resetting anymore")
+ self.warning(
+ "Pipeline error detected multiple times in a row, not resetting anymore")
return
self.warning("Pipeline error detected during playback, resetting")
self.pendingRecovery = True
@@ -494,6 +505,7 @@ class SimplePipeline(GObject.Object, Loggable):
class AssetPipeline(SimplePipeline):
+
"""
Pipeline for playing a single clip.
"""
@@ -519,6 +531,7 @@ class AssetPipeline(SimplePipeline):
class Pipeline(GES.Pipeline, SimplePipeline):
+
"""
Helper to handle GES.Pipeline through the SimplePipeline API
and handle the Seeker properly
@@ -570,17 +583,19 @@ class Pipeline(GES.Pipeline, SimplePipeline):
try:
position = self.getPosition()
except PipelineError:
- self.warning("Couldn't get position (you're framestepping too quickly), ignoring this request")
+ self.warning(
+ "Couldn't get position (you're framestepping too quickly), ignoring this request")
return
- cur_frame = int(round(position * framerate.num / float(Gst.SECOND * framerate.denom), 2))
+ cur_frame = int(
+ round(position * framerate.num / float(Gst.SECOND * framerate.denom), 2))
new_frame = cur_frame + frames_offset
new_pos = int(new_frame * Gst.SECOND * framerate.denom / framerate.num)
Loggable.info(self, "From frame %d to %d at %f fps, seek to %s s",
- cur_frame,
- new_frame,
- framerate.num / framerate.denom,
- new_pos / float(Gst.SECOND))
+ cur_frame,
+ new_frame,
+ framerate.num / framerate.denom,
+ new_pos / float(Gst.SECOND))
self.simple_seek(new_pos)
def _seekCb(self, unused_seeker, position):
@@ -596,7 +611,8 @@ class Pipeline(GES.Pipeline, SimplePipeline):
st = Gst.Structure.new_empty("seek")
if self.getState() == Gst.State.PLAYING:
- st.set_value("playback_time", float(self.getPosition()) / Gst.SECOND)
+ st.set_value("playback_time", float(
+ self.getPosition()) / Gst.SECOND)
st.set_value("start", float(position / Gst.SECOND))
st.set_value("flags", "accurate+flush")
diff --git a/pitivi/utils/ripple_update_group.py b/pitivi/utils/ripple_update_group.py
index b746623..a2fe821 100644
--- a/pitivi/utils/ripple_update_group.py
+++ b/pitivi/utils/ripple_update_group.py
@@ -21,6 +21,7 @@
class RippleUpdateGroup(object):
+
"""Allows for event-driven spreadsheet-like ripple updates without
infinite loops.
@@ -75,7 +76,7 @@ class RippleUpdateGroup(object):
self.ignore_new_signals = False
def addVertex(self, widget, signal=None, update_func=None,
- update_func_args=()):
+ update_func_args=()):
"""Add a widget to the list of vertexes.
@param widget: The vertex to be added.
diff --git a/pitivi/utils/system.py b/pitivi/utils/system.py
index 4f8a155..acb4f88 100644
--- a/pitivi/utils/system.py
+++ b/pitivi/utils/system.py
@@ -31,6 +31,7 @@ from pitivi.utils.loggable import Loggable
class System(GObject.Object, Loggable):
+
"""
A base class for systems in which Pitivi runs.
"""
@@ -49,7 +50,7 @@ class System(GObject.Object, Loggable):
self._screensaver_keys = []
self._sleep_keys = []
- # Generic functions
+ # generic functions
def _inhibit(self, list_, key):
assert key is not None
assert isinstance(key, str)
@@ -80,7 +81,7 @@ class System(GObject.Object, Loggable):
return False
- # Screensaver
+ # screensaver
def inhibitScreensaver(self, key):
"""increase screensaver inhibitor count
@arg key: C{str} a unique translated string, giving the reason for
@@ -166,6 +167,7 @@ class System(GObject.Object, Loggable):
class FreedesktopOrgSystem(System):
+
"""provides messaging capabilites for desktops that implement fd.o specs"""
def __init__(self):
@@ -175,7 +177,7 @@ class FreedesktopOrgSystem(System):
Notify.init(APPNAME)
def desktopMessage(self, title, message, icon="pitivi"):
- # Call super method for consistent logging
+ # call super method for consistent logging
System.desktopMessage(self, title, message, icon)
if "Notify" not in missing_soft_deps:
@@ -185,8 +187,10 @@ class FreedesktopOrgSystem(System):
notification.show()
except RuntimeError as e:
# This can happen if the system is not properly configured.
- # See for example https://bugzilla.gnome.org/show_bug.cgi?id=719627.
- self.error("desktopMessage: Failed displaying notification: %s", e.message)
+ # See for example
+ # https://bugzilla.gnome.org/show_bug.cgi?id=719627.
+ self.error(
+ "desktopMessage: Failed displaying notification: %s", e.message)
return None
return notification
return None
@@ -204,14 +208,16 @@ COOKIE_SLEEP = 2
class GnomeSystem(FreedesktopOrgSystem):
+
def __init__(self):
FreedesktopOrgSystem.__init__(self)
self.bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
+ # connect to gnome sessionmanager
self.sessionmanager = self.bus.get_object('org.gnome.SessionManager',
- '/org/gnome/SessionManager')
+ '/org/gnome/SessionManager')
self.session_iface = dbus.Interface(self.sessionmanager,
- 'org.gnome.SessionManager')
+ 'org.gnome.SessionManager')
self.cookie = None
self.cookie_type = COOKIE_NONE
@@ -224,19 +230,19 @@ class GnomeSystem(FreedesktopOrgSystem):
return True
def _updatePowerInhibitionCb(self, unused_system):
- # There are two states we want the program to be in, with regards to
- # power saving: the screen saver is inhibited while playing, and we
- # inhibit sleep/powersaving when processing data. Things are done the
- # way they are here because the viewer typically shows the output
+ # there are two states we want the program to be in, with regards to
+ # power saving, the screen saver is inhibited when the viewer is watched.
+ # or we inhibit sleep/powersaving when we are processing data
+ # we do things the way we do here because the viewer shows the the output
# of the render pipeline
self.log("updating power inhibitors")
toplevel_id = 0
- # Inhibit power saving if we are rendering, maybe downloading a video
+ # inhibit power saving if we are rendering, maybe downloading a video
if self.sleepIsInhibited():
if self.cookie_type != COOKIE_SLEEP:
new_cookie = self.session_iface.Inhibit(APPNAME, toplevel_id,
- self.getSleepInhibitors(), INHIBIT_SUSPEND | INHIBIT_LOGOUT)
+ self.getSleepInhibitors(), INHIBIT_SUSPEND |
INHIBIT_LOGOUT)
if self.cookie is not None:
self.session_iface.Uninhibit(self.cookie)
self.cookie = new_cookie
@@ -244,11 +250,11 @@ class GnomeSystem(FreedesktopOrgSystem):
self.debug("sleep inhibited")
else:
self.debug("sleep already inhibited")
- # Inhibit screensaver if we are just watching the viewer
+ # inhibit screensaver if we are just watching the viewer
elif self.screensaverIsInhibited():
if self.cookie_type != COOKIE_SCREENSAVER:
new_cookie = self.session_iface.Inhibit(APPNAME, toplevel_id,
- self.getScreensaverInhibitors(), INHIBIT_SESSION_IDLE)
+ self.getScreensaverInhibitors(),
INHIBIT_SESSION_IDLE)
if self.cookie is not None:
self.session_iface.Uninhibit(self.cookie)
self.cookie = new_cookie
@@ -256,7 +262,7 @@ class GnomeSystem(FreedesktopOrgSystem):
self.debug("screensaver inhibited")
else:
self.debug("screensaver already inhibited")
- # Unblock everything otherwise
+ # unblock everything otherwise
else:
if self.cookie != COOKIE_NONE:
self.session_iface.Uninhibit(self.cookie)
@@ -269,7 +275,7 @@ class GnomeSystem(FreedesktopOrgSystem):
system_ = None
-# Attempts to identify the System, import dependencies and overide system_
+# attempts to identify the System, import dependencies and overide system_
if os.name == 'posix':
if 'GNOME_DESKTOP_SESSION_ID' in os.environ:
try:
@@ -298,12 +304,15 @@ def getSystem():
class CPUUsageTracker(object):
+
def __init__(self):
self.reset()
def usage(self):
- delta_time = (datetime.datetime.now() - self.last_moment).total_seconds()
- delta_usage = resource.getrusage(resource.RUSAGE_SELF).ru_utime - self.last_usage.ru_utime
+ delta_time = (datetime.datetime.now()
+ - self.last_moment).total_seconds()
+ delta_usage = resource.getrusage(
+ resource.RUSAGE_SELF).ru_utime - self.last_usage.ru_utime
usage = float(delta_usage) / delta_time * 100
return usage / multiprocessing.cpu_count()
diff --git a/pitivi/utils/threads.py b/pitivi/utils/threads.py
index 7e9912f..3519b68 100644
--- a/pitivi/utils/threads.py
+++ b/pitivi/utils/threads.py
@@ -32,6 +32,7 @@ from pitivi.utils.loggable import Loggable
class Thread(threading.Thread, GObject.Object, Loggable):
+
"""
Event-powered thread
"""
@@ -65,6 +66,7 @@ class Thread(threading.Thread, GObject.Object, Loggable):
class ThreadMaster(Loggable):
+
"""
Controls all the threads existing in Pitivi.
"""
diff --git a/pitivi/utils/ui.py b/pitivi/utils/ui.py
index 90e98b3..3dbb189 100644
--- a/pitivi/utils/ui.py
+++ b/pitivi/utils/ui.py
@@ -173,7 +173,8 @@ def set_cairo_color(context, color):
# Cairo's set_source_rgb function expects values from 0.0 to 1.0
cairo_color = [max(0, min(1, x / 255.0)) for x in color]
else:
- raise Exception("Unexpected color parameter: %s, %s" % (type(color), color))
+ raise Exception("Unexpected color parameter: %s, %s" %
+ (type(color), color))
context.set_source_rgb(*cairo_color)
@@ -207,7 +208,7 @@ def beautify_info(info):
nice_streams_txts.append(beautified_string)
return ("<b>" + path_from_uri(info.get_uri()) + "</b>\n" +
- "\n".join(nice_streams_txts))
+ "\n".join(nice_streams_txts))
def info_name(info):
@@ -227,11 +228,12 @@ def info_name(info):
def beautify_stream(stream):
if type(stream) is DiscovererAudioInfo:
- templ = ngettext("<b>Audio:</b> %d channel at %d <i>Hz</i> (%d <i>bits</i>)",
- "<b>Audio:</b> %d channels at %d <i>Hz</i> (%d <i>bits</i>)",
- stream.get_channels())
+ templ = ngettext(
+ "<b>Audio:</b> %d channel at %d <i>Hz</i> (%d <i>bits</i>)",
+ "<b>Audio:</b> %d channels at %d <i>Hz</i> (%d <i>bits</i>)",
+ stream.get_channels())
templ = templ % (stream.get_channels(), stream.get_sample_rate(),
- stream.get_depth())
+ stream.get_depth())
return templ
elif type(stream) is DiscovererVideoInfo:
@@ -240,9 +242,10 @@ def beautify_stream(stream):
templ = _("<b>Video:</b> %d×%d <i>pixels</i> at %.3f <i>fps</i>")
try:
templ = templ % (par * stream.get_width(), stream.get_height(),
- float(stream.get_framerate_num()) / stream.get_framerate_denom())
+ float(stream.get_framerate_num()) / stream.get_framerate_denom())
except ZeroDivisionError:
- templ = templ % (par * stream.get_width(), stream.get_height(), 0)
+ templ = templ % (
+ par * stream.get_width(), stream.get_height(), 0)
else:
templ = _("<b>Image:</b> %d×%d <i>pixels</i>")
templ = templ % (par * stream.get_width(), stream.get_height())
@@ -394,7 +397,8 @@ def alter_style_class(style_class, target_widget, css_style):
toolbar_css = "%s { %s }" % (style_class, css_style)
css_provider.load_from_data(toolbar_css.encode('UTF-8'))
style_context = target_widget.get_style_context()
- style_context.add_provider(css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
+ style_context.add_provider(
+ css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
# ----------------------- encoding datas --------------------------------------- #
diff --git a/pitivi/utils/widgets.py b/pitivi/utils/widgets.py
index 63f983c..a931668 100644
--- a/pitivi/utils/widgets.py
+++ b/pitivi/utils/widgets.py
@@ -55,6 +55,7 @@ class DynamicWidget(object):
"""An interface which provides a uniform way to get, set, and observe
widget properties"""
+
def __init__(self, default):
self.default = default
@@ -76,6 +77,7 @@ class DynamicWidget(object):
class DefaultWidget(Gtk.Label):
+
"""When all hope fails...."""
def __init__(self, *unused, **unused_kwargs):
@@ -83,6 +85,7 @@ class DefaultWidget(Gtk.Label):
class TextWidget(Gtk.HBox, DynamicWidget):
+
"""
A Gtk.Entry which emits a "value-changed" signal only when its input is
valid (matches the provided regex). If the input is invalid, a warning
@@ -209,7 +212,8 @@ class NumericWidget(Gtk.HBox, DynamicWidget):
self.lower = lower
self._type = None
if (lower is not None and upper is not None) and (lower > -5000 and upper < 5000):
- self.slider = Gtk.Scale.new(Gtk.Orientation.HORIZONTAL, self.adjustment)
+ self.slider = Gtk.Scale.new(
+ Gtk.Orientation.HORIZONTAL, self.adjustment)
self.pack_start(self.slider, expand=True, fill=True, padding=0)
self.slider.show()
self.slider.props.draw_value = False
@@ -228,7 +232,8 @@ class NumericWidget(Gtk.HBox, DynamicWidget):
self.adjustment.props.lower = lower
self.adjustment.props.upper = upper
self.spinner = Gtk.SpinButton(adjustment=self.adjustment)
- self.pack_end(self.spinner, fill=True, expand=not hasattr(self, 'slider'), padding=0)
+ self.pack_end(self.spinner, fill=True,
+ expand=not hasattr(self, 'slider'), padding=0)
self.spinner.show()
def connectValueChanged(self, callback, *args):
@@ -263,6 +268,7 @@ class NumericWidget(Gtk.HBox, DynamicWidget):
class TimeWidget(TextWidget, DynamicWidget):
+
"""
A widget that contains a time in nanoseconds. Accepts timecode formats
or a frame number (integer).
@@ -270,7 +276,8 @@ class TimeWidget(TextWidget, DynamicWidget):
# The "frame number" match rule is ^([0-9]+)$ (with a + to require 1 digit)
# The "timecode" rule is ^([0-9]:[0-5][0-9]:[0-5][0-9])\.[0-9][0-9][0-9]$"
# Combining the two, we get:
- VALID_REGEX = re.compile("^([0-9]+)$|^([0-9]:)?([0-5][0-9]:[0-5][0-9])\.[0-9][0-9][0-9]$")
+ VALID_REGEX = re.compile(
+ "^([0-9]+)$|^([0-9]:)?([0-5][0-9]:[0-5][0-9])\.[0-9][0-9][0-9]$")
__gtype_name__ = 'TimeWidget'
@@ -477,14 +484,15 @@ class PathWidget(Gtk.FileChooserButton, DynamicWidget):
__gsignals__ = {
"value-changed": (GObject.SignalFlags.RUN_LAST,
- None,
- ()),
+ None,
+ ()),
}
def __init__(self, action=Gtk.FileChooserAction.OPEN, default=None):
DynamicWidget.__init__(self, default)
self.dialog = Gtk.FileChooserDialog(action=action)
- self.dialog.add_buttons(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_CLOSE,
Gtk.ResponseType.CLOSE)
+ self.dialog.add_buttons(
+ Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)
self.dialog.set_default_response(Gtk.ResponseType.OK)
Gtk.FileChooserButton.__init__(self, dialog=self.dialog)
self.dialog.connect("response", self._responseCb)
@@ -531,7 +539,7 @@ class ColorWidget(Gtk.ColorButton, DynamicWidget):
color = value
else:
raise TypeError("%r is not something we can convert to a color" %
- value)
+ value)
self.set_color(color)
self.set_alpha(alpha)
@@ -565,6 +573,7 @@ class FontWidget(Gtk.FontButton, DynamicWidget):
class GstElementSettingsWidget(Gtk.VBox, Loggable):
+
"""
Widget to view/modify properties of a Gst.Element
"""
@@ -630,9 +639,11 @@ class GstElementSettingsWidget(Gtk.VBox, Loggable):
is_effect = False
if isinstance(self.element, GES.Effect):
is_effect = True
- props = [prop for prop in self.element.list_children_properties() if prop.name not in
self.ignore]
+ props = [
+ prop for prop in self.element.list_children_properties() if prop.name not in self.ignore]
else:
- props = [prop for prop in GObject.list_properties(self.element) if prop.name not in self.ignore]
+ props = [prop for prop in GObject.list_properties(
+ self.element) if prop.name not in self.ignore]
if not props:
table = Gtk.Table(n_rows=1, n_columns=1)
widget = Gtk.Label(label=_("No properties."))
@@ -656,14 +667,15 @@ class GstElementSettingsWidget(Gtk.VBox, Loggable):
# We do not know how to work with GObjects, so blacklist
# them to avoid noise in the UI
if (not prop.flags & GObject.PARAM_WRITABLE or
- not prop.flags & GObject.PARAM_READABLE or
- GObject.type_is_a(prop.value_type, GObject.Object)):
+ not prop.flags & GObject.PARAM_READABLE or
+ GObject.type_is_a(prop.value_type, GObject.Object)):
continue
if is_effect:
result, prop_value = self.element.get_child_property(prop.name)
if result is False:
- self.debug("Could not get value for property: %s", prop.name)
+ self.debug(
+ "Could not get value for property: %s", prop.name)
else:
if use_element_props:
prop_value = self.element.get_property(prop.name)
@@ -673,17 +685,21 @@ class GstElementSettingsWidget(Gtk.VBox, Loggable):
widget = self._makePropertyWidget(prop, prop_value)
if isinstance(widget, ToggleWidget):
widget.set_label(prop.nick)
- table.attach(widget, 0, 2, y, y + 1, yoptions=Gtk.AttachOptions.FILL)
+ table.attach(
+ widget, 0, 2, y, y + 1, yoptions=Gtk.AttachOptions.FILL)
else:
label = Gtk.Label(label=prop.nick + ":")
label.set_alignment(0.0, 0.5)
- table.attach(label, 0, 1, y, y + 1, xoptions=Gtk.AttachOptions.FILL,
yoptions=Gtk.AttachOptions.FILL)
- table.attach(widget, 1, 2, y, y + 1, yoptions=Gtk.AttachOptions.FILL)
+ table.attach(
+ label, 0, 1, y, y + 1, xoptions=Gtk.AttachOptions.FILL, yoptions=Gtk.AttachOptions.FILL)
+ table.attach(
+ widget, 1, 2, y, y + 1, yoptions=Gtk.AttachOptions.FILL)
if not isinstance(widget, ToggleWidget) and not isinstance(widget, ChoiceWidget) and
self.isControllable:
button = self._getKeyframeToggleButton(prop)
self.keyframeToggleButtons[button] = widget
- table.attach(button, 3, 4, y, y + 1, xoptions=Gtk.AttachOptions.FILL,
yoptions=Gtk.AttachOptions.FILL)
+ table.attach(
+ button, 3, 4, y, y + 1, xoptions=Gtk.AttachOptions.FILL, yoptions=Gtk.AttachOptions.FILL)
if hasattr(prop, 'blurb'):
widget.set_tooltip_text(prop.blurb)
@@ -695,13 +711,15 @@ class GstElementSettingsWidget(Gtk.VBox, Loggable):
widget.propName = prop.name.split("-")[0]
if self.isControllable:
- # If this element is controlled, the value means nothing anymore.
+ # If this element is controlled, the value means nothing
+ # anymore.
binding = self.element.get_control_binding(prop.name)
if binding:
widget.set_sensitive(False)
self.bindings[widget] = binding
button = self._getResetToDefaultValueButton(prop, widget)
- table.attach(button, 2, 3, y, y + 1, xoptions=Gtk.AttachOptions.FILL,
yoptions=Gtk.AttachOptions.FILL)
+ table.attach(
+ button, 2, 3, y, y + 1, xoptions=Gtk.AttachOptions.FILL, yoptions=Gtk.AttachOptions.FILL)
self.buttons[button] = widget
y += 1
@@ -811,7 +829,8 @@ class GstElementSettingsWidget(Gtk.VBox, Loggable):
minimum = prop.minimum
if hasattr(prop, "maximum"):
maximum = prop.maximum
- widget = NumericWidget(default=prop.default_value, upper=maximum, lower=minimum)
+ widget = NumericWidget(
+ default=prop.default_value, upper=maximum, lower=minimum)
elif type_name == "gboolean":
widget = ToggleWidget(default=prop.default_value)
elif type_name == "GEnum":
@@ -820,7 +839,8 @@ class GstElementSettingsWidget(Gtk.VBox, Loggable):
choices.append([val.value_name, int(val)])
widget = ChoiceWidget(choices, default=prop.default_value)
elif type_name == "GstFraction":
- widget = FractionWidget(None, presets=["0:1"], default=prop.default_value)
+ widget = FractionWidget(
+ None, presets=["0:1"], default=prop.default_value)
else:
# TODO: implement widgets for: GBoxed, GFlags
self.fixme("Unsupported property type: %s", type_name)
@@ -835,6 +855,7 @@ class GstElementSettingsWidget(Gtk.VBox, Loggable):
class GstElementSettingsDialog(Loggable):
+
"""
Dialog window for viewing/modifying properties of a Gst.Element
"""
@@ -844,7 +865,8 @@ class GstElementSettingsDialog(Loggable):
self.debug("factory: %s, properties: %s", elementfactory, properties)
self.builder = Gtk.Builder()
- self.builder.add_from_file(os.path.join(get_ui_dir(), "elementsettingsdialog.ui"))
+ self.builder.add_from_file(
+ os.path.join(get_ui_dir(), "elementsettingsdialog.ui"))
self.builder.connect_signals(self)
self.ok_btn = self.builder.get_object("okbutton1")
@@ -855,7 +877,8 @@ class GstElementSettingsDialog(Loggable):
self.factory = elementfactory
self.element = self.factory.create("elementsettings")
if not self.element:
- self.warning("Couldn't create element from factory %s", self.factory)
+ self.warning(
+ "Couldn't create element from factory %s", self.factory)
self.properties = properties
self._fillWindow()
@@ -864,10 +887,12 @@ class GstElementSettingsDialog(Loggable):
contents_height = self.elementsettings.size_request().height
maximum_contents_height = max(500, 0.7 * screen_height)
if contents_height < maximum_contents_height:
- # The height of the content is small enough, disable the scrollbars.
+ # The height of the content is small enough, disable the
+ # scrollbars.
default_height = -1
scrolledwindow = self.builder.get_object("scrolledwindow1")
- scrolledwindow.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.NEVER)
+ scrolledwindow.set_policy(
+ Gtk.PolicyType.NEVER, Gtk.PolicyType.NEVER)
scrolledwindow.set_shadow_type(Gtk.ShadowType.NONE)
else:
# If we need to scroll, set a reasonable height for the window.
@@ -880,7 +905,8 @@ class GstElementSettingsDialog(Loggable):
def _fillWindow(self):
# set title and frame label
- self.window.set_title(_("Properties for %s") % self.factory.get_longname())
+ self.window.set_title(
+ _("Properties for %s") % self.factory.get_longname())
self.elementsettings.setElement(self.element, self.properties)
def getSettings(self):
@@ -896,6 +922,7 @@ class GstElementSettingsDialog(Loggable):
class BaseTabs(Gtk.Notebook):
+
def __init__(self, app, hide_hpaned=False):
""" initialize """
Gtk.Notebook.__init__(self)
@@ -925,7 +952,7 @@ class BaseTabs(Gtk.Notebook):
label.props.xalign = 0.0
def _detachedComponentWindowDestroyCb(self, window, child,
- original_position, label):
+ original_position, label):
notebook = window.get_child()
position = notebook.child_get_property(child, "position")
notebook.remove_page(position)
@@ -946,7 +973,7 @@ class BaseTabs(Gtk.Notebook):
window.set_title(label)
window.set_default_size(600, 400)
window.connect("destroy", self._detachedComponentWindowDestroyCb,
- child, original_position, label)
+ child, original_position, label)
notebook = Gtk.Notebook()
notebook.props.show_tabs = False
window.add(notebook)
@@ -978,6 +1005,7 @@ class BaseTabs(Gtk.Notebook):
class ZoomBox(Gtk.Grid, Zoomable):
+
"""
Container holding the widgets for zooming.
@@ -994,7 +1022,8 @@ class ZoomBox(Gtk.Grid, Zoomable):
zoom_fit_btn.set_relief(Gtk.ReliefStyle.NONE)
zoom_fit_btn.set_tooltip_text(_("Zoom Fit"))
zoom_fit_btn_grid = Gtk.Grid()
- zoom_fit_icon = Gtk.Image.new_from_icon_name("zoom-best-fit", Gtk.IconSize.BUTTON)
+ zoom_fit_icon = Gtk.Image.new_from_icon_name(
+ "zoom-best-fit", Gtk.IconSize.BUTTON)
zoom_fit_btn_grid.add(zoom_fit_icon)
zoom_fit_btn_label = Gtk.Label(label=_("Zoom"))
zoom_fit_btn_grid.add(zoom_fit_btn_label)
@@ -1007,7 +1036,8 @@ class ZoomBox(Gtk.Grid, Zoomable):
self._zoomAdjustment = Gtk.Adjustment()
self._zoomAdjustment.props.lower = 0
self._zoomAdjustment.props.upper = Zoomable.zoom_steps
- zoomslider = Gtk.Scale.new(Gtk.Orientation.HORIZONTAL, adjustment=self._zoomAdjustment)
+ zoomslider = Gtk.Scale.new(
+ Gtk.Orientation.HORIZONTAL, adjustment=self._zoomAdjustment)
# Setting _zoomAdjustment's value must be done after we create the
# zoom slider, otherwise the slider remains at the leftmost position.
self._zoomAdjustment.set_value(Zoomable.getCurrentZoomLevel())
@@ -1016,7 +1046,8 @@ class ZoomBox(Gtk.Grid, Zoomable):
zoomslider.connect("value-changed", self._zoomAdjustmentChangedCb)
zoomslider.connect("query-tooltip", self._sliderTooltipCb)
zoomslider.set_has_tooltip(True)
- zoomslider.set_size_request(100, 0) # At least 100px wide for precision
+ # At least 100px wide for precision
+ zoomslider.set_size_request(100, 0)
zoomslider.set_hexpand(True)
self.attach(zoomslider, 1, 0, 1, 1)
@@ -1056,7 +1087,8 @@ class ZoomBox(Gtk.Grid, Zoomable):
self._zoomAdjustment.set_value(zoomLevel)
def _sliderTooltipCb(self, unused_slider, unused_x, unused_y, unused_keyboard_mode, tooltip):
- # We assume the width of the ruler is exactly the width of the timeline.
+ # We assume the width of the ruler is exactly the width of the
+ # timeline.
width_px = self.timeline.ruler.get_allocated_width()
timeline_width_ns = Zoomable.pixelToNs(width_px)
if timeline_width_ns >= Gst.SECOND:
@@ -1064,6 +1096,7 @@ class ZoomBox(Gtk.Grid, Zoomable):
tip = _("%s displayed") % beautify_length(timeline_width_ns)
else:
# Translators: This is a tooltip
- tip = _("%d nanoseconds displayed, because we can") % timeline_width_ns
+ tip = _(
+ "%d nanoseconds displayed, because we can") % timeline_width_ns
tooltip.set_text(tip)
return True
diff --git a/pitivi/viewer.py b/pitivi/viewer.py
index fdcbf1a..53c0f58 100644
--- a/pitivi/viewer.py
+++ b/pitivi/viewer.py
@@ -48,39 +48,40 @@ import platform
GlobalSettings.addConfigSection("viewer")
GlobalSettings.addConfigOption("viewerDocked", section="viewer",
- key="docked",
- default=True)
+ key="docked",
+ default=True)
GlobalSettings.addConfigOption("viewerWidth", section="viewer",
- key="width",
- default=320)
+ key="width",
+ default=320)
GlobalSettings.addConfigOption("viewerHeight", section="viewer",
- key="height",
- default=240)
+ key="height",
+ default=240)
GlobalSettings.addConfigOption("viewerX", section="viewer",
- key="x-pos",
- default=0)
+ key="x-pos",
+ default=0)
GlobalSettings.addConfigOption("viewerY", section="viewer",
- key="y-pos",
- default=0)
+ key="y-pos",
+ default=0)
GlobalSettings.addConfigOption("pointSize", section="viewer",
- key="point-size",
- default=25)
+ key="point-size",
+ default=25)
GlobalSettings.addConfigOption("clickedPointColor", section="viewer",
- key="clicked-point-color",
- default='ffa854')
+ key="clicked-point-color",
+ default='ffa854')
GlobalSettings.addConfigOption("pointColor", section="viewer",
- key="point-color",
- default='49a0e0')
+ key="point-color",
+ default='49a0e0')
class ViewerContainer(Gtk.VBox, Loggable):
+
"""
A wiget holding a viewer and the controls.
"""
__gtype_name__ = 'ViewerContainer'
__gsignals__ = {
"activate-playback-controls": (GObject.SignalFlags.RUN_LAST,
- None, (GObject.TYPE_BOOLEAN,)),
+ None, (GObject.TYPE_BOOLEAN,)),
}
INHIBIT_REASON = _("Currently playing")
@@ -99,7 +100,8 @@ class ViewerContainer(Gtk.VBox, Loggable):
self.docked = True
self.seeker = Seeker()
- # Only used for restoring the pipeline position after a live clip trim preview:
+ # Only used for restoring the pipeline position after a live clip trim
+ # preview:
self._oldTimelinePos = None
self._haveUI = False
@@ -185,7 +187,8 @@ class ViewerContainer(Gtk.VBox, Loggable):
def _createUi(self):
""" Creates the Viewer GUI """
# Drawing area
- self.internal = ViewerWidget(self.app.settings, realizedCb=self._videoRealizedCb)
+ self.internal = ViewerWidget(
+ self.app.settings, realizedCb=self._videoRealizedCb)
# Transformation boxed DISABLED
# self.internal.init_transformation_events()
self.pack_start(self.internal, True, True, 0)
@@ -194,10 +197,13 @@ class ViewerContainer(Gtk.VBox, Loggable):
vbox = Gtk.VBox()
vbox.set_spacing(SPACING)
self.external_window.add(vbox)
- self.external = ViewerWidget(self.app.settings, realizedCb=self._videoRealizedCb)
+ self.external = ViewerWidget(
+ self.app.settings, realizedCb=self._videoRealizedCb)
vbox.pack_start(self.external, True, True, 0)
- self.external_window.connect("delete-event", self._externalWindowDeleteCb)
- self.external_window.connect("configure-event", self._externalWindowConfigureCb)
+ self.external_window.connect(
+ "delete-event", self._externalWindowDeleteCb)
+ self.external_window.connect(
+ "configure-event", self._externalWindowConfigureCb)
self.external_vbox = vbox
# Buttons/Controls
@@ -211,7 +217,8 @@ class ViewerContainer(Gtk.VBox, Loggable):
self.goToStart_button = Gtk.ToolButton()
self.goToStart_button.set_icon_name("media-skip-backward")
self.goToStart_button.connect("clicked", self._goToStartCb)
- self.goToStart_button.set_tooltip_text(_("Go to the beginning of the timeline"))
+ self.goToStart_button.set_tooltip_text(
+ _("Go to the beginning of the timeline"))
self.goToStart_button.set_sensitive(False)
bbox.pack_start(self.goToStart_button, False, True, 0)
@@ -237,20 +244,23 @@ class ViewerContainer(Gtk.VBox, Loggable):
self.goToEnd_button = Gtk.ToolButton()
self.goToEnd_button.set_icon_name("media-skip-forward")
self.goToEnd_button.connect("clicked", self._goToEndCb)
- self.goToEnd_button.set_tooltip_text(_("Go to the end of the timeline"))
+ self.goToEnd_button.set_tooltip_text(
+ _("Go to the end of the timeline"))
self.goToEnd_button.set_sensitive(False)
bbox.pack_start(self.goToEnd_button, False, True, 0)
self.timecode_entry = TimeWidget()
self.timecode_entry.setWidgetValue(0)
- self.timecode_entry.set_tooltip_text(_('Enter a timecode or frame number\nand press "Enter" to go to
that position'))
+ self.timecode_entry.set_tooltip_text(
+ _('Enter a timecode or frame number\nand press "Enter" to go to that position'))
self.timecode_entry.connectActivateEvent(self._entryActivateCb)
bbox.pack_start(self.timecode_entry, False, 10, 0)
self.undock_button = Gtk.ToolButton()
self.undock_button.set_icon_name("view-restore")
self.undock_button.connect("clicked", self.undock)
- self.undock_button.set_tooltip_text(_("Detach the viewer\nYou can re-attach it by closing the newly
created window."))
+ self.undock_button.set_tooltip_text(
+ _("Detach the viewer\nYou can re-attach it by closing the newly created window."))
bbox.pack_start(self.undock_button, False, True, 0)
self._haveUI = True
@@ -361,8 +371,10 @@ class ViewerContainer(Gtk.VBox, Loggable):
self.undock_button.hide()
self.fullscreen_button = Gtk.ToggleToolButton()
self.fullscreen_button.set_icon_name("view-fullscreen")
- self.fullscreen_button.set_tooltip_text(_("Show this window in fullscreen"))
- self.buttons.pack_end(self.fullscreen_button, expand=False, fill=False, padding=6)
+ self.fullscreen_button.set_tooltip_text(
+ _("Show this window in fullscreen"))
+ self.buttons.pack_end(
+ self.fullscreen_button, expand=False, fill=False, padding=6)
self.fullscreen_button.show()
self.fullscreen_button.connect("toggled", self._toggleFullscreen)
@@ -370,7 +382,8 @@ class ViewerContainer(Gtk.VBox, Loggable):
self._switch_output_window()
self.hide()
self.external_window.move(self.settings.viewerX, self.settings.viewerY)
- self.external_window.resize(self.settings.viewerWidth, self.settings.viewerHeight)
+ self.external_window.resize(
+ self.settings.viewerWidth, self.settings.viewerHeight)
def dock(self):
if self.docked:
@@ -416,14 +429,15 @@ class ViewerContainer(Gtk.VBox, Loggable):
While a clip is being trimmed, show a live preview of it.
"""
if isinstance(tl_obj, GES.TitleClip) or tl_obj.props.is_image or not hasattr(tl_obj, "get_uri"):
- self.log("%s is an image or has no URI, so not previewing trim" % tl_obj)
+ self.log(
+ "%s is an image or has no URI, so not previewing trim" % tl_obj)
return False
clip_uri = tl_obj.props.uri
cur_time = time()
if self.pipeline == self.app.project_manager.current_project.pipeline:
self.debug("Creating temporary pipeline for clip %s, position %s",
- clip_uri, format_ns(position))
+ clip_uri, format_ns(position))
self._oldTimelinePos = self.pipeline.getPosition()
self.setPipeline(AssetPipeline(tl_obj))
self._lastClipTrimTime = cur_time
@@ -441,7 +455,8 @@ class ViewerContainer(Gtk.VBox, Loggable):
self.pipeline.setState(Gst.State.NULL)
# Using pipeline.getPosition() here does not work because for some
# reason it's a bit off, that's why we need self._oldTimelinePos.
- self.setPipeline(self.app.project_manager.current_project.pipeline, self._oldTimelinePos)
+ self.setPipeline(
+ self.app.project_manager.current_project.pipeline, self._oldTimelinePos)
self.debug("Back to the project's pipeline")
def _pipelineStateChangedCb(self, unused_pipeline, state, old_state):
@@ -461,7 +476,7 @@ class ViewerContainer(Gtk.VBox, Loggable):
st = Gst.Structure.new_empty("pause")
if old_state == int(Gst.State.PLAYING):
st.set_value("playback_time", float(self.pipeline.getPosition()) /
- Gst.SECOND)
+ Gst.SECOND)
self.app.write_action(st)
self.playpause_button.setPlay()
@@ -491,6 +506,7 @@ class ViewerContainer(Gtk.VBox, Loggable):
class Point():
+
"""
Draw a point, used as a handle for the transformation box
"""
@@ -523,25 +539,25 @@ class Point():
def draw(self, cr):
linear = cairo.LinearGradient(self.x, self.y - self.radius,
- self.x, self.y + self.radius)
+ self.x, self.y + self.radius)
linear.add_color_stop_rgba(0.00, .6, .6, .6, 1)
linear.add_color_stop_rgba(0.50, .4, .4, .4, .1)
linear.add_color_stop_rgba(0.60, .4, .4, .4, .1)
linear.add_color_stop_rgba(1.00, .6, .6, .6, 1)
radial = cairo.RadialGradient(self.x + self.radius / 2,
- self.y - self.radius / 2, 1,
- self.x, self.y,
- self.radius)
+ self.y - self.radius / 2, 1,
+ self.x, self.y,
+ self.radius)
if self.clicked:
radial.add_color_stop_rgb(0, *self.clickedColor)
else:
radial.add_color_stop_rgb(0, *self.color)
radial.add_color_stop_rgb(1, 0.1, 0.1, 0.1)
radial_glow = cairo.RadialGradient(self.x, self.y,
- self.radius * .9,
- self.x, self.y,
- self.radius * 1.2)
+ self.radius * .9,
+ self.x, self.y,
+ self.radius * 1.2)
radial_glow.add_color_stop_rgba(0, 0.9, 0.9, 0.9, 1)
radial_glow.add_color_stop_rgba(1, 0.9, 0.9, 0.9, 0)
@@ -568,6 +584,7 @@ class Point():
class TransformationBox():
+
"""
Box for transforming the video on the ViewerWidget
"""
@@ -610,8 +627,10 @@ class TransformationBox():
def update_from_effect(self, effect):
self.scale_x = effect.get_property("scale-x")
self.scale_y = effect.get_property("scale-y")
- self.center_factor.x = 2 * (effect.get_property("tilt-x") - 0.5) + self.scale_x
- self.center_factor.y = 2 * (effect.get_property("tilt-y") - 0.5) + self.scale_y
+ self.center_factor.x = 2 * \
+ (effect.get_property("tilt-x") - 0.5) + self.scale_x
+ self.center_factor.y = 2 * \
+ (effect.get_property("tilt-y") - 0.5) + self.scale_y
self.left_factor = self.center_factor.x - self.scale_x
self.right_factor = self.center_factor.x + self.scale_x
self.top_factor = self.center_factor.y - self.scale_y
@@ -642,7 +661,8 @@ class TransformationBox():
self.points[TOP_LEFT] = Point(self.left, self.top, self.settings)
self.points[TOP_RIGHT] = Point(self.right, self.top, self.settings)
self.points[BOTTOM_LEFT] = Point(self.left, self.bottom, self.settings)
- self.points[BOTTOM_RIGHT] = Point(self.right, self.bottom, self.settings)
+ self.points[BOTTOM_RIGHT] = Point(
+ self.right, self.bottom, self.settings)
# Edge boxes
self.points[TOP] = Point(self.center.x, self.top, self.settings)
self.points[BOTTOM] = Point(self.center.x, self.bottom, self.settings)
@@ -682,7 +702,8 @@ class TransformationBox():
self.update_points()
# main box
cr.set_source_rgba(0.5, 0.5, 0.5, 0.7)
- cr.rectangle(self.left, self.top, self.right - self.left, self.bottom - self.top)
+ cr.rectangle(
+ self.left, self.top, self.right - self.left, self.bottom - self.top)
cr.stroke()
for point in list(self.points.values()):
@@ -780,7 +801,8 @@ class TransformationBox():
self.right = area.x + area.width
self.top = area.y
self.bottom = area.y + area.height
- self.center = Point((self.left + self.right) / 2, (self.top + self.bottom) / 2, self.settings)
+ self.center = Point((self.left + self.right) / 2, (
+ self.top + self.bottom) / 2, self.settings)
self.init_points()
self._update_measure()
@@ -795,8 +817,10 @@ class TransformationBox():
if self.transformation_properties:
self.transformation_properties.disconnectSpinButtonsFromFlush()
values = self.transformation_properties.spin_buttons
- values["tilt_x"].set_value((self.center_factor.x - self.scale_x) / 2.0 + 0.5)
- values["tilt_y"].set_value((self.center_factor.y - self.scale_y) / 2.0 + 0.5)
+ values["tilt_x"].set_value(
+ (self.center_factor.x - self.scale_x) / 2.0 + 0.5)
+ values["tilt_y"].set_value(
+ (self.center_factor.y - self.scale_y) / 2.0 + 0.5)
values["scale_x"].set_value(self.scale_x)
values["scale_y"].set_value(self.scale_y)
@@ -804,6 +828,7 @@ class TransformationBox():
class ViewerWidget(Gtk.AspectFrame, Loggable):
+
"""
Widget for displaying a GStreamer video sink.
@@ -916,12 +941,14 @@ class ViewerWidget(Gtk.AspectFrame, Loggable):
# crop away 1 pixel border to avoid artefacts on the pixbuf
self.pixbuf = Gdk.pixbuf_get_from_window(self.get_window(),
- self.box.area.x + 1, self.box.area.y + 1,
- self.box.area.width - 2, self.box.area.height - 2)
+ self.box.area.x +
+ 1, self.box.area.y + 1,
+ self.box.area.width - 2, self.box.area.height - 2)
else:
self.pixbuf = Gdk.pixbuf_get_from_window(self.get_window(),
- 0, 0,
- self.get_window().get_width(),
+ 0, 0,
+ self.get_window(
+ ).get_width(),
self.get_window().get_height())
self.stored = True
@@ -972,7 +999,8 @@ class ViewerWidget(Gtk.AspectFrame, Loggable):
self.renderbox()
def _update_gradient(self):
- self.gradient_background = cairo.LinearGradient(0, 0, 0, self.area.height)
+ self.gradient_background = cairo.LinearGradient(
+ 0, 0, 0, self.area.height)
self.gradient_background.add_color_stop_rgb(0.00, .1, .1, .1)
self.gradient_background.add_color_stop_rgb(0.50, .2, .2, .2)
self.gradient_background.add_color_stop_rgb(1.00, .5, .5, .5)
@@ -995,7 +1023,8 @@ class ViewerWidget(Gtk.AspectFrame, Loggable):
# translate when zoomed out
if self.pixbuf:
if self.box.area.width != self.pixbuf.get_width():
- scale = float(self.box.area.width) / float(self.pixbuf.get_width())
+ scale = float(self.box.area.width) / float(
+ self.pixbuf.get_width())
cr.save()
cr.scale(scale, scale)
cr.set_source_pixbuf(self.pixbuf, 0, 0)
@@ -1010,6 +1039,7 @@ class ViewerWidget(Gtk.AspectFrame, Loggable):
class PlayPauseButton(Gtk.Button, Loggable):
+
"""
Double state Gtk.Button which displays play/pause
"""
@@ -1036,13 +1066,15 @@ class PlayPauseButton(Gtk.Button, Loggable):
def setPlay(self):
self.log("Displaying the play image")
self.playing = True
- self.set_image(Gtk.Image.new_from_icon_name("media-playback-start", Gtk.IconSize.BUTTON))
+ self.set_image(Gtk.Image.new_from_icon_name(
+ "media-playback-start", Gtk.IconSize.BUTTON))
self.set_tooltip_text(_("Play"))
self.playing = False
def setPause(self):
self.log("Displaying the pause image")
self.playing = False
- self.set_image(Gtk.Image.new_from_icon_name("media-playback-pause", Gtk.IconSize.BUTTON))
+ self.set_image(Gtk.Image.new_from_icon_name(
+ "media-playback-pause", Gtk.IconSize.BUTTON))
self.set_tooltip_text(_("Pause"))
self.playing = True
diff --git a/tests/common.py b/tests/common.py
index 5b7930b..08c25d1 100644
--- a/tests/common.py
+++ b/tests/common.py
@@ -62,7 +62,7 @@ class TestCase(unittest.TestCase):
# don't barf gc info all over the console if we have already failed a
# test case
if (self._num_failures < len(getattr(self._result, 'failures', []))
- or self._num_errors < len(getattr(self._result, 'failures', []))):
+ or self._num_errors < len(getattr(self._result, 'failures', []))):
return
if detect_leaks:
self.gccollect()
@@ -82,6 +82,7 @@ class TestCase(unittest.TestCase):
class SignalMonitor(object):
+
def __init__(self, obj, *signals):
self.signals = signals
self.connectToObj(obj)
diff --git a/tests/dogtail_scripts/common.py b/tests/dogtail_scripts/common.py
index 0062d10..747acaf 100644
--- a/tests/dogtail_scripts/common.py
+++ b/tests/dogtail_scripts/common.py
@@ -22,7 +22,8 @@ DURATION_OF_ONE_CLIP = "00:01.999"
DURATION_OF_TWO_CLIPS = "00:03.999"
# Constants from pitivi.ui
-# TODO: Use directly the constants from pitivi.ui when these UI tests are ported to Python3.
+# TODO: Use directly the constants from pitivi.ui when these UI tests are
+# ported to Python3.
CONTROL_WIDTH = 250
EXPANDED_SIZE = 65
SPACING = 10
@@ -46,9 +47,12 @@ class PitiviTestCase(unittest.TestCase):
# chosen by the current user.
if not hasattr(self, "user_dir"):
self.user_dir = tempfile.mkdtemp()
- os.environ["PITIVI_USER_CONFIG_DIR"] = os.path.pathsep.join([self.user_dir, "config"])
- os.environ["PITIVI_USER_DATA_DIR"] = os.path.pathsep.join([self.user_dir, "data"])
- os.environ["PITIVI_USER_CACHE_DIR"] = os.path.pathsep.join([self.user_dir, "cache"])
+ os.environ["PITIVI_USER_CONFIG_DIR"] = os.path.pathsep.join(
+ [self.user_dir, "config"])
+ os.environ["PITIVI_USER_DATA_DIR"] = os.path.pathsep.join(
+ [self.user_dir, "data"])
+ os.environ["PITIVI_USER_CACHE_DIR"] = os.path.pathsep.join(
+ [self.user_dir, "cache"])
from dogtail.utils import run
from dogtail.tree import root
# Setting appName is critically important here.
@@ -80,28 +84,37 @@ class PitiviTestCase(unittest.TestCase):
self.assertEqual('timeline area', timeline_area.name)
# Tabs
- primary_tabs = upper_half.children[0].child(name="primary tabs", recursive=False)
- secondary_tabs = upper_half.children[0].child(name="secondary tabs", recursive=False)
+ primary_tabs = upper_half.children[0].child(
+ name="primary tabs", recursive=False)
+ secondary_tabs = upper_half.children[0].child(
+ name="secondary tabs", recursive=False)
self.medialibrary = primary_tabs.children[0]
self.effectslibrary = primary_tabs.children[1]
self.clipproperties = secondary_tabs.children[0]
self.transitions = secondary_tabs.children[1]
self.titles = secondary_tabs.children[2]
self.viewer = upper_half.child(name="viewer", recursive=False)
- self.import_button = self.medialibrary.child(name="media_import_button")
- self.insert_button = self.medialibrary.child(name="media_insert_button")
+ self.import_button = self.medialibrary.child(
+ name="media_import_button")
+ self.insert_button = self.medialibrary.child(
+ name="media_insert_button")
# Timeline area
- self.zoom_best_fit_button = timeline_area.child(name="Zoom", recursive=True)
- self.timeline = timeline_area.child(name="timeline canvas", recursive=False)
- self.timeline_toolbar = timeline_area.child(name="timeline toolbar", recursive=False)
+ self.zoom_best_fit_button = timeline_area.child(
+ name="Zoom", recursive=True)
+ self.timeline = timeline_area.child(
+ name="timeline canvas", recursive=False)
+ self.timeline_toolbar = timeline_area.child(
+ name="timeline toolbar", recursive=False)
start_time = time.time() - timer_start
if start_time > 0.1:
# When we were simply searching the toplevel for the menu bar,
# startup time was 0.0043 seconds. Anything significantly longer
- # means there are optimizations to be done, avoid recursive searches
- print("\nWARNING: setUp in test_base took", start_time, "seconds, that's too slow.\n")
+ # means there are optimizations to be done, avoid recursive
+ # searches
+ print("\nWARNING: setUp in test_base took",
+ start_time, "seconds, that's too slow.\n")
try:
self.unlink
except AttributeError:
@@ -130,7 +143,8 @@ class PitiviTestCase(unittest.TestCase):
if saveAs:
self.assertIsNotNone(path)
dogtail.rawinput.keyCombo("<Control><Shift>s") # Save project as
- save_dialog = self.pitivi.child(name="Save As...", roleName='file chooser', recursive=False)
+ save_dialog = self.pitivi.child(
+ name="Save As...", roleName='file chooser', recursive=False)
text_field = save_dialog.child(roleName="text")
text_field.text = path
time.sleep(0.2)
@@ -147,12 +161,15 @@ class PitiviTestCase(unittest.TestCase):
dogtail.rawinput.keyCombo("<Control>o") # Open project
# If an "unsaved changes" prompt is expected to show up, deal with it:
if unsaved_changes is not None:
- result = self._check_unsaved_changes_dialog(decision=unsaved_changes)
+ result = self._check_unsaved_changes_dialog(
+ decision=unsaved_changes)
if result is False: # The user clicked "Cancel" (no decision)
return
- load = self.pitivi.child(name="Open File...", roleName="file chooser", recursive=False)
- path_toggle = load.child(name="Type a file name", roleName="toggle button")
+ load = self.pitivi.child(
+ name="Open File...", roleName="file chooser", recursive=False)
+ path_toggle = load.child(
+ name="Type a file name", roleName="toggle button")
if not path_toggle.checked:
path_toggle.click()
@@ -170,21 +187,26 @@ class PitiviTestCase(unittest.TestCase):
"""
time.sleep(1)
try:
- dialog = self.pitivi.child(name="unsaved changes dialog", roleName="dialog", recursive=False,
retry=False)
+ dialog = self.pitivi.child(
+ name="unsaved changes dialog", roleName="dialog", recursive=False, retry=False)
except SearchError:
- self.fail('The "unsaved changes" dialog/prompt was expected but did not appear')
+ self.fail(
+ 'The "unsaved changes" dialog/prompt was expected but did not appear')
if decision is "discard":
- dialog.child(name="Close without saving", roleName="push button").click()
+ dialog.child(
+ name="Close without saving", roleName="push button").click()
return True
elif decision is "cancel":
dialog.child(name="Cancel", roleName="push button").click()
- return False # Prevent us from expecting the file chooser in loadProject
+ # Prevent us from expecting the file chooser in loadProject
+ return False
elif decision is "save":
dialog.child(name="Save", roleName="push button").click()
return True
else:
- self.fail("You didn't provide a valid answer for the unsaved changes dialog!")
+ self.fail(
+ "You didn't provide a valid answer for the unsaved changes dialog!")
def search_by_text(self, text, parent, name=None, roleName=None, exactMatchOnly=True):
"""
@@ -192,7 +214,8 @@ class PitiviTestCase(unittest.TestCase):
If you want to search for a widget "containing" the text, set the
"exactMatchOnly" parameter to False (it will also be case-insensitive).
"""
- children = parent.findChildren(GenericPredicate(roleName=roleName, name=name))
+ children = parent.findChildren(
+ GenericPredicate(roleName=roleName, name=name))
for child in children:
if hasattr(child, "text"):
# This is cute and all, but we're not just searching inside
@@ -211,7 +234,8 @@ class PitiviTestCase(unittest.TestCase):
"""
Search a parent widget for childs containing the given regular expression
"""
- children = parent.findChildren(GenericPredicate(roleName=roleName, name=name))
+ children = parent.findChildren(
+ GenericPredicate(roleName=roleName, name=name))
r = re.compile(regex, regex_flags)
for child in children:
if child.text is not None and r.match(child.text):
@@ -238,7 +262,8 @@ class PitiviTestCase(unittest.TestCase):
import_dialog = self.pitivi.child(name="Select One or More Files",
roleName="file chooser", recursive=False)
- path_toggle = import_dialog.child(name="Type a file name", roleName="toggle button")
+ path_toggle = import_dialog.child(
+ name="Type a file name", roleName="toggle button")
if not path_toggle.checked:
path_toggle.click()
@@ -254,7 +279,8 @@ class PitiviTestCase(unittest.TestCase):
# The time it takes for the icon to appear is unpredictable,
# therefore we try up to 5 times to look for it
try:
- icons = self.medialibrary.findChildren(GenericPredicate(roleName="icon"))
+ icons = self.medialibrary.findChildren(
+ GenericPredicate(roleName="icon"))
except TypeError:
# If no icon can be seen due to restrictive search results,
# don't try to loop over "icons" (which will be a None type).
@@ -266,7 +292,8 @@ class PitiviTestCase(unittest.TestCase):
time.sleep(0.5)
# Failure to find an icon might be because it is hidden due to a search
- current_search_text = self.medialibrary.child(name="media_search_entry",
roleName="text").text.lower()
+ current_search_text = self.medialibrary.child(
+ name="media_search_entry", roleName="text").text.lower()
self.assertNotEqual(current_search_text, "")
self.assertNotIn(filename.lower(), current_search_text)
return None
@@ -278,11 +305,13 @@ class PitiviTestCase(unittest.TestCase):
import_dialog = self.pitivi.child(name="Select One or More Files",
roleName="file chooser", recursive=False)
- path_toggle = import_dialog.child(name="Type a file name", roleName="toggle button")
+ path_toggle = import_dialog.child(
+ name="Type a file name", roleName="toggle button")
if not path_toggle.checked:
path_toggle.click()
- dir_path = os.path.realpath(__file__).split("dogtail_scripts/")[0] + "samples/"
+ dir_path = os.path.realpath(__file__).split(
+ "dogtail_scripts/")[0] + "samples/"
import_dialog.child(roleName='text').text = dir_path
time.sleep(0.2)
dogtail.rawinput.pressKey("Enter")
@@ -303,7 +332,8 @@ class PitiviTestCase(unittest.TestCase):
registry.generateKeyboardEvent(ctrl_code, None, KEY_RELEASE)
import_dialog.button('Add').click()
- current_search_text = self.medialibrary.child(name="media_search_entry",
roleName="text").text.lower()
+ current_search_text = self.medialibrary.child(
+ name="media_search_entry", roleName="text").text.lower()
if current_search_text != "":
# Failure to find some icons might be because of search filtering.
# The following avoids searching for files that can't be found.
@@ -315,7 +345,8 @@ class PitiviTestCase(unittest.TestCase):
for i in range(5):
# The time it takes for icons to appear is unpredictable,
# therefore we try up to 5 times to look for them
- icons = self.medialibrary.findChildren(GenericPredicate(roleName="icon"))
+ icons = self.medialibrary.findChildren(
+ GenericPredicate(roleName="icon"))
for icon in icons:
for f in files:
if icon.text == f:
@@ -391,7 +422,8 @@ class PitiviTestCase(unittest.TestCase):
# Ensure the welcome dialog is closed.
dogtail.rawinput.pressKey("Esc")
# Make sure the list view is hidden.
- self.medialibrary.child(name="media_listview_button", roleName="panel").click()
+ self.medialibrary.child(
+ name="media_listview_button", roleName="panel").click()
self.wait_for_node_hidden(listview, timeout=2)
@staticmethod
diff --git a/tests/dogtail_scripts/test_clipproperties.py b/tests/dogtail_scripts/test_clipproperties.py
index 4f48127..dd15113 100644
--- a/tests/dogtail_scripts/test_clipproperties.py
+++ b/tests/dogtail_scripts/test_clipproperties.py
@@ -6,6 +6,7 @@ from time import sleep
class ClipTransformationTest(PitiviTestCase):
+
def test_transformation_options(self):
# Load a sample file, insert it twice in the timeline and wait for
# the insertion animation to be complete before we start clicking
@@ -20,7 +21,8 @@ class ClipTransformationTest(PitiviTestCase):
clip1_pos = (self.timeline.position[0] + 300, _layer1_clips_y)
# The second clip position should be right in the middle of the timeline
# but we compensate (approximately) for the width of layer controls:
- _middle_x = self.timeline.position[0] + 300 + (self.timeline.size[0] - 300) / 2
+ _middle_x = self.timeline.position[
+ 0] + 300 + (self.timeline.size[0] - 300) / 2
clip2_pos = (_middle_x, _layer1_clips_y)
# For now, only select the first clip on the timeline
dogtail.rawinput.click(clip1_pos[0], clip1_pos[1])
@@ -28,28 +30,31 @@ class ClipTransformationTest(PitiviTestCase):
tab = self.clipproperties
tab.click()
tab.child(name="Transformation", roleName="toggle button").click()
- #Just try changing values
- #Test slider
+ # Just try changing values
+ # Test slider
slider = tab.child(roleName="slider")
self.assertEqual(slider.value, 1.0)
slider.click()
# Clicking in the middle of the slider will set it backwards to 0.9
self.assertNotEqual(slider.value, 1.0)
- #Test position
- spinb = tab.child(roleName="panel", name="Position").findChildren(GenericPredicate(roleName="spin
button"))
+ # Test position
+ spinb = tab.child(roleName="panel", name="Position").findChildren(
+ GenericPredicate(roleName="spin button"))
self.assertEqual(len(spinb), 2)
spinb[0].text = "0.3"
spinb[1].text = "0.2"
- #Test size
- spinb = tab.child(roleName="panel", name="Size").findChildren(GenericPredicate(roleName="spin
button"))
+ # Test size
+ spinb = tab.child(roleName="panel", name="Size").findChildren(
+ GenericPredicate(roleName="spin button"))
self.assertEqual(len(spinb), 2)
spinb[0].text = "0.4"
spinb[1].text = "0.1"
- #Test crop
- spinb = tab.child(roleName="panel", name="Crop").findChildren(GenericPredicate(roleName="spin
button"))
+ # Test crop
+ spinb = tab.child(roleName="panel", name="Crop").findChildren(
+ GenericPredicate(roleName="spin button"))
self.assertEqual(len(spinb), 4)
spinb[0].text = "0.05"
spinb[1].text = "0.12"
@@ -64,30 +69,46 @@ class ClipTransformationTest(PitiviTestCase):
dogtail.rawinput.click(clip1_pos[0], clip1_pos[1])
self.assertNotEqual(tab.child(roleName="slider").value, 1.0)
- self.assertNotNone(self.search_by_text("0.3", tab.child(roleName="panel", name="Position")))
- self.assertNotNone(self.search_by_text("0.2", tab.child(roleName="panel", name="Position")))
-
- self.assertNotNone(self.search_by_text("0.4", tab.child(roleName="panel", name="Size")))
- self.assertNotNone(self.search_by_text("0.1", tab.child(roleName="panel", name="Size")))
-
- self.assertNotNone(self.search_by_text("0.05", tab.child(roleName="panel", name="Crop")))
- self.assertNotNone(self.search_by_text("0.12", tab.child(roleName="panel", name="Crop")))
- self.assertNotNone(self.search_by_text("0.14", tab.child(roleName="panel", name="Crop")))
- self.assertNotNone(self.search_by_text("0.07", tab.child(roleName="panel", name="Crop")))
-
- #Push clear
+ self.assertNotNone(
+ self.search_by_text("0.3", tab.child(roleName="panel", name="Position")))
+ self.assertNotNone(self.search_by_text(
+ "0.2", tab.child(roleName="panel", name="Position")))
+
+ self.assertNotNone(
+ self.search_by_text("0.4", tab.child(roleName="panel", name="Size")))
+ self.assertNotNone(
+ self.search_by_text("0.1", tab.child(roleName="panel", name="Size")))
+
+ self.assertNotNone(self.search_by_text(
+ "0.05", tab.child(roleName="panel", name="Crop")))
+ self.assertNotNone(self.search_by_text(
+ "0.12", tab.child(roleName="panel", name="Crop")))
+ self.assertNotNone(
+ self.search_by_text("0.14", tab.child(roleName="panel", name="Crop")))
+ self.assertNotNone(self.search_by_text(
+ "0.07", tab.child(roleName="panel", name="Crop")))
+
+ # Push clear
tab.child(roleName="scroll bar").value = 140
tab.button("Clear")
self.assertEqual(tab.child(roleName="slider").value, 1.0)
- self.assertNone(self.search_by_text("0.3", tab.child(roleName="panel", name="Position")))
- self.assertNone(self.search_by_text("0.2", tab.child(roleName="panel", name="Position")))
-
- self.assertNone(self.search_by_text("0.4", tab.child(roleName="panel", name="Size")))
- self.assertNone(self.search_by_text("0.1", tab.child(roleName="panel", name="Size")))
-
- self.assertNone(self.search_by_text("0.05", tab.child(roleName="panel", name="Crop")))
- self.assertNone(self.search_by_text("0.12", tab.child(roleName="panel", name="Crop")))
- self.assertNone(self.search_by_text("0.14", tab.child(roleName="panel", name="Crop")))
- self.assertNone(self.search_by_text("0.07", tab.child(roleName="panel", name="Crop")))
+ self.assertNone(self.search_by_text(
+ "0.3", tab.child(roleName="panel", name="Position")))
+ self.assertNone(self.search_by_text(
+ "0.2", tab.child(roleName="panel", name="Position")))
+
+ self.assertNone(self.search_by_text(
+ "0.4", tab.child(roleName="panel", name="Size")))
+ self.assertNone(self.search_by_text(
+ "0.1", tab.child(roleName="panel", name="Size")))
+
+ self.assertNone(
+ self.search_by_text("0.05", tab.child(roleName="panel", name="Crop")))
+ self.assertNone(self.search_by_text(
+ "0.12", tab.child(roleName="panel", name="Crop")))
+ self.assertNone(
+ self.search_by_text("0.14", tab.child(roleName="panel", name="Crop")))
+ self.assertNone(self.search_by_text(
+ "0.07", tab.child(roleName="panel", name="Crop")))
diff --git a/tests/dogtail_scripts/test_dialogs_clipmediaprops.py
b/tests/dogtail_scripts/test_dialogs_clipmediaprops.py
index 84d8bd7..5e08eb5 100644
--- a/tests/dogtail_scripts/test_dialogs_clipmediaprops.py
+++ b/tests/dogtail_scripts/test_dialogs_clipmediaprops.py
@@ -5,6 +5,7 @@ from dogtail.predicate import GenericPredicate, IsATextEntryNamed
class DialogsClipMediaPropsTest(PitiviTestCase):
+
def test_clip_props_dialog(self):
sample = self.import_media("flat_colour1_640x480.png")
sample.click()
@@ -12,13 +13,14 @@ class DialogsClipMediaPropsTest(PitiviTestCase):
media_props_button.click()
# Now check that a dialog shows up with the clip's properties:
- dialog = self.pitivi.child(name="Clip Properties", roleName="dialog", recursive=False)
+ dialog = self.pitivi.child(
+ name="Clip Properties", roleName="dialog", recursive=False)
labels = {"640", "480"}
real_labels = set([])
for label in dialog.findChildren(GenericPredicate(roleName="label")):
real_labels.add(label.text)
self.assertEqual(len(labels.difference(real_labels)), 0,
- "Info seems incorrect\n\tExpected: %s \n\tObtained: %s" % (labels, real_labels))
+ "Info seems incorrect\n\tExpected: %s \n\tObtained: %s" % (labels, real_labels))
self.assertFalse(dialog.child(name="Audio:", roleName="panel").showing)
dialog.child(name="Cancel").click()
sample.deselect()
@@ -29,15 +31,16 @@ class DialogsClipMediaPropsTest(PitiviTestCase):
media_props_button.click()
# Check again for the presence of the dialog and its contents
- dialog = self.pitivi.child(name="Clip Properties", roleName="dialog", recursive=False)
+ dialog = self.pitivi.child(
+ name="Clip Properties", roleName="dialog", recursive=False)
# These are the properties of "tears_of_steel.webm":
labels = {"Video:", "960", "400", "25 fps", "Square",
- "Audio:", "Mono", "44.1 kHz"}
+ "Audio:", "Mono", "44.1 kHz"}
real_labels = set([])
for label in dialog.findChildren(GenericPredicate(roleName="label")):
real_labels.add(label.text)
self.assertEqual(len(labels.difference(real_labels)), 0,
- "Info seems incorrect.\n\tExpected: %s \n\tObtained: %s" % (labels, real_labels))
+ "Info seems incorrect.\n\tExpected: %s \n\tObtained: %s" % (labels, real_labels))
# Uncheck the "mono" channels, so the project should stay stereo
dialog.child(name="Channels:").click()
@@ -46,7 +49,8 @@ class DialogsClipMediaPropsTest(PitiviTestCase):
# Check if correctly applied
self.main_menu_button.click()
self.main_menu_button.menuItem("Project Settings").click()
- dialog = self.pitivi.child(name="Project Settings", roleName="dialog", recursive=False)
+ dialog = self.pitivi.child(
+ name="Project Settings", roleName="dialog", recursive=False)
children = dialog.findChildren(IsATextEntryNamed(""))
childtext = {}
@@ -55,7 +59,8 @@ class DialogsClipMediaPropsTest(PitiviTestCase):
# Framerates and aspect ratio:
self.assertIn("25:1", childtext)
self.assertIn("1:1", childtext)
- children = dialog.findChildren(GenericPredicate(roleName="spin button"))
+ children = dialog.findChildren(
+ GenericPredicate(roleName="spin button"))
spintext = {}
for child in children:
spintext[child.text] = child
@@ -67,4 +72,5 @@ class DialogsClipMediaPropsTest(PitiviTestCase):
try:
dialog.child(name="Stereo", roleName="combo box")
except SearchError:
- self.fail('"Mono" clip property was applied to project settings. Expected the "Stereo" setting
to be preserved.')
+ self.fail(
+ '"Mono" clip property was applied to project settings. Expected the "Stereo" setting to be
preserved.')
diff --git a/tests/dogtail_scripts/test_dialogs_prefs.py b/tests/dogtail_scripts/test_dialogs_prefs.py
index ecc8c74..156ab4f 100644
--- a/tests/dogtail_scripts/test_dialogs_prefs.py
+++ b/tests/dogtail_scripts/test_dialogs_prefs.py
@@ -10,8 +10,10 @@ class DialogsPreferencesTest(PitiviTestCase):
dogtail.rawinput.pressKey("Esc")
self.main_menu_button.click()
self.main_menu_button.menuItem("Preferences").click()
- dialog = self.pitivi.child(name="Preferences", roleName="dialog", recursive=False)
- dialog.child("Reset to Factory Settings", roleName="push button").click()
+ dialog = self.pitivi.child(
+ name="Preferences", roleName="dialog", recursive=False)
+ dialog.child(
+ "Reset to Factory Settings", roleName="push button").click()
# Set the thumbnail gap setting (or whatever the first spinbutton is)
foo = dialog.child(roleName="spin button")
@@ -30,7 +32,8 @@ class DialogsPreferencesTest(PitiviTestCase):
dogtail.rawinput.pressKey("Esc")
self.main_menu_button.click()
self.main_menu_button.menuItem("Preferences").click()
- dialog = self.pitivi.child(name="Preferences", roleName="dialog", recursive=False)
+ dialog = self.pitivi.child(
+ name="Preferences", roleName="dialog", recursive=False)
# Check if the previous values were correctly saved
self.assertEqual(dialog.child(roleName="spin button").text, "12")
@@ -43,8 +46,11 @@ class DialogsPreferencesTest(PitiviTestCase):
# Otherwise the Revert button will not be made sensitive
foo.typeText("888\n")
dialog.child("Revert", roleName="push button").click()
- self.assertEqual(dialog.child(roleName="spin button").text, "12", "Spacing setting was not reverted")
+ self.assertEqual(dialog.child(roleName="spin button")
+ .text, "12", "Spacing setting was not reverted")
# Check resetting to factory settings
- dialog.child("Reset to Factory Settings", roleName="push button").click()
- self.assertEqual(dialog.child(roleName="spin button").text, "5", "Resetting to factory defaults
failed")
+ dialog.child(
+ "Reset to Factory Settings", roleName="push button").click()
+ self.assertEqual(dialog.child(roleName="spin button")
+ .text, "5", "Resetting to factory defaults failed")
diff --git a/tests/dogtail_scripts/test_dialogs_startupwizard.py
b/tests/dogtail_scripts/test_dialogs_startupwizard.py
index e717839..9f4d4a1 100644
--- a/tests/dogtail_scripts/test_dialogs_startupwizard.py
+++ b/tests/dogtail_scripts/test_dialogs_startupwizard.py
@@ -4,6 +4,7 @@ from time import time, sleep
class DialogsStartupWizardTest(PitiviTestCase):
+
def test_welcome(self):
filename = "auto_pitivi_test_project-%i.xges" % time()
filename_full_path = "/tmp/" + filename
diff --git a/tests/dogtail_scripts/test_effects.py b/tests/dogtail_scripts/test_effects.py
index 86a23fc..acaac35 100644
--- a/tests/dogtail_scripts/test_effects.py
+++ b/tests/dogtail_scripts/test_effects.py
@@ -9,10 +9,13 @@ class EffectLibraryTest(PitiviTestCase):
def setUp(self):
PitiviTestCase.setUp(self)
- self.search = self.effectslibrary.child(name="effects library search entry")
+ self.search = self.effectslibrary.child(
+ name="effects library search entry")
self.view = self.effectslibrary.child(roleName="table")
- self.combotypes = self.effectslibrary.child(name="effect category combobox", roleName="combo box")
- self.toggle = self.effectslibrary.child(name="effects library audio togglebutton")
+ self.combotypes = self.effectslibrary.child(
+ name="effect category combobox", roleName="combo box")
+ self.toggle = self.effectslibrary.child(
+ name="effects library audio togglebutton")
def test_effect_library(self):
self.import_media()
@@ -43,7 +46,8 @@ class EffectLibraryTest(PitiviTestCase):
self.insert_clip(sample)
# Assume that the layer controls are roughly 260 pixels wide,
# so the clip position should be x + 300, y + 30
- clippos = (self.timeline.position[0] + 300, self.timeline.position[1] + 30)
+ clippos = (self.timeline.position[
+ 0] + 300, self.timeline.position[1] + 30)
self.effectslibrary.click()
self.clipproperties.click()
@@ -55,25 +59,30 @@ class EffectLibraryTest(PitiviTestCase):
# Each time you add an effect, it adds a row, so +3 children.
self.assertEqual(len(clip_effects_table.children), 3)
- icon = self.search_by_regex("^Agingtv", self.effectslibrary, roleName="table cell")
+ icon = self.search_by_regex(
+ "^Agingtv", self.effectslibrary, roleName="table cell")
# Drag video effect on the clip
self.improved_drag(self.center(icon), clippos)
self.assertEqual(len(clip_effects_table.children), 6)
# Drag video effect to the table
- icon = self.search_by_regex("^3Dflippo", self.effectslibrary, roleName="table cell")
+ icon = self.search_by_regex(
+ "^3Dflippo", self.effectslibrary, roleName="table cell")
self.improved_drag(self.center(icon), self.center(clip_effects_table))
self.assertEqual(len(clip_effects_table.children), 9)
# Drag audio effect on the clip
self.toggle.click()
- effect = self.search_by_regex("^Amplifier", self.effectslibrary, roleName="table cell")
+ effect = self.search_by_regex(
+ "^Amplifier", self.effectslibrary, roleName="table cell")
self.improved_drag(self.center(effect), clippos)
self.assertEqual(len(clip_effects_table.children), 12)
# Drag audio effect on the table
- effect = self.search_by_regex("^Audiokaraoke", self.effectslibrary, roleName="table cell")
- self.improved_drag(self.center(effect), self.center(clip_effects_table))
+ effect = self.search_by_regex(
+ "^Audiokaraoke", self.effectslibrary, roleName="table cell")
+ self.improved_drag(
+ self.center(effect), self.center(clip_effects_table))
self.assertEqual(len(clip_effects_table.children), 15)
self.clipproperties.child(roleName="table").child(name="Amplifier").click()
diff --git a/tests/dogtail_scripts/test_medialibrary.py b/tests/dogtail_scripts/test_medialibrary.py
index 95096bf..e394cd3 100644
--- a/tests/dogtail_scripts/test_medialibrary.py
+++ b/tests/dogtail_scripts/test_medialibrary.py
@@ -8,8 +8,10 @@ class MediaLibraryTest(PitiviTestCase):
def test_medialibrary(self):
# Some commonly-used widgets in this test:
- search = self.medialibrary.child(name="media_search_entry", roleName="text")
- unused_media_button = search.child(name="starred-symbolic", roleName="icon")
+ search = self.medialibrary.child(
+ name="media_search_entry", roleName="text")
+ unused_media_button = search.child(
+ name="starred-symbolic", roleName="icon")
self.force_medialibrary_iconview_mode()
@@ -43,11 +45,14 @@ class MediaLibraryTest(PitiviTestCase):
search.text = ""
search.typeText("colour")
self.assertEqual(len(iconview.children), 3)
- self.import_media() # Not appending to Samples, because it will be None
- # The default clip that gets imported does not have "colour" in its name
+ # Not appending to Samples, because it will be None
+ self.import_media()
+ # The default clip that gets imported does not have "colour" in its
+ # name
self.assertEqual(len(iconview.children), 3)
# However, these ones should show up immediately in the iconview:
- samples.append(self.import_media_multiple(["flat_colour4_1600x1200.jpg",
"flat_colour5_1600x1200.jpg"]))
+ samples.append(self.import_media_multiple(
+ ["flat_colour4_1600x1200.jpg", "flat_colour5_1600x1200.jpg"]))
self.assertEqual(len(iconview.children), 5)
search.text = ""
self.assertEqual(len(iconview.children), 6)
diff --git a/tests/dogtail_scripts/test_project.py b/tests/dogtail_scripts/test_project.py
index 4831540..edf662b 100644
--- a/tests/dogtail_scripts/test_project.py
+++ b/tests/dogtail_scripts/test_project.py
@@ -18,28 +18,33 @@ class ProjectPropertiesTest(PitiviTestCase):
dogtail.rawinput.pressKey("Esc") # Dismiss the welcome dialog
dogtail.rawinput.keyCombo("<Control>o") # Open project
# The file chooser shows up, dismiss it without choosing any project:
- chooser = self.pitivi.child(name="Open File...", roleName="file chooser", recursive=False)
+ chooser = self.pitivi.child(
+ name="Open File...", roleName="file chooser", recursive=False)
chooser.child(name="Cancel", roleName="push button").click()
# We should be able to import clips in the media library
# without failing due to a missing app project instance:
try:
the_clip = self.import_media()
except AssertionError:
- self.fail("The clip import dialog didn't work, something is broken")
+ self.fail(
+ "The clip import dialog didn't work, something is broken")
self.force_medialibrary_iconview_mode()
iconview = self.medialibrary.child(roleName="layered pane")
self.assertEqual(len(iconview.children), 1)
self.insert_clip(the_clip)
# Try to quit, it should warn us about unsaved changes.
dogtail.rawinput.keyCombo("<Control>q") # Quit the app
- unsaved_changes = self.pitivi.child(name="unsaved changes dialog", roleName="dialog",
recursive=False)
+ unsaved_changes = self.pitivi.child(
+ name="unsaved changes dialog", roleName="dialog", recursive=False)
unsaved_changes.button("Close without saving").click()
def test_settings_video(self):
# TODO: test the audio and metadata tabs too
- welcome_dialog = self.pitivi.child(name="Welcome", roleName="frame", recursive=False)
+ welcome_dialog = self.pitivi.child(
+ name="Welcome", roleName="frame", recursive=False)
welcome_dialog.button("New").click()
- dialog = self.pitivi.child(name="Project Settings", roleName="dialog", recursive=False)
+ dialog = self.pitivi.child(
+ name="Project Settings", roleName="dialog", recursive=False)
video = dialog.tab("Video")
# Select a different preset
@@ -74,7 +79,8 @@ class ProjectPropertiesTest(PitiviTestCase):
# Test pixel and display aspect ratio (PAR and DAR)
pixelCombo = video.child(name="Square", roleName="combo box")
pixelText = childtext["1:1"]
- displayCombo = video.child(name="DV Widescreen (16:9)", roleName="combo box")
+ displayCombo = video.child(
+ name="DV Widescreen (16:9)", roleName="combo box")
displayText = childtext["16:9"]
pixelCombo.click()
@@ -88,7 +94,8 @@ class ProjectPropertiesTest(PitiviTestCase):
self.assertEqual(displayCombo.combovalue, "Standard (4:3)")
self.assertEqual(displayText.text, "4:3")
- video.child(name="Display aspect ratio", roleName="radio button").click()
+ video.child(name="Display aspect ratio",
+ roleName="radio button").click()
displayCombo.click()
video.child(name="Cinema (1.37)", roleName="menu item").click()
self.assertEqual(displayCombo.combovalue, "Cinema (1.37)")
@@ -132,8 +139,10 @@ class ProjectPropertiesTest(PitiviTestCase):
sleep(1) # Give enough time for GES to load the project
self.main_menu_button.click()
self.main_menu_button.menuItem("Project Settings").click()
- # Since we shut down the whole app, we must reset our shortcut variables:
- dialog = self.pitivi.child(name="Project Settings", roleName="dialog", recursive=False)
+ # Since we shut down the whole app, we must reset our shortcut
+ # variables:
+ dialog = self.pitivi.child(
+ name="Project Settings", roleName="dialog", recursive=False)
video = dialog.tab("Video")
# Check the resolution:
@@ -145,19 +154,25 @@ class ProjectPropertiesTest(PitiviTestCase):
self.assertIn("1000", spintext, "Video width was not saved")
# Check the aspect ratios:
- dialog = self.pitivi.child(name="Project Settings", roleName="dialog", recursive=False)
+ dialog = self.pitivi.child(
+ name="Project Settings", roleName="dialog", recursive=False)
video = dialog.tab("Video")
children = video.findChildren(IsATextEntryNamed(""))
childtext = {} # The framerate, DAR and PAR custom text entry widgets
for child in children:
childtext[child.text] = child
# You'd expect a PAR of 333:320 and DAR of 37:20... but we changed the
- # resolution (500x1000) right before saving, so the PAR changed to 37:10
- self.assertIn("37:10", childtext, "Pixel aspect ratio was not saved: %s" % childtext)
- # However, the DAR is expected to be unaffected by the image resolution:
+ # resolution (500x1000) right before saving, so the PAR changed to
+ # 37:10
+ self.assertIn(
+ "37:10", childtext, "Pixel aspect ratio was not saved: %s" % childtext)
+ # However, the DAR is expected to be unaffected by the image
+ # resolution:
displayCombo = video.child(name="Cinema (1.85)", roleName="combo box")
- self.assertEqual(displayCombo.combovalue, "Cinema (1.85)", "Display aspect ratio was not saved
(combobox)")
- self.assertIn("37:20", childtext, "Display aspect ratio was not saved (text): %s" % childtext)
+ self.assertEqual(displayCombo.combovalue, "Cinema (1.85)",
+ "Display aspect ratio was not saved (combobox)")
+ self.assertIn(
+ "37:20", childtext, "Display aspect ratio was not saved (text): %s" % childtext)
def test_backup(self):
self.force_medialibrary_iconview_mode()
@@ -170,7 +185,8 @@ class ProjectPropertiesTest(PitiviTestCase):
self.unlink.append(backup_path)
# Set up one clip in the timeline, then save.
- seektime = self.viewer.child(name="timecode_entry").child(roleName="text")
+ seektime = self.viewer.child(
+ name="timecode_entry").child(roleName="text")
self.assertIsNotNone(seektime)
self.insert_clip(sample)
self.goToEnd_button = self.viewer.child(name="goToEnd_button")
@@ -185,16 +201,20 @@ class ProjectPropertiesTest(PitiviTestCase):
self.goToEnd_button.click()
self.assertEqual(seektime.text, DURATION_OF_TWO_CLIPS)
# A backup should appear after 10 secs if no further changes were made
- self.assertTrue(self.wait_for_file(backup_path, timeout=11), "Backup not created")
- self.assertTrue(os.path.getmtime(backup_path) - os.path.getmtime(path) > 0,
- "Backup is older than saved file")
+ self.assertTrue(
+ self.wait_for_file(backup_path, timeout=11), "Backup not created")
+ self.assertTrue(
+ os.path.getmtime(backup_path) - os.path.getmtime(path) > 0,
+ "Backup is older than saved file")
# Try to quit, it should warn us about unsaved changes.
dogtail.rawinput.keyCombo("<Control>q") # Quit the app
- self.pitivi.child(name="unsaved changes dialog", roleName="dialog",
recursive=False).button("Cancel").click()
+ self.pitivi.child(name="unsaved changes dialog",
+ roleName="dialog", recursive=False).button("Cancel").click()
# Check again to ensure the backup didn't disappear - and then save
dogtail.rawinput.keyCombo("<Control>q") # Quit the app
- self.pitivi.child(name="unsaved changes dialog", roleName="dialog",
recursive=False).button("Save").click()
+ self.pitivi.child(name="unsaved changes dialog",
+ roleName="dialog", recursive=False).button("Save").click()
# The backup should now be deleted, and should not come back:
sleep(1)
self.assertFalse(os.path.exists(backup_path))
@@ -203,43 +223,53 @@ class ProjectPropertiesTest(PitiviTestCase):
# Start the app again, make a trivial change, ensure the backup exists
self.setUp()
- welcome_dialog = self.pitivi.child(name="Welcome", roleName="frame", recursive=False)
+ welcome_dialog = self.pitivi.child(
+ name="Welcome", roleName="frame", recursive=False)
welcome_dialog.child(name=filename).doubleClick()
sample = self.import_media("flat_colour1_640x480.png")
# Go figure why, this one takes much longer (30+ seconds) to appear:
- self.assertTrue(self.wait_for_file(backup_path, timeout=45), "Backup not created")
+ self.assertTrue(
+ self.wait_for_file(backup_path, timeout=45), "Backup not created")
self.tearDown(clean=False, kill=True)
sleep(0.5)
# After another "crash", try loading from the backup.
self.setUp()
- seektime = self.viewer.child(name="timecode_entry").child(roleName="text")
- welcome_dialog = self.pitivi.child(name="Welcome", roleName="frame", recursive=False)
+ seektime = self.viewer.child(
+ name="timecode_entry").child(roleName="text")
+ welcome_dialog = self.pitivi.child(
+ name="Welcome", roleName="frame", recursive=False)
welcome_dialog.child(name=filename).doubleClick()
- self.pitivi.child(name="restore from backup dialog", roleName="dialog",
recursive=False).button("Restore from backup").click()
+ self.pitivi.child(name="restore from backup dialog", roleName="dialog", recursive=False).button(
+ "Restore from backup").click()
# Ensure the backup ACTUALLY LOADED instead of a blank project. Really.
sleep(5)
iconview = self.medialibrary.child(roleName="layered pane")
- self.assertEqual(len(iconview.children), 2, "Loaded from backup but the media library does not have
the expected amount of clips")
+ self.assertEqual(len(iconview.children), 2,
+ "Loaded from backup but the media library does not have the expected amount of
clips")
self.goToEnd_button = self.viewer.child(name="goToEnd_button")
self.goToEnd_button.click()
self.assertEqual(seektime.text, DURATION_OF_TWO_CLIPS)
# ...and that clicking "Save" actually triggers "Save As":
dogtail.rawinput.keyCombo("<Control>s") # Save project
try:
- _save_as_dialog = self.pitivi.child(name="Save As...", roleName="file chooser", recursive=False,
retry=False)
+ _save_as_dialog = self.pitivi.child(
+ name="Save As...", roleName="file chooser", recursive=False, retry=False)
dogtail.rawinput.pressKey("Esc") # Dismiss the dialog
except SearchError:
- self.fail('Clicking "Save" after loading a backup project should have triggered the "Save As"
dialog')
+ self.fail(
+ 'Clicking "Save" after loading a backup project should have triggered the "Save As" dialog')
# Do not save, kill once more - the backup should be preserved
# and the user should be prompted again on the next startup
self.tearDown(clean=False, kill=True)
timestamp = os.path.getmtime(backup_path)
sleep(0.5)
self.setUp()
- welcome_dialog = self.pitivi.child(name="Welcome", roleName="frame", recursive=False)
+ welcome_dialog = self.pitivi.child(
+ name="Welcome", roleName="frame", recursive=False)
welcome_dialog.child(name=filename).doubleClick()
- self.pitivi.child(name="restore from backup dialog", roleName="dialog",
recursive=False).button("Ignore backup").click()
+ self.pitivi.child(name="restore from backup dialog",
+ roleName="dialog", recursive=False).button("Ignore backup").click()
# The backup file must not have changed or vanished:
self.assertEqual(timestamp, os.path.getmtime(backup_path))
@@ -247,10 +277,12 @@ class ProjectPropertiesTest(PitiviTestCase):
sample = self.import_media("flat_colour2_640x480.png")
self.assertTrue(self.wait_for_update(backup_path, timestamp))
- # Quitting should warn us about unsaved changes (still in a newer version)
+ # Quitting should warn us about unsaved changes (still in a newer
+ # version)
dogtail.rawinput.keyCombo("<Control>q") # Quit the app
# Dismiss the unsaved changes warning by cancelling it:
- self.pitivi.child(name="unsaved changes dialog", roleName="dialog",
recursive=False).button("Cancel").click()
+ self.pitivi.child(name="unsaved changes dialog",
+ roleName="dialog", recursive=False).button("Cancel").click()
# Save stuff behind the scenes...
self.saveProject(saveAs=False)
# The backup file should now be gone, and no warning displayed:
@@ -259,15 +291,18 @@ class ProjectPropertiesTest(PitiviTestCase):
def test_load_save(self):
self.goToEnd_button = self.viewer.child(name="goToEnd_button")
- seektime = self.viewer.child(name="timecode_entry").child(roleName="text")
- infobar_media = self.medialibrary.child(name="Information", roleName="alert")
+ seektime = self.viewer.child(
+ name="timecode_entry").child(roleName="text")
+ infobar_media = self.medialibrary.child(
+ name="Information", roleName="alert")
iconview = self.medialibrary.child(roleName="layered pane")
filename1 = "/tmp/auto_pitivi_test_project-1.xges"
filename2 = "/tmp/auto_pitivi_test_project-2.xges"
self.unlink.append(filename1)
self.unlink.append(filename2)
- # FIXME: this test would fail in listview mode - for now we just force iconview mode.
+ # FIXME: this test would fail in listview mode - for now we just force
+ # iconview mode.
self.force_medialibrary_iconview_mode()
# Create project #1 - one clip with only one instance on the timeline
@@ -277,22 +312,26 @@ class ProjectPropertiesTest(PitiviTestCase):
self.insert_clip(project1_sample1)
self.saveProject(filename1)
- # Creating a blank project should clear the library and show its infobar
+ # Creating a blank project should clear the library and show its
+ # infobar
sleep(0.5)
dogtail.rawinput.keyCombo("<Control>n") # Create a new project
- self.pitivi.child(name="Project Settings", roleName="dialog", recursive=False).button("OK").click()
+ self.pitivi.child(
+ name="Project Settings", roleName="dialog", recursive=False).button("OK").click()
self.assertEqual(len(iconview.children), 0,
- "Created a new project, but the media library is not empty")
+ "Created a new project, but the media library is not empty")
self.assertTrue(infobar_media.showing)
# We don't have a very good way to check that the timeline was cleared,
# but this is better than nothing as a quick sanity check:
self.goToEnd_button.click()
sleep(0.5)
- self.assertEqual(seektime.text, "00:00.000", "The timeline is not empty")
+ self.assertEqual(
+ seektime.text, "00:00.000", "The timeline is not empty")
# Create project #2 - 2 clips with 2 timeline instances of the first one
- # We use only the first one on the timeline because we know its duration
+ # We use only the first one on the timeline because we know its
+ # duration
project2_sample1 = self.import_media()
__project2_sample2 = self.import_media("flat_colour1_640x480.png")
self.assertFalse(infobar_media.showing)
@@ -313,7 +352,7 @@ class ProjectPropertiesTest(PitiviTestCase):
sleep(0.5)
self.medialibrary.child(name="media_remove_button").click()
self.assertEqual(len(iconview.children), 1,
- "A clip has just been removed so only one should be left")
+ "A clip has just been removed so only one should be left")
self.loadProject(filename1, unsaved_changes="discard")
sleep(3)
self.assertEqual(len(iconview.children), 1)
diff --git a/tests/dogtail_scripts/test_timeline.py b/tests/dogtail_scripts/test_timeline.py
index 4cc0ae7..590963e 100644
--- a/tests/dogtail_scripts/test_timeline.py
+++ b/tests/dogtail_scripts/test_timeline.py
@@ -9,11 +9,13 @@ from pyatspi import KEY_PRESS, KEY_RELEASE
class TimelineTest(PitiviTestCase):
+
def setUp(self):
super(TimelineTest, self).setUp()
self.goToEnd_button = self.viewer.child(name="goToEnd_button")
self.goToStart_button = self.viewer.child(name="goToStart_button")
- self.timecode_widget = self.viewer.child(name="timecode_entry").child(roleName="text")
+ self.timecode_widget = self.viewer.child(
+ name="timecode_entry").child(roleName="text")
def insertTwoClipsAndSeekToEnd(self):
# Just a small helper method to facilitate timeline setup
@@ -51,8 +53,10 @@ class TimelineTest(PitiviTestCase):
for i in range(20):
if i % 4 == 0:
# Drag to center, next layer, out, and then back in
- middle = [self.center(timeline), endpos[(i + 1) % 2], self.center(sample)]
- self.improved_drag(self.center(sample), endpos[i % 3], middle=middle)
+ middle = [self.center(timeline), endpos[
+ (i + 1) % 2], self.center(sample)]
+ self.improved_drag(
+ self.center(sample), endpos[i % 3], middle=middle)
else:
# Simple drag
self.improved_drag(self.center(sample), endpos[i % 3])
@@ -77,15 +81,19 @@ class TimelineTest(PitiviTestCase):
self.assertEqual(self.timecode_widget.text, DURATION_OF_TWO_CLIPS)
dogtail.rawinput.click(self.getTimelineX(0.75), self.getTimelineY(0))
- self.timeline_toolbar.child(name="Split", roleName="push button").click()
+ self.timeline_toolbar.child(
+ name="Split", roleName="push button").click()
# Delete the first half of the split clip.
- dogtail.rawinput.click(self.getTimelineX(0.75 - 0.125), self.getTimelineY(0))
- self.timeline_toolbar.child(name="Delete", roleName="push button").click()
+ dogtail.rawinput.click(
+ self.getTimelineX(0.75 - 0.125), self.getTimelineY(0))
+ self.timeline_toolbar.child(
+ name="Delete", roleName="push button").click()
self.goToEnd_button.click()
self.assertEqual(self.timecode_widget.text, DURATION_OF_TWO_CLIPS)
# Delete also the second half of the split clip.
- dogtail.rawinput.click(self.getTimelineX(0.75 + 0.125), self.getTimelineY(0))
+ dogtail.rawinput.click(
+ self.getTimelineX(0.75 + 0.125), self.getTimelineY(0))
dogtail.rawinput.pressKey("Del")
self.goToEnd_button.click()
@@ -98,7 +106,8 @@ class TimelineTest(PitiviTestCase):
pos = (0.05, 0.48, 0.17, 0.24, 0.35, 0.61, 0.41, 0.51)
for k in pos:
for p in pos:
- dogtail.rawinput.click(self.getTimelineX(p + k / 10), self.getTimelineY(0))
+ dogtail.rawinput.click(
+ self.getTimelineX(p + k / 10), self.getTimelineY(0))
# Allow the UI to update
sleep(0.1)
# Split
@@ -115,19 +124,23 @@ class TimelineTest(PitiviTestCase):
sleep(0.1)
dogtail.rawinput.press(self.getTimelineX(0.75), self.getTimelineY(0))
# Drag in, this should create a transition.
- dogtail.rawinput.absoluteMotion(self.getTimelineX(0.5), self.getTimelineY(0))
+ dogtail.rawinput.absoluteMotion(
+ self.getTimelineX(0.5), self.getTimelineY(0))
sleep(0.1)
# Drag out, the transition should be gone.
- dogtail.rawinput.absoluteMotion(self.getTimelineX(0.9), self.getTimelineY(0))
+ dogtail.rawinput.absoluteMotion(
+ self.getTimelineX(0.9), self.getTimelineY(0))
sleep(0.1)
# Drag in again, this should create a transition.
- dogtail.rawinput.absoluteMotion(self.getTimelineX(0.25), self.getTimelineY(0))
+ dogtail.rawinput.absoluteMotion(
+ self.getTimelineX(0.25), self.getTimelineY(0))
sleep(0.1)
dogtail.rawinput.release(self.getTimelineX(0.5), self.getTimelineY(0))
sleep(0.1)
# Click the transition, make sure it's selected.
- dogtail.rawinput.click(self.getTimelineX(0.5 - 0.125), self.getTimelineY(0))
+ dogtail.rawinput.click(
+ self.getTimelineX(0.5 - 0.125), self.getTimelineY(0))
sleep(0.1)
iconlist = self.transitions.child(roleName="layered pane")
self.assertTrue(iconlist.sensitive)
@@ -150,20 +163,26 @@ class TimelineTest(PitiviTestCase):
maxx = middle
else:
minx = middle
- #+5 due to handle size
+ # +5 due to handle size
return maxx - timeline.position[0] + 5
def ripple_roll(self, from_percent, to_percent):
- dogtail.rawinput.click(self.getTimelineX(from_percent), self.getTimelineY(0))
+ dogtail.rawinput.click(
+ self.getTimelineX(from_percent), self.getTimelineY(0))
sleep(0.1)
- registry.generateKeyboardEvent(dogtail.rawinput.keyNameToKeyCode("Shift_L"), None, KEY_PRESS)
+ registry.generateKeyboardEvent(
+ dogtail.rawinput.keyNameToKeyCode("Shift_L"), None, KEY_PRESS)
try:
- dogtail.rawinput.press(self.getTimelineX(from_percent), self.getTimelineY(0))
- dogtail.rawinput.absoluteMotion(self.getTimelineX(to_percent), self.getTimelineY(0))
+ dogtail.rawinput.press(
+ self.getTimelineX(from_percent), self.getTimelineY(0))
+ dogtail.rawinput.absoluteMotion(
+ self.getTimelineX(to_percent), self.getTimelineY(0))
sleep(0.1)
- dogtail.rawinput.release(self.getTimelineX(to_percent), self.getTimelineY(0))
+ dogtail.rawinput.release(
+ self.getTimelineX(to_percent), self.getTimelineY(0))
finally:
- registry.generateKeyboardEvent(dogtail.rawinput.keyNameToKeyCode("Shift_L"), None, KEY_RELEASE)
+ registry.generateKeyboardEvent(
+ dogtail.rawinput.keyNameToKeyCode("Shift_L"), None, KEY_RELEASE)
sleep(0.1)
def test_ripple_roll(self):
@@ -174,7 +193,8 @@ class TimelineTest(PitiviTestCase):
self.ripple_roll(from_percent, to_percent)
self.goToEnd_button.click()
sleep(0.1)
- self.assertGreater(self.timecode_widget.text, DURATION_OF_TWO_CLIPS)
+ self.assertGreater(
+ self.timecode_widget.text, DURATION_OF_TWO_CLIPS)
self.goToStart_button.click()
sleep(0.1)
self.ripple_roll(to_percent, from_percent)
@@ -189,8 +209,10 @@ class TimelineTest(PitiviTestCase):
self.effectslibrary.click()
self.clipproperties.click()
table = self.clipproperties.child(roleName="table")
- effect_from_library = self.search_by_text("Agingtv", self.effectslibrary, roleName="table cell",
exactMatchOnly=False)
- self.improved_drag(self.center(effect_from_library), self.center(table))
+ effect_from_library = self.search_by_text(
+ "Agingtv", self.effectslibrary, roleName="table cell", exactMatchOnly=False)
+ self.improved_drag(
+ self.center(effect_from_library), self.center(table))
sleep(1.1)
ripple_roll(from_percent=0.25, to_percent=0.75)
@@ -214,7 +236,8 @@ class TimelineTest(PitiviTestCase):
video_percent = 2.0 / 15
# Delete the first clip to make some space.
- dogtail.rawinput.click(self.getTimelineX(image_percent / 4), self.getTimelineY(0))
+ dogtail.rawinput.click(
+ self.getTimelineX(image_percent / 4), self.getTimelineY(0))
dogtail.rawinput.pressKey("Del")
sleep(0.1)
@@ -222,7 +245,8 @@ class TimelineTest(PitiviTestCase):
self.ripple_roll(video_percent + image_percent / 4, 0)
# Without this the next call does not work because
# the last riple_roll is a bit off because of the 0.
- dogtail.rawinput.click(self.getTimelineX(image_percent / 4), self.getTimelineY(0))
+ dogtail.rawinput.click(
+ self.getTimelineX(image_percent / 4), self.getTimelineY(0))
self.goToEnd_button.click()
sleep(0.1)
self.assertEqual(self.timecode_widget.text, "00:12.999")
diff --git a/tests/runtests.py b/tests/runtests.py
index 4d6fd95..3877084 100644
--- a/tests/runtests.py
+++ b/tests/runtests.py
@@ -40,7 +40,8 @@ def get_build_dir():
# Probably running make distcheck. The path to the test files
# is different than the build path, so we must use the current
# dir which is build_path/tests.
- build_dir = os.path.join(os.path.abspath(os.path.curdir), os.path.pardir)
+ build_dir = os.path.join(
+ os.path.abspath(os.path.curdir), os.path.pardir)
return os.path.abspath(build_dir)
@@ -84,7 +85,7 @@ if __name__ == "__main__":
# Run the tests.
testRunner = unittest.TextTestRunner(descriptions=descriptions,
- verbosity=verbosity)
+ verbosity=verbosity)
result = testRunner.run(suite)
if result.failures or result.errors:
sys.exit(1)
diff --git a/tests/test_application.py b/tests/test_application.py
index 62d8d56..5d7ae0d 100644
--- a/tests/test_application.py
+++ b/tests/test_application.py
@@ -27,6 +27,7 @@ from pitivi import configure
class MockGioFile(object):
+
def load_contents_finish(self, result):
return (True, result)
@@ -45,13 +46,15 @@ class TestPitivi(common.TestCase):
app = application.Pitivi()
app._checkVersion()
- app._versionInfoReceivedCb(MockGioFile(), "%s=CURRENT" % configure.VERSION, None)
+ app._versionInfoReceivedCb(
+ MockGioFile(), "%s=CURRENT" % configure.VERSION, None)
self.assertTrue(app.isLatest())
self.assertEqual(configure.VERSION, app.getLatest())
app = application.Pitivi()
app._checkVersion()
- app._versionInfoReceivedCb(MockGioFile(), "%s=current\n0=supported" % configure.VERSION, None)
+ app._versionInfoReceivedCb(
+ MockGioFile(), "%s=current\n0=supported" % configure.VERSION, None)
self.assertTrue(app.isLatest())
self.assertEqual(configure.VERSION, app.getLatest())
@@ -63,7 +66,8 @@ class TestPitivi(common.TestCase):
app = application.Pitivi()
app._checkVersion()
- app._versionInfoReceivedCb(MockGioFile(), "999.0=CURRENT\n%s=SUPPORTED" % configure.VERSION, None)
+ app._versionInfoReceivedCb(
+ MockGioFile(), "999.0=CURRENT\n%s=SUPPORTED" % configure.VERSION, None)
self.assertFalse(app.isLatest())
self.assertEqual("999.0", app.getLatest())
diff --git a/tests/test_check.py b/tests/test_check.py
index 0201ea6..1106dce 100644
--- a/tests/test_check.py
+++ b/tests/test_check.py
@@ -35,7 +35,8 @@ class FakeDependency(check.Dependency):
class TestDependency(common.TestCase):
def testBoolEvaluation(self):
- dependency = FakeDependency(modulename="module1", version_required_string=None)
+ dependency = FakeDependency(
+ modulename="module1", version_required_string=None)
self.assertFalse(dependency)
self.assertFalse(dependency.satisfied)
diff --git a/tests/test_clipproperties.py b/tests/test_clipproperties.py
index d4d7fac..af4c5bb 100644
--- a/tests/test_clipproperties.py
+++ b/tests/test_clipproperties.py
@@ -28,21 +28,35 @@ class EffectPropertiesTest(unittest.TestCase):
def testCalculateEffectPriority(self):
# Dragging 1 onto itself and nearby.
- self.assertEqual(1, EffectProperties.calculateEffectPriority(1, 0, Gtk.TreeViewDropPosition.AFTER))
- self.assertEqual(1, EffectProperties.calculateEffectPriority(1, 1, Gtk.TreeViewDropPosition.BEFORE))
- self.assertEqual(1, EffectProperties.calculateEffectPriority(1, 1,
Gtk.TreeViewDropPosition.INTO_OR_BEFORE))
- self.assertEqual(1, EffectProperties.calculateEffectPriority(1, 1,
Gtk.TreeViewDropPosition.INTO_OR_AFTER))
- self.assertEqual(1, EffectProperties.calculateEffectPriority(1, 1, Gtk.TreeViewDropPosition.AFTER))
- self.assertEqual(1, EffectProperties.calculateEffectPriority(1, 2, Gtk.TreeViewDropPosition.BEFORE))
+ self.assertEqual(1, EffectProperties.calculateEffectPriority(
+ 1, 0, Gtk.TreeViewDropPosition.AFTER))
+ self.assertEqual(1, EffectProperties.calculateEffectPriority(
+ 1, 1, Gtk.TreeViewDropPosition.BEFORE))
+ self.assertEqual(1, EffectProperties.calculateEffectPriority(
+ 1, 1, Gtk.TreeViewDropPosition.INTO_OR_BEFORE))
+ self.assertEqual(1, EffectProperties.calculateEffectPriority(
+ 1, 1, Gtk.TreeViewDropPosition.INTO_OR_AFTER))
+ self.assertEqual(1, EffectProperties.calculateEffectPriority(
+ 1, 1, Gtk.TreeViewDropPosition.AFTER))
+ self.assertEqual(1, EffectProperties.calculateEffectPriority(
+ 1, 2, Gtk.TreeViewDropPosition.BEFORE))
# Dragging 0 and 3 between rows 1 and 2.
- self.assertEqual(1, EffectProperties.calculateEffectPriority(0, 1, Gtk.TreeViewDropPosition.AFTER))
- self.assertEqual(1, EffectProperties.calculateEffectPriority(0, 2, Gtk.TreeViewDropPosition.BEFORE))
- self.assertEqual(2, EffectProperties.calculateEffectPriority(3, 1, Gtk.TreeViewDropPosition.AFTER))
- self.assertEqual(2, EffectProperties.calculateEffectPriority(3, 2, Gtk.TreeViewDropPosition.BEFORE))
+ self.assertEqual(1, EffectProperties.calculateEffectPriority(
+ 0, 1, Gtk.TreeViewDropPosition.AFTER))
+ self.assertEqual(1, EffectProperties.calculateEffectPriority(
+ 0, 2, Gtk.TreeViewDropPosition.BEFORE))
+ self.assertEqual(2, EffectProperties.calculateEffectPriority(
+ 3, 1, Gtk.TreeViewDropPosition.AFTER))
+ self.assertEqual(2, EffectProperties.calculateEffectPriority(
+ 3, 2, Gtk.TreeViewDropPosition.BEFORE))
# Dragging 0 and 2 onto 1.
- self.assertEqual(1, EffectProperties.calculateEffectPriority(0, 1,
Gtk.TreeViewDropPosition.INTO_OR_BEFORE))
- self.assertEqual(1, EffectProperties.calculateEffectPriority(0, 1,
Gtk.TreeViewDropPosition.INTO_OR_AFTER))
- self.assertEqual(1, EffectProperties.calculateEffectPriority(2, 1,
Gtk.TreeViewDropPosition.INTO_OR_BEFORE))
- self.assertEqual(1, EffectProperties.calculateEffectPriority(2, 1,
Gtk.TreeViewDropPosition.INTO_OR_AFTER))
+ self.assertEqual(1, EffectProperties.calculateEffectPriority(
+ 0, 1, Gtk.TreeViewDropPosition.INTO_OR_BEFORE))
+ self.assertEqual(1, EffectProperties.calculateEffectPriority(
+ 0, 1, Gtk.TreeViewDropPosition.INTO_OR_AFTER))
+ self.assertEqual(1, EffectProperties.calculateEffectPriority(
+ 2, 1, Gtk.TreeViewDropPosition.INTO_OR_BEFORE))
+ self.assertEqual(1, EffectProperties.calculateEffectPriority(
+ 2, 1, Gtk.TreeViewDropPosition.INTO_OR_AFTER))
diff --git a/tests/test_log.py b/tests/test_log.py
index da9aa79..4e6975d 100644
--- a/tests/test_log.py
+++ b/tests/test_log.py
@@ -261,7 +261,7 @@ class TestLogNames(unittest.TestCase):
def testGetLevelNames(self):
self.assertEqual(['ERROR', 'WARN', 'FIXME', 'INFO', 'DEBUG', 'LOG'],
- log.getLevelNames())
+ log.getLevelNames())
def testGetLevelCode(self):
self.assertEqual(1, log.getLevelInt('ERROR'))
diff --git a/tests/test_mainwindow.py b/tests/test_mainwindow.py
index 51615a0..e0374ca 100644
--- a/tests/test_mainwindow.py
+++ b/tests/test_mainwindow.py
@@ -42,7 +42,9 @@ class TestMainWindow(TestCase):
(0, GES.AudioUriSource()),
(1, GES.AudioTransition())]:
self.mainwindow.switchContextTab(bElement)
- self.assertEqual(expected_tab, self.mainwindow.context_tabs.get_current_page())
+ self.assertEqual(
+ expected_tab, self.mainwindow.context_tabs.get_current_page())
# Make sure the tab does not change when using an invalid argument.
self.mainwindow.switchContextTab("invalid")
- self.assertEqual(expected_tab, self.mainwindow.context_tabs.get_current_page())
+ self.assertEqual(
+ expected_tab, self.mainwindow.context_tabs.get_current_page())
diff --git a/tests/test_prefs.py b/tests/test_prefs.py
index dd77661..d0bde95 100644
--- a/tests/test_prefs.py
+++ b/tests/test_prefs.py
@@ -26,64 +26,65 @@ class PreferencesDialogTest(unittest.TestCase):
def testNumeric(self):
PreferencesDialog.addNumericPreference('numericPreference1',
- label="Open Range",
- section="Test",
- description="This option has no upper bound",
- lower=-10)
- self.assertTrue('numericPreference1' in PreferencesDialog.prefs['Test'])
+ label="Open Range",
+ section="Test",
+ description="This option has no upper bound",
+ lower=-10)
+ self.assertTrue(
+ 'numericPreference1' in PreferencesDialog.prefs['Test'])
PreferencesDialog.addNumericPreference('numericPreference2',
- label="Closed Range",
- section="Test",
- description="This option has both upper and lower bounds",
- lower=-10,
- upper=10000)
+ label="Closed Range",
+ section="Test",
+ description="This option has both upper and lower bounds",
+ lower=-10,
+ upper=10000)
def testText(self):
PreferencesDialog.addTextPreference('textPreference1',
- label="Unfiltered",
- section="Test",
- description="Anything can go in this box")
+ label="Unfiltered",
+ section="Test",
+ description="Anything can go in this box")
PreferencesDialog.addTextPreference('textPreference2',
- label="Numbers only",
- section="Test",
- description="This input validates its input with a regex",
- matches=r"^-?\d+(\.\d+)?$")
+ label="Numbers only",
+ section="Test",
+ description="This input validates its input with a regex",
+ matches=r"^-?\d+(\.\d+)?$")
def testOther(self):
PreferencesDialog.addPathPreference('aPathPreference',
- label="Test Path",
- section="Test",
- description="Test the path widget")
+ label="Test Path",
+ section="Test",
+ description="Test the path widget")
PreferencesDialog.addChoicePreference('aChoicePreference',
- label="Swallow Velocity",
- section="Test",
- description="What is the airspeed velocity of a coconut-laden swallow?",
- choices=(
- ("42 Knots", 32),
- ("9 furlongs per fortnight", 42),
- ("I don't know that!", None)))
+ label="Swallow Velocity",
+ section="Test",
+ description="What is the airspeed velocity of a coconut-laden
swallow?",
+ choices=(
+ ("42 Knots", 32),
+ ("9 furlongs per fortnight", 42),
+ ("I don't know that!", None)))
PreferencesDialog.addChoicePreference('aLongChoicePreference',
- label="Favorite Color",
- section="Test",
- description="What is the color of the parrot's plumage?",
- choices=(
- ("Mauve", "Mauve"),
- ("Chartreuse", "Chartreuse"),
- ("Magenta", "Magenta"),
- ("Pink", "Pink"),
- ("Norwegian Blue", "Norwegian Blue"),
- ("Yellow Ochre", "Yellow Ochre")))
+ label="Favorite Color",
+ section="Test",
+ description="What is the color of the parrot's plumage?",
+ choices=(
+ ("Mauve", "Mauve"),
+ ("Chartreuse", "Chartreuse"),
+ ("Magenta", "Magenta"),
+ ("Pink", "Pink"),
+ ("Norwegian Blue", "Norwegian Blue"),
+ ("Yellow Ochre", "Yellow Ochre")))
PreferencesDialog.addTogglePreference('aTogglePreference',
- label="Test Toggle",
- section="Test",
- description="Test the toggle widget")
+ label="Test Toggle",
+ section="Test",
+ description="Test the toggle widget")
PreferencesDialog.addFontPreference('aFontPreference',
- label="Foo Font",
- section="Test",
- description="Test the font widget")
+ label="Foo Font",
+ section="Test",
+ description="Test the font widget")
diff --git a/tests/test_preset.py b/tests/test_preset.py
index 481c82c..b4e89f2 100644
--- a/tests/test_preset.py
+++ b/tests/test_preset.py
@@ -95,11 +95,12 @@ class TestPresetBasics(TestCase):
def testAddPreset(self):
self.manager.addPreset('preseT onE', {'name1': '1A'})
self.assertRaises(DuplicatePresetNameException,
- self.manager.addPreset, 'Preset One', {'name1': '2A'})
+ self.manager.addPreset, 'Preset One', {'name1': '2A'})
def testAddDuplicatePreset(self):
self.manager.addPreset('x', {})
- self.assertRaises(DuplicatePresetNameException, self.manager.addPreset, 'x', {})
+ self.assertRaises(
+ DuplicatePresetNameException, self.manager.addPreset, 'x', {})
def testAddPresetWithNonAsciiName(self):
unicode_name = "ソリッド・スネーク"
@@ -115,10 +116,10 @@ class TestPresetBasics(TestCase):
# Renaming 'Preset One' to 'Preset TWO'.
self.assertRaises(DuplicatePresetNameException,
- self.manager.renamePreset, '0', 'Preset TWO')
+ self.manager.renamePreset, '0', 'Preset TWO')
# Renaming 'Preset One' to 'Preset two'.
self.assertRaises(DuplicatePresetNameException,
- self.manager.renamePreset, '0', 'Preset two')
+ self.manager.renamePreset, '0', 'Preset two')
class TestAudioPresetsIO(TestCase):
@@ -138,34 +139,36 @@ class TestAudioPresetsIO(TestCase):
def testSaveAndLoad(self):
self.manager.addPreset("Vegeta",
- {"channels": 6000,
- "sample-rate": 44100})
+ {"channels": 6000,
+ "sample-rate": 44100})
self.manager.saveAll()
self.assertEqual(1, countUserPresets(self.manager))
self.manager.addPreset("Nappa",
- {"channels": 4000,
- "sample-rate": 44100})
+ {"channels": 4000,
+ "sample-rate": 44100})
self.manager.saveAll()
self.assertEqual(2, countUserPresets(self.manager))
other_manager = self.createOtherManager()
other_manager.loadAll()
- total_presets = countDefaultPresets(self.manager) + countUserPresets(self.manager)
+ total_presets = countDefaultPresets(
+ self.manager) + countUserPresets(self.manager)
self.assertEqual(total_presets, len(other_manager.presets))
def testNonAsciiFilenamesSaveAndLoad(self):
non_ascii_preset_name = "Solid Snake (ソリッド・スネーク) \\#!\"'$%?&*"
self.manager.addPreset(non_ascii_preset_name,
- {"channels": 2,
- "sample-rate": 44100})
+ {"channels": 2,
+ "sample-rate": 44100})
snake = self.manager.presets[non_ascii_preset_name]
self.assertEqual(2, len(snake))
self.manager.saveAll()
other_manager = self.createOtherManager()
other_manager.loadAll()
- self.assertEqual(1 + countDefaultPresets(other_manager), len(other_manager.presets))
+ self.assertEqual(1 + countDefaultPresets(
+ other_manager), len(other_manager.presets))
snaaaake = other_manager.presets[non_ascii_preset_name]
self.assertEqual(snake, snaaaake)
@@ -173,14 +176,15 @@ class TestAudioPresetsIO(TestCase):
# This would be an invalid file name as is.
preset_name = " / % "
self.manager.addPreset(preset_name,
- {"channels": 2,
- "sample-rate": 44100})
+ {"channels": 2,
+ "sample-rate": 44100})
values = self.manager.presets[preset_name]
self.assertEqual(2, len(values))
self.manager.saveAll()
other_manager = self.createOtherManager()
other_manager.loadAll()
- self.assertEqual(1 + countDefaultPresets(other_manager), len(other_manager.presets))
+ self.assertEqual(1 + countDefaultPresets(
+ other_manager), len(other_manager.presets))
other_values = other_manager.presets[preset_name]
self.assertEqual(values, other_values)
diff --git a/tests/test_project.py b/tests/test_project.py
index a5ad911..0783252 100644
--- a/tests/test_project.py
+++ b/tests/test_project.py
@@ -58,6 +58,7 @@ class MockProject(object):
class ProjectManagerListener(object):
+
def __init__(self, manager):
self.manager = manager
self.connectToProjectManager(self.manager)
@@ -68,8 +69,8 @@ class ProjectManagerListener(object):
def connectToProjectManager(self, manager):
for signal in ("new-project-loading", "new-project-loaded",
- "new-project-created", "new-project-failed", "missing-uri",
- "closing-project", "project-closed"):
+ "new-project-created", "new-project-failed", "missing-uri",
+ "closing-project", "project-closed"):
self.manager.connect(signal, self._recordSignal, signal)
def _recordSignal(self, *args):
@@ -81,6 +82,7 @@ class ProjectManagerListener(object):
class TestProjectManager(TestCase):
+
def setUp(self):
self.manager = ProjectManager(None)
self.listener = ProjectManagerListener(self.manager)
@@ -147,7 +149,8 @@ class TestProjectManager(TestCase):
self.mainloop = GLib.MainLoop()
result = [False]
- self.manager.connect("missing-uri", missingUriCb, self.mainloop, result)
+ self.manager.connect(
+ "missing-uri", missingUriCb, self.mainloop, result)
# Load a project with a missing asset.
unused, xges_path = tempfile.mkstemp()
@@ -297,11 +300,13 @@ class TestProjectManager(TestCase):
backup_uri = self.manager._makeBackupURI(uri)
# Save the backup
- self.assertTrue(self.manager.saveProject(self.manager.current_project, backup=True))
+ self.assertTrue(self.manager.saveProject(
+ self.manager.current_project, backup=True))
self.assertTrue(uri_is_reachable(backup_uri))
self.manager.closeRunningProject()
- self.assertFalse(uri_is_reachable(backup_uri), "Backup file not deleted when project closed")
+ self.assertFalse(uri_is_reachable(backup_uri),
+ "Backup file not deleted when project closed")
class TestProjectLoading(TestCase):
@@ -328,7 +333,8 @@ class TestProjectLoading(TestCase):
self.assertTrue(project.createTimeline())
GLib.timeout_add_seconds(5, quit, self.mainloop)
self.mainloop.run()
- self.assertTrue(result[0], "Blank project creation failed to trigger signal: loaded")
+ self.assertTrue(
+ result[0], "Blank project creation failed to trigger signal: loaded")
# Load the blank project and make sure "loaded" is triggered.
unused, xges_path = tempfile.mkstemp()
@@ -342,7 +348,8 @@ class TestProjectLoading(TestCase):
project2.connect("loaded", loaded, self.mainloop, result)
GLib.timeout_add_seconds(5, quit, self.mainloop)
self.mainloop.run()
- self.assertTrue(result[0], "Blank project loading failed to trigger signal: loaded")
+ self.assertTrue(
+ result[0], "Blank project loading failed to trigger signal: loaded")
finally:
os.remove(xges_path)
@@ -369,19 +376,23 @@ class TestProjectLoading(TestCase):
# Create a blank project and save it.
project = _createRealProject()
result = [False, False, False]
- uris = ["file://%s/samples/tears_of_steel.webm" % os.path.dirname(os.path.abspath(__file__))]
+ uris = ["file://%s/samples/tears_of_steel.webm" %
+ os.path.dirname(os.path.abspath(__file__))]
project.connect("loaded", loaded, self.mainloop, result, uris)
project.connect("done-importing", added, self.mainloop, result, uris)
self.assertTrue(project.createTimeline())
GLib.timeout_add_seconds(5, quit, self.mainloop)
self.mainloop.run()
- self.assertTrue(result[0], "Project creation failed to trigger signal: loaded")
- self.assertTrue(result[1], "Asset add failed to trigger signal: done-importing")
+ self.assertTrue(
+ result[0], "Project creation failed to trigger signal: loaded")
+ self.assertTrue(
+ result[1], "Asset add failed to trigger signal: done-importing")
self.assertTrue(result[2], "Asset re-adding failed")
class TestExportSettings(TestCase):
+
"""Test the project.MultimediaSettings class."""
def testMasterAttributes(self):
diff --git a/tests/test_projectsettings.py b/tests/test_projectsettings.py
index ebff2d5..fafe376 100644
--- a/tests/test_projectsettings.py
+++ b/tests/test_projectsettings.py
@@ -34,11 +34,13 @@ class TestProjectSettingsDialog(TestCase):
self.assertEqual('New preset', name)
preset_manager.addPreset(name, {})
- new_preset1 = ProjectSettingsDialog._getUniquePresetName(preset_manager)
+ new_preset1 = ProjectSettingsDialog._getUniquePresetName(
+ preset_manager)
self.assertEqual('New preset 1', new_preset1)
# Intentionally add 'New preset 2' before 'New preset 1'.
preset_manager.addPreset('New preset 2', {})
preset_manager.addPreset('New preset 1', {})
- new_preset3 = ProjectSettingsDialog._getUniquePresetName(preset_manager)
+ new_preset3 = ProjectSettingsDialog._getUniquePresetName(
+ preset_manager)
self.assertEqual('New preset 3', new_preset3)
diff --git a/tests/test_system.py b/tests/test_system.py
index 4999392..df9153e 100644
--- a/tests/test_system.py
+++ b/tests/test_system.py
@@ -28,6 +28,7 @@ from pitivi.utils.system import System, getSystem, GnomeSystem, \
class TestSystem(TestCase):
+
def setUp(self):
self.system = System()
@@ -41,17 +42,17 @@ class TestSystem(TestCase):
self.assertEqual("a b", self.system.getUniqueFilename("a b"))
def testScreensaverInhibit(self):
- #check that we start of uninhibited
+ # check that we start of uninhibited
self.assertTrue(not self.system.screensaverIsInhibited())
- #inhibit and check that we are
+ # inhibit and check that we are
self.system.inhibitScreensaver("a")
self.assertTrue(self.system.screensaverIsInhibited())
- #uninhibit and check that we are
+ # uninhibit and check that we are
self.system.uninhibitScreensaver("a")
self.assertTrue(not self.system.screensaverIsInhibited())
- #check that adding/removing is consistent with multiple keys
+ # check that adding/removing is consistent with multiple keys
for c in range(0, 5):
self.system.inhibitScreensaver(str(c))
self.assertTrue(self.system.screensaverIsInhibited(str(c)))
@@ -63,17 +64,17 @@ class TestSystem(TestCase):
self.assertTrue(not self.system.screensaverIsInhibited())
def testSleepInhibit(self):
- #check that we start of uninhibited
+ # check that we start of uninhibited
self.assertTrue(not self.system.sleepIsInhibited())
- #inhibit and check that we are
+ # inhibit and check that we are
self.system.inhibitSleep("a")
self.assertTrue(self.system.sleepIsInhibited())
- #uninhibit and check that we are
+ # uninhibit and check that we are
self.system.uninhibitSleep("a")
self.assertTrue(not self.system.sleepIsInhibited())
- #check that adding/removing is consistent with multiple keys
+ # check that adding/removing is consistent with multiple keys
for c in range(0, 5):
self.system.inhibitSleep(str(c))
self.assertTrue(self.system.sleepIsInhibited(str(c)))
diff --git a/tests/test_undo.py b/tests/test_undo.py
index 6199a5a..f52ab22 100644
--- a/tests/test_undo.py
+++ b/tests/test_undo.py
@@ -41,6 +41,7 @@ class DummyUndoableAction(UndoableAction):
class TestUndoableAction(TestCase):
+
def testSimpleSignals(self):
"""
Test signal emission from _done() and _undone().
@@ -62,6 +63,7 @@ class TestUndoableAction(TestCase):
class TestUndoableActionStack(TestCase):
+
def testDoUndoEmpty(self):
"""
Undo an empty stack.
@@ -93,6 +95,7 @@ class TestUndoableActionStack(TestCase):
state["done"] = 2
class Action(UndoableAction):
+
def do(self):
state["actions"] += 1
self._done()
@@ -129,6 +132,7 @@ class TestUndoableActionStack(TestCase):
state["actions"] = 2
class Action(UndoableAction):
+
def undo(self):
state["actions"] -= 1
if state["actions"] == 1:
@@ -152,6 +156,7 @@ class TestUndoableActionStack(TestCase):
class TestUndoableActionLog(TestCase):
+
def setUp(self):
self.log = UndoableActionLog()
self._connectToUndoableActionLog(self.log)
@@ -167,7 +172,7 @@ class TestUndoableActionLog(TestCase):
def _connectToUndoableActionLog(self, log):
for signalName in ("begin", "push", "rollback", "commit",
- "undo", "redo"):
+ "undo", "redo"):
log.connect(signalName, self._undoActionLogSignalCb, signalName)
def _disconnectFromUndoableActionLog(self, log):
@@ -394,6 +399,7 @@ class TestUndoableActionLog(TestCase):
call_sequence = []
class Action(UndoableAction):
+
def __init__(self, n):
UndoableAction.__init__(self)
self.n = n
diff --git a/tests/test_undo_timeline.py b/tests/test_undo_timeline.py
index 55e45be..0d6aac4 100644
--- a/tests/test_undo_timeline.py
+++ b/tests/test_undo_timeline.py
@@ -35,6 +35,7 @@ from pitivi.undo.undo import UndoableActionLog
class TimelineLogObserverSpy(TimelineLogObserver):
+
def _connectToTimeline(self, timeline):
TimelineLogObserver._connectToTimeline(self, timeline)
timeline.connected = True
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 877bfaf..d3ca94b 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -33,6 +33,7 @@ hour = minute * 60
class TestBeautifyLength(TestCase):
+
def testBeautifySeconds(self):
self.assertEqual(beautify_length(second), "1 second")
self.assertEqual(beautify_length(second * 2), "2 seconds")
@@ -47,14 +48,15 @@ class TestBeautifyLength(TestCase):
def testBeautifyMinutesAndSeconds(self):
self.assertEqual(beautify_length(minute + second),
- "1 minute, 1 second")
+ "1 minute, 1 second")
def testBeautifyHoursAndMinutes(self):
self.assertEqual(beautify_length(hour + minute + second),
- "1 hour, 1 minute")
+ "1 hour, 1 minute")
class TestDependencyChecks(TestCase):
+
def testDependencies(self):
gi_dep = GstDependency("Gst", "1.0.0")
gi_dep.check()
diff --git a/win32/setup.py b/win32/setup.py
index 223695e..229c082 100644
--- a/win32/setup.py
+++ b/win32/setup.py
@@ -41,7 +41,6 @@ class Deploy():
self.runPy2exeSetup()
self.close()
-
def close(self, message=None):
if message is not None:
print 'ERROR: %s' % message
@@ -53,12 +52,13 @@ class Deploy():
self.curr_dir = os.getcwd()
if not self.curr_dir.endswith('win32'):
self.close("The script must be run from 'pitivi/win32'")
- self.root_dir = os.path.abspath(os.path.join(self.curr_dir,'..'))
+ self.root_dir = os.path.abspath(os.path.join(self.curr_dir, '..'))
self.dist_dir = os.path.join(self.root_dir, 'win32', 'dist')
self.dist_bin_dir = os.path.join(self.dist_dir, 'bin')
self.dist_etc_dir = os.path.join(self.dist_dir, 'etc')
self.dist_share_dir = os.path.join(self.dist_dir, 'share')
- self.dist_share_pixmaps_dir = os.path.join(self.dist_share_dir, 'pitivi', 'pixmaps')
+ self.dist_share_pixmaps_dir = os.path.join(
+ self.dist_share_dir, 'pitivi', 'pixmaps')
self.dist_lib_dir = os.path.join(self.dist_dir, 'lib')
self.dist_lib_pitivi_dir = os.path.join(self.dist_lib_dir, 'pitivi')
@@ -69,12 +69,13 @@ class Deploy():
sys.path.insert(0, os.path.join(self.curr_dir, 'site-packages'))
# Add Gtk and GStreamer folder to the system path
for folder in [self.gstPath, self.gtkPath]:
- os.environ['PATH'] = os.environ['PATH']+';'+os.path.join(folder, 'bin')
+ os.environ['PATH'] = os.environ[
+ 'PATH'] + ';' + os.path.join(folder, 'bin')
# FIXME: libgoocanvas links to libxml2.dll while the GStreamer installer
# provides libxml2-2.dll
- shutil.copy(os.path.join(self.gstPath, 'bin', 'libxml2-2.dll'),
- os.path.join(self.dist_bin_dir, 'libxml2.dll'))
- os.environ['PATH'] = os.environ['PATH']+';'+self.dist_bin_dir
+ shutil.copy(os.path.join(self.gstPath, 'bin', 'libxml2-2.dll'),
+ os.path.join(self.dist_bin_dir, 'libxml2.dll'))
+ os.environ['PATH'] = os.environ['PATH'] + ';' + self.dist_bin_dir
def createDeploymentFolder(self):
# Create a Unix-like diretory tree to deploy Pitivi
@@ -82,12 +83,12 @@ class Deploy():
if os.path.exists(self.dist_dir):
try:
shutil.rmtree(self.dist_dir)
- except :
- self.close("ERROR: Can't delete folder %s"%self.dist_dir)
+ except:
+ self.close("ERROR: Can't delete folder %s" % self.dist_dir)
for path in [self.dist_dir, self.dist_bin_dir, self.dist_etc_dir,
- self.dist_share_dir, self.dist_lib_pitivi_dir,
- self.dist_share_pixmaps_dir]:
+ self.dist_share_dir, self.dist_lib_pitivi_dir,
+ self.dist_share_pixmaps_dir]:
os.makedirs(path)
def checkDependencies(self):
@@ -98,8 +99,8 @@ class Deploy():
import gst
except ImportError:
self.close('IMPORT_ERROR: Could not found the GStreamer Pythonbindings.\n'
- 'You can download the installers at:\n'
- 'http://www.gstreamer-winbuild.ylatuya.es')
+ 'You can download the installers at:\n'
+ 'http://www.gstreamer-winbuild.ylatuya.es')
else:
print ('GStreamer... OK')
@@ -111,9 +112,9 @@ class Deploy():
import gobject
except ImportError:
self.close('IMPORT_ERROR: Could not find the Gtk Python bindings.\n'
- 'You can download the installers at:\n'
- 'http://www.pygtk.org/\n'
- 'http://www.gtk.org/')
+ 'You can download the installers at:\n'
+ 'http://www.pygtk.org/\n'
+ 'http://www.gtk.org/')
else:
print ('Gtk... OK')
@@ -121,9 +122,9 @@ class Deploy():
import goocanvas
except ImportError:
self.close('IMPORT_ERROR: Could not find the Goocanvas Python bindings.\n'
- 'You can download the intallers at:\n'
- 'http://ftp.gnome.org/pub/GNOME/binaries/win32/goocanvas/\n'
- 'http://sqlkit.argolinux.org/download/goocanvas.pyd')
+ 'You can download the intallers at:\n'
+ 'http://ftp.gnome.org/pub/GNOME/binaries/win32/goocanvas/\n'
+ 'http://sqlkit.argolinux.org/download/goocanvas.pyd')
else:
print ('goocanvas... OK')
@@ -134,74 +135,70 @@ class Deploy():
else:
print ('zope.interface... OK')
-
def deployPitivi(self):
print('Deploying Pitivi')
# Copy files autogenerated using autotools
shutil.copy(os.path.join(self.curr_dir, 'configure.py'),
- os.path.join(self.root_dir, 'pitivi'))
+ os.path.join(self.root_dir, 'pitivi'))
# Copy ui files to lib/pitivi
ui_dir = os.path.join(self.root_dir, 'pitivi', 'ui')
shutil.copy(os.path.join(ui_dir, 'mainwindow.xml'),
- os.path.join(self.dist_lib_pitivi_dir, 'mainwindow.xml'))
+ os.path.join(self.dist_lib_pitivi_dir, 'mainwindow.xml'))
for name in [x for x in os.listdir(ui_dir) if x.endswith('glade')]:
shutil.copy(os.path.join(ui_dir, name),
- os.path.join(self.dist_lib_pitivi_dir, name))
+ os.path.join(self.dist_lib_pitivi_dir, name))
# Copy the pixmaps to the dist dir
pitivi_pixmaps_dir = os.path.join(self.root_dir, 'pitivi', 'pixmaps')
win32_pixmaps_dir = os.path.join(self.curr_dir, 'pixmaps')
for name in os.listdir(pitivi_pixmaps_dir):
- shutil.copy(os.path.join(pitivi_pixmaps_dir,name),
- self.dist_share_pixmaps_dir)
+ shutil.copy(os.path.join(pitivi_pixmaps_dir, name),
+ self.dist_share_pixmaps_dir)
# Override SVG pixmaps with PNG pixmaps using the .svg extension
# so they can be loaded if gdk doesn't support svg
for name in os.listdir(win32_pixmaps_dir):
out_name = name.replace('.png', '.svg')
shutil.copy(os.path.join(win32_pixmaps_dir, name),
- os.path.join(self.dist_share_pixmaps_dir, out_name))
+ os.path.join(self.dist_share_pixmaps_dir, out_name))
def deployGStreamer(self):
print ('Deploying GStreamer')
# Copy gstreamer binaries to the dist folder
for name in os.listdir(os.path.join(self.gstPath, 'bin')):
shutil.copy(os.path.join(self.gstPath, 'bin', name),
- self.dist_bin_dir)
+ self.dist_bin_dir)
shutil.copytree(os.path.join(self.gstPath, 'lib', 'gstreamer-0.10'),
- os.path.join(self.dist_lib_dir, 'gstreamer-0.10'))
+ os.path.join(self.dist_lib_dir, 'gstreamer-0.10'))
def deployGTK(self):
print ('Deploying Gtk dependencies')
# Copy Gtk files to the dist folder
for name in ['fonts', 'pango', 'gtk-2.0']:
shutil.copytree(os.path.join(self.gtkPath, 'etc', name),
- os.path.join(self.dist_etc_dir, name))
+ os.path.join(self.dist_etc_dir, name))
shutil.copytree(os.path.join(self.gtkPath, 'lib', 'gtk-2.0'),
- os.path.join(self.dist_lib_dir, name))
+ os.path.join(self.dist_lib_dir, name))
def runPy2exeSetup(self):
sys.argv.insert(1, 'py2exe')
setup(
- name = 'Pitivi',
- description = 'Video Editor',
- version = '0.13.4',
-
- windows = [
- {
- 'script': 'pitivi',
- 'icon_resources': [(1, "pitivi.ico")],
- }
- ],
-
- options = {
- 'py2exe': {
- 'packages':'pitivi',
- 'includes': 'gtk, cairo, pango, atk, pangocairo,\
- zope.interface, gobject, gst, email',
- 'dist_dir' : self.dist_bin_dir
- }
- },
-
- zipfile = None,
+ name='Pitivi',
+ description='Video Editor',
+ version='0.13.4',
+
+ windows=[{'script': 'pitivi',
+ 'icon_resources': [(1, "pitivi.ico")],
+ }
+ ],
+
+ options={
+ 'py2exe': {
+ 'packages': 'pitivi',
+ 'dist_dir': self.dist_bin_dir,
+ 'includes': 'gtk, cairo, pango, atk, pangocairo, zope.interface, gobject, gst, email'
+ }
+ },
+
+ zipfile=None,
)
@@ -209,11 +206,11 @@ def main():
usage = "usage: %prog [options]"
parser = OptionParser(usage)
parser.add_option("-g", "--gst-path", action="store",
- dest="gstPath",default="c:\\gstreamer", type="string",
- help="GStreamer installation path")
+ dest="gstPath", default="c:\\gstreamer", type="string",
+ help="GStreamer installation path")
parser.add_option("-k", "--gtk-path", action="store",
- dest="gtkPath",default="c:\\gtk", type="string",
- help="GTK+ installation path")
+ dest="gtkPath", default="c:\\gtk", type="string",
+ help="GTK+ installation path")
(options, args) = parser.parse_args()
Deploy(options.gstPath, options.gtkPath)
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]