effects.py 27.7 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
# Pitivi video editor
3
# Copyright (c) 2010, Thibault Saunier <tsaunier@gnome.org>
4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2005, Edward Hervey <bilboed@bilboed.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the
Hicham HAOUARI's avatar
Hicham HAOUARI committed
18 19
# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301, USA.
20
"""Effects categorization and management.
21 22 23 24 25 26 27 28 29

 There are different types of effects available:
  _ Simple Audio/Video Effects
     GStreamer elements that only apply to audio OR video
     Only take the elements who have a straightforward meaning/action
  _ Expanded Audio/Video Effects
     These are the Gstreamer elements that don't have a easy meaning/action or
     that are too cumbersome to use as such
  _ Complex Audio/Video Effects
Edward Hervey's avatar
Edward Hervey committed
30
"""
31
import os
32
import re
33
from gettext import gettext as _
34

35 36
from gi.repository import Gdk
from gi.repository import GdkPixbuf
37
from gi.repository import GES
38
from gi.repository import GLib
39
from gi.repository import GObject
40 41 42
from gi.repository import Gst
from gi.repository import Gtk
from gi.repository import Pango
Thibault Saunier's avatar
Thibault Saunier committed
43

44 45
from pitivi.configure import get_pixmap_dir
from pitivi.configure import get_ui_dir
46 47
from pitivi.settings import GlobalSettings
from pitivi.utils.loggable import Loggable
48 49 50 51
from pitivi.utils.ui import EFFECT_TARGET_ENTRY
from pitivi.utils.ui import SPACING
from pitivi.utils.widgets import FractionWidget
from pitivi.utils.widgets import GstElementSettingsWidget
52

53
(VIDEO_EFFECT, AUDIO_EFFECT) = list(range(1, 3))
54

55
AUDIO_EFFECTS_CATEGORIES = ()
56

57 58
ALLOWED_ONLY_ONCE_EFFECTS = ['videoflip']

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
VIDEO_EFFECTS_CATEGORIES = (
    (_("Colors"), (
        # Mostly "serious" stuff that relates to correction/adjustments
        # Fancier stuff goes into the "fancy" category
        "cogcolorspace", "videobalance", "chromahold", "gamma",
        "coloreffects", "exclusion", "burn", "dodge", "videomedian",
        "frei0r-filter-color-distance", "frei0r-filter-threshold0r",
        "frei0r-filter-contrast0r", "frei0r-filter-saturat0r",
        "frei0r-filter-white-balance", "frei0r-filter-brightness",
        "frei0r-filter-gamma", "frei0r-filter-invert0r",
        "frei0r-filter-hueshift0r", "frei0r-filter-equaliz0r",
        "frei0r-filter-bw0r", "frei0r-filter-glow",
        "frei0r-filter-twolay0r", "frei0r-filter-3-point-color-balance",
        "frei0r-filter-coloradj-rgb", "frei0r-filter-curves",
        "frei0r-filter-levels", "frei0r-filter-primaries",
        "frei0r-filter-sop-sat", "frei0r-filter-threelay0r",
        "frei0r-filter-tint0r",
    )),
    (_("Compositing"), (
        "alpha", "alphacolor", "gdkpixbufoverlay",
        "frei0r-filter-transparency", "frei0r-filter-mask0mate",
        "frei0r-filter-alpha0ps", "frei0r-filter-alphagrad",
        "frei0r-filter-alphaspot", "frei0r-filter-bluescreen0r",
        "frei0r-filter-select0r",
    )),
    (_("Noise & blur"), (
        "gaussianblur", "diffuse", "dilate", "marble", "smooth",
        "frei0r-filter-hqdn3d", "frei0r-filter-squareblur",
        "frei0r-filter-sharpness", "frei0r-filter-edgeglow",
        "frei0r-filter-facebl0r",
    )),
    (_("Analysis"), (
        "videoanalyse", "videodetect", "videomark", "revtv",
        "navigationtest", "frei0r-filter-rgb-parade",
        "frei0r-filter-r", "frei0r-filter-g", "frei0r-filter-b",
        "frei0r-filter-vectorscope", "frei0r-filter-luminance",
        "frei0r-filter-opencvfacedetect", "frei0r-filter-pr0be",
        "frei0r-filter-pr0file",
    )),
    (_("Geometry"), (
        "cogscale", "aspectratiocrop", "cogdownsample", "videoscale",
        "videocrop", "videoflip", "videobox", "gdkpixbufscale",
        "kaleidoscope", "mirror", "pinch", "sphere", "square", "fisheye",
        "stretch", "twirl", "waterriple", "rotate", "bulge", "circle",
        "frei0r-filter-letterb0xed", "frei0r-filter-k-means-clustering",
        "frei0r-filter-lens-correction", "frei0r-filter-defish0r",
        "frei0r-filter-perspective", "frei0r-filter-c0rners",
        "frei0r-filter-scale0tilt", "frei0r-filter-pixeliz0r",
        "frei0r-filter-flippo", "frei0r-filter-3dflippo",
    )),
    (_("Fancy"), (
        "rippletv", "streaktv", "radioactv", "optv", "solarize",
        "quarktv", "vertigotv", "shagadelictv", "warptv", "dicetv",
        "agingtv", "edgetv", "bulge", "circle", "fisheye", "tunnel",
        "kaleidoscope", "mirror", "pinch", "sphere", "square",
        "stretch", "twirl", "waterripple", "glfiltersobel", "chromium",
        "frei0r-filter-sobel", "frei0r-filter-cartoon",
        "frei0r-filter-water", "frei0r-filter-nosync0r",
        "frei0r-filter-k-means-clustering", "frei0r-filter-delay0r",
        "frei0r-filter-distort0r", "frei0r-filter-light-graffiti",
        "frei0r-filter-tehroxx0r", "frei0r-filter-vertigo",
    )),
    (_("Time"), (
        "videorate", "frei0r-filter-delay0r", "frei0r-filter-baltan",
        "frei0r-filter-nervous",
    )),
)

