diff --git a/plater.py b/plater.py
index c6f3ba4..aa3d82e 100755
--- a/plater.py
+++ b/plater.py
@@ -1,17 +1,17 @@
#!/usr/bin/env python
# This file is part of the Printrun suite.
-#
+#
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
-#
+#
# Printrun is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
-#
+#
# You should have received a copy of the GNU General Public License
# along with Printrun. If not, see .
@@ -336,25 +336,25 @@ class stlwin(wx.Frame):
def center(self, event):
i = self.l.GetSelection()
if i != -1:
- m = self.models[self.l.GetString(i)]
- m.offsets = [100, 100, m.offsets[2]]
- self.Refresh()
+ m = self.models[self.l.GetString(i)]
+ m.offsets = [100, 100, m.offsets[2]]
+ self.Refresh()
def snap(self, event):
i = self.l.GetSelection()
if i != -1:
- m = self.models[self.l.GetString(i)]
- m.offsets[2] = -1.0 * min(m.facetsminz)[0]
- #print m.offsets[2]
- self.Refresh()
+ m = self.models[self.l.GetString(i)]
+ m.offsets[2] = -1.0 * min(m.facetsminz)[0]
+ #print m.offsets[2]
+ self.Refresh()
def delete(self, event):
i = self.l.GetSelection()
if i != -1:
- del self.models[self.l.GetString(i)]
- self.l.Delete(i)
- self.l.Select(self.l.GetCount() - 1)
- self.Refresh()
+ del self.models[self.l.GetString(i)]
+ self.l.Delete(i)
+ self.l.Select(self.l.GetCount() - 1)
+ self.Refresh()
def done(self, event, cb):
try:
diff --git a/printcore.py b/printcore.py
index d7c5ac2..93413ec 100755
--- a/printcore.py
+++ b/printcore.py
@@ -1,17 +1,17 @@
#!/usr/bin/env python
# This file is part of the Printrun suite.
-#
+#
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
-#
+#
# Printrun is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
-#
+#
# You should have received a copy of the GNU General Public License
# along with Printrun. If not, see .
@@ -45,7 +45,7 @@ class printcore():
self.clear = 0 #clear to send, enabled after responses
self.online = False #The printer has responded to the initial command and is active
self.printing = False #is a print currently running, true if printing, false if paused
- self.mainqueue = []
+ self.mainqueue = []
self.priqueue = []
self.queueindex = 0
self.lineno = 0
@@ -69,7 +69,7 @@ class printcore():
self.print_thread = None
if port is not None and baud is not None:
self.connect(port, baud)
-
+
def disconnect(self):
"""Disconnects from printer and pauses the print
"""
@@ -82,7 +82,7 @@ class printcore():
self.printer = None
self.online = False
self.printing = False
-
+
def connect(self,port=None,baud=None):
"""Set port and baudrate if given, then connect to printer
"""
@@ -98,7 +98,7 @@ class printcore():
self.stop_read_thread = False
self.read_thread = Thread(target=self._listen)
self.read_thread.start()
-
+
def reset(self):
"""Reset the printer
"""
@@ -106,7 +106,7 @@ class printcore():
self.printer.setDTR(1)
time.sleep(0.2)
self.printer.setDTR(0)
-
+
def _readline(self):
try:
line = self.printer.readline()
@@ -164,11 +164,11 @@ class printcore():
self.clear = True
if line.startswith('ok') and "T:" in line and self.tempcb:
#callback for temp, status, whatever
- try: self.tempcb(line)
- except: pass
+ try: self.tempcb(line)
+ except: pass
elif line.startswith('Error'):
if self.errorcb:
- #callback for errors
+ #callback for errors
try: self.errorcb(line)
except: pass
if line.lower().startswith("resend") or line.startswith("rs"):
@@ -181,10 +181,10 @@ class printcore():
self.resendfrom = toresend
self.clear = True
self.clear = True
-
+
def _checksum(self, command):
return reduce(lambda x,y:x^y, map(ord, command))
-
+
def startprint(self, data, startindex = 0):
"""Start a print, data is an array of gcode commands.
returns True on success, False if already printing.
@@ -205,7 +205,7 @@ class printcore():
self.print_thread = Thread(target = self._print)
self.print_thread.start()
return True
-
+
def pause(self):
"""Pauses the print, saving the current position.
"""
@@ -213,7 +213,7 @@ class printcore():
self.printing = False
self.print_thread.join()
self.print_thread = None
-
+
def resume(self):
"""Resumes a paused print.
"""
@@ -221,11 +221,11 @@ class printcore():
self.printing = True
self.print_thread = Thread(target = self._print)
self.print_thread.start()
-
+
def send(self, command, wait = 0):
"""Adds a command to the checksummed main command queue if printing, or sends the command immediately if not printing
"""
-
+
if self.online:
if self.printing:
self.mainqueue.append(command)
@@ -243,7 +243,7 @@ class printcore():
wait -= 1
else:
print "Not connected to printer."
-
+
def send_now(self, command, wait = 0):
"""Sends a command to the printer ahead of the command queue, without a checksum
"""
@@ -263,7 +263,7 @@ class printcore():
wait -= 1
else:
print "Not connected to printer."
-
+
def _print(self):
if self.startcb:
#callback for printing started
@@ -278,7 +278,7 @@ class printcore():
#callback for printing done
try: self.endcb()
except: pass
-
+
def _sendnext(self):
if not self.printer:
return
@@ -313,7 +313,7 @@ class printcore():
self.queueindex = 0
self.lineno = 0
self._send("M110", -1, True)
-
+
def _send(self, command, lineno = 0, calcchecksum = False):
if calcchecksum:
prefix = "N" + str(lineno) + " " + command
diff --git a/printrun/SkeinforgeQuickEditDialog.py b/printrun/SkeinforgeQuickEditDialog.py
index 90a9f92..0135ffa 100644
--- a/printrun/SkeinforgeQuickEditDialog.py
+++ b/printrun/SkeinforgeQuickEditDialog.py
@@ -16,13 +16,13 @@ class SkeinforgeQuickEditDialog(wx.Dialog):
self.cancelButton = wx.Button(self, wx.ID_CANCEL, "")
self.Bind(wx.EVT_BUTTON, self.OnExit, self.cancelButton)
self.Bind(wx.EVT_BUTTON, self.OnSave, self.okButton)
-
+
"""
The following list determines which settings are shown.
The dictionary key is the plugin name and the value is a list of setting names as found in the corresponding .csv file for that plugin.
-
+
NOTE: Skeinforge is tightly integrated with Tkinter and there appears to be a dependency which stops radio-button values from being saved.
- Perhaps this can be solved, but at the moment this dialog cannot modify radio button values. One will have to use the main Skeinforge application.
+ Perhaps this can be solved, but at the moment this dialog cannot modify radio button values. One will have to use the main Skeinforge application.
"""
self.moduleSettingsMap = {
'dimension':['Filament Diameter (mm):','Retraction Distance (millimeters):', 'Retraction Distance (millimeters):','Extruder Retraction Speed (mm/s):'],
@@ -34,28 +34,28 @@ class SkeinforgeQuickEditDialog(wx.Dialog):
'raft':['First Layer Main Feedrate (mm/s):','First Layer Perimeter Feedrate (mm/s):','First Layer Flow Rate Infill(scaler):','First Layer Flow Rate Perimeter(scaler):',],
'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.settingsSizer = self.getProfileSettings()
self.scrollbarPanel.SetSizer(self.settingsSizer)
- self.__set_properties()
- self.__do_layout()
+ self.__set_properties()
+ self.__do_layout()
self.Show()
-
+
def __set_properties(self):
self.profileName = skeinforge_profile.getProfileName(skeinforge_profile.getCraftTypeName())
self.SetTitle("Skeinforge Quick Edit Profile: " + self.profileName)
-
- # For some reason the dialog size is not consistent between Windows and Linux - this is a hack to get it working
+
+ # For some reason the dialog size is not consistent between Windows and Linux - this is a hack to get it working
if (os.name == 'nt'):
self.SetMinSize(wx.DLG_SZE(self, (465, 370)))
else:
self.SetSize(wx.DLG_SZE(self, (465, 325)))
-
+
self.SetPosition((0, 0))
self.scrollbarPanel.SetScrollRate(10, 10)
-
+
def __do_layout(self):
mainSizer = wx.BoxSizer(wx.VERTICAL)
actionsSizer = wx.BoxSizer(wx.HORIZONTAL)
@@ -65,34 +65,34 @@ class SkeinforgeQuickEditDialog(wx.Dialog):
mainSizer.Add(actionsSizer, 0, wx.ALIGN_RIGHT | wx.ALL, 5)
self.SetSizer(mainSizer)
self.Layout()
-
+
def getProfileSettings(self):
settingsSizer = wx.GridBagSizer(hgap=2, vgap=1)
settingsRow = 0
-
+
for craftName in sorted(self.moduleSettingsMap.keys()):
-
+
craftStaticBox = wx.StaticBox(self.scrollbarPanel, -1, craftName.capitalize())
craftStaticBoxSizer = wx.StaticBoxSizer(craftStaticBox, wx.VERTICAL)
-
+
# For some reason the dialog size is not consistent between Windows and Linux - this is a hack to get it working
if (os.name == 'nt'):
craftStaticBoxSizer.SetMinSize((320, -1))
- else:
+ else:
craftStaticBoxSizer.SetMinSize((450, -1))
pluginModule = archive.getModuleWithPath(os.path.join(skeinforge_craft.getPluginsDirectoryPath(), craftName))
repo = pluginModule.getNewRepository()
-
+
for setting in settings.getReadRepository(repo).preferences:
if setting.name in self.moduleSettingsMap[craftName]:
-
+
settingSizer = wx.GridBagSizer(hgap=2, vgap=2)
settingSizer.AddGrowableCol(0)
settingRow = 0
settingLabel = wx.StaticText(self.scrollbarPanel, -1, setting.name)
settingLabel.Wrap(400)
settingSizer.Add(settingLabel, pos=(settingRow, 0))
-
+
if (isinstance(setting.value, bool)):
checkbox = wx.CheckBox(self.scrollbarPanel)
checkbox.SetName(craftName + '.' + setting.name)
@@ -103,7 +103,7 @@ class SkeinforgeQuickEditDialog(wx.Dialog):
textCtrl = wx.TextCtrl(self.scrollbarPanel, value=str(setting.value), size=(50, -1))
textCtrl.SetName(craftName + '.' + setting.name)
settingSizer.Add(textCtrl, pos=(settingRow, 1))
-
+
craftStaticBoxSizer.Add(settingSizer, 1, wx.EXPAND, 0)
settingRow += 1
col = settingsRow % 2
@@ -114,7 +114,7 @@ class SkeinforgeQuickEditDialog(wx.Dialog):
def OnExit(self, e):
self.Destroy()
-
+
def OnSave(self, e):
for x in self.scrollbarPanel.GetChildren():
if (isinstance(x, (wx.CheckBox, wx.TextCtrl))):
diff --git a/printrun/bmpDisplay.py b/printrun/bmpDisplay.py
index fffa2f2..25415aa 100644
--- a/printrun/bmpDisplay.py
+++ b/printrun/bmpDisplay.py
@@ -13,7 +13,7 @@ class MyFrame(wx.Frame):
def __init__(self, parent, mysize):
wx.Frame.__init__(self, parent, wx.ID_ANY, size=mysize)
self.SetBackgroundColour('black')
-
+
# milliseconds per frame
self.delay = 60
# number of loops
@@ -41,7 +41,7 @@ class MyFrame(wx.Frame):
self.image_list = []
for image_file in file_list:
self.image_list.append(wx.Bitmap(image_file))
-
+
# bind the panel to the paint event
wx.EVT_PAINT(self, self.onPaint)
@@ -73,4 +73,4 @@ width = 800
frameoffset = 35
height = 600 + frameoffset
MyFrame(None, (width, height)).Show()
-app.MainLoop()
\ No newline at end of file
+app.MainLoop()
diff --git a/printrun/bufferedcanvas.py b/printrun/bufferedcanvas.py
index 5e0868e..af8602f 100644
--- a/printrun/bufferedcanvas.py
+++ b/printrun/bufferedcanvas.py
@@ -23,9 +23,9 @@ modify it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
-As a special exception, the copyright holders of this library
+As a special exception, the copyright holders of this library
hereby recind Section 3 of the GNU Lesser General Public License. This
-means that you MAY NOT apply the terms of the ordinary GNU General
+means that you MAY NOT apply the terms of the ordinary GNU General
Public License instead of this License to any given copy of the
Library. This has been done to prevent users of the Library from being
denied access or the ability to use future improvements.
@@ -94,7 +94,7 @@ class BufferedCanvas(wx.Panel):
Causes the canvas to be updated.
"""
self.Refresh()
-
+
def getWidthHeight(self):
width,height = self.GetClientSizeTuple()
if width == 0:
diff --git a/printrun/calibrateextruder.py b/printrun/calibrateextruder.py
index 8808324..71025b3 100644
--- a/printrun/calibrateextruder.py
+++ b/printrun/calibrateextruder.py
@@ -2,150 +2,150 @@
#Interactive RepRap e axis calibration program
#(C) Nathan Zadoks 2011
#Licensed under CC-BY-SA or GPLv2 and higher - Pick your poison.
-s=300 #Extrusion speed (mm/min)
-n=100 #Default length to extrude
-m= 0 #User-entered measured extrusion length
-k=300 #Default amount of steps per mm
-port='/dev/ttyUSB0' #Default serial port to connect to printer
-temp=210 #Default extrusion temperature
+s=300 #Extrusion speed (mm/min)
+n=100 #Default length to extrude
+m= 0 #User-entered measured extrusion length
+k=300 #Default amount of steps per mm
+port='/dev/ttyUSB0' #Default serial port to connect to printer
+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
try:
- from printdummy import printcore
+ from printdummy import printcore
except ImportError:
- from printcore import printcore
+ from printcore import printcore
import time,getopt,sys,os
def float_input(prompt=''):
- import sys
- f=None
- while f==None:
- s=raw_input(prompt)
- try:
- f=float(s)
- except ValueError:
- sys.stderr.write("Not a valid floating-point number.\n")
- sys.stderr.flush()
- return f
+ import sys
+ f=None
+ while f==None:
+ s=raw_input(prompt)
+ try:
+ f=float(s)
+ except ValueError:
+ sys.stderr.write("Not a valid floating-point number.\n")
+ sys.stderr.flush()
+ return f
def wait(t,m=''):
- import time,sys
- sys.stdout.write(m+'['+(' '*t)+']\r'+m+'[')
- sys.stdout.flush()
- for i in range(t):
- for s in ['|\b','/\b','-\b','\\\b','|']:
- sys.stdout.write(s)
- sys.stdout.flush()
- time.sleep(1.0/5)
- print
+ import time,sys
+ sys.stdout.write(m+'['+(' '*t)+']\r'+m+'[')
+ sys.stdout.flush()
+ for i in range(t):
+ for s in ['|\b','/\b','-\b','\\\b','|']:
+ sys.stdout.write(s)
+ sys.stdout.flush()
+ time.sleep(1.0/5)
+ print
def w(s):
- sys.stdout.write(s)
- sys.stdout.flush()
+ sys.stdout.write(s)
+ sys.stdout.flush()
def heatup(p,temp,s=0):
- curtemp=gettemp(p)
- p.send_now('M109 S%03d'%temp)
- p.temp=0
- if not s: w("Heating extruder up..")
- f=False
- while curtemp<=(temp-1):
- p.send_now('M105')
- time.sleep(0.5)
- if not f:
- time.sleep(1.5)
- f=True
- curtemp=gettemp(p)
- if curtemp: w(u"\rHeating extruder up.. %3d \xb0C"%curtemp)
- if s: print
- else: print "\nReady."
+ curtemp=gettemp(p)
+ p.send_now('M109 S%03d'%temp)
+ p.temp=0
+ if not s: w("Heating extruder up..")
+ f=False
+ while curtemp<=(temp-1):
+ p.send_now('M105')
+ time.sleep(0.5)
+ if not f:
+ time.sleep(1.5)
+ f=True
+ curtemp=gettemp(p)
+ if curtemp: w(u"\rHeating extruder up.. %3d \xb0C"%curtemp)
+ if s: print
+ else: print "\nReady."
def gettemp(p):
- try: p.logl
- except: setattr(p,'logl',0)
- try: p.temp
- except: setattr(p,'temp',0)
- for n in range(p.logl,len(p.log)):
- line=p.log[n]
- if 'T:' in line:
- try:
- setattr(p,'temp',int(line.split('T:')[1].split()[0]))
- except: print line
- p.logl=len(p.log)
- return p.temp
+ try: p.logl
+ except: setattr(p,'logl',0)
+ try: p.temp
+ except: setattr(p,'temp',0)
+ for n in range(p.logl,len(p.log)):
+ line=p.log[n]
+ if 'T:' in line:
+ try:
+ setattr(p,'temp',int(line.split('T:')[1].split()[0]))
+ except: print line
+ p.logl=len(p.log)
+ return p.temp
if not os.path.exists(port):
- port=0
+ port=0
#Parse options
help=u"""
%s [ -l DISTANCE ] [ -s STEPS ] [ -t TEMP ] [ -p PORT ]
- -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)
- -t --temp Extrusion temperature in degrees Celsius (default: %d \xb0C, max %d \xb0C)
- -p --port Serial port the printer is connected to (default: %s)
- -h --help This cruft.
+ -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)
+ -t --temp Extrusion temperature in degrees Celsius (default: %d \xb0C, max %d \xb0C)
+ -p --port Serial port the printer is connected to (default: %s)
+ -h --help This cruft.
"""[1:-1].encode('utf-8')%(sys.argv[0],n,k,temp,tempmax,port if port else 'auto')
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:
- print str(err)
- print help
- sys.exit(2)
+ print str(err)
+ print help
+ sys.exit(2)
for o,a in opts:
- if o in ('-h','--help'):
- print help
- sys.exit()
- elif o in ('-l','--length'):
- n=float(a)
- elif o in ('-s','--steps'):
- k=int(a)
- elif o in ('-t','--temp'):
- temp=int(a)
- if temp>=tempmax:
- print (u'%d \xb0C? Are you insane?'.encode('utf-8')%temp)+(" That's over nine thousand!" if temp>9000 else '')
- sys.exit(255)
- elif o in ('-p','--port'):
- port=a
+ if o in ('-h','--help'):
+ print help
+ sys.exit()
+ elif o in ('-l','--length'):
+ n=float(a)
+ elif o in ('-s','--steps'):
+ k=int(a)
+ elif o in ('-t','--temp'):
+ temp=int(a)
+ if temp>=tempmax:
+ print (u'%d \xb0C? Are you insane?'.encode('utf-8')%temp)+(" That's over nine thousand!" if temp>9000 else '')
+ sys.exit(255)
+ elif o in ('-p','--port'):
+ port=a
#Show initial parameters
print "Initial parameters"
print "Steps per mm: %3d steps"%k
print "Length extruded: %3d mm"%n
-print
+print
print "Serial port: %s"%(port if port else 'auto')
p=None
try:
- #Connect to printer
- w("Connecting to printer..")
- try:
- p=printcore(port,115200)
- except:
- print 'Error.'
- raise
- while not p.online:
- time.sleep(1)
- w('.')
- print " connected."
-
- heatup(p,temp)
-
- #Calibration loop
- while n!=m:
- heatup(p,temp,True)
- p.send_now("G92 E0") #Reset e axis
- p.send_now("G1 E%d F%d"%(n,s)) #Extrude length of filament
- wait(t,'Extruding.. ')
- m=float_input("How many millimeters of filament were extruded? ")
- if m==0: continue
- if n!=m:
- k=(n/m)*k
- p.send_now("M92 E%d"%int(round(k))) #Set new step count
- print "Steps per mm: %3d steps"%k #Tell user
- print 'Calibration completed.' #Yay!
+ #Connect to printer
+ w("Connecting to printer..")
+ try:
+ p=printcore(port,115200)
+ except:
+ print 'Error.'
+ raise
+ while not p.online:
+ time.sleep(1)
+ w('.')
+ print " connected."
+
+ heatup(p,temp)
+
+ #Calibration loop
+ while n!=m:
+ heatup(p,temp,True)
+ p.send_now("G92 E0") #Reset e axis
+ p.send_now("G1 E%d F%d"%(n,s)) #Extrude length of filament
+ wait(t,'Extruding.. ')
+ m=float_input("How many millimeters of filament were extruded? ")
+ if m==0: continue
+ if n!=m:
+ k=(n/m)*k
+ p.send_now("M92 E%d"%int(round(k))) #Set new step count
+ print "Steps per mm: %3d steps"%k #Tell user
+ print 'Calibration completed.' #Yay!
except KeyboardInterrupt:
- pass
+ pass
finally:
- if p: p.disconnect()
+ if p: p.disconnect()
diff --git a/printrun/graph.py b/printrun/graph.py
index 28ab2a5..4e6c885 100644
--- a/printrun/graph.py
+++ b/printrun/graph.py
@@ -263,5 +263,3 @@ class Graph(BufferedCanvas):
self.drawextruder0temp(dc, gc)
self.drawextruder1targettemp(dc, gc)
self.drawextruder1temp(dc, gc)
-
-
diff --git a/printrun/gviz.py b/printrun/gviz.py
index 32f6198..3310a72 100755
--- a/printrun/gviz.py
+++ b/printrun/gviz.py
@@ -1,15 +1,15 @@
# This file is part of the Printrun suite.
-#
+#
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
-#
+#
# Printrun is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
-#
+#
# You should have received a copy of the GNU General Public License
# along with Printrun. If not, see .
import wx,time
@@ -20,9 +20,9 @@ ID_ABOUT = 101
ID_EXIT = 110
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):
- 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)
-
+
vbox = wx.BoxSizer(wx.VERTICAL)
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 [+]', '')
@@ -42,8 +42,8 @@ class window(wx.Frame):
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, lambda x:self.p.inject(), id=5)
-
-
+
+
self.CreateStatusBar(1);
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))
@@ -51,19 +51,19 @@ class window(wx.Frame):
#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.bs=wx.Button(self.p, -1, "Inject", pos=(85, 103), size=(50, 20))
-
+
#self.bu.SetToolTip(wx.ToolTip("Move up one layer"))
#self.bd.SetToolTip(wx.ToolTip("Move down one layer"))
#self.bi.SetToolTip(wx.ToolTip("Zoom view in"))
#self.bo.SetToolTip(wx.ToolTip("Zoom view out"))
#self.bs.SetToolTip(wx.ToolTip("Insert Code at start of this layer"))
-
+
#self.bu.Bind(wx.EVT_BUTTON,lambda x:self.p.layerup())
#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.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())
-
+
s=time.time()
#print time.time()-s
self.initpos=[0,0]
@@ -77,12 +77,12 @@ class window(wx.Frame):
self.Bind(wx.EVT_MOUSEWHEEL,self.zoom)
self.p.Bind(wx.EVT_MOUSE_EVENTS,self.mouse)
self.Bind(wx.EVT_MOUSE_EVENTS,self.mouse)
-
+
def resetview(self,event):
self.p.translate=[0.0,0.0]
self.p.scale=self.p.basescale
self.p.zoom(0,0,1.0)
-
+
def mouse(self,event):
if event.ButtonUp(wx.MOUSE_BTN_LEFT):
if(self.initpos is not None):
@@ -97,14 +97,14 @@ class window(wx.Frame):
self.basetrans[1]+(e[1]-self.initpos[1]) ]
self.p.repaint()
self.p.Refresh()
-
+
else:
event.Skip()
-
+
def key(self, event):
# Keycode definitions
kup=[85, 315] # Up keys
- kdo=[68, 317] # Down Keys
+ kdo=[68, 317] # Down Keys
kzi=[388, 316, 61] # Zoom In Keys
kzo=[390, 314, 45] # Zoom Out Keys
x=event.GetKeyCode()
@@ -118,7 +118,7 @@ class window(wx.Frame):
#else:
# if x==wx.WXK_UP:
# self.p.layerup()
- # if x==wx.WXK_DOWN:
+ # if x==wx.WXK_DOWN:
# self.p.layerdown()
if x in kup:
self.p.layerup()
@@ -128,7 +128,7 @@ class window(wx.Frame):
self.p.zoom(cx,cy,1.2)
if x in kzo:
self.p.zoom(cx, cy, 1/1.2)
-
+
#print p.lines.keys()
def zoom(self, event):
z=event.GetWheelRotation()
@@ -138,7 +138,7 @@ class window(wx.Frame):
else:
if z > 0: self.p.zoom(event.GetX(),event.GetY(),1.2)
elif z < 0: self.p.zoom(event.GetX(),event.GetY(),1/1.2)
-
+
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):
wx.Panel.__init__(self,parent,-1,size=(size[0],size[1]))
@@ -172,12 +172,12 @@ class gviz(wx.Panel):
self.hilightarcs=[]
self.dirty=1
self.blitmap=wx.EmptyBitmap(self.GetClientSize()[0],self.GetClientSize()[1],-1)
-
+
def inject(self):
#import pdb; pdb.set_trace()
print"Inject code here..."
print "Layer "+str(self.layerindex +1)+" - Z = "+str(self.layers[self.layerindex])+" mm"
-
+
def clear(self):
self.lastpos=[0,0,0,0,0,0,0]
self.lines={}
@@ -190,7 +190,7 @@ class gviz(wx.Panel):
self.layerindex=0
self.showall=0
self.dirty=1
- #self.repaint()
+ #self.repaint()
def layerup(self):
if(self.layerindex+10):
- self.layerindex-=1
+ self.layerindex-=1
# Display layer info on statusbar (Jezmy)
self.parent.SetStatusText("Layer "+str(self.layerindex + 1)+" - Going Down - Z = "+str(self.layers[self.layerindex])+ " mm",0)
self.repaint()
self.Refresh()
-
+
def setlayer(self,layer):
try:
self.layerindex=self.layers.index(layer)
@@ -215,17 +215,17 @@ class gviz(wx.Panel):
self.showall=0
except:
pass
-
+
def resize(self,event):
size=self.GetClientSize()
newsize=min(float(size[0])/self.size[0],float(size[1])/self.size[1])
self.size=self.GetClientSize()
wx.CallAfter(self.zoom,0,0,newsize)
-
+
def zoom(self,x,y,factor):
self.scale = [s * factor for s in self.scale]
-
+
self.translate = [ x - (x-self.translate[0]) * factor,
y - (y-self.translate[1]) * factor]
penwidth = max(1.0,self.filament_width*((self.scale[0]+self.scale[1])/2.0))
@@ -234,8 +234,8 @@ class gviz(wx.Panel):
#self.dirty=1
self.repaint()
self.Refresh()
-
-
+
+
def repaint(self):
self.blitmap=wx.EmptyBitmap(self.GetClientSize()[0],self.GetClientSize()[1],-1)
dc=wx.MemoryDC()
@@ -257,7 +257,7 @@ class gviz(wx.Panel):
dc.SetBrush(wx.Brush((0,255,0)))
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)
-
+
def _drawlines(lines,pens):
def _scaler(x):
return (self.scale[0]*x[0]+self.translate[0],
@@ -266,7 +266,7 @@ class gviz(wx.Panel):
self.scale[1]*x[3]+self.translate[1],)
scaled_lines = map(_scaler,lines)
dc.DrawLineList(scaled_lines, pens)
-
+
def _drawarcs(arcs,pens):
def _scaler(x):
return (self.scale[0]*x[0]+self.translate[0],
@@ -280,7 +280,7 @@ class gviz(wx.Panel):
dc.SetPen(pens[i] if type(pens).__name__ == 'list' else pens)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.DrawArc(*scaled_arcs[i])
-
+
if self.showall:
l=[]
for i in self.layers:
@@ -295,12 +295,12 @@ class gviz(wx.Panel):
_drawarcs(self.arcs[self.layers[layer_i]], self.fades[self.layerindex-layer_i-1])
_drawlines(self.lines[self.layers[self.layerindex]], self.pens[self.layers[self.layerindex]])
_drawarcs(self.arcs[self.layers[self.layerindex]], self.arcpens[self.layers[self.layerindex]])
-
+
_drawlines(self.hilight, self.hlpen)
_drawarcs(self.hilightarcs, self.hlpen)
-
+
dc.SelectObject(wx.NullBitmap)
-
+
def paint(self,event):
dc=wx.PaintDC(self)
if(self.dirty):
@@ -309,12 +309,12 @@ class gviz(wx.Panel):
sz=self.GetClientSize()
dc.DrawBitmap(self.blitmap,0,0)
del dc
-
+
def addfile(self,gcodes=[]):
self.clear()
for i in gcodes:
self.addgcode(i)
-
+
def addgcode(self,gcode="M105",hilight=0):
gcode=gcode.split("*")[0]
gcode=gcode.split(";")[0]
@@ -323,7 +323,7 @@ class gviz(wx.Panel):
return
if gcode[0][0] == 'n':
gcode.pop(0)
-
+
def _readgcode():
target=self.lastpos[:]
target[5]=0.0
@@ -353,14 +353,14 @@ class gviz(wx.Panel):
self.arcpens[target[2]]=[]
self.layers+=[target[2]]
return target
-
+
def _y(y):
return self.build_dimensions[1]-(y-self.build_dimensions[4])
def _x(x):
return x-self.build_dimensions[3]
-
+
start_pos = self.hilightpos[:] if hilight else self.lastpos[:]
-
+
if gcode[0] in [ "g0", "g1" ]:
target = _readgcode()
line = [ _x(start_pos[0]), _y(start_pos[1]), _x(target[0]), _y(target[1]) ]
@@ -372,7 +372,7 @@ class gviz(wx.Panel):
self.hilight += [line]
self.hilightpos = target
self.dirty = 1
-
+
if gcode[0] in [ "g2", "g3" ]:
target = _readgcode()
arc = []
@@ -381,7 +381,7 @@ class gviz(wx.Panel):
arc += [ _x(start_pos[0] + target[5]), _y(start_pos[1] + target[6]) ] # center
if gcode[0] == "g2": # clockwise, reverse endpoints
arc[0], arc[1], arc[2], arc[3] = arc[2], arc[3], arc[0], arc[1]
-
+
if not hilight:
self.arcs[ target[2] ] += [arc]
self.arcpens[ target[2] ] += [self.arcpen]
@@ -390,11 +390,10 @@ class gviz(wx.Panel):
self.hilightarcs += [arc]
self.hilightpos = target
self.dirty = 1
-
+
if __name__ == '__main__':
app = wx.App(False)
#main = window(open("/home/kliment/designs/spinner/arm_export.gcode"))
main = window(open("jam.gcode"))
main.Show()
app.MainLoop()
-
diff --git a/printrun/printrun_utils.py b/printrun/printrun_utils.py
index 8d599c8..c09941b 100644
--- a/printrun/printrun_utils.py
+++ b/printrun/printrun_utils.py
@@ -8,14 +8,14 @@ def install_locale(domain):
gettext.install(domain, '/usr/share/pronterface/locale', unicode=1)
elif os.path.exists('/usr/local/share/pronterface/locale'):
gettext.install(domain, '/usr/local/share/pronterface/locale', unicode=1)
- else:
+ else:
gettext.install(domain, './locale', unicode=1)
def imagefile(filename):
for prefix in ['/usr/local/share/pronterface/images', '/usr/share/pronterface/images']:
- candidate = os.path.join(prefix, filename)
- if os.path.exists(candidate):
- return candidate
+ candidate = os.path.join(prefix, filename)
+ if os.path.exists(candidate):
+ return candidate
local_candidate = os.path.join(os.path.dirname(__file__), "images", filename)
if os.path.exists(local_candidate):
return local_candidate
@@ -24,9 +24,9 @@ def imagefile(filename):
def lookup_file(filename, prefixes):
for prefix in prefixes:
- candidate = os.path.join(prefix, filename)
- if os.path.exists(candidate):
- return candidate
+ candidate = os.path.join(prefix, filename)
+ if os.path.exists(candidate):
+ return candidate
return filename
def pixmapfile(filename):
diff --git a/printrun/projectlayer.py b/printrun/projectlayer.py
index 81e4b31..a6a0d0c 100644
--- a/printrun/projectlayer.py
+++ b/printrun/projectlayer.py
@@ -1,15 +1,15 @@
# This file is part of the Printrun suite.
-#
+#
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
-#
+#
# Printrun is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
-#
+#
# You should have received a copy of the GNU General Public License
# along with Printrun. If not, see .
@@ -21,7 +21,7 @@ import tempfile
import shutil
import svg.document as wxpsvgdocument
import imghdr
-
+
class dispframe(wx.Frame):
def __init__(self, parent, title, res=(800, 600), printer=None):
wx.Frame.__init__(self, parent=parent, title=title)
@@ -58,7 +58,7 @@ class dispframe(wx.Frame):
points = [wx.Point(*map(lambda x:int(round(float(x) * self.scale)), j.strip().split())) for j in i.strip().split("M")[1].split("L")]
dc.DrawPolygon(points, self.size[0] / 2, self.size[1] / 2)
elif self.slicer == 'Slic3r':
- gc = wx.GraphicsContext_Create(dc)
+ gc = wx.GraphicsContext_Create(dc)
gc.Translate(*self.offset)
gc.Scale(self.scale, self.scale)
wxpsvgdocument.SVGDocument(image).render(gc)
@@ -69,12 +69,12 @@ class dispframe(wx.Frame):
self.pic.SetBitmap(self.bitmap)
self.pic.Show()
self.Refresh()
-
-
+
+
except:
raise
pass
-
+
def showimgdelay(self, image):
self.drawlayer(image)
self.pic.Show()
@@ -82,10 +82,10 @@ class dispframe(wx.Frame):
self.Refresh()
if self.p != None and self.p.online:
- self.p.send_now("G91")
- self.p.send_now("G1 Z%f F300" % (self.thickness,))
- self.p.send_now("G90")
-
+ self.p.send_now("G91")
+ self.p.send_now("G1 Z%f F300" % (self.thickness,))
+ self.p.send_now("G90")
+
def nextimg(self, event):
if self.index < len(self.layers):
i = self.index
@@ -99,8 +99,8 @@ class dispframe(wx.Frame):
wx.CallAfter(self.pic.Hide)
wx.CallAfter(self.Refresh)
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)):
wx.CallAfter(self.pic.Hide)
wx.CallAfter(self.Refresh)
@@ -117,7 +117,7 @@ class dispframe(wx.Frame):
self.timer.Start(1000 * interval + 1000 * pause)
class setframe(wx.Frame):
-
+
def __init__(self, parent, printer=None):
wx.Frame.__init__(self, parent, title="Projector setup")
self.f = dispframe(None, "", printer=printer)
@@ -147,26 +147,26 @@ class setframe(wx.Frame):
wx.StaticText(self.panel, -1, "Y:", pos=(160, 60))
self.Y = wx.TextCtrl(self.panel, -1, "768", pos=(210, 60))
-
+
wx.StaticText(self.panel, -1, "OffsetX:", pos=(160, 90))
self.offsetX = wx.TextCtrl(self.panel, -1, "50", pos=(210, 90))
wx.StaticText(self.panel, -1, "OffsetY:", pos=(160, 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.Bind(wx.EVT_BUTTON, self.startdisplay)
-
+
wx.StaticText(self.panel, -1, "Fullscreen:", pos=(160, 150))
self.fullscreen = wx.CheckBox(self.panel, -1, pos=(220, 150))
self.fullscreen.SetValue(True)
-
+
self.Show()
def __del__(self):
if hasattr(self, 'image_dir') and self.image_dir != '':
shutil.rmtree(self.image_dir)
-
+
def parsesvg(self, name):
et = xml.etree.ElementTree.ElementTree(file=name)
#xml.etree.ElementTree.dump(et)
@@ -177,18 +177,18 @@ class setframe(wx.Frame):
if (slicer == 'Slic3r'):
height = et.getroot().get('height')
width = et.getroot().get('width')
-
+
for i in et.findall("{http://www.w3.org/2000/svg}g"):
z = float(i.get('{http://slic3r.org/namespaces/slic3r}z'))
zdiff = z - zlast
zlast = z
-
+
svgSnippet = xml.etree.ElementTree.Element('{http://www.w3.org/2000/svg}svg')
svgSnippet.set('height', height + 'mm')
svgSnippet.set('width', width + 'mm')
svgSnippet.set('viewBox', '0 0 ' + height + ' ' + width)
svgSnippet.append(i)
-
+
ol += [svgSnippet]
else :
for i in et.findall("{http://www.w3.org/2000/svg}g")[0].findall("{http://www.w3.org/2000/svg}g"):
@@ -198,7 +198,7 @@ class setframe(wx.Frame):
path = i.find('{http://www.w3.org/2000/svg}path')
ol += [(path.get("d").split("z"))[:-1]]
return ol, zdiff, slicer
-
+
def parse3DLPzip(self, name):
if not zipfile.is_zipfile(name):
raise Exception(name + " is not a zip file!")
@@ -212,7 +212,7 @@ class setframe(wx.Frame):
if os.path.isfile(path) and imghdr.what(path) in acceptedImageTypes:
ol.append(wx.Bitmap(path))
return ol, -1, "bitmap"
-
+
def loadfile(self, event):
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;)"))
diff --git a/printrun/pronterface_widgets.py b/printrun/pronterface_widgets.py
index b90c960..c1e1030 100644
--- a/printrun/pronterface_widgets.py
+++ b/printrun/pronterface_widgets.py
@@ -17,7 +17,7 @@ import wx
class macroed(wx.Dialog):
"""Really simple editor to edit macro definitions"""
-
+
def __init__(self,macro_name,definition,callback,gcode=False):
self.indent_chars = " "
title=" macro %s"
@@ -54,7 +54,7 @@ class macroed(wx.Dialog):
topsizer.Fit(self)
self.Show()
self.e.SetFocus()
-
+
def find(self,ev):
# Ask user what to look for, find it and point at it ... (Jezmy)
S = self.e.GetStringSelection()
@@ -63,27 +63,27 @@ class macroed(wx.Dialog):
FindValue = wx.GetTextFromUser('Please enter a search string:', caption="Search", default_value=S, parent=None)
somecode = self.e.GetValue()
numLines = len(somecode)
- position = somecode.find(FindValue, self.e.GetInsertionPoint())
+ position = somecode.find(FindValue, self.e.GetInsertionPoint())
if position == -1 :
# ShowMessage(self,-1, "Not found!")
- titletext = wx.TextCtrl(self.panel,-1,"Not Found!")
- else:
- # self.title.SetValue("Position : "+str(position))
-
- titletext = wx.TextCtrl(self.panel,-1,str(position))
-
- # ananswer = wx.MessageBox(str(numLines)+" Lines detected in file\n"+str(position), "OK")
+ titletext = wx.TextCtrl(self.panel,-1,"Not Found!")
+ else:
+ # self.title.SetValue("Position : "+str(position))
+
+ titletext = wx.TextCtrl(self.panel,-1,str(position))
+
+ # ananswer = wx.MessageBox(str(numLines)+" Lines detected in file\n"+str(position), "OK")
self.e.SetFocus()
- self.e.SetInsertionPoint(position)
+ self.e.SetInsertionPoint(position)
self.e.SetSelection(position, position + len(FindValue))
self.e.ShowPosition(position)
-
+
def ShowMessage(self, ev , message):
dlg = wxMessageDialog(self, message,
"Info!", wxOK | wxICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
-
+
def save(self,ev):
self.Destroy()
if not self.gcode:
diff --git a/printrun/stltool.py b/printrun/stltool.py
index d54ac02..50b01ca 100644
--- a/printrun/stltool.py
+++ b/printrun/stltool.py
@@ -1,15 +1,15 @@
# This file is part of the Printrun suite.
-#
+#
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
-#
+#
# Printrun is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
-#
+#
# You should have received a copy of the GNU General Public License
# along with Printrun. If not, see .
@@ -38,15 +38,15 @@ I=[
def transpose(matrix):
return zip(*matrix)
#return [[v[i] for v in matrix] for i in xrange(len(matrix[0]))]
-
+
def multmatrix(vector,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):
#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 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]]]
m=[
[1,0,0,0],
@@ -73,7 +73,7 @@ def emitstl(filename,facets=[],objname="stltool_export",binary=1):
f.write(buf)
f.close()
return
-
+
f=open(filename,"w")
f.write("solid "+objname+"\n")
@@ -85,8 +85,8 @@ def emitstl(filename,facets=[],objname="stltool_export",binary=1):
f.write(" endfacet"+"\n")
f.write("endsolid "+objname+"\n")
f.close()
-
-
+
+
class stl:
def __init__(self, filename=None):
@@ -94,7 +94,7 @@ class stl:
self.facets=[]
self.facetsminz=[]
self.facetsmaxz=[]
-
+
self.name=""
self.insolid=0
self.infacet=0
@@ -133,7 +133,7 @@ class stl:
for i in self.f:
if not self.parseline(i):
return
-
+
def translate(self,v=[0,0,0]):
matrix=[
[1,0,0,v[0]],
@@ -142,7 +142,7 @@ class stl:
[0,0,0,1]
]
return self.transform(matrix)
-
+
def rotate(self,v=[0,0,0]):
import math
z=v[2]
@@ -167,7 +167,7 @@ class stl:
[0,0,0,1]
]
return self.transform(matrix1).transform(matrix2).transform(matrix3)
-
+
def scale(self,v=[0,0,0]):
matrix=[
[v[0],0,0,0],
@@ -176,8 +176,8 @@ class stl:
[0,0,0,1]
]
return self.transform(matrix)
-
-
+
+
def transform(self,m=I):
s=stl()
s.facets=[applymatrix(i,m) for i in self.facets]
@@ -190,7 +190,7 @@ class stl:
s.facetsminz+=[(min(map(lambda x:x[2], facet[1])),facet)]
s.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])),facet)]
return s
-
+
def export(self,f=sys.stdout):
f.write("solid "+self.name+"\n")
for i in self.facets:
@@ -202,14 +202,14 @@ class stl:
f.write(" endfacet"+"\n")
f.write("endsolid "+self.name+"\n")
f.flush()
-
+
def parseline(self,l):
l=l.strip()
if l.startswith("solid"):
self.insolid=1
self.name=l[6:]
#print self.name
-
+
elif l.startswith("endsolid"):
self.insolid=0
return 0
@@ -244,7 +244,7 @@ if __name__=="__main__":
working.remove(j[1])
else:
break
-
+
print i,len(working)
emitstl("../../Downloads/frame-vertex-neo-foot-x4-a.stl",s.facets,"emitted_object")
#stl("../prusamendel/stl/mendelplate.stl")
diff --git a/printrun/stlview.py b/printrun/stlview.py
index 0244379..bbf8682 100644
--- a/printrun/stlview.py
+++ b/printrun/stlview.py
@@ -1,17 +1,17 @@
#!/usr/bin/python
# This file is part of the Printrun suite.
-#
+#
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
-#
+#
# Printrun is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
-#
+#
# You should have received a copy of the GNU General Public License
# along with Printrun. If not, see .
@@ -304,14 +304,14 @@ class gcview(object):
('v3f/static', vertices),
('n3f/static', normals)))
if lasth is not None:
- 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))]
- self.vlists.append(self.layers[lasth].add_indexed(len(layertemp[lasth][0]) // 3,
- GL_TRIANGLES,
- None, # group,
- indices,
- ('v3f/static', layertemp[lasth][0]),
- ('n3f/static', layertemp[lasth][1])))
+ 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))]
+ self.vlists.append(self.layers[lasth].add_indexed(len(layertemp[lasth][0]) // 3,
+ GL_TRIANGLES,
+ None, # group,
+ indices,
+ ('v3f/static', layertemp[lasth][0]),
+ ('n3f/static', layertemp[lasth][1])))
def genline(self, i, h, w):
S = i[0][:3]
@@ -356,28 +356,28 @@ class gcview(object):
return spoints, epoints, S, E
def transform(self, line):
- line = line.split(";")[0]
- cur = self.prev[:]
- if len(line) > 0:
- if "G1" in line or "G0" in line or "G92" in line:
- if("X" in line):
- cur[0] = float(line.split("X")[1].split(" ")[0])
- if("Y" in line):
- cur[1] = float(line.split("Y")[1].split(" ")[0])
- if("Z" in line):
- cur[2] = float(line.split("Z")[1].split(" ")[0])
- if("E" in line):
- cur[3] = float(line.split("E")[1].split(" ")[0])
- if self.prev == cur:
- return None
- if self.fline or "G92" in line:
- self.prev = cur
- self.fline = 0
- return None
- else:
- r = [self.prev, cur]
- self.prev = cur
- return r
+ line = line.split(";")[0]
+ cur = self.prev[:]
+ if len(line) > 0:
+ if "G1" in line or "G0" in line or "G92" in line:
+ if("X" in line):
+ cur[0] = float(line.split("X")[1].split(" ")[0])
+ if("Y" in line):
+ cur[1] = float(line.split("Y")[1].split(" ")[0])
+ if("Z" in line):
+ cur[2] = float(line.split("Z")[1].split(" ")[0])
+ if("E" in line):
+ cur[3] = float(line.split("E")[1].split(" ")[0])
+ if self.prev == cur:
+ return None
+ if self.fline or "G92" in line:
+ self.prev = cur
+ self.fline = 0
+ return None
+ else:
+ r = [self.prev, cur]
+ self.prev = cur
+ return r
def delete(self):
for i in self.vlists:
@@ -570,27 +570,27 @@ class TestGlPanel(GLPanel):
self.initpos = None
elif event.Dragging() and event.RightIsDown() and event.ShiftDown():
- if self.initpos is None:
- self.initpos = event.GetPositionTuple()
- else:
- p1 = self.initpos
- p2 = event.GetPositionTuple()
- sz = self.GetClientSize()
- p1 = list(p1)
- p2 = list(p2)
- p1[1] *= -1
- p2[1] *= -1
+ if self.initpos is None:
+ self.initpos = event.GetPositionTuple()
+ else:
+ p1 = self.initpos
+ p2 = event.GetPositionTuple()
+ sz = self.GetClientSize()
+ p1 = list(p1)
+ p2 = list(p2)
+ p1[1] *= -1
+ p2[1] *= -1
- self.transv = map(lambda x, y, z, c: c - self.dist * (x - y) / z, list(p1) + [0], list(p2) + [0], list(sz) + [1], self.transv)
+ self.transv = map(lambda x, y, z, c: c - self.dist * (x - y) / z, list(p1) + [0], list(p2) + [0], list(sz) + [1], self.transv)
- glLoadIdentity()
- glTranslatef(self.transv[0], self.transv[1], 0)
- glTranslatef(0, 0, self.transv[2])
- if(self.rot):
- glMultMatrixd(build_rotmatrix(self.basequat))
- glGetDoublev(GL_MODELVIEW_MATRIX, self.mvmat)
- self.rot = 1
- self.initpos = None
+ glLoadIdentity()
+ glTranslatef(self.transv[0], self.transv[1], 0)
+ glTranslatef(0, 0, self.transv[2])
+ if(self.rot):
+ glMultMatrixd(build_rotmatrix(self.basequat))
+ glGetDoublev(GL_MODELVIEW_MATRIX, self.mvmat)
+ self.rot = 1
+ self.initpos = None
else:
#mouse is moving without a button press
p = event.GetPositionTuple()
diff --git a/printrun/svg/__init__.py b/printrun/svg/__init__.py
index aeb79cb..61a481c 100644
--- a/printrun/svg/__init__.py
+++ b/printrun/svg/__init__.py
@@ -5,9 +5,9 @@
import wx
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)"""
-
+
if True:
import warnings
warnings.warn("elliptical arcs are not supported")
@@ -15,7 +15,7 @@ def AddEllipticalArc(self, x, y, w, h, startAngle, endAngle, clockwise=False):
h = h/2.0
self.AddArc(x+w, y+h, ((w+h)/2), startAngle, endAngle, clockwise)
return
- else:
+ else:
#implement in terms of AddArc by applying a transformation matrix
#Sigh this can't work, still need to patch wx to allow
#either a) AddPath that's not a closed path or
@@ -25,19 +25,18 @@ def AddEllipticalArc(self, x, y, w, h, startAngle, endAngle, clockwise=False):
#possibly be simulated by combining the current transform with option a.
mtx = wx.GraphicsRenderer_GetDefaultRenderer().CreateMatrix()
path = wx.GraphicsRenderer_GetDefaultRenderer().CreatePath()
-
+
mtx.Translate(x+(w/2.0), y+(h/2.0))
mtx.Scale(w/2.0, y/2.0)
-
+
path.AddArc(0, 0, 1, startAngle, endAngle, clockwise)
path.Transform(mtx)
self.AddPath(path)
self.MoveToPoint(path.GetCurrentPoint())
self.CloseSubpath()
-
+
if not hasattr(wx.GraphicsPath, "AddEllipticalArc"):
wx.GraphicsPath.AddEllipticalArc = AddEllipticalArc
del AddEllipticalArc
-
\ No newline at end of file
diff --git a/printrun/svg/attributes.py b/printrun/svg/attributes.py
index ac6ac8c..62a3f88 100644
--- a/printrun/svg/attributes.py
+++ b/printrun/svg/attributes.py
@@ -2,7 +2,7 @@
Parsers for specific attributes
"""
import urlparse
-from pyparsing import (Literal,
+from pyparsing import (Literal,
Optional, oneOf, Group, StringEnd, Combine, Word, alphas, hexnums,
CaselessLiteral, SkipTo
)
@@ -21,14 +21,14 @@ def parsePossibleURL(t):
colorDeclaration = none | currentColor | colourValue
urlEnd = (
- Literal(")").suppress() +
- Optional(Group(colorDeclaration), default=()) +
+ Literal(")").suppress() +
+ Optional(Group(colorDeclaration), default=()) +
StringEnd()
)
url = (
CaselessLiteral("URL")
- +
+ +
Literal("(").suppress()+
Group(SkipTo(urlEnd, include=True).setParseAction(parsePossibleURL))
)
@@ -37,7 +37,7 @@ url = (
#For none and currentColor, the details tuple will be the empty tuple
#for CSS color declarations, it will be (type, (R,G,B))
#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
#The fallback will be another (type, details) tuple as a parsed
#colorDeclaration, but may be the empty tuple if it is not present
diff --git a/printrun/svg/css/atrule.py b/printrun/svg/css/atrule.py
index a88ebbd..7a0face 100644
--- a/printrun/svg/css/atrule.py
+++ b/printrun/svg/css/atrule.py
@@ -3,4 +3,4 @@
from pyparsing import Literal, Combine
from .identifier import identifier
-atkeyword = Combine(Literal("@") + identifier)
\ No newline at end of file
+atkeyword = Combine(Literal("@") + identifier)
diff --git a/printrun/svg/css/block.py b/printrun/svg/css/block.py
index 7199436..804f0c2 100644
--- a/printrun/svg/css/block.py
+++ b/printrun/svg/css/block.py
@@ -5,4 +5,3 @@
from pyparsing import nestedExpr
block = nestedExpr(opener="{", closer="}")
-
diff --git a/printrun/svg/css/colour.py b/printrun/svg/css/colour.py
index 9be548b..c7b6e87 100644
--- a/printrun/svg/css/colour.py
+++ b/printrun/svg/css/colour.py
@@ -21,31 +21,31 @@ comma = Literal(",").suppress()
def clampColourByte(val):
val = int(val)
return min(max(0,val), 255)
-
+
def clampColourPerc(val):
val = float(val)
return min(max(0,val), 100)
-
+
def parseColorPerc(token):
val = token[0]
val = clampColourPerc(val)
#normalize to bytes
return int(255 * (val / 100.0))
-
+
colorByte = Optional(sign) + integerConstant.setParseAction(lambda t: clampColourByte(t[0]))
colorPerc = number.setParseAction(parseColorPerc) + Literal("%").suppress()
rgb = (
- Literal("rgb(").setParseAction(lambda t: "RGB") +
-
+ Literal("rgb(").setParseAction(lambda t: "RGB") +
+
(
#integer constants, ie 255,255,255
Group(colorByte + comma + colorByte + comma + colorByte) ^
#percentage values, ie 100%, 50%
Group(colorPerc + comma + colorPerc + comma + colorPerc)
)
- +
+ +
Literal(")").suppress() + StringEnd()
)
@@ -54,10 +54,10 @@ def parseShortHex(t):
doubleHex = Word(hexnums, exact=2).setParseAction(lambda t: int(t[0], 16))
-hexLiteral = (Literal("#").setParseAction(lambda t: "RGB") +
+hexLiteral = (Literal("#").setParseAction(lambda t: "RGB") +
(
Group(doubleHex + doubleHex + doubleHex) |
- Word(hexnums, exact=3).setParseAction(parseShortHex)
+ Word(hexnums, exact=3).setParseAction(parseShortHex)
) + StringEnd()
)
@@ -66,7 +66,7 @@ def parseNamedColour(t):
return ["RGB", NamedColours[t[0].lower()]]
except KeyError:
return ["RGB", (0,0,0)]
-
+
namedColour = Word(alphas).setParseAction(parseNamedColour)
@@ -246,7 +246,7 @@ NamedColours = {
def fillCSS2SystemColours():
#The system colours require a wxApp to be present to retrieve,
- #so if you wnat support for them you'll need
+ #so if you wnat support for them you'll need
#to call this function after your wxApp instance starts
systemColors = {
"ActiveBorder": wx.SYS_COLOUR_ACTIVEBORDER,
@@ -280,4 +280,4 @@ def fillCSS2SystemColours():
NamedColours.update(
#strip the alpha from the system colors. Is this really what we want to do?
(k.lower(), wx.SystemSettings.GetColour(v)[:3]) for (k,v) in systemColors.iteritems()
- )
\ No newline at end of file
+ )
diff --git a/printrun/svg/css/identifier.py b/printrun/svg/css/identifier.py
index cb3e485..64472ee 100644
--- a/printrun/svg/css/identifier.py
+++ b/printrun/svg/css/identifier.py
@@ -10,7 +10,7 @@ class White(White):
super(White, self).__init__(ws, min, max, exact)
escaped = (
- Literal("\\").suppress() +
+ Literal("\\").suppress() +
#chr(20)-chr(126) + chr(128)-unichr(sys.maxunicode)
Regex(u"[\u0020-\u007e\u0080-\uffff]", re.IGNORECASE)
)
@@ -18,7 +18,7 @@ escaped = (
def convertToUnicode(t):
return unichr(int(t[0], 16))
hex_unicode = (
- Literal("\\").suppress() +
+ Literal("\\").suppress() +
Regex("[0-9a-f]{1,6}", re.IGNORECASE) +
Optional(White(exact=1)).suppress()
).setParseAction(convertToUnicode)
@@ -29,9 +29,9 @@ escape = hex_unicode | escaped
#any unicode literal outside the 0-127 ascii range
nonascii = Regex(u"[^\u0000-\u007f]")
-#single character for starting an identifier.
+#single character for starting an identifier.
nmstart = Regex(u"[A-Z]", re.IGNORECASE) | nonascii | escape
nmchar = Regex(u"[0-9A-Z-]", re.IGNORECASE) | nonascii | escape
-identifier = Combine(nmstart + ZeroOrMore(nmchar))
\ No newline at end of file
+identifier = Combine(nmstart + ZeroOrMore(nmchar))
diff --git a/printrun/svg/css/inline.py b/printrun/svg/css/inline.py
index 1aa90b0..9d23e70 100644
--- a/printrun/svg/css/inline.py
+++ b/printrun/svg/css/inline.py
@@ -5,4 +5,4 @@ def inlineStyle(styleString):
return {}
styles = styleString.split(";")
rv = dict(style.split(":") for style in styles if len(style) != 0)
- return rv
\ No newline at end of file
+ return rv
diff --git a/printrun/svg/css/transform.py b/printrun/svg/css/transform.py
index a49a400..852b39b 100644
--- a/printrun/svg/css/transform.py
+++ b/printrun/svg/css/transform.py
@@ -48,4 +48,4 @@ transformList = delimitedList(Group(transform), delim=maybeComma)
if __name__ == '__main__':
from tests.test_css import *
- unittest.main()
\ No newline at end of file
+ unittest.main()
diff --git a/printrun/svg/css/values.py b/printrun/svg/css/values.py
index bb6aee9..48efbd0 100644
--- a/printrun/svg/css/values.py
+++ b/printrun/svg/css/values.py
@@ -43,4 +43,4 @@ length = lengthValue + Optional(lengthUnit, default=None) + StringEnd()
length.leaveWhitespace()
#set the parse action aftward so it doesn't "infect" the parsers that build on it
-number.setParseAction(asFloat)
\ No newline at end of file
+number.setParseAction(asFloat)
diff --git a/printrun/svg/document.py b/printrun/svg/document.py
index 17e1f08..e31bffd 100644
--- a/printrun/svg/document.py
+++ b/printrun/svg/document.py
@@ -15,7 +15,7 @@ from svg.css import values
from attributes import paintValue
document = """
-