#!/usr/bin/env python
# WBMP save plugin
# (C) Copyright 2004 Wojtek Kaniewski <wojtekka@toxygen.net>
# Licensed under terms of GPL v2
#
# Based on colorhtml.py by Manish Singh

import string
import struct
import os.path

import gimp
from gimpfu import *

def python_wbmp(img, drawable, filename, raw_filename):
    width = drawable.width
    height = drawable.height
    bwidth = width / 8
    if width % 8:
        bwidth = bwidth + 1

    if not drawable.is_indexed:
        gimp.message('Only black and white images are supported')
        return

    if width > 127 or height > 127:
	gimp.message('Maximum size is 127x127')
	return

    gimp.tile_cache_ntiles(width / gimp.tile_width() + 1)

    wbmp = file(filename, 'w')

    wbmp.write('%c%c%c%c' % (0, 0, width, height))

    pr = drawable.get_pixel_rgn(0, 0, width, height, FALSE, FALSE)

    gimp.progress_init("Saving '%s' as WAP bitmap..." % filename)

    for y in range(0, height):
        row = pr[0:width, y]

	output = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

	for x in range(0, width):
		if ord(row[x]) > 0:
			output[x / 8] = output[x / 8] | (128 >> (x % 8))

	for x in range(0, bwidth):
		wbmp.write('%c' % output[x])

        gimp.progress_update(y / float(height))

    wbmp.close()

def register_save():
    gimp.register_save_handler("file_wbmp_save", "wbmp", "")

register(
    "file_wbmp_save",
    "Saves the image as WAP bitmap",
    "Saves the image as WAP bitmap (based on colorhtml.py by Manish Singh)",
    "Wojtek Kaniewski",
    "Wojtek Kaniewski",
    "2004",
    "<Save>/WBMP",
    "RGB",
    [],
    [],
    python_wbmp,
    on_query=register_save)

main()