127
BLACKLISTED_EFFECTS = ["colorconvert", "coglogoinsert", "festival",
128
                       "alphacolor", "cogcolorspace", "videodetect",
129
                       "navigationtest", "videoanalyse", "volume"]
130

131
BLACKLISTED_PLUGINS = []
132

133 134 135 136 137 138 139 140 141 142 143 144 145
HIDDEN_EFFECTS = [
    # Overlaying an image onto a video stream can already be done.
    "gdkpixbufoverlay"]

GlobalSettings.addConfigSection('effect-library')

(COL_NAME_TEXT,
 COL_DESC_TEXT,
 COL_EFFECT_TYPE,
 COL_EFFECT_CATEGORIES,
 COL_ELEMENT_NAME,
 COL_ICON) = list(range(6))

146
ICON_WIDTH = 48 + 2 * 6  # 48 pixels, plus a margin on each side
147

148

149
class EffectInfo(object):
150 151 152 153 154
    """Info for displaying and using an effect.

    Attributes:
        effect_name (str): The bin_description identifying the effect.
    """
155

156
    def __init__(self, effect_name, media_type, categories,
Thibault Saunier's avatar
Thibault Saunier committed
157
                 human_name, description):
158
        object.__init__(self)
159
        self.effect_name = effect_name
160
        self.media_type = media_type
161 162 163 164
        self.categories = categories
        self.description = description
        self.human_name = human_name

165 166 167 168 169 170 171 172 173 174 175 176 177 178
    @property
    def icon(self):
        pixdir = os.path.join(get_pixmap_dir(), "effects")
        try:
            # We can afford to scale the images here, the impact is negligible
            icon = GdkPixbuf.Pixbuf.new_from_file_at_size(
                os.path.join(pixdir, self.effect_name + ".png"),
                ICON_WIDTH, ICON_WIDTH)
        # An empty except clause is bad, but "gi._glib.GError" is not helpful.
        except:
            icon = GdkPixbuf.Pixbuf.new_from_file(
                os.path.join(pixdir, "defaultthumbnail.svg"))
        return icon

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    @property
    def bin_description(self):
        """Gets the bin description which defines this effect."""
        if self.effect_name.startswith("gl"):
            return "glupload ! %s ! gldownload" % self.effect_name
        else:
            return self.effect_name

    @staticmethod
    def name_from_bin_description(bin_description):
        """Gets the name of the effect defined by the `bin_description`."""
        if bin_description.startswith("glupload"):
            return bin_description.split("!")[1].strip()
        else:
            return bin_description

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    def good_for_track_element(self, track_element):
        """Checks the effect is compatible with the specified track element.

        Args:
            track_element (GES.TrackElement): The track element to check against.

        Returns:
            bool: Whether it makes sense to apply the effect to the track element.
        """
        track_type = track_element.get_track_type()
        if track_type == GES.TrackType.AUDIO:
            return self.media_type == AUDIO_EFFECT
        elif track_type == GES.TrackType.VIDEO:
            return self.media_type == VIDEO_EFFECT
        else:
            return False

