#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cx/map.h>
#include "toolkit.h"
#include "icon.h"
#include "../common/properties.h"
static CxMap *image_map;
static GtkIconTheme *icon_theme;
#if GTK_MAJOR_VERSION >=
4
#define ICONTHEME_GET_DEFAULT() gtk_icon_theme_get_for_display(gdk_display_get_default())
#else
#define ICONTHEME_GET_DEFAULT() gtk_icon_theme_get_default()
#endif
void ui_image_init(
void) {
image_map = cxHashMapCreateSimple(
CX_STORE_POINTERS);
icon_theme =
ICONTHEME_GET_DEFAULT();
}
GdkPixbuf* ui_get_image(
const char *name) {
UiImage *img = cxMapGet(image_map, name);
if(img) {
return img->pixbuf;
}
else {
return NULL;
}
}
static UiIcon* get_icon(
const char *name,
int size,
int scale) {
#if GTK_MAJOR_VERSION >=
4
GtkIconPaintable *info = gtk_icon_theme_lookup_icon(icon_theme, name,
NULL, size, scale,
GTK_TEXT_DIR_LTR,
GTK_ICON_LOOKUP_FORCE_REGULAR);
#elif defined(
UI_SUPPORTS_SCALE)
GtkIconInfo *info = gtk_icon_theme_lookup_icon_for_scale(icon_theme, name, size, scale,
0);
#else
GtkIconInfo *info = gtk_icon_theme_lookup_icon(icon_theme, name, size,
0);
#endif
if(info) {
UiIcon *icon = malloc(
sizeof(UiIcon));
icon->info = info;
icon->pixbuf =
NULL;
return icon;
}
return NULL;
}
UiIcon* ui_icon(
const char* name,
size_t size) {
return get_icon(name, size, ui_get_scalefactor());
}
UiIcon* ui_imageicon(
const char* file) {
GError *error =
NULL;
GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(file, &error);
if(!pixbuf) {
fprintf(stderr,
"UiError: Cannot load image: %s\n", file);
return NULL;
}
UiIcon *icon = malloc(
sizeof(UiIcon));
icon->info =
NULL;
icon->pixbuf = pixbuf;
return icon;
}
void ui_icon_free(UiIcon* icon) {
if(icon->info) {
g_object_unref(icon->info);
}
if(icon->pixbuf) {
g_object_unref(icon->pixbuf);
}
free(icon);
}
UiIcon* ui_foldericon(
size_t size) {
return ui_icon(
"folder", size);
}
UiIcon* ui_fileicon(
size_t size) {
UiIcon *icon = ui_icon(
"file", size);
#if GTK_MAJOR_VERSION >=
4
GFile *file = gtk_icon_paintable_get_file(icon->info);
char *path = g_file_get_path(file);
if(!path) {
icon = ui_icon(
"application-x-generic", size);
}
#else
if(!icon) {
icon = ui_icon(
"application-x-generic", size);
}
#endif
return icon;
}
UiIcon* ui_icon_unscaled(
const char *name,
int size) {
return get_icon(name, size,
1);
}
#if GTK_MAJOR_VERSION >=
4
GdkPixbuf* ui_icon_pixbuf(UiIcon *icon) {
if(!icon->pixbuf) {
GFile *file = gtk_icon_paintable_get_file(icon->info);
GError *error =
NULL;
char *path = g_file_get_path(file);
icon->pixbuf = gdk_pixbuf_new_from_file(path, &error);
}
return icon->pixbuf;
}
#else
GdkPixbuf* ui_icon_pixbuf(UiIcon *icon) {
if(!icon->pixbuf) {
GError *error =
NULL;
icon->pixbuf = gtk_icon_info_load_icon(icon->info, &error);
}
return icon->pixbuf;
}
#endif
void ui_free_image(UiImage *img) {
g_object_unref(img->pixbuf);
free(img);
}