#! /usr/bin/env python
###############################################################################
#                                                                             #
#   Copyright 2005 University of Cambridge Computer Laboratory.               #
#                                                                             #
#   This file is part of Nprobe.                                              #
#                                                                             #
#   Nprobe 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.                                       #
#                                                                             #
#   Nprobe 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 Nprobe; if not, write to the Free Software                     #
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA #
#                                                                             #
###############################################################################


##############################################################################
## 
##
## 
## 
##
## 

############################################################################ 

#import string
from string import *
from Tkinter import *
from np_widgets import *
import pyColorChooser

S_RGB = 0
S_ALPHA = 1
S_DENS = 2

class ColFrame(Frame):

    def lookat(self, ev):

        c = ev.widget
        y = int(c.canvasy(ev.y)) + 12
        i = y/25 -1

	cycle = self.sort_curr.get()

	if cycle == 0:
	    cols = self.cols_by_filepos #rgb.txt order
	elif cycle == 1:
	    cols = self.cols_by_name #name order
	elif cycle == 2:
	    cols = self.cols_by_density #all RGB components
            
        if self.sortdir == -1:
            i = len(cols) - i -1

        #print 'selected %s' % (cols[i][1])

        col = splitfields(cols[i][1], '/')[0]
        rgb, col = pyColorChooser.askcolor(color=col, master = self)
        

    def toggle_bkgnd(self):
        
	self.draw.delete(ALL)
	if self.fg == 'black':
	    self.fg = 'white'
	else:
	    self.fg = 'black'
	if self.bg ==  'black':
	    self.bg = 'white'
	else:
	    self.bg = 'black'
	
	self.draw.config(bg=self.bg)
	self.draw_cols()

    def toggle_sortdir(self):

        self.sortdir = -self.sortdir
        self.draw_cols()

    def quitfun(self):
	self.master.destroy()

    def draw_cols(self):

	x = 25
	yinc = 25
	ncols = 1
	canv = self.draw

	cycle = self.sort_curr.get()
	#print 'drawing',
	#print cycle
        
	self.draw.delete(ALL)

	if cycle == 0:
	    cols = self.cols_by_filepos #rgb.txt order
	elif cycle == 1:
	    cols = self.cols_by_name #name order
	elif cycle == 2:
	    cols = self.cols_by_density #all RGB components

        if self.sortdir == 1:
            i1 = 0
            i2 = len(cols)-1
            inc = 1
        else:
            i1 = len(cols)-1
            i2 = 0
            inc = -1

	#for colt in cols:
        for i in range(i1, i2, inc):
            colt = cols[i]
	    col = colt[0]
	    #print 'drawing %s' % (col)
	    y = yinc*ncols
	    canv.create_line(x, y, x+25, y, fill=col)
	    canv.create_line(x+30, y, x+55, y, fill=col, width=2)
	    canv.create_rectangle(x+60, y-5, x+85, y+5, fill=col, 
				       outline="")
	    canv.create_text(x+100, y, fill=col, text='text', anchor=W)
	    canv.create_text(x+130, y, fill=self.fg, text=colt[1], anchor=W)
	    ncols = ncols+1

	#print 'done'

    def createCanvas(self, lencols):

	self.draw = Canvas(self, width=500, height=725,
			   background=self.bg,
			   scrollregion=(0, 0, 500, (lencols+1)*25))


	self.draw.scrollY = Scrollbar(self, orient=VERTICAL)
	self.draw['yscrollcommand'] = self.draw.scrollY.set
	self.draw.scrollY['command'] = self.draw.yview
	self.draw.scrollY.pack(side=RIGHT, fill=Y)

        self.draw.bind("<Button-1>", self.lookat)
        self.draw.bind("<Button-4>", self.wheelscroll)
        self.draw.bind("<Button-5>", self.wheelscroll)

	self.draw.pack(side=BOTTOM)

	self.draw.master = self

    

    def create_toolbar(self):
        
	# create a toolbar
	toolbar = self.toolbar = Frame(self, width=500, height=25,)
	toolbar.configure(bg='grey')
	toolbar.pack(side=TOP, fill=X)
        
	# quit button
	toolbar.quitb = Button(toolbar, text="quit", width=6, 
			       command=self.quitfun)
	toolbar.quitb.configure(bg='grey', fg='red')
	toolbar.quitb.pack(side=RIGHT, padx=2)
        
        # background button
        toolbar.bkgndb = Button(toolbar, text="background", width=6, 
                               command=self.toggle_bkgnd)
        toolbar.bkgndb.configure(bg='grey', fg='black')
        toolbar.bkgndb.pack(side=LEFT, padx=2)
        
        # reverse sort button
        self.sortdir = 1
        toolbar.srevb = Button(toolbar, text="reverse", width=6, 
                               command=self.toggle_sortdir)
        toolbar.srevb.configure(bg='grey', fg='black')
        toolbar.srevb.pack(side=LEFT, padx=2)

        # colour sort
	toolbar.sbm = BarButton(toolbar, 
				text='sort', bg='gray', 
				relief=RAISED, padx=2).menu

 	self.sort_curr = IntVar(self)
 	self.sort_curr.set(0)
        
        toolbar.sbm.add_radiobutton(label='RGB', 
				  command=self.draw_cols, 
				  variable=self.sort_curr,
				  value=S_RGB, indicatoron=1, 
				  selectcolor='blue')
        
        toolbar.sbm.add_radiobutton(label='Alpha', 
				  command=self.draw_cols, 
				  variable=self.sort_curr,
				  value=S_ALPHA, indicatoron=1, 
				  selectcolor='blue')
        
        toolbar.sbm.add_radiobutton(label='Density', 
				  command=self.draw_cols, 
				  variable=self.sort_curr,
				  value=S_DENS, indicatoron=1, 
				  selectcolor='blue')

        

    def wheelscroll(self, ev):
        #print 'scroll button %d' % (ev.num)
        if ev.num == 4:
            self.draw.yview(SCROLL, -1, UNITS)
        else:
            self.draw.yview(SCROLL, 1, UNITS)


    def __init__(self, cols, master=None):

	def sort_cols_by_density(a, b):
	    ad = a[2][0]+a[2][1]+a[2][2]
	    bd = b[2][0]+b[2][1]+b[2][2]
	    return bd - ad

	self.bg = 'white'
	self.fg = 'black'

	self.cols_by_filepos = cols
	self.cols_by_name = cols[:]
	self.cols_by_name.sort()
	self.cols_by_density = cols[:]
	self.cols_by_density.sort(sort_cols_by_density)
	lencols = len(cols)
	Frame.__init__(self, master)

        self.winfo_toplevel().title('X11 Colours')
        
	Pack.config(self)
        t = self.create_toolbar()
	c = self.createCanvas(lencols)
	self.sort_cycle = 0
	self.draw_cols()
	self.mainloop()