212

213
class EffectsManager(Loggable):
214
    """Keeps info about effects and their categories.
215

216 217 218
    Attributes:
        video_effects (List[Gst.ElementFactory]): The available video effects.
        audio_effects (List[Gst.ElementFactory]): The available audio effects.
219
    """
220

Edward Hervey's avatar
Edward Hervey committed
221
    def __init__(self):
222
        Loggable.__init__(self)
223 224
        self.video_effects = []
        self.audio_effects = []
225
        self.gl_effects = []
226 227
        self._effects = {}

228 229 230
        useless_words = ["Video", "Audio", "audio", "effect",
                         _("Video"), _("Audio"), _("Audio").lower(), _("effect")]
        uselessRe = re.compile(" |".join(useless_words))
231

232 233
        registry = Gst.Registry.get()
        factories = registry.get_feature_list(Gst.ElementFactory)
234 235 236 237 238 239 240 241
        longnames = set()
        duplicate_longnames = set()
        for factory in factories:
            longname = factory.get_longname()
            if longname in longnames:
                duplicate_longnames.add(longname)
            else:
                longnames.add(longname)
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
        for factory in factories:
            klass = factory.get_klass()
            name = factory.get_name()
            if ("Effect" not in klass or
                    any(black in name for black in BLACKLISTED_PLUGINS)):
                continue

            media_type = None
            if "Audio" in klass:
                self.audio_effects.append(factory)
                media_type = AUDIO_EFFECT
            elif "Video" in klass:
                self.video_effects.append(factory)
                media_type = VIDEO_EFFECT
            if not media_type:
                HIDDEN_EFFECTS.append(name)
                continue

260 261 262 263 264 265
            longname = factory.get_longname()
            if longname in duplicate_longnames:
                # Workaround https://bugzilla.gnome.org/show_bug.cgi?id=760566
                # Add name which identifies the element and is unique.
                longname = "%s %s" % (longname, name)
            human_name = uselessRe.sub("", longname).title()
266 267 268 269 270 271
            effect = EffectInfo(name,
                                media_type,
                                categories=self._getEffectCategories(name),
                                human_name=human_name,
                                description=factory.get_description())
            self._effects[name] = effect
272

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
        gl_element_factories = registry.get_feature_list_by_plugin("opengl")
        self.gl_effects = [element_factory.get_name()
                           for element_factory in gl_element_factories]
        if self.gl_effects:
            # Checking whether the GL effects can be used
            # by setting a pipeline with "gleffects" to PAUSED.
            pipeline = Gst.parse_launch("videotestsrc ! glupload ! gleffects ! fakesink")
            bus = pipeline.get_bus()
            bus.add_signal_watch()
            bus.connect("message", self._gl_pipeline_message_cb, pipeline)
            assert pipeline.set_state(Gst.State.PAUSED) == Gst.StateChangeReturn.ASYNC

    def _gl_pipeline_message_cb(self, bus, message, pipeline):
        """Handles a `message` event on the pipeline for checking gl effects."""
        done = False
        if message.type == Gst.MessageType.ASYNC_DONE:
            self.debug("GL effects check pipeline successfully PAUSED")
            done = True
        elif message.type == Gst.MessageType.ERROR:
            # The pipeline cannot be set to PAUSED.
            error, detail = message.parse_error()
            self.debug("Hiding the GL effects because: %s, %s", error, detail)
            HIDDEN_EFFECTS.extend(self.gl_effects)
            done = True

        if done:
            bus.remove_signal_watch()
            bus.disconnect_by_func(self._gl_pipeline_message_cb)
            pipeline.set_state(Gst.State.NULL)

