Fix runtime error
[geeqie.git] / src / exif-common.c
index 2af25a5..833a86c 100644 (file)
 #include "filefilter.h"
 #include "filecache.h"
 #include "format_raw.h"
+#include "glua.h"
 #include "ui_fileops.h"
 #include "cache.h"
 #include "jpeg_parser.h"
+#include "misc.h"
+#include "zonedetect.h"
 
 
 static gdouble exif_rational_to_double(ExifRational *r, gint sign)
@@ -383,6 +386,8 @@ static gchar *exif_build_formatted_ISOSpeedRating(ExifData *exif)
        gchar *text;
 
        text = exif_get_data_as_text(exif, "Exif.Photo.ISOSpeedRatings");
+       /* old canon may set this instead */
+       if (!text) text = exif_get_data_as_text(exif, "Exif.CanonSi.ISOSpeed");
        /* kodak may set this instead */
        if (!text) text = exif_get_data_as_text(exif, "Exif.Photo.ExposureIndex");
        return text;
@@ -607,6 +612,303 @@ static gchar *exif_build_formatted_GPSAltitude(ExifData *exif)
        return g_strdup_printf("%0.f m %s", alt, (ref==0)?_("Above Sea Level"):_("Below Sea Level"));
 }
 
+/**
+ * @brief Extracts timezone data from a ZoneDetect search structure
+ * @param[in] results ZoneDetect search structure
+ * @param[out] timezone in the form "Europe/London"
+ * @param[out] countryname in the form "United Kingdom"
+ * @param[out] countryalpha2 in the form "GB"
+ * 
+ * Refer to https://github.com/BertoldVdb/ZoneDetect
+ * for structure details
+ */
+static void zd_tz(ZoneDetectResult *results, gchar **timezone, gchar **countryname, gchar **countryalpha2)
+{
+       gchar *timezone_pre = NULL;
+       gchar *timezone_id = NULL;
+       unsigned int index = 0;
+
+       while(results[index].lookupResult != ZD_LOOKUP_END)
+               {
+               if(results[index].data)
+                       {
+                       for(unsigned int i=0; i<results[index].numFields; i++)
+                               {
+                               if (g_strstr_len(results[index].fieldNames[i], -1, "TimezoneIdPrefix"))
+                                       {
+                                       timezone_pre = g_strdup(results[index].data[i]);
+                                       }
+                               if (g_strstr_len(results[index].fieldNames[i], -1, "TimezoneId"))
+                                       {
+                                       timezone_id = g_strdup(results[index].data[i]);
+                                       }
+                               if (g_strstr_len(results[index].fieldNames[i], -1, "CountryName"))
+                                       {
+                                       *countryname = g_strdup(results[index].data[i]);
+                                       }
+                               if (g_strstr_len(results[index].fieldNames[i], -1, "CountryAlpha2"))
+                                       {
+                                       *countryalpha2 = g_strdup(results[index].data[i]);
+                                       }
+                               }
+                       }
+               index++;
+               }
+
+       *timezone = g_strconcat(timezone_pre, timezone_id, NULL);
+       g_free(timezone_pre);
+       g_free(timezone_id);
+}
+
+/**
+ * @brief Gets timezone data from an exif structure
+ * @param[in] exif
+ * @returns TRUE if timezone data found AND GPS date and time found
+ * @param[out] exif_date_time exif date/time in the form 2018:11:30:17:05:04
+ * @param[out] timezone in the form "Europe/London"
+ * @param[out] countryname in the form "United Kingdom"
+ * @param[out] countryalpha2 in the form "GB"
+ *
+ *
+ */
+static gboolean exif_build_tz_data(ExifData *exif, gchar **exif_date_time, gchar **timezone, gchar **countryname, gchar **countryalpha2)
+{
+       gfloat latitude;
+       gfloat longitude;
+       gchar *text_latitude;
+       gchar *text_longitude;
+       gchar *text_latitude_ref;
+       gchar *text_longitude_ref;
+       gchar *text_date;
+       gchar *text_time;
+       gchar *lat_deg;
+       gchar *lat_min;
+       gchar *lon_deg;
+       gchar *lon_min;
+       gchar *timezone_path;
+       ZoneDetect *cd;
+       ZoneDetectResult *results;
+       gboolean ret = FALSE;
+       gchar *basename;
+       gchar *path;
+
+       text_latitude = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSLatitude");
+       text_longitude = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSLongitude");
+       text_latitude_ref = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSLatitudeRef");
+       text_longitude_ref = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSLongitudeRef");
+       text_date = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSDateStamp");
+       text_time = exif_get_data_as_text(exif, "Exif.GPSInfo.GPSTimeStamp");
+
+       if (text_latitude && text_longitude && text_latitude_ref && text_longitude_ref)
+               {
+               lat_deg = strtok(text_latitude, "deg'");
+               lat_min = strtok(NULL, "deg'");
+               if (!lat_deg || !lat_min)
+                       {
+                       return FALSE;
+                       }
+               latitude = atof(lat_deg) + atof(lat_min) / 60;
+               if (!g_strcmp0(text_latitude_ref, "South"))
+                       {
+                       latitude = -latitude;
+                       }
+               lon_deg = strtok(text_longitude, "deg'");
+               lon_min = strtok(NULL, "deg'");
+               if (!lon_deg || !lon_min)
+                       {
+                       return FALSE;
+                       }
+               longitude = atof(lon_deg) + atof(lon_min) / 60;
+               if (!g_strcmp0(text_longitude_ref, "West"))
+                       {
+                       longitude = -longitude;
+                       }
+
+               path = path_from_utf8(TIMEZONE_DATABASE);
+               basename = g_path_get_basename(path);
+               timezone_path = g_build_filename(get_rc_dir(), basename, NULL);
+               if (g_file_test(timezone_path, G_FILE_TEST_EXISTS))
+                       {
+                       cd = ZDOpenDatabase(timezone_path);
+                       if (cd)
+                               {
+                               results = ZDLookup(cd, latitude, longitude, NULL);
+                               if (results)
+                                       {
+                                       zd_tz(results, timezone, countryname, countryalpha2);
+                                       ret = TRUE;
+                                       }
+                               }
+                       else
+                               {
+                               log_printf("Error: Init of timezone database %s failed\n", timezone_path);
+                               }
+                       ZDCloseDatabase(cd);
+                       }
+               g_free(path);
+               g_free(timezone_path);
+               g_free(basename);
+               }
+
+       if (ret && text_date && text_time)
+               {
+               *exif_date_time = g_strconcat(text_date, ":", text_time, NULL);
+               }
+       else
+               {
+               ret = FALSE;
+               }
+       return ret;
+}
+
+/**
+ * @brief Creates local time from GPS lat/long
+ * @param[in] exif
+ * @returns Localised time and date
+ *
+ * GPS lat/long is translated to timezone using ZoneDetect.
+ * GPS UTC is converted to Unix time stamp (seconds since 1970).
+ * The TZ environment variable is set to the relevant timezone
+ * and the Unix timestamp converted to local time using locale.
+ * If the conversion fails, unformatted UTC is returned.
+ */
+static gchar *exif_build_formatted_localtime(ExifData *exif)
+{
+       gchar buf[128];
+       gchar *tmp;
+       gint buflen;
+       GError *error = NULL;
+       gchar *time_zone_image;
+       gchar *time_zone_org;
+       struct tm *tm_local;
+       struct tm tm_utc;
+       time_t stamp;
+       gchar *exif_date_time = NULL;
+       gchar *timezone = NULL;
+       gchar *countryname = NULL;
+       gchar *countryalpha2 = NULL;
+
+       if (exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2))
+               {
+               time_zone_image = g_strconcat("TZ=", timezone, NULL);
+               time_zone_org = g_strconcat("TZ=", getenv("TZ"), NULL);
+               putenv("TZ=UTC");
+
+               memset(&tm_utc, 0, sizeof(tm_utc));
+               if (exif_date_time && strptime(exif_date_time, "%Y:%m:%d:%H:%M:%S", &tm_utc))
+                       {
+                       stamp = mktime(&tm_utc);        // Convert the struct to a Unix timestamp
+                       putenv(time_zone_image);        // Switch to destination time zone
+
+                       tm_local = localtime(&stamp);
+
+                       /* Convert to localtime using locale */
+                       buflen = strftime(buf, sizeof(buf), "%x %X", tm_local);
+                       if (buflen > 0)
+                               {
+                               tmp = g_locale_to_utf8(buf, buflen, NULL, NULL, &error);
+                               if (error)
+                                       {
+                                       log_printf("Error converting locale strftime to UTF-8: %s\n", error->message);
+                                       g_error_free(error);
+                                       }
+                               else
+                                       {
+                                       g_free(exif_date_time);
+                                       exif_date_time = tmp;
+                                       }
+                               }
+                       }
+               putenv(time_zone_org);
+
+               g_free(time_zone_image);
+               g_free(time_zone_org);
+               }
+
+       g_free(timezone);
+       g_free(countryname);
+       g_free(countryalpha2);
+
+       return exif_date_time;
+}
+
+/**
+ * @brief Gets timezone from GPS lat/long
+ * @param[in] exif
+ * @returns Timezone string in the form "Europe/London"
+ *
+ *
+ */
+static gchar *exif_build_formatted_timezone(ExifData *exif)
+{
+       gchar *exif_date_time = NULL;
+       gchar *timezone = NULL;
+       gchar *countryname = NULL;
+       gchar *countryalpha2 = NULL;
+
+       exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2);
+
+       g_free(exif_date_time);
+       g_free(countryname);
+       g_free(countryalpha2);
+
+       return timezone;
+}
+
+/**
+ * @brief Gets countryname from GPS lat/long
+ * @param[in] exif
+ * @returns Countryname string
+ *
+ *
+ */
+static gchar *exif_build_formatted_countryname(ExifData *exif)
+{
+       gchar *exif_date_time = NULL;
+       gchar *timezone = NULL;
+       gchar *countryname = NULL;
+       gchar *countryalpha2 = NULL;
+
+       exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2);
+
+       g_free(exif_date_time);
+       g_free(timezone);
+       g_free(countryalpha2);
+
+       return countryname;
+}
+
+/**
+ * @brief Gets two-letter country code from GPS lat/long
+ * @param[in] exif
+ * @returns Countryalpha2 string
+ *
+ *
+ */
+static gchar *exif_build_formatted_countrycode(ExifData *exif)
+{
+       gchar *exif_date_time = NULL;
+       gchar *timezone = NULL;
+       gchar *countryname = NULL;
+       gchar *countryalpha2 = NULL;
+
+       exif_build_tz_data(exif, &exif_date_time, &timezone, &countryname, &countryalpha2);
+
+       g_free(exif_date_time);
+       g_free(timezone);
+       g_free(countryname);
+
+       return countryalpha2;
+}
+
+static gchar *exif_build_formatted_star_rating(ExifData *exif)
+{
+       gint n = 0;
+
+       exif_get_integer(exif, "Xmp.xmp.Rating", &n);
+
+       return convert_rating_to_stars(n);
+}
 
 /* List of custom formatted pseudo-exif tags */
 #define EXIF_FORMATTED_TAG(name, label) { EXIF_FORMATTED()#name, label, exif_build_formatted##_##name }
