#!/usr/bin/python

# LADITools - Linux Audio Desktop Integration Tools
# wmladi - Window maker dockapp for jackdbus
# Copyright (C) 2012 Alessio Treglia <quadrispro@ubuntu.com>
# Copyright (C) 2007-2010, Marc-Olivier Barre <marco@marcochapeau.org>
# Copyright (C) 2007-2009, Nedko Arnaudov <nedko@arnaudov.name>
#
# 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/>.

import sys
import os
import signal
from wmdocklib import wmoo, pywmhelpers
import time
import argparse
import gettext
from gi.repository import Gdk

sig_handler = signal.getsignal(signal.SIGTERM)
signal.signal(signal.SIGINT, sig_handler)

from laditools import _gettext_domain
gettext.install(_gettext_domain)

from laditools import get_version_string
from laditools import LadiConfiguration
from laditools import LadiApp

from gi.repository import Gtk
from gi.repository import GObject

from laditools.gtk import LadiMenu

# Default configuration
autostart_default = 0
debug = False

class wmladi (wmoo.Application, LadiMenu, LadiApp):

    _appname = 'wmladi'
    _appname_long = _("LADI WindowMaker dockapp")
    _appid = 'org.linuxaudio.ladi.wmlami'

    # Default configuration
    _default_config = {
        'autostart' : False,
    }

    def on_about(self, *args):
        LadiMenu.on_about(self, version=get_version_string())

    def quit(self, *args):
        Gtk.main_quit()

    def __init__ (self):
        # Handle the configuration
        self.global_config = LadiConfiguration (self.appname,
                                                self._default_config)
        self.config_dict = self.global_config.get_config_section (self.appname)
        autostart = bool(eval(self.config_dict['autostart']))
        wmoo.Application.__init__ (
            self,
            #background = os.path.dirname(sys.argv[0]) + os.sep + "wmjackctl.xpm",
            margin = 2,
            debug = False)

        LadiMenu.__init__(self, autostart)
        LadiApp.__init__(self)
        self.connect_signals_quit()

        self.addCallback (self.on_button_release, 'buttonrelease', area=(0,0,64,64))

        self.lines = []
        for i in range (6):
            self.lines.append ("")
        self.clear ()
        self.started = False

    def set_starting_status (self):
        self.set_line (0, "JACK")
        self.set_line (1, "Starting")
        self.clear_line (2)
        self.clear_line (3)
        self.clear_line (4)
        self.clear_line (5)

    def on_button_release (self, event):
        if event['button'] == 3:
            self.menu_activate ()

    def set_line (self, line, text):
        self.lines[line] = text
        while len (self.lines[line]) < 9:
            self.lines[line] += ' '

    def clear_line (self, line):
        self.set_line (line, "")

    def clear (self):
        for i in range (6):
            self.clear_line (i)

    def update (self):
        try:
            if self.jack_is_started():
                self.started = True

                line0 = "JACK"
                if self.jack_is_realtime():
                    line0 += " RT"
                else:
                    line0 += "   "

                if self.a2j_is_available():
                    try:
                        if self.a2j_is_started():
                            line0 += ' A'
                        else:
                            line0 += ' a'
                    except:
                        pass

                self.set_line(0, line0)
                self.set_line(1, "started")
                self.set_line(2, "%.3f %%" % self.jack_get_load())

                xruns = self.jack_get_xruns()
                if xruns == 0:
                    self.set_line(3, "no xruns")
                elif xruns == 1:
                    self.set_line(3, "1 xrun")
                elif xruns > 999:
                    self.set_line(3, "lot xruns")
                else:
                    self.set_line(3, "%s xruns" % xruns)

                rate = self.jack_get_sample_rate()
                if rate % 1000.0 == 0:
                    self.set_line(4, "%.0f Khz" % (rate / 1000.0))
                else:
                    self.set_line(4, "%.1f Khz" % (rate / 1000.0))

                self.set_line(5, "%.1f ms" % self.jack_get_latency())
            else:
                self.set_line(0, "JACK")
                self.set_line(1, "stopped")
                if self.started:
                    self.clear_line(2)
                    self.clear_line(3)
                    self.clear_line(4)
                    self.clear_line(5)
                    self.started = False
            self.clear_diagnose_text()
        except Exception, e:
            self.set_diagnose_text(repr(e))
            if debug:
                print repr (e)
            self.set_line(0, "JACK")
            self.set_line(1, "is sick")
            self.clear_line(2)
            self.clear_line(3)
            self.clear_line(4)
            self.clear_line(5)
            self.clear_jack_proxies()

        self.put_lines (self.lines)
        wmoo.Application.update (self)
        LadiMenu.update(self)

    def put_lines (self, lines):
        x = 3
        y = 2
        for line in lines:
            self.putString (x, y, line)
            y += 9

    def do_dockapp (self, user_data = None):
        """this is called from event loop.  events are examined and if a
        callback has been registered, it is called, passing it the event as
        argument.
        """
        event = pywmhelpers.getEvent ()
        while not event is None:
            if event['type'] == 'destroynotify':
                sys.exit (0)

            for evtype, key, area, callback in self._events:
                if evtype is not None and evtype != event['type']: continue
                if key is not None and key != event['button']: continue
                if area is not None:
                    if not area[0] <= event['x'] <= area[2]: continue
                    if not area[1] <= event['y'] <= area[3]: continue

                callback (event)
                
            event = pywmhelpers.getEvent ()
        self.redraw ()
        #print "tick"
        return True

    def run_sleep (self):
        self.go = True
        while self.go:
            while Gtk.events_pending ():
                Gtk.main_iteration ()
            self.do_dockapp ()
            while Gtk.events_pending ():
                Gtk.main_iteration ()
            time.sleep (self._sleep)

    def run_gtk (self):
        #print self._sleep
        GObject.timeout_add (int(self._sleep * 1000), self.do_dockapp, None)
        Gtk.main ()

    def run (self):
        self.run_gtk ()
        self.global_config.set_config_section (self.appname, self.config_dict)
        self.global_config.save ()

    def position_menu(self, menu, data):
        _, x, y, _ = Gdk.Display.get_default().get_pointer()
        return x, y, True

    def menu_activate(self):
        menu = self.create_menu()
        try:
            menu.popup(parent_menu_shell=None,
                       parent_menu_item=None,
                       func=self.position_menu,
                       data=None,
                       button=3,
                       activate_time=0)
        except Exception, e:
            print repr(e)
            pass

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=_('Window maker dockapp for jackdbus'),
                                     epilog=_('This program is part of the LADITools suite.'))
    parser.add_argument('--version', action='version', version="%(prog)s " + get_version_string())

    parser.parse_args()
    wmladi().run ()
    sys.exit(0)
