Rust wrapper for gphoto2 (mirror of https://git.maxicarlos.de/maxicarlos08/gphoto2-rs)

Overview

GPhoto2-rs

Rust bindings to libgphoto2

What about gphoto-rs?

I know about the other crate (gphoto and gphoto2-sys which was created by @dcuddeback, but it is missing a lot of features which make the crate unusable for me, most notably the ability to change camera settings and in memory file download.
The author hasn't been active since 2017 regardless of numerous pull- and feature requests, so I made a new project with a more up to date rust code and all the features from libgphoto2.

Features

  • Camera
    • Capture images
    • Capture preview images
    • Download images
    • Get port information
    • Get abilities (model, driver stability, permissions, ...)
    • Read configuration
    • Set configuration
    • Interact with filesystem on camera
    • Camera events
    • Usb port information
  • Context
    • Autodetect camera
    • Get list of available cameras
    • Get camera by model and port

Gettings started

Installation

Run cargo add gphoto2 to add gphoto2 to your project or add this to your Cargo.toml:

[dependencies]
gphoto2 = "1"

Install libgphoto2

The libgphoto2 library must be installed on your system to use this library.

To install libgphoto2 on Debian based systems run:

sudo apt install libgphoto2-dev

On Arch systems run:

sudo pacman -S libgphoto2

On MacOS systems with Homebrew run:

homebrew install libgphoto2
Windows

There is no official way to install libgphoto2 on windows, but you can install it with MSYS2 (link to the package: mingw-w64-libgphoto2).

Basic Usage

This example takes a picture and saves it to disk

use gphoto2::Context;
use std::path::Path;

fn main() {
  // Everything starts from a context
  let context = Context::new().expect("Failed to create context");
  // From the context you can detect cameras
  let camera = context.autodetect_camera().expect("Failed to autodetect camera");

  // And take pictures
  let file_path = camera.capture_image().expect("Could not capture image");
  file_path
    .download(&camera, Path::new(&file_path.name().to_string()))
    .expect("Failed to download image");

  // For more advanced examples take a look at the examples/ foldeer
}

You can find more examples here

Stability

In general all all APIs should be stable, I've tested the ones my camera supported and found no bugs so far.
If you encounter an error like BAD_PARAMETERS or found a bug, please create an issue on GitHub.

License

Copyright © 2022 Maxicarlos08 [email protected]

This library uses the libgphoto2 library, which is licensed under the LGPL version 2.1.

Comments
  • Make some methods infallible

    Make some methods infallible

    While technically all functions in libgphoto2 return status code, a lot of them are simple getters that always return GP_OK unless you pass null pointer or such.

    As long as our bindings are correct, this should never happen in our Rust code, and if it does, it's an actual bug in our code and can be better represented by a panic.

    For most users, this should make consumption of such getters simpler.

    Additionally, various lists were converted from structs and Vecs into iterators, which allow users themselves to choose how to process them lazily.

    opened by RReverser 12
  • CameraFile::get_data is probably leaking memory

    CameraFile::get_data is probably leaking memory

    From comment docs on gp_file_get_data_and_size:

     * For regular CameraFiles, the pointer to data that is returned is
     * still owned by libgphoto2 and its lifetime is the same as the #file.
     *
     * For filedescriptor or handler based CameraFile types, the returned
     * data pointer is owned by the caller and needs to be free()d to avoid
     * memory leaks.
     *
     **/
    
    opened by RReverser 5
  • Context & the rest shouldn't have a lifetime

    Context & the rest shouldn't have a lifetime

    Right now, Context creates an unbounded lifetime (see Unbounded Lifetimes tied to whatever scope it was created in via Context::new. This is not very useful and doesn't provide any extra guarantees, since the pointers returned from libgphoto2 are heap-allocated anyway. As such, the lifetime from Context and most of other data structures that inherit the same lifetime, can be safely removed.

    @maxicarlos08 do you want to take this one?

    opened by RReverser 5
  • Fix file info bitmasks; make all file info lazy

    Fix file info bitmasks; make all file info lazy

    Like in #9, I noticed few more bitmasks - around file info - that were incorrectly bound as Rust enums in libgphoto2-sys, causing UB.

    While fixing it, I also decided to make all file info expose consistent lazy interface where fields are converted & returned in individual methods instead of entire structure at once.

    I've also wrapped the top-level FileInfo into a Box, since it's almost 300 bytes and can be expensive to keep & move around on stack.

    opened by RReverser 4
  • Widgets revamp

    Widgets revamp

    This adds typed variations of widgets, so that it's impossible to pass incompatible value to a widget set_value, or try to access children on non-grouping widget and so on.

    More specifically, this adds widget::{GroupWidget, TextWidget, RangeWidget, ToggleWidget, RadioWidget, ButtonWidget} types that each provides its own strongly typed API.

    All those types inherit from WidgetBase that also provides core properties such as id, name and so on that can be accessed on any of strongly widget types as well.

    There is also a Widget enum that is simply a container for arbitrary widget and can be matched against or converted into the specific widget type.

    Finally, top-level function config was updated to return GroupWidget and config_key has a generic param that allows to immediately specify which widget type you want (since in most cases, when user provides a hardcoded widget name, they likely know its type as well).

    This is fairly big change, but I think the ergonomics of statically typed widgets are worth it.

    opened by RReverser 4
  • Replace Inner and InnerPtr with AsRef/AsMut

    Replace Inner and InnerPtr with AsRef/AsMut

    This replaces custom traits for inner pointers with safe, lifetime-bound access, via standard traits AsRef and AsMut. Of course, the caller will still be forced to use unsafe for any FFI calls that operate on those pointers, but the access to references themselves is safe and becomes a bit more convenient via those traits.

    opened by RReverser 4
  • Hook up logging facilities

    Hook up logging facilities

    Hooks up libgphoto2's logging to Rust log crate, so that downstream users have easier time debugging various errors.

    Example:

    > RUST_LOG=gphoto2=error cargo run --example capture_preview
       Compiling gphoto2 v1.5.0 (/mnt/c/Users/me/Documents/gphoto2-rs)
        Finished dev [unoptimized + debuginfo] target(s) in 18.29s
         Running `target/debug/examples/capture_preview`
    [2022-09-24T14:23:07Z ERROR gphoto2::context] Sorry, your Nikon camera does not support LiveView mode
    Error: Unsupported operation
    
    opened by RReverser 3
  • Fix memory leak of widget tree

    Fix memory leak of widget tree

    gp_camera_get_{single_}config return "owned" root widgets (with refcount == 1), so doing gp_widget_ref on those meant the entire Widget tree would never get freed.

    opened by RReverser 3
  • Fix segfault in StorageInfo Drop

    Fix segfault in StorageInfo Drop

    Vec::from_raw_parts requires the input pointer to be allocated using Rust allocators (e.g. via Box or Vec), as it will attempt to free the result using Rust allocators as well.

    Previously, this code passed libc-allocated pointers as-is to Vec::from_raw_parts. When Rust allocator != libc allocator, e.g. on Windows, or if custom allocator is used via #[global_allocator], this caused heap corruption errors when Vec tried to deallocate itself during Drop phase:

    ...
            "Universal Serial Bus",
        ),
        path: Some(
            "usb:002,015",
        ),
        port_type: Some(
            Usb,
        ),
    }
    error: process didn't exit successfully: `target\debug\examples\camera_info.exe` (exit code: 0xc0000374, STATUS_HEAP_CORRUPTION)
    

    After this change, the original pointer will be always freed using libc::free and the error is gone.

    opened by RReverser 3
  • Lock a global mutext whenever libtool is called

    Lock a global mutext whenever libtool is called

    libgphoto2 uses libgphoto2 which is not thread safe, to fix I added a global Mutex which is locked whenever a libgphoto2 function is called that internally calls libtool.

    fixes #22

    cc @RReverser

    opened by maxicarlos08 2
  • Improve bitflags handling

    Improve bitflags handling

    • Mark bitflag enums as such at the libghoto2-sys level. They're not really enums in the Rust sense, and treating them as such might be UB due to trying to store values out of enum range (e.g. storing 1|2 = 3 in an enum that supports only {0,1,2}). Such designation makes bindgen generate structs instead, with associated constants and some convenient bit trait implementations.
    • Add bitflags! macro to gphoto2-rs that generates fn field(&self) -> bool helpers as well as From<...> and a readable Debug implementation.
    opened by RReverser 2
Releases(1.4.0)
  • 1.4.0(Sep 20, 2022)

    API changed:

    • InnerPtr/Inner are now AsRef/AsMut #8 (by @RReverser)
    • Some methods now return a String instead of Cow

    Bugs fixed:

    • Incorrect handling of bitfield enums #9 (by @RReverser)
    • C String stack-use-after-return #7
    • Incorrect usage of MaybeUninit #5 (by @RReverser)
    • Segfault in StorageInfo #4 (by @RReverser)
    Source code(tar.gz)
    Source code(zip)
  • 1.3.0(Aug 31, 2022)

    What's Changed

    • Add Windows support by @RReverser in https://github.com/maxicarlos08/gphoto2-rs/pull/2
    • Changed license to LGPL-v2.1 (#3)
    • Added Inner and InnerPtr traits which allow access to the inner libgphoto2 pointers (unsafe)

    New Contributors

    • @RReverser made their first contribution in https://github.com/maxicarlos08/gphoto2-rs/pull/2

    Full Changelog: https://github.com/maxicarlos08/gphoto2-rs/compare/1.2.0...1.3.0

    Source code(tar.gz)
    Source code(zip)
Owner
Maxicarlos08
"null"
Maxicarlos08
A Rust CLI tool that helps you enforce Git policies through Git hooks both server and client side

GitPolicyEnforcer This is a command line utility written in Rust, that helps you utilize Git hooks, to enforce various policies. It currently supports

Vagelis Prokopiou 4 Aug 14, 2022
git-cliff can generate changelog files from the Git history by utilizing conventional commits as well as regex-powered custom parsers.⛰️

git-cliff can generate changelog files from the Git history by utilizing conventional commits as well as regex-powered custom parsers. The changelog template can be customized with a configuration file to match the desired format.

Orhun Parmaksız 4.6k Sep 22, 2022
A git sub-command to view your git repository in the web browser

git-view A git sub-command to view your git repository in the web browser! About Are you also frustrated from moving your hands away from the keyboard

Hamothy 5 Jun 30, 2022
🌌⭐cosmo is a wrapper for Git essentially, allowing you to compress multiple commands into one

❯ Cosmo Git tooling of the future New feature: Cosmo hooks! Click here for more info! ❯ ?? Features Config files (with defaults!) Fast Easy to use Fri

Jack 1 Oct 31, 2021
A wrapper around the code action dump from https://mcdiamondfire.com.

DiamondFire Action Dump for Rust A wrapper around the code action dump from https://mcdiamondfire.com. This currently only provides schema types for u

null 3 Sep 17, 2022
Check the reproducibility status of your Arch Linux packages (read-only mirror)

arch-repro-status A CLI tool for querying the reproducibility status of the Arch Linux packages using data from a rebuilderd instance such as reproduc

Arch Linux 11 Jul 3, 2022
A library that creates a terminal-like window with feature-packed drawing of text and easy input handling. MIRROR.

BearLibTerminal provides a pseudoterminal window with a grid of character cells and a simple yet powerful API for flexible textual output and uncompli

Tommy Ettinger 43 Sep 10, 2022
By mirroring traffic to and from your machine, mirrord surrounds your local service with a mirror image of its cloud environment.

mirrord lets you easily mirror traffic from your Kubernetes cluster to your development environment. It comes as both Visual Studio Code extension and

MetalBear 1.6k Sep 19, 2022
Tiny Rust CLI to checkout a recent git branch interactively

git-select-branch Tiny Rust CLI to checkout a recent git branch interactively. Installation Homebrew brew tap dnjstrom/git-select-branch brew install

Daniel Ström 4 May 10, 2021
Cli tool for git productivity written in Rust and packaged for consumption via NPM

crust ?? cli tool for git productivity written in Rust and packaged for consumption via NPM This repo is identical with @skyneticist/golee in terms of

null 2 Jul 30, 2022
A tiny crate to make it easy to share and apply Git hooks for Rust projects

Shareable git hooks for Rust project. Sloughi is a friend of Husky from North Africa! :algeria:

Walid ZIOUCHE 23 May 10, 2022
A cat(1) clone with syntax highlighting and Git integration.

A cat(1) clone with syntax highlighting and Git integration. Key Features • How To Use • Installation • Customization • Project goals, alternatives [中

David Peter 37.2k Sep 24, 2022
A command-line tool and Docker image to automatically backup Git repositories from GitHub or anywhere

A command-line tool and Docker image to automatically backup Git repositories from GitHub or anywhere

Jake Wharton 254 Sep 22, 2022
Native cross-platform full feature terminal-based sequence editor for git interactive rebase.

Native cross-platform full feature terminal-based sequence editor for git interactive rebase.

Tim Oram 1.2k Sep 26, 2022
A syntax-highlighting pager for git, diff, and grep output

Get Started Install delta and add this to your ~/.gitconfig: [core] pager = delta [interactive] diffFilter = delta --color-only [delta]

Dan Davison 15.2k Sep 28, 2022
Lazygit - simple terminal UI for git commands

A simple terminal UI for git commands, written in Go with the gocui library. Rant time: You've heard it before, git is powerful, but what good is that

Jesse Duffield 29.9k Sep 23, 2022
Dura - You shouldn't ever lose your work if you're using Git

Dura Dura is a background process that watches your Git repositories and commits your uncommitted changes without impacting HEAD, the current branch,

Tim Kellogg 4k Sep 25, 2022
🧠 A command-line utility for switching git branches more easily. Switch branches interactively or use a fuzzy search to find that long-forgotten branch name.

git-smart-checkout A git command extension for switching git branches more efficiently. About Interactively switch branches or fuzzy search for that f

Cezar Craciun 50 Sep 21, 2022
Use Git installed in Bash on Windows/Windows Subsystem for Linux (WSL) from Windows and Visual Studio Code (VSCode)

WSLGit This project provides a small executable that forwards all arguments to git running inside Bash on Windows/Windows Subsystem for Linux (WSL). T

A. R. S. 1.1k Sep 13, 2022