gphoto2 1.0.2

High-level wrapper for libgphoto2
Documentation
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Camera configuration
//!
//! ## Configuring a camera
//! ```no_run
//! use gphoto2::{Context, widget::WidgetValue, Result};
//!
//! # fn main() -> Result<()> {
//! let context = Context::new()?;
//! let camera = context.autodetect_camera()?;
//!
//! let mut config = camera.config_key("iso")?;
//! config.set_value(WidgetValue::Menu("100".to_string()))?; // Set the iso to 100
//! camera.set_config(&config); // Apply setting to camera
//! # Ok(())
//! # }
//! ```

use crate::{
  helper::{chars_to_cow, to_c_string, uninit},
  try_gp_internal, Result,
};
use std::{
  borrow::Cow,
  ffi, fmt,
  marker::PhantomData,
  os::raw::{c_char, c_float, c_int, c_void},
};

macro_rules! get_widget_value {
  ($widget:expr, $tp:ty) => {{
    let mut value: $tp = unsafe { $crate::helper::uninit() };
    $crate::try_gp_internal!(libgphoto2_sys::gp_widget_get_value(
      $widget,
      &mut value as *mut $tp as *mut c_void
    ))?;
    value
  }};
}

/// Value of a widget
#[derive(Debug, PartialEq)]
pub enum WidgetValue {
  /// Textual data
  Text(String),
  /// Float in a range
  Range(f32),
  /// Boolean
  Toggle(bool),
  /// Selected choice
  Menu(String),
  /// Date
  Date(c_int),
}

/// Type of a widget
#[derive(Debug, PartialEq)]
pub enum WidgetType {
  /// Root configuration object
  Window,
  /// Configuration section
  Section,
  /// Text configuration
  Text,
  /// Range configuration
  Range {
    /// Minimum value
    min: f32,
    /// Maximum value
    max: f32,
    /// Step
    increment: f32,
  },
  /// Boolean
  Toggle,
  /// Choice between many values
  Menu {
    /// Choices
    choices: Vec<String>,
    /// If the value was internally represented as radio (which is the same)
    radio: bool,
  },
  /// Button
  Button,
  /// Date
  Date,
}

/// Iterator over the children of a widget
pub struct WidgetIterator<'a> {
  parent_widget: &'a Widget<'a>,
  count: usize,
  index: usize,
}

/// A configuration widget
pub struct Widget<'a> {
  pub(crate) inner: *mut libgphoto2_sys::CameraWidget,
  _phantom: PhantomData<&'a ffi::c_void>,
}

impl Drop for Widget<'_> {
  fn drop(&mut self) {
    unsafe {
      libgphoto2_sys::gp_widget_unref(self.inner);
    }
  }
}

impl fmt::Debug for Widget<'_> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("Widget")
      .field("id", &self.id().ok())
      .field("name", &self.name().ok())
      .field("label", &self.label().ok())
      .field("readonly", &self.readonly().ok())
      .field("widget_type", &self.widget_type().ok())
      .field(
        "value",
        &match self.value() {
          Ok((Some(value), _)) => Some(value),
          _ => None,
        },
      )
      .field("children", &self.children_iter().map(|iter| iter.collect::<Vec<Widget>>()))
      .finish()
  }
}

impl<'a> Widget<'a> {
  pub(crate) fn new(widget: *mut libgphoto2_sys::CameraWidget) -> Self {
    unsafe { libgphoto2_sys::gp_widget_ref(widget) };

    Self { inner: widget, _phantom: PhantomData }
  }

  /// If true, the widget cannot be written
  pub fn readonly(&self) -> Result<bool> {
    let mut readonly = unsafe { uninit() };

    try_gp_internal!(libgphoto2_sys::gp_widget_get_readonly(self.inner, &mut readonly))?;

    Ok(readonly == 1)
  }

  /// Get the widget label
  pub fn label(&self) -> Result<Cow<str>> {
    let mut label = unsafe { uninit() };

    try_gp_internal!(libgphoto2_sys::gp_widget_get_label(self.inner, &mut label))?;

    Ok(chars_to_cow(label))
  }

  /// Get the widget name
  pub fn name(&self) -> Result<Cow<str>> {
    let mut name = unsafe { uninit() };

    try_gp_internal!(libgphoto2_sys::gp_widget_get_name(self.inner, &mut name))?;
    Ok(chars_to_cow(name))
  }

