#!/usr/bin/env python3

"""Provide an application dock applet for the MATE panel

Create a Mate panel applet and handle events generated
by it

Note: Functionality for docked apps is provided in docked_app.py

      Function for the dock is provided in dock.py

"""

# Copyright (C) 1997-2003 Free Software Foundation, Inc.
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
# Author:
#     Robin Thompson

# do not change the value of this variable - it will be set during build
# according to the value of the --with-gtk3 option used with .configure
build_gtk2 = False

import gi

if build_gtk2:
    gi.require_version("Gtk", "2.0")
    gi.require_version("Wnck", "1.0")
else:
    gi.require_version("Gtk", "3.0")
    gi.require_version("Wnck", "3.0")

gi.require_version("MatePanelApplet", "4.0")

import os
import sys
sys.path.insert(1, '/usr/lib/python3.5/site-packages')

from gi.repository import Gtk
from gi.repository import MatePanelApplet
from gi.repository import Gdk
from gi.repository import Gio
from gi.repository import GObject
from gi.repository import Wnck

import xdg.DesktopEntry as DesktopEntry

import docked_app
import dock
from dock_win_list import DockWinList

from log_it import log_it as log_it


def applet_button_press(widget, event, the_dock):
    """Button press event for the applet

    Handle right button press events only

    Find the app that was right clicked and make a record of it

    Args:
        widget : the widget that was clicked
        event : the event args
        the_dock : the Dock object
    """

    # we don't get click events for the right mouse button presumably
    # because the panel hijacks them in order to produce the context menu
    # However, we do get button press event for the right mouse button,
    # so we can do what we need to do here ....
    if event.button == 3:
        # right click, so save the app that was clicked because
        # the_dock.app_with_mouse is going to be set to None when the
        # right click menu appears and we move the mouse over the menu to
        # select an option
        app = the_dock.get_app_at_mouse(event.x, event.y)
        the_dock.right_clicked_app = app

        # because the right click menu is about to be shown, we need to hide
        # the window list
        the_dock.hide_win_list()


def applet_button_release(widget, event, the_dock):
    """Button press event for the applet

    Handle left button release events only

    If the button is released over a non-running app, start the app

    If the button is released over a runnning app that isn't on the
    current workspace, change workspace

    If the button is released over a running app on the current workspace:
        if it is the active app minmize all of its windows
        Otherwise, restore them all

    Args:
        widget : the widget that registered the release event
        event : the event args
        the_dock : the Dock object

    """

    if event.button == 1:

        # hide the window list window
        the_dock.hide_win_list()

        app = the_dock.get_app_at_mouse(event.x, event.y)
        if app is not None:

            # TODO
            # move this code into docked_app.in ...

            # if the app is not running start the app
            # if the app is running and the shift key is being pressed, start
            # another instance of the app

            start_app = app.is_running() is False
            start_app = start_app | (event.state &
                                     Gdk.ModifierType.SHIFT_MASK) != 0
            if start_app:
                app.start_app()
            else:
                the_dock.minimize_or_restore_windows(app, event)

    # See https://bugs.launchpad.net/ubuntu-mate/+bug/1554128
    if event.button == 2:
        app = the_dock.get_app_at_mouse(event.x, event.y)
        if app is not None:
            the_dock.hide_win_list()
            app.start_app()


def applet_enter_notify(widget, event, the_dock):
    """Enter notify event for the applet

    Brighten the icon of the app which the mouse is currently over

    If another app is currently brightened, darken it to normal

    Set up the right click menu for the dock based on the app which
    the mouse is currently over

    Start the timer for showing app window lists

    Args:
        widget : the widget that registered the event i.e. the applet
        event : the event args
        the_dock : the Dock object
    """

    # get the app underneath the mouse cursor
    app = the_dock.get_app_at_mouse(event.x, event.y)

    # if an app is currently highlighted, de-highlight it
    if the_dock.app_with_mouse is not None:

        the_dock.app_with_mouse.has_mouse = False
        the_dock.app_with_mouse.queue_draw()
        the_dock.app_with_mouse = None

    # highlight the app under the mouse cursor
    if app is not None:
        app.has_mouse = True
        app.queue_draw()
        the_dock.app_with_mouse = app

        # set up the available options for the app
        the_dock.set_actions_for_app(app)

        the_dock.reset_win_list_timer()


