#coding: utf-8
#import workflow
import ui
import console
import pickle
import os
import re

pathMain=os.getcwd()
pathMain=re.sub(r'Library.*','',pathMain)
pathMain+='Documents/'
pathDir=''
pathSave=pathMain+'_patternEditor//'


#from pattern_editor import *
#action_in = workflow.get_input()

#enum
X=0
Y=1
D=2
P=2
EMPTY=-1
START=0
END=1
FLAG=2
CENTER=2
VECTOR1=3
VECTOR2=4
VECTOR3=5
VECTOR4=6
TYPE=3
DRAW_LINE=1
DRAW_POINT=2
DRAW_CIRCLE=3
EDIT=0
SCROLL=4
ARC=11

pList=list() #point list
vList=list() #vector list
Pref=list() #preferences

def point():
data=list()
data.append(0) #x
data.append(0) #y
data.append(1) #point flag
data.append(0) #points type
return data

def line():
data=list()
data.append(0) #index start point
data.append(0) #index end point
data.append(0) #line center point
data.append(0) #line type
return data


def drawLine(sender):
view['btnDrawLine'].background_color='#C8C8C8'
view['btnDrawCircle'].background_color='#EDEDED'
view['btnEdit'].background_color='#EDEDED'
v.mainMode=DRAW_LINE

def drawCircle(sender):
view['btnDrawLine'].background_color='#EDEDED'
view['btnDrawCircle'].background_color='#C8C8C8'
view['btnEdit'].background_color='#EDEDED'
v.mainMode=DRAW_CIRCLE

def edit(sender):
view['btnDrawLine'].background_color='#EDEDED'
view['btnDrawCircle'].background_color='#EDEDED'
view['btnEdit'].background_color='#C8C8C8'
v.mainMode=EDIT

def clearAll(sender):
if(len(pList)):
del pList[0:len(pList)]
del vList[0:len(vList)]
v.set_needs_display()

def save(sender):
f = open(pathSave+'_points.txt',"w")
pickle.dump(pList, f)
f.close()
f = open(pathSave+'_lines.txt',"w")
pickle.dump(vList, f)
f.close()
Pref[0]=v.zoom
Pref[1]=v.dX
Pref[2]=v.dY
Pref[3]=v.vdX
Pref[4]=v.vdY
f = open(pathSave+'_pref.txt',"w")
pickle.dump(Pref, f)
f.close()

def saveImage(sender):
if(len(pList)):
with ui.ImageContext(view.width, view.height) as ctx:
path=ui.Path()
arc=ui.Path()
circle=ui.Path()

if(len(vList)):
l=0
while l vt=vList[l]
l=l+1
if(pList[vt[END]][X]>4000 or pList[vt[END]][X]<0):
continue
#draw circles
if(vt[CENTER]==vt[END]):
pt=pList[vt[START]]
r=pList[vt[END]][Y]-pt[Y]
circle.append_path(ui.Path.oval(pt[X]-r,pt[Y]-r,r*2, r*2))
else:
pt=pList[vt[START]]
path.move_to(pt[X],pt[Y])
ptc=pList[vt[CENTER]]
if(ptc[FLAG]==ARC ):
arc.move_to(pt[X],pt[Y])
pt=pList[vt[END]]
ptc=pList[vt[CENTER]]
arc.add_quad_curve(pt[X],pt[Y],ptc[X],ptc[Y])
else:
ptInd=vt[END]
pt=pList[ptInd]
path.line_to(pt[X],pt[Y])

ui.set_color('green')
path.line_width=3
path.stroke()
ui.set_color('#DB0072')
arc.line_width=3
arc.stroke()
ui.set_color('#DB0072')
circle.line_width=3
circle.stroke()
#draw points
for pt in pList:
if(pt[X]>4000 or pt[X]<0 or pt[FLAG]==EMPTY):
continue
if(pt[TYPE]==CENTER):
ui.set_color('#00B687')
point=ui.Path.oval(pt[X]-3,pt[Y]-3, 6, 6)
else:
ui.set_color('black')
point=ui.Path.oval(pt[X]-5,pt[Y]-5, 10, 10)
point.fill()
#draw selection
if(v.selectEnd>EMPTY):
p=pList[v.selectStart]
path=ui.Path()
path.move_to(p[X],p[Y])
p=pList[v.selectEnd]
path.line_to(p[X],p[Y])
ui.set_color('blue')
path.line_width=5
path.stroke()
point=ui.Path.oval(p[X]-7,p[Y]-7, 14, 14)
ui.set_color('red')
point.fill()