303
    def getInfo(self, bin_description):
304
        """Gets the info for an effect which can be applied.
305

306
        Args:
307
            bin_description (str): The bin_description defining the effect.
308

309 310
        Returns:
            EffectInfo: The info corresponding to the name, or None.
311
        """
312
        name = EffectInfo.name_from_bin_description(bin_description)
313
        return self._effects.get(name)
314 315

    def _getEffectCategories(self, effect_name):
316 317 318 319 320 321 322
        """Gets the categories to which the specified effect belongs.

        Args:
            effect_name (str): The bin_description identifying the effect.

        Returns:
            List[str]: The categories which contain the effect.
323
        """
324
        categories = []
325 326 327 328 329 330
        for category_name, effects in AUDIO_EFFECTS_CATEGORIES:
            if effect_name in effects:
                categories.append(category_name)
        for category_name, effects in VIDEO_EFFECTS_CATEGORIES:
            if effect_name in effects:
                categories.append(category_name)
331
        if not categories:
332
            categories.append(_("Uncategorized"))
333
        categories.insert(0, _("All effects"))
334 335
        return categories

336 337
    @property
    def video_categories(self):
338
        """Gets all video effect categories names."""
339
        return EffectsManager._getCategoriesNames(VIDEO_EFFECTS_CATEGORIES)
340

341 342
    @property
    def audio_categories(self):
343
        """Gets all audio effect categories names."""
344 345 346 347 348
        return EffectsManager._getCategoriesNames(AUDIO_EFFECTS_CATEGORIES)

    @staticmethod
    def _getCategoriesNames(categories):
        ret = [category_name for category_name, unused_effects in categories]
349
        ret.sort()
350
        ret.insert(0, _("All effects"))
351 352
        if categories:
            # Add Uncategorized only if there are other categories defined.
353
            ret.append(_("Uncategorized"))
354
        return ret
355

356

357
# ----------------------- UI classes to manage effects -------------------------#
358

359

360
class EffectListWidget(Gtk.Box, Loggable):
361
    """Widget for listing effects."""
362

363
    def __init__(self, instance):
364
        Gtk.Box.__init__(self)
365 366 367 368
        Loggable.__init__(self)

        self.app = instance

369
        self._draggedItems = None
370 371
        self._effectType = VIDEO_EFFECT

372
        self.set_orientation(Gtk.Orientation.VERTICAL)
373 374 375 376
        builder = Gtk.Builder()
        builder.add_from_file(os.path.join(get_ui_dir(), "effectslibrary.ui"))
        builder.connect_signals(self)
        toolbar = builder.get_object("effectslibrary_toolbar")
377
        toolbar.get_style_context().add_class(Gtk.STYLE_CLASS_INLINE_TOOLBAR)
378 379 380 381
        self.video_togglebutton = builder.get_object("video_togglebutton")
        self.audio_togglebutton = builder.get_object("audio_togglebutton")
        self.categoriesWidget = builder.get_object("categories")
        self.searchEntry = builder.get_object("search_entry")
382 383

        # Store
384
        self.storemodel = Gtk.ListStore(
385
            str, str, int, object, str, GdkPixbuf.Pixbuf)
386 387
        self.storemodel.set_sort_column_id(
            COL_NAME_TEXT, Gtk.SortType.ASCENDING)
388

389 390 391 392 393
        # Create the filter for searching the storemodel.
        self.model_filter = self.storemodel.filter_new()
        self.model_filter.set_visible_func(self._setRowVisible, data=None)

        self.view = Gtk.TreeView(model=self.model_filter)
394
        self.view.props.headers_visible = False
395 396
        self.view.get_selection().set_mode(Gtk.SelectionMode.SINGLE)

397
        icon_col = Gtk.TreeViewColumn()
Alexandru Băluț's avatar
Alexandru Băluț committed
398
        icon_col.set_spacing(SPACING)
399
        icon_col.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
400
        icon_col.props.fixed_width = ICON_WIDTH
401
        icon_cell = Gtk.CellRendererPixbuf()
402
        icon_cell.props.xpad = 6
403
        icon_col.pack_start(icon_cell, True)
404 405
        icon_col.add_attribute(icon_cell, "pixbuf", COL_ICON)

406
        text_col = Gtk.TreeViewColumn()
