use crate::charset::InternationalCharset;
use crate::codepage::CodePage;
use crate::command::{
Alignment, BarcodeData, BarcodeSystem, Command, CutMode, DrawerPin, FontFamily,
HeatingParameters, ImageData, PrintDensity, QrCorrectionLevel, QrData, UnderlineMode,
};
use crate::layout::column::{
PaperWidth, TableColumn, format_table_row, format_three_column, format_two_column,
};
use crate::tax::ZatcaInvoice;
#[derive(Debug, Clone, PartialEq)]
pub struct Receipt {
paper_width: PaperWidth,
commands: Vec<Command>,
active_columns: Option<Vec<TableColumn>>,
}
impl Default for Receipt {
fn default() -> Self {
Self::new(PaperWidth::Mm80)
}
}
impl Receipt {
#[must_use]
pub fn new(paper_width: PaperWidth) -> Self {
Self {
paper_width,
commands: Vec::with_capacity(32),
active_columns: None,
}
}
#[must_use]
pub const fn paper_width(&self) -> PaperWidth {
self.paper_width
}
#[must_use]
pub const fn columns(&self) -> usize {
self.paper_width.columns()
}
#[must_use]
pub fn commands(&self) -> &[Command] {
&self.commands
}
#[must_use]
pub fn into_commands(self) -> Vec<Command> {
self.commands
}
#[must_use]
pub fn init(mut self) -> Self {
self.commands.push(Command::Init);
self
}
#[must_use]
pub fn text(mut self, text: impl Into<String>) -> Self {
self.commands.push(Command::Text(text.into()));
self
}
#[must_use]
pub fn text_ln(mut self, text: impl Into<String>) -> Self {
let mut s = text.into();
s.push('\n');
self.commands.push(Command::Text(s));
self
}
#[must_use]
pub fn feed(mut self, lines: u8) -> Self {
self.commands.push(Command::Feed(lines));
self
}
#[must_use]
pub fn feed_ln(self) -> Self {
self.feed(1)
}
#[must_use]
pub fn align(mut self, alignment: Alignment) -> Self {
self.commands.push(Command::Align(alignment));
self
}
#[must_use]
pub fn left(self) -> Self {
self.align(Alignment::Left)
}
#[must_use]
pub fn center(self) -> Self {
self.align(Alignment::Center)
}
#[must_use]
pub fn right(self) -> Self {
self.align(Alignment::Right)
}
#[must_use]
pub fn bold(mut self, enable: bool) -> Self {
self.commands.push(Command::Bold(enable));
self
}
#[must_use]
pub fn underline(mut self, mode: UnderlineMode) -> Self {
self.commands.push(Command::Underline(mode));
self
}
#[must_use]
pub fn underline_on(self) -> Self {
self.underline(UnderlineMode::Single)
}
#[must_use]
pub fn underline_off(self) -> Self {
self.underline(UnderlineMode::Off)
}
#[must_use]
pub fn invert(mut self, enable: bool) -> Self {
self.commands.push(Command::Invert(enable));
self
}
#[must_use]
pub fn double_height(mut self, enable: bool) -> Self {
self.commands.push(Command::DoubleHeight(enable));
self
}
#[must_use]
pub fn double_width(mut self, enable: bool) -> Self {
self.commands.push(Command::DoubleWidth(enable));
self
}
#[must_use]
pub fn double_size(self, enable: bool) -> Self {
self.double_height(enable).double_width(enable)
}
#[must_use]
pub fn font(mut self, font: FontFamily) -> Self {
self.commands.push(Command::Font(font));
self
}
#[must_use]
pub fn divider(self, ch: char) -> Self {
let cols = self.columns();
let rule: String = std::iter::repeat_n(ch, cols).collect();
self.text_ln(rule)
}
#[must_use]
pub fn divider_double(self) -> Self {
self.divider('=')
}
#[must_use]
pub fn divider_dotted(self) -> Self {
self.divider('.')
}
#[must_use]
pub fn divider_dashed(self) -> Self {
self.divider_pattern("- ")
}
#[must_use]
pub fn divider_pattern(self, pattern: &str) -> Self {
if pattern.is_empty() {
return self;
}
let cols = self.columns();
let pat_width = crate::layout::column::str_display_width(pattern);
if pat_width == 0 {
return self;
}
let mut result = String::with_capacity(cols + pattern.len());
while crate::layout::column::str_display_width(&result) + pat_width <= cols {
result.push_str(pattern);
}
let cur_w = crate::layout::column::str_display_width(&result);
if cur_w < cols {
result.push_str(&" ".repeat(cols - cur_w));
}
self.text_ln(result)
}
#[must_use]
pub fn two_column(self, left: impl AsRef<str>, right: impl AsRef<str>) -> Self {
let cols = self.columns();
let formatted = format_two_column(left.as_ref(), right.as_ref(), cols);
self.text_ln(formatted)
}
#[must_use]
pub fn three_column(
self,
left: impl AsRef<str>,
center: impl AsRef<str>,
right: impl AsRef<str>,
) -> Self {
let cols = self.columns();
let formatted = format_three_column(left.as_ref(), center.as_ref(), right.as_ref(), cols);
self.text_ln(formatted)
}
#[must_use]
pub fn table_row<S: AsRef<str>>(mut self, cells: &[S], columns: &[TableColumn]) -> Self {
let str_cells: Vec<&str> = cells.iter().map(|s| s.as_ref()).collect();
let lines = format_table_row(&str_cells, columns, self.columns());
for line in lines {
self = self.text_ln(line);
}
self
}
#[must_use]
pub fn table<S: AsRef<str>>(mut self, columns: &[TableColumn], rows: &[&[S]]) -> Self {
for row in rows {
self = self.table_row(row, columns);
}
self
}
#[must_use]
pub fn set_columns(mut self, columns: &[TableColumn]) -> Self {
self.active_columns = Some(columns.to_vec());
self
}
#[must_use]
pub fn table_header<S: AsRef<str>>(mut self, headers: &[S], columns: &[TableColumn]) -> Self {
self.active_columns = Some(columns.to_vec());
self = self.bold(true).table_row(headers, columns).bold(false);
self
}
#[must_use]
pub fn header<S: AsRef<str>>(mut self, headers: &[S]) -> Self {
self = self.bold(true).row(headers).bold(false);
self
}
#[must_use]
pub fn active_columns(&self) -> Option<&[TableColumn]> {
self.active_columns.as_deref()
}
#[must_use]
pub fn clear_columns(mut self) -> Self {
self.active_columns = None;
self
}
#[must_use]
pub fn row<S: AsRef<str>>(mut self, cells: &[S]) -> Self {
if let Some(ref cols) = self.active_columns {
let str_cells: Vec<&str> = cells.iter().map(|s| s.as_ref()).collect();
let lines = format_table_row(&str_cells, cols, self.columns());
for line in lines {
self = self.text_ln(line);
}
self
} else {
let joined = cells
.iter()
.map(|s| s.as_ref())
.collect::<Vec<_>>()
.join(" ");
self.text_ln(joined)
}
}
#[must_use]
pub fn barcode(mut self, barcode: BarcodeData) -> Self {
self.commands.push(Command::Barcode(barcode));
self
}
#[must_use]
pub fn barcode_128(self, data: impl Into<String>) -> Self {
self.barcode(BarcodeData {
system: BarcodeSystem::Code128,
data: data.into(),
width: 2,
height: 64,
})
}
#[must_use]
pub fn qr_code(mut self, qr: QrData) -> Self {
self.commands.push(Command::QrCode(qr));
self
}
#[must_use]
pub fn qr(self, data: impl Into<String>) -> Self {
self.qr_code(QrData {
data: data.into(),
model: 2,
cell_size: 4,
correction: QrCorrectionLevel::M,
})
}
#[must_use]
pub fn zatca_qr(self, invoice: &ZatcaInvoice) -> Self {
let payload = invoice.to_qr_base64();
self.qr(payload)
}
#[must_use]
pub fn image(mut self, image: ImageData) -> Self {
self.commands.push(Command::Image(image));
self
}
#[cfg(feature = "image")]
pub fn image_from_path(self, path: impl AsRef<std::path::Path>) -> crate::error::Result<Self> {
let max_w = self.paper_width.dots();
self.image_from_path_with_options(
path,
Some(max_w),
crate::image::DitherMode::FloydSteinberg,
)
}
#[cfg(feature = "image")]
pub fn image_from_path_with_options(
self,
path: impl AsRef<std::path::Path>,
max_width: Option<u32>,
mode: crate::image::DitherMode,
) -> crate::error::Result<Self> {
let img = ImageData::from_path(path, max_width, mode)?;
Ok(self.image(img))
}
#[cfg(feature = "image")]
pub fn image_from_bytes(self, bytes: &[u8]) -> crate::error::Result<Self> {
let max_w = self.paper_width.dots();
self.image_from_bytes_with_options(
bytes,
Some(max_w),
crate::image::DitherMode::FloydSteinberg,
)
}
#[cfg(feature = "image")]
pub fn image_from_bytes_with_options(
self,
bytes: &[u8],
max_width: Option<u32>,
mode: crate::image::DitherMode,
) -> crate::error::Result<Self> {
let img = ImageData::from_bytes(bytes, max_width, mode)?;
Ok(self.image(img))
}
#[must_use]
pub fn cut(mut self, mode: CutMode) -> Self {
self.commands.push(Command::Cut(mode));
self
}
#[must_use]
pub fn cut_full(self) -> Self {
self.cut(CutMode::Full)
}
#[must_use]
pub fn cut_partial(self) -> Self {
self.cut(CutMode::Partial)
}
#[must_use]
pub fn drawer_kick(mut self, pin: DrawerPin) -> Self {
self.commands.push(Command::DrawerKick(pin));
self
}
#[must_use]
pub fn open_drawer(self) -> Self {
self.drawer_kick(DrawerPin::Pin2)
}
#[must_use]
pub fn beep(mut self, count: u8, duration: u8) -> Self {
self.commands.push(Command::Beep { count, duration });
self
}
#[must_use]
pub fn line_spacing(mut self, spacing: Option<u8>) -> Self {
self.commands.push(Command::LineSpacing(spacing));
self
}
#[must_use]
pub fn default_line_spacing(self) -> Self {
self.line_spacing(None)
}
#[must_use]
pub fn upside_down(mut self, enable: bool) -> Self {
self.commands.push(Command::UpsideDown(enable));
self
}
#[must_use]
pub fn code_page(mut self, page: impl Into<CodePage>) -> Self {
self.commands.push(Command::CodePage(page.into()));
self
}
#[must_use]
pub fn international_charset(mut self, charset: impl Into<InternationalCharset>) -> Self {
self.commands
.push(Command::InternationalCharset(charset.into()));
self
}
#[must_use]
pub fn charset_usa(self) -> Self {
self.international_charset(InternationalCharset::Usa)
}
#[must_use]
pub fn charset_uk(self) -> Self {
self.international_charset(InternationalCharset::Uk)
}
#[must_use]
pub fn charset_france(self) -> Self {
self.international_charset(InternationalCharset::France)
}
#[must_use]
pub fn charset_germany(self) -> Self {
self.international_charset(InternationalCharset::Germany)
}
#[must_use]
pub fn charset_spain(self) -> Self {
self.international_charset(InternationalCharset::SpainI)
}
#[must_use]
pub fn charset_italy(self) -> Self {
self.international_charset(InternationalCharset::Italy)
}
#[must_use]
pub fn charset_japan(self) -> Self {
self.international_charset(InternationalCharset::Japan)
}
#[must_use]
pub fn charset_arabia(self) -> Self {
self.international_charset(InternationalCharset::Arabia)
}
#[must_use]
pub fn print_density(mut self, density: PrintDensity) -> Self {
self.commands.push(Command::PrintDensity(density));
self
}
#[must_use]
pub fn density_light(self) -> Self {
self.print_density(PrintDensity::Light)
}
#[must_use]
pub fn density_normal(self) -> Self {
self.print_density(PrintDensity::Normal)
}
#[must_use]
pub fn density_dark(self) -> Self {
self.print_density(PrintDensity::Dark)
}
#[must_use]
pub fn density_high_contrast(self) -> Self {
self.print_density(PrintDensity::HighContrast)
}
#[must_use]
pub fn heating_parameters(mut self, params: HeatingParameters) -> Self {
self.commands.push(Command::HeatingParameters(params));
self
}
#[must_use]
pub fn raw(mut self, bytes: impl Into<Vec<u8>>) -> Self {
self.commands.push(Command::Raw(bytes.into()));
self
}
#[must_use]
pub fn render_svg(&self) -> String {
crate::layout::preview::render_svg(self)
}
#[must_use]
pub fn render_html(&self) -> String {
crate::layout::preview::render_html(self)
}
}