glycin_utils/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
use std::any::Any;

#[derive(zbus::DBusError, Debug, Clone)]
#[zbus(prefix = "org.gnome.glycin.Error")]
#[non_exhaustive]
/// Error within the remote process.
///
/// Errors that appear within the loader or editor.
pub enum RemoteError {
    #[zbus(error)]
    ZBus(zbus::Error),
    LoadingError(String),
    InternalLoaderError(String),
    EditingError(String),
    InternalEditorError(String),
    UnsupportedImageFormat(String),
    ConversionTooLargerError,
    OutOfMemory(String),
}

type Location = std::panic::Location<'static>;

impl ProcessError {
    pub fn into_loader_error(self) -> RemoteError {
        match self {
            err @ ProcessError::ExpectedError { .. } => RemoteError::LoadingError(err.to_string()),
            err @ ProcessError::InternalError { .. } => {
                RemoteError::InternalLoaderError(err.to_string())
            }
            ProcessError::UnsupportedImageFormat(msg) => RemoteError::UnsupportedImageFormat(msg),
            ProcessError::ConversionTooLargerError => RemoteError::ConversionTooLargerError,
            err @ ProcessError::OutOfMemory { .. } => RemoteError::OutOfMemory(err.to_string()),
        }
    }

    pub fn into_editor_error(self) -> RemoteError {
        match self {
            err @ ProcessError::ExpectedError { .. } => RemoteError::EditingError(err.to_string()),
            err @ ProcessError::InternalError { .. } => {
                RemoteError::InternalEditorError(err.to_string())
            }
            ProcessError::UnsupportedImageFormat(msg) => RemoteError::UnsupportedImageFormat(msg),
            ProcessError::ConversionTooLargerError => RemoteError::ConversionTooLargerError,
            err @ ProcessError::OutOfMemory { .. } => RemoteError::OutOfMemory(err.to_string()),
        }
    }
}

#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum ProcessError {
    #[error("{location}: {err}")]
    ExpectedError { err: String, location: Location },
    #[error("{location}: Internal error: {err}")]
    InternalError { err: String, location: Location },
    #[error("Unsupported image format: {0}")]
    UnsupportedImageFormat(String),
    #[error("Dimension too large for system")]
    ConversionTooLargerError,
    #[error("{location}: Not enough memory available")]
    OutOfMemory { location: Location },
}

impl ProcessError {
    #[track_caller]
    pub fn expected(err: &impl ToString) -> Self {
        Self::ExpectedError {
            err: err.to_string(),
            location: *Location::caller(),
        }
    }

    #[track_caller]
    pub fn out_of_memory() -> Self {
        Self::OutOfMemory {
            location: *Location::caller(),
        }
    }
}

impl From<DimensionTooLargerError> for ProcessError {
    fn from(err: DimensionTooLargerError) -> Self {
        eprintln!("Decoding error: {err:?}");
        Self::ConversionTooLargerError
    }
}

pub trait GenericContexts<T> {
    fn expected_error(self) -> Result<T, ProcessError>;
    fn internal_error(self) -> Result<T, ProcessError>;
}

impl<T, E> GenericContexts<T> for Result<T, E>
where
    E: std::error::Error + Any + Send + Sync + 'static,
{
    #[track_caller]
    fn expected_error(self) -> Result<T, ProcessError> {
        match self {
            Ok(x) => Ok(x),
            Err(err) => Err(
                if let Some(err) = ((&err) as &dyn Any).downcast_ref::<ProcessError>() {
                    if matches!(err, ProcessError::OutOfMemory { .. }) {
                        ProcessError::out_of_memory()
                    } else {
                        ProcessError::expected(err)
                    }
                } else {
                    ProcessError::expected(&err)
                },
            ),
        }
    }

    #[track_caller]
    fn internal_error(self) -> Result<T, ProcessError> {
        match self {
            Ok(x) => Ok(x),
            Err(err) => Err(ProcessError::InternalError {
                err: err.to_string(),
                location: *Location::caller(),
            }),
        }
    }
}

impl<T> GenericContexts<T> for Option<T> {
    #[track_caller]
    fn expected_error(self) -> Result<T, ProcessError> {
        match self {
            Some(x) => Ok(x),
            None => Err(ProcessError::ExpectedError {
                err: String::from("None"),
                location: *Location::caller(),
            }),
        }
    }

    #[track_caller]
    fn internal_error(self) -> Result<T, ProcessError> {
        match self {
            Some(x) => Ok(x),
            None => Err(ProcessError::InternalError {
                err: String::from("None"),
                location: *Location::caller(),
            }),
        }
    }
}

#[derive(Debug)]
pub struct DimensionTooLargerError;

impl std::fmt::Display for DimensionTooLargerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        f.write_str("Dimension too large for system")
    }
}

impl std::error::Error for DimensionTooLargerError {}