BrowserWindow.vala
[app.webkitpdf] / File.js
1 // <script type ="text/Javascript">
2 GLib = imports.gi.GLib;
3 Gio = imports.gi.Gio;
4
5 String  = imports.String.String;
6
7 /**
8 * @class File
9 * @singleton
10
11 * Library to wrap GLib and Gio basic File related methods
12
13 * usage:
14
15 * File = import.File.File;
16
17 * var contents = File.read("/tmp/test.txt");
18 *
19
20
21 */
22 var File = {
23     
24     /**
25      * @static
26      * @type {String} File seperator. (should be dynamic....)
27      */
28      
29     
30     SEPARATOR : '/',
31
32  // fixme - this needs a bitter location.. 
33     // they where in a string class before, but  overriding String methods is not a good normally a good idea..
34       
35     /**
36      * Right trim (in here to reduce dependancies)
37      * @param {String} s the string to trim
38      * @param {String} string to trim off right..
39      * @return {String} the trimmed string
40      */
41     rtrim : function (s,toTrim) {
42         if (s.substr(s.length - toTrim.length) == toTrim) {
43             return s.slice(0, s.length - toTrim.length);
44         }
45    
46         return s;
47     },
48     /**
49      * Trim a string (in here to reduce dependancies)
50      * @param {String} s the string to trim
51      * @param {String} string to trim off right..
52      * @return {String} the trimmed string
53      */
54     trim : function (s,toTrim) {
55         var out = this.ltrim(s,toTrim);
56         out = this.rtrim(out,toTrim);
57         return out;
58     },
59     /**
60      * Left Trim a string (in here to reduce dependancies)
61      * @param {String} s the string to trim
62      * @param {String} string to trim off right..
63      * @return {String} the trimmed string
64      */
65     ltrim : function (s, toTrim) {
66         if (s.substr(0, toTrim.length) == toTrim) {
67             return s.slice(toTrim.length);
68         }
69         
70         return s;
71     },
72     /**
73      * Get the base name of a path.
74      * @param {String} path
75      * @returns {String} basename
76     */
77     basename : function(path)
78     {
79         return path.split(File.SEPARATOR).pop();
80     },
81     
82     /**
83      * Get the directory name of a path. (could use Glib really)
84      * @param {String} path
85      * @returns {String} dirname
86     */
87     dirname : function(path)
88     {
89        var r = path.split(File.SEPARATOR)
90        r.pop();
91        return r.join(File.SEPARATOR);
92     },
93     
94     
95     /**
96      * Join a path with the Correct File seperator (unix only at present...)
97      * Takes a variable number of arguments, and joins them together.
98      * @return {String} the joined path
99      */
100     join : function () {
101         var out = "";
102         for (var i = 0; i < arguments.length; i++) {
103             if (i == 0) {
104               out += this.rtrim(arguments[i], File.SEPARATOR);
105             }
106             else if (i == arguments.length - 1) {
107               out += File.SEPARATOR + this.ltrim(arguments[i], File.SEPARATOR);
108             }
109             else {
110               out += File.SEPARATOR + this.trim(arguments[i], File.SEPARATOR);
111             }
112         }
113         return out;
114     },
115     /**
116      * Read a file and return as string
117      * @param {String} path The file location
118      * @return {String} the joined path
119      */
120     read : function (path) {
121         var out = {};
122         GLib.file_get_contents(path, out, null, null);
123         return out['value'];
124     },
125     /**
126      * Check if a path points to a file.
127      * @param {String} path The location
128      * @return {Boolean} true if it's a file
129      */
130     isFile : function (path) {
131       return GLib.file_test(path, GLib.FileTest.IS_REGULAR);
132     },
133     /**
134      * Check if a path points to a file, directory or link..
135      * @param {String} path The location
136      * @return {Boolean} true if it exists
137      */
138     exists : function (path) {
139       return GLib.file_test(path, GLib.FileTest.EXISTS);
140     },
141     /**
142      * Check if a path points to a directory.
143      * @param {String} path The location
144      * @return {Boolean} true if it's a directory
145      */
146     isDirectory : function (path) {
147       return GLib.file_test(path, GLib.FileTest.IS_DIR);
148     },
149     /**
150      * list files in a directory.
151      * @param {String} path The directory
152      * @return {Array} list of files (with full path?)
153      */
154     list : function (path) {
155         var listing = [];
156
157         var f = Gio.file_new_for_path(String(path));
158         var file_enum = f.enumerate_children(Gio.FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, Gio.FileQueryInfoFlags.NONE, null);
159
160         var next_file = null;
161
162         while ((next_file = file_enum.next_file(null)) != null) {
163           listing.push(next_file.get_display_name());
164         }
165
166         file_enum.close(null);
167
168         listing.sort();
169
170         return listing;
171     },
172     /**
173      * Get the last modification time of a file
174      * @param {String} path The location
175      * @return {Date} when the file was last modified
176      */
177     mtime : function (path) {
178         var f = Gio.file_new_for_path(String(path));
179         var mtime = new GLib.TimeVal();
180
181         var info = f.query_info(Gio.FILE_ATTRIBUTE_TIME_MODIFIED, Gio.FileQueryInfoFlags.NONE, null);
182         info.get_modification_time(mtime);
183
184         return new Date(mtime.tv_sec * 1000);
185     },
186     /**
187      * Resovle the absolute path of a file
188      * @param {String} path The location (relative) to current working directory?
189      * @return {String} the full path
190      */
191     canonical : function (path) {
192         var f = Gio.file_new_for_path(String(path));
193         var can = f.resolve_relative_path('');
194         return can.get_path();
195     },
196     
197     /**
198      * write a string to file
199      * @param {String} pathFile to write to
200      * @param {String} string  Contents of file.
201      * 
202      */
203     write : function (path, string) {
204         var f = Gio.file_new_for_path(String(path));
205         var data_out = new Gio.DataOutputStream({base_stream:f.replace(null, false, Gio.FileCreateFlags.NONE, null)});
206         data_out.put_string(string, null);
207         data_out.close(null);
208     },
209         /**
210      * write a string to file
211      * @param {String} pathFile to write to
212      * @param {String} string  Contents of file.
213      * 
214      */
215     writeBinaryArray : function (path, stringAr) {
216         var f = Gio.file_new_for_path(String(path));
217         var data_out = new Gio.DataOutputStream({base_stream:f.replace(null, false, Gio.FileCreateFlags.NONE, null)});
218         for(var i =0; i < stringAr.length; i++) {
219             data_out.put_byte(stringAr[i], null);
220             if (i % 10000 == 0) {
221                 print("wrote " + i + "/" + stringAr.length + "\n");
222             }
223             
224         }
225         data_out.close(null);
226     },
227     /**
228      * append a string to a file
229      * @param {String} path  File to write to
230      * @param {String}  string string to append to file.
231      * 
232      */
233     append : function (path, string) {
234         var f = Gio.file_new_for_path(String(path));
235         var data_out = new Gio.DataOutputStream({
236                 base_stream:f.append_to(Gio.FileCreateFlags.NONE, null)
237         });
238         data_out.put_string(string, null);
239         data_out.close(null);
240     },
241     /**
242      * Delete a file.
243      * @param  {String} path  File to remove    
244      */
245     remove : function (path)
246     {
247         var f = Gio.file_new_for_path(String(path));
248         return f['delete']();
249     },
250     /**
251      * copy files recursively from fromDir, silently ignore them if they already exist in toDir
252      *        unless you select overwrite..
253      * @param {String} src source path
254      * @param {String} dest destination path
255      * @param {Gio.FileCopyFlags} options (optional)  - use Gio.FileCopyFlags.OVERWRITE to 
256      *      otherwise they will not be copied
257      * 
258      */
259     silentRecursiveCopy : function (fromDir, toDir, opts) {
260         
261         var filesToCopy = File.recursiveListing(fromDir);
262         var srcPath, destPath, src, dest;
263         if (typeof(opts) =='undefined') {
264             opts = Gio.FileCopyFlags.NONE;
265         }
266         
267         for (var index in filesToCopy) {
268             srcPath = File.join(String(fromDir), filesToCopy[index]);
269             destPath = File.join(String(toDir), filesToCopy[index]);
270
271             if (File.isDirectory(srcPath) && !File.isDirectory(destPath)) {
272                 File.mkdir(destPath);
273                 continue;
274             }
275             // source is not file..?!?!?
276             if (!File.isFile(srcPath)) {
277                 continue;
278             }
279             if (File.isFile(destPath) && opts == Gio.FileCopyFlags.NONE) {
280                 // do not overwrite.. - if file exists and we are not flaged to overwrite.
281                 continue;
282             }
283             
284             File.copyFile(srcPath, destPath, opts);
285            
286         }
287     },
288     
289     /**
290      * make a directory..
291      * @param {String} dstPath directory to make
292      */
293     mkdir : function (destPath) {
294         var dest = Gio.file_new_for_path(String(destPath));
295         print (destPath);
296         try {
297                 return dest.make_directory(null, null);
298 } catch(e) {
299 return false;
300 }
301     },
302     
303     /**
304      * make a directory..
305      * @param {String} dstPath directory to make
306      */
307     mkdirall : function (destPath) {
308         var parent = File.dirname(destPath);
309         if (!File.exists(parent)) {
310             File.mkdirall(parent);
311         }
312         if (!File.exists(destPath)) {
313             return File.mkdir(destPath); 
314         }
315         return true;
316     },
317     
318     /**
319      * copy a File
320      * @param {String} src source path
321      * @param {String} dest destination path
322      * @param {Gio.FileCopyFlags} options (optional)  - use Gio.FileCopyFlags.OVERWRITE to .. overwrite..
323      * 
324      */
325     copyFile : function (srcPath, destPath, opts) {
326         if (typeof(opts) =='undefined') {
327             opts = Gio.FileCopyFlags.NONE;
328         }
329         var dest = Gio.file_new_for_path(String(destPath));
330         var src = Gio.file_new_for_path(String(srcPath));
331
332         // a bit of a hack for the fact that Gio.File.copy arguments
333         // can be nulled, but not according to the GIR file
334         return src.copy(dest, opts);
335     },
336     /**
337      * recursively list files in a directory.
338      * @param {String} path The directory
339      * @return {Array} list of files (with full path?)
340      */
341     recursiveListing : function (dir) {
342
343         function recursiveListingInternal(prefix, listing, dir) {
344             var entries = File.list(dir);
345             var next, fullPath;
346   
347             for (var index in entries) {
348               next = entries[index];
349               fullPath = File.join(prefix, dir, next);
350   
351               if (File.isDirectory(fullPath)) {
352                 listing.push(next);
353                 listing = listing.concat(recursiveListingInternal(next, [], fullPath));
354               }
355               else {
356                 if (prefix) {
357                   next = File.join(prefix, next);
358                 }
359                 listing.push(next);
360               }
361             }
362   
363             return listing;
364         }
365
366         return recursiveListingInternal('', [], dir);
367     }
368
369 };