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