Commit 77eb2440 authored by Guillaume Seguin's avatar Guillaume Seguin

Semi-automated coding style cleanup

parent cbd8cc06
Some cleanup commands :
To add a space after each comma :
sed -e "s/\(\w\),\(\w\)/\1, \2/g" -i *.py printrun/*.py printrun/svg/*.py
To add spaces around each = :
sed -e "s/\(\w\)=\(\w\)/\1 = \2/g" -i *.py printrun/*.py printrun/svg/*.py
sed -e "s/\(\w\)=\(\"\)/\1 = \2/g" -i *.py printrun/*.py printrun/svg/*.py
sed -e "s/\(\w\)=\((\)/\1 = \2/g" -i *.py printrun/*.py printrun/svg/*.py
To add spaces around each == :
sed -e "s/\(\w\)==\(\w\)/\1 == \2/g" -i *.py printrun/*.py printrun/svg/*.py
sed -e "s/\(\w\)==\(\"\)/\1 == \2/g" -i *.py printrun/*.py printrun/svg/*.py
sed -e "s/\(\w\)==\((\)/\1 == \2/g" -i *.py printrun/*.py printrun/svg/*.py
sed -e "s/\()\)==\(\w\)/\1 == \2/g" -i *.py printrun/*.py printrun/svg/*.py
sed -e "s/\()\)==\((\)/\1 == \2/g" -i *.py printrun/*.py printrun/svg/*.py
Obviously this is not a perfect solution, it WILL break the code. Juste check the diff and fix what's wrong before commiting.
...@@ -46,7 +46,7 @@ def evalme(s): ...@@ -46,7 +46,7 @@ def evalme(s):
class stlwrap: class stlwrap:
def __init__(self, obj, name=None): def __init__(self, obj, name = None):
self.obj = obj self.obj = obj
self.name = name self.name = name
if name is None: if name is None:
...@@ -58,7 +58,7 @@ class stlwrap: ...@@ -58,7 +58,7 @@ class stlwrap:
class showstl(wx.Window): class showstl(wx.Window):
def __init__(self, parent, size, pos): def __init__(self, parent, size, pos):
wx.Window.__init__(self, parent, size=size, pos=pos) wx.Window.__init__(self, parent, size = size, pos = pos)
#self.SetBackgroundColour((0, 0, 0)) #self.SetBackgroundColour((0, 0, 0))
#wx.FutureCall(200, self.paint) #wx.FutureCall(200, self.paint)
self.i = 0 self.i = 0
...@@ -141,7 +141,7 @@ class showstl(wx.Window): ...@@ -141,7 +141,7 @@ class showstl(wx.Window):
self.i += angle self.i += angle
if not self.triggered: if not self.triggered:
self.triggered = 1 self.triggered = 1
threading.Thread(target=self.cr).start() threading.Thread(target = self.cr).start()
def keypress(self, event): def keypress(self, event):
"""gets keypress events and moves/rotates acive shape""" """gets keypress events and moves/rotates acive shape"""
...@@ -200,9 +200,9 @@ class showstl(wx.Window): ...@@ -200,9 +200,9 @@ class showstl(wx.Window):
def repaint(self, event): def repaint(self, event):
dc = wx.PaintDC(self) dc = wx.PaintDC(self)
self.paint(dc=dc) self.paint(dc = dc)
def paint(self, coord1="x", coord2="y", dc=None): def paint(self, coord1 = "x", coord2 = "y", dc = None):
coords = {"x": 0, "y": 1, "z": 2} coords = {"x": 0, "y": 1, "z": 2}
if dc is None: if dc is None:
dc = wx.ClientDC(self) dc = wx.ClientDC(self)
...@@ -231,7 +231,7 @@ class showstl(wx.Window): ...@@ -231,7 +231,7 @@ class showstl(wx.Window):
bm = wx.BitmapFromImage(im) bm = wx.BitmapFromImage(im)
dcs.SelectObject(bm) dcs.SelectObject(bm)
bsz = bm.GetSize() bsz = bm.GetSize()
dc.Blit(scale * m.offsets[0] - bsz[0] / 2, 400 - (scale * m.offsets[1] + bsz[1] / 2), bsz[0], bsz[1], dcs, 0, 0, useMask=1) dc.Blit(scale * m.offsets[0] - bsz[0] / 2, 400 - (scale * m.offsets[1] + bsz[1] / 2), bsz[0], bsz[1], dcs, 0, 0, useMask = 1)
#for i in m.facets:#random.sample(m.facets, min(100000, len(m.facets))): #for i in m.facets:#random.sample(m.facets, min(100000, len(m.facets))):
# dc.DrawPolygon([wx.Point(offset[0]+scale*m.offsets[0]+scale*p[0], 400-(offset[1]+scale*m.offsets[1]+scale*p[1])) for p in i[1]]) # dc.DrawPolygon([wx.Point(offset[0]+scale*m.offsets[0]+scale*p[0], 400-(offset[1]+scale*m.offsets[1]+scale*p[1])) for p in i[1]])
#if(time.time()-t)>5: #if(time.time()-t)>5:
...@@ -242,29 +242,29 @@ class showstl(wx.Window): ...@@ -242,29 +242,29 @@ class showstl(wx.Window):
class stlwin(wx.Frame): class stlwin(wx.Frame):
def __init__(self, size=(800, 580), callback=None, parent=None): def __init__(self, size = (800, 580), callback = None, parent = None):
wx.Frame.__init__(self, parent, title=_("Plate building tool"), size=size) wx.Frame.__init__(self, parent, title = _("Plate building tool"), size = size)
self.SetIcon(wx.Icon(pixmapfile("plater.ico"), wx.BITMAP_TYPE_ICO)) self.SetIcon(wx.Icon(pixmapfile("plater.ico"), wx.BITMAP_TYPE_ICO))
self.mainsizer = wx.BoxSizer(wx.HORIZONTAL) self.mainsizer = wx.BoxSizer(wx.HORIZONTAL)
self.panel = wx.Panel(self, -1, size=(150, 600), pos=(0, 0)) self.panel = wx.Panel(self, -1, size = (150, 600), pos = (0, 0))
#self.panel.SetBackgroundColour((10, 10, 10)) #self.panel.SetBackgroundColour((10, 10, 10))
self.l = wx.ListBox(self.panel, size=(300, 180), pos=(0, 30)) self.l = wx.ListBox(self.panel, size = (300, 180), pos = (0, 30))
self.cl = wx.Button(self.panel, label=_("Clear"), pos=(0, 205)) self.cl = wx.Button(self.panel, label = _("Clear"), pos = (0, 205))
self.lb = wx.Button(self.panel, label=_("Load"), pos=(0, 0)) self.lb = wx.Button(self.panel, label = _("Load"), pos = (0, 0))
if(callback is None): if(callback is None):
self.eb = wx.Button(self.panel, label=_("Export"), pos=(100, 0)) self.eb = wx.Button(self.panel, label = _("Export"), pos = (100, 0))
self.eb.Bind(wx.EVT_BUTTON, self.export) self.eb.Bind(wx.EVT_BUTTON, self.export)
else: else:
self.eb = wx.Button(self.panel, label=_("Export"), pos=(200, 205)) self.eb = wx.Button(self.panel, label = _("Export"), pos = (200, 205))
self.eb.Bind(wx.EVT_BUTTON, self.export) self.eb.Bind(wx.EVT_BUTTON, self.export)
self.edb = wx.Button(self.panel, label=_("Done"), pos=(100, 0)) self.edb = wx.Button(self.panel, label = _("Done"), pos = (100, 0))
self.edb.Bind(wx.EVT_BUTTON, lambda e: self.done(e, callback)) self.edb.Bind(wx.EVT_BUTTON, lambda e: self.done(e, callback))
self.eb = wx.Button(self.panel, label=_("Cancel"), pos=(200, 0)) self.eb = wx.Button(self.panel, label = _("Cancel"), pos = (200, 0))
self.eb.Bind(wx.EVT_BUTTON, lambda e: self.Destroy()) self.eb.Bind(wx.EVT_BUTTON, lambda e: self.Destroy())
self.sb = wx.Button(self.panel, label=_("Snap to Z = 0"), pos=(00, 255)) self.sb = wx.Button(self.panel, label = _("Snap to Z = 0"), pos = (00, 255))
self.cb = wx.Button(self.panel, label=_("Put at 100, 100"), pos=(0, 280)) self.cb = wx.Button(self.panel, label = _("Put at 100, 100"), pos = (0, 280))
self.db = wx.Button(self.panel, label=_("Delete"), pos=(0, 305)) self.db = wx.Button(self.panel, label = _("Delete"), pos = (0, 305))
self.ab = wx.Button(self.panel, label=_("Auto"), pos=(0, 330)) self.ab = wx.Button(self.panel, label = _("Auto"), pos = (0, 330))
self.cl.Bind(wx.EVT_BUTTON, self.clear) self.cl.Bind(wx.EVT_BUTTON, self.clear)
self.lb.Bind(wx.EVT_BUTTON, self.right) self.lb.Bind(wx.EVT_BUTTON, self.right)
self.sb.Bind(wx.EVT_BUTTON, self.snap) self.sb.Bind(wx.EVT_BUTTON, self.snap)
...@@ -368,7 +368,7 @@ class stlwin(wx.Frame): ...@@ -368,7 +368,7 @@ class stlwin(wx.Frame):
self.Destroy() self.Destroy()
def export(self, event): def export(self, event):
dlg = wx.FileDialog(self, _("Pick file to save to"), self.basedir, style=wx.FD_SAVE) dlg = wx.FileDialog(self, _("Pick file to save to"), self.basedir, style = wx.FD_SAVE)
dlg.SetWildcard(_("STL files (;*.stl;*.STL;)")) dlg.SetWildcard(_("STL files (;*.stl;*.STL;)"))
if(dlg.ShowModal() == wx.ID_OK): if(dlg.ShowModal() == wx.ID_OK):
name = dlg.GetPath() name = dlg.GetPath()
...@@ -393,7 +393,7 @@ class stlwin(wx.Frame): ...@@ -393,7 +393,7 @@ class stlwin(wx.Frame):
print _("wrote %s") % name print _("wrote %s") % name
def right(self, event): def right(self, event):
dlg = wx.FileDialog(self, _("Pick file to load"), self.basedir, style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) dlg = wx.FileDialog(self, _("Pick file to load"), self.basedir, style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
dlg.SetWildcard(_("STL files (;*.stl;*.STL;)|*.stl|OpenSCAD files (;*.scad;)|*.scad")) dlg.SetWildcard(_("STL files (;*.stl;*.STL;)|*.stl|OpenSCAD files (;*.scad;)|*.scad"))
if(dlg.ShowModal() == wx.ID_OK): if(dlg.ShowModal() == wx.ID_OK):
name = dlg.GetPath() name = dlg.GetPath()
...@@ -443,7 +443,7 @@ class stlwin(wx.Frame): ...@@ -443,7 +443,7 @@ class stlwin(wx.Frame):
self.Refresh() self.Refresh()
#print time.time()-t #print time.time()-t
def load_stl_into_model(self, path, name, offset=[0, 0, 0], rotation=0, scale=[1.0, 1.0, 1.0]): def load_stl_into_model(self, path, name, offset=[0, 0, 0], rotation = 0, scale=[1.0, 1.0, 1.0]):
newname = os.path.split(name.lower())[1] newname = os.path.split(name.lower())[1]
c = 1 c = 1
while newname in self.models: while newname in self.models:
......
...@@ -83,7 +83,7 @@ class printcore(): ...@@ -83,7 +83,7 @@ class printcore():
self.online = False self.online = False
self.printing = False self.printing = False
def connect(self,port=None,baud=None): def connect(self, port = None, baud = None):
"""Set port and baudrate if given, then connect to printer """Set port and baudrate if given, then connect to printer
""" """
if self.printer: if self.printer:
...@@ -96,7 +96,7 @@ class printcore(): ...@@ -96,7 +96,7 @@ class printcore():
disable_hup(self.port) disable_hup(self.port)
self.printer = Serial(port = self.port, baudrate = self.baud, timeout = 0.25) self.printer = Serial(port = self.port, baudrate = self.baud, timeout = 0.25)
self.stop_read_thread = False self.stop_read_thread = False
self.read_thread = Thread(target=self._listen) self.read_thread = Thread(target = self._listen)
self.read_thread.start() self.read_thread.start()
def reset(self): def reset(self):
...@@ -183,7 +183,7 @@ class printcore(): ...@@ -183,7 +183,7 @@ class printcore():
self.clear = True self.clear = True
def _checksum(self, command): def _checksum(self, command):
return reduce(lambda x,y:x^y, map(ord, command)) return reduce(lambda x, y:x^y, map(ord, command))
def startprint(self, data, startindex = 0): def startprint(self, data, startindex = 0):
"""Start a print, data is an array of gcode commands. """Start a print, data is an array of gcode commands.
...@@ -289,7 +289,7 @@ class printcore(): ...@@ -289,7 +289,7 @@ class printcore():
self.clear = True self.clear = True
return return
if self.resendfrom < self.lineno and self.resendfrom > -1: if self.resendfrom < self.lineno and self.resendfrom > -1:
self._send(self.sentlines[self.resendfrom],self.resendfrom,False) self._send(self.sentlines[self.resendfrom],self.resendfrom, False)
self.resendfrom += 1 self.resendfrom += 1
return return
self.resendfrom = -1 self.resendfrom = -1
...@@ -369,7 +369,7 @@ if __name__ == '__main__': ...@@ -369,7 +369,7 @@ if __name__ == '__main__':
try: try:
if statusreport: if statusreport:
p.loud=False p.loud = False
sys.stdout.write("Progress: 00.0%") sys.stdout.write("Progress: 00.0%")
sys.stdout.flush() sys.stdout.flush()
while p.printing: while p.printing:
......
...@@ -35,7 +35,7 @@ class SkeinforgeQuickEditDialog(wx.Dialog): ...@@ -35,7 +35,7 @@ class SkeinforgeQuickEditDialog(wx.Dialog):
'speed':['Main Feed Rate (mm/s):','Main Flow Rate (scaler):','Perimeter Feed Rate (mm/s):','Perimeter Flow Rate (scaler):','Travel Feed Rate (mm/s):'] 'speed':['Main Feed Rate (mm/s):','Main Flow Rate (scaler):','Perimeter Feed Rate (mm/s):','Perimeter Flow Rate (scaler):','Travel Feed Rate (mm/s):']
} }
self.scrollbarPanel = wx.ScrolledWindow(self, -1, style=wx.TAB_TRAVERSAL) self.scrollbarPanel = wx.ScrolledWindow(self, -1, style = wx.TAB_TRAVERSAL)
self.settingsSizer = self.getProfileSettings() self.settingsSizer = self.getProfileSettings()
self.scrollbarPanel.SetSizer(self.settingsSizer) self.scrollbarPanel.SetSizer(self.settingsSizer)
...@@ -67,7 +67,7 @@ class SkeinforgeQuickEditDialog(wx.Dialog): ...@@ -67,7 +67,7 @@ class SkeinforgeQuickEditDialog(wx.Dialog):
self.Layout() self.Layout()
def getProfileSettings(self): def getProfileSettings(self):
settingsSizer = wx.GridBagSizer(hgap=2, vgap=1) settingsSizer = wx.GridBagSizer(hgap = 2, vgap = 1)
settingsRow = 0 settingsRow = 0
for craftName in sorted(self.moduleSettingsMap.keys()): for craftName in sorted(self.moduleSettingsMap.keys()):
...@@ -86,28 +86,28 @@ class SkeinforgeQuickEditDialog(wx.Dialog): ...@@ -86,28 +86,28 @@ class SkeinforgeQuickEditDialog(wx.Dialog):
for setting in settings.getReadRepository(repo).preferences: for setting in settings.getReadRepository(repo).preferences:
if setting.name in self.moduleSettingsMap[craftName]: if setting.name in self.moduleSettingsMap[craftName]:
settingSizer = wx.GridBagSizer(hgap=2, vgap=2) settingSizer = wx.GridBagSizer(hgap = 2, vgap = 2)
settingSizer.AddGrowableCol(0) settingSizer.AddGrowableCol(0)
settingRow = 0 settingRow = 0
settingLabel = wx.StaticText(self.scrollbarPanel, -1, setting.name) settingLabel = wx.StaticText(self.scrollbarPanel, -1, setting.name)
settingLabel.Wrap(400) settingLabel.Wrap(400)
settingSizer.Add(settingLabel, pos=(settingRow, 0)) settingSizer.Add(settingLabel, pos = (settingRow, 0))
if (isinstance(setting.value, bool)): if (isinstance(setting.value, bool)):
checkbox = wx.CheckBox(self.scrollbarPanel) checkbox = wx.CheckBox(self.scrollbarPanel)
checkbox.SetName(craftName + '.' + setting.name) checkbox.SetName(craftName + '.' + setting.name)
checkbox.SetValue(setting.value) checkbox.SetValue(setting.value)
settingSizer.Add(checkbox, pos=(settingRow, 1)) settingSizer.Add(checkbox, pos = (settingRow, 1))
settingSizer.AddSpacer((25, -1), pos=(settingRow, 2)) settingSizer.AddSpacer((25, -1), pos = (settingRow, 2))
else: else:
textCtrl = wx.TextCtrl(self.scrollbarPanel, value=str(setting.value), size=(50, -1)) textCtrl = wx.TextCtrl(self.scrollbarPanel, value = str(setting.value), size = (50, -1))
textCtrl.SetName(craftName + '.' + setting.name) textCtrl.SetName(craftName + '.' + setting.name)
settingSizer.Add(textCtrl, pos=(settingRow, 1)) settingSizer.Add(textCtrl, pos = (settingRow, 1))
craftStaticBoxSizer.Add(settingSizer, 1, wx.EXPAND, 0) craftStaticBoxSizer.Add(settingSizer, 1, wx.EXPAND, 0)
settingRow += 1 settingRow += 1
col = settingsRow % 2 col = settingsRow % 2
settingsSizer.Add(craftStaticBoxSizer, pos=(settingsRow - col, col)) settingsSizer.Add(craftStaticBoxSizer, pos = (settingsRow - col, col))
settingsRow += 1 settingsRow += 1
return settingsSizer return settingsSizer
......
...@@ -11,7 +11,7 @@ import shutil ...@@ -11,7 +11,7 @@ import shutil
class MyFrame(wx.Frame): class MyFrame(wx.Frame):
def __init__(self, parent, mysize): def __init__(self, parent, mysize):
wx.Frame.__init__(self, parent, wx.ID_ANY, size=mysize) wx.Frame.__init__(self, parent, wx.ID_ANY, size = mysize)
self.SetBackgroundColour('black') self.SetBackgroundColour('black')
# milliseconds per frame # milliseconds per frame
...@@ -49,7 +49,7 @@ class MyFrame(wx.Frame): ...@@ -49,7 +49,7 @@ class MyFrame(wx.Frame):
if self.mytmpdir: if self.mytmpdir:
shutil.rmtree(self.mytmpdir) shutil.rmtree(self.mytmpdir)
def onPaint(self, event=None): def onPaint(self, event = None):
# this is the wxPython drawing surface/canvas # this is the wxPython drawing surface/canvas
dc = wx.PaintDC(self) dc = wx.PaintDC(self)
while self.loops: while self.loops:
...@@ -59,7 +59,7 @@ class MyFrame(wx.Frame): ...@@ -59,7 +59,7 @@ class MyFrame(wx.Frame):
w, h = bmp.GetSize() w, h = bmp.GetSize()
info = "%s %dx%d" % (self.name_list[ix], w, h) info = "%s %dx%d" % (self.name_list[ix], w, h)
self.SetTitle(info) self.SetTitle(info)
#self.SetSize((w,h)) #self.SetSize((w, h))
# draw the image # draw the image
dc.DrawBitmap(bmp, 0, 0, True) dc.DrawBitmap(bmp, 0, 0, True)
wx.MilliSleep(self.delay) wx.MilliSleep(self.delay)
......
...@@ -66,10 +66,10 @@ class BufferedCanvas(wx.Panel): ...@@ -66,10 +66,10 @@ class BufferedCanvas(wx.Panel):
def __init__(self, def __init__(self,
parent, parent,
ID=-1, ID=-1,
pos=wx.DefaultPosition, pos = wx.DefaultPosition,
size=wx.DefaultSize, size = wx.DefaultSize,
style=wx.NO_FULL_REPAINT_ON_RESIZE|wx.WANTS_CHARS): style = wx.NO_FULL_REPAINT_ON_RESIZE|wx.WANTS_CHARS):
wx.Panel.__init__(self,parent,ID,pos,size,style) wx.Panel.__init__(self, parent, ID, pos, size, style)
# Bind events # Bind events
self.Bind(wx.EVT_PAINT, self.onPaint) self.Bind(wx.EVT_PAINT, self.onPaint)
...@@ -83,7 +83,7 @@ class BufferedCanvas(wx.Panel): ...@@ -83,7 +83,7 @@ class BufferedCanvas(wx.Panel):
## General methods ## General methods
## ##
def draw(self,dc): def draw(self, dc):
""" """
Stub: called when the canvas needs to be re-drawn. Stub: called when the canvas needs to be re-drawn.
""" """
...@@ -96,7 +96,7 @@ class BufferedCanvas(wx.Panel): ...@@ -96,7 +96,7 @@ class BufferedCanvas(wx.Panel):
self.Refresh() self.Refresh()
def getWidthHeight(self): def getWidthHeight(self):
width,height = self.GetClientSizeTuple() width, height = self.GetClientSizeTuple()
if width == 0: if width == 0:
width = 1 width = 1
if height == 0: if height == 0:
......
...@@ -2,36 +2,36 @@ ...@@ -2,36 +2,36 @@
#Interactive RepRap e axis calibration program #Interactive RepRap e axis calibration program
#(C) Nathan Zadoks 2011 #(C) Nathan Zadoks 2011
#Licensed under CC-BY-SA or GPLv2 and higher - Pick your poison. #Licensed under CC-BY-SA or GPLv2 and higher - Pick your poison.
s=300 #Extrusion speed (mm/min) s = 300 #Extrusion speed (mm/min)
n=100 #Default length to extrude n = 100 #Default length to extrude
m= 0 #User-entered measured extrusion length m= 0 #User-entered measured extrusion length
k=300 #Default amount of steps per mm k = 300 #Default amount of steps per mm
port='/dev/ttyUSB0' #Default serial port to connect to printer port='/dev/ttyUSB0' #Default serial port to connect to printer
temp=210 #Default extrusion temperature temp = 210 #Default extrusion temperature
tempmax=250 #Maximum extrusion temperature tempmax = 250 #Maximum extrusion temperature
t=int(n*60)/s #Time to wait for extrusion t = int(n*60)/s #Time to wait for extrusion
try: try:
from printdummy import printcore from printdummy import printcore
except ImportError: except ImportError:
from printcore import printcore from printcore import printcore
import time,getopt,sys,os import time, getopt, sys, os
def float_input(prompt=''): def float_input(prompt=''):
import sys import sys
f=None f = None
while f==None: while f == None:
s=raw_input(prompt) s = raw_input(prompt)
try: try:
f=float(s) f = float(s)
except ValueError: except ValueError:
sys.stderr.write("Not a valid floating-point number.\n") sys.stderr.write("Not a valid floating-point number.\n")
sys.stderr.flush() sys.stderr.flush()
return f return f
def wait(t,m=''): def wait(t, m=''):
import time,sys import time, sys
sys.stdout.write(m+'['+(' '*t)+']\r'+m+'[') sys.stdout.write(m+'['+(' '*t)+']\r'+m+'[')
sys.stdout.flush() sys.stdout.flush()
for i in range(t): for i in range(t):
...@@ -45,19 +45,19 @@ def w(s): ...@@ -45,19 +45,19 @@ def w(s):
sys.stdout.flush() sys.stdout.flush()
def heatup(p,temp,s=0): def heatup(p, temp, s = 0):
curtemp=gettemp(p) curtemp = gettemp(p)
p.send_now('M109 S%03d'%temp) p.send_now('M109 S%03d'%temp)
p.temp=0 p.temp = 0
if not s: w("Heating extruder up..") if not s: w("Heating extruder up..")
f=False f = False
while curtemp<=(temp-1): while curtemp<=(temp-1):
p.send_now('M105') p.send_now('M105')
time.sleep(0.5) time.sleep(0.5)
if not f: if not f:
time.sleep(1.5) time.sleep(1.5)
f=True f = True
curtemp=gettemp(p) curtemp = gettemp(p)
if curtemp: w(u"\rHeating extruder up.. %3d \xb0C"%curtemp) if curtemp: w(u"\rHeating extruder up.. %3d \xb0C"%curtemp)
if s: print if s: print
else: print "\nReady." else: print "\nReady."
...@@ -67,47 +67,47 @@ def gettemp(p): ...@@ -67,47 +67,47 @@ def gettemp(p):
except: setattr(p,'logl',0) except: setattr(p,'logl',0)
try: p.temp try: p.temp
except: setattr(p,'temp',0) except: setattr(p,'temp',0)
for n in range(p.logl,len(p.log)): for n in range(p.logl, len(p.log)):
line=p.log[n] line = p.log[n]
if 'T:' in line: if 'T:' in line:
try: try:
setattr(p,'temp',int(line.split('T:')[1].split()[0])) setattr(p,'temp',int(line.split('T:')[1].split()[0]))
except: print line except: print line
p.logl=len(p.log) p.logl = len(p.log)
return p.temp return p.temp
if not os.path.exists(port): if not os.path.exists(port):
port=0 port = 0
#Parse options #Parse options
help=u""" help = u"""
%s [ -l DISTANCE ] [ -s STEPS ] [ -t TEMP ] [ -p PORT ] %s [ -l DISTANCE ] [ -s STEPS ] [ -t TEMP ] [ -p PORT ]
-l --length Length of filament to extrude for each calibration step (default: %d mm) -l --length Length of filament to extrude for each calibration step (default: %d mm)
-s --steps Initial amount of steps to use (default: %d steps) -s --steps Initial amount of steps to use (default: %d steps)
-t --temp Extrusion temperature in degrees Celsius (default: %d \xb0C, max %d \xb0C) -t --temp Extrusion temperature in degrees Celsius (default: %d \xb0C, max %d \xb0C)
-p --port Serial port the printer is connected to (default: %s) -p --port Serial port the printer is connected to (default: %s)
-h --help This cruft. -h --help This cruft.
"""[1:-1].encode('utf-8')%(sys.argv[0],n,k,temp,tempmax,port if port else 'auto') """[1:-1].encode('utf-8')%(sys.argv[0],n, k,temp, tempmax, port if port else 'auto')
try: try:
opts,args=getopt.getopt(sys.argv[1:],"hl:s:t:p:",["help","length=","steps=","temp=","port="]) opts, args = getopt.getopt(sys.argv[1:],"hl:s:t:p:",["help","length = ","steps = ","temp = ","port = "])
except getopt.GetoptError,err: except getopt.GetoptError, err:
print str(err) print str(err)
print help print help
sys.exit(2) sys.exit(2)
for o,a in opts: for o, a in opts:
if o in ('-h','--help'): if o in ('-h','--help'):
print help print help
sys.exit() sys.exit()
elif o in ('-l','--length'): elif o in ('-l','--length'):
n=float(a) n = float(a)
elif o in ('-s','--steps'): elif o in ('-s','--steps'):
k=int(a) k = int(a)
elif o in ('-t','--temp'): elif o in ('-t','--temp'):
temp=int(a) temp = int(a)
if temp>=tempmax: if temp>=tempmax:
print (u'%d \xb0C? Are you insane?'.encode('utf-8')%temp)+(" That's over nine thousand!" if temp>9000 else '') print (u'%d \xb0C? Are you insane?'.encode('utf-8')%temp)+(" That's over nine thousand!" if temp>9000 else '')
sys.exit(255) sys.exit(255)
elif o in ('-p','--port'): elif o in ('-p','--port'):
port=a port = a
#Show initial parameters #Show initial parameters
print "Initial parameters" print "Initial parameters"
...@@ -116,12 +116,12 @@ print "Length extruded: %3d mm"%n ...@@ -116,12 +116,12 @@ print "Length extruded: %3d mm"%n
print print
print "Serial port: %s"%(port if port else 'auto') print "Serial port: %s"%(port if port else 'auto')
p=None p = None
try: try:
#Connect to printer #Connect to printer
w("Connecting to printer..") w("Connecting to printer..")
try: try:
p=printcore(port,115200) p = printcore(port, 115200)
except: except:
print 'Error.' print 'Error.'
raise raise
...@@ -130,18 +130,18 @@ try: ...@@ -130,18 +130,18 @@ try:
w('.') w('.')
print " connected." print " connected."
heatup(p,temp) heatup(p, temp)
#Calibration loop #Calibration loop
while n!=m: while n!=m:
heatup(p,temp,True) heatup(p, temp, True)
p.send_now("G92 E0") #Reset e axis p.send_now("G92 E0") #Reset e axis
p.send_now("G1 E%d F%d"%(n,s)) #Extrude length of filament p.send_now("G1 E%d F%d"%(n, s)) #Extrude length of filament
wait(t,'Extruding.. ') wait(t,'Extruding.. ')
m=float_input("How many millimeters of filament were extruded? ") m = float_input("How many millimeters of filament were extruded? ")
if m==0: continue if m == 0: continue
if n!=m: if n!=m:
k=(n/m)*k k = (n/m)*k
p.send_now("M92 E%d"%int(round(k))) #Set new step count p.send_now("M92 E%d"%int(round(k))) #Set new step count
print "Steps per mm: %3d steps"%k #Tell user print "Steps per mm: %3d steps"%k #Tell user
print 'Calibration completed.' #Yay! print 'Calibration completed.' #Yay!
......
...@@ -19,8 +19,8 @@ import threading ...@@ -19,8 +19,8 @@ import threading
class GLPanel(wx.Panel): class GLPanel(wx.Panel):
'''A simple class for using OpenGL with wxPython.''' '''A simple class for using OpenGL with wxPython.'''
def __init__(self, parent, id, pos=wx.DefaultPosition, def __init__(self, parent, id, pos = wx.DefaultPosition,
size=wx.DefaultSize, style=0): size = wx.DefaultSize, style = 0):
# Forcing a no full repaint to stop flickering # Forcing a no full repaint to stop flickering
style = style | wx.NO_FULL_REPAINT_ON_RESIZE style = style | wx.NO_FULL_REPAINT_ON_RESIZE
#call super function #call super function
...@@ -33,7 +33,7 @@ class GLPanel(wx.Panel): ...@@ -33,7 +33,7 @@ class GLPanel(wx.Panel):
glcanvas.WX_GL_DEPTH_SIZE, 24) # 24 bit glcanvas.WX_GL_DEPTH_SIZE, 24) # 24 bit
# Create the canvas # Create the canvas
self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.canvas = glcanvas.GLCanvas(self, attribList=attribList) self.canvas = glcanvas.GLCanvas(self, attribList = attribList)
self.sizer.Add(self.canvas, 1, wx.EXPAND) self.sizer.Add(self.canvas, 1, wx.EXPAND)
self.SetSizer(self.sizer) self.SetSizer(self.sizer)
#self.sizer.Fit(self) #self.sizer.Fit(self)
...@@ -200,7 +200,7 @@ def _dist(dist): ...@@ -200,7 +200,7 @@ def _dist(dist):
class gcpoint(object): class gcpoint(object):
"""gcode point """gcode point
stub for first line""" stub for first line"""
def __init__(self, x=0,y=0,z=0,e=0): def __init__(self, x = 0, y = 0, z = 0, e = 0):
self.x = x self.x = x
self.y = y self.y = y
self.z = z self.z = z
...@@ -210,10 +210,10 @@ class gcpoint(object): ...@@ -210,10 +210,10 @@ class gcpoint(object):
class gcline(object): class gcline(object):
"""gcode move line """gcode move line
Once initialised,it knows its position, length and extrusion ratio Once initialised, it knows its position, length and extrusion ratio
Returns lines into gcview batch() Returns lines into gcview batch()
""" """
def __init__(self, x=None, y=None, z=None, e=None, f=None, prev_gcline=None, orgline = False): def __init__(self, x = None, y = None, z = None, e = None, f = None, prev_gcline = None, orgline = False):
if prev_gcline is None: if prev_gcline is None:
self.prev_gcline = gcpoint() self.prev_gcline = gcpoint()
else: else:
...@@ -255,7 +255,7 @@ class gcline(object): ...@@ -255,7 +255,7 @@ class gcline(object):
self.orgline, self.orgline,
) )
def calc_delta(self, prev_gcline=None): def calc_delta(self, prev_gcline = None):
if prev_gcline is None: if prev_gcline is None:
prev_gcline = self.prev_gcline prev_gcline = self.prev_gcline
if self.prev_gcline is not None: if self.prev_gcline is not None:
...@@ -290,7 +290,7 @@ class gcline(object): ...@@ -290,7 +290,7 @@ class gcline(object):
] ]
def glcolor(self, upper_limit = None, lower_limit = 0, max_feedrate = 0): def glcolor(self, upper_limit = None, lower_limit = 0, max_feedrate = 0):
if self.extrusion_ratio == 0: if self.extrusion_ratio == 0:
return [255,255,255,0,0,0] return [255, 255, 255, 0,0, 0]
else: else:
blue_color = 0 blue_color = 0
green_color = 0 green_color = 0
...@@ -312,7 +312,7 @@ class gcline(object): ...@@ -312,7 +312,7 @@ class gcline(object):
blue_color = 255 blue_color = 255
if blue_color < 0: if blue_color < 0:
blue_color = 0 blue_color = 0
return[255,green_color,blue_color,128,green_color,blue_color/4] return[255, green_color, blue_color, 128, green_color, blue_color/4]
def float_from_line(axe, line): def float_from_line(axe, line):
...@@ -340,7 +340,7 @@ class gcview(object): ...@@ -340,7 +340,7 @@ class gcview(object):
"""gcode visualiser """gcode visualiser
Holds opengl objects for all layers Holds opengl objects for all layers
""" """
def __init__(self, lines, batch, w=0.5, h=0.5): def __init__(self, lines, batch, w = 0.5, h = 0.5):
if len(lines) == 0: if len(lines) == 0:
return return
print "Loading %s lines" % (len(lines)) print "Loading %s lines" % (len(lines))
...@@ -430,7 +430,7 @@ class gcview(object): ...@@ -430,7 +430,7 @@ class gcview(object):
else: else:
self.lastf = cur[4] self.lastf = cur[4]
r = gcline(x=cur[0], y=cur[1], z=cur[2],e=cur[3], f=cur[4], prev_gcline=self.prev, orgline=orgline) r = gcline(x = cur[0], y = cur[1], z = cur[2],e = cur[3], f = cur[4], prev_gcline = self.prev, orgline = orgline)
self.prev = r self.prev = r
return r return r
return None return None
...@@ -524,7 +524,7 @@ def mulquat(q1, rq): ...@@ -524,7 +524,7 @@ def mulquat(q1, rq):
class TestGlPanel(GLPanel): class TestGlPanel(GLPanel):
def __init__(self, parent, size, id=wx.ID_ANY): def __init__(self, parent, size, id = wx.ID_ANY):
super(TestGlPanel, self).__init__(parent, id, wx.DefaultPosition, size, 0) super(TestGlPanel, self).__init__(parent, id, wx.DefaultPosition, size, 0)
self.batches = [] self.batches = []
self.rot = 0 self.rot = 0
...@@ -553,7 +553,7 @@ class TestGlPanel(GLPanel): ...@@ -553,7 +553,7 @@ class TestGlPanel(GLPanel):
def forceresize(self): def forceresize(self):
self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1)) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1))
self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] - 1)) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] - 1))
threading.Thread(target=self.update).start() threading.Thread(target = self.update).start()
self.initialized = 0 self.initialized = 0
def move_shape(self, delta): def move_shape(self, delta):
...@@ -605,7 +605,7 @@ class TestGlPanel(GLPanel): ...@@ -605,7 +605,7 @@ class TestGlPanel(GLPanel):
p1y = -(float(p1[1]) - sz[1] / 2) / (sz[1] / 2) p1y = -(float(p1[1]) - sz[1] / 2) / (sz[1] / 2)
p2x = (float(p2[0]) - sz[0] / 2) / (sz[0] / 2) p2x = (float(p2[0]) - sz[0] / 2) / (sz[0] / 2)
p2y = -(float(p2[1]) - sz[1] / 2) / (sz[1] / 2) p2y = -(float(p2[1]) - sz[1] / 2) / (sz[1] / 2)
#print p1x,p1y,p2x,p2y #print p1x, p1y, p2x, p2y
quat = trackball(p1x, p1y, p2x, p2y, -self.transv[2] / 250.0) quat = trackball(p1x, p1y, p2x, p2y, -self.transv[2] / 250.0)
if self.rot: if self.rot:
self.basequat = mulquat(self.basequat, quat) self.basequat = mulquat(self.basequat, quat)
...@@ -768,7 +768,7 @@ class TestGlPanel(GLPanel): ...@@ -768,7 +768,7 @@ class TestGlPanel(GLPanel):
def drawmodel(self, m, n): def drawmodel(self, m, n):
batch = pyglet.graphics.Batch() batch = pyglet.graphics.Batch()
stl = stlview(m.facets, batch=batch) stl = stlview(m.facets, batch = batch)
m.batch = batch m.batch = batch
m.animoffset = 300 m.animoffset = 300
#print m #print m
...@@ -907,8 +907,8 @@ class TestGlPanel(GLPanel): ...@@ -907,8 +907,8 @@ class TestGlPanel(GLPanel):
class GCFrame(wx.Frame): class GCFrame(wx.Frame):
'''A simple class for using OpenGL with wxPython.''' '''A simple class for using OpenGL with wxPython.'''
def __init__(self, parent, ID, title, pos=wx.DefaultPosition, def __init__(self, parent, ID, title, pos = wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE): size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE):
super(GCFrame, self).__init__(parent, ID, title, pos, (size[0] + 150, size[1]), style) super(GCFrame, self).__init__(parent, ID, title, pos, (size[0] + 150, size[1]), style)
class d: class d:
...@@ -921,7 +921,7 @@ class GCFrame(wx.Frame): ...@@ -921,7 +921,7 @@ class GCFrame(wx.Frame):
m.curlayer = -1 m.curlayer = -1
m.scale = [1.0, 1.0, 1.0] m.scale = [1.0, 1.0, 1.0]
m.batch = pyglet.graphics.Batch() m.batch = pyglet.graphics.Batch()
m.gc = gcview([], batch=m.batch) m.gc = gcview([], batch = m.batch)
self.models = {"GCODE": m} self.models = {"GCODE": m}
self.l = d() self.l = d()
self.modelindex = 0 self.modelindex = 0
...@@ -929,14 +929,14 @@ class GCFrame(wx.Frame): ...@@ -929,14 +929,14 @@ class GCFrame(wx.Frame):
def addfile(self, gcode=[]): def addfile(self, gcode=[]):
self.models["GCODE"].gc.delete() self.models["GCODE"].gc.delete()
self.models["GCODE"].gc = gcview(gcode, batch=self.models["GCODE"].batch) self.models["GCODE"].gc = gcview(gcode, batch = self.models["GCODE"].batch)
self.setlayerindex(None) self.setlayerindex(None)
def clear(self): def clear(self):
self.models["GCODE"].gc.delete() self.models["GCODE"].gc.delete()
self.models["GCODE"].gc = gcview([], batch=self.models["GCODE"].batch) self.models["GCODE"].gc = gcview([], batch = self.models["GCODE"].batch)
def Show(self, arg=True): def Show(self, arg = True):
wx.Frame.Show(self, arg) wx.Frame.Show(self, arg)
self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1)) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1))
self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] - 1)) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] - 1))
...@@ -975,8 +975,8 @@ class GCFrame(wx.Frame): ...@@ -975,8 +975,8 @@ class GCFrame(wx.Frame):
def main(): def main():
app = wx.App(redirect=False) app = wx.App(redirect = False)
frame = GCFrame(None, wx.ID_ANY, 'Gcode view, shift to move view, mousewheel to set layer', size=(400, 400)) frame = GCFrame(None, wx.ID_ANY, 'Gcode view, shift to move view, mousewheel to set layer', size = (400, 400))
import sys import sys
for filename in sys.argv: for filename in sys.argv:
if ".gcode" in filename: if ".gcode" in filename:
...@@ -985,8 +985,8 @@ def main(): ...@@ -985,8 +985,8 @@ def main():
#TODO: add stl here #TODO: add stl here
pass pass
#frame = wx.Frame(None, -1, "GL Window", size=(400, 400)) #frame = wx.Frame(None, -1, "GL Window", size = (400, 400))
#panel = TestGlPanel(frame, size=(300,300)) #panel = TestGlPanel(frame, size = (300, 300))
frame.Show(True) frame.Show(True)
app.MainLoop() app.MainLoop()
app.Destroy() app.Destroy()
......
...@@ -22,8 +22,8 @@ from bufferedcanvas import * ...@@ -22,8 +22,8 @@ from bufferedcanvas import *
class Graph(BufferedCanvas): class Graph(BufferedCanvas):
'''A class to show a Graph with Pronterface.''' '''A class to show a Graph with Pronterface.'''
def __init__(self, parent, id, pos=wx.DefaultPosition, def __init__(self, parent, id, pos = wx.DefaultPosition,
size=wx.DefaultSize, style=0): size = wx.DefaultSize, style = 0):
# Forcing a no full repaint to stop flickering # Forcing a no full repaint to stop flickering
style = style | wx.NO_FULL_REPAINT_ON_RESIZE style = style | wx.NO_FULL_REPAINT_ON_RESIZE
#call super function #call super function
...@@ -53,7 +53,7 @@ class Graph(BufferedCanvas): ...@@ -53,7 +53,7 @@ class Graph(BufferedCanvas):
#self.sizer = wx.BoxSizer(wx.HORIZONTAL) #self.sizer = wx.BoxSizer(wx.HORIZONTAL)
#self.sizer.Add(wx.Button(self, -1, "Button1", (0,0))) #self.sizer.Add(wx.Button(self, -1, "Button1", (0, 0)))
#self.SetSizer(self.sizer) #self.SetSizer(self.sizer)
...@@ -78,23 +78,23 @@ class Graph(BufferedCanvas): ...@@ -78,23 +78,23 @@ class Graph(BufferedCanvas):
def drawgrid(self, dc, gc): def drawgrid(self, dc, gc):
#cold,medium,hot = wx.Colour(0,167,223),wx.Colour(239,233,119),wx.Colour(210,50.100) #cold, medium, hot = wx.Colour(0, 167, 223),wx.Colour(239, 233, 119),wx.Colour(210, 50.100)
#col1 = wx.Colour(255,0,0, 255) #col1 = wx.Colour(255, 0,0, 255)
#col2 = wx.Colour(255,255,255, 128) #col2 = wx.Colour(255, 255, 255, 128)
#b = gc.CreateLinearGradientBrush(0, 0, w, h, col1, col2) #b = gc.CreateLinearGradientBrush(0, 0, w, h, col1, col2)
gc.SetPen(wx.Pen(wx.Colour(255,0,0,0), 4)) gc.SetPen(wx.Pen(wx.Colour(255, 0,0, 0), 4))
#gc.SetBrush(gc.CreateBrush(wx.Brush(wx.Colour(245,245,255,252)))) #gc.SetBrush(gc.CreateBrush(wx.Brush(wx.Colour(245, 245, 255, 252))))
#gc.SetBrush(b) #gc.SetBrush(b)
gc.DrawRectangle(0, 0, self.width, self.height) gc.DrawRectangle(0, 0, self.width, self.height)
#gc.SetBrush(wx.Brush(wx.Colour(245,245,255,52))) #gc.SetBrush(wx.Brush(wx.Colour(245, 245, 255, 52)))
#gc.SetBrush(gc.CreateBrush(wx.Brush(wx.Colour(0,0,0,255)))) #gc.SetBrush(gc.CreateBrush(wx.Brush(wx.Colour(0, 0,0, 255))))
#gc.SetPen(wx.Pen(wx.Colour(255,0,0,0), 4)) #gc.SetPen(wx.Pen(wx.Colour(255, 0,0, 0), 4))
#gc.DrawLines(wx.Point(0,0), wx.Point(50,10)) #gc.DrawLines(wx.Point(0, 0), wx.Point(50, 10))
#path = gc.CreatePath() #path = gc.CreatePath()
#path.MoveToPoint(0.0, 0.0) #path.MoveToPoint(0.0, 0.0)
...@@ -107,34 +107,34 @@ class Graph(BufferedCanvas): ...@@ -107,34 +107,34 @@ class Graph(BufferedCanvas):
font = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD) font = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD)
gc.SetFont(font, wx.Colour(23,44,44)) gc.SetFont(font, wx.Colour(23, 44, 44))
dc.SetPen(wx.Pen(wx.Colour(225,225,225), 1)) dc.SetPen(wx.Pen(wx.Colour(225, 225, 225), 1))
for x in range(self.xbars): for x in range(self.xbars):
dc.DrawLine(x*(float(self.width)/self.xbars), 0, x*(float(self.width)/self.xbars), self.height) dc.DrawLine(x*(float(self.width)/self.xbars), 0, x*(float(self.width)/self.xbars), self.height)
dc.SetPen(wx.Pen(wx.Colour(225,225,225), 1)) dc.SetPen(wx.Pen(wx.Colour(225, 225, 225), 1))
for y in range(self.ybars): for y in range(self.ybars):
y_pos = y*(float(self.height)/self.ybars) y_pos = y*(float(self.height)/self.ybars)
dc.DrawLine(0,y_pos, self.width,y_pos) dc.DrawLine(0, y_pos, self.width, y_pos)
gc.DrawText(unicode(int(self.maxyvalue - (y * (self.maxyvalue/self.ybars)))), 1, y_pos - (font.GetPointSize() / 2)) gc.DrawText(unicode(int(self.maxyvalue - (y * (self.maxyvalue/self.ybars)))), 1, y_pos - (font.GetPointSize() / 2))
if self.timer.IsRunning() == False: if self.timer.IsRunning() == False:
font = wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.BOLD) font = wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.BOLD)
gc.SetFont(font, wx.Colour(3,4,4)) gc.SetFont(font, wx.Colour(3, 4,4))
gc.DrawText("Graph offline", self.width/2 - (font.GetPointSize() * 3), self.height/2 - (font.GetPointSize() * 1)) gc.DrawText("Graph offline", self.width/2 - (font.GetPointSize() * 3), self.height/2 - (font.GetPointSize() * 1))
#dc.DrawCircle(50,50, 1) #dc.DrawCircle(50, 50, 1)
#gc.SetPen(wx.Pen(wx.Colour(255,0,0,0), 1)) #gc.SetPen(wx.Pen(wx.Colour(255, 0,0, 0), 1))
#gc.DrawLines([[20,30], [10,53]]) #gc.DrawLines([[20, 30], [10, 53]])
#dc.SetPen(wx.Pen(wx.Colour(255,0,0,0), 1)) #dc.SetPen(wx.Pen(wx.Colour(255, 0,0, 0), 1))
def drawtemperature(self, dc, gc, temperature_list, text, text_xoffset, r, g, b, a): def drawtemperature(self, dc, gc, temperature_list, text, text_xoffset, r, g, b, a):
if self.timer.IsRunning() == False: if self.timer.IsRunning() == False:
dc.SetPen(wx.Pen(wx.Colour(128,128,128,128), 1)) dc.SetPen(wx.Pen(wx.Colour(128, 128, 128, 128), 1))
else: else:
dc.SetPen(wx.Pen(wx.Colour(r,g,b,a), 1)) dc.SetPen(wx.Pen(wx.Colour(r, g,b, a), 1))
x_add = float(self.width)/self.xsteps x_add = float(self.width)/self.xsteps
x_pos = float(0.0) x_pos = float(0.0)
...@@ -143,7 +143,7 @@ class Graph(BufferedCanvas): ...@@ -143,7 +143,7 @@ class Graph(BufferedCanvas):
for temperature in (temperature_list): for temperature in (temperature_list):
y_pos = int((float(self.height-self.y_offset)/self.maxyvalue)*temperature) + self.y_offset y_pos = int((float(self.height-self.y_offset)/self.maxyvalue)*temperature) + self.y_offset
if (x_pos > 0.0): # One need 2 points to draw a line. if (x_pos > 0.0): # One need 2 points to draw a line.
dc.DrawLine(lastxvalue,self.height-self._lastyvalue, x_pos, self.height-y_pos) dc.DrawLine(lastxvalue, self.height-self._lastyvalue, x_pos, self.height-y_pos)
lastxvalue = x_pos lastxvalue = x_pos
x_pos = float(x_pos) + x_add x_pos = float(x_pos) + x_add
...@@ -153,9 +153,9 @@ class Graph(BufferedCanvas): ...@@ -153,9 +153,9 @@ class Graph(BufferedCanvas):
font = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD) font = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD)
#font = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.NORMAL) #font = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
if self.timer.IsRunning() == False: if self.timer.IsRunning() == False:
gc.SetFont(font, wx.Colour(128,128,128)) gc.SetFont(font, wx.Colour(128, 128, 128))
else: else:
gc.SetFont(font, wx.Colour(r,g,b)) gc.SetFont(font, wx.Colour(r, g,b))
#gc.DrawText(text, self.width - (font.GetPointSize() * ((len(text) * text_xoffset + 1))), self.height - self._lastyvalue - (font.GetPointSize() / 2)) #gc.DrawText(text, self.width - (font.GetPointSize() * ((len(text) * text_xoffset + 1))), self.height - self._lastyvalue - (font.GetPointSize() / 2))
gc.DrawText(text, x_pos - x_add - (font.GetPointSize() * ((len(text) * text_xoffset + 1))), self.height - self._lastyvalue - (font.GetPointSize() / 2)) gc.DrawText(text, x_pos - x_add - (font.GetPointSize() * ((len(text) * text_xoffset + 1))), self.height - self._lastyvalue - (font.GetPointSize() / 2))
...@@ -163,24 +163,24 @@ class Graph(BufferedCanvas): ...@@ -163,24 +163,24 @@ class Graph(BufferedCanvas):
def drawbedtemp(self, dc, gc): def drawbedtemp(self, dc, gc):
self.drawtemperature(dc, gc, self.bedtemps, "Bed",2, 255,0,0, 128) self.drawtemperature(dc, gc, self.bedtemps, "Bed",2, 255, 0,0, 128)
def drawbedtargettemp(self, dc, gc): def drawbedtargettemp(self, dc, gc):
self.drawtemperature(dc, gc, self.bedtargettemps, "Bed Target",2, 255,120,0, 128) self.drawtemperature(dc, gc, self.bedtargettemps, "Bed Target",2, 255, 120, 0, 128)
def drawextruder0temp(self, dc, gc): def drawextruder0temp(self, dc, gc):
self.drawtemperature(dc, gc, self.extruder0temps, "Ex0",1, 0,155,255, 128) self.drawtemperature(dc, gc, self.extruder0temps, "Ex0",1, 0, 155, 255, 128)
def drawextruder0targettemp(self, dc, gc): def drawextruder0targettemp(self, dc, gc):
self.drawtemperature(dc, gc, self.extruder0targettemps, "Ex0 Target",2, 0,5,255, 128) self.drawtemperature(dc, gc, self.extruder0targettemps, "Ex0 Target",2, 0, 5,255, 128)
def drawextruder1temp(self, dc, gc): def drawextruder1temp(self, dc, gc):
self.drawtemperature(dc, gc, self.extruder1temps, "Ex1",3, 55,55,0, 128) self.drawtemperature(dc, gc, self.extruder1temps, "Ex1",3, 55, 55, 0, 128)
def drawextruder1targettemp(self, dc, gc): def drawextruder1targettemp(self, dc, gc):
self.drawtemperature(dc, gc, self.extruder1targettemps, "Ex1 Target",2, 55,55,0, 128) self.drawtemperature(dc, gc, self.extruder1targettemps, "Ex1 Target",2, 55, 55, 0, 128)
def SetBedTemperature(self, value): def SetBedTemperature(self, value):
......
...@@ -12,45 +12,45 @@ ...@@ -12,45 +12,45 @@
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>. # along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import wx,time import wx, time
from printrun_utils import imagefile from printrun_utils import imagefile
ID_ABOUT = 101 ID_ABOUT = 101
ID_EXIT = 110 ID_EXIT = 110
class window(wx.Frame): class window(wx.Frame):
def __init__(self,f,size=(600,600),build_dimensions=[200,200,100,0,0,0],grid=(10,50),extrusion_width=0.5): def __init__(self, f,size = (600, 600),build_dimensions=[200, 200, 100, 0,0, 0],grid = (10, 50),extrusion_width = 0.5):
wx.Frame.__init__(self,None,title="Gcode view, shift to move view, mousewheel to set layer",size=(size[0],size[1])) wx.Frame.__init__(self, None, title = "Gcode view, shift to move view, mousewheel to set layer",size = (size[0],size[1]))
self.p=gviz(self,size=size,build_dimensions=build_dimensions,grid=grid,extrusion_width=extrusion_width) self.p = gviz(self, size = size, build_dimensions = build_dimensions, grid = grid, extrusion_width = extrusion_width)
vbox = wx.BoxSizer(wx.VERTICAL) vbox = wx.BoxSizer(wx.VERTICAL)
toolbar = wx.ToolBar(self, -1, style=wx.TB_HORIZONTAL | wx.NO_BORDER) toolbar = wx.ToolBar(self, -1, style = wx.TB_HORIZONTAL | wx.NO_BORDER)
toolbar.AddSimpleTool(1, wx.Image(imagefile('zoom_in.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Zoom In [+]', '') toolbar.AddSimpleTool(1, wx.Image(imagefile('zoom_in.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Zoom In [+]', '')
toolbar.AddSimpleTool(2, wx.Image(imagefile('zoom_out.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Zoom Out [-]', '') toolbar.AddSimpleTool(2, wx.Image(imagefile('zoom_out.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Zoom Out [-]', '')
toolbar.AddSeparator() toolbar.AddSeparator()
toolbar.AddSimpleTool(3, wx.Image(imagefile('arrow_up.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Move Up a Layer [U]', '') toolbar.AddSimpleTool(3, wx.Image(imagefile('arrow_up.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Move Up a Layer [U]', '')
toolbar.AddSimpleTool(4, wx.Image(imagefile('arrow_down.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Move Down a Layer [D]', '') toolbar.AddSimpleTool(4, wx.Image(imagefile('arrow_down.png'), wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Move Down a Layer [D]', '')
toolbar.AddSimpleTool(5, wx.EmptyBitmap(16,16), 'Reset view', '') toolbar.AddSimpleTool(5, wx.EmptyBitmap(16, 16), 'Reset view', '')
toolbar.AddSeparator() toolbar.AddSeparator()
#toolbar.AddSimpleTool(5, wx.Image('./images/inject.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Insert Code at start of this layer', '') #toolbar.AddSimpleTool(5, wx.Image('./images/inject.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'Insert Code at start of this layer', '')
toolbar.Realize() toolbar.Realize()
vbox.Add(toolbar, 0, border=5) vbox.Add(toolbar, 0, border = 5)
self.SetSizer(vbox) self.SetSizer(vbox)
self.Bind(wx.EVT_TOOL, lambda x:self.p.zoom(200,200,1.2), id=1) self.Bind(wx.EVT_TOOL, lambda x:self.p.zoom(200, 200, 1.2), id = 1)
self.Bind(wx.EVT_TOOL, lambda x:self.p.zoom(200,200,1/1.2), id=2) self.Bind(wx.EVT_TOOL, lambda x:self.p.zoom(200, 200, 1/1.2), id = 2)
self.Bind(wx.EVT_TOOL, lambda x:self.p.layerup(), id=3) self.Bind(wx.EVT_TOOL, lambda x:self.p.layerup(), id = 3)
self.Bind(wx.EVT_TOOL, lambda x:self.p.layerdown(), id=4) self.Bind(wx.EVT_TOOL, lambda x:self.p.layerdown(), id = 4)
self.Bind(wx.EVT_TOOL, self.resetview, id=5) self.Bind(wx.EVT_TOOL, self.resetview, id = 5)
#self.Bind(wx.EVT_TOOL, lambda x:self.p.inject(), id=5) #self.Bind(wx.EVT_TOOL, lambda x:self.p.inject(), id = 5)
self.CreateStatusBar(1); self.CreateStatusBar(1);
self.SetStatusText("Layer number and Z position show here when you scroll"); self.SetStatusText("Layer number and Z position show here when you scroll");
#self.bu=wx.Button(self.p,-1,"U",pos=(0,100),size=(40,140)) #self.bu = wx.Button(self.p,-1,"U",pos = (0, 100),size = (40, 140))
#self.bd=wx.Button(self.p,-1,"D",pos=(0,140),size=(40,140)) #self.bd = wx.Button(self.p,-1,"D",pos = (0, 140),size = (40, 140))
#self.bi=wx.Button(self.p,-1,"+",pos=(40,100),size=(40,140)) #self.bi = wx.Button(self.p,-1,"+",pos = (40, 100),size = (40, 140))
#self.bo=wx.Button(self.p,-1,"-",pos=(40,140),size=(40,140)) #self.bo = wx.Button(self.p,-1,"-",pos = (40, 140),size = (40, 140))
#self.bs=wx.Button(self.p, -1, "Inject", pos=(85, 103), size=(50, 20)) #self.bs = wx.Button(self.p, -1, "Inject", pos = (85, 103), size = (50, 20))
#self.bu.SetToolTip(wx.ToolTip("Move up one layer")) #self.bu.SetToolTip(wx.ToolTip("Move up one layer"))
#self.bd.SetToolTip(wx.ToolTip("Move down one layer")) #self.bd.SetToolTip(wx.ToolTip("Move down one layer"))
...@@ -58,41 +58,41 @@ class window(wx.Frame): ...@@ -58,41 +58,41 @@ class window(wx.Frame):
#self.bo.SetToolTip(wx.ToolTip("Zoom view out")) #self.bo.SetToolTip(wx.ToolTip("Zoom view out"))
#self.bs.SetToolTip(wx.ToolTip("Insert Code at start of this layer")) #self.bs.SetToolTip(wx.ToolTip("Insert Code at start of this layer"))
#self.bu.Bind(wx.EVT_BUTTON,lambda x:self.p.layerup()) #self.bu.Bind(wx.EVT_BUTTON, lambda x:self.p.layerup())
#self.bd.Bind(wx.EVT_BUTTON,lambda x:self.p.layerdown()) #self.bd.Bind(wx.EVT_BUTTON, lambda x:self.p.layerdown())
#self.bi.Bind(wx.EVT_BUTTON,lambda x:self.p.zoom(200,200,1.2)) #self.bi.Bind(wx.EVT_BUTTON, lambda x:self.p.zoom(200, 200, 1.2))
#self.bo.Bind(wx.EVT_BUTTON,lambda x:self.p.zoom(200,200,1/1.2)) #self.bo.Bind(wx.EVT_BUTTON, lambda x:self.p.zoom(200, 200, 1/1.2))
#self.bs.Bind(wx.EVT_BUTTON,lambda x:self.p.inject()) #self.bs.Bind(wx.EVT_BUTTON, lambda x:self.p.inject())
s=time.time() s = time.time()
#print time.time()-s #print time.time()-s
self.initpos=[0,0] self.initpos=[0, 0]
self.p.Bind(wx.EVT_KEY_DOWN,self.key) self.p.Bind(wx.EVT_KEY_DOWN, self.key)
#self.bu.Bind(wx.EVT_KEY_DOWN,self.key) #self.bu.Bind(wx.EVT_KEY_DOWN, self.key)
#self.bd.Bind(wx.EVT_KEY_DOWN,self.key) #self.bd.Bind(wx.EVT_KEY_DOWN, self.key)
#self.bi.Bind(wx.EVT_KEY_DOWN,self.key) #self.bi.Bind(wx.EVT_KEY_DOWN, self.key)
#self.bo.Bind(wx.EVT_KEY_DOWN,self.key) #self.bo.Bind(wx.EVT_KEY_DOWN, self.key)
self.Bind(wx.EVT_KEY_DOWN,self.key) self.Bind(wx.EVT_KEY_DOWN, self.key)
self.p.Bind(wx.EVT_MOUSEWHEEL,self.zoom) self.p.Bind(wx.EVT_MOUSEWHEEL, self.zoom)
self.Bind(wx.EVT_MOUSEWHEEL,self.zoom) self.Bind(wx.EVT_MOUSEWHEEL, self.zoom)
self.p.Bind(wx.EVT_MOUSE_EVENTS,self.mouse) self.p.Bind(wx.EVT_MOUSE_EVENTS, self.mouse)
self.Bind(wx.EVT_MOUSE_EVENTS,self.mouse) self.Bind(wx.EVT_MOUSE_EVENTS, self.mouse)
def resetview(self,event): def resetview(self, event):
self.p.translate=[0.0,0.0] self.p.translate=[0.0, 0.0]
self.p.scale=self.p.basescale self.p.scale = self.p.basescale
self.p.zoom(0,0,1.0) self.p.zoom(0, 0,1.0)
def mouse(self,event): def mouse(self, event):
if event.ButtonUp(wx.MOUSE_BTN_LEFT): if event.ButtonUp(wx.MOUSE_BTN_LEFT):
if(self.initpos is not None): if(self.initpos is not None):
self.initpos=None self.initpos = None
elif event.Dragging(): elif event.Dragging():
e=event.GetPositionTuple() e = event.GetPositionTuple()
if self.initpos is None or not hasattr(self,"basetrans"): if self.initpos is None or not hasattr(self,"basetrans"):
self.initpos=e self.initpos = e
self.basetrans=self.p.translate self.basetrans = self.p.translate
#print self.p.translate,e,self.initpos #print self.p.translate, e,self.initpos
self.p.translate = [ self.basetrans[0]+(e[0]-self.initpos[0]), self.p.translate = [ self.basetrans[0]+(e[0]-self.initpos[0]),
self.basetrans[1]+(e[1]-self.initpos[1]) ] self.basetrans[1]+(e[1]-self.initpos[1]) ]
self.p.repaint() self.p.repaint()
...@@ -107,31 +107,31 @@ class window(wx.Frame): ...@@ -107,31 +107,31 @@ class window(wx.Frame):
kdo=[68, 317] # Down Keys kdo=[68, 317] # Down Keys
kzi=[388, 316, 61] # Zoom In Keys kzi=[388, 316, 61] # Zoom In Keys
kzo=[390, 314, 45] # Zoom Out Keys kzo=[390, 314, 45] # Zoom Out Keys
x=event.GetKeyCode() x = event.GetKeyCode()
#print "Key event - "+str(x) #print "Key event - "+str(x)
#if event.ShiftDown(): #if event.ShiftDown():
cx,cy=self.p.translate cx, cy = self.p.translate
# if x==wx.WXK_UP: # if x == wx.WXK_UP:
# self.p.zoom(cx,cy,1.2) # self.p.zoom(cx, cy, 1.2)
# if x==wx.WXK_DOWN: # if x == wx.WXK_DOWN:
# self.p.zoom(cx,cy,1/1.2) # self.p.zoom(cx, cy, 1/1.2)
#else: #else:
# if x==wx.WXK_UP: # if x == wx.WXK_UP:
# self.p.layerup() # self.p.layerup()
# if x==wx.WXK_DOWN: # if x == wx.WXK_DOWN:
# self.p.layerdown() # self.p.layerdown()
if x in kup: if x in kup:
self.p.layerup() self.p.layerup()
if x in kdo: if x in kdo:
self.p.layerdown() self.p.layerdown()
if x in kzi: if x in kzi:
self.p.zoom(cx,cy,1.2) self.p.zoom(cx, cy, 1.2)
if x in kzo: if x in kzo:
self.p.zoom(cx, cy, 1/1.2) self.p.zoom(cx, cy, 1/1.2)
#print p.lines.keys() #print p.lines.keys()
def zoom(self, event): def zoom(self, event):
z=event.GetWheelRotation() z = event.GetWheelRotation()
if event.ShiftDown(): if event.ShiftDown():
if z > 0: self.p.layerdown() if z > 0: self.p.layerdown()
elif z < 0: self.p.layerup() elif z < 0: self.p.layerup()
...@@ -140,38 +140,38 @@ class window(wx.Frame): ...@@ -140,38 +140,38 @@ class window(wx.Frame):
elif z < 0: self.p.zoom(event.GetX(),event.GetY(),1/1.2) elif z < 0: self.p.zoom(event.GetX(),event.GetY(),1/1.2)
class gviz(wx.Panel): class gviz(wx.Panel):
def __init__(self,parent,size=(200,200),build_dimensions=[200,200,100,0,0,0],grid=(10,50),extrusion_width=0.5): def __init__(self, parent, size = (200, 200),build_dimensions=[200, 200, 100, 0,0, 0],grid = (10, 50),extrusion_width = 0.5):
wx.Panel.__init__(self,parent,-1,size=(size[0],size[1])) wx.Panel.__init__(self, parent,-1, size = (size[0],size[1]))
self.parent=parent self.parent = parent
self.size=size self.size = size
self.build_dimensions=build_dimensions self.build_dimensions = build_dimensions
self.grid=grid self.grid = grid
self.lastpos=[0,0,0,0,0,0,0] self.lastpos=[0, 0,0, 0,0, 0,0]
self.hilightpos=self.lastpos[:] self.hilightpos = self.lastpos[:]
self.Bind(wx.EVT_PAINT,self.paint) self.Bind(wx.EVT_PAINT, self.paint)
self.Bind(wx.EVT_SIZE,self.resize) self.Bind(wx.EVT_SIZE, self.resize)
self.lines={} self.lines={}
self.pens={} self.pens={}
self.arcs={} self.arcs={}
self.arcpens={} self.arcpens={}
self.layers=[] self.layers=[]
self.layerindex=0 self.layerindex = 0
self.filament_width=extrusion_width # set it to 0 to disable scaling lines with zoom self.filament_width = extrusion_width # set it to 0 to disable scaling lines with zoom
self.basescale=[min(float(size[0])/build_dimensions[0],float(size[1])/build_dimensions[1])]*2 self.basescale=[min(float(size[0])/build_dimensions[0],float(size[1])/build_dimensions[1])]*2
self.scale=self.basescale self.scale = self.basescale
penwidth = max(1.0,self.filament_width*((self.scale[0]+self.scale[1])/2.0)) penwidth = max(1.0, self.filament_width*((self.scale[0]+self.scale[1])/2.0))
self.translate=[0.0,0.0] self.translate=[0.0, 0.0]
self.mainpen=wx.Pen(wx.Colour(0,0,0),penwidth) self.mainpen = wx.Pen(wx.Colour(0, 0,0),penwidth)
self.arcpen=wx.Pen(wx.Colour(255,0,0),penwidth) self.arcpen = wx.Pen(wx.Colour(255, 0,0),penwidth)
self.travelpen=wx.Pen(wx.Colour(10,80,80),penwidth) self.travelpen = wx.Pen(wx.Colour(10, 80, 80),penwidth)
self.hlpen=wx.Pen(wx.Colour(200,50,50),penwidth) self.hlpen = wx.Pen(wx.Colour(200, 50, 50),penwidth)
self.fades=[wx.Pen(wx.Colour(250-0.6**i*100,250-0.6**i*100,200-0.4**i*50),penwidth) for i in xrange(6)] self.fades=[wx.Pen(wx.Colour(250-0.6**i*100, 250-0.6**i*100, 200-0.4**i*50),penwidth) for i in xrange(6)]
self.penslist=[self.mainpen,self.travelpen,self.hlpen]+self.fades self.penslist=[self.mainpen, self.travelpen, self.hlpen]+self.fades
self.showall=0 self.showall = 0
self.hilight=[] self.hilight=[]
self.hilightarcs=[] self.hilightarcs=[]
self.dirty=1 self.dirty = 1
self.blitmap=wx.EmptyBitmap(self.GetClientSize()[0],self.GetClientSize()[1],-1) self.blitmap = wx.EmptyBitmap(self.GetClientSize()[0],self.GetClientSize()[1],-1)
def inject(self): def inject(self):
#import pdb; pdb.set_trace() #import pdb; pdb.set_trace()
...@@ -179,7 +179,7 @@ class gviz(wx.Panel): ...@@ -179,7 +179,7 @@ class gviz(wx.Panel):
print "Layer "+str(self.layerindex +1)+" - Z = "+str(self.layers[self.layerindex])+" mm" print "Layer "+str(self.layerindex +1)+" - Z = "+str(self.layers[self.layerindex])+" mm"
def clear(self): def clear(self):
self.lastpos=[0,0,0,0,0,0,0] self.lastpos=[0, 0,0, 0,0, 0,0]
self.lines={} self.lines={}
self.pens={} self.pens={}
self.arcs={} self.arcs={}
...@@ -187,9 +187,9 @@ class gviz(wx.Panel): ...@@ -187,9 +187,9 @@ class gviz(wx.Panel):
self.layers=[] self.layers=[]
self.hilight=[] self.hilight=[]
self.hilightarcs=[] self.hilightarcs=[]
self.layerindex=0 self.layerindex = 0
self.showall=0 self.showall = 0
self.dirty=1 self.dirty = 1
#self.repaint() #self.repaint()
def layerup(self): def layerup(self):
if(self.layerindex+1<len(self.layers)): if(self.layerindex+1<len(self.layers)):
...@@ -207,67 +207,67 @@ class gviz(wx.Panel): ...@@ -207,67 +207,67 @@ class gviz(wx.Panel):
self.repaint() self.repaint()
self.Refresh() self.Refresh()
def setlayer(self,layer): def setlayer(self, layer):
try: try:
self.layerindex=self.layers.index(layer) self.layerindex = self.layers.index(layer)
self.repaint() self.repaint()
wx.CallAfter(self.Refresh) wx.CallAfter(self.Refresh)
self.showall=0 self.showall = 0
except: except:
pass pass
def resize(self,event): def resize(self, event):
size=self.GetClientSize() size = self.GetClientSize()
newsize=min(float(size[0])/self.size[0],float(size[1])/self.size[1]) newsize = min(float(size[0])/self.size[0],float(size[1])/self.size[1])
self.size=self.GetClientSize() self.size = self.GetClientSize()
wx.CallAfter(self.zoom,0,0,newsize) wx.CallAfter(self.zoom, 0,0, newsize)
def zoom(self,x,y,factor): def zoom(self, x,y, factor):
self.scale = [s * factor for s in self.scale] self.scale = [s * factor for s in self.scale]
self.translate = [ x - (x-self.translate[0]) * factor, self.translate = [ x - (x-self.translate[0]) * factor,
y - (y-self.translate[1]) * factor] y - (y-self.translate[1]) * factor]
penwidth = max(1.0,self.filament_width*((self.scale[0]+self.scale[1])/2.0)) penwidth = max(1.0, self.filament_width*((self.scale[0]+self.scale[1])/2.0))
for pen in self.penslist: for pen in self.penslist:
pen.SetWidth(penwidth) pen.SetWidth(penwidth)
#self.dirty=1 #self.dirty = 1
self.repaint() self.repaint()
self.Refresh() self.Refresh()
def repaint(self): def repaint(self):
self.blitmap=wx.EmptyBitmap(self.GetClientSize()[0],self.GetClientSize()[1],-1) self.blitmap = wx.EmptyBitmap(self.GetClientSize()[0],self.GetClientSize()[1],-1)
dc=wx.MemoryDC() dc = wx.MemoryDC()
dc.SelectObject(self.blitmap) dc.SelectObject(self.blitmap)
dc.SetBackground(wx.Brush((250,250,200))) dc.SetBackground(wx.Brush((250, 250, 200)))
dc.Clear() dc.Clear()
dc.SetPen(wx.Pen(wx.Colour(180,180,150))) dc.SetPen(wx.Pen(wx.Colour(180, 180, 150)))
for grid_unit in self.grid: for grid_unit in self.grid:
if grid_unit > 0: if grid_unit > 0:
for x in xrange(int(self.build_dimensions[0]/grid_unit)+1): for x in xrange(int(self.build_dimensions[0]/grid_unit)+1):
dc.DrawLine(self.translate[0]+x*self.scale[0]*grid_unit,self.translate[1],self.translate[0]+x*self.scale[0]*grid_unit,self.translate[1]+self.scale[1]*self.build_dimensions[1]) dc.DrawLine(self.translate[0]+x*self.scale[0]*grid_unit, self.translate[1],self.translate[0]+x*self.scale[0]*grid_unit, self.translate[1]+self.scale[1]*self.build_dimensions[1])
for y in xrange(int(self.build_dimensions[1]/grid_unit)+1): for y in xrange(int(self.build_dimensions[1]/grid_unit)+1):
dc.DrawLine(self.translate[0],self.translate[1]+y*self.scale[1]*grid_unit,self.translate[0]+self.scale[0]*self.build_dimensions[0],self.translate[1]+y*self.scale[1]*grid_unit) dc.DrawLine(self.translate[0],self.translate[1]+y*self.scale[1]*grid_unit, self.translate[0]+self.scale[0]*self.build_dimensions[0],self.translate[1]+y*self.scale[1]*grid_unit)
dc.SetPen(wx.Pen(wx.Colour(0,0,0))) dc.SetPen(wx.Pen(wx.Colour(0, 0,0)))
if not self.showall: if not self.showall:
self.size = self.GetSize() self.size = self.GetSize()
dc.SetBrush(wx.Brush((43,144,255))) dc.SetBrush(wx.Brush((43, 144, 255)))
dc.DrawRectangle(self.size[0]-15,0,15,self.size[1]) dc.DrawRectangle(self.size[0]-15, 0,15, self.size[1])
dc.SetBrush(wx.Brush((0,255,0))) dc.SetBrush(wx.Brush((0, 255, 0)))
if len(self.layers): if len(self.layers):
dc.DrawRectangle(self.size[0]-14,(1.0-(1.0*(self.layerindex+1))/len(self.layers))*self.size[1],13,self.size[1]-1) dc.DrawRectangle(self.size[0]-14,(1.0-(1.0*(self.layerindex+1))/len(self.layers))*self.size[1],13, self.size[1]-1)
def _drawlines(lines,pens): def _drawlines(lines, pens):
def _scaler(x): def _scaler(x):
return (self.scale[0]*x[0]+self.translate[0], return (self.scale[0]*x[0]+self.translate[0],
self.scale[1]*x[1]+self.translate[1], self.scale[1]*x[1]+self.translate[1],
self.scale[0]*x[2]+self.translate[0], self.scale[0]*x[2]+self.translate[0],
self.scale[1]*x[3]+self.translate[1],) self.scale[1]*x[3]+self.translate[1],)
scaled_lines = map(_scaler,lines) scaled_lines = map(_scaler, lines)
dc.DrawLineList(scaled_lines, pens) dc.DrawLineList(scaled_lines, pens)
def _drawarcs(arcs,pens): def _drawarcs(arcs, pens):
def _scaler(x): def _scaler(x):
return (self.scale[0]*x[0]+self.translate[0], return (self.scale[0]*x[0]+self.translate[0],
self.scale[1]*x[1]+self.translate[1], self.scale[1]*x[1]+self.translate[1],
...@@ -275,7 +275,7 @@ class gviz(wx.Panel): ...@@ -275,7 +275,7 @@ class gviz(wx.Panel):
self.scale[1]*x[3]+self.translate[1], self.scale[1]*x[3]+self.translate[1],
self.scale[0]*x[4]+self.translate[0], self.scale[0]*x[4]+self.translate[0],
self.scale[1]*x[5]+self.translate[1],) self.scale[1]*x[5]+self.translate[1],)
scaled_arcs = map(_scaler,arcs) scaled_arcs = map(_scaler, arcs)
for i in range(len(scaled_arcs)): for i in range(len(scaled_arcs)):
dc.SetPen(pens[i] if type(pens).__name__ == 'list' else pens) dc.SetPen(pens[i] if type(pens).__name__ == 'list' else pens)
dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.SetBrush(wx.TRANSPARENT_BRUSH)
...@@ -284,12 +284,12 @@ class gviz(wx.Panel): ...@@ -284,12 +284,12 @@ class gviz(wx.Panel):
if self.showall: if self.showall:
l=[] l=[]
for i in self.layers: for i in self.layers:
dc.DrawLineList(l,self.fades[0]) dc.DrawLineList(l, self.fades[0])
_drawlines(self.lines[i], self.pens[i]) _drawlines(self.lines[i], self.pens[i])
_drawarcs(self.arcs[i], self.arcpens[i]) _drawarcs(self.arcs[i], self.arcpens[i])
return return
if self.layerindex<len(self.layers) and self.layers[self.layerindex] in self.lines.keys(): if self.layerindex<len(self.layers) and self.layers[self.layerindex] in self.lines.keys():
for layer_i in xrange(max(0,self.layerindex-6),self.layerindex): for layer_i in xrange(max(0, self.layerindex-6),self.layerindex):
#print i, self.layerindex, self.layerindex-i #print i, self.layerindex, self.layerindex-i
_drawlines(self.lines[self.layers[layer_i]], self.fades[self.layerindex-layer_i-1]) _drawlines(self.lines[self.layers[layer_i]], self.fades[self.layerindex-layer_i-1])
_drawarcs(self.arcs[self.layers[layer_i]], self.fades[self.layerindex-layer_i-1]) _drawarcs(self.arcs[self.layers[layer_i]], self.fades[self.layerindex-layer_i-1])
...@@ -301,23 +301,23 @@ class gviz(wx.Panel): ...@@ -301,23 +301,23 @@ class gviz(wx.Panel):
dc.SelectObject(wx.NullBitmap) dc.SelectObject(wx.NullBitmap)
def paint(self,event): def paint(self, event):
dc=wx.PaintDC(self) dc = wx.PaintDC(self)
if(self.dirty): if(self.dirty):
self.repaint() self.repaint()
self.dirty=0 self.dirty = 0
sz=self.GetClientSize() sz = self.GetClientSize()
dc.DrawBitmap(self.blitmap,0,0) dc.DrawBitmap(self.blitmap, 0,0)
del dc del dc
def addfile(self,gcodes=[]): def addfile(self, gcodes=[]):
self.clear() self.clear()
for i in gcodes: for i in gcodes:
self.addgcode(i) self.addgcode(i)
def addgcode(self,gcode="M105",hilight=0): def addgcode(self, gcode = "M105",hilight = 0):
gcode=gcode.split("*")[0] gcode = gcode.split("*")[0]
gcode=gcode.split(";")[0] gcode = gcode.split(";")[0]
gcode = gcode.lower().strip().split() gcode = gcode.lower().strip().split()
if len(gcode) == 0: if len(gcode) == 0:
return return
...@@ -325,11 +325,11 @@ class gviz(wx.Panel): ...@@ -325,11 +325,11 @@ class gviz(wx.Panel):
gcode.pop(0) gcode.pop(0)
def _readgcode(): def _readgcode():
target=self.lastpos[:] target = self.lastpos[:]
target[5]=0.0 target[5]=0.0
target[6]=0.0 target[6]=0.0
if hilight: if hilight:
target=self.hilightpos[:] target = self.hilightpos[:]
for i in gcode: for i in gcode:
if i[0]=="x": if i[0]=="x":
target[0]=float(i[1:]) target[0]=float(i[1:])
......
...@@ -5,11 +5,11 @@ import gettext ...@@ -5,11 +5,11 @@ import gettext
# searching for installed locales on /usr/share; uses relative folder if not found (windows) # searching for installed locales on /usr/share; uses relative folder if not found (windows)
def install_locale(domain): def install_locale(domain):
if os.path.exists('/usr/share/pronterface/locale'): if os.path.exists('/usr/share/pronterface/locale'):
gettext.install(domain, '/usr/share/pronterface/locale', unicode=1) gettext.install(domain, '/usr/share/pronterface/locale', unicode = 1)
elif os.path.exists('/usr/local/share/pronterface/locale'): elif os.path.exists('/usr/local/share/pronterface/locale'):
gettext.install(domain, '/usr/local/share/pronterface/locale', unicode=1) gettext.install(domain, '/usr/local/share/pronterface/locale', unicode = 1)
else: else:
gettext.install(domain, './locale', unicode=1) gettext.install(domain, './locale', unicode = 1)
def imagefile(filename): def imagefile(filename):
for prefix in ['/usr/local/share/pronterface/images', '/usr/share/pronterface/images']: for prefix in ['/usr/local/share/pronterface/images', '/usr/share/pronterface/images']:
......
...@@ -23,8 +23,8 @@ import svg.document as wxpsvgdocument ...@@ -23,8 +23,8 @@ import svg.document as wxpsvgdocument
import imghdr import imghdr
class dispframe(wx.Frame): class dispframe(wx.Frame):
def __init__(self, parent, title, res=(800, 600), printer=None): def __init__(self, parent, title, res = (800, 600), printer = None):
wx.Frame.__init__(self, parent=parent, title=title) wx.Frame.__init__(self, parent = parent, title = title)
self.p = printer self.p = printer
self.pic = wx.StaticBitmap(self) self.pic = wx.StaticBitmap(self)
self.bitmap = wx.EmptyBitmap(*res) self.bitmap = wx.EmptyBitmap(*res)
...@@ -101,7 +101,7 @@ class dispframe(wx.Frame): ...@@ -101,7 +101,7 @@ class dispframe(wx.Frame):
wx.CallAfter(self.ShowFullScreen, 0) wx.CallAfter(self.ShowFullScreen, 0)
wx.CallAfter(self.timer.Stop) wx.CallAfter(self.timer.Stop)
def present(self, layers, interval=0.5, pause=0.2, thickness=0.4, scale=20, size=(800, 600), offset=(0, 0)): def present(self, layers, interval = 0.5, pause = 0.2, thickness = 0.4, scale = 20, size = (800, 600), offset = (0, 0)):
wx.CallAfter(self.pic.Hide) wx.CallAfter(self.pic.Hide)
wx.CallAfter(self.Refresh) wx.CallAfter(self.Refresh)
self.layers = layers self.layers = layers
...@@ -118,47 +118,47 @@ class dispframe(wx.Frame): ...@@ -118,47 +118,47 @@ class dispframe(wx.Frame):
class setframe(wx.Frame): class setframe(wx.Frame):
def __init__(self, parent, printer=None): def __init__(self, parent, printer = None):
wx.Frame.__init__(self, parent, title="Projector setup") wx.Frame.__init__(self, parent, title = "Projector setup")
self.f = dispframe(None, "", printer=printer) self.f = dispframe(None, "", printer = printer)
self.panel = wx.Panel(self) self.panel = wx.Panel(self)
self.panel.SetBackgroundColour("orange") self.panel.SetBackgroundColour("orange")
self.bload = wx.Button(self.panel, -1, "Load", pos=(0, 0)) self.bload = wx.Button(self.panel, -1, "Load", pos = (0, 0))
self.bload.Bind(wx.EVT_BUTTON, self.loadfile) self.bload.Bind(wx.EVT_BUTTON, self.loadfile)
wx.StaticText(self.panel, -1, "Layer:", pos=(0, 30)) wx.StaticText(self.panel, -1, "Layer:", pos = (0, 30))
wx.StaticText(self.panel, -1, "mm", pos=(130, 30)) wx.StaticText(self.panel, -1, "mm", pos = (130, 30))
self.thickness = wx.TextCtrl(self.panel, -1, "0.5", pos=(50, 30)) self.thickness = wx.TextCtrl(self.panel, -1, "0.5", pos = (50, 30))
wx.StaticText(self.panel, -1, "Exposure:", pos=(0, 60)) wx.StaticText(self.panel, -1, "Exposure:", pos = (0, 60))
wx.StaticText(self.panel, -1, "s", pos=(130, 60)) wx.StaticText(self.panel, -1, "s", pos = (130, 60))
self.interval = wx.TextCtrl(self.panel, -1, "0.5", pos=(50, 60)) self.interval = wx.TextCtrl(self.panel, -1, "0.5", pos = (50, 60))
wx.StaticText(self.panel, -1, "Blank:", pos=(0, 90)) wx.StaticText(self.panel, -1, "Blank:", pos = (0, 90))
wx.StaticText(self.panel, -1, "s", pos=(130, 90)) wx.StaticText(self.panel, -1, "s", pos = (130, 90))
self.delay = wx.TextCtrl(self.panel, -1, "0.5", pos=(50, 90)) self.delay = wx.TextCtrl(self.panel, -1, "0.5", pos = (50, 90))
wx.StaticText(self.panel, -1, "Scale:", pos=(0, 120)) wx.StaticText(self.panel, -1, "Scale:", pos = (0, 120))
wx.StaticText(self.panel, -1, "x", pos=(130, 120)) wx.StaticText(self.panel, -1, "x", pos = (130, 120))
self.scale = wx.TextCtrl(self.panel, -1, "5", pos=(50, 120)) self.scale = wx.TextCtrl(self.panel, -1, "5", pos = (50, 120))
wx.StaticText(self.panel, -1, "X:", pos=(160, 30)) wx.StaticText(self.panel, -1, "X:", pos = (160, 30))
self.X = wx.TextCtrl(self.panel, -1, "1024", pos=(210, 30)) self.X = wx.TextCtrl(self.panel, -1, "1024", pos = (210, 30))
wx.StaticText(self.panel, -1, "Y:", pos=(160, 60)) wx.StaticText(self.panel, -1, "Y:", pos = (160, 60))
self.Y = wx.TextCtrl(self.panel, -1, "768", pos=(210, 60)) self.Y = wx.TextCtrl(self.panel, -1, "768", pos = (210, 60))
wx.StaticText(self.panel, -1, "OffsetX:", pos=(160, 90)) wx.StaticText(self.panel, -1, "OffsetX:", pos = (160, 90))
self.offsetX = wx.TextCtrl(self.panel, -1, "50", pos=(210, 90)) self.offsetX = wx.TextCtrl(self.panel, -1, "50", pos = (210, 90))
wx.StaticText(self.panel, -1, "OffsetY:", pos=(160, 120)) wx.StaticText(self.panel, -1, "OffsetY:", pos = (160, 120))
self.offsetY = wx.TextCtrl(self.panel, -1, "50", pos=(210, 120)) self.offsetY = wx.TextCtrl(self.panel, -1, "50", pos = (210, 120))
self.bload = wx.Button(self.panel, -1, "Present", pos=(0, 150)) self.bload = wx.Button(self.panel, -1, "Present", pos = (0, 150))
self.bload.Bind(wx.EVT_BUTTON, self.startdisplay) self.bload.Bind(wx.EVT_BUTTON, self.startdisplay)
wx.StaticText(self.panel, -1, "Fullscreen:", pos=(160, 150)) wx.StaticText(self.panel, -1, "Fullscreen:", pos = (160, 150))
self.fullscreen = wx.CheckBox(self.panel, -1, pos=(220, 150)) self.fullscreen = wx.CheckBox(self.panel, -1, pos = (220, 150))
self.fullscreen.SetValue(True) self.fullscreen.SetValue(True)
self.Show() self.Show()
...@@ -168,7 +168,7 @@ class setframe(wx.Frame): ...@@ -168,7 +168,7 @@ class setframe(wx.Frame):
shutil.rmtree(self.image_dir) shutil.rmtree(self.image_dir)
def parsesvg(self, name): def parsesvg(self, name):
et = xml.etree.ElementTree.ElementTree(file=name) et = xml.etree.ElementTree.ElementTree(file = name)
#xml.etree.ElementTree.dump(et) #xml.etree.ElementTree.dump(et)
slicer = 'Slic3r' if et.getroot().find('{http://www.w3.org/2000/svg}metadata') == None else 'Skeinforge' slicer = 'Slic3r' if et.getroot().find('{http://www.w3.org/2000/svg}metadata') == None else 'Skeinforge'
zlast = 0 zlast = 0
...@@ -214,7 +214,7 @@ class setframe(wx.Frame): ...@@ -214,7 +214,7 @@ class setframe(wx.Frame):
return ol, -1, "bitmap" return ol, -1, "bitmap"
def loadfile(self, event): def loadfile(self, event):
dlg = wx.FileDialog(self, ("Open file to print"), style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) dlg = wx.FileDialog(self, ("Open file to print"), style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
dlg.SetWildcard(("Slic3r or Skeinforge svg files (;*.svg;*.SVG;);3DLP Zip (;*.3dlp.zip;)")) dlg.SetWildcard(("Slic3r or Skeinforge svg files (;*.svg;*.SVG;);3DLP Zip (;*.3dlp.zip;)"))
if(dlg.ShowModal() == wx.ID_OK): if(dlg.ShowModal() == wx.ID_OK):
name = dlg.GetPath() name = dlg.GetPath()
...@@ -240,12 +240,12 @@ class setframe(wx.Frame): ...@@ -240,12 +240,12 @@ class setframe(wx.Frame):
self.f.ShowFullScreen(1) self.f.ShowFullScreen(1)
l = self.layers[0][:] l = self.layers[0][:]
self.f.present(l, self.f.present(l,
thickness=float(self.thickness.GetValue()), thickness = float(self.thickness.GetValue()),
interval=float(self.interval.GetValue()), interval = float(self.interval.GetValue()),
scale=float(self.scale.GetValue()), scale = float(self.scale.GetValue()),
pause=float(self.delay.GetValue()), pause = float(self.delay.GetValue()),
size=(float(self.X.GetValue()), float(self.Y.GetValue())), size = (float(self.X.GetValue()), float(self.Y.GetValue())),
offset=(float(self.offsetX.GetValue()), float(self.offsetY.GetValue()))) offset = (float(self.offsetX.GetValue()), float(self.offsetY.GetValue())))
if __name__ == "__main__": if __name__ == "__main__":
a = wx.App() a = wx.App()
......
...@@ -18,49 +18,49 @@ import wx ...@@ -18,49 +18,49 @@ import wx
class macroed(wx.Dialog): class macroed(wx.Dialog):
"""Really simple editor to edit macro definitions""" """Really simple editor to edit macro definitions"""
def __init__(self,macro_name,definition,callback,gcode=False): def __init__(self, macro_name, definition, callback, gcode = False):
self.indent_chars = " " self.indent_chars = " "
title=" macro %s" title = " macro %s"
if gcode: if gcode:
title=" %s" title = " %s"
self.gcode=gcode self.gcode = gcode
wx.Dialog.__init__(self,None,title=title % macro_name,style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) wx.Dialog.__init__(self, None, title = title % macro_name, style = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
self.callback = callback self.callback = callback
self.panel=wx.Panel(self,-1) self.panel = wx.Panel(self,-1)
titlesizer=wx.BoxSizer(wx.HORIZONTAL) titlesizer = wx.BoxSizer(wx.HORIZONTAL)
titletext = wx.StaticText(self.panel,-1," _") #title%macro_name) titletext = wx.StaticText(self.panel,-1," _") #title%macro_name)
#title.SetFont(wx.Font(11,wx.NORMAL,wx.NORMAL,wx.BOLD)) #title.SetFont(wx.Font(11, wx.NORMAL, wx.NORMAL, wx.BOLD))
titlesizer.Add(titletext,1) titlesizer.Add(titletext, 1)
self.findb = wx.Button(self.panel, -1, _("Find"),style=wx.BU_EXACTFIT) #New button for "Find" (Jezmy) self.findb = wx.Button(self.panel, -1, _("Find"),style = wx.BU_EXACTFIT) #New button for "Find" (Jezmy)
self.findb.Bind(wx.EVT_BUTTON, self.find) self.findb.Bind(wx.EVT_BUTTON, self.find)
self.okb = wx.Button(self.panel, -1, _("Save"),style=wx.BU_EXACTFIT) self.okb = wx.Button(self.panel, -1, _("Save"),style = wx.BU_EXACTFIT)
self.okb.Bind(wx.EVT_BUTTON, self.save) self.okb.Bind(wx.EVT_BUTTON, self.save)
self.Bind(wx.EVT_CLOSE, self.close) self.Bind(wx.EVT_CLOSE, self.close)
titlesizer.Add(self.findb) titlesizer.Add(self.findb)
titlesizer.Add(self.okb) titlesizer.Add(self.okb)
self.cancelb = wx.Button(self.panel, -1, _("Cancel"),style=wx.BU_EXACTFIT) self.cancelb = wx.Button(self.panel, -1, _("Cancel"),style = wx.BU_EXACTFIT)
self.cancelb.Bind(wx.EVT_BUTTON, self.close) self.cancelb.Bind(wx.EVT_BUTTON, self.close)
titlesizer.Add(self.cancelb) titlesizer.Add(self.cancelb)
topsizer=wx.BoxSizer(wx.VERTICAL) topsizer = wx.BoxSizer(wx.VERTICAL)
topsizer.Add(titlesizer,0,wx.EXPAND) topsizer.Add(titlesizer, 0,wx.EXPAND)
self.e=wx.TextCtrl(self.panel,style=wx.TE_MULTILINE+wx.HSCROLL,size=(400,400)) self.e = wx.TextCtrl(self.panel, style = wx.TE_MULTILINE+wx.HSCROLL, size = (400, 400))
if not self.gcode: if not self.gcode:
self.e.SetValue(self.unindent(definition)) self.e.SetValue(self.unindent(definition))
else: else:
self.e.SetValue("\n".join(definition)) self.e.SetValue("\n".join(definition))
topsizer.Add(self.e,1,wx.ALL+wx.EXPAND) topsizer.Add(self.e, 1,wx.ALL+wx.EXPAND)
self.panel.SetSizer(topsizer) self.panel.SetSizer(topsizer)
topsizer.Layout() topsizer.Layout()
topsizer.Fit(self) topsizer.Fit(self)
self.Show() self.Show()
self.e.SetFocus() self.e.SetFocus()
def find(self,ev): def find(self, ev):
# Ask user what to look for, find it and point at it ... (Jezmy) # Ask user what to look for, find it and point at it ... (Jezmy)
S = self.e.GetStringSelection() S = self.e.GetStringSelection()
if not S : if not S :
S = "Z" S = "Z"
FindValue = wx.GetTextFromUser('Please enter a search string:', caption="Search", default_value=S, parent=None) FindValue = wx.GetTextFromUser('Please enter a search string:', caption = "Search", default_value = S, parent = None)
somecode = self.e.GetValue() somecode = self.e.GetValue()
numLines = len(somecode) numLines = len(somecode)
position = somecode.find(FindValue, self.e.GetInsertionPoint()) position = somecode.find(FindValue, self.e.GetInsertionPoint())
...@@ -70,7 +70,7 @@ class macroed(wx.Dialog): ...@@ -70,7 +70,7 @@ class macroed(wx.Dialog):
else: else:
# self.title.SetValue("Position : "+str(position)) # self.title.SetValue("Position : "+str(position))
titletext = wx.TextCtrl(self.panel,-1,str(position)) titletext = wx.TextCtrl(self.panel,-1, str(position))
# ananswer = wx.MessageBox(str(numLines)+" Lines detected in file\n"+str(position), "OK") # ananswer = wx.MessageBox(str(numLines)+" Lines detected in file\n"+str(position), "OK")
self.e.SetFocus() self.e.SetFocus()
...@@ -84,20 +84,20 @@ class macroed(wx.Dialog): ...@@ -84,20 +84,20 @@ class macroed(wx.Dialog):
dlg.ShowModal() dlg.ShowModal()
dlg.Destroy() dlg.Destroy()
def save(self,ev): def save(self, ev):
self.Destroy() self.Destroy()
if not self.gcode: if not self.gcode:
self.callback(self.reindent(self.e.GetValue())) self.callback(self.reindent(self.e.GetValue()))
else: else:
self.callback(self.e.GetValue().split("\n")) self.callback(self.e.GetValue().split("\n"))
def close(self,ev): def close(self, ev):
self.Destroy() self.Destroy()
if self.webInterface: if self.webInterface:
webinterface.KillWebInterfaceThread() webinterface.KillWebInterfaceThread()
def unindent(self,text): def unindent(self, text):
self.indent_chars = text[:len(text)-len(text.lstrip())] self.indent_chars = text[:len(text)-len(text.lstrip())]
if len(self.indent_chars)==0: if len(self.indent_chars) == 0:
self.indent_chars=" " self.indent_chars = " "
unindented = "" unindented = ""
lines = re.split(r"(?:\r\n?|\n)",text) lines = re.split(r"(?:\r\n?|\n)",text)
#print lines #print lines
...@@ -109,7 +109,7 @@ class macroed(wx.Dialog): ...@@ -109,7 +109,7 @@ class macroed(wx.Dialog):
else: else:
unindented += line + "\n" unindented += line + "\n"
return unindented return unindented
def reindent(self,text): def reindent(self, text):
lines = re.split(r"(?:\r\n?|\n)",text) lines = re.split(r"(?:\r\n?|\n)",text)
if len(lines) <= 1: if len(lines) <= 1:
return text return text
...@@ -121,64 +121,64 @@ class macroed(wx.Dialog): ...@@ -121,64 +121,64 @@ class macroed(wx.Dialog):
class options(wx.Dialog): class options(wx.Dialog):
"""Options editor""" """Options editor"""
def __init__(self,pronterface): def __init__(self, pronterface):
wx.Dialog.__init__(self, None, title=_("Edit settings"), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) wx.Dialog.__init__(self, None, title = _("Edit settings"), style = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
topsizer=wx.BoxSizer(wx.VERTICAL) topsizer = wx.BoxSizer(wx.VERTICAL)
vbox=wx.StaticBoxSizer(wx.StaticBox(self, label=_("Defaults")) ,wx.VERTICAL) vbox = wx.StaticBoxSizer(wx.StaticBox(self, label = _("Defaults")) ,wx.VERTICAL)
topsizer.Add(vbox,1,wx.ALL+wx.EXPAND) topsizer.Add(vbox, 1,wx.ALL+wx.EXPAND)
grid=wx.FlexGridSizer(rows=0,cols=2,hgap=8,vgap=2) grid = wx.FlexGridSizer(rows = 0, cols = 2, hgap = 8, vgap = 2)
grid.SetFlexibleDirection( wx.BOTH ) grid.SetFlexibleDirection( wx.BOTH )
grid.AddGrowableCol( 1 ) grid.AddGrowableCol( 1 )
grid.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED ) grid.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED )
vbox.Add(grid,0,wx.EXPAND) vbox.Add(grid, 0,wx.EXPAND)
ctrls = {} ctrls = {}
for k,v in sorted(pronterface.settings._all_settings().items()): for k, v in sorted(pronterface.settings._all_settings().items()):
ctrls[k,0] = wx.StaticText(self,-1,k) ctrls[k, 0] = wx.StaticText(self,-1, k)
ctrls[k,1] = wx.TextCtrl(self,-1,str(v)) ctrls[k, 1] = wx.TextCtrl(self,-1, str(v))
if k in pronterface.helpdict: if k in pronterface.helpdict:
ctrls[k,0].SetToolTipString(pronterface.helpdict.get(k)) ctrls[k, 0].SetToolTipString(pronterface.helpdict.get(k))
ctrls[k,1].SetToolTipString(pronterface.helpdict.get(k)) ctrls[k, 1].SetToolTipString(pronterface.helpdict.get(k))
grid.Add(ctrls[k,0],0,wx.ALIGN_CENTER_VERTICAL|wx.ALL|wx.ALIGN_RIGHT) grid.Add(ctrls[k, 0],0, wx.ALIGN_CENTER_VERTICAL|wx.ALL|wx.ALIGN_RIGHT)
grid.Add(ctrls[k,1],1,wx.ALIGN_CENTER_VERTICAL|wx.ALL|wx.EXPAND) grid.Add(ctrls[k, 1],1, wx.ALIGN_CENTER_VERTICAL|wx.ALL|wx.EXPAND)
topsizer.Add(self.CreateSeparatedButtonSizer(wx.OK+wx.CANCEL),0,wx.EXPAND) topsizer.Add(self.CreateSeparatedButtonSizer(wx.OK+wx.CANCEL),0, wx.EXPAND)
self.SetSizer(topsizer) self.SetSizer(topsizer)
topsizer.Layout() topsizer.Layout()
topsizer.Fit(self) topsizer.Fit(self)
if self.ShowModal()==wx.ID_OK: if self.ShowModal() == wx.ID_OK:
for k,v in pronterface.settings._all_settings().items(): for k, v in pronterface.settings._all_settings().items():
if ctrls[k,1].GetValue() != str(v): if ctrls[k, 1].GetValue() != str(v):
pronterface.set(k,str(ctrls[k,1].GetValue())) pronterface.set(k, str(ctrls[k, 1].GetValue()))
self.Destroy() self.Destroy()
class ButtonEdit(wx.Dialog): class ButtonEdit(wx.Dialog):
"""Custom button edit dialog""" """Custom button edit dialog"""
def __init__(self,pronterface): def __init__(self, pronterface):
wx.Dialog.__init__(self, None, title=_("Custom button"),style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) wx.Dialog.__init__(self, None, title = _("Custom button"),style = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
self.pronterface=pronterface self.pronterface = pronterface
topsizer=wx.BoxSizer(wx.VERTICAL) topsizer = wx.BoxSizer(wx.VERTICAL)
grid=wx.FlexGridSizer(rows=0,cols=2,hgap=4,vgap=2) grid = wx.FlexGridSizer(rows = 0, cols = 2, hgap = 4, vgap = 2)
grid.AddGrowableCol(1,1) grid.AddGrowableCol(1, 1)
grid.Add(wx.StaticText(self,-1, _("Button title")), 0, wx.BOTTOM|wx.RIGHT) grid.Add(wx.StaticText(self,-1, _("Button title")), 0, wx.BOTTOM|wx.RIGHT)
self.name=wx.TextCtrl(self,-1,"") self.name = wx.TextCtrl(self,-1,"")
grid.Add(self.name,1,wx.EXPAND) grid.Add(self.name, 1,wx.EXPAND)
grid.Add(wx.StaticText(self, -1, _("Command")), 0, wx.BOTTOM|wx.RIGHT) grid.Add(wx.StaticText(self, -1, _("Command")), 0, wx.BOTTOM|wx.RIGHT)
self.command=wx.TextCtrl(self,-1,"") self.command = wx.TextCtrl(self,-1,"")
xbox=wx.BoxSizer(wx.HORIZONTAL) xbox = wx.BoxSizer(wx.HORIZONTAL)
xbox.Add(self.command,1,wx.EXPAND) xbox.Add(self.command, 1,wx.EXPAND)
self.command.Bind(wx.EVT_TEXT,self.macrob_enabler) self.command.Bind(wx.EVT_TEXT, self.macrob_enabler)
self.macrob=wx.Button(self,-1,"..",style=wx.BU_EXACTFIT) self.macrob = wx.Button(self,-1,"..",style = wx.BU_EXACTFIT)
self.macrob.Bind(wx.EVT_BUTTON,self.macrob_handler) self.macrob.Bind(wx.EVT_BUTTON, self.macrob_handler)
xbox.Add(self.macrob,0) xbox.Add(self.macrob, 0)
grid.Add(xbox,1,wx.EXPAND) grid.Add(xbox, 1,wx.EXPAND)
grid.Add(wx.StaticText(self,-1, _("Color")),0,wx.BOTTOM|wx.RIGHT) grid.Add(wx.StaticText(self,-1, _("Color")),0, wx.BOTTOM|wx.RIGHT)
self.color=wx.TextCtrl(self,-1,"") self.color = wx.TextCtrl(self,-1,"")
grid.Add(self.color,1,wx.EXPAND) grid.Add(self.color, 1,wx.EXPAND)
topsizer.Add(grid,0,wx.EXPAND) topsizer.Add(grid, 0,wx.EXPAND)
topsizer.Add( (0,0),1) topsizer.Add( (0, 0),1)
topsizer.Add(self.CreateStdDialogButtonSizer(wx.OK|wx.CANCEL),0,wx.ALIGN_CENTER) topsizer.Add(self.CreateStdDialogButtonSizer(wx.OK|wx.CANCEL),0, wx.ALIGN_CENTER)
self.SetSizer(topsizer) self.SetSizer(topsizer)
def macrob_enabler(self,e): def macrob_enabler(self, e):
macro = self.command.GetValue() macro = self.command.GetValue()
valid = False valid = False
try: try:
...@@ -186,7 +186,7 @@ class ButtonEdit(wx.Dialog): ...@@ -186,7 +186,7 @@ class ButtonEdit(wx.Dialog):
valid = True valid = True
elif self.pronterface.macros.has_key(macro): elif self.pronterface.macros.has_key(macro):
valid = True valid = True
elif hasattr(self.pronterface.__class__,u"do_"+macro): elif hasattr(self.pronterface.__class__, u"do_"+macro):
valid = False valid = False
elif len([c for c in macro if not c.isalnum() and c != "_"]): elif len([c for c in macro if not c.isalnum() and c != "_"]):
valid = False valid = False
...@@ -203,7 +203,7 @@ class ButtonEdit(wx.Dialog): ...@@ -203,7 +203,7 @@ class ButtonEdit(wx.Dialog):
valid = True valid = True
self.macrob.Enable(valid) self.macrob.Enable(valid)
def macrob_handler(self,e): def macrob_handler(self, e):
macro = self.command.GetValue() macro = self.command.GetValue()
macro = self.pronterface.edit_macro(macro) macro = self.pronterface.edit_macro(macro)
self.command.SetValue(macro) self.command.SetValue(macro)
...@@ -212,106 +212,106 @@ class ButtonEdit(wx.Dialog): ...@@ -212,106 +212,106 @@ class ButtonEdit(wx.Dialog):
class TempGauge(wx.Panel): class TempGauge(wx.Panel):
def __init__(self,parent,size=(200,22),title="",maxval=240,gaugeColour=None): def __init__(self, parent, size = (200, 22),title = "",maxval = 240, gaugeColour = None):
wx.Panel.__init__(self,parent,-1,size=size) wx.Panel.__init__(self, parent,-1, size = size)
self.Bind(wx.EVT_PAINT,self.paint) self.Bind(wx.EVT_PAINT, self.paint)
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM) self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
self.width,self.height=size self.width, self.height = size
self.title=title self.title = title
self.max=maxval self.max = maxval
self.gaugeColour=gaugeColour self.gaugeColour = gaugeColour
self.value=0 self.value = 0
self.setpoint=0 self.setpoint = 0
self.recalc() self.recalc()
def recalc(self): def recalc(self):
mmax=max(int(self.setpoint*1.05),self.max) mmax = max(int(self.setpoint*1.05),self.max)
self.scale=float(self.width-2)/float(mmax) self.scale = float(self.width-2)/float(mmax)
self.ypt=max(16,int(self.scale*max(self.setpoint,self.max/6))) self.ypt = max(16, int(self.scale*max(self.setpoint, self.max/6)))
def SetValue(self,value): def SetValue(self, value):
self.value=value self.value = value
wx.CallAfter(self.Refresh) wx.CallAfter(self.Refresh)
def SetTarget(self,value): def SetTarget(self, value):
self.setpoint=value self.setpoint = value
self.recalc() self.recalc()
wx.CallAfter(self.Refresh) wx.CallAfter(self.Refresh)
def interpolatedColour(self,val,vmin,vmid,vmax,cmin,cmid,cmax): def interpolatedColour(self, val, vmin, vmid, vmax, cmin, cmid, cmax):
if val < vmin: return cmin if val < vmin: return cmin
if val > vmax: return cmax if val > vmax: return cmax
if val <= vmid: if val <= vmid:
lo,hi,val,valhi = cmin,cmid,val-vmin,vmid-vmin lo, hi, val, valhi = cmin, cmid, val-vmin, vmid-vmin
else: else:
lo,hi,val,valhi = cmid,cmax,val-vmid,vmax-vmid lo, hi, val, valhi = cmid, cmax, val-vmid, vmax-vmid
vv = float(val)/valhi vv = float(val)/valhi
rgb=lo.Red()+(hi.Red()-lo.Red())*vv,lo.Green()+(hi.Green()-lo.Green())*vv,lo.Blue()+(hi.Blue()-lo.Blue())*vv rgb = lo.Red()+(hi.Red()-lo.Red())*vv, lo.Green()+(hi.Green()-lo.Green())*vv, lo.Blue()+(hi.Blue()-lo.Blue())*vv
rgb=map(lambda x:x*0.8,rgb) rgb = map(lambda x:x*0.8, rgb)
return wx.Colour(*map(int,rgb)) return wx.Colour(*map(int, rgb))
def paint(self,ev): def paint(self, ev):
x0,y0,x1,y1,xE,yE = 1,1,self.ypt+1,1,self.width+1-2,20 x0, y0, x1, y1, xE, yE = 1, 1,self.ypt+1, 1,self.width+1-2, 20
dc=wx.PaintDC(self) dc = wx.PaintDC(self)
dc.SetBackground(wx.Brush((255,255,255))) dc.SetBackground(wx.Brush((255, 255, 255)))
dc.Clear() dc.Clear()
cold,medium,hot = wx.Colour(0,167,223),wx.Colour(239,233,119),wx.Colour(210,50.100) cold, medium, hot = wx.Colour(0, 167, 223),wx.Colour(239, 233, 119),wx.Colour(210, 50.100)
gauge1,gauge2 = wx.Colour(255,255,210),(self.gaugeColour or wx.Colour(234,82,0)) gauge1, gauge2 = wx.Colour(255, 255, 210),(self.gaugeColour or wx.Colour(234, 82, 0))
shadow1,shadow2 = wx.Colour(110,110,110),wx.Colour(255,255,255) shadow1, shadow2 = wx.Colour(110, 110, 110),wx.Colour(255, 255, 255)
gc = wx.GraphicsContext.Create(dc) gc = wx.GraphicsContext.Create(dc)
# draw shadow first # draw shadow first
# corners # corners
gc.SetBrush(gc.CreateRadialGradientBrush(xE-7,9,xE-7,9,8,shadow1,shadow2)) gc.SetBrush(gc.CreateRadialGradientBrush(xE-7, 9,xE-7, 9,8, shadow1, shadow2))
gc.DrawRectangle(xE-7,1,8,8) gc.DrawRectangle(xE-7, 1,8, 8)
gc.SetBrush(gc.CreateRadialGradientBrush(xE-7,17,xE-7,17,8,shadow1,shadow2)) gc.SetBrush(gc.CreateRadialGradientBrush(xE-7, 17, xE-7, 17, 8,shadow1, shadow2))
gc.DrawRectangle(xE-7,17,8,8) gc.DrawRectangle(xE-7, 17, 8,8)
gc.SetBrush(gc.CreateRadialGradientBrush(x0+6,17,x0+6,17,8,shadow1,shadow2)) gc.SetBrush(gc.CreateRadialGradientBrush(x0+6, 17, x0+6, 17, 8,shadow1, shadow2))
gc.DrawRectangle(0,17,x0+6,8) gc.DrawRectangle(0, 17, x0+6, 8)
# edges # edges
gc.SetBrush(gc.CreateLinearGradientBrush(xE-13,0,xE-6,0,shadow1,shadow2)) gc.SetBrush(gc.CreateLinearGradientBrush(xE-13, 0,xE-6, 0,shadow1, shadow2))
gc.DrawRectangle(xE-6,9,10,8) gc.DrawRectangle(xE-6, 9,10, 8)
gc.SetBrush(gc.CreateLinearGradientBrush(x0,yE-2,x0,yE+5,shadow1,shadow2)) gc.SetBrush(gc.CreateLinearGradientBrush(x0, yE-2, x0, yE+5, shadow1, shadow2))
gc.DrawRectangle(x0+6,yE-2,xE-12,7) gc.DrawRectangle(x0+6, yE-2, xE-12, 7)
# draw gauge background # draw gauge background
gc.SetBrush(gc.CreateLinearGradientBrush(x0,y0,x1+1,y1,cold,medium)) gc.SetBrush(gc.CreateLinearGradientBrush(x0, y0, x1+1, y1, cold, medium))
gc.DrawRoundedRectangle(x0,y0,x1+4,yE,6) gc.DrawRoundedRectangle(x0, y0, x1+4, yE, 6)
gc.SetBrush(gc.CreateLinearGradientBrush(x1-2,y1,xE,y1,medium,hot)) gc.SetBrush(gc.CreateLinearGradientBrush(x1-2, y1, xE, y1, medium, hot))
gc.DrawRoundedRectangle(x1-2,y1,xE-x1,yE,6) gc.DrawRoundedRectangle(x1-2, y1, xE-x1, yE, 6)
# draw gauge # draw gauge
width=12 width = 12
w1=y0+9-width/2 w1 = y0+9-width/2
w2=w1+width w2 = w1+width
value=x0+max(10,min(self.width+1-2,int(self.value*self.scale))) value = x0+max(10, min(self.width+1-2, int(self.value*self.scale)))
#gc.SetBrush(gc.CreateLinearGradientBrush(x0,y0+3,x0,y0+15,gauge1,gauge2)) #gc.SetBrush(gc.CreateLinearGradientBrush(x0, y0+3, x0, y0+15, gauge1, gauge2))
#gc.SetBrush(gc.CreateLinearGradientBrush(0,3,0,15,wx.Colour(255,255,255),wx.Colour(255,90,32))) #gc.SetBrush(gc.CreateLinearGradientBrush(0, 3,0, 15, wx.Colour(255, 255, 255),wx.Colour(255, 90, 32)))
gc.SetBrush(gc.CreateLinearGradientBrush(x0,y0+3,x0,y0+15,gauge1,self.interpolatedColour(value,x0,x1,xE,cold,medium,hot))) gc.SetBrush(gc.CreateLinearGradientBrush(x0, y0+3, x0, y0+15, gauge1, self.interpolatedColour(value, x0, x1, xE, cold, medium, hot)))
val_path = gc.CreatePath() val_path = gc.CreatePath()
val_path.MoveToPoint(x0,w1) val_path.MoveToPoint(x0, w1)
val_path.AddLineToPoint(value,w1) val_path.AddLineToPoint(value, w1)
val_path.AddLineToPoint(value+2,w1+width/4) val_path.AddLineToPoint(value+2, w1+width/4)
val_path.AddLineToPoint(value+2,w2-width/4) val_path.AddLineToPoint(value+2, w2-width/4)
val_path.AddLineToPoint(value,w2) val_path.AddLineToPoint(value, w2)
#val_path.AddLineToPoint(value-4,10) #val_path.AddLineToPoint(value-4, 10)
val_path.AddLineToPoint(x0,w2) val_path.AddLineToPoint(x0, w2)
gc.DrawPath(val_path) gc.DrawPath(val_path)
# draw setpoint markers # draw setpoint markers
setpoint=x0+max(10,int(self.setpoint*self.scale)) setpoint = x0+max(10, int(self.setpoint*self.scale))
gc.SetBrush(gc.CreateBrush(wx.Brush(wx.Colour(0,0,0)))) gc.SetBrush(gc.CreateBrush(wx.Brush(wx.Colour(0, 0,0))))
setp_path = gc.CreatePath() setp_path = gc.CreatePath()
setp_path.MoveToPoint(setpoint-4,y0) setp_path.MoveToPoint(setpoint-4, y0)
setp_path.AddLineToPoint(setpoint+4,y0) setp_path.AddLineToPoint(setpoint+4, y0)
setp_path.AddLineToPoint(setpoint,y0+5) setp_path.AddLineToPoint(setpoint, y0+5)
setp_path.MoveToPoint(setpoint-4,yE) setp_path.MoveToPoint(setpoint-4, yE)
setp_path.AddLineToPoint(setpoint+4,yE) setp_path.AddLineToPoint(setpoint+4, yE)
setp_path.AddLineToPoint(setpoint,yE-5) setp_path.AddLineToPoint(setpoint, yE-5)
gc.DrawPath(setp_path) gc.DrawPath(setp_path)
# draw readout # draw readout
text=u"T\u00B0 %u/%u"%(self.value,self.setpoint) text = u"T\u00B0 %u/%u"%(self.value, self.setpoint)
#gc.SetFont(gc.CreateFont(wx.Font(12,wx.FONTFAMILY_DEFAULT,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_BOLD),wx.WHITE)) #gc.SetFont(gc.CreateFont(wx.Font(12, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD),wx.WHITE))
#gc.DrawText(text,29,-2) #gc.DrawText(text, 29,-2)
gc.SetFont(gc.CreateFont(wx.Font(10,wx.FONTFAMILY_DEFAULT,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_BOLD),wx.WHITE)) gc.SetFont(gc.CreateFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD),wx.WHITE))
gc.DrawText(self.title,x0+19,y0+4) gc.DrawText(self.title, x0+19, y0+4)
gc.DrawText(text, x0+119,y0+4) gc.DrawText(text, x0+119, y0+4)
gc.SetFont(gc.CreateFont(wx.Font(10,wx.FONTFAMILY_DEFAULT,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_BOLD))) gc.SetFont(gc.CreateFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)))
gc.DrawText(self.title,x0+18,y0+3) gc.DrawText(self.title, x0+18, y0+3)
gc.DrawText(text, x0+118,y0+3) gc.DrawText(text, x0+118, y0+3)
...@@ -15,56 +15,56 @@ ...@@ -15,56 +15,56 @@
import sys, struct, math import sys, struct, math
def cross(v1,v2): def cross(v1, v2):
return [v1[1]*v2[2]-v1[2]*v2[1],v1[2]*v2[0]-v1[0]*v2[2],v1[0]*v2[1]-v1[1]*v2[0]] return [v1[1]*v2[2]-v1[2]*v2[1],v1[2]*v2[0]-v1[0]*v2[2],v1[0]*v2[1]-v1[1]*v2[0]]
def genfacet(v): def genfacet(v):
veca=[v[1][0]-v[0][0],v[1][1]-v[0][1],v[1][2]-v[0][2]] veca=[v[1][0]-v[0][0],v[1][1]-v[0][1],v[1][2]-v[0][2]]
vecb=[v[2][0]-v[1][0],v[2][1]-v[1][1],v[2][2]-v[1][2]] vecb=[v[2][0]-v[1][0],v[2][1]-v[1][1],v[2][2]-v[1][2]]
vecx=cross(veca,vecb) vecx = cross(veca, vecb)
vlen=math.sqrt(sum(map(lambda x:x*x,vecx))) vlen = math.sqrt(sum(map(lambda x:x*x, vecx)))
if vlen==0: if vlen == 0:
vlen=1 vlen = 1
normal=map(lambda x:x/vlen, vecx) normal = map(lambda x:x/vlen, vecx)
return [normal,v] return [normal, v]
I=[ I=[
[1,0,0,0], [1, 0,0, 0],
[0,1,0,0], [0, 1,0, 0],
[0,0,1,0], [0, 0,1, 0],
[0,0,0,1] [0, 0,0, 1]
] ]
def transpose(matrix): def transpose(matrix):
return zip(*matrix) return zip(*matrix)
#return [[v[i] for v in matrix] for i in xrange(len(matrix[0]))] #return [[v[i] for v in matrix] for i in xrange(len(matrix[0]))]
def multmatrix(vector,matrix): def multmatrix(vector, matrix):
return map(sum, transpose(map(lambda x:[x[0]*p for p in x[1]], zip(vector, transpose(matrix))))) return map(sum, transpose(map(lambda x:[x[0]*p for p in x[1]], zip(vector, transpose(matrix)))))
def applymatrix(facet,matrix=I): def applymatrix(facet, matrix = I):
#return facet #return facet
#return [map(lambda x:-1.0*x,multmatrix(facet[0]+[1],matrix)[:3]),map(lambda x:multmatrix(x+[1],matrix)[:3],facet[1])] #return [map(lambda x:-1.0*x, multmatrix(facet[0]+[1],matrix)[:3]),map(lambda x:multmatrix(x+[1],matrix)[:3],facet[1])]
return genfacet(map(lambda x:multmatrix(x+[1],matrix)[:3],facet[1])) return genfacet(map(lambda x:multmatrix(x+[1],matrix)[:3],facet[1]))
f=[[0,0,0],[[-3.022642, 0.642482, -9.510565],[-3.022642, 0.642482, -9.510565],[-3.022642, 0.642482, -9.510565]]] f=[[0, 0,0],[[-3.022642, 0.642482, -9.510565],[-3.022642, 0.642482, -9.510565],[-3.022642, 0.642482, -9.510565]]]
m=[ m=[
[1,0,0,0], [1, 0,0, 0],
[0,1,0,0], [0, 1,0, 0],
[0,0,1,1], [0, 0,1, 1],
[0,0,0,1] [0, 0,0, 1]
] ]
def emitstl(filename,facets=[],objname="stltool_export",binary=1): def emitstl(filename, facets=[],objname = "stltool_export",binary = 1):
if filename is None: if filename is None:
return return
if binary: if binary:
f=open(filename,"wb") f = open(filename,"wb")
buf="".join(["\0"]*80) buf = "".join(["\0"]*80)
buf+=struct.pack("<I",len(facets)) buf+=struct.pack("<I",len(facets))
facetformat=struct.Struct("<ffffffffffffH") facetformat = struct.Struct("<ffffffffffffH")
for i in facets: for i in facets:
l=list(i[0][:]) l = list(i[0][:])
for j in i[1]: for j in i[1]:
l+=j[:] l+=j[:]
l+=[0] l+=[0]
...@@ -75,12 +75,12 @@ def emitstl(filename,facets=[],objname="stltool_export",binary=1): ...@@ -75,12 +75,12 @@ def emitstl(filename,facets=[],objname="stltool_export",binary=1):
return return
f=open(filename,"w") f = open(filename,"w")
f.write("solid "+objname+"\n") f.write("solid "+objname+"\n")
for i in facets: for i in facets:
f.write(" facet normal "+" ".join(map(str,i[0]))+"\n outer loop\n") f.write(" facet normal "+" ".join(map(str, i[0]))+"\n outer loop\n")
for j in i[1]: for j in i[1]:
f.write(" vertex "+" ".join(map(str,j))+"\n") f.write(" vertex "+" ".join(map(str, j))+"\n")
f.write(" endloop"+"\n") f.write(" endloop"+"\n")
f.write(" endfacet"+"\n") f.write(" endfacet"+"\n")
f.write("endsolid "+objname+"\n") f.write("endsolid "+objname+"\n")
...@@ -89,43 +89,43 @@ def emitstl(filename,facets=[],objname="stltool_export",binary=1): ...@@ -89,43 +89,43 @@ def emitstl(filename,facets=[],objname="stltool_export",binary=1):
class stl: class stl:
def __init__(self, filename=None): def __init__(self, filename = None):
self.facet=[[0,0,0],[[0,0,0],[0,0,0],[0,0,0]]] self.facet=[[0, 0,0],[[0, 0,0],[0, 0,0],[0, 0,0]]]
self.facets=[] self.facets=[]
self.facetsminz=[] self.facetsminz=[]
self.facetsmaxz=[] self.facetsmaxz=[]
self.name="" self.name = ""
self.insolid=0 self.insolid = 0
self.infacet=0 self.infacet = 0
self.inloop=0 self.inloop = 0
self.facetloc=0 self.facetloc = 0
if filename is None: if filename is None:
return return
self.f=list(open(filename)) self.f = list(open(filename))
if not self.f[0].startswith("solid"): if not self.f[0].startswith("solid"):
print "Not an ascii stl solid - attempting to parse as binary" print "Not an ascii stl solid - attempting to parse as binary"
f=open(filename,"rb") f = open(filename,"rb")
buf=f.read(84) buf = f.read(84)
while(len(buf)<84): while(len(buf)<84):
newdata=f.read(84-len(buf)) newdata = f.read(84-len(buf))
if not len(newdata): if not len(newdata):
break break
buf+=newdata buf+=newdata
facetcount=struct.unpack_from("<I",buf,80) facetcount = struct.unpack_from("<I",buf, 80)
facetformat=struct.Struct("<ffffffffffffH") facetformat = struct.Struct("<ffffffffffffH")
for i in xrange(facetcount[0]): for i in xrange(facetcount[0]):
buf=f.read(50) buf = f.read(50)
while(len(buf)<50): while(len(buf)<50):
newdata=f.read(50-len(buf)) newdata = f.read(50-len(buf))
if not len(newdata): if not len(newdata):
break break
buf+=newdata buf+=newdata
fd=list(facetformat.unpack(buf)) fd = list(facetformat.unpack(buf))
self.name="binary soloid" self.name = "binary soloid"
self.facet=[fd[:3],[fd[3:6],fd[6:9],fd[9:12]]] self.facet=[fd[:3],[fd[3:6],fd[6:9],fd[9:12]]]
self.facets+=[self.facet] self.facets+=[self.facet]
facet=self.facet facet = self.facet
self.facetsminz+=[(min(map(lambda x:x[2], facet[1])),facet)] self.facetsminz+=[(min(map(lambda x:x[2], facet[1])),facet)]
self.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])),facet)] self.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])),facet)]
f.close() f.close()
...@@ -134,106 +134,106 @@ class stl: ...@@ -134,106 +134,106 @@ class stl:
if not self.parseline(i): if not self.parseline(i):
return return
def translate(self,v=[0,0,0]): def translate(self, v=[0, 0,0]):
matrix=[ matrix=[
[1,0,0,v[0]], [1, 0,0, v[0]],
[0,1,0,v[1]], [0, 1,0, v[1]],
[0,0,1,v[2]], [0, 0,1, v[2]],
[0,0,0,1] [0, 0,0, 1]
] ]
return self.transform(matrix) return self.transform(matrix)
def rotate(self,v=[0,0,0]): def rotate(self, v=[0, 0,0]):
import math import math
z=v[2] z = v[2]
matrix1=[ matrix1=[
[math.cos(math.radians(z)),-math.sin(math.radians(z)),0,0], [math.cos(math.radians(z)),-math.sin(math.radians(z)),0, 0],
[math.sin(math.radians(z)),math.cos(math.radians(z)),0,0], [math.sin(math.radians(z)),math.cos(math.radians(z)),0, 0],
[0,0,1,0], [0, 0,1, 0],
[0,0,0,1] [0, 0,0, 1]
] ]
y=v[0] y = v[0]
matrix2=[ matrix2=[
[1,0,0,0], [1, 0,0, 0],
[0,math.cos(math.radians(y)),-math.sin(math.radians(y)),0], [0, math.cos(math.radians(y)),-math.sin(math.radians(y)),0],
[0,math.sin(math.radians(y)),math.cos(math.radians(y)),0], [0, math.sin(math.radians(y)),math.cos(math.radians(y)),0],
[0,0,0,1] [0, 0,0, 1]
] ]
x=v[1] x = v[1]
matrix3=[ matrix3=[
[math.cos(math.radians(x)),0,-math.sin(math.radians(x)),0], [math.cos(math.radians(x)),0,-math.sin(math.radians(x)),0],
[0,1,0,0], [0, 1,0, 0],
[math.sin(math.radians(x)),0,math.cos(math.radians(x)),0], [math.sin(math.radians(x)),0, math.cos(math.radians(x)),0],
[0,0,0,1] [0, 0,0, 1]
] ]
return self.transform(matrix1).transform(matrix2).transform(matrix3) return self.transform(matrix1).transform(matrix2).transform(matrix3)
def scale(self,v=[0,0,0]): def scale(self, v=[0, 0,0]):
matrix=[ matrix=[
[v[0],0,0,0], [v[0],0, 0,0],
[0,v[1],0,0], [0, v[1],0, 0],
[0,0,v[2],0], [0, 0,v[2],0],
[0,0,0,1] [0, 0,0, 1]
] ]
return self.transform(matrix) return self.transform(matrix)
def transform(self,m=I): def transform(self, m = I):
s=stl() s = stl()
s.facets=[applymatrix(i,m) for i in self.facets] s.facets=[applymatrix(i, m) for i in self.facets]
s.insolid=0 s.insolid = 0
s.infacet=0 s.infacet = 0
s.inloop=0 s.inloop = 0
s.facetloc=0 s.facetloc = 0
s.name=self.name s.name = self.name
for facet in s.facets: for facet in s.facets:
s.facetsminz+=[(min(map(lambda x:x[2], facet[1])),facet)] s.facetsminz+=[(min(map(lambda x:x[2], facet[1])),facet)]
s.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])),facet)] s.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])),facet)]
return s return s
def export(self,f=sys.stdout): def export(self, f = sys.stdout):
f.write("solid "+self.name+"\n") f.write("solid "+self.name+"\n")
for i in self.facets: for i in self.facets:
f.write(" facet normal "+" ".join(map(str,i[0]))+"\n") f.write(" facet normal "+" ".join(map(str, i[0]))+"\n")
f.write(" outer loop"+"\n") f.write(" outer loop"+"\n")
for j in i[1]: for j in i[1]:
f.write(" vertex "+" ".join(map(str,j))+"\n") f.write(" vertex "+" ".join(map(str, j))+"\n")
f.write(" endloop"+"\n") f.write(" endloop"+"\n")
f.write(" endfacet"+"\n") f.write(" endfacet"+"\n")
f.write("endsolid "+self.name+"\n") f.write("endsolid "+self.name+"\n")
f.flush() f.flush()
def parseline(self,l): def parseline(self, l):
l=l.strip() l = l.strip()
if l.startswith("solid"): if l.startswith("solid"):
self.insolid=1 self.insolid = 1
self.name=l[6:] self.name = l[6:]
#print self.name #print self.name
elif l.startswith("endsolid"): elif l.startswith("endsolid"):
self.insolid=0 self.insolid = 0
return 0 return 0
elif l.startswith("facet normal"): elif l.startswith("facet normal"):
l=l.replace(",",".") l = l.replace(",",".")
self.infacet=11 self.infacet = 11
self.facetloc=0 self.facetloc = 0
self.facet=[[0,0,0],[[0,0,0],[0,0,0],[0,0,0]]] self.facet=[[0, 0,0],[[0, 0,0],[0, 0,0],[0, 0,0]]]
self.facet[0]=map(float,l.split()[2:]) self.facet[0]=map(float, l.split()[2:])
elif l.startswith("endfacet"): elif l.startswith("endfacet"):
self.infacet=0 self.infacet = 0
self.facets+=[self.facet] self.facets+=[self.facet]
facet=self.facet facet = self.facet
self.facetsminz+=[(min(map(lambda x:x[2], facet[1])),facet)] self.facetsminz+=[(min(map(lambda x:x[2], facet[1])),facet)]
self.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])),facet)] self.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])),facet)]
elif l.startswith("vertex"): elif l.startswith("vertex"):
l=l.replace(",",".") l = l.replace(",",".")
self.facet[1][self.facetloc]=map(float,l.split()[1:]) self.facet[1][self.facetloc]=map(float, l.split()[1:])
self.facetloc+=1 self.facetloc+=1
return 1 return 1
if __name__=="__main__": if __name__ == "__main__":
s=stl("../../Downloads/frame-vertex-neo-foot-x4.stl") s = stl("../../Downloads/frame-vertex-neo-foot-x4.stl")
for i in xrange(11,11): for i in xrange(11, 11):
working=s.facets[:] working = s.facets[:]
for j in reversed(sorted(s.facetsminz)): for j in reversed(sorted(s.facetsminz)):
if(j[0]>i): if(j[0]>i):
working.remove(j[1]) working.remove(j[1])
...@@ -245,6 +245,6 @@ if __name__=="__main__": ...@@ -245,6 +245,6 @@ if __name__=="__main__":
else: else:
break break
print i,len(working) print i, len(working)
emitstl("../../Downloads/frame-vertex-neo-foot-x4-a.stl",s.facets,"emitted_object") emitstl("../../Downloads/frame-vertex-neo-foot-x4-a.stl",s.facets,"emitted_object")
#stl("../prusamendel/stl/mendelplate.stl") #stl("../prusamendel/stl/mendelplate.stl")
...@@ -32,8 +32,8 @@ from pyglet.gl import * ...@@ -32,8 +32,8 @@ from pyglet.gl import *
class GLPanel(wx.Panel): class GLPanel(wx.Panel):
'''A simple class for using OpenGL with wxPython.''' '''A simple class for using OpenGL with wxPython.'''
def __init__(self, parent, id, pos=wx.DefaultPosition, def __init__(self, parent, id, pos = wx.DefaultPosition,
size=wx.DefaultSize, style=0): size = wx.DefaultSize, style = 0):
# Forcing a no full repaint to stop flickering # Forcing a no full repaint to stop flickering
style = style | wx.NO_FULL_REPAINT_ON_RESIZE style = style | wx.NO_FULL_REPAINT_ON_RESIZE
#call super function #call super function
...@@ -46,7 +46,7 @@ class GLPanel(wx.Panel): ...@@ -46,7 +46,7 @@ class GLPanel(wx.Panel):
glcanvas.WX_GL_DEPTH_SIZE, 24) # 24 bit glcanvas.WX_GL_DEPTH_SIZE, 24) # 24 bit
# Create the canvas # Create the canvas
self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.canvas = glcanvas.GLCanvas(self, attribList=attribList) self.canvas = glcanvas.GLCanvas(self, attribList = attribList)
self.sizer.Add(self.canvas, 1, wx.EXPAND) self.sizer.Add(self.canvas, 1, wx.EXPAND)
self.SetSizer(self.sizer) self.SetSizer(self.sizer)
#self.sizer.Fit(self) #self.sizer.Fit(self)
...@@ -215,7 +215,7 @@ class stlview(object): ...@@ -215,7 +215,7 @@ class stlview(object):
normals.extend(i[0]) normals.extend(i[0])
# Create a list of triangle indices. # Create a list of triangle indices.
indices = range(3 * len(facets)) # [[3*i,3*i+1,3*i+2] for i in xrange(len(facets))] indices = range(3 * len(facets)) # [[3*i, 3*i+1, 3*i+2] for i in xrange(len(facets))]
#print indices[:10] #print indices[:10]
self.vertex_list = batch.add_indexed(len(vertices) // 3, self.vertex_list = batch.add_indexed(len(vertices) // 3,
GL_TRIANGLES, GL_TRIANGLES,
...@@ -233,7 +233,7 @@ def vdiff(v, o): ...@@ -233,7 +233,7 @@ def vdiff(v, o):
class gcview(object): class gcview(object):
def __init__(self, lines, batch, w=0.5, h=0.5): def __init__(self, lines, batch, w = 0.5, h = 0.5):
# Create the vertex and normal arrays. # Create the vertex and normal arrays.
vertices = [] vertices = []
normals = [] normals = []
...@@ -258,7 +258,7 @@ class gcview(object): ...@@ -258,7 +258,7 @@ class gcview(object):
if lasth is not None: if lasth is not None:
self.layers[lasth] = pyglet.graphics.Batch() self.layers[lasth] = pyglet.graphics.Batch()
lt = layertemp[lasth][0] lt = layertemp[lasth][0]
indices = range(len(layertemp[lasth][0]) // 3) # [[3*i,3*i+1,3*i+2] for i in xrange(len(facets))] indices = range(len(layertemp[lasth][0]) // 3) # [[3*i, 3*i+1, 3*i+2] for i in xrange(len(facets))]
self.vlists.append(self.layers[lasth].add_indexed(len(layertemp[lasth][0]) // 3, self.vlists.append(self.layers[lasth].add_indexed(len(layertemp[lasth][0]) // 3,
GL_TRIANGLES, GL_TRIANGLES,
None, # group, None, # group,
...@@ -296,7 +296,7 @@ class gcview(object): ...@@ -296,7 +296,7 @@ class gcview(object):
t0 = time.time() t0 = time.time()
# Create a list of triangle indices. # Create a list of triangle indices.
indices = range(3 * 16 * len(lines)) # [[3*i,3*i+1,3*i+2] for i in xrange(len(facets))] indices = range(3 * 16 * len(lines)) # [[3*i, 3*i+1, 3*i+2] for i in xrange(len(facets))]
self.vlists.append(batch.add_indexed(len(vertices) // 3, self.vlists.append(batch.add_indexed(len(vertices) // 3,
GL_TRIANGLES, GL_TRIANGLES,
None, # group, None, # group,
...@@ -305,7 +305,7 @@ class gcview(object): ...@@ -305,7 +305,7 @@ class gcview(object):
('n3f/static', normals))) ('n3f/static', normals)))
if lasth is not None: if lasth is not None:
self.layers[lasth] = pyglet.graphics.Batch() self.layers[lasth] = pyglet.graphics.Batch()
indices = range(len(layertemp[lasth][0])) # [[3*i,3*i+1,3*i+2] for i in xrange(len(facets))] indices = range(len(layertemp[lasth][0])) # [[3*i, 3*i+1, 3*i+2] for i in xrange(len(facets))]
self.vlists.append(self.layers[lasth].add_indexed(len(layertemp[lasth][0]) // 3, self.vlists.append(self.layers[lasth].add_indexed(len(layertemp[lasth][0]) // 3,
GL_TRIANGLES, GL_TRIANGLES,
None, # group, None, # group,
...@@ -466,7 +466,7 @@ def mulquat(q1, rq): ...@@ -466,7 +466,7 @@ def mulquat(q1, rq):
class TestGlPanel(GLPanel): class TestGlPanel(GLPanel):
def __init__(self, parent, size, id=wx.ID_ANY): def __init__(self, parent, size, id = wx.ID_ANY):
super(TestGlPanel, self).__init__(parent, id, wx.DefaultPosition, size, 0) super(TestGlPanel, self).__init__(parent, id, wx.DefaultPosition, size, 0)
self.batches = [] self.batches = []
self.rot = 0 self.rot = 0
...@@ -495,7 +495,7 @@ class TestGlPanel(GLPanel): ...@@ -495,7 +495,7 @@ class TestGlPanel(GLPanel):
def forceresize(self): def forceresize(self):
self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1)) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1))
self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] - 1)) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] - 1))
threading.Thread(target=self.update).start() threading.Thread(target = self.update).start()
self.initialized = 0 self.initialized = 0
def move_shape(self, delta): def move_shape(self, delta):
...@@ -547,7 +547,7 @@ class TestGlPanel(GLPanel): ...@@ -547,7 +547,7 @@ class TestGlPanel(GLPanel):
p1y = -(float(p1[1]) - sz[1] / 2) / (sz[1] / 2) p1y = -(float(p1[1]) - sz[1] / 2) / (sz[1] / 2)
p2x = (float(p2[0]) - sz[0] / 2) / (sz[0] / 2) p2x = (float(p2[0]) - sz[0] / 2) / (sz[0] / 2)
p2y = -(float(p2[1]) - sz[1] / 2) / (sz[1] / 2) p2y = -(float(p2[1]) - sz[1] / 2) / (sz[1] / 2)
#print p1x,p1y,p2x,p2y #print p1x, p1y, p2x, p2y
quat = trackball(p1x, p1y, p2x, p2y, -self.transv[2] / 250.0) quat = trackball(p1x, p1y, p2x, p2y, -self.transv[2] / 250.0)
if self.rot: if self.rot:
self.basequat = mulquat(self.basequat, quat) self.basequat = mulquat(self.basequat, quat)
...@@ -710,7 +710,7 @@ class TestGlPanel(GLPanel): ...@@ -710,7 +710,7 @@ class TestGlPanel(GLPanel):
def drawmodel(self, m, n): def drawmodel(self, m, n):
batch = pyglet.graphics.Batch() batch = pyglet.graphics.Batch()
stl = stlview(m.facets, batch=batch) stl = stlview(m.facets, batch = batch)
m.batch = batch m.batch = batch
m.animoffset = 300 m.animoffset = 300
#print m #print m
...@@ -819,8 +819,8 @@ class TestGlPanel(GLPanel): ...@@ -819,8 +819,8 @@ class TestGlPanel(GLPanel):
class GCFrame(wx.Frame): class GCFrame(wx.Frame):
'''A simple class for using OpenGL with wxPython.''' '''A simple class for using OpenGL with wxPython.'''
def __init__(self, parent, ID, title, pos=wx.DefaultPosition, def __init__(self, parent, ID, title, pos = wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE): size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE):
super(GCFrame, self).__init__(parent, ID, title, pos, (size[0] + 150, size[1]), style) super(GCFrame, self).__init__(parent, ID, title, pos, (size[0] + 150, size[1]), style)
class d: class d:
...@@ -833,7 +833,7 @@ class GCFrame(wx.Frame): ...@@ -833,7 +833,7 @@ class GCFrame(wx.Frame):
m.curlayer = 0.0 m.curlayer = 0.0
m.scale = [1.0, 1.0, 1.0] m.scale = [1.0, 1.0, 1.0]
m.batch = pyglet.graphics.Batch() m.batch = pyglet.graphics.Batch()
m.gc = gcview([], batch=m.batch) m.gc = gcview([], batch = m.batch)
self.models = {"": m} self.models = {"": m}
self.l = d() self.l = d()
self.modelindex = 0 self.modelindex = 0
...@@ -841,13 +841,13 @@ class GCFrame(wx.Frame): ...@@ -841,13 +841,13 @@ class GCFrame(wx.Frame):
def addfile(self, gcode=[]): def addfile(self, gcode=[]):
self.models[""].gc.delete() self.models[""].gc.delete()
self.models[""].gc = gcview(gcode, batch=self.models[""].batch) self.models[""].gc = gcview(gcode, batch = self.models[""].batch)
def clear(self): def clear(self):
self.models[""].gc.delete() self.models[""].gc.delete()
self.models[""].gc = gcview([], batch=self.models[""].batch) self.models[""].gc = gcview([], batch = self.models[""].batch)
def Show(self, arg=True): def Show(self, arg = True):
wx.Frame.Show(self, arg) wx.Frame.Show(self, arg)
self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1)) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1))
self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] - 1)) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] - 1))
...@@ -868,10 +868,10 @@ class GCFrame(wx.Frame): ...@@ -868,10 +868,10 @@ class GCFrame(wx.Frame):
def main(): def main():
app = wx.App(redirect=False) app = wx.App(redirect = False)
frame = GCFrame(None, wx.ID_ANY, 'Gcode view, shift to move view, mousewheel to set layer', size=(400, 400)) frame = GCFrame(None, wx.ID_ANY, 'Gcode view, shift to move view, mousewheel to set layer', size = (400, 400))
frame.addfile(list(open("carriage dump_export.gcode"))) frame.addfile(list(open("carriage dump_export.gcode")))
#frame = wx.Frame(None, -1, "GL Window", size=(400, 400)) #frame = wx.Frame(None, -1, "GL Window", size = (400, 400))
#panel = TestGlPanel(frame) #panel = TestGlPanel(frame)
#frame.Show(True) #frame.Show(True)
#app.MainLoop() #app.MainLoop()
......
...@@ -4,8 +4,8 @@ ...@@ -4,8 +4,8 @@
import wx import wx
def AddEllipticalArc(self, x, y, w, h, startAngle, endAngle, clockwise=False): def AddEllipticalArc(self, x, y, w, h, startAngle, endAngle, clockwise = False):
""" Draws an arc of an ellipse within bounding rect (x,y,w,h) """ Draws an arc of an ellipse within bounding rect (x, y,w, h)
from startArc to endArc (in radians, relative to the horizontal line of the eclipse)""" from startArc to endArc (in radians, relative to the horizontal line of the eclipse)"""
if True: if True:
......
...@@ -22,7 +22,7 @@ colorDeclaration = none | currentColor | colourValue ...@@ -22,7 +22,7 @@ colorDeclaration = none | currentColor | colourValue
urlEnd = ( urlEnd = (
Literal(")").suppress() + Literal(")").suppress() +
Optional(Group(colorDeclaration), default=()) + Optional(Group(colorDeclaration), default = ()) +
StringEnd() StringEnd()
) )
...@@ -30,12 +30,12 @@ url = ( ...@@ -30,12 +30,12 @@ url = (
CaselessLiteral("URL") CaselessLiteral("URL")
+ +
Literal("(").suppress()+ Literal("(").suppress()+
Group(SkipTo(urlEnd, include=True).setParseAction(parsePossibleURL)) Group(SkipTo(urlEnd, include = True).setParseAction(parsePossibleURL))
) )
#paint value will parse into a (type, details) tuple. #paint value will parse into a (type, details) tuple.
#For none and currentColor, the details tuple will be the empty tuple #For none and currentColor, the details tuple will be the empty tuple
#for CSS color declarations, it will be (type, (R,G,B)) #for CSS color declarations, it will be (type, (R, G,B))
#for URLs, it will be ("URL", ((url tuple), fallback)) #for URLs, it will be ("URL", ((url tuple), fallback))
#The url tuple will be as returned by urlparse.urlsplit, and can be #The url tuple will be as returned by urlparse.urlsplit, and can be
#an empty tuple if the parser has an error #an empty tuple if the parser has an error
......
...@@ -14,22 +14,22 @@ from svg.css.colour import colourValue ...@@ -14,22 +14,22 @@ from svg.css.colour import colourValue
from svg.css import values from svg.css import values
from attributes import paintValue from attributes import paintValue
document = """<?xml version="1.0" standalone="no"?> document = """<?xml version = "1.0" standalone = "no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="4cm" height="4cm" viewBox="0 0 400 400" <svg width = "4cm" height = "4cm" viewBox = "0 0 400 400"
xmlns="http://www.w3.org/2000/svg" version="1.1"> xmlns = "http://www.w3.org/2000/svg" version = "1.1">
<title>Example triangle01- simple example of a 'path'</title> <title>Example triangle01- simple example of a 'path'</title>
<desc>A path that draws a triangle</desc> <desc>A path that draws a triangle</desc>
<rect x="1" y="1" width="398" height="398" <rect x = "1" y = "1" width = "398" height = "398"
fill="none" stroke="blue" /> fill = "none" stroke = "blue" />
<path d="M 100 100 L 300 100 L 200 300 z" <path d = "M 100 100 L 300 100 L 200 300 z"
fill="red" stroke="blue" stroke-width="3" /> fill = "red" stroke = "blue" stroke-width = "3" />
</svg>""" </svg>"""
makePath = lambda: wx.GraphicsRenderer_GetDefaultRenderer().CreatePath() makePath = lambda: wx.GraphicsRenderer_GetDefaultRenderer().CreatePath()
def attrAsFloat(node, attr, defaultValue="0"): def attrAsFloat(node, attr, defaultValue = "0"):
val = node.get(attr, defaultValue) val = node.get(attr, defaultValue)
#TODO: process stuff like "inherit" by walking back up the nodes #TODO: process stuff like "inherit" by walking back up the nodes
#fast path optimization - if it's a valid float, don't #fast path optimization - if it's a valid float, don't
...@@ -39,7 +39,7 @@ def attrAsFloat(node, attr, defaultValue="0"): ...@@ -39,7 +39,7 @@ def attrAsFloat(node, attr, defaultValue="0"):
except ValueError: except ValueError:
return valueToPixels(val) return valueToPixels(val)
def valueToPixels(val, defaultUnits="px"): def valueToPixels(val, defaultUnits = "px"):
#TODO manage default units #TODO manage default units
from pyparsing import ParseException from pyparsing import ParseException
try: try:
...@@ -175,14 +175,14 @@ class SVGDocument(object): ...@@ -175,14 +175,14 @@ class SVGDocument(object):
) )
if transform == 'skewX': if transform == 'skewX':
matrix = wx.GraphicsRenderer_GetDefaultRenderer().CreateMatrix( matrix = wx.GraphicsRenderer_GetDefaultRenderer().CreateMatrix(
1,0,math.tan(math.radians(args[0])),1,0,0 1, 0,math.tan(math.radians(args[0])),1, 0,0
) )
ops.append( ops.append(
(wx.GraphicsContext.ConcatTransform, (matrix,)) (wx.GraphicsContext.ConcatTransform, (matrix,))
) )
if transform == 'skewY': if transform == 'skewY':
matrix = wx.GraphicsRenderer_GetDefaultRenderer().CreateMatrix( matrix = wx.GraphicsRenderer_GetDefaultRenderer().CreateMatrix(
1,math.tan(math.radians(args[0])),0,1,0,0 1, math.tan(math.radians(args[0])),0, 1,0, 0
) )
ops.append( ops.append(
(wx.GraphicsContext.ConcatTransform, (matrix,)) (wx.GraphicsContext.ConcatTransform, (matrix,))
...@@ -231,7 +231,7 @@ class SVGDocument(object): ...@@ -231,7 +231,7 @@ class SVGDocument(object):
def addTextToDocument(self, node): def addTextToDocument(self, node):
x, y = [attrAsFloat(node, attr) for attr in ('x', 'y')] x, y = [attrAsFloat(node, attr) for attr in ('x', 'y')]
def DoDrawText(context, text, x, y, brush=wx.NullGraphicsBrush): def DoDrawText(context, text, x, y, brush = wx.NullGraphicsBrush):
#SVG spec appears to originate text from the bottom #SVG spec appears to originate text from the bottom
#rather than the top as with our API. This function #rather than the top as with our API. This function
#will measure and then re-orient the text as needed. #will measure and then re-orient the text as needed.
...@@ -259,7 +259,7 @@ class SVGDocument(object): ...@@ -259,7 +259,7 @@ class SVGDocument(object):
rx = node.get('rx') rx = node.get('rx')
ry = node.get('ry') ry = node.get('ry')
if not (w and h): if not (w and h):
path.MoveToPoint(x,y) #keep the current point correct path.MoveToPoint(x, y) #keep the current point correct
return return
if rx or ry: if rx or ry:
if rx and ry: if rx and ry:
...@@ -449,7 +449,7 @@ class SVGDocument(object): ...@@ -449,7 +449,7 @@ class SVGDocument(object):
pen.SetJoin(joinmap.get(self.state.get('stroke-linejoin', None), wx.JOIN_MITER)) pen.SetJoin(joinmap.get(self.state.get('stroke-linejoin', None), wx.JOIN_MITER))
return wx.GraphicsRenderer_GetDefaultRenderer().CreatePen(pen) return wx.GraphicsRenderer_GetDefaultRenderer().CreatePen(pen)
def getBrushFromState(self, path=None): def getBrushFromState(self, path = None):
brushcolour = self.state.get('fill', 'black').strip() brushcolour = self.state.get('fill', 'black').strip()
type, details = paintValue.parseString(brushcolour) type, details = paintValue.parseString(brushcolour)
if type == "URL": if type == "URL":
...@@ -465,29 +465,29 @@ class SVGDocument(object): ...@@ -465,29 +465,29 @@ class SVGDocument(object):
box = path.GetBox() box = path.GetBox()
x, y, w, h = box.Get() x, y, w, h = box.Get()
return wx.GraphicsRenderer.GetDefaultRenderer().CreateLinearGradientBrush( return wx.GraphicsRenderer.GetDefaultRenderer().CreateLinearGradientBrush(
x,y,x+w,y+h,wx.Colour(0,0,255,128), wx.RED x, y,x+w, y+h, wx.Colour(0, 0,255, 128), wx.RED
) )
elif element.tag == '{http://www.w3.org/2000/svg}radialGradient': elif element.tag == '{http://www.w3.org/2000/svg}radialGradient':
box = path.GetBox() box = path.GetBox()
x, y, w, h = box.Get() x, y, w, h = box.Get()
#print w #print w
mx = wx.GraphicsRenderer.GetDefaultRenderer().CreateMatrix(x,y,w,h) mx = wx.GraphicsRenderer.GetDefaultRenderer().CreateMatrix(x, y,w, h)
cx, cy = mx.TransformPoint(0.5, 0.5) cx, cy = mx.TransformPoint(0.5, 0.5)
fx, fy = cx, cy fx, fy = cx, cy
return wx.GraphicsRenderer.GetDefaultRenderer().CreateRadialGradientBrush( return wx.GraphicsRenderer.GetDefaultRenderer().CreateRadialGradientBrush(
cx,cy, cx, cy,
fx,fy, fx, fy,
(max(w,h))/2, (max(w, h))/2,
wx.Colour(0,0,255,128), wx.RED wx.Colour(0, 0,255, 128), wx.RED
) )
else: else:
#invlid gradient specified #invlid gradient specified
return wx.NullBrush return wx.NullBrush
r,g,b = 0,0,0 r, g,b = 0, 0,0
if type == 'CURRENTCOLOR': if type == 'CURRENTCOLOR':
type, details = paintValue.parseString(self.state.get('color', 'none')) type, details = paintValue.parseString(self.state.get('color', 'none'))
if type == 'RGB': if type == 'RGB':
r,g,b = details r, g,b = details
elif type == "NONE": elif type == "NONE":
return wx.NullBrush return wx.NullBrush
opacity = self.state.get('fill-opacity', self.state.get('opacity', '1')) opacity = self.state.get('fill-opacity', self.state.get('opacity', '1'))
...@@ -499,9 +499,9 @@ class SVGDocument(object): ...@@ -499,9 +499,9 @@ class SVGDocument(object):
#be created every time anyway in order to pass them, #be created every time anyway in order to pass them,
#defeating the purpose of the cache #defeating the purpose of the cache
try: try:
return SVGDocument.brushCache[(r,g,b,a)] return SVGDocument.brushCache[(r, g,b, a)]
except KeyError: except KeyError:
return SVGDocument.brushCache.setdefault((r,g,b,a), wx.Brush(wx.Colour(r,g,b,a))) return SVGDocument.brushCache.setdefault((r, g,b, a), wx.Brush(wx.Colour(r, g,b, a)))
def resolveURL(self, urlData): def resolveURL(self, urlData):
...@@ -571,7 +571,7 @@ class SVGDocument(object): ...@@ -571,7 +571,7 @@ class SVGDocument(object):
#~ cp = path.GetCurrentPoint() #~ cp = path.GetCurrentPoint()
#~ path.AddCircle(c1x, c1y, 5) #~ path.AddCircle(c1x, c1y, 5)
#~ path.AddCircle(c2x, c2y, 3) #~ path.AddCircle(c2x, c2y, 3)
#~ path.AddCircle(x,y, 7) #~ path.AddCircle(x, y, 7)
#~ path.MoveToPoint(cp) #~ path.MoveToPoint(cp)
#~ print "C", control1, control2, endpoint #~ print "C", control1, control2, endpoint
...@@ -592,7 +592,7 @@ class SVGDocument(object): ...@@ -592,7 +592,7 @@ class SVGDocument(object):
endpoint endpoint
) )
elif type == "Q": elif type == "Q":
(cx, cy), (x,y) = map(normalizePoint, arg) (cx, cy), (x, y) = map(normalizePoint, arg)
self.lastControlQ = (cx, cy) self.lastControlQ = (cx, cy)
path.AddQuadCurveToPoint(cx, cy, x, y) path.AddQuadCurveToPoint(cx, cy, x, y)
elif type == "T": elif type == "T":
...@@ -607,12 +607,12 @@ class SVGDocument(object): ...@@ -607,12 +607,12 @@ class SVGDocument(object):
elif type == "V": elif type == "V":
_, y = normalizePoint((0, arg)) _, y = normalizePoint((0, arg))
x, _ = path.GetCurrentPoint() x, _ = path.GetCurrentPoint()
path.AddLineToPoint(x,y) path.AddLineToPoint(x, y)
elif type == "H": elif type == "H":
x, _ = normalizePoint((arg, 0)) x, _ = normalizePoint((arg, 0))
_, y = path.GetCurrentPoint() _, y = path.GetCurrentPoint()
path.AddLineToPoint(x,y) path.AddLineToPoint(x, y)
elif type == "A": elif type == "A":
#wxGC currently only supports circular arcs, #wxGC currently only supports circular arcs,
...@@ -625,14 +625,14 @@ class SVGDocument(object): ...@@ -625,14 +625,14 @@ class SVGDocument(object):
(x, y) #endpoint on the arc (x, y) #endpoint on the arc
) = arg ) = arg
x, y = normalizePoint((x,y)) x, y = normalizePoint((x, y))
cx, cy = path.GetCurrentPoint() cx, cy = path.GetCurrentPoint()
if (cx, cy) == (x, y): if (cx, cy) == (x, y):
return #noop return #noop
if (rx == 0 or ry == 0): if (rx == 0 or ry == 0):
#no radius is effectively a line #no radius is effectively a line
path.AddLineToPoint(x,y) path.AddLineToPoint(x, y)
return return
#find the center point for the ellipse #find the center point for the ellipse
...@@ -685,7 +685,7 @@ class SVGDocument(object): ...@@ -685,7 +685,7 @@ class SVGDocument(object):
path.MoveToPoint(x, y) path.MoveToPoint(x, y)
#~ npath = makePath() #~ npath = makePath()
#~ npath.AddEllipticalArc(cnx-rx, cny-ry, rx*2, ry*2, firstArc, lastArc, False) #~ npath.AddEllipticalArc(cnx-rx, cny-ry, rx*2, ry*2, firstArc, lastArc, False)
#~ npath.MoveToPoint(x,y) #~ npath.MoveToPoint(x, y)
#~ path.AddPath(npath) #~ path.AddPath(npath)
elif type == 'Z': elif type == 'Z':
......
...@@ -27,12 +27,12 @@ class CaselessPreservingLiteral(CaselessLiteral): ...@@ -27,12 +27,12 @@ class CaselessPreservingLiteral(CaselessLiteral):
instead of as defined. instead of as defined.
""" """
def __init__( self, matchString ): def __init__( self, matchString ):
super(CaselessPreservingLiteral,self).__init__( matchString.upper() ) super(CaselessPreservingLiteral, self).__init__( matchString.upper() )
self.name = "'%s'" % matchString self.name = "'%s'" % matchString
self.errmsg = "Expected " + self.name self.errmsg = "Expected " + self.name
self.myException.msg = self.errmsg self.myException.msg = self.errmsg
def parseImpl( self, instring, loc, doActions=True ): def parseImpl( self, instring, loc, doActions = True ):
test = instring[ loc:loc+self.matchLen ] test = instring[ loc:loc+self.matchLen ]
if test.upper() == self.match: if test.upper() == self.match:
return loc+self.matchLen, test return loc+self.matchLen, test
...@@ -117,7 +117,7 @@ ellipticalArcArgument = Group( ...@@ -117,7 +117,7 @@ ellipticalArcArgument = Group(
arcRadius + maybeComma + #rx, ry arcRadius + maybeComma + #rx, ry
number + maybeComma +#rotation number + maybeComma +#rotation
arcFlags + #large-arc-flag, sweep-flag arcFlags + #large-arc-flag, sweep-flag
coordinatePair #(x,y) coordinatePair #(x, y)
) )
......
...@@ -8,10 +8,10 @@ from printrun.printrun_utils import configfile, imagefile, sharedfile ...@@ -8,10 +8,10 @@ from printrun.printrun_utils import configfile, imagefile, sharedfile
users = {} users = {}
def PrintHeader(): def PrintHeader():
return '<html>\n<head>\n<title>Pronterface-Web</title>\n<link rel="stylesheet" type="text/css" href="/css/style.css" type="text/css"></link>\n</head>\n<body>\n' return '<html>\n<head>\n<title>Pronterface-Web</title>\n<link rel = "stylesheet" type = "text/css" href = "/css/style.css" type = "text/css"></link>\n</head>\n<body>\n'
def PrintMenu(): def PrintMenu():
return '<div id="mainmenu"><ul><li><a href="/">home</a></li><li><a href="/settings">settings</a></li><li><a href="/console">console</a></li><li><a href="/status">status (XML)</a></li></ul></div>' return '<div id = "mainmenu"><ul><li><a href = "/">home</a></li><li><a href = "/settings">settings</a></li><li><a href = "/console">console</a></li><li><a href = "/status">status (XML)</a></li></ul></div>'
def PrintFooter(): def PrintFooter():
return "</body></html>" return "</body></html>"
...@@ -30,41 +30,41 @@ gWeblog = "" ...@@ -30,41 +30,41 @@ gWeblog = ""
gLogRefresh =5 gLogRefresh =5
class SettingsPage(object): class SettingsPage(object):
def __init__(self): def __init__(self):
self.name="<div id='title'>Pronterface Settings</div>" self.name = "<div id='title'>Pronterface Settings</div>"
def index(self): def index(self):
pageText=PrintHeader()+self.name+PrintMenu() pageText = PrintHeader()+self.name+PrintMenu()
pageText=pageText+"<div id='settings'><table>\n<tr><th>setting</th><th>value</th>" pageText = pageText+"<div id='settings'><table>\n<tr><th>setting</th><th>value</th>"
pageText=pageText+"<tr>\n <td><b>Build Dimenstions</b></td><td>"+str(gPronterPtr.settings.build_dimensions)+"</td>\n</tr>" pageText = pageText+"<tr>\n <td><b>Build Dimenstions</b></td><td>"+str(gPronterPtr.settings.build_dimensions)+"</td>\n</tr>"
pageText=pageText+" <tr>\n <td><b>Last Bed Temp</b></td><td>"+str(gPronterPtr.settings.last_bed_temperature)+"</td>\n</tr>" pageText = pageText+" <tr>\n <td><b>Last Bed Temp</b></td><td>"+str(gPronterPtr.settings.last_bed_temperature)+"</td>\n</tr>"
pageText=pageText+" <tr>\n <td><b>Last File Path</b></td><td>"+gPronterPtr.settings.last_file_path+"</td>\n</tr>" pageText = pageText+" <tr>\n <td><b>Last File Path</b></td><td>"+gPronterPtr.settings.last_file_path+"</td>\n</tr>"
pageText=pageText+" <tr>\n <td><b>Last Temperature</b></td><td>"+str(gPronterPtr.settings.last_temperature)+"</td>\n</tr>" pageText = pageText+" <tr>\n <td><b>Last Temperature</b></td><td>"+str(gPronterPtr.settings.last_temperature)+"</td>\n</tr>"
pageText=pageText+" <tr>\n <td><b>Preview Extrusion Width</b></td><td>"+str(gPronterPtr.settings.preview_extrusion_width)+"</td>\n</tr>" pageText = pageText+" <tr>\n <td><b>Preview Extrusion Width</b></td><td>"+str(gPronterPtr.settings.preview_extrusion_width)+"</td>\n</tr>"
pageText=pageText+" <tr>\n <td><b>Filename</b></td><td>"+str(gPronterPtr.filename)+"</td></tr></div>" pageText = pageText+" <tr>\n <td><b>Filename</b></td><td>"+str(gPronterPtr.filename)+"</td></tr></div>"
pageText=pageText+PrintFooter() pageText = pageText+PrintFooter()
return pageText return pageText
index.exposed = True index.exposed = True
class LogPage(object): class LogPage(object):
def __init__(self): def __init__(self):
self.name="<div id='title'>Pronterface Console</div>" self.name = "<div id='title'>Pronterface Console</div>"
def index(self): def index(self):
pageText="<html><head><meta http-equiv='refresh' content='"+str(gLogRefresh)+"'></head><body>" pageText = "<html><head><meta http-equiv='refresh' content='"+str(gLogRefresh)+"'></head><body>"
pageText+="<div id='status'>" pageText+="<div id='status'>"
pageText+=gPronterPtr.status.GetStatusText() pageText+=gPronterPtr.status.GetStatusText()
pageText+="</div>" pageText+="</div>"
pageText=pageText+"<div id='console'>"+gWeblog+"</div>" pageText = pageText+"<div id='console'>"+gWeblog+"</div>"
pageText=pageText+"</body></html>" pageText = pageText+"</body></html>"
return pageText return pageText
index.exposed = True index.exposed = True
class ConsolePage(object): class ConsolePage(object):
def __init__(self): def __init__(self):
self.name="<div id='title'>Pronterface Settings</div>" self.name = "<div id='title'>Pronterface Settings</div>"
def index(self): def index(self):
pageText=PrintHeader()+self.name+PrintMenu() pageText = PrintHeader()+self.name+PrintMenu()
pageText+="<div id='logframe'><iframe src='/logpage' width='100%' height='100%'>iFraming Not Supported?? No log for you.</iframe></div>" pageText+="<div id='logframe'><iframe src='/logpage' width='100%' height='100%'>iFraming Not Supported?? No log for you.</iframe></div>"
pageText+=PrintFooter() pageText+=PrintFooter()
return pageText return pageText
...@@ -129,7 +129,7 @@ class MoveButton(object): ...@@ -129,7 +129,7 @@ class MoveButton(object):
def axis(self, *args): def axis(self, *args):
if not args: if not args:
raise cherrypy.HTTPError(400, "No Move Command Provided!") raise cherrypy.HTTPError(400, "No Move Command Provided!")
margs=list(args) margs = list(args)
axis = margs.pop(0) axis = margs.pop(0)
if(margs and axis == "x"): if(margs and axis == "x"):
distance = margs.pop(0) distance = margs.pop(0)
...@@ -154,7 +154,7 @@ class CustomButton(object): ...@@ -154,7 +154,7 @@ class CustomButton(object):
def button(self, *args): def button(self, *args):
if not args: if not args:
raise cherrypy.HTTPError(400, "No Custom Command Provided!") raise cherrypy.HTTPError(400, "No Custom Command Provided!")
margs=list(args) margs = list(args)
command = margs.pop(0) command = margs.pop(0)
if(command): if(command):
gPronterPtr.onecmd(command) gPronterPtr.onecmd(command)
...@@ -169,7 +169,7 @@ class HomeButton(object): ...@@ -169,7 +169,7 @@ class HomeButton(object):
def axis(self, *args): def axis(self, *args):
if not args: if not args:
raise cherrypy.HTTPError(400, "No Axis Provided!") raise cherrypy.HTTPError(400, "No Axis Provided!")
margs=list(args) margs = list(args)
taxis = margs.pop(0) taxis = margs.pop(0)
if(taxis == "x"): if(taxis == "x"):
gPronterPtr.onecmd('home X') gPronterPtr.onecmd('home X')
...@@ -193,31 +193,31 @@ class HomeButton(object): ...@@ -193,31 +193,31 @@ class HomeButton(object):
class XMLstatus(object): class XMLstatus(object):
def index(self): def index(self):
#handle connect push, then reload page #handle connect push, then reload page
txt='<?xml version="1.0"?>\n<pronterface>\n' txt='<?xml version = "1.0"?>\n<pronterface>\n'
state="Offline" state = "Offline"
if gPronterPtr.statuscheck or gPronterPtr.p.online: if gPronterPtr.statuscheck or gPronterPtr.p.online:
state="Idle" state = "Idle"
if gPronterPtr.sdprinting: if gPronterPtr.sdprinting:
state="SDPrinting" state = "SDPrinting"
if gPronterPtr.p.printing: if gPronterPtr.p.printing:
state="Printing" state = "Printing"
if gPronterPtr.paused: if gPronterPtr.paused:
state="Paused" state = "Paused"
txt=txt+'<state>'+state+'</state>\n' txt = txt+'<state>'+state+'</state>\n'
txt=txt+'<file>'+str(gPronterPtr.filename)+'</file>\n' txt = txt+'<file>'+str(gPronterPtr.filename)+'</file>\n'
txt=txt+'<status>'+str(gPronterPtr.status.GetStatusText())+'</status>\n' txt = txt+'<status>'+str(gPronterPtr.status.GetStatusText())+'</status>\n'
try: try:
temp = str(float(filter(lambda x:x.startswith("T:"),gPronterPtr.tempreport.split())[0].split(":")[1])) temp = str(float(filter(lambda x:x.startswith("T:"),gPronterPtr.tempreport.split())[0].split(":")[1]))
txt=txt+'<hotend>'+temp+'</hotend>\n' txt = txt+'<hotend>'+temp+'</hotend>\n'
except: except:
txt=txt+'<hotend>NA</hotend>\n' txt = txt+'<hotend>NA</hotend>\n'
pass pass
try: try:
temp = str(float(filter(lambda x:x.startswith("B:"),gPronterPtr.tempreport.split())[0].split(":")[1])) temp = str(float(filter(lambda x:x.startswith("B:"),gPronterPtr.tempreport.split())[0].split(":")[1]))
txt=txt+'<bed>'+temp+'</bed>\n' txt = txt+'<bed>'+temp+'</bed>\n'
except: except:
txt=txt+'<bed>NA</bed>\n' txt = txt+'<bed>NA</bed>\n'
pass pass
if gPronterPtr.sdprinting: if gPronterPtr.sdprinting:
fractioncomplete = float(gPronterPtr.percentdone/100.0) fractioncomplete = float(gPronterPtr.percentdone/100.0)
...@@ -238,7 +238,7 @@ class WebInterface(object): ...@@ -238,7 +238,7 @@ class WebInterface(object):
def __init__(self, pface): def __init__(self, pface):
if (sys.version_info[1] > 6): if (sys.version_info[1] > 6):
# 'allow_no_value' wasn't added until 2.7 # 'allow_no_value' wasn't added until 2.7
config = ConfigParser.SafeConfigParser(allow_no_value=True) config = ConfigParser.SafeConfigParser(allow_no_value = True)
else: else:
config = ConfigParser.SafeConfigParser() config = ConfigParser.SafeConfigParser()
config.read(configfile(pface.web_auth_config or 'auth.config')) config.read(configfile(pface.web_auth_config or 'auth.config'))
...@@ -246,7 +246,7 @@ class WebInterface(object): ...@@ -246,7 +246,7 @@ class WebInterface(object):
self.pface = pface self.pface = pface
global gPronterPtr global gPronterPtr
global gWeblog global gWeblog
self.name="<div id='title'>Pronterface Web-Interface</div>" self.name = "<div id='title'>Pronterface Web-Interface</div>"
gWeblog = "" gWeblog = ""
gPronterPtr = self.pface gPronterPtr = self.pface
...@@ -266,7 +266,7 @@ class WebInterface(object): ...@@ -266,7 +266,7 @@ class WebInterface(object):
custom =CustomButton() custom =CustomButton()
def index(self): def index(self):
pageText=PrintHeader()+self.name+PrintMenu() pageText = PrintHeader()+self.name+PrintMenu()
pageText+="<div id='content'>\n" pageText+="<div id='content'>\n"
pageText+="<div id='controls'>\n" pageText+="<div id='controls'>\n"
pageText+="<ul><li><a href='/connect'>Connect</a></li>\n" pageText+="<ul><li><a href='/connect'>Connect</a></li>\n"
...@@ -286,40 +286,40 @@ class WebInterface(object): ...@@ -286,40 +286,40 @@ class WebInterface(object):
pageText+="<div id='gui'>\n" pageText+="<div id='gui'>\n"
pageText+="<div id='control_xy'>" pageText+="<div id='control_xy'>"
pageText+="<img src='/images/control_xy.png' usemap='#xymap'/>" pageText+="<img src='/images/control_xy.png' usemap='#xymap'/>"
pageText+='<map name="xymap">' pageText+='<map name = "xymap">'
pageText+='<area shape="rect" coords="8,5,51,48" href="/home/axis/x" alt="X Home" title="X Home" />' pageText+='<area shape = "rect" coords = "8, 5,51, 48" href = "/home/axis/x" alt = "X Home" title = "X Home" />'
pageText+='<area shape="rect" coords="195,6,236,46" href="/home/axis/y" alt="Y Home" title="Y Home" />' pageText+='<area shape = "rect" coords = "195, 6,236, 46" href = "/home/axis/y" alt = "Y Home" title = "Y Home" />'
pageText+='<area shape="rect" coords="7,192,48,232" href="/home/axis/all" alt="All Home" title="All Home" />' pageText+='<area shape = "rect" coords = "7, 192, 48, 232" href = "/home/axis/all" alt = "All Home" title = "All Home" />'
pageText+='<area shape="rect" coords="194,192,235,232" href="/home/axis/z" alt="Z Home" title="Z Home" />' pageText+='<area shape = "rect" coords = "194, 192, 235, 232" href = "/home/axis/z" alt = "Z Home" title = "Z Home" />'
pageText+='<area shape="rect" coords="62,7,185,34" href="/move/axis/y/100" alt="Y 100" title="Y 100" />' pageText+='<area shape = "rect" coords = "62, 7,185, 34" href = "/move/axis/y/100" alt = "Y 100" title = "Y 100" />'
pageText+='<area shape="rect" coords="68,34,175,61" href="/move/axis/y/10" alt="Y 10" title="Y 10" />' pageText+='<area shape = "rect" coords = "68, 34, 175, 61" href = "/move/axis/y/10" alt = "Y 10" title = "Y 10" />'
pageText+='<area shape="rect" coords="80,60,163,84" href="/move/axis/y/1" alt="Y 1" title="Y 1" />' pageText+='<area shape = "rect" coords = "80, 60, 163, 84" href = "/move/axis/y/1" alt = "Y 1" title = "Y 1" />'
pageText+='<area shape="rect" coords="106,83,138,107" href="/move/axis/y/.1" alt="Y .1" title="Y .1" />' pageText+='<area shape = "rect" coords = "106, 83, 138, 107" href = "/move/axis/y/.1" alt = "Y .1" title = "Y .1" />'
pageText+='<area shape="rect" coords="110,135,142,159" href="/move/axis/y/-.1" alt="Y -.1" title="Y -.1" />' pageText+='<area shape = "rect" coords = "110, 135, 142, 159" href = "/move/axis/y/-.1" alt = "Y -.1" title = "Y -.1" />'
pageText+='<area shape="rect" coords="81,157,169,181" href="/move/axis/y/-1" alt="Y -1" title="Y -1" />' pageText+='<area shape = "rect" coords = "81, 157, 169, 181" href = "/move/axis/y/-1" alt = "Y -1" title = "Y -1" />'
pageText+='<area shape="rect" coords="69,180,178,206" href="/move/axis/y/-10" alt="Y -10" title="Y -10" />' pageText+='<area shape = "rect" coords = "69, 180, 178, 206" href = "/move/axis/y/-10" alt = "Y -10" title = "Y -10" />'
pageText+='<area shape="rect" coords="60,205,186,231" href="/move/axis/y/-100" alt="Y -100" title="Y -100" />' pageText+='<area shape = "rect" coords = "60, 205, 186, 231" href = "/move/axis/y/-100" alt = "Y -100" title = "Y -100" />'
pageText+='<area shape="rect" coords="11,53,37,179" href="/move/axis/x/-100" alt="X -100" title="X -100" />' pageText+='<area shape = "rect" coords = "11, 53, 37, 179" href = "/move/axis/x/-100" alt = "X -100" title = "X -100" />'
pageText+='<area shape="rect" coords="210,59,236,185" href="/move/axis/x/100" alt="X 100" title="X 100" />' pageText+='<area shape = "rect" coords = "210, 59, 236, 185" href = "/move/axis/x/100" alt = "X 100" title = "X 100" />'
pageText+='<area shape="rect" coords="38,60,64,172" href="/move/axis/x/-10" alt="X -10" title="X -10" />' pageText+='<area shape = "rect" coords = "38, 60, 64, 172" href = "/move/axis/x/-10" alt = "X -10" title = "X -10" />'
pageText+='<area shape="rect" coords="185,66,211,178" href="/move/axis/x/10" alt="X 10" title="X 10" />' pageText+='<area shape = "rect" coords = "185, 66, 211, 178" href = "/move/axis/x/10" alt = "X 10" title = "X 10" />'
pageText+='<area shape="rect" coords="62,84,83,157" href="/move/axis/x/-1" alt="X -1" title="X -1" />' pageText+='<area shape = "rect" coords = "62, 84, 83, 157" href = "/move/axis/x/-1" alt = "X -1" title = "X -1" />'
pageText+='<area shape="rect" coords="163,87,187,160" href="/move/axis/x/1" alt="X 1" title="X 1" />' pageText+='<area shape = "rect" coords = "163, 87, 187, 160" href = "/move/axis/x/1" alt = "X 1" title = "X 1" />'
pageText+='<area shape="rect" coords="82,104,110,139" href="/move/axis/x/-.1" alt="X -.1" title="X -.1" />' pageText+='<area shape = "rect" coords = "82, 104, 110, 139" href = "/move/axis/x/-.1" alt = "X -.1" title = "X -.1" />'
pageText+='<area shape="rect" coords="137,105,165,140" href="/move/axis/x/.1" alt="X .1" title="X .1" />' pageText+='<area shape = "rect" coords = "137, 105, 165, 140" href = "/move/axis/x/.1" alt = "X .1" title = "X .1" />'
pageText+="</map>" pageText+="</map>"
pageText+="</div>\n" #endxy pageText+="</div>\n" #endxy
pageText+="<div id='control_z'>" pageText+="<div id='control_z'>"
pageText+="<img src='/images/control_z.png' usemap='#zmap'/>" pageText+="<img src='/images/control_z.png' usemap='#zmap'/>"
pageText+='<map name="zmap">' pageText+='<map name = "zmap">'
pageText+='<area shape="rect" coords="4,35,54,64" href="/move/axis/z/10" alt="Z 10" title="Z 10" />' pageText+='<area shape = "rect" coords = "4, 35, 54, 64" href = "/move/axis/z/10" alt = "Z 10" title = "Z 10" />'
pageText+='<area shape="rect" coords="4,60,54,89" href="/move/axis/z/1" alt="Z 1" title="Z 1" />' pageText+='<area shape = "rect" coords = "4, 60, 54, 89" href = "/move/axis/z/1" alt = "Z 1" title = "Z 1" />'
pageText+='<area shape="rect" coords="4,87,54,116" href="/move/axis/z/.1" alt="Z .1" title="Z .1" />' pageText+='<area shape = "rect" coords = "4, 87, 54, 116" href = "/move/axis/z/.1" alt = "Z .1" title = "Z .1" />'
pageText+='<area shape="rect" coords="4,121,54,150" href="/move/axis/z/-.1" alt="Z -.1" title="Z -.1" />' pageText+='<area shape = "rect" coords = "4, 121, 54, 150" href = "/move/axis/z/-.1" alt = "Z -.1" title = "Z -.1" />'
pageText+='<area shape="rect" coords="4,147,54,176" href="/move/axis/z/-1" alt="Z -1" title="Z -1" />' pageText+='<area shape = "rect" coords = "4, 147, 54, 176" href = "/move/axis/z/-1" alt = "Z -1" title = "Z -1" />'
pageText+='<area shape="rect" coords="4,173,54,202" href="/move/axis/z/-10" alt="Z -10" title="Z -10" />' pageText+='<area shape = "rect" coords = "4, 173, 54, 202" href = "/move/axis/z/-10" alt = "Z -10" title = "Z -10" />'
pageText+="</map>" pageText+="</map>"
#TODO Map Z Moves #TODO Map Z Moves
pageText+="</div>\n" #endz pageText+="</div>\n" #endz
...@@ -337,17 +337,17 @@ class WebInterface(object): ...@@ -337,17 +337,17 @@ class WebInterface(object):
# pageText+="</div>" # pageText+="</div>"
# pageText+="</div>" # pageText+="</div>"
pageText=pageText+"<div id='file'>File Loaded: <i>"+str(gPronterPtr.filename)+"</i></div>" pageText = pageText+"<div id='file'>File Loaded: <i>"+str(gPronterPtr.filename)+"</i></div>"
pageText+="<div id='logframe'><iframe src='/logpage' width='100%' height='100%'>iFraming Not Supported?? No log for you.</iframe></div>" pageText+="<div id='logframe'><iframe src='/logpage' width='100%' height='100%'>iFraming Not Supported?? No log for you.</iframe></div>"
pageText+=PrintFooter() pageText+=PrintFooter()
return pageText return pageText
def AddLog(self, log): def AddLog(self, log):
global gWeblog global gWeblog
gWeblog=gWeblog+"</br>"+log gWeblog = gWeblog+"</br>"+log
def AppendLog(self, log): def AppendLog(self, log):
global gWeblog global gWeblog
gWeblog=re.sub("\n", "</br>", gWeblog)+log gWeblog = re.sub("\n", "</br>", gWeblog)+log
index.exposed = True index.exposed = True
class WebInterfaceStub(object): class WebInterfaceStub(object):
...@@ -372,7 +372,7 @@ def StartWebInterfaceThread(webInterface): ...@@ -372,7 +372,7 @@ def StartWebInterfaceThread(webInterface):
'tools.staticfile.filename': imagefile('control_z.png'), 'tools.staticfile.filename': imagefile('control_z.png'),
}} }}
cherrypy.config.update(configfile(webInterface.pface.web_config or "http.config")) cherrypy.config.update(configfile(webInterface.pface.web_config or "http.config"))
cherrypy.quickstart(webInterface, '/', config=conf) cherrypy.quickstart(webInterface, '/', config = conf)
if __name__ == '__main__': if __name__ == '__main__':
cherrypy.config.update(configfile("http.config")) cherrypy.config.update(configfile("http.config"))
......
...@@ -41,7 +41,7 @@ class XYButtons(BufferedCanvas): ...@@ -41,7 +41,7 @@ class XYButtons(BufferedCanvas):
center = (124, 121) center = (124, 121)
spacer = 7 spacer = 7
def __init__(self, parent, moveCallback=None, cornerCallback=None, spacebarCallback=None, bgcolor="#FFFFFF", ID=-1): def __init__(self, parent, moveCallback = None, cornerCallback = None, spacebarCallback = None, bgcolor = "#FFFFFF", ID=-1):
self.bg_bmp = wx.Image(imagefile("control_xy.png"),wx.BITMAP_TYPE_PNG).ConvertToBitmap() self.bg_bmp = wx.Image(imagefile("control_xy.png"),wx.BITMAP_TYPE_PNG).ConvertToBitmap()
self.keypad_bmp = wx.Image(imagefile("arrow_keys.png"),wx.BITMAP_TYPE_PNG).ConvertToBitmap() self.keypad_bmp = wx.Image(imagefile("arrow_keys.png"),wx.BITMAP_TYPE_PNG).ConvertToBitmap()
self.keypad_idx = -1 self.keypad_idx = -1
...@@ -181,7 +181,7 @@ class XYButtons(BufferedCanvas): ...@@ -181,7 +181,7 @@ class XYButtons(BufferedCanvas):
self.drawPartialPie(gc, center, r1-inner_ring_radius, r2-inner_ring_radius, a1+fudge, a2-fudge) self.drawPartialPie(gc, center, r1-inner_ring_radius, r2-inner_ring_radius, a1+fudge, a2-fudge)
def drawCorner(self, gc, x, y, angle=0.0): def drawCorner(self, gc, x, y, angle = 0.0):
w, h = XYButtons.corner_size w, h = XYButtons.corner_size
gc.PushState() gc.PushState()
...@@ -197,7 +197,7 @@ class XYButtons(BufferedCanvas): ...@@ -197,7 +197,7 @@ class XYButtons(BufferedCanvas):
gc.DrawPath(path) gc.DrawPath(path)
gc.PopState() gc.PopState()
def highlightCorner(self, gc, corner=0): def highlightCorner(self, gc, corner = 0):
w, h = XYButtons.corner_size w, h = XYButtons.corner_size
cx, cy = XYButtons.center cx, cy = XYButtons.center
ww, wh = self.GetSizeTuple() ww, wh = self.GetSizeTuple()
...@@ -229,8 +229,8 @@ class XYButtons(BufferedCanvas): ...@@ -229,8 +229,8 @@ class XYButtons(BufferedCanvas):
if self.enabled: if self.enabled:
# Brush and pen for grey overlay when mouse hovers over # Brush and pen for grey overlay when mouse hovers over
gc.SetPen(wx.Pen(wx.Colour(100,100,100,172), 4)) gc.SetPen(wx.Pen(wx.Colour(100, 100, 100, 172), 4))
gc.SetBrush(wx.Brush(wx.Colour(0,0,0,128))) gc.SetBrush(wx.Brush(wx.Colour(0, 0,0, 128)))
if self.concentric != None: if self.concentric != None:
if self.concentric < len(XYButtons.concentric_circle_radii): if self.concentric < len(XYButtons.concentric_circle_radii):
...@@ -246,8 +246,8 @@ class XYButtons(BufferedCanvas): ...@@ -246,8 +246,8 @@ class XYButtons(BufferedCanvas):
gc.DrawBitmap(self.keypad_bmp, pos[0], pos[1], padw, padh) gc.DrawBitmap(self.keypad_bmp, pos[0], pos[1], padw, padh)
# Draw label overlays # Draw label overlays
gc.SetPen(wx.Pen(wx.Colour(255,255,255,128), 1)) gc.SetPen(wx.Pen(wx.Colour(255, 255, 255, 128), 1))
gc.SetBrush(wx.Brush(wx.Colour(255,255,255,128+64))) gc.SetBrush(wx.Brush(wx.Colour(255, 255, 255, 128+64)))
for idx, kpos in XYButtons.label_overlay_positions.items(): for idx, kpos in XYButtons.label_overlay_positions.items():
if idx != self.concentric: if idx != self.concentric:
r = kpos[2] r = kpos[2]
......
...@@ -32,7 +32,7 @@ class ZButtons(BufferedCanvas): ...@@ -32,7 +32,7 @@ class ZButtons(BufferedCanvas):
3: None 3: None
} }
def __init__(self, parent, moveCallback=None, bgcolor="#FFFFFF", ID=-1): def __init__(self, parent, moveCallback = None, bgcolor = "#FFFFFF", ID=-1):
self.bg_bmp = wx.Image(imagefile("control_z.png"),wx.BITMAP_TYPE_PNG).ConvertToBitmap() self.bg_bmp = wx.Image(imagefile("control_z.png"),wx.BITMAP_TYPE_PNG).ConvertToBitmap()
self.range = None self.range = None
self.direction = None self.direction = None
...@@ -108,16 +108,16 @@ class ZButtons(BufferedCanvas): ...@@ -108,16 +108,16 @@ class ZButtons(BufferedCanvas):
if self.enabled: if self.enabled:
# Draw label overlays # Draw label overlays
gc.SetPen(wx.Pen(wx.Colour(255,255,255,128), 1)) gc.SetPen(wx.Pen(wx.Colour(255, 255, 255, 128), 1))
gc.SetBrush(wx.Brush(wx.Colour(255,255,255,128+64))) gc.SetBrush(wx.Brush(wx.Colour(255, 255, 255, 128+64)))
for idx, kpos in ZButtons.label_overlay_positions.items(): for idx, kpos in ZButtons.label_overlay_positions.items():
if kpos and idx != self.range: if kpos and idx != self.range:
r = kpos[2] r = kpos[2]
gc.DrawEllipse(ZButtons.center[0]-kpos[0]-r, ZButtons.center[1]-kpos[1]-r, r*2, r*2) gc.DrawEllipse(ZButtons.center[0]-kpos[0]-r, ZButtons.center[1]-kpos[1]-r, r*2, r*2)
# Top 'layer' is the mouse-over highlights # Top 'layer' is the mouse-over highlights
gc.SetPen(wx.Pen(wx.Colour(100,100,100,172), 4)) gc.SetPen(wx.Pen(wx.Colour(100, 100, 100, 172), 4))
gc.SetBrush(wx.Brush(wx.Colour(0,0,0,128))) gc.SetBrush(wx.Brush(wx.Colour(0, 0,0, 128)))
if self.range != None and self.direction != None: if self.range != None and self.direction != None:
self.highlight(gc, self.range, self.direction) self.highlight(gc, self.range, self.direction)
else: else:
......
...@@ -13,63 +13,63 @@ ...@@ -13,63 +13,63 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>. # along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import wx,math import wx, math
from stltool import * from stltool import *
a=wx.App() a = wx.App()
def genscape(data=[[0,1,0,0],[1,0,2,0],[1,0,0,0],[0,1,0,1]],pscale=1.0,bheight=1.0,zscale=1.0): def genscape(data=[[0, 1,0, 0],[1, 0,2, 0],[1, 0,0, 0],[0, 1,0, 1]],pscale = 1.0, bheight = 1.0, zscale = 1.0):
o=stl(None) o = stl(None)
datal=len(data) datal = len(data)
datah=len(data[0]) datah = len(data[0])
#create bottom: #create bottom:
bmidpoint=(pscale*(datal-1)/2.0,pscale*(datah-1)/2.0) bmidpoint = (pscale*(datal-1)/2.0, pscale*(datah-1)/2.0)
#print range(datal),bmidpoint #print range(datal),bmidpoint
for i in zip(range(datal+1)[:-1],range(datal+1)[1:])[:-1]: for i in zip(range(datal+1)[:-1],range(datal+1)[1:])[:-1]:
#print (pscale*i[0],pscale*i[1]) #print (pscale*i[0],pscale*i[1])
o.facets+=[[[0,0,-1],[[0.0,pscale*i[0],0.0],[0.0,pscale*i[1],0.0],[bmidpoint[0],bmidpoint[1],0.0]]]] o.facets+=[[[0, 0,-1],[[0.0, pscale*i[0],0.0],[0.0, pscale*i[1],0.0],[bmidpoint[0],bmidpoint[1],0.0]]]]
o.facets+=[[[0,0,-1],[[2.0*bmidpoint[1],pscale*i[1],0.0],[2.0*bmidpoint[1],pscale*i[0],0.0],[bmidpoint[0],bmidpoint[1],0.0]]]] o.facets+=[[[0, 0,-1],[[2.0*bmidpoint[1],pscale*i[1],0.0],[2.0*bmidpoint[1],pscale*i[0],0.0],[bmidpoint[0],bmidpoint[1],0.0]]]]
o.facets+=[genfacet([[0.0,pscale*i[0],data[i[0]][0]*zscale+bheight],[0.0,pscale*i[1],data[i[1]][0]*zscale+bheight],[0.0,pscale*i[1],0.0]])] o.facets+=[genfacet([[0.0, pscale*i[0],data[i[0]][0]*zscale+bheight],[0.0, pscale*i[1],data[i[1]][0]*zscale+bheight],[0.0, pscale*i[1],0.0]])]
o.facets+=[genfacet([[2.0*bmidpoint[1],pscale*i[1],data[i[1]][datah-1]*zscale+bheight],[2.0*bmidpoint[1],pscale*i[0],data[i[0]][datah-1]*zscale+bheight],[2.0*bmidpoint[1],pscale*i[1],0.0]])] o.facets+=[genfacet([[2.0*bmidpoint[1],pscale*i[1],data[i[1]][datah-1]*zscale+bheight],[2.0*bmidpoint[1],pscale*i[0],data[i[0]][datah-1]*zscale+bheight],[2.0*bmidpoint[1],pscale*i[1],0.0]])]
o.facets+=[genfacet([[0.0,pscale*i[0],data[i[0]][0]*zscale+bheight],[0.0,pscale*i[1],0.0],[0.0,pscale*i[0],0.0]])] o.facets+=[genfacet([[0.0, pscale*i[0],data[i[0]][0]*zscale+bheight],[0.0, pscale*i[1],0.0],[0.0, pscale*i[0],0.0]])]
o.facets+=[genfacet([[2.0*bmidpoint[1],pscale*i[1],0.0],[2.0*bmidpoint[1],pscale*i[0],data[i[0]][datah-1]*zscale+bheight],[2.0*bmidpoint[1],pscale*i[0],0.0]])] o.facets+=[genfacet([[2.0*bmidpoint[1],pscale*i[1],0.0],[2.0*bmidpoint[1],pscale*i[0],data[i[0]][datah-1]*zscale+bheight],[2.0*bmidpoint[1],pscale*i[0],0.0]])]
#print o.facets[-1] #print o.facets[-1]
pass pass
#print o.facets[-4:] #print o.facets[-4:]
for i in zip(range(datah+1)[:-1],range(datah+1)[1:])[:-1]: for i in zip(range(datah+1)[:-1],range(datah+1)[1:])[:-1]:
#print (pscale*i[0],pscale*i[1]) #print (pscale*i[0],pscale*i[1])
o.facets+=[[[0,0,-1],[[pscale*i[1],0.0,0.0],[pscale*i[0],0.0,0.0],[bmidpoint[0],bmidpoint[1],0.0]]]] o.facets+=[[[0, 0,-1],[[pscale*i[1],0.0, 0.0],[pscale*i[0],0.0, 0.0],[bmidpoint[0],bmidpoint[1],0.0]]]]
o.facets+=[[[0,0,-1],[[pscale*i[0],2.0*bmidpoint[0],0.0],[pscale*i[1],2.0*bmidpoint[0],0.0],[bmidpoint[0],bmidpoint[1],0.0]]]] o.facets+=[[[0, 0,-1],[[pscale*i[0],2.0*bmidpoint[0],0.0],[pscale*i[1],2.0*bmidpoint[0],0.0],[bmidpoint[0],bmidpoint[1],0.0]]]]
o.facets+=[genfacet([[pscale*i[1],0.0,data[0][i[1]]*zscale+bheight],[pscale*i[0],0.0,data[0][i[0]]*zscale+bheight],[pscale*i[1],0.0,0.0]])] o.facets+=[genfacet([[pscale*i[1],0.0, data[0][i[1]]*zscale+bheight],[pscale*i[0],0.0, data[0][i[0]]*zscale+bheight],[pscale*i[1],0.0, 0.0]])]
#break #break
o.facets+=[genfacet([[pscale*i[0],2.0*bmidpoint[0],data[datal-1][i[0]]*zscale+bheight],[pscale*i[1],2.0*bmidpoint[0],data[datal-1][i[1]]*zscale+bheight],[pscale*i[1],2.0*bmidpoint[0],0.0]])] o.facets+=[genfacet([[pscale*i[0],2.0*bmidpoint[0],data[datal-1][i[0]]*zscale+bheight],[pscale*i[1],2.0*bmidpoint[0],data[datal-1][i[1]]*zscale+bheight],[pscale*i[1],2.0*bmidpoint[0],0.0]])]
o.facets+=[genfacet([[pscale*i[1],0.0,0.0],[pscale*i[0],0.0,data[0][i[0]]*zscale+bheight],[pscale*i[0],0.0,0.0]])] o.facets+=[genfacet([[pscale*i[1],0.0, 0.0],[pscale*i[0],0.0, data[0][i[0]]*zscale+bheight],[pscale*i[0],0.0, 0.0]])]
o.facets+=[genfacet([[pscale*i[0],2.0*bmidpoint[0],data[datal-1][i[0]]*zscale+bheight],[pscale*i[1],2.0*bmidpoint[0],0.0],[pscale*i[0],2.0*bmidpoint[0],0.0]])] o.facets+=[genfacet([[pscale*i[0],2.0*bmidpoint[0],data[datal-1][i[0]]*zscale+bheight],[pscale*i[1],2.0*bmidpoint[0],0.0],[pscale*i[0],2.0*bmidpoint[0],0.0]])]
pass pass
for i in xrange(datah-1): for i in xrange(datah-1):
for j in xrange(datal-1): for j in xrange(datal-1):
o.facets+=[genfacet([[pscale*i,pscale*j,data[j][i]*zscale+bheight],[pscale*(i+1),pscale*(j),data[j][i+1]*zscale+bheight],[pscale*(i+1),pscale*(j+1),data[j+1][i+1]*zscale+bheight]])] o.facets+=[genfacet([[pscale*i, pscale*j, data[j][i]*zscale+bheight],[pscale*(i+1),pscale*(j),data[j][i+1]*zscale+bheight],[pscale*(i+1),pscale*(j+1),data[j+1][i+1]*zscale+bheight]])]
o.facets+=[genfacet([[pscale*(i),pscale*(j+1),data[j+1][i]*zscale+bheight],[pscale*i,pscale*j,data[j][i]*zscale+bheight],[pscale*(i+1),pscale*(j+1),data[j+1][i+1]*zscale+bheight]])] o.facets+=[genfacet([[pscale*(i),pscale*(j+1),data[j+1][i]*zscale+bheight],[pscale*i, pscale*j, data[j][i]*zscale+bheight],[pscale*(i+1),pscale*(j+1),data[j+1][i+1]*zscale+bheight]])]
#print o.facets[-1] #print o.facets[-1]
facet=[[0,0,0],[[0,0,0],[0,0,0],[0,0,0]]] facet=[[0, 0,0],[[0, 0,0],[0, 0,0],[0, 0,0]]]
return o return o
def zimage(name,out): def zimage(name, out):
i=wx.Image(name) i = wx.Image(name)
s=i.GetSize() s = i.GetSize()
print len(map(ord,i.GetData()[::3])) print len(map(ord, i.GetData()[::3]))
b=map(ord,i.GetData()[::3]) b = map(ord, i.GetData()[::3])
data=[] data=[]
for i in xrange(s[0]): for i in xrange(s[0]):
data+=[b[i*s[1]:(i+1)*s[1]]] data+=[b[i*s[1]:(i+1)*s[1]]]
#data=[i[::5] for i in data[::5]] #data=[i[::5] for i in data[::5]]
emitstl(out,genscape(data,zscale=0.1).facets,name) emitstl(out, genscape(data, zscale = 0.1).facets, name)
""" """
class scapewin(wx.Frame): class scapewin(wx.Frame):
def __init__(self,size=(400,530)): def __init__(self, size = (400, 530)):
wx.Frame.__init__(self,None,title="Right-click to load an image",size=size) wx.Frame.__init__(self, None, title = "Right-click to load an image",size = size)
self.SetIcon(wx.Icon("plater.ico",wx.BITMAP_TYPE_ICO)) self.SetIcon(wx.Icon("plater.ico",wx.BITMAP_TYPE_ICO))
self.SetClientSize(size) self.SetClientSize(size)
self.panel=wx.Panel(self,size=size) self.panel = wx.Panel(self, size = size)
""" """
......
...@@ -25,60 +25,60 @@ import printcore ...@@ -25,60 +25,60 @@ import printcore
from printrun.printrun_utils import install_locale from printrun.printrun_utils import install_locale
install_locale('pronterface') install_locale('pronterface')
if os.name=="nt": if os.name == "nt":
try: try:
import _winreg import _winreg
except: except:
pass pass
READLINE=True READLINE = True
try: try:
import readline import readline
try: try:
readline.rl.mode.show_all_if_ambiguous="on" #config pyreadline on windows readline.rl.mode.show_all_if_ambiguous = "on" #config pyreadline on windows
except: except:
pass pass
except: except:
READLINE=False #neither readline module is available READLINE = False #neither readline module is available
def dosify(name): def dosify(name):
return os.path.split(name)[1].split(".")[0][:8]+".g" return os.path.split(name)[1].split(".")[0][:8]+".g"
def measurements(g): def measurements(g):
Xcur=0.0 Xcur = 0.0
Ycur=0.0 Ycur = 0.0
Zcur=0.0 Zcur = 0.0
Xmin=1000000 Xmin = 1000000
Ymin=1000000 Ymin = 1000000
Zmin=1000000 Zmin = 1000000
Xmax=-1000000 Xmax=-1000000
Ymax=-1000000 Ymax=-1000000
Zmax=-1000000 Zmax=-1000000
Xtot=0 Xtot = 0
Ytot=0 Ytot = 0
Ztot=0 Ztot = 0
for i in g: for i in g:
if "X" in i and ("G1" in i or "G0" in i): if "X" in i and ("G1" in i or "G0" in i):
try: try:
Xcur = float(i.split("X")[1].split(" ")[0]) Xcur = float(i.split("X")[1].split(" ")[0])
if Xcur<Xmin and Xcur>5.0: Xmin=Xcur if Xcur<Xmin and Xcur>5.0: Xmin = Xcur
if Xcur>Xmax: Xmax=Xcur if Xcur>Xmax: Xmax = Xcur
except: except:
pass pass
if "Y" in i and ("G1" in i or "G0" in i): if "Y" in i and ("G1" in i or "G0" in i):
try: try:
Ycur = float(i.split("Y")[1].split(" ")[0]) Ycur = float(i.split("Y")[1].split(" ")[0])
if Ycur<Ymin and Ycur>5.0: Ymin=Ycur if Ycur<Ymin and Ycur>5.0: Ymin = Ycur
if Ycur>Ymax: Ymax=Ycur if Ycur>Ymax: Ymax = Ycur
except: except:
pass pass
if "Z" in i and ("G1" in i or "G0" in i): if "Z" in i and ("G1" in i or "G0" in i):
try: try:
Zcur = float(i.split("Z")[1].split(" ")[0]) Zcur = float(i.split("Z")[1].split(" ")[0])
if Zcur<Zmin: Zmin=Zcur if Zcur<Zmin: Zmin = Zcur
if Zcur>Zmax: Zmax=Zcur if Zcur>Zmax: Zmax = Zcur
except: except:
pass pass
...@@ -87,15 +87,15 @@ def measurements(g): ...@@ -87,15 +87,15 @@ def measurements(g):
Ytot = Ymax - Ymin Ytot = Ymax - Ymin
Ztot = Zmax - Zmin Ztot = Zmax - Zmin
return (Xtot,Ytot,Ztot,Xmin,Xmax,Ymin,Ymax,Zmin,Zmax) return (Xtot, Ytot, Ztot, Xmin, Xmax, Ymin, Ymax, Zmin, Zmax)
def totalelength(g): def totalelength(g):
tot=0 tot = 0
cur=0 cur = 0
for i in g: for i in g:
if "E" in i and ("G1" in i or "G0" in i): if "E" in i and ("G1" in i or "G0" in i):
try: try:
cur=float(i.split("E")[1].split(" ")[0]) cur = float(i.split("E")[1].split(" ")[0])
except: except:
pass pass
elif "G92" in i and "E0" in i: elif "G92" in i and "E0" in i:
...@@ -108,7 +108,7 @@ def get_coordinate_value(axis, parts): ...@@ -108,7 +108,7 @@ def get_coordinate_value(axis, parts):
return float(i[1:]) return float(i[1:])
return None return None
def hypot3d(X1, Y1, Z1, X2=0.0, Y2=0.0, Z2=0.0): def hypot3d(X1, Y1, Z1, X2 = 0.0, Y2 = 0.0, Z2 = 0.0):
return math.hypot(X2-X1, math.hypot(Y2-Y1, Z2-Z1)) return math.hypot(X2-X1, math.hypot(Y2-Y1, Z2-Z1))
def estimate_duration(g): def estimate_duration(g):
...@@ -122,13 +122,13 @@ def estimate_duration(g): ...@@ -122,13 +122,13 @@ def estimate_duration(g):
acceleration = 1500.0 #mm/s/s ASSUMING THE DEFAULT FROM SPRINTER !!!! acceleration = 1500.0 #mm/s/s ASSUMING THE DEFAULT FROM SPRINTER !!!!
layerduration = 0.0 layerduration = 0.0
layerbeginduration = 0.0 layerbeginduration = 0.0
layercount=0 layercount = 0
#TODO: #TODO:
# get device caps from firmware: max speed, acceleration/axis (including extruder) # get device caps from firmware: max speed, acceleration/axis (including extruder)
# calculate the maximum move duration accounting for above ;) # calculate the maximum move duration accounting for above ;)
# print ".... estimating ...." # print ".... estimating ...."
for i in g: for i in g:
i=i.split(";")[0] i = i.split(";")[0]
if "G4" in i or "G1" in i: if "G4" in i or "G1" in i:
if "G4" in i: if "G4" in i:
parts = i.split(" ") parts = i.split(" ")
...@@ -140,15 +140,15 @@ def estimate_duration(g): ...@@ -140,15 +140,15 @@ def estimate_duration(g):
if "G1" in i: if "G1" in i:
parts = i.split(" ") parts = i.split(" ")
x = get_coordinate_value("X", parts[1:]) x = get_coordinate_value("X", parts[1:])
if x is None: x=lastx if x is None: x = lastx
y = get_coordinate_value("Y", parts[1:]) y = get_coordinate_value("Y", parts[1:])
if y is None: y=lasty if y is None: y = lasty
z = get_coordinate_value("Z", parts[1:]) z = get_coordinate_value("Z", parts[1:])
if (z is None) or (z<lastz): z=lastz # Do not increment z if it's below the previous (Lift z on move fix) if (z is None) or (z<lastz): z = lastz # Do not increment z if it's below the previous (Lift z on move fix)
e = get_coordinate_value("E", parts[1:]) e = get_coordinate_value("E", parts[1:])
if e is None: e=laste if e is None: e = laste
f = get_coordinate_value("F", parts[1:]) f = get_coordinate_value("F", parts[1:])
if f is None: f=lastf if f is None: f = lastf
else: f /= 60.0 # mm/s vs mm/m else: f /= 60.0 # mm/s vs mm/m
# given last feedrate and current feedrate calculate the distance needed to achieve current feedrate. # given last feedrate and current feedrate calculate the distance needed to achieve current feedrate.
...@@ -182,7 +182,7 @@ def estimate_duration(g): ...@@ -182,7 +182,7 @@ def estimate_duration(g):
class Settings: class Settings:
#def _temperature_alias(self): return {"pla":210,"abs":230,"off":0} #def _temperature_alias(self): return {"pla":210,"abs":230,"off":0}
#def _temperature_validate(self,v): #def _temperature_validate(self, v):
# if v < 0: raise ValueError("You cannot set negative temperatures. To turn the hotend off entirely, set its temperature to 0.") # if v < 0: raise ValueError("You cannot set negative temperatures. To turn the hotend off entirely, set its temperature to 0.")
#def _bedtemperature_alias(self): return {"pla":60,"abs":110,"off":0} #def _bedtemperature_alias(self): return {"pla":60,"abs":110,"off":0}
def _baudrate_list(self): return ["2400", "9600", "19200", "38400", "57600", "115200"] def _baudrate_list(self): return ["2400", "9600", "19200", "38400", "57600", "115200"]
...@@ -198,11 +198,11 @@ class Settings: ...@@ -198,11 +198,11 @@ class Settings:
self.xy_feedrate = 3000 self.xy_feedrate = 3000
self.z_feedrate = 200 self.z_feedrate = 200
self.e_feedrate = 300 self.e_feedrate = 300
self.slicecommand="python skeinforge/skeinforge_application/skeinforge_utilities/skeinforge_craft.py $s" self.slicecommand = "python skeinforge/skeinforge_application/skeinforge_utilities/skeinforge_craft.py $s"
self.sliceoptscommand="python skeinforge/skeinforge_application/skeinforge.py" self.sliceoptscommand = "python skeinforge/skeinforge_application/skeinforge.py"
self.final_command = "" self.final_command = ""
def _set(self,key,value): def _set(self, key, value):
try: try:
value = getattr(self,"_%s_alias"%key)()[value] value = getattr(self,"_%s_alias"%key)()[value]
except KeyError: except KeyError:
...@@ -213,13 +213,13 @@ class Settings: ...@@ -213,13 +213,13 @@ class Settings:
getattr(self,"_%s_validate"%key)(value) getattr(self,"_%s_validate"%key)(value)
except AttributeError: except AttributeError:
pass pass
setattr(self,key,type(getattr(self,key))(value)) setattr(self, key, type(getattr(self, key))(value))
try: try:
getattr(self,"_%s_cb"%key)(key,value) getattr(self,"_%s_cb"%key)(key, value)
except AttributeError: except AttributeError:
pass pass
return value return value
def _tabcomplete(self,key): def _tabcomplete(self, key):
try: try:
return getattr(self,"_%s_list"%key)() return getattr(self,"_%s_list"%key)()
except AttributeError: except AttributeError:
...@@ -230,38 +230,38 @@ class Settings: ...@@ -230,38 +230,38 @@ class Settings:
pass pass
return [] return []
def _all_settings(self): def _all_settings(self):
return dict([(k,getattr(self,k)) for k in self.__dict__.keys() if not k.startswith("_")]) return dict([(k, getattr(self, k)) for k in self.__dict__.keys() if not k.startswith("_")])
class pronsole(cmd.Cmd): class pronsole(cmd.Cmd):
def __init__(self): def __init__(self):
cmd.Cmd.__init__(self) cmd.Cmd.__init__(self)
if not READLINE: if not READLINE:
self.completekey=None self.completekey = None
self.p=printcore.printcore() self.p = printcore.printcore()
self.p.recvcb=self.recvcb self.p.recvcb = self.recvcb
self.recvlisteners=[] self.recvlisteners=[]
self.prompt="PC>" self.prompt = "PC>"
self.p.onlinecb=self.online self.p.onlinecb = self.online
self.f=None self.f = None
self.listing=0 self.listing = 0
self.sdfiles=[] self.sdfiles=[]
self.paused=False self.paused = False
self.sdprinting=0 self.sdprinting = 0
self.temps={"pla":"185","abs":"230","off":"0"} self.temps={"pla":"185","abs":"230","off":"0"}
self.bedtemps={"pla":"60","abs":"110","off":"0"} self.bedtemps={"pla":"60","abs":"110","off":"0"}
self.percentdone=0 self.percentdone = 0
self.tempreadings="" self.tempreadings = ""
self.macros={} self.macros={}
self.rc_loaded=False self.rc_loaded = False
self.processing_rc=False self.processing_rc = False
self.processing_args=False self.processing_args = False
self.settings = Settings() self.settings = Settings()
self.settings._port_list = self.scanserial self.settings._port_list = self.scanserial
self.settings._temperature_abs_cb = self.set_temp_preset self.settings._temperature_abs_cb = self.set_temp_preset
self.settings._temperature_pla_cb = self.set_temp_preset self.settings._temperature_pla_cb = self.set_temp_preset
self.settings._bedtemp_abs_cb = self.set_temp_preset self.settings._bedtemp_abs_cb = self.set_temp_preset
self.settings._bedtemp_pla_cb = self.set_temp_preset self.settings._bedtemp_pla_cb = self.set_temp_preset
self.monitoring=0 self.monitoring = 0
self.helpdict = {} self.helpdict = {}
self.helpdict["baudrate"] = _("Communications Speed (default: 115200)") self.helpdict["baudrate"] = _("Communications Speed (default: 115200)")
self.helpdict["bedtemp_abs"] = _("Heated Build Platform temp for ABS (default: 110 deg C)") self.helpdict["bedtemp_abs"] = _("Heated Build Platform temp for ABS (default: 110 deg C)")
...@@ -276,11 +276,11 @@ class pronsole(cmd.Cmd): ...@@ -276,11 +276,11 @@ class pronsole(cmd.Cmd):
self.helpdict["z_feedrate"] = _("Feedrate for Control Panel Moves in Z (default: 200mm/min)") self.helpdict["z_feedrate"] = _("Feedrate for Control Panel Moves in Z (default: 200mm/min)")
self.helpdict["final_command"] = _("Executable to run when the print is finished") self.helpdict["final_command"] = _("Executable to run when the print is finished")
self.commandprefixes='MGT$' self.commandprefixes='MGT$'
self.webrequested=False self.webrequested = False
self.web_config=None self.web_config = None
self.web_auth_config=None self.web_auth_config = None
def set_temp_preset(self,key,value): def set_temp_preset(self, key, value):
if not key.startswith("bed"): if not key.startswith("bed"):
self.temps["pla"] = str(self.settings.temperature_pla) self.temps["pla"] = str(self.settings.temperature_pla)
self.temps["abs"] = str(self.settings.temperature_abs) self.temps["abs"] = str(self.settings.temperature_abs)
...@@ -293,12 +293,12 @@ class pronsole(cmd.Cmd): ...@@ -293,12 +293,12 @@ class pronsole(cmd.Cmd):
def scanserial(self): def scanserial(self):
"""scan for available ports. return a list of device names.""" """scan for available ports. return a list of device names."""
baselist=[] baselist=[]
if os.name=="nt": if os.name == "nt":
try: try:
key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM") key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
i=0 i = 0
while(1): while(1):
baselist+=[_winreg.EnumValue(key,i)[1]] baselist+=[_winreg.EnumValue(key, i)[1]]
i+=1 i+=1
except: except:
pass pass
...@@ -310,28 +310,28 @@ class pronsole(cmd.Cmd): ...@@ -310,28 +310,28 @@ class pronsole(cmd.Cmd):
sys.stdout.write(self.prompt) sys.stdout.write(self.prompt)
sys.stdout.flush() sys.stdout.flush()
def help_help(self,l): def help_help(self, l):
self.do_help("") self.do_help("")
def do_gcodes(self,l): def do_gcodes(self, l):
self.help_gcodes() self.help_gcodes()
def help_gcodes(self): def help_gcodes(self):
print "Gcodes are passed through to the printer as they are" print "Gcodes are passed through to the printer as they are"
def complete_macro(self,text,line,begidx,endidx): def complete_macro(self, text, line, begidx, endidx):
if (len(line.split())==2 and line[-1] != " ") or (len(line.split())==1 and line[-1]==" "): if (len(line.split()) == 2 and line[-1] != " ") or (len(line.split()) == 1 and line[-1]==" "):
return [i for i in self.macros.keys() if i.startswith(text)] return [i for i in self.macros.keys() if i.startswith(text)]
elif(len(line.split())==3 or (len(line.split())==2 and line[-1]==" ")): elif(len(line.split()) == 3 or (len(line.split()) == 2 and line[-1]==" ")):
return [i for i in ["/D", "/S"] + self.completenames(text) if i.startswith(text)] return [i for i in ["/D", "/S"] + self.completenames(text) if i.startswith(text)]
else: else:
return [] return []
def hook_macro(self,l): def hook_macro(self, l):
l = l.rstrip() l = l.rstrip()
ls = l.lstrip() ls = l.lstrip()
ws = l[:len(l)-len(ls)] # just leading whitespace ws = l[:len(l)-len(ls)] # just leading whitespace
if len(ws)==0: if len(ws) == 0:
self.end_macro() self.end_macro()
# pass the unprocessed line to regular command processor to not require empty line in .pronsolerc # pass the unprocessed line to regular command processor to not require empty line in .pronsolerc
return self.onecmd(l) return self.onecmd(l)
...@@ -339,12 +339,12 @@ class pronsole(cmd.Cmd): ...@@ -339,12 +339,12 @@ class pronsole(cmd.Cmd):
def end_macro(self): def end_macro(self):
if self.__dict__.has_key("onecmd"): del self.onecmd # remove override if self.__dict__.has_key("onecmd"): del self.onecmd # remove override
self.prompt="PC>" self.prompt = "PC>"
if self.cur_macro_def!="": if self.cur_macro_def!="":
self.macros[self.cur_macro_name] = self.cur_macro_def self.macros[self.cur_macro_name] = self.cur_macro_def
macro = self.compile_macro(self.cur_macro_name,self.cur_macro_def) macro = self.compile_macro(self.cur_macro_name, self.cur_macro_def)
setattr(self.__class__,"do_"+self.cur_macro_name,lambda self,largs,macro=macro:macro(self,*largs.split())) setattr(self.__class__,"do_"+self.cur_macro_name, lambda self, largs, macro = macro:macro(self,*largs.split()))
setattr(self.__class__,"help_"+self.cur_macro_name,lambda self,macro_name=self.cur_macro_name: self.subhelp_macro(macro_name)) setattr(self.__class__,"help_"+self.cur_macro_name, lambda self, macro_name = self.cur_macro_name: self.subhelp_macro(macro_name))
if not self.processing_rc: if not self.processing_rc:
print "Macro '"+self.cur_macro_name+"' defined" print "Macro '"+self.cur_macro_name+"' defined"
# save it # save it
...@@ -356,22 +356,22 @@ class pronsole(cmd.Cmd): ...@@ -356,22 +356,22 @@ class pronsole(cmd.Cmd):
else: else:
macro_def += " " macro_def += " "
macro_def += self.cur_macro_def macro_def += self.cur_macro_def
self.save_in_rc(macro_key,macro_def) self.save_in_rc(macro_key, macro_def)
else: else:
print "Empty macro - cancelled" print "Empty macro - cancelled"
del self.cur_macro_name,self.cur_macro_def del self.cur_macro_name, self.cur_macro_def
def compile_macro_line(self,line): def compile_macro_line(self, line):
line = line.rstrip() line = line.rstrip()
ls = line.lstrip() ls = line.lstrip()
ws = line[:len(line)-len(ls)] # just leading whitespace ws = line[:len(line)-len(ls)] # just leading whitespace
if ls=="" or ls.startswith('#'): return "" # no code if ls == "" or ls.startswith('#'): return "" # no code
if ls.startswith('!'): if ls.startswith('!'):
return ws + ls[1:] + "\n" # python mode return ws + ls[1:] + "\n" # python mode
else: else:
return ws + 'self.onecmd("'+ls+'".format(*arg))\n' # parametric command mode return ws + 'self.onecmd("'+ls+'".format(*arg))\n' # parametric command mode
def compile_macro(self,macro_name,macro_def): def compile_macro(self, macro_name, macro_def):
if macro_def.strip() == "": if macro_def.strip() == "":
print "Empty macro - cancelled" print "Empty macro - cancelled"
return return
...@@ -385,15 +385,15 @@ class pronsole(cmd.Cmd): ...@@ -385,15 +385,15 @@ class pronsole(cmd.Cmd):
exec pycode exec pycode
return macro return macro
def start_macro(self,macro_name,prev_definition="",suppress_instructions=False): def start_macro(self, macro_name, prev_definition = "",suppress_instructions = False):
if not self.processing_rc and not suppress_instructions: if not self.processing_rc and not suppress_instructions:
print "Enter macro using indented lines, end with empty line" print "Enter macro using indented lines, end with empty line"
self.cur_macro_name = macro_name self.cur_macro_name = macro_name
self.cur_macro_def = "" self.cur_macro_def = ""
self.onecmd = self.hook_macro # override onecmd temporarily self.onecmd = self.hook_macro # override onecmd temporarily
self.prompt="..>" self.prompt = "..>"
def delete_macro(self,macro_name): def delete_macro(self, macro_name):
if macro_name in self.macros.keys(): if macro_name in self.macros.keys():
delattr(self.__class__,"do_"+macro_name) delattr(self.__class__,"do_"+macro_name)
del self.macros[macro_name] del self.macros[macro_name]
...@@ -402,11 +402,11 @@ class pronsole(cmd.Cmd): ...@@ -402,11 +402,11 @@ class pronsole(cmd.Cmd):
self.save_in_rc("macro "+macro_name,"") self.save_in_rc("macro "+macro_name,"")
else: else:
print "Macro '"+macro_name+"' is not defined" print "Macro '"+macro_name+"' is not defined"
def do_macro(self,args): def do_macro(self, args):
if args.strip()=="": if args.strip()=="":
self.print_topics("User-defined macros",self.macros.keys(),15,80) self.print_topics("User-defined macros",self.macros.keys(),15, 80)
return return
arglist = args.split(None,1) arglist = args.split(None, 1)
macro_name = arglist[0] macro_name = arglist[0]
if macro_name not in self.macros and hasattr(self.__class__,"do_"+macro_name): if macro_name not in self.macros and hasattr(self.__class__,"do_"+macro_name):
print "Name '"+macro_name+"' is being used by built-in command" print "Name '"+macro_name+"' is being used by built-in command"
...@@ -424,7 +424,7 @@ class pronsole(cmd.Cmd): ...@@ -424,7 +424,7 @@ class pronsole(cmd.Cmd):
self.end_macro() self.end_macro()
return return
if self.macros.has_key(macro_name): if self.macros.has_key(macro_name):
self.start_macro(macro_name,self.macros[macro_name]) self.start_macro(macro_name, self.macros[macro_name])
else: else:
self.start_macro(macro_name) self.start_macro(macro_name)
...@@ -437,7 +437,7 @@ class pronsole(cmd.Cmd): ...@@ -437,7 +437,7 @@ class pronsole(cmd.Cmd):
print "Show macro definition: macro <name> /s" print "Show macro definition: macro <name> /s"
print "'macro' without arguments displays list of defined macros" print "'macro' without arguments displays list of defined macros"
def subhelp_macro(self,macro_name): def subhelp_macro(self, macro_name):
if macro_name in self.macros.keys(): if macro_name in self.macros.keys():
macro_def = self.macros[macro_name] macro_def = self.macros[macro_name]
if "\n" in macro_def: if "\n" in macro_def:
...@@ -448,27 +448,27 @@ class pronsole(cmd.Cmd): ...@@ -448,27 +448,27 @@ class pronsole(cmd.Cmd):
else: else:
print "Macro '"+macro_name+"' is not defined" print "Macro '"+macro_name+"' is not defined"
def set(self,var,str): def set(self, var, str):
try: try:
t = type(getattr(self.settings,var)) t = type(getattr(self.settings, var))
value = self.settings._set(var,str) value = self.settings._set(var, str)
if not self.processing_rc and not self.processing_args: if not self.processing_rc and not self.processing_args:
self.save_in_rc("set "+var,"set %s %s" % (var,value)) self.save_in_rc("set "+var,"set %s %s" % (var, value))
except AttributeError: except AttributeError:
print "Unknown variable '%s'" % var print "Unknown variable '%s'" % var
except ValueError, ve: except ValueError, ve:
print "Bad value for variable '%s', expecting %s (%s)" % (var,repr(t)[1:-1],ve.args[0]) print "Bad value for variable '%s', expecting %s (%s)" % (var, repr(t)[1:-1],ve.args[0])
def do_set(self,argl): def do_set(self, argl):
args = argl.split(None,1) args = argl.split(None, 1)
if len(args) < 1: if len(args) < 1:
for k in [kk for kk in dir(self.settings) if not kk.startswith("_")]: for k in [kk for kk in dir(self.settings) if not kk.startswith("_")]:
print "%s = %s" % (k,str(getattr(self.settings,k))) print "%s = %s" % (k, str(getattr(self.settings, k)))
return return
value = getattr(self.settings,args[0]) value = getattr(self.settings, args[0])
if len(args) < 2: if len(args) < 2:
try: try:
print "%s = %s" % (args[0],getattr(self.settings,args[0])) print "%s = %s" % (args[0],getattr(self.settings, args[0]))
except AttributeError: except AttributeError:
print "Unknown variable '%s'" % args[0] print "Unknown variable '%s'" % args[0]
return return
...@@ -480,9 +480,9 @@ class pronsole(cmd.Cmd): ...@@ -480,9 +480,9 @@ class pronsole(cmd.Cmd):
print "'set' without arguments displays all variables" print "'set' without arguments displays all variables"
def complete_set(self, text, line, begidx, endidx): def complete_set(self, text, line, begidx, endidx):
if (len(line.split())==2 and line[-1] != " ") or (len(line.split())==1 and line[-1]==" "): if (len(line.split()) == 2 and line[-1] != " ") or (len(line.split()) == 1 and line[-1]==" "):
return [i for i in dir(self.settings) if not i.startswith("_") and i.startswith(text)] return [i for i in dir(self.settings) if not i.startswith("_") and i.startswith(text)]
elif(len(line.split())==3 or (len(line.split())==2 and line[-1]==" ")): elif(len(line.split()) == 3 or (len(line.split()) == 2 and line[-1]==" ")):
return [i for i in self.settings._tabcomplete(line.split()[1]) if i.startswith(text)] return [i for i in self.settings._tabcomplete(line.split()[1]) if i.startswith(text)]
else: else:
return [] return []
...@@ -491,10 +491,10 @@ class pronsole(cmd.Cmd): ...@@ -491,10 +491,10 @@ class pronsole(cmd.Cmd):
self.p.disconnect() self.p.disconnect()
cmd.Cmd.postloop(self) cmd.Cmd.postloop(self)
def load_rc(self,rc_filename): def load_rc(self, rc_filename):
self.processing_rc=True self.processing_rc = True
try: try:
rc=codecs.open(rc_filename,"r","utf-8") rc = codecs.open(rc_filename,"r","utf-8")
self.rc_filename = os.path.abspath(rc_filename) self.rc_filename = os.path.abspath(rc_filename)
for rc_cmd in rc: for rc_cmd in rc:
if not rc_cmd.lstrip().startswith("#"): if not rc_cmd.lstrip().startswith("#"):
...@@ -504,9 +504,9 @@ class pronsole(cmd.Cmd): ...@@ -504,9 +504,9 @@ class pronsole(cmd.Cmd):
self.end_macro() self.end_macro()
self.rc_loaded = True self.rc_loaded = True
finally: finally:
self.processing_rc=False self.processing_rc = False
def load_default_rc(self,rc_filename=".pronsolerc"): def load_default_rc(self, rc_filename = ".pronsolerc"):
try: try:
try: try:
self.load_rc(os.path.join(os.path.expanduser("~"),rc_filename)) self.load_rc(os.path.join(os.path.expanduser("~"),rc_filename))
...@@ -516,7 +516,7 @@ class pronsole(cmd.Cmd): ...@@ -516,7 +516,7 @@ class pronsole(cmd.Cmd):
# make sure the filename is initialized # make sure the filename is initialized
self.rc_filename = os.path.abspath(os.path.join(os.path.expanduser("~"),rc_filename)) self.rc_filename = os.path.abspath(os.path.join(os.path.expanduser("~"),rc_filename))
def save_in_rc(self,key,definition): def save_in_rc(self, key, definition):
""" """
Saves or updates macro or other definitions in .pronsolerc Saves or updates macro or other definitions in .pronsolerc
key is prefix that determines what is being defined/updated (e.g. 'macro foo') key is prefix that determines what is being defined/updated (e.g. 'macro foo')
...@@ -528,16 +528,16 @@ class pronsole(cmd.Cmd): ...@@ -528,16 +528,16 @@ class pronsole(cmd.Cmd):
Updates are made in the same file position. Updates are made in the same file position.
Additions are made to the end of the file. Additions are made to the end of the file.
""" """
rci,rco = None,None rci, rco = None, None
if definition != "" and not definition.endswith("\n"): if definition != "" and not definition.endswith("\n"):
definition += "\n" definition += "\n"
try: try:
written = False written = False
if os.path.exists(self.rc_filename): if os.path.exists(self.rc_filename):
import shutil import shutil
shutil.copy(self.rc_filename,self.rc_filename+"~bak") shutil.copy(self.rc_filename, self.rc_filename+"~bak")
rci=codecs.open(self.rc_filename+"~bak","r","utf-8") rci = codecs.open(self.rc_filename+"~bak","r","utf-8")
rco=codecs.open(self.rc_filename,"w","utf-8") rco = codecs.open(self.rc_filename,"w","utf-8")
if rci is not None: if rci is not None:
overwriting = False overwriting = False
for rc_cmd in rci: for rc_cmd in rci:
...@@ -565,31 +565,31 @@ class pronsole(cmd.Cmd): ...@@ -565,31 +565,31 @@ class pronsole(cmd.Cmd):
except Exception, e: except Exception, e:
print "Saving failed for",key+":",str(e) print "Saving failed for",key+":",str(e)
finally: finally:
del rci,rco del rci, rco
def preloop(self): def preloop(self):
print "Welcome to the printer console! Type \"help\" for a list of available commands." print "Welcome to the printer console! Type \"help\" for a list of available commands."
cmd.Cmd.preloop(self) cmd.Cmd.preloop(self)
def do_connect(self,l): def do_connect(self, l):
a=l.split() a = l.split()
p=self.scanserial() p = self.scanserial()
port=self.settings.port port = self.settings.port
if (port == "" or port not in p) and len(p)>0: if (port == "" or port not in p) and len(p)>0:
port=p[0] port = p[0]
baud=self.settings.baudrate or 115200 baud = self.settings.baudrate or 115200
if(len(a)>0): if(len(a)>0):
port=a[0] port = a[0]
if(len(a)>1): if(len(a)>1):
try: try:
baud=int(a[1]) baud = int(a[1])
except: except:
print "Bad baud value '"+a[1]+"' ignored" print "Bad baud value '"+a[1]+"' ignored"
if len(p)==0 and not port: if len(p) == 0 and not port:
print "No serial ports detected - please specify a port" print "No serial ports detected - please specify a port"
return return
if len(a)==0: if len(a) == 0:
print "No port specified - connecting to %s at %dbps" % (port,baud) print "No port specified - connecting to %s at %dbps" % (port, baud)
if port != self.settings.port: if port != self.settings.port:
self.settings.port = port self.settings.port = port
self.save_in_rc("set port","set port %s" % port) self.save_in_rc("set port","set port %s" % port)
...@@ -602,28 +602,28 @@ class pronsole(cmd.Cmd): ...@@ -602,28 +602,28 @@ class pronsole(cmd.Cmd):
print "Connect to printer" print "Connect to printer"
print "connect <port> <baudrate>" print "connect <port> <baudrate>"
print "If port and baudrate are not specified, connects to first detected port at 115200bps" print "If port and baudrate are not specified, connects to first detected port at 115200bps"
ports=self.scanserial() ports = self.scanserial()
if(len(ports)): if(len(ports)):
print "Available ports: ", " ".join(ports) print "Available ports: ", " ".join(ports)
else: else:
print "No serial ports were automatically found." print "No serial ports were automatically found."
def complete_connect(self, text, line, begidx, endidx): def complete_connect(self, text, line, begidx, endidx):
if (len(line.split())==2 and line[-1] != " ") or (len(line.split())==1 and line[-1]==" "): if (len(line.split()) == 2 and line[-1] != " ") or (len(line.split()) == 1 and line[-1]==" "):
return [i for i in self.scanserial() if i.startswith(text)] return [i for i in self.scanserial() if i.startswith(text)]
elif(len(line.split())==3 or (len(line.split())==2 and line[-1]==" ")): elif(len(line.split()) == 3 or (len(line.split()) == 2 and line[-1]==" ")):
return [i for i in ["2400", "9600", "19200", "38400", "57600", "115200"] if i.startswith(text)] return [i for i in ["2400", "9600", "19200", "38400", "57600", "115200"] if i.startswith(text)]
else: else:
return [] return []
def do_disconnect(self,l): def do_disconnect(self, l):
self.p.disconnect() self.p.disconnect()
def help_disconnect(self): def help_disconnect(self):
print "Disconnects from the printer" print "Disconnects from the printer"
def do_load(self,l): def do_load(self, l):
if len(l)==0: if len(l) == 0:
print "No file name given." print "No file name given."
return return
print "Loading file:"+l print "Loading file:"+l
...@@ -631,14 +631,14 @@ class pronsole(cmd.Cmd): ...@@ -631,14 +631,14 @@ class pronsole(cmd.Cmd):
print "File not found!" print "File not found!"
return return
self.f=[i.replace("\n","").replace("\r","") for i in open(l)] self.f=[i.replace("\n","").replace("\r","") for i in open(l)]
self.filename=l self.filename = l
print "Loaded ",l,", ",len(self.f)," lines." print "Loaded ",l,", ",len(self.f)," lines."
def complete_load(self, text, line, begidx, endidx): def complete_load(self, text, line, begidx, endidx):
s=line.split() s = line.split()
if len(s)>2: if len(s)>2:
return [] return []
if (len(s)==1 and line[-1]==" ") or (len(s)==2 and line[-1]!=" "): if (len(s) == 1 and line[-1]==" ") or (len(s) == 2 and line[-1]!=" "):
if len(s)>1: if len(s)>1:
return [i[len(s[1])-len(text):] for i in glob.glob(s[1]+"*/")+glob.glob(s[1]+"*.g*")] return [i[len(s[1])-len(text):] for i in glob.glob(s[1]+"*/")+glob.glob(s[1]+"*.g*")]
else: else:
...@@ -647,8 +647,8 @@ class pronsole(cmd.Cmd): ...@@ -647,8 +647,8 @@ class pronsole(cmd.Cmd):
def help_load(self): def help_load(self):
print "Loads a gcode file (with tab-completion)" print "Loads a gcode file (with tab-completion)"
def do_upload(self,l): def do_upload(self, l):
if len(l)==0: if len(l) == 0:
print "No file name given." print "No file name given."
return return
print "Loading file:"+l.split()[0] print "Loading file:"+l.split()[0]
...@@ -659,11 +659,11 @@ class pronsole(cmd.Cmd): ...@@ -659,11 +659,11 @@ class pronsole(cmd.Cmd):
print "Not connected to printer." print "Not connected to printer."
return return
self.f=[i.replace("\n","") for i in open(l.split()[0])] self.f=[i.replace("\n","") for i in open(l.split()[0])]
self.filename=l.split()[0] self.filename = l.split()[0]
print "Loaded ",l,", ",len(self.f)," lines." print "Loaded ",l,", ",len(self.f)," lines."
tname="" tname = ""
if len(l.split())>1: if len(l.split())>1:
tname=l.split()[1] tname = l.split()[1]
else: else:
print "please enter target name in 8.3 format." print "please enter target name in 8.3 format."
return return
...@@ -682,8 +682,8 @@ class pronsole(cmd.Cmd): ...@@ -682,8 +682,8 @@ class pronsole(cmd.Cmd):
sys.stdout.flush() sys.stdout.flush()
self.p.send_now("M29 "+tname) self.p.send_now("M29 "+tname)
self.sleep(0.2) self.sleep(0.2)
self.p.clear=1 self.p.clear = 1
self.listing=0 self.listing = 0
self.sdfiles=[] self.sdfiles=[]
self.recvlisteners+=[self.listfiles] self.recvlisteners+=[self.listfiles]
self.p.send_now("M20") self.p.send_now("M20")
...@@ -695,16 +695,16 @@ class pronsole(cmd.Cmd): ...@@ -695,16 +695,16 @@ class pronsole(cmd.Cmd):
self.p.pause() self.p.pause()
self.p.send_now("M29 "+tname) self.p.send_now("M29 "+tname)
time.sleep(0.2) time.sleep(0.2)
self.p.clear=1 self.p.clear = 1
self.p.startprint([]) self.p.startprint([])
print "A partial file named ",tname," may have been written to the sd card." print "A partial file named ",tname," may have been written to the sd card."
def complete_upload(self, text, line, begidx, endidx): def complete_upload(self, text, line, begidx, endidx):
s=line.split() s = line.split()
if len(s)>2: if len(s)>2:
return [] return []
if (len(s)==1 and line[-1]==" ") or (len(s)==2 and line[-1]!=" "): if (len(s) == 1 and line[-1]==" ") or (len(s) == 2 and line[-1]!=" "):
if len(s)>1: if len(s)>1:
return [i[len(s[1])-len(text):] for i in glob.glob(s[1]+"*/")+glob.glob(s[1]+"*.g*")] return [i[len(s[1])-len(text):] for i in glob.glob(s[1]+"*/")+glob.glob(s[1]+"*.g*")]
else: else:
...@@ -730,10 +730,10 @@ class pronsole(cmd.Cmd): ...@@ -730,10 +730,10 @@ class pronsole(cmd.Cmd):
print("You can monitor the print with the monitor command.") print("You can monitor the print with the monitor command.")
self.p.startprint(self.f) self.p.startprint(self.f)
#self.p.pause() #self.p.pause()
#self.paused=True #self.paused = True
#self.do_resume(None) #self.do_resume(None)
def do_pause(self,l): def do_pause(self, l):
if self.sdprinting: if self.sdprinting:
self.p.send_now("M25") self.p.send_now("M25")
else: else:
...@@ -742,18 +742,18 @@ class pronsole(cmd.Cmd): ...@@ -742,18 +742,18 @@ class pronsole(cmd.Cmd):
return return
self.p.pause() self.p.pause()
#self.p.connect()# This seems to work, but is not a good solution. #self.p.connect()# This seems to work, but is not a good solution.
self.paused=True self.paused = True
#self.do_resume(None) #self.do_resume(None)
def help_pause(self): def help_pause(self):
print "Pauses a running print" print "Pauses a running print"
def do_resume(self,l): def do_resume(self, l):
if not self.paused: if not self.paused:
print "Not paused, unable to resume. Start a print first." print "Not paused, unable to resume. Start a print first."
return return
self.paused=False self.paused = False
if self.sdprinting: if self.sdprinting:
self.p.send_now("M24") self.p.send_now("M24")
return return
...@@ -766,23 +766,23 @@ class pronsole(cmd.Cmd): ...@@ -766,23 +766,23 @@ class pronsole(cmd.Cmd):
def emptyline(self): def emptyline(self):
pass pass
def do_shell(self,l): def do_shell(self, l):
exec(l) exec(l)
def listfiles(self,line): def listfiles(self, line):
if "Begin file list" in line: if "Begin file list" in line:
self.listing=1 self.listing = 1
elif "End file list" in line: elif "End file list" in line:
self.listing=0 self.listing = 0
self.recvlisteners.remove(self.listfiles) self.recvlisteners.remove(self.listfiles)
elif self.listing: elif self.listing:
self.sdfiles+=[line.replace("\n","").replace("\r","").lower()] self.sdfiles+=[line.replace("\n","").replace("\r","").lower()]
def do_ls(self,l): def do_ls(self, l):
if not self.p.online: if not self.p.online:
print "Printer is not online. Try connect to it first." print "Printer is not online. Try connect to it first."
return return
self.listing=2 self.listing = 2
self.sdfiles=[] self.sdfiles=[]
self.recvlisteners+=[self.listfiles] self.recvlisteners+=[self.listfiles]
self.p.send_now("M20") self.p.send_now("M20")
...@@ -792,7 +792,7 @@ class pronsole(cmd.Cmd): ...@@ -792,7 +792,7 @@ class pronsole(cmd.Cmd):
def help_ls(self): def help_ls(self):
print "lists files on the SD card" print "lists files on the SD card"
def waitforsdresponse(self,l): def waitforsdresponse(self, l):
if "file.open failed" in l: if "file.open failed" in l:
print "Opening file failed." print "Opening file failed."
self.recvlisteners.remove(self.waitforsdresponse) self.recvlisteners.remove(self.waitforsdresponse)
...@@ -802,34 +802,34 @@ class pronsole(cmd.Cmd): ...@@ -802,34 +802,34 @@ class pronsole(cmd.Cmd):
if "File selected" in l: if "File selected" in l:
print "Starting print" print "Starting print"
self.p.send_now("M24") self.p.send_now("M24")
self.sdprinting=1 self.sdprinting = 1
#self.recvlisteners.remove(self.waitforsdresponse) #self.recvlisteners.remove(self.waitforsdresponse)
return return
if "Done printing file" in l: if "Done printing file" in l:
print l print l
self.sdprinting=0 self.sdprinting = 0
self.recvlisteners.remove(self.waitforsdresponse) self.recvlisteners.remove(self.waitforsdresponse)
return return
if "SD printing byte" in l: if "SD printing byte" in l:
#M27 handler #M27 handler
try: try:
resp=l.split() resp = l.split()
vals=resp[-1].split("/") vals = resp[-1].split("/")
self.percentdone=100.0*int(vals[0])/int(vals[1]) self.percentdone = 100.0*int(vals[0])/int(vals[1])
except: except:
pass pass
def do_reset(self,l): def do_reset(self, l):
self.p.reset() self.p.reset()
def help_reset(self): def help_reset(self):
print "Resets the printer." print "Resets the printer."
def do_sdprint(self,l): def do_sdprint(self, l):
if not self.p.online: if not self.p.online:
print "Printer is not online. Try connect to it first." print "Printer is not online. Try connect to it first."
return return
self.listing=2 self.listing = 2
self.sdfiles=[] self.sdfiles=[]
self.recvlisteners+=[self.listfiles] self.recvlisteners+=[self.listfiles]
self.p.send_now("M20") self.p.send_now("M20")
...@@ -849,17 +849,17 @@ class pronsole(cmd.Cmd): ...@@ -849,17 +849,17 @@ class pronsole(cmd.Cmd):
def complete_sdprint(self, text, line, begidx, endidx): def complete_sdprint(self, text, line, begidx, endidx):
if self.sdfiles==[] and self.p.online: if self.sdfiles==[] and self.p.online:
self.listing=2 self.listing = 2
self.recvlisteners+=[self.listfiles] self.recvlisteners+=[self.listfiles]
self.p.send_now("M20") self.p.send_now("M20")
time.sleep(0.5) time.sleep(0.5)
if (len(line.split())==2 and line[-1] != " ") or (len(line.split())==1 and line[-1]==" "): if (len(line.split()) == 2 and line[-1] != " ") or (len(line.split()) == 1 and line[-1]==" "):
return [i for i in self.sdfiles if i.startswith(text)] return [i for i in self.sdfiles if i.startswith(text)]
def recvcb(self,l): def recvcb(self, l):
if "T:" in l: if "T:" in l:
self.tempreadings=l self.tempreadings = l
tstring=l.rstrip() tstring = l.rstrip()
if(tstring!="ok" and not tstring.startswith("ok T") and not tstring.startswith("T:") and not self.listing and not self.monitoring): if(tstring!="ok" and not tstring.startswith("ok T") and not tstring.startswith("T:") and not self.listing and not self.monitoring):
print tstring print tstring
sys.stdout.write(self.prompt) sys.stdout.write(self.prompt)
...@@ -871,7 +871,7 @@ class pronsole(cmd.Cmd): ...@@ -871,7 +871,7 @@ class pronsole(cmd.Cmd):
print "Executes a python command. Example:" print "Executes a python command. Example:"
print "! os.listdir('.')" print "! os.listdir('.')"
def default(self,l): def default(self, l):
if(l[0] in self.commandprefixes.upper()): if(l[0] in self.commandprefixes.upper()):
if(self.p and self.p.online): if(self.p and self.p.online):
print "SENDING:"+l print "SENDING:"+l
...@@ -887,16 +887,16 @@ class pronsole(cmd.Cmd): ...@@ -887,16 +887,16 @@ class pronsole(cmd.Cmd):
print "Printer is not online." print "Printer is not online."
return return
else: else:
cmd.Cmd.default(self,l) cmd.Cmd.default(self, l)
def help_help(self): def help_help(self):
self.do_help("") self.do_help("")
def tempcb(self,l): def tempcb(self, l):
if "T:" in l: if "T:" in l:
print l.replace("\r","").replace("T","Hotend").replace("B","Bed").replace("\n","").replace("ok ","") print l.replace("\r","").replace("T","Hotend").replace("B","Bed").replace("\n","").replace("ok ","")
def do_gettemp(self,l): def do_gettemp(self, l):
if self.p.online: if self.p.online:
self.recvlisteners+=[self.tempcb] self.recvlisteners+=[self.tempcb]
self.p.send_now("M105") self.p.send_now("M105")
...@@ -906,12 +906,12 @@ class pronsole(cmd.Cmd): ...@@ -906,12 +906,12 @@ class pronsole(cmd.Cmd):
def help_gettemp(self): def help_gettemp(self):
print "Read the extruder and bed temperature." print "Read the extruder and bed temperature."
def do_settemp(self,l): def do_settemp(self, l):
try: try:
l=l.lower().replace(",",".") l = l.lower().replace(",",".")
for i in self.temps.keys(): for i in self.temps.keys():
l=l.replace(i,self.temps[i]) l = l.replace(i, self.temps[i])
f=float(l) f = float(l)
if f>=0: if f>=0:
if self.p.online: if self.p.online:
self.p.send_now("M104 S"+l) self.p.send_now("M104 S"+l)
...@@ -929,15 +929,15 @@ class pronsole(cmd.Cmd): ...@@ -929,15 +929,15 @@ class pronsole(cmd.Cmd):
print ", ".join([i+"("+self.temps[i]+")" for i in self.temps.keys()]) print ", ".join([i+"("+self.temps[i]+")" for i in self.temps.keys()])
def complete_settemp(self, text, line, begidx, endidx): def complete_settemp(self, text, line, begidx, endidx):
if (len(line.split())==2 and line[-1] != " ") or (len(line.split())==1 and line[-1]==" "): if (len(line.split()) == 2 and line[-1] != " ") or (len(line.split()) == 1 and line[-1]==" "):
return [i for i in self.temps.keys() if i.startswith(text)] return [i for i in self.temps.keys() if i.startswith(text)]
def do_bedtemp(self,l): def do_bedtemp(self, l):
try: try:
l=l.lower().replace(",",".") l = l.lower().replace(",",".")
for i in self.bedtemps.keys(): for i in self.bedtemps.keys():
l=l.replace(i,self.bedtemps[i]) l = l.replace(i, self.bedtemps[i])
f=float(l) f = float(l)
if f>=0: if f>=0:
if self.p.online: if self.p.online:
self.p.send_now("M140 S"+l) self.p.send_now("M140 S"+l)
...@@ -955,10 +955,10 @@ class pronsole(cmd.Cmd): ...@@ -955,10 +955,10 @@ class pronsole(cmd.Cmd):
print ", ".join([i+"("+self.bedtemps[i]+")" for i in self.bedtemps.keys()]) print ", ".join([i+"("+self.bedtemps[i]+")" for i in self.bedtemps.keys()])
def complete_bedtemp(self, text, line, begidx, endidx): def complete_bedtemp(self, text, line, begidx, endidx):
if (len(line.split())==2 and line[-1] != " ") or (len(line.split())==1 and line[-1]==" "): if (len(line.split()) == 2 and line[-1] != " ") or (len(line.split()) == 1 and line[-1]==" "):
return [i for i in self.bedtemps.keys() if i.startswith(text)] return [i for i in self.bedtemps.keys() if i.startswith(text)]
def do_move(self,l): def do_move(self, l):
if(len(l.split())<2): if(len(l.split())<2):
print "No move specified." print "No move specified."
return return
...@@ -968,30 +968,30 @@ class pronsole(cmd.Cmd): ...@@ -968,30 +968,30 @@ class pronsole(cmd.Cmd):
if not self.p.online: if not self.p.online:
print "Printer is not online. Unable to move." print "Printer is not online. Unable to move."
return return
l=l.split() l = l.split()
if(l[0].lower()=="x"): if(l[0].lower()=="x"):
feed=self.settings.xy_feedrate feed = self.settings.xy_feedrate
axis="X" axis = "X"
elif(l[0].lower()=="y"): elif(l[0].lower()=="y"):
feed=self.settings.xy_feedrate feed = self.settings.xy_feedrate
axis="Y" axis = "Y"
elif(l[0].lower()=="z"): elif(l[0].lower()=="z"):
feed=self.settings.z_feedrate feed = self.settings.z_feedrate
axis="Z" axis = "Z"
elif(l[0].lower()=="e"): elif(l[0].lower()=="e"):
feed=self.settings.e_feedrate feed = self.settings.e_feedrate
axis="E" axis = "E"
else: else:
print "Unknown axis." print "Unknown axis."
return return
dist=0 dist = 0
try: try:
dist=float(l[1]) dist = float(l[1])
except: except:
print "Invalid distance" print "Invalid distance"
return return
try: try:
feed=int(l[2]) feed = int(l[2])
except: except:
pass pass
self.p.send_now("G91") self.p.send_now("G91")
...@@ -1006,42 +1006,42 @@ class pronsole(cmd.Cmd): ...@@ -1006,42 +1006,42 @@ class pronsole(cmd.Cmd):
print "Common amounts are in the tabcomplete list." print "Common amounts are in the tabcomplete list."
def complete_move(self, text, line, begidx, endidx): def complete_move(self, text, line, begidx, endidx):
if (len(line.split())==2 and line[-1] != " ") or (len(line.split())==1 and line[-1]==" "): if (len(line.split()) == 2 and line[-1] != " ") or (len(line.split()) == 1 and line[-1]==" "):
return [i for i in ["X ","Y ","Z ","E "] if i.lower().startswith(text)] return [i for i in ["X ","Y ","Z ","E "] if i.lower().startswith(text)]
elif(len(line.split())==3 or (len(line.split())==2 and line[-1]==" ")): elif(len(line.split()) == 3 or (len(line.split()) == 2 and line[-1]==" ")):
base=line.split()[-1] base = line.split()[-1]
rlen=0 rlen = 0
if base.startswith("-"): if base.startswith("-"):
rlen=1 rlen = 1
if line[-1]==" ": if line[-1]==" ":
base="" base = ""
return [i[rlen:] for i in ["-100","-10","-1","-0.1","100","10","1","0.1","-50","-5","-0.5","50","5","0.5","-200","-20","-2","-0.2","200","20","2","0.2"] if i.startswith(base)] return [i[rlen:] for i in ["-100","-10","-1","-0.1","100","10","1","0.1","-50","-5","-0.5","50","5","0.5","-200","-20","-2","-0.2","200","20","2","0.2"] if i.startswith(base)]
else: else:
return [] return []
def do_extrude(self,l,override=None,overridefeed=300): def do_extrude(self, l,override = None, overridefeed = 300):
length=5#default extrusion length length = 5#default extrusion length
feed=self.settings.e_feedrate#default speed feed = self.settings.e_feedrate#default speed
if not self.p.online: if not self.p.online:
print "Printer is not online. Unable to move." print "Printer is not online. Unable to move."
return return
if self.p.printing: if self.p.printing:
print "Printer is currently printing. Please pause the print before you issue manual commands." print "Printer is currently printing. Please pause the print before you issue manual commands."
return return
ls=l.split() ls = l.split()
if len(ls): if len(ls):
try: try:
length=float(ls[0]) length = float(ls[0])
except: except:
print "Invalid length given." print "Invalid length given."
if len(ls)>1: if len(ls)>1:
try: try:
feed=int(ls[1]) feed = int(ls[1])
except: except:
print "Invalid speed given." print "Invalid speed given."
if override is not None: if override is not None:
length=override length = override
feed=overridefeed feed = overridefeed
if length > 0: if length > 0:
print "Extruding %fmm of filament."%(length,) print "Extruding %fmm of filament."%(length,)
elif length <0: elif length <0:
...@@ -1060,26 +1060,26 @@ class pronsole(cmd.Cmd): ...@@ -1060,26 +1060,26 @@ class pronsole(cmd.Cmd):
print "extrude 10 210 - extrudes 10mm of filament at 210mm/min (3.5mm/s)" print "extrude 10 210 - extrudes 10mm of filament at 210mm/min (3.5mm/s)"
def do_reverse(self, l): def do_reverse(self, l):
length=5#default extrusion length length = 5#default extrusion length
feed=self.settings.e_feedrate#default speed feed = self.settings.e_feedrate#default speed
if not self.p.online: if not self.p.online:
print "Printer is not online. Unable to move." print "Printer is not online. Unable to move."
return return
if self.p.printing: if self.p.printing:
print "Printer is currently printing. Please pause the print before you issue manual commands." print "Printer is currently printing. Please pause the print before you issue manual commands."
return return
ls=l.split() ls = l.split()
if len(ls): if len(ls):
try: try:
length=float(ls[0]) length = float(ls[0])
except: except:
print "Invalid length given." print "Invalid length given."
if len(ls)>1: if len(ls)>1:
try: try:
feed=int(ls[1]) feed = int(ls[1])
except: except:
print "Invalid speed given." print "Invalid speed given."
self.do_extrude("",length*-1.0,feed) self.do_extrude("",length*-1.0, feed)
def help_reverse(self): def help_reverse(self):
print "Reverses the extruder, 5mm by default, or the number of mm given as a parameter" print "Reverses the extruder, 5mm by default, or the number of mm given as a parameter"
...@@ -1088,7 +1088,7 @@ class pronsole(cmd.Cmd): ...@@ -1088,7 +1088,7 @@ class pronsole(cmd.Cmd):
print "reverse 10 210 - extrudes 10mm of filament at 210mm/min (3.5mm/s)" print "reverse 10 210 - extrudes 10mm of filament at 210mm/min (3.5mm/s)"
print "reverse -5 - EXTRUDES 5mm of filament at 300mm/min (5mm/s)" print "reverse -5 - EXTRUDES 5mm of filament at 300mm/min (5mm/s)"
def do_exit(self,l): def do_exit(self, l):
print "Disconnecting from printer..." print "Disconnecting from printer..."
self.p.disconnect() self.p.disconnect()
print "Exiting program. Goodbye!" print "Exiting program. Goodbye!"
...@@ -1097,19 +1097,19 @@ class pronsole(cmd.Cmd): ...@@ -1097,19 +1097,19 @@ class pronsole(cmd.Cmd):
def help_exit(self): def help_exit(self):
print "Disconnects from the printer and exits the program." print "Disconnects from the printer and exits the program."
def do_monitor(self,l): def do_monitor(self, l):
interval=5 interval = 5
if not self.p.online: if not self.p.online:
print "Printer is not online. Please connect first." print "Printer is not online. Please connect first."
return return
print "Monitoring printer, use ^C to interrupt." print "Monitoring printer, use ^C to interrupt."
if len(l): if len(l):
try: try:
interval=float(l) interval = float(l)
except: except:
print "Invalid period given." print "Invalid period given."
print "Updating values every %f seconds."%(interval,) print "Updating values every %f seconds."%(interval,)
self.monitoring=1 self.monitoring = 1
try: try:
while(1): while(1):
self.p.send_now("M105") self.p.send_now("M105")
...@@ -1126,24 +1126,24 @@ class pronsole(cmd.Cmd): ...@@ -1126,24 +1126,24 @@ class pronsole(cmd.Cmd):
except: except:
print "Done monitoring." print "Done monitoring."
pass pass
self.monitoring=0 self.monitoring = 0
def help_monitor(self): def help_monitor(self):
print "Monitor a machine's temperatures and an SD print's status." print "Monitor a machine's temperatures and an SD print's status."
print "monitor - Reports temperature and SD print status (if SD printing) every 5 seconds" print "monitor - Reports temperature and SD print status (if SD printing) every 5 seconds"
print "monitor 2 - Reports temperature and SD print status (if SD printing) every 2 seconds" print "monitor 2 - Reports temperature and SD print status (if SD printing) every 2 seconds"
def expandcommand(self,c): def expandcommand(self, c):
return c.replace("$python",sys.executable) return c.replace("$python",sys.executable)
def do_skein(self,l): def do_skein(self, l):
l=l.split() l = l.split()
if len(l)==0: if len(l) == 0:
print "No file name given." print "No file name given."
return return
settings=0 settings = 0
if(l[0]=="set"): if(l[0]=="set"):
settings=1 settings = 1
else: else:
print "Skeining file:"+l[0] print "Skeining file:"+l[0]
if not(os.path.exists(l[0])): if not(os.path.exists(l[0])):
...@@ -1162,14 +1162,14 @@ class pronsole(cmd.Cmd): ...@@ -1162,14 +1162,14 @@ class pronsole(cmd.Cmd):
subprocess.call(params) subprocess.call(params)
print "Loading sliced file." print "Loading sliced file."
self.do_load(l[0].replace(".stl","_export.gcode")) self.do_load(l[0].replace(".stl","_export.gcode"))
except Exception,e: except Exception, e:
print "Skeinforge execution failed: ",e print "Skeinforge execution failed: ",e
def complete_skein(self, text, line, begidx, endidx): def complete_skein(self, text, line, begidx, endidx):
s=line.split() s = line.split()
if len(s)>2: if len(s)>2:
return [] return []
if (len(s)==1 and line[-1]==" ") or (len(s)==2 and line[-1]!=" "): if (len(s) == 1 and line[-1]==" ") or (len(s) == 2 and line[-1]!=" "):
if len(s)>1: if len(s)>1:
return [i[len(s[1])-len(text):] for i in glob.glob(s[1]+"*/")+glob.glob(s[1]+"*.stl")] return [i[len(s[1])-len(text):] for i in glob.glob(s[1]+"*/")+glob.glob(s[1]+"*.stl")]
else: else:
...@@ -1182,7 +1182,7 @@ class pronsole(cmd.Cmd): ...@@ -1182,7 +1182,7 @@ class pronsole(cmd.Cmd):
print "skein set - adjust slicer settings" print "skein set - adjust slicer settings"
def do_home(self,l): def do_home(self, l):
if not self.p.online: if not self.p.online:
print "Printer is not online. Unable to move." print "Printer is not online. Unable to move."
return return
...@@ -1209,11 +1209,11 @@ class pronsole(cmd.Cmd): ...@@ -1209,11 +1209,11 @@ class pronsole(cmd.Cmd):
print "home e - set extruder position to zero (Using G92)" print "home e - set extruder position to zero (Using G92)"
print "home xyze - homes all axes and zeroes the extruder (Using G28 and G92)" print "home xyze - homes all axes and zeroes the extruder (Using G28 and G92)"
def parse_cmdline(self,args): def parse_cmdline(self, args):
import getopt import getopt
opts,args = getopt.getopt(args, "c:e:hw", ["conf=","config=","help","web","web-config=", "web-auth-config="]) opts, args = getopt.getopt(args, "c:e:hw", ["conf = ","config = ","help","web","web-config = ", "web-auth-config = "])
for o,a in opts: for o, a in opts:
#print repr((o,a)) #print repr((o, a))
if o in ("-c","--conf","--config"): if o in ("-c","--conf","--config"):
self.load_rc(a) self.load_rc(a)
elif o in ("-w","--web"): elif o in ("-w","--web"):
...@@ -1231,15 +1231,15 @@ class pronsole(cmd.Cmd): ...@@ -1231,15 +1231,15 @@ class pronsole(cmd.Cmd):
sys.exit() sys.exit()
if not self.rc_loaded: if not self.rc_loaded:
self.load_default_rc() self.load_default_rc()
for o,a in opts: for o, a in opts:
if o == "-e": if o == "-e":
self.processing_args = True self.processing_args = True
self.onecmd(a) self.onecmd(a)
self.processing_args = False self.processing_args = False
if __name__=="__main__": if __name__ == "__main__":
interp=pronsole() interp = pronsole()
interp.parse_cmdline(sys.argv[1:]) interp.parse_cmdline(sys.argv[1:])
try: try:
interp.cmdloop() interp.cmdloop()
......
...@@ -29,14 +29,14 @@ import sys, glob, time, datetime, threading, traceback, cStringIO, subprocess ...@@ -29,14 +29,14 @@ import sys, glob, time, datetime, threading, traceback, cStringIO, subprocess
from printrun.pronterface_widgets import * from printrun.pronterface_widgets import *
StringIO=cStringIO StringIO = cStringIO
winsize=(800,500) winsize = (800, 500)
layerindex=0 layerindex = 0
global buttonSize global buttonSize
buttonSize = (70, 25) # Define sizes for the buttons on top rows buttonSize = (70, 25) # Define sizes for the buttons on top rows
if os.name=="nt": if os.name == "nt":
winsize=(800,530) winsize = (800, 530)
try: try:
import _winreg import _winreg
except: except:
...@@ -66,7 +66,7 @@ class Tee(object): ...@@ -66,7 +66,7 @@ class Tee(object):
def __init__(self, target): def __init__(self, target):
self.stdout = sys.stdout self.stdout = sys.stdout
sys.stdout = self sys.stdout = self
self.target=target self.target = target
def __del__(self): def __del__(self):
sys.stdout = self.stdout sys.stdout = self.stdout
def write(self, data): def write(self, data):
...@@ -79,10 +79,10 @@ class Tee(object): ...@@ -79,10 +79,10 @@ class Tee(object):
self.stdout.flush() self.stdout.flush()
class PronterWindow(wx.Frame,pronsole.pronsole): class PronterWindow(wx.Frame, pronsole.pronsole):
def __init__(self, filename=None,size=winsize): def __init__(self, filename = None, size = winsize):
pronsole.pronsole.__init__(self) pronsole.pronsole.__init__(self)
self.settings.build_dimensions = '200x200x100+0+0+0' #default build dimensions are 200x200x100 with 0,0,0 in the corner of the bed self.settings.build_dimensions = '200x200x100+0+0+0' #default build dimensions are 200x200x100 with 0, 0, 0 in the corner of the bed
self.settings.last_bed_temperature = 0.0 self.settings.last_bed_temperature = 0.0
self.settings.last_file_path = "" self.settings.last_file_path = ""
self.settings.last_temperature = 0.0 self.settings.last_temperature = 0.0
...@@ -90,7 +90,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -90,7 +90,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
self.settings.preview_grid_step1 = 10. self.settings.preview_grid_step1 = 10.
self.settings.preview_grid_step2 = 50. self.settings.preview_grid_step2 = 50.
self.settings.bgcolor = "#FFFFFF" self.settings.bgcolor = "#FFFFFF"
self.helpdict["build_dimensions"] = _("Dimensions of Build Platform\n & optional offset of origin\n\nExamples:\n XXXxYYY\n XXX,YYY,ZZZ\n XXXxYYYxZZZ+OffX+OffY+OffZ") self.helpdict["build_dimensions"] = _("Dimensions of Build Platform\n & optional offset of origin\n\nExamples:\n XXXxYYY\n XXX, YYY, ZZZ\n XXXxYYYxZZZ+OffX+OffY+OffZ")
self.helpdict["last_bed_temperature"] = _("Last Set Temperature for the Heated Print Bed") self.helpdict["last_bed_temperature"] = _("Last Set Temperature for the Heated Print Bed")
self.helpdict["last_file_path"] = _("Folder of last opened file") self.helpdict["last_file_path"] = _("Folder of last opened file")
self.helpdict["last_temperature"] = _("Last Temperature of the Hot End") self.helpdict["last_temperature"] = _("Last Temperature of the Hot End")
...@@ -98,31 +98,31 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -98,31 +98,31 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
self.helpdict["preview_grid_step1"] = _("Fine Grid Spacing (default: 10)") self.helpdict["preview_grid_step1"] = _("Fine Grid Spacing (default: 10)")
self.helpdict["preview_grid_step2"] = _("Coarse Grid Spacing (default: 50)") self.helpdict["preview_grid_step2"] = _("Coarse Grid Spacing (default: 50)")
self.helpdict["bgcolor"] = _("Pronterface background color (default: #FFFFFF)") self.helpdict["bgcolor"] = _("Pronterface background color (default: #FFFFFF)")
self.filename=filename self.filename = filename
os.putenv("UBUNTU_MENUPROXY","0") os.putenv("UBUNTU_MENUPROXY","0")
wx.Frame.__init__(self,None,title=_("Printer Interface"),size=size); wx.Frame.__init__(self, None, title = _("Printer Interface"),size = size);
self.SetIcon(wx.Icon(pixmapfile("P-face.ico"),wx.BITMAP_TYPE_ICO)) self.SetIcon(wx.Icon(pixmapfile("P-face.ico"),wx.BITMAP_TYPE_ICO))
self.panel=wx.Panel(self,-1,size=size) self.panel = wx.Panel(self,-1, size = size)
self.statuscheck=False self.statuscheck = False
self.status_thread=None self.status_thread = None
self.capture_skip={} self.capture_skip={}
self.capture_skip_newline=False self.capture_skip_newline = False
self.tempreport="" self.tempreport = ""
self.monitor=0 self.monitor = 0
self.f=None self.f = None
self.skeinp=None self.skeinp = None
self.monitor_interval=3 self.monitor_interval = 3
self.paused=False self.paused = False
self.sentlines=Queue.Queue(30) self.sentlines = Queue.Queue(30)
xcol=(245,245,108) xcol = (245, 245, 108)
ycol=(180,180,255) ycol = (180, 180, 255)
zcol=(180,255,180) zcol = (180, 255, 180)
self.cpbuttons=[ self.cpbuttons=[
[_("Motors off"),("M84"),None,(250,250,250),0, _("Switch all motors off")], [_("Motors off"),("M84"),None,(250, 250, 250),0, _("Switch all motors off")],
[_("Check temp"),("M105"),(2,5),(225,200,200),(1,1), _("Check current hotend temperature")], [_("Check temp"),("M105"),(2, 5),(225, 200, 200),(1, 1), _("Check current hotend temperature")],
[_("Extrude"),("extrude"),(4,0),(225,200,200),(1,2), _("Advance extruder by set length")], [_("Extrude"),("extrude"),(4, 0),(225, 200, 200),(1, 2), _("Advance extruder by set length")],
[_("Reverse"),("reverse"),(5,0),(225,200,200),(1,2), _("Reverse extruder by set length")], [_("Reverse"),("reverse"),(5, 0),(225, 200, 200),(1, 2), _("Reverse extruder by set length")],
] ]
self.custombuttons=[] self.custombuttons=[]
self.btndict={} self.btndict={}
...@@ -137,12 +137,12 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -137,12 +137,12 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
try: try:
self.custombuttons = customdict["btns"] self.custombuttons = customdict["btns"]
for n in xrange(len(self.custombuttons)): for n in xrange(len(self.custombuttons)):
self.cbutton_save(n,self.custombuttons[n]) self.cbutton_save(n, self.custombuttons[n])
os.rename("custombtn.txt","custombtn.old") os.rename("custombtn.txt","custombtn.old")
rco=open("custombtn.txt","w") rco = open("custombtn.txt","w")
rco.write(_("# I moved all your custom buttons into .pronsolerc.\n# Please don't add them here any more.\n# Backup of your old buttons is in custombtn.old\n")) rco.write(_("# I moved all your custom buttons into .pronsolerc.\n# Please don't add them here any more.\n# Backup of your old buttons is in custombtn.old\n"))
rco.close() rco.close()
except IOError,x: except IOError, x:
print str(x) print str(x)
else: else:
print _("Note!!! You have specified custom buttons in both custombtn.txt and .pronsolerc") print _("Note!!! You have specified custom buttons in both custombtn.txt and .pronsolerc")
...@@ -152,30 +152,30 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -152,30 +152,30 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
pass pass
self.popmenu() self.popmenu()
self.popwindow() self.popwindow()
self.t=Tee(self.catchprint) self.t = Tee(self.catchprint)
self.stdout=sys.stdout self.stdout = sys.stdout
self.skeining=0 self.skeining = 0
self.mini=False self.mini = False
self.p.sendcb=self.sentcb self.p.sendcb = self.sentcb
self.p.startcb=self.startcb self.p.startcb = self.startcb
self.p.endcb=self.endcb self.p.endcb = self.endcb
self.starttime=0 self.starttime = 0
self.extra_print_time=0 self.extra_print_time = 0
self.curlayer=0 self.curlayer = 0
self.cur_button=None self.cur_button = None
self.predisconnect_mainqueue = None self.predisconnect_mainqueue = None
self.predisconnect_queueindex = None self.predisconnect_queueindex = None
self.predisconnect_layer = None self.predisconnect_layer = None
self.hsetpoint=0.0 self.hsetpoint = 0.0
self.bsetpoint=0.0 self.bsetpoint = 0.0
self.webInterface=None self.webInterface = None
if self.webrequested: if self.webrequested:
try : try :
import cherrypy import cherrypy
from printrun import webinterface from printrun import webinterface
try: try:
self.webInterface=webinterface.WebInterface(self) self.webInterface = webinterface.WebInterface(self)
self.webThread=threading.Thread(target=webinterface.StartWebInterfaceThread, args=(self.webInterface, )) self.webThread = threading.Thread(target = webinterface.StartWebInterfaceThread, args = (self.webInterface, ))
self.webThread.start() self.webThread.start()
except: except:
print _("Failed to start web interface") print _("Failed to start web interface")
...@@ -185,29 +185,29 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -185,29 +185,29 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
print _("CherryPy is not installed. Web Interface Disabled.") print _("CherryPy is not installed. Web Interface Disabled.")
def startcb(self): def startcb(self):
self.starttime=time.time() self.starttime = time.time()
print "Print Started at: " + format_time(self.starttime) print "Print Started at: " + format_time(self.starttime)
def endcb(self): def endcb(self):
if(self.p.queueindex==0): if(self.p.queueindex == 0):
print "Print ended at: " + format_time(time.time()) print "Print ended at: " + format_time(time.time())
print_duration = int(time.time () - self.starttime + self.extra_print_time) print_duration = int(time.time () - self.starttime + self.extra_print_time)
print "and took: " + format_duration(print_duration) print "and took: " + format_duration(print_duration)
wx.CallAfter(self.pausebtn.Disable) wx.CallAfter(self.pausebtn.Disable)
wx.CallAfter(self.printbtn.SetLabel,_("Print")) wx.CallAfter(self.printbtn.SetLabel, _("Print"))
param = self.settings.final_command param = self.settings.final_command
if not param: if not param:
return return
import shlex import shlex
pararray=[i.replace("$s",str(self.filename)).replace("$t", format_duration(print_duration)).encode() for i in shlex.split(param.replace("\\","\\\\").encode())] pararray=[i.replace("$s",str(self.filename)).replace("$t", format_duration(print_duration)).encode() for i in shlex.split(param.replace("\\","\\\\").encode())]
self.finalp=subprocess.Popen(pararray,stderr=subprocess.STDOUT,stdout=subprocess.PIPE) self.finalp = subprocess.Popen(pararray, stderr = subprocess.STDOUT, stdout = subprocess.PIPE)
def online(self): def online(self):
print _("Printer is now online.") print _("Printer is now online.")
self.connectbtn.SetLabel(_("Disconnect")) self.connectbtn.SetLabel(_("Disconnect"))
self.connectbtn.SetToolTip(wx.ToolTip("Disconnect from the printer")) self.connectbtn.SetToolTip(wx.ToolTip("Disconnect from the printer"))
self.connectbtn.Bind(wx.EVT_BUTTON,self.disconnect) self.connectbtn.Bind(wx.EVT_BUTTON, self.disconnect)
for i in self.printerControls: for i in self.printerControls:
wx.CallAfter(i.Enable) wx.CallAfter(i.Enable)
...@@ -234,8 +234,8 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -234,8 +234,8 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
self.sentlines.put_nowait(line) self.sentlines.put_nowait(line)
except: except:
pass pass
#threading.Thread(target=self.gviz.addgcode,args=(line,1)).start() #threading.Thread(target = self.gviz.addgcode, args = (line, 1)).start()
#self.gwindow.p.addgcode(line,hilight=1) #self.gwindow.p.addgcode(line, hilight = 1)
if "M104" in line or "M109" in line: if "M104" in line or "M109" in line:
if "S" in line: if "S" in line:
try: try:
...@@ -273,7 +273,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -273,7 +273,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
try: try:
if not l.__class__ in (str, unicode) or not len(l): if not l.__class__ in (str, unicode) or not len(l):
l = str(- float(self.edist.GetValue())) l = str(- float(self.edist.GetValue()))
pronsole.pronsole.do_extrude(self,l) pronsole.pronsole.do_extrude(self, l)
except: except:
pass pass
...@@ -373,7 +373,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -373,7 +373,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
pronsole.pronsole.delete_macro(self, macro_name) pronsole.pronsole.delete_macro(self, macro_name)
self.update_macros_menu() self.update_macros_menu()
def start_macro(self, macro_name, old_macro_definition=""): def start_macro(self, macro_name, old_macro_definition = ""):
if not self.processing_rc: if not self.processing_rc:
def cb(definition): def cb(definition):
if len(definition.strip()) == 0: if len(definition.strip()) == 0:
...@@ -468,7 +468,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -468,7 +468,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
panel = wx.Panel(dialog, -1) panel = wx.Panel(dialog, -1)
vbox = wx.BoxSizer(wx.VERTICAL) vbox = wx.BoxSizer(wx.VERTICAL)
wx.StaticText(panel, -1, _("Macro name:"), (8, 14)) wx.StaticText(panel, -1, _("Macro name:"), (8, 14))
dialog.namectrl = wx.TextCtrl(panel, -1, '', (110, 8), size=(130, 24), style = wx.TE_PROCESS_ENTER) dialog.namectrl = wx.TextCtrl(panel, -1, '', (110, 8), size = (130, 24), style = wx.TE_PROCESS_ENTER)
hbox = wx.BoxSizer(wx.HORIZONTAL) hbox = wx.BoxSizer(wx.HORIZONTAL)
okb = wx.Button(dialog, wx.ID_OK, _("Ok"), size = (60, 24)) okb = wx.Button(dialog, wx.ID_OK, _("Ok"), size = (60, 24))
dialog.Bind(wx.EVT_TEXT_ENTER, lambda e:dialog.EndModal(wx.ID_OK), dialog.namectrl) dialog.Bind(wx.EVT_TEXT_ENTER, lambda e:dialog.EndModal(wx.ID_OK), dialog.namectrl)
...@@ -501,7 +501,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -501,7 +501,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
return return
else: else:
old_def = "" old_def = ""
self.start_macro(macro,old_def) self.start_macro(macro, old_def)
return macro return macro
def update_macros_menu(self): def update_macros_menu(self):
...@@ -544,22 +544,22 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -544,22 +544,22 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
#upper section contains the mini view buttons #upper section contains the mini view buttons
#lower section contains the rest of the window - manual controls, console, visualizations #lower section contains the rest of the window - manual controls, console, visualizations
#TOP ROW: #TOP ROW:
uts=self.uppertopsizer=wx.BoxSizer(wx.HORIZONTAL) uts = self.uppertopsizer = wx.BoxSizer(wx.HORIZONTAL)
self.rescanbtn=wx.Button(self.panel,-1,_("Port"),size=buttonSize) self.rescanbtn = wx.Button(self.panel,-1, _("Port"),size = buttonSize)
self.rescanbtn.SetToolTip(wx.ToolTip("Communication Settings\nClick to rescan ports")) self.rescanbtn.SetToolTip(wx.ToolTip("Communication Settings\nClick to rescan ports"))
self.rescanbtn.Bind(wx.EVT_BUTTON,self.rescanports) self.rescanbtn.Bind(wx.EVT_BUTTON, self.rescanports)
uts.Add(self.rescanbtn,0,wx.TOP|wx.LEFT,0) uts.Add(self.rescanbtn, 0, wx.TOP|wx.LEFT, 0)
self.serialport = wx.ComboBox(self.panel, -1, self.serialport = wx.ComboBox(self.panel, -1,
choices=self.scanserial(), choices = self.scanserial(),
style=wx.CB_DROPDOWN, size=(100, 25)) style = wx.CB_DROPDOWN, size = (100, 25))
self.serialport.SetToolTip(wx.ToolTip("Select Port Printer is connected to")) self.serialport.SetToolTip(wx.ToolTip("Select Port Printer is connected to"))
self.rescanports() self.rescanports()
uts.Add(self.serialport) uts.Add(self.serialport)
uts.Add(wx.StaticText(self.panel,-1,"@"),0,wx.RIGHT|wx.ALIGN_CENTER,0) uts.Add(wx.StaticText(self.panel,-1,"@"),0, wx.RIGHT|wx.ALIGN_CENTER, 0)
self.baud = wx.ComboBox(self.panel, -1, self.baud = wx.ComboBox(self.panel, -1,
choices=["2400", "9600", "19200", "38400", "57600", "115200", "250000"], choices=["2400", "9600", "19200", "38400", "57600", "115200", "250000"],
style=wx.CB_DROPDOWN, size=(100, 25)) style = wx.CB_DROPDOWN, size = (100, 25))
self.baud.SetToolTip(wx.ToolTip("Select Baud rate for printer communication")) self.baud.SetToolTip(wx.ToolTip("Select Baud rate for printer communication"))
try: try:
self.baud.SetValue("115200") self.baud.SetValue("115200")
...@@ -567,164 +567,164 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -567,164 +567,164 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
except: except:
pass pass
uts.Add(self.baud) uts.Add(self.baud)
self.connectbtn=wx.Button(self.panel,-1,_("Connect"), size=buttonSize) self.connectbtn = wx.Button(self.panel,-1, _("Connect"), size = buttonSize)
uts.Add(self.connectbtn) uts.Add(self.connectbtn)
self.connectbtn.SetToolTip(wx.ToolTip("Connect to the printer")) self.connectbtn.SetToolTip(wx.ToolTip("Connect to the printer"))
self.connectbtn.Bind(wx.EVT_BUTTON,self.connect) self.connectbtn.Bind(wx.EVT_BUTTON, self.connect)
self.resetbtn=wx.Button(self.panel,-1,_("Reset"),style=wx.BU_EXACTFIT,size=(-1,buttonSize[1])) self.resetbtn = wx.Button(self.panel,-1, _("Reset"),style = wx.BU_EXACTFIT, size = (-1, buttonSize[1]))
self.resetbtn.Bind(wx.EVT_BUTTON,self.reset) self.resetbtn.Bind(wx.EVT_BUTTON, self.reset)
self.resetbtn.SetToolTip(wx.ToolTip("Reset the printer")) self.resetbtn.SetToolTip(wx.ToolTip("Reset the printer"))
uts.Add(self.resetbtn) uts.Add(self.resetbtn)
#self.minibtn=wx.Button(self.panel,-1,_("Mini mode"),style=wx.BU_EXACTFIT) #self.minibtn = wx.Button(self.panel,-1, _("Mini mode"),style = wx.BU_EXACTFIT)
#self.minibtn.Bind(wx.EVT_BUTTON,self.toggleview) #self.minibtn.Bind(wx.EVT_BUTTON, self.toggleview)
#uts.Add((25,-1)) #uts.Add((25,-1))
#uts.Add((15,-1),flag=wx.EXPAND) #uts.Add((15,-1),flag = wx.EXPAND)
#uts.Add(self.minibtn,0,wx.ALIGN_CENTER) #uts.Add(self.minibtn, 0, wx.ALIGN_CENTER)
#SECOND ROW #SECOND ROW
ubs=self.upperbottomsizer=uts#wx.BoxSizer(wx.HORIZONTAL) ubs = self.upperbottomsizer = uts#wx.BoxSizer(wx.HORIZONTAL)
self.loadbtn=wx.Button(self.panel,-1,_("Load file"),style=wx.BU_EXACTFIT,size=(-1,buttonSize[1])) self.loadbtn = wx.Button(self.panel,-1, _("Load file"),style = wx.BU_EXACTFIT, size = (-1, buttonSize[1]))
self.loadbtn.Bind(wx.EVT_BUTTON,self.loadfile) self.loadbtn.Bind(wx.EVT_BUTTON, self.loadfile)
self.loadbtn.SetToolTip(wx.ToolTip("Load a 3D model file")) self.loadbtn.SetToolTip(wx.ToolTip("Load a 3D model file"))
ubs.Add(self.loadbtn) ubs.Add(self.loadbtn)
self.platebtn=wx.Button(self.panel,-1,_("Compose"),style=wx.BU_EXACTFIT,size=(-1,buttonSize[1])) self.platebtn = wx.Button(self.panel,-1, _("Compose"),style = wx.BU_EXACTFIT, size = (-1, buttonSize[1]))
self.platebtn.Bind(wx.EVT_BUTTON,self.plate) self.platebtn.Bind(wx.EVT_BUTTON, self.plate)
self.platebtn.SetToolTip(wx.ToolTip("Simple Plater System")) self.platebtn.SetToolTip(wx.ToolTip("Simple Plater System"))
#self.printerControls.append(self.uploadbtn) #self.printerControls.append(self.uploadbtn)
ubs.Add(self.platebtn) ubs.Add(self.platebtn)
self.sdbtn=wx.Button(self.panel,-1,_("SD"),style=wx.BU_EXACTFIT,size=(-1,buttonSize[1])) self.sdbtn = wx.Button(self.panel,-1, _("SD"),style = wx.BU_EXACTFIT, size = (-1, buttonSize[1]))
self.sdbtn.Bind(wx.EVT_BUTTON,self.sdmenu) self.sdbtn.Bind(wx.EVT_BUTTON, self.sdmenu)
self.sdbtn.SetToolTip(wx.ToolTip("SD Card Printing")) self.sdbtn.SetToolTip(wx.ToolTip("SD Card Printing"))
self.printerControls.append(self.sdbtn) self.printerControls.append(self.sdbtn)
ubs.Add(self.sdbtn) ubs.Add(self.sdbtn)
self.printbtn=wx.Button(self.panel,-1,_("Print"), size=buttonSize) self.printbtn = wx.Button(self.panel,-1, _("Print"), size = buttonSize)
self.printbtn.Bind(wx.EVT_BUTTON,self.printfile) self.printbtn.Bind(wx.EVT_BUTTON, self.printfile)
self.printbtn.SetToolTip(wx.ToolTip("Start Printing Loaded File")) self.printbtn.SetToolTip(wx.ToolTip("Start Printing Loaded File"))
self.printbtn.Disable() self.printbtn.Disable()
ubs.Add(self.printbtn) ubs.Add(self.printbtn)
self.pausebtn=wx.Button(self.panel,-1,_("Pause"), size=buttonSize) self.pausebtn = wx.Button(self.panel,-1, _("Pause"), size = buttonSize)
self.pausebtn.SetToolTip(wx.ToolTip("Pause Current Print")) self.pausebtn.SetToolTip(wx.ToolTip("Pause Current Print"))
self.pausebtn.Bind(wx.EVT_BUTTON,self.pause) self.pausebtn.Bind(wx.EVT_BUTTON, self.pause)
ubs.Add(self.pausebtn) ubs.Add(self.pausebtn)
self.recoverbtn=wx.Button(self.panel,-1,_("Recover"), size=buttonSize) self.recoverbtn = wx.Button(self.panel,-1, _("Recover"), size = buttonSize)
self.recoverbtn.SetToolTip(wx.ToolTip("Recover previous Print")) self.recoverbtn.SetToolTip(wx.ToolTip("Recover previous Print"))
self.recoverbtn.Bind(wx.EVT_BUTTON,self.recover) self.recoverbtn.Bind(wx.EVT_BUTTON, self.recover)
ubs.Add(self.recoverbtn) ubs.Add(self.recoverbtn)
#Right full view #Right full view
lrs=self.lowerrsizer=wx.BoxSizer(wx.VERTICAL) lrs = self.lowerrsizer = wx.BoxSizer(wx.VERTICAL)
self.logbox=wx.TextCtrl(self.panel,style = wx.TE_MULTILINE,size=(350,-1)) self.logbox = wx.TextCtrl(self.panel, style = wx.TE_MULTILINE, size = (350,-1))
self.logbox.SetEditable(0) self.logbox.SetEditable(0)
lrs.Add(self.logbox,1,wx.EXPAND) lrs.Add(self.logbox, 1, wx.EXPAND)
lbrs=wx.BoxSizer(wx.HORIZONTAL) lbrs = wx.BoxSizer(wx.HORIZONTAL)
self.commandbox=wx.TextCtrl(self.panel,style = wx.TE_PROCESS_ENTER) self.commandbox = wx.TextCtrl(self.panel, style = wx.TE_PROCESS_ENTER)
self.commandbox.SetToolTip(wx.ToolTip("Send commands to printer\n(Type 'help' for simple\nhelp function)")) self.commandbox.SetToolTip(wx.ToolTip("Send commands to printer\n(Type 'help' for simple\nhelp function)"))
self.commandbox.Bind(wx.EVT_TEXT_ENTER,self.sendline) self.commandbox.Bind(wx.EVT_TEXT_ENTER, self.sendline)
self.commandbox.Bind(wx.EVT_CHAR, self.cbkey) self.commandbox.Bind(wx.EVT_CHAR, self.cbkey)
self.commandbox.history=[u""] self.commandbox.history=[u""]
self.commandbox.histindex=1 self.commandbox.histindex = 1
#self.printerControls.append(self.commandbox) #self.printerControls.append(self.commandbox)
lbrs.Add(self.commandbox,1) lbrs.Add(self.commandbox, 1)
self.sendbtn=wx.Button(self.panel,-1,_("Send"),style=wx.BU_EXACTFIT) self.sendbtn = wx.Button(self.panel,-1, _("Send"),style = wx.BU_EXACTFIT)
self.sendbtn.SetToolTip(wx.ToolTip("Send Command to Printer")) self.sendbtn.SetToolTip(wx.ToolTip("Send Command to Printer"))
self.sendbtn.Bind(wx.EVT_BUTTON,self.sendline) self.sendbtn.Bind(wx.EVT_BUTTON, self.sendline)
#self.printerControls.append(self.sendbtn) #self.printerControls.append(self.sendbtn)
lbrs.Add(self.sendbtn) lbrs.Add(self.sendbtn)
lrs.Add(lbrs,0,wx.EXPAND) lrs.Add(lbrs, 0, wx.EXPAND)
#left pane #left pane
lls=self.lowerlsizer=wx.GridBagSizer() lls = self.lowerlsizer = wx.GridBagSizer()
llts=wx.BoxSizer(wx.HORIZONTAL) llts = wx.BoxSizer(wx.HORIZONTAL)
#lls.Add(wx.StaticText(self.panel,-1,_("mm/min")),pos=(0,4),span=(1,4)) #lls.Add(wx.StaticText(self.panel,-1, _("mm/min")),pos = (0, 4),span = (1, 4))
lls.Add(llts,pos=(0,0),span=(1,9)) lls.Add(llts, pos = (0, 0),span = (1, 9))
#lls.Add((200,375)) #lls.Add((200, 375))
szbuttons=wx.GridBagSizer() szbuttons = wx.GridBagSizer()
self.xyb = XYButtons(self.panel, self.moveXY, self.homeButtonClicked, self.spacebarAction, self.settings.bgcolor) self.xyb = XYButtons(self.panel, self.moveXY, self.homeButtonClicked, self.spacebarAction, self.settings.bgcolor)
szbuttons.Add(self.xyb,pos=(0,1),flag=wx.ALIGN_CENTER) szbuttons.Add(self.xyb, pos = (0, 1),flag = wx.ALIGN_CENTER)
self.zb = ZButtons(self.panel, self.moveZ, self.settings.bgcolor) self.zb = ZButtons(self.panel, self.moveZ, self.settings.bgcolor)
szbuttons.Add(self.zb,pos=(0,2),flag=wx.ALIGN_CENTER) szbuttons.Add(self.zb, pos = (0, 2),flag = wx.ALIGN_CENTER)
#lls.Add(self.zb, pos=(2,6), span=(1,1), flag=wx.ALIGN_CENTER) #lls.Add(self.zb, pos = (2, 6), span = (1, 1), flag = wx.ALIGN_CENTER)
wx.CallAfter(self.xyb.SetFocus) wx.CallAfter(self.xyb.SetFocus)
lls.Add(szbuttons, pos=(1,0), span=(1,8), flag=wx.ALIGN_CENTER) lls.Add(szbuttons, pos = (1, 0), span = (1, 8), flag = wx.ALIGN_CENTER)
for i in self.cpbuttons: for i in self.cpbuttons:
btn=wx.Button(self.panel,-1,i[0],style=wx.BU_EXACTFIT) btn = wx.Button(self.panel,-1, i[0],style = wx.BU_EXACTFIT)
btn.SetToolTip(wx.ToolTip(i[5])) btn.SetToolTip(wx.ToolTip(i[5]))
btn.SetBackgroundColour(i[3]) btn.SetBackgroundColour(i[3])
btn.SetForegroundColour("black") btn.SetForegroundColour("black")
btn.properties=i btn.properties = i
btn.Bind(wx.EVT_BUTTON,self.procbutton) btn.Bind(wx.EVT_BUTTON, self.procbutton)
self.btndict[i[1]]=btn self.btndict[i[1]]=btn
self.printerControls.append(btn) self.printerControls.append(btn)
if(i[2]==None): if(i[2]==None):
if(i[4]==0): if(i[4]==0):
llts.Add(btn) llts.Add(btn)
else: else:
lls.Add(btn,pos=i[2],span=i[4]) lls.Add(btn, pos = i[2],span = i[4])
self.xyfeedc=wx.SpinCtrl(self.panel,-1,str(self.settings.xy_feedrate),min=0,max=50000,size=(70,-1)) self.xyfeedc = wx.SpinCtrl(self.panel,-1, str(self.settings.xy_feedrate),min = 0, max = 50000, size = (70,-1))
self.xyfeedc.SetToolTip(wx.ToolTip("Set Maximum Speed for X & Y axes (mm/min)")) self.xyfeedc.SetToolTip(wx.ToolTip("Set Maximum Speed for X & Y axes (mm/min)"))
llts.Add(wx.StaticText(self.panel,-1,_("XY:")), flag=wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) llts.Add(wx.StaticText(self.panel,-1, _("XY:")), flag = wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
llts.Add(self.xyfeedc) llts.Add(self.xyfeedc)
llts.Add(wx.StaticText(self.panel,-1,_("mm/min Z:")), flag=wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) llts.Add(wx.StaticText(self.panel,-1, _("mm/min Z:")), flag = wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
self.zfeedc=wx.SpinCtrl(self.panel,-1,str(self.settings.z_feedrate),min=0,max=50000,size=(70,-1)) self.zfeedc = wx.SpinCtrl(self.panel,-1, str(self.settings.z_feedrate),min = 0, max = 50000, size = (70,-1))
self.zfeedc.SetToolTip(wx.ToolTip("Set Maximum Speed for Z axis (mm/min)")) self.zfeedc.SetToolTip(wx.ToolTip("Set Maximum Speed for Z axis (mm/min)"))
llts.Add(self.zfeedc,) llts.Add(self.zfeedc,)
self.monitorbox=wx.CheckBox(self.panel,-1,_("Watch")) self.monitorbox = wx.CheckBox(self.panel,-1, _("Watch"))
self.monitorbox.SetToolTip(wx.ToolTip("Monitor Temperatures in Graph")) self.monitorbox.SetToolTip(wx.ToolTip("Monitor Temperatures in Graph"))
lls.Add(self.monitorbox,pos=(2,6)) lls.Add(self.monitorbox, pos = (2, 6))
self.monitorbox.Bind(wx.EVT_CHECKBOX,self.setmonitor) self.monitorbox.Bind(wx.EVT_CHECKBOX, self.setmonitor)
lls.Add(wx.StaticText(self.panel,-1,_("Heat:")),pos=(2,0),span=(1,1),flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT) lls.Add(wx.StaticText(self.panel,-1, _("Heat:")),pos = (2, 0),span = (1, 1),flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
htemp_choices=[self.temps[i]+" ("+i+")" for i in sorted(self.temps.keys(),key=lambda x:self.temps[x])] htemp_choices=[self.temps[i]+" ("+i+")" for i in sorted(self.temps.keys(),key = lambda x:self.temps[x])]
self.settoff=wx.Button(self.panel,-1,_("Off"),size=(36,-1),style=wx.BU_EXACTFIT) self.settoff = wx.Button(self.panel,-1, _("Off"),size = (36,-1),style = wx.BU_EXACTFIT)
self.settoff.SetToolTip(wx.ToolTip("Switch Hotend Off")) self.settoff.SetToolTip(wx.ToolTip("Switch Hotend Off"))
self.settoff.Bind(wx.EVT_BUTTON,lambda e:self.do_settemp("off")) self.settoff.Bind(wx.EVT_BUTTON, lambda e:self.do_settemp("off"))
self.printerControls.append(self.settoff) self.printerControls.append(self.settoff)
lls.Add(self.settoff,pos=(2,1),span=(1,1)) lls.Add(self.settoff, pos = (2, 1),span = (1, 1))
if self.settings.last_temperature not in map(float,self.temps.values()): if self.settings.last_temperature not in map(float, self.temps.values()):
htemp_choices = [str(self.settings.last_temperature)] + htemp_choices htemp_choices = [str(self.settings.last_temperature)] + htemp_choices
self.htemp=wx.ComboBox(self.panel, -1, self.htemp = wx.ComboBox(self.panel, -1,
choices=htemp_choices,style=wx.CB_DROPDOWN, size=(70,-1)) choices = htemp_choices, style = wx.CB_DROPDOWN, size = (70,-1))
self.htemp.SetToolTip(wx.ToolTip("Select Temperature for Hotend")) self.htemp.SetToolTip(wx.ToolTip("Select Temperature for Hotend"))
self.htemp.Bind(wx.EVT_COMBOBOX,self.htemp_change) self.htemp.Bind(wx.EVT_COMBOBOX, self.htemp_change)
lls.Add(self.htemp,pos=(2,2),span=(1,2)) lls.Add(self.htemp, pos = (2, 2),span = (1, 2))
self.settbtn=wx.Button(self.panel,-1,_("Set"),size=(38,-1),style=wx.BU_EXACTFIT) self.settbtn = wx.Button(self.panel,-1, _("Set"),size = (38,-1),style = wx.BU_EXACTFIT)
self.settbtn.SetToolTip(wx.ToolTip("Switch Hotend On")) self.settbtn.SetToolTip(wx.ToolTip("Switch Hotend On"))
self.settbtn.Bind(wx.EVT_BUTTON,self.do_settemp) self.settbtn.Bind(wx.EVT_BUTTON, self.do_settemp)
self.printerControls.append(self.settbtn) self.printerControls.append(self.settbtn)
lls.Add(self.settbtn,pos=(2,4),span=(1,1)) lls.Add(self.settbtn, pos = (2, 4),span = (1, 1))
lls.Add(wx.StaticText(self.panel,-1,_("Bed:")),pos=(3,0),span=(1,1),flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT) lls.Add(wx.StaticText(self.panel,-1, _("Bed:")),pos = (3, 0),span = (1, 1),flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
btemp_choices=[self.bedtemps[i]+" ("+i+")" for i in sorted(self.bedtemps.keys(),key=lambda x:self.temps[x])] btemp_choices=[self.bedtemps[i]+" ("+i+")" for i in sorted(self.bedtemps.keys(),key = lambda x:self.temps[x])]
self.setboff=wx.Button(self.panel,-1,_("Off"),size=(36,-1),style=wx.BU_EXACTFIT) self.setboff = wx.Button(self.panel,-1, _("Off"),size = (36,-1),style = wx.BU_EXACTFIT)
self.setboff.SetToolTip(wx.ToolTip("Switch Heated Bed Off")) self.setboff.SetToolTip(wx.ToolTip("Switch Heated Bed Off"))
self.setboff.Bind(wx.EVT_BUTTON,lambda e:self.do_bedtemp("off")) self.setboff.Bind(wx.EVT_BUTTON, lambda e:self.do_bedtemp("off"))
self.printerControls.append(self.setboff) self.printerControls.append(self.setboff)
lls.Add(self.setboff,pos=(3,1),span=(1,1)) lls.Add(self.setboff, pos = (3, 1),span = (1, 1))
if self.settings.last_bed_temperature not in map(float,self.bedtemps.values()): if self.settings.last_bed_temperature not in map(float, self.bedtemps.values()):
btemp_choices = [str(self.settings.last_bed_temperature)] + btemp_choices btemp_choices = [str(self.settings.last_bed_temperature)] + btemp_choices
self.btemp=wx.ComboBox(self.panel, -1, self.btemp = wx.ComboBox(self.panel, -1,
choices=btemp_choices,style=wx.CB_DROPDOWN, size=(70,-1)) choices = btemp_choices, style = wx.CB_DROPDOWN, size = (70,-1))
self.btemp.SetToolTip(wx.ToolTip("Select Temperature for Heated Bed")) self.btemp.SetToolTip(wx.ToolTip("Select Temperature for Heated Bed"))
self.btemp.Bind(wx.EVT_COMBOBOX,self.btemp_change) self.btemp.Bind(wx.EVT_COMBOBOX, self.btemp_change)
lls.Add(self.btemp,pos=(3,2),span=(1,2)) lls.Add(self.btemp, pos = (3, 2),span = (1, 2))
self.setbbtn=wx.Button(self.panel,-1,_("Set"),size=(38,-1),style=wx.BU_EXACTFIT) self.setbbtn = wx.Button(self.panel,-1, _("Set"),size = (38,-1),style = wx.BU_EXACTFIT)
self.setbbtn.SetToolTip(wx.ToolTip("Switch Heated Bed On")) self.setbbtn.SetToolTip(wx.ToolTip("Switch Heated Bed On"))
self.setbbtn.Bind(wx.EVT_BUTTON,self.do_bedtemp) self.setbbtn.Bind(wx.EVT_BUTTON, self.do_bedtemp)
self.printerControls.append(self.setbbtn) self.printerControls.append(self.setbbtn)
lls.Add(self.setbbtn,pos=(3,4),span=(1,1)) lls.Add(self.setbbtn, pos = (3, 4),span = (1, 1))
self.btemp.SetValue(str(self.settings.last_bed_temperature)) self.btemp.SetValue(str(self.settings.last_bed_temperature))
self.htemp.SetValue(str(self.settings.last_temperature)) self.htemp.SetValue(str(self.settings.last_temperature))
...@@ -745,81 +745,81 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -745,81 +745,81 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
if( '(' not in self.htemp.Value): if( '(' not in self.htemp.Value):
self.htemp.SetValue(self.htemp.Value + ' (user)') self.htemp.SetValue(self.htemp.Value + ' (user)')
#lls.Add(self.btemp,pos=(4,1),span=(1,3)) #lls.Add(self.btemp, pos = (4, 1),span = (1, 3))
#lls.Add(self.setbbtn,pos=(4,4),span=(1,2)) #lls.Add(self.setbbtn, pos = (4, 4),span = (1, 2))
self.tempdisp=wx.StaticText(self.panel,-1,"") self.tempdisp = wx.StaticText(self.panel,-1,"")
self.edist=wx.SpinCtrl(self.panel,-1,"5",min=0,max=1000,size=(60,-1)) self.edist = wx.SpinCtrl(self.panel,-1,"5",min = 0, max = 1000, size = (60,-1))
self.edist.SetBackgroundColour((225,200,200)) self.edist.SetBackgroundColour((225, 200, 200))
self.edist.SetForegroundColour("black") self.edist.SetForegroundColour("black")
lls.Add(self.edist,pos=(4,2),span=(1,2)) lls.Add(self.edist, pos = (4, 2),span = (1, 2))
lls.Add(wx.StaticText(self.panel,-1,_("mm")),pos=(4,4),span=(1,1)) lls.Add(wx.StaticText(self.panel,-1, _("mm")),pos = (4, 4),span = (1, 1))
self.edist.SetToolTip(wx.ToolTip("Amount to Extrude or Retract (mm)")) self.edist.SetToolTip(wx.ToolTip("Amount to Extrude or Retract (mm)"))
self.efeedc=wx.SpinCtrl(self.panel,-1,str(self.settings.e_feedrate),min=0,max=50000,size=(60,-1)) self.efeedc = wx.SpinCtrl(self.panel,-1, str(self.settings.e_feedrate),min = 0, max = 50000, size = (60,-1))
self.efeedc.SetToolTip(wx.ToolTip("Extrude / Retract speed (mm/min)")) self.efeedc.SetToolTip(wx.ToolTip("Extrude / Retract speed (mm/min)"))
self.efeedc.SetBackgroundColour((225,200,200)) self.efeedc.SetBackgroundColour((225, 200, 200))
self.efeedc.SetForegroundColour("black") self.efeedc.SetForegroundColour("black")
self.efeedc.Bind(wx.EVT_SPINCTRL,self.setfeeds) self.efeedc.Bind(wx.EVT_SPINCTRL, self.setfeeds)
lls.Add(self.efeedc,pos=(5,2),span=(1,2)) lls.Add(self.efeedc, pos = (5, 2),span = (1, 2))
lls.Add(wx.StaticText(self.panel,-1,_("mm/\nmin")),pos=(5,4),span=(1,1)) lls.Add(wx.StaticText(self.panel,-1, _("mm/\nmin")),pos = (5, 4),span = (1, 1))
self.xyfeedc.Bind(wx.EVT_SPINCTRL,self.setfeeds) self.xyfeedc.Bind(wx.EVT_SPINCTRL, self.setfeeds)
self.zfeedc.Bind(wx.EVT_SPINCTRL,self.setfeeds) self.zfeedc.Bind(wx.EVT_SPINCTRL, self.setfeeds)
self.zfeedc.SetBackgroundColour((180,255,180)) self.zfeedc.SetBackgroundColour((180, 255, 180))
self.zfeedc.SetForegroundColour("black") self.zfeedc.SetForegroundColour("black")
# lls.Add((10,0),pos=(0,11),span=(1,1)) # lls.Add((10, 0),pos = (0, 11),span = (1, 1))
#self.hottgauge=TempGauge(self.panel,size=(200,24),title=_("Heater:"),maxval=230) #self.hottgauge = TempGauge(self.panel, size = (200, 24),title = _("Heater:"),maxval = 230)
#lls.Add(self.hottgauge,pos=(7,0),span=(1,4)) #lls.Add(self.hottgauge, pos = (7, 0),span = (1, 4))
#self.bedtgauge=TempGauge(self.panel,size=(200,24),title=_("Bed:"),maxval=130) #self.bedtgauge = TempGauge(self.panel, size = (200, 24),title = _("Bed:"),maxval = 130)
#lls.Add(self.bedtgauge,pos=(8,0),span=(1,4)) #lls.Add(self.bedtgauge, pos = (8, 0),span = (1, 4))
#def scroll_setpoint(e): #def scroll_setpoint(e):
# if e.GetWheelRotation()>0: # if e.GetWheelRotation()>0:
# self.do_settemp(str(self.hsetpoint+1)) # self.do_settemp(str(self.hsetpoint+1))
# elif e.GetWheelRotation()<0: # elif e.GetWheelRotation()<0:
# self.do_settemp(str(max(0,self.hsetpoint-1))) # self.do_settemp(str(max(0, self.hsetpoint-1)))
#self.tgauge.Bind(wx.EVT_MOUSEWHEEL,scroll_setpoint) #self.tgauge.Bind(wx.EVT_MOUSEWHEEL, scroll_setpoint)
self.graph = Graph(self.panel, wx.ID_ANY) self.graph = Graph(self.panel, wx.ID_ANY)
lls.Add(self.graph, pos=(3,5), span=(3,3)) lls.Add(self.graph, pos = (3, 5), span = (3, 3))
lls.Add(self.tempdisp,pos=(6,0),span=(1,1)) lls.Add(self.tempdisp, pos = (6, 0),span = (1, 1))
self.gviz=gviz.gviz(self.panel,(300,300), self.gviz = gviz.gviz(self.panel,(300, 300),
build_dimensions=self.build_dimensions_list, build_dimensions = self.build_dimensions_list,
grid=(self.settings.preview_grid_step1,self.settings.preview_grid_step2), grid = (self.settings.preview_grid_step1, self.settings.preview_grid_step2),
extrusion_width=self.settings.preview_extrusion_width) extrusion_width = self.settings.preview_extrusion_width)
self.gviz.SetToolTip(wx.ToolTip("Click to examine / edit\n layers of loaded file")) self.gviz.SetToolTip(wx.ToolTip("Click to examine / edit\n layers of loaded file"))
self.gviz.showall=1 self.gviz.showall = 1
try: try:
raise "" raise ""
import stlview import stlview
self.gwindow=stlview.GCFrame(None, wx.ID_ANY, 'Gcode view, shift to move view, mousewheel to set layer', size=(600,600)) self.gwindow = stlview.GCFrame(None, wx.ID_ANY, 'Gcode view, shift to move view, mousewheel to set layer', size = (600, 600))
except: except:
self.gwindow=gviz.window([], self.gwindow = gviz.window([],
build_dimensions=self.build_dimensions_list, build_dimensions = self.build_dimensions_list,
grid=(self.settings.preview_grid_step1,self.settings.preview_grid_step2), grid = (self.settings.preview_grid_step1, self.settings.preview_grid_step2),
extrusion_width=self.settings.preview_extrusion_width) extrusion_width = self.settings.preview_extrusion_width)
self.gviz.Bind(wx.EVT_LEFT_DOWN,self.showwin) self.gviz.Bind(wx.EVT_LEFT_DOWN, self.showwin)
self.gwindow.Bind(wx.EVT_CLOSE,lambda x:self.gwindow.Hide()) self.gwindow.Bind(wx.EVT_CLOSE, lambda x:self.gwindow.Hide())
vcs=wx.BoxSizer(wx.VERTICAL) vcs = wx.BoxSizer(wx.VERTICAL)
vcs.Add(self.gviz,1,flag=wx.SHAPED) vcs.Add(self.gviz, 1, flag = wx.SHAPED)
cs=self.centersizer=wx.GridBagSizer() cs = self.centersizer = wx.GridBagSizer()
vcs.Add(cs,0,flag=wx.EXPAND) vcs.Add(cs, 0, flag = wx.EXPAND)
self.uppersizer=wx.BoxSizer(wx.VERTICAL) self.uppersizer = wx.BoxSizer(wx.VERTICAL)
self.uppersizer.Add(self.uppertopsizer) self.uppersizer.Add(self.uppertopsizer)
#self.uppersizer.Add(self.upperbottomsizer) #self.uppersizer.Add(self.upperbottomsizer)
self.lowersizer=wx.BoxSizer(wx.HORIZONTAL) self.lowersizer = wx.BoxSizer(wx.HORIZONTAL)
self.lowersizer.Add(lls) self.lowersizer.Add(lls)
self.lowersizer.Add(vcs,1,wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL) self.lowersizer.Add(vcs, 1, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL)
self.lowersizer.Add(lrs,0,wx.EXPAND) self.lowersizer.Add(lrs, 0, wx.EXPAND)
self.topsizer=wx.BoxSizer(wx.VERTICAL) self.topsizer = wx.BoxSizer(wx.VERTICAL)
self.topsizer.Add(self.uppersizer) self.topsizer.Add(self.uppersizer)
self.topsizer.Add(self.lowersizer,1,wx.EXPAND) self.topsizer.Add(self.lowersizer, 1, wx.EXPAND)
self.panel.SetSizer(self.topsizer) self.panel.SetSizer(self.topsizer)
self.status=self.CreateStatusBar() self.status = self.CreateStatusBar()
self.status.SetStatusText(_("Not connected to printer.")) self.status.SetStatusText(_("Not connected to printer."))
self.panel.Bind(wx.EVT_MOUSE_EVENTS,self.editbutton) self.panel.Bind(wx.EVT_MOUSE_EVENTS, self.editbutton)
self.Bind(wx.EVT_CLOSE, self.kill) self.Bind(wx.EVT_CLOSE, self.kill)
self.topsizer.Layout() self.topsizer.Layout()
...@@ -835,62 +835,62 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -835,62 +835,62 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
#uts.Layout() #uts.Layout()
self.cbuttons_reload() self.cbuttons_reload()
def cbkey(self,e): def cbkey(self, e):
if e.GetKeyCode()==wx.WXK_UP: if e.GetKeyCode() == wx.WXK_UP:
if self.commandbox.histindex==len(self.commandbox.history): if self.commandbox.histindex == len(self.commandbox.history):
self.commandbox.history+=[self.commandbox.GetValue()] #save current command self.commandbox.history+=[self.commandbox.GetValue()] #save current command
if len(self.commandbox.history): if len(self.commandbox.history):
self.commandbox.histindex=(self.commandbox.histindex-1)%len(self.commandbox.history) self.commandbox.histindex = (self.commandbox.histindex-1)%len(self.commandbox.history)
self.commandbox.SetValue(self.commandbox.history[self.commandbox.histindex]) self.commandbox.SetValue(self.commandbox.history[self.commandbox.histindex])
self.commandbox.SetSelection(0,len(self.commandbox.history[self.commandbox.histindex])) self.commandbox.SetSelection(0, len(self.commandbox.history[self.commandbox.histindex]))
elif e.GetKeyCode()==wx.WXK_DOWN: elif e.GetKeyCode() == wx.WXK_DOWN:
if self.commandbox.histindex==len(self.commandbox.history): if self.commandbox.histindex == len(self.commandbox.history):
self.commandbox.history+=[self.commandbox.GetValue()] #save current command self.commandbox.history+=[self.commandbox.GetValue()] #save current command
if len(self.commandbox.history): if len(self.commandbox.history):
self.commandbox.histindex=(self.commandbox.histindex+1)%len(self.commandbox.history) self.commandbox.histindex = (self.commandbox.histindex+1)%len(self.commandbox.history)
self.commandbox.SetValue(self.commandbox.history[self.commandbox.histindex]) self.commandbox.SetValue(self.commandbox.history[self.commandbox.histindex])
self.commandbox.SetSelection(0,len(self.commandbox.history[self.commandbox.histindex])) self.commandbox.SetSelection(0, len(self.commandbox.history[self.commandbox.histindex]))
else: else:
e.Skip() e.Skip()
def plate(self,e): def plate(self, e):
import plater import plater
print "plate function activated" print "plate function activated"
plater.stlwin(size=(800,580),callback=self.platecb,parent=self).Show() plater.stlwin(size = (800, 580),callback = self.platecb, parent = self).Show()
def platecb(self,name): def platecb(self, name):
print "plated: "+name print "plated: "+name
self.loadfile(None,name) self.loadfile(None, name)
def sdmenu(self,e): def sdmenu(self, e):
obj = e.GetEventObject() obj = e.GetEventObject()
popupmenu=wx.Menu() popupmenu = wx.Menu()
item = popupmenu.Append(-1,_("SD Upload")) item = popupmenu.Append(-1, _("SD Upload"))
if not self.f or not len(self.f): if not self.f or not len(self.f):
item.Enable(False) item.Enable(False)
self.Bind(wx.EVT_MENU,self.upload,id=item.GetId()) self.Bind(wx.EVT_MENU, self.upload, id = item.GetId())
item = popupmenu.Append(-1,_("SD Print")) item = popupmenu.Append(-1, _("SD Print"))
self.Bind(wx.EVT_MENU,self.sdprintfile,id=item.GetId()) self.Bind(wx.EVT_MENU, self.sdprintfile, id = item.GetId())
self.panel.PopupMenu(popupmenu, obj.GetPosition()) self.panel.PopupMenu(popupmenu, obj.GetPosition())
def htemp_change(self,event): def htemp_change(self, event):
if self.hsetpoint > 0: if self.hsetpoint > 0:
self.do_settemp("") self.do_settemp("")
wx.CallAfter(self.htemp.SetInsertionPoint,0) wx.CallAfter(self.htemp.SetInsertionPoint, 0)
def btemp_change(self,event): def btemp_change(self, event):
if self.bsetpoint > 0: if self.bsetpoint > 0:
self.do_bedtemp("") self.do_bedtemp("")
wx.CallAfter(self.btemp.SetInsertionPoint,0) wx.CallAfter(self.btemp.SetInsertionPoint, 0)
def showwin(self,event): def showwin(self, event):
if(self.f is not None): if(self.f is not None):
self.gwindow.Show(True) self.gwindow.Show(True)
self.gwindow.SetToolTip(wx.ToolTip("Mousewheel zooms the display\nShift / Mousewheel scrolls layers")) self.gwindow.SetToolTip(wx.ToolTip("Mousewheel zooms the display\nShift / Mousewheel scrolls layers"))
self.gwindow.Raise() self.gwindow.Raise()
def setfeeds(self,e): def setfeeds(self, e):
self.feedrates_changed = True self.feedrates_changed = True
try: try:
self.settings._set("e_feedrate",self.efeedc.GetValue()) self.settings._set("e_feedrate",self.efeedc.GetValue())
...@@ -905,16 +905,16 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -905,16 +905,16 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
except: except:
pass pass
def toggleview(self,e): def toggleview(self, e):
if(self.mini): if(self.mini):
self.mini=False self.mini = False
self.topsizer.Fit(self) self.topsizer.Fit(self)
#self.SetSize(winsize) #self.SetSize(winsize)
wx.CallAfter(self.minibtn.SetLabel, _("Mini mode")) wx.CallAfter(self.minibtn.SetLabel, _("Mini mode"))
else: else:
self.mini=True self.mini = True
self.uppersizer.Fit(self) self.uppersizer.Fit(self)
#self.SetSize(winssize) #self.SetSize(winssize)
...@@ -922,15 +922,15 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -922,15 +922,15 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
def cbuttons_reload(self): def cbuttons_reload(self):
allcbs = [] allcbs = []
ubs=self.upperbottomsizer ubs = self.upperbottomsizer
cs=self.centersizer cs = self.centersizer
#for item in ubs.GetChildren(): #for item in ubs.GetChildren():
# if hasattr(item.GetWindow(),"custombutton"): # if hasattr(item.GetWindow(),"custombutton"):
# allcbs += [(ubs,item.GetWindow())] # allcbs += [(ubs, item.GetWindow())]
for item in cs.GetChildren(): for item in cs.GetChildren():
if hasattr(item.GetWindow(),"custombutton"): if hasattr(item.GetWindow(),"custombutton"):
allcbs += [(cs,item.GetWindow())] allcbs += [(cs, item.GetWindow())]
for sizer,button in allcbs: for sizer, button in allcbs:
#sizer.Remove(button) #sizer.Remove(button)
button.Destroy() button.Destroy()
self.custombuttonbuttons=[] self.custombuttonbuttons=[]
...@@ -942,37 +942,37 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -942,37 +942,37 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
for i in xrange(len(self.custombuttons)): for i in xrange(len(self.custombuttons)):
btndef = self.custombuttons[i] btndef = self.custombuttons[i]
try: try:
b=wx.Button(self.panel,-1,btndef[0],style=wx.BU_EXACTFIT) b = wx.Button(self.panel,-1, btndef[0],style = wx.BU_EXACTFIT)
b.SetToolTip(wx.ToolTip(_("Execute command: ")+btndef[1])) b.SetToolTip(wx.ToolTip(_("Execute command: ")+btndef[1]))
if len(btndef)>2: if len(btndef)>2:
b.SetBackgroundColour(btndef[2]) b.SetBackgroundColour(btndef[2])
rr,gg,bb=b.GetBackgroundColour().Get() rr, gg, bb = b.GetBackgroundColour().Get()
if 0.3*rr+0.59*gg+0.11*bb < 60: if 0.3*rr+0.59*gg+0.11*bb < 60:
b.SetForegroundColour("#ffffff") b.SetForegroundColour("#ffffff")
except: except:
if i == newbuttonbuttonindex: if i == newbuttonbuttonindex:
self.newbuttonbutton=b=wx.Button(self.panel,-1,"+",size=(19,18),style=wx.BU_EXACTFIT) self.newbuttonbutton = b = wx.Button(self.panel,-1,"+",size = (19, 18),style = wx.BU_EXACTFIT)
#b.SetFont(wx.Font(12,wx.FONTFAMILY_SWISS,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_BOLD)) #b.SetFont(wx.Font(12, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD))
b.SetForegroundColour("#4444ff") b.SetForegroundColour("#4444ff")
b.SetToolTip(wx.ToolTip(_("click to add new custom button"))) b.SetToolTip(wx.ToolTip(_("click to add new custom button")))
b.Bind(wx.EVT_BUTTON,self.cbutton_edit) b.Bind(wx.EVT_BUTTON, self.cbutton_edit)
else: else:
b=wx.Button(self.panel,-1,".",size=(1,1)) b = wx.Button(self.panel,-1,".",size = (1, 1))
#b=wx.StaticText(self.panel,-1,"",size=(72,22),style=wx.ALIGN_CENTRE+wx.ST_NO_AUTORESIZE) #+wx.SIMPLE_BORDER #b = wx.StaticText(self.panel,-1,"",size = (72, 22),style = wx.ALIGN_CENTRE+wx.ST_NO_AUTORESIZE) #+wx.SIMPLE_BORDER
b.Disable() b.Disable()
#continue #continue
b.custombutton=i b.custombutton = i
b.properties=btndef b.properties = btndef
if btndef is not None: if btndef is not None:
b.Bind(wx.EVT_BUTTON,self.procbutton) b.Bind(wx.EVT_BUTTON, self.procbutton)
b.Bind(wx.EVT_MOUSE_EVENTS,self.editbutton) b.Bind(wx.EVT_MOUSE_EVENTS, self.editbutton)
#else: #else:
# b.Bind(wx.EVT_BUTTON,lambda e:e.Skip()) # b.Bind(wx.EVT_BUTTON, lambda e:e.Skip())
self.custombuttonbuttons.append(b) self.custombuttonbuttons.append(b)
#if i<4: #if i<4:
# ubs.Add(b) # ubs.Add(b)
#else: #else:
cs.Add(b,pos=((i)/4,(i)%4)) cs.Add(b, pos = ((i)/4,(i)%4))
self.topsizer.Layout() self.topsizer.Layout()
def help_button(self): def help_button(self):
...@@ -980,25 +980,25 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -980,25 +980,25 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
if self.webInterface: if self.webInterface:
self.webInterface.AddLog('Defines custom button. Usage: button <num> "title" [/c "colour"] command') self.webInterface.AddLog('Defines custom button. Usage: button <num> "title" [/c "colour"] command')
def do_button(self,argstr): def do_button(self, argstr):
def nextarg(rest): def nextarg(rest):
rest=rest.lstrip() rest = rest.lstrip()
if rest.startswith('"'): if rest.startswith('"'):
return rest[1:].split('"',1) return rest[1:].split('"',1)
else: else:
return rest.split(None,1) return rest.split(None, 1)
#try: #try:
num,argstr=nextarg(argstr) num, argstr = nextarg(argstr)
num=int(num) num = int(num)
title,argstr=nextarg(argstr) title, argstr = nextarg(argstr)
colour=None colour = None
try: try:
c1,c2=nextarg(argstr) c1, c2 = nextarg(argstr)
if c1=="/c": if c1 == "/c":
colour,argstr=nextarg(c2) colour, argstr = nextarg(c2)
except: except:
pass pass
command=argstr.strip() command = argstr.strip()
if num<0 or num>=64: if num<0 or num>=64:
print _("Custom button number should be between 0 and 63") print _("Custom button number should be between 0 and 63")
if self.webInterface: if self.webInterface:
...@@ -1006,44 +1006,44 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1006,44 +1006,44 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
return return
while num >= len(self.custombuttons): while num >= len(self.custombuttons):
self.custombuttons+=[None] self.custombuttons+=[None]
self.custombuttons[num]=[title,command] self.custombuttons[num]=[title, command]
if colour is not None: if colour is not None:
self.custombuttons[num]+=[colour] self.custombuttons[num]+=[colour]
if not self.processing_rc: if not self.processing_rc:
self.cbuttons_reload() self.cbuttons_reload()
#except Exception,x: #except Exception, x:
# print "Bad syntax for button definition, see 'help button'" # print "Bad syntax for button definition, see 'help button'"
# print x # print x
def cbutton_save(self,n,bdef,new_n=None): def cbutton_save(self, n, bdef, new_n = None):
if new_n is None: new_n=n if new_n is None: new_n = n
if bdef is None or bdef == "": if bdef is None or bdef == "":
self.save_in_rc(("button %d" % n),'') self.save_in_rc(("button %d" % n),'')
elif len(bdef)>2: elif len(bdef)>2:
colour=bdef[2] colour = bdef[2]
if type(colour) not in (str,unicode): if type(colour) not in (str, unicode):
#print type(colour),map(type,colour) #print type(colour),map(type, colour)
if type(colour)==tuple and tuple(map(type,colour))==(int,int,int): if type(colour) == tuple and tuple(map(type, colour)) == (int, int, int):
colour = map(lambda x:x%256,colour) colour = map(lambda x:x%256, colour)
colour = wx.Colour(*colour).GetAsString(wx.C2S_NAME|wx.C2S_HTML_SYNTAX) colour = wx.Colour(*colour).GetAsString(wx.C2S_NAME|wx.C2S_HTML_SYNTAX)
else: else:
colour = wx.Colour(colour).GetAsString(wx.C2S_NAME|wx.C2S_HTML_SYNTAX) colour = wx.Colour(colour).GetAsString(wx.C2S_NAME|wx.C2S_HTML_SYNTAX)
self.save_in_rc(("button %d" % n),'button %d "%s" /c "%s" %s' % (new_n,bdef[0],colour,bdef[1])) self.save_in_rc(("button %d" % n),'button %d "%s" /c "%s" %s' % (new_n, bdef[0],colour, bdef[1]))
else: else:
self.save_in_rc(("button %d" % n),'button %d "%s" %s' % (new_n,bdef[0],bdef[1])) self.save_in_rc(("button %d" % n),'button %d "%s" %s' % (new_n, bdef[0],bdef[1]))
def cbutton_edit(self,e,button=None): def cbutton_edit(self, e, button = None):
bedit=ButtonEdit(self) bedit = ButtonEdit(self)
if button is not None: if button is not None:
n = button.custombutton n = button.custombutton
bedit.name.SetValue(button.properties[0]) bedit.name.SetValue(button.properties[0])
bedit.command.SetValue(button.properties[1]) bedit.command.SetValue(button.properties[1])
if len(button.properties)>2: if len(button.properties)>2:
colour=button.properties[2] colour = button.properties[2]
if type(colour) not in (str,unicode): if type(colour) not in (str, unicode):
#print type(colour) #print type(colour)
if type(colour)==tuple and tuple(map(type,colour))==(int,int,int): if type(colour) == tuple and tuple(map(type, colour)) == (int, int, int):
colour = map(lambda x:x%256,colour) colour = map(lambda x:x%256, colour)
colour = wx.Colour(*colour).GetAsString(wx.C2S_NAME|wx.C2S_HTML_SYNTAX) colour = wx.Colour(*colour).GetAsString(wx.C2S_NAME|wx.C2S_HTML_SYNTAX)
else: else:
colour = wx.Colour(colour).GetAsString(wx.C2S_NAME|wx.C2S_HTML_SYNTAX) colour = wx.Colour(colour).GetAsString(wx.C2S_NAME|wx.C2S_HTML_SYNTAX)
...@@ -1052,61 +1052,61 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1052,61 +1052,61 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
n = len(self.custombuttons) n = len(self.custombuttons)
while n>0 and self.custombuttons[n-1] is None: while n>0 and self.custombuttons[n-1] is None:
n -= 1 n -= 1
if bedit.ShowModal()==wx.ID_OK: if bedit.ShowModal() == wx.ID_OK:
if n==len(self.custombuttons): if n == len(self.custombuttons):
self.custombuttons+=[None] self.custombuttons+=[None]
self.custombuttons[n]=[bedit.name.GetValue().strip(),bedit.command.GetValue().strip()] self.custombuttons[n]=[bedit.name.GetValue().strip(),bedit.command.GetValue().strip()]
if bedit.color.GetValue().strip()!="": if bedit.color.GetValue().strip()!="":
self.custombuttons[n]+=[bedit.color.GetValue()] self.custombuttons[n]+=[bedit.color.GetValue()]
self.cbutton_save(n,self.custombuttons[n]) self.cbutton_save(n, self.custombuttons[n])
bedit.Destroy() bedit.Destroy()
self.cbuttons_reload() self.cbuttons_reload()
def cbutton_remove(self,e,button): def cbutton_remove(self, e, button):
n = button.custombutton n = button.custombutton
self.custombuttons[n]=None self.custombuttons[n]=None
self.cbutton_save(n,None) self.cbutton_save(n, None)
#while len(self.custombuttons) and self.custombuttons[-1] is None: #while len(self.custombuttons) and self.custombuttons[-1] is None:
# del self.custombuttons[-1] # del self.custombuttons[-1]
wx.CallAfter(self.cbuttons_reload) wx.CallAfter(self.cbuttons_reload)
def cbutton_order(self,e,button,dir): def cbutton_order(self, e, button, dir):
n = button.custombutton n = button.custombutton
if dir<0: if dir<0:
n=n-1 n = n-1
if n+1 >= len(self.custombuttons): if n+1 >= len(self.custombuttons):
self.custombuttons+=[None] # pad self.custombuttons+=[None] # pad
# swap # swap
self.custombuttons[n],self.custombuttons[n+1] = self.custombuttons[n+1],self.custombuttons[n] self.custombuttons[n],self.custombuttons[n+1] = self.custombuttons[n+1],self.custombuttons[n]
self.cbutton_save(n,self.custombuttons[n]) self.cbutton_save(n, self.custombuttons[n])
self.cbutton_save(n+1,self.custombuttons[n+1]) self.cbutton_save(n+1, self.custombuttons[n+1])
#if self.custombuttons[-1] is None: #if self.custombuttons[-1] is None:
# del self.custombuttons[-1] # del self.custombuttons[-1]
self.cbuttons_reload() self.cbuttons_reload()
def editbutton(self,e): def editbutton(self, e):
if e.IsCommandEvent() or e.ButtonUp(wx.MOUSE_BTN_RIGHT): if e.IsCommandEvent() or e.ButtonUp(wx.MOUSE_BTN_RIGHT):
if e.IsCommandEvent(): if e.IsCommandEvent():
pos = (0,0) pos = (0, 0)
else: else:
pos = e.GetPosition() pos = e.GetPosition()
popupmenu = wx.Menu() popupmenu = wx.Menu()
obj = e.GetEventObject() obj = e.GetEventObject()
if hasattr(obj,"custombutton"): if hasattr(obj,"custombutton"):
item = popupmenu.Append(-1,_("Edit custom button '%s'") % e.GetEventObject().GetLabelText()) item = popupmenu.Append(-1, _("Edit custom button '%s'") % e.GetEventObject().GetLabelText())
self.Bind(wx.EVT_MENU,lambda e,button=e.GetEventObject():self.cbutton_edit(e,button),item) self.Bind(wx.EVT_MENU, lambda e, button = e.GetEventObject():self.cbutton_edit(e, button),item)
item = popupmenu.Append(-1,_("Move left <<")) item = popupmenu.Append(-1, _("Move left <<"))
self.Bind(wx.EVT_MENU,lambda e,button=e.GetEventObject():self.cbutton_order(e,button,-1),item) self.Bind(wx.EVT_MENU, lambda e, button = e.GetEventObject():self.cbutton_order(e, button,-1),item)
if obj.custombutton == 0: item.Enable(False) if obj.custombutton == 0: item.Enable(False)
item = popupmenu.Append(-1,_("Move right >>")) item = popupmenu.Append(-1, _("Move right >>"))
self.Bind(wx.EVT_MENU,lambda e,button=e.GetEventObject():self.cbutton_order(e,button,1),item) self.Bind(wx.EVT_MENU, lambda e, button = e.GetEventObject():self.cbutton_order(e, button, 1),item)
if obj.custombutton == 63: item.Enable(False) if obj.custombutton == 63: item.Enable(False)
pos = self.panel.ScreenToClient(e.GetEventObject().ClientToScreen(pos)) pos = self.panel.ScreenToClient(e.GetEventObject().ClientToScreen(pos))
item = popupmenu.Append(-1,_("Remove custom button '%s'") % e.GetEventObject().GetLabelText()) item = popupmenu.Append(-1, _("Remove custom button '%s'") % e.GetEventObject().GetLabelText())
self.Bind(wx.EVT_MENU,lambda e,button=e.GetEventObject():self.cbutton_remove(e,button),item) self.Bind(wx.EVT_MENU, lambda e, button = e.GetEventObject():self.cbutton_remove(e, button),item)
else: else:
item = popupmenu.Append(-1,_("Add custom button")) item = popupmenu.Append(-1, _("Add custom button"))
self.Bind(wx.EVT_MENU,self.cbutton_edit,item) self.Bind(wx.EVT_MENU, self.cbutton_edit, item)
self.panel.PopupMenu(popupmenu, pos) self.panel.PopupMenu(popupmenu, pos)
elif e.Dragging() and e.ButtonIsDown(wx.MOUSE_BTN_LEFT): elif e.Dragging() and e.ButtonIsDown(wx.MOUSE_BTN_LEFT):
obj = e.GetEventObject() obj = e.GetEventObject()
...@@ -1116,7 +1116,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1116,7 +1116,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
e.Skip() e.Skip()
return return
else: else:
dx,dy=self.dragpos[0]-scrpos[0],self.dragpos[1]-scrpos[1] dx, dy = self.dragpos[0]-scrpos[0],self.dragpos[1]-scrpos[1]
if dx*dx+dy*dy < 5*5: # threshold to detect dragging for jittery mice if dx*dx+dy*dy < 5*5: # threshold to detect dragging for jittery mice
e.Skip() e.Skip()
return return
...@@ -1124,25 +1124,25 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1124,25 +1124,25 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
# init dragging of the custom button # init dragging of the custom button
if hasattr(obj,"custombutton") and obj.properties is not None: if hasattr(obj,"custombutton") and obj.properties is not None:
#self.newbuttonbutton.SetLabel("") #self.newbuttonbutton.SetLabel("")
#self.newbuttonbutton.SetFont(wx.Font(10,wx.FONTFAMILY_DEFAULT,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_NORMAL)) #self.newbuttonbutton.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
#self.newbuttonbutton.SetForegroundColour("black") #self.newbuttonbutton.SetForegroundColour("black")
#self.newbuttonbutton.SetSize(obj.GetSize()) #self.newbuttonbutton.SetSize(obj.GetSize())
#if self.upperbottomsizer.GetItem(self.newbuttonbutton) is not None: #if self.upperbottomsizer.GetItem(self.newbuttonbutton) is not None:
# self.upperbottomsizer.SetItemMinSize(self.newbuttonbutton,obj.GetSize()) # self.upperbottomsizer.SetItemMinSize(self.newbuttonbutton, obj.GetSize())
# self.topsizer.Layout() # self.topsizer.Layout()
for b in self.custombuttonbuttons: for b in self.custombuttonbuttons:
#if b.IsFrozen(): b.Thaw() #if b.IsFrozen(): b.Thaw()
if b.properties is None: if b.properties is None:
b.Enable() b.Enable()
b.SetLabel("") b.SetLabel("")
b.SetFont(wx.Font(10,wx.FONTFAMILY_DEFAULT,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_NORMAL)) b.SetFont(wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
b.SetForegroundColour("black") b.SetForegroundColour("black")
b.SetSize(obj.GetSize()) b.SetSize(obj.GetSize())
if self.upperbottomsizer.GetItem(b) is not None: if self.upperbottomsizer.GetItem(b) is not None:
self.upperbottomsizer.SetItemMinSize(b,obj.GetSize()) self.upperbottomsizer.SetItemMinSize(b, obj.GetSize())
self.topsizer.Layout() self.topsizer.Layout()
# b.SetStyle(wx.ALIGN_CENTRE+wx.ST_NO_AUTORESIZE+wx.SIMPLE_BORDER) # b.SetStyle(wx.ALIGN_CENTRE+wx.ST_NO_AUTORESIZE+wx.SIMPLE_BORDER)
self.dragging = wx.Button(self.panel,-1,obj.GetLabel(),style=wx.BU_EXACTFIT) self.dragging = wx.Button(self.panel,-1, obj.GetLabel(),style = wx.BU_EXACTFIT)
self.dragging.SetBackgroundColour(obj.GetBackgroundColour()) self.dragging.SetBackgroundColour(obj.GetBackgroundColour())
self.dragging.SetForegroundColour(obj.GetForegroundColour()) self.dragging.SetForegroundColour(obj.GetForegroundColour())
self.dragging.sourcebutton = obj self.dragging.sourcebutton = obj
...@@ -1216,8 +1216,8 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1216,8 +1216,8 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
src_i = src.custombutton src_i = src.custombutton
dst_i = dst.custombutton dst_i = dst.custombutton
self.custombuttons[src_i],self.custombuttons[dst_i] = self.custombuttons[dst_i],self.custombuttons[src_i] self.custombuttons[src_i],self.custombuttons[dst_i] = self.custombuttons[dst_i],self.custombuttons[src_i]
self.cbutton_save(src_i,self.custombuttons[src_i]) self.cbutton_save(src_i, self.custombuttons[src_i])
self.cbutton_save(dst_i,self.custombuttons[dst_i]) self.cbutton_save(dst_i, self.custombuttons[dst_i])
while self.custombuttons[-1] is None: while self.custombuttons[-1] is None:
del self.custombuttons[-1] del self.custombuttons[-1]
wx.CallAfter(self.dragging.Destroy) wx.CallAfter(self.dragging.Destroy)
...@@ -1258,27 +1258,27 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1258,27 +1258,27 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
self.zb.repeatLast() self.zb.repeatLast()
self.xyb.repeatLast() self.xyb.repeatLast()
def procbutton(self,e): def procbutton(self, e):
try: try:
if hasattr(e.GetEventObject(),"custombutton"): if hasattr(e.GetEventObject(),"custombutton"):
if wx.GetKeyState(wx.WXK_CONTROL) or wx.GetKeyState(wx.WXK_ALT): if wx.GetKeyState(wx.WXK_CONTROL) or wx.GetKeyState(wx.WXK_ALT):
return self.editbutton(e) return self.editbutton(e)
self.cur_button=e.GetEventObject().custombutton self.cur_button = e.GetEventObject().custombutton
self.onecmd(e.GetEventObject().properties[1]) self.onecmd(e.GetEventObject().properties[1])
self.cur_button=None self.cur_button = None
except: except:
print _("event object missing") print _("event object missing")
if self.webInterface: if self.webInterface:
self.webInterface.AddLog("event object missing") self.webInterface.AddLog("event object missing")
self.cur_button=None self.cur_button = None
raise raise
def kill(self,e): def kill(self, e):
self.statuscheck = False self.statuscheck = False
if self.status_thread: if self.status_thread:
self.status_thread.join() self.status_thread.join()
self.status_thread = None self.status_thread = None
self.p.recvcb=None self.p.recvcb = None
self.p.disconnect() self.p.disconnect()
if hasattr(self,"feedrates_changed"): if hasattr(self,"feedrates_changed"):
self.save_in_rc("set xy_feedrate","set xy_feedrate %d" % self.settings.xy_feedrate) self.save_in_rc("set xy_feedrate","set xy_feedrate %d" % self.settings.xy_feedrate)
...@@ -1293,15 +1293,15 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1293,15 +1293,15 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
from printrun import webinterface from printrun import webinterface
webinterface.KillWebInterfaceThread() webinterface.KillWebInterfaceThread()
def do_monitor(self,l=""): def do_monitor(self, l = ""):
if l.strip()=="": if l.strip()=="":
self.monitorbox.SetValue(not self.monitorbox.GetValue()) self.monitorbox.SetValue(not self.monitorbox.GetValue())
elif l.strip()=="off": elif l.strip()=="off":
wx.CallAfter(self.monitorbox.SetValue,False) wx.CallAfter(self.monitorbox.SetValue, False)
else: else:
try: try:
self.monitor_interval=float(l) self.monitor_interval = float(l)
wx.CallAfter(self.monitorbox.SetValue,self.monitor_interval>0) wx.CallAfter(self.monitorbox.SetValue, self.monitor_interval>0)
except: except:
print _("Invalid period given.") print _("Invalid period given.")
if self.webInterface: if self.webInterface:
...@@ -1316,32 +1316,32 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1316,32 +1316,32 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
if self.webInterface: if self.webInterface:
self.webInterface.AddLog("Done monitoring.") self.webInterface.AddLog("Done monitoring.")
def setmonitor(self,e): def setmonitor(self, e):
self.monitor=self.monitorbox.GetValue() self.monitor = self.monitorbox.GetValue()
if self.monitor: if self.monitor:
wx.CallAfter(self.graph.StartPlotting,1000) wx.CallAfter(self.graph.StartPlotting, 1000)
else: else:
wx.CallAfter(self.graph.StopPlotting) wx.CallAfter(self.graph.StopPlotting)
def sendline(self,e): def sendline(self, e):
command=self.commandbox.GetValue() command = self.commandbox.GetValue()
if not len(command): if not len(command):
return return
wx.CallAfter(self.logbox.AppendText,">>>"+command+"\n") wx.CallAfter(self.logbox.AppendText,">>>"+command+"\n")
if self.webInterface: if self.webInterface:
self.webInterface.AppendLog(">>>"+command+"\n") self.webInterface.AppendLog(">>>"+command+"\n")
self.onecmd(str(command)) self.onecmd(str(command))
self.commandbox.SetSelection(0,len(command)) self.commandbox.SetSelection(0, len(command))
self.commandbox.history+=[command] self.commandbox.history+=[command]
self.commandbox.histindex=len(self.commandbox.history) self.commandbox.histindex = len(self.commandbox.history)
def clearOutput(self,e): def clearOutput(self, e):
self.logbox.Clear() self.logbox.Clear()
def statuschecker(self): def statuschecker(self):
while self.statuscheck: while self.statuscheck:
string = "" string = ""
wx.CallAfter(self.tempdisp.SetLabel,self.tempreport.strip().replace("ok ","")) wx.CallAfter(self.tempdisp.SetLabel, self.tempreport.strip().replace("ok ",""))
try: try:
#self.hottgauge.SetValue(parse_temperature_report(self.tempreport, "T:")) #self.hottgauge.SetValue(parse_temperature_report(self.tempreport, "T:"))
wx.CallAfter(self.graph.SetExtruder0Temperature, parse_temperature_report(self.tempreport, "T:")) wx.CallAfter(self.graph.SetExtruder0Temperature, parse_temperature_report(self.tempreport, "T:"))
...@@ -1384,88 +1384,88 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1384,88 +1384,88 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
wx.CallAfter(self.gviz.addgcode, gc, 1) wx.CallAfter(self.gviz.addgcode, gc, 1)
except: except:
break break
wx.CallAfter(self.status.SetStatusText,_("Not connected to printer.")) wx.CallAfter(self.status.SetStatusText, _("Not connected to printer."))
def capture(self, func, *args, **kwargs): def capture(self, func, *args, **kwargs):
stdout=sys.stdout stdout = sys.stdout
cout=None cout = None
try: try:
cout=self.cout cout = self.cout
except: except:
pass pass
if cout is None: if cout is None:
cout=cStringIO.StringIO() cout = cStringIO.StringIO()
sys.stdout=cout sys.stdout = cout
retval=None retval = None
try: try:
retval=func(*args,**kwargs) retval = func(*args,**kwargs)
except: except:
traceback.print_exc() traceback.print_exc()
sys.stdout=stdout sys.stdout = stdout
return retval return retval
def recvcb(self,l): def recvcb(self, l):
if "T:" in l: if "T:" in l:
self.tempreport=l self.tempreport = l
wx.CallAfter(self.tempdisp.SetLabel,self.tempreport.strip().replace("ok ","")) wx.CallAfter(self.tempdisp.SetLabel, self.tempreport.strip().replace("ok ",""))
try: try:
#self.hottgauge.SetValue(parse_temperature_report(self.tempreport, "T:")) #self.hottgauge.SetValue(parse_temperature_report(self.tempreport, "T:"))
wx.CallAfter(self.graph.SetExtruder0Temperature, parse_temperature_report(self.tempreport, "T:")) wx.CallAfter(self.graph.SetExtruder0Temperature, parse_temperature_report(self.tempreport, "T:"))
wx.CallAfter(self.graph.SetBedTemperature, parse_temperature_report(self.tempreport, "B:")) wx.CallAfter(self.graph.SetBedTemperature, parse_temperature_report(self.tempreport, "B:"))
except: except:
traceback.print_exc() traceback.print_exc()
tstring=l.rstrip() tstring = l.rstrip()
#print tstring #print tstring
if (tstring!="ok") and (tstring!="wait") and ("ok T:" not in tstring): if (tstring!="ok") and (tstring!="wait") and ("ok T:" not in tstring):
# print "*"+tstring+"*" # print "*"+tstring+"*"
# print "[" + time.strftime('%H:%M:%S',time.localtime(time.time())) + "] " + tstring # print "[" + time.strftime('%H:%M:%S',time.localtime(time.time())) + "] " + tstring
wx.CallAfter(self.logbox.AppendText,tstring+"\n") wx.CallAfter(self.logbox.AppendText, tstring+"\n")
for i in self.recvlisteners: for i in self.recvlisteners:
i(l) i(l)
def listfiles(self,line): def listfiles(self, line):
if "Begin file list" in line: if "Begin file list" in line:
self.listing=1 self.listing = 1
elif "End file list" in line: elif "End file list" in line:
self.listing=0 self.listing = 0
self.recvlisteners.remove(self.listfiles) self.recvlisteners.remove(self.listfiles)
wx.CallAfter(self.filesloaded) wx.CallAfter(self.filesloaded)
elif self.listing: elif self.listing:
self.sdfiles+=[line.replace("\n","").replace("\r","").lower()] self.sdfiles+=[line.replace("\n","").replace("\r","").lower()]
def waitforsdresponse(self,l): def waitforsdresponse(self, l):
if "file.open failed" in l: if "file.open failed" in l:
wx.CallAfter(self.status.SetStatusText,_("Opening file failed.")) wx.CallAfter(self.status.SetStatusText, _("Opening file failed."))
self.recvlisteners.remove(self.waitforsdresponse) self.recvlisteners.remove(self.waitforsdresponse)
return return
if "File opened" in l: if "File opened" in l:
wx.CallAfter(self.status.SetStatusText,l) wx.CallAfter(self.status.SetStatusText, l)
if "File selected" in l: if "File selected" in l:
wx.CallAfter(self.status.SetStatusText,_("Starting print")) wx.CallAfter(self.status.SetStatusText, _("Starting print"))
self.sdprinting=1 self.sdprinting = 1
self.p.send_now("M24") self.p.send_now("M24")
self.startcb() self.startcb()
return return
if "Done printing file" in l: if "Done printing file" in l:
wx.CallAfter(self.status.SetStatusText,l) wx.CallAfter(self.status.SetStatusText, l)
self.sdprinting=0 self.sdprinting = 0
self.recvlisteners.remove(self.waitforsdresponse) self.recvlisteners.remove(self.waitforsdresponse)
self.endcb() self.endcb()
return return
if "SD printing byte" in l: if "SD printing byte" in l:
#M27 handler #M27 handler
try: try:
resp=l.split() resp = l.split()
vals=resp[-1].split("/") vals = resp[-1].split("/")
self.percentdone=100.0*int(vals[0])/int(vals[1]) self.percentdone = 100.0*int(vals[0])/int(vals[1])
except: except:
pass pass
def filesloaded(self): def filesloaded(self):
dlg=wx.SingleChoiceDialog(self, _("Select the file to print"), _("Pick SD file"), self.sdfiles) dlg = wx.SingleChoiceDialog(self, _("Select the file to print"), _("Pick SD file"), self.sdfiles)
if(dlg.ShowModal()==wx.ID_OK): if(dlg.ShowModal() == wx.ID_OK):
target=dlg.GetStringSelection() target = dlg.GetStringSelection()
if len(target): if len(target):
self.recvlisteners+=[self.waitforsdresponse] self.recvlisteners+=[self.waitforsdresponse]
self.p.send_now("M23 "+target.lower()) self.p.send_now("M23 "+target.lower())
...@@ -1475,7 +1475,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1475,7 +1475,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
if not self.p.online: if not self.p.online:
self.sdfiles=[] self.sdfiles=[]
return return
self.listing=0 self.listing = 0
self.sdfiles=[] self.sdfiles=[]
self.recvlisteners+=[self.listfiles] self.recvlisteners+=[self.listfiles]
self.p.send_now("M21") self.p.send_now("M21")
...@@ -1490,75 +1490,75 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1490,75 +1490,75 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
self.webInterface.AddLog("Slicing: "+param) self.webInterface.AddLog("Slicing: "+param)
pararray=[i.replace("$s",self.filename).replace("$o",self.filename.replace(".stl","_export.gcode").replace(".STL","_export.gcode")).encode() for i in shlex.split(param.replace("\\","\\\\").encode())] pararray=[i.replace("$s",self.filename).replace("$o",self.filename.replace(".stl","_export.gcode").replace(".STL","_export.gcode")).encode() for i in shlex.split(param.replace("\\","\\\\").encode())]
#print pararray #print pararray
self.skeinp=subprocess.Popen(pararray,stderr=subprocess.STDOUT,stdout=subprocess.PIPE) self.skeinp = subprocess.Popen(pararray, stderr = subprocess.STDOUT, stdout = subprocess.PIPE)
while True: while True:
o = self.skeinp.stdout.read(1) o = self.skeinp.stdout.read(1)
if o == '' and self.skeinp.poll() != None: break if o == '' and self.skeinp.poll() != None: break
sys.stdout.write(o) sys.stdout.write(o)
self.skeinp.wait() self.skeinp.wait()
self.stopsf=1 self.stopsf = 1
except: except:
print _("Failed to execute slicing software: ") print _("Failed to execute slicing software: ")
if self.webInterface: if self.webInterface:
self.webInterface.AddLog("Failed to execute slicing software: ") self.webInterface.AddLog("Failed to execute slicing software: ")
self.stopsf=1 self.stopsf = 1
traceback.print_exc(file=sys.stdout) traceback.print_exc(file = sys.stdout)
def skein_monitor(self): def skein_monitor(self):
while(not self.stopsf): while(not self.stopsf):
try: try:
wx.CallAfter(self.status.SetStatusText,_("Slicing..."))#+self.cout.getvalue().split("\n")[-1]) wx.CallAfter(self.status.SetStatusText, _("Slicing..."))#+self.cout.getvalue().split("\n")[-1])
except: except:
pass pass
time.sleep(0.1) time.sleep(0.1)
fn=self.filename fn = self.filename
try: try:
self.filename=self.filename.replace(".stl","_export.gcode").replace(".STL","_export.gcode").replace(".obj","_export.gcode").replace(".OBJ","_export.gcode") self.filename = self.filename.replace(".stl","_export.gcode").replace(".STL","_export.gcode").replace(".obj","_export.gcode").replace(".OBJ","_export.gcode")
of=open(self.filename) of = open(self.filename)
self.f=[i.replace("\n","").replace("\r","") for i in of] self.f=[i.replace("\n","").replace("\r","") for i in of]
of.close() of.close()
if self.p.online: if self.p.online:
wx.CallAfter(self.printbtn.Enable) wx.CallAfter(self.printbtn.Enable)
wx.CallAfter(self.status.SetStatusText,_("Loaded ")+self.filename+_(", %d lines") % (len(self.f),)) wx.CallAfter(self.status.SetStatusText, _("Loaded ")+self.filename+_(", %d lines") % (len(self.f),))
wx.CallAfter(self.pausebtn.Disable) wx.CallAfter(self.pausebtn.Disable)
wx.CallAfter(self.printbtn.SetLabel,_("Print")) wx.CallAfter(self.printbtn.SetLabel, _("Print"))
threading.Thread(target=self.loadviz).start() threading.Thread(target = self.loadviz).start()
except: except:
self.filename=fn self.filename = fn
wx.CallAfter(self.loadbtn.SetLabel,_("Load File")) wx.CallAfter(self.loadbtn.SetLabel, _("Load File"))
self.skeining=0 self.skeining = 0
self.skeinp=None self.skeinp = None
def skein(self,filename): def skein(self, filename):
wx.CallAfter(self.loadbtn.SetLabel,_("Cancel")) wx.CallAfter(self.loadbtn.SetLabel, _("Cancel"))
print _("Slicing ") + filename print _("Slicing ") + filename
self.cout=StringIO.StringIO() self.cout = StringIO.StringIO()
self.filename=filename self.filename = filename
self.stopsf=0 self.stopsf = 0
self.skeining=1 self.skeining = 1
threading.Thread(target=self.skein_func).start() threading.Thread(target = self.skein_func).start()
threading.Thread(target=self.skein_monitor).start() threading.Thread(target = self.skein_monitor).start()
def loadfile(self,event,filename=None): def loadfile(self, event, filename = None):
if self.skeining and self.skeinp is not None: if self.skeining and self.skeinp is not None:
self.skeinp.terminate() self.skeinp.terminate()
return return
basedir=self.settings.last_file_path basedir = self.settings.last_file_path
if not os.path.exists(basedir): if not os.path.exists(basedir):
basedir = "." basedir = "."
try: try:
basedir=os.path.split(self.filename)[0] basedir = os.path.split(self.filename)[0]
except: except:
pass pass
dlg=wx.FileDialog(self,_("Open file to print"),basedir,style=wx.FD_OPEN|wx.FD_FILE_MUST_EXIST) dlg = wx.FileDialog(self, _("Open file to print"),basedir, style = wx.FD_OPEN|wx.FD_FILE_MUST_EXIST)
dlg.SetWildcard(_("OBJ, STL, and GCODE files (*.gcode;*.gco;*.g;*.stl;*.STL;*.obj;*.OBJ)|*.gcode;*.gco;*.g;*.stl;*.STL;*.obj;*.OBJ|All Files (*.*)|*.*")) dlg.SetWildcard(_("OBJ, STL, and GCODE files (*.gcode;*.gco;*.g;*.stl;*.STL;*.obj;*.OBJ)|*.gcode;*.gco;*.g;*.stl;*.STL;*.obj;*.OBJ|All Files (*.*)|*.*"))
if(filename is not None or dlg.ShowModal() == wx.ID_OK): if(filename is not None or dlg.ShowModal() == wx.ID_OK):
if filename is not None: if filename is not None:
name=filename name = filename
else: else:
name=dlg.GetPath() name = dlg.GetPath()
if not(os.path.exists(name)): if not(os.path.exists(name)):
self.status.SetStatusText(_("File not found!")) self.status.SetStatusText(_("File not found!"))
return return
...@@ -1570,8 +1570,8 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1570,8 +1570,8 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
elif name.lower().endswith(".obj"): elif name.lower().endswith(".obj"):
self.skein(name) self.skein(name)
else: else:
self.filename=name self.filename = name
of=open(self.filename) of = open(self.filename)
self.f=[i.replace("\n","").replace("\r","") for i in of] self.f=[i.replace("\n","").replace("\r","") for i in of]
of.close() of.close()
self.status.SetStatusText(_("Loaded %s, %d lines") % (name, len(self.f))) self.status.SetStatusText(_("Loaded %s, %d lines") % (name, len(self.f)))
...@@ -1581,10 +1581,10 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1581,10 +1581,10 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
wx.CallAfter(self.recoverbtn.Disable) wx.CallAfter(self.recoverbtn.Disable)
if self.p.online: if self.p.online:
wx.CallAfter(self.printbtn.Enable) wx.CallAfter(self.printbtn.Enable)
threading.Thread(target=self.loadviz).start() threading.Thread(target = self.loadviz).start()
def loadviz(self): def loadviz(self):
Xtot,Ytot,Ztot,Xmin,Xmax,Ymin,Ymax,Zmin,Zmax = pronsole.measurements(self.f) Xtot, Ytot, Ztot, Xmin, Xmax, Ymin, Ymax, Zmin, Zmax = pronsole.measurements(self.f)
print pronsole.totalelength(self.f), _("mm of filament used in this print\n") print pronsole.totalelength(self.f), _("mm of filament used in this print\n")
print _("the print goes from %f mm to %f mm in X\nand is %f mm wide\n") % (Xmin, Xmax, Xtot) print _("the print goes from %f mm to %f mm in X\nand is %f mm wide\n") % (Xmin, Xmax, Xtot)
if self.webInterface: if self.webInterface:
...@@ -1596,22 +1596,22 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1596,22 +1596,22 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
except: except:
pass pass
#import time #import time
#t0=time.time() #t0 = time.time()
self.gviz.clear() self.gviz.clear()
self.gwindow.p.clear() self.gwindow.p.clear()
self.gviz.addfile(self.f) self.gviz.addfile(self.f)
#print "generated 2d view in %f s"%(time.time()-t0) #print "generated 2d view in %f s"%(time.time()-t0)
#t0=time.time() #t0 = time.time()
self.gwindow.p.addfile(self.f) self.gwindow.p.addfile(self.f)
#print "generated 3d view in %f s"%(time.time()-t0) #print "generated 3d view in %f s"%(time.time()-t0)
self.gviz.showall=1 self.gviz.showall = 1
wx.CallAfter(self.gviz.Refresh) wx.CallAfter(self.gviz.Refresh)
def printfile(self,event): def printfile(self, event):
self.extra_print_time=0 self.extra_print_time = 0
if self.paused: if self.paused:
self.p.paused=0 self.p.paused = 0
self.paused=0 self.paused = 0
self.on_startprint() self.on_startprint()
if self.sdprinting: if self.sdprinting:
self.p.send_now("M26 S0") self.p.send_now("M26 S0")
...@@ -1622,7 +1622,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1622,7 +1622,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
wx.CallAfter(self.status.SetStatusText, _("No file loaded. Please use load first.")) wx.CallAfter(self.status.SetStatusText, _("No file loaded. Please use load first."))
return return
if not self.p.online: if not self.p.online:
wx.CallAfter(self.status.SetStatusText,_("Not connected to printer.")) wx.CallAfter(self.status.SetStatusText, _("Not connected to printer."))
return return
self.on_startprint() self.on_startprint()
self.p.startprint(self.f) self.p.startprint(self.f)
...@@ -1636,30 +1636,30 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1636,30 +1636,30 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
self.p.send_now("M29 ") self.p.send_now("M29 ")
wx.CallAfter(self.status.SetStatusText, _("File upload complete")) wx.CallAfter(self.status.SetStatusText, _("File upload complete"))
time.sleep(0.5) time.sleep(0.5)
self.p.clear=True self.p.clear = True
self.uploading=False self.uploading = False
def uploadtrigger(self,l): def uploadtrigger(self, l):
if "Writing to file" in l: if "Writing to file" in l:
self.uploading=True self.uploading = True
self.p.startprint(self.f) self.p.startprint(self.f)
self.p.endcb=self.endupload self.p.endcb = self.endupload
self.recvlisteners.remove(self.uploadtrigger) self.recvlisteners.remove(self.uploadtrigger)
elif "open failed, File" in l: elif "open failed, File" in l:
self.recvlisteners.remove(self.uploadtrigger) self.recvlisteners.remove(self.uploadtrigger)
def upload(self,event): def upload(self, event):
if not self.f or not len(self.f): if not self.f or not len(self.f):
return return
if not self.p.online: if not self.p.online:
return return
dlg=wx.TextEntryDialog(self, ("Enter a target filename in 8.3 format:"), _("Pick SD filename") ,dosify(self.filename)) dlg = wx.TextEntryDialog(self, ("Enter a target filename in 8.3 format:"), _("Pick SD filename") ,dosify(self.filename))
if dlg.ShowModal()==wx.ID_OK: if dlg.ShowModal() == wx.ID_OK:
self.p.send_now("M21") self.p.send_now("M21")
self.p.send_now("M28 "+str(dlg.GetValue())) self.p.send_now("M28 "+str(dlg.GetValue()))
self.recvlisteners+=[self.uploadtrigger] self.recvlisteners+=[self.uploadtrigger]
def pause(self,event): def pause(self, event):
print _("Paused.") print _("Paused.")
if not self.paused: if not self.paused:
if self.sdprinting: if self.sdprinting:
...@@ -1669,45 +1669,45 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1669,45 +1669,45 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
#print "Not printing, cannot pause." #print "Not printing, cannot pause."
return return
self.p.pause() self.p.pause()
self.paused=True self.paused = True
self.extra_print_time += int(time.time() - self.starttime) self.extra_print_time += int(time.time() - self.starttime)
wx.CallAfter(self.pausebtn.SetLabel, _("Resume")) wx.CallAfter(self.pausebtn.SetLabel, _("Resume"))
else: else:
self.paused=False self.paused = False
if self.sdprinting: if self.sdprinting:
self.p.send_now("M24") self.p.send_now("M24")
else: else:
self.p.resume() self.p.resume()
wx.CallAfter(self.pausebtn.SetLabel, _("Pause")) wx.CallAfter(self.pausebtn.SetLabel, _("Pause"))
def sdprintfile(self,event): def sdprintfile(self, event):
self.on_startprint() self.on_startprint()
threading.Thread(target=self.getfiles).start() threading.Thread(target = self.getfiles).start()
def connect(self,event): def connect(self, event):
print _("Connecting...") print _("Connecting...")
port=None port = None
try: try:
port=self.scanserial()[0] port = self.scanserial()[0]
except: except:
pass pass
if self.serialport.GetValue()!="": if self.serialport.GetValue()!="":
port=str(self.serialport.GetValue()) port = str(self.serialport.GetValue())
baud=115200 baud = 115200
try: try:
baud=int(self.baud.GetValue()) baud = int(self.baud.GetValue())
except: except:
pass pass
if self.paused: if self.paused:
self.p.paused=0 self.p.paused = 0
self.p.printing=0 self.p.printing = 0
wx.CallAfter(self.pausebtn.SetLabel, _("Pause")) wx.CallAfter(self.pausebtn.SetLabel, _("Pause"))
wx.CallAfter(self.printbtn.SetLabel, _("Print")) wx.CallAfter(self.printbtn.SetLabel, _("Print"))
self.paused=0 self.paused = 0
if self.sdprinting: if self.sdprinting:
self.p.send_now("M26 S0") self.p.send_now("M26 S0")
self.p.connect(port,baud) self.p.connect(port, baud)
self.statuscheck=True self.statuscheck = True
if port != self.settings.port: if port != self.settings.port:
self.set("port",port) self.set("port",port)
if baud != self.settings.baudrate: if baud != self.settings.baudrate:
...@@ -1720,7 +1720,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1720,7 +1720,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
def recover(self, event): def recover(self, event):
self.extra_print_time = 0 self.extra_print_time = 0
if not self.p.online: if not self.p.online:
wx.CallAfter(self.status.SetStatusText,_("Not connected to printer.")) wx.CallAfter(self.status.SetStatusText, _("Not connected to printer."))
return return
# Reset Z # Reset Z
self.p.send_now("G92 Z%f" % self.predisconnect_layer) self.p.send_now("G92 Z%f" % self.predisconnect_layer)
...@@ -1734,7 +1734,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1734,7 +1734,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
self.predisconnect_queueindex = self.p.queueindex self.predisconnect_queueindex = self.p.queueindex
self.predisconnect_layer = self.curlayer self.predisconnect_layer = self.curlayer
def disconnect(self,event): def disconnect(self, event):
print _("Disconnected.") print _("Disconnected.")
if self.p.printing or self.p.paused or self.paused: if self.p.printing or self.p.paused or self.paused:
self.store_predisconnect_state() self.store_predisconnect_state()
...@@ -1746,7 +1746,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1746,7 +1746,7 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
self.connectbtn.SetLabel(_("Connect")) self.connectbtn.SetLabel(_("Connect"))
self.connectbtn.SetToolTip(wx.ToolTip("Connect to the printer")) self.connectbtn.SetToolTip(wx.ToolTip("Connect to the printer"))
self.connectbtn.Bind(wx.EVT_BUTTON,self.connect) self.connectbtn.Bind(wx.EVT_BUTTON, self.connect)
wx.CallAfter(self.printbtn.Disable) wx.CallAfter(self.printbtn.Disable)
wx.CallAfter(self.pausebtn.Disable) wx.CallAfter(self.pausebtn.Disable)
...@@ -1759,29 +1759,29 @@ class PronterWindow(wx.Frame,pronsole.pronsole): ...@@ -1759,29 +1759,29 @@ class PronterWindow(wx.Frame,pronsole.pronsole):
wx.CallAfter(self.zb.disable) wx.CallAfter(self.zb.disable)
if self.paused: if self.paused:
self.p.paused=0 self.p.paused = 0
self.p.printing=0 self.p.printing = 0
wx.CallAfter(self.pausebtn.SetLabel, _("Pause")) wx.CallAfter(self.pausebtn.SetLabel, _("Pause"))
wx.CallAfter(self.printbtn.SetLabel, _("Print")) wx.CallAfter(self.printbtn.SetLabel, _("Print"))
self.paused=0 self.paused = 0
if self.sdprinting: if self.sdprinting:
self.p.send_now("M26 S0") self.p.send_now("M26 S0")
def reset(self,event): def reset(self, event):
print _("Reset.") print _("Reset.")
dlg=wx.MessageDialog(self, _("Are you sure you want to reset the printer?"), _("Reset?"), wx.YES|wx.NO) dlg = wx.MessageDialog(self, _("Are you sure you want to reset the printer?"), _("Reset?"), wx.YES|wx.NO)
if dlg.ShowModal()==wx.ID_YES: if dlg.ShowModal() == wx.ID_YES:
self.p.reset() self.p.reset()
self.sethotendgui(0) self.sethotendgui(0)
self.setbedgui(0) self.setbedgui(0)
self.p.printing=0 self.p.printing = 0
wx.CallAfter(self.printbtn.SetLabel, _("Print")) wx.CallAfter(self.printbtn.SetLabel, _("Print"))
if self.paused: if self.paused:
self.p.paused=0 self.p.paused = 0
wx.CallAfter(self.pausebtn.SetLabel, _("Pause")) wx.CallAfter(self.pausebtn.SetLabel, _("Pause"))
self.paused=0 self.paused = 0
def get_build_dimensions(self,bdim): def get_build_dimensions(self, bdim):
import re import re
# a string containing up to six numbers delimited by almost anything # a string containing up to six numbers delimited by almost anything
# first 0-3 numbers specify the build volume, no sign, always positive # first 0-3 numbers specify the build volume, no sign, always positive
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment