Debian Codegraph @

src/utilities/utilities_files.py

raw symbols SCIP
1 # Licensed under GPL3 https://github.com/maoschanz/drawing/blob/master/LICENSE
2
3 from gi.repository import Gtk, Gio
4
5 ################################################################################
6
7 def utilities_add_filechooser_filters(dialog):
8 """Add file filters for images to file chooser dialogs."""
9 allPictures = Gtk.FileFilter()
10 allPictures.set_name(_("All pictures"))
11 allPictures.add_mime_type('image/png')
12 allPictures.add_mime_type('image/jpeg')
13 allPictures.add_mime_type('image/bmp')
14
15 pngPictures = Gtk.FileFilter()
16 pngPictures.set_name(_("PNG images"))
17 pngPictures.add_mime_type('image/png')
18
19 jpegPictures = Gtk.FileFilter()
20 jpegPictures.set_name(_("JPEG images"))
21 jpegPictures.add_mime_type('image/jpeg')
22
23 bmpPictures = Gtk.FileFilter()
24 bmpPictures.set_name(_("BMP images"))
25 bmpPictures.add_mime_type('image/bmp')
26
27 dialog.add_filter(allPictures)
28 dialog.add_filter(pngPictures)
29 dialog.add_filter(jpegPictures)
30 dialog.add_filter(bmpPictures)
31
32 ################################################################################
33
34 def utilities_gfile_is_image(gfile, error_msg=""):
35 try:
36 infos = gfile.query_info('standard::*', Gio.FileQueryInfoFlags.NONE, None)
37 if 'image/' in infos.get_content_type():
38 # The exact file format of the image isn't validated here because i
39 # can't assume what gdkpixbuf is able to read (it's modular, and it
40 # evolves). An InvalidFileFormatException will be raised by DrImage
41 # if the file can't be loaded.
42 return True, error_msg
43 else:
44 error_msg = error_msg + _("%s isn't an image.") % gfile.get_path()
45 except Exception as err:
46 error_msg = error_msg + err.message
47 return False, error_msg
48
49 class InvalidFileFormatException(Exception):
50 def __init__(self, initial_message, fpath):
51 self.message = initial_message
52 cpt = 0
53 with open(fpath, 'rb') as f:
54 riff_bytes = f.read(4)
55 size_bytes = f.read(4)
56 webp_bytes = f.read(4)
57 if riff_bytes == b'RIFF' and webp_bytes == b'WEBP':
58 msg = _("Sorry, WEBP images can't be loaded by this app.") + " 😢 "
59 if fpath[-5:] != '.webp':
60 # Context: an error message, %s is a file path
61 msg = msg + _("Despite its name, %s is a WEBP file.") % fpath
62 self.message = msg
63 super().__init__(self.message)
64 # This exception is meant to be raised when a file is detected as an image
65 # by Gio (see utility function above) BUT can't be loaded into a GdkPixbuf.
66 # It usually means the file is corrupted, or has a deceptive name (for
67 # example "xxx.jpeg" despite being a text file), or is just an image format
68 # not supported by the GdkPixbuf version installed by the user.
69
70 ################################################################################
71