img = ctx.get_image()
f = open(pathSave+'_draw.png',"w")
f.write(img.to_png())
f.close()


def isNear(x,x1,d):
if(x==x1):
return 0 #near but not the same
if(x>x1+d):
return 0
if(x return 0
return 1

def isNearP(pt,x,y,d):
if(x==pt[X] or y==pt[Y]):
return 0 #near but not the same
if(x>pt[X]+d or y>pt[Y]+d or x return 0
return 1


def movePoints(d,mode):
for p in pList:
p[mode]+=d

def moveDraw(sender):
if(v.scrollMode==0):
v.scrollMode=1
view['btnMoveDraw'].background_color='#C8C8C8'
else:
v.scrollMode=0
view['btnMoveDraw'].background_color='#EDEDED'


def setLineCenter(i):
l=vList[i]
if(l[START]==l[END]):
del vList[i]
return 0
xSt=pList[l[START]][X]
ySt=pList[l[START]][Y]
xEnd=pList[l[END]][X]
yEnd=pList[l[END]][Y]
pList[l[CENTER]][X]=(xSt+xEnd)/2
pList[l[CENTER]][Y]=(ySt+yEnd)/2


def setAllLineCenter():
i=0
while i l=vList[i]
if(l[START]==l[END]):
del vList[i]
i+=1
continue
if(l[CENTER]==l[END]): #circles
i+=1
continue
if(pList[l[CENTER]][FLAG]==ARC):
i+=1
continue
xSt=pList[l[START]][X]
ySt=pList[l[START]][Y]
xEnd=pList[l[END]][X]
yEnd=pList[l[END]][Y]
if(l[CENTER]==1):
p=point()
p[TYPE]=CENTER
p[X]=(xSt+xEnd)/2
p[Y]=(ySt+yEnd)/2
l[CENTER]=len(pList)
pList.append(p)
vList[i]=l
else:
pList[l[CENTER]][X]=(xSt+xEnd)/2
pList[l[CENTER]][Y]=(ySt+yEnd)/2
i+=1


def scrollLeft(sender):
if(v.scrollMode==0):
v.x+=v.ds
v.dX+=v.ds
else:
v.vdX-=v.ds*3
movePoints(v.ds*3,X)
v.x=v.xCenter-(v.width/2)*v.zoom/v.vS+v.vdX*v.zoom/v.vS+v.dX
v.y=v.yCenter-(v.height/2)*v.zoom/v.vS+v.vdY*v.zoom/v.vS+v.dY
v.set_needs_display()


def scrollRight(sender):
if(v.scrollMode==0):
v.x-=v.ds
v.dX-=v.ds
else:
v.vdX+=v.ds*3
movePoints(-v.ds*3,X)
v.x=v.xCenter-(v.width/2)*v.zoom/v.vS+v.vdX*v.zoom/v.vS+v.dX
v.y=v.yCenter-(v.height/2)*v.zoom/v.vS+v.vdY*v.zoom/v.vS+v.dY
v.set_needs_display()

def scrollUp(sender):
if(v.scrollMode==0):
v.y-=v.ds
v.dY-=v.ds
else:
v.vdY+=v.ds
movePoints(-v.ds,Y)
v.x=v.xCenter-(v.width/2)*v.zoom/v.vS+v.vdX*v.zoom/v.vS+v.dX
v.y=v.yCenter-(v.height/2)*v.zoom/v.vS+v.vdY*v.zoom/v.vS+v.dY
v.set_needs_display()

def scrollDown(sender):
if(v.scrollMode==0):
v.y+=v.ds
v.dY+=v.ds
else:
v.vdY-=v.ds
movePoints(v.ds,Y)
v.x=v.xCenter-(v.width/2)*v.zoom/v.vS+v.vdX*v.zoom/v.vS+v.dX
v.y=v.yCenter-(v.height/2)*v.zoom/v.vS+v.vdY*v.zoom/v.vS+v.dY
v.set_needs_display()


def zoomOut(sender):
zOld=v.zoom
v.zoom-=v.zoom*v.dz
tr=ui.Transform.scale(v.zoom/v.vS,v.zoom/v.vS)
v.transform=tr
#notes. web.width not changed it transformations
v.x=v.xCenter-(v.width/2)*v.zoom/v.vS+v.vdX*v.zoom/v.vS+v.dX
v.y=v.yCenter-(v.height/2)*v.zoom/v.vS+v.vdY*v.zoom/v.vS+v.dY
#set all views on screen senter after zoom

dlt=v.dY/zOld*(zOld-v.zoom)
v.y-=dlt
v.dY-=dlt
dlt=v.dX/zOld*(zOld-v.zoom)
#print 'dlt={} v.dX={} z={} zO={} w={}'.format(dlt,v.dX,v.zoom,zOld, web.width*v.zoom*v.wS)
v.x-=dlt
v.dX-=dlt



def zoomIn(sender):
zOld=v.zoom
v.zoom+=v.zoom*v.dz
tr=ui.Transform.scale(v.zoom/v.vS,v.zoom/v.vS)
v.transform=tr
#notes. web.width not changed it transformations
v.x=v.xCenter-(v.width/2)*v.zoom/v.vS+v.vdX*v.zoom/v.vS+v.dX
v.y=v.yCenter-(v.height/2)*v.zoom/v.vS+v.vdY*v.zoom/v.vS+v.dY
#set all views on screen senter after zoom
dlt=v.dY/zOld*(zOld-v.zoom)
v.y-=dlt
v.dY-=dlt
dlt=v.dX/zOld*(zOld-v.zoom)
#print 'dlt={} v.dX={} z={} zO={} w={}'.format(dlt,v.dX,v.zoom,zOld, web.width*v.zoom*v.wS)
v.x-=dlt
v.dX-=dlt


def setView():
v.zoom=1
#Pref[0]
v.dX=Pref[1]
v.dY=Pref[2]
v.vdX=Pref[3]
v.vdY=Pref[4]
v.width=view.width/2
v.height=view.height/2
v.x=0
v.y=125
v.border_width=3
v.border_color='grey'
view.add_subview(v)
v.xCenter=view.width/2
v.yCenter=view.height/2
##tr=ui.Transform.scale(v.zoom/v.vS,v.zoom/v.vS)
#v.transform=tr
#v.send_to_back()
#v.transform=tr
#v.x=v.xCenter-(v.width/2)*v.zoom/v.vS+v.vdX*v.zoom/v.vS+v.dX
#v.y=v.yCenter-(v.height/2)*v.zoom/v.vS+v.vdY*v.zoom/v.vS+v.dY

v.background_color='#070707'

view['btnEdit'].background_color='#C8C8C8'
view.present('full_screen',hide_title_bar=True)
v.set_needs_display()

def replacePoint(oldP,newP):
"""replace point in vector list"""
pList[oldP][FLAG]=EMPTY
i=0
while i < len(vList):
if(vList[i][START]==oldP):
vList[i][START]=newP
if(vList[i][END]==oldP):
vList[i][END]=newP
if(vList[i][START]==vList[i][END]):
pList[vList[i][CENTER]][FLAG]=EMPTY
del vList[i]
else:
i+=1
setPointType()
v.set_needs_display()

def removePoint(index):
"""remove point in point and vector lists"""
i=0
pList[index][FLAG]=EMPTY
while i < len(vList):
if(vList[i][START]==index):
del vList[i]
elif(vList[i][START]==vList[i][END]):
del vList[i]
elif(vList[i][END]==index):
del vList[i]
elif(vList[i][CENTER]==index):
del vList[i]
i+=1
setPointType()
v.set_needs_display()

def removeLine():
if(v.selectStart>EMPTY and v.selectEnd>EMPTY):
#del pList[v.selectStart]
#del pList[v.selectEnd]
i=0
while i < len(vList):
if(vList[i][START]==v.selectStart):
if(vList[i][END]==v.selectEnd):
removePoint(vList[i][CENTER])
continue
if(vList[i][END]==v.selectStart):
if(vList[i][START]==v.selectEnd):
removePoint(vList[i][CENTER])
continue
i+=1
v.selectStart=EMPTY
v.selectEnd=EMPTY
setPointType()
v.set_needs_display()

def clearSelect(sender):
if(v.selectStart>EMPTY and v.selectEnd>EMPTY):
removeLine()
elif(v.selectStart>EMPTY):
removePoint(v.selectStart)
elif(v.selectCenter>EMPTY):
removePoint(v.selectCenter)
v.selectStart=EMPTY
v.selectEnd=EMPTY
v.selectCenter=EMPTY
v.set_needs_display()


def setPointType():
i=0
while(i p=pList[i]
if(p[FLAG]==EMPTY or p[TYPE]==CENTER):
i+=1
continue
flag=0
for v in vList:
if(v[START]==i or v[END]==i):
flag+=1

pList[i][TYPE]=flag+2
i+=1

def close(sender):
view.close()

class drawView (ui.View):
mainMode=EDIT
selectStart=-1
selectCenter=-1
selectEnd=-1
oldX=0
oldY=0


#scrool and zoom
ds=150 #delta scroll
dz=0.1 #delta zoom
dX=0 #scroll by x
dY=0 #scroll by y
vdX=0 #shift of draw view by x relatively to web view center
vdY=0 #shift of draw view by y relatively to web view center
zoom=1 #page zoom
wS=2.5 #scale factor for web view zoom(it is bigger)
vS=10 #scale factor for draw view zoom(it is smaller)
xCenter=0 #drawing page center x relatively of superview
yCenter=0 #drawing page center x relatively of superview
#scrollMode=1 #scroll draw arrea relatively to web view
scrollMode=0 #scroll web view and draw view


def __init__(self):
# This will also be called without arguments when the view is loaded from a UI file.
# You don't have to call super. Note that this is called *before* the attributes
# defined in the UI file are set. Implement `did_load` to customize a view after
# it's been fully loaded from a UI file.
pass

def did_load(self):
# This will be called when a view has been fully loaded from a UI file.
pass

def will_close(self):
# This will be called when a presented view is about to be dismissed.
# You might want to save data here.
self.save()

def draw(self):
# This will be called whenever the view's content needs to be drawn.
# You can use any of the ui module's drawing functions here to render
# content into the view's visible rectangle.
# Do not call this method directly, instead, if you need your view
# to redraw its content, call set_needs_display().
# Example:
#path = ui.Path.rect(0, 0, self.width, self.height)
#ui.set_color('white')
#path.fill()

path=ui.Path()
arc=ui.Path()
circle=ui.Path()

#draw image
img = ui.Image.named(pathSave+'IMG_0326.JPG')
img.draw(0, 0, self.width, self.height)

if(len(vList)):
l=0



while l #circle.append_path(ui.Path.oval(pt[X]-r,pt[Y]-r,r*2, r*2))
path.move_to(pt[X],pt[Y])
#arc.move_to(pt[X],pt[Y])
#arc.add_curve(pt[X],pt[Y],ptc[X],ptc[Y],ptc[X],ptc[Y])
path.line_to(pt[X],pt[Y])

ui.set_color('green')
path.line_width=3
path.stroke()
ui.set_color('#DB0072')
arc.line_width=3
arc.stroke()
ui.set_color('#DB0072')
circle.line_width=3
circle.stroke()
#draw points
'''
for pt in pList:
if(pt[X]>4000 or pt[X]<0 or pt[FLAG]==EMPTY):
continue
if(pt[TYPE]==CENTER):
ui.set_color('#00B687')
point=ui.Path.oval(pt[X]-3,pt[Y]-3, 6, 6)
point.fill()
elif(pt[TYPE]==VECTOR2):
ui.set_color('black')
point=ui.Path.oval(pt[X]-5,pt[Y]-5, 10, 10)
point.fill()
elif(pt[TYPE]==VECTOR3):
ui.set_color('#0027A4')
point=ui.Path.oval(pt[X]-5,pt[Y]-5, 10, 10)
point.fill()
elif(pt[TYPE]>VECTOR3):
ui.set_color('yellow')
point=ui.Path.oval(pt[X]-5,pt[Y]-5, 10, 10)
point.fill()
else:
ui.set_color('green')
point=ui.Path.oval(pt[X]-5,pt[Y]-5, 10, 10)
point.fill()
#draw selection
if(self.selectEnd>EMPTY):
p=pList[self.selectStart]
path=ui.Path()
path.move_to(p[X],p[Y])
p=pList[self.selectEnd]
path.line_to(p[X],p[Y])
ui.set_color('blue')
path.line_width=5
path.stroke()
point=ui.Path.oval(p[X]-7,p[Y]-7, 14, 14)
ui.set_color('red')
point.fill()

if(self.selectStart>EMPTY):
p=pList[self.selectStart]
point=ui.Path.oval(p[X]-7,p[Y]-7, 14, 14)
ui.set_color('red')
point.fill()

if(self.selectCenter>EMPTY):
p=pList[self.selectCenter]
point=ui.Path.oval(p[X]-7,p[Y]-7, 14, 14)
ui.set_color('#DB0072')
point.fill()
'''

def layout(self):
# This will be called when a view is resized. You should typically set the
# frames of the view's subviews here, if your layout requirements cannot
# be fulfilled with the standard auto-resizing (flex) attribute.
pass

def touch_began(self, touch):
# Called when a touch begins.
x=touch.location[0]
y=touch.location[1]
self.oldX=x
self.oldY=y
if(self.mainMode==DRAW_CIRCLE):
if(self.selectStart==EMPTY):
p=point()
p[X]=x
p[Y]=y
pList.append(p)
self.selectStart=len(pList)-1
else:
v=line()
v[START]=self.selectStart
p=point()
p[X]=x
p[Y]=y
p[TYPE]=CENTER
pList.append(p)
v[END]=len(pList)-1
v[CENTER]=v[END]
self.selectStart=-1
vList.append(v)


if(self.mainMode==DRAW_LINE):
index=-1
i=0
for p in pList:
if(p[TYPE]==CENTER or p[FLAG]==EMPTY):
i+=1
continue
if(isNearP(p,x,y,15)):
index=i
break
i+=1
if(self.selectStart==EMPTY):
if(index>-1):
self.selectStart=index
else:
p=point()
p[X]=x
p[Y]=y
pList.append(p)
self.selectStart=len(pList)-1
else:
v=line()
v[START]=self.selectStart
if(index>-1):
v[END]=index
else:
p=point()
p[X]=x
p[Y]=y
pList.append(p)
v[END]=len(pList)-1

p=point()
xSt=pList[v[START]][X]
ySt=pList[v[START]][Y]
xEnd=pList[v[END]][X]
yEnd=pList[v[END]][Y]
p[X]=(xSt+xEnd)/2
p[Y]=(ySt+yEnd)/2
p[TYPE]=CENTER
v[CENTER]=len(pList)
pList.append(p)
self.selectStart=-1
vList.append(v)

self.set_needs_display()


def touch_moved(self, touch):
# Called when a touch moves.
x=touch.location[0]
y=touch.location[1]

index=-1
i=0
for p in pList:
if(p[TYPE]==CENTER or p[FLAG]==EMPTY):
continue
if(isNearP(p,x,y,15)):
x=p[X]
y=p[Y]
index=i
break
i+=1
if(self.mainMode==DRAW_LINE):
pass
#if(index>-1 and index!=len(pList)-1):
#vList[len(vList)-1][END]=index
#else:
#pList[len(pList)-1][X]=x
#pList[len(pList)-1][Y]=y

if(self.mainMode==EDIT):
if(self.selectCenter>EMPTY):
if(self.oldX>0):
pList[self.selectCenter][X]+=x-self.oldX
pList[self.selectCenter][Y]+=y-self.oldY
pList[self.selectCenter][FLAG]=ARC

elif(self.selectEnd>EMPTY):
if(self.oldX>0):
pList[self.selectStart][X]+=x-self.old
pList[self.selectStart][Y]+=y-self.oldY
pList[self.selectEnd][X]+=x-self.oldX
pList[self.selectEnd][Y]+=y-self.oldY
elif(self.selectStart>EMPTY):
index=EMPTY
i=0
x_=pList[self.selectStart][X]+x-self.oldX
y_=pList[self.selectStart][Y]+y-self.oldY
for p in pList:
if(p[TYPE]==CENTER or p[FLAG]==EMPTY ):
i+=1
continue
if(i!=self.selectStart):
if(isNearP(p,x_,y_,15)):
index=i
break
i+=1
if(index>EMPTY and pList[index][TYPE]!=CENTER):
replacePoint(self.selectStart,index)
self.selectStart=index
else:
if(self.oldX>0):
pList[self.selectStart][X]+=x-self.oldX
pList[self.selectStart][Y]+=y-self.oldY
self.oldX=x
self.oldY=y
setAllLineCenter()
self.set_needs_display()

def touch_ended(self, touch):
# Called when a touch end
x=touch.location[0]
y=touch.location[1]
if(self.mainMode==EDIT):
i=0
index=-1
while i p=pList[i]
if(p[FLAG]==EMPTY):
i+=1
continue
if(isNearP(p,x,y,15)):
x=p[X]
y=p[Y]
index=i
break
i=i+1
if(index>EMPTY):
if(self.selectStart>-1):
if(index!=self.selectStart):
self.selectEnd=index
else:
if(pList[index][TYPE]==CENTER):
self.selectCenter=index
else:
self.selectStart=index

#check line ends after whole line move
if(self.selectEnd>-1):
x=pList[self.selectStart][X]
y=pList[self.selectStart][Y]
for p in pList:
if(p[TYPE]==CENTER or p[FLAG]==EMPTY):
continue
if(isNearP(p,x,y,15)):
x=p[X]
y=p[Y]
break
pList[self.selectStart][X]=x
pList[self.selectStart][Y]=y
x=pList[self.selectEnd][X]
y=pList[self.selectEnd][Y]
for p in pList:
if(p[TYPE]==CENTER):
continue
if(isNearP(p,x,y,15)):
x=p[X]
y=p[Y]
break
pList[self.selectEnd][X]=x
pList[self.selectEnd][Y]=y
if(index==-1): #deselect all
self.selectStart=-1
self.selectCenter=-1
self.selectEnd=-1

self.set_needs_display()
#log.write('www'+'{}'.format(self.selectStart)+'\n')
#log.flush()

self.set_needs_display()

def keyboard_frame_will_change(self, frame):
# Called when the on-screen keyboard appears/disappears
# Note: The frame is in screen coordinates.
pass

def keyboard_frame_did_change(self, frame):
# Called when the on-screen keyboard appears/disappears
# Note: The frame is in screen coordinates.
pass



view = ui.load_view() #super view
v = drawView() #draw view


f = open(pathSave+'_points.txt',"r")
pList=pickle.load(f)
f.close()
f = open(pathSave+'_lines.txt',"r")
vList=pickle.load(f)
f.close()
f = open(pathSave+'_pref.txt',"r")
Pref=pickle.load(f)
f.close()

if(len(Pref)<5):
Pref.append(0)
Pref.append(0)
Pref.append(0)
Pref.append(0)
Pref.append(0)


setView()





#draw Image
#imageView=scroll['imageview1']
#imageView.width=w
##imageView.height=h
#imageView.load_from_url('file://'+pathSave+'432.pdf')
#imageView.load_from_url('file://'+pathSave+'shar_rdza_vol_7-0528.tif')
#imageView.transform=tr
#imageView.x=-1000
#imageView.y=-500
#imageView.alpha=0.7


#action_out = action_in
#workflow.set_output(action_out)