#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 A S Lewis
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# 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 General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.


"""Main window classes."""


# Import Gtk modules
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject, Gdk, GdkPixbuf


# Import other modules
import cgi
import datetime
from gi.repository import Gio
import os
from gi.repository import Pango
import re
import sys
import threading
import time


# Import our modules
import config
import formats
import __main__
import mainapp
import media
import options
import utils


# !!! Debugging flag
DEBUG_FUNC_FLAG = False


# Classes
class MainWin(Gtk.ApplicationWindow):

    """Python class that handles the main window.

    The main window has three tabs - the Videos Tab, the Progress Tab and the
    Errors tab.

    In the Videos Tab, the Video Index is visible on the left, and the Video
    Catalogue is visible on the right.

    In the Progress Tab, the Progress List is visible at the top, and the
    Results List is visible at the bottom.

    In the Errors Tab, any errors generated by youtube-dl are displayed. (The
    display is not reset at the beginning of every download operation).

    Args:

        app_obj (mainapp.TartubeApp): The main application object

    """


    # Standard class methods


    def __init__(self, app_obj):

        if DEBUG_FUNC_FLAG:
            print('mw 85 __init__')

        super(MainWin, self).__init__(
            title=__main__.__packagename__.title() + ' v' \
            + __main__.__version__,
            application=app_obj
        )

        # IV list - class objects
        # -----------------------
        # The main application
        self.app_obj = app_obj


        # IV list - Gtk widgets
        # ---------------------
        # (from self.setup_grid)
        self.grid = None                        # Gtk.Grid
        # (from self.setup_menubar)
        self.menubar = None                     # Gtk.MenuBar
        # (from self.setup_toolbar)
        self.main_toolbar = None                # Gtk.Toolbar
        # (from self.setup_notebook)
        self.notebook = None                    # Gtk.Notebook
        self.videos_tab = None                  # Gtk.Box
        self.videos_label = None                # Gtk.Label
        self.progress_tab = None                # Gkt.Box
        self.progress_label = None              # Gtk.Label
        self.output_tab = None                  # Gkt.Box
        self.output_label = None                # Gtk.Label
        self.errors_tab = None                  # Gkt.Box
        self.errors_label = None                # Gkt.Label
        # (from self.setup_videos_tab)
        self.videos_paned = None                # Gtk.HPaned
        self.video_index_scrolled = None        # Gtk.ScrolledWindow
        self.video_index_frame = None           # Gtk.Frame
        self.video_index_treeview = None        # Gtk.TreeView
        self.video_index_treestore = None       # Gtk.TreeStore
        self.video_index_sortmodel = None       # Gtk.TreeModelSort
        self.button_box = None                  # Gtk.VBox
        self.check_media_button = None          # Gtk.Button
        self.download_media_button = None       # Gtk.Button
        self.catalogue_scrolled = None          # Gtk.ScrolledWindow
        self.catalogue_frame = None             # Gtk.Frame
        self.catalogue_listbox = None           # Gtk.ListBox
        self.catalogue_toolbar = None           # Gtk.Toolbar
        self.catalogue_page_entry = None        # Gtk.Entry
        self.catalogue_last_entry = None        # Gtk.Entry
        self.catalogue_first_button = None      # Gtk.ToolButton
        self.catalogue_back_button = None       # Gtk.ToolButton
        self.catalogue_forwards_button = None   # Gtk.ToolButton
        self.catalogue_last_button = None       # Gtk.ToolButton
        self.catalogue_find_button = None       # Gtk.ToolButton
        self.catalogue_size_entry = None        # Gtk.Entry
        self.catalogue_scroll_up_button = None  # Gtk.ToolButton
        self.catalogue_scroll_down_button = None
                                                # Gtk.ToolButton
        # (from self.setup_progress_tab)
        self.progress_paned = None              # Gtk.VPaned
        self.progress_list_scrolled = None      # Gtk.ScrolledWindow
        self.progress_list_frame = None         # Gtk.Frame
        self.progress_list_treeview = None      # Gtk.TreeView
        self.progress_list_liststore = None     # Gtk.ListStore
        self.results_list_scrolled = None       # Gtk.Frame
        self.results_list_frame = None          # Gtk.Frame
        self.results_list_treeview = None       # Gtk.TreeView
        self.results_list_liststore = None      # Gtk.ListStore
        self.num_worker_checkbutton = None      # Gtk.CheckButton
        self.num_worker_spinbutton = None       # Gtk.SpinButton
        self.bandwidth_checkbutton = None       # Gtk.CheckButton
        self.bandwidth_spinbutton = None        # Gtk.SpinButton
        self.video_res_checkbutton = None       # Gtk.CheckButton
        self.video_res_combobox = None          # Gtk.ComboBox
        self.progress_box = None                # Gtk.HBox
        self.progress_bar = None                # Gtk.ProgressBar
        self.progress_label = None              # Gtk.Label
        # (from self.setup_output_tab)
        self.output_notebook = None             # Gtk.Notebook
        # (from self.setup_errors_tab)
        self.errors_list_scrolled = None        # Gtk.ScrolledWindow
        self.errors_list_framed = None          # Gtk.Frame
        self.errors_list_treeview = None        # Gtk.TreeView
        self.errors_list_liststore = None       # Gtk.ListStore
        self.error_list_button = None           # Gtk.Button

        # (Widgets which must be (de)sensitised during download/update/refresh
        #   operations, in addition to self.check_media_button and
        #   self.download_media_button)
        self.save_db_menu_item = None           # Gtk.MenuItem
        self.system_prefs_menu_item = None      # Gtk.MenuItem
        self.gen_options_menu_item = None       # Gtk.MenuItem
        self.add_video_menu_item = None         # Gtk.MenuItem
        self.add_channel_menu_item = None       # Gtk.MenuItem
        self.add_playlist_menu_item = None      # Gtk.MenuItem
        self.add_folder_menu_item = None        # Gtk.MenuItem
        self.check_all_menu_item = None         # Gtk.MenuItem
        self.download_all_menu_item = None      # Gtk.MenuItem
        self.stop_operation_menu_item = None    # Gtk.MenuItem
        self.update_ytdl_menu_item = None       # Gtk.MenuItem
        self.refresh_db_menu_item = None        # Gtk.MenuItem
        self.check_all_toolbutton = None        # Gtk.ToolButton
        self.download_all_toolbutton = None     # Gtk.ToolButton
        self.stop_operation_toolbutton = None   # Gtk.ToolButton
        # (Other widgets that might be modified, depending on current
        #   conditions)
        self.test_menu_item = None              # Gtk.MenuItem
        self.test_button = None                 # Gtk.Button


        # IV list - other
        # ---------------
        # Size (in pixels) of gaps between main window widgets
        self.spacing_size = self.app_obj.default_spacing_size
        # In the Videos Tab, the width (in pixels) of the Video Index
        self.videos_paned_posn = 200
        # In the Progress Tab, the height (in pixels) of the Progress List
        self.progress_paned_posn = 200
        # Standard size of video thumbnails in the Video Catalogue, in pixels,
        #   assuming that the actual thumbnail file is 1280x720
        self.thumb_width = 128
        self.thumb_height = 76

        # Paths to Tartube standard icon files. Dictionary in the form
        #   key - a string like 'video_both_large'
        #   value - full filepath to the icon file
        self.icon_dict = {}
        # Loading icon files whenever they're neeeded causes frequent Gtk
        #   crashes. Instead, we create a GdkPixbuf.Pixbuf for all standard
        #   icon files at the beginning
        # A dictionary of those pixbufs, created by self.setup_pixbufs()
        # Dictionary in the form
        #   key - a string like 'video_both_large' (the same key set used by
        #       self.icon_dict)
        #   value - A GdkPixbuf.Pixbuf object
        self.pixbuf_dict = {}
        # List of pixbufs used as each window's icon list
        self.win_pixbuf_list = []

        # Standard limits for the length of strings displayed in various
        #   widgets
        self.long_string_max_len = 64
        self.medium_string_max_len = 45
        self.string_max_len = 32
        self.short_string_max_len = 24
        self.tiny_string_max_len = 16
        # Use a separate IV for video descriptions (so we can tweak it
        #   specifically)
        # The value is low, because descriptions in ALL CAPS are too big for
        #   the Video Catalogue, otherwise
        self.descrip_line_max_len = 50
        # Use a separate IV for tooltips in the Video Index/Video Catalogue
        self.tooltip_max_len = 60

        # List of configuration windows (anything inheriting from
        #   config.GenericConfigWin) that are currently open. A download/
        #   update/refresh operation cannot start when one of these windows are
        #   open (and the windows cannot be opened during such an operation)
        self.config_win_list = []

        # Videos Tab IVs
        # The Video Index is the left-hand side of the main window, and
        #   displays only channels, playlists and folders
        # The Video Index uses a Gtk.TreeView to display media data objects
        #   (channels, playlist and folders, but not videos). This dictionary
        #   keeps track of which row in the Gtk.TreeView is displaying which
        #   media data object
        # Dictionary in the form
        #   key = name of the media data object (stored in its .name IV)
        #   value = Gtk.TreeRowReference
        self.video_index_row_dict = {}
        # The call to self.video_index_add_row() causes the auto-sorting
        #   function self.video_index_auto_sort() to be called before we're
        #   ready, due to some Gtk problem I don't understand
        # Temporary solution is to disable auto-sorting during calls to that
        #   function
        self.video_index_no_sort_flag = False
        # The name of the channel, playlist or folder currently visible in the
        #   Video Catalogue (None if no channel, playlist or folder is
        #   selected)
        self.video_index_current = None
        # Flag set to True when the currently visible item is a private folder
        #   (media.Folder.priv_flag is True), set to False at all other times
        self.video_index_current_priv_flag = False
        # Don't update the Video Catalogue during certain procedures, such as
        #   removing a row from the Video Index (in which case, this flag will
        #   be set to True
        self.ignore_video_index_select_flag = False

        # The Video Catalogue is the right-hand side of the main window. When
        #   the user clicks on a channel, playlist or folder, all the videos
        #   it contains are displayed in the Video catalogue (replacing any
        #   previous contents)
        # Dictionary of mainwin.SimpleCatalogueItem or
        #   mainwin.ComplexCatalogueItem objects (depending on the current
        #   value of self.catalogue_mode)
        # There is one catalogue item object for each row that's currently
        #   visible in the Video Catalogue
        # Dictionary in the form
        #   key = dbid (of the mainWin.SimpleCatalogueItem or
        #       mainWin.ComplexCatalogueItem, which matches the dbid of its
        #       media.Video object)
        #   value = the catalogue item itself
        self.video_catalogue_dict = {}

        # The video catalogue splits its video list into pages (as Gtk
        #   struggles with a list of hundreds, or thousands, of videos)
        # The number of videos per page is specified by
        #   mainapp.TartubeApp.catalogue_page_size
        # The current page number (minimum 1, maximum 9999)
        self.catalogue_toolbar_current_page = 1
        # The number of pages currently in use (minimum 1, maximum 9999)
        self.catalogue_toolbar_last_page = 1

        # Progress Tab IVs
        # The Progress List uses a Gtk.TreeView display download jobs, whether
        #   they are waiting to start, currently in progress, or finished. This
        #   dictionary keeps track of which row in the Gtk.TreeView is handling
        #   which download job
        # Dictionary in the form
        #   key = The downloads.DownloadItem.item_id for the download item
        #       handling the media data object
        #   value = the row number (0 is the first row)
        self.progress_list_row_dict = {}
        # The number of rows added to the treeview
        self.progress_list_row_count = 0

        # During a download operation, self.progress_list_receive_dl_stats() is
        #   called every time youtube-dl writes some output to STDOUT. This can
        #   happen many times a second
        # Updating data displayed in the Progress List several times a second,
        #   and irregularly, doesn't look very nice. Instead, we only update
        #   the displayed data at fixed intervals
        # Thus, when self.progress_list_receive_dl_stats() is called, it
        #   temporarily stores the download statistics it has received in this
        #   IV. The statistics are received in a dictionary in the standard
        #   format described in the comments to
        #   media.VideoDownloader.extract_stdout_data()
        # Then, during calls at fixed intervals to
        #   self.progress_list_display_dl_stats(), those download statistics
        #   are displayed
        # Dictionary of download statistics yet to be displayed, emptied after
        #   every call to self.progress_list_display_dl_stats()
        # Dictionary in the form
        #   key = The downloads.DownloadItem.item_id for the download item
        #       handling the media data object
        #   value = A dictionary of download statistics dictionary in the
        #       standard format
        self.progress_list_temp_dict = {}

        # Whenever a video is downloaded (in reality, or just in simulation),
        #   a row is added to Gtk.TreeView in the Results List
        # The number of rows added to the treeview
        self.results_list_row_count = 0
        # At the instant youtube-dl reports that a video has been downloaded,
        #   the file doesn't yet exist in Tartube's data directory (so the
        #   Python test for the existence of the file fails)
        # Therefore, self.results_list_add_row() adds a temporary entry to this
        #   list. Items in the list are checked by
        #   self.results_list_update_row() and removed from the list, as soon
        #   as the file is confirmed to exist, at which time the Results List
        #   is updated
        # (For simulated downloads, the entry is checked by
        #   self.results_list_update_row() just once. For real downloads, it
        #   is checked many times until either the file exists or the
        #   download operation halts)
        # List of python dictionaries, one for each downloaded video. Each of
        #   those dictionaries are in the form:
        #       'video_obj': a media.Video object
        #       'row_num': the row on the treeview, matching
        #           self.results_list_row_count
        #       'keep_description', 'keep_info', 'keep_annotations',
        #           'keep_thumbnail': flags from the options.OptionsManager
        #           object used for to download the video (not added to the
        #           dictionary at all for simulated downloads)
        self.results_list_temp_list = []

        # Output Tab IVs
        # The number of pages in the Output Tab's notebook. The number matches
        #   the highest value of mainapp.TartubeApp.num_worker_default during
        #   this session (i.e. if the user increases the value, new page(s) are
        #   created, but if the user reduces the value, no pages are destroyed)
        self.output_page_count = 0
        # Dictionary of Gtk.TextView objects created in the Output Tab; one for
        #   each page
        # Dictionary in the form
        #   key = The page number (the first page is #1)
        #   value = The corresponding Gtk.TextView object
        self.output_textview_dict = {}
        # When youtube-dl generates output, that text cannot be displayed in
        #   the Output Tab's pages immediately (because Gtk widgets cannot be
        #   updated from within a thread)
        # Instead, values are appended to this list
        # During a download operation, mainapp.TartubeApp.dl_timer_callback()
        #   calls self.output_tab_update() regularly to display the output in
        #   the Output Tab (which empties the list)
        # List in groups of 3, in the form
        #   (page_number, mssage, error_flag...)
        # ...where 'page_number' matches a key in self.output_textview_dict,
        #   'msg' is a string to display, and 'error_flag' is True for an
        #   error/warning message, False otherwise
        self.output_tab_insert_list = []

        # Errors / Warnings Tab IVs
        # The number of errors added to the Error List, since this tab was the
        #   visible one (updated by self.errors_list_add_row() or
        #   self.errors_list_add_system_error(), and reset back to zero by
        #   self.on_notebook_switch_page() when the tab becomes the visible one
        #   again)
        self.tab_error_count = 0
        # The number of warnings added to the Error List, since this tab was
        #   the visible one
        self.tab_warning_count = 0
        # The number of the tab in self.notebook that is currently visible
        #   (only required to test whether the Errors/Warnings tab is the
        #   visible one)
        self.visible_tab_num = 0


        # Code
        # ----

        # Create GdkPixbuf.Pixbufs for all Tartube standard icons
        self.setup_pixbufs()
        # Set up the main window
        self.setup_win()


    # Public class methods


    def setup_pixbufs(self):

        """Called by self.__init__().

        Populates self.icon_dict and self.pixbuf.dict from the lists provided
        by formats.py.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 385 setup_pixbufs')

        # The default location for icons is ../icons. Packagers may have moved
        #   them to one of the directories specified by
        #   __main__.__icon_dir_list__
        # Check all locations, and use the first one which actually exists
        icon_dir_list = __main__.__icon_dir_list__.copy()
        icon_dir_list.insert(
            0,
            os.path.abspath(
                os.path.join(self.app_obj.script_parent_dir, 'icons'),
            ),
        )

        for icon_dir_path in icon_dir_list:
            if os.path.isdir(icon_dir_path):

                for key in formats.DIALOGUE_ICON_DICT:
                    rel_path = formats.DIALOGUE_ICON_DICT[key]
                    full_path = os.path.abspath(
                        os.path.join(icon_dir_path, 'dialogue', rel_path),
                    )
                    self.icon_dict[key] = full_path

                for key in formats.TOOLBAR_ICON_DICT:
                    rel_path = formats.TOOLBAR_ICON_DICT[key]
                    full_path = os.path.abspath(
                        os.path.join(icon_dir_path, 'toolbar', rel_path),
                    )
                    self.icon_dict[key] = full_path

                for key in formats.LARGE_ICON_DICT:
                    rel_path = formats.LARGE_ICON_DICT[key]
                    full_path = os.path.abspath(
                        os.path.join(icon_dir_path, 'large', rel_path),
                    )
                    self.icon_dict[key] = full_path

                for key in formats.SMALL_ICON_DICT:
                    rel_path = formats.SMALL_ICON_DICT[key]
                    full_path = os.path.abspath(
                        os.path.join(icon_dir_path, 'small', rel_path),
                    )
                    self.icon_dict[key] = full_path

                # (At the moment, the system preference window only uses one
                #   flag, but more may be added later)
                full_path = os.path.abspath(
                    os.path.join(icon_dir_path, 'locale', 'flag_uk.png'),
                )
                self.icon_dict['flag_uk'] = full_path

                # Now create the pixbufs themselves
                for key in self.icon_dict:
                    full_path = self.icon_dict[key]

                    if not os.path.isfile(full_path):
                        self.pixbuf_dict[key] = None
                    else:
                        self.pixbuf_dict[key] \
                        = GdkPixbuf.Pixbuf.new_from_file(full_path)

                for rel_path in formats.WIN_ICON_LIST:
                    full_path = os.path.abspath(
                        os.path.join(icon_dir_path, 'win', rel_path),
                    )
                    self.win_pixbuf_list.append(
                        GdkPixbuf.Pixbuf.new_from_file(full_path),
                    )

                return

        # No icons directory found; this is a fatal error
        print(
            'Missing icons directory; ' \
            + utils.upper_case_first(__main__.__packagename__) \
            + ' cannot start',
            file=sys.stderr,
        )

        self.app_obj.do_shutdown()


    def setup_win(self):

        """Called by self.__init__().

        Sets up the main window, calling various function to create its
        widgets.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 477 setup_win')

        # Set the default window size
        self.set_default_size(
            self.app_obj.main_win_width,
            self.app_obj.main_win_height,
        )
        # Set the window's Gtk icon list
        self.set_icon_list(self.win_pixbuf_list)

        # Create main window widgets
        self.setup_grid()
        self.setup_menubar()
        self.setup_main_toolbar()
        self.setup_notebook()
        self.setup_videos_tab()
        self.setup_progress_tab()
        self.setup_output_tab()
        self.setup_errors_tab()


    # (Create main window widgets)


    def setup_grid(self):

        """Called by self.setup_win().

        Sets up a Gtk.Grid on which all the main window's widgets are placed.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 508 setup_grid')

        self.grid = Gtk.Grid()
        self.add(self.grid)


    def setup_menubar(self):

        """Called by self.setup_win().

        Sets up a Gtk.Menu at the top of the main window.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 522 setup_menubar')

        self.menubar = Gtk.MenuBar()
        self.grid.attach(self.menubar, 0, 0, 1, 1)

        # File column
        file_menu_column = Gtk.MenuItem.new_with_mnemonic('_File')
        self.menubar.add(file_menu_column)

        file_sub_menu = Gtk.Menu()
        file_menu_column.set_submenu(file_sub_menu)

        self.save_db_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Save database',
        )
        file_sub_menu.append(self.save_db_menu_item)
        self.save_db_menu_item.set_action_name('app.save_db_menu')

        file_sub_menu.append(Gtk.SeparatorMenuItem())

        quit_menu_item = Gtk.MenuItem.new_with_mnemonic('_Quit')
        file_sub_menu.append(quit_menu_item)
        quit_menu_item.set_action_name('app.quit_menu')

        # Edit column
        edit_menu_column = Gtk.MenuItem.new_with_mnemonic('E_dit')
        self.menubar.add(edit_menu_column)

        edit_sub_menu = Gtk.Menu()
        edit_menu_column.set_submenu(edit_sub_menu)

        self.system_prefs_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_System preferences...',
        )
        edit_sub_menu.append(self.system_prefs_menu_item)
        self.system_prefs_menu_item.set_action_name('app.system_prefs_menu')

        self.gen_options_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_General download options...',
        )
        edit_sub_menu.append(self.gen_options_menu_item)
        self.gen_options_menu_item.set_action_name('app.gen_options_menu')

        # Media column
        media_menu_column = Gtk.MenuItem.new_with_mnemonic('_Media')
        self.menubar.add(media_menu_column)

        media_sub_menu = Gtk.Menu()
        media_menu_column.set_submenu(media_sub_menu)

        self.add_video_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Add _videos...',
        )
        media_sub_menu.append(self.add_video_menu_item)
        self.add_video_menu_item.set_action_name('app.add_video_menu')

        self.add_channel_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Add _channel...',
        )
        media_sub_menu.append(self.add_channel_menu_item)
        self.add_channel_menu_item.set_action_name('app.add_channel_menu')

        self.add_playlist_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Add _playlist...',
        )
        media_sub_menu.append(self.add_playlist_menu_item)
        self.add_playlist_menu_item.set_action_name('app.add_playlist_menu')

        self.add_folder_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Add _folder...',
        )
        media_sub_menu.append(self.add_folder_menu_item)
        self.add_folder_menu_item.set_action_name('app.add_folder_menu')

        media_sub_menu.append(Gtk.SeparatorMenuItem())

        self.export_db_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Export from database',
        )
        media_sub_menu.append(self.export_db_menu_item)
        self.export_db_menu_item.set_action_name('app.export_db_menu')

        import_sub_menu = Gtk.Menu()

        import_json_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_JSON export file',
        )
        import_sub_menu.append(import_json_menu_item)
        import_json_menu_item.set_action_name('app.import_json_menu')

        import_text_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Plain _text export file',
        )
        import_sub_menu.append(import_text_menu_item)
        import_text_menu_item.set_action_name('app.import_text_menu')

        self.import_db_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Import into database'
        )
        self.import_db_menu_item.set_submenu(import_sub_menu)
        media_sub_menu.append(self.import_db_menu_item)

        media_sub_menu.append(Gtk.SeparatorMenuItem())

        switch_view_menu_item = \
        Gtk.MenuItem.new_with_mnemonic('_Switch between views')
        media_sub_menu.append(switch_view_menu_item)
        switch_view_menu_item.set_action_name('app.switch_view_menu')

        self.show_hidden_menu_item = \
        Gtk.MenuItem.new_with_mnemonic('Show _hidden folders')
        media_sub_menu.append(self.show_hidden_menu_item)
        self.show_hidden_menu_item.set_action_name('app.show_hidden_menu')

        if self.app_obj.debug_test_media_menu_flag:

            media_sub_menu.append(Gtk.SeparatorMenuItem())

            self.test_menu_item = Gtk.MenuItem.new_with_mnemonic(
                '_Add test media',
            )
            media_sub_menu.append(self.test_menu_item)
            self.test_menu_item.set_action_name('app.test_menu')

        # Operations column
        ops_menu_column = Gtk.MenuItem.new_with_mnemonic('_Operations')
        self.menubar.add(ops_menu_column)

        ops_sub_menu = Gtk.Menu()
        ops_menu_column.set_submenu(ops_sub_menu)

        self.check_all_menu_item = Gtk.MenuItem.new_with_mnemonic('_Check all')
        ops_sub_menu.append(self.check_all_menu_item)
        self.check_all_menu_item.set_action_name('app.check_all_menu')

        self.download_all_menu_item = \
        Gtk.MenuItem.new_with_mnemonic('_Download all')
        ops_sub_menu.append(self.download_all_menu_item)
        self.download_all_menu_item.set_action_name('app.download_all_menu')

        ops_sub_menu.append(Gtk.SeparatorMenuItem())

        self.refresh_db_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Refresh database',
        )
        ops_sub_menu.append(self.refresh_db_menu_item)
        self.refresh_db_menu_item.set_action_name('app.refresh_db_menu')

        ops_sub_menu.append(Gtk.SeparatorMenuItem())

        self.update_ytdl_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Update youtube-dl',
        )
        ops_sub_menu.append(self.update_ytdl_menu_item)
        self.update_ytdl_menu_item.set_action_name('app.update_ytdl_menu')
        if __main__.__debian_install_flag__:
            self.update_ytdl_menu_item.set_sensitive(False)

        self.install_ffmpeg_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Install FFmpeg',
        )
        ops_sub_menu.append(self.install_ffmpeg_menu_item)
        self.install_ffmpeg_menu_item.set_action_name(
            'app.install_ffmpeg_menu',
        )
        if os.name != 'nt':
            self.install_ffmpeg_menu_item.set_sensitive(False)

        ops_sub_menu.append(Gtk.SeparatorMenuItem())

        self.stop_operation_menu_item = \
        Gtk.MenuItem.new_with_mnemonic('_Stop current operation')
        ops_sub_menu.append(self.stop_operation_menu_item)
        self.stop_operation_menu_item.set_action_name(
            'app.stop_operation_menu',
        )
        self.stop_operation_menu_item.set_sensitive(False)

        # Help column
        help_menu_column = Gtk.MenuItem.new_with_mnemonic('_Help')
        self.menubar.add(help_menu_column)

        help_sub_menu = Gtk.Menu()
        help_menu_column.set_submenu(help_sub_menu)

        about_menu_item = Gtk.MenuItem.new_with_mnemonic('_About...')
        help_sub_menu.append(about_menu_item)
        about_menu_item.set_action_name('app.about_menu')

        go_website_menu_item = Gtk.MenuItem.new_with_mnemonic('Go to _website')
        help_sub_menu.append(go_website_menu_item)
        go_website_menu_item.set_action_name('app.go_website_menu')


    def setup_main_toolbar(self):

        """Called by self.setup_win(). Also called by
        self.redraw_main_toolbar().

        Sets up a Gtk.Toolbar near the top of the main window, below the menu,
        replacing the previous one, if it exists.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 712 setup_main_toolbar')

        # If a toolbar already exists, destroy it to make room for the new one
        if self.main_toolbar:
            self.grid.remove(self.main_toolbar)

        # Create a new toolbar
        self.main_toolbar = Gtk.Toolbar()
        self.grid.attach(self.main_toolbar, 0, 1, 1, 1)

        # Toolbar items. If mainapp.TartubeApp.toolbar_squeeze_flag is True,
        #   we don't display labels in the toolbuttons
        squeeze_flag = self.app_obj.toolbar_squeeze_flag

        if not squeeze_flag:
            self.add_video_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_video_small'],
                ),
            )
            self.add_video_toolbutton.set_label('Videos')
            self.add_video_toolbutton.set_is_important(True)
        else:
            self.add_video_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_video_large'],
                ),
            )

        self.main_toolbar.insert(self.add_video_toolbutton, -1)
        self.add_video_toolbutton.set_tooltip_text('Add new video(s)')
        self.add_video_toolbutton.set_action_name('app.add_video_toolbutton')

        if not squeeze_flag:
            self.add_channel_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_channel_small'],
                ),
            )
            self.add_channel_toolbutton.set_label('Channel')
            self.add_channel_toolbutton.set_is_important(True)
        else:
            self.add_channel_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_channel_large'],
                ),
            )

        self.main_toolbar.insert(self.add_channel_toolbutton, -1)
        self.add_channel_toolbutton.set_tooltip_text('Add a new channel')
        self.add_channel_toolbutton.set_action_name(
            'app.add_channel_toolbutton',
        )

        if not squeeze_flag:
            self.add_playlist_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_playlist_small'],
                ),
            )
            self.add_playlist_toolbutton.set_label('Playlist')
            self.add_playlist_toolbutton.set_is_important(True)
        else:
            self.add_playlist_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_playlist_large'],
                ),
            )

        self.main_toolbar.insert(self.add_playlist_toolbutton, -1)
        self.add_playlist_toolbutton.set_tooltip_text('Add a new playlist')
        self.add_playlist_toolbutton.set_action_name(
            'app.add_playlist_toolbutton',
        )

        if not squeeze_flag:
            self.add_folder_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_folder_small'],
                ),
            )
            self.add_folder_toolbutton.set_label('Folder')
            self.add_folder_toolbutton.set_is_important(True)
        else:
            self.add_folder_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_folder_large'],
                ),
            )

        self.main_toolbar.insert(self.add_folder_toolbutton, -1)
        self.add_folder_toolbutton.set_tooltip_text('Add a new folder')
        self.add_folder_toolbutton.set_action_name('app.add_folder_toolbutton')

        # (Conversely, if there are no labels, then we have enough room for a
        #   separator)
        if squeeze_flag:
            self.main_toolbar.insert(Gtk.SeparatorToolItem(), -1)

        if not squeeze_flag:
            self.check_all_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_check_small'],
                ),
            )
            self.check_all_toolbutton.set_label('Check')
            self.check_all_toolbutton.set_is_important(True)
        else:
            self.check_all_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_check_large'],
                ),
            )

        self.main_toolbar.insert(self.check_all_toolbutton, -1)
        self.check_all_toolbutton.set_tooltip_text(
            'Check all videos, channels, playlists and folders',
        )
        self.check_all_toolbutton.set_action_name('app.check_all_toolbutton')

        if not squeeze_flag:
            self.download_all_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_download_small'],
                ),
            )
            self.download_all_toolbutton.set_label('Download')
            self.download_all_toolbutton.set_is_important(True)
        else:
            self.download_all_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_download_large'],
                ),
            )

        self.main_toolbar.insert(self.download_all_toolbutton, -1)
        self.download_all_toolbutton.set_tooltip_text(
            'Download all videos, channels, playlists and folders',
        )
        self.download_all_toolbutton.set_action_name(
            'app.download_all_toolbutton',
        )

        if squeeze_flag:
            self.main_toolbar.insert(Gtk.SeparatorToolItem(), -1)

        if not squeeze_flag:
            self.stop_operation_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_stop_small'],
                ),
            )
            self.stop_operation_toolbutton.set_label('Stop')
            self.stop_operation_toolbutton.set_is_important(True)
        else:
            self.stop_operation_toolbutton = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_stop_large'],
                ),
            )

        self.main_toolbar.insert(self.stop_operation_toolbutton, -1)
        self.stop_operation_toolbutton.set_sensitive(False)
        self.stop_operation_toolbutton.set_tooltip_text(
            'Stop the current operation',
        )
        self.stop_operation_toolbutton.set_action_name(
            'app.stop_operation_toolbutton',
        )

        if not squeeze_flag:
            switch_view_button = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_switch_small'],
                ),
            )
            switch_view_button.set_label('Switch')
            switch_view_button.set_is_important(True)
        else:
            switch_view_button = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_switch_large'],
                ),
            )

        self.main_toolbar.insert(switch_view_button, -1)
        switch_view_button.set_tooltip_text(
            'Switch between simple and complex views',
        )
        switch_view_button.set_action_name('app.switch_view_toolbutton')

        if self.app_obj.debug_test_media_toolbar_flag:

            if not squeeze_flag:
                self.test_button = Gtk.ToolButton.new(
                    Gtk.Image.new_from_pixbuf(
                        self.pixbuf_dict['tool_test_small'],
                    ),
                )
                self.test_button.set_label('Test')
                self.test_button.set_is_important(True)
            else:
                self.test_button = Gtk.ToolButton.new(
                    Gtk.Image.new_from_pixbuf(
                        self.pixbuf_dict['tool_test_large'],
                    ),
                )

            self.main_toolbar.insert(self.test_button, -1)
            self.test_button.set_tooltip_text('Add test media data objects')
            self.test_button.set_action_name('app.test_toolbutton')

        if squeeze_flag:
            self.main_toolbar.insert(Gtk.SeparatorToolItem(), -1)

        if not squeeze_flag:
            quit_button = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_quit_small'],
                ),
            )
            quit_button.set_label('Quit')
            quit_button.set_is_important(True)
        else:
            quit_button = Gtk.ToolButton.new(
                Gtk.Image.new_from_pixbuf(
                    self.pixbuf_dict['tool_quit_large'],
                ),
            )

        self.main_toolbar.insert(quit_button, -1)
        quit_button.set_tooltip_text(
            'Close ' + utils.upper_case_first(__main__.__packagename__),
        )
        quit_button.set_action_name('app.quit_toolbutton')


    def setup_notebook(self):

        """Called by self.setup_win().

        Sets up a Gtk.Notebook occupying all the space below the menu and
        toolbar. Creates two tabs, the Videos Tab and the Progress Tab.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 954 setup_notebook')

        self.notebook = Gtk.Notebook()
        self.grid.attach(self.notebook, 0, 2, 1, 1)
        self.notebook.set_border_width(self.spacing_size)
        self.notebook.connect('switch-page', self.on_notebook_switch_page)

        # Videos Tab
        self.videos_tab = Gtk.Box()
        self.videos_label = Gtk.Label.new_with_mnemonic('_Videos')
        self.notebook.append_page(self.videos_tab, self.videos_label)
        self.videos_tab.set_hexpand(True)
        self.videos_tab.set_vexpand(True)
        self.videos_tab.set_border_width(self.spacing_size)

        # Progress Tab
        self.progress_tab = Gtk.Box()
        self.progress_label = Gtk.Label.new_with_mnemonic('_Progress')
        self.notebook.append_page(self.progress_tab, self.progress_label)
        self.progress_tab.set_hexpand(True)
        self.progress_tab.set_vexpand(True)
        self.progress_tab.set_border_width(self.spacing_size)

        # Output Tab
        self.output_tab = Gtk.Box()
        self.output_label = Gtk.Label.new_with_mnemonic('_Output')
        self.notebook.append_page(self.output_tab, self.output_label)
        self.output_tab.set_hexpand(True)
        self.output_tab.set_vexpand(True)
        self.output_tab.set_border_width(self.spacing_size)

        # Errors Tab
        self.errors_tab = Gtk.Box()
        self.errors_label = Gtk.Label.new_with_mnemonic('_Errors / Warnings')
        self.notebook.append_page(self.errors_tab, self.errors_label)
        self.errors_tab.set_hexpand(True)
        self.errors_tab.set_vexpand(True)
        self.errors_tab.set_border_width(self.spacing_size)


    def setup_videos_tab(self):

        """Called by self.setup_win().

        Creates widgets for the Videos Tab.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 994 setup_videos_tab')

        self.videos_paned = Gtk.HPaned()
        self.videos_tab.pack_start(self.videos_paned, True, True, 0)
        self.videos_paned.set_position(self.videos_paned_posn)
        self.videos_paned.set_wide_handle(True)

        # Left-hand side
        vbox = Gtk.VBox()
        self.videos_paned.add1(vbox)

        self.video_index_scrolled = Gtk.ScrolledWindow()
        vbox.pack_start(self.video_index_scrolled, True, True, 0)
        self.video_index_scrolled.set_policy(
            Gtk.PolicyType.AUTOMATIC,
            Gtk.PolicyType.AUTOMATIC,
        )

        self.video_index_frame = Gtk.Frame()
        self.video_index_scrolled.add_with_viewport(self.video_index_frame)

        # Video index
        self.video_index_reset()

        # 'Check all' and 'Download all' buttons
        self.button_box = Gtk.VBox()
        vbox.pack_start(self.button_box, False, False, 0)

        self.check_media_button = Gtk.Button()
        self.button_box.pack_start(
            self.check_media_button,
            True,
            True,
            self.spacing_size,
        )
        self.check_media_button.set_label('Check all')
        self.check_media_button.set_tooltip_text(
            'Check all videos, channels, playlists and folders',
        )
        self.check_media_button.set_action_name('app.check_all_button')

        self.download_media_button = Gtk.Button()
        self.button_box.pack_start(self.download_media_button, True, True, 0)
        self.download_media_button.set_label('Download all')
        self.download_media_button.set_tooltip_text(
            'Download all videos, channels, playlists and folders',
        )
        self.download_media_button.set_action_name('app.download_all_button')

        # Right-hand side
        vbox2 = Gtk.VBox()
        self.videos_paned.add2(vbox2)

        # Video catalogue
        self.catalogue_scrolled = Gtk.ScrolledWindow()
        vbox2.pack_start(self.catalogue_scrolled, True, True, 0)
        self.catalogue_scrolled.set_policy(
            Gtk.PolicyType.AUTOMATIC,
            Gtk.PolicyType.AUTOMATIC,
        )

        self.catalogue_frame = Gtk.Frame()
        self.catalogue_scrolled.add_with_viewport(self.catalogue_frame)

        # Video catalogue toolbar
        self.catalogue_toolbar = Gtk.Toolbar()
        vbox2.pack_start(self.catalogue_toolbar, False, False, 0)

        toolitem = Gtk.ToolItem.new()
        self.catalogue_toolbar.insert(toolitem, -1)
        label = Gtk.Label('Page  ')
        toolitem.add(label)

        toolitem2 = Gtk.ToolItem.new()
        self.catalogue_toolbar.insert(toolitem2, -1)
        self.catalogue_page_entry = Gtk.Entry()
        toolitem2.add(self.catalogue_page_entry)
        self.catalogue_page_entry.set_text(
            str(self.catalogue_toolbar_current_page),
        )
        self.catalogue_page_entry.set_width_chars(4)
        self.catalogue_page_entry.set_sensitive(False)
        self.catalogue_page_entry.set_tooltip_text('Set visible page')
        self.catalogue_page_entry.connect(
            'activate',
            self.on_video_catalogue_page_entry_activated,
        )

        toolitem3 = Gtk.ToolItem.new()
        self.catalogue_toolbar.insert(toolitem3, -1)
        label2 = Gtk.Label('  of  ')
        toolitem3.add(label2)

        toolitem4 = Gtk.ToolItem.new()
        self.catalogue_toolbar.insert(toolitem4, -1)
        self.catalogue_last_entry = Gtk.Entry()
        toolitem4.add(self.catalogue_last_entry)
        self.catalogue_last_entry.set_text(
            str(self.catalogue_toolbar_last_page),
        )
        self.catalogue_last_entry.set_width_chars(4)
        self.catalogue_last_entry.set_sensitive(False)
        self.catalogue_last_entry.set_editable(False)

        self.catalogue_toolbar.insert(Gtk.SeparatorToolItem(), -1)

        self.catalogue_first_button \
        = Gtk.ToolButton.new_from_stock(Gtk.STOCK_GOTO_FIRST)
        self.catalogue_toolbar.insert(self.catalogue_first_button, -1)
        self.catalogue_first_button.set_sensitive(False)
        self.catalogue_first_button.set_tooltip_text('Go to first page')
        self.catalogue_first_button.set_action_name(
            'app.first_page_toolbutton',
        )

        self.catalogue_back_button \
        = Gtk.ToolButton.new_from_stock(Gtk.STOCK_GO_BACK)
        self.catalogue_toolbar.insert(self.catalogue_back_button, -1)
        self.catalogue_back_button.set_sensitive(False)
        self.catalogue_back_button.set_tooltip_text('Go to previous page')
        self.catalogue_back_button.set_action_name(
            'app.previous_page_toolbutton',
        )

        self.catalogue_forwards_button \
        = Gtk.ToolButton.new_from_stock(Gtk.STOCK_GO_FORWARD)
        self.catalogue_toolbar.insert(self.catalogue_forwards_button, -1)
        self.catalogue_forwards_button.set_sensitive(False)
        self.catalogue_forwards_button.set_tooltip_text('Go to next page')
        self.catalogue_forwards_button.set_action_name(
            'app.next_page_toolbutton',
        )

        self.catalogue_last_button \
        = Gtk.ToolButton.new_from_stock(Gtk.STOCK_GOTO_LAST)
        self.catalogue_toolbar.insert(self.catalogue_last_button, -1)
        self.catalogue_last_button.set_sensitive(False)
        self.catalogue_last_button.set_tooltip_text('Go to last page')
        self.catalogue_last_button.set_action_name(
            'app.last_page_toolbutton',
        )

        self.catalogue_find_button \
        = Gtk.ToolButton.new_from_stock(Gtk.STOCK_FIND)
        self.catalogue_toolbar.insert(self.catalogue_find_button, -1)
        self.catalogue_find_button.set_sensitive(False)
        self.catalogue_find_button.set_tooltip_text('Find videos by date')
        self.catalogue_find_button.set_action_name(
            'app.find_date_toolbutton',
        )

        self.catalogue_toolbar.insert(Gtk.SeparatorToolItem(), -1)

        toolitem5 = Gtk.ToolItem.new()
        self.catalogue_toolbar.insert(toolitem5, -1)
        label3 = Gtk.Label('Size   ')
        toolitem5.add(label3)

        toolitem6 = Gtk.ToolItem.new()
        self.catalogue_toolbar.insert(toolitem6, -1)
        self.catalogue_size_entry = Gtk.Entry()
        toolitem6.add(self.catalogue_size_entry)
        self.catalogue_size_entry.set_text(
            str(self.app_obj.catalogue_page_size),
        )
        self.catalogue_size_entry.set_width_chars(4)
        self.catalogue_size_entry.set_tooltip_text('Set page size')
        self.catalogue_size_entry.connect(
            'activate',
            self.on_video_catalogue_size_entry_activated,
        )

        self.catalogue_scroll_up_button \
        = Gtk.ToolButton.new_from_stock(Gtk.STOCK_GO_UP)
        self.catalogue_toolbar.insert(self.catalogue_scroll_up_button, -1)
        self.catalogue_scroll_up_button.set_sensitive(False)
        self.catalogue_scroll_up_button.set_tooltip_text('Scroll up')
        self.catalogue_scroll_up_button.set_action_name(
            'app.scroll_up_toolbutton',
        )

        self.catalogue_scroll_down_button \
        = Gtk.ToolButton.new_from_stock(Gtk.STOCK_GO_DOWN)
        self.catalogue_toolbar.insert(self.catalogue_scroll_down_button, -1)
        self.catalogue_scroll_down_button.set_sensitive(False)
        self.catalogue_scroll_down_button.set_tooltip_text('Scroll down')
        self.catalogue_scroll_down_button.set_action_name(
            'app.scroll_down_toolbutton',
        )

        # Video catalogue
        self.video_catalogue_reset()


    def setup_progress_tab(self):

        """Called by self.setup_win().

        Creates widgets for the Progress Tab.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 1196 setup_progress_tab')

        vbox = Gtk.VBox()
        self.progress_tab.pack_start(vbox, True, True, 0)

        self.progress_paned = Gtk.VPaned()
        vbox.pack_start(self.progress_paned, True, True, 0)
        self.progress_paned.set_position(self.progress_paned_posn)
        self.progress_paned.set_wide_handle(True)

        # Upper half
        self.progress_list_scrolled = Gtk.ScrolledWindow()
        self.progress_paned.add1(self.progress_list_scrolled)
        self.progress_list_scrolled.set_policy(
            Gtk.PolicyType.AUTOMATIC,
            Gtk.PolicyType.AUTOMATIC,
        )

        self.progress_list_frame = Gtk.Frame()
        self.progress_list_scrolled.add_with_viewport(self.progress_list_frame)

        # Progress List
        self.progress_list_treeview = Gtk.TreeView()
        self.progress_list_frame.add(self.progress_list_treeview)
        self.progress_list_treeview.set_can_focus(False)
        # (Detect right-clicks on the treeview)
        self.progress_list_treeview.connect(
            'button-press-event',
            self.on_progress_list_right_click,
        )

        for i, column_title in enumerate(
            [
                'hide', '', 'Source', 'Videos', 'Status', 'Incoming file',
                'Ext', 'Size', '%', 'ETA', 'Speed',
            ]
        ):
            if not column_title:
                renderer_pixbuf = Gtk.CellRendererPixbuf()
                column_pixbuf = Gtk.TreeViewColumn(
                    '',
                    renderer_pixbuf,
                    pixbuf=i,
                )
                self.progress_list_treeview.append_column(column_pixbuf)
                column_pixbuf.set_resizable(False)

            else:
                renderer_text = Gtk.CellRendererText()
                column_text = Gtk.TreeViewColumn(
                    column_title,
                    renderer_text,
                    text=i,
                )
                self.progress_list_treeview.append_column(column_text)
                column_text.set_resizable(True)
                column_text.set_min_width(20)
                if column_title == 'hide':
                    column_text.set_visible(False)

        self.progress_list_liststore = Gtk.ListStore(
            int,
            GdkPixbuf.Pixbuf,
            str, str, str, str, str, str, str, str, str,
        )
        self.progress_list_treeview.set_model(self.progress_list_liststore)

        # Lower half
        self.results_list_scrolled = Gtk.ScrolledWindow()
        self.progress_paned.add2(self.results_list_scrolled)
        self.results_list_scrolled.set_policy(
            Gtk.PolicyType.AUTOMATIC,
            Gtk.PolicyType.AUTOMATIC,
        )

        self.results_list_frame = Gtk.Frame()
        self.results_list_scrolled.add_with_viewport(self.results_list_frame)

        # Results List
        self.results_list_treeview = Gtk.TreeView()
        self.results_list_frame.add(self.results_list_treeview)
        self.results_list_treeview.set_can_focus(False)
        # (Detect right-clicks on the treeview)
        self.results_list_treeview.connect(
            'button-press-event',
            self.on_results_list_right_click,
        )

        for i, column_title in enumerate(
            [
                'hide', '', 'New videos', 'Duration', 'Size', 'Date', 'File',
                '', 'Downloaded to',
            ]
        ):
            if not column_title:
                renderer_pixbuf = Gtk.CellRendererPixbuf()
                column_pixbuf = Gtk.TreeViewColumn(
                    column_title,
                    renderer_pixbuf,
                    pixbuf=i,
                )
                self.results_list_treeview.append_column(column_pixbuf)
                column_pixbuf.set_resizable(False)

            elif column_title == 'File':
                renderer_toggle = Gtk.CellRendererToggle()
                column_toggle = Gtk.TreeViewColumn(
                    column_title,
                    renderer_toggle,
                    active=i,
                )
                self.results_list_treeview.append_column(column_toggle)
                column_toggle.set_resizable(False)

            else:
                renderer_text = Gtk.CellRendererText()
                column_text = Gtk.TreeViewColumn(
                    column_title,
                    renderer_text,
                    text=i,
                )
                self.results_list_treeview.append_column(column_text)
                column_text.set_resizable(True)
                column_text.set_min_width(20)
                if column_title == 'hide':
                    column_text.set_visible(False)

        self.results_list_liststore = Gtk.ListStore(
            int,
            GdkPixbuf.Pixbuf,
            str, str, str, str,
            bool,
            GdkPixbuf.Pixbuf,
            str,
        )
        self.results_list_treeview.set_model(self.results_list_liststore)

        # Strip of widgets at the bottom
        hbox = Gtk.HBox()
        vbox.pack_start(hbox, False, False, self.spacing_size)
        hbox.set_border_width(self.spacing_size)

        self.num_worker_checkbutton = Gtk.CheckButton()
        hbox.pack_start(self.num_worker_checkbutton, False, False, 0)
        self.num_worker_checkbutton.set_label('Max downloads')
        self.num_worker_checkbutton.set_active(
            self.app_obj.num_worker_apply_flag,
        )
        self.num_worker_checkbutton.connect(
            'toggled',
            self.on_num_worker_checkbutton_changed,
        )

        self.num_worker_spinbutton = Gtk.SpinButton.new_with_range(
            self.app_obj.num_worker_min,
            self.app_obj.num_worker_max,
            1,
        )
        hbox.pack_start(
            self.num_worker_spinbutton,
            True,
            False,
            self.spacing_size,
        )
        self.num_worker_spinbutton.set_value(self.app_obj.num_worker_default)
        self.num_worker_spinbutton.connect(
            'value-changed',
            self.on_num_worker_spinbutton_changed,
        )

        self.bandwidth_checkbutton = Gtk.CheckButton()
        hbox.pack_start(self.bandwidth_checkbutton, False, False, 0)
        self.bandwidth_checkbutton.set_label('D/L speed (KiB/s)')
        self.bandwidth_checkbutton.set_active(
            self.app_obj.bandwidth_apply_flag,
        )
        self.bandwidth_checkbutton.connect(
            'toggled',
            self.on_bandwidth_checkbutton_changed,
        )

        self.bandwidth_spinbutton = Gtk.SpinButton.new_with_range(
            self.app_obj.bandwidth_min,
            self.app_obj.bandwidth_max,
            1,
        )
        hbox.pack_start(
            self.bandwidth_spinbutton,
            True,
            False,
            self.spacing_size,
        )
        self.bandwidth_spinbutton.set_value(self.app_obj.bandwidth_default)
        self.bandwidth_spinbutton.connect(
            'value-changed',
            self.on_bandwidth_spinbutton_changed,
        )

        self.video_res_checkbutton = Gtk.CheckButton()
        hbox.pack_start(self.video_res_checkbutton, False, False, 0)
        self.video_res_checkbutton.set_label('Video resolution')
        self.video_res_checkbutton.set_active(
            self.app_obj.video_res_apply_flag,
        )
        self.video_res_checkbutton.connect(
            'toggled',
            self.on_video_res_checkbutton_changed,
        )

        store = Gtk.ListStore(str)
        for string in formats.VIDEO_RESOLUTION_LIST:
            store.append( [string] )

        self.video_res_combobox = Gtk.ComboBox.new_with_model(store)
        hbox.pack_start(self.video_res_combobox, False, False, 0)
        renderer_text = Gtk.CellRendererText()
        self.video_res_combobox.pack_start(renderer_text, True)
        self.video_res_combobox.add_attribute(renderer_text, 'text', 0)
        self.video_res_combobox.set_entry_text_column(0)
        self.set_video_res_limit(None)        # Uses default resolution, 720p
        self.video_res_combobox.connect('changed', self.on_combobox_changed)


    def setup_output_tab(self):

        """Called by self.setup_win().

        Creates widgets for the Output Tab.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 1197 setup_output_tab')

        vbox = Gtk.VBox()
        self.output_tab.pack_start(vbox, True, True, 0)

        # During a download operation, each page in the notebook displays
        #   output from a single downloads.DownloadWorker object
        # The pages are added later, via a call to
        #   self.output_tab_setup_pages()
        self.output_notebook = Gtk.Notebook()
        vbox.pack_start(self.output_notebook, True, True, 0)
        self.output_notebook.set_border_width(0)

        # When the user switches between notebook pages, scroll the visible
        #   page's textview to the bottom (otherwise it gets confusing)
        self.output_notebook.connect(
            'switch-page',
            self.on_output_notebook_switch_page,
        )


    def setup_errors_tab(self):

        """Called by self.setup_win().

        Creates widgets for the Errors Tab.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 1380 setup_errors_tab')

        vbox = Gtk.VBox()
        self.errors_tab.pack_start(vbox, True, True, 0)

        # Errors List
        self.errors_list_scrolled = Gtk.ScrolledWindow()
        vbox.pack_start(self.errors_list_scrolled, True, True, 0)
        self.errors_list_scrolled.set_policy(
            Gtk.PolicyType.AUTOMATIC,
            Gtk.PolicyType.AUTOMATIC,
        )

        self.errors_list_frame = Gtk.Frame()
        self.errors_list_scrolled.add_with_viewport(self.errors_list_frame)

        self.errors_list_treeview = Gtk.TreeView()
        self.errors_list_frame.add(self.errors_list_treeview)
        self.errors_list_treeview.set_can_focus(False)

        for i, column_title in enumerate(['', '', 'Time', 'Media', 'Message']):

            if not column_title:
                renderer_pixbuf = Gtk.CellRendererPixbuf()
                column_pixbuf = Gtk.TreeViewColumn(
                    '',
                    renderer_pixbuf,
                    pixbuf=i,
                )
                self.errors_list_treeview.append_column(column_pixbuf)

            else:
                renderer_text = Gtk.CellRendererText()
                column_text = Gtk.TreeViewColumn(
                    column_title,
                    renderer_text,
                    text=i,
                )
                self.errors_list_treeview.append_column(column_text)

        self.errors_list_liststore = Gtk.ListStore(
            GdkPixbuf.Pixbuf, GdkPixbuf.Pixbuf,
            str, str, str,
        )
        self.errors_list_treeview.set_model(self.errors_list_liststore)

        # Strip of widgets at the bottom

        hbox = Gtk.HBox()
        vbox.pack_start(hbox, False, False, self.spacing_size)
        hbox.set_border_width(self.spacing_size)

        self.error_list_button = Gtk.Button()
        hbox.pack_end(self.error_list_button, False, False, 0)
        self.error_list_button.set_label('Clear the list')
        self.error_list_button.connect(
            'clicked',
            self.on_errors_list_clear,
        )


    # (Moodify main window widgets)


    def sensitise_operation_widgets(self, sens_flag, \
    refresh_update_flag=False):

        """Called by mainapp.TartubeApp.download_manager_start(),
        .download_manager_finished(), self.modify_operation_widgets(),
        .modify_widgets_in_update_operation() and
        .modify_widgets_in_refresh_operation().

        (De)sensitises widgets that must not be sensitised during a download,
        update or refresh operation.

        Args:

            sens_flag (True or False): False to desensitise widget at the start
                of an operation, True to re-sensitise widgets at the end of the
                operation

            refresh_update_flag (True, False or None): True when called by
                self.modify_widgets_in_update_operation() or
                self.modify_widgets_in_refresh_operation(), False (or None)
                when called by anything else

        """

        if DEBUG_FUNC_FLAG:
            print('mw 1461 sensitise_operation_widgets')

        self.system_prefs_menu_item.set_sensitive(sens_flag)
        self.gen_options_menu_item.set_sensitive(sens_flag)
        self.export_db_menu_item.set_sensitive(sens_flag)
        self.import_db_menu_item.set_sensitive(sens_flag)
        self.check_all_menu_item.set_sensitive(sens_flag)

        if not self.app_obj.disable_dl_all_flag:
            self.download_all_menu_item.set_sensitive(sens_flag)
        else:
            self.download_all_menu_item.set_sensitive(False)

        self.refresh_db_menu_item.set_sensitive(sens_flag)
        self.check_all_toolbutton.set_sensitive(sens_flag)

        if not self.app_obj.disable_dl_all_flag:
            self.download_all_toolbutton.set_sensitive(sens_flag)
        else:
            self.download_all_toolbutton.set_sensitive(False)

        if not __main__.__debian_install_flag__:
            self.update_ytdl_menu_item.set_sensitive(sens_flag)

        # (The 'Add videos', 'Add channel' etc menu items/buttons are
        #   sensitised during a download operation, but desensitised during an
        #   update/refresh operation)
        if refresh_update_flag:
            self.add_video_menu_item.set_sensitive(sens_flag)
            self.add_channel_menu_item.set_sensitive(sens_flag)
            self.add_playlist_menu_item.set_sensitive(sens_flag)
            self.add_folder_menu_item.set_sensitive(sens_flag)
            self.add_video_toolbutton.set_sensitive(sens_flag)
            self.add_channel_toolbutton.set_sensitive(sens_flag)
            self.add_playlist_toolbutton.set_sensitive(sens_flag)
            self.add_folder_toolbutton.set_sensitive(sens_flag)

        # (The 'Save database' menu item must remain desensitised if file load/
        #   save is disabled)
        if not self.app_obj.disable_load_save_flag:
            self.save_db_menu_item.set_sensitive(sens_flag)

        # (The 'Stop' button/menu item are only sensitised during a download/
        #   update/refresh operation)
        if not sens_flag:
            self.stop_operation_menu_item.set_sensitive(True)
            self.stop_operation_toolbutton.set_sensitive(True)
        else:
            self.stop_operation_menu_item.set_sensitive(False)
            self.stop_operation_toolbutton.set_sensitive(False)


    def modify_widgets_in_update_operation(self, finish_flag, \
    ffmpeg_flag=False):

        """Called by mainapp.TartubeApp.update_manager_start() and
        .update_manager_finished().

        Modify and de(sensitise) widgets during an update operation.

        Args:

            finish_flag (True or False): False at the start of the update
                operation, True at the end of it

            ffmpeg_flag (bool): True when called by .update_manager_start() to
                install FFmpeg. Otherwise False

        """

        if DEBUG_FUNC_FLAG:
            print('mw 1515 modify_widgets_in_update_operation')

        # Remove existing widgets. In previous code, we simply changed the
        #   label on on self.check_media_button, but this causes frequent
        #   crashes
        # Get around the crashes by destroying the old widgets and creating new
        #   ones
        self.button_box.remove(self.check_media_button)
        self.check_media_button = None
        self.button_box.remove(self.download_media_button)
        self.download_media_button = None

        # Add replacement widgets
        self.check_media_button = Gtk.Button()
        self.button_box.pack_start(self.check_media_button, True, True, 0)
        self.check_media_button.set_action_name('app.check_all_button')

        self.download_media_button = Gtk.Button()
        self.button_box.pack_start(self.download_media_button, True, True, 0)
        self.download_media_button.set_action_name('app.download_all_button')

        if not finish_flag:

            if ffmpeg_flag:
                self.check_media_button.set_label('Installing')
                self.download_media_button.set_label('FFmpeg')
            else:
                self.check_media_button.set_label('Updating')
                self.download_media_button.set_label('youtube-dl')

            self.check_media_button.set_sensitive(False)
            self.download_media_button.set_sensitive(False)

            self.sensitise_operation_widgets(False, True)

        else:
            self.check_media_button.set_label('Check all')
            self.check_media_button.set_sensitive(True)
            self.check_media_button.set_tooltip_text(
                'Check all videos, channels, playlists and folders',
            )

            self.download_media_button.set_label('Download all')

            self.download_media_button.set_tooltip_text(
                'Download all videos, channels, playlists and folders',
            )

            if not self.app_obj.disable_dl_all_flag:
                self.download_media_button.set_sensitive(True)
            else:
                self.download_media_button.set_sensitive(False)

            self.sensitise_operation_widgets(True, True)

        # Make the widget changes visible
        self.show_all()


    def modify_widgets_in_refresh_operation(self, finish_flag):

        """Called by mainapp.TartubeApp.refresh_manager_start() and
        .refresh_manager_finished().

        Modify and de(sensitise) widgets during a refresh operation.

        Args:

            finish_flag (True or False): False at the start of the refresh
                operation, True at the end of it

        """

        if DEBUG_FUNC_FLAG:
            print('mw 1584 modify_widgets_in_refresh_operation')

        # Remove existing widgets. In previous code, we simply changed the
        #   label on on self.check_media_button, but this causes frequent
        #   crashes
        # Get around the crashes by destroying the old widgets and creating new
        #   ones
        self.button_box.remove(self.check_media_button)
        self.check_media_button = None
        self.button_box.remove(self.download_media_button)
        self.download_media_button = None

        # Add replacement widgets
        self.check_media_button = Gtk.Button()
        self.button_box.pack_start(self.check_media_button, True, True, 0)
        self.check_media_button.set_action_name('app.check_all_button')

        self.download_media_button = Gtk.Button()
        self.button_box.pack_start(self.download_media_button, True, True, 0)
        self.download_media_button.set_action_name('app.download_all_button')

        if not finish_flag:

            self.check_media_button.set_label('Refreshing')
            self.check_media_button.set_sensitive(False)

            self.download_media_button.set_label('database')
            self.download_media_button.set_sensitive(False)

            self.sensitise_operation_widgets(False, True)

        else:
            self.check_media_button.set_label('Check all')
            self.check_media_button.set_sensitive(True)
            self.check_media_button.set_tooltip_text(
                'Check all videos, channels, playlists and folders',
            )

            self.download_media_button.set_label('Download all')
            self.download_media_button.set_tooltip_text(
                'Download all videos, channels, playlists and folders',
            )

            if not self.app_obj.disable_dl_all_flag:
                self.download_media_button.set_sensitive(True)
            else:
                self.download_media_button.set_sensitive(False)

            self.sensitise_operation_widgets(True, True)

        # Make the widget changes visible
        self.show_all()


    def redraw_main_toolbar(self):

        """Called by mainapp.TartubeApp.set_toolbar_squeeze_flag() when the
        value of the flag is changed.

        Redraws the main toolbar, with or without labels, depending on the
        value of the flag.

        """

        if DEBUG_FUNC_FLAG:
            print('mw 1648 redraw_main_toolbar')

        self.setup_main_toolbar()

        if self.app_obj.disable_dl_all_flag:
            self.download_all_menu_item.set_sensitive(False)

        self.show_all()


    def show_progress_bar(self, force_sim_flag=False):

        """Called by mainapp.TartubeApp.download_manager_start().

        At the start of a download operation, replace
        self.download_media_button with a progress bar (and a label just above
        it).

        Args:

            force_sim_flag (True/False): True if playlists/channels are to be
                checked for new videos, without downloading anything. False if
                videos are to be downloaded (or not) depending on each media
                data object's .dl_sim_flag IV

        """

        if DEBUG_FUNC_FLAG:
            print('mw 1672 show_progress_bar')

        if self.progress_bar:
            return self.app_obj.system_error(
                201,
                'Videos Tab progress bar is already visible',
            )

        # Remove existing widgets. In previous code, we simply changed the
        #   label on on self.check_media_button, but this causes frequent
        #   crashes
        # Get around the crashes by destroying the old widgets and creating new
        #   ones
        self.button_box.remove(self.check_media_button)
        self.check_media_button = None
        self.button_box.remove(self.download_media_button)
        self.download_media_button = None

        # Add replacement widgets
        self.check_media_button = Gtk.Button()
        self.button_box.pack_start(self.check_media_button, True, True, 0)
        self.check_media_button.set_action_name('app.check_all_button')
        self.check_media_button.set_sensitive(False)
        if force_sim_flag:
            self.check_media_button.set_label('Checking...')
        else:
            self.check_media_button.set_label('Downloading...')

        # (Put the progress bar inside a box, so it doesn't touch the divider,
        #   because that doesn't look nice)
        self.progress_box = Gtk.HBox()
        self.button_box.pack_start(
            self.progress_box,
            True,
            True,
            (self.spacing_size * 2),
        )

        self.progress_bar = Gtk.ProgressBar()
        self.progress_box.pack_start(
            self.progress_bar,
            True,
            True,
            (self.spacing_size * 2),
        )
        self.progress_bar.set_fraction(0)
        self.progress_bar.set_show_text(True)
        if force_sim_flag:
            self.progress_bar.set_text('Checking...')
        else:
            self.progress_bar.set_text('Downloading...')

        # Make the changes visible
        self.button_box.show_all()


    def hide_progress_bar(self):

        """Called by mainapp.TartubeApp.download_manager_finished().

        At the end of a download operation, replace self.progress_list with the
        original button.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 1736 hide_progress_bar')

        if not self.progress_bar:
            return self.app_obj.system_error(
                202,
                'Videos Tab progress bar is not already visible',
            )

        # Remove existing widgets. In previous code, we simply changed the
        #   label on on self.check_media_button, but this causes frequent
        #   crashes
        # Get around the crashes by destroying the old widget and creating a
        #   new one
        self.button_box.remove(self.check_media_button)
        self.check_media_button = None
        self.button_box.remove(self.progress_box)
        self.progress_box = None
        self.progress_bar = None

        # Add replacement widgets
        self.check_media_button = Gtk.Button()
        self.button_box.pack_start(self.check_media_button, True, True, 0)
        self.check_media_button.set_label('Check all')
        self.check_media_button.set_tooltip_text(
            'Check all videos, channels, playlists and folders',
        )
        self.check_media_button.set_action_name('app.check_all_button')

        self.download_media_button = Gtk.Button()
        self.button_box.pack_start(self.download_media_button, True, True, 0)
        self.download_media_button.set_label('Download all')
        self.download_media_button.set_tooltip_text(
            'Download all videos, channels, playlists and folders',
        )
        self.download_media_button.set_action_name('app.download_all_button')

        # (For some reason, the button must be desensitised after setting the
        #   action name)
        if not self.app_obj.disable_dl_all_flag:
            self.download_media_button.set_sensitive(True)
        else:
            self.download_media_button.set_sensitive(False)

        # Make the changes visible
        self.button_box.show_all()


    def update_progress_bar(self, text, count, total):

        """Called by downloads.DownloadManager.run().

        During a download operation, updates the progress bar just below the
        Video Index.

        Args:

            text (string): The text of the progress bar's label, matching the
                name of the media data object which has just been passed to
                youtube-dl

            count (int): The number of media data objects passed to youtube-dl
                so far. Note that a channel or a playlist counts as one media
                data object, as far as youtube-dl is concerned

            total (int): The total number of media data objects to be passed
                to youtube-dl

        """

        if DEBUG_FUNC_FLAG:
            print('mw 1805 update_progress_bar')

        if not self.progress_bar:
            return self.app_obj.system_error(
                203,
                'Videos Tab progress bar is missing and cannot be updated',
            )

        # (The 0.5 guarantees that the progress bar is never empty. If
        #   downloading a single video, the progress bar is half full. If
        #   downloading the first out of 3 videos, it is 16% full, and so on)
        self.progress_bar.set_fraction(float(count - 0.5) / total)
        self.progress_bar.set_text(
            utils.shorten_string(text, self.short_string_max_len) \
            + ' ' + str(count) + '/' + str(total)
        )


    def enable_tooltips(self, update_catalogue_flag=False):

        """Called by mainapp.TartubeApp.start() and .set_show_tooltips_flag().

        Enables tooltips in the Video Index and Video Catalogue (only).

        Args:

            update_catalogue_flag (bool): True when called by
                .set_show_tooltips_flag(), in which case the Video Catalogue
                must be redrawn

        """

        if DEBUG_FUNC_FLAG:
            print('mw 1841 enable_tooltips')

        self.video_index_treeview.set_tooltip_column(2)
        if update_catalogue_flag:
            self.video_catalogue_redraw_all(
                self.video_index_current,
                self.catalogue_toolbar_current_page,
            )


    def disable_tooltips(self, update_catalogue_flag=False):

        """Called by mainapp.TartubeApp.start() and .set_show_tooltips_flag().

        Disables tooltips in the Video Index and Video Catalogue (only).

        Args:

            update_catalogue_flag (bool): True when called by
                .set_show_tooltips_flag(), in which case the Video Catalogue
                must be redrawn

        """

        if DEBUG_FUNC_FLAG:
            print('mw 1866 disable_tooltips')

        self.video_index_treeview.set_tooltip_column(-1)
        if update_catalogue_flag:
            self.video_catalogue_redraw_all(
                self.video_index_current,
                self.catalogue_toolbar_current_page,
            )


    def enable_dl_all_buttons(self):

        """Called by mainapp.TartubeApp.set_disable_dl_all_flag().

        Enables (sensitises) the 'Download all' buttons and menu items.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 1884 enable_dl_all_buttons')

        # This setting doesn't apply during a download/update/refresh
        #   operation
        if not self.app_obj.current_manager_obj:
            self.download_all_menu_item.set_sensitive(True)
            self.download_all_toolbutton.set_sensitive(True)
            self.download_media_button.set_sensitive(True)


    def disable_dl_all_buttons(self):

        """Called by mainapp.TartubeApp.load_config() and
        set_disable_dl_all_flag().

        Disables (desensitises) the 'Download all' buttons and menu items.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 1903 move_container')

        # This setting doesn't apply during a download/update/refresh
        #   operation
        if not self.app_obj.current_manager_obj:
            self.download_all_menu_item.set_sensitive(False)
            self.download_all_toolbutton.set_sensitive(False)
            self.download_media_button.set_sensitive(False)


    def set_video_res_limit(self, resolution):

        """Called by mainapp.TartubeApp.load_config() and
        self.setup_progress_tab().

        Sets a new video resolution limit. Updates the combobox in the
        Progress Tab, and calls the main application to update its IV.

        Args:

            resolution (str): The new progressive scan resolution; a key in
                formats.VIDEO_RESOLUTION_DICT (e.g. '720p'), or None to use the
                default resolution limit specified by
                formats.VIDEO_RESOLUTION_DEFAULT.

        """

        # Check it's a recognised value
        if not resolution in formats.VIDEO_RESOLUTION_LIST:
            resolution = formats.VIDEO_RESOLUTION_DEFAULT

        self.video_res_combobox.set_active(
            formats.VIDEO_RESOLUTION_LIST.index(resolution),
        )

        self.app_obj.set_video_res_default(resolution)


    # (Auto-sort functions for main window widgets)


    def video_index_auto_sort(self, treestore, row_iter1, row_iter2, data):

        """Sorting function created by self.videos_tab.

        Automatically sorts rows in the Video Index.

        Args:

            treestore (Gtk.TreeStore): Rows in the Video Index are stored in
                this treestore.

            row_iter1, row_iter2 (Gtk.TreeIter): Iters pointing at two rows
                in the treestore, one of which must be sorted before the other

            data (None): Ignored

        Returns:
            -1 if row_iter1 comes before row_iter2, 1 if row_iter2 comes before
                row_iter1, 0 if their order should not be changed

        """

        if DEBUG_FUNC_FLAG:
            print('mw 1924 video_index_auto_sort')

        # If auto-sorting is disabled temporarily, we can prevent the list
        #   being sorted by returning -1 for all cases
        if self.video_index_no_sort_flag:
            return -1

        # Get the names of the media data objects on each row
        sort_column, sort_type \
        = self.video_index_sortmodel.get_sort_column_id()
        name1 = treestore.get_value(row_iter1, sort_column)
        name2 = treestore.get_value(row_iter2, sort_column)

        # Get corresponding media data objects
        id1 = self.app_obj.media_name_dict[name1]
        obj1 = self.app_obj.media_reg_dict[id1]

        id2 = self.app_obj.media_name_dict[name2]
        obj2 = self.app_obj.media_reg_dict[id2]

        # Do sort. Treat media.Channel and media.Playlist objects as the same
        #   type of thing, so that all folders appear first (sorted
        #   alphabetically), followed by all channels/playlists (sorted
        #   alphabetically)
        if str(obj1.__class__) == str(obj2.__class__) \
        or (
            isinstance(obj1, media.GenericRemoteContainer) \
            and isinstance(obj2, media.GenericRemoteContainer)
        ):
            # Private folders are shown first, then (public) fixed folders,
            #   then user-created folders
            if isinstance(obj1, media.Folder):
                if obj1.priv_flag and not obj2.priv_flag:
                    return -1
                elif not obj1.priv_flag and obj2.priv_flag:
                    return 1
                elif obj1.fixed_flag and not obj2.fixed_flag:
                    return -1
                elif not obj1.fixed_flag and obj2.fixed_flag:
                    return 1

            # Media data objects can't have the same name, but they might have
            #   the same nickname
            # If two nicknames both start with an index, e.g. '1 Music' and
            #   '11 Comedy' then make sure the one with the lowest index comes
            #   first
            index1_list = re.findall(r'^(\d+)', obj1.nickname)
            index2_list = re.findall(r'^(\d+)', obj2.nickname)
            if index1_list and index2_list:
                if int(index1_list[0]) < int(index2_list[0]):
                    return -1
                else:
                    return 1
            elif obj1.nickname.lower() < obj2.nickname.lower():
                return -1
            else:
                return 1

        else:

            # (Folders displayed first, channels/playlists next, and of course
            #   videos aren't displayed here at all)
            if isinstance(obj1, media.Folder):
                return -1
            elif isinstance(obj2, media.Folder):
                return 1
            else:
                return 0


    def video_catalogue_auto_sort(self, row1, row2, data, notify):

        """Sorting function created by self.videos_tab.

        Automatically sorts rows in the Video Catalogue.

        Args:

            row1, row2 (mainwin.CatalogueRow): Two rows in the liststore, one
                of which must be sorted before the other

            data (None): Ignored

            notify (False): Ignored

        Returns:
            -1 if row1 comes before row2, 1 if row2 comes before row1, 0 if
                their order should not be changed

        """

        if DEBUG_FUNC_FLAG:
            print('mw 2016 video_catalogue_auto_sort')

        # Get the media.Video objects displayed on each row
        obj1 = row1.video_obj
        obj2 = row2.video_obj

        # Sort videos by playlist index (if set), then by upload time, and then
        #   by receive (download) time
        # The video's index is not relevant unless sorting a playlist (and not
        #   relevant in private folders, e.g. 'All Videos')
        if isinstance(obj1.parent_obj, media.Playlist) \
        and not self.video_index_current_priv_flag \
        and obj1.parent_obj == obj2.parent_obj \
        and obj1.index is not None and obj2.index is not None:
            if obj1.index < obj2.index:
                return -1
            else:
                return 1
        elif obj1.upload_time is not None and obj2.upload_time is not None:
            if obj1.upload_time > obj2.upload_time:
                return -1
            elif obj1.upload_time < obj2.upload_time:
                return 1
            elif obj1.receive_time is not None \
            and obj2.receive_time is not None:
                # In private folders, the most recently received video goes to
                #   the top of the list
                if self.video_index_current_priv_flag:
                    if obj1.receive_time > obj2.receive_time:
                        return -1
                    elif obj1.receive_time < obj2.receive_time:
                        return 1
                    else:
                        return 0
                # ...but for everything else, the sorting algorithm is the same
                #   as for media.GenericRemoteContainer.do_sort(), in which we
                #   assume the website is sending us videos, newest first
                else:
                    if obj1.receive_time < obj2.receive_time:
                        return -1
                    elif obj1.receive_time > obj2.receive_time:
                        return 1
                    else:
                        return 0
            else:
                return 0
        else:
            return 0


    # (Popup menu functions for main window widgets)


    def video_index_popup_menu(self, event, name):

        """Called by self.video_index_treeview_click_event().

        When the user right-clicks on the Video Index, show a context-sensitive
        popup menu.

        Args:

            event (Gdk.EventButton): The mouse click event

            name (string): The name of the clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 2085 video_index_popup_menu')

        # Find the right-clicked media data object (and a string to describe
        #   its type)
        dbid = self.app_obj.media_name_dict[name]
        media_data_obj = self.app_obj.media_reg_dict[dbid]

        if isinstance(media_data_obj, media.Channel):
            media_type = 'channel'
        elif isinstance(media_data_obj, media.Playlist):
            media_type = 'playlist'
        else:
            media_type = 'folder'

        # Set up the popup menu
        popup_menu = Gtk.Menu()

        # Check/download/refresh items
        check_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Check ' + media_type,
        )
        check_menu_item.connect(
            'activate',
            self.on_video_index_check,
            media_data_obj,
        )
        if self.app_obj.current_manager_obj \
        or (
            isinstance(media_data_obj, media.Folder) \
            and media_data_obj.priv_flag
        ):
            check_menu_item.set_sensitive(False)
        popup_menu.append(check_menu_item)

        download_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Download ' + media_type,
        )
        download_menu_item.connect(
            'activate',
            self.on_video_index_download,
            media_data_obj,
        )
        if self.app_obj.current_manager_obj \
        or (
            isinstance(media_data_obj, media.Folder) \
            and media_data_obj.priv_flag
        ):
            download_menu_item.set_sensitive(False)
        popup_menu.append(download_menu_item)

        refresh_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Refresh ' + media_type,
        )
        refresh_menu_item.connect(
            'activate',
            self.on_video_index_refresh,
            media_data_obj,
        )
        if self.app_obj.current_manager_obj \
        or (
            isinstance(media_data_obj, media.Folder) \
            and media_data_obj.priv_flag
        ):
            refresh_menu_item.set_sensitive(False)
        popup_menu.append(refresh_menu_item)

        # Separator
        popup_menu.append(Gtk.SeparatorMenuItem())

        # Contents
        contents_submenu = Gtk.Menu()

        if not isinstance(media_data_obj, media.Folder):

            self.video_index_setup_contents_submenu(
                contents_submenu,
                media_data_obj,
                False,
            )

        else:

            # All contents
            all_contents_submenu = Gtk.Menu()

            self.video_index_setup_contents_submenu(
                all_contents_submenu,
                media_data_obj,
                False,
            )

            # Separator
            all_contents_submenu.append(Gtk.SeparatorMenuItem())

            empty_folder_menu_item = Gtk.MenuItem.new_with_mnemonic(
                '_Empty folder',
            )
            empty_folder_menu_item.connect(
                'activate',
                self.on_video_index_empty_folder,
                media_data_obj,
            )
            all_contents_submenu.append(empty_folder_menu_item)
            if not media_data_obj.child_list or media_data_obj.priv_flag:
                empty_folder_menu_item.set_sensitive(False)

            all_contents_menu_item = Gtk.MenuItem.new_with_mnemonic(
                '_All contents',
            )
            all_contents_menu_item.set_submenu(all_contents_submenu)
            contents_submenu.append(all_contents_menu_item)

            # Just folder videos
            just_videos_submenu = Gtk.Menu()

            self.video_index_setup_contents_submenu(
                just_videos_submenu,
                media_data_obj,
                True,
            )

            # Separator
            just_videos_submenu.append(Gtk.SeparatorMenuItem())

            empty_videos_menu_item = Gtk.MenuItem.new_with_mnemonic(
                '_Remove videos',
            )
            empty_videos_menu_item.connect(
                'activate',
                self.on_video_index_remove_videos,
                media_data_obj,
            )
            just_videos_submenu.append(empty_videos_menu_item)
            if not media_data_obj.child_list or media_data_obj.priv_flag:
                empty_videos_menu_item.set_sensitive(False)

            just_videos_menu_item = Gtk.MenuItem.new_with_mnemonic(
                '_Just folder videos',
            )
            just_videos_menu_item.set_submenu(just_videos_submenu)
            contents_submenu.append(just_videos_menu_item)

        contents_menu_item = Gtk.MenuItem.new_with_mnemonic(
            utils.upper_case_first(media_type) + ' co_ntents',
        )
        contents_menu_item.set_submenu(contents_submenu)
        popup_menu.append(contents_menu_item)

        # Actions
        actions_submenu = Gtk.Menu()

        move_top_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Move to _top level',
        )
        move_top_menu_item.connect(
            'activate',
            self.on_video_index_move_to_top,
            media_data_obj,
        )
        actions_submenu.append(move_top_menu_item)
        if not media_data_obj.parent_obj \
        or self.app_obj.current_manager_obj:
            move_top_menu_item.set_sensitive(False)

        # Separator
        actions_submenu.append(Gtk.SeparatorMenuItem())

        if isinstance(media_data_obj, media.Folder):

            hide_folder_menu_item = Gtk.MenuItem.new_with_mnemonic(
                '_Hide folder',
            )
            hide_folder_menu_item.connect(
                'activate',
                self.on_video_index_hide_folder,
                media_data_obj,
            )
            actions_submenu.append(hide_folder_menu_item)

        set_nickname_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Set _nickname...',
        )
        set_nickname_menu_item.connect(
            'activate',
            self.on_video_index_set_nickname,
            media_data_obj,
        )
        actions_submenu.append(set_nickname_menu_item)
        if isinstance(media_data_obj, media.Folder) \
        and media_data_obj.priv_flag:
            set_nickname_menu_item.set_sensitive(False)

        set_destination_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Set _download destination...',
        )
        set_destination_menu_item.connect(
            'activate',
            self.on_video_index_set_destination,
            media_data_obj,
        )
        actions_submenu.append(set_destination_menu_item)
        if isinstance(media_data_obj, media.Folder) \
        and media_data_obj.fixed_flag:
            set_destination_menu_item.set_sensitive(False)

        # Separator
        actions_submenu.append(Gtk.SeparatorMenuItem())

        export_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Export ' + media_type + '...',
        )
        export_menu_item.connect(
            'activate',
            self.on_video_index_export,
            media_data_obj,
        )
        actions_submenu.append(export_menu_item)
        if self.app_obj.current_manager_obj:
            export_menu_item.set_sensitive(False)

        actions_menu_item = Gtk.MenuItem.new_with_mnemonic(
            utils.upper_case_first(media_type) + ' _actions',
        )
        actions_menu_item.set_submenu(actions_submenu)
        popup_menu.append(actions_menu_item)

        # Apply/remove/edit download options, disable downloads
        downloads_submenu = Gtk.Menu()

        # (Desensitise these menu items, if an edit window is already open)
        no_options_flag = False
        for win_obj in self.config_win_list:
            if isinstance(win_obj, config.OptionsEditWin) \
            and media_data_obj.options_obj == win_obj.edit_obj:
                no_options_flag = True
                break

        if not media_data_obj.options_obj:

            apply_options_menu_item = Gtk.MenuItem.new_with_mnemonic(
                'Apply download _options...',
            )
            apply_options_menu_item.connect(
                'activate',
                self.on_video_index_apply_options,
                media_data_obj,
            )
            downloads_submenu.append(apply_options_menu_item)
            if no_options_flag or self.app_obj.current_manager_obj \
            or (
                isinstance(media_data_obj, media.Folder)
                and media_data_obj.priv_flag
            ):
                apply_options_menu_item.set_sensitive(False)

        else:

            remove_options_menu_item = Gtk.MenuItem.new_with_mnemonic(
                'Remove download _options',
            )
            remove_options_menu_item.connect(
                'activate',
                self.on_video_index_remove_options,
                media_data_obj,
            )
            downloads_submenu.append(remove_options_menu_item)
            if no_options_flag or self.app_obj.current_manager_obj \
            or (
                isinstance(media_data_obj, media.Folder)
                and media_data_obj.priv_flag
            ):
                remove_options_menu_item.set_sensitive(False)

        edit_options_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Edit download options...',
        )
        edit_options_menu_item.connect(
            'activate',
            self.on_video_index_edit_options,
            media_data_obj,
        )
        downloads_submenu.append(edit_options_menu_item)
        if no_options_flag or self.app_obj.current_manager_obj \
        or not media_data_obj.options_obj:
            edit_options_menu_item.set_sensitive(False)

        # Separator
        downloads_submenu.append(Gtk.SeparatorMenuItem())

        disable_menu_item = Gtk.CheckMenuItem.new_with_mnemonic(
            'D_isable checking/downloading',
        )
        disable_menu_item.set_active(media_data_obj.dl_disable_flag)
        disable_menu_item.connect(
            'activate',
            self.on_video_index_dl_disable,
            media_data_obj,
        )
        downloads_submenu.append(disable_menu_item)
        # (Widget sensitivity set below)

        enforce_check_menu_item = Gtk.CheckMenuItem.new_with_mnemonic(
            '_Just disable downloading',
        )
        enforce_check_menu_item.set_active(media_data_obj.dl_sim_flag)
        enforce_check_menu_item.connect(
            'activate',
            self.on_video_index_enforce_check,
            media_data_obj,
        )
        downloads_submenu.append(enforce_check_menu_item)
        if self.app_obj.current_manager_obj or media_data_obj.dl_disable_flag \
        or (
            isinstance(media_data_obj, media.Folder) \
            and media_data_obj.fixed_flag
        ):
            enforce_check_menu_item.set_sensitive(False)

        # (Widget sensitivity from above)
        if self.app_obj.current_manager_obj \
        or (
            isinstance(media_data_obj, media.Folder) \
            and media_data_obj.fixed_flag
        ):
            disable_menu_item.set_sensitive(False)
            enforce_check_menu_item.set_sensitive(False)

        downloads_menu_item = Gtk.MenuItem.new_with_mnemonic('_Downloads')
        downloads_menu_item.set_submenu(downloads_submenu)
        popup_menu.append(downloads_menu_item)

        # Filesystem
        filesystem_submenu = Gtk.Menu()

        show_location_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Show default location',
        )
        show_location_menu_item.connect(
            'activate',
            self.on_video_index_show_location,
            media_data_obj,
        )
        filesystem_submenu.append(show_location_menu_item)
        if isinstance(media_data_obj, media.Folder) \
        and media_data_obj.priv_flag:
            show_location_menu_item.set_sensitive(False)

        rename_location_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Rename default location...',
        )
        rename_location_menu_item.connect(
            'activate',
            self.on_video_index_rename_location,
            media_data_obj,
        )
        filesystem_submenu.append(rename_location_menu_item)
        if self.app_obj.current_manager_obj or self.config_win_list \
        or (
            isinstance(media_data_obj, media.Folder) \
            and media_data_obj.fixed_flag
        ):
            rename_location_menu_item.set_sensitive(False)

        # Separator
        filesystem_submenu.append(Gtk.SeparatorMenuItem())

        show_destination_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Show download destination',
        )
        show_destination_menu_item.connect(
            'activate',
            self.on_video_index_show_destination,
            media_data_obj,
        )
        filesystem_submenu.append(show_destination_menu_item)
        if isinstance(media_data_obj, media.Folder) \
        and media_data_obj.priv_flag:
            show_destination_menu_item.set_sensitive(False)

        filesystem_menu_item = Gtk.MenuItem.new_with_mnemonic('_Filesystem')
        filesystem_menu_item.set_submenu(filesystem_submenu)
        popup_menu.append(filesystem_menu_item)

        # Separator
        popup_menu.append(Gtk.SeparatorMenuItem())

        show_properties_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Show _properties...',
        )
        show_properties_menu_item.connect(
            'activate',
            self.on_video_index_show_properties,
            media_data_obj,
        )
        popup_menu.append(show_properties_menu_item)
        if self.app_obj.current_manager_obj:
            show_properties_menu_item.set_sensitive(False)

        # Separator
        popup_menu.append(Gtk.SeparatorMenuItem())

        # Delete items
        delete_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'De_lete ' + media_type,
        )
        delete_menu_item.connect(
            'activate',
            self.on_video_index_delete_container,
            media_data_obj,
        )
        if self.app_obj.current_manager_obj:
            delete_menu_item.set_sensitive(False)
        popup_menu.append(delete_menu_item)

        # Create the popup menu
        popup_menu.show_all()
        popup_menu.popup(None, None, None, None, event.button, event.time)


    def video_catalogue_popup_menu(self, event, video_obj):

        """Called by mainwin.SimpleCatalogueItem.on_right_click() and
        mainwin.ComplexCatalogueItem.on_right_click().

        When the user right-clicks on the Video Catalogue, show a context-
        sensitive popup menu.

        Args:

            event (Gdk.EventButton): The mouse click event

            video_obj (media.Video): The video object displayed in the clicked
                row

        """

        if DEBUG_FUNC_FLAG:
            print('mw 2522 video_catalogue_popup_menu')

        # Use a different popup menu for multiple selected rows
        # Because of Gtk weirdness, check that the clicked row is actually
        #   one of those selected
        catalogue_item_obj = self.video_catalogue_dict[video_obj.dbid]
        row_list = self.catalogue_listbox.get_selected_rows()
        if catalogue_item_obj.catalogue_row in row_list \
        and len(row_list) > 1:

            return self.video_catalogue_multi_popup_menu(event, row_list)

        else:

            # Otherwise, right-clicking a row selects (and unselects everything
            #   else)
            self.catalogue_listbox.unselect_all()
            self.catalogue_listbox.select_row(catalogue_item_obj.catalogue_row)

        # Set up the popup menu
        popup_menu = Gtk.Menu()

        # Check/download videos
        check_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Check video'
        )
        check_menu_item.connect(
            'activate',
            self.on_video_catalogue_check,
            video_obj,
        )
        if self.app_obj.current_manager_obj:
            check_menu_item.set_sensitive(False)
        popup_menu.append(check_menu_item)

        if not video_obj.dl_flag:

            download_menu_item = Gtk.MenuItem.new_with_mnemonic(
                '_Download video'
            )
            download_menu_item.connect(
                'activate',
                self.on_video_catalogue_download,
                video_obj,
            )
            if self.app_obj.current_manager_obj:
                download_menu_item.set_sensitive(False)
            popup_menu.append(download_menu_item)

        else:

            download_menu_item = Gtk.MenuItem.new_with_mnemonic(
                'Re-_download this video'
            )
            download_menu_item.connect(
                'activate',
                self.on_video_catalogue_re_download,
                video_obj,
            )
            if self.app_obj.current_manager_obj:
                download_menu_item.set_sensitive(False)
            popup_menu.append(download_menu_item)

        # Separator
        popup_menu.append(Gtk.SeparatorMenuItem())

        # Watch video
        self.add_watch_video_menu_items(popup_menu, video_obj)

        # Separator
        popup_menu.append(Gtk.SeparatorMenuItem())

        # New/favourite videos
        new_video_menu_item = Gtk.CheckMenuItem.new_with_mnemonic(
            'Video is _new',
        )
        new_video_menu_item.set_active(video_obj.new_flag)
        new_video_menu_item.connect(
            'toggled',
            self.on_video_catalogue_toggle_new_video,
            video_obj,
        )
        popup_menu.append(new_video_menu_item)
        if not video_obj.dl_flag:
            new_video_menu_item.set_sensitive(False)

        fav_video_menu_item = Gtk.CheckMenuItem.new_with_mnemonic(
            'Video is _favourite',
        )
        fav_video_menu_item.set_active(video_obj.fav_flag)
        fav_video_menu_item.connect(
            'toggled',
            self.on_video_catalogue_toggle_favourite_video,
            video_obj,
        )
        popup_menu.append(fav_video_menu_item)
        if not video_obj.dl_flag:
            fav_video_menu_item.set_sensitive(False)

        archive_video_menu_item = Gtk.CheckMenuItem.new_with_mnemonic(
            'Video is _archived',
        )
        archive_video_menu_item.set_active(video_obj.archive_flag)
        archive_video_menu_item.connect(
            'toggled',
            self.on_video_catalogue_toggle_archived_video,
            video_obj,
        )
        popup_menu.append(archive_video_menu_item)
        if not video_obj.dl_flag:
            archive_video_menu_item.set_sensitive(False)

        # Separator
        popup_menu.append(Gtk.SeparatorMenuItem())

        # Apply/remove/edit download options, disable downloads
        downloads_submenu = Gtk.Menu()

        # (Desensitise these menu items, if an edit window is already open)
        no_options_flag = False
        for win_obj in self.config_win_list:
            if isinstance(win_obj, config.OptionsEditWin) \
            and video_obj.options_obj == win_obj.edit_obj:
                no_options_flag = True
                break

        if not video_obj.options_obj:

            apply_options_menu_item = Gtk.MenuItem.new_with_mnemonic(
                'Apply download _options...',
            )
            apply_options_menu_item.connect(
                'activate',
                self.on_video_catalogue_apply_options,
                video_obj,
            )
            downloads_submenu.append(apply_options_menu_item)
            if no_options_flag or self.app_obj.current_manager_obj:
                apply_options_menu_item.set_sensitive(False)

        else:

            remove_options_menu_item = Gtk.MenuItem.new_with_mnemonic(
                'Remove download _options',
            )
            remove_options_menu_item.connect(
                'activate',
                self.on_video_catalogue_remove_options,
                video_obj,
            )
            downloads_submenu.append(remove_options_menu_item)
            if no_options_flag or self.app_obj.current_manager_obj:
                remove_options_menu_item.set_sensitive(False)

        edit_options_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Edit download options...',
        )
        edit_options_menu_item.connect(
            'activate',
            self.on_video_catalogue_edit_options,
            video_obj,
        )
        downloads_submenu.append(edit_options_menu_item)
        if no_options_flag or self.app_obj.current_manager_obj \
        or not video_obj.options_obj:
            edit_options_menu_item.set_sensitive(False)

        # Separator
        downloads_submenu.append(Gtk.SeparatorMenuItem())

        enforce_check_menu_item = Gtk.CheckMenuItem.new_with_mnemonic(
            'D_isable downloads',
        )
        enforce_check_menu_item.set_active(video_obj.dl_sim_flag)
        enforce_check_menu_item.connect(
            'activate',
            self.on_video_catalogue_enforce_check,
            video_obj,
        )
        downloads_submenu.append(enforce_check_menu_item)
        # (Don't allow the user to change the setting of
        #   media.Video.dl_sim_flag if the video is in a channel or playlist,
        #   since media.Channel.dl_sim_flag or media.Playlist.dl_sim_flag
        #   applies instead)
        if self.app_obj.current_manager_obj \
        or not isinstance(video_obj.parent_obj, media.Folder):
            enforce_check_menu_item.set_sensitive(False)

        downloads_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Downloads',
        )
        downloads_menu_item.set_submenu(downloads_submenu)
        popup_menu.append(downloads_menu_item)

        # Show properties
        show_properties_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Show _properties...',
        )
        show_properties_menu_item.connect(
            'activate',
            self.on_video_catalogue_show_properties,
            video_obj,
        )
        popup_menu.append(show_properties_menu_item)
        if self.app_obj.current_manager_obj:
            show_properties_menu_item.set_sensitive(False)

        # Separator
        popup_menu.append(Gtk.SeparatorMenuItem())

        # Delete video
        delete_menu_item = Gtk.MenuItem.new_with_mnemonic('De_lete video')
        delete_menu_item.connect(
            'activate',
            self.on_video_catalogue_delete_video,
            video_obj,
        )
        popup_menu.append(delete_menu_item)

        # Create the popup menu
        popup_menu.show_all()
        popup_menu.popup(None, None, None, None, event.button, event.time)


    def video_catalogue_multi_popup_menu(self, event, row_list):

        """Called by self.video_catalogue_popup_menu().

        When multiple rows are selected in the Video Catalogue and the user
        right-clicks one of them, show a context-sensitive popup menu.

        Args:

            event (Gdk.EventButton): The mouse click event

            row_list (list): List of mainwin.CatalogueRow objects that are
                currently selected (each one corresponding to a single
                media.Video object)

        """

        if DEBUG_FUNC_FLAG:
            print('mw 2779 video_catalogue_multi_popup_menu')

        # Convert row_list, a list of mainwin.CatalogueRow objects, into a
        #   list of media.Video objects
        video_list = []
        for row in row_list:
            video_list.append(row.video_obj)

        # So we can desensitise some menu items, work out in advance whether
        #   any of the selected videos are marked as downloaded, or have a
        #   source URL
        dl_flag = False
        for video_obj in video_list:
            if video_obj.dl_flag:
                dl_flag = True
                break

        not_dl_flag = False
        for video_obj in video_list:
            if not video_obj.dl_flag:
                not_dl_flag = True
                break

        source_flag = False
        for video_obj in video_list:
            if video_obj.source is not None:
                source_flag = True
                break

        # Set up the popup menu
        popup_menu = Gtk.Menu()

        # Check/download videos
        check_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Check videos'
        )
        check_menu_item.connect(
            'activate',
            self.on_video_catalogue_check_multi,
            video_list,
        )
        if self.app_obj.current_manager_obj:
            check_menu_item.set_sensitive(False)
        popup_menu.append(check_menu_item)

        download_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Download videos'
        )
        download_menu_item.connect(
            'activate',
            self.on_video_catalogue_download_multi,
            video_list,
        )
        if self.app_obj.current_manager_obj:
            download_menu_item.set_sensitive(False)
        popup_menu.append(download_menu_item)

        # Separator
        popup_menu.append(Gtk.SeparatorMenuItem())

        # Watch video in player/download and watch
        if not_dl_flag:

            dl_watch_menu_item = Gtk.MenuItem.new_with_mnemonic(
                'D_ownload and watch',
            )
            dl_watch_menu_item.connect(
                'activate',
                self.on_video_catalogue_dl_and_watch_multi,
                video_list,
            )
            popup_menu.append(dl_watch_menu_item)
            if not source_flag \
            or self.app_obj.update_manager_obj \
            or self.app_obj.refresh_manager_obj:
                dl_watch_menu_item.set_sensitive(False)

        else:

            watch_player_menu_item = Gtk.MenuItem.new_with_mnemonic(
                'Watch in _player',
            )
            watch_player_menu_item.connect(
                'activate',
                self.on_video_catalogue_watch_video_multi,
                video_list,
            )
            popup_menu.append(watch_player_menu_item)

        watch_website_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'W_atch on website',
        )
        watch_website_menu_item.connect(
            'activate',
            self.on_video_catalogue_watch_website_multi,
            video_list,
        )
        if not source_flag:
            watch_website_menu_item.set_sensitive(False)
        popup_menu.append(watch_website_menu_item)

        # Mark videos
        mark_videos_submenu = Gtk.Menu()

        new_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_New'
        )
        new_menu_item.connect(
            'activate',
            self.on_video_catalogue_toggle_new_video_multi,
            True,
            video_list,
        )
        if not dl_flag:
            new_menu_item.set_sensitive(False)
        mark_videos_submenu.append(new_menu_item)

        not_new_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Not n_ew'
        )
        not_new_menu_item.connect(
            'activate',
            self.on_video_catalogue_toggle_new_video_multi,
            False,
            video_list,
        )
        if not dl_flag:
            not_new_menu_item.set_sensitive(False)
        mark_videos_submenu.append(not_new_menu_item)

        # Separator
        mark_videos_submenu.append(Gtk.SeparatorMenuItem())

        fav_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Favourite'
        )
        fav_menu_item.connect(
            'activate',
            self.on_video_catalogue_toggle_favourite_video_multi,
            True,
            video_list,
        )
        if not dl_flag:
            fav_menu_item.set_sensitive(False)
        mark_videos_submenu.append(fav_menu_item)

        not_fav_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Not fa_vourite'
        )
        not_fav_menu_item.connect(
            'activate',
            self.on_video_catalogue_toggle_favourite_video_multi,
            False,
            video_list,
        )
        if not dl_flag:
            not_fav_menu_item.set_sensitive(False)
        mark_videos_submenu.append(not_fav_menu_item)

        # Separator
        mark_videos_submenu.append(Gtk.SeparatorMenuItem())

        archive_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Archived'
        )
        archive_menu_item.connect(
            'activate',
            self.on_video_catalogue_toggle_archived_video_multi,
            True,
            video_list,
        )
        if not dl_flag:
            archive_menu_item.set_sensitive(False)
        mark_videos_submenu.append(archive_menu_item)

        not_archive_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Not a_rchived'
        )
        not_archive_menu_item.connect(
            'activate',
            self.on_video_catalogue_toggle_archived_video_multi,
            False,
            video_list,
        )
        if not dl_flag:
            not_archive_menu_item.set_sensitive(False)
        mark_videos_submenu.append(not_archive_menu_item)

        mark_videos_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Mark videos',
        )
        mark_videos_menu_item.set_submenu(mark_videos_submenu)
        popup_menu.append(mark_videos_menu_item)

        # Separator
        popup_menu.append(Gtk.SeparatorMenuItem())

        # Show properties
        show_properties_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Show _properties...',
        )
        show_properties_menu_item.connect(
            'activate',
            self.on_video_catalogue_show_properties_multi,
            video_list,
        )
        popup_menu.append(show_properties_menu_item)
        if self.app_obj.current_manager_obj:
            show_properties_menu_item.set_sensitive(False)

        # Separator
        popup_menu.append(Gtk.SeparatorMenuItem())

        # Delete videos
        delete_menu_item = Gtk.MenuItem.new_with_mnemonic('De_lete videos')
        delete_menu_item.connect(
            'activate',
            self.on_video_catalogue_delete_video_multi,
            video_list,
        )
        popup_menu.append(delete_menu_item)

        # Create the popup menu
        popup_menu.show_all()
        popup_menu.popup(None, None, None, None, event.button, event.time)


    def progress_list_popup_menu(self, event, item_id):

        """Called by self.on_progress_list_right_click().

        When the user right-clicks on the Progress List, show a context-
        sensitive popup menu.

        Args:

            event (Gdk.EventButton): The mouse click event

            item_id (int): The .item_id of the clicked downloads.DownloadItem
                object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 3005 progress_list_popup_menu')

        # Find the downloads.VideoDownloader which is currently handling the
        #   clicked media data object (if any)
        download_manager_obj = self.app_obj.download_manager_obj
        download_list_obj = None
        download_item_obj = None
        worker_obj = None
        video_downloader_obj = None

        if download_manager_obj:

            download_list_obj = download_manager_obj.download_list_obj
            download_item_obj = download_list_obj.download_item_dict[item_id]

            for this_worker_obj in download_manager_obj.worker_list:
                if this_worker_obj.running_flag \
                and this_worker_obj.download_item_obj == download_item_obj \
                and this_worker_obj.video_downloader_obj is not None:
                    worker_obj = this_worker_obj
                    video_downloader_obj = this_worker_obj.video_downloader_obj
                    break


        # Set up the popup menu
        popup_menu = Gtk.Menu()

        # Stop check/download
        stop_now_menu_item = Gtk.MenuItem.new_with_mnemonic(
            '_Stop now',
        )
        stop_now_menu_item.connect(
            'activate',
            self.on_progress_list_stop_now,
            download_item_obj,
            worker_obj,
            video_downloader_obj,
        )
        popup_menu.append(stop_now_menu_item)
        if not download_manager_obj \
        or video_downloader_obj is None:
            stop_now_menu_item.set_sensitive(False)

        stop_soon_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Stop after this _video',
        )
        stop_soon_menu_item.connect(
            'activate',
            self.on_progress_list_stop_soon,
            download_item_obj,
            worker_obj,
            video_downloader_obj,
        )
        popup_menu.append(stop_soon_menu_item)
        if not download_manager_obj \
        or video_downloader_obj is None:
            stop_soon_menu_item.set_sensitive(False)

        # Separator
        popup_menu.append(Gtk.SeparatorMenuItem())

        # Check/download next/last
        dl_next_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Download _next',
        )
        dl_next_menu_item.connect(
            'activate',
            self.on_progress_list_dl_next,
            download_item_obj,
        )
        popup_menu.append(dl_next_menu_item)
        if not download_manager_obj or worker_obj:
            dl_next_menu_item.set_sensitive(False)

        dl_last_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Download _last',
        )
        dl_last_menu_item.connect(
            'activate',
            self.on_progress_list_dl_last,
            download_item_obj,
        )
        popup_menu.append(dl_last_menu_item)
        if not download_manager_obj or worker_obj:
            dl_last_menu_item.set_sensitive(False)

        # Create the popup menu
        popup_menu.show_all()
        popup_menu.popup(None, None, None, None, event.button, event.time)


    def results_list_popup_menu(self, event, path, dbid):

        """Called by self.on_results_list_right_click().

        When the user right-clicks on the Results List, show a context-
        sensitive popup menu.

        Args:

            event (Gdk.EventButton): The mouse click event

            path (Gtk.TreePath): Path to the clicked row in the treeview

            dbid (int): The dbid of the clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 3114 video_index_popup_menu')

        # Find the right-clicked video object, and check it still exists
        if not dbid in self.app_obj.media_reg_dict:
            return

        video_obj = self.app_obj.media_reg_dict[dbid]
        if not isinstance(video_obj, media.Video):
            return

        # Set up the popup menu
        popup_menu = Gtk.Menu()

        # Watch video
        self.add_watch_video_menu_items(popup_menu, video_obj)

        # Separator
        separator_item = Gtk.SeparatorMenuItem()
        popup_menu.append(separator_item)

        # Delete video
        delete_menu_item = Gtk.MenuItem.new_with_mnemonic('_Delete video')
        delete_menu_item.connect(
            'activate',
            self.on_results_list_delete_video,
            video_obj,
            path,
        )
        popup_menu.append(delete_menu_item)
        if self.app_obj.current_manager_obj:
            delete_menu_item.set_sensitive(False)

        # Create the popup menu
        popup_menu.show_all()
        popup_menu.popup(None, None, None, None, event.button, event.time)


    def video_index_setup_contents_submenu(self, submenu, media_data_obj,
    only_child_videos_flag=False):

        """Called by self.video_index_popup_menu().

        Sets up a submenu for handling the contents of a channel, playlist
        or folder.

        Args:

            submenu (Gtk.Menu): The submenu to set up, currently empty

            media_data_obj (media.Channel, media.Playlist, media.Folder): The
                channel, playlist or folder whose contents should be modified
                by items in the sub-menu

            only_child_videos_flag (True or False): Set to True when only a
                folder's child videos (not anything in its child channels,
                playlists or folders) should be modified by items in the
                sub-menu; False if all child objects should be modified

        """

        if DEBUG_FUNC_FLAG:
            print('mw 3193 video_index_setup_contents_submenu')

        mark_new_menu_item = Gtk.MenuItem.new_with_mnemonic('Mark as _new')
        mark_new_menu_item.connect(
            'activate',
            self.on_video_index_mark_new,
            media_data_obj,
            only_child_videos_flag,
        )
        submenu.append(mark_new_menu_item)
        if media_data_obj == self.app_obj.fixed_new_folder:
            mark_new_menu_item.set_sensitive(False)

        mark_old_menu_item = Gtk.MenuItem.new_with_mnemonic('Mark as n_ot new')
        mark_old_menu_item.connect(
            'activate',
            self.on_video_index_mark_not_new,
            media_data_obj,
            only_child_videos_flag,
        )
        submenu.append(mark_old_menu_item)

        # Separator
        submenu.append(Gtk.SeparatorMenuItem())

        mark_fav_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Mark as _favourite',
        )
        mark_fav_menu_item.connect(
            'activate',
            self.on_video_index_mark_favourite,
            media_data_obj,
            only_child_videos_flag,
        )
        submenu.append(mark_fav_menu_item)
        if media_data_obj == self.app_obj.fixed_fav_folder:
            mark_fav_menu_item.set_sensitive(False)

        mark_not_fav_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Mark as not f_avourite',
        )
        mark_not_fav_menu_item.connect(
            'activate',
            self.on_video_index_mark_not_favourite,
            media_data_obj,
            only_child_videos_flag,
        )
        submenu.append(mark_not_fav_menu_item)

        # Separator
        submenu.append(Gtk.SeparatorMenuItem())

        mark_archived_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Mark videos as _archived',
        )
        mark_archived_menu_item.connect(
            'activate',
            self.on_video_index_mark_archived,
            media_data_obj,
            only_child_videos_flag,
        )
        submenu.append(mark_archived_menu_item)

        mark_not_archive_menu_item = Gtk.MenuItem.new_with_mnemonic(
            'Mark videos as not ar_chived',
        )
        mark_not_archive_menu_item.connect(
            'activate',
            self.on_video_index_mark_not_archived,
            media_data_obj,
            only_child_videos_flag,
        )
        submenu.append(mark_not_archive_menu_item)


    def add_watch_video_menu_items(self, popup_menu, video_obj):

        """Called by self.video_catalogue_popup_menu() and
        self.results_list_popup_menu().

        Adds common menu items to the popup menu.

        Args:

            popup_menu (Gtk.Menu): The popup menu

            video_obj (media.Video): The video object that was right-clicked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 3284 add_watch_video_menu_items')

        # Watch video in player/download and watch
        if not video_obj.dl_flag:

            dl_watch_menu_item = Gtk.MenuItem.new_with_mnemonic(
                'D_ownload and watch',
            )
            dl_watch_menu_item.connect(
                'activate',
                self.on_video_catalogue_dl_and_watch,
                video_obj,
            )
            popup_menu.append(dl_watch_menu_item)
            if not video_obj.source \
            or self.app_obj.update_manager_obj \
            or self.app_obj.refresh_manager_obj:
                dl_watch_menu_item.set_sensitive(False)

        else:

            watch_player_menu_item = Gtk.MenuItem.new_with_mnemonic(
                'Watch in _player',
            )
            watch_player_menu_item.connect(
                'activate',
                self.on_video_catalogue_watch_video,
                video_obj,
            )
            popup_menu.append(watch_player_menu_item)

        # Watch video online. For YouTube URLs, offer an alternative website
        if not video_obj.source:
            watch_website_menu_item = Gtk.MenuItem.new_with_mnemonic(
                'W_atch on website',
            )
        else:
            mod_source = utils.convert_youtube_to_hooktube(video_obj.source)
            if video_obj.source != mod_source:
                watch_website_menu_item = Gtk.MenuItem.new_with_mnemonic(
                    'W_atch on YouTube',
                )

            else:
                watch_website_menu_item = Gtk.MenuItem.new_with_mnemonic(
                    'W_atch on website',
                )

        watch_website_menu_item.connect(
            'activate',
            self.on_video_catalogue_watch_website,
            video_obj,
        )
        if not video_obj.source:
            watch_website_menu_item.set_sensitive(False)
        popup_menu.append(watch_website_menu_item)

        if video_obj.source and video_obj.source != mod_source:

            watch_hooktube_menu_item = Gtk.MenuItem.new_with_mnemonic(
                'Watch on _HookTube',
            )
            watch_hooktube_menu_item.connect(
                'activate',
                self.on_video_catalogue_watch_hooktube,
                video_obj,
            )
            popup_menu.append(watch_hooktube_menu_item)


    # (Video Index)


    def video_index_reset(self):

        """Called by self.setup_videos_tab() and then by
        mainapp.TartubeApp.load_db(), .switch_db() and
        config.SystemPrefWin.on_complex_button_toggled().

        On the first call, sets up the widgets for the Video Index.

        On subsequent calls, replaces those widgets, ready for them to be
        filled with new data.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 3346 video_index_reset')

        # If not called by self.setup_videos_tab()...
        if self.video_index_treeview:

            # Reset Video Index IVs
            self.video_index_row_dict = {}

            # Remove the old widgets
            if self.video_index_frame.get_child():
                self.video_index_frame.remove(
                    self.video_index_frame.get_child(),
                )

        # Set up the widgets
        self.video_index_treeview = Gtk.TreeView()
        self.video_index_frame.add(self.video_index_treeview)
        self.video_index_treeview.set_can_focus(False)
        self.video_index_treeview.set_headers_visible(False)
        # (Tooltips are initially enabled, and disabled by a call to
        #   self.disable_tooltips() after the config file is loaded, if
        #   necessary)
        self.video_index_treeview.set_tooltip_column(2)
        # (Detect right-clicks on the treeview)
        self.video_index_treeview.connect(
            'button-press-event',
            self.on_video_index_right_click,
        )
        # (Setup up drag and drop)
        drag_target_list = [('video index', 0, 0)]
        self.video_index_treeview.enable_model_drag_source(
            # Mask of mouse buttons allowed to start a drag
            Gdk.ModifierType.BUTTON1_MASK,
            # Table of targets the drag procedure supports, and array length
            drag_target_list,
            # Bitmask of possible actions for a drag from this widget
            Gdk.DragAction.MOVE,
        )
        self.video_index_treeview.enable_model_drag_dest(
            # Table of targets the drag procedure supports, and array length
            drag_target_list,
            # Bitmask of possible actions for a drag from this widget
            Gdk.DragAction.DEFAULT,
        )
        self.video_index_treeview.connect(
            'drag-drop',
            self.on_video_index_drag_drop,
        )
        self.video_index_treeview.connect(
            'drag-data-received',
            self.on_video_index_drag_data_received,
        )

        self.video_index_treestore = Gtk.TreeStore(
            int,
            str, str,
            GdkPixbuf.Pixbuf,
            str,
        )
        self.video_index_sortmodel = Gtk.TreeModelSort(
            self.video_index_treestore
        )
        self.video_index_treeview.set_model(self.video_index_sortmodel)
        self.video_index_sortmodel.set_sort_column_id(1, 0)
        self.video_index_sortmodel.set_sort_func(
            1,
            self.video_index_auto_sort,
            None,
        )

        count = -1
        for item in ['hide', 'hide', 'hide', 'pixbuf', 'show']:

            count += 1

            if item == 'pixbuf':

                renderer_pixbuf = Gtk.CellRendererPixbuf()
                column_pixbuf = Gtk.TreeViewColumn(
                    None,
                    renderer_pixbuf,
                    pixbuf=count,
                )
                self.video_index_treeview.append_column(column_pixbuf)

            else:
                renderer_text = Gtk.CellRendererText()
                column_text = Gtk.TreeViewColumn(
                    None,
                    renderer_text,
                    text=count,
                )
                self.video_index_treeview.append_column(column_text)
                if item == 'hide':
                    column_text.set_visible(False)
                else:
                    column_text.set_cell_data_func(
                        renderer_text,
                        self.video_index_render_text,
                    )

        selection = self.video_index_treeview.get_selection()
        selection.connect('changed', self.on_video_index_selection_changed)

        # Make the changes visible
        self.video_index_treeview.show_all()


    def video_index_populate(self):

        """Called by mainapp.TartubeApp.start(), .load_db() and .switch_db().

        Repopulates the Video Index (assuming that it is already empty, either
        because Tartube has just started, or because of an earlier call to
        self.video_index_reset() ).

        After the call to this function, new rows can be added via a call to
        self.self.video_index_add_row().
        """

        if DEBUG_FUNC_FLAG:
            print('mw 3466 video_index_populate')

        for dbid in self.app_obj.media_top_level_list:

            media_data_obj = self.app_obj.media_reg_dict[dbid]
            if not media_data_obj:
                return self.app_obj.system_error(
                    204,
                    'Video Index initialisation failure',
                )

            else:
                self.video_index_setup_row(media_data_obj, None)

        # Make the changes visible
        self.video_index_treeview.show_all()


    def video_index_setup_row(self, media_data_obj, parent_pointer=None):

        """Called by self.video_index_repopulate(), and then by this function
        recursively.

        Adds a row to the Video Index.

        Args:

            media_data_obj (media.Video, media.Channel, media.Playlist,
                media.Folder): The media data object for this row

            parent_pointer (Gtk.TreeIter): None if the media data object has no
                parent. Otherwise, a pointer to the position of the parent
                object in the treeview

        """

        if DEBUG_FUNC_FLAG:
            print('mw 3503 video_index_setup_row')

        # Don't show a hidden folder, or any of its children
        if isinstance(media_data_obj, media.Folder) \
        and media_data_obj.hidden_flag:
            return

        # Prepare the icon
        pixbuf = self.video_index_get_icon(media_data_obj)
        if not pixbuf:
            return self.app_obj.system_error(
                205,
                'Video index setup row request failed sanity check',
            )

        # Add a row to the treeview
        new_pointer = self.video_index_treestore.append(
            parent_pointer,
            [
                media_data_obj.dbid,
                media_data_obj.name,
                media_data_obj.fetch_tooltip_text(
                    self.app_obj,
                    self.tooltip_max_len,
                ),
                pixbuf,
                self.video_index_get_text(media_data_obj),
            ],
        )

        # Create a reference to the row, so we can find it later
        tree_ref = Gtk.TreeRowReference.new(
            self.video_index_treestore,
            self.video_index_treestore.get_path(new_pointer),
        )
        self.video_index_row_dict[media_data_obj.name] = tree_ref

        # Call this function recursively for any child objects that are
        #   channels, playlists or folders (videos are not displayed in the
        #   Video Index)
        for child_obj in media_data_obj.child_list:

            if not(isinstance(child_obj, media.Video)):
                self.video_index_setup_row(child_obj, new_pointer)


    def video_index_add_row(self, media_data_obj):

        """Called by mainapp.TartubeApp.move_container_to_top(),
        .move_container(), .mark_folder_hidden().

        Also called by callbacks in mainapp.TartubeApp.on_menu_add_channel(),
        .cb on_menu_add_folder() and cb on_menu_add_playlist().

        Adds a row to the Video Index.

        Args:

            media_data_obj (media.Video, media.Channel, media.Playlist,
                media.Folder): The media data object for this row

        """

        if DEBUG_FUNC_FLAG:
            print('mw 3567 video_index_add_row')

        # Don't add a hidden folder, or any of its children
        if media_data_obj.is_hidden():
            return

        # Prepare the icon
        pixbuf = self.video_index_get_icon(media_data_obj)
        if not pixbuf:
            return self.app_obj.system_error(
                206,
                'Video index setup row request failed sanity check',
            )

        # Add a row to the treeview
        if media_data_obj.parent_obj:

            # This media data object has a parent, so we add a row inside the
            #   parent's row

            # Fetch the treeview reference to the parent media data object...
            parent_ref \
            = self.video_index_row_dict[media_data_obj.parent_obj.name]
            # ...and add the new object inside its parent
            tree_iter = self.video_index_treestore.get_iter(
                parent_ref.get_path(),
            )

            new_pointer = self.video_index_treestore.append(
                tree_iter,
                [
                    media_data_obj.dbid,
                    media_data_obj.name,
                    media_data_obj.fetch_tooltip_text(
                        self.app_obj,
                        self.tooltip_max_len,
                    ),
                    pixbuf,
                    self.video_index_get_text(media_data_obj),
                ],
            )

        else:

            # The media data object has no parent, so add a row to the
            #   treeview's top level
            new_pointer = self.video_index_treestore.append(
                None,
                [
                    media_data_obj.dbid,
                    media_data_obj.name,
                    media_data_obj.fetch_tooltip_text(
                        self.app_obj,
                        self.tooltip_max_len,
                    ),
                    pixbuf,
                    self.video_index_get_text(media_data_obj),
                ],
            )

        # Create a reference to the row, so we can find it later
        tree_ref = Gtk.TreeRowReference.new(
            self.video_index_treestore,
            self.video_index_treestore.get_path(new_pointer),
        )
        self.video_index_row_dict[media_data_obj.name] = tree_ref

        if media_data_obj.parent_obj:

            # Expand rows to make the new media data object visible...
            self.video_index_treeview.expand_to_path(
                self.video_index_sortmodel.convert_child_path_to_path(
                    parent_ref.get_path(),
                ),
            )

        # Select the row (which clears the Video Catalogue)
        selection = self.video_index_treeview.get_selection()
        selection.select_path(
            self.video_index_sortmodel.convert_child_path_to_path(
                tree_ref.get_path(),
            ),
        )

        # Make the changes visible
        self.video_index_treeview.show_all()


    def video_index_delete_row(self, media_data_obj):

        """Called by mainapp.TartubeApp.move_container_to_top(),
        .move_container(), .delete_container() and .mark_folder_hidden().

        Removes a row from the Video Index.

        Args:

            media_data_obj (media.Video, media.Channel, media.Playlist,
                media.Folder): The media data object for this row

        """

        if DEBUG_FUNC_FLAG:
            print('mw 3670 video_index_delete_row')

        # Videos can't be shown in the Video Index
        if isinstance(media_data_obj, media.Video):
            return self.app_obj.system_error(
                207,
                'Video index delete row request failed sanity check',
            )

        # During this procedure, ignore any changes to the selected row (i.e.
        #   don't allow self.on_video_index_selection_changed() to redraw the
        #   catalogue)
        self.ignore_video_index_select_flag = True

        # Remove the treeview row
        tree_ref = self.video_index_row_dict[media_data_obj.name]
        tree_path = tree_ref.get_path()
        tree_iter = self.video_index_treestore.get_iter(tree_path)
        self.video_index_treestore.remove(tree_iter)

        self.ignore_video_index_select_flag = False

        # If the deleted row was the previously selected one, the new selected
        #   row is the one just above/below that
        # In this situation, unselect the row (which resets the Video
        #   Catalogue)
        if self.video_index_current is not None \
        and self.video_index_current == media_data_obj.name:

            selection = self.video_index_treeview.get_selection()
            selection.unselect_all()

        # Make the changes visible
        self.video_index_treeview.show_all()


    def video_index_select_row(self, media_data_obj):

        """Called by mainapp.TartubeApp.move_container_to_top(),
        .move_container() and .on_menu_add_video().

        Selects a row in the Video Index, as if the user had clicked it.

        Args:

            media_data_obj (media.Channel, media.Playlist or media.Folder):
                The media data object whose row should be selected

        """

        if DEBUG_FUNC_FLAG:
            print('mw 3721 video_index_select_row')

        # Cannot select a hidden folder, or any of its children
        if isinstance(media_data_obj, media.Video) \
        or media_data_obj.is_hidden():
            return self.app_obj.system_error(
                208,
                'Video Index select row request failed sanity check',
            )

        # Select the row, expanding the treeview path to make it visible, if
        #   necessary
        if media_data_obj.parent_obj:

            # Expand rows to make the new media data object visible...
            parent_ref \
            = self.video_index_row_dict[media_data_obj.parent_obj.name]

            self.video_index_treeview.expand_to_path(
                self.video_index_sortmodel.convert_child_path_to_path(
                    parent_ref.get_path(),
                ),
            )

        # Select the row
        tree_ref = self.video_index_row_dict[media_data_obj.name]

        selection = self.video_index_treeview.get_selection()
        selection.select_path(
            self.video_index_sortmodel.convert_child_path_to_path(
                tree_ref.get_path(),
            ),
        )


    def video_index_update_row_icon(self, media_data_obj):

        """Called by mainapp.TartubeApp.mark_container_favourite(),
        .apply_download_options() and .remove_download_options().

        The icons used in the Video Index must be changed when a media data
        object is marked (or unmarked) favourite, and when download options
        are applied/removed.

        This function updates a row in the Video Index to show the right icon.

        Args:

            media_data_obj (media.Channel, media.Playlist or media.Folder):
                The media data object whose row should be updated

        """

        if DEBUG_FUNC_FLAG:
            print('mw 3775 video_index_update_row_icon')

        # Videos can't be shown in the Video Index
        if isinstance(media_data_obj, media.Video):
            return self.app_obj.system_error(
                209,
                'Video index update row request failed sanity check',
            )

        # If media_data_obj is a hidden folder, then there's nothing to update
        if isinstance(media_data_obj, media.Folder) \
        and media_data_obj.hidden_flag:
            return

        # Because of Gtk issues, we don't update the Video Index during a
        #   download/refresh operation if the flag is set
        if self.app_obj.gtk_broken_flag \
        and (
            self.app_obj.download_manager_obj \
            or self.app_obj.refresh_manager_obj
        ):
            return

        # Update the treeview row
        tree_ref = self.video_index_row_dict[media_data_obj.name]
        model = tree_ref.get_model()
        tree_path = tree_ref.get_path()
        tree_iter = model.get_iter(tree_path)
        model.set(tree_iter, 3, self.video_index_get_icon(media_data_obj))

        # Make the changes visible
        self.video_index_treeview.show_all()


    def video_index_update_row_text(self, media_data_obj):

        """Called by callback in self.on_video_index_enforce_check().

        Also called by mainapp.TartubeApp.add_video(), .delete_video(),
        .mark_video_new(), .mark_video_downloaded(),
        .mark_video_favourite() and .mark_container_favourite().

        The text used in the Video Index must be changed when a media data
        object is updated, including when a child video object is added or
        removed.

        This function updates a row in the Video Index to show the new text.

        Args:

            media_data_obj (media.Channel, media.Playlist or media.Folder):
                The media data object whose row should be updated

        """

        if DEBUG_FUNC_FLAG:
            print('mw 3831 video_index_update_row_text')

        # Videos can't be shown in the Video Index
        if isinstance(media_data_obj, media.Video):
            return self.app_obj.system_error(
                210,
                'Video index update row request failed sanity check',
            )

        # If media_data_obj is a hidden folder, then there's nothing to update
        if isinstance(media_data_obj, media.Folder) \
        and media_data_obj.hidden_flag:
            return

        # Because of Gtk issues, we don't update the Video Index during a
        #   download operation if the flag is set
        if self.app_obj.gtk_broken_flag \
        and (
            self.app_obj.download_manager_obj \
            or self.app_obj.refresh_manager_obj
        ):
            return

        # Update the treeview row
        tree_ref = self.video_index_row_dict[media_data_obj.name]
        model = tree_ref.get_model()
        tree_path = tree_ref.get_path()
        tree_iter = model.get_iter(tree_path)
        model.set(tree_iter, 4, self.video_index_get_text(media_data_obj))

        # Make the changes visible
        self.video_index_treeview.show_all()


    def video_index_get_icon(self, media_data_obj):

        """Called by self.video_index_setup_row(),
        .video_index_add_row() and .video_index_update_row_icon().

        Finds the icon to display on a Video Index row for the specified media
        data object.

        Looks up the GdkPixbuf which has already been created for that icon
        and returns it (or None, if the icon file is missing or if no
        corresponding pixbuf can be found.)

        Args:

            media_data_obj (media.Channel, media.Playlist or media.Folder):
                The media data object whose row should be updated

        Returns:

            A GdkPixbuf or None.

        """

        if DEBUG_FUNC_FLAG:
            print('mw 3889 video_index_get_icon')

        icon = None
        if not self.app_obj.show_small_icons_in_index:

            # Large icons, bigger selection
            if isinstance(media_data_obj, media.Channel):

                if media_data_obj.fav_flag and media_data_obj.options_obj:
                    icon = 'channel_both_large'
                elif media_data_obj.fav_flag:
                    icon = 'channel_left_large'
                elif media_data_obj.options_obj:
                    icon = 'channel_right_large'
                else:
                    icon = 'channel_none_large'

            elif isinstance(media_data_obj, media.Playlist):

                if media_data_obj.fav_flag and media_data_obj.options_obj:
                    icon = 'playlist_both_large'
                elif media_data_obj.fav_flag:
                    icon = 'playlist_left_large'
                elif media_data_obj.options_obj:
                    icon = 'playlist_right_large'
                else:
                    icon = 'playlist_none_large'

            elif isinstance(media_data_obj, media.Folder):

                if media_data_obj.priv_flag:
                    if media_data_obj.fav_flag and media_data_obj.options_obj:
                        icon = 'folder_private_both_large'
                    elif media_data_obj.fav_flag:
                        icon = 'folder_private_left_large'
                    elif media_data_obj.options_obj:
                        icon = 'folder_private_right_large'
                    else:
                        icon = 'folder_private_none_large'

                elif media_data_obj.temp_flag:
                    if media_data_obj.fav_flag and media_data_obj.options_obj:
                        icon = 'folder_temp_both_large'
                    elif media_data_obj.fav_flag:
                        icon = 'folder_temp_left_large'
                    elif media_data_obj.options_obj:
                        icon = 'folder_temp_right_large'
                    else:
                        icon = 'folder_temp_none_large'

                elif media_data_obj.fixed_flag:
                    if media_data_obj.fav_flag and media_data_obj.options_obj:
                        icon = 'folder_fixed_both_large'
                    elif media_data_obj.fav_flag:
                        icon = 'folder_fixed_left_large'
                    elif media_data_obj.options_obj:
                        icon = 'folder_fixed_right_large'
                    else:
                        icon = 'folder_fixed_none_large'

                else:
                    if media_data_obj.fav_flag and media_data_obj.options_obj:
                        icon = 'folder_both_large'
                    elif media_data_obj.fav_flag:
                        icon = 'folder_left_large'
                    elif media_data_obj.options_obj:
                        icon = 'folder_right_large'
                    else:
                        icon = 'folder_none_large'

        else:

            # Small icons, smaller selection
            if isinstance(media_data_obj, media.Channel):
                icon = 'channel_small'
            elif isinstance(media_data_obj, media.Playlist):
                icon = 'playlist_small'
            elif isinstance(media_data_obj, media.Folder):
                if media_data_obj.priv_flag:
                    icon = 'folder_red_small'
                elif media_data_obj.temp_flag:
                    icon = 'folder_blue_small'
                elif media_data_obj.fixed_flag:
                    icon = 'folder_green_small'
                else:
                    icon = 'folder_small'

        if icon is not None and icon in self.icon_dict:
            return self.pixbuf_dict[icon]
        else:
            # Invalid 'icon', or file not found
            return None


    def video_index_get_text(self, media_data_obj):

        """Called by self.video_index_setup_row(), .video_index_add_row() and
        .video_index_update_row_text().

        Sets the text to display on a Video Index row for the specified media
        data object.

        Args:

            media_data_obj (media.Channel, media.Playlist or media.Folder):
                A media data object visible in the Video Index

        Returns:

            A string.

        """

        if DEBUG_FUNC_FLAG:
            print('mw 4003 video_index_get_text')

        text = utils.shorten_string(
            media_data_obj.nickname,
            self.tiny_string_max_len,
        )

        if not self.app_obj.complex_index_flag:

            if media_data_obj.dl_count:
                text += ' (' + str(media_data_obj.new_count) + '/' \
                + str(media_data_obj.dl_count) + ')'

        else:

            if media_data_obj.vid_count:
                text += '\nV:' + str(media_data_obj.vid_count) \
                + ' N:' + str(media_data_obj.new_count) \
                + ' F:' + str(media_data_obj.fav_count) \
                + ' D:' + str(media_data_obj.dl_count)

            if not isinstance(media_data_obj, media.Folder) \
            and (media_data_obj.error_list or media_data_obj.warning_list):

                if not media_data_obj.vid_count:
                    text += '\n'
                else:
                    text += ' '

                text += 'E:' + str(len(media_data_obj.error_list)) \
                + ' W:' + str(len(media_data_obj.warning_list))

        return text


    def video_index_render_text(self, col, renderer, model, tree_iter, data):

        """Called by self.video_index_reset().

        Cell renderer function. When the text column of the Video Index is
        about to be rendered, set the font to normal, bold or italic, depending
        on the media data object's IVs.

        Args:
            col (Gtk.TreeViewColumn): The treeview column about to be rendered.

            renderer (Gtk.CellRendererText): The Gtk object handling the
                rendering.

            model (Gtk.TreeModelSort): The treeview's row data is stored here.

            tree_iter (Gtk.TreeIter): A pointer to the row containing the cell
                to be rendered.

            data (None): Ignored

        """

        if DEBUG_FUNC_FLAG:
            print('mw 4062 video_index_render_text')

        # Because of Gtk issues, we don't update the Video Index during a
        #   download/refresh operation if the flag is set
        if not self.app_obj.gtk_broken_flag \
        or (
            not self.app_obj.download_manager_obj \
            and not self.app_obj.refresh_manager_obj
        ):
            dbid = model.get_value(tree_iter, 0)
            media_data_obj = self.app_obj.media_reg_dict[dbid]

            # If marked new (unwatched), show as bold text
            if media_data_obj.new_count:
                renderer.set_property('weight', Pango.Weight.BOLD)
            else:
                renderer.set_property('weight', Pango.Weight.NORMAL)

            # If downloads disabled, show as italic text
            if media_data_obj.dl_disable_flag:
                renderer.set_property('style', Pango.Style.ITALIC)
                renderer.set_property('underline', True)
            elif media_data_obj.dl_sim_flag:
                renderer.set_property('style', Pango.Style.ITALIC)
                renderer.set_property('underline', False)
            else:
                renderer.set_property('style', Pango.Style.NORMAL)
                renderer.set_property('underline', False)


    # (Video Catalogue)


    def video_catalogue_reset(self):

        """Called by self.setup_videos_tab() and then by
        self.video_catalogue_redraw_all().

        On the first call, sets up the widgets for the Video Catalogue. On
        subsequent calls, replaces those widgets, ready for them to be filled
        with new data.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 4106 video_catalogue_reset')

        # If not called by self.setup_videos_tab()...
        if self.catalogue_listbox:
            self.catalogue_frame.remove(self.catalogue_frame.get_child())

        # Reset IVs (when called by anything)
        self.video_catalogue_dict = {}

        # Set up the widgets
        self.catalogue_listbox = Gtk.ListBox()
        self.catalogue_frame.add(self.catalogue_listbox)
        self.catalogue_listbox.set_can_focus(False)
        self.catalogue_listbox.set_selection_mode(Gtk.SelectionMode.MULTIPLE)
        # (Without this line, it's not possible to unselect rows by clicking
        #   on one of them)
        self.catalogue_listbox.set_activate_on_single_click(False)

        self.catalogue_listbox.set_sort_func(
            self.video_catalogue_auto_sort,
            None,
            False,
        )

        # Make the changes visible
        self.catalogue_frame.show_all()


    def video_catalogue_redraw_all(self, name, page_num=1,
    reset_scroll_flag=False):

        """Called from callbacks in self.on_video_index_selection_changed(),
        mainapp.TartubeApp.on_button_switch_view(),
        .on_menu_add_video() and on_menu_test().

        Also called from callbacks in
        mainapp.TartubeApp.on_button_catalogue_size(),
        .on_button_first_page(), .on_button_last_page(),
        .on_button_next_page() and .on_button_previous_page().

        When the user clicks on a media data object in the Video Index (a
        channel, playlist or folder), this function is called to replace the
        contents of the Video Catalogue with some or all of the video objects
        stored as children in that channel, playlist or folder.

        Depending on the value of self.catalogue_mode, the Video Catalogue
        consists of a list of mainwin.SimpleCatalogueItem or
        mainwin.ComplexCatalogueItem objects, one for each row in the
        Gtk.ListBox (corresponding to a single video).

        The video catalogue splits its video list into pages (as Gtk struggles
        with a list of hundreds, or thousands, of videos). Only videos on the
        specified page (or on the current page, if no page is specified) are
        drawn. If mainapp.TartubeApp.catalogue_page_size is set to zero, all
        videos are drawn on a single page.

        This function clears the previous contents of the Gtk.ListBox and
        resets IVs.

        Then, it adds new rows to the Gtk.ListBox and creates a new
        mainwin.SimpleCatalogueItem or mainwin.ComplexCatalogueItem object for
        each video on the page.

        Args:

            name (string): The selected media data object's name; one of the
                keys in self.media_name_dict

            page_num (int): The number of the page to be drawn (a value in the
                range 1 to self.catalogue_toolbar_last_page). If None, the
                current page is drawn

            reset_scroll_flag (True or False): Set to True when called by
                self.on_video_index_selection_changed(). The scrollbars must
                always be reset when switching between channels/playlist/
                folders

        """

        if DEBUG_FUNC_FLAG:
            print('mw 4186 video_catalogue_redraw_all')

        # If actually switching to a different channel/playlist/folder, or a
        #   different page on the same channel/playlist/folder, must reset the
        #   scrollbars later in the function
        if not reset_scroll_flag:
            if self.video_index_current is None \
            or self.video_index_current != name \
            or self.catalogue_toolbar_current_page != page_num:
                reset_scroll_flag = True

        # The parent media data object is a media.Channel, media.playlist or
        #   media.Folder object
        dbid = self.app_obj.media_name_dict[name]
        parent_obj = self.app_obj.media_reg_dict[dbid]

        # Sanity check - the selected item in the Video Index should not be a
        #   media.Video object
        if not parent_obj or (isinstance(parent_obj, media.Video)):
            return self.system_error(
                211,
                'Videos should not appear in the Video Index',
            )

        # Reset the previous contents of the Video Catalogue, if any, and reset
        #   IVs
        self.video_catalogue_reset()

        # Temporarily reset widgets in the Video Catalogue toolbar (in case
        #   something goes wrong, or in case drawing the page takes a long
        #   time)
        self.video_catalogue_toolbar_reset()

        # The parent media data object has any number of child media data
        #   objects, but this function is only interested in those that are
        #   media.Video objects
        video_count = 0
        page_size = self.app_obj.catalogue_page_size

        for child_obj in parent_obj.child_list:
            if isinstance(child_obj, media.Video):

                # (We need the number of child videos when we update widgets in
                #   the toolbar)
                video_count += 1

                # Only draw videos on this page. If the page size is zero, all
                #   videos are drawn on a single page
                if page_size \
                and (
                    video_count <= ((page_num - 1) * page_size) \
                    or video_count > (page_num * page_size)
                ):
                    # Don't draw the video on this page
                    continue

                # Create a new catalogue item object for the video
                if self.app_obj.catalogue_mode == 'simple_hide_parent' \
                or self.app_obj.catalogue_mode == 'simple_show_parent':
                    catalogue_item_obj = SimpleCatalogueItem(
                        self,
                        child_obj,
                    )

                else:
                    catalogue_item_obj = ComplexCatalogueItem(
                        self,
                        child_obj,
                    )

                self.video_catalogue_dict[catalogue_item_obj.dbid] = \
                catalogue_item_obj

                # Add a row to the Gtk.ListBox

                # Instead of using Gtk.ListBoxRow directly, use a wrapper class
                #   so we can quickly retrieve the video displayed on each row
                wrapper_obj = CatalogueRow(child_obj)
                self.catalogue_listbox.add(wrapper_obj)

                # Populate the row with widgets...
                catalogue_item_obj.draw_widgets(wrapper_obj)
                # ...and give them their initial appearance
                catalogue_item_obj.update_widgets()

        # Update widgets in the toolbar, now that we know the number of child
        #   videos
        self.video_catalogue_toolbar_update(page_num, video_count)

        # In all cases, sensitise the scroll up/down toolbar buttons
        self.catalogue_scroll_up_button.set_sensitive(True)
        self.catalogue_scroll_down_button.set_sensitive(True)
        # Reset the scrollbar, if required
        if reset_scroll_flag:
            self.catalogue_scrolled.get_vadjustment().set_value(0)

        # Procedure complete
        self.catalogue_listbox.show_all()


    def video_catalogue_update_row(self, video_obj):

        """Called by self.results_list_update_row and a callback in
        self.on_video_catalogue_enforce_check().

        Also called by mainapp.TartubeApp.create_video_from_download(),
        .announce_video_download(), .mark_video_new() and
        .mark_video_favourite().

        This function is called with a media.Video object. If that video is
        already visible in the Video Catalogue, updates the corresponding
        mainwin.SimpleCatalogueItem or mainwin.ComplexCatalogueItem (which
        updates the widgets in the Gtk.ListBox).

        If the video is now yet visible in the Video Catalogue, but should be
        drawn on the current page, creates a new mainwin.SimpleCatalogueItem or
        mainwin.ComplexCatalogueItem object and adds a row to the Gtk.ListBox,
        removing an existing catalogue item to make room, if necessary.

        Args:

            video_obj (media.Video) - The video to update

        """

        if DEBUG_FUNC_FLAG:
            print('mw 4312 video_catalogue_update_row')

        # Is the video's parent channel, playlist or folder the one that is
        #   currently selected in the Video Index? If not, the video is not
        #   displayed in the Video Catalogue
        if self.video_index_current is None:
            return

        elif self.video_index_current != video_obj.parent_obj.name \
        and self.video_index_current != self.app_obj.fixed_all_folder.name \
        and (
            self.video_index_current != self.app_obj.fixed_new_folder.name \
            or not video_obj.new_flag
        ):
            return

        # Does a mainwin.SimpleCatalogueItem or mainwin.ComplexCatalogueItem
        #   object already exist for this video?
        if video_obj.dbid in self.video_catalogue_dict:

            # Update the catalogue item object, which updates the widgets in
            #   the Gtk.ListBox
            catalogue_item_obj = self.video_catalogue_dict[video_obj.dbid]
            catalogue_item_obj.update_widgets()

        else:

            # Find the video's position in the parent container's list of
            #   child objects, ignoring any child objects that aren't videos
            # At the same time, count the number of child video object so that
            #   we can update the toolbar widgets
            video_count = 0
            page_num = 1
            current_page_num = self.catalogue_toolbar_current_page
            page_size = self.app_obj.catalogue_page_size

            dbid = self.app_obj.media_name_dict[self.video_index_current]
            container_obj = self.app_obj.media_reg_dict[dbid]

            for child_obj in container_obj.child_list:
                if isinstance(child_obj, media.Video):
                    video_count += 1
                    # If the page size is 0, then all videos are drawn on one
                    #   page
                    if child_obj == video_obj and page_size:
                        page_num = int((video_count - 1) / page_size) + 1

            # If the video should be drawn on the current page, or on any
            #   previous page, and if the current page is already full, then we
            #   might need to remove a catalogue item from this page, and
            #   replace it with another
            if page_num <= current_page_num \
            and len(self.video_catalogue_dict) >= page_size:

                # Compile a dictionary of videos which are currently visible on
                #   this page
                visible_dict = {}
                for catalogue_item in self.video_catalogue_dict.values():
                    visible_dict[catalogue_item.video_obj.dbid] \
                    = catalogue_item.video_obj

                # Check the videos which should be visible on this page. This
                #   code leaves us with 'visible_dict' containing videos that
                #   should no longer be visible on the page, and 'missing_dict'
                #   containing videos that should be visible on the page, but
                #   are not
                # Each dictionary should have 0 or 1 entries, but the code will
                #   cope if it's more than that
                missing_dict = {}
                for index in range (
                    (((current_page_num - 1) * page_size) + 1),
                    ((current_page_num * page_size) + 1),
                ):
                    if index <= video_count:
                        child_obj = container_obj.child_list[index]
                        if not child_obj.dbid in visible_dict:
                            missing_dict[child_obj.dbid] = child_obj
                        else:
                            del visible_dict[child_obj.dbid]

                # Remove any catalogue items for videos that shouldn't be
                #   visible, but are
                for dbid in visible_dict:
                    catalogue_item_obj = self.video_catalogue_dict[dbid]
                    self.catalogue_listbox.remove(
                        catalogue_item_obj.catalogue_row,
                    )

                    del self.video_catalogue_dict[dbid]

                # Add any new catalogue items for videos which should be
                #   visible, but aren't
                for dbid in missing_dict:

                    # Get the media.Video object
                    missing_obj = self.app_obj.media_reg_dict[dbid]

                    # Create a new catalogue item
                    self.video_catalogue_insert_item(missing_obj)

            else:

                # Page is not full, so just create a new catalogue item
                self.video_catalogue_insert_item(video_obj)

            # Update widgets in the toolbar
            self.video_catalogue_toolbar_update(
                self.catalogue_toolbar_current_page,
                video_count,
            )

        # Force the Gtk.ListBox to sort its rows, so that videos are displayed
        #   in the correct order
        self.catalogue_listbox.invalidate_sort()

        # Procedure complete
        self.catalogue_listbox.show_all()


    def video_catalogue_insert_item(self, video_obj):

        """Called by self.video_catalogue_update_row() (only).

        Adds a new mainwin.SimpleCatalogueItem or mainwin.ComplexCatalogueItem
        to the Video Catalogue.

        Args:

            video_obj (media.Video): The video for which a new catalogue item
                should be created

        """

        if DEBUG_FUNC_FLAG:
            print('mw 4470 video_catalogue_insert_item')

        # Create the new catalogue item
        if self.app_obj.catalogue_mode == 'simple_hide_parent' \
        or self.app_obj.catalogue_mode == 'simple_show_parent':
            catalogue_item_obj = SimpleCatalogueItem(
                self,
                video_obj,
            )

        else:
            catalogue_item_obj = ComplexCatalogueItem(
                self,
                video_obj,
            )

        self.video_catalogue_dict[video_obj.dbid] = catalogue_item_obj

        # Add a row to the Gtk.ListBox

        # Instead of using Gtk.ListBoxRow directly, use a wrapper
        #   class so we can quickly retrieve the video displayed on
        #   each row
        wrapper_obj = CatalogueRow(video_obj)
        self.catalogue_listbox.add(wrapper_obj)

        # Populate the row with widgets...
        catalogue_item_obj.draw_widgets(wrapper_obj)
        # ...and give them their initial appearance
        catalogue_item_obj.update_widgets()


    def video_catalogue_delete_row(self, video_obj):

        """Called by mainapp.TartubeApp.delete_video(),
        .mark_video_new() and .mark_video_favourite().

        This function is called with a media.Video object. If that video is
        already visible in the Video Catalogue, removes the corresponding
        mainwin.SimpleCatalogueItem or mainwin.ComplexCatalogueItem .

        Args:

            video_obj (media.Video) - The video to remove

        """

        if DEBUG_FUNC_FLAG:
            print('mw 4491 video_catalogue_delete_row')

        # Is the video's parent channel, playlist or folder the one that is
        #   currently selected in the Video Index? If not, the video is not
        #   displayed in the Video Catalogue
        if self.video_index_current is None:
            return

        elif self.video_index_current != video_obj.parent_obj.name \
        and self.video_index_current != self.app_obj.fixed_all_folder.name \
        and (
            self.video_index_current != self.app_obj.fixed_new_folder.name \
            or video_obj.new_flag
        ) and (
            self.video_index_current != self.app_obj.fixed_fav_folder.name \
            or video_obj.fav_flag
        ):
            return

        # Does a mainwin.SimpleCatalogueItem or mainwin.ComplexCatalogueItem
        #   object exist for this video?
        if video_obj.dbid in self.video_catalogue_dict:

            # Remove the catalogue item object and its mainwin.CatalogueRow
            #   object (the latter being a wrapper for Gtk.ListBoxRow)
            catalogue_item_obj = self.video_catalogue_dict[video_obj.dbid]

            # Remove the row from the Gtk.ListBox
            self.catalogue_listbox.remove(catalogue_item_obj.catalogue_row)

            # Update IVs
            del self.video_catalogue_dict[video_obj.dbid]

            # If the current page is not the last one, we can create a new
            #   catalogue item to replace the removed one
            move_obj = None
            dbid = self.app_obj.media_name_dict[self.video_index_current]
            container_obj = self.app_obj.media_reg_dict[dbid]
            video_count = 0

            if self.video_catalogue_dict \
            and self.catalogue_toolbar_current_page \
            < self.catalogue_toolbar_last_page:

                # Get the last mainwin.CatalogueRow object directly from the
                #   Gtk listbox, as it is auto-sorted frequently
                row_list = self.catalogue_listbox.get_children()
                last_row = row_list[-1]
                if last_row:
                    last_obj = last_row.video_obj

                # Find the video object that would be drawn after that, if the
                #   videos were all drawn on a single page
                # At the same time, count the number of remaining child video
                #   objects so we can update the toolbar
                next_flag = False

                for child_obj in container_obj.child_list:
                    if isinstance(child_obj, media.Video):
                        video_count += 1
                        if child_obj.dbid == last_obj.dbid:
                            # (Use the next video after this one)
                            next_flag = True

                        elif next_flag == True:
                            # (Use this video)
                            move_obj = child_obj
                            next_flag = False

                # Create the new catalogue item
                if move_obj:
                    self.video_catalogue_update_row(move_obj)

            else:

                # We're already on the last (or only) page, so no need to
                #   replace anything. Just count the number of remanining child
                #   video objects
                for child_obj in container_obj.child_list:
                    if isinstance(child_obj, media.Video):
                        video_count += 1

            # Update widgets in the Video Catalogue toolbar
            self.video_catalogue_toolbar_update(
                self.catalogue_toolbar_current_page,
                video_count,
            )

            # Procedure complete
            self.catalogue_listbox.show_all()


    def video_catalogue_toolbar_reset(self):

        """Called by self.video_catalogue_redraw_all().

        Just before completely redrawing the Video Catalogue, temporarily reset
        widgets in the Video Catalogue toolbar (in case something goes wrong,
        or in case drawing the page takes a long time).
        """

        if DEBUG_FUNC_FLAG:
            print('mw 4620 video_catalogue_toolbar_reset')

        self.catalogue_toolbar_current_page = 1
        self.catalogue_toolbar_last_page = 1

        self.catalogue_page_entry.set_sensitive(True)
        self.catalogue_page_entry.set_text(
            str(self.catalogue_toolbar_current_page),
        )

        self.catalogue_last_entry.set_sensitive(True)
        self.catalogue_last_entry.set_text(
            str(self.catalogue_toolbar_last_page),
        )

        self.catalogue_first_button.set_sensitive(False)
        self.catalogue_back_button.set_sensitive(False)
        self.catalogue_forwards_button.set_sensitive(False)
        self.catalogue_last_button.set_sensitive(False)
        self.catalogue_find_button.set_sensitive(False)


    def video_catalogue_toolbar_update(self, page_num, video_count):

        """Called by self.video_catalogue_redraw_all(),
        self.video_catalogue_update_row() and
        self.video_catalogue_delete_row().

        After the Video Catalogue is redrawn or updated, update widgets in the
        Video Catalogue toolbar.

        Args:

            page_num (int): The page number to draw (a value in the range 1 to
                self.catalogue_toolbar_last_page)

            video_count (int): The number of videos that are children of the
                selected channel, playlist or folder (may be 0)

         """

        if DEBUG_FUNC_FLAG:
            print('mw 4662 video_catalogue_toolbar_update')

        self.catalogue_toolbar_current_page = page_num

        # If the page size is 0, then all videos are drawn on one page
        if not self.app_obj.catalogue_page_size:
            self.catalogue_toolbar_last_page = page_num
        else:
            self.catalogue_toolbar_last_page \
            = int((video_count - 1) / self.app_obj.catalogue_page_size) + 1

        self.catalogue_page_entry.set_sensitive(True)
        self.catalogue_page_entry.set_text(
            str(self.catalogue_toolbar_current_page),
        )

        self.catalogue_last_entry.set_sensitive(True)
        self.catalogue_last_entry.set_text(
            str(self.catalogue_toolbar_last_page),
        )

        if page_num == 1:
            self.catalogue_first_button.set_sensitive(False)
            self.catalogue_back_button.set_sensitive(False)
        else:
            self.catalogue_first_button.set_sensitive(True)
            self.catalogue_back_button.set_sensitive(True)

        if page_num == self.catalogue_toolbar_last_page:
            self.catalogue_forwards_button.set_sensitive(False)
            self.catalogue_last_button.set_sensitive(False)
        else:
            self.catalogue_forwards_button.set_sensitive(True)
            self.catalogue_last_button.set_sensitive(True)

        if not video_count:
            self.catalogue_find_button.set_sensitive(False)
        else:
            self.catalogue_find_button.set_sensitive(True)


    # (Progress List)


    def progress_list_reset(self):

        """Called by mainapp.TartubeApp.download_manager_start().

        Empties the Gtk.TreeView in the Progress List, ready for it to be
        refilled.

        Also resets related IVs.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 4684 progress_list_reset')

        # Reset widgets
        self.progress_list_liststore = Gtk.ListStore(
            int,
            GdkPixbuf.Pixbuf,
            str, str, str, str, str, str, str, str, str,
        )
        self.progress_list_treeview.set_model(self.progress_list_liststore)

        # Reset IVs
        self.progress_list_row_dict = {}
        self.progress_list_row_count = 0
        self.progress_list_temp_dict = {}


    def progress_list_init(self, download_list_obj):

        """Called by mainapp.TartubeApp.download_manager_start().

        At the start of the download operation, a downloads.DownloadList
        object is created, listing all the media data objects (channels,
        playlists and videos) from which videos are to be downloaded.

        This function is then called to add each of those media data objects to
        the Progress List.

        As the download operation progresses,
        downloads.DownloadWorker.talk_to_mainwin() calls
        self.progress_list_receive_dl_stats() to update the contents of the
        Progress List.

        Args:

            download_list_obj (downloads.DownloadList): The download list
                object that has just been created

        """

        if DEBUG_FUNC_FLAG:
            print('mw 4724 progress_list_init')

        # For each download item object, add a row to the treeview, and store
        #   the download item's .dbid IV so that
        #   self.progress_list_receive_dl_stats() can update the correct row
        for item_id in download_list_obj.download_item_list:

            download_item_obj = download_list_obj.download_item_dict[item_id]

            self.progress_list_add_row(
                item_id,
                download_item_obj.media_data_obj,
            )


    def progress_list_add_row(self, item_id, media_data_obj):

        """Called by self.progress_list_init and
        mainapp.TartubeApp.download_watch_videos().

        Adds a row to the Progress List.

        Args:

            item_id (int): The downloads.DownloadItem.item_id

            media_data_obj (media.Video, media.Channel or media.Playlist):
                The media data object for which a row should be added

        """

        if DEBUG_FUNC_FLAG:
            print('mw 4789 progress_list_add_row')

        # Prepare the icon
        if isinstance(media_data_obj, media.Channel):
            pixbuf = self.pixbuf_dict['channel_small']
        elif isinstance(media_data_obj, media.Playlist):
            pixbuf = self.pixbuf_dict['playlist_small']
        elif isinstance(media_data_obj, media.Folder):
            pixbuf = self.pixbuf_dict['folder_small']
        else:
            pixbuf = self.pixbuf_dict['video_small']

        # Prepare the new row in the treeview
        row_list = []

        row_list.append(item_id)
        row_list.append(pixbuf)
        row_list.append(
            utils.shorten_string(media_data_obj.name, self.string_max_len),
        )
        row_list.append(None)
        row_list.append('Waiting')
        row_list.append(None)
        row_list.append(None)
        row_list.append(None)
        row_list.append(None)
        row_list.append(None)
        row_list.append(None)

        # Create a new row in the treeview. Doing the .show_all() first
        #   prevents a Gtk error (for unknown reasons)
        self.progress_list_treeview.show_all()
        self.progress_list_liststore.append(row_list)

        # Store the row's details so we can update it later
        self.progress_list_row_dict[item_id] \
        = self.progress_list_row_count
        self.progress_list_row_count += 1


    def progress_list_receive_dl_stats(self, download_item_obj, dl_stat_dict):

        """Called by downloads.DownloadWorker.talk_to_mainwin().

        During a download operation, this function is called every time
        youtube-dl writes some output to STDOUT.

        Updating data displayed in the Progress List several times a second,
        and irregularly, doesn't look very nice. Instead, we only update the
        displayed data at fixed intervals.

        Thus, when this function is called, it is passed a dictionary of
        download statistics in a standard format (the one described in the
        comments to media.VideoDownloader.extract_stdout_data() ).

        We store that dictionary temporarily. During periodic calls to
        self.progress_list_display_dl_stats(), the contents of any stored
        dictionaries are displayed and then the dictionaries themselves are
        destroyed.

        Args:

            download_item_obj (downloads.DownloadItem): The download item
                object handling a download for a media data object

            dl_stat_dict (dict): The dictionary of download statistics
                described above.

        """

        if DEBUG_FUNC_FLAG:
            print('mw 4824 progress_list_receive_dl_stats')

        # Check that the Progress List actually has a row for the specified
        #   downloads.DownloadItem object
        if not download_item_obj.item_id in self.progress_list_row_dict:
            return self.app_obj.system_error(
                212,
                'Missing row in Progress List',
            )

        # Temporarily store the dictionary of download statistics
        if not download_item_obj.item_id in self.progress_list_temp_dict:
            new_dl_stat_dict = {}
        else:
            new_dl_stat_dict \
            = self.progress_list_temp_dict[download_item_obj.item_id]

        for key in dl_stat_dict:
            new_dl_stat_dict[key] = dl_stat_dict[key]

        self.progress_list_temp_dict[download_item_obj.item_id] \
        = new_dl_stat_dict


    def progress_list_display_dl_stats(self):

        """Called by mainapp.TartubeApp.dl_timer_callback(), which is itself
        called periodically by a gobject timer.

        As the download operation progresses, youtube-dl writes statistics to
        its STDOUT. Those statistics have been interpreted and stored in
        self.progress_list_temp_dict, waiting for periodic calls to this
        function to display them.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 4860 progress_list_display_dl_stats')

        # Import the contents of the IV (in case it gets updated during the
        #   call to this function), and use the imported copy
        temp_dict = self.progress_list_temp_dict
        self.progress_list_temp_dict = {}

        # For each media data object displayed in the Progress List...
        for item_id in temp_dict:

            # Get a dictionary of download statistics for this media object
            # The dictionary is in the standard format described in the
            #   comments to media.VideoDownloader.extract_stdout_data()
            dl_stat_dict = temp_dict[item_id]

            # Get the corresponding treeview row
            tree_path = Gtk.TreePath(self.progress_list_row_dict[item_id])

            # Update statistics displayed in that row
            # (Columns 0, 1 and 2 are not modified, once the row has been added
            #   to the treeview)
            column = 2

            for key in (
                'playlist_index',
                'status',
                'filename',
                'extension',
                'filesize',
                'percent',
                'eta',
                'speed',
            ):
                column += 1

                if key in dl_stat_dict:

                    if key == 'playlist_index':

                        if 'dl_sim_flag' in dl_stat_dict \
                        and dl_stat_dict['dl_sim_flag']:
                            # (Don't know how many videos there are in a
                            #   channel/playlist, so ignore value of
                            #   'playlist_size')
                            string = str(dl_stat_dict['playlist_index'])

                        else:
                            string = str(dl_stat_dict['playlist_index'])
                            if 'playlist_size' in dl_stat_dict:
                                string = string + '/' \
                                + str(dl_stat_dict['playlist_size'])
                            else:
                                string = string + '/1'

                    else:
                        string = utils.shorten_string(
                            dl_stat_dict[key],
                            self.string_max_len,
                        )

                    self.progress_list_liststore.set(
                        self.progress_list_liststore.get_iter(tree_path),
                        column,
                        string,
                    )


    # (Results List)


    def results_list_reset(self):

        """Called by mainapp.TartubeApp.download_manager_start().

        Empties the Gtk.TreeView in the Results List, ready for it to be
        refilled.

        (There are no IVs to reset.)
        """

        if DEBUG_FUNC_FLAG:
            print('mw 4941 results_list_reset')

        # Reset widgets
        self.results_list_liststore = Gtk.ListStore(
            int,
            GdkPixbuf.Pixbuf,
            str, str, str, str,
            bool,
            GdkPixbuf.Pixbuf,
            str,
        )
        self.results_list_treeview.set_model(self.results_list_liststore)

        # Reset IVs
        self.results_list_row_count = 0
        self.results_list_temp_list = []


    def results_list_add_row(self, download_item_obj, video_obj, \
    keep_description=None, keep_info=None, keep_annotations=None,
    keep_thumbnail=None):

        """Called by mainapp.TartubeApp.announce_video_download().

        At the instant when youtube-dl completes a video download, the standard
        python test for the existence of a file fails.

        Therefore, when this function is called, we display the downloaded
        video in the Results List immediately, but we also add the video to a
        temporary list.

        Thereafter, periodic calls to self.results_list_update_row() check
        whether the file actually exists yet, and updates the Results List
        accordingly.

        Args:

            download_item_obj (downloads.DownloadItem): The download item
                object handling a download for a media data object

            video_obj (media.Video): The media data object for the downloaded
                video

            keep_description (True, False):
            keep_info (True, False):
            keep_annotations (True, False):
            keep_thumbnail (True, False): Settings from the
                options.OptionsManager object used to download the video (all
                of them set to 'None' for a simulated download)

        """

        if DEBUG_FUNC_FLAG:
            print('mw 4994 results_list_add_row')

        # Prepare the icons
        if self.app_obj.download_manager_obj.force_sim_flag \
        or download_item_obj.media_data_obj.dl_sim_flag:
            pixbuf = self.pixbuf_dict['check_small']
        else:
            pixbuf = self.pixbuf_dict['download_small']

        if isinstance(video_obj.parent_obj, media.Channel):
            pixbuf2 = self.pixbuf_dict['channel_small']
        elif isinstance(video_obj.parent_obj, media.Playlist):
            pixbuf2 = self.pixbuf_dict['playlist_small']
        elif isinstance(video_obj.parent_obj, media.Folder):
            pixbuf2 = self.pixbuf_dict['folder_small']
        else:
            return self.app_obj.system_error(
                213,
                'Results List add row request failed sanity check',
            )

        # Prepare the new row in the treeview
        row_list = []

        # Set the row's initial contents
        row_list.append(video_obj.dbid)
        row_list.append(pixbuf)
        row_list.append(
            utils.shorten_string(video_obj.nickname, self.string_max_len),
        )

        # (For a simulated download, the video duration (etc) will already be
        #   available, so we can display those values)
        if video_obj.duration is not None:
            row_list.append(
                utils.convert_seconds_to_string(video_obj.duration),
            )
        else:
            row_list.append(None)

        if video_obj.file_size is not None:
            row_list.append(video_obj.get_file_size_string())
        else:
            row_list.append(None)

        if video_obj.upload_time is not None:
            row_list.append(video_obj.get_upload_date_string())
        else:
            row_list.append(None)

        row_list.append(video_obj.dl_flag)
        row_list.append(pixbuf2)
        row_list.append(
            utils.shorten_string(
                video_obj.parent_obj.name,
                self.string_max_len,
            ),
        )

        # Create a new row in the treeview. Doing the .show_all() first
        #   prevents a Gtk error (for unknown reasons)
        self.results_list_treeview.show_all()
        if not self.app_obj.results_list_reverse_flag:
            self.results_list_liststore.append(row_list)
        else:
            self.results_list_liststore.prepend(row_list)

        # Store some information about this download so that periodic calls to
        #   self.results_list_update_row() can retrieve it, and check whether
        #   the file exists yet
        temp_dict = {
            'video_obj': video_obj,
            'row_num': self.results_list_row_count,
        }

        if keep_description is not None:
            temp_dict['keep_description'] = keep_description

        if keep_info is not None:
            temp_dict['keep_info'] = keep_info

        if keep_annotations is not None:
            temp_dict['keep_annotations'] = keep_annotations

        if keep_thumbnail is not None:
            temp_dict['keep_thumbnail'] = keep_thumbnail

        # Update IVs
        self.results_list_temp_list.append(temp_dict)
        # (The number of rows has just increased, so increment the IV for the
        #   next call to this function)
        self.results_list_row_count += 1


    def results_list_update_row(self):

        """Called by mainapp.TartubeApp.dl_timer_callback(), which is itself
        called periodically by a gobject timer.

        self.results_list_temp_list contains a set of dictionaries, one for
        each video download whose file has not yet been confirmed to exist.

        Go through each of those dictionaries. If the file still doesn't exist,
        re-insert the dictionary back into self.results_list_temp_list, ready
        for it to be checked by the next call to this function.

        If the file does now exist, update the corresponding media.Video
        object. Then update the Video Catalogue and the Progress List.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 5105 results_list_update_row')

        new_temp_list = []

        while self.results_list_temp_list:

            temp_dict = self.results_list_temp_list.pop(0)

            # For convenience, retrieve the media.Video object, leaving the
            #   other values in the dictionary until we need them
            video_obj = temp_dict['video_obj']
            # Get the video's full file path now, as we use it several times
            video_path = os.path.abspath(
                os.path.join(
                    self.app_obj.downloads_dir,
                    video_obj.file_dir,
                    video_obj.file_name + video_obj.file_ext,
                ),
            )

            # Because of the 'Requested formats are incompatible for merge and
            #   will be merged into mkv' warning, we have to check for that
            #   extension, too
            mkv_flag = False
            if not os.path.isfile(video_path) and video_obj.file_ext == '.mp4':

                mkv_flag = True
                video_path = os.path.abspath(
                    os.path.join(
                        self.app_obj.downloads_dir,
                        video_obj.file_dir,
                        video_obj.file_name + '.mkv',
                    ),
                )

            # Does the downloaded file now exist on the user's hard drive?
            if os.path.isfile(video_path):

                # Update the media.Video object using the temporary dictionary
                self.app_obj.update_video_when_file_found(
                    video_obj,
                    video_path,
                    temp_dict,
                    mkv_flag,
                )

                # The parent container objects can now be sorted
                video_obj.parent_obj.sort_children()
                self.app_obj.fixed_all_folder.sort_children()
                if video_obj.new_flag:
                    self.app_obj.fixed_new_folder.sort_children()
                if video_obj.fav_flag:
                    self.app_obj.fixed_fav_folder.sort_children()

                # Update the video catalogue in the 'Videos' tab
                self.video_catalogue_update_row(video_obj)

                # Prepare icons
                if isinstance(video_obj.parent_obj, media.Channel):
                    pixbuf = self.pixbuf_dict['channel_small']
                elif isinstance(video_obj.parent_obj, media.Channel):
                    pixbuf = self.pixbuf_dict['playlist_small']
                else:
                    pixbuf = self.pixbuf_dict['folder_small']

                # Update the corresponding row in the Results List
                tree_path = Gtk.TreePath(temp_dict['row_num'])
                row_iter = self.results_list_liststore.get_iter(tree_path)

                self.results_list_liststore.set(
                    row_iter,
                    2,
                    utils.shorten_string(
                        video_obj.nickname,
                        self.string_max_len,
                    ),
                )

                if video_obj.duration is not None:
                    self.results_list_liststore.set(
                        row_iter,
                        3,
                        utils.convert_seconds_to_string(
                            video_obj.duration,
                        ),
                    )

                if video_obj.file_size:
                    self.results_list_liststore.set(
                        row_iter,
                        4,
                        video_obj.get_file_size_string(),
                    )

                if video_obj.upload_time:
                    self.results_list_liststore.set(
                        row_iter,
                        5,
                        video_obj.get_upload_date_string(),
                    )

                self.results_list_liststore.set(row_iter, 6, video_obj.dl_flag)
                self.results_list_liststore.set(row_iter, 7, pixbuf)

                self.results_list_liststore.set(
                    row_iter,
                    8,
                    utils.shorten_string(
                        video_obj.parent_obj.name,
                        self.string_max_len,
                    ),
                )

            else:

                # File not found

                # If this was a simulated download, the key 'keep_description'
                #   won't exist in temp_dict
                # For simulated downloads, we only check once (in case the
                #   video file already existed on the user's filesystem)
                # For real downloads, we check again on the next call to this
                #   function
                if 'keep_description' in temp_dict:
                    new_temp_list.append(temp_dict)

        # Any files that don't exist yet must be checked on the next call to
        #   this function
        self.results_list_temp_list = new_temp_list


    # (Output tab)

    def output_tab_setup_pages(self):

        """Called by mainapp.TartubeApp.start() and .set_num_worker_default().

        Makes sure there are enough pages in the Output Tab's notebook for
        each simultaneous download allowed (a value specified by
        mainapp.TartubeApp.num_worker_default).
        """

        if DEBUG_FUNC_FLAG:
            print('mw 5106 output_tab_setup_pages')

        # The number of pages in the notebook should match the highest value of
        #   mainapp.TartubeApp.num_worker_default during this session (i.e. if
        #   the user reduces its value, we don't remove pages; but we do add
        #   pages if the user increases its value)
        if self.output_page_count < self.app_obj.num_worker_default:

            for num in range(1, (self.app_obj.num_worker_default + 1)):
                if not num in self.output_textview_dict:
                    self.output_tab_add_page()


    def output_tab_add_page(self):

        """Called by self.output_tab_setup_pages().

        Adds a new page to the Output Tab's notebook, and updates IVs.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 5106 output_tab_add_page')

        # Each page corresponds to a single downloads.DownloadWorker object.
        #   The page number matches the worker's .worker_id. The first page/
        #   worker is numbered #1
        self.output_page_count += 1

        # Add the new page
        tab = Gtk.Box()
        label = Gtk.Label.new_with_mnemonic(
            'Thread #_' + str(self.output_page_count),
        )
        self.output_notebook.append_page(tab, label)
        tab.set_hexpand(True)
        tab.set_vexpand(True)
        tab.set_border_width(self.spacing_size)

        # Add a textview to the tab, using a css style sheet to provide
        #   monospaced white text on a black background
        scrolled = Gtk.ScrolledWindow()
        tab.pack_start(scrolled, True, True, 0)
        scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)

        frame = Gtk.Frame()
        scrolled.add_with_viewport(frame)

        style_provider = self.output_tab_set_textview_css(
            '#css_text_id_' + str(self.output_page_count) \
            + ', textview text {\n' \
            + '   background-color: #000000;\n' \
            + '   color: #FFFFFF;\n' \
            + '}\n' \
            + '#css_label_id_' + str(self.output_page_count) \
            + ', textview {\n' \
            + '   font-family: monospace, monospace;\n' \
            + '   font-size: 10pt;\n' \
            + '}'
        )

        textview = Gtk.TextView()
        frame.add(textview)
        textview.set_wrap_mode(Gtk.WrapMode.WORD)
        textview.set_editable(False)
        textview.set_cursor_visible(False)

        context = textview.get_style_context()
        context.add_provider(style_provider, 600)

        # Reset css properties for the next Gtk.TextView created (for example,
        #   by AddVideoDialogue) so it uses default values, rather than the
        #   white text on black background used above
        # To do that, create a dummy textview, and apply a css style to it
        textview2 = Gtk.TextView()
        style_provider2 = self.output_tab_set_textview_css(
            '#css_text_id_default, textview text {\n' \
            + '   background-color: unset;\n' \
            + '   color: unset;\n' \
            + '}\n' \
            + '#css_label_id_default, textview {\n' \
            + '   font-family: unset;\n' \
            + '   font-size: unset;\n' \
            + '}'
        )

        context = textview2.get_style_context()
        context.add_provider(style_provider2, 600)

        # Set up auto-scrolling
        textview.connect(
            'size-allocate',
            self.output_tab_do_autoscroll,
            scrolled,
        )

        # Make the page visible
        self.show_all()

        # Update IVs
        self.output_textview_dict[self.output_page_count] = textview


    def output_tab_set_textview_css(self, css_string):

        """Called by self.output_tab_add_page().

        Applies a CSS style to the current screen. Called once to create a
        white-on-black Gtk.TextView, then a second time to create a dummy
        textview with default properties.

        Args:

            css_string (str): The CSS style to apply

        Return values:

            The Gtk.CssProvider created

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5107 output_tab_set_textview_css')

        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(bytes(css_string.encode()))
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(),
            style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )

        return style_provider


    def output_tab_write_stdout(self, page_num, msg):

        """Called by downloads.VideoDownloader.do_download() and by various
        functions in refresh.RefreshManager.

        During a download operation, youtube-dl sends output to STDOUT. If
        permitted, this output is displayed in the Output Tab. However, it
        can't be displayed immediately, because Gtk widgets can't be updated
        from within a thread.

        Instead, add the received values to a list, and wait for the GObject
        timer mainapp.TartubeApp.dl_timer_id to call self.output_tab_update().

        Args:

            page_num (int): The page number on which this message should be
                displayed. Matches a key in self.output_textview_dict

            msg (str): The message to display. A newline character will be
                added by self.output_tab_update_pages().

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5107 output_tab_write_stdout')

        self.output_tab_insert_list.extend( [page_num, msg, False] )


    def output_tab_write_stderr(self, page_num, msg):

        """Called by downloads.VideoDownloader.do_download().

        During a download operation, youtube-dl sends output to STDERR. If
        permitted, this output is displayed in the Output Tab. However, it
        can't be displayed immediately, because Gtk widgets can't be updated
        from within a thread.

        Instead, add the received values to a list, and wait for the GObject
        timer mainapp.TartubeApp.dl_timer_id to call self.output_tab_update().

        Args:

            page_num (int): The page number on which this message should be
                displayed. Matches a key in self.output_textview_dict

            msg (str): The message to display. A newline character will be
                added by self.output_tab_update_pages().

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5107 output_tab_write_stderr')

        self.output_tab_insert_list.extend( [page_num, msg, True] )


    def output_tab_update_pages(self):

        """Called by mainapp.TartubeApp.dl_timer_callback(),
        .refresh_timer_callback() and .refresh_manager_finished().

        During a download operation, youtube-dl sends output to STDOUT/STDERR.
        If permitted, this output is displayed in the Output Tab. However, it
        can't be displayed immediately, because Gtk widgets can't be updated
        from within a thread.

        Instead, the output has been added to self.output_tab_insert_list. This
        output can now be displayed (and the list can be emptied).
        """

        if DEBUG_FUNC_FLAG:
            print('mw 5108 output_tab_update_pages')

        if self.output_tab_insert_list:

            while self.output_tab_insert_list:

                page_num = self.output_tab_insert_list.pop(0)
                msg = self.output_tab_insert_list.pop(0)
                error_flag = self.output_tab_insert_list.pop(0)

                # Add the output to the textview. STDERR messages are displayed
                #   in cyan text
                textview = self.output_textview_dict[page_num]
                textbuffer = textview.get_buffer()

                if not error_flag:
                    textbuffer.insert(textbuffer.get_end_iter(), msg + '\n')
                else:
                    string = '<span color="{:s}">' + msg + '</span>\n'
                    textbuffer.insert_markup(
                        textbuffer.get_end_iter(),
                        string.format('cyan'),
                        -1,
                    )

            # Make the new output visible
            for textview in self.output_textview_dict.values():
                textview.show_all()


    def output_tab_do_autoscroll(self, textview, rect, scrolled):

        """Called from a callback in self.output_tab_add_page().

        When one of the textviews in the Output Tab is modified (text added or
        removed), make sure the page is scrolled to the bottom.

        Args:

            textview (Gtk.TextView): The textview to scroll

            rect (Gdk.Rectangle): Ignored

            scrolled (Gtk.ScrolledWindow): The scroller which contains the
                textview

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5108 output_tab_do_autoscroll')

        adj = scrolled.get_vadjustment()
        adj.set_value(adj.get_upper() - adj.get_page_size())


    def output_tab_scroll_visible_page(self, page_num):

        """Called by self.on_output_notebook_switch_page() and
        .on_notebook_switch_page().

        When the user switches between pages in the Output Tab, scroll the
        visible textview to the bottom (otherwise it gets confusing).

        Args:

            page_num (int): The page to be scrolled, matching a key in
                self.output_textview_dict

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5109 output_tab_scroll_visible_page')

        if page_num in self.output_textview_dict:
            textview = self.output_textview_dict[page_num]

            frame = textview.get_parent()
            viewport = frame.get_parent()
            scrolled = viewport.get_parent()

            adj = scrolled.get_vadjustment()
            adj.set_value(adj.get_upper() - adj.get_page_size())


    def output_tab_reset_pages(self):

        """Called by mainapp.TartubeApp.download_manager_start() and
        .refresh_manager_start().

        At the start of a download/refresh operation, empty the pages in the
        Output Tab (if allowed).
        """

        if DEBUG_FUNC_FLAG:
            print('mw 5110 output_tab_clear_pages')

        for textview in self.output_textview_dict.values():
            textbuffer = textview.get_buffer()
            textbuffer.set_text('')
            textview.show_all()


    # (Errors Tab)


    def errors_list_reset(self):

        """Called by self.on_errors_list_clear() and various functions in the
        main application.

        Empties the Gtk.TreeView in the Errors List, ready for it to be
        refilled.

        (There are no IVs to reset.)
        """

        if DEBUG_FUNC_FLAG:
            print('mw 5249 errors_list_reset')

        # Reset widgets
        self.errors_list_liststore = Gtk.ListStore(
            GdkPixbuf.Pixbuf, GdkPixbuf.Pixbuf,
            str, str, str,
        )
        self.errors_list_treeview.set_model(self.errors_list_liststore)

        self.tab_error_count = 0
        self.tab_warning_count = 0
        self.errors_list_refresh_label()


    def errors_list_add_row(self, media_data_obj):

        """Called by downloads.DownloadWorker.run().

        When a download job generates error and/or warning messages, display
        this function is called to display them in the Errors List.

        Args:

            media_data_obj (media.Video, media.Channel or media.Playlist): The
                media data object whose download (real or simulated) generated
                the error/warning messages.

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5279 errors_list_add_row')

        # Create a new row for every error and warning message
        # Use the same time on each
        utc = datetime.datetime.utcfromtimestamp(time.time())
        time_string = str(utc.strftime('%H:%M:%S'))

        for msg in media_data_obj.error_list:

            # Prepare the icons
            pixbuf = self.pixbuf_dict['error_small']

            if isinstance(media_data_obj, media.Video):
                pixbuf2 = self.pixbuf_dict['video_small']
            elif isinstance(media_data_obj, media.Channel):
                pixbuf2 = self.pixbuf_dict['channel_small']
            elif isinstance(media_data_obj, media.Playlist):
                pixbuf2 = self.pixbuf_dict['playlist_small']
            else:
                return self.app_obj.system_error(
                    214,
                    'Errors List add row request failed sanity check',
                )

            # Prepare the new row in the treeview
            row_list = []
            row_list.append(pixbuf)
            row_list.append(pixbuf2)
            row_list.append(time_string)
            row_list.append(
                utils.shorten_string(media_data_obj.name, self.string_max_len),
            )
            row_list.append(utils.tidy_up_long_string(msg))

            # Create a new row in the treeview. Doing the .show_all() first
            #   prevents a Gtk error (for unknown reasons)
            self.errors_list_treeview.show_all()
            self.errors_list_liststore.append(row_list)

            # (Don't update the Errors/Warnings tab label if it's the visible
            #   tab)
            if self.visible_tab_num != 3:
                self.tab_error_count += 1

        for msg in media_data_obj.warning_list:

            # Prepare the icons
            pixbuf = self.pixbuf_dict['warning_small']

            if isinstance(media_data_obj, media.Video):
                pixbuf2 = self.pixbuf_dict['video_small']
            elif isinstance(media_data_obj, media.Channel):
                pixbuf2 = self.pixbuf_dict['channel_small']
            elif isinstance(media_data_obj, media.Playlist):
                pixbuf2 = self.pixbuf_dict['playlist_small']
            else:
                return self.app_obj.system_error(
                    215,
                    'Errors List add row request failed sanity check',
                )

            # Prepare the new row in the treeview
            row_list = []
            row_list.append(pixbuf)
            row_list.append(pixbuf2)
            row_list.append(time_string)
            row_list.append(
                utils.shorten_string(media_data_obj.name, self.string_max_len),
            )
            row_list.append(utils.tidy_up_long_string(msg))

            # Create a new row in the treeview. Doing the .show_all() first
            #   prevents a Gtk error (for unknown reasons)
            self.errors_list_treeview.show_all()
            self.errors_list_liststore.append(row_list)

            # (Don't update the Errors/Warnings tab label if it's the visible
            #   tab)
            if self.visible_tab_num != 3:
                self.tab_warning_count += 1

        # Update the tab's label to show the number of warnings/errors visible
        if self.visible_tab_num != 3:
            self.errors_list_refresh_label()


    def errors_list_add_system_error(self, error_code, msg):

        """Can be called by anything. The quickest way is to call
        mainapp.TartubeApp.system_error(), which acts as a wrapper for this
        function.

        Display a system error message in the Errors List.

        Args:

            error_code (int): An error code in the range 100-999 (see
                the .system_error() function)

            msg (str): The system error message to display

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5383 errors_list_add_system_error')

        # Prepare the icons
        pixbuf = self.pixbuf_dict['error_small']
        pixbuf2 = self.pixbuf_dict['system_error_small']

        # Prepare the new row in the treeview
        row_list = []
        utc = datetime.datetime.utcfromtimestamp(time.time())
        time_string = str(utc.strftime('%H:%M:%S'))

        row_list.append(pixbuf)
        row_list.append(pixbuf2)
        row_list.append(time_string)
        row_list.append(
            utils.upper_case_first(__main__.__packagename__) + ' error',
        )
        row_list.append(
            utils.tidy_up_long_string('#' + str(error_code) + ': ' + msg),
        )

        # Create a new row in the treeview. Doing the .show_all() first
        #   prevents a Gtk error (for unknown reasons)
        self.errors_list_treeview.show_all()
        self.errors_list_liststore.append(row_list)

        # (Don't update the Errors/Warnings tab label if it's the visible
        #   tab)
        if self.visible_tab_num != 3:
            self.tab_error_count += 1
            self.errors_list_refresh_label()


    def errors_list_add_system_warning(self, error_code, msg):

        """Can be called by anything. The quickest way is to call
        mainapp.TartubeApp.system_warning(), which acts as a wrapper for this
        function.

        Display a system warning message in the Errors List.

        Args:

            error_code (int): An error code in the range 100-999 (see
                the .system_error() function)

            msg (str): The system warning message to display

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5434 errors_list_add_system_warning')

        # Prepare the icons
        pixbuf = self.pixbuf_dict['warning_small']
        pixbuf2 = self.pixbuf_dict['system_warning_small']

        # Prepare the new row in the treeview
        row_list = []
        utc = datetime.datetime.utcfromtimestamp(time.time())
        time_string = str(utc.strftime('%H:%M:%S'))

        row_list.append(pixbuf)
        row_list.append(pixbuf2)
        row_list.append(time_string)
        row_list.append(
            utils.upper_case_first(__main__.__packagename__) + ' warning',
        )
        row_list.append(
            utils.tidy_up_long_string('#' + str(error_code) + ': ' + msg) \
            + '\n\n' + utils.tidy_up_long_string(
                'To disable system warning messages, click Edit >' \
                + ' System preferences... > Windows, and then deselect \'' \
                + 'Show system warning messages in the \'Errors/Warnings\'' \
                + ' tab\'',
            ),
        )

        # Create a new row in the treeview. Doing the .show_all() first
        #   prevents a Gtk error (for unknown reasons)
        self.errors_list_treeview.show_all()
        self.errors_list_liststore.append(row_list)

        # (Don't update the Errors/Warnings tab label if it's the visible
        #   tab)
        if self.visible_tab_num != 3:
            self.tab_warning_count += 1
            self.errors_list_refresh_label()


    def errors_list_refresh_label(self):

        """Called by self.errors_list_add_row(),
        .errors_list_add_system_error() and .on_notebook_switch_page().

        When the Errors / Warnings tab becomes the visible one, reset the
        tab's label (to show 'Errors / Warnings')

        When an error or warning is added to the Error List, refresh the tab's
        label (to show something like 'Errors (4) / Warnings (1)' )
        """

        if DEBUG_FUNC_FLAG:
            print('mw 5486 errors_list_refresh_label')

        text = '_Errors'
        if self.tab_error_count:
            text += ' (' + str(self.tab_error_count) + ')'

        text += ' / Warnings'
        if self.tab_warning_count:
            text += ' (' + str(self.tab_warning_count) + ')'

        self.errors_label.set_text_with_mnemonic(text)


    # Callback class methods


    def on_notebook_switch_page(self, notebook, box, page_num):

        """Called from callback in self.setup_notebook().

        The Errors / Warnings tab shows the number of errors/warnings in its
        tab label. When the user switches to this tab, reset the tab label.

        Args:

            notebook (Gtk.Notebook): The main window's notebook, providing
                several tabs

            box (Gtk.Box) - The box in which the tab's widgets are placed

            page_num (int) - The number of the newly-visible tab (the Videos
                Tab is number 0)

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5522 on_notebook_switch_page')

        self.visible_tab_num = page_num

        if page_num == 2:
            # Switching between tabs causes pages in the Output Tab to scroll
            #   to the top. Make sure they're all scrolled back to the bottom
            for page_num in range(1, (self.output_page_count + 1)):
                self.output_tab_scroll_visible_page(page_num)

        elif page_num == 3 and not self.app_obj.system_msg_keep_totals_flag:
            # Update the tab's label
            self.tab_error_count = 0
            self.tab_warning_count = 0
            self.errors_list_refresh_label()


    def on_output_notebook_switch_page(self, notebook, box, page_num):

        """Called from callback in self.setup_output_tab().

        When the user switches between pages in the Output Tab, scroll the
        visible textview to the bottom (otherwise it gets confusing).

        Args:

            notebook (Gtk.Notebook): The Output Tab's notebook, providing
                several pages

            box (Gtk.Box) - The box in which the page's widgets are placed

            page_num (int) - The number of the newly-visible page (the first
                page is number 0)

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5523 on_ouput_notebook_switch_page')

        # Output Tab IVs number the first page as #1, and so on
        self.output_tab_scroll_visible_page(page_num + 1)


    def on_video_index_apply_options(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Adds a set of download options (handled by an
        options.OptionsManager object) to the specified media data object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5549 on_video_index_apply_options')

        if self.app_obj.current_manager_obj \
        or media_data_obj.options_obj\
        or (
            isinstance(media_data_obj, media.Folder)
            and media_data_obj.priv_flag
        ):
            return self.app_obj.system_error(
                216,
                'Callback request denied due to current conditions',
            )

        # Apply download options to the media data object
        self.app_obj.apply_download_options(media_data_obj)

        # Open an edit window to show the options immediately
        config.OptionsEditWin(
            self.app_obj,
            media_data_obj.options_obj,
            media_data_obj,
        )


    def on_video_index_dl_disable(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Set the media data object's flag to disable checking and downloading.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5589 on_video_index_dl_disable')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                217,
                'Callback request denied due to current conditions',
            )

        if not media_data_obj.dl_disable_flag:
            media_data_obj.set_dl_disable_flag(True)
        else:
            media_data_obj.set_dl_disable_flag(False)

        self.video_index_update_row_text(media_data_obj)


    def on_video_index_check(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Check the right-clicked media data object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5621 on_video_index_check')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                218,
                'Callback request denied due to current conditions',
            )

        # Start a download operation
        self.app_obj.download_manager_start(True, False, [media_data_obj] )


    def on_video_index_delete_container(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Deletes the channel, playlist or folder.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Folder):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5649 on_video_index_delete_container')

        self.app_obj.delete_container(media_data_obj)


    def on_video_index_download(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Download the right-clicked media data object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5670 on_video_index_download')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                219,
                'Callback request denied due to current conditions',
            )

        # Start a download operation
        self.app_obj.download_manager_start(False, False, [media_data_obj] )


    def on_video_index_drag_data_received(self, treeview, drag_context, x, y, \
    selection_data, info, timestamp):

        """Called from callback in self.setup_videos_tab().

        Retrieve the source and destination media data objects, and pass them
        on to a function in the main application.

        Args:

            treeview (Gtk.TreeView): The Video Index's treeview

            drag_context (GdkX11.X11DragContext): Data from the drag procedure

            x, y (int): Cell coordinates in the treeview

            selection_data (Gtk.SelectionData): Data from the dragged row

            info (int): Ignored

            timestamp (int): Ignored

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5707 on_video_index_drag_data_received')

        # Must override the usual Gtk handler
        treeview.stop_emission('drag_data_received')

        # Extract the drop destination
        drop_info = treeview.get_dest_row_at_pos(x, y)
        if drop_info is not None:

            # Get the dragged media data object
            old_selection = self.video_index_treeview.get_selection()
            (model, start_iter) = old_selection.get_selected()
            drag_name = model[start_iter][1]

            # Get the destination media data object
            drop_path, drop_posn = drop_info[0], drop_info[1]
            drop_iter = model.get_iter(drop_path)
            dest_name = model[drop_iter][1]

            if drag_name and dest_name:

                drag_id = self.app_obj.media_name_dict[drag_name]
                dest_id = self.app_obj.media_name_dict[dest_name]

                self.app_obj.move_container(
                    self.app_obj.media_reg_dict[drag_id],
                    self.app_obj.media_reg_dict[dest_id],
                )


    def on_video_index_drag_drop(self, treeview, drag_context, x, y, time):

        """Called from callback in self.setup_videos_tab().

        Override the usual Gtk handler, and allow
        self.on_video_index_drag_data_received() to collect the results of the
        drag procedure.

        Args:

            treeview (Gtk.TreeView): The Video Index's treeview

            drag_context (GdkX11.X11DragContext): Data from the drag procedure

            x, y (int): Cell coordinates in the treeview

            time (int): A timestamp

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5758 on_video_index_drag_drop')

        # Must override the usual Gtk handler
        treeview.stop_emission('drag_drop')

        # The second of these lines cause the 'drag-data-received' signal to be
        #   emitted
        target_list = drag_context.list_targets()
        treeview.drag_get_data(drag_context, target_list[-1], time)


    def on_video_index_edit_options(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Edit the download options (handled by an
        options.OptionsManager object) for the specified media data object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5786 on_video_index_edit_options')

        if self.app_obj.current_manager_obj or not media_data_obj.options_obj:
            return self.app_obj.system_error(
                220,
                'Callback request denied due to current conditions',
            )

        # Open an edit window
        config.OptionsEditWin(
            self.app_obj,
            media_data_obj.options_obj,
            media_data_obj,
        )


    def on_video_index_empty_folder(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Empties the folder.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Folder): The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5817 on_video_index_empty_folder')

        # The True flag tells the function to empty the container, rather than
        #   delete it
        self.app_obj.delete_container(media_data_obj, True)


    def on_video_index_enforce_check(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Set the media data object's flag to force checking of the channel/
        playlist/folder (disabling actual downloads).

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5841 on_video_index_enforce_check')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                221,
                'Callback request denied due to current conditions',
            )

        if not media_data_obj.dl_sim_flag:
            media_data_obj.set_dl_sim_flag(True)
        else:
            media_data_obj.set_dl_sim_flag(False)

        self.video_index_update_row_text(media_data_obj)


    def on_video_index_export(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Exports a summary of the database, containing the selected channel/
        playlist/folder and its descendants.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5874 on_video_index_export')

        self.app_obj.export_from_db( [media_data_obj] )


    def on_video_index_mark_archived(self, menu_item, media_data_obj,
    only_child_videos_flag):

        """Called from a callback in self.video_index_popup_menu().

        Mark all of the children of this channel, playlist or folder (and all
        of their chidlren, and so on) as archived.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

            only_child_videos_flag (True or False): Set to True if only child
                video objects should be marked; False if all descendants should
                be marked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5901 on_video_index_mark_archived')

        self.app_obj.mark_container_archived(
            media_data_obj,
            True,
            only_child_videos_flag,
        )


    def on_video_index_mark_not_archived(self, menu_item, media_data_obj,
    only_child_videos_flag):

        """Called from a callback in self.video_index_popup_menu().

        Mark all videos in this folder (and in any child channels, playlists
        and folders) as not archived.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

            only_child_videos_flag (True or False): Set to True if only child
                video objects should be marked; False if all descendants should
                be marked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5932 on_video_index_mark_not_archived')

        self.app_obj.mark_container_archived(
            media_data_obj,
            False,
            only_child_videos_flag,
        )


    def on_video_index_mark_favourite(self, menu_item, media_data_obj,
    only_child_videos_flag):

        """Called from a callback in self.video_index_popup_menu().

        Mark all of the children of this channel, playlist or folder (and all
        of their chidlren, and so on) as favourite.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

            only_child_videos_flag (True or False): Set to True if only child
                video objects should be marked; False if all descendants should
                be marked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5963 on_video_index_mark_favourite')

        self.app_obj.mark_container_favourite(
            media_data_obj,
            True,
            only_child_videos_flag,
        )


    def on_video_index_mark_not_favourite(self, menu_item, media_data_obj,
    only_child_videos_flag):

        """Called from a callback in self.video_index_popup_menu().

        Mark all videos in this folder (and in any child channels, playlists
        and folders) as not favourite.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

            only_child_videos_flag (True or False): Set to True if only child
                video objects should be marked; False if all descendants should
                be marked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 5994 on_video_index_mark_not_favourite')

        self.app_obj.mark_container_favourite(
            media_data_obj,
            False,
            only_child_videos_flag,
        )


    def on_video_index_hide_folder(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Hides the folder in the Video Index.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6019 on_video_index_hide_folder')

        self.app_obj.mark_folder_hidden(media_data_obj, True)


    def on_video_index_mark_new(self, menu_item, media_data_obj,
    only_child_videos_flag):

        """Called from a callback in self.video_index_popup_menu().

        Mark all videos in this channel, playlist or folder (and in any child
        channels, playlists and folders) as new (but only if they have been
        downloaded).

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

            only_child_videos_flag (True or False): Set to True if only child
                video objects should be marked; False if all descendants should
                be marked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6047 on_video_index_mark_new')

        # Special arrangements for private folders
        # (Don't need to check the 'New Videos' folder, as the popup menu item
        #   is commented out for that)
        if media_data_obj == self.app_obj.fixed_all_folder:

            # Check every video
            for other_obj in list(self.app_obj.media_reg_dict.values()):

                if isinstance(other_obj, media.Video):
                    self.app_obj.mark_video_new(other_obj, True)

        elif media_data_obj == self.app_obj.fixed_fav_folder:

            # Check every favourite video
            for other_obj in list(self.app_obj.media_reg_dict.values()):

                if isinstance(other_obj, media.Video) and other_obj.fav_flag:
                    self.app_obj.mark_video_new(other_obj, True)

        elif only_child_videos_flag:

            # Check only videos that are children of the specified media data
            #   object
            for other_obj in media_data_obj.child_list:
                if isinstance(other_obj, media.Video):
                    self.app_obj.mark_video_new(other_obj, True)

        else:

            # Check only videos that are descendants of the specified media
            #   data object
            for other_obj in media_data_obj.compile_all_videos( [] ):

                # (Only downloaded videos can be marked as new)
                if other_obj.dl_flag:
                    self.app_obj.mark_video_new(other_obj, True)


    def on_video_index_mark_not_new(self, menu_item, media_data_obj,
    only_child_videos_flag):

        """Called from a callback in self.video_index_popup_menu().

        Mark all videos in this channel, playlist or folder (and in any child
        channels, playlists and folders) as not new.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

            only_child_videos_flag (True or False): Set to True if only child
                video objects should be marked; False if all descendants should
                be marked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6109 on_video_index_mark_not_new')

        # Special arrangements for private folders
        if media_data_obj == self.app_obj.fixed_all_folder \
        or media_data_obj == self.app_obj.fixed_new_folder:

            # Check every video
            for other_obj in list(self.app_obj.media_reg_dict.values()):

                if isinstance(other_obj, media.Video):
                    self.app_obj.mark_video_new(other_obj, False)

        elif media_data_obj == self.app_obj.fixed_fav_folder:

            # Check every favourite video
            for other_obj in list(self.app_obj.media_reg_dict.values()):

                if isinstance(other_obj, media.Video) and other_obj.fav_flag:
                    self.app_obj.mark_video_new(other_obj, False)

        elif only_child_videos_flag:

            # Check only videos that are children of the specified media data
            #   object
            for other_obj in media_data_obj.child_list:
                if isinstance(other_obj, media.Video):
                    self.app_obj.mark_video_new(other_obj, False)

        else:

            # Check only videos that are descendants of the specified media
            #   data object
            for other_obj in media_data_obj.compile_all_videos( [] ):
                self.app_obj.mark_video_new(other_obj, False)


    def on_video_index_move_to_top(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Moves a channel, playlist or folder to the top level (in other words,
        removes its parent folder).

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6162 on_video_index_move_to_top')

        self.app_obj.move_container_to_top(media_data_obj)


    def on_video_index_refresh(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Refresh the right-clicked media data object, checking the corresponding
        directory on the user's filesystem against video objects in the
        database.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6185 on_video_index_refresh')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                222,
                'Callback request denied due to current conditions',
            )

        # Start a refresh operation
        self.app_obj.refresh_manager_start(media_data_obj)


    def on_video_index_remove_options(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Removes a set of download options (handled by an
        options.OptionsManager object) from the specified media data object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6214 on_video_index_remove_options')

        if self.app_obj.current_manager_obj \
        or not media_data_obj.options_obj:
            return self.app_obj.system_error(
                223,
                'Callback request denied due to current conditions',
            )

        # Remove download options from the media data object
        self.app_obj.remove_download_options(media_data_obj)


    def on_video_index_remove_videos(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Empties all child videos of a folder object, but doesn't remove any
        child channel, playlist or folder objects.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Folder): The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6243 on_video_index_remove_videos')

        for child_obj in media_data_obj.child_list:
            if isinstance(child_obj, media.Video):
                self.app_obj.delete_video(child_obj)


    def on_video_index_rename_location(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Renames a channel, playlist or folder. Also renames the corresponding
        directory in Tartube's data directory.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6267 on_video_index_rename_location')

        self.app_obj.rename_container(media_data_obj)


    def on_video_index_right_click(self, treeview, event):

        """Called from callback in self.setup_videos_tab().

        When the user right-clicks an item in the Video Index, create a
        context-sensitive popup menu.

        Args:

            treeview (Gtk.TreeView): The Video Index's treeview

            event (Gdk.EventButton): The event emitting the Gtk signal

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6288 on_video_index_right_click')

        if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:

            # If the user right-clicked on empty space, the call to
            #   .get_path_at_pos returns None (or an empty list)
            if not treeview.get_path_at_pos(
                int(event.x),
                int(event.y),
            ):
                return

            path, column, cellx, celly = treeview.get_path_at_pos(
                int(event.x),
                int(event.y),
            )

            iter = self.video_index_sortmodel.get_iter(path)
            if iter is not None:
                self.video_index_popup_menu(
                    event,
                    self.video_index_sortmodel[iter][1],
                )


    def on_video_index_selection_changed(self, selection):

        """Called from callback in self.video_index_reset().

        Also called from callbacks in mainapp.TartubeApp.on_menu_test,
        .on_button_switch_view() and .on_menu_add_video().

        When the user clicks to select an item in the Video Index, call a
        function to update the Video Catalogue.

        Args:

            selection (Gtk.TreeSelection): Data for the selected row

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6330 on_video_index_selection_changed')

        (model, iter) = selection.get_selected()
        if iter is None or not model.iter_is_valid(iter):
            return
        else:
            name = model[iter][1]

        # Don't update the Video Catalogue during certain procedures, such as
        #   removing a row from the Video Index (in which case, the flag will
        #   be set)
        if not self.ignore_video_index_select_flag:

            if iter is None:
                self.video_index_current = None
                self.video_index_current_priv_flag = False
                self.video_catalogue_reset()

            else:

                # Update IVs
                self.video_index_current = name

                dbid = self.app_obj.media_name_dict[name]
                media_data_obj = self.app_obj.media_reg_dict[dbid]

                if isinstance(media_data_obj, media.Folder) \
                and media_data_obj.priv_flag:
                    self.video_index_current_priv_flag = True
                else:
                    self.video_index_current_priv_flag = False

                # Expand the tree beneath the selected line, if allowed
                if self.app_obj.auto_expand_video_index_flag:
                    self.video_index_treeview.expand_to_path(
                        model.get_path(iter),
                    )

                # Redraw the Video Catalogue, on the first page, and reset its
                #   scrollbars back to the top
                self.video_catalogue_redraw_all(name, 1, True)


    def on_video_index_set_destination(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Sets (or resets) the alternative download destination for the selected
        channel, playlist or folder.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6390 on_video_index_set_destination')

        if isinstance(media_data_obj, media.Video):
            return self.app_obj.system_error(
                224,
                'Cannot set the download destination of a video',
            )

        dialogue_win = SetDestinationDialogue(self, media_data_obj)
        response = dialogue_win.run()

        # Retrieve user choices from the dialogue window, before destroying it
        dbid = dialogue_win.choice
        dialogue_win.destroy()

        if response == Gtk.ResponseType.OK:

            if dbid != media_data_obj.master_dbid:
                media_data_obj.set_master_dbid(self.app_obj, dbid)


    def on_video_index_set_nickname(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Sets (or resets) the nickname for the selected channel, playlist or
        folder.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6428 on_video_index_set_nickname')

        if isinstance(media_data_obj, media.Video):
            return self.app_obj.system_error(
                225,
                'Cannot set the nickname of a video',
            )

        dialogue_win = SetNicknameDialogue(self, media_data_obj)
        response = dialogue_win.run()

        # Retrieve user choices from the dialogue window, before destroying it
        nickname = dialogue_win.entry.get_text()
        dialogue_win.destroy()

        if response == Gtk.ResponseType.OK:

            # If nickname is an empty string, then the call to .set_nickname()
            #   resets the .nickname IV to match the .name IV
            media_data_obj.set_nickname(nickname)

            # Update the name displayed in the Video Index
            self.video_index_update_row_text(media_data_obj)


    def on_video_index_show_destination(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Opens the sub-directory in which downloads for the specified media data
        object are stored (which might be the default sub-directory for
        another media data object, if the media data object's .master_dbid has
        been modified).

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6472 on_video_index_show_destination')

        other_obj = self.app_obj.media_reg_dict[media_data_obj.master_dbid]
        path = other_obj.get_dir(self.app_obj)
        utils.open_file(path)


    def on_video_index_show_location(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Opens the sub-directory in which downloads for the specified media data
        object are stored (by default).

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6496 on_video_index_show_location')

        path = media_data_obj.get_dir(self.app_obj)
        utils.open_file(path)


    def on_video_index_show_properties(self, menu_item, media_data_obj):

        """Called from a callback in self.video_index_popup_menu().

        Opens an edit window for the media data object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Channel, media.Playlist or media.Channel):
                The clicked media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6518 on_video_index_show_properties')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                226,
                'Callback request denied due to current conditions',
            )

        # Open the edit window immediately
        if isinstance(media_data_obj, media.Folder):
            config.FolderEditWin(self.app_obj, media_data_obj)
        else:
            config.ChannelPlaylistEditWin(self.app_obj, media_data_obj)


    def on_video_catalogue_apply_options(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Adds a set of download options (handled by an
        options.OptionsManager object) to the specified video object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6549 on_video_catalogue_apply_options')

        if self.app_obj.current_manager_obj or media_data_obj.options_obj:
            return self.app_obj.system_error(
                227,
                'Callback request denied due to current conditions',
            )

        # Apply download options to the media data object
        media_data_obj.set_options_obj(options.OptionsManager())
        # Update the video catalogue to show the right icon
        self.video_catalogue_update_row(media_data_obj)

        # Open an edit window to show the options immediately
        config.OptionsEditWin(
            self.app_obj,
            media_data_obj.options_obj,
            media_data_obj,
        )


    def on_video_catalogue_check(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Check the right-clicked media data object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6585 on_video_catalogue_check')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                228,
                'Callback request denied due to current conditions',
            )

        # Start a download operation
        self.app_obj.download_manager_start(True, False, [media_data_obj] )


    def on_video_catalogue_check_multi(self, menu_item, media_data_list):

        """Called from a callback in self.video_catalogue_multi_popup_menu().

        Check the right-clicked media data object(s).

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_list (list): List of one or more media.Video objects

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6612 on_video_catalogue_check_multi')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                229,
                'Callback request denied due to current conditions',
            )

        # Start a download operation
        self.app_obj.download_manager_start(True, False, media_data_list)

        # Standard de-selection of everything in the Video Catalogue
        self.catalogue_listbox.unselect_all()


    def on_video_catalogue_delete_video(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Deletes the right-clicked media data object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6642 on_video_catalogue_delete_video')

        self.app_obj.delete_video(media_data_obj, True)


    def on_video_catalogue_delete_video_multi(self, menu_item,
    media_data_list):

        """Called from a callback in self.video_catalogue_multi_popup_menu().

        Deletes the right-clicked media data objects.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_list (list): List of one or more media.Video objects

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6663 on_video_catalogue_delete_video_multi')

        for media_data_obj in media_data_list:
            self.app_obj.delete_video(media_data_obj, True)

        # Standard de-selection of everything in the Video Catalogue
        self.catalogue_listbox.unselect_all()


    def on_video_catalogue_dl_and_watch(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Downloads a video and then opens it using the system's default media
        player.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6688 on_video_catalogue_dl_and_watch')

        # Can't download the video if it has no source, or if an update/
        #   refresh operation has started since the popup menu was created
        if not media_data_obj.dl_flag or not media_data_obj.source \
        or self.app_obj.update_manager_obj \
        or self.app_obj.refresh_manager_obj:

            # Download the video, and mark it to be opened in the system's
            #   default media player as soon as the download operation is
            #   complete
            # If a download operation is already in progress, the video is
            #   added to it
            self.app_obj.download_watch_videos( [media_data_obj] )


    def on_video_catalogue_dl_and_watch_multi(self, menu_item,
    media_data_list):

        """Called from a callback in self.video_catalogue_multi_popup_menu().

        Download the videos and then open them using the system's default media
        player.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_list (list): List of one or more media.Video objects

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6721 on_video_catalogue_dl_and_watch_multi')

        # Only download videos which have a source URL
        mod_list = []
        for media_data_obj in media_data_list:
            if media_data_obj.source:
                mod_list.append(media_data_obj)

        # Can't download the videos if none have no source, or if an update/
        #   refresh operation has started since the popup menu was created
        if mod_list \
        and not self.app_obj.update_manager_obj \
        and not self.app_obj.refresh_manager_obj:

            # Download the videos, and mark them to be opened in the system's
            #   default media player as soon as the download operation is
            #   complete
            # If a download operation is already in progress, the videos are
            #   added to it
            self.app_obj.download_watch_videos(mod_list)

        # Standard de-selection of everything in the Video Catalogue
        self.catalogue_listbox.unselect_all()

    def on_video_catalogue_download(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Download the right-clicked media data object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6760 on_video_catalogue_download')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                230,
                'Callback request denied due to current conditions',
            )

        # Start a download operation
        self.app_obj.download_manager_start(False, False, [media_data_obj] )


    def on_video_catalogue_download_multi(self, menu_item, media_data_list):

        """Called from a callback in self.video_catalogue_multi_popup_menu().

        Download the right-clicked media data objects(s).

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_list (list): List of one or more media.Video objects

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6787 on_video_catalogue_download_multi')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                231,
                'Callback request denied due to current conditions',
            )

        # Start a download operation
        self.app_obj.download_manager_start(False, False, media_data_list)

        # Standard de-selection of everything in the Video Catalogue
        self.catalogue_listbox.unselect_all()


    def on_video_catalogue_edit_options(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Edit the download options (handled by an
        options.OptionsManager object) for the specified video object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6818 on_video_catalogue_edit_options')

        if self.app_obj.current_manager_obj or not media_data_obj.options_obj:
            return self.app_obj.system_error(
                232,
                'Callback request denied due to current conditions',
            )

        # Open an edit window
        config.OptionsEditWin(
            self.app_obj,
            media_data_obj.options_obj,
            media_data_obj,
        )


    def on_video_catalogue_enforce_check(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Set the video object's flag to force checking (disabling an actual
        downloads).

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6850 on_video_catalogue_enforce_check')

        # (Don't allow the user to change the setting of
        #   media.Video.dl_sim_flag if the video is in a channel or playlist,
        #   since media.Channel.dl_sim_flag or media.Playlist.dl_sim_flag
        #   applies instead)
        if self.app_obj.current_manager_obj \
        or not isinstance(media_data_obj.parent_obj, media.Folder):
            return self.app_obj.system_error(
                233,
                'Callback request denied due to current conditions',
            )

        if not media_data_obj.dl_sim_flag:
            media_data_obj.set_dl_sim_flag(True)
        else:
            media_data_obj.set_dl_sim_flag(False)

        self.video_catalogue_update_row(media_data_obj)


    def on_video_catalogue_page_entry_activated(self, entry):

        """Called from a callback in self.setup_videos_tab().

        Switches to a different page in the Video Catalogue (or re-inserts the
        current page number, if the user typed an invalid page number).

        Args:

            entry (Gtk.Entry): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6885 on_video_catalogue_size_entry_activated')

        page_num = utils.strip_whitespace(entry.get_text())

        if self.video_index_current is None \
        or not page_num.isdigit() \
        or int(page_num) < 1 \
        or int(page_num) > self.catalogue_toolbar_last_page:
            # Invalid page number, so reinsert the number of the page that's
            #   actually visible
            entry.set_text(str(self.catalogue_toolbar_current_page))

        else:
            # Switch to a different page
            self.video_catalogue_redraw_all(
                self.video_index_current,
                int(page_num),
            )


    def on_video_catalogue_re_download(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Re-downloads the right-clicked media data object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6920 on_video_catalogue_re_download')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                234,
                'Callback request denied due to current conditions',
            )

        # If the file exists, delete it (otherwise youtube-dl won't download
        #   anything)
        # Don't even check media.Video.dl_flag: the file might exist, even if
        #   the flag has not been set
        if media_data_obj.file_dir:

            path = os.path.abspath(
                os.path.join(
                    self.app_obj.downloads_dir,
                    media_data_obj.file_dir,
                    media_data_obj.file_name + media_data_obj.file_ext,
                ),
            )

            if os.path.isfile(path):
                os.remove(path)

        # No download operation will start, if the media.Video object is marked
        #   as downloaded
        self.app_obj.mark_video_downloaded(media_data_obj, False)

        # Now we're ready to start the download operation
        self.app_obj.download_manager_start(False, False, [media_data_obj] )


    def on_video_catalogue_remove_options(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Removes a set of download options (handled by an
        options.OptionsManager object) from the specified video object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6968 on_video_catalogue_remove_options')

        if self.app_obj.current_manager_obj or not media_data_obj.options_obj:
            return self.app_obj.system_error(
                235,
                'Callback request denied due to current conditions',
            )

        # Remove download options from the media data object
        media_data_obj.set_options_obj(None)
        # Update the video catalogue to show the right icon
        self.video_catalogue_update_row(media_data_obj)


    def on_video_catalogue_size_entry_activated(self, entry):

        """Called from a callback in self.setup_videos_tab().

        Sets the page size, and redraws the Video Catalogue (with the first
        page visible).

        Args:

            entry (Gtk.Entry): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 6996 on_video_catalogue_size_entry_activated')

        size = utils.strip_whitespace(entry.get_text())

        if size.isdigit():
            self.app_obj.set_catalogue_page_size(int(size))

            # Need to completely redraw the video catalogue to take account of
            #   the new page size
            if self.video_index_current is not None:
                self.video_catalogue_redraw_all(self.video_index_current, 1)

        else:
            # Invalid page size, so reinsert the size that's already visible
            entry.set_text(str(self.catalogue_page_size))


    def on_video_catalogue_show_properties(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Opens an edit window for the video object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7028 on_video_catalogue_show_properties')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                236,
                'Callback request denied due to current conditions',
            )

        # Open the edit window immediately
        config.VideoEditWin(self.app_obj, media_data_obj)


    def on_video_catalogue_show_properties_multi(self, menu_item,
    media_data_list):

        """Called from a callback in self.video_catalogue_multi_popup_menu().

        Opens an edit window for each video object.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_list (list): List of one or more media.Video objects

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7056 on_video_catalogue_show_properties_multi')

        if self.app_obj.current_manager_obj:
            return self.app_obj.system_error(
                237,
                'Callback request denied due to current conditions',
            )

        # Open the edit window immediately
        for media_data_obj in media_data_list:
            config.VideoEditWin(self.app_obj, media_data_obj)

        # Standard de-selection of everything in the Video Catalogue
        self.catalogue_listbox.unselect_all()


    def on_video_catalogue_toggle_archived_video(self, menu_item, \
    media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Marks the video as archived or not archived.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7088 on_video_catalogue_toggle_archived_video')

        if not media_data_obj.archive_flag:
            media_data_obj.set_archive_flag(True)
        else:
            media_data_obj.set_archive_flag(False)

        self.video_catalogue_update_row(media_data_obj)


    def on_video_catalogue_toggle_archived_video_multi(self, menu_item,
    archived_flag, media_data_list):

        """Called from a callback in self.video_catalogue_multi_popup_menu().

        Mark the videos as archived or not archived.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            archived_flag (bool): True to mark the videos as archived, False to
                mark the videos as not archived

            media_data_list (list): List of one or more media.Video objects

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7117 on_video_catalogue_toggle_archived_video_multi')

        for media_data_obj in media_data_list:
            media_data_obj.set_archive_flag(archived_flag)
            self.video_catalogue_update_row(media_data_obj)

        # Standard de-selection of everything in the Video Catalogue
        self.catalogue_listbox.unselect_all()


    def on_video_catalogue_toggle_favourite_video(self, menu_item, \
    media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Marks the video as favourite or not favourite.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7143 on_video_catalogue_toggle_favourite_video')

        if not media_data_obj.fav_flag:
            self.app_obj.mark_video_favourite(media_data_obj, True)
        else:
            self.app_obj.mark_video_favourite(media_data_obj, False)


    def on_video_catalogue_toggle_favourite_video_multi(self, menu_item,
    fav_flag, media_data_list):

        """Called from a callback in self.video_catalogue_multi_popup_menu().

        Mark the videos as favourite or not favourite.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            fav_flag (bool): True to mark the videos as favourite, False to
                mark the videos as not favourite

            media_data_list (list): List of one or more media.Video objects

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7170 on_video_catalogue_toggle_favourite_video_multi')

        for media_data_obj in media_data_list:
            self.app_obj.mark_video_favourite(media_data_obj, fav_flag)

        # Standard de-selection of everything in the Video Catalogue
        self.catalogue_listbox.unselect_all()


    def on_video_catalogue_toggle_new_video(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Marks the video as new (unwatched) or not new (watched).

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7194 on_video_catalogue_toggle_new_video')

        if not media_data_obj.new_flag:
            self.app_obj.mark_video_new(media_data_obj, True)
        else:
            self.app_obj.mark_video_new(media_data_obj, False)


    def on_video_catalogue_toggle_new_video_multi(self, menu_item,
    new_flag, media_data_list):

        """Called from a callback in self.video_catalogue_multi_popup_menu().

        Mark the videos as new (unwatched) or not new (watched).

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            new_flag (bool): True to mark the videos as favourite, False to
                mark the videos as not favourite

            media_data_list (list): List of one or more media.Video objects

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7221 on_video_catalogue_toggle_new_video_multi')

        for media_data_obj in media_data_list:
            self.app_obj.mark_video_new(media_data_obj, new_flag)

        # Standard de-selection of everything in the Video Catalogue
        self.catalogue_listbox.unselect_all()


    def on_video_catalogue_watch_hooktube(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Watch a YouTube video on HookTube.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7245 on_video_catalogue_watch_hooktube')

        # Launch the video
        utils.open_file(
            utils.convert_youtube_to_hooktube(media_data_obj.source),
        )

        # Mark the video as not new (having been watched)
        if media_data_obj.new_flag:
            self.app_obj.mark_video_new(media_data_obj, False)


    def on_video_catalogue_watch_video(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Watch a video using the system's default media player, first checking
        that a file actually exists.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7273 on_video_catalogue_watch_video')

        # Launch the video
        self.app_obj.watch_video_in_player(media_data_obj)

        # Mark the video as not new (having been watched)
        if media_data_obj.new_flag:
            self.app_obj.mark_video_new(media_data_obj, False)


    def on_video_catalogue_watch_video_multi(self, menu_item, media_data_list):

        """Called from a callback in self.video_catalogue_multi_popup_menu().

        Watch the videos using the system's default media player, first
        checking that the files actually exist.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_list (list): List of one or more media.Video objects

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7299 on_video_catalogue_watch_video_multi')

        # Only watch videos which are marked as downloaded
        for media_data_obj in media_data_list:
            if media_data_obj.dl_flag:

                self.app_obj.watch_video_in_player(media_data_obj)

                # Mark the video as not new (having been watched)
                if media_data_obj.new_flag:
                    self.app_obj.mark_video_new(media_data_obj, False)

        # Standard de-selection of everything in the Video Catalogue
        self.catalogue_listbox.unselect_all()


    def on_video_catalogue_watch_website(self, menu_item, media_data_obj):

        """Called from a callback in self.video_catalogue_popup_menu().

        Watch a video on its primary website.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_obj (media.Video) - The clicked video object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7330 on_video_catalogue_watch_website')

        # Launch the video
        utils.open_file(media_data_obj.source)

        # Mark the video as not new (having been watched)
        if media_data_obj.new_flag:
            self.app_obj.mark_video_new(media_data_obj, False)


    def on_video_catalogue_watch_website_multi(self, menu_item,
    media_data_list):

        """Called from a callback in self.video_catalogue_multi_popup_menu().

        Watch videos on their primary websites.

        Args:

            menu_item (Gtk.MenuItem): The clicked menu item

            media_data_list (list): List of one or more media.Video objects

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7356 on_video_catalogue_watch_website_multi')

        # Only watch videos which have a source URL
        for media_data_obj in media_data_list:
            if media_data_obj.source is not None:

                # Launch the video
                utils.open_file(media_data_obj.source)

                # Mark the video as not new (having been watched)
                if media_data_obj.new_flag:
                    self.app_obj.mark_video_new(media_data_obj, False)

        # Standard de-selection of everything in the Video Catalogue
        self.catalogue_listbox.unselect_all()


    def on_progress_list_right_click(self, treeview, event):

        """Called from callback in self.setup_progress_tab().

        When the user right-clicks an item in the Progress List, create a
        context-sensitive popup menu.

        Args:

            treeview (Gtk.TreeView): The Progress List's treeview

            event (Gdk.EventButton): The event emitting the Gtk signal

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7389 on_progress_list_right_click')

        if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:

            # If the user right-clicked on empty space, the call to
            #   .get_path_at_pos returns None (or an empty list)
            if not treeview.get_path_at_pos(
                int(event.x),
                int(event.y),
            ):
                return

            path, column, cellx, celly = treeview.get_path_at_pos(
                int(event.x),
                int(event.y),
            )

            iter = self.progress_list_liststore.get_iter(path)
            if iter is not None:
                self.progress_list_popup_menu(
                    event,
                    self.progress_list_liststore[iter][0],
                )


    def on_progress_list_stop_now(self, menu_item, download_item_obj,
    worker_obj, video_downloader_obj):

        """Called from a callback in self.progress_list_popup_menu().

        Halts checking/downloading the selected media data object.

        Args:

            menu_item (Gtk.MenuItem): The menu item that was clicked

            download_item_obj (downloads.DownloadItem): The download item
                object for the selected media data object

            worker_obj (downloads.DownloadWorker): The worker currently
                handling checking/downloading this media data object

            video_downloader_obj (downloads.VideoDownloader): The video
                downloader handling checking/downloading this media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7437 on_progress_list_stop_now')

        # Check that, since the popup menu was created, the video downloader
        #   hasn't already finished checking/downloading the selected media
        #   data object
        if not self.app_obj.download_manager_obj \
        or not worker_obj.running_flag \
        or worker_obj.download_item_obj != download_item_obj \
        or worker_obj.video_downloader_obj is None:
            # Do nothing
            return

        # Stop the video downloader (causing the worker to be assigned a new
        #   downloads.DownloadItem, if there are any left)
        video_downloader_obj.stop()


    def on_progress_list_stop_soon(self, menu_item, download_item_obj,
    worker_obj, video_downloader_obj):

        """Called from a callback in self.progress_list_popup_menu().

        Halts checking/downloading the selected media data object, after the
        current video check/download has finished.

        Args:

            menu_item (Gtk.MenuItem): The menu item that was clicked

            download_item_obj (downloads.DownloadItem): The download item
                object for the selected media data object

            worker_obj (downloads.DownloadWorker): The worker currently
                handling checking/downloading this media data object

            video_downloader_obj (downloads.VideoDownloader): The video
                downloader handling checking/downloading this media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7478 on_progress_list_stop_soon')

        # Check that, since the popup menu was created, the video downloader
        #   hasn't already finished checking/downloading the selected media
        #   data object
        if not self.app_obj.download_manager_obj \
        or not worker_obj.running_flag \
        or worker_obj.download_item_obj != download_item_obj \
        or worker_obj.video_downloader_obj is None:
            # Do nothing
            return

        # Tell the video downloader to stop after the current video check/
        #   download has finished
        video_downloader_obj.stop_soon()


    def on_progress_list_dl_last(self, menu_item, download_item_obj):

        """Called from a callback in self.progress_list_popup_menu().

        Moves the selected media data object to the bottom of the
        downloads.DownloadList, so it is assigned to the last available worker.

        Args:

            menu_item (Gtk.MenuItem): The menu item that was clicked

            download_item_obj (downloads.DownloadItem): The download item
                object for the selected media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7512 on_progress_list_dl_last')

        # Check that, since the popup menu was created, the media data object
        #   hasn't been assigned a worker
        for this_worker_obj in self.app_obj.download_manager_obj.worker_list:
            if this_worker_obj.running_flag \
            and this_worker_obj.download_item_obj == download_item_obj \
            and this_worker_obj.video_downloader_obj is not None:
                return

        # Assign this media data object to the last available worker
        download_list_obj = self.app_obj.download_manager_obj.download_list_obj
        download_list_obj.move_item_to_bottom(download_item_obj)

        # Change the row's icon to show that it will be checked/downloaded
        #   last
        # (Because of the way the Progress List has been set up, borrowing from
        #   the design in youtube-dl-gui, reordering the rows in the list is
        #   not practial)
        tree_path = Gtk.TreePath(
            self.progress_list_row_dict[download_item_obj.item_id],
        )

        self.progress_list_liststore.set(
            self.progress_list_liststore.get_iter(tree_path),
            1,
            self.pixbuf_dict['arrow_down_small'],
        )


    def on_progress_list_dl_next(self, menu_item, download_item_obj):

        """Called from a callback in self.progress_list_popup_menu().

        Moves the selected media data object to the top of the
        downloads.DownloadList, so it is assigned to the next available worker.

        Args:

            menu_item (Gtk.MenuItem): The menu item that was clicked

            download_item_obj (downloads.DownloadItem): The download item
                object for the selected media data object

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7559 on_progress_list_dl_next')

        # Check that, since the popup menu was created, the media data object
        #   hasn't been assigned a worker
        for this_worker_obj in self.app_obj.download_manager_obj.worker_list:
            if this_worker_obj.running_flag \
            and this_worker_obj.download_item_obj == download_item_obj \
            and this_worker_obj.video_downloader_obj is not None:
                return

        # Assign this media data object to the next available worker
        download_list_obj = self.app_obj.download_manager_obj.download_list_obj
        download_list_obj.move_item_to_top(download_item_obj)

        # Change the row's icon to show that it will be checked/downloaded
        #   next
        tree_path = Gtk.TreePath(
            self.progress_list_row_dict[download_item_obj.item_id],
        )

        self.progress_list_liststore.set(
            self.progress_list_liststore.get_iter(tree_path),
            1,
            self.pixbuf_dict['arrow_up_small'],
        )


    def on_results_list_right_click(self, treeview, event):

        """Called from callback in self.setup_progress_tab().

        When the user right-clicks an item in the Results List, create a
        context-sensitive popup menu.

        Args:

            treeview (Gtk.TreeView): The Results List's treeview

            event (Gdk.EventButton): The event emitting the Gtk signal

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7602 on_results_list_right_click')

        if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:

            # If the user right-clicked on empty space, the call to
            #   .get_path_at_pos returns None (or an empty list)
            if not treeview.get_path_at_pos(
                int(event.x),
                int(event.y),
            ):
                return

            path, column, cellx, celly = treeview.get_path_at_pos(
                int(event.x),
                int(event.y),
            )

            iter = self.results_list_liststore.get_iter(path)
            if iter is not None:
                self.results_list_popup_menu(
                    event,
                    path,
                    self.results_list_liststore[iter][0],
                )


    def on_results_list_delete_video(self, menu_item, media_data_obj, path):

        """Called from a callback in self.video_catalogue_popup_menu() and
        self.results_list_popup_menu().

        Deletes the video, and removes a row from the Results List.

        Args:

            menu_item (Gtk.MenuItem): The menu item that was clicked

            media_data_obj (media.Video): The video displayed on the clicked
                row

            path (Gtk.TreePath): Path to the clicked row in the treeview

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7647 on_results_list_delete_video')

        # Delete the video
        self.app_obj.delete_video(media_data_obj, True)

        # Remove the row from the Results List
        iter = self.results_list_liststore.get_iter(path)
        self.results_list_liststore.remove(iter)


    def on_num_worker_spinbutton_changed(self, spinbutton):

        """Called from callback in self.setup_progress_tab().

        In the Progress Tab, when the user sets the number of simultaneous
        downloads allowed, inform mainapp.TartubeApp, which in turn informs the
        downloads.DownloadManager object.

        Args:

            spinbutton (Gtk.SpinButton) - The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7672 on_num_worker_spinbutton_changed')

        if self.num_worker_checkbutton.get_active():
            self.app_obj.set_num_worker_default(
                int(self.num_worker_spinbutton.get_value())
            )


    def on_num_worker_checkbutton_changed(self, checkbutton):

        """Called from callback in self.setup_progress_tab().

        In the Progress Tab, when the user sets the number of simultaneous
        downloads allowed, inform mainapp.TartubeApp, which in turn informs the
        downloads.DownloadManager object.

        Args:

            checkbutton (Gtk.CheckButton) - The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7695 on_checkbutton_changed')

        if self.num_worker_checkbutton.get_active():

            self.app_obj.set_num_worker_apply_flag(True)
            self.app_obj.set_num_worker_default(
                int(self.num_worker_spinbutton.get_value())
            )

        else:

            self.app_obj.set_num_worker_apply_flag(False)


    def on_bandwidth_spinbutton_changed(self, spinbutton):

        """Called from callback in self.setup_progress_tab().

        In the Progress Tab, when the user sets the bandwidth limit, inform
        mainapp.TartubeApp. The new setting is applied to the next download
        job.

        Args:

            spinbutton (Gtk.SpinButton): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7724 on_bandwidth_spinbutton_changed')

        self.app_obj.set_bandwidth_default(
            int(self.bandwidth_spinbutton.get_value())
        )


    def on_bandwidth_checkbutton_changed(self, checkbutton):

        """Called from callback in self.setup_progress_tab().

        In the Progress Tab, when the user turns the bandwidth limit on/off,
        inform mainapp.TartubeApp. The new setting is applied to the next
        download job.

        Args:

            checkbutton (Gtk.CheckButton): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7746 on_bandwidth_checkbutton_changed')

        self.app_obj.set_bandwidth_apply_flag(
            self.bandwidth_checkbutton.get_active(),
        )


    def on_combobox_changed(self, combobox):

        """Called from callback in self.setup_progress_tab().

        In the Progress Tab, when the user sets the video resolution limit,
        inform mainapp.TartubeApp. The new setting is applied to the next
        download job.

        Args:

            combobox (Gtk.ComboBox): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7747 on_combobox_changed')

        tree_iter = self.video_res_combobox.get_active_iter()
        model = self.video_res_combobox.get_model()
        self.app_obj.set_video_res_default(model[tree_iter][0])


    def on_video_res_checkbutton_changed(self, checkbutton):

        """Called from callback in self.setup_progress_tab().

        In the Progress Tab, when the user turns the video resolution limit
        on/off, inform mainapp.TartubeApp. The new setting is applied to the
        next download job.

        Args:

            checkbutton (Gtk.CheckButton): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7748 on_video_res_checkbutton_changed')

        self.app_obj.set_video_res_apply_flag(
            self.video_res_checkbutton.get_active(),
        )


    def on_errors_list_clear(self, button):

        """Called from callback in self.setup_errors_tab().

        In the Errors Tab, when the user clicks the 'Clear the list' button,
        clear the Errors List.

        Args:

            button (Gtk.Button): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7765 on_errors_list_clear')

        self.errors_list_reset()


    # Set accessors


    def add_child_window(self, config_win_obj):

        """Called by config.GenericConfigWin.setup().

        When a configuration window opens, add it to our list of such windows.

        Args:

            config_win_obj (config.GenericConfigWin): The window to add

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7786 add_child_window')

        # Check that the window isn't already in the list (unlikely, but check
        #   anyway)
        if config_win_obj in self.config_win_list:
            return self.app_obj.system_error(
                238,
                'Callback request denied due to current conditions',
            )

        # Update the IV
        self.config_win_list.append(config_win_obj)


    def del_child_window(self, config_win_obj):

        """Called by config.GenericConfigWin.close().

        When a configuration window closes, remove it to our list of such
        windows.

        Args:

            config_win_obj (config.GenericConfigWin): The window to remove

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7814 del_child_window')

        # Update the IV
        # (Don't show an error if the window isn't in the list, as it's
        #   conceivable this function might be called twice)
        if config_win_obj in self.config_win_list:
            self.config_win_list.remove(config_win_obj)


class SimpleCatalogueItem(object):

    """Python class that handles a single row in the Video Catalogue.

    Each mainwin.SimpleCatalogueItem objects stores widgets used in that row,
    and updates them when required.

    This class offers a simple view with a minimum of widgets (for example, no
    video thumbnails). The mainwin.ComplexCatalogueItem class offers a more
    complex view (for example, with video thumbnails).

    Args:

        main_win_obj (mainwin.MainWin): The main window object

        video_obj (media.Video): The media data object itself (always a video)

    """


    # Standard class methods


    def __init__(self, main_win_obj, video_obj):

        if DEBUG_FUNC_FLAG:
            print('mw 7849 __init__')

        # IV list - class objects
        # -----------------------
        # The main window object
        self.main_win_obj = main_win_obj
        # The media data object itself (always a video)
        self.video_obj = video_obj


        # IV list - Gtk widgets
        # ---------------------
        self.catalogue_row = None           # mainwin.CatalogueRow
        self.hbox = None                    # Gtk.HBox
        self.status_image = None            # Gtk.Image
        self.name_label = None              # Gtk.Label
        self.parent_label = None            # Gtk.Label
        self.stats_label = None             # Gtk.Label


        # IV list - other
        # ---------------
        # Unique ID for this object, matching the .dbid for self.video_obj (an
        #   integer)
        self.dbid = video_obj.dbid
        # Size (in pixels) of gaps between various widgets
        self.spacing_size = 5


    # Public class methods


    def draw_widgets(self, catalogue_row):

        """Called by mainwin.MainWin.video_catalogue_redraw_all() and
        .video_catalogue_update_row().

        After a Gtk.ListBoxRow has been created for this object, populate it
        with widgets.

        Args:

            catalogue_row (mainwin.CatalogueRow): A wrapper for a
                Gtk.ListBoxRow object, storing the media.Video object displayed
                in that row.

        """

        if DEBUG_FUNC_FLAG:
            print('mw 7898 draw_widgets')

        self.catalogue_row = catalogue_row

        event_box = Gtk.EventBox()
        self.catalogue_row.add(event_box)
        event_box.connect('button-press-event', self.on_right_click_row)

        self.hbox = Gtk.Box(
            orientation=Gtk.Orientation.HORIZONTAL,
            spacing=0,
        )
        event_box.add(self.hbox)
#       self.hbox.set_border_width(self.spacing_size)
        self.hbox.set_border_width(0)

        self.status_image = Gtk.Image()
        self.hbox.pack_start(
            self.status_image,
            False,
            False,
            self.spacing_size,
        )

        vbox = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL,
            spacing=0,
        )
        self.hbox.pack_start(vbox, True, True, self.spacing_size)

        # Video name
        self.name_label = Gtk.Label('', xalign = 0)
        vbox.pack_start(self.name_label, True, True, 0)

        # Parent channel/playlist/folder name (if allowed)
        if self.main_win_obj.app_obj.catalogue_mode == 'simple_show_parent':
            self.parent_label = Gtk.Label('', xalign = 0)
            vbox.pack_start(self.parent_label, True, True, 0)

        # Video stats
        self.stats_label = Gtk.Label('', xalign=0)
        vbox.pack_start(self.stats_label, True, True, 0)


    def update_widgets(self):

        """Called by mainwin.MainWin.video_catalogue_redraw_all() and
        .video_catalogue_update_row().

        Sets the values displayed by each widget.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 7951 update_widgets')

        self.update_tooltips()
        self.update_status_image()
        self.update_video_name()
        self.update_parent_name()
        self.update_video_stats()


    def update_tooltips(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the tooltips for the Gtk.HBox that contains everything.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 7968 update_tooltips')

        if self.main_win_obj.app_obj.show_tooltips_flag:
            self.hbox.set_tooltip_text(
                self.video_obj.fetch_tooltip_text(
                    self.main_win_obj.app_obj,
                    self.main_win_obj.tooltip_max_len,
                ),
            )


    def update_status_image(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the Gtk.Image widget to display the video's download status.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 7986 update_status_image')

        # Set the download status
        if self.video_obj.dl_flag:
            if self.video_obj.archive_flag:
                self.status_image.set_from_pixbuf(
                    self.main_win_obj.pixbuf_dict['archived_small'],
                )
            else:
                self.status_image.set_from_pixbuf(
                    self.main_win_obj.pixbuf_dict['have_file_small'],
                )
        else:
            self.status_image.set_from_pixbuf(
                self.main_win_obj.pixbuf_dict['no_file_small'],
            )


    def update_video_name(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the Gtk.Label widget to display the video's current name.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 8012 update_video_name')

        # For videos whose name is unknown, display the URL, rather than the
        #   usual '(video with no name)' string
        name = self.video_obj.nickname
        if name is None \
        or name == self.main_win_obj.app_obj.default_video_name:

            if self.video_obj.source is not None:

                # Using pango markup to display a URL is too risky, so just use
                #   ordinary text
                self.name_label.set_text(
                    utils.shorten_string(
                        self.video_obj.source,
                        self.main_win_obj.long_string_max_len,
                    ),
                )

                return

            else:

                # No URL to show, so we're forced to use '(video with no name)'
                name = self.main_win_obj.app_obj.default_video_name

        string = ''
        if self.video_obj.new_flag:
            string += ' font_weight="bold"'

        if self.video_obj.dl_sim_flag:
            string += ' style="italic"'

        self.name_label.set_markup(
            '<span font_size="large"' + string + '>' + \
            cgi.escape(
                utils.shorten_string(
                    name,
                    self.main_win_obj.long_string_max_len,
                ),
                quote=True,
            ) + '</span>'
        )


    def update_parent_name(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the Gtk.Label widget to display the name of the parent channel,
        playlist or folder.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 8066 update_parent_name')

        if self.main_win_obj.app_obj.catalogue_mode != 'simple_show_parent':
            return

        if isinstance(self.video_obj.parent_obj, media.Channel):
            string = 'From channel \''
        elif isinstance(self.video_obj.parent_obj, media.Playlist):
            string = 'From playlist \''
        else:
            string = 'From folder \''

        string2 = cgi.escape(
            utils.shorten_string(
                self.video_obj.parent_obj.name,
                self.main_win_obj.medium_string_max_len,
            ),
            quote=True,
        )

        self.parent_label.set_markup(string + string2 + '\'')


    def update_video_stats(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the Gtk.Label widget to display the video's current side/
        duration/date information.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 8098 update_video_stats')

        if self.video_obj.duration is not None:
            string = 'Duration: ' + utils.convert_seconds_to_string(
                self.video_obj.duration,
                True,
            )

        else:
            string = 'Duration: <i>unknown</i>'

        size = self.video_obj.get_file_size_string()
        if size is not None:
            string = string + '  -  Size: ' + size
        else:
            string = string + '  -  Size: <i>unknown</i>'

        date = self.video_obj.get_upload_date_string()
        if date is not None:
            string = string + '  -  Date: ' + date
        else:
            string = string + '  -  Date: <i>unknown</i>'

        self.stats_label.set_markup(string)


    # Callback methods


    def on_right_click_row(self, event_box, event):

        """Called from callback in self.draw_widgets().

        When the user right-clicks an a row, create a context-sensitive popup
        menu.

        Args:

            event_box (Gtk.EventBox), event (Gtk.EventButton): Data from the
                signal emitted by the click

        """

        if DEBUG_FUNC_FLAG:
            print('mw 8142 on_right_click_row')

        if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:

            self.main_win_obj.video_catalogue_popup_menu(event, self.video_obj)


class ComplexCatalogueItem(object):

    """Python class that handles a single row in the Video Catalogue.

    Each mainwin.ComplexCatalogueItem objects stores widgets used in that row,
    and updates them when required.

    The mainwin.SimpleCatalogueItem class offers a simple view with a minimum
    of widgets (for example, no video thumbnails). This class offers a more
    complex view (for example, with video thumbnails).

    Args:

        main_win_obj (mainwin.MainWin): The main window object

        video_obj (media.Video): The media data object itself (always a video)

    """


    # Standard class methods


    def __init__(self, main_win_obj, video_obj):

        if DEBUG_FUNC_FLAG:
            print('mw 8175 __init__')

        # IV list - class objects
        # -----------------------
        # The main window object
        self.main_win_obj = main_win_obj
        # The media data object itself (always a video)
        self.video_obj = video_obj


        # IV list - Gtk widgets
        # ---------------------
        self.catalogue_row = None           # mainwin.CatalogueRow
        self.frame = None                   # Gtk.Frame
        self.thumb_image = None             # Gtk.Image
        self.name_label = None              # Gtk.Label
        self.status_image = None            # Gtk.Image
        self.error_image = None             # Gtk.Image
        self.warning_image = None           # Gtk.Image
        self.descrip_label = None           # Gtk.Label
        self.expand_label = None            # Gtk.Label
        self.stats_label = None             # Gtk.Label
        self.watch_label = None             # Gtk.Label
        self.watch_player_label = None      # Gtk.Label
        self.watch_web_label = None         # Gtk.Label
        self.watch_hooktube_label = None    # Gtk.Label


        # IV list - other
        # ---------------
        # Unique ID for this object, matching the .dbid for self.video_obj (an
        #   integer)
        self.dbid = video_obj.dbid
        # Size (in pixels) of gaps between various widgets
        self.spacing_size = 5
        # The state of the More/Less label. False if the video's short
        #   description (or no description at all) is visible, True if the
        #   video's full description is visible
        self.expand_descrip_flag = False


    # Public class methods


    def draw_widgets(self, catalogue_row):

        """Called by mainwin.MainWin.video_catalogue_redraw_all() and
        .video_catalogue_update_row().

        After a Gtk.ListBoxRow has been created for this object, populate it
        with widgets.

        Args:

            catalogue_row (mainwin.CatalogueRow): A wrapper for a
                Gtk.ListBoxRow object, storing the media.Video object displayed
                in that row.

        """

        if DEBUG_FUNC_FLAG:
            print('mw 8236 draw_widgets')

        self.catalogue_row = catalogue_row

        event_box = Gtk.EventBox()
        self.catalogue_row.add(event_box)
        event_box.connect('button-press-event', self.on_right_click_row)

        self.frame = Gtk.Frame()
        event_box.add(self.frame)
        self.frame.set_border_width(self.spacing_size)

        hbox = Gtk.Box(
            orientation=Gtk.Orientation.HORIZONTAL,
            spacing=0,
        )
        self.frame.add(hbox)
        hbox.set_border_width(self.spacing_size)

        # The thumbnail is in its own vbox, so we can keep it in the top-left
        #   when the video's description has multiple lines
        vbox = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL,
            spacing=0,
        )
        hbox.pack_start(vbox, False, False, 0)

        self.thumb_image = Gtk.Image()
        vbox.pack_start(self.thumb_image, False, False, 0)

        # Everything to the right of the thumbnail is in vbox2
        vbox2 = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL,
            spacing=0,
        )
        hbox.pack_start(vbox2, True, True, self.spacing_size)

        # Video name
        hbox2 = Gtk.Box(
            orientation=Gtk.Orientation.HORIZONTAL,
            spacing=0,
        )
        vbox2.pack_start(hbox2, True, True, 0)

        self.name_label = Gtk.Label('', xalign = 0)
        hbox2.pack_start(self.name_label, True, True, 0)

        # Status/error/warning icons
        self.status_image = Gtk.Image()
        hbox2.pack_end(self.status_image, False, False, 0)

        self.warning_image = Gtk.Image()
        hbox2.pack_end(self.warning_image, False, False, self.spacing_size)

        self.error_image = Gtk.Image()
        hbox2.pack_end(self.error_image, False, False, self.spacing_size)

        # Video description (incorporating the the More/Less label), or the
        #   name of the parent channel/playlist/folder, depending on settings
        self.descrip_label = Gtk.Label('', xalign=0)
        vbox2.pack_start(self.descrip_label, True, True, 0)
        self.descrip_label.connect(
            'activate-link',
            self.on_click_descrip_label,
        )

        # Video stats
        self.stats_label = Gtk.Label('', xalign=0)
        vbox2.pack_start(self.stats_label, True, True, 0)

        hbox3 = Gtk.Box(
            orientation=Gtk.Orientation.HORIZONTAL,
            spacing=0,
        )
        vbox2.pack_start(hbox3, True, True, 0)

        # Watch...
        self.watch_label = Gtk.Label('Watch:   ', xalign=0)
        hbox3.pack_start(self.watch_label, False, False, 0)

        # Watch in player
        self.watch_player_label = Gtk.Label('', xalign=0)
        hbox3.pack_start(self.watch_player_label, False, False, 0)
        self.watch_player_label.connect(
            'activate-link',
            self.on_click_watch_player_label,
        )

        # Watch on website/YouTube
        self.watch_web_label = Gtk.Label('', xalign=0)
        hbox3.pack_start(
            self.watch_web_label,
            False,
            False,
            (self.spacing_size * 2),
        )
        self.watch_web_label.connect(
            'activate-link',
            self.on_click_watch_web_label,
        )

        # Watch on HookTube
        self.watch_hooktube_label = Gtk.Label('', xalign=0)
        hbox3.pack_start(self.watch_hooktube_label, False, False, 0)
        self.watch_hooktube_label.connect(
            'activate-link',
            self.on_click_watch_hooktube_label,
        )


    def update_widgets(self):

        """Called by mainwin.MainWin.video_catalogue_redraw_all() and
        .video_catalogue_update_row().

        Sets the values displayed by each widget.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 8355 update_widgets')

        self.update_tooltips()
        self.update_thumb_image()
        self.update_video_name()
        self.update_status_images()
        self.update_video_descrip()
        self.update_video_stats()
        self.update_watch_player()
        self.update_watch_web()


    def update_tooltips(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the tooltips for the Gtk.Frame that contains everything.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 8375 update_tooltips')

        if self.main_win_obj.app_obj.show_tooltips_flag:
            self.frame.set_tooltip_text(
                self.video_obj.fetch_tooltip_text(
                    self.main_win_obj.app_obj,
                    self.main_win_obj.tooltip_max_len,
                ),
            )


    def update_thumb_image(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the Gtk.Image widget to display the video's thumbnail, if
        available.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 8394 update_thumb_image')

        # See if the video's thumbnail file has been downloaded
        thumb_flag = False
        if self.video_obj.file_dir:

            # No way to know which image format is used by all websites for
            #   their video thumbnails, so look for the most common ones
            # The True argument means that if the thumbnail isn't found in
            #   Tartube's main data directory, look in the temporary directory
            #   too
            path = utils.find_thumbnail(
                self.main_win_obj.app_obj,
                self.video_obj,
                True,
            )

            if path:

                # Thumbnail file exists, so use it
                thumb_flag = True
                self.thumb_image.set_from_pixbuf(
                    self.main_win_obj.app_obj.file_manager_obj.load_to_pixbuf(
                        path,
                        self.main_win_obj.thumb_width,
                        self.main_win_obj.thumb_height,
                   ),
                )

        # No thumbnail file found, so use a standard icon file
        if not thumb_flag:
            if self.video_obj.fav_flag and self.video_obj.options_obj:
                self.thumb_image.set_from_pixbuf(
                    self.main_win_obj.pixbuf_dict['video_both_large'],
                )
            elif self.video_obj.fav_flag:
                self.thumb_image.set_from_pixbuf(
                    self.main_win_obj.pixbuf_dict['video_left_large'],
                )
            elif self.video_obj.options_obj:
                self.thumb_image.set_from_pixbuf(
                    self.main_win_obj.pixbuf_dict['video_right_large'],
                )
            else:
                self.thumb_image.set_from_pixbuf(
                    self.main_win_obj.pixbuf_dict['video_none_large'],
                )


    def update_video_name(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the Gtk.Label widget to display the video's current name.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 8451 update_video_name')

        # For videos whose name is unknown, display the URL, rather than the
        #   usual '(video with no name)' string
        name = self.video_obj.nickname
        if name is None \
        or name == self.main_win_obj.app_obj.default_video_name:

            if self.video_obj.source is not None:

                # Using pango markup to display a URL is too risky, so just use
                #   ordinary text
                self.name_label.set_text(
                    utils.shorten_string(
                        self.video_obj.source,
                        self.main_win_obj.medium_string_max_len,
                    ),
                )

                return

            else:

                # No URL to show, so we're forced to use '(video with no name)'
                name = self.main_win_obj.app_obj.default_video_name

        string = ''
        if self.video_obj.new_flag:
            string += ' font_weight="bold"'

        if self.video_obj.dl_sim_flag:
            string += ' style="italic"'

        self.name_label.set_markup(
            '<span font_size="large"' + string + '>' + \
            cgi.escape(
                utils.shorten_string(
                    name,
                    self.main_win_obj.medium_string_max_len,
                ),
                quote=True,
            ) + '</span>'
        )


    def update_status_images(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the Gtk.Image widgets to display the video's download status,
        error and warning settings.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 8505 update_status_images')

        # Set the download status
        if self.video_obj.dl_flag:
            if self.video_obj.archive_flag:
                self.status_image.set_from_pixbuf(
                    self.main_win_obj.pixbuf_dict['archived_small'],
                )
            else:
                self.status_image.set_from_pixbuf(
                    self.main_win_obj.pixbuf_dict['have_file_small'],
                )
        else:
            self.status_image.set_from_pixbuf(
                self.main_win_obj.pixbuf_dict['no_file_small'],
            )

        # Set an indication of any error/warning messages. If there is an error
        #   but no warning, show the error icon in the warning image (so there
        #   isn't a large gap in the middle)
        if self.video_obj.error_list and self.video_obj.warning_list:

            self.warning_image.set_from_pixbuf(
                self.main_win_obj.pixbuf_dict['warning_small'],
            )

            self.error_image.set_from_pixbuf(
                self.main_win_obj.pixbuf_dict['error_small'],
            )

        elif self.video_obj.error_list:

            self.warning_image.set_from_pixbuf(
                self.main_win_obj.pixbuf_dict['error_small'],
            )

            self.error_image.clear()

        elif self.video_obj.warning_list:

            self.warning_image.set_from_pixbuf(
                self.main_win_obj.pixbuf_dict['warning_small'],
            )

            self.error_image.clear()

        else:

            self.error_image.clear()
            self.warning_image.clear()


    def update_video_descrip(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the Gtk.Label widget to display the video's current
        description.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 8566 update_video_descrip')

        if self.main_win_obj.app_obj.catalogue_mode == 'complex_hide_parent':

            # Show the first line of the video description, or all of it,
            #   depending on settings
            if self.video_obj.short:

                # Work with a list of lines, displaying either the fist line,
                #   or all of them, as the user clicks the More/Less button
                line_list = self.video_obj.descrip.split('\n')

                if not self.expand_descrip_flag:

                    string = cgi.escape(
                        utils.shorten_string(
                            line_list[0],
                            self.main_win_obj.long_string_max_len,
                        ),
                        quote=True,
                    )

                    if len(line_list) > 1:
                        self.descrip_label.set_markup(
                            '<a href="more">More</a>   ' + string,
                        )
                    else:
                        self.descrip_label.set_text(string)

                else:

                    descrip = cgi.escape(self.video_obj.descrip, quote=True)

                    if len(line_list) > 1:
                        self.descrip_label.set_markup(
                            '<a href="less">Less</a>   ' + descrip + '\n',
                        )
                    else:
                        self.descrip_label.set_text(descrip)

            else:
                self.descrip_label.set_markup('<i>No description set</i>')

        else:

            # Show the name of the parent channel/playlist/folder, optionally
            #   followed by the whole video description, depending on settings
            if isinstance(self.video_obj.parent_obj, media.Channel):
                string = 'From channel \''
            elif isinstance(self.video_obj.parent_obj, media.Playlist):
                string = 'From playlist \''
            else:
                string = 'From folder \''

            string += cgi.escape(
                utils.shorten_string(
                    self.video_obj.parent_obj.name,
                    self.main_win_obj.long_string_max_len,
                ),
                quote=True,
            ) + '\''

            if not self.video_obj.descrip:
                self.descrip_label.set_text(string)

            elif not self.expand_descrip_flag:

                self.descrip_label.set_markup(
                    '<a href="more">More</a>   ' + string,
                )

            else:

                descrip = cgi.escape(self.video_obj.descrip, quote=True)
                self.descrip_label.set_markup(
                    '<a href="less">Less</a>   ' + string + '\n' + descrip \
                    + '\n',
                )


    def update_video_stats(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the Gtk.Label widget to display the video's current side/
        duration/date information.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 8655 update_video_stats')

        if self.video_obj.duration is not None:
            string = 'Duration: ' + utils.convert_seconds_to_string(
                self.video_obj.duration,
                True,
            )

        else:
            string = 'Duration: <i>unknown</i>'

        size = self.video_obj.get_file_size_string()
        if size is not None:
            string = string + '  -  Size: ' + size
        else:
            string = string + '  -  Size: <i>unknown</i>'

        date = self.video_obj.get_upload_date_string()
        if date is not None:
            string = string + '  -  Date: ' + date
        else:
            string = string + '  -  Date: <i>unknown</i>'

        self.stats_label.set_markup(string)


    def update_watch_player(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the clickable Gtk.Label widget for watching the video in an
        external media player.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 8690 update_watch_player')

        if self.video_obj.file_dir and self.video_obj.dl_flag:

            # Link clickable
            self.watch_player_label.set_markup(
                '<a href="watch">Media player</a>',
            )

        elif self.video_obj.source \
        and not self.main_win_obj.app_obj.update_manager_obj \
        and not self.main_win_obj.app_obj.refresh_manager_obj:

            # Link clickable
            self.watch_player_label.set_markup(
                '<a href="watch">Download and watch</a>',
            )

        else:

            # Link not clickable
            self.watch_player_label.set_markup('<i>Not downloaded</i>')


    def update_watch_web(self):

        """Called by anything, but mainly called by self.update_widgets().

        Updates the clickable Gtk.Label widget for watching the video in an
        external web browser.
        """

        if DEBUG_FUNC_FLAG:
            print('mw 8723 update_watch_web')

        if self.video_obj.source:

            # Convert a YouTube link into a HookTube link (but don't modify any
            #   other weblink)
            mod_source = utils.convert_youtube_to_hooktube(
                self.video_obj.source,
            )

            # For YouTube URLs, offer an alternative website
            if self.video_obj.source != mod_source:

                # Links clickable
                self.watch_web_label.set_markup(
                    '<a href="' + self.video_obj.source + \
                    '">YouTube</a>',
                )

                self.watch_hooktube_label.set_markup(
                    '<a href="' + mod_source + '">HookTube</a>',
                )

            else:

                self.watch_web_label.set_markup(
                    '<a href="' + self.video_obj.source + \
                    '">Website</a>',
                )

                self.watch_hooktube_label.set_text('')

        else:

            # Link not clickable
            self.watch_web_label.set_markup('<i>No weblink</i>')
            self.watch_hooktube_label.set_text('')


    # Callback methods


    def on_right_click_row(self, event_box, event):

        """Called from callback in self.draw_widgets().

        When the user right-clicks an a row, create a context-sensitive popup
        menu.

        Args:

            event_box (Gtk.EventBox), event (Gtk.EventButton): Data from the
                signal emitted by the click

        """

        if DEBUG_FUNC_FLAG:
            print('mw 8780 on_right_click_row')

        if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:

            self.main_win_obj.video_catalogue_popup_menu(event, self.video_obj)


    def on_click_descrip_label(self, label, uri):

        """Called from callback in self.draw_widgets().

        When the user clicks on the More/Less label, show more or less of the
        video's description.

        Args:

            label (Gtk.Label): The clicked widget

            uri (string): Ignored

        """

        if DEBUG_FUNC_FLAG:
            print('mw 8003 on_click_descrip_label')

        if not self.expand_descrip_flag:
            self.expand_descrip_flag = True
        else:
            self.expand_descrip_flag = False

        # Because of an unexplained Gtk problem, there is usually a crash after
        #   this function returns. Workaround is to make the label unclickable,
        #   then use a Glib timer to restore it (after some small fraction of a
        #   second)
        self.descrip_label.set_markup('')
        GObject.timeout_add(0, self.update_video_descrip)


    def on_click_watch_hooktube_label(self, label, uri):

        """Called from callback in self.draw_widgets().

        Watch a YouTube video on HookTube.

        Args:

            label (Gtk.Label): The clicked widget

            uri (string): Ignored

        Returns:

            True to show the action has been handled

        """

        if DEBUG_FUNC_FLAG:
            print('mw 8837 on_click_watch_hooktube_label')

        # Launch the video
        utils.open_file(uri)

        # Mark the video as not new (having been watched)
        if self.video_obj.new_flag:
            self.main_win_obj.app_obj.mark_video_new(self.video_obj, False)

        # Because of an unexplained Gtk problem, there is usually a crash after
        #   this function returns. Workaround is to make the label unclickable,
        #   then use a Glib timer to restore it (after some small fraction of a
        #   second)
        self.watch_hooktube_label.set_markup('HookTube')
        GObject.timeout_add(0, self.update_watch_web)

        return True


    def on_click_watch_player_label(self, label, uri):

        """Called from callback in self.draw_widgets().

        Watch a video using the system's default media player, first checking
        that a file actually exists.

        Args:

            label (Gtk.Label): The clicked widget

            uri (string): Ignored

        Returns:

            True to show the action has been handled

        """

        if DEBUG_FUNC_FLAG:
            print('mw 8876 on_click_watch_player_label')

        if not self.video_obj.dl_flag and self.video_obj.source \
        and not self.main_win_obj.app_obj.update_manager_obj \
        and not self.main_win_obj.app_obj.refresh_manager_obj:

            # Download the video, and mark it to be opened in the system's
            #   default media player as soon as the download operation is
            #   complete
            # If a download operation is already in progress, the video is
            #   added to it
            self.main_win_obj.app_obj.download_watch_videos( [self.video_obj] )

        else:

            # Launch the video in the system's media player
            self.main_win_obj.app_obj.watch_video_in_player(self.video_obj)

            # Mark the video as not new (having been watched)
            if self.video_obj.new_flag:
                self.main_win_obj.app_obj.mark_video_new(self.video_obj, False)

        # Because of an unexplained Gtk problem, there is usually a crash after
        #   this function returns. Workaround is to make the label unclickable,
        #   then use a Glib timer to restore it (after some small fraction of a
        #   second)
        self.watch_player_label.set_markup('Player')
        GObject.timeout_add(0, self.update_watch_player)

        return True


    def on_click_watch_web_label(self, label, uri):

        """Called from callback in self.draw_widgets().

        Watch a video on its primary website.

        Args:

            label (Gtk.Label): The clicked widget

            uri (string): Ignored

        Returns:

            True to show the action has been handled

        """

        if DEBUG_FUNC_FLAG:
            print('mw 8927 on_click_watch_web_label')

        # Launch the video
        utils.open_file(uri)

        # Mark the video as not new (having been watched)
        if self.video_obj.new_flag:
            self.main_win_obj.app_obj.mark_video_new(self.video_obj, False)

        # Because of an unexplained Gtk problem, there is usually a crash after
        #   this function returns. Workaround is to make the label unclickable,
        #   then use a Glib timer to restore it (after some small fraction of a
        #   second)
        mod_source = utils.convert_youtube_to_hooktube(
            self.video_obj.source,
        )

        if self.video_obj.source != mod_source:
            self.watch_web_label.set_markup('YouTube')
        else:
            self.watch_web_label.set_markup('Website')

        GObject.timeout_add(0, self.update_watch_web)


        return True


class CatalogueRow(Gtk.ListBoxRow):

    """Python class acting as a wrapper for Gtk.ListBoxRow, so that we can
    retrieve the media.Video object displayed in each row.

    Args:

        video_obj (media.Video): The video object displayed on this row

    """


    # Standard class methods


    def __init__(self, video_obj):

        if DEBUG_FUNC_FLAG:
            print('mw 8973 __init__')

        super(Gtk.ListBoxRow, self).__init__()

        # IV list - class objects
        # -----------------------

        self.video_obj = video_obj


# (Dialogue window classes)


class AddVideoDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that adds invidual video(s) to
    the media registry.

    Args:

        main_win_obj (mainwin.MainWin): The parent main window

    """


    # Standard class methods


    def __init__(self, main_win_obj):

        if DEBUG_FUNC_FLAG:
            print('mw 9004 __init__')

        Gtk.Dialog.__init__(
            self,
            'Add videos',
            main_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            (
                Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OK, Gtk.ResponseType.OK,
            )
        )

        self.set_modal(False)

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(main_win_obj.spacing_size)
        grid.set_row_spacing(main_win_obj.spacing_size)

        label = Gtk.Label('Copy and paste the links to one or more videos')
        grid.attach(label, 0, 0, 2, 1)

        frame = Gtk.Frame()
        grid.attach(frame, 0, 1, 2, 1)

        scrolledwindow = Gtk.ScrolledWindow()
        frame.add(scrolledwindow)
        # (Set enough vertical room for at least five URLs)
        scrolledwindow.set_size_request(-1, 100)

        textview = Gtk.TextView()
        scrolledwindow.add(textview)
        textview.set_hexpand(True)

        # (Store various widgets as IVs, so the calling function can retrieve
        #   their contents)
        self.textbuffer = textview.get_buffer()

        separator = Gtk.HSeparator()
        grid.attach(separator, 0, 2, 2, 1)

        self.button = Gtk.RadioButton.new_with_label_from_widget(
            None,
            'I want to download these videos automatically',
        )
        grid.attach(self.button, 0, 3, 2, 1)

        self.button2 = Gtk.RadioButton.new_from_widget(self.button)
        self.button2.set_label(
            'Don\'t download anything, just check the videos',
        )
        grid.attach(self.button2, 0, 4, 2, 1)

        separator2 = Gtk.HSeparator()
        grid.attach(separator2, 0, 5, 2, 1)

        # (There are two fixed folders always at the top of this list)
        self.folder_list = []
        for name, dbid in main_win_obj.app_obj.media_name_dict.items():
            media_data_obj = main_win_obj.app_obj.media_reg_dict[dbid]

            if isinstance(media_data_obj, media.Folder) \
            and not media_data_obj.fixed_flag \
            and not media_data_obj.restrict_flag:
                self.folder_list.append(media_data_obj.name)

        self.folder_list.sort()
        self.folder_list.insert(0, main_win_obj.app_obj.fixed_misc_folder.name)
        self.folder_list.insert(1, main_win_obj.app_obj.fixed_temp_folder.name)

        label2 = Gtk.Label('Add the videos to this folder')
        grid.attach(label2, 0, 6, 2, 1)

        box = Gtk.Box()
        grid.attach(box, 0, 7, 1, 1)
        box.set_border_width(main_win_obj.spacing_size)

        image = Gtk.Image()
        box.add(image)
        image.set_from_pixbuf(main_win_obj.pixbuf_dict['folder_small'])

        listmodel = Gtk.ListStore(str)
        for item in self.folder_list:
            listmodel.append([item])

        combo = Gtk.ComboBox.new_with_model(listmodel)
        grid.attach(combo, 1, 7, 1, 1)
        combo.set_hexpand(True)

        cell = Gtk.CellRendererText()
        combo.pack_start(cell, False)
        combo.add_attribute(cell, 'text', 0)
        combo.set_active(0)
        combo.connect('changed', self.on_combo_changed)

        # Paste in the contents of the clipboard (if it contains valid URLs)
        if main_win_obj.app_obj.dialogue_copy_clipboard_flag:
            utils.add_links_from_clipboard(
                main_win_obj.app_obj,
                self.textbuffer,
            )

        # Display the dialogue window
        self.show_all()


    # Public class methods


    def on_combo_changed(self, combo):

        """Called from callback in self.__init__().

        Store the combobox's selected item, so the calling function can
        retrieve it.

        Args:

            combo (Gtk.ComboBox): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 9131 on_combo_changed')

        self.parent_name = self.folder_list[combo.get_active()]


class AddChannelDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that adds a channel to the media
    registry.

    Args:

        main_win_obj (mainwin.MainWin): The parent main window

    """


    # Standard class methods


    def __init__(self, main_win_obj, keep_folder_name=None):

        if DEBUG_FUNC_FLAG:
            print('mw 9154 __init__')


        Gtk.Dialog.__init__(
            self,
            'Add channel',
            main_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            (
                Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OK, Gtk.ResponseType.OK,
            )
        )

        self.set_modal(False)

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(main_win_obj.spacing_size)
        grid.set_row_spacing(main_win_obj.spacing_size)

        label = Gtk.Label('Enter the channel name')
        grid.attach(label, 0, 0, 2, 1)
        label2 = Gtk.Label()
        grid.attach(label2, 0, 1, 2, 1)
        label2.set_markup(
            '<i>(Use the channel\'s real name or a customised name)</i>',
        )

        # (Store various widgets as IVs, so the calling function can retrieve
        #   their contents)
        self.entry = Gtk.Entry()
        grid.attach(self.entry, 0, 2, 2, 1)
        self.entry.set_hexpand(True)

        label3 = Gtk.Label('Copy and paste a link to the channel')
        grid.attach(label3, 0, 3, 2, 1)

        self.entry2 = Gtk.Entry()
        grid.attach(self.entry2, 0, 4, 2, 1)
        self.entry2.set_hexpand(True)

        separator = Gtk.HSeparator()
        grid.attach(separator, 0, 5, 2, 1)

        self.button = Gtk.RadioButton.new_with_label_from_widget(
            None,
            'I want to download videos from this channel automatically',
        )
        grid.attach(self.button, 0, 6, 2, 1)

        self.button2 = Gtk.RadioButton.new_from_widget(self.button)
        self.button2.set_label(
            'Don\'t download anything, just check for new videos',
        )
        grid.attach(self.button2, 0, 7, 2, 1)

        # (There is one fixed folder always at the top of this list)
        self.folder_list = []
        for name, dbid in main_win_obj.app_obj.media_name_dict.items():
            media_data_obj = main_win_obj.app_obj.media_reg_dict[dbid]

            if isinstance(media_data_obj, media.Folder) \
            and not media_data_obj.fixed_flag \
            and not media_data_obj.restrict_flag \
            and media_data_obj.get_depth() \
            < main_win_obj.app_obj.media_max_level \
            and (
                keep_folder_name is None
                or keep_folder_name != media_data_obj.name
            ):
                self.folder_list.append(media_data_obj.name)

        self.folder_list.sort()
        self.folder_list.insert(0, '')
        self.folder_list.insert(1, main_win_obj.app_obj.fixed_temp_folder.name)

        # (If continuously re-opening this dialogue window, show the same
        #   folder at the top of the list as the previous time)
        if keep_folder_name is not None:
            self.folder_list.insert(0, keep_folder_name)

        separator2 = Gtk.HSeparator()
        grid.attach(separator2, 0, 8, 2, 1)

        label4 = Gtk.Label('(Optional) Add this channel inside a folder')
        grid.attach(label4, 0, 9, 2, 1)

        box = Gtk.Box()
        grid.attach(box, 0, 10, 1, 1)
        box.set_border_width(main_win_obj.spacing_size)

        image = Gtk.Image()
        box.add(image)
        image.set_from_pixbuf(main_win_obj.pixbuf_dict['folder_small'])

        listmodel = Gtk.ListStore(str)
        for item in self.folder_list:
            listmodel.append([item])

        combo = Gtk.ComboBox.new_with_model(listmodel)
        grid.attach(combo, 1, 10, 1, 1)
        combo.set_hexpand(True)

        cell = Gtk.CellRendererText()
        combo.pack_start(cell, False)
        combo.add_attribute(cell, 'text', 0)
        combo.set_active(0)
        combo.connect('changed', self.on_combo_changed)

        # Paste in the contents of the clipboard (if it contains at least one
        #   valid URL)
        if main_win_obj.app_obj.dialogue_copy_clipboard_flag \
        and not main_win_obj.app_obj.dialogue_keep_open_flag:
            utils.add_links_from_clipboard(main_win_obj.app_obj, self.entry2)

        # Display the dialogue window
        self.show_all()


    # Public class methods


    def on_combo_changed(self, combo):

        """Called from callback in self.__init__().

        Store the combobox's selected item, so the calling function can
        retrieve it.

        Args:

            combo (Gtk.ComboBox): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 9294 on_combo_changed')

        self.parent_name = self.folder_list[combo.get_active()]


class AddPlaylistDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that adds a playlist to the
    media registry.

    Args:

        main_win_obj (mainwin.MainWin): The parent main window

    """


    # Standard class methods


    def __init__(self, main_win_obj, keep_folder_name=None):

        if DEBUG_FUNC_FLAG:
            print('mw 9317 __init__')

        Gtk.Dialog.__init__(
            self,
            'Add playlist',
            main_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            (
                Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OK, Gtk.ResponseType.OK,
            )
        )

        self.set_modal(False)

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(main_win_obj.spacing_size)
        grid.set_row_spacing(main_win_obj.spacing_size)

        label = Gtk.Label('Enter the playlist name')
        grid.attach(label, 0, 0, 2, 1)
        label2 = Gtk.Label()
        grid.attach(label2, 0, 1, 2, 1)
        label2.set_markup(
            '<i>(Use the playlist\'s real name or a customised name)</i>',
        )

        # (Store various widgets as IVs, so the calling function can retrieve
        #   their contents)
        self.entry = Gtk.Entry()
        grid.attach(self.entry, 0, 2, 2, 1)
        self.entry.set_hexpand(True)

        label3 = Gtk.Label('Copy and paste a link to the playlist')
        grid.attach(label3, 0, 3, 2, 1)

        self.entry2 = Gtk.Entry()
        grid.attach(self.entry2, 0, 4, 2, 1)
        self.entry2.set_hexpand(True)

        separator = Gtk.HSeparator()
        grid.attach(separator, 0, 5, 2, 1)

        self.button = Gtk.RadioButton.new_with_label_from_widget(
            None,
            'I want to download videos from this playlist automatically',
        )
        grid.attach(self.button, 0, 6, 2, 1)

        self.button2 = Gtk.RadioButton.new_from_widget(self.button)
        self.button2.set_label(
            'Don\'t download anything, just check for new videos',
        )
        grid.attach(self.button2, 0, 7, 2, 1)

        self.folder_list = []
        for name, dbid in main_win_obj.app_obj.media_name_dict.items():
            media_data_obj = main_win_obj.app_obj.media_reg_dict[dbid]

            if isinstance(media_data_obj, media.Folder) \
            and not media_data_obj.fixed_flag \
            and not media_data_obj.restrict_flag \
            and media_data_obj.get_depth() \
            < main_win_obj.app_obj.media_max_level \
            and (
                keep_folder_name is None
                or keep_folder_name != media_data_obj.name
            ):
                self.folder_list.append(media_data_obj.name)

        self.folder_list.sort()
        self.folder_list.insert(0, '')
        self.folder_list.insert(1, main_win_obj.app_obj.fixed_temp_folder.name)

        # (If continuously re-opening this dialogue window, show the same
        #   folder at the top of the list as the previous time)
        if keep_folder_name is not None:
            self.folder_list.insert(0, keep_folder_name)

        separator2 = Gtk.HSeparator()
        grid.attach(separator2, 0, 8, 2, 1)

        label4 = Gtk.Label('(Optional) Add this playlist inside a folder')
        grid.attach(label4, 0, 9, 2, 1)

        box = Gtk.Box()
        grid.attach(box, 0, 10, 1, 1)
        box.set_border_width(main_win_obj.spacing_size)

        image = Gtk.Image()
        box.add(image)
        image.set_from_pixbuf(main_win_obj.pixbuf_dict['folder_small'])

        listmodel = Gtk.ListStore(str)
        for item in self.folder_list:
            listmodel.append([item])

        combo = Gtk.ComboBox.new_with_model(listmodel)
        grid.attach(combo, 1, 10, 1, 1)
        combo.set_hexpand(True)

        cell = Gtk.CellRendererText()
        combo.pack_start(cell, False)
        combo.add_attribute(cell, 'text', 0)
        combo.set_active(0)
        combo.connect('changed', self.on_combo_changed)

        # Paste in the contents of the clipboard (if it contains at least one
        #   valid URL)
        if main_win_obj.app_obj.dialogue_copy_clipboard_flag \
        and not main_win_obj.app_obj.dialogue_keep_open_flag:
            utils.add_links_from_clipboard(main_win_obj.app_obj, self.entry2)

        # Display the dialogue window
        self.show_all()


    # Public class methods


    def on_combo_changed(self, combo):

        """Called from callback in self.__init__().

        Store the combobox's selected item, so the calling function can
        retrieve it.

        Args:

            combo (Gtk.ComboBox): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 9455 on_combo_changed')

        self.parent_name = self.folder_list[combo.get_active()]


class AddFolderDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that adds a folder to the media
    registry.

    Args:

        main_win_obj (mainwin.MainWin): The parent main window

    """


    # Standard class methods


    def __init__(self, main_win_obj):

        if DEBUG_FUNC_FLAG:
            print('mw 9478 __init__')

        Gtk.Dialog.__init__(
            self,
            'Add folder',
            main_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            (
                Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OK, Gtk.ResponseType.OK,
            )
        )

        self.set_modal(False)

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(main_win_obj.spacing_size)
        grid.set_row_spacing(main_win_obj.spacing_size)

        label = Gtk.Label('Enter the folder name')
        grid.attach(label, 0, 0, 2, 1)

        # (Store various widgets as IVs, so the calling function can retrieve
        #   their contents)
        self.entry = Gtk.Entry()
        grid.attach(self.entry, 0, 1, 2, 1)
        self.entry.set_hexpand(True)

        separator = Gtk.HSeparator()
        grid.attach(separator, 0, 2, 2, 1)

        self.button = Gtk.RadioButton.new_with_label_from_widget(
            None,
            'I want to download videos from this folder automatically',
        )
        grid.attach(self.button, 0, 3, 2, 1)

        self.button2 = Gtk.RadioButton.new_from_widget(self.button)
        self.button2.set_label(
            'Don\'t download anything, just check for new videos',
        )
        grid.attach(self.button2, 0, 4, 2, 1)

        # (There is one fixed folder always at the top of this list)
        self.folder_list = []
        for name, dbid in main_win_obj.app_obj.media_name_dict.items():
            media_data_obj = main_win_obj.app_obj.media_reg_dict[dbid]

            if isinstance(media_data_obj, media.Folder) \
            and not media_data_obj.fixed_flag \
            and not media_data_obj.restrict_flag \
            and media_data_obj.get_depth() \
            < main_win_obj.app_obj.media_max_level:
                self.folder_list.append(media_data_obj.name)

        self.folder_list.insert(0, '')
        self.folder_list.insert(1, main_win_obj.app_obj.fixed_temp_folder.name)

        separator2 = Gtk.HSeparator()
        grid.attach(separator2, 0, 5, 2, 1)

        label4 = Gtk.Label(
            '(Optional) Add this folder inside another folder',
        )
        grid.attach(label4, 0, 6, 2, 1)

        box = Gtk.Box()
        grid.attach(box, 0, 7, 1, 1)
        box.set_border_width(main_win_obj.spacing_size)

        image = Gtk.Image()
        box.add(image)
        image.set_from_pixbuf(main_win_obj.pixbuf_dict['folder_small'])

        self.folder_list.sort()

        listmodel = Gtk.ListStore(str)
        for item in self.folder_list:
            listmodel.append([item])

        combo = Gtk.ComboBox.new_with_model(listmodel)
        grid.attach(combo, 1, 7, 1, 1)
        combo.set_hexpand(True)

        cell = Gtk.CellRendererText()
        combo.pack_start(cell, False)
        combo.add_attribute(cell, 'text', 0)
        combo.set_active(0)
        combo.connect('changed', self.on_combo_changed)

        # Display the dialogue window
        self.show_all()


    # Public class methods


    def on_combo_changed(self, combo):

        """Called from callback in self.__init__().

        Store the combobox's selected item, so the calling function can
        retrieve it.

        Args:

            combo (Gtk.ComboBox): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 9593 on_combo_changed')

        self.parent_name = self.folder_list[combo.get_active()]


class DeleteContainerDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that prompts the user for
    confirmation, before removing a media.Channel, media.Playlist or
    media.Folder object.

    Args:

        main_win_obj (mainwin.MainWin): The parent main window

        media_data_obj (media.Channel, media.Playlist or media.Folder): The
            container media data object to be deleted

        empty_flag (True or False): If True, the container media data object is
            to be emptied, rather than being deleted

    """


    # Standard class methods


    def __init__(self, main_win_obj, media_data_obj, empty_flag):

        if DEBUG_FUNC_FLAG:
            print('mw 9623 __init__')

        # Prepare variables
        pkg_string = utils.upper_case_first(__main__. __packagename__)

        if isinstance(media_data_obj, media.Channel):
            obj_type = 'channel'
        elif isinstance(media_data_obj, media.Playlist):
            obj_type = 'playlist'
        elif isinstance(media_data_obj, media.Folder):
            obj_type = 'folder'
        else:
            return self.app_obj.system_error(
                239,
                'Dialogue window setup failed sanity check',
            )

        # Count the container object's children
        total_count, self.video_count, channel_count, playlist_count, \
        folder_count = media_data_obj.count_descendants( [0, 0, 0, 0, 0] )

        # Create the dialogue window
        if not empty_flag:
            title = 'Delete ' + obj_type
        else:
            title = 'Empty ' + obj_type

        Gtk.Dialog.__init__(
            self,
            title,
            main_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            (
                Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OK, Gtk.ResponseType.OK,
            )
        )

        self.set_modal(False)
        self.set_resizable(False)

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(main_win_obj.spacing_size)
        grid.set_row_spacing(main_win_obj.spacing_size)

        label = Gtk.Label()
        grid.attach(label, 0, 0, 1, 1)
        label.set_markup('<b>' + media_data_obj.name + '</b>')

        separator = Gtk.HSeparator()
        grid.attach(separator, 0, 1, 1, 1)

        if not total_count:

            if obj_type == 'folder':

                label2 = Gtk.Label(
                    'This ' + obj_type + ' does not contain any videos,' \
                    + ' channels,\nplaylists or folders (but there might be' \
                    + ' some files\nin ' + pkg_string + '\'s data directory)',
                )

            else:
                label2 = Gtk.Label(
                    'This ' + obj_type + ' does not contain any videos (but' \
                    + ' there might\nbe some files in ' + pkg_string \
                    + '\'s data directory)',
                )

            grid.attach(label2, 0, 2, 1, 5)
            label2.set_alignment(0, 0.5)

        else:

            label2 = Gtk.Label('This ' + obj_type + ' contains:')
            grid.attach(label2, 0, 2, 1, 1)
            label2.set_alignment(0, 0.5)

            if folder_count == 1:
                label_string = '<b>1</b> folder'
            else:
                label_string = '<b>' + str(folder_count) + '</b> folders'

            label3 = Gtk.Label()
            grid.attach(label3, 0, 3, 1, 1)
            label3.set_markup(label_string)

            if channel_count == 1:
                label_string = '<b>1</b> channel'
            else:
                label_string = '<b>' + str(channel_count) + '</b> channels'

            label4 = Gtk.Label()
            grid.attach(label4, 0, 4, 1, 1)
            label4.set_markup(label_string)

            if playlist_count == 1:
                label_string = '<b>1</b> playlist'
            else:
                label_string = '<b>' + str(playlist_count) + '</b> playlists'

            label5 = Gtk.Label()
            grid.attach(label5, 0, 5, 1, 1)
            label5.set_markup(label_string)

            if self.video_count == 1:
                label_string = '<b>1</b> video'
            else:
                label_string = '<b>' + str(self.video_count) + '</b> videos'

            label6 = Gtk.Label()
            grid.attach(label6, 0, 6, 1, 1)
            label6.set_markup(label_string)

        separator2 = Gtk.HSeparator()
        grid.attach(separator2, 0, 7, 1, 1)

        if not empty_flag:
            label7 = Gtk.Label(
                'Do you want to delete the ' + obj_type + ' from ' \
                + pkg_string + '\'s data\ndirectory, deleting all of its' \
                + ' files, or do you just want to\nremove the ' + obj_type \
                + ' from this list?',
            )
        else:
            label7 = Gtk.Label(
                'Do you want to empty the ' + obj_type + ' in ' \
                + pkg_string + '\'s data\ndirectory, deleting all of its' \
                + ' files, or do you just want to\nempty the ' + obj_type \
                + ' in this list?',
            )

        grid.attach(label7, 0, 8, 1, 1)
        label7.set_alignment(0, 0.5)

        if not empty_flag:
            self.button = Gtk.RadioButton.new_with_label_from_widget(
                None,
                'Just remove the ' + obj_type + ' from this list',
            )
        else:
            self.button = Gtk.RadioButton.new_with_label_from_widget(
                None,
                'Just empty the ' + obj_type + ' in this list',
            )

        grid.attach(self.button, 0, 9, 1, 1)

        self.button2 = Gtk.RadioButton.new_from_widget(self.button)
        self.button2.set_label(
            'Delete all files',
        )
        grid.attach(self.button2, 0, 10, 1, 1)

        # Display the dialogue window
        self.show_all()


class SetDirectoryDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that prompts the user to set the
    directory used as Tartube's data directory.

    Args:

        main_win_obj (mainwin.MainWin): The parent main window

        default_dir (str): The path to the default data directory, which is the
            current value of mainapp.TartubeApp.data_dir

    """


    # Standard class methods


    def __init__(self, main_win_obj, default_dir):

        if DEBUG_FUNC_FLAG:
            print('mw 9799 __init__')

        Gtk.Dialog.__init__(
            self,
            'Welcome to ' + utils.upper_case_first(__main__.__packagename__) \
            + '!',
            main_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            (
                Gtk.STOCK_OK, Gtk.ResponseType.OK,
            )
        )

        self.set_modal(True)

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(main_win_obj.spacing_size)
        grid.set_row_spacing(main_win_obj.spacing_size)

        if os.name == 'nt':
            folder = 'folder'
        else:
            folder = 'directory'

        label = Gtk.Label(
            utils.upper_case_first(__main__.__packagename__) \
            + '\'s default data ' + folder + ' is:\n\n' + default_dir + '\n'
        )
        grid.attach(label, 0, 0, 1, 1)

        # (Store various widgets as IVs, so the calling function can retrieve
        #   their contents)
        self.button = Gtk.RadioButton.new_with_label_from_widget(
            None,
            'Use this ' + folder
        )
        grid.attach(self.button, 0, 1, 1, 1)

        self.button2 = Gtk.RadioButton.new_from_widget(self.button)
        self.button2.set_label('Choose a different ' + folder)
        grid.attach(self.button2, 0, 2, 1, 1)

        # Display the dialogue window
        self.show_all()


class ExportDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that prompts the user before
    creating a database export.

    Args:

        main_win_obj (mainwin.MainWin): The parent main window

        whole_flag (bool): True if the whole database is to be exported, False
            if only part of the database is to be exported

    """


    # Standard class methods


    def __init__(self, main_win_obj, whole_flag):

        if DEBUG_FUNC_FLAG:
            print('mw 9870 __init__')

        Gtk.Dialog.__init__(
            self,
            'Export from database',
            main_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            (
                Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OK, Gtk.ResponseType.OK,
            )
        )

        self.set_modal(False)

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(main_win_obj.spacing_size)
        grid.set_row_spacing(main_win_obj.spacing_size)

        if not whole_flag:
            msg = utils.upper_case_first(__main__.__packagename__) \
            + ' is ready to export a partial summary of its\ndatabase,' \
            + ' containing a list of videos, channels,\nplaylists and/or' \
            + ' folders (but not including the\nvideos themselves)'
        else:
            msg = utils.upper_case_first(__main__.__packagename__) \
            + ' is ready to export a summary of its database,\n' \
            + ' containing a list of videos, channels, playlists and/or\n' \
            + ' folders (but not including the videos themselves)'

        label = Gtk.Label(msg)
        grid.attach(label, 0, 0, 1, 1)

        separator = Gtk.HSeparator()
        grid.attach(separator, 0, 1, 1, 1)

        label = Gtk.Label('Choose what should be included:')
        grid.attach(label, 0, 2, 1, 1)

        # (Store various widgets as IVs, so the calling function can retrieve
        #   their contents)
        self.checkbutton = Gtk.CheckButton()
        grid.attach(self.checkbutton, 0, 3, 1, 1)
        self.checkbutton.set_label('Include lists of videos')
        self.checkbutton.set_active(False)

        self.checkbutton2 = Gtk.CheckButton()
        grid.attach(self.checkbutton2, 0, 4, 1, 1)
        self.checkbutton2.set_label('Include channels')
        self.checkbutton2.set_active(True)

        self.checkbutton3 = Gtk.CheckButton()
        grid.attach(self.checkbutton3, 0, 5, 1, 1)
        self.checkbutton3.set_label('Include playlists')
        self.checkbutton3.set_active(True)

        self.checkbutton4 = Gtk.CheckButton()
        grid.attach(self.checkbutton4, 0, 6, 1, 1)
        self.checkbutton4.set_label('Preserve folder structure')
        self.checkbutton4.set_active(True)

        separator2 = Gtk.HSeparator()
        grid.attach(separator2, 0, 7, 1, 1)

        self.checkbutton5 = Gtk.CheckButton()
        grid.attach(self.checkbutton5, 0, 8, 1, 1)
        self.checkbutton5.set_label('Export as plain text')
        self.checkbutton5.set_active(False)
        self.checkbutton5.connect('toggled', self.on_checkbutton_toggled)

        # Display the dialogue window
        self.show_all()


    # Public class methods


    def on_checkbutton_toggled(self, checkbutton):

        """Called from callback in self.__init__().

        When the specified checkbutton is toggled, modify other widgets in the
        dialogue window.

        Args:

            checkbutton (Gtk.CheckButton): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 9965 on_checkbutton_toggled')

        if not checkbutton.get_active():
            self.checkbutton.set_sensitive(True)
            self.checkbutton4.set_sensitive(True)
        else:
            self.checkbutton.set_active(False)
            self.checkbutton.set_sensitive(False)
            self.checkbutton4.set_active(False)
            self.checkbutton4.set_sensitive(False)


class ImportDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that prompts the user before
    hanlding an export file, created by mainapp.TartubeApp.export_from_db().

    Args:

        main_win_obj (mainwin.MainWin): The parent main window

        db_dict (dict): The imported data, a dictionary described in the
            comments in mainapp.TartubeApp.export_from_db()

    """


    # Standard class methods


    def __init__(self, main_win_obj, db_dict):

        if DEBUG_FUNC_FLAG:
            print('mw 9998 __init__')

        Gtk.Dialog.__init__(
            self,
            'Import into database',
            main_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            (
                Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OK, Gtk.ResponseType.OK,
            )
        )

        self.set_modal(False)
        self.set_default_size(
            main_win_obj.app_obj.config_win_width,
            main_win_obj.app_obj.config_win_height,
        )

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(main_win_obj.spacing_size)
        grid.set_row_spacing(main_win_obj.spacing_size)

        label = Gtk.Label('Choose which items to import')
        grid.attach(label, 0, 0, 4, 1)

        scrolled = Gtk.ScrolledWindow()
        grid.attach(scrolled, 0, 1, 4, 1)
        scrolled.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        scrolled.set_hexpand(True)
        scrolled.set_vexpand(True)

        frame = Gtk.Frame()
        scrolled.add_with_viewport(frame)

        # (Store various widgets as IVs, so the calling function can retrieve
        #   their contents)
        self.treeview = Gtk.TreeView()
        frame.add(self.treeview)
        self.treeview.set_can_focus(False)

        renderer_toggle = Gtk.CellRendererToggle()
        renderer_toggle.connect('toggled', self.on_checkbutton_toggled)
        column_toggle = Gtk.TreeViewColumn(
            'Import',
            renderer_toggle,
            active=0,
        )
        self.treeview.append_column(column_toggle)

        renderer_pixbuf = Gtk.CellRendererPixbuf()
        column_pixbuf = Gtk.TreeViewColumn(
            '',
            renderer_pixbuf,
            pixbuf=1,
        )
        self.treeview.append_column(column_pixbuf)

        renderer_text = Gtk.CellRendererText()
        column_text = Gtk.TreeViewColumn(
            'Name',
            renderer_text,
            text=2,
        )
        self.treeview.append_column(column_text)

        renderer_text2 = Gtk.CellRendererText()
        column_text2 = Gtk.TreeViewColumn(
            'hide',
            renderer_text2,
            text=3,
        )
        column_text2.set_visible(False)
        self.treeview.append_column(column_text2)

        self.liststore = Gtk.ListStore(bool, GdkPixbuf.Pixbuf, str, int)
        self.treeview.set_model(self.liststore)

        self.checkbutton = Gtk.CheckButton()
        grid.attach(self.checkbutton, 0, 2, 1, 1)
        self.checkbutton.set_label('Import videos')
        self.checkbutton.set_active(False)

        self.checkbutton2 = Gtk.CheckButton()
        grid.attach(self.checkbutton2, 1, 2, 1, 1)
        self.checkbutton2.set_label('Merge channels/playlists/folders')
        self.checkbutton2.set_active(False)

        button = Gtk.Button.new_with_label('Select all')
        grid.attach(button, 2, 2, 1, 1)
        button.set_hexpand(False)
        button.connect('clicked', self.on_select_all_clicked)

        button2 = Gtk.Button.new_with_label('Deselect all')
        grid.attach(button2, 3, 2, 1, 1)
        button2.set_hexpand(False)
        button2.connect('clicked', self.on_deselect_all_clicked)

        # The data is imported as a dictionary, perhaps preserving the original
        #   folder structure of the database, or perhaps not
        # The 'db_dict' format is described in the comments in
        #   mainapp.TartubeApp.export_from_db()
        # 'db_dict' contains mini-dictionaries, 'mini_dict', whose format is
        #   also described in that function. Each 'mini_dict' represents a
        #   single media data object
        #
        # Convert 'db_dict' to a list. Each item in the list is a 'mini_dict'.
        #   Each 'mini_dict' has some new key-value pairs (except those
        #   representing videos):
        #
        #   - 'video_count': int (showing the number of videos the channel,
        #       playlist or folder contains)
        #   - 'display_name': str (the channel/playlist/folder name indented
        #       with extra whitespace (so the user can clearly see the folder
        #       structure)
        #   - 'import_flag': bool (True if this channel/playlist/folder should
        #       be imported, False if not)
        converted_list = self.convert_to_list( db_dict, [] )

        # Add a line to the textview for each channel, playlist and folder
        for mini_dict in converted_list:

            pixbuf = main_win_obj.pixbuf_dict[mini_dict['type'] + '_small']
            text = mini_dict['display_name']
            if mini_dict['video_count'] == 1:
                text += '   [ 1 video ]'
            elif mini_dict['video_count']:
                text += '   [ ' + str(mini_dict['video_count']) + ' videos ]'

            self.liststore.append( [True, pixbuf, text, mini_dict['dbid']] )

        # Compile a dictionary, a flattened version of the original 'db_dict'
        #   (i.e. which the original database's folder structure removed)
        # This new dictionary contains a single key-value pair for every
        #   channel, playlist and folder. Dictionary in the form:
        #
        #   key: the channel/playlist/folder dbid
        #   value: the 'mini_dict' for that channel/playlist/folder
        #
        # If the channel/playlist/folder has any child videos, then its
        #   'mini_dict' still has some child 'mini_dicts', one for each video
        self.flat_db_dict = {}
        for mini_dict in converted_list:
            self.flat_db_dict[mini_dict['dbid']] = mini_dict

        # Display the dialogue window
        self.show_all()


    # Public class methods


    def convert_to_list(self, db_dict, converted_list,
    parent_mini_dict=None, recursion_level=0):

        """Called by self.__init__(), and then recursively by this function.

        Converts the imported 'db_dict' into a list, with each item in the
        list being a 'mini_dict' (the format of both dictionaries is described
        in the comments in mainapp.TartubeApp.export_from_db() ).

        Args:

            db_dict (dict): The dictionary described in self.export_from_db();
                if called from self.__init__(), the original imported
                dictionary; if called recursively, a dictionary from somewhere
                inside the original imported dictionary

            converted_list (list): The converted list so far; this function
                adds more 'mini_dict' items to the list

            parent_mini_dict (dict): The contents of db_dict all represent
                children of the channel/playlist/folder represent by this
                dictionary

            recursion_level (int): The number of recursive calls to this
                function (so far)

        """

        if DEBUG_FUNC_FLAG:
            print('mw 10183 convert_to_list')

        # (Sorting function for the code immediately below)
        def sort_dict_by_name(this_dict):
            return this_dict['name']

        # Deal with importable videos/channels/playlists/folders in
        #   alphabetical order
        for mini_dict in sorted(db_dict.values(), key=sort_dict_by_name):

            if mini_dict['type'] == 'video':

                # Videos are not displayed in the treeview (but we count the
                #   number of videos in each channel/playlist/folder)
                if parent_mini_dict:
                   parent_mini_dict['video_count'] += 1

            else:

                # In the treeview, the channel/playlist/folder name is
                #   indented, so the user can see the folder structure
                mini_dict['display_name'] = (' ' * 3 * recursion_level) \
                + mini_dict['name']

                # Count the number of videos this channel/playlist/folder
                #   contains
                mini_dict['video_count'] = 0

                # Import everything, until the user chooses otherwise
                mini_dict['import_flag'] = True

                # Add this channel/playlist/folder to the list visible in the
                #   textview
                converted_list.append(mini_dict)
                # Call this function to process any child videos/channels/
                #   playlists/folders
                converted_list = self.convert_to_list(
                    mini_dict['db_dict'],
                    converted_list,
                    mini_dict,
                    recursion_level + 1,
                )

        # Procedure complete
        return converted_list


    def on_checkbutton_toggled(self, checkbutton, path):

        """Called from a callback in self.__init__().

        Respond when the user selects/deselects an item in the treeview.

        Args:

            checkbutton (Gtk.CheckButton): The widget clicked

            path (int): A number representing the widget's row

        """


        if DEBUG_FUNC_FLAG:
            print('mw 10246 on_cell_toggled')

        # The user has clicked on the checkbutton widget, so toggle the widget
        #   itself
        self.liststore[path][0] = not self.liststore[path][0]

        # Update the data to be returned (eventually) to the calling
        #   mainapp.TartubeApp.import_into_db() function
        mini_dict = self.flat_db_dict[self.liststore[path][3]]
        mini_dict['import_flag'] = self.liststore[path][0]


    def on_select_all_clicked(self, widget):

        """Called from a callback in self.__init__().

        Mark all channels/playlists/folders to be imported.

        Args:

            button (Gtk.Button): The widget clicked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 10271 on_select_all_clicked')

        for path in range(0, len(self.liststore)):
            self.liststore[path][0] = True

        for mini_dict in self.flat_db_dict.values():
            mini_dict['import_flag'] = True


    def on_deselect_all_clicked(self, widget):

        """Called from a callback in self.__init__().

        Mark all channels/playlists/folders to be not imported.

        Args:

            button (Gtk.Button): The widget clicked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 10293 on_deselect_all_clicked')

        for path in range(0, len(self.liststore)):
            self.liststore[path][0] = False

        for mini_dict in self.flat_db_dict.values():
            mini_dict['import_flag'] = False


class SetNicknameDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that prompts the user to set the
    nickname of a channel, playlist or folder.

    Args:

        main_win_obj (mainwin.MainWin): The parent main window

        media_data_obj (media.Channel, media.Playlist, media.Folder): The media
            data object whose nickname is to be changed

    """


    # Standard class methods


    def __init__(self, main_win_obj, media_data_obj):

        if DEBUG_FUNC_FLAG:
            print('mw 10323 __init__')

        Gtk.Dialog.__init__(
            self,
            'Set nickname',
            main_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            (
                Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OK, Gtk.ResponseType.OK,
            )
        )

        self.set_modal(False)

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(main_win_obj.spacing_size)
        grid.set_row_spacing(main_win_obj.spacing_size)

        if isinstance(media_data_obj, media.Channel):
            obj_type = 'channel'
        elif isinstance(media_data_obj, media.Playlist):
            obj_type = 'playlist'
        else:
            obj_type = 'folder'

        label = Gtk.Label(
            'Set the nickname for the ' + obj_type + ' \'' \
            + media_data_obj.name \
            + '\'\n(or leave it blank to reset the nickname)',
        )
        grid.attach(label, 0, 0, 1, 1)

        # (Store various widgets as IVs, so the calling function can retrieve
        #   their contents)
        self.entry = Gtk.Entry()
        grid.attach(self.entry, 0, 1, 1, 1)
        self.entry.set_text(media_data_obj.nickname)

        # Display the dialogue window
        self.show_all()


class SetDestinationDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that prompts the user to set the
    alternative download destination for a channel, playlist or folder.

    Args:

        main_win_obj (mainwin.MainWin): The parent main window

        media_data_obj (media.Channel, media.Playlist, media.Folder): The media
            data object whose download destination is to be changed

    """


    # Standard class methods


    def __init__(self, main_win_obj, media_data_obj):

        if DEBUG_FUNC_FLAG:
            print('mw 10391 __init__')

        Gtk.Dialog.__init__(
            self,
            'Set download destination',
            main_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            (
                Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OK, Gtk.ResponseType.OK,
            )
        )

        self.set_modal(False)

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(main_win_obj.spacing_size)
        grid.set_row_spacing(main_win_obj.spacing_size)

        if os.name == 'nt':
            dir_name = 'folder'
        else:
            dir_name = 'directory'

        if isinstance(media_data_obj, media.Channel):
            obj_type = 'channel'
        elif isinstance(media_data_obj, media.Playlist):
            obj_type = 'playlist'
        else:
            obj_type = 'folder'

        label = Gtk.Label(
            'This ' + obj_type + ' can store its videos in its own ' \
            + dir_name + ', or it can store\nthem in a different ' \
            + dir_name \
            + '\n\nChoose a different ' + dir_name + ' if:' \
            + '\n\n1. You want to add a channel and its playlists, without' \
            + ' downloading\nthe same video twice' \
            + '\n\n2. A video creator has channels on both YouTube and' \
            + ' BitChute, and\nyou want to add both without downloading the' \
            + ' same video twice',
        )
        grid.attach(label, 0, 0, 1, 1)

        separator = Gtk.HSeparator()
        grid.attach(separator, 0, 1, 1, 1)

        radiobutton = Gtk.RadioButton.new_with_label_from_widget(
            None,
            'Use this ' + obj_type + '\'s own ' + dir_name,
        )
        grid.attach(radiobutton, 0, 2, 1, 1)
        # Signal connect appears below

        radiobutton2 = Gtk.RadioButton.new_from_widget(radiobutton)
        radiobutton2.set_label('Choose a different ' + dir_name + ':')
        grid.attach(radiobutton2, 0, 3, 1, 1)
        # Signal connect appears below

        # Get a sorted list of channels/playlists/folders
        app_obj = main_win_obj.app_obj
        name_list = list(app_obj.media_name_dict.keys())
        name_list.sort(key=lambda x: x.lower())

        # Add a combo
        store = Gtk.ListStore(GdkPixbuf.Pixbuf, str)

        count = -1
        select_index = 0

        for name in name_list:
            dbid = app_obj.media_name_dict[name]
            obj = app_obj.media_reg_dict[dbid]

            if isinstance(obj, media.Channel):
                icon_name = 'channel_small'
            elif isinstance(obj, media.Playlist):
                icon_name = 'playlist_small'
            else:
                icon_name = 'folder_small'

            store.append( [main_win_obj.pixbuf_dict[icon_name], name] )

            count += 1
            if dbid == media_data_obj.master_dbid:
                select_index = count

        combo = Gtk.ComboBox.new_with_model(store)
        grid.attach(combo, 0, 4, 1, 1)
        combo.set_hexpand(True)

        renderer_pixbuf = Gtk.CellRendererPixbuf()
        combo.pack_start(renderer_pixbuf, False)
        combo.add_attribute(renderer_pixbuf, 'pixbuf', 0)

        renderer_text = Gtk.CellRendererText()
        combo.pack_start(renderer_text, True)
        combo.add_attribute(renderer_text, 'text', 1)

        combo.set_active(select_index)
        # Signal connect appears below

        if media_data_obj.master_dbid == media_data_obj.dbid:
            combo.set_sensitive(False)
        else:
            radiobutton2.set_active(True)
            combo.set_sensitive(True)

        # (Store function arguments as IVs, so callback functions can retrieve
        #   them)
        self.main_win_obj = main_win_obj
        self.media_data_obj = media_data_obj
        # (Store the user's choice as an IV, so the calling function can
        #   retrieve it)
        self.choice = media_data_obj.master_dbid

        # Signal connects from above
        radiobutton.connect(
            'toggled',
            self.on_radiobutton_toggled,
            combo,
        )

        radiobutton2.connect(
            'toggled',
            self.on_radiobutton2_toggled,
            combo,
        )

        combo.connect('changed', self.on_combo_changed)

        # Display the dialogue window
        self.show_all()


    def on_combo_changed(self, combo):

        """Called from callback in self.__init__().

        Store the combobox's selected item, so the calling function can
        retrieve it.

        Args:

            combo (Gtk.ComboBox): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 10544 on_combo_changed')

        tree_iter = combo.get_active_iter()
        model = combo.get_model()
        pixbuf, name = model[tree_iter][:2]

        # (Allow for the possibility that the media data object might have
        #   been deleted, since the dialogue window opened)
        if name in self.main_win_obj.app_obj.media_name_dict:
            dbid = self.main_win_obj.app_obj.media_name_dict[name]
            obj = self.main_win_obj.app_obj.media_reg_dict[dbid]
            self.choice = obj.dbid


    def on_radiobutton_toggled(self, radiobutton, combo):

        """Called from callback in self.__init__().

        When the specified radiobutton is toggled, modify other widgets in the
        dialogue window, and set self.choice (the value to be retrieved by the
        calling function)

        Args:

            radiobutton (Gtk.RadioButton): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 10573 on_radiobutton_toggled')

        if radiobutton.get_active():
            combo.set_sensitive(False)
            self.choice = self.media_data_obj.dbid


    def on_radiobutton2_toggled(self, radiobutton2, combo):

        """Called from callback in self.__init__().

        When the specified radiobutton is toggled, modify other widgets in the
        dialogue window, and set self.choice (the value to be retrieved by the
        calling function)

        Args:

            radiobutton2 (Gtk.RadioButton): The clicked widget

        """

        if DEBUG_FUNC_FLAG:
            print('mw 10595 on_radiobutton2_toggled')

        if radiobutton2.get_active():
            combo.set_sensitive(True)

            tree_iter = combo.get_active_iter()
            model = combo.get_model()
            pixbuf, name = model[tree_iter][:2]

            # (Allow for the possibility that the media data object might have
            #   been deleted, since the dialogue window opened)
            if name in self.main_win_obj.app_obj.media_name_dict:
                dbid = self.main_win_obj.app_obj.media_name_dict[name]
                obj = self.main_win_obj.app_obj.media_reg_dict[dbid]
                self.choice = obj.dbid


class RenameContainerDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that prompts the user to rename
    a channel, playlist or folder.

    Args:

        main_win_obj (mainwin.MainWin): The parent main window

        media_data_obj (media.Channel, media.Playlist, media.Folder): The media
            data object whose name is to be changed

    """


    # Standard class methods


    def __init__(self, main_win_obj, media_data_obj):

        if DEBUG_FUNC_FLAG:
            print('mw 10633 __init__')

        if isinstance(media_data_obj, media.Channel):
            obj_type = 'channel'
        elif isinstance(media_data_obj, media.Playlist):
            obj_type = 'playlist'
        else:
            obj_type = 'folder'

        Gtk.Dialog.__init__(
            self,
            'Rename ' + obj_type,
            main_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            (
                Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OK, Gtk.ResponseType.OK,
            )
        )

        self.set_modal(False)

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(main_win_obj.spacing_size)
        grid.set_row_spacing(main_win_obj.spacing_size)

        label = Gtk.Label(
            'Set the new name for the ' + obj_type + ' \'' \
            + media_data_obj.name \
            + '\'\n\nNB This operation will make changes to your filesystem!',
        )
        grid.attach(label, 0, 0, 1, 1)

        # (Store various widgets as IVs, so the calling function can retrieve
        #   their contents)
        self.entry = Gtk.Entry()
        grid.attach(self.entry, 0, 1, 1, 1)
        self.entry.set_text(media_data_obj.name)

        # Display the dialogue window
        self.show_all()


class CalendarDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that prompts the user to choose
    a date on a calendar

    Args:

        parent_win_obj (mainwin.MainWin): The parent window

        date (str): A date in the form YYYYMMDD. If set, that date is
            selected in the calendar. If an empty string or None, no date is
            selected

    """


    # Standard class methods


    def __init__(self, parent_win_obj, date=None):

        if DEBUG_FUNC_FLAG:
            print('mw 10702 __init__')

        Gtk.Dialog.__init__(
            self,
            'Select a date',
            parent_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
            (
                Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                Gtk.STOCK_OK, Gtk.ResponseType.OK,
            )
        )

        self.set_modal(True)

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(parent_win_obj.spacing_size)
        grid.set_row_spacing(parent_win_obj.spacing_size)

        # (Store various widgets as IVs, so the calling function can retrieve
        #   their contents)
        self.calendar = Gtk.Calendar.new()
        grid.attach(self.calendar, 0, 0, 1, 1)

        # If the date was specified, it should be a string in the form YYYYMMDD
        if date:
            year = int(date[0:3])
            month = int(date[4:5])
            day = int(date[6:7])

            if day >= 1 and day <= 31 and month >= 1 and month <= 12 \
            and year >=1:
                self.calendar.select_month(month, year)
                self.calendar.select_day(day)

        # Display the dialogue window
        self.show_all()


class MountDriveDialogue(Gtk.Dialog):

    """Python class handling a dialogue window that asks the user what to do,
    if the drive containing Tartube's data directory is not mounted.

    Args:

        main_win_obj (mainwin.MainWin): The parent main window

    """


    # Standard class methods


    def __init__(self, main_win_obj):

        if DEBUG_FUNC_FLAG:
            print('mw 10703 __init__')

        Gtk.Dialog.__init__(
            self,
            'Mount drive',
            main_win_obj,
            Gtk.DialogFlags.DESTROY_WITH_PARENT,
        )

        self.set_modal(True)

        # Set up the dialogue window
        box = self.get_content_area()

        grid = Gtk.Grid()
        box.add(grid)
        grid.set_border_width(main_win_obj.spacing_size)
        grid.set_row_spacing(main_win_obj.spacing_size)

        script_name = utils.upper_case_first(__main__.__packagename__)
        if os.name == 'nt':
            folder = 'folder'
        else:
            folder = 'directory'

        # (Store various widgets as IVs, so the calling function can retrieve
        #   their contents)
        self.main_win_obj = main_win_obj

        label = Gtk.Label(
            'The ' + script_name + ' data ' + folder + ' is set to:',
        )
        grid.attach(label, 0, 0, 1, 1)

        label = Gtk.Label()
        grid.attach(label, 0, 1, 1, 1)
        label.set_markup(
            '<b>' \
            + utils.shorten_string(main_win_obj.app_obj.data_dir, 50) \
            + '</b>',
        )

        label = Gtk.Label(
            '...but this ' + folder + ' doesn\'t exist',
        )
        grid.attach(label, 0, 2, 1, 1)

        separator = Gtk.HSeparator()
        grid.attach(separator, 0, 3, 1, 1)

        self.mounted_button = Gtk.Button.new_with_label(
            'I have mounted the drive, please try again',
        )
        grid.attach(self.mounted_button, 0, 4, 1, 1)
        self.mounted_button.set_hexpand(False)
        self.mounted_button.connect('clicked', self.on_mounted_clicked)

        self.select_button = Gtk.Button.new_with_label(
            'Select a different data directory',
        )
        grid.attach(self.select_button, 0, 5, 1, 1)
        self.select_button.set_hexpand(False)
        self.select_button.connect('clicked', self.on_select_clicked)

        self.default_button = Gtk.Button.new_with_label(
            'Use the default data directory',
        )
        grid.attach(self.default_button, 0, 6, 1, 1)
        self.default_button.set_hexpand(False)
        self.default_button.connect('clicked', self.on_default_clicked)

        self.stop_button = Gtk.Button.new_with_label(
            'Shut down ' + script_name,
        )
        grid.attach(self.stop_button, 0, 7, 1, 1)
        self.stop_button.set_hexpand(False)
        self.stop_button.connect('clicked', self.on_stop_clicked)

        # Flag set to True if the data directory specified by
        #   mainapp.TartubeApp.data_dir is now available
        self.available_flag = False

        # Display the dialogue window
        self.show_all()


    # Public class methods


    def on_mounted_clicked(self, widget):

        """Called from a callback in self.__init__().

        The user claims to have mounted the drive containing Tartube's data
        directory. Check this is the case.

        Args:

            button (Gtk.Button): The widget clicked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 10704 on_mounted_clicked')

        app_obj = self.main_win_obj.app_obj

        if os.path.exists(app_obj.data_dir):

            # Data directory exists
            self.available_flag = True
            self.destroy()

        else:

            # Data directory still does not exist. Inform the user
            if os.name == 'nt':
                folder = 'folder'
            else:
                folder = 'directory'


            mini_win = app_obj.dialogue_manager_obj.show_msg_dialogue(
                'The ' + folder + ' still doesn\'t exist\nPlease try a' \
                + ' different option',
                'error',
                'ok',
                self,           # Parent window is this window
            )

            mini_win.set_modal(True)


    def on_select_clicked(self, widget):

        """Called from a callback in self.__init__().

        Prompt the user to select a new data directory.

        Args:

            button (Gtk.Button): The widget clicked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 10705 on_select_clicked')

        result = self.main_win_obj.app_obj.prompt_user_for_data_dir()
        if result:

            # New data directory selected
            self.available_flag = True
            self.destroy()


    def on_default_clicked(self, widget):

        """Called from a callback in self.__init__().

        Sets the data directory to the default location for this system.

        Args:

            button (Gtk.Button): The widget clicked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 10706 on_default_clicked')

        self.main_win_obj.app_obj.reset_data_dir()
        self.available_flag = True
        self.destroy()


    def on_stop_clicked(self, widget):

        """Called from a callback in self.__init__().

        Don't select a new data directory; just tell Tartube to shut down.

        Args:

            button (Gtk.Button): The widget clicked

        """

        if DEBUG_FUNC_FLAG:
            print('mw 10707 on_stop_clicked')

        self.available_flag = False
        self.destroy()


