[cairo-commit] pycairo/examples/cairo_snippets c_to_python.py, NONE, 1.1 snippets_gtk.py, NONE, 1.1 snippets_png.py, NONE, 1.1

Steve Chaplin commit at pdx.freedesktop.org
Wed Apr 6 06:54:12 PDT 2005


Committed by: stevech1097

Update of /cvs/cairo/pycairo/examples/cairo_snippets
In directory gabe:/tmp/cvs-serv23095/examples/cairo_snippets

Added Files:
	c_to_python.py snippets_gtk.py snippets_png.py 
Log Message:
SC 2005/04/06

--- NEW FILE: c_to_python.py ---
#!/usr/bin/env python
"""
translate C <snippet>.cairo to Python <snippet>.py

;       -> ''
cairo_  -> cr.
'(cr, ' -> (     but not snippet_normalize (cr, width, height)
(cr)    -> ()
/*      -> #/*
CAIRO_  -> cairo.
"""

import sys


if len(sys.argv) != 2 or not sys.argv[1].endswith('.cairo'):
    raise SystemExit('usage: c_to_python.py <file>.cairo')

filename_in  = sys.argv[1]
filename_out = filename_in.replace('.cairo', '.py')

file_in  = file(filename_in)
file_out = file(filename_out, 'w')    

for line in file_in:
    line = line.replace(';', '')    # should be ';' and whitespace to EOL only -> \n
    if not line.startswith('snippet_'):
        line = line.replace('cairo_', 'cr.')
        line = line.replace('(cr, ',  '(')
        line = line.replace('(cr)',   '()')
        line = line.replace('/*',     '#/*')
        line = line.replace('    ',   '')
        line = line.replace('CAIRO_', 'cairo.')
    
    file_out.write (line)

--- NEW FILE: snippets_gtk.py ---
#!/usr/bin/env python
"""Python version of cairo-demo/cairo_snippets/cairo_snippets_gtk.c
"""
from __future__ import division
from math import pi as M_PI  # used by many snippets

import gtk
import pango
import cairo
import cairo.gtk

from snippets import snip_list, snippet_normalize, snippet_set_bg_svg

M_PI = math.pi   # used by many snippets

Width, Height = 400, 400
    

def gdkcolor_to_rgb (gdkcolor):
    return gdkcolor.red/65535, gdkcolor.green/65535, gdkcolor.blue/65535


