# vim:set et sts=4 sw=4 fileencoding=utf-8:
#
# ibus-hangul - The Hangul Engine For IBus
#
# Copyright (c) 2009-2011 Choe Hwanjin <choe.hwanjin@gmail.com>
#
# 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.


from gi.repository import Gtk
from gi.repository import Gdk
import gettext

import config

_ = lambda a : gettext.dgettext(config.gettext_package, a)
N_ = lambda a: a

class KeyCaptureDialog ():
    def __init__ (self, title, parent, keyboard_104_keys = None):
        self.__key_str = ''
        self.__dialog = Gtk.MessageDialog(transient_for = parent)
        buttons = (_("_Cancel"), Gtk.ResponseType.CANCEL,
                        _("_Ok"), Gtk.ResponseType.OK)
        self.__dialog.add_buttons(*buttons)
        self.__dialog.set_markup(_("Press any key which you want to use as hotkey. \n"
                "The key you pressed is displayed below.\n"
                "If you want to use it, click \"Ok\" or click \"Cancel\""))

        self.__dialog.format_secondary_markup(self.__key_str)
        self.__dialog.connect("key-press-event", self.on_keypress, keyboard_104_keys)

    def destroy(self):
        self.__dialog.destroy()

    def run(self):
        return self.__dialog.run()

    def set_markup(self, text):
        self.__dialog.set_markup(text)

    def get_key_string(self):
        return self.__key_str

    def on_keypress(self, widget, event, data = None):
        # enter, tab, arrow [ up, left, right, down]
        if event.hardware_keycode in [36, 111, 113, 114, 116]:
            return

        self.__key_str = ""
        if event.state & Gdk.ModifierType.CONTROL_MASK :
            self.__key_str += "Control+"
        if event.state & Gdk.ModifierType.MOD1_MASK :
            self.__key_str += "Alt+"
        if event.state & Gdk.ModifierType.SHIFT_MASK :
            self.__key_str += "Shift+"

        if data:#104 keyboard True
            key_name = Gdk.keyval_name(event.keyval)
            if key_name == 'Alt_R':
                key_name = 'Hangul'
            elif key_name == 'Control_R':
                key_name = 'Hangul_Hanja'
            self.__key_str += key_name
        else:
            self.__key_str += Gdk.keyval_name(event.keyval)
            
        self.__dialog.format_secondary_markup('<span size="large" weight="bold">%s</span>' % self.__key_str)
