
import gtk, gtk.gdk, sys

pen_device = (device for device in gtk.gdk.devices_list() if device.name == sys.argv[1]).next()
pen_device.set_mode(gtk.gdk.MODE_SCREEN)

class Program(object):
    def __init__(self):
        self.drawing_area = gtk.DrawingArea()
        self.drawing_area.set_events(gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.POINTER_MOTION_MASK)
        self.drawing_area.set_extension_events(gtk.gdk.EXTENSION_EVENTS_ALL)
        self.drawing_area.connect("realize", self.on_realize)
        self.drawing_area.connect("button-press-event", self.on_button_press_event)
        self.drawing_area.connect("button-release-event", self.on_button_release_event)
        self.drawing_area.connect("motion-notify-event", self.on_motion_notify_event)

        self.window = gtk.Window()
        self.window.add(self.drawing_area)
        self.window.connect("destroy", self.on_destroy)
        self.window.set_title("Try to draw some points with both mouse and pen.")
        self.window.maximize()
        self.window.show_all()
        
        self.mouse_down = False
        
    def on_realize(self, drawing_area):
        self.drawable = self.drawing_area.window
        colormap = gtk.gdk.colormap_get_system()
        self.gc_mouse = self.drawable.new_gc(foreground=colormap.alloc_color("#00AA00"), background=colormap.alloc_color("#00AA00"))
        self.gc_pen = self.drawable.new_gc(foreground=colormap.alloc_color("#AA0000"), background=colormap.alloc_color("#AA0000"))
        
    def on_destroy(self, window):
        gtk.main_quit()
        
    def get_gc(self, event):
        if event.device == pen_device:
            return self.gc_pen
        else:
            return self.gc_mouse
        
    def on_button_press_event(self, window, event):
        gc = self.get_gc(event)
        self.drawable.draw_point(gc, int(event.x), int(event.y))
        self.mouse_down = True

    def on_button_release_event(self, window, event):
        gc = self.get_gc(event)
        self.drawable.draw_line(gc, int(event.x-3), int(event.y-3), int(event.x+3), int(event.y+3))
        self.drawable.draw_line(gc, int(event.x-3), int(event.y+3), int(event.x+3), int(event.y-3))
        self.mouse_down = False

    def on_motion_notify_event(self, window, event):
        if self.mouse_down:
            gc = self.get_gc(event)
            self.drawable.draw_point(gc, int(event.x), int(event.y))

program = Program()
gtk.main()
