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