#!/usr/bin/python
import gimp,gimpplugin
from gimpfu import PLUGIN, PF_INT, PF_IMAGE, PF_DRAWABLE
pdb = gimp.pdb
import os

class PColormap(gimpplugin.plugin):
    def query(self):
	d = ''
	blurb = 'Convert the colormap of the image to a palette, overwriting the existing contents of the palette.'
	help = "Convert the colormap of the image to a palette named after the image. \nIf such a palette exists, its contents are overwritten."
	gimp.install_procedure('plug_in_palette_from_colormap', blurb,help,
	    'David Gowers <00ai99@gmail.com>','David Gowers <00ai99@gmail.com>','2006','<Image>/_Colors/Cop_y colormap to palette', '',
	    PLUGIN, 
	    [(PF_INT, 'run_mode', "run mode"),(PF_IMAGE, 'image', 'Image'), (PF_DRAWABLE, 'drawable', 'Drawable')], 
	    []
	    )

    def plug_in_palette_from_colormap(self, run_mode, image, drawable):
	fname = os.path.split(image.filename)[1]
	try:
	    ncolors = pdb.gimp_palette_get_info(fname)
	    pdb.gimp_palette_delete(fname)
	except:
	    pass
	name = pdb.gimp_palette_new( fname)
	for n in range(len(image.colormap)/3):
	    r,g,b = [ord(v) for v in image.colormap[n*3:(n*3)+3]]
	    pdb.gimp_palette_add_entry(fname,'', (r,g,b))
	pdb.gimp_context_set_palette(fname)

    def start(self):
	gimpplugin.plugin.start(self)
	
if __name__ == '__main__':
    PColormap().start()