-
Notifications
You must be signed in to change notification settings - Fork 14
/
util.rs
329 lines (276 loc) · 8.84 KB
/
util.rs
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
//! Rust PTouch Command Line Utility
//
// https://github.com/ryankurte/rust-ptouch
// Copyright 2021 Ryan Kurte
use log::{debug, info, warn};
use simplelog::{LevelFilter, TermLogger, TerminalMode, ColorChoice};
use structopt::StructOpt;
use strum::VariantNames;
use ptouch::{Options, PTouch, render::RenderTemplate};
use ptouch::device::{Media, PrintInfo, Status};
use ptouch::render::{FontKind, Op, Render, RenderConfig};
#[derive(Clone, Debug, PartialEq, StructOpt)]
pub struct Flags {
#[structopt(flatten)]
options: Options,
#[structopt(subcommand)]
command: Command,
#[structopt(long, default_value="16")]
/// Padding for start and end of renders
pad: usize,
#[structopt(long, possible_values = &Media::VARIANTS, default_value="tze12mm")]
/// Default media kind when unable to query this from printer
media: Media,
#[structopt(long, default_value = "info")]
log_level: LevelFilter,
}
#[derive(Clone, Debug, PartialEq, StructOpt)]
pub enum RenderCommand {
/// Basic text rendering
Text {
/// Text value
text: String,
#[structopt(long, possible_values = &FontKind::VARIANTS, default_value="12x16")]
/// Text font
font: FontKind,
},
/// QR Code with text
QrText {
/// QR value
qr: String,
/// Text value
text: String,
#[structopt(long, possible_values = &FontKind::VARIANTS, default_value="12x16")]
/// Text font
font: FontKind,
},
/// QR Code
Qr {
/// QR value
qr: String,
},
/// Barcode (EXPERIMENTAL)
Barcode {
/// Barcode value
code: String,
},
/// Render from template
Template{
/// Template file
file: String,
},
/// Render from image
Image{
/// Image file
file: String,
},
/// Render example
Example,
}
#[derive(Clone, Debug, PartialEq, StructOpt)]
pub enum Command {
// Fetch printer info
Info,
// Fetch printer status
Status,
// Render and display a preview
Preview(RenderCommand),
// Render to an image file
Render{
#[structopt(long)]
/// Image file to save render output
file: String,
#[structopt(subcommand)]
cmd: RenderCommand,
},
// Print data!
Print(RenderCommand),
}
fn main() -> anyhow::Result<()> {
// Parse CLI options
let opts = Flags::from_args();
// Setup logging
TermLogger::init(
opts.log_level,
simplelog::Config::default(),
TerminalMode::Mixed,
ColorChoice::Auto,
)
.unwrap();
// Create default render configuration
let mut rc = RenderConfig{
y: opts.media.area().1 as usize,
..Default::default()
};
debug!("Connecting to PTouch device: {:?}", opts.options);
// Attempt to connect to ptouch device to inform configuration
let connect = match PTouch::new(&opts.options) {
Ok(mut pt) => {
let status;
if opts.options.no_status_fetch {
info!("Connected! status request disabled, using default status...");
// Getting default status
status = Status::new(&opts.media)?;
info!("Device status (default one used): {:?}", status);
} else {
info!("Connected! fetching status...");
// Fetch device status
status = pt.status()?;
info!("Device status (fetched from device): {:?}", status);
}
// Build MediaWidth from status message to retrieve offsets
let media = Media::from((status.media_kind, status.media_width));
// Update render config to reflect tape
rc.y = media.area().1 as usize;
// TODO: update colours too?
// Return device and mediat width
Ok((pt, status, media))
},
Err(e) => Err(e),
};
// TODO: allow RenderConfig override from CLI
// Run commands that do not _require_ the printer
match &opts.command {
#[cfg(feature = "preview")]
Command::Preview(cmd) => {
// Inform user if print boundaries are unset
if connect.is_err() {
warn!("Using default media: {}, override with `--media` argument", opts.media);
}
// Load render operations from command
let ops = cmd.load(opts.pad)?;
// Create renderer
let mut r = Render::new(rc);
// Apply render operations
r.render(&ops)?;
// Display render output
r.show()?;
return Ok(());
},
#[cfg(not(feature = "preview"))]
Command::Preview(_cmd) => {
warn!("Preview not enabled (or not supported on this platform");
warn!("Try `render` command to render to image files");
return Ok(())
}
Command::Render{ file, cmd } => {
// Inform user if print boundaries are unset
if connect.is_err() {
warn!("Using default media: {}, override with `--media` argument", opts.media);
}
// Load render operations from command
let ops = cmd.load(opts.pad)?;
// Create renderer
let mut r = Render::new(rc);
// Apply render operations
r.render(&ops)?;
// Display render output
r.save(file)?;
return Ok(());
},
_ => (),
}
// Check PTouch connection was successful
let (mut ptouch, status, media) = match connect {
Ok(d) => d,
Err(e) => {
return Err(anyhow::anyhow!("Error connecting to PTouch: {:?}", e));
}
};
// Run commands that -do- require the printer
match &opts.command {
Command::Info => {
let i = ptouch.info()?;
println!("Info: {:?}", i);
},
Command::Status => {
println!("Status: {:?}", status);
},
Command::Print(cmd) => {
// Load render operations from command
let ops = cmd.load(opts.pad)?;
// Create renderer
let mut r = Render::new(rc);
// Apply render operations
r.render(&ops)?;
// Generate raster data for printing
let data = r.raster(media.area())?;
// Setup print info based on media and rastered data
let info = PrintInfo {
width: Some(status.media_width),
length: Some(0),
raster_no: data.len() as u32,
..Default::default()
};
// Print the thing!
ptouch.print_raw(data, &info)?;
},
_ => (),
}
// TODO: close the printer?
Ok(())
}
impl RenderCommand {
pub fn load(&self, pad: usize) -> Result<Vec<Op>, anyhow::Error> {
match self {
RenderCommand::Text { text, font } => {
let ops = vec![
Op::pad(pad),
Op::text_with_font(text, *font),
Op::pad(pad),
];
Ok(ops)
},
RenderCommand::QrText { qr, text, font } => {
let ops = vec![
Op::pad(pad),
Op::qr(qr),
Op::text_with_font(text, *font),
Op::pad(pad)
];
Ok(ops)
},
RenderCommand::Qr { qr } => {
let ops = vec![
Op::pad(pad),
Op::qr(qr),
Op::pad(pad)
];
Ok(ops)
},
RenderCommand::Barcode { code } => {
let ops = vec![
Op::pad(pad),
Op::barcode(code),
Op::pad(pad)
];
Ok(ops)
},
RenderCommand::Template { file } => {
// Read template file
let t = std::fs::read_to_string(file)?;
// Parse to render ops
let c: RenderTemplate = toml::from_str(&t)?;
// Return render operations
Ok(c.ops)
},
RenderCommand::Image { file } => {
let ops = vec![
Op::pad(pad),
Op::image(file),
Op::pad(pad)
];
Ok(ops)
}
RenderCommand::Example => {
let ops = vec![
Op::pad(pad),
Op::qr("https://hello.world"),
Op::text("hello world,,\nhow's it going?"),
Op::pad(pad)
];
Ok(ops)
}
}
}
}