gphoto2 3.2.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
//! Library context
use crate::{
  abilities::AbilitiesList,
  camera::Camera,
  helper::{as_ref, chars_to_string, to_c_string},
  list::CameraList,
  list::{CameraDescriptor, CameraListIter},
  port::PortInfoList,
  task::{BackgroundPtr, Task},
  try_gp_internal, Error, Result,
};
use std::ffi;
use std::ops::DerefMut;
use std::os::raw::{c_char, c_float, c_uint, c_void};
use std::sync::{Arc, Mutex};

/// Progress handler trait
pub trait ProgressHandler: 'static + Send {
  /// This method is called when a progress starts.
  ///
  /// It must return a unique ID which is passed to the following functions
  fn start(&mut self, target: f32, message: String) -> u32;

  /// Progress has updated
  fn update(&mut self, id: u32, progress: f32);

  /// Progress has stopped
  fn stop(&mut self, id: u32);
}

/// Cancel handler trait
pub(crate) trait CancelHandler: 'static + Send {
  fn cancel(&mut self) -> bool;
}

/// Context used internally by libgphoto2
///
/// ## Example
///
/// ```no_run
/// use gphoto2::{Context, Result};
///
/// # fn main() -> Result<()> {
/// let context = Context::new()?;
///
/// // Use first camera in the camera list
///
/// let camera_desc = context.list_cameras().wait()?.next().ok_or("No cameras found")?;
/// let camera = context.get_camera(&camera_desc).wait()?;
///
/// # Ok(())
/// # }
///
/// ```
pub struct Context {
  pub(crate) inner: BackgroundPtr<libgphoto2_sys::GPContext>,
  progress_handler: Option<Arc<Mutex<dyn ProgressHandler>>>,
  cancel_handler: Option<Arc<Mutex<dyn CancelHandler>>>,
}

impl Drop for Context {
  fn drop(&mut self) {
    let context = self.inner;

    unsafe {
      Task::new(move || libgphoto2_sys::gp_context_unref(*context));
    }
  }
}

impl Clone for Context {
  fn clone(&self) -> Self {
    unsafe {
      libgphoto2_sys::gp_context_ref(*self.inner);
    }

    Self {
      inner: self.inner,
      progress_handler: self.progress_handler.clone(),
      cancel_handler: self.cancel_handler.clone(),
    }
  }
}

as_ref!(Context -> libgphoto2_sys::GPContext, **self.inner);

// TODO: once CoerceUnsized is stable, make this a function.
macro_rules! alloc_handler {
  ($handler:expr) => {{
    let mut handler = Arc::new(Mutex::new($handler));

    // Now that handler is on the heap, the pointer should be stable.
    // Also, we know that there are and won't be other mutable references to it,
    // so we can safely retrieve a raw mutable pointer from the Mutex
    // and give it to the C code.
    let handler_ptr: *mut _ = Arc::get_mut(&mut handler).unwrap().get_mut().unwrap();

    (handler, handler_ptr.cast::<c_void>())
  }};
}

impl Context {
  /// Create a new context
  pub fn new() -> Result<Self> {
    #[cfg(feature = "extended_logs")]
    crate::helper::hook_gp_log();

    let context_ptr = unsafe { libgphoto2_sys::gp_context_new() };

    if context_ptr.is_null() {
      return Err(Error::new(libgphoto2_sys::GP_ERROR_NO_MEMORY, None));
    }

    #[cfg(not(feature = "extended_logs"))]
    crate::helper::hook_gp_context_log_func(context_ptr);

    Ok(Self { inner: BackgroundPtr(context_ptr), progress_handler: None, cancel_handler: None })
  }

  /// Lists all available cameras and their ports
  ///
  /// Returns a list of (camera_name, port_path)
  /// which can be used in [`Context::get_camera`].
  pub fn list_cameras(&self) -> Task<Result<CameraListIter>> {
    let context = self.clone().inner;

    unsafe {
      Task::new(move || {
        let camera_list = CameraList::new()?;
        try_gp_internal!(gp_camera_autodetect(*camera_list.inner, *context)?);

        Ok(CameraListIter::new(camera_list))
      })
    }
    .context(self.inner)
  }

