""" ValueMonitor.py

"""
__copyright__ = "Copyright (c) 2002-2005 Free Software Foundation, Inc."
__license__ = """
Straw 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.

Straw 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., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA. """


import pygtk
pygtk.require('2.0')
import gobject
import error

class ValueMonitor(object):
    def __init__(self, current, timeout, notify, data):
        self._previous_value = current
        self._value = None
        self._timeout = timeout
        self._notify = notify
        self._data = data
        self._connected = True
        self._value_changed = False

    def get_value(self):
        return self._value

    def set_value(self, value):
        if self._connected:
            if value != self._value:
                self._value_changed = True
                gobject.timeout_add(self._timeout, self._check_value)
            self._value = value

    value = property(get_value, set_value)

    def connect(self):
        self._connected = True

    def disconnect(self):
        self.flush()
        self._connected = False

    def flush(self):
        self._check_value()

    def _check_value(self):
        if (self._connected and self._value_changed and self.value != self._previous_value):
            self._notify(self.value, self._data)
            self._previous_value = self.value

def create_for_gtkentry(widget, timeout, notify):
    vm = ValueMonitor(widget.get_text(), timeout, notify, widget)
    def changed(object, *data):
        vm.value = object.get_text()
    widget.connect("changed", changed)
    return vm

def create_for_gtkspin(widget, timeout, notify):
    vm = ValueMonitor(widget.get_value_as_int, timeout, notify, widget)
    def changed(object, *data):
        vm.value = object.get_value_as_int()
    widget.connect("value-changed", changed)
    return vm