407 408
        text_col.set_expand(True)
        text_col.set_spacing(SPACING)
409 410
        text_col.set_sizing(Gtk.TreeViewColumnSizing.AUTOSIZE)
        text_cell = Gtk.CellRendererText()
411 412
        text_cell.props.yalign = 0.0
        text_cell.props.xpad = 6
413 414
        text_cell.set_property("ellipsize", Pango.EllipsizeMode.END)
        text_col.pack_start(text_cell, True)
415
        text_col.set_cell_data_func(
416
            text_cell, self.viewDescriptionCellDataFunc, None)
417

418 419
        self.view.append_column(icon_col)
        self.view.append_column(text_col)
420

421 422 423
        self.view.connect("query-tooltip", self._treeViewQueryTooltipCb)
        self.view.props.has_tooltip = True

424
        # Make the treeview a drag source which provides effects.
425 426
        self.view.enable_model_drag_source(
            Gdk.ModifierType.BUTTON1_MASK, [EFFECT_TARGET_ENTRY], Gdk.DragAction.COPY)
427

428 429
        self.view.connect("button-press-event", self._buttonPressEventCb)
        self.view.connect("select-cursor-row", self._enterPressEventCb)
430
        self.view.connect("drag-data-get", self._dndDragDataGetCb)
431

432 433 434 435 436
        scrollwin = Gtk.ScrolledWindow()
        scrollwin.props.hscrollbar_policy = Gtk.PolicyType.NEVER
        scrollwin.props.vscrollbar_policy = Gtk.PolicyType.AUTOMATIC
        scrollwin.add(self.view)

437
        self.pack_start(toolbar, False, False, 0)
438 439
        self.pack_start(scrollwin, True, True, 0)

440 441
        # Delay the loading of the available effects so the application
        # starts faster.
442
        GLib.idle_add(self._loadAvailableEffectsCb)
443
        self.populate_categories_widget()
444

445 446 447
        # Individually show the tab's widgets.
        # If you use self.show_all(), the tab will steal focus on startup.
        scrollwin.show_all()
448
        toolbar.show_all()
449

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    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)
        if not is_row:
            return False

        view.set_tooltip_row(tooltip, path)
        tooltip.set_markup(self.formatDescription(model, tree_iter))
        return True

    def viewDescriptionCellDataFunc(self, unused_column, cell, model, iter_, unused_data):
        cell.props.markup = self.formatDescription(model, iter_)

    def formatDescription(self, model, iter_):
        name, element_name, desc = model.get(iter_, COL_NAME_TEXT, COL_ELEMENT_NAME, COL_DESC_TEXT)
465
        escape = GLib.markup_escape_text
466
        return "<b>%s</b>\n%s" % (escape(name), escape(desc))
467 468

    def _loadAvailableEffectsCb(self):
469 470
        self._addFactories(self.app.effects.video_effects, VIDEO_EFFECT)
        self._addFactories(self.app.effects.audio_effects, AUDIO_EFFECT)
471 472 473 474 475
        return False

    def _addFactories(self, elements, effectType):
        for element in elements:
            name = element.get_name()
476 477 478 479 480 481 482 483 484
            if name in HIDDEN_EFFECTS:
                continue
            effect_info = self.app.effects.getInfo(name)
            self.storemodel.append([effect_info.human_name,
                                    effect_info.description,
                                    effectType,
                                    effect_info.categories,
                                    name,
                                    effect_info.icon])
485

486 487
    def populate_categories_widget(self):
        self.categoriesWidget.get_model().clear()
488
        icon_column = self.view.get_column(0)
489

490 491 492
        if self._effectType is VIDEO_EFFECT:
            for category in self.app.effects.video_categories:
                self.categoriesWidget.append_text(category)
493
            icon_column.props.visible = True
494
        else:
495 496
            for category in self.app.effects.audio_categories:
                self.categoriesWidget.append_text(category)
497
            icon_column.props.visible = False
498

499
        self.categoriesWidget.set_active(0)
500

501
    def _dndDragDataGetCb(self, unused_view, drag_context, selection_data, unused_info, unused_timestamp):
502 503
        data = bytes(self.getSelectedEffect(), "UTF-8")
        selection_data.set(drag_context.list_targets()[0], 0, data)
