Builder/RightGtkView.js
[app.Builder.js] / Builder / RightGtkView.js
1 //<script type="text/javascript">
2 Gio = imports.gi.Gio;
3 Gtk = imports.gi.Gtk;
4 Gdk = imports.gi.Gdk;
5 GObject = imports.gi.GObject;
6  
7
8 /**
9 * we use a hidden window to render the created dialog...
10 * then use snapshot to render it to an image...
11
12 */
13  
14
15 XObject = imports.XObject.XObject;
16 File = imports.File.File;
17 console = imports.console;
18
19 LeftTree = imports.Builder.LeftTree.LeftTree ;
20 LeftPanel = imports.Builder.LeftPanel.LeftPanel;
21  //console.dump(imports.Builder.LeftTree);
22  //Seed.quit();
23
24 RightGtkView = new XObject({
25         xtype : Gtk.VBox,
26         lastSrc : '',
27         pack : [ 'append_page', new Gtk.Label({ label : "Gtk View" })  ],
28         items : [
29         
30             {
31                 xtype: Gtk.HBox,
32                 pack : [ 'pack_start', false, true, 0 ],
33                 items : [       
34                     {
35                         
36                         
37                         xtype: Gtk.Button,
38                         label : 'Show in New Window',
39                         pack : [ 'pack_start', false, false, 0 ],
40                         listeners : {
41                             // pressed...
42                             'button-press-event' : function(w, ev ){
43                                 /// dump..
44                                 RightGtkView.showInWindow();
45                                 return true;
46                                 // show the MidPropTree..
47                             }
48                           
49                         }
50                     }
51                 ]
52             }, 
53             {
54             
55                      
56                 renderedData : false, 
57                 xtype: Gtk.ScrolledWindow,
58                 id: 'view-sw',
59                 smooth_scroll : true,
60                 shadow_type : Gtk.ShadowType.IN ,
61                 init : function() {
62                     XObject.prototype.init.call(this); 
63                      
64                     this.el.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC);
65                 },
66                 
67                 items : [
68                     {
69                         
70                         id : 'view-vbox',
71                         xtype : Gtk.Viewport,
72                         init : function () {
73                             XObject.prototype.init.call(this); 
74                             this.el.set_hadjustment(this.parent.el.get_hadjustment());
75                             this.el.set_vadjustment(this.parent.el.get_vadjustment());
76                                 
77                         },
78                         packing : ['add' ],
79                         items: [
80                             {
81                                 id : 'view',
82                                 xtype : function() {
83                                     return new Gtk.Image.from_stock (Gtk.STOCK_HOME, 100) 
84
85                                 },
86                                 packing : ['add' ],
87                                 ready : false,
88                                 init : function() {
89                                     XObject.prototype.init.call(this); 
90                                     // fixme!
91                                    
92                                     Gtk.drag_dest_set
93                                     (
94                                             this.el,              /* widget that will accept a drop */
95                                             Gtk.DestDefaults.MOTION  | Gtk.DestDefaults.HIGHLIGHT,
96                                             null,            /* lists of target to support */
97                                             0,              /* size of list */
98                                             Gdk.DragAction.COPY         /* what to do with data after dropped */
99                                     );
100                                     
101                                    // print("RB: TARGETS : " + LeftTree.atoms["STRING"]);
102                                     Gtk.drag_dest_set_target_list(this.el, LeftTree.targetList);
103                                     //Gtk.drag_dest_add_text_targets(this.el);
104                                 },   
105                                 listeners : {
106                                     
107                                       
108                                     
109                                     "drag-leave" : function () {
110                                         Seed.print("TARGET: drag-leave");
111                                         // stop monitoring of mouse montion in rendering..
112                                         return true;
113                                     },
114                                     'drag-motion' : function (w, ctx,  x,   y,   time, ud) 
115                                     {
116                                         
117                                     
118                                        // console.log('DRAG MOTION'); 
119                                         // status:
120                                         // if lastCurrentNode == this.currentNode.. -- don't change anything..
121                                          
122                                         
123                                         // A) find out from drag all the places that node could be dropped.
124                                         var src = Gtk.drag_get_source_widget(ctx);
125                                         if (!src.dropList) {
126                                             Gdk.drag_status(ctx, 0, time);
127                                             return true;
128                                         }
129                                         // b) get what we are over.. (from activeNode)
130                                         // tree is empty.. - list should be correct..
131                                         if (!LeftTree.get('model').currentTree) {
132                                             Gdk.drag_status(ctx, Gdk.DragAction.COPY,time);
133                                             return true;
134                                             
135                                         }
136                                         // c) ask tree where it should be dropped... - eg. parent.. (after node ontop)
137                                         var activeNode = this.getActiveNode(x, y);
138                                         
139                                         
140                                         var tg = LeftTree.get('model').findDropNode(activeNode, src.dropList);
141                                         console.dump(tg);
142                                         if (!tg.length) {
143                                             Gdk.drag_status(ctx, 0,time);
144                                             LeftTree.get('view').highlight(false);
145                                             return true;
146                                         }
147                                          
148                                         // if we have a target..
149                                         // -> highlight it! (in browser)
150                                         // -> highlight it! (in tree)
151                                         
152                                         Gdk.drag_status(ctx, Gdk.DragAction.COPY,time);
153                                         LeftTree.get('view').highlight(tg);
154                                         this.targetData = tg;
155                                         // for tree we should handle this...
156                                         return true;
157                                         
158                                     },
159                                     "drag-drop"  : function (w, ctx,x,y,time, ud) 
160                                     {
161                                                 
162                                         Seed.print("TARGET: drag-drop");
163                                         is_valid_drop_site = true;
164                                         
165                                          
166                                         Gtk.drag_get_data
167                                         (
168                                                 w,         /* will receive 'drag-data-received' signal */
169                                                 ctx,        /* represents the current state of the DnD */
170                                                 LeftTree.atoms["STRING"],    /* the target type we want */
171                                                 time            /* time stamp */
172                                         );
173                                         
174                                         
175                                         /* No target offered by source => error */
176                                        
177
178                                         return  is_valid_drop_site;
179                                         
180
181                                     },
182                                     "drag-data-received" : function (w, ctx,  x,  y, sel_data,  target_type,  time, ud) 
183                                     {
184                                         Seed.print("GtkView: drag-data-received");
185                                         var delete_selection_data = false;
186                                         var dnd_success = false;
187                                         /* Deal with what we are given from source */
188                                         if( sel_data && sel_data.length ) {
189                                             
190                                             if (ctx.action == Gdk.DragAction.ASK)  {
191                                                 /* Ask the user to move or copy, then set the ctx action. */
192                                             }
193
194                                             if (ctx.action == Gdk.DragAction.MOVE) {
195                                                 delete_selection_data = true;
196                                             }
197                                             var source = Gtk.drag_get_source_widget(ctx);
198
199                                             Seed.print("Browser: source.DRAGDATA? " + source.dragData);
200                                             if (this.targetData) {
201                                                 Seed.print(this.targetData);
202                                                 LeftTree.get('model').dropNode(this.targetData,  source.dragData);
203                                             }
204                                             
205                                             
206                                             
207                                             dnd_success = true;
208                  
209                                         }
210
211                                         if (dnd_success == false)
212                                         {
213                                                 Seed.print ("DnD data transfer failed!\n");
214                                         }
215                                         
216                                         Gtk.drag_finish (ctx, dnd_success, delete_selection_data, time);
217                                         return true;
218                                     }
219                                     
220                                    //'line-mark-activated' : line_mark_activated,
221                                    
222                                     
223                                 },
224                                  
225                                 getActiveNode : function(x,y)
226                                 {
227                                    // workout what node is here..
228                                     return '0'; // top..
229                                 }
230                             }
231                         ]
232                     }
233                 ]
234             }
235                 
236         ],
237         
238         showInWindow: function ()
239         {
240             var src= this.lastSrc;
241             if (!this.lastSrc.length) {
242                 return;
243             }
244             var x = new imports.sandbox.Context();
245             x.add_globals();
246             //print(src);
247             try {
248                 Seed.check_syntax('var e = ' + src);
249                 x.eval(src);
250             } catch( e) {
251                 print(e.message || e.toString());
252                 console.dump(e);
253                 if (e.line) {
254                     var lines = src.split("\n");
255                     var start = Math.max(0, e.line - 10);
256                     var end = Math.min(lines.length, e.line + 10);
257                     for (var i =start ; i < end; i++) {
258                         if (i == e.line) {
259                             print(">>>>>" + lines[i]);
260                             continue;
261                         }
262                         print(lines[i]);
263                     }
264                     
265                 }
266                 
267                 return;
268             }
269              
270             var _top = x.get_global_object()._top;
271             
272             _top.el.set_screen(Gdk.Screen.get_default()); // just in case..
273             _top.el.show_all();
274             if (_top.el.popup) {
275                 _top.el.popup(null, null, null, null, 3, null);
276             }
277         },
278         
279         buildJS: function(data,withDebug) {
280             var i = [ 'Gtk', 'Gdk', 'Pango', 'GLib', 'Gio', 'GObject', 'GtkSource', 'WebKit' ];
281             var src = "";
282             i.forEach(function(e) {
283                 src += e+" = imports.gi." + e +";\n";
284             });
285             src += "console = imports.console;\n"; // path?!!?
286             src += "XObject = imports.XObject.XObject;\n"; // path?!!?
287             if (withDebug) {
288                 src += "XObject.debug=true;\n"; 
289             }
290             
291             
292             src += '_top=new XObject('+ this.mungeToString(data) + ')\n;';
293             src += '_top.init();\n';
294             File.write('/tmp/BuilderGtkView.js', src);
295             print("Test code  in /tmp/BuilderGtkView.js");
296             this.lastSrc = src;
297             return src;
298         },
299         
300         renderJS : function(data, withDebug)
301         {
302             // can we mess with data?!?!?
303             
304             /**
305              * first effort..
306              * sandbox it? - nope then will have dificulting passing. stuff aruond..
307              * 
308              */
309             if (!data) {
310                  return; 
311             }
312             var src = this.buildJS(data,withDebug);
313             var x = new imports.sandbox.Context();
314             x.add_globals();
315             //x.get_global_object().a = "hello world";
316             
317             try {
318                 Seed.check_syntax('var e = ' + src);
319                 x.eval(src);
320             } catch( e) {
321                 if (!withDebug) {
322                    return this.renderJS(data,true);
323                 }
324                 print(e.message || e.toString());
325                 console.dump(e);
326                 return;
327             }
328             
329             var r = new Gdk.Rectangle();
330             var _top = x.get_global_object()._top;
331             
332             _top.el.set_screen(Gdk.Screen.get_default()); // just in case..
333             _top.el.show_all();
334             if (_top.el.popup) {
335                 _top.el.popup(null, null, null, null, 3, null);
336             }
337             
338             
339             
340             var pb = _top.el.get_snapshot(r);
341             if (!pb) {
342                 return;
343             }
344             _top.el.hide();
345             _top.el.destroy();
346             x._top = false;
347             var Window = imports.Builder.Window.Window;
348             var gc = new Gdk.GC.c_new(Window.el.window);
349                 
350                 // 10 points all round..
351             var full = new Gdk.Pixmap.c_new (Window.el.window, r.width+20, r.height+20, pb.get_depth());
352             // draw a white background..
353            // gc.set_rgb_fg_color({ red: 0, white: 0, black : 0 });
354             Gdk.draw_rectangle(full, gc, true, 0, 0, r.width+20, r.height+20);
355             // paint image..
356             Gdk.draw_drawable (full, gc, pb, 0, 0, 10, 10, r.width, r.height);
357             // boxes..
358             //gc.set_rgb_fg_color({ red: 255, white: 255, black : 255 });
359             Gdk.draw_rectangle(full, gc, true, 0, 0, 10, 10);
360             this.get('view').el.set_from_pixmap(full, null);
361             //this.get('view-vbox').el.set_size_request( r.width+20, r.height+20);
362             //var img = new Gtk.Image.from_file("/home/alan/solarpanels.jpeg");
363             
364             
365             
366         },
367         mungeToString:  function(obj, isListener, pad)
368         {
369             pad = pad || '';
370             var keys = [];
371             var isArray = false;
372             isListener = isListener || false;
373             
374             // am I munging a object or array...
375             if (obj.constructor.toString() === Array.toString()) {
376                 for (var i= 0; i < obj.length; i++) {
377                     keys.push(i);
378                 }
379                 isArray = true;
380             } else {
381                 for (var i in obj) {
382                     keys.push(i);
383                 }
384             }
385             
386             
387             var els = []; 
388             var skip = [];
389             if (!isArray && 
390                     typeof(obj['|xns']) != 'undefined' &&
391                     typeof(obj['xtype']) != 'undefined'
392                 ) {
393                     els.push('xtype: '+ obj['|xns'] + '.' + obj['xtype']);
394                     skip.push('|xns','xtype');
395                 }
396             
397             var _this = this;
398             
399             
400             
401             keys.forEach(function(i) {
402                 var el = obj[i];
403                 if (!isArray && skip.indexOf(i) > -1) {
404                     return;
405                 }
406                 if (isListener) {
407                     if (obj[i].match(/Gtk.main_quit/)) { // we can not handle this very well..
408                         return;
409                     }
410                     var str= ('' + obj[i]).replace(/^\s+|\s+$/g,"");
411                     var lines = str.split("\n");
412                     if (lines.length > 1) {
413                         str = lines.join("\n" + pad);
414                     }
415                     els.push(JSON.stringify(i) + ":" + str);
416                     return;
417                 }
418                 if (i[0] == '|') {
419                     // does not hapepnd with arrays..
420                     if (typeof(el) == 'string' && !obj[i].length) { //skip empty.
421                         return;
422                     }
423                     
424                     if (typeof(el) == 'string'  && obj[i].match(/Gtk.main_quit/)) { // we can not handle this very well..
425                         return;
426                     }
427                     
428                     var str= ('' + obj[i]).replace(/^\s+|\s+$/g,"");;
429                     var lines = str.split("\n");
430                     if (lines.length > 1) {
431                         str = lines.join("\n" + pad);
432                     }
433                     
434                     els.push(JSON.stringify(i.substring(1)) + ":" + str);
435                     return;
436                 }
437                 var left = isArray ? '' : (JSON.stringify(i) + " : " )
438                 if (typeof(el) == 'object') {
439                     els.push(left + _this.mungeToString(el, i == 'listeners', pad + '    '));
440                     return;
441                 }
442                 els.push(JSON.stringify(i) + ":" + JSON.stringify(obj[i]));
443             });
444             return (isArray ? '[' : '{') + "\n" +
445                 pad  + els.join(",\n" + pad ) +
446                 (isArray ? ']' : '}');
447                
448             
449             
450         }
451         
452     }
453     
454     
455 );
456