#!/usr/bin/env python
import Tix,math,tkFont

class Punkt:
	def __init__(self,x=0,y=0):
		self.x=x
		self.y=y

	def text(self):
		return "[%9.4f,%9.4f]"%(self.x,self.y)

class Appn(Tix.Frame):
	def in_range_line(self,x1,y1,x2,y2,xr,yr):
		if x1>x2:
			if not(x1 >= xr >= x2): return False
		else:
			if not(x1<=xr<=x2): return False
		if y1>y2:
			if not(y1 >= yr >= y2): return False
		else:
			if not(y1<=yr<=y2):
				return False
		return True
	def search_int(self,x1,y1,x2,y2,x3,y3,x4,y4):
		r=(x1*(y3-y4)+x2*(y4-y3)+(x3-x4)*(y2-y1))
		e=[(x1*(x3*(y2-y4)+x4*(y3-y2))-x2*(x3*(y1-y4)+x4*(y3-y1)))/r
		,(x1*y2*(y3-y4)+x2*y1*(y4-y3)+(y2-y1)*(x3*y4-x4*y3))/r]
		return e
	def PushPop(self, event, v, b):
		self.move[v]=b
	def MouseMove(self, event):
		nx=event.x
		ny=event.y
		if self.move[0]:
			self.c.coords('p1',nx-4,ny-4,nx+4,ny+4)
			w=self.c.coords('l1')
			w[0]=nx;w[1]=ny
			self.c.coords('l1',tuple(w))
		if self.move[1]:
			self.c.coords('p2',nx-4,ny-4,nx+4,ny+4)
			w=self.c.coords('l1')
			w[2]=nx;w[3]=ny
			self.c.coords('l1',tuple(w))
		if self.move[2]:
			self.c.coords('p3',nx-4,ny-4,nx+4,ny+4)
			w=self.c.coords('l2')
			w[0]=nx;w[1]=ny
			self.c.coords('l2',tuple(w))
		if self.move[3]:
			self.c.coords('p4',nx-4,ny-4,nx+4,ny+4)
			w=self.c.coords('l2')
			w[2]=nx;w[3]=ny
			self.c.coords('l2',tuple(w))

		p12=self.c.coords('l1')
		p34=self.c.coords('l2')
		np=self.search_int(p12[0],p12[1],p12[2],p12[3],p34[0],p34[1],p34[2],p34[3])
		self.c.coords('cut',np[0]-4,np[1]-4,np[0]+4,np[1]+4)

	def __init__(self,master=None):
		Tix.Frame.__init__(self,master)
		self.pack()
		self.c=Tix.Canvas(width=400,height=400,bg="white")

		self.c.create_line(100,100,300,300,fill="green",tag="l1")
		self.c.create_oval(100-4,100-4,100+4,100+4,fill="red",tag="p1")
		self.c.create_oval(300-4,300-4,300+4,300+4,fill="red",tag="p2")

		self.c.create_line(100,300,300,100,fill="blue",tag="l2")
		self.c.create_oval(100-4,300-4,100+4,300+4,fill="red",tag="p3")
		self.c.create_oval(300-4,100-4,300+4,100+4,fill="red",tag="p4")

		self.c.create_oval(200-4,200-4,200+4,200+4,fill="cyan",tag="cut")

		self.c.tag_bind('p1', '<ButtonRelease-1>', lambda e,s=self:s.PushPop(e,0,False))
		self.c.tag_bind('p1', '<Button-1>', lambda e,s=self:s.PushPop(e,0,True))
		self.c.tag_bind('p2', '<ButtonRelease-1>', lambda e,s=self:s.PushPop(e,1,False))
		self.c.tag_bind('p2', '<Button-1>', lambda e,s=self:s.PushPop(e,1,True))
		self.c.tag_bind('p3', '<ButtonRelease-1>', lambda e,s=self:s.PushPop(e,2,False))
		self.c.tag_bind('p3', '<Button-1>', lambda e,s=self:s.PushPop(e,2,True))
		self.c.tag_bind('p4', '<ButtonRelease-1>', lambda e,s=self:s.PushPop(e,3,False))
		self.c.tag_bind('p4', '<Button-1>', lambda e,s=self:s.PushPop(e,3,True))
		self.c.bind("<Motion>",self.MouseMove)

		self.c.pack()
		self.move=[False,False,False,False]

root=Tix.Tk()
app=Appn(master=root)
app.master.title("TEST")
app.mainloop()