Debian Codegraph @

src/utils/Util.vala

raw
1 /*
2 * This code was partially imported from GNOME: https://github.com/GNOME/ease/blob/master/ease-core/ease-utilities.vala
3 *
4 * Ease, a GTK presentation application
5 * Copyright (C) 2010 Nate Stedman
6 * Copyright (c) 2017-2019 José Amuedo (https://github.com/spheras)
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 namespace DesktopFolder.Util {
23
24 /**
25 * @name get_desktop_bounding_box
26 * @description obtain the bounding box of all the desktop, calculating the area of all the get_n_monitors
27 * in the past this was done easier, but now the display get_width and height are deprecated
28 * @return {Gdk.Rectangle} the bounding box rectangle of all the desktop
29 */
30 public Gdk.Rectangle get_desktop_bounding_box () {
31 Gdk.Rectangle result = Gdk.Rectangle ();
32 Gdk.Screen screen = Gdk.Screen.get_default ();
33 Gdk.Display display = screen.get_display ();
34 int monitors = display.get_n_monitors ();
35 for (int i = 0; i < monitors; i++) {
36 Gdk.Monitor monitor = display.get_monitor (i);
37 Gdk.Rectangle warea = monitor.get_workarea ();
38 // debug("New rectangle: %d,%d -- %d,%d",warea.x,warea.y,warea.width,warea.height);
39 warea.union (result, out result);
40 }
41
42 return result;
43 }
44
45 /**
46 * Display a simple error message.
47 * @param title The title of the dialog.
48 * @param message The error message.
49 */
50 public void show_error_dialog (string ? title, string message) {
51 var dialog = new Gtk.MessageDialog (null, 0,
52 Gtk.MessageType.ERROR,
53 Gtk.ButtonsType.CLOSE,
54 "%s", message
55 );
56 dialog.title = title;
57 dialog.border_width = 5;
58 dialog.run ();
59 dialog.destroy ();
60 }
61
62 /**
63 * @name FileOperationAction
64 * @description delegate function to inform about the copy being operated
65 * @param {GLib.File} file the file being operated
66 */
67 public delegate void FileOperationAction (GLib.File file);
68
69 /**
70 * @name copy_recursive
71 * @description this function copy recursively from a GLib.File to a GLib.File
72 * @param {GLib.File} src the origin file
73 * @param {GLib.File} src the destination file
74 * @param {GLib.FileCopyFlags} flags the set of flags for the copy operation (NONE by default)
75 * @param {GLib.Cancellable} cancellable object to allow cancel the operation
76 * @param {FileOperationAction} listener the listener to get the current operation
77 * @return bool true->if everything was OK
78 */
79 public bool copy_recursive (GLib.File src, GLib.File dest, GLib.FileCopyFlags flags = GLib.FileCopyFlags.NONE,
80 GLib.Cancellable ? cancellable = null, FileOperationAction ? listener = null) throws GLib.Error {
81 GLib.FileType src_type = src.query_file_type (GLib.FileQueryInfoFlags.NONE, cancellable);
82
83 string src_path = src.get_path ();
84
85 GLib.File real_dest = dest;
86
87 if (src_path == real_dest.get_path ()) {
88 string basename = dest.get_basename ();
89 string dirname = dest.get_path ().replace (basename, "");
90 real_dest = GLib.File.new_for_path (dirname + make_next_duplicate_name (basename, dirname));
91 }
92
93 if (src_type == GLib.FileType.DIRECTORY) {
94 real_dest.make_directory (cancellable);
95 src.copy_attributes (real_dest, flags, cancellable);
96
97 GLib.FileEnumerator enumerator = src.enumerate_children (GLib.FileAttribute.STANDARD_NAME, GLib.FileQueryInfoFlags.NONE, cancellable);
98 for (GLib.FileInfo ? info = enumerator.next_file (cancellable); info != null; info = enumerator.next_file (cancellable)) {
99 copy_recursive (
100 GLib.File.new_for_path (GLib.Path.build_filename (src_path, info.get_name ())),
101 GLib.File.new_for_path (GLib.Path.build_filename (real_dest.get_path (), info.get_name ())),
102 flags,
103 cancellable, listener
104 );
105 }
106 } else if (src_type == GLib.FileType.REGULAR) {
107 if (listener != null) {
108 listener (real_dest);
109 } else {
110 debug ("copying %s", real_dest.get_basename ());
111 }
112
113 src.copy (real_dest, flags, cancellable);
114 }
115
116 return true;
117 }
118
119 /**
120 * Returns the parent window of the specified widget.
121 */
122 public Gtk.Window widget_window (Gtk.Widget widg) {
123 while (widg.get_parent () != null) widg = widg.get_parent ();
124 return widg as Gtk.Window;
125 }
126
127 /**
128 * Returns an absolute path for the given path.
129 */
130 public static string absolute_path (string path) {
131 var file = GLib.File.new_for_path (path);
132 return file.resolve_relative_path (".").get_path ();
133 }
134
135 /**
136 * Converts the given angle from degrees to radians.
137 *
138 * @param deg Angle in radians
139 * @return Angle in degrees
140 */
141 public static double deg_to_rad (double deg) {
142 return (deg * Math.PI / 180f);
143 }
144
145 /**
146 * Converts the given angle from radians to degrees.
147 *
148 * @param rad Angle in degrees
149 * @return Angle in radians
150 */
151 public static double rad_to_deg (double rad) {
152 return (rad / Math.PI * 180f);
153 }
154
155 /**
156 * @name create_new_photo
157 * @param {Gtk.Window} window the parent window to show the dialog
158 * @description show a dialog to create a new photo
159 */
160 public static void create_new_photo (Gtk.Window window, int x, int y) {
161 Gtk.FileChooserDialog chooser = new Gtk.FileChooserDialog (
162 DesktopFolder.Lang.PHOTO_SELECT_PHOTO_MESSAGE, window,
163 Gtk.FileChooserAction.OPEN,
164 DesktopFolder.Lang.DIALOG_CANCEL,
165 Gtk.ResponseType.CANCEL,
166 DesktopFolder.Lang.DIALOG_SELECT,
167 Gtk.ResponseType.ACCEPT);
168
169 Gtk.FileFilter filter = new Gtk.FileFilter ();
170 filter.set_name ("Images");
171 filter.add_mime_type ("image");
172 filter.add_mime_type ("image/png");
173 filter.add_mime_type ("image/jpeg");
174 filter.add_mime_type ("image/gif");
175 filter.add_pattern ("*.png");
176 filter.add_pattern ("*.jpg");
177 filter.add_pattern ("*.gif");
178 filter.add_pattern ("*.tif");
179 filter.add_pattern ("*.xpm");
180 chooser.add_filter (filter);
181
182 // Process response:
183 if (chooser.run () == Gtk.ResponseType.ACCEPT) {
184 var photo_path = chooser.get_filename ();
185 debug ("Photo path: " + photo_path);
186
187 try {
188 // Check if the image is valid
189 new Gdk.Pixbuf.from_file (photo_path);
190
191 PhotoSettings ps = new PhotoSettings (photo_path, window.get_window ());
192 ps.x = x;
193 ps.y = y;
194 string path = DesktopFolderApp.get_app_folder () + "/" + ps.name + "." + DesktopFolder.NEW_PHOTO_EXTENSION;
195 File file = File.new_for_path (path);
196 if (file.query_exists ()) {
197 debug ("Photo already exists, not creating.");
198 } else {
199 ps.save_to_file (file);
200 }
201 } catch {
202 debug ("Invalid photo: " + photo_path);
203 }
204 }
205 chooser.close ();
206 }
207
208 /**
209 * @name create_new_desktop_folder
210 * @description Create a new panel on the desktop
211 * @param {Gtk.Window} window The parent window to show the dialog
212 */
213 public static void create_new_desktop_folder (Gtk.Window window, int x, int y) {
214 string name = sanitize_name (make_next_duplicate_name (DesktopFolder.Lang.NEWLY_CREATED_PANEL, DesktopFolderApp.get_app_folder () + "/"));
215
216 // cancelling the current monitor
217 string folder_name = DesktopFolderApp.get_app_folder () + "/" + name;
218 DirUtils.create (folder_name, 0755);
219 File file = File.new_for_path (folder_name + "/.desktopfolder");
220 DesktopFolder.FolderSettings fs = new DesktopFolder.FolderSettings (name);
221
222 fs.x = x;
223 fs.y = y;
224 fs.recently_created = true;
225 fs.arrangement_type = get_default_arrangement_setting ();
226
227 fs.save_to_file (file);
228 }
229
230 /**
231 * @name make_next_duplicate_name
232 * @description Find a new name for the file
233 * @param {string} The base name to check if there's a duplicate
234 * @param {string} The path for the file
235 * @return {string} Either the original basename (if there wasn't a duplicate) or a new basename
236 */
237 public static string make_next_duplicate_name (string basename, string path) {
238 // TODO: Copy elementary's way of doing it
239 string new_path = sanitize_name (path);
240 if (!new_path.has_suffix ("/")) {
241 new_path += "/";
242 }
243 string name = sanitize_name (basename);
244 int ext_pos = name.last_index_of (".");
245 string ext = "";
246 string name_no_ext = name;
247 if (ext_pos != -1) {
248 ext = name.substring (ext_pos);
249 name_no_ext = name.replace (ext, "");
250 name_no_ext = name_no_ext.strip ();
251 }
252 try {
253 var regex = new Regex ("([ ]+[0-9]+)$");
254 MatchInfo matchinfo;
255 if (regex.match (name_no_ext, 0, out matchinfo)) {
256 int startpos = 0;
257 int endpos = 0;
258 matchinfo.fetch_pos (0, out startpos, out endpos);
259 // string regex_output = name_no_ext.slice ((long) startpos, (long) endpos);
260 name_no_ext = name_no_ext.splice ((long) startpos, (long) endpos);
261 }
262 } catch (Error e) {
263 debug (@"Error: $(e.message)");
264 }
265
266 string new_filename = "";
267
268 for (int i = 2; i < 1000000; i++) {
269 new_filename = @"$name_no_ext $i";
270 File file = File.new_for_path (new_path + new_filename + ext);
271 if (!file.query_exists ()) {
272 break;
273 }
274 }
275
276 // debug ("name: " + name + ", ext_pos: " + ext_pos.to_string () + ", ext: " + ext + ", name_no_ext: " + name_no_ext + ", file_to_check: " + file_to_check);
277 return new_filename;
278 }
279
280 /**
281 * @name create_new_link_panel
282 * @description create a new link panel to a folder (this means a link panel)
283 * @param {Gtk.Window} window the parent window to show the dialog
284 */
285 public static void create_new_link_panel (Gtk.Window window, int x, int y) {
286 Gtk.FileChooserDialog chooser = new Gtk.FileChooserDialog (
287 DesktopFolder.Lang.DESKTOPFOLDER_PANELLINK_MESSAGE, window, Gtk.FileChooserAction.OPEN,
288 DesktopFolder.Lang.DIALOG_CANCEL,
289 Gtk.ResponseType.CANCEL,
290 DesktopFolder.Lang.DIALOG_SELECT,
291 Gtk.ResponseType.ACCEPT);
292
293 chooser.set_action (Gtk.FileChooserAction.SELECT_FOLDER);
294
295 // Process response:
296 if (chooser.run () == Gtk.ResponseType.ACCEPT) {
297 var folderpath = chooser.get_filename ();
298 var foldername = Path.get_basename (folderpath);
299 File linkdest = File.new_for_path (DesktopFolderApp.get_app_folder () + "/" + foldername);
300 File settings_file = File.new_for_path (folderpath + "/.desktopfolder");
301
302 var fs = new FolderSettings (foldername);
303 fs.x = x;
304 fs.y = y;
305 fs.arrangement_type = get_default_arrangement_setting ();
306
307 fs.save_to_file (settings_file);
308
309 debug ("creating settings at: %s", folderpath + "/.desktopfolder");
310 debug ("file:%s", folderpath);
311 debug ("file name:%s", foldername);
312 debug ("link path:%s", DesktopFolderApp.get_app_folder () + "/" + foldername);
313 if (linkdest.query_exists ()) {
314 debug ("Link already exists, not creating.");
315 } else {
316 try {
317 var command = "ln -s \"" + folderpath + "\" \"" + DesktopFolderApp.get_app_folder () + "\"";
318 var appinfo = AppInfo.create_from_commandline (command, null, AppInfoCreateFlags.SUPPORTS_URIS);
319 appinfo.launch_uris (null, null);
320 } catch (Error e) {
321 stderr.printf ("Error: %s\n", e.message);
322 Util.show_error_dialog ("Error", e.message);
323 }
324 }
325
326
327 }
328
329 chooser.close ();
330 }
331
332 /**
333 * @name get_default_arrangement_setting
334 * @description return the global default arragament for new panels
335 */
336 private int get_default_arrangement_setting () {
337 GLib.Settings settings = new GLib.Settings ("com.github.spheras.desktopfolder");
338 string[] keys = settings.list_keys ();
339 bool found = false;
340 for (int i = 0; i < keys.length; i++) {
341 string key = keys[i];
342 if (key == "default-arrangement") {
343 found = true;
344 break;
345 }
346 }
347 int default_arrangement = FolderArrangement.ARRANGEMENT_TYPE_FREE;
348 if (found) {
349 default_arrangement = (int) settings.get_enum ("default-arrangement");
350 }
351 // debug ("default_arrangement: %d", default_arrangement);
352 return default_arrangement;
353 }
354
355 /**
356 * @name create_new_note
357 * @description create a new note inside the desktop
358 * @param {Gtk.Window} window the parent window to show the dialog
359 */
360 public static void create_new_note (Gtk.Window window, int x, int y) {
361 string newly_created_note = DesktopFolder.Lang.NEWLY_CREATED_NOTE;
362 string name = sanitize_name (make_next_duplicate_name (newly_created_note + "." + DesktopFolder.NEW_NOTE_EXTENSION, DesktopFolderApp.get_app_folder () + "/"));
363
364 string path = DesktopFolderApp.get_app_folder () + "/" + name + "." + DesktopFolder.NEW_NOTE_EXTENSION;
365 File file = File.new_for_path (path);
366 NoteSettings ns = new NoteSettings (name);
367
368 ns.x = x;
369 ns.y = y;
370
371 ns.edit_label_on_creation = true;
372
373 ns.save_to_file (file);
374 }
375
376 private static string sanitize_name (string new_name) {
377 string sanitized_name = new_name.strip ();
378 return sanitized_name;
379 }
380
381 private static bool check_name (string new_name) {
382 if (new_name != "" && !("/" in new_name) && !new_name.has_prefix (".")) {
383 return true;
384 } else {
385 return false;
386 }
387 }
388
389 delegate void ExecuteAfterError (Gtk.Window window);
390
391 /**
392 * @name show_file_exists_error_dialog
393 * @description Show an error saying that the file exists.
394 */
395 private static void show_file_exists_error_dialog (Gtk.Window window, string new_name, string widget_name, ExecuteAfterError ? callback) {
396 string message = "<big><b>" +
397 _("Could not create \"%'s\"").printf (new_name) +
398 "</b></big>\n\n" +
399 _(widget_name + " already exists.");
400 Gtk.MessageDialog dialog = new Gtk.MessageDialog (window, Gtk.DialogFlags.MODAL,
401 Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, message);
402 debug (widget_name + " already exists, not creating.");
403 dialog.response.connect ((response_id) => {
404 dialog.destroy ();
405 if (callback != null) {
406 callback (window);
407 }
408 });
409 dialog.set_deletable (false);
410 dialog.use_markup = true;
411 dialog.show ();
412 }
413
414 /**
415 * @name show_invalid_name_error_dialog
416 * @description Show an error saying that the name is invalid.
417 */
418 private static void show_invalid_name_error_dialog (Gtk.Window window, string new_name) {
419 string message = "<big><b>" +
420 _("Could not create \"%'s\"").printf (new_name) +
421 "</b></big>\n\n" +
422 _("Name is invalid.");
423 Gtk.MessageDialog dialog = new Gtk.MessageDialog (window, Gtk.DialogFlags.MODAL,
424 Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, message);
425 debug ("Invalid name, not creating");
426 dialog.response.connect ((response_id) => {
427 dialog.destroy ();
428 });
429 dialog.set_deletable (false);
430 dialog.use_markup = true;
431 dialog.show ();
432 }
433
434 /**
435 * Adds a closed sub-path rounded rectangle of the given size and border radius to the current path
436 * at position (x, y) in user-space coordinates.
437 *
438 * @param cr a {@link Cairo.Context}
439 * @param x the X coordinate of the top left corner of the rounded rectangle
440 * @param y the Y coordinate to the top left corner of the rounded rectangle
441 * @param width the width of the rounded rectangle
442 * @param height the height of the rounded rectangle
443 * @param radius the border radius of the rounded rectangle
444 */
445 public static void cairo_rounded_rectangle (Cairo.Context cr, double x, double y, double width, double height, double radius) {
446
447 cr.move_to (x + radius, y);
448 cr.arc (x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2);
449 cr.arc (x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5);
450 cr.arc (x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI);
451 cr.arc (x + radius, y + radius, radius, Math.PI, Math.PI * 1.5);
452 cr.close_path ();
453 }
454
455 /**
456 * @name blur_image_surface
457 * @description Performs a simple 2D Gaussian blur of radius @radius on surface @surface.
458 */
459 public static void blur_image_surface (Cairo.ImageSurface surface, int radius) {
460 debug ("start blur1");
461
462 Cairo.ImageSurface tmp;
463 int width, height;
464 int src_stride, dst_stride;
465 int x, y, z, w;
466 uchar[] src;
467 uchar[] dst;
468 int s, d;
469 uint32 a, p;
470 int i, j, k;
471 uint8 kernel[17];
472 int size = (int) (17 / sizeof (uint8));
473 int half = (int) ((17 / sizeof (uint8)) / 2);
474
475 if (surface.status () != Cairo.Status.SUCCESS) {
476 return;
477 }
478
479 width = surface.get_width ();
480 height = surface.get_height ();
481
482 debug ("start blur2");
483
484 switch (surface.get_format ()) {
485 case Cairo.Format.A1:
486 default:
487 /* Don't even think about it! */
488 return;
489 case Cairo.Format.A8:
490 /* Handle a8 surfaces by effectively unrolling the loops by a
491 * factor of 4 - this is safe since we know that stride has to be a
492 * multiple of uint32_t. */
493 width = width / 4;
494 break;
495 case Cairo.Format.RGB24:
496 case Cairo.Format.ARGB32:
497 break;
498 }
499
500 debug ("start blur2.1");
501
502 tmp = new Cairo.ImageSurface (Cairo.Format.ARGB32, width, height);
503 if (tmp.status () != Cairo.Status.SUCCESS)
504 return;
505
506 debug ("start blur2.2");
507 src = surface.get_data ();
508 debug ("start blur2.3");
509 src_stride = surface.get_stride ();
510 debug ("start blur2.4");
511
512 debug ("start blur2.5");
513
514 dst = tmp.get_data ();
515 dst_stride = tmp.get_stride ();
516
517 debug ("start blur3");
518
519 a = 0;
520 for (i = 0; i < size; i++) {
521 double f = i - half;
522 kernel[i] = (uint8) (Math.exp (-f * f / 30.0) * 80);
523 a = a + kernel[i];
524 }
525
526 /* Horizontally blur from surface -> tmp */
527 for (i = 0; i < height; i++) {
528 s = i * src_stride;
529 d = i * dst_stride;
530 for (j = 0; j < width; j++) {
531 if (radius < j && j < width - radius) {
532 dst[d + j] = src[s + j];
533 continue;
534 }
535
536 x = y = z = w = 0;
537 for (k = 0; k < size; k++) {
538 if (j - half + k < 0 || j - half + k >= width) {
539 continue;
540 }
541
542 p = src[s + j - half + k];
543
544 x = x + (int) (((p >> 24) & 0xff) * kernel[k]);
545 y = y + (int) (((p >> 16) & 0xff) * kernel[k]);
546 z = z + (int) (((p >> 8) & 0xff) * kernel[k]);
547 w = w + (int) (((p >> 0) & 0xff) * kernel[k]);
548 }
549 dst[d + j] = (uchar) ((x / a << 24) | (y / a << 16) | (z / a << 8) | w / a);
550 }
551 }
552
553 debug ("start blur4");
554
555 /* Then vertically blur from tmp -> surface */
556 for (i = 0; i < height; i++) {
557 s = i * dst_stride;
558 d = i * src_stride;
559 for (j = 0; j < width; j++) {
560 if (radius <= i && i < height - radius) {
561 src[j] = dst[j];
562 continue;
563 }
564
565 x = y = z = w = 0;
566 for (k = 0; k < size; k++) {
567 if (i - half + k < 0 || i - half + k >= height) {
568 continue;
569 }
570
571 s = (i - half + k) * dst_stride;
572 p = dst[s + j];
573
574 x = x + (int) (((p >> 24) & 0xff) * kernel[k]);
575 y = y + (int) (((p >> 16) & 0xff) * kernel[k]);
576 z = z + (int) (((p >> 8) & 0xff) * kernel[k]);
577 w = w + (int) (((p >> 0) & 0xff) * kernel[k]);
578 }
579 src[d + j] = (uchar) ((x / a << 24) | (y / a << 16) | (z / a << 8) | w / a);
580 }
581 }
582
583 debug ("start blur5");
584
585 // cairo_surface_destroy (tmp);
586 surface.mark_dirty ();
587 }
588
589 }