Commit ce8c3f3c authored by Guillaume Seguin's avatar Guillaume Seguin

Apply 2to3 and clean 2 minor conversion issues

parent 0376729a
...@@ -209,5 +209,5 @@ class GCodeAnalyzer(): ...@@ -209,5 +209,5 @@ class GCodeAnalyzer():
def print_status(self): def print_status(self):
attrs = vars(self) attrs = vars(self)
print '\n'.join("%s: %s" % item for item in attrs.items()) print('\n'.join("%s: %s" % item for item in list(attrs.items())))
\ No newline at end of file
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
# Set up Internationalization using gettext # Set up Internationalization using 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)
import os, Queue, re import os, queue, re
from printrun.printrun_utils import install_locale from printrun.printrun_utils import install_locale
install_locale('plater') install_locale('plater')
...@@ -209,18 +209,18 @@ class showstl(wx.Window): ...@@ -209,18 +209,18 @@ class showstl(wx.Window):
offset = [0, 0] offset = [0, 0]
scale = 2 scale = 2
dc.SetPen(wx.Pen(wx.Colour(100, 100, 100))) dc.SetPen(wx.Pen(wx.Colour(100, 100, 100)))
for i in xrange(20): for i in range(20):
dc.DrawLine(0, i * scale * 10, 400, i * scale * 10) dc.DrawLine(0, i * scale * 10, 400, i * scale * 10)
dc.DrawLine(i * scale * 10, 0, i * scale * 10, 400) dc.DrawLine(i * scale * 10, 0, i * scale * 10, 400)
dc.SetPen(wx.Pen(wx.Colour(0, 0, 0))) dc.SetPen(wx.Pen(wx.Colour(0, 0, 0)))
for i in xrange(4): for i in range(4):
dc.DrawLine(0, i * scale * 50, 400, i * scale * 50) dc.DrawLine(0, i * scale * 50, 400, i * scale * 50)
dc.DrawLine(i * scale * 50, 0, i * scale * 50, 400) dc.DrawLine(i * scale * 50, 0, i * scale * 50, 400)
dc.SetBrush(wx.Brush(wx.Colour(128, 255, 128))) dc.SetBrush(wx.Brush(wx.Colour(128, 255, 128)))
dc.SetPen(wx.Pen(wx.Colour(128, 128, 128))) dc.SetPen(wx.Pen(wx.Colour(128, 128, 128)))
t = time.time() t = time.time()
dcs = wx.MemoryDC() dcs = wx.MemoryDC()
for m in self.parent.models.values(): for m in list(self.parent.models.values()):
b = m.bitmap b = m.bitmap
#print b #print b
im = b.ConvertToImage() im = b.ConvertToImage()
...@@ -288,7 +288,7 @@ class stlwin(wx.Frame): ...@@ -288,7 +288,7 @@ class stlwin(wx.Frame):
#self.SetClientSize(size) #self.SetClientSize(size)
def autoplate(self, event): def autoplate(self, event):
print _("Autoplating") print(_("Autoplating"))
separation = 2 separation = 2
bedsize = [200, 200, 100] bedsize = [200, 200, 100]
cursor = [0, 0, 0] cursor = [0, 0, 0]
...@@ -316,7 +316,7 @@ class stlwin(wx.Frame): ...@@ -316,7 +316,7 @@ class stlwin(wx.Frame):
max[1] = cursor[1] + x max[1] = cursor[1] + x
cursor[0] += x + separation cursor[0] += x + separation
if (cursor[1] + y) >= bedsize[1]: if (cursor[1] + y) >= bedsize[1]:
print _("Bed full, sorry sir :(") print(_("Bed full, sorry sir :("))
self.Refresh() self.Refresh()
return return
centreoffset = [(bedsize[0] - max[0]) / 2, (bedsize[1] - max[1]) / 2] centreoffset = [(bedsize[0] - max[0]) / 2, (bedsize[1] - max[1]) / 2]
...@@ -378,7 +378,7 @@ class stlwin(wx.Frame): ...@@ -378,7 +378,7 @@ class stlwin(wx.Frame):
def writefiles(self, name): def writefiles(self, name):
sf = open(name.replace(".", "_") + ".scad", "w") sf = open(name.replace(".", "_") + ".scad", "w")
facets = [] facets = []
for i in self.models.values(): for i in list(self.models.values()):
r = i.rot r = i.rot
o = i.offsets o = i.offsets
...@@ -390,7 +390,7 @@ class stlwin(wx.Frame): ...@@ -390,7 +390,7 @@ class stlwin(wx.Frame):
facets += i.facets facets += i.facets
sf.close() sf.close()
stltool.emitstl(name, facets, "plater_export") stltool.emitstl(name, facets, "plater_export")
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)
......
...@@ -21,6 +21,7 @@ from select import error as SelectError ...@@ -21,6 +21,7 @@ from select import error as SelectError
import time, getopt, sys import time, getopt, sys
import platform, os import platform, os
from GCodeAnalyzer import GCodeAnalyzer from GCodeAnalyzer import GCodeAnalyzer
from functools import reduce
def control_ttyhup(port, disable_hup): def control_ttyhup(port, disable_hup):
"""Controls the HUPCL""" """Controls the HUPCL"""
...@@ -120,19 +121,19 @@ class printcore(): ...@@ -120,19 +121,19 @@ class printcore():
if self.recvcb: if self.recvcb:
try: self.recvcb(line) try: self.recvcb(line)
except: pass except: pass
if self.loud: print "RECV: ", line.rstrip() if self.loud: print("RECV: ", line.rstrip())
return line return line
except SelectError, e: except SelectError as e:
if 'Bad file descriptor' in e.args[1]: if 'Bad file descriptor' in e.args[1]:
print "Can't read from printer (disconnected?)." print("Can't read from printer (disconnected?).")
return None return None
else: else:
raise raise
except SerialException, e: except SerialException as e:
print "Can't read from printer (disconnected?)." print("Can't read from printer (disconnected?).")
return None return None
except OSError, e: except OSError as e:
print "Can't read from printer (disconnected?)." print("Can't read from printer (disconnected?).")
return None return None
def _listen_can_continue(self): def _listen_can_continue(self):
...@@ -201,7 +202,7 @@ class printcore(): ...@@ -201,7 +202,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, list(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.
...@@ -312,7 +313,7 @@ class printcore(): ...@@ -312,7 +313,7 @@ class printcore():
time.sleep(0.001) time.sleep(0.001)
wait -= 1 wait -= 1
else: else:
print "Not connected to printer." print("Not connected to printer.")
def send_now(self, command, wait = 0): def send_now(self, command, wait = 0):
"""Sends a command to the printer ahead of the command queue, without a checksum """Sends a command to the printer ahead of the command queue, without a checksum
...@@ -332,7 +333,7 @@ class printcore(): ...@@ -332,7 +333,7 @@ class printcore():
time.sleep(0.001) time.sleep(0.001)
wait -= 1 wait -= 1
else: else:
print "Not connected to printer." print("Not connected to printer.")
def _print(self): def _print(self):
if self.startcb: if self.startcb:
...@@ -414,14 +415,14 @@ class printcore(): ...@@ -414,14 +415,14 @@ class printcore():
self.sent.append(command) self.sent.append(command)
self.analyzer.Analyze(command) # run the command through the analyzer self.analyzer.Analyze(command) # run the command through the analyzer
if self.loud: if self.loud:
print "SENT: ", command print("SENT: ", command)
if self.sendcb: if self.sendcb:
try: self.sendcb(command) try: self.sendcb(command)
except: pass except: pass
try: try:
self.printer.write(str(command+"\n")) self.printer.write(str(command+"\n"))
except SerialException, e: except SerialException as e:
print "Can't write to printer (disconnected?)." print("Can't write to printer (disconnected?).")
if __name__ == '__main__': if __name__ == '__main__':
baud = 115200 baud = 115200
...@@ -430,13 +431,13 @@ if __name__ == '__main__': ...@@ -430,13 +431,13 @@ if __name__ == '__main__':
try: try:
opts, args = getopt.getopt(sys.argv[1:], "h,b:,v,s", opts, args = getopt.getopt(sys.argv[1:], "h,b:,v,s",
["help", "baud", "verbose", "statusreport"]) ["help", "baud", "verbose", "statusreport"])
except getopt.GetoptError, err: except getopt.GetoptError as err:
print str(err) print(str(err))
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'):
# FIXME: Fix help # FIXME: Fix help
print "Opts are: --help , -b --baud = baudrate, -v --verbose, -s --statusreport" print("Opts are: --help , -b --baud = baudrate, -v --verbose, -s --statusreport")
sys.exit(1) sys.exit(1)
if o in ('-b', '--baud'): if o in ('-b', '--baud'):
baud = int(a) baud = int(a)
...@@ -448,9 +449,9 @@ if __name__ == '__main__': ...@@ -448,9 +449,9 @@ if __name__ == '__main__':
if len (args) > 1: if len (args) > 1:
port = args[-2] port = args[-2]
filename = args[-1] filename = args[-1]
print "Printing: %s on %s with baudrate %d" % (filename, port, baud) print("Printing: %s on %s with baudrate %d" % (filename, port, baud))
else: else:
print "Usage: python [-h|-b|-v|-s] printcore.py /dev/tty[USB|ACM]x filename.gcode" print("Usage: python [-h|-b|-v|-s] printcore.py /dev/tty[USB|ACM]x filename.gcode")
sys.exit(2) sys.exit(2)
p = printcore(port, baud) p = printcore(port, baud)
p.loud = loud p.loud = loud
......
...@@ -141,7 +141,7 @@ class SkeinforgeQuickEditDialog(wx.Dialog): ...@@ -141,7 +141,7 @@ class SkeinforgeQuickEditDialog(wx.Dialog):
for setting in settings.getReadRepository(repo).preferences: for setting in settings.getReadRepository(repo).preferences:
if setting.name == settingName: if setting.name == settingName:
if setting.value == None or str(x.GetValue()) != str(setting.value): if setting.value == None or str(x.GetValue()) != str(setting.value):
print('Saving ... ' + settingName + ' = ' + str(x.GetValue())) print(('Saving ... ' + settingName + ' = ' + str(x.GetValue())))
setting.value = x.GetValue() setting.value = x.GetValue()
isDirty = True isDirty = True
if isDirty: if isDirty:
......
...@@ -38,7 +38,7 @@ def float_input(prompt=''): ...@@ -38,7 +38,7 @@ def float_input(prompt=''):
import sys import sys
f = None f = None
while f == None: while f == None:
s = raw_input(prompt) s = input(prompt)
try: try:
f = float(s) f = float(s)
except ValueError: except ValueError:
...@@ -54,7 +54,7 @@ def wait(t, m=''): ...@@ -54,7 +54,7 @@ def wait(t, m=''):
sys.stdout.write(s) sys.stdout.write(s)
sys.stdout.flush() sys.stdout.flush()
time.sleep(1.0/5) time.sleep(1.0/5)
print print()
def w(s): def w(s):
sys.stdout.write(s) sys.stdout.write(s)
sys.stdout.flush() sys.stdout.flush()
...@@ -73,9 +73,9 @@ def heatup(p, temp, s = 0): ...@@ -73,9 +73,9 @@ def heatup(p, temp, s = 0):
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("\rHeating extruder up.. %3d \xb0C"%curtemp)
if s: print if s: print()
else: print "\nReady." else: print("\nReady.")
def gettemp(p): def gettemp(p):
try: p.logl try: p.logl
...@@ -87,14 +87,14 @@ def gettemp(p): ...@@ -87,14 +87,14 @@ def gettemp(p):
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 = """
%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)
...@@ -104,13 +104,13 @@ help = u""" ...@@ -104,13 +104,13 @@ help = u"""
"""[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 as 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)
...@@ -119,17 +119,17 @@ for o, a in opts: ...@@ -119,17 +119,17 @@ for o, a in opts:
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(('%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")
print "Steps per mm: %3d steps"%k print("Steps per mm: %3d steps"%k)
print "Length extruded: %3d mm"%n 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:
...@@ -138,12 +138,12 @@ try: ...@@ -138,12 +138,12 @@ try:
try: try:
p = printcore(port, 115200) p = printcore(port, 115200)
except: except:
print 'Error.' print('Error.')
raise raise
while not p.online: while not p.online:
time.sleep(1) time.sleep(1)
w('.') w('.')
print " connected." print(" connected.")
heatup(p, temp) heatup(p, temp)
...@@ -158,8 +158,8 @@ try: ...@@ -158,8 +158,8 @@ try:
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!
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass
finally: finally:
......
...@@ -190,7 +190,7 @@ class GCode(object): ...@@ -190,7 +190,7 @@ class GCode(object):
old_lines += cur_lines old_lines += cur_lines
layers[prev_z] = old_lines layers[prev_z] = old_lines
for idx in layers.keys(): for idx in list(layers.keys()):
cur_lines = layers[idx] cur_lines = layers[idx]
has_movement = False has_movement = False
for l in layers[idx]: for l in layers[idx]:
...@@ -215,7 +215,7 @@ class GCode(object): ...@@ -215,7 +215,7 @@ class GCode(object):
ymax = float("-inf") ymax = float("-inf")
zmax = float("-inf") zmax = float("-inf")
for l in self.layers.values(): for l in list(self.layers.values()):
(xm, xM), (ym, yM), (zm, zM) = l.measure() (xm, xM), (ym, yM), (zm, zM) = l.measure()
xmin = min(xm, xmin) xmin = min(xm, xmin)
xmax = max(xM, xmax) xmax = max(xM, xmax)
...@@ -266,7 +266,7 @@ class GCode(object): ...@@ -266,7 +266,7 @@ class GCode(object):
#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 ;)
zs = self.layers.keys() zs = list(self.layers.keys())
zs.sort() zs.sort()
for z in zs: for z in zs:
layer = self.layers[z] layer = self.layers[z]
...@@ -316,7 +316,7 @@ class GCode(object): ...@@ -316,7 +316,7 @@ class GCode(object):
def main(): def main():
if len(sys.argv) < 2: if len(sys.argv) < 2:
print "usage: %s filename.gcode" % sys.argv[0] print("usage: %s filename.gcode" % sys.argv[0])
return return
# d = [i.replace("\n","") for i in open(sys.argv[1])] # d = [i.replace("\n","") for i in open(sys.argv[1])]
...@@ -325,13 +325,13 @@ def main(): ...@@ -325,13 +325,13 @@ def main():
gcode.measure() gcode.measure()
print "Dimensions:" print("Dimensions:")
print "\tX: %0.02f - %0.02f (%0.02f)" % (gcode.xmin,gcode.xmax,gcode.width) print("\tX: %0.02f - %0.02f (%0.02f)" % (gcode.xmin,gcode.xmax,gcode.width))
print "\tY: %0.02f - %0.02f (%0.02f)" % (gcode.ymin,gcode.ymax,gcode.depth) print("\tY: %0.02f - %0.02f (%0.02f)" % (gcode.ymin,gcode.ymax,gcode.depth))
print "\tZ: %0.02f - %0.02f (%0.02f)" % (gcode.zmin,gcode.zmax,gcode.height) print("\tZ: %0.02f - %0.02f (%0.02f)" % (gcode.zmin,gcode.zmax,gcode.height))
print "Filament used: %0.02fmm" % gcode.filament_length() print("Filament used: %0.02fmm" % gcode.filament_length())
print "Number of layers: %d" % gcode.num_layers() print("Number of layers: %d" % gcode.num_layers())
print "Estimated duration (pessimistic): %s" % gcode.estimate_duration() print("Estimated duration (pessimistic): %s" % gcode.estimate_duration())
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -26,7 +26,7 @@ pyglet.options['shadow_window'] = False ...@@ -26,7 +26,7 @@ pyglet.options['shadow_window'] = False
pyglet.options['debug_gl'] = False pyglet.options['debug_gl'] = False
from pyglet.gl import * from pyglet.gl import *
import stltool from . import stltool
import threading import threading
...@@ -258,7 +258,7 @@ class gcline(object): ...@@ -258,7 +258,7 @@ class gcline(object):
self.calc_len() self.calc_len()
def __str__(self): def __str__(self):
return u"line from %s,%s,%s to %s,%s,%s with extrusion ratio %s and feedrate %s\n%s" % ( return "line from %s,%s,%s to %s,%s,%s with extrusion ratio %s and feedrate %s\n%s" % (
self.prev_gcline.x, self.prev_gcline.x,
self.prev_gcline.y, self.prev_gcline.y,
self.prev_gcline.z, self.prev_gcline.z,
...@@ -338,18 +338,18 @@ class gcThreadRenderer(threading.Thread): ...@@ -338,18 +338,18 @@ class gcThreadRenderer(threading.Thread):
threading.Thread.__init__(self) threading.Thread.__init__(self)
self.gcview = gcview self.gcview = gcview
self.lines = lines self.lines = lines
print "q init" print("q init")
def run(self): def run(self):
for line in self.lines: for line in self.lines:
layer_name = line.z layer_name = line.z
if line.z not in self.gcview.layers: if line.z not in self.gcview.layers:
self.gcview.layers[line.z] = pyglet.graphics.Batch() self.gcview.layers[line.z] = pyglet.graphics.Batch()
self.gcview.layerlist = self.gcview.layers.keys() self.gcview.layerlist = list(self.gcview.layers.keys())
self.gcview.layerlist.sort() self.gcview.layerlist.sort()
self.gcview.layers[line.z].add(2, GL_LINES, None, ("v3f", line.glline()), ("c3B", line.glcolor(self.gcview.upper_limit, self.gcview.lower_limit, self.gcview.max_feedrate))) self.gcview.layers[line.z].add(2, GL_LINES, None, ("v3f", line.glline()), ("c3B", line.glcolor(self.gcview.upper_limit, self.gcview.lower_limit, self.gcview.max_feedrate)))
self.gcview.t2 = time.time() self.gcview.t2 = time.time()
print "Rendered lines in %fs" % (self.gcview.t2-self.gcview.t1) print("Rendered lines in %fs" % (self.gcview.t2-self.gcview.t1))
class gcview(object): class gcview(object):
"""gcode visualiser """gcode visualiser
...@@ -358,7 +358,7 @@ class gcview(object): ...@@ -358,7 +358,7 @@ 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):
if len(lines) == 0: if len(lines) == 0:
return return
print "Loading %s lines" % (len(lines)) print("Loading %s lines" % (len(lines)))
#End pos of previous mode #End pos of previous mode
self.prev = gcpoint() self.prev = gcpoint()
# Correction for G92 moves # Correction for G92 moves
...@@ -369,7 +369,7 @@ class gcview(object): ...@@ -369,7 +369,7 @@ class gcview(object):
lines = [self.transform(i) for i in lines] lines = [self.transform(i) for i in lines]
lines = [i for i in lines if i is not None] lines = [i for i in lines if i is not None]
self.t1 = time.time() self.t1 = time.time()
print "transformed %s lines in %fs" % (len(lines), self.t1- self.t0) print("transformed %s lines in %fs" % (len(lines), self.t1- self.t0))
self.upper_limit = 0 self.upper_limit = 0
self.lower_limit = None self.lower_limit = None
self.max_feedrate = 0 self.max_feedrate = 0
...@@ -472,8 +472,8 @@ def trackball(p1x, p1y, p2x, p2y, r): ...@@ -472,8 +472,8 @@ def trackball(p1x, p1y, p2x, p2y, r):
p2 = [p2x, p2y, project_to_sphere(TRACKBALLSIZE, p2x, p2y)] p2 = [p2x, p2y, project_to_sphere(TRACKBALLSIZE, p2x, p2y)]
a = stltool.cross(p2, p1) a = stltool.cross(p2, p1)
d = map(lambda x, y: x - y, p1, p2) d = list(map(lambda x, y: x - y, p1, p2))
t = math.sqrt(sum(map(lambda x: x * x, d))) / (2.0 * TRACKBALLSIZE) t = math.sqrt(sum([x * x for x in d])) / (2.0 * TRACKBALLSIZE)
if (t > 1.0): if (t > 1.0):
t = 1.0 t = 1.0
...@@ -490,9 +490,9 @@ def vec(*args): ...@@ -490,9 +490,9 @@ def vec(*args):
def axis_to_quat(a, phi): def axis_to_quat(a, phi):
#print a, phi #print a, phi
lena = math.sqrt(sum(map(lambda x: x * x, a))) lena = math.sqrt(sum([x * x for x in a]))
q = map(lambda x: x * (1 / lena), a) q = [x * (1 / lena) for x in a]
q = map(lambda x: x * math.sin(phi / 2.0), q) q = [x * math.sin(phi / 2.0) for x in q]
q.append(math.cos(phi / 2.0)) q.append(math.cos(phi / 2.0))
return q return q
...@@ -559,10 +559,10 @@ class TestGlPanel(GLPanel): ...@@ -559,10 +559,10 @@ class TestGlPanel(GLPanel):
def double(self, event): def double(self, event):
p = event.GetPositionTuple() p = event.GetPositionTuple()
sz = self.GetClientSize() sz = self.GetClientSize()
v = map(lambda m, w, b: b * m / w, p, sz, self.bedsize) v = list(map(lambda m, w, b: b * m / w, p, sz, self.bedsize))
v[1] = self.bedsize[1] - v[1] v[1] = self.bedsize[1] - v[1]
v += [300] v += [300]
print v print(v)
self.add_file("../prusa/metric-prusa/x-end-idler.stl", v) self.add_file("../prusa/metric-prusa/x-end-idler.stl", v)
def forceresize(self): def forceresize(self):
...@@ -654,7 +654,7 @@ class TestGlPanel(GLPanel): ...@@ -654,7 +654,7 @@ class TestGlPanel(GLPanel):
p1[1] *= -1 p1[1] *= -1
p2[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 = list(map(lambda x, y, z, c: c - self.dist * (x - y) / z, list(p1) + [0], list(p2) + [0], list(sz) + [1], self.transv))
glLoadIdentity() glLoadIdentity()
glTranslatef(self.transv[0], self.transv[1], 0) glTranslatef(self.transv[0], self.transv[1], 0)
...@@ -668,7 +668,7 @@ class TestGlPanel(GLPanel): ...@@ -668,7 +668,7 @@ class TestGlPanel(GLPanel):
#mouse is moving without a button press #mouse is moving without a button press
p = event.GetPositionTuple() p = event.GetPositionTuple()
sz = self.GetClientSize() sz = self.GetClientSize()
v = map(lambda m, w, b: b * m / w, p, sz, self.bedsize) v = list(map(lambda m, w, b: b * m / w, p, sz, self.bedsize))
v[1] = self.bedsize[1] - v[1] v[1] = self.bedsize[1] - v[1]
self.mousepos = v self.mousepos = v
...@@ -720,7 +720,7 @@ class TestGlPanel(GLPanel): ...@@ -720,7 +720,7 @@ class TestGlPanel(GLPanel):
def keypress(self, event): def keypress(self, event):
"""gets keypress events and moves/rotates acive shape""" """gets keypress events and moves/rotates acive shape"""
keycode = event.GetKeyCode() keycode = event.GetKeyCode()
print keycode print(keycode)
step = 5 step = 5
angle = 18 angle = 18
if event.ControlDown(): if event.ControlDown():
...@@ -815,14 +815,14 @@ class TestGlPanel(GLPanel): ...@@ -815,14 +815,14 @@ class TestGlPanel(GLPanel):
rows = 10 rows = 10
cols = 10 cols = 10
zheight = 50 zheight = 50
for i in xrange(-rows, rows + 1): for i in range(-rows, rows + 1):
if i % 5 == 0: if i % 5 == 0:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1))
else: else:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.2, 0.2, 0.2, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.2, 0.2, 0.2, 1))
glVertex3f(10 * -cols, 10 * i, 0) glVertex3f(10 * -cols, 10 * i, 0)
glVertex3f(10 * cols, 10 * i, 0) glVertex3f(10 * cols, 10 * i, 0)
for i in xrange(-cols, cols + 1): for i in range(-cols, cols + 1):
if i % 5 == 0: if i % 5 == 0:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1))
else: else:
...@@ -872,7 +872,7 @@ class TestGlPanel(GLPanel): ...@@ -872,7 +872,7 @@ class TestGlPanel(GLPanel):
glHint (GL_LINE_SMOOTH_HINT, GL_NICEST) glHint (GL_LINE_SMOOTH_HINT, GL_NICEST)
glLineWidth (1.5) glLineWidth (1.5)
for i in self.parent.models.values(): for i in list(self.parent.models.values()):
glPushMatrix() glPushMatrix()
glTranslatef(*(i.offsets)) glTranslatef(*(i.offsets))
glRotatef(i.rot, 0.0, 0.0, 1.0) glRotatef(i.rot, 0.0, 0.0, 1.0)
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
import wx, random import wx, random
from bufferedcanvas import * 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.'''
...@@ -110,7 +110,7 @@ class Graph(BufferedCanvas): ...@@ -110,7 +110,7 @@ class Graph(BufferedCanvas):
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(str(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)
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
try: try:
import wx import wx
except: except:
print _("WX is not installed. This program requires WX to run.") print(_("WX is not installed. This program requires WX to run."))
raise raise
global buttonSize global buttonSize
...@@ -88,13 +88,13 @@ class LeftPane(wx.GridBagSizer): ...@@ -88,13 +88,13 @@ class LeftPane(wx.GridBagSizer):
root.monitorbox.Bind(wx.EVT_CHECKBOX, root.setmonitor) root.monitorbox.Bind(wx.EVT_CHECKBOX, root.setmonitor)
self.Add(wx.StaticText(root.panel,-1, _("Heat:")), pos = (2, 0), span = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT) self.Add(wx.StaticText(root.panel,-1, _("Heat:")), pos = (2, 0), span = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
htemp_choices = [root.temps[i]+" ("+i+")" for i in sorted(root.temps.keys(), key = lambda x:root.temps[x])] htemp_choices = [root.temps[i]+" ("+i+")" for i in sorted(list(root.temps.keys()), key = lambda x:root.temps[x])]
root.settoff = make_button(root.panel, _("Off"), lambda e: root.do_settemp("off"), _("Switch Hotend Off"), size = (36,-1), style = wx.BU_EXACTFIT) root.settoff = make_button(root.panel, _("Off"), lambda e: root.do_settemp("off"), _("Switch Hotend Off"), size = (36,-1), style = wx.BU_EXACTFIT)
root.printerControls.append(root.settoff) root.printerControls.append(root.settoff)
self.Add(root.settoff, pos = (2, 1), span = (1, 1)) self.Add(root.settoff, pos = (2, 1), span = (1, 1))
if root.settings.last_temperature not in map(float, root.temps.values()): if root.settings.last_temperature not in list(map(float, list(root.temps.values()))):
htemp_choices = [str(root.settings.last_temperature)] + htemp_choices htemp_choices = [str(root.settings.last_temperature)] + htemp_choices
root.htemp = wx.ComboBox(root.panel, -1, root.htemp = wx.ComboBox(root.panel, -1,
choices = htemp_choices, style = wx.CB_DROPDOWN, size = (70,-1)) choices = htemp_choices, style = wx.CB_DROPDOWN, size = (70,-1))
...@@ -107,13 +107,13 @@ class LeftPane(wx.GridBagSizer): ...@@ -107,13 +107,13 @@ class LeftPane(wx.GridBagSizer):
self.Add(root.settbtn, pos = (2, 4), span = (1, 1)) self.Add(root.settbtn, pos = (2, 4), span = (1, 1))
self.Add(wx.StaticText(root.panel,-1, _("Bed:")), pos = (3, 0), span = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT) self.Add(wx.StaticText(root.panel,-1, _("Bed:")), pos = (3, 0), span = (1, 1), flag = wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT)
btemp_choices = [root.bedtemps[i]+" ("+i+")" for i in sorted(root.bedtemps.keys(), key = lambda x:root.temps[x])] btemp_choices = [root.bedtemps[i]+" ("+i+")" for i in sorted(list(root.bedtemps.keys()), key = lambda x:root.temps[x])]
root.setboff = make_button(root.panel, _("Off"), lambda e:root.do_bedtemp("off"), _("Switch Heated Bed Off"), size = (36,-1), style = wx.BU_EXACTFIT) root.setboff = make_button(root.panel, _("Off"), lambda e:root.do_bedtemp("off"), _("Switch Heated Bed Off"), size = (36,-1), style = wx.BU_EXACTFIT)
root.printerControls.append(root.setboff) root.printerControls.append(root.setboff)
self.Add(root.setboff, pos = (3, 1), span = (1, 1)) self.Add(root.setboff, pos = (3, 1), span = (1, 1))
if root.settings.last_bed_temperature not in map(float, root.bedtemps.values()): if root.settings.last_bed_temperature not in list(map(float, list(root.bedtemps.values()))):
btemp_choices = [str(root.settings.last_bed_temperature)] + btemp_choices btemp_choices = [str(root.settings.last_bed_temperature)] + btemp_choices
root.btemp = wx.ComboBox(root.panel, -1, root.btemp = wx.ComboBox(root.panel, -1,
choices = btemp_choices, style = wx.CB_DROPDOWN, size = (70,-1)) choices = btemp_choices, style = wx.CB_DROPDOWN, size = (70,-1))
...@@ -207,7 +207,7 @@ class LogPane(wx.BoxSizer): ...@@ -207,7 +207,7 @@ class LogPane(wx.BoxSizer):
root.commandbox.SetToolTip(wx.ToolTip("Send commands to printer\n(Type 'help' for simple\nhelp function)")) root.commandbox.SetToolTip(wx.ToolTip("Send commands to printer\n(Type 'help' for simple\nhelp function)"))
root.commandbox.Bind(wx.EVT_TEXT_ENTER, root.sendline) root.commandbox.Bind(wx.EVT_TEXT_ENTER, root.sendline)
root.commandbox.Bind(wx.EVT_CHAR, root.cbkey) root.commandbox.Bind(wx.EVT_CHAR, root.cbkey)
root.commandbox.history = [u""] root.commandbox.history = [""]
root.commandbox.histindex = 1 root.commandbox.histindex = 1
#root.printerControls.append(root.commandbox) #root.printerControls.append(root.commandbox)
lbrs.Add(root.commandbox, 1) lbrs.Add(root.commandbox, 1)
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
import wx, time import wx, time
from printrun import gcoder from printrun import gcoder
from printrun_utils import imagefile from .printrun_utils import imagefile
ID_ABOUT = 101 ID_ABOUT = 101
ID_EXIT = 110 ID_EXIT = 110
...@@ -149,7 +149,7 @@ class gviz(wx.Panel): ...@@ -149,7 +149,7 @@ class gviz(wx.Panel):
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 range(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 = []
...@@ -159,8 +159,8 @@ class gviz(wx.Panel): ...@@ -159,8 +159,8 @@ class gviz(wx.Panel):
def inject(self): def inject(self):
#import pdb; pdb.set_trace() #import pdb; pdb.set_trace()
print"Inject code here..." print("Inject code here...")
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]
...@@ -233,9 +233,9 @@ class gviz(wx.Panel): ...@@ -233,9 +233,9 @@ class gviz(wx.Panel):
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 range(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 range(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:
...@@ -251,7 +251,7 @@ class gviz(wx.Panel): ...@@ -251,7 +251,7 @@ class gviz(wx.Panel):
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 = list(map(_scaler, lines))
dc.DrawLineList(scaled_lines, pens) dc.DrawLineList(scaled_lines, pens)
def _drawarcs(arcs, pens): def _drawarcs(arcs, pens):
...@@ -262,7 +262,7 @@ class gviz(wx.Panel): ...@@ -262,7 +262,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 = list(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)
...@@ -275,8 +275,8 @@ class gviz(wx.Panel): ...@@ -275,8 +275,8 @@ class gviz(wx.Panel):
_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 list(self.lines.keys()):
for layer_i in xrange(max(0, self.layerindex-6), self.layerindex): for layer_i in range(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])
......
...@@ -20,11 +20,11 @@ import gettext ...@@ -20,11 +20,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')
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')
else: else:
gettext.install(domain, './locale', unicode = 1) gettext.install(domain, './locale')
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']:
......
...@@ -55,7 +55,7 @@ class dispframe(wx.Frame): ...@@ -55,7 +55,7 @@ class dispframe(wx.Frame):
if self.slicer == 'Skeinforge': if self.slicer == 'Skeinforge':
for i in image: for i in image:
#print i #print i
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")] points = [wx.Point(*[int(round(float(x) * self.scale)) for x in j.strip().split()]) for j in i.strip().split("M")[1].split("L")]
dc.DrawPolygon(points, self.size[0] / 2, self.size[1] / 2) dc.DrawPolygon(points, self.size[0] / 2, self.size[1] / 2)
elif self.slicer == 'Slic3r': elif self.slicer == 'Slic3r':
gc = wx.GraphicsContext_Create(dc) gc = wx.GraphicsContext_Create(dc)
...@@ -90,12 +90,12 @@ class dispframe(wx.Frame): ...@@ -90,12 +90,12 @@ class dispframe(wx.Frame):
if self.index < len(self.layers): if self.index < len(self.layers):
i = self.index i = self.index
print i print(i)
wx.CallAfter(self.showimgdelay, self.layers[i]) wx.CallAfter(self.showimgdelay, self.layers[i])
wx.FutureCall(1000 * self.interval, self.pic.Hide) wx.FutureCall(1000 * self.interval, self.pic.Hide)
self.index += 1 self.index += 1
else: else:
print "end" print("end")
wx.CallAfter(self.pic.Hide) wx.CallAfter(self.pic.Hide)
wx.CallAfter(self.Refresh) wx.CallAfter(self.Refresh)
wx.CallAfter(self.ShowFullScreen, 0) wx.CallAfter(self.ShowFullScreen, 0)
...@@ -228,8 +228,8 @@ class setframe(wx.Frame): ...@@ -228,8 +228,8 @@ class setframe(wx.Frame):
layers = self.parsesvg(name) layers = self.parsesvg(name)
layerHeight = layers[1] layerHeight = layers[1]
self.thickness.SetValue(str(layers[1])) self.thickness.SetValue(str(layers[1]))
print "Layer thickness detected:", layerHeight, "mm" print("Layer thickness detected:", layerHeight, "mm")
print len(layers[0]), "layers found, total height", layerHeight * len(layers[0]), "mm" print(len(layers[0]), "layers found, total height", layerHeight * len(layers[0]), "mm")
self.layers = layers self.layers = layers
self.f.slicer = layers[2] self.f.slicer = layers[2]
dlg.Destroy() dlg.Destroy()
......
...@@ -146,7 +146,7 @@ class options(wx.Dialog): ...@@ -146,7 +146,7 @@ class options(wx.Dialog):
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 list(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()
...@@ -185,9 +185,9 @@ class ButtonEdit(wx.Dialog): ...@@ -185,9 +185,9 @@ class ButtonEdit(wx.Dialog):
try: try:
if macro == "": if macro == "":
valid = True valid = True
elif self.pronterface.macros.has_key(macro): elif macro in self.pronterface.macros:
valid = True valid = True
elif hasattr(self.pronterface.__class__, u"do_"+macro): elif hasattr(self.pronterface.__class__, "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
...@@ -196,7 +196,7 @@ class ButtonEdit(wx.Dialog): ...@@ -196,7 +196,7 @@ class ButtonEdit(wx.Dialog):
except: except:
if macro == "": if macro == "":
valid = True valid = True
elif self.pronterface.macros.has_key(macro): elif macro in self.pronterface.macros:
valid = True valid = True
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
......
...@@ -22,10 +22,10 @@ def genfacet(v): ...@@ -22,10 +22,10 @@ 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([x*x for x in vecx]))
if vlen == 0: if vlen == 0:
vlen = 1 vlen = 1
normal = map(lambda x:x/vlen, vecx) normal = [x/vlen for x in vecx]
return [normal, v] return [normal, v]
I = [ I = [
...@@ -36,16 +36,16 @@ I = [ ...@@ -36,16 +36,16 @@ I = [
] ]
def transpose(matrix): def transpose(matrix):
return zip(*matrix) return list(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 list(map(sum, transpose([[x[0]*p for p in x[1]] for x in 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([multmatrix(x+[1], matrix)[:3] for x in 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 = [
...@@ -104,7 +104,7 @@ class stl: ...@@ -104,7 +104,7 @@ class stl:
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):
...@@ -114,7 +114,7 @@ class stl: ...@@ -114,7 +114,7 @@ class stl:
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 range(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))
...@@ -126,8 +126,8 @@ class stl: ...@@ -126,8 +126,8 @@ class stl:
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([x[2] for x in facet[1]]), facet)]
self.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])), facet)] self.facetsmaxz+=[(max([x[2] for x in facet[1]]), facet)]
f.close() f.close()
return return
for i in self.f: for i in self.f:
...@@ -187,8 +187,8 @@ class stl: ...@@ -187,8 +187,8 @@ class stl:
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([x[2] for x in facet[1]]), facet)]
s.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])), facet)] s.facetsmaxz+=[(max([x[2] for x in facet[1]]), facet)]
return s return s
def export(self, f = sys.stdout): def export(self, f = sys.stdout):
...@@ -218,21 +218,21 @@ class stl: ...@@ -218,21 +218,21 @@ class stl:
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]=list(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([x[2] for x in facet[1]]), facet)]
self.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])), facet)] self.facetsmaxz+=[(max([x[2] for x in 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]=list(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 range(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):
...@@ -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")
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
import os import os
import math import math
import stltool from . import stltool
import wx import wx
from wx import glcanvas from wx import glcanvas
import time import time
...@@ -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 = list(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,
...@@ -244,7 +244,7 @@ class gcview(object): ...@@ -244,7 +244,7 @@ class gcview(object):
t0 = time.time() t0 = time.time()
lines = [self.transform(i) for i in lines] lines = [self.transform(i) for i in lines]
lines = [i for i in lines if i is not None] lines = [i for i in lines if i is not None]
print "transformed lines in %fs" % (time.time() - t0) print("transformed lines in %fs" % (time.time() - t0))
t0 = time.time() t0 = time.time()
layertemp = {} layertemp = {}
lasth = None lasth = None
...@@ -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 = list(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,
...@@ -277,26 +277,26 @@ class gcview(object): ...@@ -277,26 +277,26 @@ class gcview(object):
epoints[j], epoints[j],
spoints[(j + 1) % 8], spoints[(j + 1) % 8],
epoints[(j + 1) % 8] epoints[(j + 1) % 8]
] for j in xrange(8)] ] for j in range(8)]
normalstoadd = [map(vdiff, v, [S, E, S, E, S, E]) for v in verticestoadd] normalstoadd = [list(map(vdiff, v, [S, E, S, E, S, E])) for v in verticestoadd]
v1 = [] v1 = []
map(v1.extend, verticestoadd) list(map(v1.extend, verticestoadd))
v2 = [] v2 = []
map(v2.extend, v1) list(map(v2.extend, v1))
n1 = [] n1 = []
map(n1.extend, normalstoadd) list(map(n1.extend, normalstoadd))
n2 = [] n2 = []
map(n2.extend, n1) list(map(n2.extend, n1))
layertemp[i[0][2]][0] += v2 layertemp[i[0][2]][0] += v2
vertices += v2 vertices += v2
layertemp[i[0][2]][1] += n2 layertemp[i[0][2]][1] += n2
normals += n2 normals += n2
print "appended lines in %fs" % (time.time() - t0) print("appended lines in %fs" % (time.time() - t0))
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 = list(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 = list(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,
...@@ -316,8 +316,8 @@ class gcview(object): ...@@ -316,8 +316,8 @@ class gcview(object):
def genline(self, i, h, w): def genline(self, i, h, w):
S = i[0][:3] S = i[0][:3]
E = i[1][:3] E = i[1][:3]
v = map(lambda x, y: x - y, E, S) v = list(map(lambda x, y: x - y, E, S))
vlen = math.sqrt(float(sum(map(lambda a: a * a, v[:3])))) vlen = math.sqrt(float(sum([a * a for a in v[:3]])))
if vlen == 0: if vlen == 0:
vlen = 0.01 vlen = 0.01
...@@ -336,23 +336,23 @@ class gcview(object): ...@@ -336,23 +336,23 @@ class gcview(object):
[sq2 * d, -sq2 * d, 0] [sq2 * d, -sq2 * d, 0]
] ]
axis = stltool.cross([0, 0, 1], v) axis = stltool.cross([0, 0, 1], v)
alen = math.sqrt(float(sum(map(lambda a: a * a, v[:3])))) alen = math.sqrt(float(sum([a * a for a in v[:3]])))
if alen > 0: if alen > 0:
axis = map(lambda m: m / alen, axis) axis = [m / alen for m in axis]
angle = math.acos(v[2] / vlen) angle = math.acos(v[2] / vlen)
def vrot(v, axis, angle): def vrot(v, axis, angle):
kxv = stltool.cross(axis, v) kxv = stltool.cross(axis, v)
kdv = sum(map(lambda x, y: x * y, axis, v)) kdv = sum(map(lambda x, y: x * y, axis, v))
return map(lambda x, y, z: x * math.cos(angle) + y * math.sin(angle) + z * kdv * (1.0 - math.cos(angle)), v, kxv, axis) return list(map(lambda x, y, z: x * math.cos(angle) + y * math.sin(angle) + z * kdv * (1.0 - math.cos(angle)), v, kxv, axis))
points = map(lambda x: vrot(x, axis, angle), points) points = [vrot(x, axis, angle) for x in points]
points = map(lambda x: [x[0], x[1], htw * x[2]], points) points = [[x[0], x[1], htw * x[2]] for x in points]
def vadd(v, o): def vadd(v, o):
return map(sum, zip(v, o)) return list(map(sum, list(zip(v, o))))
spoints = map(lambda x: vadd(S, x), points) spoints = [vadd(S, x) for x in points]
epoints = map(lambda x: vadd(E, x), points) epoints = [vadd(E, x) for x in points]
return spoints, epoints, S, E return spoints, epoints, S, E
def transform(self, line): def transform(self, line):
...@@ -399,8 +399,8 @@ def trackball(p1x, p1y, p2x, p2y, r): ...@@ -399,8 +399,8 @@ def trackball(p1x, p1y, p2x, p2y, r):
p2 = [p2x, p2y, project_to_sphere(TRACKBALLSIZE, p2x, p2y)] p2 = [p2x, p2y, project_to_sphere(TRACKBALLSIZE, p2x, p2y)]
a = stltool.cross(p2, p1) a = stltool.cross(p2, p1)
d = map(lambda x, y: x - y, p1, p2) d = list(map(lambda x, y: x - y, p1, p2))
t = math.sqrt(sum(map(lambda x: x * x, d))) / (2.0 * TRACKBALLSIZE) t = math.sqrt(sum([x * x for x in d])) / (2.0 * TRACKBALLSIZE)
if (t > 1.0): if (t > 1.0):
t = 1.0 t = 1.0
...@@ -417,9 +417,9 @@ def vec(*args): ...@@ -417,9 +417,9 @@ def vec(*args):
def axis_to_quat(a, phi): def axis_to_quat(a, phi):
#print a, phi #print a, phi
lena = math.sqrt(sum(map(lambda x: x * x, a))) lena = math.sqrt(sum([x * x for x in a]))
q = map(lambda x: x * (1 / lena), a) q = [x * (1 / lena) for x in a]
q = map(lambda x: x * math.sin(phi / 2.0), q) q = [x * math.sin(phi / 2.0) for x in q]
q.append(math.cos(phi / 2.0)) q.append(math.cos(phi / 2.0))
return q return q
...@@ -486,11 +486,11 @@ class TestGlPanel(GLPanel): ...@@ -486,11 +486,11 @@ class TestGlPanel(GLPanel):
def double(self, event): def double(self, event):
p = event.GetPositionTuple() p = event.GetPositionTuple()
sz = self.GetClientSize() sz = self.GetClientSize()
v = map(lambda m, w, b: b * m / w, p, sz, self.bedsize) v = list(map(lambda m, w, b: b * m / w, p, sz, self.bedsize))
v[1] = self.bedsize[1] - v[1] v[1] = self.bedsize[1] - v[1]
v += [300] v += [300]
print "Double-click at "+str(v)+" in " print("Double-click at "+str(v)+" in ")
print self print(self)
def forceresize(self): def forceresize(self):
self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1)) self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1))
...@@ -581,7 +581,7 @@ class TestGlPanel(GLPanel): ...@@ -581,7 +581,7 @@ class TestGlPanel(GLPanel):
p1[1] *= -1 p1[1] *= -1
p2[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 = list(map(lambda x, y, z, c: c - self.dist * (x - y) / z, list(p1) + [0], list(p2) + [0], list(sz) + [1], self.transv))
glLoadIdentity() glLoadIdentity()
glTranslatef(self.transv[0], self.transv[1], 0) glTranslatef(self.transv[0], self.transv[1], 0)
...@@ -595,7 +595,7 @@ class TestGlPanel(GLPanel): ...@@ -595,7 +595,7 @@ class TestGlPanel(GLPanel):
#mouse is moving without a button press #mouse is moving without a button press
p = event.GetPositionTuple() p = event.GetPositionTuple()
sz = self.GetClientSize() sz = self.GetClientSize()
v = map(lambda m, w, b: b * m / w, p, sz, self.bedsize) v = list(map(lambda m, w, b: b * m / w, p, sz, self.bedsize))
v[1] = self.bedsize[1] - v[1] v[1] = self.bedsize[1] - v[1]
self.mousepos = v self.mousepos = v
...@@ -647,7 +647,7 @@ class TestGlPanel(GLPanel): ...@@ -647,7 +647,7 @@ class TestGlPanel(GLPanel):
def keypress(self, event): def keypress(self, event):
"""gets keypress events and moves/rotates acive shape""" """gets keypress events and moves/rotates acive shape"""
keycode = event.GetKeyCode() keycode = event.GetKeyCode()
print keycode print(keycode)
step = 5 step = 5
angle = 18 angle = 18
if event.ControlDown(): if event.ControlDown():
...@@ -742,14 +742,14 @@ class TestGlPanel(GLPanel): ...@@ -742,14 +742,14 @@ class TestGlPanel(GLPanel):
rows = 10 rows = 10
cols = 10 cols = 10
zheight = 50 zheight = 50
for i in xrange(-rows, rows + 1): for i in range(-rows, rows + 1):
if i % 5 == 0: if i % 5 == 0:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1))
else: else:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.2, 0.2, 0.2, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.2, 0.2, 0.2, 1))
glVertex3f(10 * -cols, 10 * i, 0) glVertex3f(10 * -cols, 10 * i, 0)
glVertex3f(10 * cols, 10 * i, 0) glVertex3f(10 * cols, 10 * i, 0)
for i in xrange(-cols, cols + 1): for i in range(-cols, cols + 1):
if i % 5 == 0: if i % 5 == 0:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1))
else: else:
...@@ -794,7 +794,7 @@ class TestGlPanel(GLPanel): ...@@ -794,7 +794,7 @@ class TestGlPanel(GLPanel):
glPushMatrix() glPushMatrix()
glTranslatef(-100, -100, 0) glTranslatef(-100, -100, 0)
for i in self.parent.models.values(): for i in list(self.parent.models.values()):
glPushMatrix() glPushMatrix()
glTranslatef(*(i.offsets)) glTranslatef(*(i.offsets))
glRotatef(i.rot, 0.0, 0.0, 1.0) glRotatef(i.rot, 0.0, 0.0, 1.0)
...@@ -803,7 +803,7 @@ class TestGlPanel(GLPanel): ...@@ -803,7 +803,7 @@ class TestGlPanel(GLPanel):
try: try:
if i.curlayer in i.gc.layers: if i.curlayer in i.gc.layers:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.13, 0.37, 0.25, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.13, 0.37, 0.25, 1))
[i.gc.layers[j].draw() for j in i.gc.layers.keys() if j < i.curlayer] [i.gc.layers[j].draw() for j in list(i.gc.layers.keys()) if j < i.curlayer]
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.5, 0.6, 0.9, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.5, 0.6, 0.9, 1))
b = i.gc.layers[i.curlayer] b = i.gc.layers[i.curlayer]
b.draw() b.draw()
...@@ -879,4 +879,4 @@ def main(): ...@@ -879,4 +879,4 @@ def main():
if __name__ == "__main__": if __name__ == "__main__":
import cProfile import cProfile
print cProfile.run("main()") print(cProfile.run("main()"))
...@@ -16,12 +16,12 @@ ...@@ -16,12 +16,12 @@
""" """
Parsers for specific attributes Parsers for specific attributes
""" """
import urlparse import urllib.parse
from pyparsing import (Literal, from pyparsing import (Literal,
Optional, oneOf, Group, StringEnd, Combine, Word, alphas, hexnums, Optional, oneOf, Group, StringEnd, Combine, Word, alphas, hexnums,
CaselessLiteral, SkipTo CaselessLiteral, SkipTo
) )
from css.colour import colourValue from .css.colour import colourValue
import string import string
##Paint values ##Paint values
...@@ -30,7 +30,7 @@ currentColor = CaselessLiteral("currentColor").setParseAction(lambda t: ["CURREN ...@@ -30,7 +30,7 @@ currentColor = CaselessLiteral("currentColor").setParseAction(lambda t: ["CURREN
def parsePossibleURL(t): def parsePossibleURL(t):
possibleURL, fallback = t[0] possibleURL, fallback = t[0]
return [urlparse.urlsplit(possibleURL), fallback] return [urllib.parse.urlsplit(possibleURL), fallback]
#Normal color declaration #Normal color declaration
colorDeclaration = none | currentColor | colourValue colorDeclaration = none | currentColor | colourValue
......
...@@ -13,6 +13,6 @@ ...@@ -13,6 +13,6 @@
# 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/>.
from __future__ import absolute_import
from .transform import transformList from .transform import transformList
from .inline import inlineStyle from .inline import inlineStyle
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
""" """
import wx import wx
import string import string
import urlparse import urllib.parse
from pyparsing import nums, Literal, Optional, oneOf, Group, StringEnd, Combine, Word, alphas, hexnums from pyparsing import nums, Literal, Optional, oneOf, Group, StringEnd, Combine, Word, alphas, hexnums
from ..pathdata import number, sign from ..pathdata import number, sign
...@@ -294,5 +294,5 @@ def fillCSS2SystemColours(): ...@@ -294,5 +294,5 @@ def fillCSS2SystemColours():
} }
NamedColours.update( NamedColours.update(
#strip the alpha from the system colors. Is this really what we want to do? #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() (k.lower(), wx.SystemSettings.GetColour(v)[:3]) for (k,v) in systemColors.items()
) )
...@@ -27,11 +27,11 @@ class White(White): ...@@ -27,11 +27,11 @@ class White(White):
escaped = ( escaped = (
Literal("\\").suppress() + Literal("\\").suppress() +
#chr(20)-chr(126) + chr(128)-unichr(sys.maxunicode) #chr(20)-chr(126) + chr(128)-unichr(sys.maxunicode)
Regex(u"[\u0020-\u007e\u0080-\uffff]", re.IGNORECASE) Regex("[\u0020-\u007e\u0080-\uffff]", re.IGNORECASE)
) )
def convertToUnicode(t): def convertToUnicode(t):
return unichr(int(t[0], 16)) return chr(int(t[0], 16))
hex_unicode = ( hex_unicode = (
Literal("\\").suppress() + Literal("\\").suppress() +
Regex("[0-9a-f]{1,6}", re.IGNORECASE) + Regex("[0-9a-f]{1,6}", re.IGNORECASE) +
...@@ -42,11 +42,11 @@ hex_unicode = ( ...@@ -42,11 +42,11 @@ hex_unicode = (
escape = hex_unicode | escaped escape = hex_unicode | escaped
#any unicode literal outside the 0-127 ascii range #any unicode literal outside the 0-127 ascii range
nonascii = Regex(u"[^\u0000-\u007f]") nonascii = Regex("[^\u0000-\u007f]")
#single character for starting an identifier. #single character for starting an identifier.
nmstart = Regex(u"[A-Z]", re.IGNORECASE) | nonascii | escape nmstart = Regex("[A-Z]", re.IGNORECASE) | nonascii | escape
nmchar = Regex(u"[0-9A-Z-]", re.IGNORECASE) | nonascii | escape nmchar = Regex("[0-9A-Z-]", re.IGNORECASE) | nonascii | escape
identifier = Combine(nmstart + ZeroOrMore(nmchar)) identifier = Combine(nmstart + ZeroOrMore(nmchar))
...@@ -18,16 +18,16 @@ ...@@ -18,16 +18,16 @@
""" """
import wx import wx
from cStringIO import StringIO from io import StringIO
import warnings import warnings
import math import math
from functools import wraps from functools import wraps
import pathdata from . import pathdata
import css from . import css
from svg.css.colour import colourValue 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"
...@@ -60,7 +60,7 @@ def valueToPixels(val, defaultUnits = "px"): ...@@ -60,7 +60,7 @@ def valueToPixels(val, defaultUnits = "px"):
try: try:
val, unit = values.length.parseString(val) val, unit = values.length.parseString(val)
except ParseException: except ParseException:
print "***", val print("***", val)
raise raise
#todo: unit conversion to something other than pixels #todo: unit conversion to something other than pixels
return val return val
...@@ -128,7 +128,7 @@ class SVGDocument(object): ...@@ -128,7 +128,7 @@ class SVGDocument(object):
""" """
#copy the current state #copy the current state
current = dict(self.state) current = dict(self.state)
current.update(element.items()) current.update(list(element.items()))
current.update(css.inlineStyle(element.get("style", ""))) current.update(css.inlineStyle(element.get("style", "")))
self.stateStack.append(current) self.stateStack.append(current)
handler = self.handlers.get(element.tag, lambda *any: (None, None)) handler = self.handlers.get(element.tag, lambda *any: (None, None))
...@@ -389,10 +389,10 @@ class SVGDocument(object): ...@@ -389,10 +389,10 @@ class SVGDocument(object):
else: else:
arguments = iter(arguments) arguments = iter(arguments)
if command == 'm': if command == 'm':
yield (command, arguments.next()) yield (command, next(arguments))
command = "l" command = "l"
elif command == "M": elif command == "M":
yield (command, arguments.next()) yield (command, next(arguments))
command = "L" command = "L"
for arg in arguments: for arg in arguments:
yield (command, arg) yield (command, arg)
...@@ -574,9 +574,9 @@ class SVGDocument(object): ...@@ -574,9 +574,9 @@ class SVGDocument(object):
path.AddLineToPoint(normalizePoint(arg)) path.AddLineToPoint(normalizePoint(arg))
elif type == 'C': elif type == 'C':
#control1, control2, endpoint = arg #control1, control2, endpoint = arg
control1, control2, endpoint = map( control1, control2, endpoint = list(map(
normalizePoint, arg normalizePoint, arg
) ))
self.lastControl = control2 self.lastControl = control2
path.AddCurveToPoint( path.AddCurveToPoint(
control1, control1,
...@@ -592,9 +592,9 @@ class SVGDocument(object): ...@@ -592,9 +592,9 @@ class SVGDocument(object):
elif type == 'S': elif type == 'S':
#control2, endpoint = arg #control2, endpoint = arg
control2, endpoint = map( control2, endpoint = list(map(
normalizePoint, arg normalizePoint, arg
) ))
if self.lastControl: if self.lastControl:
control1 = reflectPoint(self.lastControl, path.GetCurrentPoint()) control1 = reflectPoint(self.lastControl, path.GetCurrentPoint())
else: else:
...@@ -607,7 +607,7 @@ class SVGDocument(object): ...@@ -607,7 +607,7 @@ class SVGDocument(object):
endpoint endpoint
) )
elif type == "Q": elif type == "Q":
(cx, cy), (x, y) = map(normalizePoint, arg) (cx, cy), (x, y) = list(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":
......
...@@ -14,8 +14,8 @@ ...@@ -14,8 +14,8 @@
# along with Printrun. If not, see <http://www.gnu.org/licenses/>. # along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import wx, os, math import wx, os, math
from bufferedcanvas import * from .bufferedcanvas import *
from printrun_utils import * from .printrun_utils import *
def sign(n): def sign(n):
if n < 0: return -1 if n < 0: return -1
...@@ -138,7 +138,7 @@ class XYButtons(BufferedCanvas): ...@@ -138,7 +138,7 @@ class XYButtons(BufferedCanvas):
return (quadrant, idx) return (quadrant, idx)
def mouseOverKeypad(self, mpos): def mouseOverKeypad(self, mpos):
for idx, kpos in XYButtons.keypad_positions.items(): for idx, kpos in list(XYButtons.keypad_positions.items()):
radius = self.distanceToPoint(mpos[0], mpos[1], kpos[0], kpos[1]) radius = self.distanceToPoint(mpos[0], mpos[1], kpos[0], kpos[1])
if radius < 9: if radius < 9:
return idx return idx
...@@ -247,7 +247,7 @@ class XYButtons(BufferedCanvas): ...@@ -247,7 +247,7 @@ class XYButtons(BufferedCanvas):
# 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 list(XYButtons.label_overlay_positions.items()):
if idx != self.concentric: if idx != self.concentric:
r = kpos[2] r = kpos[2]
gc.DrawEllipse(kpos[0]-r, kpos[1]-r, r*2, r*2) gc.DrawEllipse(kpos[0]-r, kpos[1]-r, r*2, r*2)
......
...@@ -14,8 +14,8 @@ ...@@ -14,8 +14,8 @@
# along with Printrun. If not, see <http://www.gnu.org/licenses/>. # along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import wx, os, math import wx, os, math
from bufferedcanvas import * from .bufferedcanvas import *
from printrun_utils import * from .printrun_utils import *
def sign(n): def sign(n):
if n < 0: return -1 if n < 0: return -1
...@@ -108,7 +108,7 @@ class ZButtons(BufferedCanvas): ...@@ -108,7 +108,7 @@ class ZButtons(BufferedCanvas):
# 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 list(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)
......
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
# 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):
...@@ -24,7 +24,7 @@ def genscape(data = [[0, 1, 0, 0],[1, 0, 2, 0],[1, 0, 0, 0],[0, 1, 0, 1]], pscal ...@@ -24,7 +24,7 @@ def genscape(data = [[0, 1, 0, 0],[1, 0, 2, 0],[1, 0, 0, 0],[0, 1, 0, 1]], pscal
#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(list(range(datal+1))[:-1], list(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]]]]
...@@ -35,7 +35,7 @@ def genscape(data = [[0, 1, 0, 0],[1, 0, 2, 0],[1, 0, 0, 0],[0, 1, 0, 1]], pscal ...@@ -35,7 +35,7 @@ def genscape(data = [[0, 1, 0, 0],[1, 0, 2, 0],[1, 0, 0, 0],[0, 1, 0, 1]], pscal
#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(list(range(datah+1))[:-1], list(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]]]]
...@@ -45,8 +45,8 @@ def genscape(data = [[0, 1, 0, 0],[1, 0, 2, 0],[1, 0, 0, 0],[0, 1, 0, 1]], pscal ...@@ -45,8 +45,8 @@ def genscape(data = [[0, 1, 0, 0],[1, 0, 2, 0],[1, 0, 0, 0],[0, 1, 0, 1]], pscal
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 range(datah-1):
for j in xrange(datal-1): for j in range(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]
...@@ -55,10 +55,10 @@ def genscape(data = [[0, 1, 0, 0],[1, 0, 2, 0],[1, 0, 0, 0],[0, 1, 0, 1]], pscal ...@@ -55,10 +55,10 @@ def genscape(data = [[0, 1, 0, 0],[1, 0, 2, 0],[1, 0, 0, 0],[0, 1, 0, 1]], pscal
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(list(map(ord, i.GetData()[::3]))))
b = map(ord, i.GetData()[::3]) b = list(map(ord, i.GetData()[::3]))
data = [] data = []
for i in xrange(s[0]): for i in range(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)
......
...@@ -21,7 +21,7 @@ import pronsole ...@@ -21,7 +21,7 @@ import pronsole
from server import basic_auth from server import basic_auth
import random import random
import textwrap import textwrap
import SocketServer import socketserver
import socket import socket
import mdns import mdns
import uuid import uuid
...@@ -133,21 +133,21 @@ class ConstructSocketHandler(tornado.websocket.WebSocketHandler): ...@@ -133,21 +133,21 @@ class ConstructSocketHandler(tornado.websocket.WebSocketHandler):
def open(self): def open(self):
pronserve.listeners.add(self) pronserve.listeners.add(self)
self.write_message({'connected': {'jobs': pronserve.jobs.public_list()}}) self.write_message({'connected': {'jobs': pronserve.jobs.public_list()}})
print "WebSocket opened. %i sockets currently open." % len(pronserve.listeners) print("WebSocket opened. %i sockets currently open." % len(pronserve.listeners))
def send(self, dict_args = {}, **kwargs): def send(self, dict_args = {}, **kwargs):
args = dict(dict_args.items() + kwargs.items()) args = dict(list(dict_args.items()) + list(kwargs.items()))
args['timestamp']= time.time() args['timestamp']= time.time()
self.write_message(args) self.write_message(args)
def on_message(self, msg): def on_message(self, msg):
print "message received: %s"%(msg) print("message received: %s"%(msg))
# TODO: the read bit of repl! # TODO: the read bit of repl!
# self.write_message("You said: " + msg) # self.write_message("You said: " + msg)
def on_close(self): def on_close(self):
pronserve.listeners.remove(self) pronserve.listeners.remove(self)
print "WebSocket closed. %i sockets currently open." % len(pronserve.listeners) print("WebSocket closed. %i sockets currently open." % len(pronserve.listeners))
dir = os.path.dirname(__file__) dir = os.path.dirname(__file__)
settings = dict( settings = dict(
...@@ -226,12 +226,12 @@ class Pronserve(pronsole.pronsole, EventEmitter): ...@@ -226,12 +226,12 @@ class Pronserve(pronsole.pronsole, EventEmitter):
self.update_job_progress(100) self.update_job_progress(100)
self.fire("job_finished", self.jobs.sanitize(self.current_job)) self.fire("job_finished", self.jobs.sanitize(self.current_job))
if len(self.jobs.list) > 0: if len(self.jobs.list) > 0:
print "Starting the next print job" print("Starting the next print job")
self.current_job = self.jobs.list.popleft() self.current_job = self.jobs.list.popleft()
self.p.startprint(self.current_job['body'].split("\n")) self.p.startprint(self.current_job['body'].split("\n"))
self.fire("job_started", self.jobs.sanitize(self.current_job)) self.fire("job_started", self.jobs.sanitize(self.current_job))
else: else:
print "Finished all print jobs" print("Finished all print jobs")
self.current_job = None self.current_job = None
self.printing_jobs = False self.printing_jobs = False
...@@ -273,12 +273,12 @@ class Pronserve(pronsole.pronsole, EventEmitter): ...@@ -273,12 +273,12 @@ class Pronserve(pronsole.pronsole, EventEmitter):
def _receive_sensor_update(self, l): def _receive_sensor_update(self, l):
words = filter(lambda s: s.find(":") > 0, l.split(" ")) words = [s for s in l.split(" ") if s.find(":") > 0]
d = dict([ s.split(":") for s in words]) d = dict([ s.split(":") for s in words])
# print "sensor update received!" # print "sensor update received!"
for key, value in d.iteritems(): for key, value in d.items():
self.__update_sensor(key, value) self.__update_sensor(key, value)
self.fire("sensor_changed") self.fire("sensor_changed")
...@@ -295,7 +295,7 @@ class Pronserve(pronsole.pronsole, EventEmitter): ...@@ -295,7 +295,7 @@ class Pronserve(pronsole.pronsole, EventEmitter):
def log(self, *msg): def log(self, *msg):
msg = ''.join(str(i) for i in msg) msg = ''.join(str(i) for i in msg)
msg.replace("\r", "") msg.replace("\r", "")
print msg print(msg)
self.fire("log", {'msg': msg, 'level': "debug"}) self.fire("log", {'msg': msg, 'level': "debug"})
def write_prompt(self): def write_prompt(self):
...@@ -338,14 +338,14 @@ class PrintJobQueue(EventEmitter): ...@@ -338,14 +338,14 @@ class PrintJobQueue(EventEmitter):
self.__last_id += 1 self.__last_id += 1
self.list.append(job) self.list.append(job)
print "Added %s"%(original_file_name) print("Added %s"%(original_file_name))
self.fire("job_added", job) self.fire("job_added", job)
def display_summary(self): def display_summary(self):
print "Print Jobs:" print("Print Jobs:")
for job in self.list: for job in self.list:
print " %i: %s"%(job['id'], job['original_file_name']) print(" %i: %s"%(job['id'], job['original_file_name']))
print "" print("")
return True return True
def remove(self, job_id): def remove(self, job_id):
...@@ -353,7 +353,7 @@ class PrintJobQueue(EventEmitter): ...@@ -353,7 +353,7 @@ class PrintJobQueue(EventEmitter):
if job == None: if job == None:
return False return False
self.list.remove(job) self.list.remove(job)
print "Print Job Removed" print("Print Job Removed")
self.fire("job_removed", job) self.fire("job_removed", job)
def update(self, job_id, job_attrs): def update(self, job_id, job_attrs):
...@@ -362,7 +362,7 @@ class PrintJobQueue(EventEmitter): ...@@ -362,7 +362,7 @@ class PrintJobQueue(EventEmitter):
return False return False
job['rank'] = job_attrs['position'] job['rank'] = job_attrs['position']
self.order() self.order()
print "Print Job Updated" print("Print Job Updated")
self.fire("job_updated", job) self.fire("job_updated", job)
def find_by_id(self, job_id): def find_by_id(self, job_id):
...@@ -379,7 +379,7 @@ class PrintJobQueue(EventEmitter): ...@@ -379,7 +379,7 @@ class PrintJobQueue(EventEmitter):
# Server Start Up # Server Start Up
# ------------------------------------------------- # -------------------------------------------------
print "Pronserve is starting..." print("Pronserve is starting...")
pronserve = Pronserve() pronserve = Pronserve()
pronserve.do_connect("") pronserve.do_connect("")
...@@ -389,13 +389,13 @@ pronserve.run_print_queue_loop() ...@@ -389,13 +389,13 @@ pronserve.run_print_queue_loop()
if __name__ == "__main__": if __name__ == "__main__":
application.listen(8888) application.listen(8888)
print "\n"+"-"*80 print("\n"+"-"*80)
welcome = textwrap.dedent(u""" welcome = textwrap.dedent("""
+---+ \x1B[0;32mPronserve: Your printer just got a whole lot better.\x1B[0m +---+ \x1B[0;32mPronserve: Your printer just got a whole lot better.\x1B[0m
| \u2713 | Ready to print. | \u2713 | Ready to print.
+---+ More details at http://localhost:8888/""") +---+ More details at http://localhost:8888/""")
sys.stdout.write(welcome) sys.stdout.write(welcome)
print "\n\n" + "-"*80 + "\n" print("\n\n" + "-"*80 + "\n")
try: try:
pronserve.ioloop.start() pronserve.ioloop.start()
......
...@@ -28,7 +28,7 @@ install_locale('pronterface') ...@@ -28,7 +28,7 @@ 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
...@@ -45,7 +45,7 @@ def dosify(name): ...@@ -45,7 +45,7 @@ def dosify(name):
return os.path.split(name)[1].split(".")[0][:8]+".g" return os.path.split(name)[1].split(".")[0][:8]+".g"
def confirm(): def confirm():
y_or_n = raw_input("y/n: ") y_or_n = input("y/n: ")
if y_or_n == "y": if y_or_n == "y":
return True return True
elif y_or_n != "n": elif y_or_n != "n":
...@@ -97,12 +97,12 @@ class Settings: ...@@ -97,12 +97,12 @@ class Settings:
except AttributeError: except AttributeError:
pass pass
try: try:
return getattr(self, "_%s_alias"%key)().keys() return list(getattr(self, "_%s_alias"%key)().keys())
except AttributeError: except AttributeError:
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 list(self.__dict__.keys()) if not k.startswith("_")])
class Status: class Status:
...@@ -186,7 +186,7 @@ class pronsole(cmd.Cmd): ...@@ -186,7 +186,7 @@ class pronsole(cmd.Cmd):
"online" : "%(bold)sT:%(extruder_temp_fancy)s %(progress_fancy)s >%(normal)s "} "online" : "%(bold)sT:%(extruder_temp_fancy)s %(progress_fancy)s >%(normal)s "}
def log(self, *msg): def log(self, *msg):
print ''.join(str(i) for i in msg) print(''.join(str(i) for i in msg))
def promptf(self): def promptf(self):
"""A function to generate prompts so that we can do dynamic prompts. """ """A function to generate prompts so that we can do dynamic prompts. """
...@@ -248,10 +248,10 @@ class pronsole(cmd.Cmd): ...@@ -248,10 +248,10 @@ class pronsole(cmd.Cmd):
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
...@@ -277,7 +277,7 @@ class pronsole(cmd.Cmd): ...@@ -277,7 +277,7 @@ class pronsole(cmd.Cmd):
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 list(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:
...@@ -294,7 +294,7 @@ class pronsole(cmd.Cmd): ...@@ -294,7 +294,7 @@ class pronsole(cmd.Cmd):
self.cur_macro_def += l + "\n" self.cur_macro_def += l + "\n"
def end_macro(self): def end_macro(self):
if self.__dict__.has_key("onecmd"): del self.onecmd # remove override if "onecmd" in self.__dict__: del self.onecmd # remove override
self.in_macro = False self.in_macro = False
self.prompt = self.promptf() self.prompt = self.promptf()
if self.cur_macro_def!="": if self.cur_macro_def!="":
...@@ -339,7 +339,7 @@ class pronsole(cmd.Cmd): ...@@ -339,7 +339,7 @@ class pronsole(cmd.Cmd):
lines = macro_def.split("\n") lines = macro_def.split("\n")
for l in lines: for l in lines:
pycode += self.compile_macro_line(l) pycode += self.compile_macro_line(l)
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):
...@@ -352,7 +352,7 @@ class pronsole(cmd.Cmd): ...@@ -352,7 +352,7 @@ class pronsole(cmd.Cmd):
self.prompt = self.promptf() self.prompt = self.promptf()
def delete_macro(self, macro_name): def delete_macro(self, macro_name):
if macro_name in self.macros.keys(): if macro_name in list(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]
self.log("Macro '"+macro_name+"' removed") self.log("Macro '"+macro_name+"' removed")
...@@ -362,7 +362,7 @@ class pronsole(cmd.Cmd): ...@@ -362,7 +362,7 @@ class pronsole(cmd.Cmd):
self.log("Macro '"+macro_name+"' is not defined") self.log("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", list(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]
...@@ -381,7 +381,7 @@ class pronsole(cmd.Cmd): ...@@ -381,7 +381,7 @@ class pronsole(cmd.Cmd):
self.cur_macro_name = macro_name self.cur_macro_name = macro_name
self.end_macro() self.end_macro()
return return
if self.macros.has_key(macro_name): if macro_name in self.macros:
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)
...@@ -396,7 +396,7 @@ class pronsole(cmd.Cmd): ...@@ -396,7 +396,7 @@ class pronsole(cmd.Cmd):
self.log("'macro' without arguments displays list of defined macros") self.log("'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 list(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:
self.log("Macro '"+macro_name+"' defined as:") self.log("Macro '"+macro_name+"' defined as:")
...@@ -414,7 +414,7 @@ class pronsole(cmd.Cmd): ...@@ -414,7 +414,7 @@ class pronsole(cmd.Cmd):
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:
self.log("Unknown variable '%s'" % var) self.log("Unknown variable '%s'" % var)
except ValueError, ve: except ValueError as ve:
self.log("Bad value for variable '%s', expecting %s (%s)" % (var, repr(t)[1:-1], ve.args[0])) self.log("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):
...@@ -520,7 +520,7 @@ class pronsole(cmd.Cmd): ...@@ -520,7 +520,7 @@ class pronsole(cmd.Cmd):
# self.log("Saved '"+key+"' to '"+self.rc_filename+"'") # self.log("Saved '"+key+"' to '"+self.rc_filename+"'")
#else: #else:
# self.log("Removed '"+key+"' from '"+self.rc_filename+"'") # self.log("Removed '"+key+"' from '"+self.rc_filename+"'")
except Exception, e: except Exception as e:
self.log("Saving failed for ", key+":", str(e)) self.log("Saving failed for ", key+":", str(e))
finally: finally:
del rci, rco del rci, rco
...@@ -826,7 +826,7 @@ class pronsole(cmd.Cmd): ...@@ -826,7 +826,7 @@ class pronsole(cmd.Cmd):
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):
if tstring[:5] == "echo:": if tstring[:5] == "echo:":
tstring = tstring[5:].lstrip() tstring = tstring[5:].lstrip()
if self.silent == False: print "\r" + tstring.ljust(15) if self.silent == False: print("\r" + tstring.ljust(15))
sys.stdout.write(self.promptf()) sys.stdout.write(self.promptf())
sys.stdout.flush() sys.stdout.flush()
for i in self.recvlisteners: for i in self.recvlisteners:
...@@ -870,10 +870,10 @@ class pronsole(cmd.Cmd): ...@@ -870,10 +870,10 @@ class pronsole(cmd.Cmd):
self.p.send_now("M105") self.p.send_now("M105")
time.sleep(0.75) time.sleep(0.75)
if not self.status.bed_enabled: if not self.status.bed_enabled:
print "Hotend: %s/%s" % (self.status.extruder_temp, self.status.extruder_temp_target) print("Hotend: %s/%s" % (self.status.extruder_temp, self.status.extruder_temp_target))
else: else:
print "Hotend: %s/%s" % (self.status.extruder_temp, self.status.extruder_temp_target) print("Hotend: %s/%s" % (self.status.extruder_temp, self.status.extruder_temp_target))
print "Bed: %s/%s" % (self.status.bed_temp, self.status.bed_temp_target) print("Bed: %s/%s" % (self.status.bed_temp, self.status.bed_temp_target))
def help_gettemp(self): def help_gettemp(self):
self.log("Read the extruder and bed temperature.") self.log("Read the extruder and bed temperature.")
...@@ -881,12 +881,12 @@ class pronsole(cmd.Cmd): ...@@ -881,12 +881,12 @@ class pronsole(cmd.Cmd):
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 list(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 f > 250: if f > 250:
print f, " is a high temperature to set your extruder to. Are you sure you want to do that?" print(f, " is a high temperature to set your extruder to. Are you sure you want to do that?")
if not confirm(): if not confirm():
return return
if self.p.online: if self.p.online:
...@@ -902,16 +902,16 @@ class pronsole(cmd.Cmd): ...@@ -902,16 +902,16 @@ class pronsole(cmd.Cmd):
def help_settemp(self): def help_settemp(self):
self.log("Sets the hotend temperature to the value entered.") self.log("Sets the hotend temperature to the value entered.")
self.log("Enter either a temperature in celsius or one of the following keywords") self.log("Enter either a temperature in celsius or one of the following keywords")
self.log(", ".join([i+"("+self.temps[i]+")" for i in self.temps.keys()])) self.log(", ".join([i+"("+self.temps[i]+")" for i in list(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 list(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 list(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:
...@@ -928,11 +928,11 @@ class pronsole(cmd.Cmd): ...@@ -928,11 +928,11 @@ class pronsole(cmd.Cmd):
def help_bedtemp(self): def help_bedtemp(self):
self.log("Sets the bed temperature to the value entered.") self.log("Sets the bed temperature to the value entered.")
self.log("Enter either a temperature in celsius or one of the following keywords") self.log("Enter either a temperature in celsius or one of the following keywords")
self.log(", ".join([i+"("+self.bedtemps[i]+")" for i in self.bedtemps.keys()])) self.log(", ".join([i+"("+self.bedtemps[i]+")" for i in list(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 list(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):
...@@ -1066,17 +1066,17 @@ class pronsole(cmd.Cmd): ...@@ -1066,17 +1066,17 @@ class pronsole(cmd.Cmd):
def do_exit(self, l): def do_exit(self, l):
if self.status.extruder_temp_target != 0: if self.status.extruder_temp_target != 0:
print "Setting extruder temp to 0" print("Setting extruder temp to 0")
self.p.send_now("M104 S0.0") self.p.send_now("M104 S0.0")
if self.status.bed_enabled: if self.status.bed_enabled:
if self.status.bed_temp_taret != 0: if self.status.bed_temp_taret != 0:
print "Setting bed temp to 0" print("Setting bed temp to 0")
self.p.send_now("M140 S0.0") self.p.send_now("M140 S0.0")
self.log("Disconnecting from printer...") self.log("Disconnecting from printer...")
print self.p.printing print(self.p.printing)
if self.p.printing: if self.p.printing:
print "Are you sure you want to exit while printing?" print("Are you sure you want to exit while printing?")
print "(this will terminate the print)." print("(this will terminate the print).")
if not confirm(): if not confirm():
return False return False
self.log("Exiting program. Goodbye!") self.log("Exiting program. Goodbye!")
...@@ -1123,7 +1123,7 @@ class pronsole(cmd.Cmd): ...@@ -1123,7 +1123,7 @@ class pronsole(cmd.Cmd):
sys.stdout.flush() sys.stdout.flush()
prev_msg_len = len(prev_msg) prev_msg_len = len(prev_msg)
except KeyboardInterrupt: except KeyboardInterrupt:
if self.silent == False: print "Done monitoring." if self.silent == False: print("Done monitoring.")
self.monitoring = 0 self.monitoring = 0
def help_monitor(self): def help_monitor(self):
...@@ -1160,7 +1160,7 @@ class pronsole(cmd.Cmd): ...@@ -1160,7 +1160,7 @@ class pronsole(cmd.Cmd):
subprocess.call(params) subprocess.call(params)
self.log("Loading sliced file.") self.log("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 as e:
self.log("Skeinforge execution failed: ", e) self.log("Skeinforge execution failed: ", e)
def complete_skein(self, text, line, begidx, endidx): def complete_skein(self, text, line, begidx, endidx):
...@@ -1256,14 +1256,14 @@ class pronsole(cmd.Cmd): ...@@ -1256,14 +1256,14 @@ class pronsole(cmd.Cmd):
else: else:
if self.use_rawinput: if self.use_rawinput:
try: try:
line = raw_input(self.prompt) line = input(self.prompt)
except EOFError: except EOFError:
print "" print("")
should_exit = self.do_exit("") should_exit = self.do_exit("")
if should_exit: if should_exit:
exit() exit()
except KeyboardInterrupt: except KeyboardInterrupt:
print "" print("")
line = "" line = ""
else: else:
self.stdout.write(self.prompt) self.stdout.write(self.prompt)
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
# 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 os, Queue, re import os, queue, re
from printrun.printrun_utils import install_locale from printrun.printrun_utils import install_locale
install_locale('pronterface') install_locale('pronterface')
...@@ -23,9 +23,9 @@ install_locale('pronterface') ...@@ -23,9 +23,9 @@ install_locale('pronterface')
try: try:
import wx import wx
except: except:
print _("WX is not installed. This program requires WX to run.") print(_("WX is not installed. This program requires WX to run."))
raise raise
import sys, glob, time, datetime, threading, traceback, cStringIO, subprocess import sys, glob, time, datetime, threading, traceback, io, subprocess
from printrun.pronterface_widgets import * from printrun.pronterface_widgets import *
from serial import SerialException from serial import SerialException
...@@ -37,7 +37,7 @@ layerindex = 0 ...@@ -37,7 +37,7 @@ layerindex = 0
if os.name == "nt": if os.name == "nt":
winsize = (800, 530) winsize = (800, 530)
try: try:
import _winreg import winreg
except: except:
pass pass
...@@ -120,7 +120,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -120,7 +120,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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)
self.cpbuttons = [ self.cpbuttons = [
SpecialButton(_("Motors off"), ("M84"), (250, 250, 250), None, 0, _("Switch all motors off")), SpecialButton(_("Motors off"), ("M84"), (250, 250, 250), None, 0, _("Switch all motors off")),
SpecialButton(_("Check temp"), ("M105"), (225, 200, 200), (2, 5), (1, 1), _("Check current hotend temperature")), SpecialButton(_("Check temp"), ("M105"), (225, 200, 200), (2, 5), (1, 1), _("Check current hotend temperature")),
...@@ -158,22 +158,22 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -158,22 +158,22 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.panel.SetBackgroundColour(self.settings.bgcolor) self.panel.SetBackgroundColour(self.settings.bgcolor)
customdict = {} customdict = {}
try: try:
execfile(configfile("custombtn.txt"), customdict) exec(compile(open(configfile("custombtn.txt")).read(), configfile("custombtn.txt"), 'exec'), customdict)
if len(customdict["btns"]): if len(customdict["btns"]):
if not len(self.custombuttons): if not len(self.custombuttons):
try: try:
self.custombuttons = customdict["btns"] self.custombuttons = customdict["btns"]
for n in xrange(len(self.custombuttons)): for n in range(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 as 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"))
print _("Ignoring custombtn.txt. Remove all current buttons to revert to custombtn.txt") print(_("Ignoring custombtn.txt. Remove all current buttons to revert to custombtn.txt"))
except: except:
pass pass
...@@ -200,13 +200,13 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -200,13 +200,13 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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_duration = int(time.time () - self.starttime + self.extra_print_time) print_duration = int(time.time () - self.starttime + self.extra_print_time)
print _("Print ended at: %(end_time)s and took %(duration)s") % {"end_time": format_time(time.time()), print(_("Print ended at: %(end_time)s and took %(duration)s") % {"end_time": format_time(time.time()),
"duration": format_duration(print_duration)} "duration": 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"))
...@@ -220,7 +220,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -220,7 +220,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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)
...@@ -277,7 +277,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -277,7 +277,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def do_extrude(self, l = ""): def do_extrude(self, l = ""):
try: try:
if not l.__class__ in (str, unicode) or not len(l): if not l.__class__ in (str, str) or not len(l):
l = str(self.edist.GetValue()) l = str(self.edist.GetValue())
pronsole.pronsole.do_extrude(self, l) pronsole.pronsole.do_extrude(self, l)
except: except:
...@@ -285,7 +285,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -285,7 +285,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def do_reverse(self, l = ""): def do_reverse(self, l = ""):
try: try:
if not l.__class__ in (str, unicode) or not len(l): if not l.__class__ in (str, str) 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:
...@@ -331,43 +331,43 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -331,43 +331,43 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def do_settemp(self, l = ""): def do_settemp(self, l = ""):
try: try:
if not l.__class__ in (str, unicode) or not len(l): if not l.__class__ in (str, str) or not len(l):
l = str(self.htemp.GetValue().split()[0]) l = str(self.htemp.GetValue().split()[0])
l = l.lower().replace(", ", ".") l = l.lower().replace(", ", ".")
for i in self.temps.keys(): for i in list(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)
print _("Setting hotend temperature to %f degrees Celsius.") % f print(_("Setting hotend temperature to %f degrees Celsius.") % f)
self.sethotendgui(f) self.sethotendgui(f)
else: else:
print _("Printer is not online.") print(_("Printer is not online."))
else: else:
print _("You cannot set negative temperatures. To turn the hotend off entirely, set its temperature to 0.") print(_("You cannot set negative temperatures. To turn the hotend off entirely, set its temperature to 0."))
except Exception, x: except Exception as x:
print _("You must enter a temperature. (%s)") % (repr(x),) print(_("You must enter a temperature. (%s)") % (repr(x),))
def do_bedtemp(self, l = ""): def do_bedtemp(self, l = ""):
try: try:
if not l.__class__ in (str, unicode) or not len(l): if not l.__class__ in (str, str) or not len(l):
l = str(self.btemp.GetValue().split()[0]) l = str(self.btemp.GetValue().split()[0])
l = l.lower().replace(", ", ".") l = l.lower().replace(", ", ".")
for i in self.bedtemps.keys(): for i in list(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)
print _("Setting bed temperature to %f degrees Celsius.") % f print(_("Setting bed temperature to %f degrees Celsius.") % f)
self.setbedgui(f) self.setbedgui(f)
else: else:
print _("Printer is not online.") print(_("Printer is not online."))
else: else:
print _("You cannot set negative temperatures. To turn the bed off entirely, set its temperature to 0.") print(_("You cannot set negative temperatures. To turn the bed off entirely, set its temperature to 0."))
except Exception, x: except Exception as x:
print _("You must enter a temperature. (%s)") % (repr(x),) print(_("You must enter a temperature. (%s)") % (repr(x),))
def end_macro(self): def end_macro(self):
pronsole.pronsole.end_macro(self) pronsole.pronsole.end_macro(self)
...@@ -386,7 +386,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -386,7 +386,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
if dialog.ShowModal() == wx.ID_YES: if dialog.ShowModal() == wx.ID_YES:
self.delete_macro(macro_name) self.delete_macro(macro_name)
return return
print _("Cancelled.") print(_("Cancelled."))
return return
self.cur_macro_name = macro_name self.cur_macro_name = macro_name
self.cur_macro_def = definition self.cur_macro_def = definition
...@@ -399,7 +399,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -399,7 +399,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
if self.capture_skip_newline and len(l) and not len(l.strip("\n\r")): if self.capture_skip_newline and len(l) and not len(l.strip("\n\r")):
self.capture_skip_newline = False self.capture_skip_newline = False
return return
for pat in self.capture_skip.keys(): for pat in list(self.capture_skip.keys()):
if self.capture_skip[pat] > 0 and pat.match(l): if self.capture_skip[pat] > 0 and pat.match(l):
self.capture_skip[pat] -= 1 self.capture_skip[pat] -= 1
self.capture_skip_newline = True self.capture_skip_newline = True
...@@ -411,10 +411,10 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -411,10 +411,10 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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 True: while True:
baselist += [_winreg.EnumValue(key, i)[1]] baselist += [winreg.EnumValue(key, i)[1]]
i += 1 i += 1
except: except:
pass pass
...@@ -425,7 +425,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -425,7 +425,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
if self.p.online: if self.p.online:
projectlayer.setframe(self,self.p).Show() projectlayer.setframe(self,self.p).Show()
else: else:
print _("Printer is not online.") print(_("Printer is not online."))
def popmenu(self): def popmenu(self):
self.menustrip = wx.MenuBar() self.menustrip = wx.MenuBar()
...@@ -498,13 +498,13 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -498,13 +498,13 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def edit_macro(self, macro): def edit_macro(self, macro):
if macro == "": return self.new_macro() if macro == "": return self.new_macro()
if self.macros.has_key(macro): if macro in self.macros:
old_def = self.macros[macro] old_def = self.macros[macro]
elif len([c for c in macro.encode("ascii", "replace") if not c.isalnum() and c != "_"]): elif len([c for c in macro.encode("ascii", "replace") if not c.isalnum() and c != "_"]):
print _("Macro name may contain only ASCII alphanumeric symbols and underscores") print(_("Macro name may contain only ASCII alphanumeric symbols and underscores"))
return return
elif hasattr(self.__class__, "do_"+macro): elif hasattr(self.__class__, "do_"+macro):
print _("Name '%s' is being used by built-in command") % macro print(_("Name '%s' is being used by built-in command") % macro)
return return
else: else:
old_def = "" old_def = ""
...@@ -521,7 +521,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -521,7 +521,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.macros_menu.DeleteItem(item) self.macros_menu.DeleteItem(item)
except: except:
pass pass
for macro in self.macros.keys(): for macro in list(self.macros.keys()):
self.Bind(wx.EVT_MENU, lambda x, m = macro: self.start_macro(m, self.macros[m]), self.macros_menu.Append(-1, macro)) self.Bind(wx.EVT_MENU, lambda x, m = macro: self.start_macro(m, self.macros[m]), self.macros_menu.Append(-1, macro))
def OnExit(self, event): def OnExit(self, event):
...@@ -562,11 +562,11 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -562,11 +562,11 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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):
...@@ -645,7 +645,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -645,7 +645,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
newbuttonbuttonindex -= 1 newbuttonbuttonindex -= 1
while len(self.custombuttons) < 13: while len(self.custombuttons) < 13:
self.custombuttons.append(None) self.custombuttons.append(None)
for i in xrange(len(self.custombuttons)): for i in range(len(self.custombuttons)):
btndef = self.custombuttons[i] btndef = self.custombuttons[i]
try: try:
b = wx.Button(self.panel, -1, btndef.label, style = wx.BU_EXACTFIT) b = wx.Button(self.panel, -1, btndef.label, style = wx.BU_EXACTFIT)
...@@ -682,7 +682,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -682,7 +682,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.mainsizer.Layout() self.mainsizer.Layout()
def help_button(self): def help_button(self):
print _('Defines custom button. Usage: button <num> "title" [/c "colour"] command') print(_('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):
...@@ -704,7 +704,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -704,7 +704,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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"))
return return
while num >= len(self.custombuttons): while num >= len(self.custombuttons):
self.custombuttons.append(None) self.custombuttons.append(None)
...@@ -723,10 +723,10 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -723,10 +723,10 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.save_in_rc(("button %d" % n),'') self.save_in_rc(("button %d" % n),'')
elif bdef.background: elif bdef.background:
colour = bdef.background colour = bdef.background
if type(colour) not in (str, unicode): if type(colour) not in (str, str):
#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 = [x%256 for x in 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)
...@@ -742,10 +742,10 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -742,10 +742,10 @@ class PronterWindow(MainWindow, pronsole.pronsole):
bedit.command.SetValue(button.properties.command) bedit.command.SetValue(button.properties.command)
if button.properties.background: if button.properties.background:
colour = button.properties.background colour = button.properties.background
if type(colour) not in (str, unicode): if type(colour) not in (str, str):
#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 = [x%256 for x in 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)
...@@ -969,7 +969,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -969,7 +969,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.onecmd(e.GetEventObject().properties.command) self.onecmd(e.GetEventObject().properties.command)
self.cur_button = None self.cur_button = None
except: except:
print _("event object missing") print(_("event object missing"))
self.cur_button = None self.cur_button = None
raise raise
...@@ -1000,12 +1000,12 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -1000,12 +1000,12 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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."))
self.setmonitor(None) self.setmonitor(None)
if self.monitor: if self.monitor:
print _("Monitoring printer.") print(_("Monitoring printer."))
else: else:
print _("Done monitoring.") print(_("Done monitoring."))
def setmonitor(self, e): def setmonitor(self, e):
self.monitor = self.monitorbox.GetValue() self.monitor = self.monitorbox.GetValue()
...@@ -1018,7 +1018,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -1018,7 +1018,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
try: try:
self.logbox.AppendText(text) self.logbox.AppendText(text)
except: except:
print _("Attempted to write invalid text to console, which could be due to an invalid baudrate") print(_("Attempted to write invalid text to console, which could be due to an invalid baudrate"))
def setloud(self,e): def setloud(self,e):
self.p.loud=e.IsChecked() self.p.loud=e.IsChecked()
...@@ -1090,7 +1090,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -1090,7 +1090,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
except: except:
pass pass
if cout is None: if cout is None:
cout = cStringIO.StringIO() cout = io.StringIO()
sys.stdout = cout sys.stdout = cout
retval = None retval = None
...@@ -1180,7 +1180,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -1180,7 +1180,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
try: try:
import shlex import shlex
param = self.expandcommand(self.settings.slicecommand).encode() param = self.expandcommand(self.settings.slicecommand).encode()
print "Slicing: ", param print("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)
...@@ -1191,7 +1191,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -1191,7 +1191,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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: "))
self.stopsf = 1 self.stopsf = 1
traceback.print_exc(file = sys.stdout) traceback.print_exc(file = sys.stdout)
...@@ -1224,7 +1224,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -1224,7 +1224,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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
...@@ -1283,11 +1283,11 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -1283,11 +1283,11 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def loadviz(self): def loadviz(self):
gcode = gcoder.GCode(self.f) gcode = gcoder.GCode(self.f)
gcode.measure() gcode.measure()
print gcode.filament_length(), _("mm of filament used in this print\n") print(gcode.filament_length(), _("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") % (gcode.xmin, gcode.xmax, gcode.width) print(_("the print goes from %f mm to %f mm in X\nand is %f mm wide\n") % (gcode.xmin, gcode.xmax, gcode.width))
print _("the print goes from %f mm to %f mm in Y\nand is %f mm wide\n") % (gcode.ymin, gcode.ymax, gcode.depth) print(_("the print goes from %f mm to %f mm in Y\nand is %f mm wide\n") % (gcode.ymin, gcode.ymax, gcode.depth))
print _("the print goes from %f mm to %f mm in Z\nand is %f mm high\n") % (gcode.zmin, gcode.zmax, gcode.height) print(_("the print goes from %f mm to %f mm in Z\nand is %f mm high\n") % (gcode.zmin, gcode.zmax, gcode.height))
print _("Estimated duration (pessimistic): "), gcode.estimate_duration() print(_("Estimated duration (pessimistic): "), gcode.estimate_duration())
#import time #import time
#t0 = time.time() #t0 = time.time()
self.gviz.clear() self.gviz.clear()
...@@ -1353,7 +1353,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -1353,7 +1353,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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:
self.p.send_now("M25") self.p.send_now("M25")
...@@ -1380,7 +1380,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -1380,7 +1380,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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]
...@@ -1406,12 +1406,12 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -1406,12 +1406,12 @@ class PronterWindow(MainWindow, pronsole.pronsole):
except SerialException as e: except SerialException as e:
# Currently, there is no errno, but it should be there in the future # Currently, there is no errno, but it should be there in the future
if e.errno == 2: if e.errno == 2:
print _("Error: You are trying to connect to a non-exisiting port.") print(_("Error: You are trying to connect to a non-exisiting port."))
elif e.errno == 8: elif e.errno == 8:
print _("Error: You don't have permission to open %s.") % port print(_("Error: You don't have permission to open %s.") % port)
print _("You might need to add yourself to the dialout group.") print(_("You might need to add yourself to the dialout group."))
else: else:
print e print(e)
# Kill the scope anyway # Kill the scope anyway
return return
self.statuscheck = True self.statuscheck = True
...@@ -1442,7 +1442,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -1442,7 +1442,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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()
self.p.disconnect() self.p.disconnect()
...@@ -1475,7 +1475,7 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -1475,7 +1475,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
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()
......
...@@ -57,7 +57,7 @@ def authenticate(realm, authenticator,user_extractor) : ...@@ -57,7 +57,7 @@ def authenticate(realm, authenticator,user_extractor) :
auth_decoded = base64.decodestring(auth_hdr[6:]) auth_decoded = base64.decodestring(auth_hdr[6:])
username, password = auth_decoded.split(':', 2) username, password = auth_decoded.split(':', 2)
user_info = authenticator(realm, unicode(username), password) user_info = authenticator(realm, str(username), password)
if user_info : if user_info :
self._user_info = user_info self._user_info = user_info
self._current_user = user_extractor(user_info) self._current_user = user_extractor(user_info)
...@@ -65,7 +65,7 @@ def authenticate(realm, authenticator,user_extractor) : ...@@ -65,7 +65,7 @@ def authenticate(realm, authenticator,user_extractor) :
str(self._user_info)) str(self._user_info))
else: else:
return _request_basic_auth(self) return _request_basic_auth(self)
except Exception, e: except Exception as e:
return _request_basic_auth(self) return _request_basic_auth(self)
return True return True
return wrapper return wrapper
...@@ -90,4 +90,4 @@ def interceptor(func): ...@@ -90,4 +90,4 @@ def interceptor(func):
return cls return cls
return classwrapper return classwrapper
print "moo" print("moo")
\ No newline at end of file \ No newline at end of file
...@@ -35,7 +35,7 @@ class install (_install): ...@@ -35,7 +35,7 @@ class install (_install):
if self.prefix: if self.prefix:
length += len (self.prefix) length += len (self.prefix)
if length: if length:
for counter in xrange (len (outputs)): for counter in range (len (outputs)):
outputs[counter] = outputs[counter][length:] outputs[counter] = outputs[counter][length:]
data = "\n".join (outputs) data = "\n".join (outputs)
try: try:
...@@ -56,7 +56,7 @@ class install_data (_install_data): ...@@ -56,7 +56,7 @@ class install_data (_install_data):
except: except:
self.warn ("Could not chmod data file %s" % file) self.warn ("Could not chmod data file %s" % file)
_install_data.run (self) _install_data.run (self)
map (chmod_data_file, self.get_outputs ()) list(map (chmod_data_file, self.get_outputs ()))
class uninstall (_install): class uninstall (_install):
...@@ -75,10 +75,10 @@ class uninstall (_install): ...@@ -75,10 +75,10 @@ class uninstall (_install):
if self.prefix: if self.prefix:
prepend += self.prefix prepend += self.prefix
if len (prepend): if len (prepend):
for counter in xrange (len (files)): for counter in range (len (files)):
files[counter] = prepend + files[counter].rstrip () files[counter] = prepend + files[counter].rstrip ()
for file in files: for file in files:
print "Uninstalling %s" % file print("Uninstalling %s" % file)
try: try:
os.unlink (file) os.unlink (file)
except: except:
...@@ -87,7 +87,7 @@ class uninstall (_install): ...@@ -87,7 +87,7 @@ class uninstall (_install):
ops = ("install", "build", "sdist", "uninstall", "clean") ops = ("install", "build", "sdist", "uninstall", "clean")
if len (sys.argv) < 2 or sys.argv[1] not in ops: if len (sys.argv) < 2 or sys.argv[1] not in ops:
print "Please specify operation : %s" % " | ".join (ops) print("Please specify operation : %s" % " | ".join (ops))
raise SystemExit raise SystemExit
prefix = None prefix = None
...@@ -126,14 +126,14 @@ for basedir, subdirs, files in os.walk("locale"): ...@@ -126,14 +126,14 @@ for basedir, subdirs, files in os.walk("locale"):
if not basedir.endswith("LC_MESSAGES"): if not basedir.endswith("LC_MESSAGES"):
continue continue
destpath = os.path.join("share", "pronterface", basedir) destpath = os.path.join("share", "pronterface", basedir)
files = filter(lambda x: x.endswith(".mo"), files) files = [x for x in files if x.endswith(".mo")]
files = map(lambda x: os.path.join(basedir, x), files) files = [os.path.join(basedir, x) for x in files]
data_files.append ((destpath, files)) data_files.append ((destpath, files))
extra_data_dirs = ["css"] extra_data_dirs = ["css"]
for extra_data_dir in extra_data_dirs: for extra_data_dir in extra_data_dirs:
for basedir, subdirs, files in os.walk(extra_data_dir): for basedir, subdirs, files in os.walk(extra_data_dir):
files = map(lambda x: os.path.join(basedir, x), files) files = [os.path.join(basedir, x) for x in files]
destpath = os.path.join("share", "pronterface", basedir) destpath = os.path.join("share", "pronterface", basedir)
data_files.append ((destpath, files)) data_files.append ((destpath, files))
......
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