  /// Auto chooses a camera
  ///
  /// ```no_run
  /// use gphoto2::{Context, Result};
  ///
  /// # fn main() -> Result<()> {
  /// let context = Context::new()?;
  /// if let Ok(camera) = context.autodetect_camera().wait() {
  ///   println!("Successfully autodetected camera '{}'", camera.abilities().model());
  /// } else {
  ///   println!("Could not autodetect camera");
  /// }
  /// # Ok(())
  /// # }
  /// ```
  pub fn autodetect_camera(&self) -> Task<Result<Camera>> {
    let context = self.clone();

    unsafe {
      Task::new(move || {
        try_gp_internal!(gp_camera_new(&out camera_ptr)?);
        try_gp_internal!(gp_camera_init(camera_ptr, *context.inner)?);

        Ok(Camera::new(BackgroundPtr(camera_ptr), context))
      })
      .context(self.inner)
    }
  }

  /// Initialize a camera knowing its model name and port path
  ///
  /// ```no_run
  /// use gphoto2::{Context, Result};
  ///
  /// # fn main() -> Result<()> {
  /// let context = Context::new()?;
  ///
  /// let camera_desc = context.list_cameras().wait()?.next().ok_or("No cameras found")?;
  /// let camera = context.get_camera(&camera_desc).wait()?;
  ///
  /// # Ok(())
  /// # }
  pub fn get_camera(&self, camera_descriptor: &CameraDescriptor) -> Task<Result<Camera>> {
    let context = self.clone();
    let camera_descriptor = camera_descriptor.clone();

    unsafe {
      Task::new(move || {
        let abilities_list = AbilitiesList::new_inner(&context)?;
        let port_info_list = PortInfoList::new_inner()?;

        try_gp_internal!(gp_camera_new(&out camera)?);

        try_gp_internal!(let model_index = gp_abilities_list_lookup_model(
          *abilities_list.inner,
          to_c_string!(camera_descriptor.model.as_str())
        )?);

        try_gp_internal!(gp_abilities_list_get_abilities(
          *abilities_list.inner,
          model_index,
          &out model_abilities
        )?);
        try_gp_internal!(gp_camera_set_abilities(camera, model_abilities)?);

        try_gp_internal!(let p = gp_port_info_list_lookup_path(
          port_info_list.inner,
          to_c_string!(camera_descriptor.port.as_str())
        )?);
        let port_info = port_info_list.get_port_info(p)?;
        try_gp_internal!(gp_camera_set_port_info(camera, port_info.inner)?);

        Ok(Camera::new(BackgroundPtr(camera), context))
      })
    }
    .context(self.inner)
  }

  /// Set context progress functions
  ///
  /// `libgphoto2` allows you to set progress functions to a context, these
  /// allow you to show some progress bars whenever eg. an image is being downloaded.
  ///
  /// # Example
  ///
  /// An example can be found in the examples directory
  pub fn set_progress_handlers<H: ProgressHandler>(&mut self, handler: H) {
    unsafe extern "C" fn start_func<H: ProgressHandler>(
      _ctx: *mut libgphoto2_sys::GPContext,
      target: c_float,
      message: *const c_char,
      data: *mut c_void,
    ) -> c_uint {
      as_handler::<H>(data).start(target, chars_to_string(message))
    }

    unsafe extern "C" fn update_func<H: ProgressHandler>(
      _ctx: *mut libgphoto2_sys::GPContext,
      id: c_uint,
      current: c_float,
      data: *mut c_void,
    ) {
      as_handler::<H>(data).update(id, current)
    }

    unsafe extern "C" fn stop_func<H: ProgressHandler>(
      _ctx: *mut libgphoto2_sys::GPContext,
      id: c_uint,
      data: *mut c_void,
    ) {
      as_handler::<H>(data).stop(id)
    }

    let (progress_handler, progress_handler_ptr) = alloc_handler!(handler);

    unsafe {
      libgphoto2_sys::gp_context_set_progress_funcs(
        *self.inner,
        Some(start_func::<H>),
        Some(update_func::<H>),
        Some(stop_func::<H>),
        progress_handler_ptr,
      );
    }

    self.progress_handler = Some(progress_handler);
  }

