/
tutor.py
1786 lines (1469 loc) · 59.9 KB
/
tutor.py
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#-------------------------------------------------------------------------------
#
# Copyright (c) 2007, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
#
# Author: David C. Morrill
# Date: 03/30/2007
#
# fixme:
# - Get custom tree view images.
# - Write a program to create a directory structure from a lesson plan file.
#
#-------------------------------------------------------------------------------
""" A framework for creating interactive Python tutorials.
"""
#-------------------------------------------------------------------------------
# Imports:
#-------------------------------------------------------------------------------
import sys
import os
import re
from string \
import capwords
from traits.api \
import HasPrivateTraits, HasTraits, File, Directory, Instance, Int, Str, \
List, Bool, Dict, Any, Property, Delegate, Button, cached_property
from traitsui.api \
import View, VGroup, HGroup, VSplit, HSplit, Tabbed, Item, Heading, \
Handler, ListEditor, CodeEditor, EnumEditor, HTMLEditor, \
TreeEditor, TitleEditor, ValueEditor, ShellEditor
from traitsui.menu \
import NoButtons
from traitsui.tree_node \
import TreeNode
from pyface.image_resource \
import ImageResource
try:
from traitsui.wx.extra.windows.ie_html_editor \
import IEHTMLEditor
from traitsui.wx.extra.windows.flash_editor \
import FlashEditor
except:
IEHTMLEditor = FlashEditor = None
#-------------------------------------------------------------------------------
# Constants:
#-------------------------------------------------------------------------------
# Correct program usage information:
Usage = """
Correct usage is: tutor.py [root_dir]
where:
root_dir = Path to root of the tutorial tree
If omitted, 'root_dir' defaults to the current directory."""
# The standard list editor used:
list_editor = ListEditor(
use_notebook = True,
deletable = False,
page_name = '.title',
export = 'DockWindowShell',
dock_style = 'fixed'
)
# The standard code snippet editor used:
snippet_editor = ListEditor(
use_notebook = True,
deletable = False,
page_name = '.title',
export = 'DockWindowShell',
dock_style = 'tab',
selected = 'snippet'
)
# Regular expressions used to match section directories:
dir_pat1 = re.compile( r'^(\d\d\d\d)_(.*)$' )
dir_pat2 = re.compile( r'^(.*)_(\d+\.\d+)$' )
# Regular expression used to match section header in a Python source file:
section_pat1 = re.compile( r'^#-*\[(.*)\]' ) # Normal
section_pat2 = re.compile( r'^#-*<(.*)>' ) # Hidden
section_pat3 = re.compile( r'^#-*\((.*)\)' ) # Description
# Regular expression used to extract item titles from URLs:
url_pat1 = re.compile( r'^(.*)\[(.*)\](.*)$' ) # Normal
# Is this running on the Windows platform?
is_windows = (sys.platform in ( 'win32', 'win64' ))
# Python file section types:
IsCode = 0
IsHiddenCode = 1
IsDescription = 2
# HTML template for a default lecture:
DefaultLecture = """<html>
<head>
</head>
<body>
<p>This section contains the following topics:</p>
<ul>
%s
</ul>
</body>
</html>
"""
# HTML template for displaying a .wmv/.avi movie file:
WMVMovieTemplate = """<html>
<head>
</head>
<body>
<p><object classid="clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715">
<param name="FileName" value="%s">
<param name="AutoStart" value="true">
<param name="ShowTracker" value="true">
<param name="ShowControls" value="true">
<param name="ShowGotoBar" value="false">
<param name="ShowDisplay" value="false">
<param name="ShowStatusBar" value="false">
<param name="AutoSize" value="true">
<embed src="%s" AutoStart="true" ShowTracker="true" ShowControls="true" ShowGotoBar="false" ShowDisplay="false" ShowStatusBar="false" AutoSize="true" pluginspage="http://www.microsoft.com/windows/windowsmedia/download/"></object></p>
</body>
</html>
"""
# HTML template for displaying a QuickTime.mov movie file:
QTMovieTemplate = """<html>
<head>
</head>
<body>
<p><object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="100%%" height="100%%">
<param name="src" value="file:///%s">
<param name="scale" value="aspect">
<param name="autoplay" value="true">
<param name="loop" value="false">
<param name="controller" value="true">
<embed src="file:///%s" width="100%%" height="100%%" scale="aspect" autoplay="true" loop="false" controller="true" pluginspage="http://www.apple.com/quicktime/download"></object></p>
</body>
</html>
"""
# HTML template for displaying an image file:
ImageTemplate = """<html>
<head>
</head>
<body>
<img src="%s">
</body>
</html>
"""
# HTML template for playing an MP3 audio file:
MP3Template = """<html>
<head>
<bgsound src="%s">
</head>
<body>
<p> </p>
</body>
</html>
"""
#-------------------------------------------------------------------------------
# Returns the contents of a specified text file (or None):
#-------------------------------------------------------------------------------
def read_file ( path, mode = 'rb' ):
""" Returns the contents of a specified text file (or None).
"""
fh = result = None
try:
fh = file( path, mode )
result = fh.read()
except:
pass
if fh is not None:
try:
fh.close()
except:
pass
return result
#-------------------------------------------------------------------------------
# Creates a title from a specified string:
#-------------------------------------------------------------------------------
def title_for ( title ):
""" Creates a title from a specified string.
"""
return capwords( title.replace( '_', ' ' ) )
#-------------------------------------------------------------------------------
# Returns a relative CSS style sheet path for a specified path and parent
# section:
#-------------------------------------------------------------------------------
def css_path_for ( path, parent ):
""" Returns a relative CSS style sheet path for a specified path and parent
section.
"""
if os.path.isfile( os.path.join( path, 'default.css' ) ):
return 'default.css'
if parent is not None:
result = parent.css_path
if result != '':
if path != parent.path:
result = os.path.join( '..', result )
return result
return ''
#-------------------------------------------------------------------------------
# 'StdOut' class:
#-------------------------------------------------------------------------------
class StdOut ( object ):
""" Simulate stdout, but redirect the output to the 'output' string
supplied by some 'owner' object.
"""
def __init__ ( self, owner ):
self.owner = owner
def write ( self, data ):
""" Adds the specified data to the output log.
"""
self.owner.output += data
def flush ( self ):
""" Flushes all current data to the output log.
"""
pass
#-------------------------------------------------------------------------------
# 'NoDemo' class:
#-------------------------------------------------------------------------------
class NoDemo ( HasPrivateTraits ):
#-- Traits View Definitions ------------------------------------------------
view = View(
Heading( 'No demo defined for this lab.' ),
resizable = True
)
#-------------------------------------------------------------------------------
# 'DemoPane' class:
#-------------------------------------------------------------------------------
class DemoPane ( HasPrivateTraits ):
""" Displays the contents of a Python lab's *demo* value.
"""
#-- Trait Definitions ------------------------------------------------------
demo = Instance( HasTraits, factory = NoDemo )
#-- Traits View Definitions ------------------------------------------------
view = View(
Item( 'demo',
id = 'demo',
show_label = False,
style = 'custom',
resizable = True
),
id = 'enthought.tutor.demo',
resizable = True
)
#-------------------------------------------------------------------------------
# 'ATutorialItem' class:
#-------------------------------------------------------------------------------
class ATutorialItem ( HasPrivateTraits ):
""" Defines the abstract base class for each type of item (HTML, Flash,
text, code) displayed within the tutor.
"""
#-- Traits Definitions -----------------------------------------------------
# The title for the item:
title = Str
# The path to the item:
path = File
# The displayable content for the item:
content = Property
#-------------------------------------------------------------------------------
# 'ADescriptionItem' class:
#-------------------------------------------------------------------------------
class ADescriptionItem ( ATutorialItem ):
""" Defines a common base class for all description items.
"""
#-- Event Handlers ---------------------------------------------------------
def _path_changed ( self, path ):
""" Sets the title for the item based on the item's path name.
"""
self.title = title_for( os.path.splitext( os.path.basename(
path ) )[0] )
#-------------------------------------------------------------------------------
# 'HTMLItem' class:
#-------------------------------------------------------------------------------
class HTMLItem ( ADescriptionItem ):
""" Defines a class used for displaying a single HTML page within the tutor
using the default Traits HTML editor.
"""
#-- Traits Definitions -----------------------------------------------------
url = Str
#-- Traits View Definitions ------------------------------------------------
view = View(
Item( 'content',
style = 'readonly',
show_label = False,
editor = HTMLEditor()
)
)
#-- Event Handlers ---------------------------------------------------------
def _url_changed ( self, url ):
""" Sets the item title when the 'url' is changed.
"""
match = url_pat1.match( url )
if match is not None:
title = match.group(2).strip()
else:
title = url.strip()
col = title.rfind( '/' )
if col >= 0:
title = os.path.splitext( title[ col + 1: ] )[0]
self.title = title
#-- Property Implementations -----------------------------------------------
@cached_property
def _get_content ( self ):
""" Returns the item content.
"""
url = self.url
if url != '':
match = url_pat1.match( url )
if match is not None:
url = match.group(1) + match.group(3)
return url
return read_file( self.path )
def _set_content ( self, content ):
""" Sets the item content.
"""
self._content = content
#-------------------------------------------------------------------------------
# 'HTMLStrItem' class:
#-------------------------------------------------------------------------------
class HTMLStrItem ( HTMLItem ):
""" Defines a class used for displaying a single HTML text string within
the tutor using the default Traits HTML editor.
"""
# Make the content a real trait rather than a property:
content = Str
#-------------------------------------------------------------------------------
# 'IEHTMLItem' class:
#-------------------------------------------------------------------------------
class IEHTMLItem ( HTMLItem ):
""" Defines a class used for displaying a single HTML page within the tutor
using the Traits Internet Explorer HTML editor.
"""
#-- Traits View Definitions ------------------------------------------------
view = View(
Item( 'content',
style = 'readonly',
show_label = False,
editor = IEHTMLEditor()
)
)
#-------------------------------------------------------------------------------
# 'IEHTMLStrItem' class:
#-------------------------------------------------------------------------------
class IEHTMLStrItem ( IEHTMLItem ):
""" Defines a class used for displaying a single HTML text string within
the tutor using the Traits Internet Explorer HTML editor.
"""
# Make the content a real trait rather than a property:
content = Str
#-------------------------------------------------------------------------------
# 'FlashItem' class:
#-------------------------------------------------------------------------------
class FlashItem ( HTMLItem ):
""" Defines a class used for displaying a Flash-based animation or video
within the tutor.
"""
#-- Traits View Definitions ------------------------------------------------
view = View(
Item( 'content',
style = 'readonly',
show_label = False,
editor = FlashEditor()
)
)
#-------------------------------------------------------------------------------
# 'TextItem' class:
#-------------------------------------------------------------------------------
class TextItem ( ADescriptionItem ):
""" Defines a class used for displaying a text file within the tutor.
"""
#-- Traits View Definitions ------------------------------------------------
view = View(
Item( 'content',
style = 'readonly',
show_label = False,
editor = CodeEditor( show_line_numbers = False,
selected_color = 0xFFFFFF )
)
)
#-- Property Implementations -----------------------------------------------
@cached_property
def _get_content ( self ):
""" Returns the item content.
"""
return read_file( self.path )
#-------------------------------------------------------------------------------
# 'TextStrItem' class:
#-------------------------------------------------------------------------------
class TextStrItem ( TextItem ):
""" Defines a class used for displaying a text file within the tutor.
"""
# Make the content a real trait, rather than a property:
content = Str
#-------------------------------------------------------------------------------
# 'CodeItem' class:
#-------------------------------------------------------------------------------
class CodeItem ( ATutorialItem ):
""" Defines a class used for displaying a Python source code fragment
within the tutor.
"""
#-- Trait Definitions ------------------------------------------------------
# The displayable content for the item (override):
content = Str
# The starting line of the code snippet within the original file:
start_line = Int
# The currently selected line:
selected_line = Int
# Should this section normally be hidden?
hidden = Bool
#-- Traits View Definitions ------------------------------------------------
view = View(
Item( 'content',
style = 'custom',
show_label = False,
editor = CodeEditor( selected_line = 'selected_line' )
)
)
#-------------------------------------------------------------------------------
# 'ASection' abstract base class:
#-------------------------------------------------------------------------------
class ASection ( HasPrivateTraits ):
""" Defines an abstract base class for a single section of a tutorial.
"""
#-- Traits Definitions -----------------------------------------------------
# The title of the section:
title = Str
# The path to this section:
path = Directory
# The parent section of this section (if any):
parent = Instance( 'ASection' )
# Optional table of contents (can be used to define/locate the subsections):
toc = List( Str )
# The path to the CSS style sheet to use for this section:
css_path = Property
# The list of subsections contained in this section:
subsections = Property # List( ASection )
# This section can be executed:
is_runnable = Bool( True )
# Should the Python code be automatically executed on start-up?
auto_run = Bool( False )
#-- Property Implementations -----------------------------------------------
@cached_property
def _get_subsections ( self ):
""" Returns the subsections for this section:
"""
if len( self.toc ) > 0:
self._load_toc()
else:
self._load_dirs()
# Return the cached list of sections:
return self._subsections
@cached_property
def _get_css_path ( self ):
""" Returns the path to the CSS style sheet for this section.
"""
return css_path_for( self.path, self.parent )
#-- Private Methods --------------------------------------------------------
def _load_dirs ( self ):
""" Defines the section's subsections by analyzing all of the section's
sub-directories.
"""
# No value cached yet:
dirs = []
path = self.path
# Find every sub-directory whose name begins with a number of the
# form ddd, or ends with a number of the form _ddd.ddd (used for
# sorting them into the correct presentation order):
for name in os.listdir( path ):
dir = os.path.join( path, name )
if os.path.isdir( dir ):
match = dir_pat1.match( name )
if match is not None:
dirs.append( ( float( match.group(1) ),
match.group(2), dir ) )
else:
match = dir_pat2.match( name )
if match is not None:
dirs.append( ( float( match.group(2) ),
match.group(1), dir ) )
# Sort the directories by their index value:
dirs.sort( lambda l, r: cmp( l[0], r[0] ) )
# Create the appropriate type of section for each valid directory:
self._subsections = [
sf.section for sf in [
SectionFactory( title = title_for( title ),
parent = self ).set(
path = dir )
for index, title, dir in dirs
] if sf.section is not None
]
def _load_toc ( self ):
""" Defines the section's subsections by finding matches for the items
defined in the section's table of contents.
"""
toc = self.toc
base_names = [ item.split( ':', 1 )[0] for item in toc ]
subsections = [ None ] * len( base_names )
path = self.path
# Classify all file names that match a base name in the table of
# contents:
for name in os.listdir( path ):
try:
base_name = os.path.splitext( os.path.basename( name ) )[0]
index = base_names.index( base_name )
if subsections[ index ] is None:
subsections[ index ] = []
subsections[ index ].append( name )
except:
pass
# Try to convert each group of names into a section:
for i, names in enumerate( subsections ):
# Only process items for which we found at least one matching file
# name:
if names is not None:
# Get the title for the section from its table of contents
# entry:
parts = toc[i].split( ':', 1 )
if len( parts ) == 1:
title = title_for( parts[0].strip() )
else:
title = parts[1].strip()
# Handle an item with one file which is a directory as a normal
# section:
if len( names ) == 1:
dir = os.path.join( path, names[0] )
if os.path.isdir( dir ):
subsections[i] = SectionFactory( title = title,
parent = self ).set(
path = dir ).section
continue
# Otherwise, create a section from the list of matching files:
subsections[i] = SectionFactory( title = title,
parent = self,
files = names ).set(
path = path ).section
# Set the subsections to the non-None values that are left:
self._subsections = [ subsection for subsection in subsections
if subsection is not None ]
#-------------------------------------------------------------------------------
# 'Lecture' class:
#-------------------------------------------------------------------------------
class Lecture ( ASection ):
""" Defines a lecture, which is a section of a tutorial with descriptive
information, but no associated Python code. Can be used to provide
course overviews, introductory sections, or lead-ins to follow-on
lessons or labs.
"""
#-- Trait Definitions-------------------------------------------------------
# The list of descriptive items for the lecture:
descriptions = List( ATutorialItem )
# This section can be executed (override):
is_runnable = False
#-- Traits View Definitions ------------------------------------------------
view = View(
Item( 'descriptions',
style = 'custom',
show_label = False,
editor = list_editor
),
id = 'enthought.tutor.lecture'
)
#-------------------------------------------------------------------------------
# 'LabHandler' class:
#-------------------------------------------------------------------------------
class LabHandler ( Handler ):
""" Defines the controller functions for the Lab view.
"""
def init ( self, info ):
""" Handles initialization of the view.
"""
# Run the associated Python code if the 'auto-run' feature is enabled:
if info.object.auto_run:
info.object.run_code()
#-------------------------------------------------------------------------------
# 'Lab' class:
#-------------------------------------------------------------------------------
class Lab ( ASection ):
""" Defines a lab, which is a section of a tutorial with only Python code.
This type of section might typically follow a lecture which introduced
the code being worked on in the lab.
"""
#-- Trait Definitions-------------------------------------------------------
# The set-up code (if any) for the lab:
setup = Instance( CodeItem )
# The list of code items for the lab:
snippets = List( CodeItem )
# The list of visible code items for the lab:
visible_snippets = Property( depends_on = 'visible', cached = True )
# The currently selected snippet:
snippet = Instance( CodeItem )
# Should normally hidden code items be shown?
visible = Bool( False )
# The dictionary containing the items from the Python code execution:
values = Dict #Any( {} )
# The run Python code button:
run = Button( image = ImageResource( 'run' ), height_padding = 1 )
# User error message:
message = Str
# The output produced while the program is running:
output = Str
# The current demo pane (if any):
demo = Instance( DemoPane, () )
#-- Traits View Definitions ------------------------------------------------
view = View(
VSplit(
VGroup(
Item( 'visible_snippets',
style = 'custom',
show_label = False,
editor = snippet_editor
),
HGroup(
Item( 'run',
style = 'custom',
show_label = False,
tooltip = 'Run the Python code'
),
'_',
Item( 'message',
springy = True,
show_label = False,
editor = TitleEditor()
),
'_',
Item( 'visible',
label = 'View hidden sections'
)
),
),
Tabbed(
Item( 'values',
id = 'values_1',
label = 'Shell',
editor = ShellEditor( share = True ),
dock = 'tab',
export = 'DockWindowShell'
),
Item( 'values',
id = 'values_2',
editor = ValueEditor(),
dock = 'tab',
export = 'DockWindowShell'
),
Item( 'output',
style = 'readonly',
editor = CodeEditor( show_line_numbers = False,
selected_color = 0xFFFFFF ),
dock = 'tab',
export = 'DockWindowShell'
),
Item( 'demo',
id = 'demo',
style = 'custom',
resizable = True,
dock = 'tab',
export = 'DockWindowShell'
),
show_labels = False,
),
id = 'splitter',
),
id = 'enthought.tutor.lab',
handler = LabHandler
)
#-- Event Handlers ---------------------------------------------------------
def _run_changed ( self ):
""" Runs the current set of snippet code.
"""
self.run_code()
#-- Property Implementations -----------------------------------------------
@cached_property
def _get_visible_snippets ( self ):
""" Returns the list of code items that are currently visible.
"""
if self.visible:
return self.snippets
return [ snippet for snippet in self.snippets if (not snippet.hidden) ]
#-- Public Methods ---------------------------------------------------------
def run_code ( self ):
""" Runs all of the code snippets associated with the section.
"""
# Reconstruct the lab code from the current set of code snippets:
start_line = 1
module = ''
for snippet in self.snippets:
snippet.start_line = start_line
module = '%s\n\n%s' % ( module, snippet.content )
start_line += (snippet.content.count( '\n' ) + 2)
# Reset any syntax error and message log values:
self.message = self.output = ''
# Redirect standard out and error to the message log:
stdout, stderr = sys.stdout, sys.stderr
sys.stdout = sys.stderr = StdOut( self )
try:
try:
# Get the execution context dictionary:
values = self.values
# Clear out any special variables defined by the last run:
for name in ( 'demo', 'popup' ):
if isinstance( values.get( name ), HasTraits ):
del values[ name ]
# Execute the current lab code:
exec module[2:] in values, values
# fixme: Hack trying to update the Traits UI view of the dict.
self.values = {}
self.values = values
# Handle a 'demo' value being defined:
demo = values.get( 'demo' )
if not isinstance( demo, HasTraits ):
demo = NoDemo()
self.demo.demo = demo
# Handle a 'popup' value being defined:
popup = values.get( 'popup' )
if isinstance( popup, HasTraits ):
popup.edit_traits( kind = 'livemodal' )
except SyntaxError, excp:
# Convert the line number of the syntax error from one in the
# composite module to one in the appropriate code snippet:
line = excp.lineno
if line is not None:
snippet = self.snippets[0]
for s in self.snippets:
if s.start_line > line:
break
snippet = s
line -= (snippet.start_line - 1)
# Highlight the line in error:
snippet.selected_line = line
# Select the correct code snippet:
self.snippet = snippet
# Display the syntax error message:
self.message = '%s in column %s of line %s' % (
excp.msg.capitalize(), excp.offset, line )
else:
# Display the syntax error message without line # info:
self.message = excp.msg.capitalize()
except:
import traceback
traceback.print_exc()
finally:
# Restore standard out and error to their original values:
sys.stdout, sys.stderr = stdout, stderr
#-------------------------------------------------------------------------------
# 'Lesson' class:
#-------------------------------------------------------------------------------
class Lesson ( Lab ):
""" Defines a lesson, which is a section of a tutorial with both descriptive
information and associated Python code.
"""
#-- Trait Definitions-------------------------------------------------------
# The list of descriptive items for the lesson:
descriptions = List( ATutorialItem )
#-- Traits View Definitions ------------------------------------------------
view = View(
HSplit(
Item( 'descriptions',
label = 'Lesson',
style = 'custom',
show_label = False,
dock = 'horizontal',
editor = list_editor
),
VSplit(
VGroup(
Item( 'visible_snippets',
style = 'custom',
show_label = False,
editor = snippet_editor
),
HGroup(
Item( 'run',
style = 'custom',
show_label = False,
tooltip = 'Run the Python code'
),
'_',
Item( 'message',
springy = True,
show_label = False,
editor = TitleEditor()
),
'_',
Item( 'visible',
label = 'View hidden sections'
)
),
label = 'Lab',
dock = 'horizontal'
),
Tabbed(
Item( 'values',
id = 'values_1',
label = 'Shell',
editor = ShellEditor( share = True ),
dock = 'tab',
export = 'DockWindowShell'
),
Item( 'values',
id = 'values_2',
editor = ValueEditor(),
dock = 'tab',
export = 'DockWindowShell'
),
Item( 'output',
style = 'readonly',
editor = CodeEditor( show_line_numbers = False,
selected_color = 0xFFFFFF ),
dock = 'tab',
export = 'DockWindowShell'
),
Item( 'demo',
id = 'demo',
style = 'custom',
resizable = True,