#!/usr/pkg/bin/python2.7
# -*- coding: utf-8 -*-

# Copyright (C) 2009 The Tegaki project contributors
#
# 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.

# Contributors to this file:
# - Mathieu Blondel

import base64
from optparse import OptionParser

import gtk
from gtk import gdk

from tegakigtk.recognizer import SmartRecognizerWidget, SimpleRecognizerWidget
from tegakigtk.fakekey import send_unicode

VERSION = '0.3.1.2'

ICON = \
"""
iVBORw0KGgoAAAANSUhEUgAAABoAAAAYCAYAAADkgu3FAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz
AAAFkQAABZEBAPaFVQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAZESURB
VEiJldV7UFT3FcDx7+9yd9ldHouCAj4W5JXqFIJS8DGK5iENiqGGTKmOmhSNYlJnOmOsNm2n/aOd
vsbW1rZDk2jtGDs1tUESbcCM1rci5AEqCeoiwiICwrK4LO6De/qHaEmCSXtmztw/7r3nc37nPn5K
RBgr8ovLlwFbAQ1oA47PmGyaiRFcqJTq9vv9y+Pj4ze53e5DFRUV9WMWGRVqLCi/uHwKcHV6erJl
wZxs3J47XG5qxu/pxNkz3DYlRgZjIs2xro6bOxxTEstcLlfGwYMHx+74S6BXIyNsL1T89if0DuqE
DIPOlou4u2+Qkj6D6uoaPrnqpOcOEmHm8mBA9oL658mqCuf/DOUXlzsA56b1K/TJaTmEhg0MA4aG
fBx764/kLHwGswrR7mwgO2cuZ87Xc7q2Ae+gD6AReAvYdbKqwjW6rj4G/nzCxFh9/tw53H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WzZsoVYq4c3fr2W7FlfQ3VXI901dHpTuHjGSX1bHz/ed/NEyOA1oBe4rgMl83IzMZk+/9vTdf0B
AlBTU8MPXvkeZSufYvH0HGYm+aDpZTwqj8Y6RevNs7yyr73NdTu4E7gEDABNItKvA5nZX834HDI6
vF4vm1/eSu0lF9l5hWROicJ5fTwD3a2cq4vlyLkj/PWE19Pb73sTqAQCwBXAJSPbgw70V1WfJHac
nVlZj2C1hH8KMQyD3bt303/HR/w4K323rvPOCeFGWweVJ8IwRyXxUUsYAZr3ge8kcGPk2wmMrqMW
PL1hjhjGe0rTIjWlmDJpIhmpDjJSHGSkOkhPmUoo6MflcuF2u/H5fJ9q5O2aU5yubXBfPHd4C7BP
RO6ONRUlIlhsUTkTJqXmR8cmpFoj7Glmiy1NN5mTQYUBJEyMvYenOkhLnkyKI5EImwWvd5C1m39J
V6fr8AfHD/xURM4/bPxKRO6/bROBmJG0m8KtUfFTM5KixyemWyOiU0fwpPt43Hg7/kCQgTuDgY/r
jmzsvdX6bxG5/oXQmCeUsgD2kRyFP5JsH5+QZomITgPoamt+1+Vs+Bg4KiLB/xv6Ejxm1NEHNItI
zxfd+x8njL5ng4fNdwAAAABJRU5ErkJggg==
"""

class TegakiRecognize(object):

    def __init__(self, options):
        self._position = None
        self._hide = options.hide
        self._simple = options.simple
        self._dont_quit = options.dont_quit
        self._init_pixbuf()
        self._create_window()
        self._init_status_icon()
        self._size = None

    def _init_pixbuf(self):
        data = base64.b64decode(ICON.replace("\n", ""))
        loader = gdk.PixbufLoader()
        loader.write(data)
        loader.close()
        self._pixbuf = loader.get_pixbuf()

    def _init_status_icon(self):
        self._status_icon = gtk.StatusIcon()
        self._status_icon.set_from_pixbuf(self._pixbuf)

        self._status_icon.connect("activate", self._on_activate)
        self._status_icon.connect("popup-menu", self._on_popup)

        self._status_icon.set_visible(True)

    def _create_window(self):
        self._window = gtk.Window()
        self._window.set_icon(self._pixbuf)
        self._window.set_position(gtk.WIN_POS_CENTER)
        self._window.set_title("Tegaki")
        self._window.set_accept_focus(False)

        if self._simple:
            rw = SimpleRecognizerWidget()
        else:
            rw = SmartRecognizerWidget()
        self._window.add(rw)

        rw.connect("commit-string", self._on_commit)
        self._window.connect("delete-event", self._on_delete_event)

        # add quit button if the option "don't quit" is passed
        if self._dont_quit:
            vbox = rw.get_toolbar_vbox()
            button = gtk.Button()
            image = gtk.image_new_from_stock(gtk.STOCK_QUIT, 
                                             gtk.ICON_SIZE_BUTTON)
            button.set_image(image)
            button.connect("clicked", lambda x: gtk.main_quit())
            vbox.pack_start(button, expand=False)

        if not self._hide:
            self._window.show_all()

    def _save_window_position(self):
        self._size = self._window.get_size()
        self._position = self._window.get_position()

    def _load_window_position(self):
        if self._size and self._position:
            self._window.resize(*self._size)
            self._window.move(*self._position)

    def _on_delete_event(self, widget, event):
        if self._dont_quit:
            self._save_window_position()
            self._window.hide()
            return True # don't propagate the event
        else:
            gtk.main_quit()

    def _on_activate(self, widget):
        if self._window.get_property("visible"):
            self._save_window_position()
            self._window.hide()
        else:
            self._window.show_all()
            self._load_window_position()

    def _on_popup(self, widget, button, time):
        menu = gtk.Menu()
        quit = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        quit.connect("activate", lambda x: gtk.main_quit())
        menu.append(quit)
        menu.show_all()
        menu.popup(None, None, None, button, time)

    def _on_commit(self, widget, string):
        if not send_unicode(unicode(string, "utf8")):
            # save to clipboard if send_unicode isn't supported
            clipboard = gtk.Clipboard()
            clipboard.set_text(string)

    def run(self):
        gtk.main()

parser = OptionParser(version="%prog " + VERSION)
parser.add_option("", "--hide",
                  action="store_true", dest="hide", default=False,
                  help="don't show window on startup")
parser.add_option("-s", "--simple",
                  action="store_true", dest="simple", default=False,
                  help="use simple recognizer instead of the smart one")
parser.add_option("-d", "--dont-quit",
                  action="store_true", dest="dont_quit", default=False,
                  help="don't quit when main window is closed")

(options, args) = parser.parse_args()

TegakiRecognize(options).run()
