from gettext import gettext as _
import gi

gi.require_version("GtkSource", "5")

from gi.repository import Adw, Gio, GLib, GObject, Gtk, GtkSource, Pango

import logging

from iotas.category_header_bar import CategoryHeaderBar
from iotas.category_treeview_list_store import CategoryTreeViewListStore
import iotas.config_manager
from iotas.font_size_selector import FontSizeSelector
from iotas.note import Note
from iotas.theme_selector import ThemeSelector
from iotas.ui_utils import add_mouse_button_accel


@Gtk.Template(resource_path="/org/gnome/gitlab/cheywood/Iotas/ui/editor.ui")
class Editor(Adw.Bin):
    __gtype_name__ = "Editor"
    __gsignals__ = {
        "note-modified": (GObject.SignalFlags.RUN_FIRST, None, (Note,)),
        "note-deleted": (GObject.SignalFlags.RUN_FIRST, None, (Note,)),
        "category-changed": (GObject.SignalFlags.RUN_FIRST, None, (Note, str)),
        "exit": (GObject.SignalFlags.RUN_FIRST, None, ()),
    }

    LINE_LENGTH_STEP = 50
    SETTING_CHANGE_NOTIFICATION_DURATION = 3.0
    FONT_SETTING_KEYS = ["monospace-font-name", "document-font-name"]

    _title_button = Gtk.Template.Child()
    _main_header_bar = Gtk.Template.Child()
    _rename_header_bar = Gtk.Template.Child()
    _search_header_bar = Gtk.Template.Child()
    _category_header_bar = Gtk.Template.Child()

    _stack = Gtk.Template.Child()
    _menu_button = Gtk.Template.Child()
    _render_edit_stack = Gtk.Template.Child()
    _render_edit_button_stack = Gtk.Template.Child()
    _render_button = Gtk.Template.Child()
    _edit_button = Gtk.Template.Child()
    _sourceview = Gtk.Template.Child()
    _editor_scrolledwin = Gtk.Template.Child()
    _read_only_banner = Gtk.Template.Child()
    _timed_notification = Gtk.Template.Child()

    def __init__(self):
        super().__init__()

        self.__note = None
        self.__updating_from_remote = False
        self.__sync_authenticated = False
        self.__buffer_handlers = []
        self.__current_note_handlers = []
        self._render_view = None
        self._render_view_added = False
        self.__headerbar_manually_hidden = False
        self.__active = False
        self.__font_families = {}

        self._menu_button.get_popover().add_child(ThemeSelector(), "theme")
        self.__font_size_selector = FontSizeSelector()
        self._menu_button.get_popover().add_child(self.__font_size_selector, "fontsize")

        # Retain whether markdown is enabled for the session. At the time of writing instantiating
        # WebKit after startup was crashing, so we wait until restart to change the behaviour.
        self.__markdown_render_enabled = iotas.config_manager.get_markdown_render_enabled()

        self._category_header_bar.connect("categories-changed", self.__category_changed)
        self._category_header_bar.connect("abort", self.__abort_category_change)

        self._search_header_bar.connect("resumed", self.__on_search_resumed)

        self._rename_header_bar.connect("renamed", self.__on_title_renamed)
        self._rename_header_bar.connect("cancelled", self.__on_rename_cancelled)

        self._render_edit_button_stack.set_visible(self.__markdown_render_enabled)
        if self.__markdown_render_enabled:
            self.__init_webkit()

        self.__categories_model = None

        style_manager = Adw.StyleManager.get_default()
        style_manager.connect("notify::dark", self.__on_dark_style_updated)

        iotas.config_manager.settings.connect(
            f"changed::{iotas.config_manager.LINE_LENGTH}", self.__on_line_length_changed
        )

        # Use system setting for monospace font family
        self.__dbus_proxy = Gio.DBusProxy.new_for_bus_sync(
            bus_type=Gio.BusType.SESSION,
            flags=Gio.DBusProxyFlags.NONE,
            info=None,
            name="org.freedesktop.portal.Desktop",
            object_path="/org/freedesktop/portal/desktop",
            interface_name="org.freedesktop.portal.Settings",
            cancellable=None,
        )
        if self.__dbus_proxy is None:
            logging.warning("Unable to establish D-Bus proxy for FreeDesktop.org font setting")
        else:
            self.__load_font_family_from_setting()
            self.__dbus_proxy.connect_object("g-signal", self.__desktop_setting_changed, None)

        if self.__dbus_proxy is not None:
            iotas.config_manager.settings.connect(
                f"changed::{iotas.config_manager.USE_MONOSPACE_FONT}", self.__on_font_family_changed
            )
            iotas.config_manager.settings.connect(
                f"changed::{iotas.config_manager.MARKDOWN_USE_MONOSPACE_FONT}",
                self.__on_font_family_changed,
            )

    def setup(self, model: CategoryTreeViewListStore) -> None:
        """Perform initial setup.

        :param CategoryTreeViewListStore model: Tree model
        """
        self.__setup_actions()
        self._category_header_bar.setup(model)
        self._search_header_bar.setup(self._sourceview)
        self.__font_size_selector.setup()
        self.__refresh_line_length_from_setting()

    def init_note(self, note) -> None:
        """Initialise editing session.

        :param Note note: Note to edit
        """
        self.current_note = note
        buffer = self._sourceview.get_buffer()
        for handler_id in self.__buffer_handlers:
            buffer.disconnect(handler_id)
        self._sourceview.set_visible(True)
        self._sourceview.spellchecker_enabled = False
        buffer.set_text(note.content)

        def delayed_enable_spellchecker():
            self._sourceview.spellchecker_enabled = True

        if iotas.config_manager.get_spelling_enabled():
            GLib.idle_add(delayed_enable_spellchecker)

        self.__buffer_handlers = []
        handler_id = buffer.connect("changed", self.__buffer_changed)
        self.__buffer_handlers.append(handler_id)
        handler_id = buffer.connect_after("insert-text", self.__on_insert_text)
        self.__buffer_handlers.append(handler_id)

        if iotas.config_manager.get_markdown_syntax_hightlighting_enabled():
            language = GtkSource.LanguageManager.get_default().get_language("iotas-markdown")
            buffer.set_language(language)
            buffer.set_highlight_syntax(True)
        else:
            buffer.set_language(None)
            buffer.set_highlight_syntax(False)

        self.__setup_note_signals()
        self.__update_title()

        self._read_only_banner.set_revealed(note.read_only)
        self._sourceview.set_editable(not note.read_only)
        self.__update_readonly_actions()

        # Handle case of leaflet swiped back to index while renaming or searching
        if self._stack.get_visible_child() in (
            self._rename_header_bar,
            self._search_header_bar,
            self._category_header_bar,
        ):
            self._stack.set_visible_child(self._main_header_bar)

        self._sourceview.set_visible(True)
        if self._render_edit_stack.get_visible_child() != self._editor_scrolledwin:
            self.__toggle_render()

        self._sourceview.grab_focus()
        buffer.place_cursor(buffer.get_start_iter())

        # Set scroll to top
        self._editor_scrolledwin.get_vadjustment().set_value(0)

        self.__update_scheme_and_dark_style()

        # Handle initialising in view mode
        if (
            iotas.config_manager.get_markdown_render_enabled()
            and iotas.config_manager.get_markdown_default_to_render()
        ):
            # Prevent a flash of the editor while loading rendered view
            self._sourceview.set_visible(False)
            self.__toggle_render()

    def close_note(self) -> None:
        """Close the current editing note."""

        # During note creation we ignore sanitised titles returning from the server (to avoid
        # replacing a title which is being edited via the first buffer line with something the
        # server returns). To ensure that sanitisation runs we now flag the note dirty on close to
        # ensure sanitisation occurs.
        if self.current_note.title_is_top_line:
            self.current_note.title_is_top_line = False
            self.__note.flag_changed()
            GLib.idle_add(self.emit, "note-modified", self.__note)

        for handler in self.__current_note_handlers:
            self.__note.disconnect(handler)
        self.__current_note_handlers = []

        self.current_note = None

    def cancel(self) -> None:
        """Perform a cancel action.

        Action performed will depend on whether currently editing the title.
        """
        if self._stack.get_visible_child() in (
            self._rename_header_bar,
            self._category_header_bar,
        ):
            self._stack.set_visible_child(self._main_header_bar)
            self._sourceview.grab_focus()
        elif self._stack.get_visible_child() == self._search_header_bar:
            self.__exit_search()
        else:
            self.emit("exit")

    def show_headerbar(self) -> None:
        """Show the headerbar."""
        self._stack.set_visible(True)
        self.headerbar_manually_hidden = False

    def hide_headerbar(self, editor_active: bool) -> None:
        """Hide the headerbar.

        :param bool editor_active: Whether we're currently editing.
        """
        if self._stack.get_visible_child() == self._search_header_bar:
            self.__exit_search()
        self._stack.set_visible(False)
        if editor_active:
            self._sourceview.grab_focus()

    def set_sync_authenticated(self, authenticated: bool) -> None:
        """Set that an authenticated sync session exists.

        :param bool authenticated: Whether authenticated
        """
        self.__sync_authenticated = authenticated

    @GObject.Property(type=bool, default=False)
    def active(self) -> bool:
        return self.__active

    @active.setter
    def active(self, value: bool) -> None:
        self.__active = value
        self.__enable_actions(value)

    @GObject.Property(type=Note, default=None)
    def current_note(self) -> Note:
        return self.__note

    @current_note.setter
    def current_note(self, value: Note) -> None:
        self.__note = value

    @GObject.Property(type=bool, default=False)
    def editing(self) -> bool:
        """Whether editing.

        :returns: Whether editing
        :rtype: bool
        """
        # Using the editor having an active note to determine if
        return self.__note is not None

    @GObject.Property(type=bool, default=False)
    def headerbar_manually_hidden(self) -> bool:
        return self.__headerbar_manually_hidden

    @headerbar_manually_hidden.setter
    def headerbar_manually_hidden(self, value: bool) -> None:
        self.__headerbar_manually_hidden = value

    @Gtk.Template.Callback()
    def _on_mouse_back_button_click(
        self, _gesture: Gtk.GestureClick, _n_press: int, _x: float, _y: float
    ) -> None:
        self.cancel()

    def __setup_actions(self) -> None:
        action_group = Gio.SimpleActionGroup.new()
        app = Gio.Application.get_default()

        action = Gio.SimpleAction.new("rename")
        action.connect("activate", self.__do_rename)
        action_group.add_action(action)
        app.set_accels_for_action("editor.rename", ["F2"])

        action = Gio.SimpleAction.new("edit-category")
        action.connect("activate", self.__edit_category)
        action_group.add_action(action)
        app.set_accels_for_action("editor.edit-category", ["<Control>e"])

        action = Gio.SimpleAction.new("enter-search")
        action.connect("activate", self.__on_enter_search)
        action_group.add_action(action)
        app.set_accels_for_action("editor.enter-search", ["<Control>f"])

        action = Gio.SimpleAction.new("toggle-render")
        action.connect("activate", self.__on_toggle_render)
        action_group.add_action(action)
        app.set_accels_for_action("editor.toggle-render", ["<Control>d"])

        action = Gio.SimpleAction.new("toggle-headerbar")
        action.connect("activate", self.__toggle_headerbar)
        action_group.add_action(action)
        app.set_accels_for_action("editor.toggle-headerbar", ["<Control>h"])

        action = Gio.SimpleAction.new("go-back-or-cancel")
        action.connect("activate", self.__on_cancel)
        action_group.add_action(action)
        app.set_accels_for_action("editor.go-back-or-cancel", ["Escape", "<Alt>Left"])

        action = Gio.SimpleAction.new("clear-category")
        action.connect("activate", self.__on_clear_category)
        action_group.add_action(action)
        app.set_accels_for_action("editor.clear-category", ["<Shift>Delete"])

        action = Gio.SimpleAction.new("delete-note")
        action.connect("activate", self.__on_delete_note)
        action_group.add_action(action)

        action = Gio.SimpleAction.new("increase-line-length")
        action.connect("activate", self.__on_increase_line_length)
        action_group.add_action(action)
        app.set_accels_for_action("editor.increase-line-length", ["<Control>Up"])

        action = Gio.SimpleAction.new("decrease-line-length")
        action.connect("activate", self.__on_decrease_line_length)
        action_group.add_action(action)
        app.set_accels_for_action("editor.decrease-line-length", ["<Control>Down"])

        action = Gio.SimpleAction.new("increase-line-length")
        action.connect("activate", self.__on_increase_line_length)
        action_group.add_action(action)
        app.set_accels_for_action("editor.increase-line-length", ["<Control>Up"])

        action = Gio.SimpleAction.new("decrease-line-length")
        action.connect("activate", self.__on_decrease_line_length)
        action_group.add_action(action)
        app.set_accels_for_action("editor.decrease-line-length", ["<Control>Down"])

        action = Gio.SimpleAction.new("increase-font-size")
        action.connect("activate", self.__on_increase_font_size)
        action_group.add_action(action)
        app.set_accels_for_action("editor.increase-font-size", ["<Control>plus", "<Control>equal"])

        action = Gio.SimpleAction.new("decrease-font-size")
        action.connect("activate", self.__on_decrease_font_size)
        action_group.add_action(action)
        app.set_accels_for_action(
            "editor.decrease-font-size", ["<Control>minus", "<Control>underscore"]
        )

        action = Gio.SimpleAction.new("reset-font-size")
        action.connect("activate", self.__on_reset_font_size)
        action_group.add_action(action)
        app.set_accels_for_action("editor.reset-font-size", ["<Control>0"])

        app.get_active_window().insert_action_group("font-size-selector", action_group)
        self.__action_group = action_group

        self.__action_group = action_group
        app.get_active_window().insert_action_group("editor", action_group)

    def __enable_actions(self, enabled: bool) -> None:
        """Toggle whether editor actions are enabled.

        :param bool enabled: New value
        """
        actions = self.__action_group.list_actions()
        for action in actions:
            self.__action_group.lookup_action(action).set_enabled(enabled)
        # Disable specific actions for read-only
        if enabled and self.__note is not None and self.__note.read_only:
            self.__update_readonly_actions()

    def __on_insert_text(
        self, _buffer: GtkSource.Buffer, location: Gtk.TextIter, char: str, length: int
    ) -> None:
        if self.__updating_from_remote:
            return

    def __on_checkbox_toggled(self, _obj: GObject.Object, line: int, new_value: bool) -> None:
        buffer = self._sourceview.get_buffer()

        def get_iter_inside_checkbox(line):
            (success, line_start) = buffer.get_iter_at_line(line)
            if not success:
                return None

            line_end = line_start.copy()
            line_end.forward_to_line_end()
            match = line_start.forward_search("[", Gtk.TextSearchFlags.VISIBLE_ONLY, line_end)
            if match is None:
                logging.warn(f"Couldn't find checkbox on line {line}")
                return None

            (_, match_end) = match
            return match_end

        match_end = get_iter_inside_checkbox(line)
        if match_end is None:
            return

        buffer.insert(match_end, "x" if new_value else " ")

        match_end = get_iter_inside_checkbox(line)
        if match_end is None:
            return
        match_end.forward_char()
        delete_end = match_end.copy()
        delete_end.forward_char()
        buffer.delete(match_end, delete_end)

    def __on_web_view_loaded(self, _obj: GObject.Object) -> None:
        # Attempt to reduce time spent with blank view visible
        if not self._render_view_added:
            self._render_view.show()
            self._render_edit_stack.add_child(self._render_view)
            self._render_view_added = True
        self._render_edit_button_stack.set_visible_child(self._edit_button)
        self._render_edit_stack.set_visible_child(self._render_view)

    def __on_enter_search(self, _action: Gio.SimpleAction, _param: GLib.Variant) -> None:
        self.__enter_search(False)

    def __on_search_resumed(self, _object: GObject.Object) -> None:
        self.__enter_search(True)

    def __on_title_renamed(self, _obj: GObject.Object, new_title: str) -> None:
        if self.__note.title != new_title:
            self.__note.title = new_title
            if self.__note.title_is_top_line:
                self.__note.title_is_top_line = False
            self.__note.flag_changed()
            # Always called on UI thread
            self.emit("note-modified", self.__note)
        self._stack.set_visible_child(self._main_header_bar)
        self._sourceview.grab_focus()

    def __on_rename_cancelled(self, _obj: GObject.Object) -> None:
        self._stack.set_visible_child(self._main_header_bar)
        self._sourceview.grab_focus()

    def __on_toggle_render(self, _action: Gio.SimpleAction, _param: GLib.Variant) -> None:
        self.__toggle_render()

    def __on_cancel(self, _action: Gio.SimpleAction, _param: GLib.Variant) -> None:
        self.cancel()

    def __on_clear_category(self, _action: Gio.SimpleAction, _param: GLib.Variant) -> None:
        if not self._stack.get_visible():
            return
        if self._stack.get_visible_child() == self._category_header_bar:
            self._category_header_bar.clear_and_apply()

    def __on_delete_note(self, _action: Gio.SimpleAction, _param: GLib.Variant) -> None:
        self.emit("note-deleted", self.__note)

    def __on_line_length_changed(self, _settings: Gio.Settings, _key: str) -> None:
        length = iotas.config_manager.get_line_length()
        logging.debug(f"Line length now {length}px")
        self.__refresh_line_length_from_setting()

    def __on_increase_line_length(self, _action: Gio.SimpleAction, _param: GLib.Variant) -> None:
        length = iotas.config_manager.get_line_length() + self.LINE_LENGTH_STEP
        if length < self.get_width():
            iotas.config_manager.set_line_length(length)
            self.__notify_line_length_change(length)

    def __on_decrease_line_length(self, _action: Gio.SimpleAction, _param: GLib.Variant) -> None:
        length = iotas.config_manager.get_line_length() - self.LINE_LENGTH_STEP
        if length >= self.LINE_LENGTH_STEP:
            iotas.config_manager.set_line_length(length)
            self.__notify_line_length_change(length)

    def __on_font_family_changed(self, _settings: Gio.Settings, _key: str) -> None:
        self.__load_font_family_from_setting()

    def __notify_line_length_change(self, length: int) -> None:
        # Translators: Description, notification, {0} is a number
        msg = _("Line length now {0}px").format(length)
        self.__notify_setting_change(msg)

    def __notify_font_size(self) -> None:
        size = iotas.config_manager.get_font_size()
        # Translators: Description, notification, {0} is a number
        msg = _("Font size now {0}pt").format(size)
        self.__notify_setting_change(msg)

    def __notify_setting_change(self, msg: str) -> None:
        self._timed_notification.show(
            msg,
            self.SETTING_CHANGE_NOTIFICATION_DURATION,
        )

    def __on_note_update_from_sync(
        self,
        _obj: GObject.Object,
        _value: GObject.ParamSpec,
    ) -> None:
        self.__update_title()

    def __on_dark_style_updated(
        self,
        _obj: GObject.Object,
        _value: GObject.ParamSpec,
    ) -> None:
        self.__update_scheme_and_dark_style()

    def __on_increase_font_size(
        self,
        _obj: GObject.Object,
        _value: GObject.ParamSpec,
    ) -> None:
        if self.__font_size_selector.increase():
            self.__notify_font_size()

    def __on_decrease_font_size(
        self,
        _obj: GObject.Object,
        _value: GObject.ParamSpec,
    ) -> None:
        if self.__font_size_selector.decrease():
            self.__notify_font_size()

    def __on_reset_font_size(
        self,
        _obj: GObject.Object,
        _value: GObject.ParamSpec,
    ) -> None:
        self.__font_size_selector.reset()
        self.__notify_font_size()

    def __init_webkit(self) -> None:
        # Lazy import module in an attempt to reduce startup performance hit on devices with
        # render view disabled
        from iotas.markdown_render_view import MarkdownRenderView

        self._render_view = MarkdownRenderView()
        self._render_view.connect("checkbox-toggled", self.__on_checkbox_toggled)
        self._render_view.connect("loaded", self.__on_web_view_loaded)
        self._render_view.setup()

        # Allow using the mouse back button to return to index, typically button #8
        def callback(gesture: Gtk.GestureClick, _n_press: int, _x: float, _y: float) -> None:
            if gesture.get_current_button() == 8:
                self.cancel()

        add_mouse_button_accel(self._render_view, callback)

    def __setup_note_signals(self) -> None:
        self.__current_note_handlers = []

        handler_id = self.__note.connect("notify::dirty", self.__on_note_update_from_sync)
        self.__current_note_handlers.append(handler_id)
        handler_id = self.__note.connect("notify::title", self.__on_note_update_from_sync)
        self.__current_note_handlers.append(handler_id)

        handler_id = self.__note.connect("remote-content-update", self.__update_content_from_remote)
        self.__current_note_handlers.append(handler_id)

    def __get_content(self) -> None:
        buffer = self._sourceview.get_buffer()
        (start, end) = buffer.get_bounds()
        return buffer.get_text(start, end, True)

    def __buffer_changed(self, _buffer: GtkSource.Buffer) -> None:
        if self.__updating_from_remote:
            return

        self.__note.content = self.__get_content()
        if self.__note.title_is_top_line:
            self.__note.update_title_from_top_line()
        self.__note.flag_changed()

        GLib.idle_add(self.emit, "note-modified", self.__note)

    def __update_title(self) -> None:
        title = self.__note.title
        if self.__sync_authenticated and self.__note.dirty and title != "":
            title = f"•  {title}"
        self._title_button.set_label(title)
        self._title_button.get_child().props.ellipsize = Pango.EllipsizeMode.END

    def __update_content_from_remote(self, note: Note) -> None:
        if self.__note and not self.__note.dirty:
            self.set_sensitive(False)
            self.__updating_from_remote = True
            editor_scroll_value = self._editor_scrolledwin.get_vadjustment().get_value()
            self._sourceview.get_buffer().set_text(self.__note.content)

            def delayed_editor_scroll_reset():
                self._editor_scrolledwin.get_vadjustment().set_value(editor_scroll_value)

            GLib.idle_add(delayed_editor_scroll_reset)
            if self._render_edit_stack.get_visible_child() != self._editor_scrolledwin:
                self._render_view.render_retaining_scroll(
                    self.__note.content, self.__note.read_only
                )
            self.__updating_from_remote = False
            self.set_sensitive(True)

    def __get_editor_scroll_position(self) -> None:
        adj = self._editor_scrolledwin.get_vadjustment()
        value = adj.get_value()
        upper = adj.get_upper()
        page_size = adj.get_page_size()
        if upper > page_size:
            return value / (upper - page_size)
        else:
            return 0

    def __set_editor_scroll_position(self, position: float) -> None:
        adj = self._editor_scrolledwin.get_vadjustment()
        upper = adj.get_upper()
        page_size = adj.get_page_size()
        adj.set_value((upper - page_size) * position)

    def __edit_category(self, _action: Gio.SimpleAction, _param: GLib.Variant) -> None:
        """Show the category editing."""
        if not self._stack.get_visible():
            self.show_headerbar()
        if self._stack.get_visible_child() == self._category_header_bar:
            return
        elif self._stack.get_visible_child() == self._search_header_bar:
            self.__exit_search()
        self._stack.set_visible_child(self._category_header_bar)
        self._category_header_bar.activate([self.__note])

    def __do_rename(self, _action: Gio.SimpleAction, _param: GLib.Variant) -> None:
        """Show the title rename entry."""
        if self.__note.read_only:
            return
        if not self._stack.get_visible():
            self.show_headerbar()
        if self._stack.get_visible_child() == self._rename_header_bar:
            return
        elif self._stack.get_visible_child() == self._search_header_bar:
            self.__exit_search()
        self._stack.set_visible_child(self._rename_header_bar)
        self._rename_header_bar.enter(self.__note.title)

    def __enter_search(self, resuming: bool = False) -> None:
        """Start searching within note."""
        self._search_header_bar.enter(resuming)

        if self._render_edit_stack.get_visible_child() != self._editor_scrolledwin:
            self.__toggle_render()

        if not self._stack.get_visible():
            self.show_headerbar()

        self._stack.set_visible_child(self._search_header_bar)

    def __exit_search(self) -> None:
        """Stop searching within note."""
        self._stack.set_visible_child(self._main_header_bar)
        self._sourceview.grab_focus()
        if self._search_header_bar.jump_back_on_hide:
            self._sourceview.scroll_to_insertion_point()
        self._search_header_bar.exit()

    def __toggle_render(self) -> None:
        """Toggle whether showing rendered view."""

        if not self.__markdown_render_enabled:
            return

        if self._render_edit_stack.get_visible_child() == self._editor_scrolledwin:
            if self._stack.get_visible_child() == self._search_header_bar:
                self.__exit_search()

            self._render_view.render(
                self.__note.content, self.__note.read_only, self.__get_editor_scroll_position()
            )
        else:
            self._render_edit_button_stack.set_visible_child(self._render_button)
            self.__set_editor_scroll_position(self._render_view.scroll_position)
            self._sourceview.set_visible(True)
            self._render_edit_stack.set_visible_child(self._editor_scrolledwin)
            if not iotas.config_manager.get_markdown_keep_webkit_process():
                self._render_view.terminate_web_process()
                # Reduce flash when next loading render view
                self._render_view.hide()
                self._render_edit_stack.remove(self._render_view)
                self._render_view_added = False
            self._sourceview.grab_focus()

    def __category_changed(self, _obj: CategoryHeaderBar) -> None:
        changeset = self._category_header_bar.take_changeset()
        if len(changeset) > 0:
            (note, old_category) = changeset[0]
            self.emit("category-changed", note, old_category)
        self._stack.set_visible_child(self._main_header_bar)
        self._sourceview.grab_focus()

    def __abort_category_change(self, _obj: CategoryHeaderBar) -> None:
        self._stack.set_visible_child(self._main_header_bar)
        self._sourceview.grab_focus()

    def __toggle_headerbar(self, _action: Gio.SimpleAction, _param: GLib.Variant) -> None:
        """Toggle the headerbar."""
        if self._stack.get_visible():
            self.headerbar_manually_hidden = True
            self.hide_headerbar(True)
        else:
            self.show_headerbar()

    def __update_readonly_actions(self):
        editable = not not self.__note.read_only
        for action in ("rename", "edit-category", "clear-category", "delete-note"):
            self.__action_group.lookup_action(action).set_enabled(editable)

    def __update_scheme_and_dark_style(self) -> None:
        """Sync. dark style change to editor style."""
        buffer = self._sourceview.get_buffer()
        if not buffer:
            return

        style_manager = Adw.StyleManager.get_default()
        style_scheme_manager = GtkSource.StyleSchemeManager.get_default()

        scheme_id = iotas.config_manager.get_editor_theme()
        scheme_id = f"{scheme_id}-dark" if style_manager.get_dark() else scheme_id
        scheme = style_scheme_manager.get_scheme(scheme_id)
        buffer.set_style_scheme(scheme)

    def __refresh_line_length_from_setting(self) -> None:
        length = iotas.config_manager.get_line_length()
        self._sourceview.set_property("maximum-width", length)
        self._sourceview.queue_resize()

    def __desktop_setting_changed(
        self, _sender_name: str, _signal_name: str, _parameters: str, data: GLib.Variant
    ) -> None:
        if _parameters != "SettingChanged":
            return
        (path, setting_name, value) = data
        if path == "org.gnome.desktop.interface" and setting_name in self.FONT_SETTING_KEYS:
            if value.strip() != "":
                font_description = Pango.font_description_from_string(value)
                self.__font_families[setting_name] = font_description.get_family()
                self.__push_font_updates()

    def __process_desktop_settings(self, variant: GLib.Variant) -> None:
        if variant.get_type_string() != "(a{sa{sv}})":
            return
        for v in variant:
            for key, value in v.items():
                if key == "org.gnome.desktop.interface":
                    for font_key in self.FONT_SETTING_KEYS:
                        if font_key in value:
                            font_description = Pango.font_description_from_string(value[font_key])
                            self.__font_families[font_key] = font_description.get_family()
        self.__push_font_updates()

    def __push_font_updates(self) -> None:
        font_setting = self.__fetch_editor_font_setting_name()
        if font_setting in self.__font_families:
            family = self.__font_families[font_setting]
            self._sourceview.update_font_family(family)

        if iotas.config_manager.get_markdown_render_enabled():
            font_setting = self.__fetch_render_font_setting_name()
            if font_setting in self.__font_families:
                family = self.__font_families[font_setting]
                self._render_view.update_font(family)

    def __fetch_editor_font_setting_name(self):
        return (
            "monospace-font-name"
            if iotas.config_manager.get_use_monospace_font()
            else "document-font-name"
        )

    def __fetch_render_font_setting_name(self):
        return (
            "monospace-font-name"
            if iotas.config_manager.get_markdown_use_monospace_font()
            else "document-font-name"
        )

    def __load_font_family_from_setting(self) -> None:
        if self.__dbus_proxy is None:
            return
        try:
            variant = self.__dbus_proxy.call_sync(
                method_name="ReadAll",
                parameters=GLib.Variant("(as)", ("org.gnome.desktop.*",)),
                flags=Gio.DBusCallFlags.NO_AUTO_START,
                timeout_msec=-1,
                cancellable=None,
            )
        except GLib.GError as e:
            logging.warning("Unable to access D-Bus FreeDesktop.org font family setting: %s", e)
            return
        self.__process_desktop_settings(variant)
        self.__push_font_updates()
