diff --git a/.gitignore b/.gitignore index 796f5c19..307a4dd4 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ *.swp *.DS_Store *.kpf -build/* \ No newline at end of file +build/* +pymt/c_ext/c_*.c diff --git a/doc/autobuild.py b/doc/autobuild.py index a59470e5..2550c2f0 100644 --- a/doc/autobuild.py +++ b/doc/autobuild.py @@ -23,7 +23,7 @@ def writefile(filename, data): global dest_dir - print 'write', filename + print('write', filename) f = os.path.join(dest_dir, filename) h = open(f, 'w') h.write(data) @@ -31,7 +31,7 @@ def writefile(filename, data): # Activate PyMT modules -for k in pymt.pymt_modules.list().keys(): +for k in list(pymt.pymt_modules.list().keys()): pymt.pymt_modules.import_module(k) # Search all pymt module @@ -117,7 +117,7 @@ def writefile(filename, data): t += " api-%s.rst\n" % subpackage # search modules - m = modules.keys() + m = list(modules.keys()) m.sort() for module in m: packagemodule = module.rsplit('.', 1)[0] @@ -129,7 +129,7 @@ def writefile(filename, data): # Create index for all module -m = modules.keys() +m = list(modules.keys()) m.sort() refid = 0 for module in m: @@ -180,4 +180,4 @@ def writefile(filename, data): # Generation finished -print 'Generation finished, do make html' +print('Generation finished, do make html') diff --git a/doc/sources/conf.py b/doc/sources/conf.py index e09f3ab6..5a418754 100644 --- a/doc/sources/conf.py +++ b/doc/sources/conf.py @@ -44,7 +44,7 @@ import os os.environ['PYMT_DOC_INCLUDE'] = '1' import pymt -print pymt.__file__ +print(pymt.__file__) version = pymt.__version__ release = pymt.__version__ diff --git a/examples/apps/3Ddrawing/3Ddrawing.py b/examples/apps/3Ddrawing/3Ddrawing.py index 7007d012..d340c8d7 100644 --- a/examples/apps/3Ddrawing/3Ddrawing.py +++ b/examples/apps/3Ddrawing/3Ddrawing.py @@ -1,4 +1,4 @@ -from __future__ import with_statement + # PYMT Plugin integration IS_PYMT_PLUGIN = True @@ -157,7 +157,7 @@ def pick(self, x,y): self.draw_picking() self.has_moved = False pick = glReadPixels(int(x), int(y), 1, 1, GL_RGB, GL_UNSIGNED_BYTE) - pick = map(ord, pick) + pick = list(map(ord, pick)) return pick[0]*4, 1024 - pick[1]*4 def paint(self, x, y): @@ -186,7 +186,7 @@ def on_touch_down(self, touch): if len(self.touch_position) == 1: self.touch1 = touch.id elif len(self.touch_position) == 2: - self.touch1, self.touch2 = self.touch_position.keys() + self.touch1, self.touch2 = list(self.touch_position.keys()) v1 = Vector(*self.touch_position[self.touch1]) v2 = Vector(*self.touch_position[self.touch2]) self.scale_dist = v1.distance(v2) @@ -209,7 +209,7 @@ def on_touch_move(self, touch): #if we got here, its a touch to turn/scale the model dx, dy, angle = 0,0,0 #two touches: scale and rotate around Z - if self.touch_position.has_key(self.touch1) and self.touch_position.has_key(self.touch2): + if self.touch1 in self.touch_position and self.touch2 in self.touch_position: v1 = Vector(*self.touch_position[self.touch1]) v2 = Vector(*self.touch_position[self.touch2]) diff --git a/examples/apps/3Dviewer/3Dviewer.py b/examples/apps/3Dviewer/3Dviewer.py index f570e364..a8797571 100644 --- a/examples/apps/3Dviewer/3Dviewer.py +++ b/examples/apps/3Dviewer/3Dviewer.py @@ -1,4 +1,4 @@ -from __future__ import with_statement + # PYMT Plugin integration IS_PYMT_PLUGIN = True diff --git a/examples/apps/flowchart/flowchart.py b/examples/apps/flowchart/flowchart.py index 6cc62e63..06912306 100644 --- a/examples/apps/flowchart/flowchart.py +++ b/examples/apps/flowchart/flowchart.py @@ -204,8 +204,8 @@ def draw(self): step = 200 * scale a = int(a[0] / step - 1) * step, int(a[1] / step - 1) * step b = int(b[0] / step + 1) * step, int(b[1] / step + 1) * step - for x in xrange(a[0], b[0], step): - for y in xrange(a[1], b[1], step): + for x in range(a[0], b[0], step): + for y in range(a[1], b[1], step): set_color(.9, .9, .9) drawLine((a[0], y, b[0], y), width=1) drawLine((x, a[1], x, b[1]), width=1) diff --git a/examples/apps/fridgeletter/fridgeletter.py b/examples/apps/fridgeletter/fridgeletter.py index 758b152e..a8195b21 100644 --- a/examples/apps/fridgeletter/fridgeletter.py +++ b/examples/apps/fridgeletter/fridgeletter.py @@ -52,12 +52,12 @@ def __init__(self, **kwargs): def createletters(self, *largs): w = self.get_parent_window() - for c in xrange(65, 91): # A-Z + for c in range(65, 91): # A-Z count = 1 if chr(c) in 'AEUIO': count = 4 - for i in xrange(0, count): - color = map(lambda x: x/255., (randint(100,255), randint(100,255), randint(100,255), 255)) + for i in range(0, count): + color = [x/255. for x in (randint(100,255), randint(100,255), randint(100,255), 255)] l = FridgeLetterAtomic(letter=chr(c), color=color) if w: l.pos = randint(0, w.width), randint(0, w.height) @@ -73,7 +73,7 @@ def randomize(self, *largs): for letter in self.children: if letter == self.buttons: continue - letter.do(Animation(pos=map(lambda x: x * random(), w.size), + letter.do(Animation(pos=[x * random() for x in w.size], f='ease_out_cubic', duration=.5)) def draw(self): diff --git a/examples/apps/gestures/gestures.py b/examples/apps/gestures/gestures.py index 6c8e0e95..b2916aa3 100644 --- a/examples/apps/gestures/gestures.py +++ b/examples/apps/gestures/gestures.py @@ -33,9 +33,9 @@ def on_gesture(self, gesture, touch): # try to find gesture from database best = self.gdb.find(gesture, minscore=0.5) if not best: - print 'No gesture found\nString version of your last gesture :\n', self.gdb.gesture_to_str(gesture) + print('No gesture found\nString version of your last gesture :\n', self.gdb.gesture_to_str(gesture)) else: - print 'Gesture found, score', best[0], ':', best[1].label + print('Gesture found, score', best[0], ':', best[1].label) self.lastgesture = gesture self.lastbest = best diff --git a/examples/apps/mtwitter/twitter.py b/examples/apps/mtwitter/twitter.py index 9da7739a..197c7a64 100644 --- a/examples/apps/mtwitter/twitter.py +++ b/examples/apps/mtwitter/twitter.py @@ -15,9 +15,9 @@ import sys import tempfile import time -import urllib -import urllib2 -import urlparse +import urllib.request, urllib.parse, urllib.error +import urllib.request, urllib.error, urllib.parse +import urllib.parse import twitter class TwitterError(Exception): @@ -1295,7 +1295,7 @@ def SetXTwitterHeaders(self, client, url, version): def _BuildUrl(self, url, path_elements=None, extra_params=None): # Break url into consituent parts - (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) + (scheme, netloc, path, params, query, fragment) = urllib.parse.urlparse(url) # Add any additional path elements to the path if path_elements: @@ -1315,7 +1315,7 @@ def _BuildUrl(self, url, path_elements=None, extra_params=None): query = extra_query # Return the rebuilt URL - return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) + return urllib.parse.urlunparse((scheme, netloc, path, params, query, fragment)) def _InitializeRequestHeaders(self, request_headers): if request_headers: @@ -1341,19 +1341,19 @@ def _GetOpener(self, url, username=None, password=None): if username and password: self._AddAuthorizationHeader(username, password) handler = self._urllib.HTTPBasicAuthHandler() - (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) + (scheme, netloc, path, params, query, fragment) = urllib.parse.urlparse(url) handler.add_password(Api._API_REALM, netloc, username, password) opener = self._urllib.build_opener(handler) else: opener = self._urllib.build_opener() - opener.addheaders = self._request_headers.items() + opener.addheaders = list(self._request_headers.items()) return opener def _Encode(self, s): if self._input_encoding: - return unicode(s, self._input_encoding).encode('utf-8') + return str(s, self._input_encoding).encode('utf-8') else: - return unicode(s).encode('utf-8') + return str(s).encode('utf-8') def _EncodeParameters(self, parameters): '''Return a string in key=value&key=value form @@ -1370,7 +1370,7 @@ def _EncodeParameters(self, parameters): if parameters is None: return None else: - return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in parameters.items() if v is not None])) + return urllib.parse.urlencode(dict([(k, self._Encode(v)) for k, v in list(parameters.items()) if v is not None])) def _EncodePostData(self, post_data): '''Return a string in key=value&key=value form @@ -1388,7 +1388,7 @@ def _EncodePostData(self, post_data): if post_data is None: return None else: - return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in post_data.items()])) + return urllib.parse.urlencode(dict([(k, self._Encode(v)) for k, v in list(post_data.items())])) def _FetchUrl(self, url, diff --git a/examples/apps/paint/paint.py b/examples/apps/paint/paint.py index 720a9133..269a9c3e 100644 --- a/examples/apps/paint/paint.py +++ b/examples/apps/paint/paint.py @@ -147,14 +147,14 @@ def on_touch_down(self, touch): self.touch_positions[touch.id] = (touch.x, touch.y) def on_touch_move(self, touch): - if self.touch_positions.has_key(touch.id): + if touch.id in self.touch_positions: ox,oy = self.touch_positions[touch.id] self.paint_queue.appendleft((self.color, (ox,oy,touch.x,touch.y))) self.do_paint_queue = True self.touch_positions[touch.id] = (touch.x, touch.y) def on_touch_up(self, touch): - if self.touch_positions.has_key(touch.id): + if touch.id in self.touch_positions: del self.touch_positions[touch.id] def update_brush(brush, size, *largs): diff --git a/examples/apps/particles/particles.py b/examples/apps/particles/particles.py index b9e10710..a8bcf4b2 100644 --- a/examples/apps/particles/particles.py +++ b/examples/apps/particles/particles.py @@ -1,4 +1,4 @@ -from __future__ import with_statement + from pymt import * from OpenGL.GL import * import random @@ -29,9 +29,9 @@ def __init__(self, settings): self.random_color() def random_color(self): - r_min, r_max = map(lambda x: x/255., self.settings.color_r) - g_min, g_max = map(lambda x: x/255., self.settings.color_g) - b_min, b_max = map(lambda x: x/255., self.settings.color_b) + r_min, r_max = [x/255. for x in self.settings.color_r] + g_min, g_max = [x/255. for x in self.settings.color_g] + b_min, b_max = [x/255. for x in self.settings.color_b] self.color = [random.uniform(r_min, r_max), random.uniform(g_min, g_max), random.uniform(b_min, b_max), diff --git a/examples/desktop/desktop-multi.py b/examples/desktop/desktop-multi.py index 8c4b5aec..8286e304 100644 --- a/examples/desktop/desktop-multi.py +++ b/examples/desktop/desktop-multi.py @@ -1,4 +1,4 @@ -from __future__ import with_statement + import os import math from pymt import * @@ -253,7 +253,7 @@ def on_gesture(self, gesture, touch): try: score, best = self.gdb.find(gesture, minscore=.5) - except Exception, e: + except Exception as e: return if best.id == 'circle': diff --git a/examples/desktop/desktop-single.py b/examples/desktop/desktop-single.py index 70116fc4..39fe8b18 100644 --- a/examples/desktop/desktop-single.py +++ b/examples/desktop/desktop-single.py @@ -82,7 +82,7 @@ def populate(self): # no icon ? if icon is None: - print 'No icon found for', infos['title'] + print('No icon found for', infos['title']) continue # create an image button for every plugin diff --git a/examples/framework/base_event_dispatcher.py b/examples/framework/base_event_dispatcher.py index 1e99254f..2e6e6408 100644 --- a/examples/framework/base_event_dispatcher.py +++ b/examples/framework/base_event_dispatcher.py @@ -12,7 +12,7 @@ # create a class to catch all events class TouchEventListener: def dispatch_event(self, event_name, *arguments): - print 'Event dispatched', event_name, 'with', arguments + print('Event dispatched', event_name, 'with', arguments) # append the class to event listeners pymt_event_listeners.append(TouchEventListener()) diff --git a/examples/framework/core/audio.py b/examples/framework/core/audio.py index 2702b5c1..6717150f 100644 --- a/examples/framework/core/audio.py +++ b/examples/framework/core/audio.py @@ -12,11 +12,11 @@ # install callack for on_play/on_stop event @sound.event def on_play(): - print '-> sound started, status is', sound.status + print('-> sound started, status is', sound.status) @sound.event def on_stop(): - print '-> sound finished, status is', sound.status + print('-> sound finished, status is', sound.status) stopTouchApp() # start to play the sound diff --git a/examples/framework/exceptions.py b/examples/framework/exceptions.py index 9852a415..270e875e 100644 --- a/examples/framework/exceptions.py +++ b/examples/framework/exceptions.py @@ -15,6 +15,6 @@ def handle_exception(self, inst): t = MTButton() @t.event def on_press(*largs): - print a + print(a) m.add_widget(t) runTouchApp() diff --git a/examples/framework/ui_dragable.py b/examples/framework/ui_dragable.py index 288b156f..9e95cf5b 100644 --- a/examples/framework/ui_dragable.py +++ b/examples/framework/ui_dragable.py @@ -5,7 +5,7 @@ # create 100 dragable object with random position and color w, h = window.size -for i in xrange(100): +for i in range(100): x = random() * w y = random() * h window.add_widget(MTDragable(pos=(x, y), diff --git a/examples/framework/ui_klist.py b/examples/framework/ui_klist.py index 355861eb..54c2c8cb 100644 --- a/examples/framework/ui_klist.py +++ b/examples/framework/ui_klist.py @@ -9,7 +9,7 @@ # create a lot of button. you should be able to click on it, and # move the list in X axis -for x in xrange(100): +for x in range(100): wlayout.add_widget(MTToggleButton(label=str(x))) runTouchApp(wlist) diff --git a/examples/framework/ui_widgets_button.py b/examples/framework/ui_widgets_button.py index cb689407..a29600f9 100644 --- a/examples/framework/ui_widgets_button.py +++ b/examples/framework/ui_widgets_button.py @@ -7,14 +7,14 @@ b = MTButton(label='Push me') @b.event def on_press(*largs): - print 'on_press()', b.state, largs + print('on_press()', b.state, largs) @b.event def on_release(*largs): - print 'on_release()', b.state, largs + print('on_release()', b.state, largs) @b.event def on_state_change(*largs): - print 'on_state_change()', b.state, largs + print('on_state_change()', b.state, largs) runTouchApp(b) diff --git a/examples/framework/ui_widgets_button_toggle.py b/examples/framework/ui_widgets_button_toggle.py index 5dd0fafb..b6af767e 100644 --- a/examples/framework/ui_widgets_button_toggle.py +++ b/examples/framework/ui_widgets_button_toggle.py @@ -4,10 +4,10 @@ @b.event def on_press(*largs): - print 'on_press()', b.state, largs + print('on_press()', b.state, largs) @b.event def on_release(*largs): - print 'on_release()', b.state, largs + print('on_release()', b.state, largs) runTouchApp(b) diff --git a/examples/framework/ui_widgets_buttonmatrix.py b/examples/framework/ui_widgets_buttonmatrix.py index fd7d5828..d06672ea 100644 --- a/examples/framework/ui_widgets_buttonmatrix.py +++ b/examples/framework/ui_widgets_buttonmatrix.py @@ -7,7 +7,7 @@ def m_on_press(args): # extract row / column / state row, column, state = args - print 'matrix change at %d x %d = %s' % (row, column, state) + print('matrix change at %d x %d = %s' % (row, column, state)) # connect the handler to the widget m.connect('on_press', m_on_press) diff --git a/examples/framework/ui_widgets_composed_filebrowser.py b/examples/framework/ui_widgets_composed_filebrowser.py index be6c17df..0a0d70ec 100644 --- a/examples/framework/ui_widgets_composed_filebrowser.py +++ b/examples/framework/ui_widgets_composed_filebrowser.py @@ -6,6 +6,6 @@ # when selection will be done, it will print the selected files @fb.event def on_select(list): - print list + print(list) runTouchApp(fb) diff --git a/examples/framework/ui_widgets_composed_textarea.py b/examples/framework/ui_widgets_composed_textarea.py index 96b2fbba..7d336ba0 100644 --- a/examples/framework/ui_widgets_composed_textarea.py +++ b/examples/framework/ui_widgets_composed_textarea.py @@ -10,11 +10,11 @@ @wid.event def on_text_validate(): - print 'Text have been validated:', wid.value + print('Text have been validated:', wid.value) @wid.event def on_text_change(text): - print 'Text have been changed (not validated):', text + print('Text have been changed (not validated):', text) runTouchApp(wid) diff --git a/examples/framework/ui_widgets_composed_textinput.py b/examples/framework/ui_widgets_composed_textinput.py index 69eab144..0de905ce 100644 --- a/examples/framework/ui_widgets_composed_textinput.py +++ b/examples/framework/ui_widgets_composed_textinput.py @@ -5,6 +5,6 @@ @wid.event def on_text_change(text): - print 'Text have been changed (not validated):', text + print('Text have been changed (not validated):', text) runTouchApp(wid) diff --git a/examples/framework/ui_widgets_composed_vkeyboard.py b/examples/framework/ui_widgets_composed_vkeyboard.py index 3b11f9be..21fbc152 100644 --- a/examples/framework/ui_widgets_composed_vkeyboard.py +++ b/examples/framework/ui_widgets_composed_vkeyboard.py @@ -3,14 +3,14 @@ @keyboard.event def on_key_down(*largs): - print 'key down:', largs + print('key down:', largs) @keyboard.event def on_key_up(*largs): - print 'key up:', largs + print('key up:', largs) @keyboard.event def on_text_change(*largs): - print 'text change', largs + print('text change', largs) runTouchApp(keyboard) diff --git a/examples/framework/ui_widgets_composed_vkeyboard_numerical.py b/examples/framework/ui_widgets_composed_vkeyboard_numerical.py index e3c87734..9ab5cd76 100644 --- a/examples/framework/ui_widgets_composed_vkeyboard_numerical.py +++ b/examples/framework/ui_widgets_composed_vkeyboard_numerical.py @@ -7,19 +7,19 @@ class NumericKeyboardLayout(KeyboardLayout): DESCRIPTION = '' SIZE = (4, 4) NORMAL_1 = [ - ('7', '7', None, 1), ('8', '8', None, 1), (u'9', u'9', None, 1), - (u'\u2a2f', None, 'escape', 1), + ('7', '7', None, 1), ('8', '8', None, 1), ('9', '9', None, 1), + ('\u2a2f', None, 'escape', 1), ] NORMAL_2 = [ - ('4', '4', None, 1), ('5', '5', None, 1), (u'6', u'6', None, 1), + ('4', '4', None, 1), ('5', '5', None, 1), ('6', '6', None, 1), ] NORMAL_3 = [ - ('1', '1', None, 1), ('2', '2', None, 1), (u'3', u'3', None, 1), - (u'\u232b', None, 'backspace', 1), + ('1', '1', None, 1), ('2', '2', None, 1), ('3', '3', None, 1), + ('\u232b', None, 'backspace', 1), ] NORMAL_4 = [ ('0', '0', None, 1), (',', ',', None, 2), - (u'\u23ce', None, 'enter', 1) + ('\u23ce', None, 'enter', 1) ] # create a keyboard, with our custom layout diff --git a/examples/framework/ui_widgets_coverflow.py b/examples/framework/ui_widgets_coverflow.py index 6f81b8e5..096d96f2 100644 --- a/examples/framework/ui_widgets_coverflow.py +++ b/examples/framework/ui_widgets_coverflow.py @@ -15,10 +15,10 @@ @coverflow.event def on_change(cover): - print 'cover changed', cover.title + print('cover changed', cover.title) @coverflow.event def on_select(cover): - print 'cover selected', cover.title + print('cover selected', cover.title) runTouchApp(coverflow) diff --git a/examples/framework/ui_widgets_list.py b/examples/framework/ui_widgets_list.py index 4f6e62e0..7cf0dd94 100644 --- a/examples/framework/ui_widgets_list.py +++ b/examples/framework/ui_widgets_list.py @@ -2,11 +2,11 @@ # callback for the buttons def test_button(btn, *largs): - print 'button pressed', btn.label + print('button pressed', btn.label) # create a grid layout with 2 rows layout = MTGridLayout(rows=2) -for x in xrange(22): +for x in range(22): btn = MTToggleButton(label='label%d' % x) btn.connect('on_press', curry(test_button, btn)) layout.add_widget(btn) diff --git a/examples/framework/ui_widgets_list_xy.py b/examples/framework/ui_widgets_list_xy.py index fe4c3226..3136035a 100644 --- a/examples/framework/ui_widgets_list_xy.py +++ b/examples/framework/ui_widgets_list_xy.py @@ -2,11 +2,11 @@ # callback for the buttons def test_button(btn, *largs): - print 'button pressed', btn.label + print('button pressed', btn.label) # create a grid layout with 2 rows layout = MTGridLayout(rows=4) -for x in xrange(50): +for x in range(50): btn = MTToggleButton(label='label%d' % x) btn.connect('on_press', curry(test_button, btn)) layout.add_widget(btn) diff --git a/examples/framework/ui_widgets_radial.py b/examples/framework/ui_widgets_radial.py index 6b6f4afa..62fd704d 100644 --- a/examples/framework/ui_widgets_radial.py +++ b/examples/framework/ui_widgets_radial.py @@ -4,14 +4,14 @@ @sl.event def on_amplitude_change(value): - print 'Slider amplitude change', value + print('Slider amplitude change', value) @sl.event def on_angle_change(value): - print 'Slider angle change', value + print('Slider angle change', value) @sl.event def on_vector_change(x, y): - print 'Slider vector change', x, y + print('Slider vector change', x, y) runTouchApp(sl) diff --git a/examples/framework/ui_widgets_slider.py b/examples/framework/ui_widgets_slider.py index bd680119..91b0e6a5 100644 --- a/examples/framework/ui_widgets_slider.py +++ b/examples/framework/ui_widgets_slider.py @@ -5,6 +5,6 @@ @sl.event def on_value_change(value): - print 'Slider value change', value + print('Slider value change', value) runTouchApp(sl) diff --git a/examples/framework/ui_widgets_slider_boundary.py b/examples/framework/ui_widgets_slider_boundary.py index 23f98cfd..579913e5 100644 --- a/examples/framework/ui_widgets_slider_boundary.py +++ b/examples/framework/ui_widgets_slider_boundary.py @@ -4,6 +4,6 @@ @sl.event def on_value_change(vmin, vmax): - print 'Slider values change: ', vmin, ' - ', vmax + print('Slider values change: ', vmin, ' - ', vmax) runTouchApp(sl) diff --git a/examples/framework/ui_widgets_slider_multi.py b/examples/framework/ui_widgets_slider_multi.py index 3caf0ae0..9fe3d80c 100644 --- a/examples/framework/ui_widgets_slider_multi.py +++ b/examples/framework/ui_widgets_slider_multi.py @@ -4,6 +4,6 @@ @sl.event def on_value_change(values): - print 'Slider values change: ', values + print('Slider values change: ', values) runTouchApp(sl) diff --git a/examples/framework/ui_widgets_slider_xy.py b/examples/framework/ui_widgets_slider_xy.py index 5cc462f1..f13d88c4 100644 --- a/examples/framework/ui_widgets_slider_xy.py +++ b/examples/framework/ui_widgets_slider_xy.py @@ -6,6 +6,6 @@ @sl.event def on_value_change(x, y): - print 'Slider value change', x, y + print('Slider value change', x, y) runTouchApp(sl) diff --git a/examples/gallery/animation_gallery.py b/examples/gallery/animation_gallery.py index e0fcb064..55152bd3 100644 --- a/examples/gallery/animation_gallery.py +++ b/examples/gallery/animation_gallery.py @@ -16,7 +16,7 @@ def __init__(self, **kwargs): self.func = getattr(AnimationAlpha, self.funcname) # get all points for curve with the selected alpha function self.points = [] - for x in xrange(0, self.precision): + for x in range(0, self.precision): progress = x / float(self.precision) self.points += [progress, self.func(progress)] # add the last one diff --git a/examples/gallery/widgets_gallery.py b/examples/gallery/widgets_gallery.py index 92078a85..65a36d04 100644 --- a/examples/gallery/widgets_gallery.py +++ b/examples/gallery/widgets_gallery.py @@ -117,18 +117,18 @@ def screen_speechbubble(w): @registerscreen('Kinetic List') def screen_kineticlist(w): m = MTKineticList(size=(210, 200)) - for x in xrange(20): + for x in range(20): m.add_widget(MTKineticItem(label=str(x))) w.add_widget(m) m = MTKineticList(size=(210, 200), searchable=False, deletable=False) - for x in xrange(20): + for x in range(20): m.add_widget(MTKineticItem(label=str(x))) w.add_widget(m) m = MTKineticList(size=(230, 200), searchable=False, deletable=False, title=None, w_limit=2) - for x in xrange(20): + for x in range(20): m.add_widget(MTKineticItem(label=str(x))) w.add_widget(m) @@ -146,22 +146,22 @@ def screen_sidepanel(w): w = getWindow() panel = MTSidePanel(side='left', size=(500, 100)) - for x in xrange(5): + for x in range(5): panel.add_widget(MTButton(label=str(x))) w.add_widget(panel) panel = MTSidePanel(side='right', size=(500, 100)) - for x in xrange(5): + for x in range(5): panel.add_widget(MTButton(label=str(x))) w.add_widget(panel) panel = MTSidePanel(side='top', size=(500, 100)) - for x in xrange(5): + for x in range(5): panel.add_widget(MTButton(label=str(x))) w.add_widget(panel) panel = MTSidePanel(side='bottom', size=(500, 100)) - for x in xrange(5): + for x in range(5): panel.add_widget(MTButton(label=str(x))) w.add_widget(panel) diff --git a/examples/games/bloop/bloop.py b/examples/games/bloop/bloop.py index 4451225b..2eefe5b5 100644 --- a/examples/games/bloop/bloop.py +++ b/examples/games/bloop/bloop.py @@ -1,4 +1,4 @@ -from __future__ import with_statement + # PYMT Plugin integration IS_PYMT_PLUGIN = True diff --git a/examples/games/bubblebattle/bubblebattle.py b/examples/games/bubblebattle/bubblebattle.py index 812cdc31..07235b75 100644 --- a/examples/games/bubblebattle/bubblebattle.py +++ b/examples/games/bubblebattle/bubblebattle.py @@ -280,7 +280,7 @@ def draw(self): # enemies + bariers for e in reversed(self.enemies): e.draw() - for bid in reversed(self.bariers.keys()): + for bid in reversed(list(self.bariers.keys())): self.bariers[bid].draw() # ui score diff --git a/examples/games/bubblebomb/bubblebomb.py b/examples/games/bubblebomb/bubblebomb.py index fa995e93..805b4ee6 100644 --- a/examples/games/bubblebomb/bubblebomb.py +++ b/examples/games/bubblebomb/bubblebomb.py @@ -18,7 +18,7 @@ def __init__(self, **kwargs): self.moved = False self.speed = 200 self.level = kwargs.get('level') - self.dx, self.dy = map(lambda x: randint(-self.speed, self.speed), xrange(2)) + self.dx, self.dy = [randint(-self.speed, self.speed) for x in range(2)] self.lifetime = 8 self.initial_lifetime = self.lifetime self.life = 1 diff --git a/examples/games/untangle/data_viewer.py b/examples/games/untangle/data_viewer.py index 618f55f7..33dfdff3 100644 --- a/examples/games/untangle/data_viewer.py +++ b/examples/games/untangle/data_viewer.py @@ -34,7 +34,7 @@ def draw(self): ends_at = self.data['touch_event_log'][touchID][-1]['t'] if not (starts_at > time_frame[0] and ends_at < time_frame[1]): - print touchID, starts_at, ends_at, time_frame + print(touchID, starts_at, ends_at, time_frame) continue for e in self.data['touch_event_log'][touchID]: t = (e['t'] - first_t)/(last_t -first_t) diff --git a/examples/games/untangle/graph.py b/examples/games/untangle/graph.py index 7e3fb7ae..2636403b 100644 --- a/examples/games/untangle/graph.py +++ b/examples/games/untangle/graph.py @@ -1,4 +1,4 @@ -from __future__ import with_statement + from random import randint from OpenGL.GL import * from OpenGL.GLU import * @@ -94,4 +94,4 @@ def collideVerts(self, x,y, regionSize=40): if __name__ == "__main__": - print "this is an implementation file only used by untabgle.py" + print("this is an implementation file only used by untabgle.py") diff --git a/examples/games/untangle/untangle.py b/examples/games/untangle/untangle.py index e9881022..c2102b3c 100644 --- a/examples/games/untangle/untangle.py +++ b/examples/games/untangle/untangle.py @@ -1,4 +1,4 @@ -from __future__ import with_statement + # PYMT Plugin integration IS_PYMT_PLUGIN = True @@ -8,7 +8,7 @@ PLUGIN_DESCRIPTION = 'Untangle game !' from pymt import * -from graph import * +from .graph import * from OpenGL.GL import * from OpenGL.GLU import * @@ -170,7 +170,7 @@ def on_touch_up(self, touch): if self.done: return self.num_moves +=1 - if self.touch2vertex.has_key(touch.id): + if touch.id in self.touch2vertex: del self.touch2vertex[touch.id] if self.g.is_solved(): #self.g = Graph(15,displaySize=w.size) @@ -184,7 +184,7 @@ def on_touch_up(self, touch): def on_touch_move(self, touch): if self.done: return - if self.touch2vertex.has_key(touch.id): + if touch.id in self.touch2vertex: self.touch2vertex[touch.id][0] = touch.x self.touch2vertex[touch.id][1] = touch.y self.num_moves_since_check += 1 diff --git a/examples/games/wang/wang.py b/examples/games/wang/wang.py index 61c54106..c1496c7b 100644 --- a/examples/games/wang/wang.py +++ b/examples/games/wang/wang.py @@ -467,7 +467,7 @@ def drawUI(self): # middle line set_color(1, 1, 1) - for x in xrange(0, w.height, int(s * 2)): + for x in range(0, w.height, int(s * 2)): drawLine([w2, x, w2, x + s], width=5) # top / bottom line diff --git a/examples/widgets/kinetic.py b/examples/widgets/kinetic.py index 2031f83b..bda6b523 100644 --- a/examples/widgets/kinetic.py +++ b/examples/widgets/kinetic.py @@ -1,7 +1,7 @@ from pymt import * def print_me(*largs): - print 'CLICKED ON', largs[0].label + print('CLICKED ON', largs[0].label) mms = MTWindow() w = MTScatterWidget(size=(500, 500)) @@ -12,7 +12,7 @@ def print_me(*largs): k = MTKineticList(pos=(50,50), size=(400, 400), w_limit=3) w.add_widget(k) -d = range(0, 20) +d = list(range(0, 20)) for x in d: item = MTKineticItem(label=str(x),deletable=True) item.push_handlers(on_press=curry(print_me, item)) diff --git a/examples/widgets/kineticimage.py b/examples/widgets/kineticimage.py index f52c89cf..72d0e28a 100644 --- a/examples/widgets/kineticimage.py +++ b/examples/widgets/kineticimage.py @@ -7,7 +7,7 @@ # search file in image directory pattern = os.path.join(os.path.dirname(__file__), 'images', '*.png') -for x in xrange(10): +for x in range(10): for filename in glob.glob(pattern): item = MTKineticImage(image=Loader.image(filename)) k.add_widget(item) diff --git a/examples/widgets/multiplescatter.py b/examples/widgets/multiplescatter.py index 1543248a..bd89b3a5 100644 --- a/examples/widgets/multiplescatter.py +++ b/examples/widgets/multiplescatter.py @@ -22,8 +22,8 @@ def on_draw(self): s1.add_widget(s2) root.add_widget(s1) w.add_widget(root) -print '' -print 'Blue line represent the (0, 0) -> scatter.pos (invalid in this case)' -print 'Green line represent the (0, 0) -> scatter position for window (valid)' -print '' +print('') +print('Blue line represent the (0, 0) -> scatter.pos (invalid in this case)') +print('Green line represent the (0, 0) -> scatter position for window (valid)') +print('') runTouchApp() diff --git a/examples/widgets/stencil.py b/examples/widgets/stencil.py index eec861e4..2bd6c89e 100644 --- a/examples/widgets/stencil.py +++ b/examples/widgets/stencil.py @@ -16,7 +16,7 @@ p.add_widget(k) w.add_widget(p) -d = range(0, 10) +d = list(range(0, 10)) for x in d: item = MTKineticItem(label=str(x)) k.add_widget(item) diff --git a/pymt/__init__.py b/pymt/__init__.py index 3a4f4927..58470576 100644 --- a/pymt/__init__.py +++ b/pymt/__init__.py @@ -230,7 +230,7 @@ def pymt_register_post_configuration(callback): try: with open(pymt_config_fn, 'w') as fd: pymt_config.write(fd) - except Exception, e: + except Exception as e: pymt_logger.exception('Core: error while saving default' 'configuration file') pymt_logger.info('Core: PyMT configuration saved.') @@ -242,7 +242,7 @@ def pymt_register_post_configuration(callback): shadow_window = MTWindow() pymt_configure() - except getopt.GetoptError, err: + except getopt.GetoptError as err: pymt_logger.error('Core: %s' % str(err)) pymt_usage() sys.exit(2) diff --git a/pymt/accelerate.py b/pymt/accelerate.py index a6b31a1c..363e72d4 100644 --- a/pymt/accelerate.py +++ b/pymt/accelerate.py @@ -31,7 +31,7 @@ try: import pymt.c_ext.c_accelerate as accelerate pymt_logger.info('Core: Using accelerate module') - except ImportError, e: + except ImportError as e: pymt_logger.warning('Core: Accelerate module not available <%s>' % e) pymt_logger.warning('Core: Execute "python setup.py build_ext ' '--inplace"') diff --git a/pymt/base.py b/pymt/base.py index 52ac6391..58c6df64 100644 --- a/pymt/base.py +++ b/pymt/base.py @@ -251,7 +251,7 @@ def pymt_usage(): --size=640x480 size of window ''' - print pymt_usage.__doc__ % (os.path.basename(sys.argv[0])) + print(pymt_usage.__doc__ % (os.path.basename(sys.argv[0]))) def _run_mainloop(): @@ -261,7 +261,7 @@ def _run_mainloop(): pymt_evloop.run() stopTouchApp() break - except BaseException, inst: + except BaseException as inst: # use exception manager first r = pymt_exception_manager.handle_exception(inst) if r == ExceptionManager.RAISE: @@ -330,7 +330,7 @@ def runTouchApp(widget=None, slave=False): pymt_evloop = TouchEventLoop() # add postproc modules - for mod in pymt_postproc_modules.values(): + for mod in list(pymt_postproc_modules.values()): pymt_evloop.add_postproc_module(mod) # add main widget diff --git a/pymt/cache.py b/pymt/cache.py index 9197dbe5..721b01ba 100644 --- a/pymt/cache.py +++ b/pymt/cache.py @@ -153,7 +153,7 @@ def remove(category, key=None): @staticmethod def _purge_oldest(category, maxpurge=1): - print 'PURGE', category + print('PURGE', category) import heapq heap_list = [] for key in Cache._objects[category]: @@ -161,12 +161,12 @@ def _purge_oldest(category, maxpurge=1): if obj['lastaccess'] == obj['timestamp']: continue heapq.heappush(heap_list, (obj['lastaccess'], key)) - print '<<<', obj['lastaccess'] + print('<<<', obj['lastaccess']) n = 0 while n < maxpurge: try: lastaccess, key = heapq.heappop(heap_list) - print '=>', key, lastaccess, getClock().get_time() + print('=>', key, lastaccess, getClock().get_time()) except Exception: return del Cache._objects[category][key] @@ -190,7 +190,7 @@ def _purge_by_timeout(dt): Cache._categories[category]['timeout'] = timeout continue - for key in Cache._objects[category].keys()[:]: + for key in list(Cache._objects[category].keys())[:]: lastaccess = Cache._objects[category][key]['lastaccess'] objtimeout = Cache._objects[category][key]['timeout'] @@ -209,14 +209,14 @@ def _purge_by_timeout(dt): @staticmethod def print_usage(): '''Print the cache usage on the console''' - print 'Cache usage :' + print('Cache usage :') for category in Cache._categories: - print ' * %s : %d / %s, timeout=%s' % ( + print(' * %s : %d / %s, timeout=%s' % ( category.capitalize(), len(Cache._objects[category]), str(Cache._categories[category]['limit']), str(Cache._categories[category]['timeout']) - ) + )) # install the schedule clock for purging getClock().schedule_interval(Cache._purge_by_timeout, 1) diff --git a/pymt/config.py b/pymt/config.py index 6c12b404..ca125e6f 100644 --- a/pymt/config.py +++ b/pymt/config.py @@ -4,7 +4,7 @@ __all__ = ('pymt_config', ) -from ConfigParser import ConfigParser +from configparser import ConfigParser import sys import os from pymt.logger import pymt_logger @@ -52,7 +52,7 @@ def write(self): if os.path.exists(pymt_config_fn): try: pymt_config.read(pymt_config_fn) - except Exception, e: + except Exception as e: pymt_logger.exception('Core: error while reading local' 'configuration') @@ -134,7 +134,7 @@ def write(self): # add log_file format pymt_config.setdefault('pymt', 'log_enable', '1') pymt_config.setdefault('pymt', 'log_dir', 'logs') - pymt_config.setdefault('pymt', 'log_name', 'pymt_%y-%m-%d_%_.txt') + pymt_config.setdefault('pymt', 'log_name', 'pymt_%%y-%%m-%%d_%%_.txt') elif pymt_config_version == 7: # add option to turn off pyOpenGL Error Checking @@ -183,7 +183,7 @@ def write(self): pymt_config_version += 1 # Said to pymt_config that we've upgrade to latest version. - pymt_config.set('pymt', 'config_version', PYMT_CONFIG_VERSION) + pymt_config.set('pymt', 'config_version', str(PYMT_CONFIG_VERSION)) # Now, activate log file if pymt_config.getint('pymt', 'log_enable'): @@ -193,5 +193,5 @@ def write(self): if not os.path.exists(pymt_config_fn) or need_save: try: pymt_config.write() - except Exception, e: + except Exception as e: pymt_logger.exception('Core: error while saving default configuration file') diff --git a/pymt/core/__init__.py b/pymt/core/__init__.py index 79f40c9f..edda04f6 100644 --- a/pymt/core/__init__.py +++ b/pymt/core/__init__.py @@ -76,4 +76,4 @@ def core_register_libs(category, libs): from pymt.core.clipboard import * # only after core loading, load extensions -from text.markup import * +from .text.markup import * diff --git a/pymt/core/clipboard/clipboard_dummy.py b/pymt/core/clipboard/clipboard_dummy.py index e7c0489f..9e48ec74 100644 --- a/pymt/core/clipboard/clipboard_dummy.py +++ b/pymt/core/clipboard/clipboard_dummy.py @@ -20,5 +20,5 @@ def put(self, data, mimetype='text/plain'): self._data[mimetype] = data def get_types(self): - return self._data.keys() + return list(self._data.keys()) diff --git a/pymt/core/image/__init__.py b/pymt/core/image/__init__.py index 77232354..79561e92 100644 --- a/pymt/core/image/__init__.py +++ b/pymt/core/image/__init__.py @@ -84,10 +84,11 @@ def get_texture(self): class ImageLoader(object): __slots__ = ('loaders') - loaders = [] @staticmethod def register(defcls): + if not subcls.loaders: + subcls.loaders = [] ImageLoader.loaders.append(defcls) @staticmethod @@ -161,7 +162,7 @@ def __init__(self, arg, **kwargs): self.height = self.texture.height elif isinstance(arg, ImageLoaderBase): self.image = arg - elif isinstance(arg, basestring): + elif isinstance(arg, str): self.filename = arg else: raise Exception('Unable to load image with type %s' % str(type(arg))) @@ -277,7 +278,7 @@ def read_pixel(self, x, y): size = 3 if data.mode in ('RGB', 'BGR') else 4 index = y * data.width * size + x * size raw = data.data[index:index+size] - color = map(lambda c: ord(c) / 255.0, raw) + color = [ord(c) / 255.0 for c in raw] # conversion for BGR->RGB, BGR->RGBA format if data.mode in ('BGR', 'BGRA'): diff --git a/pymt/core/svg/__init__.py b/pymt/core/svg/__init__.py index 43974483..788fb0fa 100644 --- a/pymt/core/svg/__init__.py +++ b/pymt/core/svg/__init__.py @@ -35,10 +35,11 @@ def __getattr__ (self, name): class SvgLoader(object): __slots__ = ('loaders') - loaders = [] @staticmethod def register(subcls): + if not subcls.loaders: + subcls.loaders = [] SvgLoader.loaders.append(subcls) @staticmethod @@ -95,7 +96,7 @@ def __init__(self, arg, **kwargs): self.anchor_y = 0 #this actually loads the svg - if isinstance(arg, basestring): + if isinstance(arg, str): self.filename = arg else: raise Exception('Unable to load image with type %s' % str(type(arg))) diff --git a/pymt/core/text/__init__.py b/pymt/core/text/__init__.py index 7661348c..90c32e04 100644 --- a/pymt/core/text/__init__.py +++ b/pymt/core/text/__init__.py @@ -341,8 +341,8 @@ def draw(self): size = list(texture.size) texc = texture.tex_coords[:] if viewport_size: - vw, vh = map(float, viewport_size) - tw, th = map(float, size) + vw, vh = list(map(float, viewport_size)) + tw, th = list(map(float, size)) oh, ow = tch, tcw = texc[1:3] tcx, tcy = 0, 0 if vw < tw: diff --git a/pymt/core/text/markup.py b/pymt/core/text/markup.py index 924783cd..8f0e75f3 100644 --- a/pymt/core/text/markup.py +++ b/pymt/core/text/markup.py @@ -188,7 +188,7 @@ def render_label(self, real, label, args): else: # really render now. x, y = _x, _y - for i in xrange(len(lines)): + for i in range(len(lines)): size, glyphs = lines[i] for glyph in glyphs: lw, lh = cache[glyph] diff --git a/pymt/core/text/text_cairo.py b/pymt/core/text/text_cairo.py index f04e22db..e0cb2b41 100644 --- a/pymt/core/text/text_cairo.py +++ b/pymt/core/text/text_cairo.py @@ -67,7 +67,7 @@ def _render_begin(self): self._select_font(self._cairo_context) def _render_text(self, text, x, y): - color = map(lambda x: x * 255, self.options['color']) + color = [x * 255 for x in self.options['color']] self._cairo_context.set_source_rgba(*color) self._cairo_context.move_to(x, y + self._font_extents[FONT_EXTENTS_ASCENT_IDX]) diff --git a/pymt/core/text/text_pil.py b/pymt/core/text/text_pil.py index 606585f7..87f394e0 100644 --- a/pymt/core/text/text_pil.py +++ b/pymt/core/text/text_pil.py @@ -21,7 +21,7 @@ class LabelPIL(LabelBase): def _select_font(self): fontsize = int(self.options['font_size'] * 1.333) fontname = self.options['font_name'].split(',')[0] - id = '%s.%s' % (unicode(fontname), unicode(fontsize)) + id = '%s.%s' % (str(fontname), str(fontsize)) if not id in self._cache: filename = os.path.join(pymt.pymt_data_dir, 'DejaVuSans.ttf') font = ImageFont.truetype(filename, fontsize) @@ -40,7 +40,7 @@ def _render_begin(self): self._pil_draw = ImageDraw.Draw(self._pil_im) def _render_text(self, text, x, y): - color = tuple(map(lambda x: int(x * 255), self.options['color'])) + color = tuple([int(x * 255) for x in self.options['color']]) self._pil_draw.text((int(x), int(y)), text, font=self._select_font(), fill=color) def _render_end(self): diff --git a/pymt/core/text/text_pygame.py b/pymt/core/text/text_pygame.py index 20f3ecd1..ec7a6109 100644 --- a/pymt/core/text/text_pygame.py +++ b/pymt/core/text/text_pygame.py @@ -19,7 +19,7 @@ class LabelPygame(LabelBase): def _get_font_id(self): - return '|'.join([unicode(self.options[x]) for x \ + return '|'.join([str(self.options[x]) for x \ in ('font_size', 'font_name', 'bold', 'italic')]) def _get_font(self): diff --git a/pymt/core/video/video_gstreamer.py b/pymt/core/video/video_gstreamer.py index 7a044325..e5788d52 100644 --- a/pymt/core/video/video_gstreamer.py +++ b/pymt/core/video/video_gstreamer.py @@ -230,7 +230,7 @@ def update(self): for i in self._decoder.src_pads(): cap = i.get_caps()[0] structure_name = cap.get_name() - if structure_name.startswith('video') and cap.has_key('width'): + if structure_name.startswith('video') and 'width' in cap: self._videosize = self.size = (cap['width'], cap['height']) self._texture = pymt.Texture.create( self._videosize[0], self._videosize[1], format=GL_RGB) diff --git a/pymt/event.py b/pymt/event.py index 83891e5e..08d4c189 100644 --- a/pymt/event.py +++ b/pymt/event.py @@ -287,7 +287,7 @@ def _get_handlers(self, args, kwargs): for name in dir(obj): if name in self._event_types: yield name, getattr(obj, name) - for name, handler in kwargs.iteritems(): + for name, handler in kwargs.items(): # Function for handling given event (no magic) if name not in self._event_types: raise Exception('Unknown event "%s"' % name) @@ -379,7 +379,7 @@ def _raise_dispatch_exception(self, event_type, args, handler): if not hasattr(handler, 'im_func'): raise - if not isinstance(handler.im_func, types.FunctionType): + if not isinstance(handler.__func__, types.FunctionType): raise n_args = len(args) @@ -390,7 +390,7 @@ def _raise_dispatch_exception(self, event_type, args, handler): n_handler_args = len(handler_args) # Remove "self" arg from handler if it's a bound method - if inspect.ismethod(handler) and handler.im_self: + if inspect.ismethod(handler) and handler.__self__: n_handler_args -= 1 # Allow *args varargs to overspecify arguments @@ -406,9 +406,9 @@ def _raise_dispatch_exception(self, event_type, args, handler): if n_handler_args != n_args: if inspect.isfunction(handler) or inspect.ismethod(handler): descr = '%s at %s:%d' % ( - handler.func_name, - handler.func_code.co_filename, - handler.func_code.co_firstlineno) + handler.__name__, + handler.__code__.co_filename, + handler.__code__.co_firstlineno) else: descr = repr(handler) @@ -449,7 +449,7 @@ def decorator(func): name = func.__name__ self.set_handler(name, func) return args[0] - elif isinstance(args[0], basestring): # @a.event('on_event') + elif isinstance(args[0], str): # @a.event('on_event') name = args[0] def decorator(func): self.set_handler(name, func) @@ -491,5 +491,5 @@ def lambda_connect(*largs): if accelerate is not None: EventDispatcher.dispatch_event = types.MethodType( accelerate.eventdispatcher_dispatch_event, None, EventDispatcher) -except ImportError, e: +except ImportError as e: pymt_logger.warning('Event: Unable to use accelerate module <%s>' % e) diff --git a/pymt/gesture.py b/pymt/gesture.py index d4533488..1cdf8f73 100644 --- a/pymt/gesture.py +++ b/pymt/gesture.py @@ -25,6 +25,7 @@ import math from pymt.vector import Vector +from functools import reduce class GestureDatabase(object): '''Class to handle a gesture database.''' @@ -54,7 +55,7 @@ def find(self, gesture, minscore=0.9, rotation_invariant=True): def gesture_to_str(self, gesture): '''Convert a gesture into a unique string''' - from cStringIO import StringIO + from io import StringIO import pickle, base64, zlib io = StringIO() p = pickle.Pickler(io) @@ -64,7 +65,7 @@ def gesture_to_str(self, gesture): def str_to_gesture(self, data): '''Convert a unique string to a gesture''' - from cStringIO import StringIO + from io import StringIO import pickle, base64, zlib io = StringIO(zlib.decompress(base64.b64decode(data))) p = pickle.Unpickler(io) @@ -129,7 +130,7 @@ def scale_stroke(self, scale_factor): scale_stroke(scale_factor=float) Scales the stroke down by scale_factor ''' - self.points = map(lambda pt: pt.scale(scale_factor), self.points) + self.points = [pt.scale(scale_factor) for pt in self.points] def points_distance(self, point1, point2): ''' @@ -150,7 +151,7 @@ def stroke_length(self, point_list=None): gesture_length = 0.0 if len(point_list) <= 1: # If there is only one point -> no length return gesture_length - for i in xrange(len(point_list)-1): + for i in range(len(point_list)-1): gesture_length += self.points_distance( point_list[i], point_list[i+1]) return gesture_length @@ -237,10 +238,10 @@ def _scale_gesture(self): ''' Scales down the gesture to a unit of 1 ''' # map() creates a list of min/max coordinates of the strokes # in the gesture and min()/max() pulls the lowest/highest value - min_x = min(map(lambda stroke: stroke.min_x, self.strokes)) - max_x = max(map(lambda stroke: stroke.max_x, self.strokes)) - min_y = min(map(lambda stroke: stroke.min_y, self.strokes)) - max_y = max(map(lambda stroke: stroke.max_y, self.strokes)) + min_x = min([stroke.min_x for stroke in self.strokes]) + max_x = max([stroke.max_x for stroke in self.strokes]) + min_y = min([stroke.min_y for stroke in self.strokes]) + max_y = max([stroke.max_y for stroke in self.strokes]) x_len = max_x - min_x self.width = x_len y_len = max_y - min_y diff --git a/pymt/graphx/bezier.py b/pymt/graphx/bezier.py index ea3b599b..50c68292 100644 --- a/pymt/graphx/bezier.py +++ b/pymt/graphx/bezier.py @@ -86,7 +86,7 @@ def path_end(self): def path_curve_to(self, x1, y1, x2, y2, x, y): '''Add a control point into bezier path''' if not self._bezier_coefficients: - for i in xrange(self._bezier_points + 1): + for i in range(self._bezier_points + 1): t = float(i) / self._bezier_points t0 = (1 - t) ** 3 t1 = 3 * t * (1 - t) ** 2 @@ -103,7 +103,7 @@ def path_curve_to(self, x1, y1, x2, y2, x, y): def calculate_from_bezier_path(self, points): '''Create a new path from a list of control points''' self.path_begin(points[0], points[1]) - for i in xrange(2, len(points), 6): + for i in range(2, len(points), 6): x1, y1, x2, y2, x, y = points[i:i+6] self.path_curve_to(x1, y1, x2, y2, x, y) self.path_end() diff --git a/pymt/graphx/colors.py b/pymt/graphx/colors.py index d62be0cf..5d56af29 100644 --- a/pymt/graphx/colors.py +++ b/pymt/graphx/colors.py @@ -36,7 +36,7 @@ def set_color(*colors, **kwargs): kwargs.setdefault('blend', None) force_blend = kwargs['blend'] == True if len(colors) == 1: - if type(colors[0]) in (unicode, str): + if type(colors[0]) in (str, str): colors = get_color_from_hex(colors[0]) else: colors = (colors[0], colors[0], colors[0]) diff --git a/pymt/graphx/draw.py b/pymt/graphx/draw.py index ae46d54c..e3816812 100644 --- a/pymt/graphx/draw.py +++ b/pymt/graphx/draw.py @@ -26,7 +26,7 @@ try: import pymt.c_ext.c_graphx as c_graphx pymt.pymt_logger.info('Graphx: Using accelerate graphx module') -except ImportError, e: +except ImportError as e: c_graphx = None pymt.pymt_logger.warning('Extensions: c_graphx not available: <%s>' % e) @@ -247,7 +247,7 @@ def drawPolygon(points, style=GL_POLYGON, linewidth=0): `linewidth`: int, defaults to current OpenGL state. Sets the linewidth if drawign style is a line based one ''' - if isinstance(style, basestring): + if isinstance(style, str): if style in ('fill', 'GL_POLYGON'): style = GL_POLYGON if style in ('line', 'GL_LINE_LOOP'): diff --git a/pymt/graphx/fbo.py b/pymt/graphx/fbo.py index 6d692077..fc641864 100644 --- a/pymt/graphx/fbo.py +++ b/pymt/graphx/fbo.py @@ -12,8 +12,8 @@ import OpenGL import pymt from OpenGL.GL import GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, \ - GL_VIEWPORT_BIT, GL_TEXTURE_2D, GL_COLOR_ATTACHMENT0_EXT, \ - GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, GL_DEPTH_ATTACHMENT_EXT, \ + GL_VIEWPORT_BIT, GL_TEXTURE_2D, \ + GL_DEPTH_COMPONENT, \ GL_BACK, GL_RGBA, GL_UNSIGNED_BYTE, GL_STENCIL_TEST, \ GL_STENCIL_BUFFER_BIT, \ glClear, glClearColor, glPushAttrib, glPopAttrib, \ @@ -31,7 +31,7 @@ glBindFramebufferEXT, glBindRenderbufferEXT, \ glDeleteRenderbuffersEXT, glDeleteFramebuffersEXT, \ glCheckFramebufferStatusEXT, glFramebufferRenderbufferEXT, \ - glRenderbufferStorageEXT, glFramebufferTexture2DEXT + glRenderbufferStorageEXT, glFramebufferTexture2DEXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT from pymt.graphx.colors import set_color from pymt.graphx.draw import drawTexturedRectangle, set_texture, get_texture_id @@ -89,7 +89,7 @@ def __init__(self, **kwargs): elif isinstance(self.texture, pymt.Texture): self.realsize = self.texture.width, self.texture.height else: - raise 'Unknown type(self.texture). Please send a bug report on pymt dev.' + raise Exception('Unknown type(self.texture). Please send a bug report on pymt dev.') def bind(self): '''Activate writing on Framebuffer. All next call will be done on it.''' @@ -158,7 +158,7 @@ def __init__(self, **kwargs): self.framebuffer = glGenFramebuffersEXT(1) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, self.framebuffer) if self.framebuffer == 0: - raise 'Failed to initialize framebuffer' + raise Exception('Failed to initialize framebuffer') if self.with_depthbuffer: self.depthbuffer = glGenRenderbuffersEXT(1) diff --git a/pymt/graphx/paint.py b/pymt/graphx/paint.py index 0f509fb8..f4dd3001 100644 --- a/pymt/graphx/paint.py +++ b/pymt/graphx/paint.py @@ -13,8 +13,10 @@ import pymt from math import sqrt from OpenGL.GL import GL_POINTS, GL_TEXTURE_2D, GL_SRC_ALPHA, \ - GL_ONE_MINUS_SRC_ALPHA, GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, \ + GL_ONE_MINUS_SRC_ALPHA, \ GL_TRUE, glPointSize, glVertex2f, glBindTexture, glTexEnvi +from OpenGL.GL.ARB.point_sprite import GL_POINT_SPRITE_ARB +from OpenGL.GL.ARB.point_sprite import GL_COORD_REPLACE_ARB from pymt.graphx.statement import gx_enable, gx_begin, DO, GlBlending __brushs_cache = dict() @@ -120,7 +122,7 @@ def paintLine(points, numsteps=None, **kwargs): steps = max(1, int(dist) / 4) # construct pointList - for i in xrange(steps): + for i in range(steps): outputList.extend([x1 + dx * (float(i) / steps), y1 + dy * (float(i) / steps)]) diff --git a/pymt/graphx/shader.py b/pymt/graphx/shader.py index 79c9e177..83b19d11 100644 --- a/pymt/graphx/shader.py +++ b/pymt/graphx/shader.py @@ -48,7 +48,7 @@ def create_shader(self, source, shadertype): shader = glCreateShader(shadertype) # PyOpenGL bug ? He's waiting for a list of string, not a string # on some card, it failed :) - if isinstance(source, basestring): + if isinstance(source, str): source = [source] glShaderSource(shader, source) glCompileShader(shader) diff --git a/pymt/graphx/stencil.py b/pymt/graphx/stencil.py index 316d39eb..67899987 100644 --- a/pymt/graphx/stencil.py +++ b/pymt/graphx/stencil.py @@ -83,7 +83,7 @@ def stencilPop(): glColorMask(0, 0, 0, 0) # replay all gl operation - for idx in xrange(__stencil_stack): + for idx in range(__stencil_stack): dl = __stencil_stack_dl[idx] view = __stencil_stack_view[idx] with gx_matrix_identity: diff --git a/pymt/input/postproc/__init__.py b/pymt/input/postproc/__init__.py index f4bbafa9..f598a710 100644 --- a/pymt/input/postproc/__init__.py +++ b/pymt/input/postproc/__init__.py @@ -5,10 +5,10 @@ __all__ = ('pymt_postproc_modules', ) import os -import doubletap -import ignorelist -import retaintouch -import dejitter +from . import doubletap +from . import ignorelist +from . import retaintouch +from . import dejitter # Mapping of ID to module pymt_postproc_modules = {} diff --git a/pymt/input/postproc/doubletap.py b/pymt/input/postproc/doubletap.py index f9421e4e..1071b4f4 100644 --- a/pymt/input/postproc/doubletap.py +++ b/pymt/input/postproc/doubletap.py @@ -61,7 +61,7 @@ def process(self, events): # second, check if up-touch is timeout for double tap time_current = getClock().get_time() - for touchid in self.touches.keys()[:]: + for touchid in list(self.touches.keys())[:]: type, touch = self.touches[touchid] if type != 'up': continue diff --git a/pymt/input/provider.py b/pymt/input/provider.py index 1ea17edd..28de2743 100644 --- a/pymt/input/provider.py +++ b/pymt/input/provider.py @@ -9,7 +9,7 @@ class TouchProvider(object): def __init__(self, device, args): self.device = device if self.__class__ == TouchProvider: - raise NotImplementedError, 'class TouchProvider is abstract' + raise NotImplementedError('class TouchProvider is abstract') def start(self): pass diff --git a/pymt/input/providers/hidinput.py b/pymt/input/providers/hidinput.py index 07ebfb4f..cfebfdaf 100644 --- a/pymt/input/providers/hidinput.py +++ b/pymt/input/providers/hidinput.py @@ -234,7 +234,7 @@ def process(points): touch = HIDTouch(device, tid, args) touches[touch.id] = touch - for tid in touches.keys()[:]: + for tid in list(touches.keys())[:]: if tid not in actives: touch = touches[tid] if tid in touches_sent: @@ -255,7 +255,7 @@ def normalize(value, vmin, vmax): # get abs infos bit = fcntl.ioctl(fd, EVIOCGBIT + (EV_MAX << 16), ' ' * sz_l) bit, = struct.unpack('Q', bit) - for x in xrange(EV_MAX): + for x in range(EV_MAX): # preserve this, we may want other things than EV_ABS if x != EV_ABS: continue @@ -265,7 +265,7 @@ def normalize(value, vmin, vmax): # ask abs info keys to the devices sbit = fcntl.ioctl(fd, EVIOCGBIT + x + (KEY_MAX << 16), ' ' * sz_l) sbit, = struct.unpack('Q', sbit) - for y in xrange(KEY_MAX): + for y in range(KEY_MAX): if (sbit & (1 << y)) == 0: continue absinfo = fcntl.ioctl(fd, EVIOCGABS + y + @@ -300,7 +300,7 @@ def normalize(value, vmin, vmax): break # extract each event - for i in xrange(len(data) / struct_input_event_sz): + for i in range(len(data) / struct_input_event_sz): ev = data[i * struct_input_event_sz:] # extract timeval + event infos diff --git a/pymt/input/providers/linuxwacom.py b/pymt/input/providers/linuxwacom.py index 762e40a1..a5e64629 100644 --- a/pymt/input/providers/linuxwacom.py +++ b/pymt/input/providers/linuxwacom.py @@ -218,8 +218,8 @@ def _thread_run(self, **kwargs): reset_touch = False def process(points): - actives = points.keys() - for args in points.itervalues(): + actives = list(points.keys()) + for args in points.values(): tid = args['id'] try: touch = touches[tid] @@ -234,7 +234,7 @@ def process(points): touches_sent.append(tid) queue.append(('move', touch)) - for tid in touches.keys()[:]: + for tid in list(touches.keys())[:]: if tid not in actives: touch = touches[tid] if tid in touches_sent: @@ -255,7 +255,7 @@ def normalize(value, vmin, vmax): # get abs infos bit = fcntl.ioctl(fd, EVIOCGBIT + (EV_MAX << 16), ' ' * sz_l) bit, = struct.unpack('Q', bit) - for x in xrange(EV_MAX): + for x in range(EV_MAX): # preserve this, we may want other things than EV_ABS if x != EV_ABS: continue @@ -265,7 +265,7 @@ def normalize(value, vmin, vmax): # ask abs info keys to the devices sbit = fcntl.ioctl(fd, EVIOCGBIT + x + (KEY_MAX << 16), ' ' * sz_l) sbit, = struct.unpack('Q', sbit) - for y in xrange(KEY_MAX): + for y in range(KEY_MAX): if (sbit & (1 << y)) == 0: continue absinfo = fcntl.ioctl(fd, EVIOCGABS + y + @@ -306,7 +306,7 @@ def normalize(value, vmin, vmax): break # extract each event - for i in xrange(len(data) / struct_input_event_sz): + for i in range(len(data) / struct_input_event_sz): ev = data[i * struct_input_event_sz:] # extract timeval + event infos diff --git a/pymt/input/providers/mactouch.py b/pymt/input/providers/mactouch.py index e8c80bcd..b84066f4 100644 --- a/pymt/input/providers/mactouch.py +++ b/pymt/input/providers/mactouch.py @@ -120,10 +120,10 @@ def start(self): # ok, listing devices, and attach ! devices = MultitouchSupport.MTDeviceCreateList() num_devices = CFArrayGetCount(devices) - print 'num_devices =', num_devices - for i in xrange(num_devices): + print('num_devices =', num_devices) + for i in range(num_devices): device = CFArrayGetValueAtIndex(devices, i) - print 'device #%d: %016x' % (i, device) + print('device #%d: %016x' % (i, device)) # create touch dict for this device data_id = str(device) self.touches[data_id] = {} @@ -158,7 +158,7 @@ def _mts_callback(device, data_ptr, n_fingers, timestamp, frame): touches = _instance.touches[devid] actives = [] - for i in xrange(n_fingers): + for i in range(n_fingers): # get pointer on data data = data_ptr[i] @@ -192,7 +192,7 @@ def _mts_callback(device, data_ptr, n_fingers, timestamp, frame): _instance.queue.append(('move', touch)) # delete old touchs - for tid in touches.keys()[:]: + for tid in list(touches.keys())[:]: if tid not in actives: touch = touches[tid] _instance.queue.append(('up', touch)) diff --git a/pymt/input/providers/mouse.py b/pymt/input/providers/mouse.py index f81d9625..2b5da1bb 100644 --- a/pymt/input/providers/mouse.py +++ b/pymt/input/providers/mouse.py @@ -76,7 +76,7 @@ def test_activity(self): def find_touch(self, x, y): factor = 10. / self.window.system_size[0] - for t in self.touches.itervalues(): + for t in self.touches.values(): if abs(x-t.sx) < factor and abs(y-t.sy) < factor: return t return False @@ -157,7 +157,7 @@ def update(self, dispatch_fn): while True: event = self.waiting_event.popleft() dispatch_fn(*event) - except Exception, e: + except Exception as e: pass # registers diff --git a/pymt/input/providers/tuio.py b/pymt/input/providers/tuio.py index dd549c58..becb126a 100644 --- a/pymt/input/providers/tuio.py +++ b/pymt/input/providers/tuio.py @@ -198,14 +198,14 @@ def __init__(self, device, id, args): def depack(self, args): if len(args) < 5: - self.sx, self.sy = map(float, args[0:2]) + self.sx, self.sy = list(map(float, args[0:2])) self.profile = ('pos', ) elif len(args) == 5: - self.sx, self.sy, self.X, self.Y, self.m = map(float, args[0:5]) + self.sx, self.sy, self.X, self.Y, self.m = list(map(float, args[0:5])) self.Y = -self.Y self.profile = ('pos', 'mov', 'motacc') else: - self.sx, self.sy, self.X, self.Y, self.m, width, height = map(float, args[0:7]) + self.sx, self.sy, self.X, self.Y, self.m, width, height = list(map(float, args[0:7])) self.Y = -self.Y self.profile = ('pos', 'mov', 'motacc', 'shape') if self.shape is None: diff --git a/pymt/input/providers/wm_touch.py b/pymt/input/providers/wm_touch.py index 14654348..6af8edb1 100644 --- a/pymt/input/providers/wm_touch.py +++ b/pymt/input/providers/wm_touch.py @@ -134,11 +134,11 @@ def update(self, dispatch_fn): self.uid, [x, y, t.size()]) dispatch_fn('down', self.touches[t.id] ) - if t.event_type == 'move' and self.touches.has_key(t.id): + if t.event_type == 'move' and t.id in self.touches: self.touches[t.id].move([x, y, t.size()]) dispatch_fn('move', self.touches[t.id] ) - if t.event_type == 'up' and self.touches.has_key(t.id): + if t.event_type == 'up' and t.id in self.touches: self.touches[t.id].move([x, y, t.size()]) dispatch_fn('up', self.touches[t.id] ) del self.touches[t.id] @@ -178,7 +178,7 @@ def _touch_handler(self, msg, wParam, lParam): wParam, pointer(touches), sizeof(TOUCHINPUT)) - for i in xrange(wParam): + for i in range(wParam): self.touch_events.appendleft(touches[i]) return True diff --git a/pymt/input/touch.py b/pymt/input/touch.py index a6810a01..8113c53c 100644 --- a/pymt/input/touch.py +++ b/pymt/input/touch.py @@ -60,7 +60,7 @@ def __new__(mcs, name, bases, attrs): return super(TouchMetaclass, mcs).__new__(mcs, name, bases, attrs) -class Touch(object): +class Touch(object, metaclass=TouchMetaclass): '''Abstract class to represent a touch, and support TUIO 1.0 definition. :Parameters: @@ -69,8 +69,6 @@ class Touch(object): `args` : list list of parameters, passed to depack() function ''' - - __metaclass__ = TouchMetaclass __uniq_id = 0 __attrs__ = \ ('device', 'attr', @@ -85,7 +83,7 @@ class Touch(object): def __init__(self, device, id, args): if self.__class__ == Touch: - raise NotImplementedError, 'class Touch is abstract' + raise NotImplementedError('class Touch is abstract') # Uniq ID Touch.__uniq_id += 1 @@ -226,7 +224,7 @@ def push(self, attrs=None): def pop(self): '''Pop attributes values from the stack''' attrs, values = self.attr.pop() - for i in xrange(len(attrs)): + for i in range(len(attrs)): setattr(self, attrs[i], values[i]) def apply_transform_2d(self, transform): diff --git a/pymt/lib/osc/OSC.py b/pymt/lib/osc/OSC.py index fab81770..b1aa3b29 100644 --- a/pymt/lib/osc/OSC.py +++ b/pymt/lib/osc/OSC.py @@ -42,10 +42,10 @@ def hexDump(bytes): for i in range(len(bytes)): sys.stdout.write("%2x " % (ord(bytes[i]))) if (i+1) % 8 == 0: - print repr(bytes[i-7:i+1]) + print(repr(bytes[i-7:i+1])) if(len(bytes) % 8 != 0): - print string.rjust("", 11), repr(bytes[i-len(bytes)%8:i+1]) + print(string.rjust("", 11), repr(bytes[i-len(bytes)%8:i+1])) class OSCMessage: @@ -114,7 +114,7 @@ def readBlob(data): def readInt(data): if(len(data)<4): - print "Error: too few bytes for int", data, len(data) + print("Error: too few bytes for int", data, len(data)) rest = data integer = 0 else: @@ -129,7 +129,7 @@ def readLong(data): """Tries to interpret the next 8 bytes of the data as a 64-bit signed integer.""" high, low = struct.unpack(">ll", data[0:8]) - big = (long(high) << 32) + low + big = (int(high) << 32) + low rest = data[8:] return (big, rest) @@ -146,7 +146,7 @@ def readDouble(data): def readFloat(data): if(len(data)<4): - print "Error: too few bytes for float", data, len(data) + print("Error: too few bytes for float", data, len(data)) rest = data float = 0 else: @@ -200,7 +200,7 @@ def parseArgs(args): possible) as floats or integers.""" parsed = [] for arg in args: - print arg + print(arg) arg = arg.strip() interpretation = None try: @@ -241,7 +241,7 @@ def decodeOSC(data): value, rest = table[tag](rest) decoded.append(value) else: - print "Oops, typetag lacks the magic ," + print("Oops, typetag lacks the magic ,") return decoded @@ -276,15 +276,15 @@ def dispatch(self, message, source = None): for msg in message : self.dispatch(msg, source) - except KeyError, e: + except KeyError as e: # address not found - print 'address %s not found ' % address + print('address %s not found ' % address) pprint.pprint(message) - except IndexError, e: - print 'got malformed OSC message' + except IndexError as e: + print('got malformed OSC message') pass - except None, e: - print "Exception in", address, "callback :", e + except None as e: + print("Exception in", address, "callback :", e) return @@ -312,7 +312,7 @@ def unbundler(self, messages): if __name__ == "__main__": hexDump("Welcome to the OSC testing program.") - print + print() message = OSCMessage() message.setAddress("/foo/play") message.append(44) @@ -321,7 +321,7 @@ def unbundler(self, messages): message.append("the white cliffs of dover") hexDump(message.getBinary()) - print "Making and unmaking a message.." + print("Making and unmaking a message..") strings = OSCMessage() strings.append("Mary had a little lamb") @@ -336,26 +336,26 @@ def unbundler(self, messages): hexDump(raw) - print "Retrieving arguments..." + print("Retrieving arguments...") data = raw for i in range(6): text, data = readString(data) - print text + print(text) number, data = readFloat(data) - print number + print(number) number, data = readFloat(data) - print number + print(number) number, data = readInt(data) - print number + print(number) hexDump(raw) - print decodeOSC(raw) - print decodeOSC(message.getBinary()) + print(decodeOSC(raw)) + print(decodeOSC(message.getBinary())) - print "Testing Blob types." + print("Testing Blob types.") blob = OSCMessage() blob.append("","b") @@ -368,7 +368,7 @@ def unbundler(self, messages): hexDump(blob.getBinary()) - print decodeOSC(blob.getBinary()) + print(decodeOSC(blob.getBinary())) def printingCallback(*stuff): sys.stdout.write("Got: ") @@ -376,7 +376,7 @@ def printingCallback(*stuff): sys.stdout.write(str(i) + " ") sys.stdout.write("\n") - print "Testing the callback manager." + print("Testing the callback manager.") c = CallbackManager() c.add(printingCallback, "/print") @@ -403,5 +403,5 @@ def printingCallback(*stuff): bundlebinary = bundle.message - print "sending a bundle to the callback manager" + print("sending a bundle to the callback manager") c.handle(bundlebinary) diff --git a/pymt/lib/osc/__init__.py b/pymt/lib/osc/__init__.py index 9276a36d..d9fea702 100644 --- a/pymt/lib/osc/__init__.py +++ b/pymt/lib/osc/__init__.py @@ -5,7 +5,7 @@ __license__ = "GNU General Public License" __all__ = ("oscAPI", "OSC") -from OSC import * -from oscAPI import * +from .OSC import * +from .oscAPI import * diff --git a/pymt/lib/osc/oscAPI.py b/pymt/lib/osc/oscAPI.py index 39edb3fa..1475e74e 100644 --- a/pymt/lib/osc/oscAPI.py +++ b/pymt/lib/osc/oscAPI.py @@ -28,7 +28,7 @@ Thanks for the support to Buchsenhausen, Innsbruck, Austria. ''' -import OSC +from . import OSC import socket, os, time, errno, sys from threading import Lock from pymt.logger import pymt_logger @@ -202,7 +202,7 @@ def run(self): self.socket.settimeout(0.5) self.haveSocket = True - except socket.error, e: + except socket.error as e: error, message = e.args # special handle for EADDRINUSE @@ -221,7 +221,7 @@ def run(self): try: message = self.socket.recv(65535) self._queue_message(message) - except Exception, e: + except Exception as e: if type(e) == socket.timeout: continue pymt_logger.error('OSC: Error in Tuio recv()') @@ -249,7 +249,7 @@ def dontListen(id = None): if id and id in oscThreads: ids = [id] else: - ids = oscThreads.keys() + ids = list(oscThreads.keys()) for id in ids: #oscThreads[id].socket.close() pymt_logger.debug('OSC: Stop thread <%s>' % id) @@ -269,9 +269,9 @@ def dontListen(id = None): def printStuff(msg): '''deals with "print" tagged OSC addresses ''' - print "printing in the printStuff function ", msg - print "the oscaddress is ", msg[0] - print "the value is ", msg[2] + print("printing in the printStuff function ", msg) + print("the oscaddress is ", msg[0]) + print("the value is ", msg[2]) bind(printStuff, "/test") diff --git a/pymt/lib/squirtle.py b/pymt/lib/squirtle.py index 29eeae3e..abe71522 100644 --- a/pymt/lib/squirtle.py +++ b/pymt/lib/squirtle.py @@ -26,10 +26,10 @@ import math try: # get the faster one - from cStringIO import StringIO + from io import StringIO except ImportError: # fallback to the default one - from StringIO import StringIO + from io import StringIO from pymt.logger import pymt_logger BEZIER_POINTS = 10 @@ -234,7 +234,7 @@ def parse_color(c, default=None): else: pymt_logger.exception('Squirtle: incorrect length for color %s' % str(c)) return [r, g, b, 255] - except Exception, ex: + except Exception as ex: pymt_logger.exception('Squirtle: exception parsing color %s' % str(c)) return None @@ -524,7 +524,7 @@ def render_slowly(self): for loop in path: self.n_lines += len(loop) - 1 loop_plus = [] - for i in xrange(len(loop) - 1): + for i in range(len(loop) - 1): loop_plus += [loop[i], loop[i+1]] if isinstance(stroke, str): g = self.gradients[stroke] @@ -562,7 +562,7 @@ def parse_doc(self): for e in self.tree._root.getchildren(): try: self.parse_element(e) - except Exception, ex: + except Exception as ex: pymt_logger.exception('Squirtle: exception while parsing element %s' % e) raise @@ -663,9 +663,9 @@ def pnext(): elif e.tag.endswith('rect'): x = 0 y = 0 - if 'x' in e.keys(): + if 'x' in list(e.keys()): x = float(e.get('x')) - if 'y' in e.keys(): + if 'y' in list(e.keys()): y = float(e.get('y')) h = float(e.get('height')) w = float(e.get('width')) @@ -701,7 +701,7 @@ def pnext(): cy = float(e.get('cy')) r = float(e.get('r')) self.new_path() - for i in xrange(self.circle_points): + for i in range(self.circle_points): theta = 2 * i * math.pi / self.circle_points self.line_to(cx + r * math.cos(theta), cy + r * math.sin(theta)) self.close_path() @@ -712,7 +712,7 @@ def pnext(): rx = float(e.get('rx')) ry = float(e.get('ry')) self.new_path() - for i in xrange(self.circle_points): + for i in range(self.circle_points): theta = 2 * i * math.pi / self.circle_points self.line_to(cx + rx * math.cos(theta), cy + ry * math.sin(theta)) self.close_path() @@ -724,7 +724,7 @@ def pnext(): for c in e.getchildren(): try: self.parse_element(c) - except Exception, ex: + except Exception as ex: pymt_logger.exception('Squirtle: exception while parsing element %s' % c) raise self.transform = oldtransform @@ -780,7 +780,7 @@ def angle(u, v): if not sweep and delta > 0: delta -= math.pi * 2 n_points = max(int(abs(self.circle_points * delta / (2 * math.pi))), 1) - for i in xrange(n_points + 1): + for i in range(n_points + 1): theta = psi + i * delta / n_points ct = math.cos(theta) st = math.sin(theta) @@ -789,7 +789,7 @@ def angle(u, v): def curve_to(self, x1, y1, x2, y2, x, y): if not self.bezier_coefficients: - for i in xrange(self.bezier_points+1): + for i in range(self.bezier_points+1): t = float(i)/self.bezier_points t0 = (1 - t) ** 3 t1 = 3 * t * (1 - t) ** 2 diff --git a/pymt/lib/transformations.py b/pymt/lib/transformations.py index f15098cb..270dd2b4 100644 --- a/pymt/lib/transformations.py +++ b/pymt/lib/transformations.py @@ -174,7 +174,7 @@ """ -from __future__ import division, print_function + import sys import os @@ -1611,7 +1611,7 @@ def arcball_nearest_axis(point, axes): 'rzxy': (1, 1, 0, 1), 'ryxy': (1, 1, 1, 1), 'ryxz': (2, 0, 0, 1), 'rzxz': (2, 0, 1, 1), 'rxyz': (2, 1, 0, 1), 'rzyz': (2, 1, 1, 1)} -_TUPLE2AXES = dict((v, k) for k, v in _AXES2TUPLE.items()) +_TUPLE2AXES = dict((v, k) for k, v in list(_AXES2TUPLE.items())) def vector_norm(data, axis=None, out=None): diff --git a/pymt/loader.py b/pymt/loader.py index 1d6abfea..f381cc1b 100644 --- a/pymt/loader.py +++ b/pymt/loader.py @@ -57,7 +57,7 @@ def on_load(self): pass -class LoaderBase(object): +class LoaderBase(object, metaclass=ABCMeta): '''Common base for Loader and specific implementation. By default, Loader will be the best available loader implementation. @@ -65,8 +65,6 @@ class LoaderBase(object): less than 25 FPS. ''' - __metaclass__ = ABCMeta - def __init__(self): self._loading_image = None @@ -143,7 +141,7 @@ def _load_local(self, filename): def _load_urllib(self, filename): '''(internal) Loading a network file. First download it, save it to a temporary file, and pass it to _load_local()''' - import urllib2, tempfile + import urllib.request, urllib.error, urllib.parse, tempfile data = None try: suffix = '.%s' % (filename.split('.')[-1]) @@ -151,7 +149,7 @@ def _load_urllib(self, filename): prefix='pymtloader', suffix=suffix) # read from internet - fd = urllib2.urlopen(filename) + fd = urllib.request.urlopen(filename) idata = fd.read() fd.close() diff --git a/pymt/logger.py b/pymt/logger.py index 2bbb7abb..7728795b 100644 --- a/pymt/logger.py +++ b/pymt/logger.py @@ -44,7 +44,7 @@ pymt_logfile_activated = False -BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) +BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = list(range(8)) #These are the sequences need to get colored ouput RESET_SEQ = "\033[0m" @@ -90,28 +90,28 @@ def purge_logs(self, directory): # Use config ? maxfiles = 100 - print 'Purge log fired. Analysing...' + print('Purge log fired. Analysing...') join = os.path.join unlink = os.unlink # search all log files - l = map(lambda x: join(directory, x), os.listdir(directory)) + l = [join(directory, x) for x in os.listdir(directory)] if len(l) > maxfiles: # get creation time on every files - l = zip(l, map(os.path.getctime, l)) + l = list(zip(l, list(map(os.path.getctime, l)))) # sort by date l.sort(cmp=lambda x, y: cmp(x[1], y[1])) # get the oldest (keep last maxfiles) l = l[:-maxfiles] - print 'Purge %d log files' % len(l) + print('Purge %d log files' % len(l)) # now, unlink every files in the list for filename in l: unlink(filename[0]) - print 'Purge finished !' + print('Purge finished !') def _configure(self): diff --git a/pymt/modules/__init__.py b/pymt/modules/__init__.py index c4da674d..d7fcedc9 100644 --- a/pymt/modules/__init__.py +++ b/pymt/modules/__init__.py @@ -105,7 +105,7 @@ def unregister_window(self, win): def update(self): '''Update status of module for each windows''' - modules_to_activate = map(lambda x: x[0], pymt.pymt_config.items('modules')) + modules_to_activate = [x[0] for x in pymt.pymt_config.items('modules')] for win in self.wins: for id in self.mods: if not id in modules_to_activate: @@ -114,15 +114,15 @@ def update(self): self.activate_module(id, win) def usage_list(self): - print - print 'Available modules' - print '=================' + print() + print('Available modules') + print('=================') for module in self.list(): if not 'module' in self.mods[module]: self.import_module(module) text = self.mods[module]['module'].__doc__.strip("\n ") - print '%-12s: %s' % (module, text) - print + print('%-12s: %s' % (module, text)) + print() pymt_modules = Modules() pymt_modules.add_path(pymt.pymt_modules_dir) @@ -130,4 +130,4 @@ def usage_list(self): pymt_modules.add_path(pymt.pymt_usermodules_dir) if __name__ == '__main__': - print pymt_modules.list() + print(pymt_modules.list()) diff --git a/pymt/modules/feedback.py b/pymt/modules/feedback.py index ddccd683..89660483 100644 --- a/pymt/modules/feedback.py +++ b/pymt/modules/feedback.py @@ -62,7 +62,7 @@ def draw(self): set_brush(particle_fn, size=5) # show all moves - for idx in xrange(0, len(self.moves)): + for idx in range(0, len(self.moves)): # decrease timeout self.moves[idx][2] -= getFrameDt() @@ -126,7 +126,7 @@ def on_draw(self): def draw(self): rings_to_delete = [] - for i in xrange(0, len(self.rings)): + for i in range(0, len(self.rings)): ring = self.rings[i] ring.draw() ring.opacity -= getFrameDt() * 1.5 diff --git a/pymt/modules/keybinding.py b/pymt/modules/keybinding.py index 6ddae54b..def26f46 100644 --- a/pymt/modules/keybinding.py +++ b/pymt/modules/keybinding.py @@ -37,7 +37,7 @@ def _screenshot(): data = glReadPixels(0, 0, win.width, win.height, GL_RGB, GL_UNSIGNED_BYTE) surface = pygame.image.fromstring(str(buffer(data)), win.size, 'RGB', True) filename = None - for i in xrange(9999): + for i in range(9999): path = os.path.join(os.getcwd(), 'screenshot%04d.jpg' % i) if not os.path.exists(path): filename = path @@ -165,9 +165,9 @@ def _on_draw(): # draw lines set_color(1, 1, 1) - for x in xrange(0, win.width, stepx): + for x in range(0, win.width, stepx): drawLine((x, 0, x, win.height)) - for y in xrange(0, win.height, stepy): + for y in range(0, win.height, stepy): drawLine((0, y, win.width, y)) # draw circles @@ -198,7 +198,7 @@ def _on_draw(): sizeh = stepy * step w2 = win.width / 2. h2 = win.height / 2. - for _x in xrange(step): + for _x in range(step): x = w2 - sizew / 2. + _x * stepx drawLabel(chr(65+_x), pos=(x + stepx / 2., h2 + 190)) c = _x / float(step) @@ -311,7 +311,7 @@ def add_new_widget(self, *args): def print_props(self, *args): for prop in self.widget.__dict__: if not prop.startswith("_"): - print prop, ":", getattr(self.widget, prop) + print(prop, ":", getattr(self.widget, prop)) @@ -333,7 +333,7 @@ def toggle_scene_graph(): -def _on_keyboard_handler(key, scancode, unicode): +def _on_keyboard_handler(key, scancode, str): if key is None: return win = getWindow() diff --git a/pymt/modules/mjpegserver.py b/pymt/modules/mjpegserver.py index 0d13c5b1..609a8b8b 100644 --- a/pymt/modules/mjpegserver.py +++ b/pymt/modules/mjpegserver.py @@ -26,9 +26,9 @@ import pymt import threading import time -import StringIO +import io import random -from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler +from http.server import HTTPServer, BaseHTTPRequestHandler from OpenGL.GL import glReadBuffer, glReadPixels, GL_RGB, GL_UNSIGNED_BYTE, GL_FRONT from pymt.utils import curry @@ -75,7 +75,7 @@ def _stream_video(self): if size == '': size = None else: - size = map(int, size.split('x')) + size = list(map(int, size.split('x'))) pymt.pymt_logger.info( 'MjpegServer: Client %s:%d connected' % self.client_address) @@ -105,7 +105,7 @@ def _stream_video(self): sem_next.release() # SYNC END - buf = StringIO.StringIO() + buf = io.StringIO() if size: im = im.resize(size) im = im.transpose(Image.FLIP_TOP_BOTTOM) diff --git a/pymt/modules/sleep.py b/pymt/modules/sleep.py index 8a34d439..d1dc2960 100644 --- a/pymt/modules/sleep.py +++ b/pymt/modules/sleep.py @@ -39,8 +39,8 @@ def __init__(self, config, win): sleep = config.get('sleep').split(':') if len(ramp) != len(sleep): raise ValueError('Sleep: Invalid ramp/sleep: list size is not the same') - self.ramp = map(float, ramp) - self.sleep = map(float, sleep) + self.ramp = list(map(float, ramp)) + self.sleep = list(map(float, sleep)) pymt_logger.debug('Sleep: ramp is %s' % str(self.ramp)) pymt_logger.debug('Sleep: sleep is %s' % str(self.sleep)) diff --git a/pymt/modules/touchinfo.py b/pymt/modules/touchinfo.py index e4662011..4e680b8c 100644 --- a/pymt/modules/touchinfo.py +++ b/pymt/modules/touchinfo.py @@ -42,7 +42,7 @@ def draw(self): bubble.dispatch_event('on_draw') alive = [x.uid for x in current] - for uid in bubbles.keys()[:]: + for uid in list(bubbles.keys())[:]: if uid not in alive: del bubbles[uid] diff --git a/pymt/obj.py b/pymt/obj.py index 3ce11266..5f714f28 100644 --- a/pymt/obj.py +++ b/pymt/obj.py @@ -99,14 +99,8 @@ def draw(self): # texture is a rectangle texture # that's mean we need to adjust the range of texture # coordinate from original 0-1 to 0-width/0-height - group.vertices[0::8] = map( - lambda x: x * group.material.texture.width, - group.vertices[0::8] - ) - group.vertices[1::8] = map( - lambda x: x * group.material.texture.height, - group.vertices[1::8] - ) + group.vertices[0::8] = [x * group.material.texture.width for x in group.vertices[0::8]] + group.vertices[1::8] = [x * group.material.texture.height for x in group.vertices[1::8]] group.array = (GLfloat * len(group.vertices))(*group.vertices) group.triangles = len(group.vertices) / 8 glInterleavedArrays(GL_T2F_N3F_V3F, 0, group.array) @@ -170,11 +164,11 @@ def __init__(self, filename, file=None, path=None, compat=True): continue if values[0] == 'v': - vertices.append(map(float, values[1:4])) + vertices.append(list(map(float, values[1:4]))) elif values[0] == 'vn': - normals.append(map(float, values[1:4])) + normals.append(list(map(float, values[1:4]))) elif values[0] == 'vt': - tex_coords.append(map(float, values[1:3])) + tex_coords.append(list(map(float, values[1:3]))) elif values[0] == 'mtllib': self.load_material_library(values[1]) elif values[0] in ('usemtl', 'usemat'): @@ -204,7 +198,7 @@ def __init__(self, filename, file=None, path=None, compat=True): vlast = None for i, v in enumerate(values[1:]): v_index, t_index, n_index = \ - (map(int, [j or 0 for j in v.split('/')]) + [0, 0])[:3] + (list(map(int, [j or 0 for j in v.split('/')])) + [0, 0])[:3] if v_index < 0: v_index += len(vertices) - 1 if t_index < 0: @@ -248,13 +242,13 @@ def load_material_library(self, filename): try: if values[0] == 'Kd': - material.diffuse = map(float, values[1:]) + material.diffuse = list(map(float, values[1:])) elif values[0] == 'Ka': - material.ambient = map(float, values[1:]) + material.ambient = list(map(float, values[1:])) elif values[0] == 'Ks': - material.specular = map(float, values[1:]) + material.specular = list(map(float, values[1:])) elif values[0] == 'Ke': - material.emission = map(float, values[1:]) + material.emission = list(map(float, values[1:])) elif values[0] == 'Ns': material.shininess = float(values[1]) elif values[0] == 'd': diff --git a/pymt/parser.py b/pymt/parser.py index 63ecf90a..1776dbae 100644 --- a/pymt/parser.py +++ b/pymt/parser.py @@ -27,7 +27,7 @@ def parse_filename(filename): def parse_image(filename): '''Parse a filename to load an image ro svg''' filename = parse_filename(filename) - if filename in (None, 'None', u'None'): + if filename in (None, 'None', 'None'): return None if filename.endswith('.svg'): return Svg(filename) @@ -46,13 +46,13 @@ def parse_color(text): value = [1, 1, 1, 1] if text.startswith('rgb'): res = re.match('rgba?\((.*)\)', text) - value = map(lambda x: int(x) / 255., re.split(',\ ?', res.groups()[0])) + value = [int(x) / 255. for x in re.split(',\ ?', res.groups()[0])] if len(value) == 3: value.append(1.) elif text.startswith('#'): res = text[1:] if len(res) == 3: - res = ''.join(map(lambda x: x+x, res)) + res = ''.join([x+x for x in res]) value = [int(x, 16) / 255. for x in re.split( '([0-9a-f]{2})', res) if x != ''] if len(value) == 3: @@ -81,7 +81,7 @@ def parse_int2(text): ''' texts = [x for x in text.split(' ') if x.strip() != ''] - value = map(parse_int, texts) + value = list(map(parse_int, texts)) if len(value) < 1: raise Exception('Invalid format int2 for %s' % text) elif len(value) == 1: @@ -98,11 +98,11 @@ def parse_float4(text): ''' texts = [x for x in text.split(' ') if x.strip() != ''] - value = map(parse_float, texts) + value = list(map(parse_float, texts)) if len(value) < 1: raise Exception('Invalid format float4 for %s' % text) elif len(value) == 1: - return map(lambda x: value[0], range(4)) + return [value[0] for x in range(4)] elif len(value) == 2: return [value[0], value[1], value[0], value[1]] elif len(value) == 3: diff --git a/pymt/plugin.py b/pymt/plugin.py index e06f4264..a41d4847 100644 --- a/pymt/plugin.py +++ b/pymt/plugin.py @@ -91,4 +91,4 @@ def deactivate(self, plugin, container): if __name__ == '__main__': a = MTPlugins() for plugin in a.list(): - print a.get_infos(a.get_plugin(plugin)) + print(a.get_infos(a.get_plugin(plugin))) diff --git a/pymt/texture.py b/pymt/texture.py index 3532bd2a..637d401d 100644 --- a/pymt/texture.py +++ b/pymt/texture.py @@ -11,14 +11,16 @@ import OpenGL from OpenGL.GL import GL_RGBA, GL_UNSIGNED_BYTE, GL_TEXTURE_MIN_FILTER, \ GL_TEXTURE_MAG_FILTER, GL_TEXTURE_WRAP_T, GL_TEXTURE_WRAP_S, \ - GL_TEXTURE_2D, GL_TEXTURE_RECTANGLE_NV, GL_TEXTURE_RECTANGLE_ARB, \ + GL_TEXTURE_2D,\ GL_CLAMP_TO_EDGE, GL_LINEAR_MIPMAP_LINEAR, GL_GENERATE_MIPMAP, \ GL_TRUE, GL_LINEAR, GL_UNPACK_ALIGNMENT, GL_BGR, GL_BGRA, GL_RGB, \ glEnable, glDisable, glBindTexture, glTexParameteri, glTexImage2D, \ glTexSubImage2D, glFlush, glGenTextures, glDeleteTextures, \ GLubyte, glPixelStorei, GL_LUMINANCE from OpenGL.GL.NV.texture_rectangle import glInitTextureRectangleNV +from OpenGL.GL.NV.texture_rectangle import GL_TEXTURE_RECTANGLE_NV from OpenGL.GL.ARB.texture_rectangle import glInitTextureRectangleARB +from OpenGL.GL.ARB.texture_rectangle import GL_TEXTURE_RECTANGLE_ARB from OpenGL.extensions import hasGLExtension # for a specific bug in 3.0.0, about deletion of framebuffer. diff --git a/pymt/tools/benchmark.py b/pymt/tools/benchmark.py index 4dc72a48..28b409b5 100644 --- a/pymt/tools/benchmark.py +++ b/pymt/tools/benchmark.py @@ -29,8 +29,8 @@ class bench_core_label: '''Core: label creation (10000 * 10 a-z)''' def __init__(self): labels = [] - for x in xrange(10000): - label = map(lambda x: chr(randint(ord('a'), ord('z'))), xrange(10)) + for x in range(10000): + label = [chr(randint(ord('a'), ord('z'))) for x in range(10)] labels.append(''.join(label)) self.labels = labels def run(self): @@ -43,22 +43,22 @@ class bench_widget_creation: '''Widget: creation (10000 MTWidget)''' def run(self): o = [] - for x in xrange(10000): + for x in range(10000): o.append(MTWidget()) class bench_widget_dispatch: '''Widget: event dispatch (1000 on_update in 10*1000 MTWidget)''' def __init__(self): root = MTWidget() - for x in xrange(10): + for x in range(10): parent = MTWidget() - for y in xrange(1000): + for y in range(1000): parent.add_widget(MTWidget()) root.add_widget(parent) self.root = root def run(self): root = self.root - for x in xrange(1000): + for x in range(1000): root.dispatch_event('on_update') class bench_graphx_line: @@ -66,12 +66,12 @@ class bench_graphx_line: def __init__(self): lines = [] w, h = window_size - for x in xrange(5000): + for x in range(5000): lines.extend([random() * w, random() * h]) self.lines = lines def run(self): lines = self.lines - for x in xrange(1000): + for x in range(1000): drawLine(lines) class bench_graphics_line: @@ -80,11 +80,11 @@ def __init__(self): w, h = window_size self.canvas = Canvas() line = self.canvas.line() - for x in xrange(5000): + for x in range(5000): line.points += [random() * w, random() * h] def run(self): canvas = self.canvas - for x in xrange(1000): + for x in range(1000): canvas.draw() @@ -93,12 +93,12 @@ class bench_graphx_rectangle: def __init__(self): rects = [] w, h = window_size - for x in xrange(5000): + for x in range(5000): rects.append(((random() * w, random() * h), (random() * w, random() * h))) self.rects = rects def run(self): rects = self.rects - for x in xrange(1000): + for x in range(1000): for pos, size in rects: drawRectangle(pos=pos, size=size) @@ -108,12 +108,12 @@ def __init__(self): rects = [] w, h = window_size canvas = Canvas() - for x in xrange(5000): + for x in range(5000): canvas.rectangle(random() * w, random() * h, random() * w, random() * h) self.canvas = canvas def run(self): canvas = self.canvas - for x in xrange(1000): + for x in range(1000): canvas.draw() class bench_graphics_rectanglemesh: @@ -124,13 +124,13 @@ def __init__(self): canvas = Canvas() mesh = canvas.graphicElement(format='vv', type='quads') vertex = [] - for x in xrange(50000): + for x in range(50000): vertex.extend([random() * w, random() * h, random() * w, random() * h]) mesh.data_v = vertex self.canvas = canvas def run(self): canvas = self.canvas - for x in xrange(1000): + for x in range(1000): canvas.draw() class bench_graphx_roundedrectangle: @@ -138,12 +138,12 @@ class bench_graphx_roundedrectangle: def __init__(self): rects = [] w, h = window_size - for x in xrange(5000): + for x in range(5000): rects.append(((random() * w, random() * h), (random() * w, random() * h))) self.rects = rects def run(self): rects = self.rects - for x in xrange(1000): + for x in range(1000): for pos, size in rects: drawRoundedRectangle(pos=pos, size=size) @@ -154,12 +154,12 @@ def __init__(self): rects = [] w, h = window_size canvas = Canvas() - for x in xrange(5000): + for x in range(5000): canvas.roundedRectangle(random() * w, random() * h, random() * w, random() * h) self.canvas = canvas def run(self): canvas = self.canvas - for x in xrange(1000): + for x in range(1000): canvas.draw() class bench_graphx_paintline: @@ -167,13 +167,13 @@ class bench_graphx_paintline: def __init__(self): lines = [] w, h = window_size - for x in xrange(500): + for x in range(500): lines.extend([random() * w, random() * h]) self.lines = lines set_brush(os.path.join(pymt_data_dir, 'particle.png')) def run(self): lines = self.lines - for x in xrange(100): + for x in range(100): paintLine(lines) class bench_graphics_paintline: @@ -183,11 +183,11 @@ def __init__(self): self.canvas = Canvas() texture = Image(os.path.join(pymt_data_dir, 'particle.png')).texture line = self.canvas.point(type='line_strip', texture=texture) - for x in xrange(500): + for x in range(500): line.points += [random() * w, random() * h] def run(self): canvas = self.canvas - for x in xrange(100): + for x in range(100): canvas.draw() @@ -201,15 +201,15 @@ def log(s, newline=True): else: report.append(s) if newline: - print s + print(s) report_newline = True else: - print s, + print(s, end=' ') report_newline = False sys.stdout.flush() clock_total = 0 - benchs = locals().keys() + benchs = list(locals().keys()) benchs.sort() benchs = [locals()[x] for x in benchs if x.startswith('bench_')] @@ -257,7 +257,7 @@ def log(s, newline=True): try: sys.stderr.write('.') test = x() - except Exception, e: + except Exception as e: log('failed %s' % str(e)) import traceback traceback.print_exc() @@ -270,7 +270,7 @@ def log(s, newline=True): test.run() clock_end = clockfn() - clock_start log('%.6f' % clock_end) - except Exception, e: + except Exception as e: log('failed %s' % str(e)) continue @@ -286,21 +286,21 @@ def log(s, newline=True): pass try: - reply = raw_input('Do you want to send benchmark to paste.pocoo.org (Y/n) : ') + reply = input('Do you want to send benchmark to paste.pocoo.org (Y/n) : ') except EOFError: sys.exit(0) if reply.lower().strip() in ('', 'y'): - print 'Please wait while sending the benchmark...' + print('Please wait while sending the benchmark...') - from xmlrpclib import ServerProxy + from xmlrpc.client import ServerProxy s = ServerProxy('http://paste.pocoo.org/xmlrpc/') r = s.pastes.newPaste('text', '\n'.join(report)) - print - print - print 'REPORT posted at http://paste.pocoo.org/show/%s/' % r - print - print + print() + print() + print('REPORT posted at http://paste.pocoo.org/show/%s/' % r) + print() + print() else: - print 'No benchmark posted.' + print('No benchmark posted.') diff --git a/pymt/tools/config.py b/pymt/tools/config.py index 60563847..56dccc46 100755 --- a/pymt/tools/config.py +++ b/pymt/tools/config.py @@ -1,8 +1,8 @@ #!/usr/bin/env python -from __future__ import with_statement -from Tkinter import * -import tkMessageBox + +from tkinter import * +import tkinter.messagebox import sys import os os.environ['PYMT_SHADOW_WINDOW'] = '0' @@ -71,7 +71,7 @@ def __getitem__(self, name): def configuration_debug(): for key in c: - print key, '=', c.get(key).get() + print(key, '=', c.get(key).get()) def configuration_save(): for key in c: @@ -105,9 +105,9 @@ def configuration_save(): try: pymt_config.write() - tkMessageBox.showinfo('PyMT', 'Configuration saved !') - except Exception, e: - tkMessageBox.showwarning('PyMT', 'Unable to save default configuration : ' + str(e)) + tkinter.messagebox.showinfo('PyMT', 'Configuration saved !') + except Exception as e: + tkinter.messagebox.showwarning('PyMT', 'Unable to save default configuration : ' + str(e)) # ================================================================ @@ -225,11 +225,11 @@ def configuration_save(): def _input_add(*largs): device_id = c_input_devicename.get() if device_id == '': - tkMessageBox.showerror('PyMT', 'No device name setted') + tkinter.messagebox.showerror('PyMT', 'No device name setted') return provider_name = c_input_provider.get() if provider_name == '': - tkMessageBox.showerror('PyMT', 'No provider selected') + tkinter.messagebox.showerror('PyMT', 'No provider selected') return options = c_input_option.get() t = '%s=%s,%s' % (str(device_id), str(provider_name), str(options)) diff --git a/pymt/tools/designer.py b/pymt/tools/designer.py index 304d4df3..b3ffdeb6 100644 --- a/pymt/tools/designer.py +++ b/pymt/tools/designer.py @@ -1,3 +1,3 @@ -from designerapp.designer import run +from .designerapp.designer import run if __name__ == '__main__': run() diff --git a/pymt/tools/designerapp/designer.py b/pymt/tools/designerapp/designer.py index 6c84cb2d..f80337c6 100644 --- a/pymt/tools/designerapp/designer.py +++ b/pymt/tools/designerapp/designer.py @@ -4,8 +4,8 @@ import os from PyQt4 import QtCore, QtGui, QtOpenGL from OpenGL import GL -from syntaxhighlighter import Highlighter -from cStringIO import StringIO +from .syntaxhighlighter import Highlighter +from io import StringIO import logging.handlers # Configure pymt BEFORE instance @@ -15,7 +15,7 @@ from pymt import pymt_logger # don't import qtmt before pymt, otherwise, initialization will fail. -from qtmtwindow import * +from .qtmtwindow import * class LoggerHandler: __slots__ = ('output', 'colors') @@ -206,7 +206,7 @@ def designerRunTouchApp(w): try: self.glWidget.create_new_pymt_window() d = {} - exec str(self.editor.toPlainText()) in d + exec(str(self.editor.toPlainText()), d) #pymt.stopTouchApp() except Exception as e: #pymt.pymt_logger.exception("Error Running PyMT Code:") diff --git a/pymt/tools/designerapp/syntaxhighlighter.py b/pymt/tools/designerapp/syntaxhighlighter.py index 9d51c0b2..a74775eb 100644 --- a/pymt/tools/designerapp/syntaxhighlighter.py +++ b/pymt/tools/designerapp/syntaxhighlighter.py @@ -20,7 +20,7 @@ def __init__(self, parent=None): 'continue', 'exec', 'import', 'pass', 'yield', 'finally', 'print', 'eval'] - keywordPatterns = map(lambda x: "\\b"+x+"\\b", keywords) + keywordPatterns = ["\\b"+x+"\\b" for x in keywords] self.highlightingRules = [(QtCore.QRegExp(pattern), keywordFormat) for pattern in keywordPatterns] diff --git a/pymt/tools/dump.py b/pymt/tools/dump.py index 26e871de..ccc44030 100644 --- a/pymt/tools/dump.py +++ b/pymt/tools/dump.py @@ -10,9 +10,9 @@ import os import sys import time -from ConfigParser import ConfigParser -from StringIO import StringIO -from xmlrpclib import ServerProxy +from configparser import ConfigParser +from io import StringIO +from xmlrpc.client import ServerProxy import OpenGL from OpenGL.GL import * @@ -63,7 +63,7 @@ def testimport(libname): try: l = __import__(libname) report.append('%-20s exist' % libname) - except ImportError, e: + except ImportError as e: report.append('%-20s is missing' % libname) for x in ( 'gst', @@ -107,39 +107,39 @@ def testimport(libname): report.append(x.message) title('Environ') -for k, v in os.environ.iteritems(): +for k, v in os.environ.items(): report.append('%s = %s' % (k, v)) title('Options') -for k, v in pymt_options.iteritems(): +for k, v in pymt_options.items(): report.append('%s = %s' % (k, v)) report = '\n'.join(report) -print report -print -print +print(report) +print() +print() try: - reply = raw_input('Do you accept to send report to paste.pocoo.org (Y/n) : ') + reply = input('Do you accept to send report to paste.pocoo.org (Y/n) : ') except EOFError: sys.exit(0) if reply.lower().strip() in ('', 'y'): - print 'Please wait while sending the report...' + print('Please wait while sending the report...') s = ServerProxy('http://paste.pocoo.org/xmlrpc/') r = s.pastes.newPaste('text', report) - print - print - print 'REPORT posted at http://paste.pocoo.org/show/%s/' % r - print - print + print() + print() + print('REPORT posted at http://paste.pocoo.org/show/%s/' % r) + print() + print() else: - print 'No report posted.' + print('No report posted.') # On windows system, the console leave directly after the end # of the dump. That's not cool if we want get report url -raw_input('Enter any key to leave.') +input('Enter any key to leave.') diff --git a/pymt/tools/dumpinput.py b/pymt/tools/dumpinput.py index 0306697b..ec8a8c61 100644 --- a/pymt/tools/dumpinput.py +++ b/pymt/tools/dumpinput.py @@ -8,13 +8,13 @@ def __init__(self): self.register_event_type('on_touch_up') def on_touch_down(self, touch): - print 'DOWN - ', repr(touch) + print('DOWN - ', repr(touch)) def on_touch_move(self, touch): - print 'MOVE - ', repr(touch) + print('MOVE - ', repr(touch)) def on_touch_up(self, touch): - print 'UP - ', repr(touch) + print('UP - ', repr(touch)) touch_event_listeners.append(DumpListener()) diff --git a/pymt/tools/packaging/osx/build.py b/pymt/tools/packaging/osx/build.py index 41e82022..8af44052 100644 --- a/pymt/tools/packaging/osx/build.py +++ b/pymt/tools/packaging/osx/build.py @@ -1,5 +1,5 @@ import os, sys, shutil, shlex, re -from urllib import urlretrieve +from urllib.request import urlretrieve from subprocess import Popen, PIPE from distutils.cmd import Command @@ -36,41 +36,41 @@ def finalize_options(self): def run(self): - print "---------------------------------" - print "Building PyMT Portable for OSX" - print "---------------------------------" + print("---------------------------------") + print("Building PyMT Portable for OSX") + print("---------------------------------") - print "\nPreparing Build..." - print "---------------------------------------" + print("\nPreparing Build...") + print("---------------------------------------") if os.path.exists(self.build_dir): - print "*Cleaning old build dir" + print("*Cleaning old build dir") shutil.rmtree(self.build_dir, ignore_errors=True) - print "*Creating build directory:" - print " "+self.build_dir + print("*Creating build directory:") + print(" "+self.build_dir) os.makedirs(self.build_dir) - print "\nGetting binary dependencies..." - print "---------------------------------------" - print "*Downloading:", self.deps_url + print("\nGetting binary dependencies...") + print("---------------------------------------") + print("*Downloading:", self.deps_url) #report_hook is called every time a piece of teh file is downloaded to print progress def report_hook(block_count, block_size, total_size): p = block_count*block_size*100.0/total_size - print "\b\b\b\b\b\b\b\b\b", "%06.2f"%p +"%", - print " Progress: 000.00%", + print("\b\b\b\b\b\b\b\b\b", "%06.2f"%p +"%", end=' ') + print(" Progress: 000.00%", end=' ') urlretrieve(self.deps_url, #location of binary dependencioes needed for portable pymt os.path.join(self.build_dir,'deps.zip'), #tmp file to store teh archive reporthook=report_hook) - print " [Done]" + print(" [Done]") - print "*Extracting binary dependencies..." + print("*Extracting binary dependencies...") #using osx sysetm command, becasue python zipfile cant handle the hidden files in teh archive Popen(['unzip', os.path.join(self.build_dir,'deps.zip')], cwd=self.build_dir, stdout=PIPE).communicate() - print "\nPutting pymt into portable environment" - print "---------------------------------------" - print "*Building pymt source distribution" + print("\nPutting pymt into portable environment") + print("---------------------------------------") + print("*Building pymt source distribution") sdist_cmd = [sys.executable, #path to python.exe os.path.join(self.src_dir,'setup.py'), #path to setup.py 'sdist', #make setup.py create a src distribution @@ -78,14 +78,14 @@ def report_hook(block_count, block_size, total_size): Popen(sdist_cmd, stdout=PIPE).communicate() - print "*Placing pymt source distribution in portable context" + print("*Placing pymt source distribution in portable context") src_dist = os.path.join(self.build_dir,self.dist_name) #using osx sysetm command, becasue python zipfile cant handle the hidden files in teh archive Popen(['tar', 'xfv', src_dist+'.tar.gz'], cwd=self.build_dir, stdout=PIPE, stderr=PIPE).communicate() if self.no_cext: - print "*Skipping C Extension build (either --no_cext or --no_mingw option set)" + print("*Skipping C Extension build (either --no_cext or --no_mingw option set)") else: - print "*Compiling C Extensions inplace for portable distribution" + print("*Compiling C Extensions inplace for portable distribution") cext_cmd = [sys.executable, #path to python.exe 'setup.py', 'build_ext', #make setup.py create a src distribution @@ -97,23 +97,23 @@ def report_hook(block_count, block_size, total_size): - print "\nFinalizing Application Bundle" - print "---------------------------------------" - print "*Copying launcher script into the app bundle" + print("\nFinalizing Application Bundle") + print("---------------------------------------") + print("*Copying launcher script into the app bundle") script_target = os.path.join(self.build_dir, 'portable-deps-osx', 'PyMT.app', 'Contents', 'Resources', 'script') script = os.path.join(src_dist,'pymt','tools','packaging','osx', 'pymt.sh') shutil.copy(script, script_target) - print "*Moving examples out of app bundle to be included in disk image" + print("*Moving examples out of app bundle to be included in disk image") examples_target = os.path.join(self.build_dir, 'portable-deps-osx', 'examples') examples = os.path.join(src_dist,'examples') shutil.move(examples, examples_target) - print "*Moving newly build pymt distribution into app bundle" + print("*Moving newly build pymt distribution into app bundle") pymt_target = os.path.join(self.build_dir, 'portable-deps-osx', 'PyMT.app', 'Contents', 'Resources', 'pymt') shutil.move(src_dist, pymt_target) - print "*Removing intermediate file" + print("*Removing intermediate file") os.remove(os.path.join(self.build_dir,'deps.zip')) os.remove(os.path.join(self.build_dir,src_dist+'.tar.gz')) shutil.rmtree(os.path.join(self.build_dir,'__MACOSX'), ignore_errors=True) @@ -123,27 +123,27 @@ def report_hook(block_count, block_size, total_size): dmg_dir = os.path.join(self.build_dir, 'portable-deps-osx') vol_name = "PyMT" - print "\nCreating disk image for distribution" - print "---------------------------------------" - print "\nCreating intermediate DMG disk image: temp.dmg" - print "*checking how much space is needed for disk image..." + print("\nCreating disk image for distribution") + print("---------------------------------------") + print("\nCreating intermediate DMG disk image: temp.dmg") + print("*checking how much space is needed for disk image...") du_cmd = 'du -sh %s'%dmg_dir du_out = Popen(shlex.split(du_cmd), stdout=PIPE).communicate()[0] size, unit = re.search('(\d+)(.*)\s+/.*', du_out).group(1,2) - print " build needs at least %s%s." % (size, unit) + print(" build needs at least %s%s." % (size, unit)) size = int(size)+10 - print "*allocating %d%s for temp.dmg (volume name:%s)" % (size, unit, vol_name) + print("*allocating %d%s for temp.dmg (volume name:%s)" % (size, unit, vol_name)) create_dmg_cmd = 'hdiutil create -srcfolder %s -volname %s -fs HFS+ \ -fsargs "-c c=64,a=16,e=16" -format UDRW -size %d%s temp.dmg' \ % (dmg_dir, vol_name, size+10, unit) Popen(shlex.split(create_dmg_cmd), cwd=self.build_dir).communicate() - print "*mounting intermediate disk image:" + print("*mounting intermediate disk image:") mount_cmd = 'hdiutil attach -readwrite -noverify -noautoopen "temp.dmg"' Popen(shlex.split(mount_cmd), cwd=self.build_dir, stdout=PIPE).communicate() - print "*running Apple Script to configure DMG layout properties:" + print("*running Apple Script to configure DMG layout properties:") dmg_config_script = """ tell application "Finder" tell disk "%s" @@ -171,18 +171,18 @@ def report_hook(block_count, block_size, total_size): end tell end tell """ % vol_name - print Popen(['osascript'], cwd=self.build_dir, stdin=PIPE, stdout=PIPE).communicate(dmg_config_script)[0] + print(Popen(['osascript'], cwd=self.build_dir, stdin=PIPE, stdout=PIPE).communicate(dmg_config_script)[0]) - print "\nCreating final disk image" + print("\nCreating final disk image") - print "*unmounting intermediate disk image" + print("*unmounting intermediate disk image") umount_cmd = 'hdiutil detach /Volumes/%s' % vol_name Popen(shlex.split(umount_cmd), cwd=self.build_dir, stdout=PIPE).communicate() - print "*compressing and finalizing disk image" + print("*compressing and finalizing disk image") convert_cmd = 'hdiutil convert "temp.dmg" -format UDZO -imagekey zlib-level=9 -o %s.dmg' % os.path.join(self.dist_dir,vol_name) Popen(shlex.split(convert_cmd), cwd=self.build_dir, stdout=PIPE).communicate() - print "*Writing disk image, and cleaning build directory" + print("*Writing disk image, and cleaning build directory") shutil.rmtree(self.build_dir, ignore_errors=True) diff --git a/pymt/tools/packaging/win32/build.py b/pymt/tools/packaging/win32/build.py index af5cc35a..9768553c 100644 --- a/pymt/tools/packaging/win32/build.py +++ b/pymt/tools/packaging/win32/build.py @@ -1,7 +1,7 @@ import os, sys, shutil import zipfile from zipfile import ZipFile -from urllib import urlretrieve +from urllib.request import urlretrieve from subprocess import Popen, PIPE from distutils.cmd import Command @@ -50,47 +50,47 @@ def finalize_options(self): def run(self): - print "---------------------------------" - print "Building PyMT Portable for Win 32" - print "---------------------------------" + print("---------------------------------") + print("Building PyMT Portable for Win 32") + print("---------------------------------") - print "\nPreparing Build..." - print "---------------------------------------" + print("\nPreparing Build...") + print("---------------------------------------") if os.path.exists(self.build_dir): - print "*Cleaning old build dir" + print("*Cleaning old build dir") shutil.rmtree(self.build_dir, ignore_errors=True) - print "*Creating build directory:" - print " "+self.build_dir + print("*Creating build directory:") + print(" "+self.build_dir) os.makedirs(self.build_dir) - print "\nGetting binary dependencies..." - print "---------------------------------------" - print "*Downloading:", self.deps_url + print("\nGetting binary dependencies...") + print("---------------------------------------") + print("*Downloading:", self.deps_url) #report_hook is called every time a piece of teh file is downloaded to print progress def report_hook(block_count, block_size, total_size): p = block_count*block_size*100.0/total_size - print "\b\b\b\b\b\b\b\b\b", "%06.2f"%p +"%", - print " Progress: 000.00%", + print("\b\b\b\b\b\b\b\b\b", "%06.2f"%p +"%", end=' ') + print(" Progress: 000.00%", end=' ') urlretrieve(self.deps_url, #location of binary dependencioes needed for portable pymt os.path.join(self.build_dir,'deps.zip'), #tmp file to store teh archive reporthook=report_hook) - print " [Done]" + print(" [Done]") - print "*Extracting binary dependencies..." + print("*Extracting binary dependencies...") zf = ZipFile(os.path.join(self.build_dir,'deps.zip')) zf.extractall(self.build_dir) zf.close() if self.no_mingw: - print "*Excluding MinGW from portable distribution (--no-mingw option is set)" + print("*Excluding MinGW from portable distribution (--no-mingw option is set)") shutil.rmtree(os.path.join(self.build_dir, 'MinGW'), ignore_errors=True) - print "\nPutting pymt into portable environment" - print "---------------------------------------" - print "*Building pymt source distribution" + print("\nPutting pymt into portable environment") + print("---------------------------------------") + print("*Building pymt source distribution") sdist_cmd = [sys.executable, #path to python.exe os.path.join(self.src_dir,'setup.py'), #path to setup.py 'sdist', #make setup.py create a src distribution @@ -98,15 +98,15 @@ def report_hook(block_count, block_size, total_size): Popen(sdist_cmd, stdout=PIPE, stderr=PIPE).communicate() - print "*Placing pymt source distribution in portable context" + print("*Placing pymt source distribution in portable context") src_dist = os.path.join(self.build_dir,self.dist_name) zf = ZipFile(src_dist+'.zip') zf.extractall(self.build_dir) zf.close() if self.no_mingw or self.no_cext: - print "*Skipping C Extension build (either --no_cext or --no_mingw option set)" + print("*Skipping C Extension build (either --no_cext or --no_mingw option set)") else: - print "*Compiling C Extensions inplace for portable distribution" + print("*Compiling C Extensions inplace for portable distribution") cext_cmd = [sys.executable, #path to python.exe 'setup.py', 'build_ext', #make setup.py create a src distribution @@ -117,9 +117,9 @@ def report_hook(block_count, block_size, total_size): Popen(cext_cmd, cwd=src_dist, stdout=PIPE, stderr=PIPE).communicate() - print "\nFinalizing pymt portable distribution..." - print "---------------------------------------" - print "*Copying scripts and resources" + print("\nFinalizing pymt portable distribution...") + print("---------------------------------------") + print("*Copying scripts and resources") #copy launcher script and readme to portable root dir/build dir pymt_bat = os.path.join(src_dist,'pymt','tools','packaging','win32', 'pymt.bat') shutil.copy(pymt_bat, os.path.join(self.build_dir, 'pymt.bat')) @@ -128,13 +128,13 @@ def report_hook(block_count, block_size, total_size): #rename pymt directory to "pymt" os.rename(src_dist, os.path.join(self.build_dir,'pymt')) - print "*Removing intermediate file" + print("*Removing intermediate file") os.remove(os.path.join(self.build_dir,'deps.zip')) os.remove(os.path.join(self.build_dir,src_dist+'.zip')) - print "*Compressing portable distribution target" + print("*Compressing portable distribution target") target = os.path.join(self.dist_dir, self.dist_name+"-w32.zip") zip_directory(self.build_dir, target) - print "*Writing target:", target - print "*Removing build dir" + print("*Writing target:", target) + print("*Removing build dir") shutil.rmtree(self.build_dir, ignore_errors=True) diff --git a/pymt/ui/animation.py b/pymt/ui/animation.py index e1c853a1..63322d6a 100644 --- a/pymt/ui/animation.py +++ b/pymt/ui/animation.py @@ -95,7 +95,7 @@ def __init__(self,**kwargs): f = AnimationAlpha.linear self.alpha_function = f - if 'generate_event' in self.params.keys(): + if 'generate_event' in list(self.params.keys()): self.generate_event = self.params['generate_event'] else: self.generate_event = True @@ -115,7 +115,7 @@ def _set_value_from(self, value, prop): attr = getattr(self.widget, prop) try: if type(attr) == dict and type(value) == dict: - for k, v in value.iteritems(): + for k, v in value.items(): attr[k] = v else: self.widget.__setattr__(prop, value, **kwargs) @@ -323,7 +323,7 @@ def _update_list(self, ip_list, op_list): def _update_dict(self, ip_dict, op_dict): '''Used by reset function to update a dict type data''' temp_dict = {} - for key in ip_dict.iterkeys(): + for key in ip_dict.keys(): if type(ip_dict[key]) in (tuple, list): temp_dict[key] = self._update_list(ip_dict[key], op_dict[key]) else: @@ -422,7 +422,7 @@ def set_widget(self, widgetx): Indicates which widget is to be set. ''' - if widgetx in self.children.keys(): + if widgetx in list(self.children.keys()): return False else: if self._animation_type == 'absolute': @@ -539,7 +539,7 @@ def start(self, widget): def stop(self, widget = None): '''Stops the sequential animation''' if widget == None: - widget = self.animations[self.anim_counter].children.keys()[0] + widget = list(self.animations[self.anim_counter].children.keys())[0] if self.animations[self.anim_counter].children[widget].generate_event and not self.single_event: widget.dispatch_event('on_animation_complete', self) #self.animations[self.anim_counter]._del_child(widget) @@ -576,7 +576,7 @@ def start(self, widget): def stop(self, widget = None, animobj = None): '''Stops the parallel animation''' if widget == None: - widget = self.animations[self.dispatch_counter].children.keys()[0] + widget = list(self.animations[self.dispatch_counter].children.keys())[0] if animobj == None: animobj = self.animations[self.dispatch_counter].children[widget] diff --git a/pymt/ui/colors.py b/pymt/ui/colors.py index 97fe6b45..f9292140 100644 --- a/pymt/ui/colors.py +++ b/pymt/ui/colors.py @@ -220,13 +220,13 @@ def get_style(self, widget): # match for cls in reversed(widget_classes): - for r, v in self._css.iteritems(): + for r, v in self._css.items(): if r == cls: styles.update(v) # match . widget_cls = widget.cls - if type(widget_cls) in (unicode, str): + if type(widget_cls) in (str, str): widget_cls = [widget.cls] if type(widget_cls) in (list, tuple): for kcls in widget_cls: @@ -237,7 +237,7 @@ def get_style(self, widget): # match . for name in reversed(widget_classes): lcls = '%s%s' % (name, cls) - for r, v in self._css.iteritems(): + for r, v in self._css.items(): if r == lcls: styles.update(v) @@ -375,8 +375,8 @@ def css_reload(): if __name__ == '__main__': from pymt import MTWidget, css_get_style, MTWindow w = MTWidget() - print w - print css_get_style(widget=w) + print(w) + print(css_get_style(widget=w)) w = MTWindow() - print w - print css_get_style(widget=w) + print(w) + print(css_get_style(widget=w)) diff --git a/pymt/ui/widgets/composed/kineticlist.py b/pymt/ui/widgets/composed/kineticlist.py index f6f5e2ef..ae191bad 100644 --- a/pymt/ui/widgets/composed/kineticlist.py +++ b/pymt/ui/widgets/composed/kineticlist.py @@ -247,7 +247,7 @@ def filter(self, pattern, attr): '''Given an attribute of the children, and a pattern, return a list of the children with which pattern is in attr ''' - return filter(lambda c: pattern in str(getattr(c, attr)), self.pchildren) + return [c for c in self.pchildren if pattern in str(getattr(c, attr))] def search(self, pattern, attr): '''Apply a search pattern to the current set of children''' @@ -315,7 +315,7 @@ def do_layout(self): # calculate size of actual content size = 0 - for i in xrange(len(self.children)): + for i in range(len(self.children)): if i % limit == 0: maxrange = min(i + limit, len(self.children)) childrens = [self.children[z] for z in range(i, maxrange)] diff --git a/pymt/ui/widgets/composed/textarea.py b/pymt/ui/widgets/composed/textarea.py index 38d9c34e..27bf7a41 100644 --- a/pymt/ui/widgets/composed/textarea.py +++ b/pymt/ui/widgets/composed/textarea.py @@ -99,7 +99,7 @@ def _get_value(self): # return ''.join(out) # optimized version return ''.join([('\n' if (lf[i] & FL_IS_NEWLINE) else '') + l[i] \ - for i in xrange(len(l))]) + for i in range(len(l))]) def _set_value(self, text): old_value = self.value self._refresh_lines(text) @@ -126,9 +126,9 @@ def _refresh_lines(self, text=None): '''Recreate all lines / flags / labels from current value ''' cursor_index = self.cursor_index - text = text if type(text) in (str, unicode) else self.value + text = text if type(text) in (str, str) else self.value self.lines, self.lines_flags = self._split_smart(text) - self.line_labels = map(self.create_line_label, self.lines) + self.line_labels = list(map(self.create_line_label, self.lines)) self.line_height = self.line_labels[0].content_height self.line_spacing = 2 self._recalc_size() @@ -282,7 +282,7 @@ def create_line_label(self, text): def glyph_size(self, g): '''Get or add size of a glyph ''' - if not self._glyph_size.has_key(g): + if g not in self._glyph_size: l = self.create_line_label(g) self._glyph_size[g] = l.content_width return self._glyph_size[g] @@ -323,7 +323,7 @@ def cursor_index(self): return 0 lf = self.lines_flags index, cr = self.cursor - for row in xrange(cr): + for row in range(cr): index += len(l[row]) if lf[row] & FL_IS_NEWLINE: index += 1 @@ -335,7 +335,7 @@ def cursor_offset(self): '''Get the cursor x offset on the current line ''' offset = 0 - for i in xrange(self.cursor_col): + for i in range(self.cursor_col): offset += self.glyph_size(self.lines[self.cursor_row][i]) return offset @@ -347,7 +347,7 @@ def get_cursor_from_index(self, index): lf = self.lines_flags l = self.lines i = 0 - for row in xrange(len(l)): + for row in range(len(l)): ni = i + len(l[row]) if lf[row] & FL_IS_NEWLINE: ni += 1 @@ -579,8 +579,8 @@ def _kbd_on_key_up(self, key, repeat=False): if internal_action in ('shift', 'shift_L', 'shift_R'): self._update_selection(True) - def _window_on_key_down(self, key, scancode=None, unicode=None): - if unicode and not key in self.interesting_keys.keys() + [27]: + def _window_on_key_down(self, key, scancode=None, str=None): + if str and not key in list(self.interesting_keys.keys()) + [27]: modifiers = getWindow().modifiers if 'ctrl' in modifiers: if key == ord('x'): # cut selection @@ -600,6 +600,6 @@ def _window_on_key_down(self, key, scancode=None, unicode=None): else: if self._selection: self.delete_selection() - self.insert_text(unicode) + self.insert_text(str) self._recalc_size() - return super(MTTextArea, self)._window_on_key_down(key, scancode, unicode) + return super(MTTextArea, self)._window_on_key_down(key, scancode, str) diff --git a/pymt/ui/widgets/composed/textinput.py b/pymt/ui/widgets/composed/textinput.py index 4ef629bd..1b7dd4d8 100644 --- a/pymt/ui/widgets/composed/textinput.py +++ b/pymt/ui/widgets/composed/textinput.py @@ -264,7 +264,7 @@ def hide_keyboard(self): on_key_down=self._kbd_on_key_down ) - def _window_on_key_down(self, key, scancode=None, unicode=None): + def _window_on_key_down(self, key, scancode=None, str=None): modifiers = getWindow().modifiers if key == ord('v') and 'ctrl' in modifiers: text = Clipboard.get('text/plain') @@ -285,12 +285,12 @@ def _window_on_key_down(self, key, scancode=None, unicode=None): key = (None, None, k, 1) self.keyboard.dispatch_event('on_key_down', key) else: - if unicode is not None: - self.keyboard.text += unicode + if str is not None: + self.keyboard.text += str else: self.keyboard.text += chr(key) - def _window_on_key_up(self, key, scancode=None, unicode=None): + def _window_on_key_up(self, key, scancode=None, str=None): k = self.interesting_keys.get(key) if k and self.keyboard: key = (None, None, k, 1) diff --git a/pymt/ui/widgets/composed/vkeyboard.py b/pymt/ui/widgets/composed/vkeyboard.py index 2153b7b0..f07b0f2d 100644 --- a/pymt/ui/widgets/composed/vkeyboard.py +++ b/pymt/ui/widgets/composed/vkeyboard.py @@ -48,30 +48,30 @@ class KeyboardLayoutQWERTY(KeyboardLayout): ('3', '3', None, 1), ('4', '4', None, 1), ('5', '5', None, 1), ('6', '6', None, 1), ('7', '7', None, 1), ('8', '8', None, 1), ('9', '9', None, 1), ('0', '0', None, 1), ('+', '+', None, 1), - ('=', '=', None, 1), (u'\u232b', None, 'backspace', 2), + ('=', '=', None, 1), ('\u232b', None, 'backspace', 2), ] NORMAL_2 = [ - (u'\u21B9', chr(0x09), None, 1.5), ('q', 'q', None, 1), ('w', 'w', None, 1), + ('\u21B9', chr(0x09), None, 1.5), ('q', 'q', None, 1), ('w', 'w', None, 1), ('e', 'e', None, 1), ('r', 'r', None, 1), ('t', 't', None, 1), ('y', 'y', None, 1), ('u', 'u', None, 1), ('i', 'i', None, 1), ('o', 'o', None, 1), ('p', 'p', None, 1), ('{', '{', None, 1), ('}', '}', None, 1), ('|', '|', None, 1.5) ] NORMAL_3 = [ - (u'\u21ea', None, 'capslock', 1.8), ('a', 'a', None, 1), ('s', 's', None, 1), + ('\u21ea', None, 'capslock', 1.8), ('a', 'a', None, 1), ('s', 's', None, 1), ('d', 'd', None, 1), ('f', 'f', None, 1), ('g', 'g', None, 1), ('h', 'h', None, 1), ('j', 'j', None, 1), ('k', 'k', None, 1), ('l', 'l', None, 1), (':', ':', None, 1), ('"', '"', None, 1), - (u'\u23ce', None, 'enter', 2.2), + ('\u23ce', None, 'enter', 2.2), ] NORMAL_4 = [ - (u'\u21e7', None, 'shift_L', 2.5), ('z', 'z', None, 1), ('x', 'x', None, 1), + ('\u21e7', None, 'shift_L', 2.5), ('z', 'z', None, 1), ('x', 'x', None, 1), ('c', 'c', None, 1), ('v', 'v', None, 1), ('b', 'b', None, 1), ('n', 'n', None, 1), ('m', 'm', None, 1), ('<', '<', None, 1), - ('>', '>', None, 1), ('?', '?', None, 1), (u'\u21e7', None, 'shift_R', 2.5), + ('>', '>', None, 1), ('?', '?', None, 1), ('\u21e7', None, 'shift_R', 2.5), ] NORMAL_5 = [ - (' ', ' ', None, 12), (u'\u2b12', None, 'layout', 1.5), (u'\u2a2f', None, 'escape', 1.5), + (' ', ' ', None, 12), ('\u2b12', None, 'layout', 1.5), ('\u2a2f', None, 'escape', 1.5), ] SHIFT_1 = [ @@ -79,30 +79,30 @@ class KeyboardLayoutQWERTY(KeyboardLayout): ('#', '#', None, 1), ('$', '$', None, 1), ('%', '%', None, 1), ('^', '^', None, 1), ('&', '&', None, 1), ('*', '*', None, 1), ('(', '(', None, 1), (')', ')', None, 1), ('_', '_', None, 1), - ('+', '+', None, 1), (u'\u232b', None, 'backspace', 2), + ('+', '+', None, 1), ('\u232b', None, 'backspace', 2), ] SHIFT_2 = [ - (u'\u21B9', chr(0x09), None, 1.5), ('Q', 'Q', None, 1), ('W', 'W', None, 1), + ('\u21B9', chr(0x09), None, 1.5), ('Q', 'Q', None, 1), ('W', 'W', None, 1), ('E', 'E', None, 1), ('R', 'R', None, 1), ('T', 'T', None, 1), ('Y', 'Y', None, 1), ('U', 'U', None, 1), ('I', 'I', None, 1), ('O', 'O', None, 1), ('P', 'P', None, 1), ('[', '[', None, 1), (']', ']', None, 1), ('?', '?', None, 1.5) ] SHIFT_3 = [ - (u'\u21ea', None, 'capslock', 1.8), ('A', 'A', None, 1), ('S', 'S', None, 1), + ('\u21ea', None, 'capslock', 1.8), ('A', 'A', None, 1), ('S', 'S', None, 1), ('D', 'D', None, 1), ('F', 'F', None, 1), ('G', 'G', None, 1), ('H', 'H', None, 1), ('J', 'J', None, 1), ('K', 'K', None, 1), ('L', 'L', None, 1), (':', ':', None, 1), ('"', '"', None, 1), - (u'\u23ce', None, 'enter', 2.2), + ('\u23ce', None, 'enter', 2.2), ] SHIFT_4 = [ - (u'\u21e7', None, 'shift_L', 2.5), ('Z', 'Z', None, 1), ('X', 'X', None, 1), + ('\u21e7', None, 'shift_L', 2.5), ('Z', 'Z', None, 1), ('X', 'X', None, 1), ('C', 'C', None, 1), ('V', 'V', None, 1), ('B', 'B', None, 1), ('N', 'N', None, 1), ('M', 'M', None, 1), (',', ',', None, 1), - ('.', '.', None, 1), ('/', '/', None, 1), (u'\u21e7', None, 'shift_R', 2.5), + ('.', '.', None, 1), ('/', '/', None, 1), ('\u21e7', None, 'shift_R', 2.5), ] SHIFT_5 = [ - (' ', ' ', None, 12), (u'\u2b12', None, 'layout', 1.5), (u'\u2a2f', None, 'escape', 1.5), + (' ', ' ', None, 12), ('\u2b12', None, 'layout', 1.5), ('\u2a2f', None, 'escape', 1.5), ] LETTERS = NORMAL_2[1:11] + NORMAL_3[1:10] + NORMAL_4[1:8] + \ @@ -116,66 +116,66 @@ class KeyboardLayoutAZERTY(KeyboardLayout): DESCRIPTION = 'A French keyboard without international keys' SIZE = (15, 5) NORMAL_1 = [ - ('@', '@', None, 1), ('&', '&', None, 1), (u'\xe9', u'\xe9', None, 1), + ('@', '@', None, 1), ('&', '&', None, 1), ('\xe9', '\xe9', None, 1), ('"', '"', None, 1), ('\'', '\'', None, 1), ('(', '(', None, 1), - ('-', '-', None, 1), (u'\xe8', u'\xe8', None, 1), ('_', '_', None, 1), - (u'\xe7', u'\xe7', None, 1), (u'\xe0', u'\xe0', None, 1), (')', ')', None, 1), - ('=', '=', None, 1), (u'\u232b', None, 'backspace', 2), + ('-', '-', None, 1), ('\xe8', '\xe8', None, 1), ('_', '_', None, 1), + ('\xe7', '\xe7', None, 1), ('\xe0', '\xe0', None, 1), (')', ')', None, 1), + ('=', '=', None, 1), ('\u232b', None, 'backspace', 2), ] NORMAL_2 = [ - (u'\u21B9', chr(0x09), None, 1.5), ('a', 'a', None, 1), ('z', 'z', None, 1), + ('\u21B9', chr(0x09), None, 1.5), ('a', 'a', None, 1), ('z', 'z', None, 1), ('e', 'e', None, 1), ('r', 'r', None, 1), ('t', 't', None, 1), ('y', 'y', None, 1), ('u', 'u', None, 1), ('i', 'i', None, 1), ('o', 'o', None, 1), ('p', 'p', None, 1), ('^', '^', None, 1), - ('$', '$', None, 1), (u'\u23ce', None, 'enter', 1.5), + ('$', '$', None, 1), ('\u23ce', None, 'enter', 1.5), ] NORMAL_3 = [ - (u'\u21ea', None, 'capslock', 1.8), ('q', 'q', None, 1), ('s', 's', None, 1), + ('\u21ea', None, 'capslock', 1.8), ('q', 'q', None, 1), ('s', 's', None, 1), ('d', 'd', None, 1), ('f', 'f', None, 1), ('g', 'g', None, 1), ('h', 'h', None, 1), ('j', 'j', None, 1), ('k', 'k', None, 1), - ('l', 'l', None, 1), ('m', 'm', None, 1), (u'\xf9', u'\xf9', None, 1), - ('*', '*', None, 1), (u'\u23ce', None, 'enter', 1.2), + ('l', 'l', None, 1), ('m', 'm', None, 1), ('\xf9', '\xf9', None, 1), + ('*', '*', None, 1), ('\u23ce', None, 'enter', 1.2), ] NORMAL_4 = [ - (u'\u21e7', None, 'shift_L', 1.5), ('<', '<', None, 1), ('w', 'w', None, 1), + ('\u21e7', None, 'shift_L', 1.5), ('<', '<', None, 1), ('w', 'w', None, 1), ('x', 'x', None, 1), ('c', 'c', None, 1), ('v', 'v', None, 1), ('b', 'b', None, 1), ('n', 'n', None, 1), (',', ',', None, 1), (';', ';', None, 1), - (':', ':', None, 1), ('!', '!', None, 1), (u'\u21e7', None, 'shift_R', 2.5), + (':', ':', None, 1), ('!', '!', None, 1), ('\u21e7', None, 'shift_R', 2.5), ] NORMAL_5 = [ - (' ', ' ', None, 12), (u'\u2b12', None, 'layout', 1.5), (u'\u2a2f', None, 'escape', 1.5), + (' ', ' ', None, 12), ('\u2b12', None, 'layout', 1.5), ('\u2a2f', None, 'escape', 1.5), ] SHIFT_1 = [ ('|', '|', None, 1), ('1', '1', None, 1), ('2', '2', None, 1), ('3', '3', None, 1), ('4', '4', None, 1), ('5', '5', None, 1), ('6', '6', None, 1), ('7', '7', None, 1), ('8', '8', None, 1), ('9', '9', None, 1), ('0', '0', None, 1), ('#', '#', None, 1), - ('+', '+', None, 1), (u'\u232b', None, 'backspace', 2), + ('+', '+', None, 1), ('\u232b', None, 'backspace', 2), ] SHIFT_2 = [ - (u'\u21B9', chr(0x09), None, 1.5), ('A', 'A', None, 1), ('Z', 'Z', None, 1), + ('\u21B9', chr(0x09), None, 1.5), ('A', 'A', None, 1), ('Z', 'Z', None, 1), ('E', 'E', None, 1), ('R', 'R', None, 1), ('T', 'T', None, 1), ('Y', 'Y', None, 1), ('U', 'U', None, 1), ('I', 'I', None, 1), ('O', 'O', None, 1), ('P', 'P', None, 1), ('[', '[', None, 1), - (']', ']', None, 1), (u'\u23ce', None, 'enter', 1.5), + (']', ']', None, 1), ('\u23ce', None, 'enter', 1.5), ] SHIFT_3 = [ - (u'\u21ea', None, 'capslock', 1.8), ('Q', 'Q', None, 1), ('S', 'S', None, 1), + ('\u21ea', None, 'capslock', 1.8), ('Q', 'Q', None, 1), ('S', 'S', None, 1), ('D', 'D', None, 1), ('F', 'F', None, 1), ('G', 'G', None, 1), ('H', 'H', None, 1), ('J', 'J', None, 1), ('K', 'K', None, 1), ('L', 'L', None, 1), ('M', 'M', None, 1), ('%', '%', None, 1), - (u'\xb5', u'\xb5', None, 1), (u'\u23ce', None, 'enter', 1.2), + ('\xb5', '\xb5', None, 1), ('\u23ce', None, 'enter', 1.2), ] SHIFT_4 = [ - (u'\u21e7', None, 'shift_L', 1.5), ('>', '>', None, 1), ('W', 'W', None, 1), + ('\u21e7', None, 'shift_L', 1.5), ('>', '>', None, 1), ('W', 'W', None, 1), ('X', 'X', None, 1), ('C', 'C', None, 1), ('V', 'V', None, 1), ('B', 'B', None, 1), ('N', 'N', None, 1), ('?', '?', None, 1), - ('.', '.', None, 1), ('/', '/', None, 1), (u'\xa7', u'\xa7', None, 1), - (u'\u21e7', None, 'shift_R', 2.5), + ('.', '.', None, 1), ('/', '/', None, 1), ('\xa7', '\xa7', None, 1), + ('\u21e7', None, 'shift_R', 2.5), ] SHIFT_5 = [ - (' ', ' ', None, 12), (u'\u2b12', None, 'layout', 1.5), (u'\u2a2f', None, 'escape', 1.5), + (' ', ' ', None, 12), ('\u2b12', None, 'layout', 1.5), ('\u2a2f', None, 'escape', 1.5), ] LETTERS = NORMAL_2[1:11] + NORMAL_3[1:11] + NORMAL_4[2:8] + \ @@ -268,7 +268,7 @@ def __init__(self, **kwargs): self._last_update = 0 self._last_update_scale = 1. self._need_update = 'now' - self._internal_text = u'' + self._internal_text = '' self._show_layout = False self._active_keys = [] self._used_label = [] @@ -342,7 +342,7 @@ def _set_mode(self, value): def clear(self): '''Clear the text''' - self.text = u'' + self.text = '' def reset_repeat(self): '''Reset key repeat @@ -401,7 +401,7 @@ def _do_update(self, mode=None): if mode == 'background': s = 1. w, h = self.size - mtop, mright, mbottom, mleft = map(lambda x: x * s, self.style['margin']) + mtop, mright, mbottom, mleft = [x * s for x in self.style['margin']] self.texsize = Vector(w - mleft - mright, h - mtop - mbottom) kx, ky = self.layout.SIZE @@ -414,7 +414,7 @@ def _do_update(self, mode=None): with self._current_cache[mode]: # draw lines - for index in xrange(1, ky + 1): + for index in range(1, ky + 1): line = self.layout.__getattribute__('%s_%d' % (self.mode, index)) # draw keys diff --git a/pymt/ui/widgets/coverflow.py b/pymt/ui/widgets/coverflow.py index f07db2df..543efca0 100644 --- a/pymt/ui/widgets/coverflow.py +++ b/pymt/ui/widgets/coverflow.py @@ -338,11 +338,11 @@ def on_draw(self): return # draw left side - for i in xrange(0, self._selection): + for i in range(0, self._selection): self._render_cover(i) # draw right side in reverse order - for i in xrange(len(self.children) - 1, self._selection, - 1): + for i in range(len(self.children) - 1, self._selection, - 1): self._render_cover(i) # draw cover diff --git a/pymt/ui/widgets/layout/abstractlayout.py b/pymt/ui/widgets/layout/abstractlayout.py index f23ae8ee..33715e75 100644 --- a/pymt/ui/widgets/layout/abstractlayout.py +++ b/pymt/ui/widgets/layout/abstractlayout.py @@ -27,7 +27,7 @@ class MTAbstractLayout(MTWidget): def __init__(self, **kwargs): if self.__class__ == MTAbstractLayout: - raise NotImplementedError, 'class MTAbstractLayout is abstract' + raise NotImplementedError('class MTAbstractLayout is abstract') # if standard size is bigger, then stretching does work, if other # things are smaller than the default (100, 100) diff --git a/pymt/ui/widgets/layout/gridlayout.py b/pymt/ui/widgets/layout/gridlayout.py index 85eeef73..acf17313 100644 --- a/pymt/ui/widgets/layout/gridlayout.py +++ b/pymt/ui/widgets/layout/gridlayout.py @@ -66,8 +66,8 @@ def update_minimum_size(self): elif current_rows is None: current_rows = 1 + (len(self.children) / current_cols) - cols = dict(zip(xrange(current_cols), [0] * current_cols)) - rows = dict(zip(xrange(current_rows), [0] * current_rows)) + cols = dict(list(zip(list(range(current_cols)), [0] * current_cols))) + rows = dict(list(zip(list(range(current_rows)), [0] * current_rows))) # calculate maximum size for each columns and rows i = 0 @@ -125,9 +125,9 @@ def do_layout(self): # reposition every child i = 0 y = _y + spacing - for row_height in self.row_heights.itervalues(): + for row_height in self.row_heights.values(): x = _x + spacing - for col_width in self.col_widths.itervalues(): + for col_width in self.col_widths.values(): if i >= len(self.children): break c = self.children[i] diff --git a/pymt/ui/widgets/layout/screenlayout.py b/pymt/ui/widgets/layout/screenlayout.py index 5c2b51a4..28955743 100644 --- a/pymt/ui/widgets/layout/screenlayout.py +++ b/pymt/ui/widgets/layout/screenlayout.py @@ -73,7 +73,7 @@ def add_widget(self, widget, tab_name=None): def remove_widget(self, widget): for btn in self.tabs.children[:]: - if isinstance(widget, basestring): + if isinstance(widget, str): if btn.label == widget: self.tabs.remove_widget(btn) break diff --git a/pymt/ui/widgets/radial.py b/pymt/ui/widgets/radial.py index 78b959a9..6ca53e58 100644 --- a/pymt/ui/widgets/radial.py +++ b/pymt/ui/widgets/radial.py @@ -2,7 +2,7 @@ Vector slider: a radial slider that provide vector manipulation ''' -from __future__ import division + __all__ = ('MTVectorSlider', ) @@ -150,7 +150,7 @@ def draw(self): if __name__ == '__main__': def on_vector_change(amp, ang): - print amp, ang + print(amp, ang) from pymt import MTWindow, runTouchApp w = MTWindow(fullscreen=False) diff --git a/pymt/ui/widgets/slider.py b/pymt/ui/widgets/slider.py index 1a973386..fba9d340 100644 --- a/pymt/ui/widgets/slider.py +++ b/pymt/ui/widgets/slider.py @@ -2,7 +2,7 @@ Slider package: provide multiple slider implementation (simple, xy, boundary...) ''' -from __future__ import division + __all__ = ('MTSlider', 'MTXYSlider', 'MTBoundarySlider', 'MTMultiSlider') @@ -365,8 +365,8 @@ def draw(self): set_color(*self.style.get('slider-color')) drawCSSRectangle(pos=pos, size=size, style=self.style, prefix='slider') if self.showtext and len(self.touchstarts): - drawLabel(u'%.1f' % (self.value_min), pos=textposmin, font_size=self.style['font-size']) - drawLabel(u'%.1f' % (self.value_max), pos=textposmax, font_size=self.style['font-size']) + drawLabel('%.1f' % (self.value_min), pos=textposmin, font_size=self.style['font-size']) + drawLabel('%.1f' % (self.value_max), pos=textposmax, font_size=self.style['font-size']) def on_touch_down(self, touch): # So the first on_touch_move in a diff --git a/pymt/ui/widgets/svg.py b/pymt/ui/widgets/svg.py index 794972cb..7deba6ab 100644 --- a/pymt/ui/widgets/svg.py +++ b/pymt/ui/widgets/svg.py @@ -88,14 +88,14 @@ def _set_filename(self, filename): try: pymt_logger.debug('SVGButton: loading %s' % filename) self.svg = squirtle.SVG(filename) - except Exception, e: + except Exception as e: try: svgpath = os.path.join(pymt_data_dir, 'icons/svg') pymt_logger.exception('SVGButton: unable to load %s' % filename) pymt_logger.warning('SVGButton: trying %s' % ( svgpath + filename)) self.svg = squirtle.SVG(os.path.join(svgpath, filename)) - except Exception, e: + except Exception as e: pymt_logger.exception('SVGButton: unable to load file %s' % filename) self._filename = filename self.size = (self.svg.width, self.svg.height) diff --git a/pymt/ui/widgets/widget.py b/pymt/ui/widgets/widget.py index 527fb0dd..d69174b8 100644 --- a/pymt/ui/widgets/widget.py +++ b/pymt/ui/widgets/widget.py @@ -36,7 +36,7 @@ def __init__(mcs, name, bases, attrs): # auto registration in factory MTWidgetFactory.register(name, mcs) -class MTWidget(EventDispatcher): +class MTWidget(EventDispatcher, metaclass=MTWidgetMetaclass): '''Global base for any multitouch widget. Implement event for mouse, object, touch and animation. @@ -81,8 +81,6 @@ class MTWidget(EventDispatcher): Fired when parent widget is resized ''' - __metaclass__ = MTWidgetMetaclass - __slots__ = ('children', 'style', 'draw_children', '_cls', '_root_window_source', '_root_window', @@ -480,5 +478,5 @@ def _set_height(self, x): MTWidget.on_update = types.MethodType(accelerate.widget_on_update, None, MTWidget) MTWidget.on_draw = types.MethodType(accelerate.widget_on_draw, None, MTWidget) MTWidget.collide_point = types.MethodType(accelerate.widget_collide_point, None, MTWidget) -except ImportError, e: +except ImportError as e: pymt_logger.warning('Widget: Unable to use accelerate module <%s>' % e) diff --git a/pymt/ui/widgets/xmlwidget.py b/pymt/ui/widgets/xmlwidget.py index 8367fc88..f3c47306 100644 --- a/pymt/ui/widgets/xmlwidget.py +++ b/pymt/ui/widgets/xmlwidget.py @@ -56,7 +56,7 @@ def autoconnect(self, obj): and you want to connect on on_press event, it will search the obj.on_plop_press() function. ''' - for widget_id, children in self.registerdb.items(): + for widget_id, children in list(self.registerdb.items()): for event in children.event_types: eventobj = event if eventobj[:3] == 'on_': @@ -75,7 +75,7 @@ def createNode(self, node): # parameters k = {} widget_id = None - for name, value in node.attributes.items(): + for name, value in list(node.attributes.items()): name = str(name) if name == 'id': widget_id = eval(value) diff --git a/pymt/ui/window/__init__.py b/pymt/ui/window/__init__.py index 43eefa05..075567a3 100644 --- a/pymt/ui/window/__init__.py +++ b/pymt/ui/window/__init__.py @@ -342,8 +342,8 @@ def draw_wallpaper(self): r_x = int(r_x) + 1 if int(r_y) != r_y: r_y = int(r_y) + 1 - for x in xrange(int(r_x)): - for y in xrange(int(r_y)): + for x in range(int(r_x)): + for y in range(int(r_y)): wallpaper.x = x * wallpaper.width wallpaper.y = y * wallpaper.height wallpaper.draw() @@ -523,7 +523,7 @@ def on_mouse_up(self, x, y, button, modifiers): '''Event called when mouse is moving, with buttons pressed''' pass - def on_keyboard(self, key, scancode=None, unicode=None): + def on_keyboard(self, key, scancode=None, str=None): '''Event called when keyboard is in action .. warning:: @@ -531,11 +531,11 @@ def on_keyboard(self, key, scancode=None, unicode=None): ''' pass - def on_key_down(self, key, scancode=None, unicode=None): + def on_key_down(self, key, scancode=None, str=None): '''Event called when a key is down (same arguments as on_keyboard)''' pass - def on_key_up(self, key, scancode=None, unicode=None): + def on_key_up(self, key, scancode=None, str=None): '''Event called when a key is up (same arguments as on_keyboard)''' pass @@ -580,7 +580,7 @@ def draw(self): if not 'PYMT_DOC' in os.environ: if 'pygame' in pymt.pymt_options['window']: try: - import win_pygame + from . import win_pygame MTWindow = win_pygame.MTWindowPygame pymt_logger.info('Window: use Pygame as window provider.') except ImportError: @@ -588,7 +588,7 @@ def draw(self): if MTWindow is None and 'glut' in pymt.pymt_options['window']: try: - import win_glut + from . import win_glut MTWindow = win_glut.MTWindowGlut pymt_logger.info('Window: use GLUT as window provider.') except ImportError: diff --git a/pymt/ui/window/win_glut.py b/pymt/ui/window/win_glut.py index 044ee0c3..fb69d773 100644 --- a/pymt/ui/window/win_glut.py +++ b/pymt/ui/window/win_glut.py @@ -58,12 +58,12 @@ def close(self): self.__glut_window = None super(MTWindowGlut, self).close() - def on_keyboard(self, key, scancode=None, unicode=None): + def on_keyboard(self, key, scancode=None, str=None): self._glut_update_modifiers() if ord(key) == 27: stopTouchApp() return True - super(MTWindowGlut, self).on_keyboard(key, scancode, unicode) + super(MTWindowGlut, self).on_keyboard(key, scancode, str) def _set_size(self, size): if super(MTWindowGlut, self)._set_size(size): diff --git a/pymt/ui/window/win_pygame.py b/pymt/ui/window/win_pygame.py index eafce288..8e819ddc 100644 --- a/pymt/ui/window/win_pygame.py +++ b/pymt/ui/window/win_pygame.py @@ -125,12 +125,12 @@ def create_window(self, params): def close(self): pygame.display.quit() - def on_keyboard(self, key, scancode=None, unicode=None): + def on_keyboard(self, key, scancode=None, str=None): if key == 27: stopTouchApp() self.close() #not sure what to do here return True - super(MTWindowPygame, self).on_keyboard(key, scancode, unicode) + super(MTWindowPygame, self).on_keyboard(key, scancode, str) def flip(self): pygame.display.flip() @@ -199,10 +199,10 @@ def _mainloop(self): # don't dispatch more key if down event is accepted if self.dispatch_event('on_key_down', event.key, - event.scancode, event.unicode): + event.scancode, event.str): continue self.dispatch_event('on_keyboard', event.key, - event.scancode, event.unicode) + event.scancode, event.str) # video resize elif event.type == pygame.VIDEORESIZE: @@ -227,7 +227,7 @@ def mainloop(self): self._mainloop() if not pygame.display.get_active(): pygame.time.wait(100) - except BaseException, inst: + except BaseException as inst: # use exception manager first r = pymt_exception_manager.handle_exception(inst) if r == ExceptionManager.RAISE: diff --git a/pymt/utils.py b/pymt/utils.py index 7d8fc4f0..d4c1dd50 100644 --- a/pymt/utils.py +++ b/pymt/utils.py @@ -20,11 +20,11 @@ def boundary(value, minvalue, maxvalue): def intersection(set1, set2): '''Return intersection between 2 list''' - return filter(lambda s:s in set2, set1) + return [s for s in set1 if s in set2] def difference(set1, set2): '''Return difference between 2 list''' - return filter(lambda s:s not in set2, set1) + return [s for s in set1 if s not in set2] def curry(fn, *cargs, **ckwargs): '''Change the function signature to pass new variable.''' @@ -105,7 +105,7 @@ def get_random_color(alpha=1.0): def get_color_for_pyglet(c): '''Transform from pymt color to pyglet color''' - return map(lambda x: int(255 * x), c) + return [int(255 * x) for x in c] def is_color_transparent(c): '''Return true if alpha channel is 0''' @@ -137,8 +137,8 @@ def new_func(*args, **kwargs): 'Called from %s line %d' ' by %s().') % ( func.__name__, - func.func_code.co_filename, - func.func_code.co_firstlineno + 1, + func.__code__.co_filename, + func.__code__.co_firstlineno + 1, file, line, caller) pymt_logger.warn(warning) if func.__doc__: @@ -165,7 +165,7 @@ def iterate(self, reverse=False): def serialize_numpy(obj): import numpy - from StringIO import StringIO + from io import StringIO from base64 import b64encode io = StringIO() numpy.save(io, obj) @@ -174,7 +174,7 @@ def serialize_numpy(obj): def deserialize_numpy(s): import numpy - from StringIO import StringIO + from io import StringIO from base64 import b64decode io = StringIO(b64decode(s)) return numpy.load(io) diff --git a/pymt/vector.py b/pymt/vector.py index 6e0af1b7..ca92f67f 100644 --- a/pymt/vector.py +++ b/pymt/vector.py @@ -42,10 +42,10 @@ def __getslice__(self, i, j): # result to vector return Vector(super(Vector, self).__getslice__(i, j)) except Exception: - raise TypeError, 'vector::FAILURE in __getslice__' + raise TypeError('vector::FAILURE in __getslice__') def __add__(self, val): - return Vector(map(lambda x, y: x + y, self, val)) + return Vector(list(map(lambda x, y: x + y, self, val))) def __iadd__(self, val): if type(val) in (int, float): @@ -57,10 +57,10 @@ def __iadd__(self, val): return self def __neg__(self): - return Vector(map(lambda x: -x, self)) + return Vector([-x for x in self]) def __sub__(self, val): - return Vector(map(lambda x, y: x - y, self, val)) + return Vector(list(map(lambda x, y: x - y, self, val))) def __isub__(self, val): if type(val) in (int, float): @@ -73,9 +73,9 @@ def __isub__(self, val): def __mul__(self, val): try: - return Vector(map(lambda x, y: x * y, self, val)) + return Vector(list(map(lambda x, y: x * y, self, val))) except Exception: - return Vector(map(lambda x: x * val, self)) + return Vector([x * val for x in self]) def __imul__(self, val): if type(val) in (int, float): @@ -91,21 +91,21 @@ def __rmul__(self, val): def __truediv__(self, val): try: - return Vector(map(lambda x, y: x / y, self, val)) + return Vector(list(map(lambda x, y: x / y, self, val))) except Exception: - return Vector(map(lambda x: x / val, self)) + return Vector([x / val for x in self]) def __div__(self, val): try: - return Vector(map(lambda x, y: x / y, self, val)) + return Vector(list(map(lambda x, y: x / y, self, val))) except Exception: - return Vector(map(lambda x: x / val, self)) + return Vector([x / val for x in self]) def __rdiv__(self, val): try: - return Vector(map(lambda x, y: x / y, other, val)) + return Vector(list(map(lambda x, y: x / y, other, val))) except Exception: - return Vector(map(lambda x: other / x, val)) + return Vector([other / x for x in val]) def __idiv__(self, val): if type(val) in (int, float): diff --git a/pymt/weakmethod.py b/pymt/weakmethod.py index 671ce4c4..ab35950c 100644 --- a/pymt/weakmethod.py +++ b/pymt/weakmethod.py @@ -10,19 +10,19 @@ ''' import weakref -import new +from types import MethodType as instancemethod class WeakMethod(object): def __init__(self, method): try: - if method.im_self is not None: + if method.__self__ is not None: # bound method - self._obj = weakref.ref(method.im_self) + self._obj = weakref.ref(method.__self__) else: # unbound method self._obj = None - self._func = method.im_func - self._class = method.im_class + self._func = method.__func__ + self._class = method.__self__.__class__ except AttributeError: # not a method self._obj = None @@ -39,7 +39,7 @@ def __call__(self): return None if self._obj is not None: # we have an instance: return a bound method - return new.instancemethod(self._func, self._obj(), self._class) + return instancemethod(self._func, self._obj(), self._class) else: # we don't have an instance: return just the function return self._func diff --git a/setup.py b/setup.py index 3c679574..ab64cefd 100644 --- a/setup.py +++ b/setup.py @@ -8,9 +8,9 @@ try: import numpy except: - print '#' * 80 - print 'PyMT require numpy now. Please install it before running PyMT setup' - print '#' * 80 + print('#' * 80) + print('PyMT require numpy now. Please install it before running PyMT setup') + print('#' * 80) sys.exit(1) @@ -56,10 +56,10 @@ if 'sdist' in sys.argv and have_cython: from glob import glob from Cython.Compiler.Main import compile - print 'Generating C files...', + print('Generating C files...', end=' ') files = glob(os.path.join(os.path.dirname(__file__), 'pymt', 'c_ext', '*.pyx')) compile(files) - print 'Done !' + print('Done !') #add cython core extension modules if cython is available if have_cython: @@ -72,7 +72,7 @@ elif sys.platform == 'darwin': # On OSX, gl.h is not in GL/gl.h but OpenGL/gl.h. Cython has no # such thing as #ifdef, hence we just copy the file here. - source = '/System/Library/Frameworks/OpenGL.framework/Versions/A/Headers/gl.h' + source = '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/OpenGL.framework/Headers/gl.h' incl = 'build/include/' dest = os.path.join(incl, 'GL/') try: @@ -183,7 +183,7 @@ 'tools/packaging/win32/README.txt', 'tools/packaging/osx/pymt.sh',] }, - data_files=examples.items(), + data_files=list(examples.items()), classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: MacOS X', diff --git a/tests/bench_event.py b/tests/bench_event.py index 7b20c880..4dc7d219 100644 --- a/tests/bench_event.py +++ b/tests/bench_event.py @@ -76,6 +76,6 @@ class TestTouch(pymt.Touch): for x in ('MTWidget', 'MTLabel', 'MTScatterWidget',): t = timeit.Timer(stmt_on_update, stmt_setup % x).timeit(number=frames) - print '%s: on_update : Time=%.3f, FPS=%.3f' % (x, t, frames / t) + print('%s: on_update : Time=%.3f, FPS=%.3f' % (x, t, frames / t)) t = timeit.Timer(stmt_on_touch_all, stmt_setup % x).timeit(number=frames) - print '%s: on_touch_*: Time=%.3f, FPS=%.3f' % (x, t, frames / t) + print('%s: on_touch_*: Time=%.3f, FPS=%.3f' % (x, t, frames / t)) diff --git a/tests/init.py b/tests/init.py index 203f6933..3ad3f4b3 100644 --- a/tests/init.py +++ b/tests/init.py @@ -34,7 +34,7 @@ def test(cond): import sys import inspect import os - frame = sys._current_frames().values()[0] + frame = list(sys._current_frames().values())[0] callers = inspect.getouterframes(frame) caller = callers[1] info = inspect.getframeinfo(caller[0]) @@ -51,12 +51,12 @@ def testresult(code, ret): import os, sys if '__verbose' not in os.environ: return - print '%-35s %-35s %4s' % ( + print('%-35s %-35s %4s' % ( '%s:%s' % (os.environ['__modname'][5:], os.environ['__testname'][9:]), code, ret - ) + )) def _set_testinfo(a, b): import os @@ -78,10 +78,10 @@ def testrun(modname, testname): getattr(mod, testname)() passed = os.environ['__test_passed'] failed = os.environ['__test_failed'] - print '%-35s %3s passed, %3s failed' % ( + print('%-35s %3s passed, %3s failed' % ( '%s:%s' % (os.environ['__modname'][5:], os.environ['__testname'][9:]), - passed, failed) + passed, failed)) def testrun_launch(modname, testname): import subprocess @@ -107,10 +107,10 @@ def testrun_launch(modname, testname): elif x in ('--debug'): os.environ['__debug'] = '1' elif x in ('--help'): - print 'Usage: python init.py [options] ' - print ' --debug show debug' - print ' --verbose show verbose' - print ' --help show this help' + print('Usage: python init.py [options] ') + print(' --debug show debug') + print(' --verbose show verbose') + print(' --help show this help') sys.exit(0) if len(sys.argv) == 3: @@ -144,6 +144,6 @@ def testrun_launch(modname, testname): testrun_launch(modname, testname) elasped = time.time() - start - print '>> Finished in %.3fs' % ( + print('>> Finished in %.3fs' % ( elasped, - ) + )) diff --git a/tests/test_baseobject.py b/tests/test_baseobject.py index a06c37a4..14ec4a9d 100644 --- a/tests/test_baseobject.py +++ b/tests/test_baseobject.py @@ -2,7 +2,7 @@ BaseObject ''' -from init import test, import_pymt_no_window +from .init import test, import_pymt_no_window def unittest_defaults(): import_pymt_no_window() diff --git a/tests/test_css.py b/tests/test_css.py index d537eae0..ceaaf658 100644 --- a/tests/test_css.py +++ b/tests/test_css.py @@ -2,7 +2,7 @@ Css styling basic tests ''' -from init import test, import_pymt_no_window +from .init import test, import_pymt_no_window def unittest_css(): import_pymt_no_window() diff --git a/tests/test_events.py b/tests/test_events.py index ed2a5676..caa86414 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -2,7 +2,7 @@ Events ''' -from init import test, import_pymt_no_window +from .init import test, import_pymt_no_window def unittest_dispatcher(): import_pymt_no_window() diff --git a/tests/test_layout.py b/tests/test_layout.py index fe08e93a..e985ab31 100644 --- a/tests/test_layout.py +++ b/tests/test_layout.py @@ -2,7 +2,7 @@ Layout ''' -from init import test, import_pymt_no_window +from .init import test, import_pymt_no_window def unittest_boxlayout_horizontal(): _test_boxlayout('horizontal') @@ -30,7 +30,7 @@ def sw(tpl): # default add m = MTBoxLayout(orientation=orientation) - for x in xrange(10): + for x in range(10): m.add_widget(MTWidget(size=(10,10))) test(sw(m.size) == (109, 10)) @@ -38,7 +38,7 @@ def sw(tpl): # spacing to 10 # m = MTBoxLayout(orientation=orientation, spacing=10) - for x in xrange(10): + for x in range(10): m.add_widget(MTWidget(size=(10,10))) test(sw(m.size) == (190, 10)) @@ -46,13 +46,13 @@ def sw(tpl): # padding to 10 # m = MTBoxLayout(orientation=orientation, padding=10, spacing=0) - for x in xrange(10): + for x in range(10): m.add_widget(MTWidget(size=(10,10))) m.do_layout() # size should be 10 (number of widget) * width (10) + 2 * padding test(sw(m.size) == (120, 30)) - for x in xrange(10): + for x in range(10): if orientation == 'vertical': test(sw(m.children[x].pos) == (10 + x * 10, 10)) else: @@ -95,12 +95,12 @@ def sw(tpl): # testing with padding + spacing # m = MTBoxLayout(orientation=orientation, spacing=10, padding=10) - for x in xrange(10): + for x in range(10): m.add_widget(MTWidget(size=(10,10))) m.do_layout() test(sw(m.size) == (210, 30)) - for x in xrange(10): + for x in range(10): if orientation == 'vertical': test(sw(m.children[x].pos) == (10 + x * 20, 10)) else: diff --git a/tests/test_textarea.py b/tests/test_textarea.py index 1ac0aec3..7558654a 100644 --- a/tests/test_textarea.py +++ b/tests/test_textarea.py @@ -2,7 +2,7 @@ Test usage of MTTextArea widget ''' -from init import test, import_pymt_window +from .init import test, import_pymt_window def instance(**kwargs): ''' Individual test framework''' @@ -71,7 +71,7 @@ def unittest_mttextarea_cursor(): # test bounds test(t.get_cursor_from_index(-1) == (0, 0)) test(t.get_cursor_from_index(-100) == (0, 0)) - print t.get_cursor_from_index(12) + print(t.get_cursor_from_index(12)) test(t.get_cursor_from_index(12) == (3, 2)) test(t.get_cursor_from_index(100) == (3, 2)) diff --git a/tests/test_textinput.py b/tests/test_textinput.py index 3f325061..d6c5529e 100644 --- a/tests/test_textinput.py +++ b/tests/test_textinput.py @@ -2,7 +2,7 @@ test usage of MTTextInput widget ''' -from init import test, import_pymt_window +from .init import test, import_pymt_window def instance(): import_pymt_window() diff --git a/tests/test_vector.py b/tests/test_vector.py index 813bccd5..040f265a 100644 --- a/tests/test_vector.py +++ b/tests/test_vector.py @@ -1,5 +1,5 @@ -from init import test, import_pymt_no_window +from .init import test, import_pymt_no_window def unittest_basics(): import_pymt_no_window() diff --git a/tests/test_widget.py b/tests/test_widget.py index 5b366f63..e1094b87 100644 --- a/tests/test_widget.py +++ b/tests/test_widget.py @@ -2,7 +2,7 @@ Widgets ''' -from init import test, import_pymt_no_window +from .init import test, import_pymt_no_window def unittest_defaults(): import_pymt_no_window() diff --git a/tools/cleanwhitespace.py b/tools/cleanwhitespace.py index e58ba042..1391154b 100644 --- a/tools/cleanwhitespace.py +++ b/tools/cleanwhitespace.py @@ -19,13 +19,13 @@ content = fd.read() lines = content.split('\r\n') changes = 0 - for idx in xrange(len(lines)): + for idx in range(len(lines)): line = endspacestab.split(lines[idx], maxsplit=1)[0] if lines[idx] != line: changes += 1 lines[idx] = line modified = '\r\n'.join(lines) if changes: - print filename, ',', changes, 'removals' + print(filename, ',', changes, 'removals') with open(filename, 'w') as fd: fd.write(modified) diff --git a/tools/depend/depend.py b/tools/depend/depend.py index 5ec7f41c..55c0281e 100644 --- a/tools/depend/depend.py +++ b/tools/depend/depend.py @@ -6,7 +6,7 @@ def f9(seq): # Not order preserving - return {}.fromkeys(seq).keys() + return list({}.fromkeys(seq).keys()) cmd = "find pymt -iname '*.py' -exec grep -H 'import' {} \;" output = Popen(cmd, shell=True, stdout=PIPE).communicate()[0] @@ -19,7 +19,7 @@ def f9(seq): continue if line.find('=') > 0: continue - filename, line = map(lambda x: x.strip(), line.split(':', 1)) + filename, line = [x.strip() for x in line.split(':', 1)] line = line.rsplit('#', 1)[0] filename = filename[:-3] if line.startswith('import'): @@ -53,7 +53,7 @@ def f9(seq): # resolve path in b cmps2 = [] -kcmp = f9(map(lambda x: x[0], cmps)) +kcmp = f9([x[0] for x in cmps]) for a, b in cmps: nb = b.lstrip('.') nbp = len(b) - len(nb) @@ -78,7 +78,7 @@ def f9(seq): cmps2.append((a, b)) cmps = cmps2 -print 'digraph {' +print('digraph {') for a, b in cmps: - print '"%s" -> "%s"' % (b, a) -print '}' + print('"%s" -> "%s"' % (b, a)) +print('}') diff --git a/tools/pep8checker/pep8.py b/tools/pep8checker/pep8.py index b7505a64..884dfb09 100644 --- a/tools/pep8checker/pep8.py +++ b/tools/pep8checker/pep8.py @@ -497,7 +497,7 @@ def message(text): """Print a message.""" # print >> sys.stderr, options.prog + ': ' + text # print >> sys.stderr, text - print text + print(text) def find_checks(argument_name): @@ -507,7 +507,7 @@ def find_checks(argument_name): """ checks = [] function_type = type(find_checks) - for name, function in globals().iteritems(): + for name, function in globals().items(): if type(function) is function_type: args = inspect.getargspec(function)[0] if len(args) >= 1 and args[0].startswith(argument_name): @@ -642,10 +642,10 @@ def check_logical(self): self.previous_indent_level = self.indent_level self.indent_level = expand_indent(indent) if options.verbose >= 2: - print self.logical_line[:80].rstrip() + print(self.logical_line[:80].rstrip()) for name, check, argument_names in self.logical_checks: if options.verbose >= 3: - print ' ', name + print(' ', name) result = self.run_check(check, argument_names) if result is not None: offset, text = result @@ -810,7 +810,7 @@ def get_statistics(prefix=''): prefix='E4' matches all errors that have to do with imports """ stats = [] - keys = options.messages.keys() + keys = list(options.messages.keys()) keys.sort() for key in keys: if key.startswith(prefix): @@ -822,21 +822,21 @@ def get_statistics(prefix=''): def print_statistics(prefix=''): """Print overall statistics (number of errors and warnings).""" for line in get_statistics(prefix): - print line + print(line) def print_benchmark(elapsed): """ Print benchmark numbers. """ - print '%-7.2f %s' % (elapsed, 'seconds elapsed') + print('%-7.2f %s' % (elapsed, 'seconds elapsed')) keys = ['directories', 'files', 'logical lines', 'physical lines'] for key in keys: if key in options.counters: - print '%-7d %s per second (%d total)' % ( + print('%-7d %s per second (%d total)' % ( options.counters[key] / elapsed, key, - options.counters[key]) + options.counters[key])) def process_options(arglist=None): diff --git a/tools/pep8checker/pep8pymt.py b/tools/pep8checker/pep8pymt.py index 7f7916fb..c2ffa515 100644 --- a/tools/pep8checker/pep8pymt.py +++ b/tools/pep8checker/pep8pymt.py @@ -15,12 +15,12 @@ def report_error(self, line_number, offset, text, check): self, line_number, offset, text, check) # html generation - print '%d%s' % (line_number, text) + print('%d%s' % (line_number, text)) if __name__ == '__main__': def usage(): - print 'Usage: python pep8pymt.py [-html] ' + print('Usage: python pep8pymt.py [-html] ') sys.exit(1) if len(sys.argv) < 2: @@ -38,7 +38,7 @@ def usage(): pep8.process_options(['']) if htmlmode: - print ''' + print(''' PyMT Pep8 checker