From 0b613229d1075f32520fd49485a506243f8dbe6b Mon Sep 17 00:00:00 2001 From: Sophie Herold Date: Thu, 18 Jul 2024 01:12:19 +0200 Subject: [PATCH 1/3] glycin: Implement Error for Error type --- glycin/src/error.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/glycin/src/error.rs b/glycin/src/error.rs index 5483413b..0b90495e 100644 --- a/glycin/src/error.rs +++ b/glycin/src/error.rs @@ -1,3 +1,4 @@ +use std::ops::Deref; use std::process::ExitStatus; use std::sync::Arc; @@ -20,20 +21,30 @@ pub struct Error { stdout: Option, } +impl Deref for Error { + type Target = ErrorKind; + + fn deref(&self) -> &Self::Target { + self.kind() + } +} + +impl std::error::Error for Error {} + impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.kind.to_string())?; if let Some(stderr) = &self.stderr { if !stderr.is_empty() { - f.write_str("stderr:\n")?; + f.write_str("\n\nstderr:\n")?; f.write_str(&stderr)?; } } if let Some(stdout) = &self.stdout { if !stdout.is_empty() { - f.write_str("stdout:\n")?; + f.write_str("\n\nstdout:\n")?; f.write_str(&stdout)?; } } -- GitLab From 8073a06f0e112bbf821c3407d5abae1269a0e81d Mon Sep 17 00:00:00 2001 From: Sophie Herold Date: Thu, 18 Jul 2024 01:33:45 +0200 Subject: [PATCH 2/3] glycin: Use "Error" and "ErrorCtx" as names --- glycin/src/api_common.rs | 11 +++-- glycin/src/api_editor.rs | 14 +++--- glycin/src/api_loader.rs | 8 ++-- glycin/src/config.rs | 12 +++--- glycin/src/dbus.rs | 67 +++++++++++++---------------- glycin/src/error.rs | 69 ++++++++++++++++-------------- glycin/src/gobject/image.rs | 4 +- glycin/src/gobject/loader.rs | 2 +- glycin/src/icc.rs | 4 +- glycin/src/lib.rs | 2 +- glycin/src/sandbox.rs | 13 +++--- libglycin/src/error.rs | 10 ++--- tools/src/bin/glycin-image-info.rs | 2 +- 13 files changed, 105 insertions(+), 113 deletions(-) diff --git a/glycin/src/api_common.rs b/glycin/src/api_common.rs index 8e18a13b..ef148c98 100644 --- a/glycin/src/api_common.rs +++ b/glycin/src/api_common.rs @@ -5,9 +5,8 @@ use gio::glib; use gio::prelude::*; use crate::dbus::{GFileWorker, RemoteProcess, ZbusProxy}; -use crate::error::ResultKind; use crate::util::RunEnvironment; -use crate::{config, ErrorKind, MimeType}; +use crate::{config, Error, MimeType}; #[derive(Debug, Copy, Clone)] /// Sandboxing mechanism for image loading and editing @@ -82,7 +81,7 @@ pub(crate) async fn spin_up<'a, P: ZbusProxy<'a> + 'a>( file: &gio::File, cancellable: &gio::Cancellable, sandbox_selector: &SandboxSelector, -) -> ResultKind> { +) -> Result, Error> { let config = config::Config::cached().await; let gfile_worker = GFileWorker::spawn(file.clone(), cancellable.clone()); @@ -108,11 +107,11 @@ pub(crate) async fn spin_up<'a, P: ZbusProxy<'a> + 'a>( }) } -pub(crate) async fn guess_mime_type(gfile_worker: &GFileWorker) -> ResultKind { +pub(crate) async fn guess_mime_type(gfile_worker: &GFileWorker) -> Result { let head = gfile_worker.head().await?; let (content_type, unsure) = gio::content_type_guess(None::, &head); let mime_type = gio::content_type_get_mime_type(&content_type) - .ok_or_else(|| ErrorKind::UnknownContentType(content_type.to_string())); + .ok_or_else(|| Error::UnknownContentType(content_type.to_string())); // Prefer file extension for TIFF since it can be a RAW format as well let is_tiff = mime_type.clone().ok() == Some("image/tiff".into()); @@ -125,7 +124,7 @@ pub(crate) async fn guess_mime_type(gfile_worker: &GFileWorker) -> ResultKind Result { + pub async fn apply_sparse(self, operations: Operations) -> Result { let process_context = spin_up(&self.file, &self.cancellable, &self.sandbox_selector) .await .err_no_context()?; @@ -92,7 +92,7 @@ impl SparseEdit { /// /// If the type does not carry sparse changes, the function will return an /// [`EditOutcome::Unchanged`] and the complete image needs to be rewritten. - pub async fn apply_to(&self, file: gio::File) -> ResultKind { + pub async fn apply_to(&self, file: gio::File) -> Result { match self { Self::Sparse(bit_changes) => { let bit_changes = bit_changes.clone(); @@ -122,11 +122,11 @@ impl SparseEdit { } impl TryFrom for SparseEdit { - type Error = ErrorKind; + type Error = Error; fn try_from(value: SparseEditorOutput) -> std::result::Result { if value.bit_changes.is_some() && value.data.is_some() { - Err(ErrorKind::RemoteError( + Err(Error::RemoteError( glycin_utils::RemoteError::InternalLoaderError( "Sparse editor output with 'bit_changes' and 'data' returned.".into(), ), @@ -136,7 +136,7 @@ impl TryFrom for SparseEdit { } else if let Some(data) = value.data { Ok(Self::Complete(data)) } else { - Err(ErrorKind::RemoteError( + Err(Error::RemoteError( glycin_utils::RemoteError::InternalLoaderError( "Sparse editor output with neither 'bit_changes' nor 'data' returned.".into(), ), diff --git a/glycin/src/api_loader.rs b/glycin/src/api_loader.rs index 37979fde..d4c54a4a 100644 --- a/glycin/src/api_loader.rs +++ b/glycin/src/api_loader.rs @@ -9,7 +9,7 @@ use crate::api_common::*; pub use crate::config::MimeType; use crate::dbus::*; use crate::error::ResultExt; -use crate::{config, Result}; +use crate::{config, ErrorCtx}; /// Image request builder #[derive(Debug)] @@ -59,7 +59,7 @@ impl Loader { } /// Load basic image information and enable further operations - pub async fn load<'a>(self) -> Result> { + pub async fn load<'a>(self) -> Result, ErrorCtx> { let process_context = spin_up(&self.file, &self.cancellable, &self.sandbox_selector) .await .err_no_context()?; @@ -98,7 +98,7 @@ impl<'a> Image<'a> { /// Loads texture and information of the next frame. For single still /// images, this can only be called once. For animated images, this /// function will loop to the first frame, when the last frame is reached. - pub async fn next_frame(&self) -> Result { + pub async fn next_frame(&self) -> Result { self.process .request_frame(glycin_utils::FrameRequest::default(), self) .await @@ -110,7 +110,7 @@ impl<'a> Image<'a> { /// /// Loads a specific frame from the file. Loaders can ignore parts of the /// instructions in the `FrameRequest`. - pub async fn specific_frame(&self, frame_request: FrameRequest) -> Result { + pub async fn specific_frame(&self, frame_request: FrameRequest) -> Result { self.process .request_frame(frame_request.request, self) .await diff --git a/glycin/src/config.rs b/glycin/src/config.rs index d189f5ff..5cb50cd7 100644 --- a/glycin/src/config.rs +++ b/glycin/src/config.rs @@ -7,7 +7,7 @@ use futures_util::StreamExt; use gio::glib; use crate::util::{read, read_dir}; -use crate::ErrorKind; +use crate::Error; #[derive(Clone, Debug, Hash, PartialEq, Eq)] /// Mime type @@ -85,20 +85,20 @@ impl Config { } } - pub fn get_loader(&self, mime_type: &MimeType) -> Result<&ImageLoaderConfig, ErrorKind> { + pub fn get_loader(&self, mime_type: &MimeType) -> Result<&ImageLoaderConfig, Error> { if self.image_loader.is_empty() { - return Err(ErrorKind::NoLoadersConfigured(self.clone())); + return Err(Error::NoLoadersConfigured(self.clone())); } self.image_loader .get(mime_type) - .ok_or_else(|| ErrorKind::UnknownImageFormat(mime_type.to_string(), self.clone())) + .ok_or_else(|| Error::UnknownImageFormat(mime_type.to_string(), self.clone())) } - pub fn get_editor(&self, mime_type: &MimeType) -> Result<&ImageEditorConfig, ErrorKind> { + pub fn get_editor(&self, mime_type: &MimeType) -> Result<&ImageEditorConfig, Error> { self.image_editor .get(mime_type) - .ok_or_else(|| ErrorKind::UnknownImageFormat(mime_type.to_string(), self.clone())) + .ok_or_else(|| Error::UnknownImageFormat(mime_type.to_string(), self.clone())) } async fn load() -> Self { diff --git a/glycin/src/dbus.rs b/glycin/src/dbus.rs index 8e04c405..cc1fa634 100644 --- a/glycin/src/dbus.rs +++ b/glycin/src/dbus.rs @@ -27,7 +27,7 @@ use crate::api_loader::{self}; use crate::config::{Config, ConfigEntry}; use crate::sandbox::Sandbox; use crate::util::{self, block_on, spawn_blocking, spawn_blocking_detached}; -use crate::{config, icc, orientation, ErrorKind, Image, MimeType, SandboxMechanism}; +use crate::{config, icc, orientation, Error, Image, MimeType, SandboxMechanism}; /// Max texture size 8 GB in bytes pub(crate) const MAX_TEXTURE_SIZE: u64 = 8 * 10u64.pow(9); @@ -44,11 +44,8 @@ pub struct RemoteProcess<'a, P: ZbusProxy<'a>> { pub trait ZbusProxy<'a>: Sized + Sync + Send + From> { fn builder(conn: &zbus::Connection) -> zbus::proxy::Builder<'a, Self>; - fn expose_base_dir(config: &Config, mime_type: &MimeType) -> Result; - fn entry_config( - config: &Config, - mime_type: &MimeType, - ) -> Result, ErrorKind>; + fn expose_base_dir(config: &Config, mime_type: &MimeType) -> Result; + fn entry_config(config: &Config, mime_type: &MimeType) -> Result, Error>; } impl<'a> ZbusProxy<'a> for LoaderProxy<'a> { @@ -56,14 +53,11 @@ impl<'a> ZbusProxy<'a> for LoaderProxy<'a> { Self::builder(conn) } - fn expose_base_dir(config: &Config, mime_type: &MimeType) -> Result { + fn expose_base_dir(config: &Config, mime_type: &MimeType) -> Result { Ok(config.get_loader(mime_type)?.expose_base_dir) } - fn entry_config( - config: &Config, - mime_type: &MimeType, - ) -> Result, ErrorKind> { + fn entry_config(config: &Config, mime_type: &MimeType) -> Result, Error> { Ok(Box::new(config.get_loader(mime_type)?.clone())) } } @@ -73,14 +67,11 @@ impl<'a> ZbusProxy<'a> for EditorProxy<'a> { Self::builder(conn) } - fn expose_base_dir(config: &Config, mime_type: &MimeType) -> Result { + fn expose_base_dir(config: &Config, mime_type: &MimeType) -> Result { Ok(config.get_editor(mime_type)?.expose_base_dir) } - fn entry_config( - config: &Config, - mime_type: &MimeType, - ) -> Result, ErrorKind> { + fn entry_config(config: &Config, mime_type: &MimeType) -> Result, Error> { Ok(Box::new(config.get_editor(mime_type)?.clone())) } } @@ -92,7 +83,7 @@ impl<'a, P: ZbusProxy<'a>> RemoteProcess<'a, P> { sandbox_mechanism: SandboxMechanism, file: &gio::File, cancellable: &gio::Cancellable, - ) -> Result { + ) -> Result { // UnixStream which facilitates the D-Bus connection. The stream is passed as // stdin to loader binaries. let (unix_stream, loader_stdin) = std::os::unix::net::UnixStream::pair()?; @@ -137,8 +128,8 @@ impl<'a, P: ZbusProxy<'a>> RemoteProcess<'a, P> { Err(glib::Error::from(gio::Cancelled).into()) }, return_status = spawn_blocking(move || subprocess.wait()).fuse() => match return_status { - Ok(status) => Err(ErrorKind::PrematureExit { status, cmd: command_dbg }), - Err(err) => Err(ErrorKind::StdIoError{ err: err.into(), info: command_dbg }), + Ok(status) => Err(Error::PrematureExit { status, cmd: command_dbg }), + Err(err) => Err(Error::StdIoError{ err: err.into(), info: command_dbg }), } }?; @@ -168,7 +159,7 @@ impl<'a, P: ZbusProxy<'a>> RemoteProcess<'a, P> { &self, gfile_worker: &GFileWorker, base_dir: Option, - ) -> Result { + ) -> Result { let (remote_reader, writer) = std::os::unix::net::UnixStream::pair()?; gfile_worker.write_to(writer)?; @@ -193,7 +184,7 @@ impl<'a> RemoteProcess<'a, LoaderProxy<'a>> { &self, gfile_worker: GFileWorker, base_dir: Option, - ) -> Result { + ) -> Result { let init_request = self.init_request(&gfile_worker, base_dir)?; let image_info = self.decoding_instruction.init(init_request).shared(); @@ -223,7 +214,7 @@ impl<'a> RemoteProcess<'a, LoaderProxy<'a>> { &self, frame_request: FrameRequest, image: &Image<'b>, - ) -> Result { + ) -> Result { let mut frame = self.decoding_instruction.frame(frame_request).await?; // Seal all constant data @@ -291,7 +282,7 @@ impl<'a> RemoteProcess<'a, EditorProxy<'a>> { gfile_worker: &GFileWorker, base_dir: Option, operations: Operations, - ) -> Result { + ) -> Result { let init_request = self.init_request(gfile_worker, base_dir)?; let edit_request = EditRequest::for_operations(operations); @@ -342,7 +333,7 @@ pub struct GFileWorker { file: gio::File, writer_send: Mutex>>, first_bytes_recv: future::Shared>>>, - error_recv: future::Shared>>, + error_recv: future::Shared>>, } use std::sync::Mutex; impl GFileWorker { @@ -362,7 +353,7 @@ impl GFileWorker { let first_bytes = Arc::new(buf[..n].to_vec()); first_bytes_send .send(first_bytes.clone()) - .or(Err(ErrorKind::InternalCommunicationCanceled))?; + .or(Err(Error::InternalCommunicationCanceled))?; let mut writer: UnixStream = block_on(writer_recv)?; @@ -390,35 +381,35 @@ impl GFileWorker { } fn handle_errors( - error_send: oneshot::Sender>, - f: impl FnOnce() -> Result<(), ErrorKind>, + error_send: oneshot::Sender>, + f: impl FnOnce() -> Result<(), Error>, ) { let result = f(); let _result = error_send.send(result); } - pub fn write_to(&self, stream: UnixStream) -> Result<(), ErrorKind> { + pub fn write_to(&self, stream: UnixStream) -> Result<(), Error> { let sender = std::mem::take(&mut *self.writer_send.lock().unwrap()); sender // TODO: this fails if write_to is called a second time .unwrap() .send(stream) - .or(Err(ErrorKind::InternalCommunicationCanceled)) + .or(Err(Error::InternalCommunicationCanceled)) } pub fn file(&self) -> &gio::File { &self.file } - pub async fn error(&self) -> Result<(), ErrorKind> { + pub async fn error(&self) -> Result<(), Error> { match self.error_recv.clone().await { Ok(result) => result, Err(_) => Ok(()), } } - pub async fn head(&self) -> Result>, ErrorKind> { + pub async fn head(&self) -> Result>, Error> { futures_util::select!( err = self.error_recv.clone() => err?, _bytes = self.first_bytes_recv.clone() => Ok(()), @@ -464,24 +455,24 @@ async fn seal_fd(fd: impl AsRawFd) -> Result<(), memfd::Error> { Ok(()) } -fn validate_frame(frame: &Frame, mmap: &MmapMut) -> Result<(), ErrorKind> { +fn validate_frame(frame: &Frame, mmap: &MmapMut) -> Result<(), Error> { if mmap.len() < frame.n_bytes()? { - return Err(ErrorKind::TextureTooSmall { + return Err(Error::TextureTooSmall { texture_size: mmap.len(), frame: format!("{:?}", frame), }); } if frame.stride < frame.width.smul(frame.memory_format.n_bytes().u32())? { - return Err(ErrorKind::StrideTooSmall(format!("{:?}", frame))); + return Err(Error::StrideTooSmall(format!("{:?}", frame))); } if frame.width < 1 || frame.height < 1 { - return Err(ErrorKind::WidgthOrHeightZero(format!("{:?}", frame))); + return Err(Error::WidgthOrHeightZero(format!("{:?}", frame))); } if (frame.stride as u64).smul(frame.height as u64)? > MAX_TEXTURE_SIZE { - return Err(ErrorKind::TextureTooLarge); + return Err(Error::TextureTooLarge); } // Ensure @@ -492,7 +483,7 @@ fn validate_frame(frame: &Frame, mmap: &MmapMut) -> Result<(), ErrorKind> { Ok(()) } -unsafe fn gbytes_from_mmap(raw_fd: RawFd) -> Result { +unsafe fn gbytes_from_mmap(raw_fd: RawFd) -> Result { let mut error = std::ptr::null_mut(); let mapped_file = glib::ffi::g_mapped_file_new_from_fd(raw_fd, glib::ffi::GFALSE, &mut error); @@ -513,7 +504,7 @@ fn remove_stride_if_needed( img_buf: ImgBuf, raw_fd: RawFd, frame: &mut Frame, -) -> Result { +) -> Result { if frame.stride.srem(frame.memory_format.n_bytes().u32())? == 0 { return Ok(img_buf); } diff --git a/glycin/src/error.rs b/glycin/src/error.rs index 0b90495e..5ef463dc 100644 --- a/glycin/src/error.rs +++ b/glycin/src/error.rs @@ -10,30 +10,27 @@ use libseccomp::error::SeccompError; use crate::config; use crate::dbus::{RemoteProcess, ZbusProxy, MAX_TEXTURE_SIZE}; -pub type ResultKind = std::result::Result; -pub type Result = std::result::Result; - #[derive(Debug, Clone)] -pub struct Error { - kind: ErrorKind, +pub struct ErrorCtx { + error: Error, stderr: Option, stdout: Option, } -impl Deref for Error { - type Target = ErrorKind; +impl Deref for ErrorCtx { + type Target = Error; fn deref(&self) -> &Self::Target { - self.kind() + self.error() } } -impl std::error::Error for Error {} +impl std::error::Error for ErrorCtx {} -impl std::fmt::Display for Error { +impl std::fmt::Display for ErrorCtx { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.kind.to_string())?; + f.write_str(&self.error.to_string())?; if let Some(stderr) = &self.stderr { if !stderr.is_empty() { @@ -53,35 +50,41 @@ impl std::fmt::Display for Error { } } -impl Error { - pub fn from_kind(kind: ErrorKind) -> Self { - Error { - kind, +impl ErrorCtx { + pub fn from_error(kind: Error) -> Self { + ErrorCtx { + error: kind, stderr: None, stdout: None, } } - pub fn kind(&self) -> &ErrorKind { - &self.kind + pub fn error(&self) -> &Error { + &self.error } } pub trait ResultExt { - fn err_context<'a, S: ZbusProxy<'a>>(self, process: &RemoteProcess<'a, S>) -> Result; - fn err_no_context(self) -> Result; + fn err_context<'a, S: ZbusProxy<'a>>( + self, + process: &RemoteProcess<'a, S>, + ) -> Result; + fn err_no_context(self) -> Result; } -impl ResultExt for ResultKind { - fn err_context<'a, S: ZbusProxy<'a>>(self, process: &RemoteProcess<'a, S>) -> Result { +impl ResultExt for Result { + fn err_context<'a, S: ZbusProxy<'a>>( + self, + process: &RemoteProcess<'a, S>, + ) -> Result { match self { Ok(x) => Ok(x), Err(kind) => { let stderr = process.stderr_content.lock().ok().map(|x| x.clone()); let stdout = process.stdout_content.lock().ok().map(|x| x.clone()); - Err(Error { - kind, + Err(ErrorCtx { + error: kind, stderr, stdout, }) @@ -89,14 +92,14 @@ impl ResultExt for ResultKind { } } - fn err_no_context(self) -> Result { - self.map_err(Error::from_kind) + fn err_no_context(self) -> Result { + self.map_err(ErrorCtx::from_error) } } #[derive(Debug, Clone, thiserror::Error)] #[non_exhaustive] -pub enum ErrorKind { +pub enum Error { #[error("Remote error: {0}")] RemoteError(#[from] RemoteError), #[error("GLib error: {0}")] @@ -145,7 +148,7 @@ pub enum ErrorKind { IccProfile(#[from] lcms2::Error), } -impl ErrorKind { +impl Error { /// Returns if the error is related to unsupported formats. /// /// Return the mime type of the unsupported format or [`None`] if the error @@ -159,7 +162,7 @@ impl ErrorKind { } } -impl From for ErrorKind { +impl From for Error { fn from(err: std::io::Error) -> Self { Self::StdIoError { err: Arc::new(err), @@ -168,7 +171,7 @@ impl From for ErrorKind { } } -impl From> for ErrorKind { +impl From> for Error { fn from(err: Arc) -> Self { Self::StdIoError { err, @@ -177,25 +180,25 @@ impl From> for ErrorKind { } } -impl From for ErrorKind { +impl From for Error { fn from(err: memfd::Error) -> Self { Self::MemFd(Arc::new(err)) } } -impl From for ErrorKind { +impl From for Error { fn from(err: SeccompError) -> Self { Self::Seccomp(Arc::new(err)) } } -impl From for ErrorKind { +impl From for Error { fn from(_err: oneshot::Canceled) -> Self { Self::InternalCommunicationCanceled } } -impl From for ErrorKind { +impl From for Error { fn from(_err: DimensionTooLargerError) -> Self { Self::ConversionTooLargerError } diff --git a/glycin/src/gobject/image.rs b/glycin/src/gobject/image.rs index e9fdc2b8..329fbcd4 100644 --- a/glycin/src/gobject/image.rs +++ b/glycin/src/gobject/image.rs @@ -5,7 +5,7 @@ use glib::subclass::prelude::*; use glycin_utils::ImageInfo; use super::GlyFrame; -use crate::Image; +use crate::{ErrorCtx, Image}; static_assertions::assert_impl_all!(GlyImage: Send, Sync); @@ -43,7 +43,7 @@ impl GlyImage { self.image().info() } - pub async fn next_frame(&self) -> crate::Result { + pub async fn next_frame(&self) -> Result { Ok(GlyFrame::new(self.image().next_frame().await?)) } diff --git a/glycin/src/gobject/loader.rs b/glycin/src/gobject/loader.rs index d9ef71d9..3e7a7539 100644 --- a/glycin/src/gobject/loader.rs +++ b/glycin/src/gobject/loader.rs @@ -43,7 +43,7 @@ impl GlyLoader { glib::Object::builder().property("file", file).build() } - pub async fn load(&self) -> Result { + pub async fn load(&self) -> Result { let mut loader = Loader::new(self.file().unwrap()); loader.sandbox_selector = self.sandbox_selector(); diff --git a/glycin/src/icc.rs b/glycin/src/icc.rs index 1a82d83f..e0d7d065 100644 --- a/glycin/src/icc.rs +++ b/glycin/src/icc.rs @@ -1,12 +1,12 @@ use glycin_utils::memory_format::MemoryFormat; -use crate::error::ResultKind; +use crate::Error; pub fn apply_transformation( iccp: &[u8], memory_format: MemoryFormat, mmap: &mut [u8], -) -> ResultKind<()> { +) -> Result<(), Error> { transform(iccp, memory_format, mmap).map_err(Into::into) } diff --git a/glycin/src/lib.rs b/glycin/src/lib.rs index 84f73846..d92ca929 100644 --- a/glycin/src/lib.rs +++ b/glycin/src/lib.rs @@ -87,7 +87,7 @@ pub use api_editor::*; pub use api_loader::*; pub use config::COMPAT_VERSION; pub use default_formats::DEFAULT_MIME_TYPES; -pub use error::{Error, ErrorKind, Result}; +pub use error::{Error, ErrorCtx}; pub use glycin_utils::{ImageInfo, ImageInfoDetails, RemoteError}; #[cfg(feature = "gdk4")] pub use util::gdk_memory_format; diff --git a/glycin/src/sandbox.rs b/glycin/src/sandbox.rs index f79c523c..caaddb4f 100644 --- a/glycin/src/sandbox.rs +++ b/glycin/src/sandbox.rs @@ -17,9 +17,8 @@ use memfd::{Memfd, MemfdOptions}; use nix::sys::resource; use crate::config::ConfigEntry; -use crate::error::ResultKind; use crate::util::{self, new_async_mutex, AsyncMutex}; -use crate::{ErrorKind, SandboxMechanism}; +use crate::{Error, SandboxMechanism}; type SystemSetupStore = Arc>>; @@ -191,7 +190,7 @@ impl Sandbox { self.ro_bind_extra.push(path); } - pub async fn spawn(self) -> ResultKind { + pub async fn spawn(self) -> Result { // Determine command line args let (bin, args, seccomp_fd) = match self.sandbox_mechanism { SandboxMechanism::Bwrap => { @@ -274,7 +273,7 @@ impl Sandbox { let command_dbg = format!("{:?}", command); tracing::debug!("Spawning loader/editor:\n {command_dbg}"); - let child = command.spawn().map_err(|err| ErrorKind::SpawnError { + let child = command.spawn().map_err(|err| Error::SpawnError { cmd: command_dbg.clone(), err: Arc::new(err), })?; @@ -286,7 +285,7 @@ impl Sandbox { }) } - async fn bwrap_args(&self) -> ResultKind> { + async fn bwrap_args(&self) -> Result, Error> { let mut args: Vec = Vec::new(); args.extend( @@ -486,7 +485,7 @@ impl Sandbox { Ok(filter) } - fn seccomp_export_bpf(filter: &ScmpFilterContext) -> ResultKind { + fn seccomp_export_bpf(filter: &ScmpFilterContext) -> Result { let mut memfd = MemfdOptions::default() .close_on_exec(false) .create("seccomp-bpf-filter")?; @@ -532,7 +531,7 @@ impl SystemSetup { } async fn load_lib_dirs(&mut self) -> io::Result<()> { - let dir_content: Result = std::fs::read_dir("/"); + let dir_content = std::fs::read_dir("/"); match dir_content { Ok(dir_content) => { diff --git a/libglycin/src/error.rs b/libglycin/src/error.rs index 044a7e89..9818b8f7 100644 --- a/libglycin/src/error.rs +++ b/libglycin/src/error.rs @@ -13,8 +13,8 @@ pub enum GlyLoaderError { UnknownImageFormat = 1, } -impl From<&glycin::ErrorKind> for GlyLoaderError { - fn from(value: &glycin::ErrorKind) -> Self { +impl From<&glycin::Error> for GlyLoaderError { + fn from(value: &glycin::Error) -> Self { if value.unsupported_format().is_some() { Self::UnknownImageFormat } else { @@ -33,13 +33,13 @@ pub unsafe extern "C" fn gly_loader_error_get_type() -> glib::ffi::GType { GlyLoaderError::static_type().into_glib() } -pub unsafe fn set_error(g_error: *mut *mut GError, err: &glycin::Error) { +pub unsafe fn set_error(g_error: *mut *mut GError, err: &glycin::ErrorCtx) { if !g_error.is_null() { *g_error = glib_error(err).into_glib_ptr(); } } -pub fn glib_error(err: &glycin::Error) -> glib::Error { - let gly_error: GlyLoaderError = err.kind().into(); +pub fn glib_error(err: &glycin::ErrorCtx) -> glib::Error { + let gly_error: GlyLoaderError = err.error().into(); glib::Error::new(gly_error, &err.to_string()) } diff --git a/tools/src/bin/glycin-image-info.rs b/tools/src/bin/glycin-image-info.rs index fc474c7f..8bc1f7c6 100644 --- a/tools/src/bin/glycin-image-info.rs +++ b/tools/src/bin/glycin-image-info.rs @@ -5,7 +5,7 @@ fn main() { glib::MainContext::default().block_on(run()).unwrap(); } -async fn run() -> Result<(), glycin::ErrorKind> { +async fn run() -> Result<(), glycin::Error> { let mut args = std::env::args(); let bin = args.next().unwrap(); let Some(path) = args.next() else { -- GitLab From 590eb454995a2d7913e9f34053d272ab9d1a0e07 Mon Sep 17 00:00:00 2001 From: Sophie Herold Date: Thu, 18 Jul 2024 01:39:30 +0200 Subject: [PATCH 3/3] glycin: Move API into loader --- glycin/src/api_loader.rs | 50 ++++++++++++++++++++++++++++------- glycin/src/default_formats.rs | 29 -------------------- glycin/src/lib.rs | 2 -- 3 files changed, 40 insertions(+), 41 deletions(-) delete mode 100644 glycin/src/default_formats.rs diff --git a/glycin/src/api_loader.rs b/glycin/src/api_loader.rs index d4c54a4a..a0ce167f 100644 --- a/glycin/src/api_loader.rs +++ b/glycin/src/api_loader.rs @@ -78,6 +78,46 @@ impl Loader { active_sandbox_mechanism: process_context.sandbox_mechanism, }) } + + /// Returns a list of mime types for which loaders are configured + pub async fn supported_mime_types() -> Vec { + config::Config::cached() + .await + .image_loader + .keys() + .cloned() + .collect() + } + + /// Formats that the default glycin loaders support + pub const DEFAULT_MIME_TYPES: &'static [&'static str] = &[ + // image-rs + "image/jpeg", + "image/png", + "image/gif", + "image/webp", + "image/tiff", + "image/x-tga", + "image/vnd-ms.dds", + "image/x-dds", + "image/bmp", + "image/vnd.microsoft.icon", + "image/vnd.radiance", + "image/x-exr", + "image/x-portable-bitmap", + "image/x-portable-graymap", + "image/x-portable-pixmap", + "image/x-portable-anymap", + "image/x-qoi", + // HEIF + "image/avif", + "image/heif", + // JXL + "image/jxl", + // SVG + "image/svg+xml", + "image/svg+xml-compressed", + ]; } /// Image handle containing metadata and allowing frame requests @@ -244,16 +284,6 @@ impl FrameRequest { } } -/// Returns a list of mime types for which loaders are configured -pub async fn supported_loader_mime_types() -> Vec { - config::Config::cached() - .await - .image_loader - .keys() - .cloned() - .collect() -} - #[cfg(test)] mod test { use super::*; diff --git a/glycin/src/default_formats.rs b/glycin/src/default_formats.rs deleted file mode 100644 index 56f50fa5..00000000 --- a/glycin/src/default_formats.rs +++ /dev/null @@ -1,29 +0,0 @@ -/// Formats that the default glycin loaders support -pub const DEFAULT_MIME_TYPES: &[&str] = &[ - // image-rs - "image/jpeg", - "image/png", - "image/gif", - "image/webp", - "image/tiff", - "image/x-tga", - "image/vnd-ms.dds", - "image/x-dds", - "image/bmp", - "image/vnd.microsoft.icon", - "image/vnd.radiance", - "image/x-exr", - "image/x-portable-bitmap", - "image/x-portable-graymap", - "image/x-portable-pixmap", - "image/x-portable-anymap", - "image/x-qoi", - // HEIF - "image/avif", - "image/heif", - // JXL - "image/jxl", - // SVG - "image/svg+xml", - "image/svg+xml-compressed", -]; diff --git a/glycin/src/lib.rs b/glycin/src/lib.rs index d92ca929..3a00eaf6 100644 --- a/glycin/src/lib.rs +++ b/glycin/src/lib.rs @@ -71,7 +71,6 @@ mod api_editor; mod api_loader; mod config; mod dbus; -mod default_formats; mod error; mod fontconfig; mod icc; @@ -86,7 +85,6 @@ pub use api_common::*; pub use api_editor::*; pub use api_loader::*; pub use config::COMPAT_VERSION; -pub use default_formats::DEFAULT_MIME_TYPES; pub use error::{Error, ErrorCtx}; pub use glycin_utils::{ImageInfo, ImageInfoDetails, RemoteError}; #[cfg(feature = "gdk4")] -- GitLab