"""TranscriptView: the list of a conversation's messages in the message pane.

Scrolled per pixel. Scrolling near the top loads the page before (the model's
load_older); the rows inserted above are compensated for, so what was on
screen stays where it was. At the bottom, new messages keep it at the bottom.
Messages are drawn by BubbleDelegate; a click on a link opens it. A right
click, or the actions button a bubble shows under the mouse, opens its menu:
quick reactions on top (reactionRequested), copy text or link, open or save the
file, and delete (asking first; on one's
own message also for the other party), handed to the pane (actionRequested). Behind them the linen texture of Sylk Mobile and
Blink for macOS (dark or light with the theme), tiled from the viewport so the
weave stays still while the transcript scrolls.
"""

from PyQt6.QtCore import Qt, QElapsedTimer, QPersistentModelIndex, QPoint, QTimer, QUrl, pyqtSignal
from PyQt6.QtGui import QBrush, QClipboard, QDesktopServices, QGuiApplication, QKeySequence, QPalette, QPixmap
from PyQt6.QtWidgets import QAbstractItemView, QApplication, QFrame, QListView, QMenu

from blink.messagepane.delegate import BubbleDelegate
from blink.messagepane.files import local_file
from blink.messagepane.format import bubble_kind, plain_summary
from blink.util import translate
from blink.resources import Resources
from blink.widgets.color import follow_theme, is_dark_theme


def copy_text(text):
    """Put text on the clipboard, and on the X11 selection too (middle-click paste), saying so in the log."""
    from PyQt6.QtGui import QClipboard
    from blink.logging import ActivityLog
    clipboard = QGuiApplication.clipboard()
    clipboard.setText(text, QClipboard.Mode.Clipboard)
    if clipboard.supportsSelection():
        clipboard.setText(text, QClipboard.Mode.Selection)
    copied = clipboard.text(QClipboard.Mode.Clipboard)
    ActivityLog().info(f'[ui] Copied {len(text)} characters to the clipboard (platform {QGuiApplication.platformName()}, read back: {"the same" if copied == text else f"{len(copied)} characters"})')


__all__ = ['TranscriptView']


