Skip to main content

collect_settings/
general.rs

1use serde::{Deserialize, Serialize};
2
3macro_rules! str_enum {
4    ($(#[$doc:meta])* $name:ident { $($(#[$vdoc:meta])* $variant:ident = $value:literal),+ $(,)? }) => {
5        $(#[$doc])*
6        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
7        pub enum $name {
8            $( $(#[$vdoc])* #[serde(rename = $value)] $variant ),+
9        }
10        impl $name {
11            /// Every variant, in declaration order.
12            pub const ALL: &'static [$name] = &[$($name::$variant),+];
13            /// The string Collect stores for this value.
14            pub fn as_str(self) -> &'static str {
15                match self { $($name::$variant => $value),+ }
16            }
17        }
18        impl std::str::FromStr for $name {
19            type Err = String;
20            fn from_str(s: &str) -> Result<Self, Self::Err> {
21                match s { $($value => Ok($name::$variant),)+ other => Err(format!("unknown {}: {other}", stringify!($name))) }
22            }
23        }
24        impl std::fmt::Display for $name {
25            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) }
26        }
27    };
28}
29
30str_enum! {
31    /// When finalized forms are sent without the interviewer pressing *Send*.
32    Autosend {
33        /// Never send automatically.
34        Off = "off",
35        /// Only over Wi-Fi.
36        WifiOnly = "wifi_only",
37        /// Only over mobile data.
38        CellularOnly = "cellular_only",
39        /// Over any connection.
40        WifiAndCellular = "wifi_and_cellular",
41    }
42}
43
44str_enum! {
45    /// How blank forms are kept in sync with the server.
46    FormUpdateMode {
47        /// Only when the interviewer opens *Get Blank Form*.
48        Manual = "manual",
49        /// Check for new versions of forms already on the device.
50        PreviouslyDownloaded = "previously_downloaded",
51        /// Mirror the server: download new forms, update changed ones, remove the rest.
52        MatchExactly = "match_exactly",
53    }
54}
55
56str_enum! {
57    /// Interval of the background check for form updates.
58    PeriodicCheck {
59        /// Every 15 minutes.
60        Every15Minutes = "every_fifteen_minutes",
61        /// Every hour.
62        EveryHour = "every_one_hour",
63        /// Every six hours.
64        Every6Hours = "every_six_hours",
65        /// Once a day.
66        Every24Hours = "every_24_hours",
67    }
68}
69
70str_enum! {
71    /// How the interviewer moves between questions.
72    Navigation {
73        /// Horizontal swipes.
74        Swipe = "swipe",
75        /// Forward/back buttons.
76        Buttons = "buttons",
77        /// Both.
78        SwipeAndButtons = "swipe_buttons",
79    }
80}
81
82str_enum! {
83    /// When constraints are validated.
84    ConstraintBehavior {
85        /// On every forward swipe.
86        OnSwipe = "on_swipe",
87        /// Only when finalizing.
88        OnFinalize = "on_finalize",
89    }
90}
91
92str_enum! {
93    /// Whether guidance hints are shown.
94    GuidanceHint {
95        /// Hidden.
96        No = "no",
97        /// Always shown.
98        Yes = "yes",
99        /// Shown collapsed.
100        YesCollapsed = "yes_collapsed",
101    }
102}
103
104str_enum! {
105    /// Downscaling applied to photos taken in the form.
106    ImageSize {
107        /// No downscaling.
108        Original = "original",
109        /// Very small (640 px).
110        VerySmall = "very_small",
111        /// Small (1024 px).
112        Small = "small",
113        /// Medium (2048 px).
114        Medium = "medium",
115        /// Large (3072 px).
116        Large = "large",
117    }
118}
119
120str_enum! {
121    /// App theme.
122    Theme {
123        /// Light.
124        Light = "light_theme",
125        /// Dark.
126        Dark = "dark_theme",
127    }
128}
129
130str_enum! {
131    /// Basemap provider for geo questions.
132    BasemapSource {
133        /// Google Maps.
134        Google = "google",
135        /// Mapbox.
136        Mapbox = "mapbox",
137        /// OpenStreetMap.
138        Osm = "osm",
139        /// USGS.
140        Usgs = "usgs",
141        /// Carto.
142        Carto = "carto",
143    }
144}
145
146/// Font size of the form entry screen, in sp. Collect accepts 13, 17, 21, 25 and 29.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
148#[serde(into = "u8", try_from = "u8")]
149pub enum FontSize {
150    /// 13 sp.
151    ExtraSmall,
152    /// 17 sp.
153    Small,
154    /// 21 sp (the app default).
155    Medium,
156    /// 25 sp.
157    Large,
158    /// 29 sp.
159    ExtraLarge,
160}
161
162impl From<FontSize> for u8 {
163    fn from(f: FontSize) -> u8 {
164        match f {
165            FontSize::ExtraSmall => 13,
166            FontSize::Small => 17,
167            FontSize::Medium => 21,
168            FontSize::Large => 25,
169            FontSize::ExtraLarge => 29,
170        }
171    }
172}
173
174impl TryFrom<u8> for FontSize {
175    type Error = String;
176    fn try_from(v: u8) -> Result<Self, Self::Error> {
177        Ok(match v {
178            13 => FontSize::ExtraSmall,
179            17 => FontSize::Small,
180            21 => FontSize::Medium,
181            25 => FontSize::Large,
182            29 => FontSize::ExtraLarge,
183            other => {
184                return Err(format!(
185                    "font_size must be 13, 17, 21, 25 or 29, got {other}"
186                ))
187            }
188        })
189    }
190}
191
192/// Unprotected settings. Every field is optional: an omitted key resets to
193/// the app default when the code is scanned, so set only what you mean.
194#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
195pub struct General {
196    // ---------------------------------------------------------------- server
197    /// Server protocol. Always `odk_default` for ODK Central and KoboToolbox.
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub protocol: Option<String>,
200    /// Base URL of the OpenRosa server. For KoboToolbox this is the KoboCAT
201    /// host (`https://kc.kobotoolbox.org`, `https://kc-eu.kobotoolbox.org`),
202    /// never the `kf.`/`eu.` web interface.
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub server_url: Option<String>,
205    /// Account the device logs in with.
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub username: Option<String>,
208    /// Password of that account.
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub password: Option<String>,
211    /// Legacy custom form list URL (`protocol = other`, removed from recent
212    /// app versions). Kept for decoding old codes.
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub formlist_url: Option<String>,
215    /// Legacy custom submission URL. See [`General::formlist_url`].
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub submission_url: Option<String>,
218
219    // ------------------------------------------------------------ interface
220    /// Light or dark theme.
221    #[serde(default, rename = "appTheme", skip_serializing_if = "Option::is_none")]
222    pub app_theme: Option<Theme>,
223    /// UI language as a BCP 47 code (`pt`, `es`, `en`…).
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub app_language: Option<String>,
226    /// Font size of the form entry screen.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub font_size: Option<FontSize>,
229    /// Swipe, buttons or both.
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub navigation: Option<Navigation>,
232
233    // ----------------------------------------------------------------- maps
234    /// Basemap provider.
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    pub basemap_source: Option<BasemapSource>,
237    /// Google map style (1–4).
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub google_map_style: Option<u8>,
240    /// Mapbox style URL.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub mapbox_map_style: Option<String>,
243    /// USGS style (`topographic`, `hybrid`, `satellite`).
244    #[serde(default, skip_serializing_if = "Option::is_none")]
245    pub usgs_map_style: Option<String>,
246    /// Carto style (`positron`, `dark_matter`).
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub carto_map_style: Option<String>,
249    /// Absolute path of an `.mbtiles` reference layer on the device.
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub reference_layer: Option<String>,
252
253    // ------------------------------------------------------ form management
254    /// How blank forms are kept in sync.
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub form_update_mode: Option<FormUpdateMode>,
257    /// Background check interval (used by `previously_downloaded` and `match_exactly`).
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub periodic_form_updates_check: Option<PeriodicCheck>,
260    /// Download updates without asking.
261    #[serde(default, skip_serializing_if = "Option::is_none")]
262    pub automatic_update: Option<bool>,
263    /// Hide superseded versions in the blank-form list.
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub hide_old_form_versions: Option<bool>,
266    /// Send finalized forms automatically.
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub autosend: Option<Autosend>,
269    /// Delete the local copy after a successful send (`delete_send` in the app).
270    #[serde(
271        default,
272        rename = "delete_send",
273        skip_serializing_if = "Option::is_none"
274    )]
275    pub delete_send: Option<bool>,
276    /// Mark forms as finalized by default on the save screen (older app versions).
277    #[serde(default, skip_serializing_if = "Option::is_none")]
278    pub default_completed: Option<bool>,
279    /// Validate on every swipe or only on finalize.
280    #[serde(default, skip_serializing_if = "Option::is_none")]
281    pub constraint_behavior: Option<ConstraintBehavior>,
282    /// Take photos at full resolution.
283    #[serde(default, skip_serializing_if = "Option::is_none")]
284    pub high_resolution: Option<bool>,
285    /// Downscale photos.
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub image_size: Option<ImageSize>,
288    /// Record audio with an external app instead of the built-in recorder.
289    #[serde(default, skip_serializing_if = "Option::is_none")]
290    pub external_app_recording: Option<bool>,
291    /// Guidance hint display.
292    #[serde(default, skip_serializing_if = "Option::is_none")]
293    pub guidance_hint: Option<GuidanceHint>,
294    /// Sync the instance list with the file system (`instance_sync`).
295    #[serde(
296        default,
297        rename = "instance_sync",
298        skip_serializing_if = "Option::is_none"
299    )]
300    pub instance_sync: Option<bool>,
301
302    // --------------------------------------------------------------- identity
303    /// Send anonymous usage data.
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub analytics: Option<bool>,
306    /// Form metadata: username.
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub metadata_username: Option<String>,
309    /// Form metadata: phone number.
310    #[serde(default, skip_serializing_if = "Option::is_none")]
311    pub metadata_phonenumber: Option<String>,
312    /// Form metadata: e-mail.
313    #[serde(default, skip_serializing_if = "Option::is_none")]
314    pub metadata_email: Option<String>,
315
316    /// Any other key, kept verbatim so unknown or future settings survive a
317    /// decode → encode roundtrip.
318    #[serde(default, flatten, skip_serializing_if = "serde_json::Map::is_empty")]
319    pub extra: serde_json::Map<String, serde_json::Value>,
320}
321
322impl General {
323    /// Server, account and the "hands-off" form management the field wants:
324    /// the device mirrors the server (`match_exactly`), downloads new versions
325    /// on its own every 15 minutes, sends finalized forms over any connection
326    /// and keeps the local copy after sending.
327    pub fn auto_sync(
328        server_url: impl Into<String>,
329        username: impl Into<String>,
330        password: impl Into<String>,
331    ) -> Self {
332        General {
333            server_url: Some(server_url.into()),
334            username: Some(username.into()),
335            password: Some(password.into()),
336            form_update_mode: Some(FormUpdateMode::MatchExactly),
337            periodic_form_updates_check: Some(PeriodicCheck::Every15Minutes),
338            automatic_update: Some(true),
339            hide_old_form_versions: Some(true),
340            autosend: Some(Autosend::WifiAndCellular),
341            delete_send: Some(false),
342            ..Default::default()
343        }
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    #[test]
352    fn enum_strings_match_collect() {
353        assert_eq!(
354            serde_json::to_string(&Autosend::WifiAndCellular).unwrap(),
355            "\"wifi_and_cellular\""
356        );
357        assert_eq!(serde_json::to_string(&FontSize::Medium).unwrap(), "21");
358        assert_eq!(
359            serde_json::from_str::<FontSize>("29").unwrap(),
360            FontSize::ExtraLarge
361        );
362        assert!(serde_json::from_str::<FontSize>("20").is_err());
363        assert_eq!(
364            "match_exactly".parse::<FormUpdateMode>().unwrap(),
365            FormUpdateMode::MatchExactly
366        );
367    }
368
369    #[test]
370    fn unknown_keys_survive() {
371        let g: General =
372            serde_json::from_str(r#"{"server_url":"https://x","future_key":1}"#).unwrap();
373        assert_eq!(g.extra["future_key"], 1);
374        let json = serde_json::to_string(&g).unwrap();
375        assert!(json.contains("future_key"));
376    }
377}