  /// Get the widget id
  pub fn id(&self) -> Result<i32> {
    let mut id = unsafe { uninit() };

    try_gp_internal!(libgphoto2_sys::gp_widget_get_id(self.inner, &mut id))?;

    Ok(id)
  }

  /// Get information about the widget
  pub fn info(&self) -> Result<Cow<str>> {
    let mut info = unsafe { uninit() };

    try_gp_internal!(libgphoto2_sys::gp_widget_get_info(self.inner, &mut info))?;

    Ok(chars_to_cow(info))
  }

  /// Creates a new [`WidgetIterator`]
  pub fn children_iter(&'a self) -> Result<WidgetIterator<'a>> {
    Ok(WidgetIterator { parent_widget: self, count: self.children_count()?, index: 0 })
  }

  /// Counts the children of the widget
  pub fn children_count(&self) -> Result<usize> {
    try_gp_internal!(libgphoto2_sys::gp_widget_count_children(self.inner))
      .map(|count| count as usize)
  }

  /// Gets a child by its index
  pub fn get_child(&self, index: usize) -> Result<Widget<'a>> {
    let mut child = unsafe { uninit() };

    try_gp_internal!(libgphoto2_sys::gp_widget_get_child(self.inner, index as c_int, &mut child))?;

    Ok(Self::new(child))
  }

  /// Get a child by its id
  pub fn get_child_by_id(&self, id: usize) -> Result<Widget<'a>> {
    let mut child = unsafe { uninit() };

    try_gp_internal!(libgphoto2_sys::gp_widget_get_child_by_id(
      self.inner,
      id as c_int,
      &mut child
    ))?;

