Commits

Anonymous committed f6c4846

Finished trunk rev merge 2544

Comments (0)

Files changed (30)

 # BREAK = change breaks existing code
 # BUG    = fixed a bug that was (or could have been) crashing
 
+[SVN 2519] July 17, 2009
+    [BUG] fix pygame.font.get_fonts() bug for Python 3.1 and Windows.
+
+[SVN 2517-2518] July 17, 2009
+    [BUG] unit test framework fails for Python 3.1 on Windows due
+          to str/bytes confusion
+
+[SVN 2516] July 16, 2009
+    Pygame dependency build now replaces the configure
+    generated SDL_config.py, which MSVC can not use,  with 
+    SDL_config_win32.py
+
+[SVN 2515] July 15, 2009
+    [BUG] surface docs typo patch submitted by Lorenz Quack
+
+[SVN 2503-2505] July 13, 2009
+    [BUG] bugzilla 29, patch to use SDL_VIDEO_DRIVER_X11 DISABLE_X11.  Thanks Robert A. Lerche.
+        So can compile pygame without X11 again.
+    [BUG] fixed bad midi test.
+    [BUG] pygame.gfxdraw docstrings were not there.  Now... they... are.
+
+[SVN 2491-2495] July 9, 2009
+    [BUG] Fixed up quit bug in eventlist.py example.  Thanks Evan Kroske!
+    [BUG] Made the test code more compatible with python2.3.
+    [BUG] python3.1 support for OSX.
+
+[SVN 2486-2488] July 8, 2009
+    [BUG] 64bit issues with Surface.get_masks and UintFromObj. 
+        thanks Lorenz Quack!
+    [BUG] Color slicing works with python3 now too.
 
 [SVN 2481] July 7, 2009
     [BUG] typo in examples/sound_array_demos.py Thanks Evan Kroske!
     elif sys.platform == 'darwin':
         print_('Using Darwin configuration...\n')
         import config_darwin as CFG
-        additional_platform_setup = file("Setup_Darwin.in", "r").readlines()
+        additional_platform_setup = open("Setup_Darwin.in", "r").readlines()
     else:
         print_('Using UNIX configuration...\n')
         import config_unix as CFG
 
     def configure(self, incdirs, libdirs):
         incname = self.checkhead
-        libnames = self.checklib, string.lower(self.name)
+        libnames = self.checklib, self.name.lower()
         for dir in incdirs:
             path = os.path.join(dir, incname)
             if os.path.isfile(path):
                     self.lib_dir = dir
                     break
         if self.lib_dir and self.inc_dir:
-            print self.name + '        '[len(self.name):] + ': found'
+            print (self.name + '        '[len(self.name):] + ': found')
             self.found = 1
         else:
-            print self.name + '        '[len(self.name):] + ': not found'
+            print (self.name + '        '[len(self.name):] + ': not found')
 
 class FrameworkDependency(Dependency):
     def configure(self, incdirs, libdirs):
             n += 'Library/Frameworks/'
             fmwk = n + self.libs + '.framework/Versions/Current/'
             if os.path.isfile(fmwk + self.libs):
