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                     cookie_jar.set_accept_policy(Soup.CookieJarAcceptPolicy.NEVER);                              
170                     cookie_jar.add_cookie(new Soup.Cookie (cookies[0], cookies[1], uri.get_host(), "/", -1));                       
171                     sess.add_feature(cookie_jar);
172                 #endif
173                                                                                     
174                 }
175             
176             } 
177             // init method
178                         
179             
180
181             {
182                   this.load_try = 0;
183             
184             #if GTK3
185                    this.el.load_changed.connect( (ev ) => {
186                      if (ev != WebKit.LoadEvent.FINISHED) {
187                            return;       
188                        }
189                                   
190                            this.printit(); 
191                           
192                          
193                         });
194             
195             #else
196              //listeners
197                       //  this.el.resource_request_starting.connect( (p0, webres, netreq ) => {
198                         //  print("resource req. started %s\n", netreq.uri);
199                              
200                       //  });
201                         
202                         this.el.load_finished.connect( ( ) => {
203                                 
204                                 
205                                this.printit(); 
206                          
207                         });
208             #endif
209             }
210         }
211
212         // user defined functions
213         public void printit () {
214            print("load_finsihed\n");
215            
216            if (this.print_started) {
217                print("load_finsihed - already printing..%d %s\n", this.load_try, this.el.uri);
218            
219               
220               
221               
222               return;
223           }
224            
225          
226             this.print_started = true; // flag to stop double call.
227             
228             
229          // inject any javascript if needed..
230          if (webkitpdf.opt_inject_js != null) {
231                 
232             print("injecting javascript files \n");
233             foreach(var inject_js in  webkitpdf.opt_inject_js) {
234             print("inject? %s\n", inject_js);
235                string str;
236                try {
237                   FileUtils.get_contents( inject_js, out str);
238                } catch(FileError e) {
239                   print("Failed to inject %s\n",  inject_js);
240                   continue;
241                }
242         #if GTK3
243                GLib.MainLoop mainloop = new GLib.MainLoop();
244                this.el.run_javascript.begin(str, null, (obj,res) => {
245                   mainloop.quit();
246                });
247                mainloop.run();
248                                 
249         #else                   
250                this.el.execute_script(str);
251         #endif
252             }
253          }
254                   
255          print("calling print in %d seconds\n", (int)webkitpdf.opt_delay);
256          
257          if (webkitpdf.opt_target_pdf != null) {
258             GLib.Timeout.add_seconds(webkitpdf.opt_delay, () => { 
259                print("delay done URL: %s\n", this.el.uri);
260                         
261                                  
262                this.printpdf();
263                 return false;
264             }, GLib.Priority.DEFAULT);
265             return;
266          }
267                         
268         
269         #if GTK3
270          print("PNG not supported in webkit2\n");
271          return;
272         #else
273                         
274             GLib.Timeout.add_seconds(webkitpdf.opt_delay, () => { 
275            
276                         
277             // ----------------- JPEG 
278             // resize the window...
279             // window.document.documentElement.scrollHeight
280             var scroll_height = (int) _this.view.el.get_dom_document().document_element.scroll_height;
281             print("Scroll height %d\n", scroll_height);
282             if (scroll_height> 1024 || webkitpdf.opt_width > 0  || webkitpdf.opt_height > 0  ) {
283                var w = webkitpdf.opt_width > 0 ?  webkitpdf.opt_width  : 1200;
284                var h = int.min(scroll_height, 6000);
285                _this.scrolled_window.el.set_size_request( w, h); 
286                _this.el.resize (w+50, h+50);
287                print("Resize to %d, %d\n", w,h);
288                 GLib.Timeout.add_seconds(webkitpdf.opt_delay > 0 ? webkitpdf.opt_delay : 1 , () => { 
289                   this.printpng();
290                   return false;
291                  }, GLib.Priority.DEFAULT);
292                    return false;
293             }
294             this.printpng();            
295             return false;
296            }, GLib.Priority.DEFAULT);
297         
298         
299         #endif    
300             
301         }
302         public bool printpdf () {
303         
304         
305         
306             var list = Gtk.PaperSize.get_paper_sizes(false);
307              var psetup = new Gtk.PageSetup();
308              for(var i = 0; i < list.length(); i++ ) {
309                  var entry = list.nth_data(i).copy();
310                  if (entry.get_name() == "iso_a2") {
311                      psetup.set_paper_size(entry);
312                  }
313              }
314                     
315         
316         #if GTK3         
317         
318             var  pe = new  WebKit.PrintOperation(this.el);
319             pe.set_page_setup(psetup);
320             pe.finished.connect( () => {
321                print("print completed\n");
322                 this.delete_cookiefile(); 
323                 Gtk.main_quit();
324                         
325             });
326                         
327             var ps = new Gtk.PrintSettings();
328              ps.set_printer("Print to File");
329              ps.set("output-file-format", "pdf");
330              ps.set("output-uri", "file://" + webkitpdf.opt_target_pdf);
331         
332                         
333             pe.set_print_settings(ps);
334                         
335         
336             pe.print();
337                                   
338         
339         #else       
340             var  pe = new  Gtk.PrintOperation();
341             pe.export_filename = webkitpdf.opt_target_pdf;
342             print("got callback for print\n");
343             pe.ref();
344             /*pe.failed.connect(() => {
345                print("print failed\n");
346                 Gtk.main_quit();
347                         
348             })
349             */;
350              pe.done.connect(() => {
351                print("print completed\n");
352                this.delete_cookiefile(); 
353                 Gtk.main_quit();
354                         
355             });
356                         
357             //pe.run_dialog(_this.el);
358                  
359                         
360                         
361         
362         
363              pe.set_default_page_setup(psetup);
364              print("Calling Print?\n");
365              //pe.run_dialog(_this.el);
366                     
367                     
368         
369         
370         
371              try {
372                 this.el.get_main_frame().print_full(pe,Gtk.PrintOperationAction.EXPORT);
373              } catch (Error e) {
374                // print failed...
375             }
376         #endif      
377                     
378                      
379             return false;
380         }
381         public void printpng () {
382             //var filename = "/tmp/test.pdf";
383             //print("load_changed %d ?= %d\n", le, LoadEvent.FINISHED);
384         
385             //if (le != LoadEvent.FINISHED) {
386             //    return;
387            // }
388            
389         // what size is the documet.
390         
391              print("making screenshot\n");
392         #if GTK3
393         
394         #else     
395             // fix vapi - get_snapshot add '?' to all null.
396             var pixmap = _this.view.el.get_snapshot( null );
397         
398             
399             
400             int w,h;
401             
402             // add out to gdkpixmap.get_size
403          pixmap.get_size( out  w , out   h);
404          var pixbuf  = Gdk.pixbuf_get_from_drawable(null, pixmap, null , 0, 0, 0, 0, w, h);
405          print("pixbuf size: %d x %d\n ", w,h);
406                  
407             
408             
409              pixbuf.save(webkitpdf.opt_target_png, "png");
410              print("Saved to %s\n", webkitpdf.opt_target_png);
411             //view.get_snapshot.begin(WebKit.SnapshotRegion.FULL_DOCUMENT, WebKit.SnapshotOptions.NONE, null, (obj, res) => {
412             //    var sf = view.get_snapshot.end(res);
413         
414             //    sf.write_to_png(Browser.opt_target_png);
415             //});
416             Gtk.main_quit();
417              
418         #endif   
419             
420             
421         
422         }
423         
424         public void delete_cookiefile () {
425                    
426                    if(this.cookie_file.length >0 ){
427                        print("deleting tmp file %s\n",this.cookie_file);
428                 File file = File.new_for_path (this.cookie_file);
429                      try {
430                          if (file.query_exists () == true) {
431                              file.delete ();                 
432                          }
433                      } catch (Error e) {
434                               stdout.printf ("Error: %s\n", e.message);
435                      }
436                    }            
437         }
438     }
439
440
441 }