    Ok(Self::new(child))
  }

  /// Get a child by its label
  pub fn get_child_by_label(&self, label: &str) -> Result<Widget<'a>> {
    let mut child = unsafe { uninit() };

    to_c_string!(label);

    try_gp_internal!(libgphoto2_sys::gp_widget_get_child_by_label(
      self.inner,
      label.as_ptr() as *const c_char,
      &mut child
    ))?;

    Ok(Self::new(child))
  }

  /// Get a child by its name
  pub fn get_child_by_name(&self, name: &str) -> Result<Widget<'a>> {
    let mut child = unsafe { uninit() };

    to_c_string!(name);

    try_gp_internal!(libgphoto2_sys::gp_widget_get_child_by_name(
      self.inner,
      name.as_ptr() as *const c_char,
      &mut child
    ))?;

    Ok(Self::new(child))
  }

  /// Get the type of the widget
  pub fn widget_type(&self) -> Result<WidgetType> {
    use libgphoto2_sys::CameraWidgetType;

    let mut widget_type = unsafe { uninit() };

    try_gp_internal!(libgphoto2_sys::gp_widget_get_type(self.inner, &mut widget_type))?;

    Ok(match widget_type {
      CameraWidgetType::GP_WIDGET_WINDOW => WidgetType::Window,
      CameraWidgetType::GP_WIDGET_SECTION => WidgetType::Section,
      CameraWidgetType::GP_WIDGET_TEXT => WidgetType::Text,
      CameraWidgetType::GP_WIDGET_RANGE => {
        let (mut min, mut max, mut increment) = unsafe { (uninit(), uninit(), uninit()) };

        try_gp_internal!(libgphoto2_sys::gp_widget_get_range(
          self.inner,
          &mut min,
          &mut max,
          &mut increment
        ))?;

        WidgetType::Range { min, max, increment }
      }
      CameraWidgetType::GP_WIDGET_TOGGLE => WidgetType::Toggle,
      CameraWidgetType::GP_WIDGET_MENU | CameraWidgetType::GP_WIDGET_RADIO => {
        let choice_count = try_gp_internal!(libgphoto2_sys::gp_widget_count_choices(self.inner))?;
        let mut choices = Vec::with_capacity(choice_count as usize);

        for choice_i in 0..choice_count {
          let mut choice = unsafe { uninit() };

          try_gp_internal!(libgphoto2_sys::gp_widget_get_choice(
            self.inner,
            choice_i,
            &mut choice
          ))?;

          choices.push(chars_to_cow(choice).to_string());
        }

        WidgetType::Menu {
          choices: choices,
          radio: widget_type == CameraWidgetType::GP_WIDGET_RADIO,
        }
      }
      CameraWidgetType::GP_WIDGET_BUTTON => WidgetType::Button,
      CameraWidgetType::GP_WIDGET_DATE => WidgetType::Date,
    })
  }

  /// Get the widget value and type
  pub fn value(&self) -> Result<(Option<WidgetValue>, WidgetType)> {
    let widget_type = self.widget_type()?;

    Ok((
      match widget_type {
        WidgetType::Window | WidgetType::Button | WidgetType::Section => None,
        WidgetType::Text => {
          let text = chars_to_cow(get_widget_value!(self.inner, *const c_char));

          Some(WidgetValue::Text(text.to_string()))
        }
        WidgetType::Range { .. } => {
          let range_value = get_widget_value!(self.inner, c_float);

          Some(WidgetValue::Range(range_value))
        }
        WidgetType::Toggle => {
          let boolean = get_widget_value!(self.inner, c_int);

          Some(WidgetValue::Toggle(boolean == 0))
        }
        WidgetType::Date => {
          let date_int = get_widget_value!(self.inner, c_int);

          Some(WidgetValue::Date(date_int))
        }
        WidgetType::Menu { .. } => {
          let choice = chars_to_cow(get_widget_value!(self.inner, *const c_char));

          Some(WidgetValue::Menu(choice.to_string()))
        }
      },
      widget_type,
    ))
  }

  /// Sets the value of the widget
  ///
  /// **Note**: This only sets the value of the configuration, to apply the setting to the camera use [`Camera::set_config`](crate::Camera::set_config)
  pub fn set_value(&mut self, value: WidgetValue) -> Result<()> {
    let self_type = self.widget_type()?;

    match self_type {
      WidgetType::Window => Err("Window has no value")?,
      WidgetType::Section => Err("Section has no value")?,
      WidgetType::Button => Err("Button has no value")?,
      WidgetType::Text => {
        if let WidgetValue::Text(text) = value {
          to_c_string!(text);
          try_gp_internal!(libgphoto2_sys::gp_widget_set_value(
            self.inner,
            text.as_ptr() as *const c_void
          ))?;
        } else {
          Err("Expected value to be a string")?;
        }
      }
      WidgetType::Range { min, max, .. } => {
        if let WidgetValue::Range(range_value) = value {
          if (range_value < min) || (range_value > max) {
            Err("Value out of range")?;
          }

          try_gp_internal!(libgphoto2_sys::gp_widget_set_value(
            self.inner,
            &range_value as *const f32 as *const c_void
          ))?;
        } else {
          Err("Expected value to be Range")?;
        }
      }
      WidgetType::Toggle => {
        if let WidgetValue::Toggle(toggle_value) = value {
          let toggle_value = if toggle_value { 1 } else { 0 };
          try_gp_internal!(libgphoto2_sys::gp_widget_set_value(
            self.inner,
            &toggle_value as *const c_int as *const c_void
          ))?;
        } else {
          Err("Expected value to be Toggle")?;
        }
      }
      WidgetType::Date => {
        if let WidgetValue::Date(unix_date) = value {
          try_gp_internal!(libgphoto2_sys::gp_widget_set_value(
            self.inner,
            &unix_date as *const c_int as *const c_void
          ))?;
        } else {
          Err("Expected value to be Date")?;
        }
      }
      WidgetType::Menu { choices, .. } => {
        if let WidgetValue::Menu(choice) = value {
          if !choices.contains(&choice) {
            Err("Choice not in choices")?;
          }

          to_c_string!(choice);

          try_gp_internal!(libgphoto2_sys::gp_widget_set_value(
            self.inner,
            choice.as_ptr() as *const c_void
          ))?;
        } else {
          Err("Expected value to be Menu")?;
        }
      }
    }

    Ok(())
  }
}

impl<'a> Iterator for WidgetIterator<'a> {
  type Item = Widget<'a>;

  fn next(&mut self) -> Option<Self::Item> {
    if self.index >= self.count {
      None
    } else {
      let child = self.parent_widget.get_child(self.index).ok();
      self.index += 1;

      child
    }
  }
}