504

505 506 507 508
    def _rowUnderMouseSelected(self, view, event):
        result = view.get_path_at_pos(int(event.x), int(event.y))
        if result:
            path = result[0]
509 510 511
            selection = view.get_selection()
            return selection.path_is_selected(path) and\
                selection.count_selected_rows() > 0
512 513
        return False

514
    def _enterPressEventCb(self, unused_view, unused_event=None):
515
        self._addSelectedEffect()
516 517 518 519 520 521

    def _buttonPressEventCb(self, view, event):
        chain_up = True

        if event.button == 3:
            chain_up = False
522
        elif event.type == getattr(Gdk.EventType, '2BUTTON_PRESS'):
523
            self._addSelectedEffect()
524 525 526
        else:
            chain_up = not self._rowUnderMouseSelected(view, event)

527
        if chain_up:
528
            self._draggedItems = None
529
        else:
530
            self._draggedItems = self.getSelectedEffect()
531

532
        Gtk.TreeView.do_button_press_event(view, event)
533 534
        return True

535
    def _addSelectedEffect(self):
536
        """Adds the selected effect to the single selected clip, if any."""
537
        effect = self.getSelectedEffect()
538 539 540
        effect_info = self.app.effects.getInfo(effect)
        if not effect_info:
            return
541
        timeline = self.app.gui.editor.timeline_ui.timeline
542 543
        clip = timeline.selection.getSingleClip()
        if not clip:
544
            return
545 546 547
        pipeline = timeline.ges_timeline.get_parent()
        from pitivi.undo.timeline import CommitTimelineFinalizingAction
        with self.app.action_log.started("add effect",
548 549
                                         finalizing_action=CommitTimelineFinalizingAction(pipeline),
                                         toplevel=True):
550
            clip.ui.add_effect(effect_info)
551 552

    def getSelectedEffect(self):
553 554
        if self._draggedItems:
            return self._draggedItems
555
        model, rows = self.view.get_selection().get_selected_rows()
556
        path = self.model_filter.convert_path_to_child_path(rows[0])
557 558
        return self.storemodel[path][COL_ELEMENT_NAME]

559
    def _toggleViewTypeCb(self, widget):
560 561
        """Switches the view mode between video and audio.

562 563 564 565 566 567 568 569 570 571 572 573 574
        This makes the two togglebuttons behave like a group of radiobuttons.
        """
        if widget is self.video_togglebutton:
            self.audio_togglebutton.set_active(not widget.get_active())
        else:
            assert widget is self.audio_togglebutton
            self.video_togglebutton.set_active(not widget.get_active())

        if self.video_togglebutton.get_active():
            self._effectType = VIDEO_EFFECT
        else:
            self._effectType = AUDIO_EFFECT
        self.populate_categories_widget()
575
        self.model_filter.refilter()
576

577
    def _categoryChangedCb(self, unused_combobox):
578
        self.model_filter.refilter()
579

580
    def _searchEntryChangedCb(self, unused_entry):
581
        self.model_filter.refilter()
582

583
    def _searchEntryIconClickedCb(self, entry, unused, unused1):
584 585
        entry.set_text("")

586
    def _setRowVisible(self, model, iter, unused_data):
587 588 589 590 591
        if not self._effectType == model.get_value(iter, COL_EFFECT_TYPE):
            return False
        if model.get_value(iter, COL_EFFECT_CATEGORIES) is None:
            return False
        if self.categoriesWidget.get_active_text() not in model.get_value(iter, COL_EFFECT_CATEGORIES):
592
            return False
593 594 595
        text = self.searchEntry.get_text().lower()
        return text in model.get_value(iter, COL_DESC_TEXT).lower() or\
            text in model.get_value(iter, COL_NAME_TEXT).lower()
596 597


598
PROPS_TO_IGNORE = ['name', 'qos', 'silent', 'message', 'parent']
599 600


601
class EffectsPropertiesManager(GObject.Object, Loggable):
602
    """Provides and caches UIs for editing effects.
603

604 605
    Attributes:
        app (Pitivi): The app.
606
    """
607

