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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Vector drawing of QR code using Cairo.
//! 
//! ## Examples
//!
//! ### PDF
//!
//! PDF example from the `examples/` directory:
//! ```rust
//! let surface = cairo::PdfSurface::new(100.0, 100.0, "example.pdf").unwrap();
//! let cr = cairo::Context::new(&surface);
//! qr2cairo::draw(&cr, 100.0, 100.0, "qr2cairo").unwrap();
//! cr.show_page();
//! ```
//! 
//! This generates this PDF: [example.pdf](https://www.willemp.be/qr2cairo/example.pdf).
//!
//! ### GTK 
//! 
//! GTK example (note: no GTK required to use qr2cairo):
//! 
//! ```sh
//! $ cd examples/gtk ; cargo run
//! ```
//! 
//! ![qr2cairo gtk example](https://www.willemp.be/qr2cairo/screenshot-qr2cairo-0.1.0-gtk.svg)
//! 
//! ### SVG
//! 
//! The underlying qrcode crate can
//! [create SVGs](https://docs.rs/qrcode/0.12.0/qrcode/render/svg/index.html).

extern crate qrcode;
use self::qrcode::types::Color::Dark as QrDark;
use self::qrcode::QrCode;
pub use qrcode::types::QrError;

/// Number of blocks that must be kept blank/light/white around the QR code.
const QUIET_ZONE: usize = 4;

/// Which color to draw the dark blocks of the QR code with.
///
/// Values are red, green, blue, alpha (i.e. opacity) from 0.0 to 1.0.
const LIGHT_COLOR_RGBA: (f64, f64, f64, f64) = (1.0, 1.0, 1.0, 1.0);

/// Which color to draw the light blocks of the QR code with.
const DARK_COLOR_RGBA: (f64, f64, f64, f64) = (0.0, 0.0, 0.0, 1.0);

/// Draw the given text as QR code to the given cairo context
///
/// # Arguments
///
/// * `cr`: what to draw on
/// * `width`: horizontal length in pixels of the draweable area
/// * `height`: vertical length in pixels of the draweable area
/// * `text`: what to draw as QR code
pub fn draw(cr: &cairo::Context, width: f64, height: f64, text: &str) -> Result<(), QrError> {
    Qr2Cairo::new(width, height, text)?.draw(cr);
    Ok(())
}

struct Qr2Cairo {
    width: f64,
    height: f64,
    qr_code: QrCode,
}

impl Qr2Cairo {
    pub fn new(width: f64, height: f64, text: &str) -> Result<Qr2Cairo, QrError> {
        let qr_code = QrCode::new(text)?;
        return Ok(Qr2Cairo {
            width,
            height,
            qr_code,
        });
    }

    /// Renders a QR code to the given cairo context `cr`.
    pub fn draw(&self, cr: &cairo::Context) {
        self.set_up_scaling(cr);
        self.draw_background(cr);
        self.draw_dark_boxes(cr);
    }

    /// Draw the dark part (i.e. not the background) of the QR code.
    fn draw_dark_boxes(&self, cr: &cairo::Context) {
        let vec = self.qr_code.to_colors();
        let (r, g, b, a) = DARK_COLOR_RGBA;
        cr.set_source_rgba(r, g, b, a);
        for row in 0..self.width_in_blocks_without_quiet() {
            for col in 0..self.width_in_blocks_without_quiet() {
                let vec_pos = row * self.width_in_blocks_without_quiet() + col;
                if vec[vec_pos] == QrDark {
                    cr.rectangle(
                        (QUIET_ZONE + col) as f64,
                        (QUIET_ZONE + row) as f64,
                        1.0,
                        1.0,
                    );
                }
            }
        }
        cr.fill();
    }

    /// Set up scaling and resizing such that we can draw with units of 1.0
    ///
    /// After this function, a distance of 1.0 in cairo will be one block of the QR code.
    fn set_up_scaling(&self, cr: &cairo::Context) {
        let drawingsize = f64::min(self.width, self.height);
        let px_per_block = drawingsize / (self.width_in_blocks() as f64);
        let move_x = f64::max(0.0, self.width - drawingsize) / 2.0;
        let move_y = f64::max(0.0, self.height - drawingsize) / 2.0;
        cr.translate(move_x, move_y);
        cr.scale(px_per_block, px_per_block);
    }

    /// Draw light background.
    ///
    /// Only draw light background only under the qr code (not the entire space) to not blind users
    /// with dark theme.
    fn draw_background(&self, cr: &cairo::Context) {
        let (r, g, b, a) = LIGHT_COLOR_RGBA;
        cr.set_source_rgba(r, g, b, a);
        cr.rectangle(
            0.0,
            0.0,
            self.width_in_blocks() as f64,
            self.width_in_blocks() as f64,
        );
        cr.fill();
    }

    /// How many blocks of the QR code, is the QR code wide (and tall), excluding quiet zone.
    fn width_in_blocks_without_quiet(&self) -> usize {
        self.qr_code.width()
    }

    /// How many blocks of the QR code, is the QR code wide (and tall), including quiet zone.
    fn width_in_blocks(&self) -> usize {
        self.width_in_blocks_without_quiet() + QUIET_ZONE * 2
    }
}