Compare commits

...

6 Commits

14 changed files with 372 additions and 337 deletions

12
.clang-format Normal file
View File

@ -0,0 +1,12 @@
BasedOnStyle: LLVM
ColumnLimit: 80
IndentWidth: 4
TabWidth: 4
UseTab: ForContinuationAndIndentation
AlwaysBreakAfterReturnType: AllDefinitions
BreakBeforeBraces: Linux
SpaceAfterCStyleCast: true
AlignAfterOpenBracket: DontAlign
AlignOperands: DontAlign
SpacesBeforeTrailingComments: 2
WhitespaceSensitiveMacros: ['G_DEFINE_QUARK']

View File

@ -2,41 +2,13 @@ fastiv
======
'fastiv' is a fast image viewer, supporting BMP, PNG, GIF, JPEG, and optionally
RAW pictures.
RAW pictures. Currently, it's not particularly usable.
It is meant to be a viable replacement for Eye of GNOME, which is slow, likes
to break on huge pictures, and its underlying gdk-pixbuf can only be made to use
the broken libopenraw
https://mail.gnome.org/archives/eog-list/2016-January/msg00004.html[as of now].
Further development
-------------------
Urgent blockers for the first stable version:
- directory browsing
- implement zoom and scrolling
High priority:
- some level of asynchronous loading and preloading,
which becomes a difficult problem with network mounts,
confusingly acting as fast devices
- write a replacement for GNOME's Nautilus in grid mode:
read-only, with focus on staggered previews and minimising wasted space
Low priority:
- display 16-bit pictures smoothly, using the 30-bit depth under X.org
- make RAW as fast as it can possibly be
- load everything that resembles a picture, potentially even play video
- port to something less hostile than the current GNOME stack, such as SDL,
although it may involve a lot of reimplemented code,
or result in reduced functionality
Non-goals:
- fancy UI, focus solely on speed of use
Non-goals
---------
- fancy UI--the focus is on speed of use first, colour accuracy second
- memory efficiency, though preloading can cause some pressure
- portability to non-UNIXy systems
Packages
--------
@ -46,8 +18,8 @@ a package with the latest development version from Archlinux's AUR.
Building and Running
--------------------
Build dependencies: Meson, pkg-config +
Runtime dependencies: gtk+-3.0, libpng > 1.5.4, libturbojpeg, LibRaw (optional),
shared-mime-info
Runtime dependencies: gtk+-3.0, shared-mime-info, libpng>=1.5.4, libturbojpeg,
LibRaw (optional)
$ git clone --recursive https://git.janouch.name/p/fastiv.git
$ meson builddir

View File