  pub(crate) fn set_cancel_handler<H>(&mut self, handler: H)
  where
    H: CancelHandler,
  {
    use libgphoto2_sys::GPContextFeedback;

    unsafe extern "C" fn handle_cancel<H: CancelHandler>(
      _ctx: *mut libgphoto2_sys::GPContext,
      data: *mut c_void,
    ) -> GPContextFeedback {
      if as_handler::<H>(data).cancel() {
        GPContextFeedback::GP_CONTEXT_FEEDBACK_CANCEL
      } else {
        GPContextFeedback::GP_CONTEXT_FEEDBACK_OK
      }
    }

    let (cancel_handler, cancel_handler_ptr) = alloc_handler!(handler);

    unsafe {
      libgphoto2_sys::gp_context_set_cancel_func(
        *self.inner,
        Some(handle_cancel::<H>),
        cancel_handler_ptr,
      );
    }

    self.cancel_handler = Some(cancel_handler);
  }

  pub(crate) fn unset_progress_handlers(&mut self) {
    unsafe {
      libgphoto2_sys::gp_context_set_progress_funcs(
        *self.inner,
        None,
        None,
        None,
        std::ptr::null_mut(),
      );
    }

    self.progress_handler = None;
  }

  pub(crate) fn unset_cancel_handlers(&mut self) {
    unsafe {
      libgphoto2_sys::gp_context_set_cancel_func(*self.inner, None, std::ptr::null_mut());
    }

    self.cancel_handler = None;
  }
}

impl Context {
  pub(crate) fn from_ptr(ptr: BackgroundPtr<libgphoto2_sys::GPContext>) -> Self {
    Self { cancel_handler: None, inner: ptr, progress_handler: None }
  }
}

unsafe fn as_handler<H>(data: *mut c_void) -> &'static mut H {
  &mut *data.cast()
}

impl ProgressHandler for Box<dyn ProgressHandler> {
  fn start(&mut self, target: f32, message: String) -> u32 {
    self.deref_mut().start(target, message)
  }

  fn update(&mut self, id: u32, progress: f32) {
    self.deref_mut().update(id, progress)
  }

  fn stop(&mut self, id: u32) {
    self.deref_mut().stop(id)
  }
}

#[cfg(all(test, feature = "test"))]
mod tests {
  // Compile-only test to ensure that Context is Send + Sync.
  const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<super::Context>()
  };

  #[test]
  fn test_list_cameras() {
    let cameras = crate::sample_context().list_cameras().wait().unwrap().collect::<Vec<_>>();
    insta::assert_debug_snapshot!(cameras);
  }

  #[test]
  fn test_progress() {
    use std::fmt::Write;

    let context = crate::sample_context();

    #[derive(Default)]
    struct TestProgress {
      log_lines: String,
      next_progress_id: u32,
    }

    impl Drop for TestProgress {
      fn drop(&mut self) {
        insta::assert_snapshot!("progress", self.log_lines);
      }
    }

    impl crate::context::ProgressHandler for TestProgress {
      fn start(&mut self, target: f32, message: String) -> u32 {
        let id = self.next_progress_id;

        // For some reason, gphoto2 discovers each dynamic library twice on Windows.
        #[cfg(windows)]
        let target = target / 2.0;

        self.next_progress_id += 1;
        writeln!(
          self.log_lines,
          "start #{id}: target: {target}, message: {message}",
          message = message.replace(
            &libgphoto2_sys::test_utils::libgphoto2_dir().to_str().unwrap().replace('\\', "/"),
            "$LIBGPHOTO2_DIR"
          ),
        )
        .unwrap();
        id
      }

      fn update(&mut self, id: u32, progress: f32) {
        writeln!(self.log_lines, "update #{id}: progress: {progress}").unwrap();
      }

      fn stop(&mut self, id: u32) {
        writeln!(self.log_lines, "stop #{id}").unwrap();
      }
    }

    let mut task = context.list_cameras();

    task.set_progress_handler(TestProgress::default());

    let _ = task.wait();
  }
}