-                print 'Framework ' + self.libs + ' found'
+                print ('Framework ' + self.libs + ' found')
                 self.found = 1
                 self.inc_dir = fmwk + 'Headers'
                 self.cflags = (
                 self.origlib = self.libs
                 self.libs = ''
                 return
-        print 'Framework ' + self.libs + ' not found'
+        print ('Framework ' + self.libs + ' not found')
 
 
 class DependencyPython:
             else:
                 self.inc_dir = os.path.split(fullpath)[0]
         if self.found:
-            print self.name + '        '[len(self.name):] + ': found', self.ver
+            print (self.name + '        '[len(self.name):] + ': found', self.ver)
         else:
-            print self.name + '        '[len(self.name):] + ': not found'
+            print (self.name + '        '[len(self.name):] + ': not found')
 
 DEPS = [
     FrameworkDependency('SDL', 'SDL.h', 'libSDL', 'SDL'),
 def main():
     global DEPS
 
-    print 'Hunting dependencies...'
+    print ('Hunting dependencies...')
     incdirs = ['/usr/local/include','/opt/local/include']
     libdirs = ['/usr/local/lib','/opt/local/lib']
     newconfig = []
 
 
 if __name__ == '__main__':
-    print """This is the configuration subscript for OSX Darwin.
-             Please run "config.py" for full configuration."""
+    print ("""This is the configuration subscript for OSX Darwin.
+             Please run "config.py" for full configuration.""")

docs/ref/surface.html

   SRCALPHA, the pixel format will include a per-pixel alpha
 </pre><p>Both flags are only a request, and may not be possible for all displays and formats. </p>
 <p>Advance users can combine a set of bitmasks with a depth value. The masks are a set of 4 integers representing which bits in a pixel will represent each color. Normal Surfaces should not require the masks argument. </p>
-<p>Surfaces can have many extra attributes like alpha planes, colorkeys, source rectangle clipping. These functions mainly effect how the Surface is blitted to other Surfaces. The blit routines will attempt to use hardware acceleratio </p>
-<pre> when possible, otherwise will use highly optimized software blitting methods.
-</pre><p>There are three types of transparency supported in Pygame: colorkeys, surface alphas, and pixel alphas. Surface alphas can be mixed with colorkeys, but an image with per pixel alphas cannot use the other modes. Colorkey transparency makes a single color value transparent. Any pixels matching the colorkey will not be drawn. The surface alpha value is a single value that changes the transparency for the entire image. <tt>A</tt> surface alpha of 255 is opaque, and a value of 0 is completely transparent. </p>
+<p>Surfaces can have many extra attributes like alpha planes, colorkeys, source rectangle clipping. These functions mainly effect how the Surface is blitted to other Surfaces. The blit routines will attempt to use hardware acceleration when possible, otherwise they will use highly optimized software blitting methods. </p>
+<p>There are three types of transparency supported in Pygame: colorkeys, surface alphas, and pixel alphas. Surface alphas can be mixed with colorkeys, but an image with per pixel alphas cannot use the other modes. Colorkey transparency makes a single color value transparent. Any pixels matching the colorkey will not be drawn. The surface alpha value is a single value that changes the transparency for the entire image. <tt>A</tt> surface alpha of 255 is opaque, and a value of 0 is completely transparent. </p>
 <p>Per pixel alphas are different because they store a transparency value for every pixel. This allows for the most precise transparency effects, but it also the slowest. Per pixel alphas cannot be mixed with surface alpha and colorkeys. </p>
 <p>There is support for pixel access for the Surfaces. Pixel access on hardware surfaces is slow and not recommended. Pixels can be accessed using the get_at() and set_at() functions. These methods are fine for simple access, but will be considerably slow when doing of pixel work with them. If you plan on doing a lot of pixel level work, it is recommended to use the <tt>pygame.surfarray</tt> module, which can treat the surfaces like large multidimensional arrays (and it's quite quick). </p>
 <p>Any functions that directly access a surface's pixel data will need that surface to be lock()'ed. These functions can lock() and unlock() the surfaces themselves without assistance. But, if a function will be called many times, there will be a lot of overhead for multiple locking and unlocking of the surface. It is best to lock the surface manually before making the function call many times, and then unlocking when you are finished. All functions that need a locked surface will say so in their docs. Remember to leave the Surface locked only while necessary. </p>

examples/eventlist.py

         display.flip()
         time.wait(10)
 
-    pygame.quit()
+    quit()
 
 
 if __name__ == '__main__':
 import os, sys
-import MacOS
+
+try:
+    import MacOS
+except:
+    MacOS = None
+
 from pygame.pkgdata import getResource
 
 from pygame import sdlmain_osx
 def Video_AutoInit():
     """This is a function that's called from the c extension code
        just before the display module is initialized"""
-    if not MacOS.WMAvailable():
+    if MacOS and not MacOS.WMAvailable():
         if not sdlmain_osx.WMEnable():
             raise ImportError("Can not access the window manager.  Use py2app or execute with the pythonw script.")
     if not sdlmain_osx.RunningFromBundleWithNSApplication():
     except ImportError:
         import winreg as _winreg
 
-    if os.environ.has_key('WINDIR'):
+    if 'WINDIR' in os.environ:
         windir = os.environ['WINDIR']
-    elif os.environ.has_key('windir'):
+    elif 'windir' in os.environ:
         windir = os.environ['windir']
     else:
         windir = "C:\\Windows\\"
 releases. (hmm, until we get to versions > 10)
 """
 
-ver =   '1.9.0rc2'
+ver =   '1.9.0rc4'
 vernum = 1,9,0
 <font size=+5><b>Pygame Readme</b></font>
 </td></tr><tr><td align=left width=33%><big>
 
-Version 1.9.0rc2
+Version 1.9.0rc4
 
 
 </td><td align=center width=34%><big>
    Eyal Lotem, Regis Desgroppes, Emmanuel Hainry, Randy Kaelber
    Matthew L Daniel, Nirav Patel, Forrest Voight, Charlie Nolan, 
    Frankie Robertson, John Krukoff, Lorenz Quack, Nick Irvine,
-   Michael George, Saul Spatz, Thomas Ibbotson, Tom Rothamel.</li>
+   Michael George, Saul Spatz, Thomas Ibbotson, Tom Rothamel, Evan Kroske,
+   Cambell Barton.</li>
 
 <li>And our bug hunters above and beyond:
     Angus, Guillaume Proux, Frank Raiser,
 
 
 
-<p><big><b><u>Todo / Ideas</u></b></big> (feel free to submit)<br><ul>
-<li>transform.skew() function</li>
-<li>transform.scroll() function</li>
-<li>image filtering (colors,blurs,etc)</li>
-<li>quake-like console with python interpreter</li>
-<li>game lobby. client, simple server, and protocol</li>
-<li>surfarrays should be able to do RGBA along with RGB</li>
-<li>draw with transparancy</li>
-<li>draw large sets of primitives with a single call</li>
-<li>drawing offsets, perhaps as subsurfaces</li>
-<li>new scale2x, scale3x, and scale4x from hiend3d</li>
-<li>switch Numeric to numarray (see docs on how to do both)</li>
-<li>audio resampling</li>
-</ul></p><br>
+<p><big><b><u>Todo / Ideas</u></b></big> (feel free to submit)<br>
+<a href="http://www.pygame.org/wiki/todo/">http://www.pygame.org/wiki/todo/</a>
+</p><br>
 
 
 
 
    Pygame Readme
-   Version 1.9.0rc2 Python Game Development
+   Version 1.9.0rc4 Python Game Development
    Originally by Pete Shinners, now an open source community project.
    http://www.pygame.org
    pygame@seul.org
    Eyal Lotem, Regis Desgroppes, Emmanuel Hainry, Randy Kaelber
    Matthew L Daniel, Nirav Patel, Forrest Voight, Charlie Nolan, 
    Frankie Robertson, John Krukoff, Lorenz Quack, Nick Irvine,
-   Michael George, Saul Spatz, Thomas Ibbotson, Tom Rothamel.
+   Michael George, Saul Spatz, Thomas Ibbotson, Tom Rothamel, Evan Kroske,
+   Cambell Barton.
 
      And our bug hunters above and beyond: Angus, Guillaume Proux, Frank
    Raiser, Austin Henry, Kaweh Kazemi, Arturo Aldama, Mike Mulcheck, 
 
 METADATA = {
     "name":             "pygame",
-    "version":          "1.9.0rc2",
+    "version":          "1.9.0rc4",
     "license":          "LGPL",
     "url":              "http://www.pygame.org",
     "author":           "Pete Shinners, Rene Dudfield, Marcus von Appen, Bob Pendleton, others...",
 static int
 UintFromObj (PyObject* obj, Uint32* val)
 {
-    PyObject* intobj;
+    PyObject* longobj;
 
     if (PyNumber_Check (obj))
     {
-        if (!(intobj = PyNumber_Int (obj)))
+        if (!(longobj = PyNumber_Long (obj)))
             return 0;
-        *val = (Uint32) PyInt_AsLong (intobj);
-        Py_DECREF (intobj);
+        *val = (Uint32) PyLong_AsUnsignedLong (longobj);
+        Py_DECREF (longobj);
         return 1;
     }
     return 0;
 }
 
-static Uint32
+static int
 UintFromObjIndex (PyObject* obj, int _index, Uint32* val)
 {
     int result = 0;
 static Py_ssize_t _color_length (PyColor *color);
 static PyObject* _color_item (PyColor *color, Py_ssize_t _index);
 static int _color_ass_item (PyColor *color, Py_ssize_t _index, PyObject *value);
-
 static PyObject * _color_slice(register PyColor *a, 
                                register Py_ssize_t ilow, 
                                register Py_ssize_t ihigh);
 
+/* Mapping protocol methods. */
+static PyObject * _color_subscript(PyColor* self, PyObject* item);
+
 
 /* Comparison */
 static PyObject* _color_richcompare(PyObject *o1, PyObject *o2, int opid);
     NULL,                              /* sq_inplace_repeat */
 };
 
+
+
+static PyMappingMethods _color_as_mapping = {
+        (lenfunc) _color_length,
+        (binaryfunc)_color_subscript,
+        NULL
+};
+
+
+
+
+
+
+
 #define DEFERRED_ADDRESS(ADDR) 0
 
 static PyTypeObject PyColor_Type =
     (reprfunc) _color_repr,     /* tp_repr */
     &_color_as_number,          /* tp_as_number */
     &_color_as_sequence,        /* tp_as_sequence */
-    0,                          /* tp_as_mapping */
+#if PY_VERSION_HEX < 0x02050000
+    0,
+#else
+    &_color_as_mapping,          /* tp_as_mapping */
+#endif
     0,                          /* tp_hash */
     0,                          /* tp_call */
     0,                          /* tp_str */
     }
 }
 
+
+
+
+
+
+
+static PyObject * _color_subscript(PyColor* self, PyObject* item) {
+
+
+#if PY_VERSION_HEX < 0x02050000
+    if (PyInt_Check(item)) {
+        Py_ssize_t i;
+        i = 0;
+#else
+    if (PyIndex_Check(item)) {
+        Py_ssize_t i;
+        i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+#endif
+
+        if (i == -1 && PyErr_Occurred())
+            return NULL;
+        /*
+        if (i < 0)
+            i += PyList_GET_SIZE(self);
+        */
+        return _color_item(self, i);
+    }
+    if (PySlice_Check(item)) {
+        int len= 4;
+        Py_ssize_t start, stop, step, slicelength;
+
+        if (PySlice_GetIndicesEx((PySliceObject*)item, len, &start, &stop, &step, &slicelength) < 0)
+            return NULL;
+
+        if (slicelength <= 0) {
+            return PyTuple_New(0);
+        }
+        else if (step == 1) {
+            return _color_slice(self, start, stop);
+        }
+        else {
+            PyErr_SetString(PyExc_TypeError, "slice steps not supported");
+            return NULL;
+        }
+    }
+    else {
+        PyErr_Format(PyExc_TypeError,
+                     "Color indices must be integers, not %.200s",
+                     item->ob_type->tp_name);
+        return NULL;
+    }
+}
+
+
+
+
+
 /**
  * color[x] = y
  */
 /*scary #ifdef's match SDL_syswm.h*/
 #if (defined(unix) || defined(__unix__) ||              \
      defined(_AIX) || defined(__OpenBSD__)) &&          \
-    (!defined(DISABLE_X11) && !defined(__CYGWIN32__) && \
+    (defined(SDL_VIDEO_DRIVER_X11) && !defined(__CYGWIN32__) && \
      !defined(ENABLE_NANOX) && !defined(__QNXNTO__))
 
     tmp = PyInt_FromLong (info.info.x11.window);
          */
 #if (defined(unix) || defined(__unix__) || defined(_AIX)        \
      || defined(__OpenBSD__)) &&                                \
-    (!defined(DISABLE_X11) && !defined(__CYGWIN32__) &&         \
+    (defined(SDL_VIDEO_DRIVER_X11) && !defined(__CYGWIN32__) &&         \
      !defined(ENABLE_NANOX) && !defined(__QNXNTO__))
 
         //printf("asdf :%d:", event->syswm.msg->event.xevent.type);
 #define PYGAME_SDLGFXPRIM_INTERNAL
 
 #include "pygame.h"
+#include "pygamedocs.h"
 #include "surface.h"
 #include "pgcompat.h"
 #include "SDL_gfx/SDL_gfxPrimitives.h"
 static PyObject* _gfx_beziercolor (PyObject *self, PyObject* args);
 
 static PyMethodDef _gfxdraw_methods[] = {
-    { "pixel", _gfx_pixelcolor, METH_VARARGS, "" },
-    { "hline", _gfx_hlinecolor, METH_VARARGS, "" },
-    { "vline", _gfx_vlinecolor, METH_VARARGS, "" },
-    { "rectangle", _gfx_rectanglecolor, METH_VARARGS, "" },
-    { "box", _gfx_boxcolor, METH_VARARGS, "" },
-    { "line", _gfx_linecolor, METH_VARARGS, "" },
-    { "arc", _gfx_arccolor, METH_VARARGS, "" },
-    { "circle", _gfx_circlecolor, METH_VARARGS, "" },
-    { "aacircle", _gfx_aacirclecolor, METH_VARARGS, "" },
-    { "filled_circle", _gfx_filledcirclecolor, METH_VARARGS, "" },
-    { "ellipse", _gfx_ellipsecolor, METH_VARARGS, "" },
-    { "aaellipse", _gfx_aaellipsecolor, METH_VARARGS, "" },
-    { "filled_ellipse", _gfx_filledellipsecolor, METH_VARARGS, "" },
-    { "pie", _gfx_piecolor, METH_VARARGS, "" },
-    { "trigon", _gfx_trigoncolor, METH_VARARGS, "" },
-    { "aatrigon", _gfx_aatrigoncolor, METH_VARARGS, "" },
-    { "filled_trigon", _gfx_filledtrigoncolor, METH_VARARGS, "" },
-    { "polygon", _gfx_polygoncolor, METH_VARARGS, "" },
-    { "aapolygon", _gfx_aapolygoncolor, METH_VARARGS, "" },
-    { "filled_polygon", _gfx_filledpolygoncolor, METH_VARARGS, "" },
-    { "textured_polygon", _gfx_texturedpolygon, METH_VARARGS, "" },
-    { "bezier", _gfx_beziercolor, METH_VARARGS, "" },
+    { "pixel", _gfx_pixelcolor, METH_VARARGS, DOC_PYGAMEGFXDRAWPIXEL },
+    { "hline", _gfx_hlinecolor, METH_VARARGS, DOC_PYGAMEGFXDRAWHLINE },
+    { "vline", _gfx_vlinecolor, METH_VARARGS, DOC_PYGAMEGFXDRAWVLINE },
+    { "rectangle", _gfx_rectanglecolor, METH_VARARGS, DOC_PYGAMEGFXDRAWRECTANGLE },
+    { "box", _gfx_boxcolor, METH_VARARGS, DOC_PYGAMEGFXDRAWRECTANGLE },
+    { "line", _gfx_linecolor, METH_VARARGS, DOC_PYGAMEGFXDRAWLINE },
+    { "circle", _gfx_circlecolor, METH_VARARGS, DOC_PYGAMEGFXDRAWCIRCLE },
+    { "arc", _gfx_arccolor, METH_VARARGS, DOC_PYGAMEGFXDRAWARC },
+    { "aacircle", _gfx_aacirclecolor, METH_VARARGS, DOC_PYGAMEGFXDRAWAACIRCLE },
+    { "filled_circle", _gfx_filledcirclecolor, METH_VARARGS, DOC_PYGAMEGFXDRAWFILLEDCIRCLE },
+    { "ellipse", _gfx_ellipsecolor, METH_VARARGS, DOC_PYGAMEGFXDRAWELLIPSE },
+    { "aaellipse", _gfx_aaellipsecolor, METH_VARARGS, DOC_PYGAMEGFXDRAWAAELLIPSE },
+    { "filled_ellipse", _gfx_filledellipsecolor, METH_VARARGS, DOC_PYGAMEGFXDRAWFILLEDELLIPSE },
+    { "pie", _gfx_piecolor, METH_VARARGS, DOC_PYGAMEGFXDRAWPIE },
+    { "trigon", _gfx_trigoncolor, METH_VARARGS, DOC_PYGAMEGFXDRAWTRIGON },
+    { "aatrigon", _gfx_aatrigoncolor, METH_VARARGS, DOC_PYGAMEGFXDRAWAATRIGON },
+    { "filled_trigon", _gfx_filledtrigoncolor, METH_VARARGS, DOC_PYGAMEGFXDRAWFILLEDTRIGON },
+    { "polygon", _gfx_polygoncolor, METH_VARARGS, DOC_PYGAMEGFXDRAWPOLYGON },
+    { "aapolygon", _gfx_aapolygoncolor, METH_VARARGS, DOC_PYGAMEGFXDRAWAAPOLYGON },
+    { "filled_polygon", _gfx_filledpolygoncolor, METH_VARARGS, DOC_PYGAMEGFXDRAWFILLEDPOLYGON },
+    { "textured_polygon", _gfx_texturedpolygon, METH_VARARGS, DOC_PYGAMEGFXDRAWTEXTUREDPOLYGON },
+    { "bezier", _gfx_beziercolor, METH_VARARGS, DOC_PYGAMEGFXDRAWBEZIER },
     { NULL, NULL, 0, NULL },
 };
 
 #if PY3
     static struct PyModuleDef _module = {
         PyModuleDef_HEAD_INIT,
-        "gfxdraw",
-        "",
+        MODPREFIX "gfxdraw",
+        DOC_PYGAMEGFXDRAW,
         -1,
         _gfxdraw_methods,
         NULL, NULL, NULL, NULL
 #if PY3
     module = PyModule_Create (&_module);
 #else
-    module = Py_InitModule3 (MODPREFIX "gfxdraw", _gfxdraw_methods, "");
+    module = Py_InitModule3 (MODPREFIX "gfxdraw", _gfxdraw_methods, DOC_PYGAMEGFXDRAW);
 #endif
 
     MODINIT_RETURN (module);
 static PyObject* _scrap_set_mode (PyObject* self, PyObject* args);
 
 /* Determine what type of clipboard we are using */
-#if defined(__unix__) && !defined(DISABLE_X11)
+#if defined(__unix__) && defined(SDL_VIDEO_DRIVER_X11)
 /*!defined(__QNXNTO__) &&*/
     #define X11_SCRAP
     #include <time.h> /* Needed for clipboard timeouts. */

src/sdlmain_osx.m

 /* Mac OS X functions to accommodate the fact SDLMain.m is not included */
 
 #include "pygame.h"
+
 #include <Carbon/Carbon.h>
 #include <Foundation/Foundation.h>
 #include <AppKit/NSApplication.h>
 #include <Foundation/NSData.h>
 #include <AppKit/NSImage.h>
 
+#include "pgcompat.h"
+
 struct CPSProcessSerNum
 {
 	UInt32 lo;
     { NULL, NULL, 0, NULL}
 };
 
-PYGAME_EXPORT
-void initsdlmain_osx (void)
+
+
+MODINIT_DEFINE (sdlmain_osx)
 {
-    PyObject *mod;
+    PyObject *module;
 
     /* create the module */
-    mod = Py_InitModule3 ("sdlmain_osx", macosx_builtins, NULL);
+
+#if PY3
+    static struct PyModuleDef _module = {
+        PyModuleDef_HEAD_INIT,
+        MODPREFIX "sdlmain_osx",
+        NULL,
+        -1,
+        macosx_builtins,
+        NULL, NULL, NULL, NULL
+    };
+#endif
+
+
+#if PY3
+    module = PyModule_Create (&_module);
+#else
+    module = Py_InitModule3 (MODPREFIX "sdlmain_osx", macosx_builtins, NULL);
+#endif
+
 
     /*imported needed apis*/
     import_pygame_base ();
+    if (PyErr_Occurred ()) {
+        MODINIT_ERROR;
+    }
+
+
+    MODINIT_RETURN (module);
 }
 
     if (!surf)
         return RAISE (PyExc_SDLError, "display Surface quit");
-    return Py_BuildValue ("(iiii)", surf->format->Rmask, surf->format->Gmask,
+    return Py_BuildValue ("(IIII)", surf->format->Rmask, surf->format->Gmask,
                           surf->format->Bmask, surf->format->Amask);
 }
 
 
 Surfaces can have many extra attributes like alpha planes, colorkeys, source
 rectangle clipping. These functions mainly effect how the Surface is blitted
-to other Surfaces. The blit routines will attempt to use hardware acceleratio
- when possible, otherwise will use highly optimized software blitting methods.
+to other Surfaces. The blit routines will attempt to use hardware acceleration
+when possible, otherwise they will use highly optimized software blitting
+methods.
 
 There are three types of transparency supported in Pygame: colorkeys, 
 surface alphas, and pixel alphas. Surface alphas can be mixed with colorkeys,

symbian/app/launcher/pygame_launcher.py

 
 THISDIR = os.path.dirname(__file__)
 
+def make_surface(rect, flags=0, depth=16):
+    return pygame.Surface(rect, flags, depth)
+
 def load_image(name, colorkey=None):
     """ Image loading utility from chimp.py """
     fullname = os.path.join(THISDIR, name)
     def tweenEaseInBack(self, t, b, c, d, s=1.7158):
         t /= d
         return c * (t) * t * ((s + 1) * t - s) + b;
-
+    
+    def easeNone(self, t, b, c, d, s=1.7158):
+        v = c*t/d + b;
+        return v
+        
     def _slide_and_replace(self, direction, surf, surfold, surfnew, v):
         
         r = surf.get_rect()
         """
         This creates an effect where the surface is scaled and moved 
         so that it looks like the surface moves to the distance.
+        
+        @param surf: The surface containing the result of the effect.
+        @param surfold: The surface to be zoomed.
+        @param surfnew: The next surface acting as a background.
+        @param v: The tween value. Position of the animation.
         """
         
         r = surf.get_rect()
         
-        w = int(r.width * (1 - v))
-        h = int(r.height * (1 - v))
+        # Define size of the scaling
+        w, h = int(r.width * (1 - v)), int(r.height * (1 - v))
+        x, y = int(r.width / 2 * (v)), int(r.height / 2 * (v))
         
-        s = pygame.transform.scale(surfold, (w, h))
+        _x = max(0,x)
+        _y = max(0,y)
+        _w = min(r.width,w)
+        _h = min(r.height,h)
+        target_subsurf = surf.subsurface((_x, _y, _w, _h))
         
+        # Scale full or only partial if scaling larger
+        use_subsurf = (v < 0)
+        if use_subsurf:
+            # Full size - exceeding size and scale that instead of full surface
+            if w > r.width:
+                w -= ( w - r.width ) * 2
+            if h > r.height:
+                h -= ( h - r.height) * 2
+            if x < 0:
+                x *= -1
+            if y < 0:
+                y *= -1
+            
+            source_subsurf = surfold.subsurface( ( x, y, w, h) )
+        else:
+            source_subsurf = surfold
+            
+        # The new surface is the background
         surf.blit(surfnew,(0,0))
-
-        surf.blit(s, (r.width / 2 * (v), r.height / 2 * (v)))        
         
+        s = pygame.transform.scale(source_subsurf, (_w, _h), target_subsurf)
+       
         return surf, 0,0
     
     def do(self, effect_tween, duration):
         now = time.time()
         
         # The animation buffer
-        #surf = pygame.Surface(self.surf1.get_size(), )
+        #surf = make_surface(self.surf1.get_size(), )
         
         while True: 
             t = now - start
         self.sysdata = sysdata
         self.screen = sysdata.screen
         screen_size = self.screen.get_size()
-        self.surface = pygame.Surface(screen_size, )
+        self.surface = make_surface(screen_size, )
 
 class BackgroundTransparent(BackgroundBase):
     
         self.rect = self.surface.get_rect()
         
         #: The logo
-        self.img_logo, r = load_image("logo.jpg")
-        
-        # Position the logo on middle of the screen.
-        c = self.rect.center
-        self.img_pos = [ c[0] - r.w / 2, c[1] - r.h / 2 ]
-        
-        #: Make alpha the same size as the image
-        #self.alpha = pygame.Surface(r.size, )
+        self.img_logo, self.img_size = load_image("logo.jpg")
         
         self.alphaval = 0.
         self.alphaprev = -1
-        self.alphadir = - 1. # per second
+        self.alphadir = - 2. # per second
         
+        self.updateAlphaValue()
+        # Position the logo on middle of the screen.
+        self.draw()
+        
+    def draw(self):
+        c = self.rect.center
+        r = self.img_size
+        self.img_pos = [ c[0] - r.w / 2, c[1] - r.h / 2 ]
+
         self.surface.fill(BLACK)
         self.surface.blit(self.img_logo, self.img_pos)
         self.surface.set_alpha(10)
         
     def updateAlphaValue(self):
         """ Update the visibility of the logo """
-        min = 6.
-        max = 12.
+        min = 12.
+        max = 24.
         
         s = self.sysdata.ticdiff / 1000.
         
         if self.alphaval < min:
             self.alphaval = min
             self.alphadir = - self.alphadir
+            
         return self.alphaval
     
     def update(self):
         self.surface.set_alpha(self.updateAlphaValue())
-        #print a
-        #a = self.alphaval
-        #self.surface.fill(BLACK)
-        #self.surface.blit(self.img_logo, self.img_pos)
-        #self.surface.fill( (a,a,a), None, BLEND_RGB_MULT )
         
 class TextField(pygame.sprite.Sprite):
     """ Handles text rendering and updating when necessary """
         
         psize = self.bg.surface.get_size()
         size = (psize[0], psize[1] - startposy)
-        surf = pygame.Surface(size, )
+        surf = make_surface(size, )
         
         # Create text contents
         DrawUtils.drawRectWithText(surf, size, TITLE_BG, TITLE_STROKE,
                                     textsurf=None)
-        #text = textwrap.dedent(text)
+        
         font = self.sysdata.getFontSmall()
         
         lines = text.split("\n")
         size = (size[0], 40)
 
         # Draw the surrounding rect
-        surf = titlebg = pygame.Surface(size, )
+        surf = titlebg = make_surface(size, )
         DrawUtils.drawRectWithText(surf, size, TITLE_BG, TITLE_STROKE,
                                     textsurf=text, textpos=textpos)
         
     
     def _create_list_bg(self, size):
         
-        surf = pygame.Surface(size, )
+        surf = make_surface(size, )
         DrawUtils.drawRectWithText(surf, size, TITLE_BG, TITLE_STROKE, textsurf=None)
         self.itemsurface = surf
         return surf
         size = (size[0], 40)
 
         # Render the final title surface with combined background and text 
-        surf = pygame.Surface(size, )
+        surf = make_surface(size, )
         DrawUtils.drawRectWithText(surf, size , TITLE_BG, TITLE_STROKE, text, textpos)
         
         # Update data
     def __init__(self):
         
         if sys.platform == "symbian_s60":
-            size = pygame.display.list_modes(16)[0]
-            self.screen = pygame.display.set_mode(size, )
+            modes = pygame.display.list_modes(16)
+            print "Available display modes:", modes
+            size = modes[0]
+            self.screen = pygame.display.set_mode(size, 0, 16)
         else:
-            self.screen = pygame.display.set_mode(DISPLAY_SIZE, 16) 
+            self.screen = pygame.display.set_mode(DISPLAY_SIZE, 0, 16) 
         
         self.sysdata = SystemData()
         self.sysdata.screen = self.screen
         
         self.mainbg = Background(self.sysdata)
-        self.bg = BackgroundTransparent(self.sysdata)
+        self.bg     = BackgroundTransparent(self.sysdata)
+        self.bganim = self.mainbg#BackgroundTransparent(self.sysdata)
         
         items = [("Applications", self.mhApplications, ()),
                  # TODO: Disabled settings for now...
         
         #: Updated by foreground event
         self.is_foreground = True
-        
-    def initialize(self):
-        pass
-    
+         
     def run(self):
-        """ Main application loop """
-        self.initialize()       
-        
+        """ Main application loop """ 
         # From black
-        black = pygame.Surface(self.screen.get_size(), )
-        self.sprites.update()
-        self.screen.blit(self.bg.surface, (0, 0))
+        def anim():
+            self.bganim.surface.fill(BLACK)
+            #black = make_surface(self.screen.get_size())
+            self.sprites.update()
+            self.screen.blit(self.bganim.surface, (0, 0))
             
-        # Start the tween animation
-        e = Effects(self.screen, self.clock, black, self.bg.surface )
-        
-        # Blocks for the duration of the animation
-        e.do( [
-               (e.effectFadeTo, e.tweenEaseOutSine),
-               #(e.effectSlideRightReplace, e.tweenEaseInBack),
-               ], 0.5)
-        
-        self.sysdata.tics = pygame.time.get_ticks()
+            # Start the tween animation
+            e = Effects(self.screen, self.clock, self.bganim.surface, self.bg.surface )
+            
+            # Blocks for the duration of the animation
+            e.do( [
+                   (e.effectFadeTo, e.tweenEaseOutSine),
+                   #(e.effectSlideRightReplace, e.tweenEaseInBack),
+                   ], 0.5)
+            
+            self.sysdata.tics = pygame.time.get_ticks()
+            
+            # Restore alpha
+            self.mainbg.surface.set_alpha(255)
+            self.mainbg.draw()
+        anim()
         
         eventhandler = self.handleEvent
         while self.running:
             self.bg.surface.set_alpha(96) # This creates a nice fade effect for menu items
             self.screen.blit(self.bg.surface, (0, 0))
             
-            
             pygame.display.flip()
             
             if self.is_foreground:
         
         if app_path is None:
             # Restore pygame launcher menu
-            
             self.__handle_transition_animation(self.focused, self._main_menu, effect=1)
             
             self.focused.clear()
             return
         
         # Start the tween animation
-        blacksurf = pygame.Surface(self.screen.get_size(), )
-        blacksurf.fill(BLACK)
-        e = Effects(self.screen, self.clock, self.focused.bg.surface, blacksurf,
+        #self.bganim.surface.fill(BLACK)
+        self.bganim.surface.set_alpha(255)
+        self.bg.surface.set_alpha(96)
+        e = Effects(self.screen, self.clock, self.focused.bg.surface, self.bganim.surface,
                     render_callback=None)
 
         # Blocks for the duration of the animation
-        effect = e.effectZoomOut
-        e.do((effect, e.tweenEaseInBack), 0.75)
+        effect =  [
+           (e.effectZoomOut, e.tweenEaseInBack),
+        ]
+        
+        e.do(effect, 0.5)
+        
+        # Fade the logo
+        self.bg.surface.fill(BLACK)
+        e = Effects(self.screen, self.clock, self.bganim.surface, self.bg.surface )
+        
+        # Blocks for the duration of the animation
+        e.do( [
+               (e.effectFadeTo, e.easeNone),
+               ], 0.5)
         
         # Remove so it won't flash at the end
         self.sprites.remove(self.focused)
         self.running = 0
     
     def __handle_transition_animation(self, menu1, menu2, effect):
-        bg1 = BackgroundTransparent(self.sysdata)
-        bg2 = BackgroundTransparent(self.sysdata)
-        menu1.bg = bg1
-        menu2.bg = bg2
         
-        def render_callback(surf): 
-            menu1.update()
-            menu2.update()
+        # We use the mainbg as temporary buffer during animation
+        self.mainbg.surface.set_alpha(255)
         
+        menu2.bg = self.bganim
+        menu1.update()
+        menu2.update()
+        
+        bg1 = menu1.bg
+        bg2 = menu2.bg
+        
+        # This makes the logo appear from behind
+        bg2.surface.set_alpha(96)
+        
+        #def render_callback(s):
+            # Make the logo appear on both
+            #menu2.bg.surface.fill(WHITE)
         # Start the tween animation
-        e = Effects(self.screen, self.clock, bg1.surface, bg2.surface,
-                    render_callback=render_callback)
+        e = Effects(self.screen, self.clock, bg1.surface, bg2.surface)#, render_callback)
         
         # Blocks for the duration of the animation
         effect = [e.effectSlideLeftReplace, e.effectSlideRightReplace, e.effectFadeTo][effect]
         menu2.bg = self.bg
         menu2.update()
         
-        bg1.surface.blit(bg2.surface, (0, 0))
+        # Restore the background logo
+        self.mainbg.draw()
         
     def mhApplications(self):
         """ Menu handler for 'Applications' item """
         self.sprites.remove(self.focused)
         
         # Create tween effect for transition
-        background = Background(self.sysdata)
-        
+        background = self.bganim
         menu = Menu(background, self.sysdata,
                         title="Applications",
                         items=items,
                         cancel_callback=(self.mhLaunchApplication, (None,)),
                         )
-        menu.textcache.max_size = 24
+        menu.textcache.max_size = 12
         menu.update()
+        
         self.__handle_transition_animation(self.focused, menu, effect=0)
         
         self.focused = menu
         """ Menu handler for exit item """
         self.running = 0
         
-        # Fade to black
-        black = pygame.Surface(self.screen.get_size(), )
-        
+        # Fade to logo and then to black
         # Start the tween animation
-        e = Effects(self.screen, self.clock, self.bg.surface, black )
+        e = Effects(self.screen, self.clock, self.bg.surface, self.bganim.surface )
         
         # Blocks for the duration of the animation
         e.do( [
-               (e.effectFadeTo, e.tweenEaseOutSine),
-               (e.effectZoomOut, lambda t, b, c, d, s=3.70158:e.tweenEaseInBack(t,0,0.5,d,s)),
+               (e.effectFadeTo, e.easeNone),
+               ], 0.5)
+        
+        self.bg.surface.fill(BLACK)
+        e = Effects(self.screen, self.clock, self.bganim.surface, self.bg.surface )
+        
+        # Blocks for the duration of the animation
+        e.do( [
+               (e.effectFadeTo, e.easeNone),
                ], 0.5)
         
         self.focused = None
         """ Menu handler for settings item """
         
         self.sprites.remove(self.focused)
-        tf = TextField(self.bg, self.sysdata,
+        tf = TextField(self.bganim, self.sysdata,
                         exit_callback=self._exit_to_main,
                         title="Settings",
                         text="Begone! Nothing to see here!",
         
     def _exit_to_main(self):
         """ Callback to exit back to main menu """
-        
         self.__handle_transition_animation(self.focused, self._main_menu, effect=1)
         
         self.sprites.remove(self.focused)
         """
         
         self.sprites.remove(self.focused)
-        self.focused = TextField(self.bg.surface, self.sysdata,
+        self.focused = TextField(self.bganim, self.sysdata,
                         exit_callback=self._exit_to_main,
                         title="About",
                         text=text,
 def start():
     """ Start pygame launcher """
          
-    pygame.init() 
+    pygame.display.init()
+    pygame.font.init() 
     while True:
         
         # Don't handle events given for launched application

test/color_test.py

         self.assertEquals(pygame.color.Color('red'), pygame.color.Color(' r e d '))
 
     def test_slice(self):
-        """|tags: python3_ignore|"""
+        #"""|tags: python3_ignore|"""
+
         # slicing a color gives you back a tuple.
         # do all sorts of slice combinations.
         c = pygame.Color(1,2,3,4)

test/midi_test.py

           # returns (interf, name, input, output, opened)
           # pygame.midi.get_device_info(an_id): return (interf, name, input,
           # output, opened)
-          # 
-          # 
+          #
+          #
           # If the id is out of range, the function returns None.
 
         an_id = pygame.midi.get_default_output_id()
             self.assertEqual(opened, 0)
 
 
-        an_in_id = pygame.midi.get_default_input_id() 
-        if an_id != -1:
+        an_in_id = pygame.midi.get_default_input_id()
+        if an_in_id != -1:
+            r = pygame.midi.get_device_info(an_in_id)
+            # if r is None, it means that the id is out of range.
             try:
-                r = pygame.midi.get_device_info(an_in_id)
                 interf, name, input, output, opened = r
             except TypeError:
                 raise Exception(repr(r))

test/surface_test.py

 
 def intify(i):
     """If i is a long, cast to an int while preserving the bits"""
-    if 0x10000000 & i:
-        return int(~(0xFFFFFFFF ^ i))
+    if 0x80000000 & i:
+        return int((0xFFFFFFFF & i))
     return i
 
 def longify(i):
-    """If i in an int, cast to a long while preserving the bits"""
+    """If i is an int, cast to a long while preserving the bits"""
     if i < 0:
         return 0xFFFFFFFF & i
     return long(i)
         if surf2.get_bitsize() == 32:
             self.assertEqual(surf2.get_flags() & SRCALPHA, SRCALPHA)
 
-    def test_flags(self):
+    def test_masks(self):
         def make_surf(bpp, flags, masks):
             pygame.Surface((10, 10), flags, bpp, masks)
         # With some masks SDL_CreateRGBSurface does not work properly.
         masks = (0xFF000000, 0xFF0000, 0xFF00, 0)
-        self.failUnlessRaises(ValueError, make_surf, 32, 0, masks)
+        self.assertEqual(make_surf(32, 0, masks), None)
         # For 24 and 32 bit surfaces Pygame assumes no losses.
         masks = (0x7F0000, 0xFF00, 0xFF, 0)
         self.failUnlessRaises(ValueError, make_surf, 24, 0, masks)

test/test_utils/__init__.py

 
     """
     clock_wise_from_top_left = (
-      ((l,       rect.top) for l in xrange_(rect.left,      rect.right)      ),
-      ((rect.right -1,  t) for t in xrange_(rect.top   + 1, rect.bottom)     ),
-      ((l, rect.bottom -1) for l in xrange_(rect.right  -2, rect.left -1, -1)), 
-      ((rect.left,      t) for t in xrange_(rect.bottom -2, rect.top,     -1))
+      [(l,       rect.top) for l in xrange_(rect.left,      rect.right)      ],
+      [(rect.right -1,  t) for t in xrange_(rect.top   + 1, rect.bottom)     ],
+      [(l, rect.bottom -1) for l in xrange_(rect.right  -2, rect.left -1, -1)], 
+      [(rect.left,      t) for t in xrange_(rect.bottom -2, rect.top,     -1)]
     )
     
     for line in clock_wise_from_top_left:

test/test_utils/async_sub.py

     return sys.exc_info()[1]
 
 if subprocess.mswindows:
+    if sys.version_info >= (3,):
+        # Test date should be in ascii.
+        def encode(s):
+            return s.encode('ascii')
+        
+        def decode(b):
+            return b.decode('ascii')
+    else:
+        # Strings only; do nothing
+        def encode(s):
+            return s
+        
+        def decode(b):
+            return b
+        
     try:
         import ctypes
         from ctypes.wintypes import DWORD
         TerminateProcess = ctypes.windll.kernel32.TerminateProcess
         def WriteFile(handle, data, ol = None):
             c_written = DWORD()
-            success = ctypes.windll.kernel32.WriteFile(handle, ctypes.create_string_buffer(data), len(data), ctypes.byref(c_written), ol)
+            success = ctypes.windll.kernel32.WriteFile(handle, ctypes.create_string_buffer(encode(data)), len(data), ctypes.byref(c_written), ol)
             return ctypes.windll.kernel32.GetLastError(), c_written.value
         def ReadFile(handle, desired_bytes, ol = None):
             c_read = DWORD()
             buffer = ctypes.create_string_buffer(desired_bytes+1)
             success = ctypes.windll.kernel32.ReadFile(handle, buffer, desired_bytes, ctypes.byref(c_read), ol)
             buffer[c_read.value] = '\0'
-            return ctypes.windll.kernel32.GetLastError(), buffer.value
+            return ctypes.windll.kernel32.GetLastError(), decode(buffer.value)
         def PeekNamedPipe(handle, desired_bytes):
             c_avail = DWORD()
             c_message = DWORD()
                 buffer = ctypes.create_string_buffer(desired_bytes+1)
                 success = ctypes.windll.kernel32.PeekNamedPipe(handle, buffer, desired_bytes, ctypes.byref(c_read), ctypes.byref(c_avail), ctypes.byref(c_message))
                 buffer[c_read.value] = '\0'
-                return buffer.value, c_avail.value, c_message.value
+                return decode(buffer.value), c_avail.value, c_message.value
             else:
                 success = ctypes.windll.kernel32.PeekNamedPipe(handle, None, desired_bytes, None, ctypes.byref(c_avail), ctypes.byref(c_message))
                 return "", c_avail.value, c_message.value
             if self.universal_newlines:
                 # Translate newlines. For Python 3.x assume read is text.
                 # If bytes then another solution is needed.
-##                read = self._translate_newlines(read)
                 read = read.replace("\r\n", "\n").replace("\r", "\n")
             return read
 

test/test_utils/run_tests.py

 import sys
 import os
 import re
-import subprocess
 import time
 import optparse
 import random

test/test_utils/test_runner.py

 # For combined results, plural
 def test_failures(results):
     errors = {}
-    total =  sum(v.get('num_tests', 0) for v in results.values())
+    total =  sum([v.get('num_tests', 0) for v in results.values()])
     for module, result in results.items():
         num_errors = (
             len(result.get('failures', [])) + len(result.get('errors', []))
 
 def from_namespace(ns, template):
     if isinstance(template, dict):
-        return dict((i, ns.get(i, template[i])) for i in template)
-    return dict((i, ns[i]) for i in template)
+        return dict([(i, ns.get(i, template[i])) for i in template])
+    return dict([(i, ns[i]) for i in template])
 
 RESULTS_TEMPLATE = {
     'output'     :  '',

test/test_utils/unittest.py

 __all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
 
 
+
+
+def _sort_using_key(seq, key_func):
+    deco = [ (key_func(word), i, word) for i, word in enumerate(seq) ]
+    deco.sort()
+    new_words = [ word for _, _, word in deco ]
+    return new_words
+
+
 ##############################################################################
 # Backward compatibility
 ##############################################################################
                 if testFnName not in testFnNames:  # handle overridden methods
                     testFnNames.append(testFnName)
         if self.sortTestMethodsUsing:
-            testFnNames.sort(key=CmpToKey(self.sortTestMethodsUsing))
+            #testFnNames.sort(key=CmpToKey(self.sortTestMethodsUsing))
+            testFnNames = _sort_using_key(testFnNames, CmpToKey(self.sortTestMethodsUsing))
         return testFnNames
 
 
 
+
+
 defaultTestLoader = TestLoader()
 
 

test/test_utils/unittest_patch.py

 ################################################################################
 
 def printErrorList(self, flavour, errors):
-    for test, err in ((e[0], e[1]) for e in errors):
+    for test, err in [(e[0], e[1]) for e in errors]:
         self.stream.writeln(self.separator1)
         self.stream.writeln("%s: %s" % (flavour, test))
         self.stream.writeln(self.separator2)
             for tags in (module_tags, class_tags, test_tags):
                 if not tags: continue
         
-                add    = set(t for t in tags if not t.startswith('-'))
-                remove = set(t[1:] for t in tags if t not in add)
+                add    = set([t for t in tags if not t.startswith('-')])
+                remove = set([t[1:] for t in tags if t not in add])
         
                 if add:     combined.update(add)
                 if remove:  combined.difference_update(remove)