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():
def print_status(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 @@
# Set up Internationalization using gettext
# 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
install_locale('plater')
......@@ -209,18 +209,18 @@ class showstl(wx.Window):
offset = [0, 0]
scale = 2
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(i * scale * 10, 0, i * scale * 10, 400)
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(i * scale * 50, 0, i * scale * 50, 400)
dc.SetBrush(wx.Brush(wx.Colour(128, 255, 128)))
dc.SetPen(wx.Pen(wx.Colour(128, 128, 128)))
t = time.time()
dcs = wx.MemoryDC()
for m in self.parent.models.values():
for m in list(self.parent.models.values()):
b = m.bitmap
#print b
im = b.ConvertToImage()
......@@ -288,7 +288,7 @@ class stlwin(wx.Frame):
#self.SetClientSize(size)
def autoplate(self, event):
print _("Autoplating")
print(_("Autoplating"))
separation = 2
bedsize = [200, 200, 100]
cursor = [0, 0, 0]
......@@ -316,7 +316,7 @@ class stlwin(wx.Frame):
max[1] = cursor[1] + x
cursor[0] += x + separation
if (cursor[1] + y) >= bedsize[1]:
print _("Bed full, sorry sir :(")
print(_("Bed full, sorry sir :("))
self.Refresh()
return
centreoffset = [(bedsize[0] - max[0]) / 2, (bedsize[1] - max[1]) / 2]
......@@ -378,7 +378,7 @@ class stlwin(wx.Frame):
def writefiles(self, name):
sf = open(name.replace(".", "_") + ".scad", "w")
facets = []
for i in self.models.values():
for i in list(self.models.values()):
r = i.rot
o = i.offsets
......@@ -390,7 +390,7 @@ class stlwin(wx.Frame):
facets += i.facets
sf.close()
stltool.emitstl(name, facets, "plater_export")
print _("wrote %s") % name
print(_("wrote %s") % name)
def right(self, event):
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
import time, getopt, sys
import platform, os
from GCodeAnalyzer import GCodeAnalyzer
from functools import reduce
def control_ttyhup(port, disable_hup):
"""Controls the HUPCL"""
......@@ -120,19 +121,19 @@ class printcore():
if self.recvcb:
try: self.recvcb(line)
except: pass
if self.loud: print "RECV: ", line.rstrip()
if self.loud: print("RECV: ", line.rstrip())
return line
except SelectError, e:
except SelectError as e:
if 'Bad file descriptor' in e.args[1]:
print "Can't read from printer (disconnected?)."
print("Can't read from printer (disconnected?).")
return None
else:
raise
except SerialException, e:
print "Can't read from printer (disconnected?)."
except SerialException as e:
print("Can't read from printer (disconnected?).")
return None
except OSError, e:
print "Can't read from printer (disconnected?)."
except OSError as e:
print("Can't read from printer (disconnected?).")
return None
def _listen_can_continue(self):
......@@ -201,7 +202,7 @@ class printcore():
self.clear = True
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):
"""Start a print, data is an array of gcode commands.
......@@ -312,7 +313,7 @@ class printcore():
time.sleep(0.001)
wait -= 1
else:
print "Not connected to printer."
print("Not connected to printer.")
def send_now(self, command, wait = 0):
"""Sends a command to the printer ahead of the command queue, without a checksum
......@@ -332,7 +333,7 @@ class printcore():
time.sleep(0.001)
wait -= 1
else:
print "Not connected to printer."
print("Not connected to printer.")
def _print(self):
if self.startcb:
......@@ -414,14 +415,14 @@ class printcore():
self.sent.append(command)
self.analyzer.Analyze(command) # run the command through the analyzer
if self.loud:
print "SENT: ", command
print("SENT: ", command)
if self.sendcb:
try: self.sendcb(command)
except: pass
try:
self.printer.write(str(command+"\n"))
except SerialException, e:
print "Can't write to printer (disconnected?)."
except SerialException as e:
print("Can't write to printer (disconnected?).")
if __name__ == '__main__':
baud = 115200
......@@ -430,13 +431,13 @@ if __name__ == '__main__':
try:
opts, args = getopt.getopt(sys.argv[1:], "h,b:,v,s",
["help", "baud", "verbose", "statusreport"])
except getopt.GetoptError, err:
print str(err)
except getopt.GetoptError as err:
print(str(err))
sys.exit(2)
for o, a in opts:
if o in ('-h', '--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)
if o in ('-b', '--baud'):
baud = int(a)
......@@ -448,9 +449,9 @@ if __name__ == '__main__':
if len (args) > 1:
port = args[-2]
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:
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)
p = printcore(port, baud)
p.loud = loud
......
......@@ -141,7 +141,7 @@ class SkeinforgeQuickEditDialog(wx.Dialog):
for setting in settings.getReadRepository(repo).preferences:
if setting.name == settingName:
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()
isDirty = True
if isDirty:
......
......@@ -38,7 +38,7 @@ def float_input(prompt=''):
import sys
f = None
while f == None:
s = raw_input(prompt)
s = input(prompt)
try:
f = float(s)
except ValueError:
......@@ -54,7 +54,7 @@ def wait(t, m=''):
sys.stdout.write(s)
sys.stdout.flush()
time.sleep(1.0/5)
print
print()
def w(s):
sys.stdout.write(s)
sys.stdout.flush()
......@@ -73,9 +73,9 @@ def heatup(p, temp, s = 0):
time.sleep(1.5)
f = True
curtemp = gettemp(p)
if curtemp: w(u"\rHeating extruder up.. %3d \xb0C"%curtemp)
if s: print
else: print "\nReady."
if curtemp: w("\rHeating extruder up.. %3d \xb0C"%curtemp)
if s: print()
else: print("\nReady.")
def gettemp(p):
try: p.logl
......@@ -87,14 +87,14 @@ def gettemp(p):
if 'T:' in line:
try:
setattr(p,'temp',int(line.split('T:')[1].split()[0]))
except: print line
except: print(line)
p.logl = len(p.log)
return p.temp
if not os.path.exists(port):
port = 0
#Parse options
help = u"""
help = """
%s [ -l DISTANCE ] [ -s STEPS ] [ -t TEMP ] [ -p PORT ]
-l --length Length of filament to extrude for each calibration step (default: %d mm)
-s --steps Initial amount of steps to use (default: %d steps)
......@@ -104,13 +104,13 @@ help = u"""
"""[1:-1].encode('utf-8')%(sys.argv[0], n, k, temp, tempmax, port if port else 'auto')
try:
opts, args = getopt.getopt(sys.argv[1:],"hl:s:t:p:",["help", "length=", "steps=", "temp=", "port="])
except getopt.GetoptError, err:
print str(err)
print help
except getopt.GetoptError as err:
print(str(err))
print(help)
sys.exit(2)
for o, a in opts:
if o in ('-h','--help'):
print help
print(help)
sys.exit()
elif o in ('-l','--length'):
n = float(a)
......@@ -119,17 +119,17 @@ for o, a in opts:
elif o in ('-t','--temp'):
temp = int(a)
if temp>=tempmax:
print (u'%d \xb0C? Are you insane?'.encode('utf-8')%temp)+(" That's over nine thousand!" if temp>9000 else '')
print(('%d \xb0C? Are you insane?'.encode('utf-8')%temp)+(" That's over nine thousand!" if temp>9000 else ''))
sys.exit(255)
elif o in ('-p','--port'):
port = a
#Show initial parameters
print "Initial parameters"
print "Steps per mm: %3d steps"%k
print "Length extruded: %3d mm"%n
print
print "Serial port: %s"%(port if port else 'auto')
print("Initial parameters")
print("Steps per mm: %3d steps"%k)
print("Length extruded: %3d mm"%n)
print()
print("Serial port: %s"%(port if port else 'auto'))
p = None
try:
......@@ -138,12 +138,12 @@ try:
try:
p = printcore(port, 115200)
except:
print 'Error.'
print('Error.')
raise
while not p.online:
time.sleep(1)
w('.')
print " connected."
print(" connected.")
heatup(p, temp)
......@@ -158,8 +158,8 @@ try:
if n!=m:
k = (n/m)*k
p.send_now("M92 E%d"%int(round(k))) #Set new step count
print "Steps per mm: %3d steps"%k #Tell user
print 'Calibration completed.' #Yay!
print("Steps per mm: %3d steps"%k) #Tell user
print('Calibration completed.') #Yay!
except KeyboardInterrupt:
pass
finally:
......
......@@ -190,7 +190,7 @@ class GCode(object):
old_lines += cur_lines
layers[prev_z] = old_lines
for idx in layers.keys():
for idx in list(layers.keys()):
cur_lines = layers[idx]
has_movement = False
for l in layers[idx]:
......@@ -215,7 +215,7 @@ class GCode(object):
ymax = 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()
xmin = min(xm, xmin)
xmax = max(xM, xmax)
......@@ -266,7 +266,7 @@ class GCode(object):
#TODO:
# get device caps from firmware: max speed, acceleration/axis (including extruder)
# calculate the maximum move duration accounting for above ;)
zs = self.layers.keys()
zs = list(self.layers.keys())
zs.sort()
for z in zs:
layer = self.layers[z]
......@@ -316,7 +316,7 @@ class GCode(object):
def main():
if len(sys.argv) < 2:
print "usage: %s filename.gcode" % sys.argv[0]
print("usage: %s filename.gcode" % sys.argv[0])
return
# d = [i.replace("\n","") for i in open(sys.argv[1])]
......@@ -325,13 +325,13 @@ def main():
gcode.measure()
print "Dimensions:"
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 "\tZ: %0.02f - %0.02f (%0.02f)" % (gcode.zmin,gcode.zmax,gcode.height)
print "Filament used: %0.02fmm" % gcode.filament_length()
print "Number of layers: %d" % gcode.num_layers()
print "Estimated duration (pessimistic): %s" % gcode.estimate_duration()
print("Dimensions:")
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("\tZ: %0.02f - %0.02f (%0.02f)" % (gcode.zmin,gcode.zmax,gcode.height))
print("Filament used: %0.02fmm" % gcode.filament_length())
print("Number of layers: %d" % gcode.num_layers())
print("Estimated duration (pessimistic): %s" % gcode.estimate_duration())
if __name__ == '__main__':
......
......@@ -26,7 +26,7 @@ pyglet.options['shadow_window'] = False
pyglet.options['debug_gl'] = False
from pyglet.gl import *
import stltool
from . import stltool
import threading
......@@ -258,7 +258,7 @@ class gcline(object):
self.calc_len()
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.y,
self.prev_gcline.z,
......@@ -338,18 +338,18 @@ class gcThreadRenderer(threading.Thread):
threading.Thread.__init__(self)
self.gcview = gcview
self.lines = lines
print "q init"
print("q init")
def run(self):
for line in self.lines:
layer_name = line.z
if line.z not in self.gcview.layers:
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.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()
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):
"""gcode visualiser
......@@ -358,7 +358,7 @@ class gcview(object):
def __init__(self, lines, batch, w = 0.5, h = 0.5):
if len(lines) == 0:
return
print "Loading %s lines" % (len(lines))
print("Loading %s lines" % (len(lines)))
#End pos of previous mode
self.prev = gcpoint()
# Correction for G92 moves
......@@ -369,7 +369,7 @@ class gcview(object):
lines = [self.transform(i) for i in lines]
lines = [i for i in lines if i is not None]
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.lower_limit = None
self.max_feedrate = 0
......@@ -472,8 +472,8 @@ def trackball(p1x, p1y, p2x, p2y, r):
p2 = [p2x, p2y, project_to_sphere(TRACKBALLSIZE, p2x, p2y)]
a = stltool.cross(p2, p1)
d = map(lambda x, y: x - y, p1, p2)
t = math.sqrt(sum(map(lambda x: x * x, d))) / (2.0 * TRACKBALLSIZE)
d = list(map(lambda x, y: x - y, p1, p2))
t = math.sqrt(sum([x * x for x in d])) / (2.0 * TRACKBALLSIZE)
if (t > 1.0):
t = 1.0
......@@ -490,9 +490,9 @@ def vec(*args):
def axis_to_quat(a, phi):
#print a, phi
lena = math.sqrt(sum(map(lambda x: x * x, a)))
q = map(lambda x: x * (1 / lena), a)
q = map(lambda x: x * math.sin(phi / 2.0), q)
lena = math.sqrt(sum([x * x for x in a]))
q = [x * (1 / lena) for x in a]
q = [x * math.sin(phi / 2.0) for x in q]
q.append(math.cos(phi / 2.0))
return q
......@@ -559,10 +559,10 @@ class TestGlPanel(GLPanel):
def double(self, event):
p = event.GetPositionTuple()
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 += [300]
print v
print(v)
self.add_file("../prusa/metric-prusa/x-end-idler.stl", v)
def forceresize(self):
......@@ -654,7 +654,7 @@ class TestGlPanel(GLPanel):
p1[1] *= -1
p2[1] *= -1
self.transv = map(lambda x, y, z, c: c - self.dist * (x - y) / z, list(p1) + [0], list(p2) + [0], list(sz) + [1], self.transv)
self.transv = 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()
glTranslatef(self.transv[0], self.transv[1], 0)
......@@ -668,7 +668,7 @@ class TestGlPanel(GLPanel):
#mouse is moving without a button press
p = event.GetPositionTuple()
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]
self.mousepos = v
......@@ -720,7 +720,7 @@ class TestGlPanel(GLPanel):
def keypress(self, event):
"""gets keypress events and moves/rotates acive shape"""
keycode = event.GetKeyCode()
print keycode
print(keycode)
step = 5
angle = 18
if event.ControlDown():
......@@ -815,14 +815,14 @@ class TestGlPanel(GLPanel):
rows = 10
cols = 10
zheight = 50
for i in xrange(-rows, rows + 1):
for i in range(-rows, rows + 1):
if i % 5 == 0:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1))
else:
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)
for i in xrange(-cols, cols + 1):
for i in range(-cols, cols + 1):
if i % 5 == 0:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1))
else:
......@@ -872,7 +872,7 @@ class TestGlPanel(GLPanel):
glHint (GL_LINE_SMOOTH_HINT, GL_NICEST)
glLineWidth (1.5)
for i in self.parent.models.values():
for i in list(self.parent.models.values()):
glPushMatrix()
glTranslatef(*(i.offsets))
glRotatef(i.rot, 0.0, 0.0, 1.0)
......
......@@ -17,7 +17,7 @@
import wx, random
from bufferedcanvas import *
from .bufferedcanvas import *
class Graph(BufferedCanvas):
'''A class to show a Graph with Pronterface.'''
......@@ -110,7 +110,7 @@ class Graph(BufferedCanvas):
for y in range(self.ybars):
y_pos = y*(float(self.height)/self.ybars)
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:
font = wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.BOLD)
......
......@@ -16,7 +16,7 @@
try:
import wx
except:
print _("WX is not installed. This program requires WX to run.")
print(_("WX is not installed. This program requires WX to run."))
raise
global buttonSize
......@@ -88,13 +88,13 @@ class LeftPane(wx.GridBagSizer):
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)
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.printerControls.append(root.settoff)
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
root.htemp = wx.ComboBox(root.panel, -1,
choices = htemp_choices, style = wx.CB_DROPDOWN, size = (70,-1))
......@@ -107,13 +107,13 @@ class LeftPane(wx.GridBagSizer):
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)
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.printerControls.append(root.setboff)
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
root.btemp = wx.ComboBox(root.panel, -1,
choices = btemp_choices, style = wx.CB_DROPDOWN, size = (70,-1))
......@@ -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.Bind(wx.EVT_TEXT_ENTER, root.sendline)
root.commandbox.Bind(wx.EVT_CHAR, root.cbkey)
root.commandbox.history = [u""]
root.commandbox.history = [""]
root.commandbox.histindex = 1
#root.printerControls.append(root.commandbox)
lbrs.Add(root.commandbox, 1)
......
......@@ -15,7 +15,7 @@
import wx, time
from printrun import gcoder
from printrun_utils import imagefile
from .printrun_utils import imagefile
ID_ABOUT = 101
ID_EXIT = 110
......@@ -149,7 +149,7 @@ class gviz(wx.Panel):
self.arcpen = wx.Pen(wx.Colour(255, 0, 0), penwidth)
self.travelpen = wx.Pen(wx.Colour(10, 80, 80), 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.showall = 0
self.hilight = []
......@@ -159,8 +159,8 @@ class gviz(wx.Panel):
def inject(self):
#import pdb; pdb.set_trace()
print"Inject code here..."
print "Layer "+str(self.layerindex +1)+" - Z = "+str(self.layers[self.layerindex])+" mm"
print("Inject code here...")
print("Layer "+str(self.layerindex +1)+" - Z = "+str(self.layers[self.layerindex])+" mm")
def clear(self):
self.lastpos = [0, 0, 0, 0, 0, 0, 0]
......@@ -233,9 +233,9 @@ class gviz(wx.Panel):
dc.SetPen(wx.Pen(wx.Colour(180, 180, 150)))
for grid_unit in self.grid:
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])
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.SetPen(wx.Pen(wx.Colour(0, 0, 0)))
if not self.showall:
......@@ -251,7 +251,7 @@ class gviz(wx.Panel):
self.scale[1]*x[1]+self.translate[1],
self.scale[0]*x[2]+self.translate[0],
self.scale[1]*x[3]+self.translate[1],)
scaled_lines = map(_scaler, lines)
scaled_lines = list(map(_scaler, lines))
dc.DrawLineList(scaled_lines, pens)
def _drawarcs(arcs, pens):
......@@ -262,7 +262,7 @@ class gviz(wx.Panel):
self.scale[1]*x[3]+self.translate[1],
self.scale[0]*x[4]+self.translate[0],
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)):
dc.SetPen(pens[i] if type(pens).__name__ == 'list' else pens)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
......@@ -275,8 +275,8 @@ class gviz(wx.Panel):
_drawlines(self.lines[i], self.pens[i])
_drawarcs(self.arcs[i], self.arcpens[i])
return
if self.layerindex<len(self.layers) and self.layers[self.layerindex] in self.lines.keys():
for layer_i in xrange(max(0, self.layerindex-6), self.layerindex):
if self.layerindex<len(self.layers) and self.layers[self.layerindex] in list(self.lines.keys()):
for layer_i in range(max(0, self.layerindex-6), self.layerindex):
#print i, self.layerindex, self.layerindex-i
_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])
......
......@@ -20,11 +20,11 @@ import gettext
# searching for installed locales on /usr/share; uses relative folder if not found (windows)
def install_locale(domain):
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'):
gettext.install(domain, '/usr/local/share/pronterface/locale', unicode = 1)
gettext.install(domain, '/usr/local/share/pronterface/locale')
else:
gettext.install(domain, './locale', unicode = 1)
gettext.install(domain, './locale')
def imagefile(filename):
for prefix in ['/usr/local/share/pronterface/images', '/usr/share/pronterface/images']:
......
......@@ -55,7 +55,7 @@ class dispframe(wx.Frame):
if self.slicer == 'Skeinforge':
for i in image:
#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)
elif self.slicer == 'Slic3r':
gc = wx.GraphicsContext_Create(dc)
......@@ -90,12 +90,12 @@ class dispframe(wx.Frame):
if self.index < len(self.layers):
i = self.index
print i
print(i)
wx.CallAfter(self.showimgdelay, self.layers[i])
wx.FutureCall(1000 * self.interval, self.pic.Hide)
self.index += 1
else:
print "end"
print("end")
wx.CallAfter(self.pic.Hide)
wx.CallAfter(self.Refresh)
wx.CallAfter(self.ShowFullScreen, 0)
......@@ -228,8 +228,8 @@ class setframe(wx.Frame):
layers = self.parsesvg(name)
layerHeight = layers[1]
self.thickness.SetValue(str(layers[1]))
print "Layer thickness detected:", layerHeight, "mm"
print len(layers[0]), "layers found, total height", layerHeight * len(layers[0]), "mm"
print("Layer thickness detected:", layerHeight, "mm")
print(len(layers[0]), "layers found, total height", layerHeight * len(layers[0]), "mm")
self.layers = layers
self.f.slicer = layers[2]
dlg.Destroy()
......
......@@ -146,7 +146,7 @@ class options(wx.Dialog):
topsizer.Layout()
topsizer.Fit(self)
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):
pronterface.set(k, str(ctrls[k, 1].GetValue()))
self.Destroy()
......@@ -185,9 +185,9 @@ class ButtonEdit(wx.Dialog):
try:
if macro == "":
valid = True
elif self.pronterface.macros.has_key(macro):
elif macro in self.pronterface.macros:
valid = True
elif hasattr(self.pronterface.__class__, u"do_"+macro):
elif hasattr(self.pronterface.__class__, "do_"+macro):
valid = False
elif len([c for c in macro if not c.isalnum() and c != "_"]):
valid = False
......@@ -196,7 +196,7 @@ class ButtonEdit(wx.Dialog):
except:
if macro == "":
valid = True
elif self.pronterface.macros.has_key(macro):
elif macro in self.pronterface.macros:
valid = True
elif len([c for c in macro if not c.isalnum() and c != "_"]):
valid = False
......
......@@ -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]]
vecb = [v[2][0]-v[1][0], v[2][1]-v[1][1], v[2][2]-v[1][2]]
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:
vlen = 1
normal = map(lambda x:x/vlen, vecx)
normal = [x/vlen for x in vecx]
return [normal, v]
I = [
......@@ -36,16 +36,16 @@ I = [
]
def transpose(matrix):
return zip(*matrix)
return list(zip(*matrix))
#return [[v[i] for v in matrix] for i in xrange(len(matrix[0]))]
def multmatrix(vector, matrix):
return map(sum, transpose(map(lambda x:[x[0]*p for p in x[1]], zip(vector, transpose(matrix)))))
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):
#return facet
#return [map(lambda x:-1.0*x, multmatrix(facet[0]+[1], matrix)[:3]), map(lambda x:multmatrix(x+[1], matrix)[:3], facet[1])]
return genfacet(map(lambda x:multmatrix(x+[1], matrix)[:3], facet[1]))
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]]]
m = [
......@@ -104,7 +104,7 @@ class stl:
return
self.f = list(open(filename))
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")
buf = f.read(84)
while(len(buf)<84):
......@@ -114,7 +114,7 @@ class stl:
buf+=newdata
facetcount = struct.unpack_from("<I", buf, 80)
facetformat = struct.Struct("<ffffffffffffH")
for i in xrange(facetcount[0]):
for i in range(facetcount[0]):
buf = f.read(50)
while(len(buf)<50):
newdata = f.read(50-len(buf))
......@@ -126,8 +126,8 @@ class stl:
self.facet = [fd[:3],[fd[3:6], fd[6:9], fd[9:12]]]
self.facets+=[self.facet]
facet = self.facet
self.facetsminz+=[(min(map(lambda x:x[2], facet[1])), facet)]
self.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])), facet)]
self.facetsminz+=[(min([x[2] for x in facet[1]]), facet)]
self.facetsmaxz+=[(max([x[2] for x in facet[1]]), facet)]
f.close()
return
for i in self.f:
......@@ -187,8 +187,8 @@ class stl:
s.facetloc = 0
s.name = self.name
for facet in s.facets:
s.facetsminz+=[(min(map(lambda x:x[2], facet[1])), facet)]
s.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])), facet)]
s.facetsminz+=[(min([x[2] for x in facet[1]]), facet)]
s.facetsmaxz+=[(max([x[2] for x in facet[1]]), facet)]
return s
def export(self, f = sys.stdout):
......@@ -218,21 +218,21 @@ class stl:
self.infacet = 11
self.facetloc = 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"):
self.infacet = 0
self.facets+=[self.facet]
facet = self.facet
self.facetsminz+=[(min(map(lambda x:x[2], facet[1])), facet)]
self.facetsmaxz+=[(max(map(lambda x:x[2], facet[1])), facet)]
self.facetsminz+=[(min([x[2] for x in facet[1]]), facet)]
self.facetsmaxz+=[(max([x[2] for x in facet[1]]), facet)]
elif l.startswith("vertex"):
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
return 1
if __name__ == "__main__":
s = stl("../../Downloads/frame-vertex-neo-foot-x4.stl")
for i in xrange(11, 11):
for i in range(11, 11):
working = s.facets[:]
for j in reversed(sorted(s.facetsminz)):
if(j[0]>i):
......@@ -245,6 +245,6 @@ if __name__ == "__main__":
else:
break
print i, len(working)
print(i, len(working))
emitstl("../../Downloads/frame-vertex-neo-foot-x4-a.stl", s.facets, "emitted_object")
#stl("../prusamendel/stl/mendelplate.stl")
......@@ -17,7 +17,7 @@
import os
import math
import stltool
from . import stltool
import wx
from wx import glcanvas
import time
......@@ -215,7 +215,7 @@ class stlview(object):
normals.extend(i[0])
# 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]
self.vertex_list = batch.add_indexed(len(vertices) // 3,
GL_TRIANGLES,
......@@ -244,7 +244,7 @@ class gcview(object):
t0 = time.time()
lines = [self.transform(i) for i in lines]
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()
layertemp = {}
lasth = None
......@@ -258,7 +258,7 @@ class gcview(object):
if lasth is not None:
self.layers[lasth] = pyglet.graphics.Batch()
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,
GL_TRIANGLES,
None, # group,
......@@ -277,26 +277,26 @@ class gcview(object):
epoints[j],
spoints[(j + 1) % 8],
epoints[(j + 1) % 8]
] for j in xrange(8)]
normalstoadd = [map(vdiff, v, [S, E, S, E, S, E]) for v in verticestoadd]
] for j in range(8)]
normalstoadd = [list(map(vdiff, v, [S, E, S, E, S, E])) for v in verticestoadd]
v1 = []
map(v1.extend, verticestoadd)
list(map(v1.extend, verticestoadd))
v2 = []
map(v2.extend, v1)
list(map(v2.extend, v1))
n1 = []
map(n1.extend, normalstoadd)
list(map(n1.extend, normalstoadd))
n2 = []
map(n2.extend, n1)
list(map(n2.extend, n1))
layertemp[i[0][2]][0] += v2
vertices += v2
layertemp[i[0][2]][1] += n2
normals += n2
print "appended lines in %fs" % (time.time() - t0)
print("appended lines in %fs" % (time.time() - t0))
t0 = time.time()
# 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,
GL_TRIANGLES,
None, # group,
......@@ -305,7 +305,7 @@ class gcview(object):
('n3f/static', normals)))
if lasth is not None:
self.layers[lasth] = pyglet.graphics.Batch()
indices = range(len(layertemp[lasth][0])) # [[3*i, 3*i+1, 3*i+2] for i in xrange(len(facets))]
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,
GL_TRIANGLES,
None, # group,
......@@ -316,8 +316,8 @@ class gcview(object):
def genline(self, i, h, w):
S = i[0][:3]
E = i[1][:3]
v = map(lambda x, y: x - y, E, S)
vlen = math.sqrt(float(sum(map(lambda a: a * a, v[:3]))))
v = list(map(lambda x, y: x - y, E, S))
vlen = math.sqrt(float(sum([a * a for a in v[:3]])))
if vlen == 0:
vlen = 0.01
......@@ -336,23 +336,23 @@ class gcview(object):
[sq2 * d, -sq2 * d, 0]
]
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:
axis = map(lambda m: m / alen, axis)
axis = [m / alen for m in axis]
angle = math.acos(v[2] / vlen)
def vrot(v, axis, angle):
kxv = stltool.cross(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 = map(lambda x: [x[0], x[1], htw * x[2]], points)
points = [vrot(x, axis, angle) for x in points]
points = [[x[0], x[1], htw * x[2]] for x in points]
def vadd(v, o):
return map(sum, zip(v, o))
spoints = map(lambda x: vadd(S, x), points)
epoints = map(lambda x: vadd(E, x), points)
return list(map(sum, list(zip(v, o))))
spoints = [vadd(S, x) for x in points]
epoints = [vadd(E, x) for x in points]
return spoints, epoints, S, E
def transform(self, line):
......@@ -399,8 +399,8 @@ def trackball(p1x, p1y, p2x, p2y, r):
p2 = [p2x, p2y, project_to_sphere(TRACKBALLSIZE, p2x, p2y)]
a = stltool.cross(p2, p1)
d = map(lambda x, y: x - y, p1, p2)
t = math.sqrt(sum(map(lambda x: x * x, d))) / (2.0 * TRACKBALLSIZE)
d = list(map(lambda x, y: x - y, p1, p2))
t = math.sqrt(sum([x * x for x in d])) / (2.0 * TRACKBALLSIZE)
if (t > 1.0):
t = 1.0
......@@ -417,9 +417,9 @@ def vec(*args):
def axis_to_quat(a, phi):
#print a, phi
lena = math.sqrt(sum(map(lambda x: x * x, a)))
q = map(lambda x: x * (1 / lena), a)
q = map(lambda x: x * math.sin(phi / 2.0), q)
lena = math.sqrt(sum([x * x for x in a]))
q = [x * (1 / lena) for x in a]
q = [x * math.sin(phi / 2.0) for x in q]
q.append(math.cos(phi / 2.0))
return q
......@@ -486,11 +486,11 @@ class TestGlPanel(GLPanel):
def double(self, event):
p = event.GetPositionTuple()
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 += [300]
print "Double-click at "+str(v)+" in "
print self
print("Double-click at "+str(v)+" in ")
print(self)
def forceresize(self):
self.SetClientSize((self.GetClientSize()[0], self.GetClientSize()[1] + 1))
......@@ -581,7 +581,7 @@ class TestGlPanel(GLPanel):
p1[1] *= -1
p2[1] *= -1
self.transv = map(lambda x, y, z, c: c - self.dist * (x - y) / z, list(p1) + [0], list(p2) + [0], list(sz) + [1], self.transv)
self.transv = 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()
glTranslatef(self.transv[0], self.transv[1], 0)
......@@ -595,7 +595,7 @@ class TestGlPanel(GLPanel):
#mouse is moving without a button press
p = event.GetPositionTuple()
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]
self.mousepos = v
......@@ -647,7 +647,7 @@ class TestGlPanel(GLPanel):
def keypress(self, event):
"""gets keypress events and moves/rotates acive shape"""
keycode = event.GetKeyCode()
print keycode
print(keycode)
step = 5
angle = 18
if event.ControlDown():
......@@ -742,14 +742,14 @@ class TestGlPanel(GLPanel):
rows = 10
cols = 10
zheight = 50
for i in xrange(-rows, rows + 1):
for i in range(-rows, rows + 1):
if i % 5 == 0:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1))
else:
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)
for i in xrange(-cols, cols + 1):
for i in range(-cols, cols + 1):
if i % 5 == 0:
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.6, 0.6, 0.6, 1))
else:
......@@ -794,7 +794,7 @@ class TestGlPanel(GLPanel):
glPushMatrix()
glTranslatef(-100, -100, 0)
for i in self.parent.models.values():
for i in list(self.parent.models.values()):
glPushMatrix()
glTranslatef(*(i.offsets))
glRotatef(i.rot, 0.0, 0.0, 1.0)
......@@ -803,7 +803,7 @@ class TestGlPanel(GLPanel):
try:
if i.curlayer in i.gc.layers:
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))
b = i.gc.layers[i.curlayer]
b.draw()
......@@ -879,4 +879,4 @@ def main():
if __name__ == "__main__":
import cProfile
print cProfile.run("main()")
print(cProfile.run("main()"))
......@@ -16,12 +16,12 @@
"""
Parsers for specific attributes
"""
import urlparse
import urllib.parse
from pyparsing import (Literal,
Optional, oneOf, Group, StringEnd, Combine, Word, alphas, hexnums,
CaselessLiteral, SkipTo
)
from css.colour import colourValue
from .css.colour import colourValue
import string
##Paint values
......@@ -30,7 +30,7 @@ currentColor = CaselessLiteral("currentColor").setParseAction(lambda t: ["CURREN
def parsePossibleURL(t):
possibleURL, fallback = t[0]
return [urlparse.urlsplit(possibleURL), fallback]
return [urllib.parse.urlsplit(possibleURL), fallback]
#Normal color declaration
colorDeclaration = none | currentColor | colourValue
......
......@@ -13,6 +13,6 @@
# You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
from .transform import transformList
from .inline import inlineStyle
......@@ -24,7 +24,7 @@
"""
import wx
import string
import urlparse
import urllib.parse
from pyparsing import nums, Literal, Optional, oneOf, Group, StringEnd, Combine, Word, alphas, hexnums
from ..pathdata import number, sign
......@@ -294,5 +294,5 @@ def fillCSS2SystemColours():
}
NamedColours.update(
#strip the alpha from the system colors. Is this really what we want to do?
(k.lower(), wx.SystemSettings.GetColour(v)[:3]) for (k,v) in systemColors.iteritems()
(k.lower(), wx.SystemSettings.GetColour(v)[:3]) for (k,v) in systemColors.items()
)
......@@ -27,11 +27,11 @@ class White(White):
escaped = (
Literal("\\").suppress() +
#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):
return unichr(int(t[0], 16))
return chr(int(t[0], 16))
hex_unicode = (
Literal("\\").suppress() +
Regex("[0-9a-f]{1,6}", re.IGNORECASE) +
......@@ -42,11 +42,11 @@ hex_unicode = (
escape = hex_unicode | escaped
#any unicode literal outside the 0-127 ascii range
nonascii = Regex(u"[^\u0000-\u007f]")
nonascii = Regex("[^\u0000-\u007f]")
#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))
......@@ -18,16 +18,16 @@
"""
import wx
from cStringIO import StringIO
from io import StringIO
import warnings
import math
from functools import wraps
import pathdata
import css
from . import pathdata
from . import css
from svg.css.colour import colourValue
from svg.css import values
from attributes import paintValue
from .attributes import paintValue
document = """<?xml version = "1.0" standalone = "no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
......@@ -60,7 +60,7 @@ def valueToPixels(val, defaultUnits = "px"):
try:
val, unit = values.length.parseString(val)
except ParseException:
print "***", val
print("***", val)
raise
#todo: unit conversion to something other than pixels
return val
......@@ -128,7 +128,7 @@ class SVGDocument(object):
"""
#copy the current state
current = dict(self.state)
current.update(element.items())
current.update(list(element.items()))
current.update(css.inlineStyle(element.get("style", "")))
self.stateStack.append(current)
handler = self.handlers.get(element.tag, lambda *any: (None, None))
......@@ -389,10 +389,10 @@ class SVGDocument(object):
else:
arguments = iter(arguments)
if command == 'm':
yield (command, arguments.next())
yield (command, next(arguments))
command = "l"
elif command == "M":
yield (command, arguments.next())
yield (command, next(arguments))
command = "L"
for arg in arguments:
yield (command, arg)
......@@ -574,9 +574,9 @@ class SVGDocument(object):
path.AddLineToPoint(normalizePoint(arg))
elif type == 'C':
#control1, control2, endpoint = arg
control1, control2, endpoint = map(
control1, control2, endpoint = list(map(
normalizePoint, arg
)
))
self.lastControl = control2
path.AddCurveToPoint(
control1,
......@@ -592,9 +592,9 @@ class SVGDocument(object):
elif type == 'S':
#control2, endpoint = arg
control2, endpoint = map(
control2, endpoint = list(map(
normalizePoint, arg
)
))
if self.lastControl:
control1 = reflectPoint(self.lastControl, path.GetCurrentPoint())
else:
......@@ -607,7 +607,7 @@ class SVGDocument(object):
endpoint
)
elif type == "Q":
(cx, cy), (x, y) = map(normalizePoint, arg)
(cx, cy), (x, y) = list(map(normalizePoint, arg))
self.lastControlQ = (cx, cy)
path.AddQuadCurveToPoint(cx, cy, x, y)
elif type == "T":
......
......@@ -14,8 +14,8 @@
# along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import wx, os, math
from bufferedcanvas import *
from printrun_utils import *
from .bufferedcanvas import *
from .printrun_utils import *
def sign(n):
if n < 0: return -1
......@@ -138,7 +138,7 @@ class XYButtons(BufferedCanvas):
return (quadrant, idx)
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])
if radius < 9:
return idx
......@@ -247,7 +247,7 @@ class XYButtons(BufferedCanvas):
# Draw label overlays
gc.SetPen(wx.Pen(wx.Colour(255, 255, 255, 128), 1))
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:
r = kpos[2]
gc.DrawEllipse(kpos[0]-r, kpos[1]-r, r*2, r*2)
......
......@@ -14,8 +14,8 @@
# along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import wx, os, math
from bufferedcanvas import *
from printrun_utils import *
from .bufferedcanvas import *
from .printrun_utils import *
def sign(n):
if n < 0: return -1
......@@ -108,7 +108,7 @@ class ZButtons(BufferedCanvas):
# Draw label overlays
gc.SetPen(wx.Pen(wx.Colour(255, 255, 255, 128), 1))
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:
r = kpos[2]
gc.DrawEllipse(ZButtons.center[0]-kpos[0]-r, ZButtons.center[1]-kpos[1]-r, r*2, r*2)
......
......@@ -14,7 +14,7 @@
# along with Printrun. If not, see <http://www.gnu.org/licenses/>.
import wx, math
from stltool import *
from .stltool import *
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):
......@@ -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:
bmidpoint = (pscale*(datal-1)/2.0, pscale*(datah-1)/2.0)
#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])
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]]]]
......@@ -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]
pass
#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])
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]]]]
......@@ -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[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
for i in xrange(datah-1):
for j in xrange(datal-1):
for i in range(datah-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+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]
......@@ -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):
i = wx.Image(name)
s = i.GetSize()
print len(map(ord, i.GetData()[::3]))
b = map(ord, i.GetData()[::3])
print(len(list(map(ord, i.GetData()[::3]))))
b = list(map(ord, i.GetData()[::3]))
data = []
for i in xrange(s[0]):
for i in range(s[0]):
data+=[b[i*s[1]:(i+1)*s[1]]]
#data = [i[::5] for i in data[::5]]
emitstl(out, genscape(data, zscale = 0.1).facets, name)
......
......@@ -21,7 +21,7 @@ import pronsole
from server import basic_auth
import random
import textwrap
import SocketServer
import socketserver
import socket
import mdns
import uuid
......@@ -133,21 +133,21 @@ class ConstructSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
pronserve.listeners.add(self)
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):
args = dict(dict_args.items() + kwargs.items())
args = dict(list(dict_args.items()) + list(kwargs.items()))
args['timestamp']= time.time()
self.write_message(args)
def on_message(self, msg):
print "message received: %s"%(msg)
print("message received: %s"%(msg))
# TODO: the read bit of repl!
# self.write_message("You said: " + msg)
def on_close(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__)
settings = dict(
......@@ -226,12 +226,12 @@ class Pronserve(pronsole.pronsole, EventEmitter):
self.update_job_progress(100)
self.fire("job_finished", self.jobs.sanitize(self.current_job))
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.p.startprint(self.current_job['body'].split("\n"))
self.fire("job_started", self.jobs.sanitize(self.current_job))
else:
print "Finished all print jobs"
print("Finished all print jobs")
self.current_job = None
self.printing_jobs = False
......@@ -273,12 +273,12 @@ class Pronserve(pronsole.pronsole, EventEmitter):
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])
# print "sensor update received!"
for key, value in d.iteritems():
for key, value in d.items():
self.__update_sensor(key, value)
self.fire("sensor_changed")
......@@ -295,7 +295,7 @@ class Pronserve(pronsole.pronsole, EventEmitter):
def log(self, *msg):
msg = ''.join(str(i) for i in msg)
msg.replace("\r", "")
print msg
print(msg)
self.fire("log", {'msg': msg, 'level': "debug"})
def write_prompt(self):
......@@ -338,14 +338,14 @@ class PrintJobQueue(EventEmitter):
self.__last_id += 1
self.list.append(job)
print "Added %s"%(original_file_name)
print("Added %s"%(original_file_name))
self.fire("job_added", job)
def display_summary(self):
print "Print Jobs:"
print("Print Jobs:")
for job in self.list:
print " %i: %s"%(job['id'], job['original_file_name'])
print ""
print(" %i: %s"%(job['id'], job['original_file_name']))
print("")
return True
def remove(self, job_id):
......@@ -353,7 +353,7 @@ class PrintJobQueue(EventEmitter):
if job == None:
return False
self.list.remove(job)
print "Print Job Removed"
print("Print Job Removed")
self.fire("job_removed", job)
def update(self, job_id, job_attrs):
......@@ -362,7 +362,7 @@ class PrintJobQueue(EventEmitter):
return False
job['rank'] = job_attrs['position']
self.order()
print "Print Job Updated"
print("Print Job Updated")
self.fire("job_updated", job)
def find_by_id(self, job_id):
......@@ -379,7 +379,7 @@ class PrintJobQueue(EventEmitter):
# Server Start Up
# -------------------------------------------------
print "Pronserve is starting..."
print("Pronserve is starting...")
pronserve = Pronserve()
pronserve.do_connect("")
......@@ -389,13 +389,13 @@ pronserve.run_print_queue_loop()
if __name__ == "__main__":
application.listen(8888)
print "\n"+"-"*80
welcome = textwrap.dedent(u"""
print("\n"+"-"*80)
welcome = textwrap.dedent("""
+---+ \x1B[0;32mPronserve: Your printer just got a whole lot better.\x1B[0m
| \u2713 | Ready to print.
+---+ More details at http://localhost:8888/""")
sys.stdout.write(welcome)
print "\n\n" + "-"*80 + "\n"
print("\n\n" + "-"*80 + "\n")
try:
pronserve.ioloop.start()
......
......@@ -28,7 +28,7 @@ install_locale('pronterface')
if os.name == "nt":
try:
import _winreg
import winreg
except:
pass
READLINE = True
......@@ -45,7 +45,7 @@ def dosify(name):
return os.path.split(name)[1].split(".")[0][:8]+".g"
def confirm():
y_or_n = raw_input("y/n: ")
y_or_n = input("y/n: ")
if y_or_n == "y":
return True
elif y_or_n != "n":
......@@ -97,12 +97,12 @@ class Settings:
except AttributeError:
pass
try:
return getattr(self, "_%s_alias"%key)().keys()
return list(getattr(self, "_%s_alias"%key)().keys())
except AttributeError:
pass
return []
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:
......@@ -186,7 +186,7 @@ class pronsole(cmd.Cmd):
"online" : "%(bold)sT:%(extruder_temp_fancy)s %(progress_fancy)s >%(normal)s "}
def log(self, *msg):
print ''.join(str(i) for i in msg)
print(''.join(str(i) for i in msg))
def promptf(self):
"""A function to generate prompts so that we can do dynamic prompts. """
......@@ -248,10 +248,10 @@ class pronsole(cmd.Cmd):
baselist = []
if os.name == "nt":
try:
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM")
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM")
i = 0
while(1):
baselist+=[_winreg.EnumValue(key, i)[1]]
baselist+=[winreg.EnumValue(key, i)[1]]
i+=1
except:
pass
......@@ -277,7 +277,7 @@ class pronsole(cmd.Cmd):
def complete_macro(self, text, line, begidx, endidx):
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]==" ")):
return [i for i in ["/D", "/S"] + self.completenames(text) if i.startswith(text)]
else:
......@@ -294,7 +294,7 @@ class pronsole(cmd.Cmd):
self.cur_macro_def += l + "\n"
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.prompt = self.promptf()
if self.cur_macro_def!="":
......@@ -339,7 +339,7 @@ class pronsole(cmd.Cmd):
lines = macro_def.split("\n")
for l in lines:
pycode += self.compile_macro_line(l)
exec pycode
exec(pycode)
return macro
def start_macro(self, macro_name, prev_definition = "", suppress_instructions = False):
......@@ -352,7 +352,7 @@ class pronsole(cmd.Cmd):
self.prompt = self.promptf()
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)
del self.macros[macro_name]
self.log("Macro '"+macro_name+"' removed")
......@@ -362,7 +362,7 @@ class pronsole(cmd.Cmd):
self.log("Macro '"+macro_name+"' is not defined")
def do_macro(self, args):
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
arglist = args.split(None, 1)
macro_name = arglist[0]
......@@ -381,7 +381,7 @@ class pronsole(cmd.Cmd):
self.cur_macro_name = macro_name
self.end_macro()
return
if self.macros.has_key(macro_name):
if macro_name in self.macros:
self.start_macro(macro_name, self.macros[macro_name])
else:
self.start_macro(macro_name)
......@@ -396,7 +396,7 @@ class pronsole(cmd.Cmd):
self.log("'macro' without arguments displays list of defined macros")
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]
if "\n" in macro_def:
self.log("Macro '"+macro_name+"' defined as:")
......@@ -414,7 +414,7 @@ class pronsole(cmd.Cmd):
self.save_in_rc("set "+var, "set %s %s" % (var, value))
except AttributeError:
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]))
def do_set(self, argl):
......@@ -520,7 +520,7 @@ class pronsole(cmd.Cmd):
# self.log("Saved '"+key+"' to '"+self.rc_filename+"'")
#else:
# self.log("Removed '"+key+"' from '"+self.rc_filename+"'")
except Exception, e:
except Exception as e:
self.log("Saving failed for ", key+":", str(e))
finally:
del rci, rco
......@@ -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[:5] == "echo:":
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.flush()
for i in self.recvlisteners:
......@@ -870,10 +870,10 @@ class pronsole(cmd.Cmd):
self.p.send_now("M105")
time.sleep(0.75)
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:
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("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))
def help_gettemp(self):
self.log("Read the extruder and bed temperature.")
......@@ -881,12 +881,12 @@ class pronsole(cmd.Cmd):
def do_settemp(self, l):
try:
l = l.lower().replace(", ",".")
for i in self.temps.keys():
for i in list(self.temps.keys()):
l = l.replace(i, self.temps[i])
f = float(l)
if f>=0:
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():
return
if self.p.online:
......@@ -902,16 +902,16 @@ class pronsole(cmd.Cmd):
def help_settemp(self):
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(", ".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):
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):
try:
l = l.lower().replace(", ",".")
for i in self.bedtemps.keys():
for i in list(self.bedtemps.keys()):
l = l.replace(i, self.bedtemps[i])
f = float(l)
if f>=0:
......@@ -928,11 +928,11 @@ class pronsole(cmd.Cmd):
def help_bedtemp(self):
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(", ".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):
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):
if(len(l.split())<2):
......@@ -1066,17 +1066,17 @@ class pronsole(cmd.Cmd):
def do_exit(self, l):
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")
if self.status.bed_enabled:
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.log("Disconnecting from printer...")
print self.p.printing
print(self.p.printing)
if self.p.printing:
print "Are you sure you want to exit while printing?"
print "(this will terminate the print)."
print("Are you sure you want to exit while printing?")
print("(this will terminate the print).")
if not confirm():
return False
self.log("Exiting program. Goodbye!")
......@@ -1123,7 +1123,7 @@ class pronsole(cmd.Cmd):
sys.stdout.flush()
prev_msg_len = len(prev_msg)
except KeyboardInterrupt:
if self.silent == False: print "Done monitoring."
if self.silent == False: print("Done monitoring.")
self.monitoring = 0
def help_monitor(self):
......@@ -1160,7 +1160,7 @@ class pronsole(cmd.Cmd):
subprocess.call(params)
self.log("Loading sliced file.")
self.do_load(l[0].replace(".stl", "_export.gcode"))
except Exception, e:
except Exception as e:
self.log("Skeinforge execution failed: ", e)
def complete_skein(self, text, line, begidx, endidx):
......@@ -1256,14 +1256,14 @@ class pronsole(cmd.Cmd):
else:
if self.use_rawinput:
try:
line = raw_input(self.prompt)
line = input(self.prompt)
except EOFError:
print ""
print("")
should_exit = self.do_exit("")
if should_exit:
exit()
except KeyboardInterrupt:
print ""
print("")
line = ""
else:
self.stdout.write(self.prompt)
......
......@@ -15,7 +15,7 @@
# You should have received a copy of the GNU General Public License
# 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
install_locale('pronterface')
......@@ -23,9 +23,9 @@ install_locale('pronterface')
try:
import wx
except:
print _("WX is not installed. This program requires WX to run.")
print(_("WX is not installed. This program requires WX to run."))
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 serial import SerialException
......@@ -37,7 +37,7 @@ layerindex = 0
if os.name == "nt":
winsize = (800, 530)
try:
import _winreg
import winreg
except:
pass
......@@ -120,7 +120,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.skeinp = None
self.monitor_interval = 3
self.paused = False
self.sentlines = Queue.Queue(30)
self.sentlines = queue.Queue(30)
self.cpbuttons = [
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")),
......@@ -158,22 +158,22 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.panel.SetBackgroundColour(self.settings.bgcolor)
customdict = {}
try:
execfile(configfile("custombtn.txt"), customdict)
exec(compile(open(configfile("custombtn.txt")).read(), configfile("custombtn.txt"), 'exec'), customdict)
if len(customdict["btns"]):
if not len(self.custombuttons):
try:
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])
os.rename("custombtn.txt", "custombtn.old")
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.close()
except IOError, x:
print str(x)
except IOError as x:
print(str(x))
else:
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(_("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"))
except:
pass
......@@ -200,13 +200,13 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def startcb(self):
self.starttime = time.time()
print "Print Started at: " + format_time(self.starttime)
print("Print Started at: " + format_time(self.starttime))
def endcb(self):
if self.p.queueindex == 0:
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()),
"duration": format_duration(print_duration)}
print(_("Print ended at: %(end_time)s and took %(duration)s") % {"end_time": format_time(time.time()),
"duration": format_duration(print_duration)})
wx.CallAfter(self.pausebtn.Disable)
wx.CallAfter(self.printbtn.SetLabel, _("Print"))
......@@ -220,7 +220,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.finalp = subprocess.Popen(pararray, stderr = subprocess.STDOUT, stdout = subprocess.PIPE)
def online(self):
print _("Printer is now online.")
print(_("Printer is now online."))
self.connectbtn.SetLabel(_("Disconnect"))
self.connectbtn.SetToolTip(wx.ToolTip("Disconnect from the printer"))
self.connectbtn.Bind(wx.EVT_BUTTON, self.disconnect)
......@@ -277,7 +277,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def do_extrude(self, l = ""):
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())
pronsole.pronsole.do_extrude(self, l)
except:
......@@ -285,7 +285,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def do_reverse(self, l = ""):
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()))
pronsole.pronsole.do_extrude(self, l)
except:
......@@ -331,43 +331,43 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def do_settemp(self, l = ""):
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 = l.lower().replace(", ", ".")
for i in self.temps.keys():
for i in list(self.temps.keys()):
l = l.replace(i, self.temps[i])
f = float(l)
if f >= 0:
if self.p.online:
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)
else:
print _("Printer is not online.")
print(_("Printer is not online."))
else:
print _("You cannot set negative temperatures. To turn the hotend off entirely, set its temperature to 0.")
except Exception, x:
print _("You must enter a temperature. (%s)") % (repr(x),)
print(_("You cannot set negative temperatures. To turn the hotend off entirely, set its temperature to 0."))
except Exception as x:
print(_("You must enter a temperature. (%s)") % (repr(x),))
def do_bedtemp(self, l = ""):
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 = l.lower().replace(", ", ".")
for i in self.bedtemps.keys():
for i in list(self.bedtemps.keys()):
l = l.replace(i, self.bedtemps[i])
f = float(l)
if f >= 0:
if self.p.online:
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)
else:
print _("Printer is not online.")
print(_("Printer is not online."))
else:
print _("You cannot set negative temperatures. To turn the bed off entirely, set its temperature to 0.")
except Exception, x:
print _("You must enter a temperature. (%s)") % (repr(x),)
print(_("You cannot set negative temperatures. To turn the bed off entirely, set its temperature to 0."))
except Exception as x:
print(_("You must enter a temperature. (%s)") % (repr(x),))
def end_macro(self):
pronsole.pronsole.end_macro(self)
......@@ -386,7 +386,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
if dialog.ShowModal() == wx.ID_YES:
self.delete_macro(macro_name)
return
print _("Cancelled.")
print(_("Cancelled."))
return
self.cur_macro_name = macro_name
self.cur_macro_def = definition
......@@ -399,7 +399,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
if self.capture_skip_newline and len(l) and not len(l.strip("\n\r")):
self.capture_skip_newline = False
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):
self.capture_skip[pat] -= 1
self.capture_skip_newline = True
......@@ -411,10 +411,10 @@ class PronterWindow(MainWindow, pronsole.pronsole):
baselist = []
if os.name == "nt":
try:
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM")
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM")
i = 0
while True:
baselist += [_winreg.EnumValue(key, i)[1]]
baselist += [winreg.EnumValue(key, i)[1]]
i += 1
except:
pass
......@@ -425,7 +425,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
if self.p.online:
projectlayer.setframe(self,self.p).Show()
else:
print _("Printer is not online.")
print(_("Printer is not online."))
def popmenu(self):
self.menustrip = wx.MenuBar()
......@@ -498,13 +498,13 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def edit_macro(self, macro):
if macro == "": return self.new_macro()
if self.macros.has_key(macro):
if macro in self.macros:
old_def = self.macros[macro]
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
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
else:
old_def = ""
......@@ -521,7 +521,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.macros_menu.DeleteItem(item)
except:
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))
def OnExit(self, event):
......@@ -562,11 +562,11 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def plate(self, e):
import plater
print "plate function activated"
print("plate function activated")
plater.stlwin(size = (800, 580), callback = self.platecb, parent = self).Show()
def platecb(self, name):
print "plated: "+name
print("plated: "+name)
self.loadfile(None, name)
def sdmenu(self, e):
......@@ -645,7 +645,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
newbuttonbuttonindex -= 1
while len(self.custombuttons) < 13:
self.custombuttons.append(None)
for i in xrange(len(self.custombuttons)):
for i in range(len(self.custombuttons)):
btndef = self.custombuttons[i]
try:
b = wx.Button(self.panel, -1, btndef.label, style = wx.BU_EXACTFIT)
......@@ -682,7 +682,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.mainsizer.Layout()
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 nextarg(rest):
......@@ -704,7 +704,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
pass
command = argstr.strip()
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
while num >= len(self.custombuttons):
self.custombuttons.append(None)
......@@ -723,10 +723,10 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.save_in_rc(("button %d" % n),'')
elif 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)
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)
else:
colour = wx.Colour(colour).GetAsString(wx.C2S_NAME|wx.C2S_HTML_SYNTAX)
......@@ -742,10 +742,10 @@ class PronterWindow(MainWindow, pronsole.pronsole):
bedit.command.SetValue(button.properties.command)
if button.properties.background:
colour = button.properties.background
if type(colour) not in (str, unicode):
if type(colour) not in (str, str):
#print type(colour)
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)
else:
colour = wx.Colour(colour).GetAsString(wx.C2S_NAME|wx.C2S_HTML_SYNTAX)
......@@ -969,7 +969,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.onecmd(e.GetEventObject().properties.command)
self.cur_button = None
except:
print _("event object missing")
print(_("event object missing"))
self.cur_button = None
raise
......@@ -1000,12 +1000,12 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.monitor_interval = float(l)
wx.CallAfter(self.monitorbox.SetValue, self.monitor_interval>0)
except:
print _("Invalid period given.")
print(_("Invalid period given."))
self.setmonitor(None)
if self.monitor:
print _("Monitoring printer.")
print(_("Monitoring printer."))
else:
print _("Done monitoring.")
print(_("Done monitoring."))
def setmonitor(self, e):
self.monitor = self.monitorbox.GetValue()
......@@ -1018,7 +1018,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
try:
self.logbox.AppendText(text)
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):
self.p.loud=e.IsChecked()
......@@ -1090,7 +1090,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
except:
pass
if cout is None:
cout = cStringIO.StringIO()
cout = io.StringIO()
sys.stdout = cout
retval = None
......@@ -1180,7 +1180,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
try:
import shlex
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())]
#print pararray
self.skeinp = subprocess.Popen(pararray, stderr = subprocess.STDOUT, stdout = subprocess.PIPE)
......@@ -1191,7 +1191,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.skeinp.wait()
self.stopsf = 1
except:
print _("Failed to execute slicing software: ")
print(_("Failed to execute slicing software: "))
self.stopsf = 1
traceback.print_exc(file = sys.stdout)
......@@ -1224,7 +1224,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def skein(self, filename):
wx.CallAfter(self.loadbtn.SetLabel, _("Cancel"))
print _("Slicing ") + filename
print(_("Slicing ") + filename)
self.cout = StringIO.StringIO()
self.filename = filename
self.stopsf = 0
......@@ -1283,11 +1283,11 @@ class PronterWindow(MainWindow, pronsole.pronsole):
def loadviz(self):
gcode = gcoder.GCode(self.f)
gcode.measure()
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 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 _("Estimated duration (pessimistic): "), gcode.estimate_duration()
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 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(_("Estimated duration (pessimistic): "), gcode.estimate_duration())
#import time
#t0 = time.time()
self.gviz.clear()
......@@ -1353,7 +1353,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.recvlisteners+=[self.uploadtrigger]
def pause(self, event):
print _("Paused.")
print(_("Paused."))
if not self.paused:
if self.sdprinting:
self.p.send_now("M25")
......@@ -1380,7 +1380,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
threading.Thread(target = self.getfiles).start()
def connect(self, event):
print _("Connecting...")
print(_("Connecting..."))
port = None
try:
port = self.scanserial()[0]
......@@ -1406,12 +1406,12 @@ class PronterWindow(MainWindow, pronsole.pronsole):
except SerialException as e:
# Currently, there is no errno, but it should be there in the future
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:
print _("Error: You don't have permission to open %s.") % port
print _("You might need to add yourself to the dialout group.")
print(_("Error: You don't have permission to open %s.") % port)
print(_("You might need to add yourself to the dialout group."))
else:
print e
print(e)
# Kill the scope anyway
return
self.statuscheck = True
......@@ -1442,7 +1442,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.predisconnect_layer = self.curlayer
def disconnect(self, event):
print _("Disconnected.")
print(_("Disconnected."))
if self.p.printing or self.p.paused or self.paused:
self.store_predisconnect_state()
self.p.disconnect()
......@@ -1475,7 +1475,7 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.p.send_now("M26 S0")
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)
if dlg.ShowModal() == wx.ID_YES:
self.p.reset()
......
......@@ -57,7 +57,7 @@ def authenticate(realm, authenticator,user_extractor) :
auth_decoded = base64.decodestring(auth_hdr[6:])
username, password = auth_decoded.split(':', 2)
user_info = authenticator(realm, unicode(username), password)
user_info = authenticator(realm, str(username), password)
if user_info :
self._user_info = user_info
self._current_user = user_extractor(user_info)
......@@ -65,7 +65,7 @@ def authenticate(realm, authenticator,user_extractor) :
str(self._user_info))
else:
return _request_basic_auth(self)
except Exception, e:
except Exception as e:
return _request_basic_auth(self)
return True
return wrapper
......@@ -90,4 +90,4 @@ def interceptor(func):
return cls
return classwrapper
print "moo"
\ No newline at end of file
print("moo")
\ No newline at end of file
......@@ -35,7 +35,7 @@ class install (_install):
if self.prefix:
length += len (self.prefix)
if length:
for counter in xrange (len (outputs)):
for counter in range (len (outputs)):
outputs[counter] = outputs[counter][length:]
data = "\n".join (outputs)
try:
......@@ -56,7 +56,7 @@ class install_data (_install_data):
except:
self.warn ("Could not chmod data file %s" % file)
_install_data.run (self)
map (chmod_data_file, self.get_outputs ())
list(map (chmod_data_file, self.get_outputs ()))
class uninstall (_install):
......@@ -75,10 +75,10 @@ class uninstall (_install):
if self.prefix:
prepend += self.prefix
if len (prepend):
for counter in xrange (len (files)):
for counter in range (len (files)):
files[counter] = prepend + files[counter].rstrip ()
for file in files:
print "Uninstalling %s" % file
print("Uninstalling %s" % file)
try:
os.unlink (file)
except:
......@@ -87,7 +87,7 @@ class uninstall (_install):
ops = ("install", "build", "sdist", "uninstall", "clean")
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
prefix = None
......@@ -126,14 +126,14 @@ for basedir, subdirs, files in os.walk("locale"):
if not basedir.endswith("LC_MESSAGES"):
continue
destpath = os.path.join("share", "pronterface", basedir)
files = filter(lambda x: x.endswith(".mo"), files)
files = map(lambda x: os.path.join(basedir, x), files)
files = [x for x in files if x.endswith(".mo")]
files = [os.path.join(basedir, x) for x in files]
data_files.append ((destpath, files))
extra_data_dirs = ["css"]
for extra_data_dir in extra_data_dirs:
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)
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