#  This file is part of monadjust.
#
#  Copyright 2008 Pierre Ossman <drzeus@drzeus.cx>
#
#  Monadjust is free software; you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as published
#  by the Free Software Foundation; either version 2 of the License,
#  or (at your option) any later version.
#
#  Monadjust 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 Lesser General Public License
#  along with PulseAudio; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
#  USA.

import subprocess

import pygtk
pygtk.require('2.0')
import gtk
import gtk.glade

class Main:
	def __init__(self):
		signals = {
			"on_main_window_destroy": gtk.main_quit,
			"on_close_button_clicked": gtk.main_quit,
			"on_contrast_scale_value_changed": self.on_change,
			"on_brightness_scale_value_changed": self.on_change,
			"on_black_scale_value_changed": self.on_change,
			"on_gamma_scale_value_changed": self.on_change,
			}

		self.glade = gtk.glade.XML("monadjust.glade")
		self.glade.signal_autoconnect(signals)

		self.update_curve()

	def on_change(self, widget):
		self.update_curve()

	def update_curve(self):
		contrast = self.glade.get_widget("contrast_scale").get_value()
		brightness = self.glade.get_widget("brightness_scale").get_value()
		black_level = self.glade.get_widget("black_scale").get_value()
		gamma = self.glade.get_widget("gamma_scale").get_value()

		contrast += 1.0
		brightness += 1.0

		vector = []
		for i in range(0,256):
			x = i / 255.0
			y = brightness * pow(x, gamma) + black_level
			if y > 0.5:
				y = 1.0 - pow((1.0 - y) * 2, contrast) / 2
			else:
				y = pow(y * 2, contrast) / 2
			vector.append(y)

		args = []
		for point in vector:
			val = int(point * 255)
			if val < 0:
				val = 0
			if val > 255:
				val = 255
			args.append(str(val))

		p = subprocess.Popen(["./monadjust_set_lut"] + args)
		p.wait()

win = Main()
gtk.main()