class Window (gtk.Window):
    """Composite widget"""
    def __init__ (self, title=None, type=gtk.WINDOW_TOPLEVEL):
        gtk.Window.__init__ (self, type)
        self.set_default_size (Width, Height)

        self.ctx = cairo.Context()

        self.da = gtk.DrawingArea()
        self.da.connect('expose-event', self.da_expose_event)
        self.da.connect('size-allocate', self.da_size_allocate)

        vpaned = gtk.VPaned()
        self.add (vpaned)

        frame = gtk.Frame (label=None)        
        vpaned.pack1 (frame, True, True)
        frame.set_property ('shadow_type', gtk.SHADOW_IN)

        sv = self.create_source_view()
        frame.add (sv)
        sv.set_size_request (Width, int(Height/2))

        hpaned = gtk.HPaned()
        vpaned.pack2 (hpaned, True, False)

        frame = gtk.Frame (label=None)
        hpaned.pack1 (frame, True, True)
        frame.set_property ('shadow_type', gtk.SHADOW_IN)

        sl = self.create_snippet_list()
        frame.add (sl)
        
        frame = gtk.Frame (label=None)
        hpaned.pack2 (frame, True, True)
        frame.set_property ('shadow_type', gtk.SHADOW_IN)
        
        frame.add (self.da)
        self.da.set_size_request (int(Width/2), int(Height/2))

        self.da.realize()
        self._bg_rgb = gdkcolor_to_rgb (self.da.style.bg[gtk.STATE_NORMAL])
        
        self._pixmap        = None
        self._draw_pixmap   = True
        self._pixmap_width  = -1
        self._pixmap_height = -1


    def da_size_allocate (self, da, allocation):
        self._draw_pixmap = True

        
    def da_expose_event (self, da, event, data=None):
        if self._draw_pixmap:
            width  = da.allocation.width
            height = da.allocation.height

            create_pixmap = False
            if width > self._pixmap_width:
                self._pixmap_width = max (int (self._pixmap_width  * 1.1),
                                          width)
                create_pixmap = True

            if height > self._pixmap_height:
                self._pixmap_height = max (int (self._pixmap_height * 1.1),
                                           height)
                create_pixmap = True

            if create_pixmap:
                self._pixmap = gtk.gdk.Pixmap (da.window, self._pixmap_width,
                                               self._pixmap_height)
                surface = cairo.gtk.surface_create_for_pixmap_with_visual(
                    self._pixmap, da.window.get_visual())
                self.ctx.set_target_surface (surface)

            self.ctx.save()

            cr = self.ctx # used by snippet
            # set window bg
            cr.set_rgb_color (*self._bg_rgb)
            cr.rectangle(0, 0, width, height)
            cr.fill()
            cr.set_rgb_color (0,0,0) # reset black
        
            exec (self.snippet_str, globals(), locals())
        
            self.ctx.restore()

            da.window.set_back_pixmap (self._pixmap, False)
            da.window.clear()  # draws the pixmap onto the window bg
            self._draw_pixmap = False
        return True


    def create_source_view (self):
        sw = gtk.ScrolledWindow()
        sw.set_policy (hscrollbar_policy=gtk.POLICY_NEVER,
                       vscrollbar_policy=gtk.POLICY_AUTOMATIC)

        text_view = gtk.TextView()
        sw.add (text_view)
        # set a fixed width font, so any tabs line up
        text_view.modify_font(pango.FontDescription ("Fixed"))
        
        self.source_buffer = text_view.get_buffer()

        return sw


    def cb_selection_changed (self, tselection, data=None):
        model, iter = tselection.get_selected()
        if iter:
            filename = model[iter][0] + '.py'
            try:
                file_obj = file('snippets/%s' % filename)
                self.snippet_str = file_obj.read()
                file_obj.close()
                self.source_buffer.set_text(self.snippet_str)
            except IOError, exc:
                print "%s: %s" % (exc.filename, exc.strerror)

            self._draw_pixmap = True
            self.da.queue_draw()


    def create_snippet_list (self):
        sw = gtk.ScrolledWindow()
        sw.set_policy (hscrollbar_policy=gtk.POLICY_NEVER,
                       vscrollbar_policy=gtk.POLICY_AUTOMATIC)

        model = gtk.ListStore (str,)
        for row in snip_list:
            model.append (row=(row,))
    
        tree_view = gtk.TreeView (model)
        sw.add (tree_view)
        tree_view.set_property ('headers-visible', False)
        tree_view.set_property ('search-column', 0)
        tree_view.set_property ('rules-hint', False)

        tselection = tree_view.get_selection()
        tselection.connect ("changed", self.cb_selection_changed)
        tselection.set_mode (gtk.SELECTION_BROWSE)
        tselection.select_path(0,) # select first item

        cr = gtk.CellRendererText()
        tvc = gtk.TreeViewColumn (None, cr, text=0)
        tree_view.append_column (tvc)
        
        return sw


if __name__ == '__main__':
    app = Window ()
    app.connect('destroy', gtk.main_quit)
    app.show_all()
    gtk.main()

--- NEW FILE: snippets_png.py ---
#!/usr/bin/env python
"""Python version of cairo-demo/cairo_snippets/cairo_snippets_png.c
"""
from __future__ import division
from math import pi as M_PI  # used by many snippets
import sys

import cairo

from snippets import snip_list, snippet_normalize, snippet_set_bg_svg

Width, Height = 256, 256


def snippet_do_png (snippet):
    print 'processing %s' % snippet,
    
    surface = cairo.Surface(cairo.FORMAT_ARGB32, Width, Height)
    cr = cairo.Context()
    cr.set_target_surface(surface)

    cr.save()

    width, height = Width, Height
    
    execfile ('snippets/%s.py' % snippet, globals(), locals())
    
    cr.restore()

    file_obj = file('snippets/%s.png' % snippet, 'wb')
    surface.write_png (file_obj)
    file_obj.close()

    print

if __name__ == '__main__':
    if len(sys.argv) > 1: # do specified snippets
        snippet_list = sys.argv[1:]
    else:                 # do all snippets
        snippet_list = snip_list

    for s in snippet_list:
        snippet_do_png (s)




More information about the cairo-commit mailing list