Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--NEWS15
-rw-r--r--TurtleArt/sprites.py287
-rw-r--r--TurtleArt/tablock.py15
-rw-r--r--TurtleArt/tacanvas.py476
-rw-r--r--TurtleArt/taconstants.py2
-rw-r--r--TurtleArt/taexporthtml.py22
-rw-r--r--TurtleArt/talogo.py10
-rw-r--r--TurtleArt/taturtle.py6
-rw-r--r--TurtleArt/tautils.py48
-rw-r--r--TurtleArt/tawindow.py123
-rw-r--r--TurtleArtActivity.py14
-rw-r--r--activity/activity.info2
-rw-r--r--pysamples/set_rgb.py7
-rwxr-xr-xturtleart.py26
14 files changed, 608 insertions, 445 deletions
diff --git a/NEWS b/NEWS
index 67881c6..3040c24 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,17 @@
+123
+
+ENHANCEMENTS
+* Using Cairo graphics
+ - antialiasing
+ - rotation of text and images
+ - filled arcs
+
+NOTE
+* For performance reasons, the coordinate grids are now drawn directly
+ onto the turtle canvas. This has two consequences: (1) the grids cannot
+ be erased except by erasing the entire screen; and (2) the turtle can
+ draw on top of the grid.
+
122
ENHANCEMENTS
@@ -26,6 +40,7 @@ ENHANCEMENTS
BUG FIXES
* Fixed type error introduced to arc commands by patch to address #3164
+
118
ENHANCEMENTS
diff --git a/TurtleArt/sprites.py b/TurtleArt/sprites.py
index 8bd3738..a67046f 100644
--- a/TurtleArt/sprites.py
+++ b/TurtleArt/sprites.py
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
#Copyright (c) 2007-8, Playful Invention Company.
-#Copyright (c) 2008-10 Walter Bender
+#Copyright (c) 2008-11 Walter Bender
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
@@ -21,29 +21,23 @@
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.
-"""
+'''
sprites.py is a simple sprites library for managing graphics objects,
-'sprites', on a canvas. It manages multiple sprites with methods such
-as move, hide, set_layer, etc.
+'sprites', on a gtk.DrawingArea. It manages multiple sprites with
+methods such as move, hide, set_layer, etc.
There are two classes:
-class Sprites maintains a collection of sprites.
+class Sprites maintains a collection of sprites
class Sprite manages individual sprites within the collection.
Example usage:
# Import the classes into your program.
from sprites import Sprites Sprite
- # In your expose callback event handler, call refresh
- def _expose_cb(self, win, event):
- self.sprite_list.refresh(event)
- return True
-
- # Create a new sprite collection for a gtk Drawing Area.
- my_drawing_area = gtk.DrawingArea()
- self.sprite_list = Sprites(my_drawing_area)
+ # Create a new sprite collection associated with your widget
+ self.sprite_list = Sprites(widget)
# Create a "pixbuf" (in this example, from SVG).
my_pixbuf = svg_str_to_pixbuf("<svg>...some svg code...</svg>")
@@ -52,7 +46,7 @@ Example usage:
my_sprite = sprites.Sprite(self.sprite_list, x1, y1, my_pixbuf)
# Move the sprite to a new position.
- my_sprite.move_relative((dx, dy))
+ my_sprite.move((x1+dx, y1+dy))
# Create another "pixbuf".
your_pixbuf = svg_str_to_pixbuf("<svg>...some svg code...</svg>")
@@ -68,6 +62,10 @@ Example usage:
# Now put my_sprite on top of your_sprite.
my_sprite.set_layer(300)
+ cr = self.window.cairo_create()
+ # In your activity's do_expose_event, put in a call to redraw_sprites
+ self.sprites.redraw_sprites(event.area, cairo_context)
+
# method for converting SVG to a gtk pixbuf
def svg_str_to_pixbuf(svg_string):
pl = gtk.gdk.PixbufLoader('svg')
@@ -75,46 +73,46 @@ def svg_str_to_pixbuf(svg_string):
pl.close()
pixbuf = pl.get_pixbuf()
return pixbuf
-"""
+
+'''
import pygtk
pygtk.require('2.0')
import gtk
import pango
+import pangocairo
class Sprites:
- """ A class for the list of sprites and everything they share in common """
-
- def __init__(self, canvas, area=None, gc=None):
- """ Initialize an empty array of sprites """
- self.canvas = canvas
- if area == None:
- self.area = self.canvas.window
- self.gc = self.area.new_gc()
- else:
- self.area = area
- self.gc = gc
- self.cm = self.gc.get_colormap()
+ ''' A class for the list of sprites and everything they share in common '''
+
+ def __init__(self, widget):
+ ''' Initialize an empty array of sprites '''
+ self.widget = widget
self.list = []
+ self.cr = None
+
+ def set_cairo_context(self, cr):
+ ''' Cairo context may be set or reset after __init__ '''
+ self.cr = cr
def get_sprite(self, i):
- """ Return a sprint from the array """
+ ''' Return a sprint from the array '''
if i < 0 or i > len(self.list) - 1:
return(None)
else:
return(self.list[i])
def length_of_list(self):
- """ How many sprites are there? """
+ ''' How many sprites are there? '''
return(len(self.list))
def append_to_list(self, spr):
- """ Append a new sprite to the end of the list. """
+ ''' Append a new sprite to the end of the list. '''
self.list.append(spr)
def insert_in_list(self, spr, i):
- """ Insert a sprite at position i. """
+ ''' Insert a sprite at position i. '''
if i < 0:
self.list.insert(0, spr)
elif i > len(self.list) - 1:
@@ -123,43 +121,46 @@ class Sprites:
self.list.insert(i, spr)
def remove_from_list(self, spr):
- """ Remove a sprite from the list. """
+ ''' Remove a sprite from the list. '''
if spr in self.list:
self.list.remove(spr)
- def find_sprite(self, pos, alpha=True):
- """ Search based on (x, y) position. Return the 'top/first' one. """
+ def find_sprite(self, pos):
+ ''' Search based on (x, y) position. Return the 'top/first' one. '''
list = self.list[:]
list.reverse()
for spr in list:
if spr.hit(pos):
- if not alpha or spr.get_pixel(pos)[3] == 255:
- return spr
+ return spr
return None
- def refresh(self, event):
- """ Handle expose event refresh """
- self.redraw_sprites(event.area)
-
- def redraw_sprites(self, area=None):
- """ Redraw the sprites that intersect area. """
+ def redraw_sprites(self, area=None, cr=None):
+ ''' Redraw the sprites that intersect area. '''
+ # I think I need to do this to save Cairo some work
+ if cr is None:
+ cr = self.cr
+ else:
+ self.cr = cr
+ if cr is None:
+ print 'sprites.redraw_sprites: no Cairo context'
+ return
for spr in self.list:
if area == None:
- spr.draw()
+ spr.draw(cr=cr)
else:
intersection = spr.rect.intersect(area)
if intersection.width > 0 or intersection.height > 0:
- spr.draw()
+ spr.draw(cr=cr)
class Sprite:
- """ A class for the individual sprites """
+ ''' A class for the individual sprites '''
def __init__(self, sprites, x, y, image):
- """ Initialize an individual sprite """
+ ''' Initialize an individual sprite '''
self._sprites = sprites
- self.rect = gtk.gdk.Rectangle(int(x), int(y), 0, 0)
self.save_xy = (x, y) # remember initial (x, y) position
+ self.rect = gtk.gdk.Rectangle(int(x), int(y), 0, 0)
self._scale = [12]
self._rescale = [True]
self._horiz_align = ["center"]
@@ -172,16 +173,18 @@ class Sprite:
self.layer = 100
self.labels = []
self.images = []
+ self.surfaces = []
self._dx = [] # image offsets
self._dy = []
+ self.type = None
self.set_image(image)
- if self._sprites is not None:
- self._sprites.append_to_list(self)
+ self._sprites.append_to_list(self)
def set_image(self, image, i=0, dx=0, dy=0):
- """ Add an image to the sprite. """
+ ''' Add an image to the sprite. '''
while len(self.images) < i + 1:
self.images.append(None)
+ self.surfaces.append(None)
self._dx.append(0)
self._dy.append(0)
self.images[i] = image
@@ -201,47 +204,42 @@ class Sprite:
if h + dy > self.rect.height:
self.rect.height = h + dy
- def move(self, pos, visible=True):
- """ Move to new (x, y) position """
- if visible:
- self.inval()
+ def move(self, pos):
+ ''' Move to new (x, y) position '''
+ self.inval()
self.rect.x, self.rect.y = int(pos[0]), int(pos[1])
- if visible:
- self.inval()
+ self.inval()
- def move_relative(self, pos, visible=True):
- """ Move to new (x+dx, y+dy) position """
- if visible:
- self.inval()
+ def move_relative(self, pos):
+ ''' Move to new (x+dx, y+dy) position '''
+ self.inval()
self.rect.x += int(pos[0])
self.rect.y += int(pos[1])
- if visible:
- self.inval()
+ self.inval()
def get_xy(self):
- """ Return current (x, y) position """
+ ''' Return current (x, y) position '''
return (self.rect.x, self.rect.y)
def get_dimensions(self):
- """ Return current size """
+ ''' Return current size '''
return (self.rect.width, self.rect.height)
def get_layer(self):
- """ Return current layer """
+ ''' Return current layer '''
return self.layer
def set_shape(self, image, i=0):
- """ Set the current image associated with the sprite """
+ ''' Set the current image associated with the sprite '''
self.inval()
self.set_image(image, i)
self.inval()
- def set_layer(self, layer):
- """ Set the layer for a sprite """
- if self._sprites is None:
- return
+ def set_layer(self, layer=None):
+ ''' Set the layer for a sprite '''
self._sprites.remove_from_list(self)
- self.layer = layer
+ if layer is not None:
+ self.layer = layer
for i in range(self._sprites.length_of_list()):
if layer < self._sprites.get_sprite(i).layer:
self._sprites.insert_in_list(self, i)
@@ -251,7 +249,7 @@ class Sprite:
self.inval()
def set_label(self, new_label, i=0):
- """ Set the label drawn on the sprite """
+ ''' Set the label drawn on the sprite '''
self._extend_labels_array(i)
if type(new_label) is str or type(new_label) is unicode:
# pango doesn't like nulls
@@ -261,15 +259,15 @@ class Sprite:
self.inval()
def set_margins(self, l=0, t=0, r=0, b=0):
- """ Set the margins for drawing the label """
+ ''' Set the margins for drawing the label '''
self._margins = [l, t, r, b]
def _extend_labels_array(self, i):
- """ Append to the labels attribute list """
+ ''' Append to the labels attribute list '''
if self._fd is None:
self.set_font('Sans')
if self._color is None:
- self._color = self._sprites.cm.alloc_color('black')
+ self._color = (0., 0., 0.)
while len(self.labels) < i + 1:
self.labels.append(" ")
self._scale.append(self._scale[0])
@@ -278,16 +276,27 @@ class Sprite:
self._vert_align.append(self._vert_align[0])
def set_font(self, font):
- """ Set the font for a label """
+ ''' Set the font for a label '''
self._fd = pango.FontDescription(font)
def set_label_color(self, rgb):
- """ Set the font color for a label """
- self._color = self._sprites.cm.alloc_color(rgb)
+ ''' Set the font color for a label '''
+ COLORTABLE = {'black': '#000000', 'white': '#FFFFFF',
+ 'red': '#FF0000', 'yellow': '#FFFF00',
+ 'green': '#00FF00', 'cyan': '#00FFFF',
+ 'blue': '#0000FF', 'purple': '#FF00FF',
+ 'gray': '#808080'}
+ if rgb.lower() in COLORTABLE:
+ rgb = COLORTABLE[rgb.lower()]
+ # Convert from '#RRGGBB' to floats
+ self._color = (int('0x' + rgb[1:3], 16) / 256.,
+ int('0x' + rgb[3:5], 16) / 256.,
+ int('0x' + rgb[5:7], 16) / 256.)
+ return
def set_label_attributes(self, scale, rescale=True, horiz_align="center",
vert_align="middle", i=0):
- """ Set the various label attributes """
+ ''' Set the various label attributes '''
self._extend_labels_array(i)
self._scale[i] = scale
self._rescale[i] = rescale
@@ -295,37 +304,51 @@ class Sprite:
self._vert_align[i] = vert_align
def hide(self):
- """ Hide a sprite """
- if self._sprites is None:
- return
+ ''' Hide a sprite '''
self.inval()
self._sprites.remove_from_list(self)
- def inval(self):
- """ Force a region redraw by gtk """
- if self._sprites is None:
- return
- self._sprites.area.invalidate_rect(self.rect, False)
+ def restore(self):
+ ''' Restore a hidden sprite '''
+ self.set_layer()
- def draw(self):
- """ Draw the sprite (and label) """
- if self._sprites is None:
+ def inval(self):
+ ''' Invalidate a region for gtk '''
+ # self._sprites.window.invalidate_rect(self.rect, False)
+ self._sprites.widget.queue_draw_area(self.rect.x,
+ self.rect.y,
+ self.rect.width,
+ self.rect.height)
+
+ def draw(self, cr=None):
+ ''' Draw the sprite (and label) '''
+ if cr is None:
+ print 'sprite.draw: no Cairo context.'
return
+ # Fix me: Cache cairo surfaces
for i, img in enumerate(self.images):
- if isinstance(img, gtk.gdk.Pixbuf):
- self._sprites.area.draw_pixbuf(self._sprites.gc, img, 0, 0,
- self.rect.x + self._dx[i],
- self.rect.y + self._dy[i])
- elif img is not None:
- self._sprites.area.draw_drawable(self._sprites.gc, img, 0, 0,
- self.rect.x + self._dx[i],
- self.rect.y + self._dy[i],
- -1, -1)
+ if self.surfaces[i] is not None:
+ cr.set_source_surface(self.surfaces[i],
+ self.rect.x + self._dx[i],
+ self.rect.y + self._dy[i])
+ elif isinstance(img, gtk.gdk.Pixbuf):
+ cr.set_source_pixbuf(img,
+ self.rect.x + self._dx[i],
+ self.rect.y + self._dy[i])
+ # self.surfaces[i] = cr.get_target()
+ else:
+ print 'sprite.draw: source not a pixbuf (%s)' % (type(img))
+ cr.rectangle(self.rect.x + self._dx[i],
+ self.rect.y + self._dy[i],
+ self.rect.width,
+ self.rect.height)
+ cr.fill()
+
if len(self.labels) > 0:
- self.draw_label()
+ self.draw_label(cr)
def hit(self, pos):
- """ Is (x, y) on top of the sprite? """
+ ''' Is (x, y) on top of the sprite? '''
x, y = pos
if x < self.rect.x:
return False
@@ -337,16 +360,18 @@ class Sprite:
return False
return True
- def draw_label(self):
- """ Draw the label based on its attributes """
- if self._sprites is None:
- return
+ def draw_label(self, cr):
+ ''' Draw the label based on its attributes '''
+ # Create a pangocairo context
+ cr = pangocairo.CairoContext(cr)
my_width = self.rect.width - self._margins[0] - self._margins[2]
if my_width < 0:
my_width = 0
my_height = self.rect.height - self._margins[1] - self._margins[3]
for i in range(len(self.labels)):
- pl = self._sprites.canvas.create_pango_layout(str(self.labels[i]))
+ pl = cr.create_layout()
+ pl.set_text(str(self.labels[i]))
+ # pl = self._sprites.canvas.create_pango_layout(str(self.labels[i]))
self._fd.set_size(int(self._scale[i] * pango.SCALE))
pl.set_font_description(self._fd)
w = pl.get_size()[0] / pango.SCALE
@@ -359,8 +384,8 @@ class Sprite:
else:
j = len(self.labels[i]) - 1
while(w > my_width and j > 0):
- pl = self._sprites.canvas.create_pango_layout(
- "…" + self.labels[i][len(self.labels[i]) - j:])
+ pl.set_text(
+ "…" + self.labels[i][len(self.labels[i]) - j:])
self._fd.set_size(int(self._scale[i] * pango.SCALE))
pl.set_font_description(self._fd)
w = pl.get_size()[0] / pango.SCALE
@@ -369,44 +394,53 @@ class Sprite:
x = int(self.rect.x + self._margins[0] + (my_width - w) / 2)
elif self._horiz_align[i] == 'left':
x = int(self.rect.x + self._margins[0])
- else: # right
+ else: # right
x = int(self.rect.x + self.rect.width - w - self._margins[2])
h = pl.get_size()[1] / pango.SCALE
if self._vert_align[i] == "middle":
y = int(self.rect.y + self._margins[1] + (my_height - h) / 2)
elif self._vert_align[i] == "top":
y = int(self.rect.y + self._margins[1])
- else: # bottom
+ else: # bottom
y = int(self.rect.y + self.rect.height - h - self._margins[3])
- self._sprites.gc.set_foreground(self._color)
- self._sprites.area.draw_layout(self._sprites.gc, x, y, pl)
+ cr.save()
+ cr.translate(x, y)
+ cr.set_source_rgb(self._color[0], self._color[1], self._color[2])
+ cr.update_layout(pl)
+ cr.show_layout(pl)
+ cr.restore()
def label_width(self):
- """ Calculate the width of a label """
- max = 0
- for i in range(len(self.labels)):
- pl = self._sprites.canvas.create_pango_layout(self.labels[i])
- self._fd.set_size(int(self._scale[i] * pango.SCALE))
- pl.set_font_description(self._fd)
- w = pl.get_size()[0] / pango.SCALE
- if w > max:
- max = w
- return max
+ ''' Calculate the width of a label '''
+ cr = pangocairo.CairoContext(self._sprites.cr)
+ if cr is not None:
+ max = 0
+ for i in range(len(self.labels)):
+ pl = cr.create_layout()
+ pl.set_text(self.labels[i])
+ self._fd.set_size(int(self._scale[i] * pango.SCALE))
+ pl.set_font_description(self._fd)
+ w = pl.get_size()[0] / pango.SCALE
+ if w > max:
+ max = w
+ return max
+ else:
+ return self.rect.width
def label_safe_width(self):
- """ Return maximum width for a label """
+ ''' Return maximum width for a label '''
return self.rect.width - self._margins[0] - self._margins[2]
def label_safe_height(self):
- """ Return maximum height for a label """
+ ''' Return maximum height for a label '''
return self.rect.height - self._margins[1] - self._margins[3]
def label_left_top(self):
- """ Return the upper-left corner of the label safe zone """
+ ''' Return the upper-left corner of the label safe zone '''
return(self._margins[0], self._margins[1])
def get_pixel(self, pos, i=0, mode='888'):
- """ Return the pixel at (x, y) """
+ ''' Return the pixel at (x, y) '''
x, y = pos
x = x - self.rect.x
y = y - self.rect.y
@@ -452,3 +486,4 @@ class Sprite:
g = g << 2
b = b << 3
return(r, g, b, 0)
+
diff --git a/TurtleArt/tablock.py b/TurtleArt/tablock.py
index d2292b1..03ddc05 100644
--- a/TurtleArt/tablock.py
+++ b/TurtleArt/tablock.py
@@ -280,7 +280,7 @@ class Block:
self._set_label_attributes()
self.svg.set_scale(self.scale)
self.refresh()
- self.spr.draw()
+ self.spr.inval()
def refresh(self):
if self.spr is None:
@@ -381,8 +381,9 @@ class Block:
self.width = copy_block.width
self.height = copy_block.height
self.shapes[0] = copy_block.shapes[0]
- self.spr = sprites.Sprite(sprite_list, x, y, self.shapes[0])
- self.spr._margins = copy_block.spr._margins[:]
+ if sprite_list is not None:
+ self.spr = sprites.Sprite(sprite_list, x, y, self.shapes[0])
+ self.spr._margins = copy_block.spr._margins[:]
if len(copy_block.shapes) > 1:
self.shapes[1] = copy_block.shapes[1]
self.docks = copy_block.docks[:]
@@ -414,15 +415,19 @@ class Block:
for i, n in enumerate(block_names[self.name]):
self._set_labels(i, n)
- if copy_block is None:
+ if copy_block is None and self.spr is not None:
if self.spr.label_width() > self.spr.label_safe_width():
self.resize()
def _set_margins(self):
+ if self.spr is None:
+ return
self.spr.set_margins(self.svg.margins[0], self.svg.margins[1],
self.svg.margins[2], self.svg.margins[3])
def _set_label_attributes(self):
+ if self.spr is None:
+ return
if self.name in content_blocks:
n = len(self.values)
if n == 0:
@@ -451,6 +456,8 @@ class Block:
True, 'center', 'middle', i)
def _set_labels(self, i, label):
+ if self.spr is None:
+ return
self.spr.set_label(label, i)
def _make_block(self, svg):
diff --git a/TurtleArt/tacanvas.py b/TurtleArt/tacanvas.py
index 59fcb1c..83f6461 100644
--- a/TurtleArt/tacanvas.py
+++ b/TurtleArt/tacanvas.py
@@ -21,9 +21,10 @@
#THE SOFTWARE.
import gtk
-from math import sin, cos, pi
+from math import sin, cos, atan, pi, sqrt
import pango
import cairo
+import pangocairo
import base64
from gettext import gettext as _
@@ -31,11 +32,11 @@ from sprites import Sprite
from tasprite_factory import SVG
from tautils import image_to_base64, get_path, data_to_string, round_int, \
debug_output
-from taconstants import CANVAS_LAYER, BLACK, WHITE
+from taconstants import BLACK, WHITE
def wrap100(n):
- """ A variant on mod... 101 -> 99; 199 -> 1 """
+ ''' A variant on mod... 101 -> 99; 199 -> 1 '''
n = int(n)
n %= 200
if n > 99:
@@ -43,25 +44,8 @@ def wrap100(n):
return n
-def calc_poly_bounds(poly_points):
- """ Calculate the minx, miny, width, height of polygon """
- minx = poly_points[0][0]
- miny = poly_points[0][1]
- maxx, maxy = minx, miny
- for p in poly_points:
- if p[0] < minx:
- minx = p[0]
- elif p[0] > maxx:
- maxx = p[0]
- if p[1] < miny:
- miny = p[1]
- elif p[1] > maxy:
- maxy = p[1]
- return(minx, miny, maxx - minx, maxy - miny)
-
-
def calc_shade(c, s, invert=False):
- """ Convert a color to the current shade (lightness/darkness). """
+ ''' Convert a color to the current shade (lightness/darkness). '''
# Assumes 16 bit input values
if invert:
if s < 0:
@@ -74,7 +58,7 @@ def calc_shade(c, s, invert=False):
def calc_gray(c, g, invert=False):
- """ Gray is a psuedo saturation calculation. """
+ ''' Gray is a psuedo saturation calculation. '''
# Assumes 16 bit input values
if g == 100:
return c
@@ -90,7 +74,7 @@ def calc_gray(c, g, invert=False):
colors = {}
DEGTOR = 2 * pi / 360
-color_table = (
+COLOR_TABLE = (
0xFF0000, 0xFF0D00, 0xFF1A00, 0xFF2600, 0xFF3300,
0xFF4000, 0xFF4D00, 0xFF5900, 0xFF6600, 0xFF7300,
0xFF8000, 0xFF8C00, 0xFF9900, 0xFFA600, 0xFFB300,
@@ -114,31 +98,24 @@ color_table = (
class TurtleGraphics:
- """ A class for the Turtle graphics canvas """
+ ''' A class for the Turtle graphics canvas '''
def __init__(self, tw, width, height):
- """ Create a sprite to hold the canvas. """
+ ''' Create a sprite to hold the canvas. '''
self.tw = tw
self.width = width
self.height = height
- if self.tw.interactive_mode:
- self.canvas = Sprite(tw.sprite_list, 0, 0,
- gtk.gdk.Pixmap(self.tw.area, self.width * 2,
- self.height * 2, -1))
- else:
- self.canvas = Sprite(None, 0, 0, self.tw.window)
- self.canvas.set_layer(CANVAS_LAYER)
- (self.cx, self.cy) = self.canvas.get_xy()
- self.canvas.type = 'canvas'
- self.gc = self.canvas.images[0].new_gc()
- self.cm = self.gc.get_colormap()
+
+ # Build a cairo.Context from a cairo.XlibSurface
+ self.canvas = cairo.Context(self.tw.turtle_canvas)
+ cr = gtk.gdk.CairoContext(self.canvas)
+ cr.set_line_cap(1) # Set the line cap to be round
+
+ self.cx = 0
+ self.cy = 0
self.fgrgb = [255, 0, 0]
- self.fgcolor = self.cm.alloc_color('red')
self.bgrgb = [255, 248, 222]
- self.bgcolor = self.cm.alloc_color('#fff8de')
self.textsize = 48 # deprecated
- self.textcolor = self.cm.alloc_color('red') # deprecated
- self.tw.active_turtle.show()
self.shade = 0
self.pendown = False
self.xcor = 0
@@ -152,17 +129,16 @@ class TurtleGraphics:
self.svg = SVG()
self.svg.set_fill_color('none')
self.tw.svg_string = ''
- self.clearscreen(False)
def start_fill(self):
- """ Start accumulating points of a polygon to fill. """
+ ''' Start accumulating points of a polygon to fill. '''
self.fill = True
self.poly_points = []
if self.tw.saving_svg:
self.tw.svg_string += '<g>'
def stop_fill(self):
- """ Fill the polygon. """
+ ''' Fill the polygon. '''
self.fill = False
if len(self.poly_points) == 0:
return
@@ -172,7 +148,7 @@ class TurtleGraphics:
for p in self.poly_points:
shared_poly_points.append((self.screen_to_turtle_coordinates(
p[0], p[1])))
- event = "F|%s" % (data_to_string([self._get_my_nick(),
+ event = 'F|%s' % (data_to_string([self._get_my_nick(),
shared_poly_points]))
self.tw.send_event(event)
self.poly_points = []
@@ -180,14 +156,21 @@ class TurtleGraphics:
self.tw.svg_string += '</g>'
def fill_polygon(self, poly_points):
- minx, miny, w, h = calc_poly_bounds(poly_points)
- self.canvas.images[0].draw_polygon(self.gc, True, poly_points)
- self.invalt(minx - self.pensize * self.tw.coord_scale / 2 - 3,
- miny - self.pensize * self.tw.coord_scale / 2 - 3,
- w + self.pensize * self.tw.coord_scale + 6,
- h + self.pensize * self.tw.coord_scale + 6)
+ ''' Draw the polygon... '''
+ self.canvas.new_path()
+ for i, p in enumerate(poly_points):
+ if p[0] == 'move':
+ self.canvas.move_to(p[1], p[2])
+ elif p[0] == 'rarc':
+ self.canvas.arc(p[1], p[2], p[3], p[4], p[5])
+ elif p[0] == 'larc':
+ self.canvas.arc_negative(p[1], p[2], p[3], p[4], p[5])
+ else: # line
+ self.canvas.line_to(p[1], p[2])
+ self.canvas.close_path()
+ self.canvas.fill()
if self.tw.saving_svg and self.pendown:
- self.svg.set_fill_color("#%02x%02x%02x" % (self.fgrgb[0],
+ self.svg.set_fill_color('#%02x%02x%02x' % (self.fgrgb[0],
self.fgrgb[1],
self.fgrgb[2]))
self.tw.svg_string += self.svg.new_path(poly_points[0][0],
@@ -196,20 +179,27 @@ class TurtleGraphics:
if p > 0:
self.tw.svg_string += self.svg.line_to(poly_points[p][0],
poly_points[p][1])
- self.tw.svg_string += "\"\n"
+ self.tw.svg_string += '"\n'
self.tw.svg_string += self.svg.style()
self.svg.set_fill_color('none')
def clearscreen(self, share=True):
- """Clear the canvas and reset most graphics attributes to defaults."""
- rect = gtk.gdk.Rectangle(0, 0, self.width * 2, self.height * 2)
- self.gc.set_foreground(self.bgcolor)
- self.canvas.images[0].draw_rectangle(self.gc, True, *rect)
- self.invalt(0, 0, self.width, self.height)
+ '''Clear the canvas and reset most graphics attributes to defaults.'''
+ self.canvas.move_to(0, 0)
+ self.canvas.set_source_rgb(self.bgrgb[0] / 255.,
+ self.bgrgb[1] / 255.,
+ self.bgrgb[2] / 255.)
+ self.canvas.rectangle(0, 0, self.width * 2, self.height * 2)
+ self.canvas.fill()
+ self.inval()
self.setpensize(5, share)
self.setgray(100, share)
self.setcolor(0, share)
self.setshade(50, share)
+ self.tw.svg_string = ''
+ self.svg.reset_min_max()
+ self.fill = False
+ self.poly_points = []
for turtle_key in iter(self.tw.turtles.dict):
# Don't reset remote turtles
if not self.tw.remote_turtle(turtle_key):
@@ -225,82 +215,82 @@ class TurtleGraphics:
self.setpen(True, share)
self.tw.active_turtle.hide()
self.set_turtle(self.tw.default_turtle_name)
- self.tw.svg_string = ''
- self.svg.reset_min_max()
- self.fill = False
- self.poly_points = []
def forward(self, n, share=True):
- """ Move the turtle forward."""
+ ''' Move the turtle forward.'''
nn = n * self.tw.coord_scale
- self.gc.set_foreground(self.fgcolor)
+ self.canvas.set_source_rgb(self.fgrgb[0] / 255., self.fgrgb[1] / 255.,
+ self.fgrgb[2] / 255.)
oldx, oldy = self.xcor, self.ycor
try:
self.xcor += nn * sin(self.heading * DEGTOR)
self.ycor += nn * cos(self.heading * DEGTOR)
except TypeError, ValueError:
- debug_output("bad value sent to %s" % (__name__),
+ debug_output('bad value sent to %s' % (__name__),
self.tw.running_sugar)
return
if self.pendown:
self.draw_line(oldx, oldy, self.xcor, self.ycor)
+
self.move_turtle()
if self.tw.sharing() and share:
- event = "f|%s" % (data_to_string([self._get_my_nick(), int(n)]))
+ event = 'f|%s' % (data_to_string([self._get_my_nick(), int(n)]))
self.tw.send_event(event)
+ self.inval()
def seth(self, n, share=True):
- """ Set the turtle heading. """
+ ''' Set the turtle heading. '''
try:
self.heading = n
except TypeError, ValueError:
- debug_output("bad value sent to %s" % (__name__),
+ debug_output('bad value sent to %s' % (__name__),
self.tw.running_sugar)
return
self.heading %= 360
self.turn_turtle()
if self.tw.sharing() and share:
- event = "r|%s" % (data_to_string([self._get_my_nick(),
+ event = 'r|%s' % (data_to_string([self._get_my_nick(),
round_int(self.heading)]))
self.tw.send_event(event)
def right(self, n, share=True):
- """ Rotate turtle clockwise """
+ ''' Rotate turtle clockwise '''
try:
self.heading += n
except TypeError, ValueError:
- debug_output("bad value sent to %s" % (__name__),
+ debug_output('bad value sent to %s' % (__name__),
self.tw.running_sugar)
return
self.heading %= 360
self.turn_turtle()
if self.tw.sharing() and share:
- event = "r|%s" % (data_to_string([self._get_my_nick(),
+ event = 'r|%s' % (data_to_string([self._get_my_nick(),
round_int(self.heading)]))
self.tw.send_event(event)
def arc(self, a, r, share=True):
- """ Draw an arc """
- self.gc.set_foreground(self.fgcolor)
- rr = r * self.tw.coord_scale
+ ''' Draw an arc '''
+ self.canvas.set_source_rgb(self.fgrgb[0] / 255., self.fgrgb[1] / 255.,
+ self.fgrgb[2] / 255.)
try:
if a < 0:
- self.larc(-a, rr)
+ self.larc(-a, r)
else:
- self.rarc(a, rr)
+ self.rarc(a, r)
except TypeError, ValueError:
- debug_output("bad value sent to %s" % (__name__),
+ debug_output('bad value sent to %s' % (__name__),
self.tw.running_sugar)
return
self.move_turtle()
if self.tw.sharing() and share:
- event = "a|%s" % (data_to_string([self._get_my_nick(),
+ event = 'a|%s' % (data_to_string([self._get_my_nick(),
[round_int(a), round_int(r)]]))
self.tw.send_event(event)
def rarc(self, a, r):
- """ draw a clockwise arc """
+ ''' draw a clockwise arc '''
+ r *= self.tw.coord_scale
if r < 0:
r = -r
a = -a
@@ -310,17 +300,21 @@ class TurtleGraphics:
oldx, oldy = self.xcor, self.ycor
cx = self.xcor + r * cos(self.heading * DEGTOR)
cy = self.ycor - r * sin(self.heading * DEGTOR)
- x, y = self.turtle_to_screen_coordinates(int(cx - r), int(cy + r))
- w = int(2 * r)
- h = w
if self.pendown:
- self.canvas.images[0].draw_arc(self.gc, False, int(x), int(y), w,
- h, int(180 - self.heading - a) * 64,
- int(a) * 64)
- self.invalt(x - self.pensize * self.tw.coord_scale / 2 - 3,
- y - self.pensize * self.tw.coord_scale / 2 - 3,
- w + self.pensize * self.tw.coord_scale + 6,
- h + self.pensize * self.tw.coord_scale + 6)
+ x, y = self.turtle_to_screen_coordinates(cx, cy)
+ self.canvas.arc(x, y, r,
+ (self.heading - 180) * DEGTOR,
+ (self.heading - 180 + a) * DEGTOR)
+ self.canvas.stroke()
+ self.inval()
+
+ if self.fill:
+ if self.poly_points == []:
+ self.poly_points.append(('move', x, y))
+ self.poly_points.append(('rarc', x, y, r,
+ (self.heading - 180) * DEGTOR,
+ (self.heading - 180 + a) * DEGTOR))
+
self.right(a, False)
self.xcor = cx - r * cos(self.heading * DEGTOR)
self.ycor = cy + r * sin(self.heading * DEGTOR)
@@ -329,11 +323,12 @@ class TurtleGraphics:
self.tw.svg_string += self.svg.new_path(x, y)
x, y = self.turtle_to_screen_coordinates(self.xcor, self.ycor)
self.tw.svg_string += self.svg.arc_to(x, y, r, a, 0, s)
- self.tw.svg_string += "\"\n"
+ self.tw.svg_string += '"\n'
self.tw.svg_string += self.svg.style()
def larc(self, a, r):
- """ draw a counter-clockwise arc """
+ ''' draw a counter-clockwise arc '''
+ r *= self.tw.coord_scale
if r < 0:
r = -r
a = -a
@@ -343,17 +338,21 @@ class TurtleGraphics:
oldx, oldy = self.xcor, self.ycor
cx = self.xcor - r * cos(self.heading * DEGTOR)
cy = self.ycor + r * sin(self.heading * DEGTOR)
- x, y = self.turtle_to_screen_coordinates(int(cx - r), int(cy + r))
- w = int(2 * r)
- h = w
if self.pendown:
- self.canvas.images[0].draw_arc(self.gc, False, int(x), int(y),
- w, h, int(360 - self.heading) * 64,
- int(a) * 64)
- self.invalt(x - self.pensize * self.tw.coord_scale / 2 - 3,
- y - self.pensize * self.tw.coord_scale / 2 - 3,
- w + self.pensize * self.tw.coord_scale + 6,
- h + self.pensize * self.tw.coord_scale + 6)
+ x, y = self.turtle_to_screen_coordinates(cx, cy)
+ self.canvas.arc_negative(x, y, r,
+ (self.heading) * DEGTOR,
+ (self.heading - a) * DEGTOR)
+ self.canvas.stroke()
+ self.inval()
+
+ if self.fill:
+ if self.poly_points == []:
+ self.poly_points.append(('move', x, y))
+ self.poly_points.append(('larc', x, y, r,
+ (self.heading) * DEGTOR,
+ (self.heading - a) * DEGTOR))
+
self.right(-a, False)
self.xcor = cx + r * cos(self.heading * DEGTOR)
self.ycor = cy - r * sin(self.heading * DEGTOR)
@@ -362,71 +361,73 @@ class TurtleGraphics:
self.tw.svg_string += self.svg.new_path(x, y)
x, y = self.turtle_to_screen_coordinates(self.xcor, self.ycor)
self.tw.svg_string += self.svg.arc_to(x, y, r, a, 0, s)
- self.tw.svg_string += "\"\n"
+ self.tw.svg_string += '"\n'
self.tw.svg_string += self.svg.style()
def setxy(self, x, y, share=True, pendown=True):
- """ Move turtle to position x,y """
+ ''' Move turtle to position x,y '''
oldx, oldy = self.xcor, self.ycor
x *= self.tw.coord_scale
y *= self.tw.coord_scale
try:
self.xcor, self.ycor = x, y
except TypeError, ValueError:
- debug_output("bad value sent to %s" % (__name__),
+ debug_output('bad value sent to %s' % (__name__),
self.tw.running_sugar)
return
if self.pendown and pendown:
- self.gc.set_foreground(self.fgcolor)
+ self.canvas.set_source_rgb(self.fgrgb[0] / 255.,
+ self.fgrgb[1] / 255.,
+ self.fgrgb[2] / 255.)
self.draw_line(oldx, oldy, self.xcor, self.ycor)
+ self.inval()
self.move_turtle()
if self.tw.sharing() and share:
- event = "x|%s" % (data_to_string([self._get_my_nick(),
+ event = 'x|%s' % (data_to_string([self._get_my_nick(),
[round_int(x), round_int(y)]]))
self.tw.send_event(event)
def setpensize(self, ps, share=True):
- """ Set the pen size """
+ ''' Set the pen size '''
try:
if ps < 0:
ps = 0
self.pensize = ps
except TypeError, ValueError:
- debug_output("bad value sent to %s" % (__name__),
+ debug_output('bad value sent to %s' % (__name__),
self.tw.running_sugar)
return
self.tw.active_turtle.set_pen_size(ps)
- self.gc.set_line_attributes(int(self.pensize * self.tw.coord_scale),
- gtk.gdk.LINE_SOLID, gtk.gdk.CAP_ROUND, gtk.gdk.JOIN_MITER)
+ self.canvas.set_line_width(ps)
self.svg.set_stroke_width(self.pensize)
if self.tw.sharing() and share:
- event = "w|%s" % (data_to_string([self._get_my_nick(),
+ event = 'w|%s' % (data_to_string([self._get_my_nick(),
round_int(ps)]))
self.tw.send_event(event)
def setcolor(self, c, share=True):
- """ Set the pen color """
+ ''' Set the pen color '''
try:
self.color = c
except TypeError, ValueError:
- debug_output("bad value sent to %s" % (__name__),
+ debug_output('bad value sent to %s' % (__name__),
self.tw.running_sugar)
return
self.tw.active_turtle.set_color(c)
self.set_fgcolor()
if self.tw.sharing() and share:
- event = "c|%s" % (data_to_string([self._get_my_nick(),
+ event = 'c|%s' % (data_to_string([self._get_my_nick(),
round_int(c)]))
self.tw.send_event(event)
def setgray(self, g, share=True):
- """ Set the gray level """
+ ''' Set the gray level '''
try:
self.gray = g
except TypeError, ValueError:
- debug_output("bad value sent to %s" % (__name__),
+ debug_output('bad value sent to %s' % (__name__),
self.tw.running_sugar)
return
if self.gray < 0:
@@ -436,47 +437,53 @@ class TurtleGraphics:
self.set_fgcolor()
self.tw.active_turtle.set_gray(self.gray)
if self.tw.sharing() and share:
- event = "g|%s" % (data_to_string([self._get_my_nick(),
+ event = 'g|%s' % (data_to_string([self._get_my_nick(),
round_int(self.gray)]))
self.tw.send_event(event)
+ def set_textcolor(self):
+ ''' Deprecated: Set the text color to foreground color. '''
+ return
+
def settextcolor(self, c): # deprecated
- """ Set the text color """
+ ''' Set the text color '''
return
def settextsize(self, c): # deprecated
- """ Set the text size """
+ ''' Set the text size '''
try:
self.tw.textsize = c
except TypeError, ValueError:
- debug_output("bad value sent to %s" % (__name__),
+ debug_output('bad value sent to %s' % (__name__),
self.tw.running_sugar)
def setshade(self, s, share=True):
- """ Set the color shade """
+ ''' Set the color shade '''
try:
self.shade = s
except TypeError, ValueError:
- debug_output("bad value sent to %s" % (__name__),
+ debug_output('bad value sent to %s' % (__name__),
self.tw.running_sugar)
return
self.tw.active_turtle.set_shade(s)
self.set_fgcolor()
if self.tw.sharing() and share:
- event = "s|%s" % (data_to_string([self._get_my_nick(),
+ event = 's|%s' % (data_to_string([self._get_my_nick(),
round_int(s)]))
self.tw.send_event(event)
def fillscreen(self, c, s):
- """ Fill screen with color/shade and reset to defaults """
+ ''' Fill screen with color/shade and reset to defaults '''
oldc, olds = self.color, self.shade
self.setcolor(c, False)
self.setshade(s, False)
- rect = gtk.gdk.Rectangle(0, 0, self.width * 2, self.height * 2)
- self.gc.set_foreground(self.fgcolor)
+ self.canvas.set_source_rgb(self.fgrgb[0] / 255.,
+ self.fgrgb[1] / 255.,
+ self.fgrgb[2] / 255.)
self.bgrgb = self.fgrgb[:]
- self.canvas.images[0].draw_rectangle(self.gc, True, *rect)
- self.invalt(0, 0, self.width, self.height)
+ self.canvas.rectangle(0, 0, self.width * 2, self.height * 2)
+ self.canvas.fill()
+ self.inval()
self.setcolor(oldc, False)
self.setshade(olds, False)
self.tw.svg_string = ''
@@ -485,7 +492,7 @@ class TurtleGraphics:
self.poly_points = []
def set_fgcolor(self):
- """ Set the foreground color """
+ ''' Set the foreground color '''
if self.color == WHITE or self.shade == WHITE:
r = 0xFF00
g = 0xFF00
@@ -496,7 +503,7 @@ class TurtleGraphics:
b = 0x0000
else:
sh = (wrap100(self.shade) - 50) / 50.0
- rgb = color_table[wrap100(self.color)]
+ rgb = COLOR_TABLE[wrap100(self.color)]
r = (rgb >> 8) & 0xff00
r = calc_gray(r, self.gray)
r = calc_shade(r, sh)
@@ -507,37 +514,45 @@ class TurtleGraphics:
b = calc_gray(b, self.gray)
b = calc_shade(b, sh)
self.fgrgb = [r >> 8, g >> 8, b >> 8]
- self.fgcolor = self.cm.alloc_color(r, g, b)
- self.svg.set_stroke_color("#%02x%02x%02x" % (self.fgrgb[0],
+ self.svg.set_stroke_color('#%02x%02x%02x' % (self.fgrgb[0],
self.fgrgb[1],
self.fgrgb[2]))
- def set_textcolor(self):
- """ Deprecated: Set the text color to foreground color. """
- return
-
def setpen(self, bool, share=True):
- """ Lower or raise the pen """
+ ''' Lower or raise the pen '''
self.pendown = bool
self.tw.active_turtle.set_pen_state(bool)
if self.tw.sharing() and share:
- event = "p|%s" % (data_to_string([self._get_my_nick(), bool]))
+ event = 'p|%s' % (data_to_string([self._get_my_nick(), bool]))
self.tw.send_event(event)
def draw_pixbuf(self, pixbuf, a, b, x, y, w, h, path, share=True):
- """ Draw a pixbuf """
- w *= self.tw.coord_scale
- h *= self.tw.coord_scale
- self.canvas.images[0].draw_pixbuf(self.gc, pixbuf, a, b, x, y)
- self.invalt(x, y, w, h)
+ ''' Draw a pixbuf '''
+ # Build a gtk.gdk.CairoContext from a cairo.Context to access
+ # the set_source_pixbuf attribute.
+ cr = gtk.gdk.CairoContext(self.canvas)
+ cr.save()
+ # center the rotation on the center of the image
+ cr.translate(x + w / 2., y + h / 2.)
+ cr.rotate(self.heading * DEGTOR)
+ cr.translate(-x - w / 2., -y - h / 2.)
+ cr.set_source_pixbuf(pixbuf, x, y)
+ cr.rectangle(x, y, w, h)
+ cr.fill()
+ cr.restore()
+ self.inval()
if self.tw.saving_svg:
if self.tw.running_sugar:
- # In Sugar, we need to embed the images inside the SVG
- self.tw.svg_string += self.svg.image(x - self.width / 2,
- y, w, h, path, image_to_base64(pixbuf,
- get_path(self.tw.activity, 'instance')))
+ # In Sugar, we embed the images inside the SVG
+ tmp_file = os.path.join(get_path(tw.activity, 'instance'),
+ 'tmpfile.png')
+ pixbuf.save(tmp_file, 'png', {'quality': '100'})
+ self.tw.svg_string += self.svg.image(
+ x - self.width / 2, y, w, h, path,
+ image_to_base64(tmp_file,
+ get_path(self.tw.activity, 'instance')))
else:
- # Outside of Sugar, we save a path
+ # In GNOME, we embed a path
self.tw.svg_string += self.svg.image(x - self.width / 2,
y, w, h, path)
if self.tw.sharing() and share:
@@ -545,11 +560,14 @@ class TurtleGraphics:
tmp_path = get_path(self.tw.activity, 'instance')
else:
tmp_path = '/tmp'
- data = image_to_base64(pixbuf, tmp_path)
+ tmp_file = os.path.join(get_path(tw.activity, 'instance'),
+ 'tmpfile.png')
+ pixbuf.save(tmp_file, 'png', {'quality': '100'})
+ data = image_to_base64(tmp_file, tmp_path)
height = pixbuf.get_height()
width = pixbuf.get_width()
x, y = self.screen_to_turtle_coordinates(x, y)
- event = "P|%s" % (data_to_string([self._get_my_nick(),
+ event = 'P|%s' % (data_to_string([self._get_my_nick(),
[round_int(a), round_int(b),
round_int(x), round_int(y),
round_int(w), round_int(h),
@@ -559,110 +577,89 @@ class TurtleGraphics:
self.tw.send_event(event)
def draw_text(self, label, x, y, size, w, share=True):
- """ Draw text """
+ ''' Draw text '''
w *= self.tw.coord_scale
- self.gc.set_foreground(self.fgcolor)
+ cr = pangocairo.CairoContext(self.canvas)
+ pl = cr.create_layout()
fd = pango.FontDescription('Sans')
- try:
- fd.set_size(int(size * self.tw.coord_scale) * pango.SCALE)
- except TypeError, ValueError:
- debug_output("bad value sent to %s" % (__name__),
- self.tw.running_sugar)
- return
- if self.tw.interactive_mode:
- if type(label) == str or type(label) == unicode:
- pl = self.tw.window.create_pango_layout(
- label.replace('\0', ' '))
- elif type(label) == float or type(label) == int:
- pl = self.tw.window.create_pango_layout(str(label))
- else:
- pl = self.tw.window.create_pango_layout(str(label))
- pl.set_font_description(fd)
- pl.set_width(int(w) * pango.SCALE)
- self.canvas.images[0].draw_layout(self.gc, int(x), int(y), pl)
- w, h = pl.get_pixel_size()
- self.invalt(x, y, w, h)
- else: # pixmap doesn't support pango
- message = str(label).replace('\0', ' ')
- context = self.canvas.images[0].cairo_create()
- context.set_font_size(size)
- q, k, w, h = context.text_extents(message)[:4]
- context.set_source_rgb(0, 0, 0)
- context.move_to(x, y + h)
- context.show_text(message)
-
+ fd.set_size(int(size * self.tw.coord_scale) * pango.SCALE)
+ pl.set_font_description(fd)
+ if type(label) == str or type(label) == unicode:
+ pl.set_text(label.replace('\0', ' '))
+ elif type(label) == float or type(label) == int:
+ pl.set_text(str(label))
+ else:
+ pl.set_text(str(label))
+ pl.set_width(int(w) * pango.SCALE)
+ cr.save()
+ cr.translate(x, y)
+ cr.rotate(self.heading * DEGTOR)
+ self.canvas.set_source_rgb(self.fgrgb[0] / 255.,
+ self.fgrgb[1] / 255.,
+ self.fgrgb[2] / 255.)
+ cr.update_layout(pl)
+ cr.show_layout(pl)
+ cr.restore()
+ self.inval()
if self.tw.saving_svg: # and self.pendown:
self.tw.svg_string += self.svg.text(x, # - self.width / 2,
y + size, size, w, label)
if self.tw.sharing() and share:
- event = "W|%s" % (data_to_string([self._get_my_nick(),
+ event = 'W|%s' % (data_to_string([self._get_my_nick(),
[label, round_int(x),
round_int(y), round_int(size),
round_int(w)]]))
self.tw.send_event(event)
def turtle_to_screen_coordinates(self, x, y):
- """ The origin of turtle coordinates is the center of the screen """
+ ''' The origin of turtle coordinates is the center of the screen '''
return self.width / 2. + x, self.invert_y_coordinate(y)
def screen_to_turtle_coordinates(self, x, y):
- """ The origin of the screen coordinates is the upper left corner """
+ ''' The origin of the screen coordinates is the upper left corner '''
return x - self.width / 2., self.invert_y_coordinate(y)
def invert_y_coordinate(self, y):
- """ Positive y goes up in turtle coordinates, down in sceeen
- coordinates """
+ ''' Positive y goes up in turtle coordinates, down in sceeen
+ coordinates '''
return self.height / 2. - y
def draw_line(self, x1, y1, x2, y2):
- """ Draw a line """
+ ''' Draw a line '''
x1, y1 = self.turtle_to_screen_coordinates(x1, y1)
x2, y2 = self.turtle_to_screen_coordinates(x2, y2)
- if x1 < x2:
- minx, maxx = int(x1), int(x2)
- else:
- minx, maxx = int(x2), int(x1)
- if y1 < y2:
- miny, maxy = int(y1), int(y2)
- else:
- miny, maxy = int(y2), int(y1)
- w, h = maxx - minx, maxy - miny
- self.canvas.images[0].draw_line(self.gc, int(x1), int(y1), int(x2),
- int(y2))
- if self.fill and self.poly_points == []:
- self.poly_points.append((int(x1), int(y1)))
+
+ self.canvas.move_to(x1, y1)
+ self.canvas.line_to(x2, y2)
+ self.canvas.stroke()
+
if self.fill:
- self.poly_points.append((int(x2), int(y2)))
- self.invalt(minx - int(self.pensize * self.tw.coord_scale / 2) - 3,
- miny - int(self.pensize * self.tw.coord_scale / 2) - 3,
- w + self.pensize * self.tw.coord_scale + 6,
- h + self.pensize * self.tw.coord_scale + 6)
+ if self.poly_points == []:
+ self.poly_points.append(('move', x1, y1))
+ self.poly_points.append(('line', x2, y2))
+
if self.tw.saving_svg and self.pendown:
self.tw.svg_string += self.svg.new_path(x1, y1)
self.tw.svg_string += self.svg.line_to(x2, y2)
- self.tw.svg_string += "\"\n"
+ self.tw.svg_string += '"\n'
self.tw.svg_string += self.svg.style()
def turn_turtle(self):
- """ Change the orientation of the turtle """
+ ''' Change the orientation of the turtle '''
self.tw.active_turtle.set_heading(self.heading)
def move_turtle(self):
- """ Move the turtle """
+ ''' Move the turtle '''
x, y = self.turtle_to_screen_coordinates(self.xcor, self.ycor)
- self.tw.active_turtle.move(
- (int(self.cx + x - self.tw.active_turtle.spr.rect.width / 2.),
- int(self.cy + y - self.tw.active_turtle.spr.rect.height / 2.)))
-
- def invalt(self, x, y, w, h):
- """ Mark a region for refresh """
if self.tw.interactive_mode:
- self.tw.area.invalidate_rect(
- gtk.gdk.Rectangle(int(x + self.cx), int(y + self.cy),
- int(w), int(h)), False)
+ self.tw.active_turtle.move(
+ (int(self.cx + x - self.tw.active_turtle.spr.rect.width / 2.),
+ int(self.cy + y - self.tw.active_turtle.spr.rect.height / 2.)))
+ else:
+ self.tw.active_turtle.move((int(self.cx + x), int(self.cy + y)))
def get_color_index(self, r, g, b, a=0):
- """ Find the closest palette entry to the rgb triplet """
+ ''' Find the closest palette entry to the rgb triplet '''
if self.shade != 50 or self.gray != 100:
r <<= 8
g <<= 8
@@ -681,7 +678,7 @@ class TurtleGraphics:
b >>= 8
min_distance = 1000000
closest_color = -1
- for i, c in enumerate(color_table):
+ for i, c in enumerate(COLOR_TABLE):
cr = int((c & 0xff0000) >> 16)
cg = int((c & 0x00ff00) >> 8)
cb = int((c & 0x0000ff))
@@ -695,16 +692,31 @@ class TurtleGraphics:
return closest_color
def get_pixel(self):
- """ Read the pixel at x, y """
+ ''' Read the pixel at x, y '''
+ # Fix me: Is there a more efficient way of doing this?
if self.tw.interactive_mode:
x, y = self.turtle_to_screen_coordinates(self.xcor, self.ycor)
- return self.canvas.get_pixel((int(x), int(y)), 0,
- self.tw.color_mode)
+ x = int(x)
+ y = int(y)
+ w = self.tw.turtle_canvas.get_width()
+ h = self.tw.turtle_canvas.get_height()
+ if x < 0 or x > (w - 1) or y < 0 or y > (h - 1):
+ return(-1, -1, -1, -1)
+ # Map the cairo surface onto a pixmap
+ pixmap = gtk.gdk.Pixmap(None, w, h, 24)
+ cr = pixmap.cairo_create()
+ cr.set_source_surface(self.tw.turtle_canvas, 0, 0)
+ cr.paint()
+ # Read the pixel
+ pixel = pixmap.get_image(x, y, 1, 1).get_pixel(0, 0)
+ return(int((pixel & 0xFF0000) >> 16),
+ int((pixel & 0x00FF00) >> 8),
+ int((pixel & 0x0000FF) >> 0), 0)
else:
return(-1, -1, -1, -1)
def set_turtle(self, k, colors=None):
- """ Select the current turtle and associated pen status """
+ ''' Select the current turtle and associated pen status '''
if k not in self.tw.turtles.dict:
# if it is a new turtle, start it in the center of the screen
self.tw.active_turtle = self.tw.turtles.get_turtle(k, True, colors)
@@ -719,8 +731,9 @@ class TurtleGraphics:
self.tw.active_turtle.show()
tx, ty = self.tw.active_turtle.get_xy()
self.xcor, self.ycor = self.screen_to_turtle_coordinates(tx, ty)
- self.xcor += self.tw.active_turtle.spr.rect.width / 2.
- self.ycor -= self.tw.active_turtle.spr.rect.height / 2.
+ if self.tw.interactive_mode:
+ self.xcor += self.tw.active_turtle.spr.rect.width / 2.
+ self.ycor -= self.tw.active_turtle.spr.rect.height / 2.
self.heading = self.tw.active_turtle.get_heading()
self.setcolor(self.tw.active_turtle.get_color(), False)
self.setgray(self.tw.active_turtle.get_gray(), False)
@@ -729,14 +742,19 @@ class TurtleGraphics:
self.setpen(self.tw.active_turtle.get_pen_state(), False)
def svg_close(self):
- """ Close current SVG graphic """
+ ''' Close current SVG graphic '''
if self.tw.svg_string == '':
return
self.svg.calc_w_h(False)
- self.tw.svg_string = "%s%s%s%s" % (self.svg.header(True),
- self.svg.background("#%02x%02x%02x" % \
- (self.bgrgb[0], self.bgrgb[1], self.bgrgb[2])),
- self.tw.svg_string, self.svg.footer())
+ self.tw.svg_string = '%s %s %s %s' % (
+ self.svg.header(True),
+ self.svg.background('#%02x%02x%02x' % (
+ self.bgrgb[0], self.bgrgb[1], self.bgrgb[2])),
+ self.tw.svg_string, self.svg.footer())
def _get_my_nick(self):
return self.tw.nick
+
+ def inval(self):
+ ''' Invalidate a region for gtk '''
+ self.tw.inval_all()
diff --git a/TurtleArt/taconstants.py b/TurtleArt/taconstants.py
index 2bb9049..5a1b06a 100644
--- a/TurtleArt/taconstants.py
+++ b/TurtleArt/taconstants.py
@@ -25,8 +25,6 @@ from gettext import gettext as _
# Sprite layers
#
-HIDE_LAYER = 100
-CANVAS_LAYER = 500
OVERLAY_LAYER = 525
TURTLE_LAYER = 550
BLOCK_LAYER = 600
diff --git a/TurtleArt/taexporthtml.py b/TurtleArt/taexporthtml.py
index 843b8b0..90dcc4d 100644
--- a/TurtleArt/taexporthtml.py
+++ b/TurtleArt/taexporthtml.py
@@ -78,40 +78,42 @@ def save_html(self, tw, embed_flag=True):
"""
htmlcode = ''
if len(tw.saved_pictures) > 0:
- for i, p in enumerate(tw.saved_pictures):
+ for i, image_file in enumerate(tw.saved_pictures):
htmlcode += HTML_GLUE['slide'][0] + str(i)
htmlcode += HTML_GLUE['slide'][1] + \
HTML_GLUE['div'][0] + \
HTML_GLUE['h1'][0]
if embed_flag:
- f = open(p, 'r')
+ f = open(image_file, 'r')
imgdata = f.read()
f.close()
- if p.endswith(('.svg')):
+ if image_file.endswith(('.svg')):
tmp = imgdata
else:
- pixbuf = gtk.gdk.pixbuf_new_from_file(p)
- imgdata = image_to_base64(pixbuf,
- get_path(tw.activity, 'instance'))
+ imgdata = image_to_base64(image_file,
+ get_path(tw.activity, 'instance'))
tmp = HTML_GLUE['img2'][0]
tmp += imgdata
tmp += HTML_GLUE['img2'][1]
else:
- if p.endswith(('.svg')):
- f = open(p, 'r')
+ if image_file.endswith(('.svg')):
+ f = open(image_file, 'r')
imgdata = f.read()
f.close()
tmp = imgdata
else:
tmp = HTML_GLUE['img3'][0]
- tmp += p
+ tmp += image_file
tmp += HTML_GLUE['img3'][1]
htmlcode += tmp + \
HTML_GLUE['h1'][1] + \
HTML_GLUE['div'][1]
else:
if embed_flag:
- imgdata = image_to_base64(save_picture(self.tw.canvas),
+ tmp_file = os.path.join(get_path(tw.activity, 'instance'),
+ 'tmpfile.png')
+ save_picture(self.tw.canvas, tmp_file)
+ imgdata = image_to_base64(tmp_file,
get_path(tw.activity, 'instance'))
else:
imgdata = os.path.join(self.tw.load_save_folder, 'image')
diff --git a/TurtleArt/talogo.py b/TurtleArt/talogo.py
index 12be92f..25ffceb 100644
--- a/TurtleArt/talogo.py
+++ b/TurtleArt/talogo.py
@@ -585,14 +585,20 @@ class LogoCode:
debug_output("Couldn't open filepath %s" % (self.filepath),
self.tw.running_sugar)
if pixbuf is not None:
+ x = self.tw.canvas.xcor
+ y = self.tw.canvas.ycor
+ w *= self.tw.coord_scale
+ h *= self.tw.coord_scale
if center:
self.tw.canvas.draw_pixbuf(pixbuf, 0, 0,
self.x2tx() - int(w / 2),
self.y2ty() - int(h / 2), w, h,
self.filepath)
else:
- self.tw.canvas.draw_pixbuf(pixbuf, 0, 0, self.x2tx(),
- self.y2ty(), w, h, self.filepath)
+ self.tw.canvas.draw_pixbuf(pixbuf, 0, 0,
+ self.x2tx(),
+ self.y2ty(),
+ w, h, self.filepath)
def insert_desc(self, mimetype=None, description=None):
""" Description text only (at current x, y) """
diff --git a/TurtleArt/taturtle.py b/TurtleArt/taturtle.py
index 0ca72e4..c7bb768 100644
--- a/TurtleArt/taturtle.py
+++ b/TurtleArt/taturtle.py
@@ -25,7 +25,7 @@ from gettext import gettext as _
from taconstants import TURTLE_LAYER, DEFAULT_TURTLE_COLORS
from tasprite_factory import SVG, svg_str_to_pixbuf
-from tacanvas import wrap100, color_table
+from tacanvas import wrap100, COLOR_TABLE
from sprites import Sprite
from tautils import debug_output
@@ -161,8 +161,8 @@ class Turtle:
elif use_color_table:
fill = wrap100(int_key)
stroke = wrap100(fill + 10)
- self.colors = ['#%06x' % (color_table[fill]),
- '#%06x' % (color_table[stroke])]
+ self.colors = ['#%06x' % (COLOR_TABLE[fill]),
+ '#%06x' % (COLOR_TABLE[stroke])]
self.shapes = generate_turtle_pixbufs(self.colors)
else:
if turtles is not None:
diff --git a/TurtleArt/tautils.py b/TurtleArt/tautils.py
index a47c063..a402563 100644
--- a/TurtleArt/tautils.py
+++ b/TurtleArt/tautils.py
@@ -20,6 +20,7 @@
#THE SOFTWARE.
import gtk
+import cairo
import pickle
import subprocess
import os.path
@@ -40,8 +41,8 @@ except (ImportError, AttributeError):
OLD_SUGAR_SYSTEM = True
from StringIO import StringIO
-from taconstants import HIDE_LAYER, COLLAPSIBLE, BLOCK_LAYER, HIT_HIDE, \
- HIT_SHOW, XO1, XO15, XO175, UNKNOWN
+from taconstants import COLLAPSIBLE, HIT_HIDE, HIT_SHOW, XO1, XO15, XO175, \
+ UNKNOWN
import logging
_logger = logging.getLogger('turtleart-activity')
@@ -260,16 +261,26 @@ def do_dialog(dialog, suffix, load_save_folder):
return _result, load_save_folder
-def save_picture(canvas, file_name=''):
- """ Save the canvas to a file. """
- _pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, canvas.width,
- canvas.height)
- _pixbuf.get_from_drawable(canvas.canvas.images[0],
- canvas.canvas.images[0].get_colormap(),
- 0, 0, 0, 0, canvas.width, canvas.height)
- if file_name != '':
- _pixbuf.save(file_name, 'png')
- return _pixbuf
+def save_picture(canvas, file_name):
+ """ Save the canvas to a file """
+ x_surface = canvas.canvas.get_target()
+ img_surface = cairo.ImageSurface(cairo.FORMAT_RGB24,
+ canvas.width, canvas.height)
+ cr = cairo.Context(img_surface)
+ cr.set_source_surface(x_surface)
+ cr.paint()
+ img_surface.write_to_png(file_name)
+
+
+def get_canvas_data(canvas):
+ x_surface = canvas.canvas.get_target()
+ img_surface = cairo.ImageSurface(cairo.FORMAT_RGB24,
+ canvas.width, canvas.height)
+ cr = cairo.Context(img_surface)
+ cr.set_source_surface(x_surface)
+ cr.paint()
+ return img_surface.get_data()
+
def save_svg(string, file_name):
@@ -307,13 +318,10 @@ def get_path(activity, subpath):
"org.laptop.TurtleArtActivity", subpath))
-def image_to_base64(pixbuf, path_name):
+def image_to_base64(image_path, tmp_path):
""" Convert an image to base64-encoded data """
- file_name = os.path.join(path_name, 'imagetmp.png')
- if pixbuf != None:
- pixbuf.save(file_name, "png")
- base64 = os.path.join(path_name, 'base64tmp')
- cmd = "base64 <" + file_name + " >" + base64
+ base64 = os.path.join(tmp_path, 'base64tmp')
+ cmd = "base64 <" + image_path + " >" + base64
subprocess.check_call(cmd, shell=True)
file_handle = open(base64, 'r')
data = file_handle.read()
@@ -491,7 +499,7 @@ def restore_stack(top):
_dy += _newdy - _olddy
else:
if not _hit_bottom:
- _blk.spr.set_layer(BLOCK_LAYER)
+ _blk.spr.restore()
_blk.status = None
else:
_blk.spr.move_relative((_dx, _dy))
@@ -574,7 +582,7 @@ def collapse_stack(top):
_dy += _newdy - _olddy
else:
if not _hit_bottom:
- _blk.spr.set_layer(HIDE_LAYER)
+ _blk.spr.hide()
_blk.status = 'collapsed'
else:
_blk.spr.move_relative((_dx, _dy))
diff --git a/TurtleArt/tawindow.py b/TurtleArt/tawindow.py
index f1917e8..f9f1696 100644
--- a/TurtleArt/tawindow.py
+++ b/TurtleArt/tawindow.py
@@ -80,10 +80,11 @@ class TurtleArtWindow():
_PLUGIN_SUBPATH = 'plugins'
def __init__(self, canvas_window, path, parent=None,
- mycolors=None, mynick=None):
+ mycolors=None, mynick=None, turtle_canvas=None):
self._loaded_project = ''
self._sharing = False
self.parent = parent
+ self.turtle_canvas = turtle_canvas
self.send_event = None # method to send events over the network
self.gst_available = GST_AVAILABLE
if type(canvas_window) == gtk.DrawingArea:
@@ -96,23 +97,11 @@ class TurtleArtWindow():
self.running_sugar = True
else:
self.running_sugar = False
- self.area = self.window.window
- if self.area is not None:
- self.gc = self.area.new_gc()
- else:
- # We lose...
- debug_output('drawable area is None... punting',
- self.running_sugar)
- exit()
self._setup_events()
- elif type(canvas_window) == gtk.gdk.Pixmap:
+ else:
self.interactive_mode = False
self.window = canvas_window
self.running_sugar = False
- if self.window is not None:
- self.gc = self.window.new_gc()
- else:
- debug_output("bad win type %s" % (type(canvas_window)), False)
if self.running_sugar:
from sugar import profile
@@ -151,9 +140,9 @@ class TurtleArtWindow():
self.orientation = HORIZONTAL_PALETTE
self.hw = get_hardware()
+ self.lead = 1.0
if self.hw in (XO1, XO15, XO175):
- self.lead = 1.0
- self.scale = 0.67
+ self.scale = 1.2 # slight scale-up of fonts on XO
if self.hw == XO1:
self.color_mode = '565'
else:
@@ -161,7 +150,6 @@ class TurtleArtWindow():
if self.running_sugar and not self.activity.has_toolbarbox:
self.orientation = VERTICAL_PALETTE
else:
- self.lead = 1.0
self.scale = 1.0
self.color_mode = '888' # TODO: Read visual mode from gtk image
@@ -201,19 +189,26 @@ class TurtleArtWindow():
self.selector_shapes = []
self.selected_blk = None
self.selected_spr = None
+ self.selected_turtle = None
self.drag_group = None
self.drag_turtle = 'move', 0, 0
self.drag_pos = 0, 0
self.turtle_movement_to_share = None
- self.paste_offset = 20
+ self.paste_offset = 20 # Don't paste on top of where you copied.
+ self.saving_svg = False
+ self.svg_string = ''
self.block_list = Blocks(font_scale_factor=self.scale,
decimal_point=self.decimal_point)
if self.interactive_mode:
- self.sprite_list = Sprites(self.window, self.area, self.gc)
+ self.sprite_list = Sprites(self.window)
else:
self.sprite_list = None
+ self.canvas = TurtleGraphics(self, self.width, self.height)
+ if self.interactive_mode:
+ self.sprite_list.set_cairo_context(self.canvas.canvas)
+
self.turtles = Turtles(self.sprite_list)
if self.nick is None:
self.default_turtle_name = DEFAULT_TURTLE
@@ -224,11 +219,9 @@ class TurtleArtWindow():
else:
Turtle(self.turtles, self.default_turtle_name, mycolors.split(','))
self.active_turtle = self.turtles.get_turtle(self.default_turtle_name)
+ self.active_turtle.show()
- self.saving_svg = False
- self.svg_string = ''
- self.selected_turtle = None
- self.canvas = TurtleGraphics(self, self.width, self.height)
+ self.canvas.clearscreen(False)
CONSTANTS['titlex'] = int(-(self.canvas.width * TITLEXY[0]) / \
(self.coord_scale * 2))
@@ -356,6 +349,7 @@ class TurtleArtWindow():
self.window.add_events(gtk.gdk.BUTTON_RELEASE_MASK)
self.window.add_events(gtk.gdk.POINTER_MOTION_MASK)
self.window.add_events(gtk.gdk.KEY_PRESS_MASK)
+ # self.window.connect('realize', self.do_realize)
self.window.connect("expose-event", self._expose_cb)
self.window.connect("button-press-event", self._buttonpress_cb)
self.window.connect("button-release-event", self._buttonrelease_cb)
@@ -417,11 +411,33 @@ class TurtleArtWindow():
""" Check to see if project has any blocks in use """
return len(self.just_blocks()) == 1
- def _expose_cb(self, win, event):
+ def _expose_cb(self, win=None, event=None):
""" Repaint """
- self.sprite_list.refresh(event)
+ self.do_expose_event(event)
return True
+ # Handle the expose-event by drawing
+ def do_expose_event(self, event=None):
+
+ # Create the cairo context
+ cr = self.window.window.cairo_create()
+
+ if event is None:
+ cr.rectangle(self.rect.x, self.rect.y,
+ self.rect.width, self.rect.height)
+ else:
+ # Restrict Cairo to the exposed area; avoid extra work
+ cr.rectangle(event.area.x, event.area.y,
+ event.area.width, event.area.height)
+ cr.clip()
+
+ if self.turtle_canvas is not None:
+ cr.set_source_surface(self.turtle_canvas)
+ cr.paint()
+
+ # Refresh sprite list
+ self.sprite_list.redraw_sprites(cr=cr)
+
def eraser_button(self):
""" Eraser_button (hide status block when clearing the screen.) """
if self.status_spr is not None:
@@ -473,6 +489,12 @@ class TurtleArtWindow():
def set_cartesian(self, flag):
""" Turn on/off Cartesian coordinates """
+ if self.coord_scale == 1:
+ self.draw_overlay('Cartesian_labeled')
+ else:
+ self.draw_overlay('Cartesian')
+ return
+ '''
if flag:
if self.coord_scale == 1:
self.overlay_shapes['Cartesian_labeled'].set_layer(
@@ -486,24 +508,45 @@ class TurtleArtWindow():
else:
self.overlay_shapes['Cartesian'].hide()
self.cartesian = False
+ '''
def set_polar(self, flag):
""" Turn on/off polar coordinates """
+ self.draw_overlay('polar')
+ return
+ '''
if flag:
self.overlay_shapes['polar'].set_layer(OVERLAY_LAYER)
self.polar = True
else:
self.overlay_shapes['polar'].hide()
self.polar = False
+ '''
def set_metric(self, flag):
""" Turn on/off metric coordinates """
+ self.draw_overlay('metric')
+ return
+ '''
if flag:
self.overlay_shapes['metric'].set_layer(OVERLAY_LAYER)
self.metric = True
else:
self.overlay_shapes['metric'].hide()
self.metric = False
+ '''
+
+ def draw_overlay(self, overlay):
+ ''' Draw a coordinate grid onto the canvas. '''
+ save_heading = self.canvas.heading
+ self.canvas.heading = 0
+ w = self.overlay_shapes[overlay].rect[2]
+ h = self.overlay_shapes[overlay].rect[3]
+ self.canvas.draw_pixbuf(self.overlay_shapes[overlay].images[0],
+ 0, 0, (self.canvas.width - w) / 2.,
+ (self.canvas.height - h) / 2.,
+ w, h, '', share=False)
+ self.canvas.heading = save_heading
def update_overlay_position(self, widget, event):
""" Reposition the overlays when window size changes """
@@ -547,8 +590,12 @@ class TurtleArtWindow():
self.hide = False
if self.running_sugar:
self.activity.recenter()
+ self.inval_all()
- self.canvas.canvas.inval()
+ def inval_all(self):
+ """ Force a refresh """
+ if self.interactive_mode:
+ self.window.queue_draw_area(0, 0, self.width, self.height)
def hideshow_palette(self, state):
""" Hide or show palette """
@@ -1048,10 +1095,7 @@ class TurtleArtWindow():
# Finally, check for anything else
if hasattr(spr, 'type'):
- if spr.type == "canvas":
- pass
- # spr.set_layer(CANVAS_LAYER)
- elif spr.type == 'selector':
+ if spr.type == 'selector':
self._select_category(spr)
elif spr.type == 'category':
if hide_button_hit(spr, x, y):
@@ -1187,6 +1231,7 @@ class TurtleArtWindow():
for gblk in group:
if collapsed(gblk):
collapse_stack(find_sandwich_top(gblk))
+
# And resize any skins.
for gblk in group:
if gblk.name in BLOCKS_WITH_SKIN:
@@ -1563,7 +1608,11 @@ class TurtleArtWindow():
self.rect.y = miny
self.rect.width = maxx - minx
self.rect.height = maxy - miny
- self.sprite_list.area.invalidate_rect(self.rect, False)
+ self.window.queue_draw_area(self.rect.x,
+ self.rect.y,
+ self.rect.width,
+ self.rect.height)
+ # self._expose_cb()
self.dx += dx
self.dy += dy
@@ -1633,6 +1682,7 @@ class TurtleArtWindow():
""" Button release """
x, y = xy(event)
self.button_release(x, y)
+ self._expose_cb()
if self.turtle_movement_to_share is not None:
self._share_mouse_move()
return True
@@ -1724,9 +1774,8 @@ class TurtleArtWindow():
def _move_turtle(self, x, y):
""" Move the selected turtle to (x, y). """
- (cx, cy) = self.canvas.canvas.get_xy()
- self.canvas.xcor = x - cx
- self.canvas.ycor = y + cy
+ self.canvas.xcor = x
+ self.canvas.ycor = y
self.canvas.move_turtle()
if self.running_sugar:
self.display_coordinates()
@@ -1876,7 +1925,6 @@ class TurtleArtWindow():
restore_stack(top) # deprecated (bottom block is invisible)
elif top is not None:
collapse_stack(top)
-
else:
self._run_stack(blk)
@@ -1988,6 +2036,9 @@ class TurtleArtWindow():
d = 200
for selected_block_dockn in range(len(selected_block.docks)):
for destination_block in self.just_blocks():
+ # Don't link to a block that is hidden
+ if destination_block.status == 'collapsed':
+ continue
# Don't link to a block to which you're already connected
if destination_block in self.drag_group:
continue
@@ -2784,7 +2835,7 @@ class TurtleArtWindow():
blk.spr.set_layer(BLOCK_LAYER)
if check_dock:
blk.connections = 'check'
- if blk.spr.labels[0] is not None and \
+ if self.running_sugar and blk.spr.labels[0] is not None and \
blk.name not in ['', ' ', 'number', 'string']:
if blk.spr.labels[0] not in self.used_block_list:
self.used_block_list.append(blk.spr.labels[0])
diff --git a/TurtleArtActivity.py b/TurtleArtActivity.py
index f5bdd69..fd44ebc 100644
--- a/TurtleArtActivity.py
+++ b/TurtleArtActivity.py
@@ -23,6 +23,7 @@
import pygtk
pygtk.require('2.0')
import gtk
+import cairo
import gobject
import dbus
@@ -76,7 +77,7 @@ class TurtleArtActivity(activity.Activity):
self._setup_toolbar()
_logger.debug('_setup_canvas')
- self._setup_canvas(self._setup_scrolled_window())
+ self._canvas = self._setup_canvas(self._setup_scrolled_window())
_logger.debug('_setup_palette_toolbar')
self._setup_palette_toolbar()
@@ -728,10 +729,17 @@ class TurtleArtActivity(activity.Activity):
def _setup_canvas(self, canvas_window):
''' Initialize the turtle art canvas. '''
+ win = canvas_window.get_window() # self._canvas.get_window()
+ cr = win.cairo_create()
+ surface = cr.get_target()
+ self.turtle_canvas = surface.create_similar(
+ cairo.CONTENT_COLOR, gtk.gdk.screen_width() * 2,
+ gtk.gdk.screen_height() * 2)
bundle_path = activity.get_bundle_path()
self.tw = TurtleArtWindow(canvas_window, bundle_path, self,
- profile.get_color().to_string(),
- profile.get_nick_name())
+ mycolors=profile.get_color().to_string(),
+ mynick=profile.get_nick_name(),
+ turtle_canvas=self.turtle_canvas)
self.tw.window.grab_focus()
path = os.path.join(os.environ['SUGAR_ACTIVITY_ROOT'], 'data')
self.tw.save_folder = path
diff --git a/activity/activity.info b/activity/activity.info
index 5373b01..d8b7f81 100644
--- a/activity/activity.info
+++ b/activity/activity.info
@@ -1,6 +1,6 @@
[Activity]
name = Turtle Art
-activity_version = 122
+activity_version = 123
license = MIT
bundle_id = org.laptop.TurtleArtActivity
exec = sugar-activity TurtleArtActivity.TurtleArtActivity
diff --git a/pysamples/set_rgb.py b/pysamples/set_rgb.py
index d4baa48..b77d9df 100644
--- a/pysamples/set_rgb.py
+++ b/pysamples/set_rgb.py
@@ -13,7 +13,6 @@
def myblock(tw, rgb_array):
''' Set rgb color from values '''
- rgb = "#%02x%02x%02x" % ((int(rgb_array[0]) % 256),
- (int(rgb_array[1]) % 256),
- (int(rgb_array[2]) % 256))
- tw.canvas.fgcolor = tw.canvas.cm.alloc_color(rgb)
+ tw.canvas.fgrgb = [(int(rgb_array[0]) % 256),
+ (int(rgb_array[1]) % 256),
+ (int(rgb_array[2]) % 256)]
diff --git a/turtleart.py b/turtleart.py
index ca9153a..9afc238 100755
--- a/turtleart.py
+++ b/turtleart.py
@@ -24,6 +24,7 @@
import pygtk
pygtk.require('2.0')
import gtk
+import cairo
import getopt
import sys
@@ -83,11 +84,13 @@ class TurtleMain():
self._plugins = []
if self.output_png:
+ # Fix me: We need to create a cairo surface to work with
pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8,
gtk.gdk.screen_width(),
gtk.gdk.screen_height())
- self.canvas, mask = pixbuf.render_pixmap_and_mask()
- self._build_window()
+ # self.canvas, mask = pixbuf.render_pixmap_and_mask()
+ self.canvas = pixbuf
+ self._build_window(interactive=False)
self._draw_and_quit()
else:
self._read_initial_pos()
@@ -174,11 +177,24 @@ class TurtleMain():
self.tw.load_start(self.ta_file)
self.tw.lc.trace = 0
self.tw.run_button(0)
- self.tw.save_as_image(self.ta_file, self.canvas)
+ self.tw.save_as_image(self.ta_file)
- def _build_window(self):
+ def _build_window(self, interactive=True):
''' Initialize the TurtleWindow instance. '''
- self.tw = TurtleArtWindow(self.canvas, self._dirname)
+ if interactive:
+ win = self.canvas.get_window()
+ cr = win.cairo_create()
+ surface = cr.get_target()
+ else:
+ img_surface = cairo.ImageSurface(cairo.FORMAT_RGB24,
+ 1024, 768)
+ cr = cairo.Context(img_surface)
+ surface = cr.get_target()
+ self.turtle_canvas = surface.create_similar(
+ cairo.CONTENT_COLOR, gtk.gdk.screen_width() * 2,
+ gtk.gdk.screen_height() * 2)
+ self.tw = TurtleArtWindow(self.canvas, self._dirname,
+ turtle_canvas=self.turtle_canvas)
self.tw.save_folder = os.path.expanduser('~')
def _init_vars(self):