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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// // https://github.com/sayanarijit/qrscan/blob/main/Cargo.toml
//
// use anyhow::Result;
// use clap::Parser;
// use csscolorparser::Color;
// use image::codecs::jpeg::JpegEncoder;
// use image::codecs::png::PngEncoder;
// use image::io::Reader as ImageReader;
// use image::ColorType;
// use image::DynamicImage;
// use image::EncodableLayout;
// use image::ImageBuffer;
// use image::ImageEncoder;
// use image::Rgba;
// use nokhwa::pixel_format::{RgbAFormat, RgbFormat};
// use nokhwa::utils::{CameraFormat, CameraIndex, FrameFormat};
// use nokhwa::utils::RequestedFormat;
// use nokhwa::utils::RequestedFormatType;
// use nokhwa::Camera;
// use qrencode::render::svg;
// use qrencode::render::unicode::Dense1x2;
// use qrencode::render::unicode::Dense1x2::Dark;
// use qrencode::render::unicode::Dense1x2::Light;
// use qrencode::QrCode;
// use std::io::Cursor;
// use std::io::Read;
// use std::io::Write;
// use std::path::PathBuf;
// use std::time::Duration;
//
// static PROGRESS: &[&str] = &[" ", ". ", ".. ", "..."];
//
// #[derive(Parser, Debug)]
// #[clap(author, version, about)]
// struct Args {
// /// Path to the image to scan. If not specified, the system camera will be used
// ///
// /// Examples:
// ///
// /// qrscan /path/to/input.png
// ///
// /// cat /path/to/input.png | qrscan -
// #[clap(value_parser)]
// image: Option<PathBuf>,
//
// /// Preview the camera on the terminal (if compatible)
// #[clap(long, short)]
// preview: bool,
//
// /// Preview display's x coordinate (works with --preview)
// #[clap(long, default_value = "0")]
// preview_x: u16,
//
// /// Preview diaplay's y coordinate (works with --preview)
// #[clap(long, default_value = "0")]
// preview_y: i16,
//
// /// Preview width (works with --preview)
// #[clap(long)]
// preview_w: Option<u32>,
//
// /// Preview height (works with --preview)
// #[clap(long)]
// preview_h: Option<u32>,
//
// /// Print metadata
// #[clap(long, short)]
// metadata: bool,
//
// /// Print the QR code
// #[clap(long)]
// qr: bool,
//
// /// Do not print the content
// #[clap(long, short)]
// no_content: bool,
//
// /// Interval between scans in milisecond
// #[clap(long, short, default_value = "200")]
// inverval: u64,
//
// /// Invert the QR code colors
// #[clap(long)]
// invert_colors: bool,
//
// /// Specify the QR code foreground color (when exporting image)
// #[clap(long, default_value = "#000")]
// fg: String,
//
// /// Specify the QR code background color (when exporting image)
// #[clap(long, default_value = "#fff")]
// bg: String,
//
// /// Do not add quiet zone to the QR code
// #[clap(long)]
// no_quiet_zone: bool,
//
// /// Export the QR code as ascii text to the given path
// #[clap(long)]
// ascii: Option<PathBuf>,
//
// /// Export the QR code as svg image to the given path
// #[clap(long)]
// svg: Option<PathBuf>,
//
// /// Export the QR code as png image to the given path
// #[clap(long)]
// png: Option<PathBuf>,
//
// /// Export the QR code as jpeg image to the given path
// #[clap(long)]
// jpeg: Option<PathBuf>,
// }
//
// fn capture(args: &Args) -> Result<()> {
// let index = CameraIndex::Index(0);
// // let format = CameraFormat::new_from(640, 480, FrameFormat::YUYV, 30);
// let formattyp = RequestedFormatType::None;
// let requested = RequestedFormat::new::<RgbFormat>(formattyp);
//
// let mut camera = Camera::new(index, requested)?;
// let mut spinner = 0;
//
// let preview = viuer::Config {
// x: args.preview_x,
// y: args.preview_y,
// restore_cursor: false,
// transparent: false,
// absolute_offset: true,
// width: args.preview_w,
// height: args.preview_h,
// ..Default::default()
// };
//
// camera.open_stream()?;
//
// loop {
// let frame = camera.frame()?;
// let image = frame.decode_image::<RgbFormat>()?;
// let image = DynamicImage::ImageRgb8(image);
//
// if print_image(args, &image).is_err() {
// if args.preview {
// viuer::print(&image.fliph(), &preview)?;
// } else {
// eprint!("\rScanning via camera{}", PROGRESS[spinner]);
// spinner = (spinner + 1) % 4;
// };
// } else {
// break;
// }
// }
//
// Ok(())
// }
// pub fn capture_image() -> Result<DynamicImage> {
// let index = CameraIndex::Index(0);
// // let format = CameraFormat::new_from(640, 480, FrameFormat::YUYV, 30);
// // let formattyp = RequestedFormatType::None;
// let formattyp = RequestedFormatType::Exact(
// CameraFormat::new_from(1920, 1080, FrameFormat::NV12, 15)
// );
// let requested = RequestedFormat::new::<RgbFormat>(formattyp);
//
// let mut camera = Camera::new(index, requested).expect("make camera");
// let mut spinner = 0;
//
// let preview = viuer::Config {
// x: 0,
// y: 0,
// restore_cursor: false,
// transparent: false,
// absolute_offset: true,
// width: Some(1920),
// height: Some(1080),
// ..Default::default()
// };
//
// camera.open_stream().expect("open stream");
//
// // loop {
// let frame = camera.frame().expect("open frame");
// let image = frame.decode_image::<RgbFormat>()?;
// let image = DynamicImage::ImageRgb8(image);
// //
// // if print_image(args, &image).is_err() {
// // if args.preview {
// // viuer::print(&image.fliph(), &preview)?;
// // } else {
// // eprint!("\rScanning via camera{}", PROGRESS[spinner]);
// // spinner = (spinner + 1) % 4;
// // };
// // } else {
// // break;
// // }
// // }
//
// // Ok(())
// Ok(image)
// }
//
// #[ignore]
// pub fn test_capture() {
// // debug_capture()
// }
//
// fn scan_stdin(args: &Args) -> Result<()> {
// let mut buf = vec![];
// let mut stdin = std::io::stdin().lock();
// stdin.read_to_end(&mut buf)?;
//
// let image = ImageReader::new(Cursor::new(buf))
// .with_guessed_format()?
// .decode()?;
//
// print_image(args, &image)
// }
//
// fn scan_file(args: &Args, path: &PathBuf) -> Result<()> {
// let image = ImageReader::open(path)?.decode()?;
// print_image(args, &image)
// }
//
//
//
// fn print_image(args: &Args, image: &DynamicImage) -> Result<()> {
// let image = image.to_luma8();
// let mut img = rqrr::PreparedImage::prepare(image);
// let grids = img.detect_grids();
//
// if let Some(grid) = grids.first() {
// let (meta, content) = grid.decode()?;
// eprint!("\r \r");
//
// // Ansi
// if args.qr {
// if args.preview {
// println!();
// }
//
// let (dark, light) = if args.invert_colors {
// (Dark, Light)
// } else {
// (Light, Dark)
// };
//
// let image = QrCode::new(&content)?
// .render::<Dense1x2>()
// .dark_color(dark)
// .light_color(light)
// .quiet_zone(!args.no_quiet_zone)
// .build();
//
// println!("{image}");
// }
//
// // Metadata
// if args.metadata {
// if args.preview || args.qr {
// println!()
// };
//
// println!("Version: {}", meta.version.0);
// println!("Grid Size: {}", meta.version.to_size());
// println!("EC Level: {}", meta.ecc_level);
// println!("Mask: {}", meta.mask);
// }
//
// // Content
// if !args.no_content {
// if args.preview || args.qr || args.metadata {
// println!();
// };
// println!("{content}");
// }
//
// // Output image colors
// let (dark, light) = if args.invert_colors {
// (&args.bg, &args.fg)
// } else {
// (&args.fg, &args.bg)
// };
//
// // SVG
// if let Some(path) = args.svg.as_ref() {
// let image = QrCode::new(&content)?
// .render()
// .dark_color(svg::Color(dark))
// .light_color(svg::Color(light))
// .quiet_zone(!args.no_quiet_zone)
// .build()
// .into_bytes();
//
// if path.to_str() == Some("-") {
// std::io::stdout().write_all(&image)?;
// } else {
// std::fs::write(path, &image)?
// }
// }
//
// // Ascii
// if let Some(path) = args.ascii.as_ref() {
// let image = QrCode::new(&content)?
// .render::<char>()
// .module_dimensions(2, 1)
// .quiet_zone(!args.no_quiet_zone)
// .build()
// .into_bytes();
//
// if path.to_str() == Some("-") {
// std::io::stdout().write_all(&image)?;
// } else {
// std::fs::write(path, &image)?
// }
// }
//
// // RGB colors
// let dark = dark.parse::<Color>()?.to_linear_rgba_u8();
// let light = light.parse::<Color>()?.to_linear_rgba_u8();
//
// // PNG
// if let Some(path) = args.png.as_ref() {
// let image = build_binary_image(&content, dark, light, !args.no_quiet_zone)?;
// let bytes = image.as_bytes();
//
// let mut result: Vec<u8> = Default::default();
// let encoder = PngEncoder::new(&mut result);
// encoder.write_image(
// bytes,
// image.width(),
// image.height(),
// ColorType::Rgba8,
// )?;
//
// if path.to_str() == Some("-") {
// std::io::stdout().write_all(&result)?;
// } else {
// std::fs::write(path, result)?
// }
// }
//
// // JPEG
// if let Some(path) = args.jpeg.as_ref() {
// let image = build_binary_image(&content, dark, light, !args.no_quiet_zone)?;
// let bytes = image.as_bytes();
//
// let mut result: Vec<u8> = Default::default();
// let mut encoder = JpegEncoder::new(&mut result);
// encoder.encode(bytes, image.width(), image.height(), ColorType::Rgba8)?;
//
// if path.to_str() == Some("-") {
// std::io::stdout().write_all(&result)?;
// } else {
// std::fs::write(path, result)?
// }
// }
// } else {
// std::thread::sleep(Duration::from_millis(args.inverval));
// anyhow::bail!("failed to read")
// };
//
// Ok(())
// }
//
// fn main() {
// let args = Args::parse();
// let mut rc = 0;
//
// if let Some(path) = args.image.as_ref() {
// if path.to_str() == Some("-") {
// if let Err(err) = scan_stdin(&args) {
// eprintln!("error: qrscan: {err}");
// rc = 1;
// }
// } else if !path.exists() {
// eprintln!("error: qrscan: {}: No such file", path.display());
// rc = 3;
// } else if path.is_dir() {
// eprintln!(
// "error: qrscan: cannot scan {}: Is a directory",
// path.display()
// );
// rc = 2;
// } else if let Err(err) = scan_file(&args, path) {
// eprintln!("error: qrscan: {err}");
// rc = 1;
// }
// } else if let Err(err) = capture(&args) {
// eprintln!("error: qrscan: {err}");
// rc = 1;
// }
//
// std::process::exit(rc);
// }
// //
// // #[cfg(test)]
// // mod tests {
// // use std::path::PathBuf;
// //
// // use assert_cmd::prelude::OutputOkExt;
// //
// // fn qrscan() -> assert_cmd::Command {
// // assert_cmd::Command::cargo_bin("qrscan").unwrap()
// // }
// //
// // pub struct TestFile {
// // pub path: PathBuf,
// // }
// //
// // impl TestFile {
// // pub fn new(id: &str, ext: &str) -> Self {
// // let path = PathBuf::from(format!("test_{id}.{}", ext));
// // let header = format!("Accept: image/{}", ext);
// // let data = format!("foo {}", ext);
// //
// // std::process::Command::new("curl")
// // .arg("https://qrcode.show")
// // .arg("-k")
// // .arg("-H")
// // .arg(&header)
// // .arg("-d")
// // .arg(&data)
// // .arg("-o")
// // .arg(&path)
// // .unwrap();
// //
// // Self { path }
// // }
// // }
// //
// // impl Drop for TestFile {
// // fn drop(&mut self) {
// // std::fs::remove_file(&self.path).unwrap();
// // }
// // }
// //
// // #[test]
// // fn test_help() {
// // qrscan().arg("-h").assert().success();
// // qrscan().arg("--help").assert().success();
// // }
// //
// // #[test]
// // fn test_scan_jpeg_file() {
// // let file = TestFile::new("scan_jpeg_file", "jpeg");
// // qrscan()
// // .arg(&file.path)
// // .assert()
// // .success()
// // .stdout("foo jpeg\n");
// // }
// //
// // #[test]
// // fn test_scan_png_file() {
// // let file = TestFile::new("scan_png_file", "png");
// // qrscan()
// // .arg(&file.path)
// // .assert()
// // .success()
// // .stdout("foo png\n");
// // }
// //
// // #[test]
// // fn test_scan_from_stdin() {
// // let file = TestFile::new("scan_from_stdin", "png");
// // qrscan()
// // .arg("-")
// // .pipe_stdin(&file.path)
// // .unwrap()
// // .assert()
// // .success()
// // .stdout("foo png\n");
// // }
// //
// // #[test]
// // fn test_scan_no_content() {
// // let file = TestFile::new("scan_no_content", "png");
// // qrscan()
// // .arg(&file.path)
// // .arg("-n")
// // .assert()
// // .success()
// // .stdout("");
// //
// // qrscan()
// // .arg(&file.path)
// // .arg("--no-content")
// // .assert()
// // .success()
// // .stdout("");
// // }
// //
// // #[test]
// // fn test_export_files() {
// // let file = TestFile::new("export_files", "png");
// // qrscan()
// // .arg(&file.path)
// // .arg("--ascii")
// // .arg("test.ascii")
// // .arg("--svg")
// // .arg("test.svg")
// // .arg("--jpeg")
// // .arg("test.jpeg")
// // .arg("--png")
// // .arg("test.png")
// // .assert()
// // .success()
// // .stdout("foo png\n");
// //
// // assert!(PathBuf::from("test.ascii").exists());
// // assert!(PathBuf::from("test.svg").exists());
// // assert!(PathBuf::from("test.jpeg").exists());
// // assert!(PathBuf::from("test.png").exists());
// //
// // std::fs::remove_file("test.ascii").unwrap();
// // std::fs::remove_file("test.svg").unwrap();
// // std::fs::remove_file("test.jpeg").unwrap();
// // std::fs::remove_file("test.png").unwrap();
// // }
// //
// // #[test]
// // fn test_err_1() {
// // qrscan().arg("-").assert().failure().code(1);
// // }
// //
// // #[test]
// // fn test_err_2() {
// // qrscan().arg("/tmp").assert().failure().code(2);
// // }
// //
// // #[test]
// // fn test_err_3() {
// // qrscan()
// // .arg("/foo/bar/doesntexists")
// // .assert()
// // .failure()
// // .code(3);
// // }
// // }