BrowserView.js
[app.webkitpdf] / BrowserView.js
1 Gtk = imports.gi.Gtk;
2 GLib = imports.gi.GLib;
3 WebKit = imports.gi.WebKit;
4
5 TabbedBrowser = imports.TabbedBrowser;
6 BrowserSettings = imports.BrowserSettings;
7 BrowserTab = imports.BrowserTab;
8
9 File = imports.File.File;
10
11 base64 = imports.base64.base64;
12
13 BrowserView = new GType({
14     parent: WebKit.WebView.type,
15     name: "BrowserView",
16     init: function ()
17     {
18         // Private
19         
20         
21         var _t = this;
22         
23         var tab = BrowserTab;
24         var browsePage = false;
25         var maxQueue = 0;
26         var injected = {};
27         
28         var current_url = '';
29  
30         var update_title = function (web_view, web_frame, title)
31         {
32             
33             print("calling update title");
34             if(title.length > 25)
35                 title = title.slice(0,25) + "...";
36
37             tab.get_tab_label().label = title;
38         };
39         
40         
41         
42           
43         
44         
45         
46         
47         var curdoc = false;
48         
49         
50         
51         var traversedom = function(web_frame) {
52             //print("TRAVERSE DOM?");
53             
54             var dom = web_frame.get_dom_document();
55             var ret = '<HTML>';
56             
57             var cb =  function(s) {
58                 //print("CB:" + s);
59                 ret+=s;
60             };
61             
62             curdoc  = web_frame.get_dom_document();
63             //Roo.select('body > div',true).each(function(el) {
64             traverseDOMTree(cb, dom.head, 1);
65             traverseDOMTree(cb, dom.body, 1);
66            //print(ret);
67             return ret +'</HTML>';
68         
69         };
70         
71         var embeded_file = 0;
72         
73         
74         var elClassToStyle = function(el)
75         {
76             var bd  = curdoc;
77             
78                     
79             
80             
81             
82             var def =  bd.document_element.append_child( bd.create_element(el.node_name));
83             
84             
85             var par_ds = el.node_name == 'BODY' ? false : bd.get_default_view().get_computed_style(el.parent_node, '');
86             
87             var ds = bd.get_default_view().get_computed_style(def, '');
88             var cs = el.owner_document.default_view.get_computed_style(el, '');
89             
90             
91             
92             
93             var ns = [];
94             for (var i = 0; i < cs.length; i++ ) {
95                 var k = cs.item(i);
96                 
97                 //print([ k, cs.get_property_value(k) ,   ds.get_property_value(k) ]);
98                 
99                 
100                 if (!cs.get_property_value(k).length) {
101                     continue;
102                 }
103                 if (par_ds && (cs.get_property_value(k) == ds.get_property_value(k) )) {
104                     continue;
105                 }
106                 //if (par_ds  && (cs.get_property_value(k) == par_ds.get_property_value(k) )) {
107                 //    continue;
108                 //}
109                 
110                 ns.push(k + ':'+ cs.get_property_value(k) +';');
111                 
112             }
113             bd.document_element.remove_child(def);
114             //print(ns.join(''));
115             
116             return ns.length ? ns.join('') : '';
117         
118             //el.remove_attribute('class');
119             //el.set_attribute('style', ns.length ? ns.join('') : '');
120             
121             
122         }
123         
124         
125         
126         var traverseDOMTree = function(cb, currentElement, depth) {
127             if (currentElement) {
128                 
129                 //if (currentElement.class_name.match(/roo-dynamic/)) {
130                 //    return;
131                 //}
132                 //print(currentElement.node_name);
133                 var j;
134                 var nodeName = currentElement.node_name;
135                 var tagName = currentElement.tag_name;
136                 
137                 if  (nodeName == '#text') {
138                     cb(currentElement.node_value);
139                     return;
140                 
141                 }
142                 if(nodeName == 'BR'){
143                     cb("<BR/>");
144                     return;
145                 }
146                
147                 if (nodeName == 'SCRIPT') {
148                      
149                     return;
150                 }
151                 //if (nodeName == 'STYLE') {  return; }
152                 var i = 0;
153               // Prints the node tagName, such as <A>, <IMG>, etc
154                 var outNodeName = nodeName;
155                 if (nodeName == 'IFRAME') {
156                     //outNodeName  = 'DIV';
157                 }
158                 if (tagName) {
159                     
160                     
161                     
162                     
163                     var attr = [];
164                     
165                     for(i = 0; i < currentElement.attributes.length;i++) {
166                         var aname = currentElement.attributes.item(i).name;
167                         //if (aname =='class' || aname == 'style') {
168                         //    continue;
169                         //}
170                         if (aname =='src' || tagName == 'IFRAME') {
171                             continue;
172                         }
173                         
174                         attr.push(aname + '="' + currentElement.attributes.item(i).value + '"' );
175                     }
176                     
177                     //if (nodeName == 'IFRAME') {
178                     //    attr.push('src="' + currentElement.attributes.item(i).value + embeded_file '"' );
179                     //}
180                     
181                     //var style = elClassToStyle(currentElement);
182                     //if (style.length) {
183                     //    attr.push('style="' + style + '"' );
184                     //}
185                     
186                     
187                     //if (depth > 1000 && (tagName == 'BODY' || tagName == 'HEAD' )) {
188                      //   cb("<DIV"+ ( attr.length ? (' ' + attr.join(' ') ) : '') + ">");
189                     //} else {
190                         cb("<"+outNodeName + ( attr.length ? (' ' + attr.join(' ') ) : '') + ">");
191                         
192                     //}
193                 } 
194                 else {
195                   cb("[unknown tag]");
196                 }
197                 
198                  if (nodeName == 'IFRAME') {
199                     
200                     cb("<HTML>\n");
201                     //traverseDOMTree(cb, currentElement.content_document.head, depth+1000);
202                     traverseDOMTree(cb, currentElement.content_document.get_document_element(), depth+1000);
203                     cb("\n</HTML>");
204                     cb("\n</IFRAME>");
205                     
206                     return;
207                 }
208                 
209                 
210                 // Traverse the tree
211                 i = 0;
212                 var currentElementChild = currentElement.child_nodes.item(i);
213                 var allText = true;
214                 while (currentElementChild) {
215                     // Formatting code (indent the tree so it looks nice on the screen)
216                     
217                     if  (currentElementChild.node_name == '#text') {
218                        // if (currentElementChild.node_value.length) {
219                             cb(currentElementChild.node_value);
220                        // }
221                         
222                         i++;
223                         currentElementChild=currentElement.child_nodes.item(i);
224                         continue;
225                     }   
226                     allText = false;
227                     //cb("\n");
228                     //for (j = 0; j < depth; j++) {
229                       // &#166 is just a vertical line
230                     //  cb("  ");
231                     //}//               
232                     
233                         
234                     // Recursively traverse the tree structure of the child node
235                     traverseDOMTree(cb, currentElementChild, depth+1);
236                     i++;
237                     currentElementChild=currentElement.child_nodes.item(i);
238                 }
239                 if (!allText) {
240                     // The remaining code is mostly for formatting the tree
241                     //cb("\n");
242                     //for (j = 0; j < depth - 1; j++) {
243                       //cb("  ");
244                     //}     
245                 }
246                 if (tagName) {
247                    // if (depth > 1000 && (tagName == 'BODY' || tagName == 'HEAD' )) {
248                    //     cb("</DIV>");
249                    // } else {
250                         cb("</"+outNodeName+">");
251                    // }
252                     
253                 }
254             }
255         };
256         
257
258         var update_url = function (web_view, web_frame)
259         {
260             var toolbar = tab.get_toolbar();
261
262             toolbar.set_url(web_frame.get_uri());
263             toolbar.set_can_go_back(web_view.can_go_back());
264             toolbar.set_can_go_forward(web_view.can_go_forward());
265             
266             
267             
268             
269         };
270
271     
272       
273
274         var create_new_tab = function (web_view, web_frame, new_web_view)
275         {
276             new_web_view = new BrowserView();
277             new_web_view.signal.web_view_ready.connect(show_new_tab);
278             return new_web_view;
279         };
280
281         var show_new_tab = function (new_web_view)
282         {
283             TabbedBrowser.browser.new_tab("", new_web_view);
284
285             return false;
286         };
287
288         var hover_link = function (web_view, link, url)
289         {
290             tab.get_statusbar().set_status(url);
291         };
292
293         
294         /*
295         
296         this.add_inject = function(force)
297         {
298             
299             if (force || (typeof(injected[this.uri]) == 'undefined' )) {
300                 injected[this.uri] = 0;
301             }
302             if (injected[this.uri] > 2) {
303                 return;
304             }
305             injected[this.uri]++;
306             var fn = __script_path__ + "/inject.js";
307             if (File.exists(fn)) {
308 //                print("Adding inject");
309                 var newjs = File.read(__script_path__ + "/inject.js");
310                 TabbedBrowser.browser.current_tab().get_web_view().execute_script(
311                     newjs
312                     
313                 );
314             }
315             
316         }
317         */
318         var after_login = false;
319         
320         
321         var load_finished_called = false;
322         
323         
324         var do_print = function(web_frame) {
325             
326              
327             
328             TabbedBrowser.browser.current_tab().get_web_view().execute_script(
329                 " var r = document.getElementsByTagName('link');" +
330                 "for (var i=0;i < r.length;i++) { " +
331                     "var a = r[i]; if (a.getAttribute('media') == 'screen')  { a.removeAttribute('media'); } " +
332                     "}"
333             );
334             
335             
336             
337             if (current_url.match(/\.coconuts\.co\//) ) {
338                 TabbedBrowser.browser.current_tab().get_web_view().execute_script(
339                     File.read( __script_path__ + "/domains/coconuts.co.js")
340                 );
341                               
342             }
343             print("Delay:" + BrowserSettings.delay);
344          
345             GLib.timeout_add(GLib.PRIORITY_LOW, BrowserSettings.delay *1, function() {
346                  
347                 if (web_frame &&  BrowserSettings.export_filename_html  ) {
348                     var html = traversedom(web_frame);
349                     File.write(BrowserSettings.export_filename_html, html);
350                     
351                 } 
352                  
353                 if (!BrowserSettings.export_filename) {
354                     Seed.quit();
355                 }
356                 var mf = _t.get_main_frame();
357                 
358                 var ar = Gtk.PaperSize.get_paper_sizes();
359                 var psetup = new Gtk.PageSetup();
360                 for(var i = 0; i < ar.length; i++) {
361                     if (ar[i].get_name() =='iso_a2') {
362                         psetup.set_paper_size(ar[i]);
363                     }
364                 }
365                 
366                 var p = new Gtk.PrintOperation({ export_filename : BrowserSettings.export_filename });
367                 p.set_default_page_setup(psetup);
368                 mf.print_full(p, Gtk.PrintOperationAction.EXPORT);
369                 print("made image - exiting");
370                 
371                 Seed.quit();
372                 return true;
373             });
374         }
375         
376         
377         var weibo_added = false;
378         
379         var is_weibo = false;
380         
381         
382         var load_finished = function (webkit, web_frame, wb)
383         {
384             
385            
386             
387             if (!is_weibo) {
388                 do_print(web_frame);
389                 return;
390             }
391              
392              
393              print("load finished");
394              if (weibo_added) {
395                  
396                  if (after_login === true) {
397                      print("do print");
398                      do_print();
399                      return;
400                      
401                  }
402                  if (after_login === false) {
403                      return; // not here?
404                  }
405                  print("adding timeout?");
406                  //return;
407                 GLib.timeout_add(GLib.PRIORITY_LOW, 2000, function() {
408                     print("Redirecting after login?" + after_login);
409                     
410                     _t.browse(after_login);
411                     after_login  = true;
412                 });
413                 return;
414              }
415             
416             weibo_added = true;
417             TabbedBrowser.browser.current_tab().get_web_view().execute_script(
418                 File.read( __script_path__ + "/weibo.js") 
419             );
420             print("run_weibo(" + JSON.stringify( BrowserSettings.username ) + ", " + JSON.stringify(BrowserSettings.passwd) + ");");
421     
422             TabbedBrowser.browser.current_tab().get_web_view().execute_script(
423                     "run_weibo(" + JSON.stringify( BrowserSettings.username ) + ", " + JSON.stringify(BrowserSettings.passwd) + ");"
424             );
425             return;
426     
427             //    return;
428             print(after_login);
429             if (after_login !== false) {
430                 
431 //                return;
432                 // wait a bit then load the real page..
433                 GLib.timeout_add(GLib.PRIORITY_LOW, 500, function() {
434                     print("Redirecting after login?");
435                     _t.browse(after_login);
436                 });
437                 
438                 return;
439             }
440          
441             if (load_finished_called) {
442                 return ;
443             
444             }
445             load_finished_called = true;
446             
447           
448             
449 //            if(document.location.host=='weibo.com') {
450 //                // clear login dialog from weibo.
451 //                //check and hidden the login dialog and overlay .....
452 //                var els = document.querySelectorAll('div[node-type]');
453 //                var bbc = [];
454 //                for (i = 0; i < els.length; i++) {
455 //                    if (els[i].hasAttribute('node-type')) {
456 //                        if(els[i].getAttribute('node-type') == 'outer'){
457 //                            bbc.push(els[i]);
458 //                        }
459 //                    }
460 //                }
461 //                for (i = 0; i < bbc.length; i++) {// hide all the outer.....
462 //                    bbc[i].style.display = 'none';
463 //                }
464 //                
465 //                //try to login 
466 //                if(document.location.pathname == '/login.php'){
467 //                    
468 //                    // fills in the user name and password 
469 //                    var els = document.querySelectorAll('input[node-type]');
470 //                    
471 //                    for (i = 0; i < els.length; i++) {
472 //                        if (els[i].hasAttribute('node-type')) {
473 //                            if(els[i].getAttribute('node-type') == 'username'){
474 //                                els[i].value = BrowserSettings.username;
475 //                            }
476 //                            if(els[i].getAttribute('node-type') == 'password'){
477 //                                els[i].value = BrowserSettings.passwd;
478 //                            }
479 //                        }
480 //                    }
481 //                    
482 //                    
483 //                    // simulating click event to login ....
484 //                    var elss = document.querySelectorAll('a[node-type]');
485 //                    
486 //                    for (i = 0; i < elss.length; i++) {
487 //                        if (elss[i].hasAttribute('node-type')) {
488 //                            if(elss[i].getAttribute('node-type') == 'submitBtn'){
489 //                                elss[i].click();
490 //                            }
491 //                        }
492 //                    }
493 //                    
494 //                    
495 //                }
496 //                
497 //            }
498             
499             
500             // clear login dialog from weibo.
501 //            TabbedBrowser.browser.current_tab().get_web_view().execute_script(
502 //                " if (document.location.host=='weibo.com') { " +
503 //                " try {  " + 
504 //                " var a = document.getElementsByClassName('W_layer')[0]; " + 
505 //                " a.parentNode.removeChild(a.previousSibling); " + 
506 //                " a.parentNode.removeChild(a); " + 
507 //                " } catch(e) { }  } " );
508             
509             
510             return;
511             GLib.timeout_add(GLib.PRIORITY_LOW, BrowserSettings.delay, function() {
512                  
513                 var mf = _t.get_main_frame();
514                 
515                 var ar = Gtk.PaperSize.get_paper_sizes();
516                 var psetup = new Gtk.PageSetup();
517                 for(var i = 0; i < ar.length; i++) {
518                     if (ar[i].get_name() =='iso_a2') {
519                         psetup.set_paper_size(ar[i]);
520                     }
521                 }
522                 
523                 var p = new Gtk.PrintOperation({ export_filename : BrowserSettings.export_filename });
524                 p.set_default_page_setup(psetup);
525                 mf.print_full(p, Gtk.PrintOperationAction.EXPORT);
526                 print("made image - exiting");
527                 
528                 Seed.quit();
529                 return true;
530             });
531             
532             return;
533         };
534  
535  
536  
537         
538         var load_committed = function (web_view, web_frame)
539         {
540             print("load commited");
541             
542             update_url(web_view, web_frame);
543              
544             // call load finished after 20seconds??
545             // so even if it never complets we try and print the thing.
546             GLib.timeout_add(GLib.PRIORITY_LOW, 40000, function() {
547                 print("load commited - 3000 ms?");
548                 load_finished();
549             });
550             
551         };
552
553         var clicked_link = function (web_view, web_frame, request,
554                                      action, decision, window)
555         {
556             if(action.get_reason() == WebKit.WebNavigationReason.LINK_CLICKED &&
557                action.get_button() == 2)
558             {
559                 browser.new_tab(request.get_uri(), null);
560                 return true;
561             }
562
563             return false;
564         };
565
566         // Public
567         
568         
569         this.browse = function (url)
570         {
571             if(url.search("://") < 0)
572                 url = "http://" + url;
573             
574             current_url = url;
575             
576             print("BROWSE: " + url);
577             if (url.match(/\/weibo\.com\//) && after_login === false) {
578                 is_weibo = true;
579                 after_login = url;
580                 url = "http://weibo.com/login.php";
581             }
582             else  if (url.match(/\/weibo\.com\//) && after_login !== false) {
583                 after_login = false;
584             }
585             print("BROWSE -really: " + url);
586             this.open(url);
587         };
588
589         this.set_tab = function (new_tab)
590         {
591             tab = new_tab;
592         };
593
594         this.get_tab = function ()
595         {
596             return tab;
597         };
598
599     
600         // Implementation
601         //this.set_scroll_adjustments(null, null);
602         
603         //this.signal.title_changed.connect(update_title);
604         //this.signal.load_committed.connect(load_committed);
605         this.signal.load_finished.connect(load_finished);
606        
607         
608         // For some reason, this segfaults seed in the instance init closure handler
609         // Once that's fixed, uncommenting the next line will give middle-click-open-in-new tab
610         //this.signal.navigation_policy_decision_requested.connect(clicked_link);
611
612         //this.signal.hovering_over_link.connect(hover_link);
613
614         this.signal.create_web_view.connect(create_new_tab);
615         
616         
617          
618 //        print("ADDing console message sig handler");
619         
620         
621          
622         
623         this.toFilename = function(url)
624         {
625             url = url.replace(/^http[s]*:\/\//, '');
626             var p = url.split('/');
627             p.unshift(storedir+'/output');
628             for (var i =1 ;i < p.length; i++) {
629                 p[i] = encodeURIComponent(p[i]);
630             
631             }
632             p[p.length-1] = decodeURIComponent(p[p.length-1]);
633             ret = p.join('/');
634             var dir = File.dirname(ret);
635             File.mkdirall(dir);
636             return ret;
637             
638         }
639         this.checkdomain = function(comp)
640         {
641             var b = parseUri(this.uri);
642             var d = parseUri(comp);
643             return (d.host == b.host && d.protocol == b.protocol);
644             
645             
646         }
647         
648         this.dupeCheck = function(url)
649         {
650             
651            // order - return highest up the queue first..
652             if (File.exists(downloaddir +'/' + encodeURIComponent(url))) {
653                 return downloaddir +'/' + encodeURIComponent(url);
654             }
655              if (File.exists(parsedir +'/' + encodeURIComponent(url))) {
656                 return parsedir +'/' + encodeURIComponent(url);
657             }
658             if (File.exists(donedir +'/' + encodeURIComponent(url))) {
659                 return donedir +'/' + encodeURIComponent(url);
660             }
661             return  false;
662             
663             
664         }
665         this.moveToParse = function(url)
666         {
667             var old = this.dupeCheck(url);
668             var target =parsedir +'/' + encodeURIComponent(url);
669             if (old == target) {
670                 return;
671             }
672             File.write(target, old ? File.read(old) : '');
673             if (old) {
674                 File.remove(old);
675             }
676             
677         }
678         
679         this.moveToDownload= function(url)
680         {
681             var old = this.dupeCheck(url);
682             var target =downloaddir +'/' + encodeURIComponent(url);
683             if (old == target) {
684                 return;
685             }
686             File.write(target, old ? File.read(old) : '');
687             if (old) {
688                 File.remove(old);
689             }
690             
691         }
692         this.moveToDone= function(url)
693         {
694             var old = this.dupeCheck(url);
695             var target = donedir +'/' + encodeURIComponent(url);
696             if (old == target) {
697                 return;
698             }
699             File.write(target, old ? File.read(old) : '');
700             if (old) {
701                 File.remove(old);
702             }
703             
704         }
705         
706     }
707 });
708
709 function parseUri (str) {
710         var     o   = parseUri.options,
711                 m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
712                 uri = {},
713                 i   = 14;
714
715         while (i--) uri[o.key[i]] = m[i] || "";
716
717         uri[o.q.name] = {};
718         uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
719                 if ($1) uri[o.q.name][$1] = $2;
720         });
721
722         return uri;
723 };
724
725 parseUri.options = {
726         strictMode: false,
727         key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
728         q:   {
729                 name:   "queryKey",
730                 parser: /(?:^|&)([^&=]*)=?([^&]*)/g
731         },
732         parser: {
733                 strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
734                 loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
735         }
736 };