Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/TurtleArt/tacanvas.py
diff options
context:
space:
mode:
Diffstat (limited to 'TurtleArt/tacanvas.py')
-rw-r--r--TurtleArt/tacanvas.py476
1 files changed, 247 insertions, 229 deletions
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()