@@ -627,9 +929,21 @@ ExifFormattedText ExifFormattedList[] = {
        EXIF_FORMATTED_TAG(ColorProfile,        N_("Color profile")),
        EXIF_FORMATTED_TAG(GPSPosition,         N_("GPS position")),
        EXIF_FORMATTED_TAG(GPSAltitude,         N_("GPS altitude")),
+       EXIF_FORMATTED_TAG(localtime,           N_("Local time")),
+       EXIF_FORMATTED_TAG(timezone,            N_("Time zone")),
+       EXIF_FORMATTED_TAG(countryname,         N_("Country name")),
+       EXIF_FORMATTED_TAG(countrycode,         N_("Country code")),
+       EXIF_FORMATTED_TAG(star_rating,         N_("Star rating")),
        {"file.size",                           N_("File size"),        NULL},
        {"file.date",                           N_("File date"),        NULL},
        {"file.mode",                           N_("File mode"),        NULL},
+       {"file.ctime",                          N_("File ctime"),       NULL},
+       {"file.owner",                          N_("File owner"),       NULL},
+       {"file.group",                          N_("File group"),       NULL},
+       {"file.link",                           N_("File link"),        NULL},
+       {"file.class",                          N_("File class"),       NULL},
+       {"file.page_no",                        N_("Page no."),         NULL},
+       {"lua.lensID",                          N_("Lens"),             NULL},
        { NULL, NULL, NULL }
 };
 
