#!/usr/bin/python
import gimp, gimpplugin
from gimpfu import *
pdb = gimp.pdb
import os

black = (0,0,0)
white = (255,255,255)
gray = (128,128,128)

neutral_color = {
    NORMAL_MODE:   -1,
    DISSOLVE_MODE: -1,
    MULTIPLY_MODE: white,
    DIVIDE_MODE:   white,
    SCREEN_MODE:   black,
    OVERLAY_MODE:  gray,
    DODGE_MODE:    black,
    BURN_MODE:     white,
    HARDLIGHT_MODE:gray,
    SOFTLIGHT_MODE:gray,
    GRAIN_EXTRACT_MODE: gray,
    GRAIN_MERGE_MODE:   gray,
    DIFFERENCE_MODE:    black,
    ADDITION_MODE: black,
    SUBTRACT_MODE: black,
    DARKEN_ONLY_MODE:   white,
    LIGHTEN_ONLY_MODE:  black,
    HUE_MODE:      -1,
    SATURATION_MODE:    -1,
    COLOR_MODE:    -1,
    VALUE_MODE:    -1,
}    

class ResetMerge(gimpplugin.plugin):
    def query(self):
#	d = ''
	gimp.install_procedure ('plug_in_reset_merge', 
	    'Merge down a layer but preserve it, cleared to have no effect.',
	    """Apply the effect of "merge down" but preserve the layer being merged down.
Useful for incremental paint application and other incremental applications of all kinds.""",
	    'David Gowers <00ai99@gmail.com>','2006','David Gowers <00ai99@gmail.com>',
	    '<Image>/_Layer/_Reset Merge', 
	    '*',
	    PLUGIN, 
	    [(PF_INT, 'run_mode', "run mode"), (PF_IMAGE, 'image', 'Image'), (PF_DRAWABLE, 'drawable', 'Drawable')],
	    [])

    def plug_in_reset_merge(self, run_mode, image, drawable):
	image.undo_group_start()
	# operate on the parent layer if the layer mask is active
	if drawable.is_layer_mask:
	    drawable = filter(lambda v: v.mask == drawable, image.layers)[0]
	fillcolor = neutral_color[drawable.mode]
	# create a new layer with the same positioning, mode, parasites... as the old layer.
	if fillcolor == -1:
	    # add alpha to layers that otherwise couldn't be neutralized.
	    newlayer = pdb.gimp_layer_copy (drawable, 1)
	else:
	    newlayer = pdb.gimp_layer_copy (drawable, 0)
	oldname = drawable.name
	image.merge_down (drawable, 0) # expand as needed
	if newlayer.has_alpha:
	    newlayer.fill (TRANSPARENT_FILL)
	    # layer mask is preserved.
	else:
	    pdb.gimp_context_push()
	    gimp.set_foreground (fillcolor)
	    newlayer.fill (FOREGROUND_FILL)
	    pdb.gimp_context_pop()
	newlayer.name = oldname
	image.add_layer (newlayer) 
	image.undo_group_end()
	gimp.displays_flush()
	
    def start(self):
	gimpplugin.plugin.start(self)
	
if __name__ == '__main__':
    ResetMerge().start()