BrowserWindow.bjs
[app.webkitpdf] / BrowserWindow.vala
1 static BrowserWindow  _BrowserWindow;
2
3 public class BrowserWindow : Object
4 {
5     public Gtk.Window el;
6     private BrowserWindow  _this;
7
8     public static BrowserWindow singleton()
9     {
10         if (_BrowserWindow == null) {
11             _BrowserWindow= new BrowserWindow();
12         }
13         return _BrowserWindow;
14     }
15     public Xcls_scrolled_window scrolled_window;
16     public Xcls_view view;
17
18         // my vars (def)
19
20     // ctor
21     public BrowserWindow()
22     {
23         _this = this;
24         this.el = new Gtk.Window( Gtk.WindowType.TOPLEVEL );
25
26         // my vars (dec)
27
28         // set gobject values
29         var child_0 = new Xcls_scrolled_window( _this );
30         child_0.ref();
31         this.el.add (  child_0.el  );
32
33         //listeners
34         this.el.destroy.connect( () => {
35             Gtk.main_quit();
36         });
37         this.el.show.connect( () => {
38                 
39                 print("resizing window\n");
40                 var w = webkitpdf.opt_width > 0 ?  webkitpdf.opt_width  : 1200;
41                 var h = webkitpdf.opt_height > 0 ?  webkitpdf.opt_height  :  500;
42                                 
43                 
44                 this.el.resize(w,h);
45         
46                 // we have to do silly stuff with blogspot!!?!?
47                 var blog = webkitpdf.opt_url;
48         
49         
50           /* Do not redirect if the domain is .com already */
51           if (/\.blogspot\.com/.match(blog)) {
52                         var r =  new Regex ("\\.blogspot\\..*?/");
53                         blog = r.replace(blog, blog.length, 0, ".blogspot.com/ncr/");
54           }
55                 
56                 print("loading url %s\n",blog); 
57                 this.view.el.load_uri(blog);
58                  
59                 // if we have not finished in 25 seconds
60                 // call printit...
61                 var cd = webkitpdf.opt_delay > 25 ? webkitpdf.opt_delay : 25;
62                   GLib.Timeout.add_seconds(1, () => { 
63                         cd--;
64                         print("timeout %d seconds :%d", (int)( webkitpdf.opt_delay > 25 ? webkitpdf.opt_delay : 25), (int)cd);
65                         if (cd < 1) {
66                                 print("calling printit - timed out");
67                                 _this.view.printit();
68                                 return false;                   
69                         }
70                         return true;
71         
72                 });
73                 
74         
75         });
76     }
77
78     // user defined functions
79     public class Xcls_scrolled_window : Object
80     {
81         public Gtk.ScrolledWindow el;
82         private BrowserWindow  _this;
83
84
85             // my vars (def)
86
87         // ctor
88         public Xcls_scrolled_window(BrowserWindow _owner )
89         {
90             _this = _owner;
91             _this.scrolled_window = this;
92             this.el = new Gtk.ScrolledWindow( null, null );
93
94             // my vars (dec)
95
96             // set gobject values
97             var child_0 = new Xcls_view( _this );
98             child_0.ref();
99             this.el.add (  child_0.el  );
100
101             // init method
102
103             {
104                 this.el.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC);
105             }
106         }
107
108         // user defined functions
109     }
110     public class Xcls_view : Object
111     {
112         public WebKit.WebView el;
113         private BrowserWindow  _this;
114
115
116             // my vars (def)
117         public string cookie_file;
118         public bool print_started;
119         public int load_try;
120
121         // ctor
122         public Xcls_view(BrowserWindow _owner )
123         {
124             _this = _owner;
125             _this.view = this;
126             this.el = new WebKit.WebView();
127
128             // my vars (dec)
129             this.print_started = false;
130             this.load_try = 0;
131
132             // set gobject values
133
134             // init method
135
136             {
137                         this.load_try = 0;
138             
139             #if GTK3
140                          this.el.load_changed.connect( (ev ) => {
141                                 if (ev != WebKit.LoadEvent.FINISHED) {
142                                         return;  
143                                   }
144                                   
145                            this.printit(); 
146                           
147                          
148                         });
149                                 this.el.resource_load_started.connect( (resource, request) => {
150                                         print("Adding referrer header %s\n" , request.get_uri());
151                                         
152                                         if (request.get_http_headers() != null) {
153                                                 request.get_http_headers().remove("Referer");           
154                                                 request.get_http_headers().append("Referer", request.get_uri());
155                                         }
156                         });
157             #else
158              //listeners
159                       //  this.el.resource_request_starting.connect( (p0, webres, netreq ) => {
160                         //  print("resource req. started %s\n", netreq.uri);
161                              
162                       //  });
163                         
164                         this.el.load_finished.connect( ( ) => {
165                                 
166                                 
167                                this.printit(); 
168                          
169                         });
170                         WebKit.get_default_session().request_started.connect((message, socket) => {
171                             Soup.URI uri = message.get_uri();
172                                 
173                                         var host = uri.get_host ();
174             
175                                         print("Adding header http://%s/\n", host);
176                                         message.request_headers.remove("Referer");                              
177                                         message.request_headers.append("Referer", "http://"+host+"/");
178                                         
179                         
180                         });
181                         
182                         
183             #endif
184             }
185                         this.cookie_file = "";
186                         if (webkitpdf.opt_cookies != null) {
187                                 print("setting cookie %s\n",webkitpdf.opt_cookies);
188             
189                                 var uri = new Soup.URI (webkitpdf.opt_url);
190                                 
191                                 string[] cookies = webkitpdf.opt_cookies.split ("=", 2);
192             
193                                 if(cookies.length > 1 ) {
194                                                      
195                                 #if GTK3                
196                                         var context = WebKit.WebContext.get_default();           
197                                         var cookie_manager = context.get_cookie_manager();
198                                         cookie_manager.set_accept_policy(WebKit.CookieAcceptPolicy.NEVER);
199                                         string scheme = uri.get_scheme ();
200                                 
201                                         try {            
202                                             FileIOStream iostream;                            
203                                             File file = File.new_tmp ("cookie-XXXXXX.txt", out iostream);
204                                             this.cookie_file = file.get_path ();        
205                                             print("cookie tmp file name: %s\n", file.get_path ());
206                                  
207                                             OutputStream ostream = iostream.output_stream;
208                                             DataOutputStream dostream = new DataOutputStream (ostream);                                      
209                                             dostream.put_string ("%s\tTRUE\t/\t%s\t2147483647\t%s\t%s".printf(uri.get_host(),scheme == "http" ? "FALSE" : "TRUE",cookies[0],cookies[1]));                             
210                                             cookie_manager.set_persistent_storage(file.get_path(), WebKit.CookiePersistentStorage.TEXT);                              
211                                         } catch (Error e) {
212                                             stdout.printf ("Error: %s\n", e.message);
213                                         }               
214                                 #else
215                                         var sess = WebKit.get_default_session();
216                                         var cookie_jar = new Soup.CookieJar();          
217                                         var cookie = new Soup.Cookie (cookies[0], cookies[1], uri.get_host(), "/", -1);
218                                         if(uri.get_scheme() =="https") {
219                                             cookie.set_secure(true);                    
220                                         }           
221                                         cookie_jar.set_accept_policy(Soup.CookieJarAcceptPolicy.NEVER);                          
222                                         cookie_jar.add_cookie(cookie);                      
223                                         sess.add_feature(cookie_jar);
224                                 #endif
225                                                                                                             
226                                 }
227             
228                         } 
229                         // init method
230         }
231
232         // user defined functions
233         public void printit () {
234            print("load_finsihed\n");
235            
236            if (this.print_started) {
237                print("load_finsihed - already printing..%d %s\n", this.load_try, this.el.uri);
238            
239               
240               
241               
242               return;
243           }
244            
245          
246             this.print_started = true; // flag to stop double call.
247             
248             
249                 // inject any javascript if needed..
250                 if (webkitpdf.opt_inject_js != null) {
251                 
252                         print("injecting javascript files \n");
253                         foreach(var inject_js in  webkitpdf.opt_inject_js) {
254                         print("inject? %s\n", inject_js);
255                                 string str;
256                                 try {
257                                         FileUtils.get_contents( inject_js, out str);
258                                 } catch(FileError e) {
259                                         print("Failed to inject %s\n",  inject_js);
260                                         continue;
261                                 }
262         #if GTK3
263                                 GLib.MainLoop mainloop = new GLib.MainLoop();
264                                 this.el.run_javascript.begin(str, null, (obj,res) => {
265                                         mainloop.quit();
266                                 });
267                                 mainloop.run();
268                                 
269         #else                   
270                                 this.el.execute_script(str);
271         #endif
272                         }
273                 }
274                   
275                 print("calling print in %d seconds\n", (int)webkitpdf.opt_delay);
276                 if (webkitpdf.opt_target_pdf != null) {
277                         GLib.Timeout.add_seconds(webkitpdf.opt_delay, () => { 
278                                 print("delay done URL: %s\n", this.el.uri);
279                         
280                                  
281                                 this.printpdf();
282                                  return false;
283                         }, GLib.Priority.DEFAULT);
284                         return;
285                 }
286                         
287         
288         #if GTK3
289                 print("PNG not supported in webkit2\n");
290                 return;
291         #else
292                         
293             GLib.Timeout.add_seconds(webkitpdf.opt_delay, () => { 
294            
295                         
296                         // ----------------- JPEG 
297                         // resize the window...
298                         // window.document.documentElement.scrollHeight
299                         var scroll_height = (int) _this.view.el.get_dom_document().document_element.scroll_height;
300                         print("Scroll height %d\n", scroll_height);
301                         if (scroll_height> 1024 || webkitpdf.opt_width > 0  || webkitpdf.opt_height > 0  ) {
302                                 var w = webkitpdf.opt_width > 0 ?  webkitpdf.opt_width  : 1200;
303                                 var h = int.min(scroll_height, 6000);
304                                 _this.scrolled_window.el.set_size_request( w, h); 
305                                 _this.el.resize (w+50, h+50);
306                                 print("Resize to %d, %d\n", w,h);
307                             GLib.Timeout.add_seconds(webkitpdf.opt_delay > 0 ? webkitpdf.opt_delay : 1 , () => { 
308                                         this.printpng();
309                                         return false;
310                                   }, GLib.Priority.DEFAULT);
311                             return false;
312                         }
313                         this.printpng();                
314                         return false;
315                   }, GLib.Priority.DEFAULT);
316         
317         
318         #endif    
319             
320         }
321         public bool printpdf () {
322         
323         
324         
325                         var list = Gtk.PaperSize.get_paper_sizes(false);
326                     var psetup = new Gtk.PageSetup();
327                     for(var i = 0; i < list.length(); i++ ) {
328                         var entry = list.nth_data(i).copy();
329                         if (entry.get_name() == "iso_a2") {
330                             psetup.set_paper_size(entry);
331                         }
332                     }
333                     
334         
335         #if GTK3         
336         
337                         var  pe = new  WebKit.PrintOperation(this.el);
338                         pe.set_page_setup(psetup);
339                         pe.finished.connect( () => {
340                                 print("print completed\n");
341                     this.delete_cookiefile(); 
342                                  Gtk.main_quit();
343                         
344                         });
345                         
346                         var ps = new Gtk.PrintSettings();
347                     ps.set_printer("Print to File");
348                     ps.set("output-file-format", "pdf");
349                     ps.set("output-uri", "file://" + webkitpdf.opt_target_pdf);
350         
351                         
352                         pe.set_print_settings(ps);
353                         
354         
355                         pe.print();
356                                   
357         
358         #else       
359                         var  pe = new  Gtk.PrintOperation();
360                         pe.export_filename = webkitpdf.opt_target_pdf;
361                         print("got callback for print\n");
362                         pe.ref();
363                         /*pe.failed.connect(() => {
364                                 print("print failed\n");
365                                  Gtk.main_quit();
366                         
367                         })
368                         */;
369                          pe.done.connect(() => {
370                                 print("print completed\n");
371                     this.delete_cookiefile(); 
372                                  Gtk.main_quit();
373                         
374                         });
375                         
376                         //pe.run_dialog(_this.el);
377                  
378                         
379                         
380         
381         
382                     pe.set_default_page_setup(psetup);
383                     print("Calling Print?\n");
384                     //pe.run_dialog(_this.el);
385                     
386                     
387         
388         
389         
390                     try {
391                             this.el.get_main_frame().print_full(pe,Gtk.PrintOperationAction.EXPORT);
392                     } catch (Error e) {
393                                 // print failed...
394                         }
395         #endif      
396                     
397                      
398                         return false;
399         }
400         public void printpng () {
401             //var filename = "/tmp/test.pdf";
402             //print("load_changed %d ?= %d\n", le, LoadEvent.FINISHED);
403         
404             //if (le != LoadEvent.FINISHED) {
405             //    return;
406            // }
407            
408         // what size is the documet.
409         
410              print("making screenshot\n");
411         #if GTK3
412         
413         #else     
414             // fix vapi - get_snapshot add '?' to all null.
415             var pixmap = _this.view.el.get_snapshot( null );
416         
417             
418             
419             int w,h;
420             
421             // add out to gdkpixmap.get_size
422                 pixmap.get_size( out  w , out   h);
423                 var pixbuf  = Gdk.pixbuf_get_from_drawable(null, pixmap, null , 0, 0, 0, 0, w, h);
424                 print("pixbuf size: %d x %d\n ", w,h);
425                  
426             
427             
428              pixbuf.save(webkitpdf.opt_target_png, "png");
429              print("Saved to %s\n", webkitpdf.opt_target_png);
430             //view.get_snapshot.begin(WebKit.SnapshotRegion.FULL_DOCUMENT, WebKit.SnapshotOptions.NONE, null, (obj, res) => {
431             //    var sf = view.get_snapshot.end(res);
432         
433             //    sf.write_to_png(Browser.opt_target_png);
434             //});
435            this.delete_cookiefile(); 
436             Gtk.main_quit();
437              
438         #endif   
439             
440             
441         
442         }
443         public void delete_cookiefile () {
444                 if(this.cookie_file.length < 1 ){
445                         return;
446                 }
447             print("deleting tmp file %s\n",this.cookie_file);
448             File file = File.new_for_path (this.cookie_file);
449             try {
450                 if (file.query_exists () == true) {
451                    file.delete ();                   
452                 }
453             } catch (Error e) {
454                 stdout.printf ("Error: %s\n", e.message);
455             }
456         
457         }
458     }
459
460
461 }