@@ -655,8 +969,7 @@ gchar *exif_get_description_by_key(const gchar *key)
 {
        if (!key) return NULL;
 
-       if (strncmp(key, EXIF_FORMATTED(), EXIF_FORMATTED_LEN) == 0 ||
-           strncmp(key, "file.", 5) == 0)
+       if (strncmp(key, EXIF_FORMATTED(), EXIF_FORMATTED_LEN) == 0 || strncmp(key, "file.", 5) == 0 || strncmp(key, "lua.", 4) == 0)
                {
                gint i;
 
@@ -878,6 +1191,8 @@ static gchar *mode_number(mode_t m)
 
 gchar *metadata_file_info(FileData *fd, const gchar *key, MetadataFormat format)
 {
+       gchar *page_n_of_m;
+
        if (strcmp(key, "file.size") == 0)
                {
                return g_strdup_printf("%ld", (long)fd->size);
@@ -890,8 +1205,63 @@ gchar *metadata_file_info(FileData *fd, const gchar *key, MetadataFormat format)
                {
                return mode_number(fd->mode);
                }
+       if (strcmp(key, "file.ctime") == 0)
+               {
+               return g_strdup(text_from_time(fd->cdate));
+               }
+       if (strcmp(key, "file.class") == 0)
+               {
+               return g_strdup(format_class_list[fd->format_class]);
+               }
+       if (strcmp(key, "file.owner") == 0)
+               {
+               return g_strdup(fd->owner);
+               }
+       if (strcmp(key, "file.group") == 0)
+               {
+               return g_strdup(fd->group);
+               }
+       if (strcmp(key, "file.link") == 0)
+               {
+               return g_strdup(fd->sym_link);
+               }
+       if (strcmp(key, "file.page_no") == 0)
+               {
+               if (fd->page_total > 1)
+                       {
+                       page_n_of_m = g_strdup_printf("[%d/%d]", fd->page_num + 1, fd->page_total);
+                       return page_n_of_m;
+                       }
+               else
+                       {
+                       return NULL;
+                       }
+               }
        return g_strdup("");
 }
 
+#ifdef HAVE_LUA
+gchar *metadata_lua_info(FileData *fd, const gchar *key, MetadataFormat format)
+{
+       gchar *script_name;
+       gchar *script_name_utf8;
+       gchar *data;
+       gchar *raw_data;
+       gchar *valid_data;
+
+       script_name_utf8 = g_strdup(key + 4);
+       script_name = path_from_utf8(script_name_utf8);
+
+       raw_data = lua_callvalue(fd, script_name, NULL);
+       valid_data = g_utf8_make_valid(raw_data, -1);
+       data = g_utf8_substring(valid_data, 0, 150);
 
+       g_free(script_name);
+       g_free(script_name_utf8);
+       g_free(raw_data);
+       g_free(valid_data);
+
+       return data;
+}
+#endif
 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */