Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2@file 

3@brief Snap rendering in a notebook. 

4""" 

5import uuid 

6import os 

7import glob 

8from .snap import __file__ as location_js_snap 

9 

10 

11class RenderSnapRaw: 

12 """ 

13 Renders `Snap <https://snap.berkeley.edu/>`_ using javascript. 

14 """ 

15 

16 def __init__(self, width="1000", height="600", divid=None, filename=None): 

17 """ 

18 initialize 

19 

20 @param width (str) width 

21 @param height (str) height 

22 @param divid (str|None) id of the div 

23 @param filename (str|None) filename 

24 """ 

25 if divid == "scratch_div_id": 

26 # we should use a static counter but it 

27 # is very unlikely more than one snap will be added to 

28 # a notebook 

29 divid += "_%s" % str(uuid.uuid4()).replace("-", "") 

30 

31 self.filename = filename 

32 self.divid = divid if divid else str(uuid.uuid4()).replace("-", "") 

33 self.width = width 

34 self.height = height 

35 

36 def generate_html(self): 

37 """ 

38 Return a couple (HTML, JS). 

39 """ 

40 w = self.width 

41 h = self.height 

42 divid = self.divid 

43 

44 js_path = os.path.dirname(location_js_snap) 

45 files = [os.path.split(_)[-1] for _ in glob.glob(js_path + "/*.js")] 

46 path = "/static/snap/" 

47 js_libs = [path + _ for _ in files] 

48 

49 html_src = """ 

50 <div id="__DIV__div" style="position:relative; width:__WIDTH__px; height:__HEIGHT__px;"> 

51 Snap showing up soon... 

52 <canvas id="__DIV__" style="width:__WIDTH__px; height:__HEIGHT__px; position:relative; " /> 

53 </div> 

54 """.replace("__DIV__", divid).replace("__WIDTH__", w).replace("__HEIGHT__", h) 

55 test_js = """<script> 

56 var world__DIV__; 

57 function loop__DIV__() { 

58 world__DIV__.doOneCycle(); 

59 } 

60 function start_snap__DIV__() { 

61 var sec = document.getElementsByClassName("__DIV__div"); 

62 sec.innerHTML = "loading..."; 

63 world__DIV__ = new WorldMorph(document.getElementById('__DIV__')); 

64 world__DIV__.worldCanvas.focus(); 

65 new IDE_Morph().openIn(world__DIV__); 

66 setInterval(loop__DIV__, 1); 

67 sec.innerHTML = ""; 

68 } 

69 window.setTimeout(start_snap__DIV__,500); 

70 </script> 

71 """.replace("__DIV__", divid) 

72 libs = ['<script type="text/javascript" src="{0}"></script>'.format(le) 

73 for le in js_libs] 

74 libs = "\n".join(libs) 

75 

76 return html_src, libs + "\n" + test_js 

77 

78 

79class RenderSnap(RenderSnapRaw): 

80 """ 

81 Render Snap using javascript, outputs only HTML. 

82 """ 

83 

84 def _repr_html_(self): 

85 ht, js = self.generate_html() 

86 ht += "{0}".format(js) 

87 return ht