Skip to content

Commit 6c0394e

Browse files
committed
Prevent missing images from breaking the app
1 parent 2fe8793 commit 6c0394e

2 files changed

Lines changed: 49 additions & 4 deletions

File tree

src/Services/Utils.vala

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,32 @@
2121

2222
public class Spice.Utils {
2323

24+
private const string[] ACCEPTED_TYPES = {
25+
"image/jpeg",
26+
"image/png",
27+
"image/tiff",
28+
"image/svg+xml",
29+
"image/gif"
30+
};
31+
32+
// Check if the filename has a picture file extension.
33+
public static bool is_valid_image (GLib.File file) {
34+
var file_info = file.query_info ("standard::*", 0);
35+
36+
// Check for correct file type, don't try to load directories and such
37+
if (file_info.get_file_type () != GLib.FileType.REGULAR) {
38+
return false;
39+
}
40+
41+
foreach (var type in ACCEPTED_TYPES) {
42+
if (GLib.ContentType.equals (file_info.get_content_type (), type)) {
43+
return true;
44+
}
45+
}
46+
47+
return false;
48+
}
49+
2450
public static void set_style (Gtk.Widget widget, string css) {
2551
try {
2652
var provider = new Gtk.CssProvider ();

src/Widgets/CanvasItems/ImageItem.vala

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,6 @@
2020
*/
2121

2222
public class Spice.ImageItem : Spice.CanvasItem {
23-
24-
public string uri = "";
25-
2623
const string IMAGE_STYLE_CSS = """
2724
.colored {
2825
background-color: transparent;
@@ -32,6 +29,24 @@ public class Spice.ImageItem : Spice.CanvasItem {
3229
background-repeat: no-repeat;
3330
}
3431
""";
32+
const string IMAGE_MISSING_CSS = """
33+
.colored {
34+
border: 4px dashed #000000;
35+
border-color: #c92e34;
36+
}""";
37+
38+
private bool valid = false;
39+
40+
private string uri_ = "";
41+
public string uri {
42+
get {
43+
return uri_;
44+
} set {
45+
uri_ = value;
46+
var file = File.new_for_uri (value);
47+
valid = (file.query_exists () && Utils.is_valid_image (file));
48+
}
49+
}
3550

3651
public ImageItem (Canvas canvas, Json.Object? save_data = null) {
3752
base (canvas);
@@ -57,6 +72,10 @@ public class Spice.ImageItem : Spice.CanvasItem {
5772
}
5873

5974
public override void style () {
60-
Utils.set_style (this, IMAGE_STYLE_CSS.printf (uri));
75+
if (valid) {
76+
Utils.set_style (this, IMAGE_STYLE_CSS.printf (uri));
77+
} else {
78+
Utils.set_style (this, IMAGE_MISSING_CSS);
79+
}
6180
}
6281
}

0 commit comments

Comments
 (0)