608 609 610 611 612 613 614 615 616 617
    def create_widget_accumulator(*args):
        """Aborts `create_widget` emission if we got a widget."""
        handler_return = args[2]
        if handler_return is None:
            return True, handler_return
        return False, handler_return

    __gsignals__ = {
        "create_widget": (GObject.SIGNAL_RUN_LAST, Gtk.Widget, (GstElementSettingsWidget, GES.Effect,),
                          create_widget_accumulator),
618 619 620
        "create_property_widget": (
            GObject.SIGNAL_RUN_LAST, object, (GstElementSettingsWidget, GES.Effect, object, object,),
            create_widget_accumulator),
621 622 623 624 625 626
    }

    def do_create_widget(self, effect_widget, effect):
        """Creates a widget if the `create_widget` handlers did not."""
        effect_name = effect.get_property("bin-description")
        self.log('UI is being auto-generated for "%s"', effect_name)
627
        effect_widget.add_widgets(create_property_widget=self.create_property_widget, with_reset_button=True)
628 629 630
        self._postConfiguration(effect, effect_widget)
        return None

631 632 633 634 635
    def do_create_property_widget(self, effect_widget, effect, prop, prop_value):
        """Creates a widget if the `create_property_widget` handlers did not."""
        widget = effect_widget.make_property_widget(prop, prop_value)
        return widget

636
    def __init__(self, app):
637 638
        GObject.Object.__init__(self)
        Loggable.__init__(self)
639
        self.cache_dict = {}
640
        self.app = app
641 642

    def getEffectConfigurationUI(self, effect):
643 644 645 646
        """Gets a configuration UI element for the effect.

        Args:
            effect (Gst.Element): The effect for which we want the UI.
647

648 649
        Returns:
            GstElementSettingsWidget: A container for configuring the effect.
650
        """
651
        if effect not in self.cache_dict:
652
            effect_widget = GstElementSettingsWidget()
653 654 655 656 657 658
            effect_widget.setElement(effect, PROPS_TO_IGNORE)
            widget = self.emit("create_widget", effect_widget, effect)
            # The default handler of `create_widget` handles visibility
            # itself and returns None
            if widget is not None:
                effect_widget.show_widget(widget)
659
            self.cache_dict[effect] = effect_widget
660
            self._connectAllWidgetCallbacks(effect_widget, effect)
661

662 663 664 665
        return self.cache_dict[effect]

    def cleanCache(self, effect):
        if effect in self.cache_dict:
666
            return self.cache_dict.pop(effect)
667 668

    def _postConfiguration(self, effect, effect_set_ui):
669
        effect_name = effect.get_property("bin-description")
670 671 672 673
        if 'aspectratiocrop' in effect.get_property("bin-description"):
            for widget in effect_set_ui.get_children()[0].get_children():
                if isinstance(widget, FractionWidget):
                    widget.addPresets(["4:3", "5:4", "9:3", "16:9", "16:10"])
674 675 676 677
        else:
            self.log('No additional set-up required for "%s"', effect_name)
            return
        self.debug('Additional properties successfully set for "%s"', effect_name)
678

679
    def _connectAllWidgetCallbacks(self, effect_settings_widget, effect):
680
        for prop, widget in effect_settings_widget.properties.items():
681
            widget.connectValueChanged(self._onValueChangedCb, widget, prop, effect)
682

683 684
    def _onSetDefaultCb(self, unused_widget, effect_widget):
        effect_widget.setWidgetToDefault()
685

686 687
    def _onValueChangedCb(self, unused_widget, effect_widget, prop, effect):
        value = effect_widget.getWidgetValue()
688

689
        # FIXME Workaround in order to make aspectratiocrop working
690 691
        if isinstance(value, Gst.Fraction):
            value = Gst.Fraction(int(value.num), int(value.denom))
692

693 694 695 696 697 698
        from pitivi.undo.timeline import CommitTimelineFinalizingAction
        pipeline = self.app.project_manager.current_project.pipeline
        with self.app.action_log.started("Effect property change",
                                         finalizing_action=CommitTimelineFinalizingAction(pipeline),
                                         toplevel=True):
            effect.set_child_property(prop.name, value)
699 700 701 702 703

    def create_property_widget(self, element_settings_widget, prop, prop_value):
        prop_widget = self.emit("create_property_widget", element_settings_widget, element_settings_widget.element,
                                prop, prop_value)
        return prop_widget