#!/usr/bin/env python3
#
# Copyright (c) 2024 Stormux
# Copyright (c) 2010-2012 The Orca Team
# Copyright (c) 2012 Igalia, S.L.
# Copyright (c) 2005-2010 Sun Microsystems Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., Franklin Street, Fifth Floor,
# Boston MA  02110-1301 USA.
#
# Fork of Orca Screen Reader (GNOME)
# Original source: https://gitlab.gnome.org/GNOME/orca

"""Custom script for SeaMonkey."""

__id__        = "$Id$"
__version__   = "$Revision$"
__date__      = "$Date$"
__copyright__ = "Copyright (c) 2016 Igalia, S.L."
__license__   = "LGPL"

import gi
gi.require_version("Atspi", "2.0")
from gi.repository import Atspi

from cthulhu import cmdnames
from cthulhu import debug
from cthulhu import input_event
from cthulhu import cthulhu_state
from cthulhu.ax_object import AXObject
from cthulhu.scripts.toolkits import Gecko


class Script(Gecko.Script):

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

    def setupInputEventHandlers(self):
        super().setupInputEventHandlers()

        self.inputEventHandlers["togglePresentationModeHandler"] = \
            input_event.InputEventHandler(
                Script.togglePresentationMode,
                cmdnames.TOGGLE_PRESENTATION_MODE)

        self.inputEventHandlers["enableStickyFocusModeHandler"] = \
            input_event.InputEventHandler(
                Script.enableStickyFocusMode,
                cmdnames.SET_FOCUS_MODE_STICKY)

        self.inputEventHandlers["enableStickyBrowseModeHandler"] = \
            input_event.InputEventHandler(
                Script.enableStickyBrowseMode,
                cmdnames.SET_BROWSE_MODE_STICKY)

    def onBusyChanged(self, event):
        """Callback for object:state-changed:busy accessibility events."""

        if self.utilities.isContentEditableWithEmbeddedObjects(event.source):
            msg = "SEAMONKEY: Ignoring, event source is content editable"
            debug.printMessage(debug.LEVEL_INFO, msg, True)
            return

        table = self.utilities.getTable(cthulhu_state.locusOfFocus)
        if table and not self.utilities.isTextDocumentTable(table):
            tokens = ["SEAMONKEY: Ignoring, locusOfFocus is", cthulhu_state.locusOfFocus]
            debug.printTokens(debug.LEVEL_INFO, tokens, True)
            return

        super().onBusyChanged(event)

    def onFocus(self, event):
        """Callback for focus: accessibility events."""

        # We should get proper state-changed events for these.
        if self.utilities.inDocumentContent(event.source):
            return

        focusRole = AXObject.get_role(cthulhu_state.locusOfFocus)
        if focusRole != Atspi.Role.ENTRY or not self.utilities.inDocumentContent():
            super().onFocus(event)
            return

        if AXObject.get_role(event.source) == Atspi.Role.MENU:
            msg = "SEAMONKEY: Non-document menu claimed focus from document entry"
            debug.printMessage(debug.LEVEL_INFO, msg, True)

            if self.utilities.lastInputEventWasPrintableKey():
                msg = "SEAMONKEY: Ignoring, believed to be result of printable input"
                debug.printMessage(debug.LEVEL_INFO, msg, True)
                return

        super().onFocus(event)

    def useFocusMode(self, obj, prevObj=None):
        if self.utilities.isEditableMessage(obj):
            tokens = ["SEAMONKEY: Using focus mode for editable message", obj]
            debug.printTokens(debug.LEVEL_INFO, tokens, True)
            return True

        tokens = ["SEAMONKEY:", obj, "is not an editable message."]
        debug.printTokens(debug.LEVEL_INFO, tokens, True)
        return super().useFocusMode(obj, prevObj)

    def enableStickyBrowseMode(self, inputEvent, forceMessage=False):
        if self.utilities.isEditableMessage(cthulhu_state.locusOfFocus):
            return

        super().enableStickyBrowseMode(inputEvent, forceMessage)

    def enableStickyFocusMode(self, inputEvent, forceMessage=False):
        if self.utilities.isEditableMessage(cthulhu_state.locusOfFocus):
            return

        super().enableStickyFocusMode(inputEvent, forceMessage)

    def togglePresentationMode(self, inputEvent, documentFrame=None):
        if self._inFocusMode \
           and self.utilities.isEditableMessage(cthulhu_state.locusOfFocus):
            return

        super().togglePresentationMode(inputEvent, documentFrame)

    def useStructuralNavigationModel(self, debugOutput=True):
        if self.utilities.isEditableMessage(cthulhu_state.locusOfFocus):
            return False

        return super().useStructuralNavigationModel(debugOutput)
