4bd8e99042649cc353d27d963f00b6ac5f1eedf8
[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                         
150                                 this.el.resource_load_started.connect( (resource, request) => {
151                                         print("Adding referrer header %s\n" , request.get_uri());
152                                         
153                                         if (request.get_http_headers() != null) {
154                                                 request.get_http_headers().remove("Referer");           
155                                                 request.get_http_headers().append("Referer", request.get_uri());
156                                         }
157                         });
158                         var settings = this.el.get_settings();
159                                 settings.set_user_agent( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36" );
160                                 settings.hardware_acceleration_policy = WebKit.HardwareAccelerationPolicy.NEVER;
161                                 settings.enable_accelerated_2d_canvas = false;
162                                 
163                                 WebKit.WebContext.get_default().set_tls_errors_policy(  WebKit.TLSErrorsPolicy.IGNORE );
164                        
165             #else
166              //listeners
167                       //  this.el.resource_request_starting.connect( (p0, webres, netreq ) => {
168                         //  print("resource req. started %s\n", netreq.uri);
169                              
170                       //  });
171                         
172                         this.el.load_finished.connect( ( ) => {
173                                 
174                                 
175                                this.printit(); 
176                          
177                         });
178                         WebKit.get_default_session().request_started.connect((message, socket) => {
179                             Soup.URI uri = message.get_uri();
180                                 
181                                         var host = uri.get_host ();
182             
183                                         print("Adding header http://%s/\n", host);
184                                         message.request_headers.remove("Referer");                              
185                                         message.request_headers.append("Referer", "http://"+host+"/");
186                                         
187                         
188                         });
189                         var sess = WebKit.get_default_session();
190                                 sess.user_agent= "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36";
191                                 sess.ssl_strict = false;
192                         
193             #endif
194             }
195                         this.cookie_file = "";
196                         if (webkitpdf.opt_cookies != null) {
197                                 print("setting cookie %s\n",webkitpdf.opt_cookies);
198             
199                                 var uri = new Soup.URI (webkitpdf.opt_url);
200                                 
201                                 string[] cookies = webkitpdf.opt_cookies.split ("=", 2);
202             
203                                 if(cookies.length > 1 ) {
204                                                      
205                                 #if GTK3        
206                                         var context = WebKit.WebContext.get_default();           
207                                         var cookie_manager = context.get_cookie_manager();
208                                         cookie_manager.set_accept_policy(WebKit.CookieAcceptPolicy.NEVER);
209                                         string scheme = uri.get_scheme ();
210                                 
211                                         try {            
212                                             FileIOStream iostream;                            
213                                             File file = File.new_tmp ("cookie-XXXXXX.txt", out iostream);
214                                             this.cookie_file = file.get_path ();        
215                                             print("cookie tmp file name: %s\n", file.get_path ());
216                                  
217                                             OutputStream ostream = iostream.output_stream;
218                                             DataOutputStream dostream = new DataOutputStream (ostream);                                      
219                                             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]));                             
220                                             cookie_manager.set_persistent_storage(file.get_path(), WebKit.CookiePersistentStorage.TEXT);                              
221                                         } catch (Error e) {
222                                             stdout.printf ("Error: %s\n", e.message);
223                                         }               
224                                 #else
225                                                 var cookie_jar = new Soup.CookieJar();          
226                                         var cookie = new Soup.Cookie (cookies[0], cookies[1], uri.get_host(), "/", -1);
227                                         if(uri.get_scheme() =="https") {
228                                             cookie.set_secure(true);                    
229                                         }           
230                                         cookie_jar.set_accept_policy(Soup.CookieJarAcceptPolicy.NEVER);                          
231                                         cookie_jar.add_cookie(cookie);                      
232                                         WebKit.get_default_session().add_feature(cookie_jar);
233                                 #endif
234                                                                                                             
235                                 }
236             
237                         } 
238                         // init method
239         }
240
241         // user defined functions
242         public void printit () {
243            print("load_finsihed\n");
244            
245            if (this.print_started) {
246                print("load_finsihed - already printing..%d %s\n", this.load_try, this.el.uri);
247            
248               
249               
250               
251               return;
252           }
253            
254          
255             this.print_started = true; // flag to stop double call.
256             
257             
258                 // inject any javascript if needed..
259                 if (webkitpdf.opt_inject_js != null) {
260                 
261                         print("injecting javascript files \n");
262                         foreach(var inject_js in  webkitpdf.opt_inject_js) {
263                         print("inject? %s\n", inject_js);
264                                 string str;
265                                 try {
266                                         FileUtils.get_contents( inject_js, out str);
267                                 } catch(FileError e) {
268                                         print("Failed to inject %s\n",  inject_js);
269                                         continue;
270                                 }
271         #if GTK3
272                                 GLib.MainLoop mainloop = new GLib.MainLoop();
273                                 this.el.run_javascript.begin(str, null, (obj,res) => {
274                                         mainloop.quit();
275                                 });
276                                 mainloop.run();
277                                 
278         #else                   
279                                 this.el.execute_script(str);
280         #endif
281                         }
282                 }
283                   
284                 print("calling print in %d seconds\n", (int)webkitpdf.opt_delay);
285                 if (webkitpdf.opt_target_pdf != null) {
286                         GLib.Timeout.add_seconds(webkitpdf.opt_delay, () => { 
287                                 print("delay done URL: %s\n", this.el.uri);
288                         
289                                  
290                                 this.printpdf();
291                                  return false;
292                         }, GLib.Priority.DEFAULT);
293                         return;
294                 }
295                         
296         
297         #if GTK3
298                 GLib.Timeout.add_seconds(webkitpdf.opt_delay, () => { 
299                                 print("delay done URL: %s\n", this.el.uri);
300                                 this.printpng();        
301                                 return false;
302                         }, GLib.Priority.DEFAULT);
303                         return;
304         #else
305                         
306             GLib.Timeout.add_seconds(webkitpdf.opt_delay, () => { 
307            
308                         
309                         // ----------------- JPEG 
310                         // resize the window...
311                         // window.document.documentElement.scrollHeight
312                         var scroll_height = (int) _this.view.el.get_dom_document().document_element.scroll_height;
313                         print("Scroll height %d\n", scroll_height);
314                         if (scroll_height> 1024 || webkitpdf.opt_width > 0  || webkitpdf.opt_height > 0  ) {
315                                 var w = webkitpdf.opt_width > 0 ?  webkitpdf.opt_width  : 1200;
316                                 var h = int.min(scroll_height, 6000);
317                                 _this.scrolled_window.el.set_size_request( w, h); 
318                                 _this.el.resize (w+50, h+50);
319                                 print("Resize to %d, %d\n", w,h);
320                             GLib.Timeout.add_seconds(webkitpdf.opt_delay > 0 ? webkitpdf.opt_delay : 1 , () => { 
321                                         this.printpng();
322                                         return false;
323                                   }, GLib.Priority.DEFAULT);
324                             return false;
325                         }
326                         this.printpng();                
327                         return false;
328                   }, GLib.Priority.DEFAULT);
329         
330         
331         #endif    
332             
333         }
334         public bool printpdf () {
335         
336         
337         
338                         var list = Gtk.PaperSize.get_paper_sizes(false);
339                     var psetup = new Gtk.PageSetup();
340                     for(var i = 0; i < list.length(); i++ ) {
341                         var entry = list.nth_data(i).copy();
342                         if (entry.get_name() == "iso_a2") {
343                             psetup.set_paper_size(entry);
344                         }
345                     }
346                     
347         
348         #if GTK3         
349         
350                         var  pe = new  WebKit.PrintOperation(this.el);
351                         pe.set_page_setup(psetup);
352                         pe.finished.connect( () => {
353                                 print("print completed\n");
354                     this.delete_cookiefile(); 
355                                  Gtk.main_quit();
356                         
357                         });
358                         
359                         var ps = new Gtk.PrintSettings();
360                     ps.set_printer("Print to File");
361                     ps.set("output-file-format", "pdf");
362                     ps.set("output-uri", "file://" + webkitpdf.opt_target_pdf);
363         
364                         
365                         pe.set_print_settings(ps);
366                         
367         
368                         pe.print();
369                                   
370         
371         #else       
372                         var  pe = new  Gtk.PrintOperation();
373                         pe.export_filename = webkitpdf.opt_target_pdf;
374                         print("got callback for print\n");
375                         pe.ref();
376                         /*pe.failed.connect(() => {
377                                 print("print failed\n");
378                                  Gtk.main_quit();
379                         
380                         })
381                         */;
382                          pe.done.connect(() => {
383                                 print("print completed\n");
384                     this.delete_cookiefile(); 
385                                  Gtk.main_quit();
386                         
387                         });
388                         
389                         //pe.run_dialog(_this.el);
390                  
391                         
392                         
393         
394         
395                     pe.set_default_page_setup(psetup);
396                     print("Calling Print?\n");
397                     //pe.run_dialog(_this.el);
398                     
399                     
400         
401         
402         
403                     try {
404                             this.el.get_main_frame().print_full(pe,Gtk.PrintOperationAction.EXPORT);
405                     } catch (Error e) {
406                                 // print failed...
407                         }
408         #endif      
409                     
410                      
411                         return false;
412         }
413         public void printpng () {
414             //var filename = "/tmp/test.pdf";
415             //print("load_changed %d ?= %d\n", le, LoadEvent.FINISHED);
416         
417             //if (le != LoadEvent.FINISHED) {
418             //    return;
419            // }
420            
421         // what size is the documet.
422         
423              print("making screenshot\n");
424         #if GTK3
425         GLib.MainLoop mainloop = new GLib.MainLoop();
426           _this.view.el.get_snapshot.begin(WebKit.SnapshotRegion.FULL_DOCUMENT, WebKit.SnapshotOptions.NONE, null, (obj, res) => {
427                          var sf = _this.view.el.get_snapshot.end(res);
428                          sf.write_to_png(webkitpdf.opt_target_png);
429                 print("Saved to %s\n", webkitpdf.opt_target_png);
430                          mainloop.quit();
431                          
432           });
433         
434                 mainloop.run();
435         
436         #else     
437             // fix vapi - get_snapshot add '?' to all null.
438             var pixmap = _this.view.el.get_snapshot( null );
439         
440             
441             
442             int w,h;
443             
444             // add out to gdkpixmap.get_size
445                 pixmap.get_size( out  w , out   h);
446                 var pixbuf  = Gdk.pixbuf_get_from_drawable(null, pixmap, null , 0, 0, 0, 0, w, h);
447                 print("pixbuf size: %d x %d\n ", w,h);
448                  
449             
450             
451              pixbuf.save(webkitpdf.opt_target_png, "png");
452              print("Saved to %s\n", webkitpdf.opt_target_png);
453             //view.get_snapshot.begin(WebKit.SnapshotRegion.FULL_DOCUMENT, WebKit.SnapshotOptions.NONE, null, (obj, res) => {
454             //    var sf = view.get_snapshot.end(res);
455         
456             //    sf.write_to_png(Browser.opt_target_png);
457             //});
458         #endif       
459            this.delete_cookiefile(); 
460            
461             Gtk.main_quit();
462              
463         
464             
465             
466         
467         }
468         public void delete_cookiefile () {
469                 if(this.cookie_file.length < 1 ){
470                         return;
471                 }
472             print("deleting tmp file %s\n",this.cookie_file);
473             File file = File.new_for_path (this.cookie_file);
474             try {
475                 if (file.query_exists () == true) {
476                    file.delete ();                   
477                 }
478             } catch (Error e) {
479                 stdout.printf ("Error: %s\n", e.message);
480             }
481         
482         }
483     }
484
485
486 }