@ -18,6 +18,7 @@
#include <math.h>
#include "fastiv-browser.h"
#include "fastiv-io.h"
#include "fastiv-view.h"
typedef struct entry Entry;
@ -73,8 +74,8 @@ fastiv_browser_get_request_mode(G_GNUC_UNUSED GtkWidget *widget)
}
static void
fastiv_browser_get_preferred_width(GtkWidget *widget,
gint *minimum, gint *natural)
fastiv_browser_get_preferred_width(
GtkWidget *widget, gint *minimum, gint *natural)
{
G_GNUC_UNUSED FastivBrowser *self = FASTIV_BROWSER(widget);
// TODO(p): Set it to the width of the widget with one wide item within.
@ -82,8 +83,8 @@ fastiv_browser_get_preferred_width(GtkWidget *widget,
}
static void
fastiv_browser_get_preferred_height_for_width(GtkWidget *widget,
G_GNUC_UNUSED gint width, gint *minimum, gint *natural)
fastiv_browser_get_preferred_height_for_width(
GtkWidget *widget, G_GNUC_UNUSED gint width, gint *minimum, gint *natural)
{
G_GNUC_UNUSED FastivBrowser *self = FASTIV_BROWSER(widget);
// TODO(p): Re-layout, figure it out.
@ -108,8 +109,8 @@ fastiv_browser_realize(GtkWidget *widget)
.wclass = GDK_INPUT_OUTPUT,
.visual = gtk_widget_get_visual(widget),
.event_mask = gtk_widget_get_events(widget)
| GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK,
.event_mask = gtk_widget_get_events(widget) | GDK_KEY_PRESS_MASK |
GDK_BUTTON_PRESS_MASK,
};
// We need this window to receive input events at all.
@ -130,8 +131,8 @@ fastiv_browser_draw(GtkWidget *widget, cairo_t *cr)
GtkAllocation allocation;
gtk_widget_get_allocation(widget, &allocation);
gtk_render_background(gtk_widget_get_style_context(widget), cr,
0, 0, allocation.width, allocation.height);
gtk_render_background(gtk_widget_get_style_context(widget), cr, 0, 0,
allocation.width, allocation.height);
const double row_height = 256;
@ -151,8 +152,8 @@ fastiv_browser_draw(GtkWidget *widget, cairo_t *cr)
int projected_width = round(scale * width);
int projected_height = round(scale * height);
if (occupied_width != 0
&& occupied_width + projected_width > allocation.width) {
if (occupied_width != 0 &&
occupied_width + projected_width > allocation.width) {
occupied_width = 0;
y += row_height;
}
@ -177,17 +178,15 @@ fastiv_browser_class_init(FastivBrowserClass *klass)
GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(klass);
widget_class->get_request_mode = fastiv_browser_get_request_mode;
widget_class->get_preferred_width =
fastiv_browser_get_preferred_width;
widget_class->get_preferred_width = fastiv_browser_get_preferred_width;
widget_class->get_preferred_height_for_width =
fastiv_browser_get_preferred_height_for_width;
widget_class->realize = fastiv_browser_realize;
widget_class->draw = fastiv_browser_draw;
// TODO(p): Connect to this and emit it.
browser_signals[ITEM_ACTIVATED] =
g_signal_new("item-activated", G_TYPE_FROM_CLASS(klass),
0, 0, NULL, NULL, NULL, G_TYPE_NONE, 0);
browser_signals[ITEM_ACTIVATED] = g_signal_new("item-activated",
G_TYPE_FROM_CLASS(klass), 0, 0, NULL, NULL, NULL, G_TYPE_NONE, 0);
// TODO(p): Later override "screen_changed", recreate Pango layouts there,
// if we get to have any, or otherwise reflect DPI changes.
@ -216,12 +215,12 @@ fastiv_browser_load(FastivBrowser *self, const char *path)
const char *filename;
while ((filename = g_dir_read_name(dir))) {
if (!strcmp(filename, ".")
|| !strcmp(filename, ".."))
if (!strcmp(filename, ".") || !strcmp(filename, ".."))
continue;
gchar *subpath = g_build_filename(path, filename, NULL);
g_array_append_val(self->entries, ((Entry) {
g_array_append_val(self->entries,
((Entry){
.thumbnail = fastiv_io_lookup_thumbnail(subpath),
.filename = subpath,
}));

View File

@ -15,8 +15,8 @@
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#include <time.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <time.h>
#include "fastiv-view.h"

View File

@ -17,8 +17,8 @@
#include "config.h"
#include <glib.h>
#include <cairo.h>
#include <glib.h>
#include <turbojpeg.h>
#ifdef HAVE_LIBRAW
#include <libraw.h>
@ -37,6 +37,22 @@
#define WUFFS_CONFIG__MODULE__ZLIB
#include "wuffs-mirror-release-c/release/c/wuffs-v0.3.c"
#include "xdg.h"
// A subset of shared-mime-info that produces an appropriate list of
// file extensions. Chiefly motivated by the suckiness of RAW images:
// someone else will maintain the list of file extensions for us.
const char *fastiv_io_supported_media_types[] = {
"image/bmp",
"image/gif",
"image/png",
"image/jpeg",
#ifdef HAVE_LIBRAW
"image/x-dcraw",
#endif // HAVE_LIBRAW
NULL
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#define FASTIV_IO_ERROR fastiv_io_error_quark()
@ -50,8 +66,7 @@ enum FastivIoError {
static void
set_error(GError **error, const char *message)
{
g_set_error_literal(error,
FASTIV_IO_ERROR, FASTIV_IO_ERROR_OPEN, message);
g_set_error_literal(error, FASTIV_IO_ERROR, FASTIV_IO_ERROR_OPEN, message);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@ -60,8 +75,8 @@ set_error(GError **error, const char *message)
// is pure C, and a good reference. I can't use the auxiliary libraries,
// since they depend on C++, which is undesirable.
static cairo_surface_t *
open_wuffs(wuffs_base__image_decoder *dec,
wuffs_base__io_buffer src, GError **error)
open_wuffs(
wuffs_base__image_decoder *dec, wuffs_base__io_buffer src, GError **error)
{
wuffs_base__image_config cfg;
wuffs_base__status status =
@ -156,8 +171,8 @@ open_wuffs(wuffs_base__image_decoder *dec,
// Starting to modify pixel data directly. Probably an unnecessary call.
cairo_surface_flush(surface);
status = wuffs_base__image_decoder__decode_frame(dec, &pb, &src,
WUFFS_BASE__PIXEL_BLEND__SRC, workbuf, NULL);
status = wuffs_base__image_decoder__decode_frame(
dec, &pb, &src, WUFFS_BASE__PIXEL_BLEND__SRC, workbuf, NULL);
if (!wuffs_base__status__is_ok(&status)) {
set_error(error, wuffs_base__status__message(&status));
cairo_surface_destroy(surface);
@ -182,8 +197,8 @@ open_wuffs_using(wuffs_base__image_decoder *(*allocate)(),
return NULL;
}
cairo_surface_t *surface = open_wuffs(dec,
wuffs_base__ptr_u8__reader((uint8_t *) data, len, TRUE), error);
cairo_surface_t *surface = open_wuffs(
dec, wuffs_base__ptr_u8__reader((uint8_t *) data, len, TRUE), error);
free(dec);
return surface;
}
@ -241,8 +256,8 @@ open_libjpeg_turbo(const gchar *data, gsize len, GError **error)
int stride = cairo_image_surface_get_stride(surface);
if (tjDecompress2(dec, (const unsigned char *) data, len,
cairo_image_surface_get_data(surface), width, stride,
height, pixel_format, TJFLAG_ACCURATEDCT)) {
cairo_image_surface_get_data(surface), width, stride, height,
pixel_format, TJFLAG_ACCURATEDCT)) {
set_error(error, tjGetErrorStr2(dec));
cairo_surface_destroy(surface);
tjDestroy(dec);
@ -253,8 +268,8 @@ open_libjpeg_turbo(const gchar *data, gsize len, GError **error)
if (pixel_format == TJPF_CMYK) {
// CAIRO_STRIDE_ALIGNMENT is 4 bytes, so there will be no padding with
// ARGB/BGR/XRGB/BGRX.
trivial_cmyk_to_bgra(cairo_image_surface_get_data(surface),
width * height);
trivial_cmyk_to_bgra(
cairo_image_surface_get_data(surface), width * height);
}
// Pixel data has been written, need to let Cairo know.
@ -270,8 +285,8 @@ static cairo_surface_t *
open_libraw(const gchar *data, gsize len, GError **error)
{
// https://github.com/LibRaw/LibRaw/issues/418
libraw_data_t *iprc = libraw_init(LIBRAW_OPIONS_NO_MEMERR_CALLBACK
| LIBRAW_OPIONS_NO_DATAERR_CALLBACK);
libraw_data_t *iprc = libraw_init(
LIBRAW_OPIONS_NO_MEMERR_CALLBACK | LIBRAW_OPIONS_NO_DATAERR_CALLBACK);
if (!iprc) {
set_error(error, "failed to obtain a LibRaw handle");
return NULL;
@ -354,8 +369,8 @@ open_libraw(const gchar *data, gsize len, GError **error)
unsigned char *p = image->data;
for (ushort y = 0; y < image->height; y++) {
for (ushort x = 0; x < image->width; x++) {
*pixels++ = 0xff000000 | (uint32_t) p[0] << 16
| (uint32_t) p[1] << 8 | (uint32_t) p[2];
*pixels++ = 0xff000000 | (uint32_t) p[0] << 16 |
(uint32_t) p[1] << 8 | (uint32_t) p[2];
p += 3;
}
}
@ -393,18 +408,18 @@ fastiv_io_open(const gchar *path, GError **error)
// Note that BMP can redirect into another format,
// which is so far unsupported here.
surface = open_wuffs_using(
wuffs_bmp__decoder__alloc_as__wuffs_base__image_decoder,
data, len, error);
wuffs_bmp__decoder__alloc_as__wuffs_base__image_decoder, data, len,
error);
break;
case WUFFS_BASE__FOURCC__GIF:
surface = open_wuffs_using(
wuffs_gif__decoder__alloc_as__wuffs_base__image_decoder,
data, len, error);
wuffs_gif__decoder__alloc_as__wuffs_base__image_decoder, data, len,
error);
break;
case WUFFS_BASE__FOURCC__PNG:
surface = open_wuffs_using(
wuffs_png__decoder__alloc_as__wuffs_base__image_decoder,
data, len, error);
wuffs_png__decoder__alloc_as__wuffs_base__image_decoder, data, len,
error);
break;
case WUFFS_BASE__FOURCC__JPEG:
surface = open_libjpeg_turbo(data, len, error);
@ -432,11 +447,8 @@ fastiv_io_open(const gchar *path, GError **error)
// scaled, linear encoded, pre-multiplied component values must be used!"
//
// We can use the pixman library to scale, PIXMAN_a8r8g8b8_sRGB.
#include <png.h>
#include <glib/gstdio.h>
// TODO(p): Reorganize the sources.
gchar *get_xdg_home_dir(const char *var, const char *default_);
#include <png.h>
static void
redirect_png_error(png_structp pngp, const char *error)
@ -453,8 +465,8 @@ discard_png_warning(png_structp pngp, const char *warning)
}
static int
check_png_thumbnail(png_structp pngp, png_infop infop, const gchar *target,
time_t mtime)
check_png_thumbnail(
png_structp pngp, png_infop infop, const gchar *target, time_t mtime)
{
// May contain Thumb::Image::Width Thumb::Image::Height,
// but those aren't interesting currently (would be for fast previews).
@ -482,8 +494,8 @@ check_png_thumbnail(png_structp pngp, png_infop infop, const gchar *target,
// TODO(p): Support spng as well (it can't premultiply alpha by itself,
// but at least it won't gamma-adjust it for us).
static cairo_surface_t *
read_png_thumbnail(const gchar *path, const gchar *uri, time_t mtime,
GError **error)
read_png_thumbnail(
const gchar *path, const gchar *uri, time_t mtime, GError **error)
{
FILE *fp;
if (!(fp = fopen(path, "rb"))) {
@ -492,8 +504,8 @@ read_png_thumbnail(const gchar *path, const gchar *uri, time_t mtime,
}
cairo_surface_t *volatile surface = NULL;
png_structp pngp = png_create_read_struct(PNG_LIBPNG_VER_STRING,
error, redirect_png_error, discard_png_warning);
png_structp pngp = png_create_read_struct(
PNG_LIBPNG_VER_STRING, error, redirect_png_error, discard_png_warning);
png_infop infop = png_create_info_struct(pngp);
if (!infop) {
set_error(error, g_strerror(errno));
@ -603,8 +615,8 @@ fastiv_io_lookup_thumbnail(const gchar *target)
const gchar *sizes[] = {"large", "x-large", "xx-large", "normal"};
GError *error = NULL;
for (gsize i = 0; !result && i < G_N_ELEMENTS(sizes); i++) {
gchar *path = g_strdup_printf("%s/thumbnails/%s/%s.png",
cache_dir, sizes[i], sum);
gchar *path = g_strdup_printf(
"%s/thumbnails/%s/%s.png", cache_dir, sizes[i], sum);
result = read_png_thumbnail(path, uri, st.st_mtim.tv_sec, &error);
if (error) {
g_debug("%s: %s", path, error->message);

26
fastiv-io.h Normal file
View File

@ -0,0 +1,26 @@
//
// fastiv-io.h: image loaders
//
// Copyright (c) 2021, Přemysl Eric Janouch <p@janouch.name>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#pragma once
#include <cairo.h>
#include <glib.h>
extern const char *fastiv_io_supported_media_types[];
cairo_surface_t *fastiv_io_open(const gchar *path, GError **error);
cairo_surface_t *fastiv_io_lookup_thumbnail(const gchar *target);

View File

@ -17,6 +17,7 @@
#include <math.h>
#include "fastiv-io.h"
#include "fastiv-view.h"
struct _FastivView {
@ -56,8 +57,8 @@ fastiv_view_finalize(GObject *gobject)
}
static void
fastiv_view_get_preferred_height(GtkWidget *widget,
gint *minimum, gint *natural)
fastiv_view_get_preferred_height(
GtkWidget *widget, gint *minimum, gint *natural)
{
*minimum = 0;
*natural = 0;
@ -67,8 +68,7 @@ fastiv_view_get_preferred_height(GtkWidget *widget,
}
static void
fastiv_view_get_preferred_width(GtkWidget *widget,
gint *minimum, gint *natural)
fastiv_view_get_preferred_width(GtkWidget *widget, gint *minimum, gint *natural)
{
*minimum = 0;
*natural = 0;
@ -112,14 +112,14 @@ static gboolean
fastiv_view_draw(GtkWidget *widget, cairo_t *cr)
{
FastivView *self = FASTIV_VIEW(widget);
if (!self->surface
|| !gtk_cairo_should_draw_window(cr, gtk_widget_get_window(widget)))
if (!self->surface ||
!gtk_cairo_should_draw_window(cr, gtk_widget_get_window(widget)))
return TRUE;
GtkAllocation allocation;
gtk_widget_get_allocation(widget, &allocation);
gtk_render_background(gtk_widget_get_style_context(widget), cr,
0, 0, allocation.width, allocation.height);
gtk_render_background(gtk_widget_get_style_context(widget), cr, 0, 0,
allocation.width, allocation.height);
int w = get_display_width(self);
int h = get_display_height(self);
@ -132,8 +132,8 @@ fastiv_view_draw(GtkWidget *widget, cairo_t *cr)
y = round((allocation.height - h) / 2.);
cairo_scale(cr, self->scale, self->scale);
cairo_set_source_surface(cr, self->surface,
x / self->scale, y / self->scale);
cairo_set_source_surface(
cr, self->surface, x / self->scale, y / self->scale);
// TODO(p): Prescale it ourselves to an off-screen bitmap, gamma-correctly.
cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_GOOD);

View File

@ -24,7 +24,3 @@ G_DECLARE_FINAL_TYPE(FastivView, fastiv_view, FASTIV, VIEW, GtkWidget)
/// Try to open the given file, synchronously, to be displayed by the widget.
gboolean fastiv_view_open(FastivView *self, const gchar *path, GError **error);
// Private, fastiv-io.c
cairo_surface_t *fastiv_io_open(const gchar *path, GError **error);
cairo_surface_t *fastiv_io_lookup_thumbnail(const gchar *target);

231
fastiv.c
View File

@ -15,25 +15,26 @@
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#include <gtk/gtk.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <gtk/gtk.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <locale.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <fnmatch.h>
#include "config.h"
#include "fastiv-view.h"
#include "fastiv-browser.h"
#include "fastiv-io.h"
#include "fastiv-view.h"
#include "xdg.h"
// --- Utilities ---------------------------------------------------------------
static void
exit_fatal(const gchar *format, ...) G_GNUC_PRINTF(1, 2);
static void exit_fatal(const gchar *format, ...) G_GNUC_PRINTF(1, 2);
static void
exit_fatal(const gchar *format, ...)
@ -49,191 +50,6 @@ exit_fatal(const gchar *format, ...)
exit(EXIT_FAILURE);
}
/// Add `element` to the `output` set. `relation` is a map of sets of strings
/// defining is-a relations, and is traversed recursively.
static void
add_applying_transitive_closure(const gchar *element, GHashTable *relation,
GHashTable *output)
{
// Stop condition.
if (!g_hash_table_add(output, g_strdup(element)))
return;
// TODO(p): Iterate over all aliases of `element` in addition to
// any direct match (and rename this no-longer-generic function).
GHashTable *targets = g_hash_table_lookup(relation, element);
if (!targets)
return;
GHashTableIter iter;
g_hash_table_iter_init(&iter, targets);
gpointer key = NULL, value = NULL;
while (g_hash_table_iter_next(&iter, &key, &value))
add_applying_transitive_closure(key, relation, output);
}
// --- XDG ---------------------------------------------------------------------
gchar *
get_xdg_home_dir(const char *var, const char *default_)
{
const char *env = getenv(var);
if (env && *env == '/')
return g_strdup(env);
// The specification doesn't handle a missing HOME variable explicitly.
// Implicitly, assuming Bourne shell semantics, it simply resolves empty.
const char *home = getenv("HOME");
return g_build_filename(home ? home : "", default_, NULL);
}
static gchar **
get_xdg_data_dirs(void)
{
// GStrvBuilder is too new, it would help a little bit.
GPtrArray *output = g_ptr_array_new_with_free_func(g_free);
g_ptr_array_add(output, get_xdg_home_dir("XDG_DATA_HOME", ".local/share"));
const gchar *xdg_data_dirs;
if (!(xdg_data_dirs = getenv("XDG_DATA_DIRS")) || !*xdg_data_dirs)
xdg_data_dirs = "/usr/local/share/:/usr/share/";
gchar **candidates = g_strsplit(xdg_data_dirs, ":", 0);
for (gchar **p = candidates; *p; p++) {
if (**p == '/')
g_ptr_array_add(output, *p);
else
g_free(*p);
}
g_free(candidates);
g_ptr_array_add(output, NULL);
return (gchar **) g_ptr_array_free(output, FALSE);
}
// --- Filtering ---------------------------------------------------------------
// Derived from shared-mime-info-spec 0.21.
// TODO(p): Move to fastiv-io.c, expose the prototype in a header file
// (perhaps finally start a new one for it).
// A subset of shared-mime-info that produces an appropriate list of
// file extensions. Chiefly motivated by the suckiness of RAW images:
// someone else will maintain the list of file extensions for us.
static const char *supported_media_types[] = {
"image/bmp",
"image/gif",
"image/png",
"image/jpeg",
#ifdef HAVE_LIBRAW
"image/x-dcraw",
#endif // HAVE_LIBRAW
};
static void
read_mime_subclasses(const gchar *path, GHashTable *subclass_sets)
{
gchar *data = NULL;
if (!g_file_get_contents(path, &data, NULL /* length */, NULL /* error */))
return;
// The format of this file is unspecified,
// but in practice it's a list of space-separated media types.
gchar *datasave = NULL;
for (gchar *line = strtok_r(data, "\r\n", &datasave); line;
line = strtok_r(NULL, "\r\n", &datasave)) {
gchar *linesave = NULL,
*subclass = strtok_r(line, " ", &linesave),
*superclass = strtok_r(NULL, " ", &linesave);
// Nothing about comments is specified, we're being nice.
if (!subclass || *subclass == '#' || !superclass)
continue;
GHashTable *set = NULL;
if (!(set = g_hash_table_lookup(subclass_sets, superclass))) {
set = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
g_hash_table_insert(subclass_sets, g_strdup(superclass), set);
}
g_hash_table_add(set, g_strdup(subclass));
}
g_free(data);
}
static gboolean
filter_mime_globs(const gchar *path, guint is_globs2, GHashTable *supported_set,
GHashTable *output_set)
{
gchar *data = NULL;
if (!g_file_get_contents(path, &data, NULL /* length */, NULL /* error */))
return FALSE;
gchar *datasave = NULL;
for (const gchar *line = strtok_r(data, "\r\n", &datasave); line;
line = strtok_r(NULL, "\r\n", &datasave)) {
if (*line == '#')
continue;
// We do not support __NOGLOBS__, nor even parse out the "cs" flag.
// The weight is irrelevant.
gchar **f = g_strsplit(line, ":", 0);
if (g_strv_length(f) >= is_globs2 + 2) {
const gchar *type = f[is_globs2 + 0], *glob = f[is_globs2 + 1];
if (g_hash_table_contains(supported_set, type))
g_hash_table_add(output_set, g_utf8_strdown(glob, -1));
}
g_strfreev(f);
}
g_free(data);
return TRUE;
}
static gchar **
get_supported_globs (void)
{
gchar **data_dirs = get_xdg_data_dirs();
// The mime.cache format is inconvenient to parse,
// we'll do it from the text files manually, and once only.
GHashTable *subclass_sets = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, (GDestroyNotify) g_hash_table_destroy);
for (gsize i = 0; data_dirs[i]; i++) {
gchar *path =
g_build_filename(data_dirs[i], "mime", "subclasses", NULL);
read_mime_subclasses(path, subclass_sets);
g_free(path);
}
// A hash set of all supported media types, including subclasses,
// but not aliases.
GHashTable *supported =
g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
for (gsize i = 0; i < G_N_ELEMENTS(supported_media_types); i++) {
add_applying_transitive_closure(supported_media_types[i],
subclass_sets, supported);
}
g_hash_table_destroy(subclass_sets);
// We do not support the distinction of case-sensitive globs (:cs).
GHashTable *globs =
g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
for (gsize i = 0; data_dirs[i]; i++) {
gchar *path2 = g_build_filename(data_dirs[i], "mime", "globs2", NULL);
gchar *path1 = g_build_filename(data_dirs[i], "mime", "globs", NULL);
if (!filter_mime_globs(path2, TRUE, supported, globs))
filter_mime_globs(path1, FALSE, supported, globs);
g_free(path2);
g_free(path1);
}
g_strfreev(data_dirs);
g_hash_table_destroy(supported);
gchar **result = (gchar **) g_hash_table_get_keys_as_array(globs, NULL);
g_hash_table_steal_all(globs);
g_hash_table_destroy(globs);
return result;
}
// --- Main --------------------------------------------------------------------
struct {
@ -275,8 +91,8 @@ is_supported(const gchar *filename)
static void
show_error_dialog(GError *error)
{
GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(g.window),
GTK_DIALOG_MODAL,
GtkWidget *dialog =
gtk_message_dialog_new(GTK_WINDOW(g.window), GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", error->message);
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
@ -350,7 +166,6 @@ open(const gchar *path)
}
}
g_free(dirname);
}
static void
@ -363,8 +178,8 @@ on_open(void)
// NOTE: gdk-pixbuf has gtk_file_filter_add_pixbuf_formats().
GtkFileFilter *filter = gtk_file_filter_new();
for (gsize i = 0; i < G_N_ELEMENTS(supported_media_types); i++)
gtk_file_filter_add_mime_type(filter, supported_media_types[i]);
for (const char **p = fastiv_io_supported_media_types; *p; p++)
gtk_file_filter_add_mime_type(filter, *p);
gtk_file_filter_set_name(filter, "Supported images");
gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter);
@ -389,9 +204,8 @@ on_previous(void)
if (g.files_index >= 0) {
int previous =
(g.files->len - 1 + g.files_index - 1) % (g.files->len - 1);
char *absolute =
g_canonicalize_filename(g_ptr_array_index(g.files, previous),
g.directory);
char *absolute = g_canonicalize_filename(
g_ptr_array_index(g.files, previous), g.directory);
open(absolute);
g_free(absolute);
}
@ -402,9 +216,8 @@ on_next(void)
{
if (g.files_index >= 0) {
int next = (g.files_index + 1) % (g.files->len - 1);
char *absolute =
g_canonicalize_filename(g_ptr_array_index(g.files, next),
g.directory);
char *absolute = g_canonicalize_filename(
g_ptr_array_index(g.files, next), g.directory);
open(absolute);
g_free(absolute);
}
@ -427,8 +240,8 @@ main(int argc, char *argv[])
};
GError *error = NULL;
if (!gtk_init_with_args(&argc, &argv, " - fast image viewer",
options, NULL, &error))
if (!gtk_init_with_args(
&argc, &argv, " - fast image viewer", options, NULL, &error))
exit_fatal("%s", error->message);
if (show_version) {
printf(PROJECT_NAME " " PROJECT_VERSION "\n");
@ -496,7 +309,7 @@ main(int argc, char *argv[])
g_cclosure_new(G_CALLBACK(on_next), NULL, NULL));
gtk_window_add_accel_group(GTK_WINDOW(g.window), accel_group);
g.supported_globs = get_supported_globs();
g.supported_globs = extract_mime_globs(fastiv_io_supported_media_types);
g.files = g_ptr_array_new_full(16, g_free);
gchar *cwd = g_get_current_dir();
@ -508,9 +321,9 @@ main(int argc, char *argv[])
if (!path_arg) {
load_directory(cwd);
} else if (g_stat(path_arg, &st)) {
show_error_dialog(g_error_new(G_FILE_ERROR,
g_file_error_from_errno(errno),
"%s: %s", path_arg, g_strerror(errno)));
show_error_dialog(
g_error_new(G_FILE_ERROR, g_file_error_from_errno(errno), "%s: %s",
path_arg, g_strerror(errno)));
load_directory(cwd);
} else {
gchar *path_arg_absolute = g_canonicalize_filename(path_arg, cwd);

View File

@ -20,7 +20,7 @@ configure_file(
)
executable('fastiv', 'fastiv.c', 'fastiv-view.c', 'fastiv-io.c',
'fastiv-browser.c',
'fastiv-browser.c', 'xdg.c',
install : true,
dependencies : [dependencies])

View File

@ -1,7 +1,7 @@
SHELL = /bin/sh
# libjq 1.6 lacks a pkg-config file, and there is no release in sight.
CFLAGS = -g -O2 -Wall -Wextra `pkg-config --cflags $(deps)`
LDFLAGS = -ljq `pkg-config --libs $(deps)`
LDLIBS = -ljq `pkg-config --libs $(deps)`
deps = libpng
targets = pnginfo

186
xdg.c Normal file
View File

@ -0,0 +1,186 @@
//
// xdg.c: various *nix desktop utilities
//
// Copyright (c) 2021, Přemysl Eric Janouch <p@janouch.name>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#include <glib.h>
/// Add `element` to the `output` set. `relation` is a map of sets of strings
/// defining is-a relations, and is traversed recursively.
static void
add_applying_transitive_closure(
const gchar *element, GHashTable *relation, GHashTable *output)
{
// Stop condition.
if (!g_hash_table_add(output, g_strdup(element)))
return;
// TODO(p): Iterate over all aliases of `element` in addition to
// any direct match (and rename this no-longer-generic function).
GHashTable *targets = g_hash_table_lookup(relation, element);
if (!targets)
return;
GHashTableIter iter;
g_hash_table_iter_init(&iter, targets);
gpointer key = NULL, value = NULL;
while (g_hash_table_iter_next(&iter, &key, &value))
add_applying_transitive_closure(key, relation, output);
}
char *
get_xdg_home_dir(const char *var, const char *default_)
{
const char *env = getenv(var);
if (env && *env == '/')
return g_strdup(env);
// The specification doesn't handle a missing HOME variable explicitly.
// Implicitly, assuming Bourne shell semantics, it simply resolves empty.
const char *home = getenv("HOME");
return g_build_filename(home ? home : "", default_, NULL);
}
static gchar **
get_xdg_data_dirs(void)
{
// GStrvBuilder is too new, it would help a little bit.
GPtrArray *output = g_ptr_array_new_with_free_func(g_free);
g_ptr_array_add(output, get_xdg_home_dir("XDG_DATA_HOME", ".local/share"));
const gchar *xdg_data_dirs;
if (!(xdg_data_dirs = getenv("XDG_DATA_DIRS")) || !*xdg_data_dirs)
xdg_data_dirs = "/usr/local/share/:/usr/share/";
gchar **candidates = g_strsplit(xdg_data_dirs, ":", 0);
for (gchar **p = candidates; *p; p++) {
if (**p == '/')
g_ptr_array_add(output, *p);
else
g_free(*p);
}
g_free(candidates);
g_ptr_array_add(output, NULL);
return (gchar **) g_ptr_array_free(output, FALSE);
}
// --- Filtering ---------------------------------------------------------------
// Derived from shared-mime-info-spec 0.21.
static void
read_mime_subclasses(const gchar *path, GHashTable *subclass_sets)
{
gchar *data = NULL;
if (!g_file_get_contents(path, &data, NULL /* length */, NULL /* error */))
return;
// The format of this file is unspecified,
// but in practice it's a list of space-separated media types.
gchar *datasave = NULL;
for (gchar *line = strtok_r(data, "\r\n", &datasave); line;
line = strtok_r(NULL, "\r\n", &datasave)) {
gchar *linesave = NULL,
*subclass = strtok_r(line, " ", &linesave),
*superclass = strtok_r(NULL, " ", &linesave);
// Nothing about comments is specified, we're being nice.
if (!subclass || *subclass == '#' || !superclass)
continue;
GHashTable *set = NULL;
if (!(set = g_hash_table_lookup(subclass_sets, superclass))) {
set = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
g_hash_table_insert(subclass_sets, g_strdup(superclass), set);
}
g_hash_table_add(set, g_strdup(subclass));
}
g_free(data);
}
static gboolean
filter_mime_globs(const gchar *path, guint is_globs2, GHashTable *supported_set,
GHashTable *output_set)
{
gchar *data = NULL;
if (!g_file_get_contents(path, &data, NULL /* length */, NULL /* error */))
return FALSE;
gchar *datasave = NULL;
for (const gchar *line = strtok_r(data, "\r\n", &datasave); line;
line = strtok_r(NULL, "\r\n", &datasave)) {
if (*line == '#')
continue;
// We do not support __NOGLOBS__, nor even parse out the "cs" flag.
// The weight is irrelevant.
gchar **f = g_strsplit(line, ":", 0);
if (g_strv_length(f) >= is_globs2 + 2) {
const gchar *type = f[is_globs2 + 0], *glob = f[is_globs2 + 1];
if (g_hash_table_contains(supported_set, type))
g_hash_table_add(output_set, g_utf8_strdown(glob, -1));
}
g_strfreev(f);
}
g_free(data);
return TRUE;
}
char **
extract_mime_globs(const char **media_types)
{
gchar **data_dirs = get_xdg_data_dirs();
// The mime.cache format is inconvenient to parse,
// we'll do it from the text files manually, and once only.
GHashTable *subclass_sets = g_hash_table_new_full(
g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_destroy);
for (gsize i = 0; data_dirs[i]; i++) {
gchar *path =
g_build_filename(data_dirs[i], "mime", "subclasses", NULL);
read_mime_subclasses(path, subclass_sets);
g_free(path);
}
// A hash set of all supported media types, including subclasses,
// but not aliases.
GHashTable *supported =
g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
while (*media_types) {
add_applying_transitive_closure(
*media_types++, subclass_sets, supported);
}
g_hash_table_destroy(subclass_sets);
// We do not support the distinction of case-sensitive globs (:cs).
GHashTable *globs =
g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
for (gsize i = 0; data_dirs[i]; i++) {
gchar *path2 = g_build_filename(data_dirs[i], "mime", "globs2", NULL);
gchar *path1 = g_build_filename(data_dirs[i], "mime", "globs", NULL);
if (!filter_mime_globs(path2, TRUE, supported, globs))
filter_mime_globs(path1, FALSE, supported, globs);
g_free(path2);
g_free(path1);
}
g_strfreev(data_dirs);
g_hash_table_destroy(supported);
gchar **result = (gchar **) g_hash_table_get_keys_as_array(globs, NULL);
g_hash_table_steal_all(globs);
g_hash_table_destroy(globs);
return result;
}

19
xdg.h Normal file
View File

@ -0,0 +1,19 @@
//
// xdg.h: various *nix desktop utilities
//
// Copyright (c) 2021, Přemysl Eric Janouch <p@janouch.name>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
char *get_xdg_home_dir(const char *var, const char *default_);
char **extract_mime_globs(const char **media_types);