#############################################################################
##############################################################################
 


cols = []
ncols = 0

cf = open('/usr/lib/X11/rgb.txt', 'r')

cf.readline()
colstrs = cf.readlines()

last_rgb = (0,0,0)

colstr = colstrs[0]
colsplit = split(colstr)
rgb = (atoi(colsplit[0]), atoi(colsplit[1]), atoi(colsplit[2]))
names = colsplit[3]
for i in colsplit[4:]:
    names = names+' '+i
col = names
last_rgb = rgb
#print '%s %d %d %d' % (names, rgb[0], rgb[1], rgb[2]),

for colstr in colstrs[1:]:
    colsplit = split(colstr)
    rgb = (atoi(colsplit[0]), atoi(colsplit[1]), atoi(colsplit[2]))
    name = colsplit[3]
    for i in colsplit[4:]:
	name = name+' '+i
    #print 'got %s %d %d %d ' % (name, rgb[0], rgb[1], rgb[2]),

    if rgb[0] == last_rgb[0] and rgb[1] == last_rgb[1] and rgb[2] == last_rgb[2]:
	names = names + '/' + name
	#print 'same'
    else:
	cols.append((col, names, last_rgb))
	#print 'adding %s %d %d %d' % (names, rgb[0], rgb[1], rgb[2])
	names = name
	col = name

    last_rgb = rgb

f = ColFrame(cols)
