#!/usr/bin/env python
from gi.repository import Gtk
from gi.repository import GLib
import cairo
import math
import cmath
import random
from numpy import poly1d

##
## This is really inefficient quick and dirty
##

# This is ugly, scale changes what points we take, drawscale changes what
# we plot, mx and my move things (but don't move axes)
scale = 1.0;
drawscale = 0.5;
drawmx = 0.0;
drawmy = 0.0;

##
##
#
#a b
#c d
# is the matrix
#
a = 1.0
b = 1.0j
c = 1.0
d = -1.0


x = [];
y = [];

stop_the_drawing = False

def OnDraw(widg, cr):
  cr.set_line_width(1)
  cr.set_source_rgb(1, 1, 1)
  cr.rectangle (0, 0, 600, 600)
  cr.fill ()

  cr.set_source_rgb(0, 0, 0)

  cr.move_to(600,0)
  cr.line_to(600,600)
  cr.stroke()

  cr.set_source_rgb(0.5, 0.5, 0.5)

  cr.move_to(0,300)
  cr.line_to(600,300)
  cr.move_to(300,0)
  cr.line_to(300,600)
  cr.stroke()

  cr.set_source_rgba(0.0, 0.0, 1.0, 0.2)

  for i in range(len(x)):
    cr.arc(x[i],y[i],0.5, 0, 2*math.pi)
    cr.fill()

def stop_drawing(widg):
  global stop_the_drawing
  stop_the_drawing = True

widg = Gtk.Window()
box = Gtk.VBox()
widg.add(box)
area = Gtk.DrawingArea()
area.set_size_request(600, 600)
box.add(area)

b2 = Gtk.HBox()
box.add(b2)


but = Gtk.Button("Stop")
but.connect('clicked', stop_drawing)
b2.add(but)

but = Gtk.Button("Quit")
but.connect('clicked', Gtk.main_quit)
b2.add(but)


def compute_few():
  for i in range(5000):
    if i & 0x11:
      while Gtk.events_pending(): Gtk.main_iteration()
    if stop_the_drawing:
      break


    z1 = 0
    z2 = 0
    while z1==0 and z2==0:
      z1 = random.uniform(-1.0/scale,1.0/scale)+1j*random.uniform(-1.0/scale,1.0/scale)
      z2 = random.uniform(-1.0/scale,1.0/scale)+1j*random.uniform(-1.0/scale,1.0/scale)

    zz = ((a*z1+b*z2)*(z1.conjugate()) + (c*z1+d*z2)*(z2.conjugate()))/(z1*(z1.conjugate())+z2*(z2.conjugate()))

    x.append(drawscale*(zz.real+drawmx)*300+300)
    y.append(-drawscale*(zz.imag+drawmy)*300+300)
  area.queue_draw()
  if len(x) > 1000000 or stop_the_drawing:
    return False
  else:
    return True
	    
widg.connect('destroy', Gtk.main_quit)
area.connect('draw', OnDraw)

widg.show_all()

GLib.idle_add(compute_few)

Gtk.main()