def applet_leave_notify(widget, event, the_dock):
    """Leave notifiy event handle for the applet

    Unbrighten any brightened app icon

    Args:
        widget : the widget that registered the event i.e. the applet
        event : the event args
        the_dock : the Dock object
    """

    if the_dock.app_with_mouse is not None:
        the_dock.app_with_mouse.has_mouse = False
        the_dock.app_with_mouse.queue_draw()
        the_dock.app_with_mouse = None

    the_dock.stop_win_list_timer()


def applet_motion_notify(widget, event, the_dock):
    """Motion notify event for the applet

    If the docked app under the mouse cursor does not have its icon
    brightened and another app has a brightened icon then darken the other app
    # icon and reset the applet tooltip text

    Then, if the docked app under the mouse cursor does not have its icon
    brightened then brighten it and setup the applet right click menu

    Args:
        widget : the widget that registered the event i.e. the applet
        event : the event args
        the_dock : the Dock object
    """

    app = the_dock.get_app_at_mouse(event.x, event.y)

    if (the_dock.app_with_mouse is not None) and \
       (the_dock.app_with_mouse != app):
        the_dock.app_with_mouse.has_mouse = False
        the_dock.app_with_mouse.queue_draw()

        widget.queue_draw()

        # because a new app is highlighted reset the window list timer and hide
        # any currently open window list
        the_dock.hide_win_list()
        the_dock.reset_win_list_timer()

        if not build_gtk2:
            # set the drag and drop cursor - needs to be done here as well
            # as in begin-drag to ensure that the first time we do a drag the
            # app icon is set correctly
            widget.drag_source_set_icon_pixbuf(the_dock.app_with_mouse.app_pb)

    if (app is not None):

        # reset the window list timer
        the_dock.reset_win_list_timer()

        if app.has_mouse is False:
            app.has_mouse = True
            app.queue_draw()
            the_dock.app_with_mouse = app
            the_dock.set_actions_for_app(app)


def applet_change_orient(applet, orient, the_dock):
    """Handler for applet change orientation event

    Set the dock to the new orientation and re-show the applet

    Args:
        widget : the widget that registered the event i.e. the applet
        event : the event args
        the_dock : the Dock object
    """

    the_dock.set_new_orientation(orient)
    the_dock.applet.show_all()
    the_dock.show_or_hide_app_icons()


def applet_change_size(applet, size, the_dock):
    """Handler for the applet change size event

    Resize the icon and recalculate the minimize location of each app in the
    dock

    Args:
        widget : the widget that registered the event i.e. the applet
        event : the event args
        the_dock : the Dock object
    """

    for app in the_dock.app_list:
        the_dock.set_app_icon(app, size)


def applet_scroll_event (applet, event, the_dock):
    """ Handler for the scroll event

    Call the dock's  function to move forward/backward through the active app's
    windows

    """

    the_dock.do_window_scroll(event.direction, event.time)


def applet_drag_begin(applet, context, the_dock):
    """
        Handler for the drag-begin event

        Let the dock know we're dragging an icon.
        Redraw the icon of the app that's being dragged so that the user has
        visual feedback that the drag has started
        Set the drag cursor to the app icon
        Start a timer to monitor the mouse x,y and move the dragged app icon
        around the dock accordingly

    """

    # we can sometimes get surious applet-leave events just before a drag
    # commences. This causes app_with_mouse to be set to None. Therefore we
    # may need to identify the app under the mouse outselves...

    if the_dock.app_with_mouse is None:
        the_dock.app_with_mouse = the_dock.get_app_under_mouse()

    if the_dock.app_with_mouse is not None:
        the_dock.app_with_mouse.set_dragee(True)
        the_dock.app_with_mouse.queue_draw()
        applet.drag_source_set_icon_pixbuf(the_dock.app_with_mouse.app_pb)

        the_dock.start_drag_motion_timer(the_dock.app_with_mouse)

def applet_drag_data_get(widget, drag_context, data, info, time):
    """
        Handler the for drag-data-get event

        Set some dummy text as data for the drag and drop
    """

    data.set_text("", -1)


