Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/tutorius/viewer.py
blob: 56428e126c66e3416c4040fffa4da0148d369110 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# Copyright (C) 2009, Tutorius.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
"""
This module renders a widget containing a graphical representation
of a tutorial and acts as a creator proxy as it has some editing
functionality.
"""
import gtk
import cairo
from math import pi as PI
PI2 = PI/2

import rsvg

from sugar.bundle import activitybundle
from sugar.tutorius import addon
from sugar.graphics import icon
from sugar.tutorius.actions import Action
import os

# FIXME ideally, apps scale correctly and we should use proportional positions
X_WIDTH = 800
X_HEIGHT = 600
ACTION_WIDTH = 100
ACTION_HEIGHT = 70

# block look
BLOCK_PADDING = 5
BLOCK_WIDTH = 100
BLOCK_CORNERS = 10
BLOCK_INNER_PAD = 10

SNAP_WIDTH = BLOCK_WIDTH - BLOCK_PADDING - BLOCK_INNER_PAD*2
SNAP_HEIGHT = SNAP_WIDTH*X_HEIGHT/X_WIDTH
SNAP_SCALE = float(SNAP_WIDTH)/X_WIDTH

class Viewer(object):
    """
    Renders a tutorial as a sequence of blocks, each block representing either
    an action or an event (transition).

    Current Viewer implementation lacks viewport management;
    having many objects in a tutorial will not render properly.
    """
    def __init__(self, tutorial, creator):
        super(Viewer, self).__init__()

        self._tutorial = tutorial
        self._creator = creator
        self.alloc = None
        self.click_pos = None
        self.drag_pos = None
        self.selection = set()

        self.win = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.win.set_size_request(400, 200)
        self.win.set_gravity(gtk.gdk.GRAVITY_SOUTH_WEST)
        self.win.show()
        self.win.set_deletable(False)
        self.win.move(0, 0)

        vbox = gtk.ScrolledWindow()
        self.win.add(vbox)

        canvas = gtk.DrawingArea()
        vbox.add_with_viewport(canvas)
        canvas.set_app_paintable(True)
        canvas.connect_after("expose-event", self.on_viewer_expose, tutorial)
        canvas.add_events(gtk.gdk.BUTTON_PRESS_MASK \
                          |gtk.gdk.BUTTON_MOTION_MASK \
                          |gtk.gdk.BUTTON_RELEASE_MASK \
                          |gtk.gdk.KEY_PRESS_MASK)
        canvas.connect('button-press-event', self._on_click)
        # drag-select disabled, for now
        #canvas.connect('motion-notify-event', self._on_drag)
        canvas.connect('button-release-event', self._on_drag_end)
        canvas.connect('key-press-event', self._on_key_press)

        canvas.set_flags(gtk.HAS_FOCUS|gtk.CAN_FOCUS)
        canvas.grab_focus()

        self.win.show_all()
        canvas.set_size_request(2048, 180) # FIXME

    def destroy(self):
        """
        Destroy ui resources associated with this object.
        """
        self.win.destroy()


    def _paint_state(self, ctx, tutorial):
        """
        Paints a tutorius fsm state in a cairo context.
        Final context state will be shifted by the size of the graphics.
        """
        block_width = BLOCK_WIDTH - BLOCK_PADDING
        block_max_height = self.alloc.height

        new_insert_point = None
        state_name = tutorial.INIT

        # FIXME: get app when we have a model that supports it
        cur_app = 'Calculate'
        app_start = ctx.get_matrix()

        while state_name:
            new_app = 'Calculate'
            if new_app != cur_app:
                ctx.save()
                ctx.set_matrix(app_start)
                self._render_app_hints(ctx, cur_app)
                ctx.restore()
                app_start = ctx.get_matrix()
                ctx.translate(BLOCK_PADDING, 0)
                cur_app = new_app

            action_list = tutorial.get_action_dict(state_name).items()
            if action_list:
                local_height = (block_max_height - BLOCK_PADDING)\
                        / len(action_list) - BLOCK_PADDING
                ctx.save()
                for action_name, action in action_list:
                    origin = tuple(ctx.get_matrix())[-2:]
                    if self.click_pos and \
                       self.click_pos[0]-BLOCK_WIDTH<origin[0] and \
                       self.drag_pos[0]>origin[0]:
                        self.selection.add((action_name, action))
                    self.render_action(ctx, block_width, local_height, action)
                    ctx.translate(0, local_height+BLOCK_PADDING)

                ctx.restore()
                ctx.translate(BLOCK_WIDTH, 0)

            # insertion cursor painting made from two opposed triangles
            # joined by a line.
            if state_name == self._creator.get_insertion_point():
                ctx.save()
                bp2 = BLOCK_PADDING/2
                ctx.move_to(-bp2, 0)
                ctx.line_to(-BLOCK_PADDING-bp2, -BLOCK_PADDING)
                ctx.line_to(bp2, -BLOCK_PADDING)
                ctx.line_to(-bp2, 0)

                ctx.line_to(-bp2, block_max_height-2*BLOCK_PADDING)
                ctx.line_to(bp2, block_max_height-BLOCK_PADDING)
                ctx.line_to(-BLOCK_PADDING-bp2, block_max_height-BLOCK_PADDING)
                ctx.line_to(-bp2, block_max_height-2*BLOCK_PADDING)

                ctx.line_to(-bp2, BLOCK_PADDING)
                ctx.set_source_rgb(1.0, 1.0, 0.0)
                ctx.stroke_preserve()
                ctx.fill()
                ctx.restore()


            event_list = tutorial.get_transition_dict(state_name).items()
            if event_list:
                local_height = (block_max_height - BLOCK_PADDING)\
                        /len(event_list) - BLOCK_PADDING
                ctx.save()
                for transition_name, transition in event_list:
                    origin = tuple(ctx.get_matrix())[-2:]
                    if self.click_pos and \
                       self.click_pos[0]-BLOCK_WIDTH<origin[0] and \
                       self.drag_pos[0]>origin[0]:
                        self.selection.add((transition_name, transition))
                    self.render_event(ctx, block_width, local_height,
                                      event=transition[0])
                    ctx.translate(0, local_height+BLOCK_PADDING)

                ctx.restore()
                ctx.translate(BLOCK_WIDTH, 0)

            if (not new_insert_point) and self.click_pos:
                origin = tuple(ctx.get_matrix())[-2:]
                if self.click_pos[0]<origin[0]:
                    new_insert_point = state_name

            if event_list and state_name != tutorial.END:
                # TODO: use marked path, to avoid infinite loops on recursive
                # tutorials.
                next_states = tutorial.get_following_states_dict(state_name)
                state_name = next_states.keys()[0]
                yield True
            else:
                break

        ctx.set_matrix(app_start)
        self._render_app_hints(ctx, cur_app)

        if self.click_pos:
            if not new_insert_point:
                new_insert_point = state_name

            self._creator.set_insertion_point(new_insert_point)

        yield False

    def _render_snapshot(self, ctx, elem):
        """
        Render the "simplified screenshot-like" representation of elements positions.
        """
        ctx.set_source_rgba(1.0, 1.0, 1.0, 0.5)
        ctx.rectangle(0, 0, SNAP_WIDTH, SNAP_HEIGHT)
        ctx.fill_preserve()
        ctx.stroke()

        if hasattr(elem, 'position'):
            pos = elem.position
            # FIXME this size approximation is fine, but I believe we could
            # do better.
            ctx.scale(SNAP_SCALE, SNAP_SCALE)
            ctx.rectangle(pos[0], pos[1], ACTION_WIDTH, ACTION_HEIGHT)
            ctx.fill_preserve()
            ctx.stroke()

    def _render_app_hints(self, ctx, appname):
        """
        Fetches the icon of the app related to current state and renders it on a
        separator, between states.
        """
        ctx.set_source_rgb(0.0, 0.0, 0.0)
        ctx.set_dash((1,1,0,0), 1)
        ctx.move_to(0, 0)
        ctx.line_to(0, self.alloc.height)
        ctx.stroke()
        ctx.set_dash(tuple(), 1)

        bundle_path = os.getenv("SUGAR_BUNDLE_PATH")
        if bundle_path:
            icon_path = activitybundle.ActivityBundle(bundle_path).get_icon()
            icon_rsvg = rsvg.Handle(icon_path)
            ctx.save()
            ctx.translate(-15, 0)
            ctx.scale(0.5, 0.5)
            icon_rsvg.render_cairo(ctx)
            ctx.restore()


    def render_action(self, ctx, width, height, action):
        """
        Renders the action block, along with the icon of the action tool.
        """
        ctx.save()
        inner_width = width-(BLOCK_CORNERS<<1)
        inner_height = height-(BLOCK_CORNERS<<1)

        paint_border = ctx.rel_line_to
        filling = cairo.LinearGradient(0, 0, 0, inner_height)
        if action not in self.selection:
            filling.add_color_stop_rgb(0.0, 0.7, 0.7, 1.0)
            filling.add_color_stop_rgb(1.0, 0.1, 0.1, 0.8)
        else:
            filling.add_color_stop_rgb(0.0, 0.4, 0.4, 0.8)
            filling.add_color_stop_rgb(1.0, 0.0, 0.0, 0.5)
        tracing = cairo.LinearGradient(0, 0, 0, inner_height)
        tracing.add_color_stop_rgb(0.0, 1.0, 1.0, 1.0)
        tracing.add_color_stop_rgb(1.0, 0.2, 0.2, 0.2)

        ctx.move_to(BLOCK_CORNERS, 0)
        paint_border(inner_width, 0)
        ctx.arc(inner_width+BLOCK_CORNERS, BLOCK_CORNERS,
                BLOCK_CORNERS, -PI2, 0.0)
        ctx.arc(inner_width+BLOCK_CORNERS, inner_height+BLOCK_CORNERS,
                BLOCK_CORNERS, 0.0, PI2)
        ctx.arc(BLOCK_CORNERS, inner_height+BLOCK_CORNERS, BLOCK_CORNERS,
                PI2, PI)
        ctx.arc(BLOCK_CORNERS, BLOCK_CORNERS, BLOCK_CORNERS, -PI, -PI2)

        ctx.set_source(tracing)
        ctx.stroke_preserve()
        ctx.set_source(filling)
        ctx.fill()

        addon_name = addon.get_name_from_type(type(action))
        # TODO use icon pool
        icon_name = addon.get_addon_meta(addon_name)['icon']
        rsvg_icon = rsvg.Handle(icon.get_icon_file_name(icon_name))
        ctx.save()
        ctx.translate(BLOCK_INNER_PAD, BLOCK_INNER_PAD)
        ctx.scale(0.5, 0.5)
        rsvg_icon.render_cairo(ctx)

        ctx.restore()

        ctx.translate(BLOCK_INNER_PAD, (height-SNAP_HEIGHT)/2)
        self._render_snapshot(ctx, action)

        ctx.restore()

    def render_event(self, ctx, width, height, event):
        """
        Renders the action block, along with the icon of the action tool.
        """
        ctx.save()
        inner_width = width-(BLOCK_CORNERS<<1)
        inner_height = height-(BLOCK_CORNERS<<1)

        filling = cairo.LinearGradient(0, 0, 0, inner_height)
        if event not in self.selection:
            filling.add_color_stop_rgb(0.0, 1.0, 0.8, 0.6)
            filling.add_color_stop_rgb(1.0, 1.0, 0.6, 0.2)
        else:
            filling.add_color_stop_rgb(0.0, 0.8, 0.6, 0.4)
            filling.add_color_stop_rgb(1.0, 0.6, 0.4, 0.1)
        tracing = cairo.LinearGradient(0, 0, 0, inner_height)
        tracing.add_color_stop_rgb(0.0, 1.0, 1.0, 1.0)
        tracing.add_color_stop_rgb(1.0, 0.3, 0.3, 0.3)

        ctx.move_to(BLOCK_CORNERS, 0)
        ctx.rel_line_to(inner_width, 0)
        ctx.rel_line_to(BLOCK_CORNERS, BLOCK_CORNERS)
        ctx.rel_line_to(0, inner_height)
        ctx.rel_line_to(-BLOCK_CORNERS, BLOCK_CORNERS)
        ctx.rel_line_to(-inner_width, 0)
        ctx.rel_line_to(-BLOCK_CORNERS, -BLOCK_CORNERS)
        ctx.rel_line_to(0, -inner_height)
        ctx.close_path()

        ctx.set_source(tracing)
        ctx.stroke_preserve()
        ctx.set_source(filling)
        ctx.fill()

        addon_name = addon.get_name_from_type(type(event))
        # TODO use icon pool
        if addon_name:
            icon_name = addon.get_addon_meta(addon_name)['icon']
            rsvg_icon = rsvg.Handle(icon.get_icon_file_name(icon_name))
            ctx.save()
            ctx.translate(BLOCK_INNER_PAD, BLOCK_INNER_PAD)
            ctx.scale(0.5, 0.5)
            rsvg_icon.render_cairo(ctx)

            ctx.restore()

        ctx.translate(BLOCK_INNER_PAD, (height-SNAP_HEIGHT)/2)
        self._render_snapshot(ctx, event)

        ctx.restore()

    def on_viewer_expose(self, widget, evt, tutorial):
        """
        Expose signal handler for the viewer's DrawingArea.
        This loops through tutorial and renders every action and transition of
        the "happy path".

        @param widget: the gtk.DrawingArea on which to draw
        @param evt: the gtk.gdk.Event containing an "expose" event
        @param tutorial: a tutorius FiniteStateMachine object to paint
        """
        ctx = widget.window.cairo_create()
        self.alloc = widget.get_allocation()
        ctx.set_source_pixmap(widget.window,
                              widget.allocation.x,
                              widget.allocation.y)

        # draw no more than our expose event intersects our child
        region = gtk.gdk.region_rectangle(widget.allocation)
        r = gtk.gdk.region_rectangle(evt.area)
        region.intersect(r)
        ctx.region (region)
        ctx.clip()
        ctx.paint()

        # padding internal to the widget, to draw the first half of the
        # activity app hint (the icon)
        ctx.translate(20, 0)
        ctx.translate(BLOCK_PADDING, BLOCK_PADDING)

        painter = self._paint_state(ctx, tutorial)
        while painter.next(): pass

        if self.click_pos and self.drag_pos:
            ctx.set_matrix(cairo.Matrix())
            ctx.rectangle(self.click_pos[0], self.click_pos[1],
                          self.drag_pos[0]-self.click_pos[0],
                          self.drag_pos[1]-self.click_pos[1])
            ctx.set_source_rgba(0, 0, 1, 0.5)
            ctx.fill_preserve()
            ctx.stroke()

        return False

    def _on_click(self, widget, evt):
        # the rendering pipeline will work out the click validation process
        self.drag_pos = None
        self.drag_pos = self.click_pos = evt.get_coords()
        widget.queue_draw()

        self.selection.clear()

    def _on_drag(self, widget, evt):
        self.drag_pos = evt.get_coords()
        widget.queue_draw()

    def _on_drag_end(self, widget, evt):
        self.click_pos = self.drag_pos = None
        widget.queue_draw()

    def _on_key_press(self, widget, evt):
        if evt.keyval == gtk.keysyms.BackSpace:
            # remove selection
            for name, obj in self.selection:
                if isinstance(obj, Action):
                    self._creator.delete_action(name)
                else:
                    self._creator.delete_state()
            self.selection.clear()
        widget.queue_draw()