From a1d9ab7584485fe0b4a992abf19486a72179d4b2 Mon Sep 17 00:00:00 2001 From: XenHat Date: Fri, 23 Jun 2023 16:33:33 -0400 Subject: [PATCH] [RFC] Filetype detection without extension (#77) * first draft of filetype detection * Nix: add file dependency * Fix coding style mistake * Manually format my code --------- Co-authored-by: Mihai Fufezan --- CMakeLists.txt | 1 + nix/default.nix | 2 ++ src/render/WallpaperTarget.cpp | 20 ++++++++++++++++++-- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 285cfac..e5bf610 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -64,6 +64,7 @@ target_link_libraries(hyprpaper OpenGL GLESv2 pthread + magic ${CMAKE_THREAD_LIBS_INIT} ${CMAKE_SOURCE_DIR}/wlr-layer-shell-unstable-v1-protocol.o ${CMAKE_SOURCE_DIR}/xdg-shell-protocol.o diff --git a/nix/default.nix b/nix/default.nix index b8650f4..0c5e918 100644 --- a/nix/default.nix +++ b/nix/default.nix @@ -5,6 +5,7 @@ cmake, ninja, cairo, + file, fribidi, libdatrie, libjpeg, @@ -34,6 +35,7 @@ stdenv.mkDerivation { buildInputs = [ cairo + file fribidi libdatrie libjpeg diff --git a/src/render/WallpaperTarget.cpp b/src/render/WallpaperTarget.cpp index 37a4cf5..ae4d986 100644 --- a/src/render/WallpaperTarget.cpp +++ b/src/render/WallpaperTarget.cpp @@ -1,5 +1,7 @@ #include "WallpaperTarget.hpp" +#include + CWallpaperTarget::~CWallpaperTarget() { cairo_surface_destroy(m_pCairoSurface); } @@ -17,8 +19,22 @@ void CWallpaperTarget::create(const std::string& path) { CAIROSURFACE = JPEG::createSurfaceFromJPEG(path); m_bHasAlpha = false; } else { - Debug::log(CRIT, "unrecognized image %s", path.c_str()); - exit(1); + // magic is slow, so only use it when no recognized extension is found + auto handle = magic_open(MAGIC_NONE|MAGIC_COMPRESS); + magic_load(handle, nullptr); + + const auto type_str = std::string(magic_file(handle, path.c_str())); + const auto first_word = type_str.substr(0, type_str.find(" ")); + + if (first_word == "PNG") { + CAIROSURFACE = cairo_image_surface_create_from_png(path.c_str()); + } else if (first_word == "JPEG") { + CAIROSURFACE = JPEG::createSurfaceFromJPEG(path); + m_bHasAlpha = false; + } else { + Debug::log(CRIT, "unrecognized image %s", path.c_str()); + exit(1); + } } if (cairo_surface_status(CAIROSURFACE) != CAIRO_STATUS_SUCCESS) {