class TranscriptView(QListView):
    load_margin = 48        # pixels from the top that load the page before
    menu_actions = None     # what a message's menu offers besides copy, open and save (None: everything); see offers()
    extra_menu_actions = None   # callable(item) -> [(label, callback)]: actions of the transcript's own (Reply in Private)

    actionRequested = pyqtSignal(str, object)      # ('delete', 'reply', 'edit', 'caption', 'info' or 'open', MessageItem)
    quoteClicked = pyqtSignal(object)              # the reply dict of a clicked quote
    audioAction = pyqtSignal(object, str, float)   # MessageItem, 'play' or 'seek', fraction (seek)
    reactionRequested = pyqtSignal(object, str)    # MessageItem, emoji

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFrameShape(QFrame.Shape.NoFrame)
        self.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)
        self.setWordWrap(True)
        self.setUniformItemSizes(False)
        self.setResizeMode(QListView.ResizeMode.Adjust)
        self.setMouseTracking(True)
        self.setContextMenuPolicy(Qt.ContextMenuPolicy.DefaultContextMenu)
        self.bubble_delegate = BubbleDelegate(self)
        self.setItemDelegate(self.bubble_delegate)
        self._set_background()
        follow_theme(self)
        from blink.messagepane.media import MediaCache
        MediaCache.instance().ready.connect(self._SH_MediaReady)
        from blink.messagepane.audio import audio_available
        if audio_available():
            from blink.messagepane.audio import AudioInfo, AudioPlayer
            AudioPlayer.instance().changed.connect(self._SH_MediaReady)
            AudioPlayer.instance().frameChanged.connect(self._SH_VideoFrame)
            AudioInfo.instance().measured.connect(self._SH_MediaReady)
        from blink.messagepane.locations import LocationStore, TileCache
        TileCache.instance().tileReady.connect(self.viewport().update)
        LocationStore.instance().changed.connect(self._SH_LocationChanged)
        from blink.messagepane.video import VideoProbe, video_available
        if video_available():
            VideoProbe.instance().probed.connect(self._SH_VideoProbed)
        self._anchor = None         # (maximum, value) before rows were inserted at the top
        self._stick = True          # follow the bottom
        self._selecting = None      # (row being selected in, as a persistent index; anchor character) while the button is down
        self._dragged = False       # the press became a text selection: its release is not a click
        self._double_click = QElapsedTimer()     # a press soon after a double click is a triple click: the paragraph
        self._decrypt_timer = QTimer(self)      # the rows in view that hold ciphertext are decrypted once the view settles
        self._decrypt_timer.setSingleShot(True)
        self._decrypt_timer.setInterval(150)
        self._decrypt_timer.timeout.connect(self._decrypt_visible)
        scrollbar = self.verticalScrollBar()
        scrollbar.valueChanged.connect(self._SH_ScrollValueChanged)
        scrollbar.rangeChanged.connect(self._SH_ScrollRangeChanged)

    def setModel(self, model):
        old = self.model()
        if old is not None:
            for signal, slot in self._connections(old):
                try:
                    signal.disconnect(slot)
                except TypeError:
                    pass
        super().setModel(model)
        self._anchor = None
        self._stick = True
        if model is not None:
            for signal, slot in self._connections(model):
                signal.connect(slot)
            QTimer.singleShot(0, self.scrollToBottom)

    def _connections(self, model):
        return ((model.rowsAboutToBeInserted, self._SH_RowsAboutToBeInserted), (model.initialLoadFinished, self._SH_InitialLoadFinished),
                (model.jumped, self._SH_Jumped), (model.rowsInserted, self._schedule_decrypt), (model.modelReset, self._schedule_decrypt))

    # Decrypting what is in view (ConversationModel.decrypt_rows)

    decrypt_margin = 5      # rows above and below the view decrypted with it, so scrolling a little shows them opened

    def _schedule_decrypt(self, *args):
        self._decrypt_timer.start()

    def _decrypt_visible(self):
        model = self.model()
        if model is None or not hasattr(model, 'decrypt_rows') or model.rowCount() == 0:
            return
        viewport = self.viewport().rect()
        top = self.indexAt(viewport.topLeft() + QPoint(viewport.width() // 2, 0))
        bottom = self.indexAt(viewport.bottomLeft() + QPoint(viewport.width() // 2, -1))
        first = top.row() if top.isValid() else 0
        last = bottom.row() if bottom.isValid() else model.rowCount() - 1
        model.decrypt_rows(first - self.decrypt_margin, last + self.decrypt_margin)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self._schedule_decrypt()

    def _SH_Jumped(self, row):
        """After a jump to a day: its first message at the top."""
        self._stick = False
        self._anchor = None
        index = self.model().index(row, 0)
        QTimer.singleShot(0, lambda: self.scrollTo(index, QAbstractItemView.ScrollHint.PositionAtTop))
        QTimer.singleShot(0, self._fill)

    def _at_bottom(self):
        scrollbar = self.verticalScrollBar()
        return scrollbar.value() >= scrollbar.maximum() - 4

    def _SH_InitialLoadFinished(self):
        self._stick = True
        QTimer.singleShot(0, self.scrollToBottom)
        QTimer.singleShot(0, self._fill)

    def _SH_RowsAboutToBeInserted(self, parent, first, last):
        model = self.model()
        scrollbar = self.verticalScrollBar()
        if first == 0 and model.rowCount() > 0:
            self._anchor = (scrollbar.maximum(), scrollbar.value())
        self._stick = self._at_bottom() and not model.has_newer

    def _SH_ScrollRangeChanged(self, minimum, maximum):
        scrollbar = self.verticalScrollBar()
        if self._anchor is not None:
            old_maximum, old_value = self._anchor
            self._anchor = None
            scrollbar.setValue(old_value + maximum - old_maximum)
        elif self._stick:
            scrollbar.setValue(maximum)
        self._fill()
        self._schedule_decrypt()

    def _fill(self):
        """A page that does not fill the view has no scroll bar to scroll up with: load the one before."""
        model = self.model()
        if model is not None and not model.loading and self.verticalScrollBar().maximum() == 0:
            if model.has_more:
                QTimer.singleShot(0, model.load_older)
            elif model.has_newer:
                QTimer.singleShot(0, model.load_newer)

    def _SH_ScrollValueChanged(self, value):
        self._schedule_decrypt()
        model = self.model()
        self._stick = self._at_bottom() and not (model is not None and model.has_newer)
        if model is not None and model.has_newer and not model.loading and value >= self.verticalScrollBar().maximum() - self.load_margin:
            model.load_newer()
        if model is not None and value <= self.load_margin and model.has_more and not model.loading and self.verticalScrollBar().maximum() > 0:
            model.load_older()

    _linen = {}         # dark: QPixmap

    def _set_background(self):
        dark = is_dark_theme()
        pixmap = self._linen.get(dark)
        if pixmap is None:
            pixmap = self._linen[dark] = QPixmap(Resources.get('icons/dark_linen.png' if dark else 'icons/light_linen.png'))
        viewport = self.viewport()
        palette = viewport.palette()
        if not pixmap.isNull():
            for group in (QPalette.ColorGroup.Active, QPalette.ColorGroup.Inactive, QPalette.ColorGroup.Disabled):
                palette.setBrush(group, QPalette.ColorRole.Base, QBrush(pixmap))
        viewport.setPalette(palette)
        viewport.setAutoFillBackground(True)
        viewport.setBackgroundRole(QPalette.ColorRole.Base)

    def apply_theme(self):
        self._set_background()
        self.bubble_delegate.clear_cache()
        self.scheduleDelayedItemsLayout()
        self.viewport().update()

    def changeEvent(self, event):
        if event.type() in (event.Type.FontChange, event.Type.StyleChange):
            self.bubble_delegate.clear_cache()
        super().changeEvent(event)

    # Links and copying

    def _link_at(self, position):
        index = self.indexAt(position)
        if not index.isValid():
            return ''
        return self.bubble_delegate.anchor_at(index, self.visualRect(index), position)

    def _on_actions_button(self, position):
        index = self.indexAt(position)
        return index.isValid() and self.bubble_delegate.actions_at(index, self.visualRect(index), position)

    # Selecting text in a bubble with the mouse: drag, double click (a word), triple click (a paragraph);
    # Ctrl+C or Copy in the menu copies it, and on X11 it is the selection middle click pastes

    def _set_text_selection(self, selection):
        if selection != self.bubble_delegate.text_selection:
            self.bubble_delegate.text_selection = selection
            self.viewport().update()

    def _selection_index(self):
        """The row the selection is in, or None."""
        selection = self.bubble_delegate.text_selection
        model = self.model()
        if selection is None or model is None or not hasattr(model, 'row_of'):
            return None
        row = model.row_of(selection[0])
        return model.index(row, 0) if row is not None else None

    def selected_text(self):
        index = self._selection_index()
        if index is None or not index.isValid():
            return ''
        return self.bubble_delegate.selected_text(index, self.visualRect(index))

    def _publish_selection(self):
        text = self.selected_text()
        clipboard = QGuiApplication.clipboard()
        if text and clipboard.supportsSelection():
            clipboard.setText(text, QClipboard.Mode.Selection)      # what middle click pastes, as anywhere on X11

    def _select_range(self, index, unit, position):
        found = self.bubble_delegate.text_range(index, self.visualRect(index), position, unit)
        if found is None:
            return False
        item = index.data(Qt.ItemDataRole.UserRole)
        self._set_text_selection((item.id, found[0], found[1]))
        self._dragged = True
        self._publish_selection()
        return True

    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            position = event.position().toPoint()
            index = self.indexAt(position)
            self._selecting = None
            self._dragged = False
            on_control = index.isValid() and (self._on_actions_button(position) or self.bubble_delegate.quote_at(index, self.visualRect(index), position) is not None
                                              or self.bubble_delegate.cancel_at(index, self.visualRect(index), position) or self.bubble_delegate.download_at(index, self.visualRect(index), position))
            found = self.bubble_delegate.text_position(index, self.visualRect(index), position) if index.isValid() and not on_control else None
            if found is not None:
                self.setFocus(Qt.FocusReason.MouseFocusReason)      # for Ctrl+C
                if self._double_click.isValid() and self._double_click.elapsed() < QApplication.doubleClickInterval():
                    self._double_click.invalidate()
                    if self._select_range(index, 'block', position):
                        return
                item = index.data(Qt.ItemDataRole.UserRole)
                self._selecting = (QPersistentModelIndex(index), found)
                self._set_text_selection((item.id, found, found))
            elif not on_control:
                self._set_text_selection(None)
        super().mousePressEvent(event)

    def mouseDoubleClickEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            position = event.position().toPoint()
            index = self.indexAt(position)
            if index.isValid() and not self._link_at(position) and self._select_range(index, 'word', position):
                self._selecting = None
                self._double_click.start()
                return
        super().mouseDoubleClickEvent(event)

    def keyPressEvent(self, event):
        if event.matches(QKeySequence.StandardKey.Copy) and self.selected_text():
            copy_text(self.selected_text())
            return
        if event.key() == Qt.Key.Key_Escape and self.bubble_delegate.text_selection is not None:
            self._set_text_selection(None)
            return
        super().keyPressEvent(event)

    def mouseMoveEvent(self, event):
        position = event.position().toPoint()
        if event.buttons() & Qt.MouseButton.LeftButton and self._selecting is not None:
            persistent = self._selecting[0]
            if persistent.isValid():
                index = self.model().index(persistent.row(), 0)
                found = self.bubble_delegate.text_position(index, self.visualRect(index), position, exact=False)
                if found is not None:
                    item = index.data(Qt.ItemDataRole.UserRole)
                    if found != self._selecting[1]:
                        self._dragged = True
                    self._set_text_selection((item.id, self._selecting[1], found))
                    self.viewport().setCursor(Qt.CursorShape.IBeamCursor)
                    return
        if event.buttons() & Qt.MouseButton.LeftButton:
            index = self.indexAt(position)
            hit = self.bubble_delegate.audio_hit(index, self.visualRect(index), position) if index.isValid() else None
            if hit is not None and hit[0] == 'seek':
                self.audioAction.emit(index.data(Qt.ItemDataRole.UserRole), 'seek', hit[1])     # dragging along the waveform
                return
        index = self.indexAt(position)
        on_quote = index.isValid() and self.bubble_delegate.quote_at(index, self.visualRect(index), position) is not None
        on_cancel = index.isValid() and self.bubble_delegate.cancel_at(index, self.visualRect(index), position)
        on_download = not on_cancel and index.isValid() and self.bubble_delegate.download_at(index, self.visualRect(index), position)
        if on_cancel:
            self.viewport().setToolTip(translate('message_pane', 'Cancel sending'))
        elif on_download:
            self.viewport().setToolTip(translate('message_pane', 'Download'))
        elif self.viewport().toolTip():
            self.viewport().setToolTip('')
        on_cancel = on_cancel or on_download
        if on_cancel or self._link_at(position) or self._on_actions_button(position) or on_quote or self._on_clickable_bubble(index, position):
            self.viewport().setCursor(Qt.CursorShape.PointingHandCursor)
        elif index.isValid() and self.bubble_delegate.text_position(index, self.visualRect(index), position) is not None:
            self.viewport().setCursor(Qt.CursorShape.IBeamCursor)
        else:
            self.viewport().unsetCursor()
        super().mouseMoveEvent(event)

    clickable_categories = ('image', 'audio', 'video', 'other', 'call', 'location')

    def _on_clickable_bubble(self, index, position):
        if not index.isValid():
            return False
        item = index.data(Qt.ItemDataRole.UserRole)
        return item is not None and item.category in self.clickable_categories and self.bubble_delegate.bubble_at(index, self.visualRect(index), position)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self._selecting = None
            if self._dragged:
                self._dragged = False       # the end of a selection, not a click (on a link, say)
                self._publish_selection()
                return
            selection = self.bubble_delegate.text_selection
            if selection is not None and selection[1] == selection[2]:
                self._set_text_selection(None)      # a click, nothing selected
            position = event.position().toPoint()
            index = self.indexAt(position)
            if index.isValid() and self.bubble_delegate.cancel_at(index, self.visualRect(index), position):
                self.actionRequested.emit('discard_upload', index.data(Qt.ItemDataRole.UserRole))     # the Cancel button of an upload
                return
            if index.isValid() and self.bubble_delegate.download_at(index, self.visualRect(index), position):
                self.actionRequested.emit('download', index.data(Qt.ItemDataRole.UserRole))          # the Download button of a file not here
                return
            if self._on_actions_button(position):
                index = self.indexAt(position)
                rect = self.visualRect(index)
                self._show_menu(index, position, self.viewport().mapToGlobal(position + QPoint(0, 12)))
                return
            index = self.indexAt(position)
            reply = self.bubble_delegate.quote_at(index, self.visualRect(index), position) if index.isValid() else None
            if reply is not None:
                self.quoteClicked.emit(reply)
                return
            anchor = self._link_at(position)
            if anchor:
                QDesktopServices.openUrl(QUrl(anchor))
                return
            if index.isValid() and self.bubble_delegate.bubble_at(index, self.visualRect(index), position):     # the bubble, not the space beside it
                item = index.data(Qt.ItemDataRole.UserRole)
                hit = self.bubble_delegate.audio_hit(index, self.visualRect(index), position)
                if hit is not None:
                    self.audioAction.emit(item, hit[0], hit[1] if hit[1] is not None else -1.0)
                    return
                if item is not None and item.category in ('image', 'audio', 'video', 'other'):
                    self.actionRequested.emit('open', item)      # a file: open it, or fetch it
                    return
                if item is not None and item.category == 'call':
                    self.actionRequested.emit('call_details', item)
                    return
                if item is not None and item.category == 'location':
                    self.actionRequested.emit('location', item)
                    return
        super().mouseReleaseEvent(event)

    def contextMenuEvent(self, event):
        index = self.indexAt(event.pos())
        if not index.isValid() or not self.bubble_delegate.bubble_at(index, self.visualRect(index), event.pos()):
            return
        self._show_menu(index, event.pos(), event.globalPos())

    def offers(self, action):
        """Whether a message's menu offers an action: 'react', 'reply', 'edit', 'caption', 'forward', 'send_again', 'info',
        'download', 'download_again' or 'delete' (a transcript without a conversation in history offers fewer)."""
        return self.menu_actions is None or action in self.menu_actions

    def _show_menu(self, index, position, global_position):
        item = index.data(Qt.ItemDataRole.UserRole)
        menu = QMenu(self)
        from blink.messagepane.reactions import EmojiPicker, reactable, reaction_action
        not_here = item.category in ('image', 'audio', 'video', 'other') and item.upload is None and not local_file(item)
        if self.offers('react') and reactable(item) and not not_here:        # a file not downloaded yet takes no reaction
            def pick_more(position):
                self._picker = EmojiPicker(self)       # kept, so nothing collects it while it is up
                self._picker.chosen.connect(lambda emoji: self._react(item, emoji, 'emoji picker'))
                self._picker.popup(position)
            # the picker opens once the menu has gone, so the two popups do not fight over the mouse
            menu.addAction(reaction_action(menu, lambda emoji: self._react(item, emoji, 'message menu'),
                                           lambda position: QTimer.singleShot(0, lambda: pick_more(position))))
            menu.addSeparator()
        selected = self.bubble_delegate.selected_text(index, self.visualRect(index))
        if selected:
            menu.addAction(translate('message_pane', 'Copy'), lambda: copy_text(selected))
        anchor = self._link_at(position)
        if anchor:
            menu.addAction(translate('message_pane', 'Copy Link'), lambda: copy_text(anchor))
        if bubble_kind(item) in ('text', 'note'):
            layout = self.bubble_delegate.layout(index, self.visualRect(index).width(), self.font())
            text = layout.document.toPlainText()
            menu.addAction(translate('message_pane', 'Copy Text'), lambda: copy_text(text))
        else:
            summary = plain_summary(item)
            menu.addAction(translate('message_pane', 'Copy Text'), lambda: copy_text(summary))
        path = local_file(item)
        if not path and self.offers('download') and self.bubble_delegate.downloadable(item):
            menu.addSeparator()
            menu.addAction(translate('message_pane', 'Download'), lambda: self.actionRequested.emit('download', item))
        if path:
            menu.addSeparator()
            menu.addAction(translate('message_pane', 'Open'), lambda: QDesktopServices.openUrl(QUrl.fromLocalFile(path)))
            menu.addAction(translate('message_pane', 'Save As…'), lambda: self._save_as(path))
            from blink.messagepane.files import can_download_again
            if self.offers('download_again') and item.upload is None and can_download_again(item, path):
                menu.addAction(translate('message_pane', 'Download Again…'), lambda: self.actionRequested.emit('download_again', item))
        if item.upload is not None:
            # being sent: not a message yet
            menu.addSeparator()
            if item.upload['state'] == 'failed':
                menu.addAction(translate('message_pane', 'Retry Sending'), lambda: self.actionRequested.emit('retry_upload', item))
                menu.addAction(translate('message_pane', 'Remove'), lambda: self.actionRequested.emit('discard_upload', item))
            elif item.upload['state'] == 'uploading':
                menu.addAction(translate('message_pane', 'Cancel Sending'), lambda: self.actionRequested.emit('discard_upload', item))
            if self.offers('info'):
                menu.addSeparator()
                menu.addAction(translate('message_pane', 'Info…'), lambda: self.actionRequested.emit('info', item))
            menu.exec(global_position)
            return
        if bubble_kind(item) != 'note' and item.category != 'call':     # a call record takes no reply
            menu.addSeparator()
            if self.offers('reply'):
                menu.addAction(translate('message_pane', 'Reply'), lambda: self.actionRequested.emit('reply', item))
            if self.offers('edit') and item.outgoing and bubble_kind(item) == 'text':
                menu.addAction(translate('message_pane', 'Edit'), lambda: self.actionRequested.emit('edit', item))
            if self.offers('caption') and item.outgoing and item.category in ('image', 'video'):
                menu.addAction(translate('message_pane', 'Edit Caption…'), lambda: self.actionRequested.emit('caption', item))
            from blink.messagepane.forward import forwardable
            if self.offers('forward') and forwardable(item):
                menu.addAction(translate('message_pane', 'Forward…'), lambda: self.actionRequested.emit('forward', item))
            if self.offers('send_again') and item.outgoing and path and item.category in ('image', 'audio', 'video', 'other'):
                menu.addAction(translate('message_pane', 'Send Again'), lambda: self.actionRequested.emit('send_again', item))
            if self.extra_menu_actions is not None:
                for label, callback in self.extra_menu_actions(item) or ():
                    menu.addAction(label, callback)
        menu.addSeparator()
        if self.offers('info'):
            menu.addAction(translate('message_pane', 'Info…'), lambda: self.actionRequested.emit('info', item))
        if self.offers('delete'):
            menu.addAction(translate('message_pane', 'Delete…'), lambda: self.actionRequested.emit('delete', item))
        menu.exec(global_position)

    def _react(self, item, emoji, where):
        self.reactionRequested.emit(item, emoji)

    def _save_as(self, path):
        import os
        import shutil
        from PyQt6.QtWidgets import QFileDialog
        target, _ = QFileDialog.getSaveFileName(self, translate('message_pane', 'Save As'), os.path.join(os.path.expanduser('~'), os.path.basename(path)))
        if target:
            try:
                shutil.copyfile(path, target)
            except OSError as e:
                from blink.logging import ActivityLog
                ActivityLog().warning(f'[ui] Cannot save {path} as {target}: {e}')

    def follow_bottom(self):
        """Go to the newest message and stay there (after sending)."""
        self._stick = True
        QTimer.singleShot(0, self.scrollToBottom)

    def show_message(self, message_id):
        """Scroll to a loaded message and point it out; False when it is not loaded."""
        model = self.model()
        row = model.row_of(message_id) if model is not None else None
        if row is None:
            return False
        self._stick = False
        self.scrollTo(model.index(row, 0), QAbstractItemView.ScrollHint.PositionAtCenter)
        self.bubble_delegate.flash(message_id)
        return True

    def _SH_VideoFrame(self, message_id):
        """A new frame of the movie playing: repaint its row only."""
        model = self.model()
        row = model.row_of(message_id) if model is not None else None
        if row is not None:
            self.viewport().update(self.visualRect(model.index(row, 0)))

    def _SH_LocationChanged(self, message_id):
        """A share was read (again): its bubble takes its new size (two lines under the map) and draws it."""
        model = self.model()
        row = model.row_of(message_id) if model is not None else None
        if row is not None:
            index = model.index(row, 0)
            self.bubble_delegate.sizeHintChanged.emit(index)
            self.viewport().update(self.visualRect(index))

    def _SH_VideoProbed(self, path):
        """A movie's size is known: its bubble takes the poster's shape."""
        self.scheduleDelayedItemsLayout()
        self.viewport().update()

    def _SH_MediaReady(self, path):
        """A picture finished decoding: repaint (a bubble that waited for it draws it now)."""
        self.viewport().update()