def applet_drag_drop(widget, context, x, y, time, the_dock):
    """
        Handler for the drag-drop event

        The drag drop is over so:
            Call Gtk.drag-finish and indicate the drag and drop completed ok
            Let the dock know that the drag and drop has finished and redraw
            the dragged app's icon
            Stop the timer that monitors the mouse position
    """

    Gtk.drag_finish(context, True, False, time)

    the_dock.stop_drag_motion_timer()

    app = the_dock.get_dragee()
    if app is not None:
        app.set_dragee(False)
        app.queue_draw()


def applet_drag_end (widget, context, the_dock):
    """
    Handler for the drag-end event

    This will be triggered when e.g. the use drags an icon off the panel and
    releases the mouse button ....
    Let the dock know that the drag and drop has finished and redraw the
    dragged app's icon
    Stop the timer that monitors the mouse position
    """

    the_dock.stop_drag_motion_timer()

    app = the_dock.get_dragee()
    if app is not None:
        app.set_dragee(False)
        app.queue_draw()


def applet_fill(applet):
    """
    Create the applet

    Register the events that we're interested in getting events for and
    connect event handlers for them

    Create a dock and add it V/HBox to the applet


    Args:
        applet : the applet
    """

    os.chdir(os.path.expanduser("~"))
    applet.set_events(applet.get_events() | Gdk.EventMask.BUTTON_PRESS_MASK \
                                          | Gdk.EventMask.BUTTON_RELEASE_MASK \
                                          | Gdk.EventMask.POINTER_MOTION_MASK \
                                          | Gdk.EventMask.KEY_PRESS_MASK \
                                          | Gdk.EventMask.KEY_RELEASE_MASK \
                                          | Gdk.EventMask.SCROLL_MASK \
                                          | Gdk.EventMask.STRUCTURE_MASK)

                                          #| Gdk.EventMask.BUTTON1_MOTION_MASK)

    the_dock = dock.Dock(applet)
    the_dock.setup_dock()

    applet.add(the_dock.box)
    applet.show_all()

    applet.connect("enter-notify-event", applet_enter_notify, the_dock)
    applet.connect("leave-notify-event", applet_leave_notify, the_dock)
    applet.connect("motion-notify-event", applet_motion_notify, the_dock)
    applet.connect("button-press-event", applet_button_press, the_dock)
    applet.connect("button-release-event", applet_button_release, the_dock)
    applet.connect("change-orient", applet_change_orient, the_dock)
    applet.connect("change-size", applet_change_size, the_dock)
    applet.connect("scroll-event", applet_scroll_event, the_dock)

    if not build_gtk2:
        # set up drag and drop - gtk3 only
        # NOTE: drag-motion events never seem to trigger on applets, which
        # makes it difficult to tell where the mouse pointer is.....
        # To get around this, dock.py now contains a timer to monitor the
        # mouse x.y during drang and drops, but if drag-motion events
        # ever start working, the code from the dock.py timer can be moved
        # to drag-motion event handler
        applet.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, None,
                               Gdk.DragAction.MOVE)
        applet.drag_dest_set(Gtk.DestDefaults.ALL, [], Gdk.DragAction.MOVE)

        applet.drag_dest_add_text_targets()
        applet.drag_source_add_text_targets()
        applet.connect_after("drag-begin", applet_drag_begin, the_dock)
        applet.connect("drag-data-get", applet_drag_data_get)
        applet.connect("drag-drop", applet_drag_drop, the_dock)
        applet.connect("drag-end", applet_drag_end, the_dock)

    applet.set_background_widget(applet)  # hack for panel transparency


def applet_factory(applet, iid, data):
    """Factory routine called when an applet needs to be created

    Create a dock applet if necessary

    Args:
        applet : the applet
        iid    : the id of the applet that needs to be created
    Returns:
        True if we created a dock applet, False otherwise
    """

    if iid != "DockApplet":
        return False

    applet_fill(applet)

    return True


MatePanelApplet.Applet.factory_main("DockAppletFactory", True,
                                    MatePanelApplet.Applet.__gtype__,
                                    applet_factory, None)

def main():
    """Main function.

    Debugging code can go here
    """
    pass

if __name__ == "__main__":
    main()

#timer object to check the mouse x and y as a substitute for drag-motion
#need to convert root coords to applet window coords - use applet window.get_origin to get its root coords
