Compare commits
18 Commits
Author | SHA1 | Date | |
---|---|---|---|
3dc5da6fc8
|
|||
5132eab6fa
|
|||
77c6b7bc7b
|
|||
f702ec5473
|
|||
59ef4189c4
|
|||
bb7ab6239d
|
|||
37ee7c10f1
|
|||
d98399949c
|
|||
a47a3189d3
|
|||
6857de7b1f
|
|||
5a38600e2a
|
|||
1163ae5745
|
|||
09a2e621d6
|
|||
28308dccad
|
|||
5f5c0f0f97
|
|||
4a59b50839
|
|||
79477baecd
|
|||
cf8492a714
|
@@ -41,7 +41,7 @@ BreakBeforeBinaryOperators: None
|
|||||||
BreakBeforeTernaryOperators: true
|
BreakBeforeTernaryOperators: true
|
||||||
BreakConstructorInitializers: BeforeColon
|
BreakConstructorInitializers: BeforeColon
|
||||||
BreakInheritanceList: BeforeColon
|
BreakInheritanceList: BeforeColon
|
||||||
ColumnLimit: 100
|
ColumnLimit: 120
|
||||||
CompactNamespaces: false
|
CompactNamespaces: false
|
||||||
ContinuationIndentWidth: 4
|
ContinuationIndentWidth: 4
|
||||||
Cpp11BracedListStyle: true
|
Cpp11BracedListStyle: true
|
||||||
|
@@ -2,7 +2,6 @@
|
|||||||
Checks: "clang-diagnostic-*,clang-analyzer-*,cppcoreguidelines-*,modernize-*,-modernize-use-trailing-return-type"
|
Checks: "clang-diagnostic-*,clang-analyzer-*,cppcoreguidelines-*,modernize-*,-modernize-use-trailing-return-type"
|
||||||
WarningsAsErrors: true
|
WarningsAsErrors: true
|
||||||
HeaderFilterRegex: ""
|
HeaderFilterRegex: ""
|
||||||
AnalyzeTemporaryDtors: false
|
|
||||||
FormatStyle: google
|
FormatStyle: google
|
||||||
CheckOptions:
|
CheckOptions:
|
||||||
- key: cert-dcl16-c.NewSuffixes
|
- key: cert-dcl16-c.NewSuffixes
|
||||||
|
2
.vscode/c_cpp_properties.json
vendored
2
.vscode/c_cpp_properties.json
vendored
@@ -4,7 +4,7 @@
|
|||||||
"name": "Linux",
|
"name": "Linux",
|
||||||
"compilerPath": "/usr/bin/clang",
|
"compilerPath": "/usr/bin/clang",
|
||||||
"cStandard": "c11",
|
"cStandard": "c11",
|
||||||
"cppStandard": "c++17",
|
"cppStandard": "c++20",
|
||||||
"compileCommands": "${workspaceFolder}/builddir/compile_commands.json",
|
"compileCommands": "${workspaceFolder}/builddir/compile_commands.json",
|
||||||
"browse": {
|
"browse": {
|
||||||
"path": ["${workspaceFolder}"]
|
"path": ["${workspaceFolder}"]
|
||||||
|
2
.vscode/launch.json
vendored
2
.vscode/launch.json
vendored
@@ -14,7 +14,7 @@
|
|||||||
"cwd": "${fileDirname}",
|
"cwd": "${fileDirname}",
|
||||||
"environment": [],
|
"environment": [],
|
||||||
"externalConsole": false,
|
"externalConsole": false,
|
||||||
"MIMode": "gdb",
|
"MIMode": "lldb",
|
||||||
"setupCommands": [
|
"setupCommands": [
|
||||||
{
|
{
|
||||||
"description": "Automatische Strukturierung und Einrückung für \"gdb\" aktivieren",
|
"description": "Automatische Strukturierung und Einrückung für \"gdb\" aktivieren",
|
||||||
|
3
.vscode/settings.json
vendored
3
.vscode/settings.json
vendored
@@ -83,8 +83,5 @@
|
|||||||
"charconv": "cpp",
|
"charconv": "cpp",
|
||||||
"*.ipp": "cpp"
|
"*.ipp": "cpp"
|
||||||
},
|
},
|
||||||
"clang-tidy.buildPath": "builddir/",
|
|
||||||
"clangd.onConfigChanged": "restart",
|
"clangd.onConfigChanged": "restart",
|
||||||
"C_Cpp.default.compileCommands": "/home/moritz/src/ptouch-prnt/builddir/compile_commands.json",
|
|
||||||
"C_Cpp.default.configurationProvider": "mesonbuild.mesonbuild"
|
|
||||||
}
|
}
|
||||||
|
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
SCRIPT_PATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
|
SCRIPT_PATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
|
||||||
HTML_COV_PATH="coverageReport/html"
|
HTML_COV_PATH="coverageReport/html"
|
||||||
|
XML_COV_PATH="coverageReport/xml"
|
||||||
HTML_START_FILE="index.html"
|
HTML_START_FILE="index.html"
|
||||||
|
|
||||||
echo "Generating Coverage report for ptouch-prnt"
|
echo "Generating Coverage report for ptouch-prnt"
|
||||||
@@ -12,10 +13,15 @@ ninja -C builddir test
|
|||||||
mkdir -p ${HTML_COV_PATH}
|
mkdir -p ${HTML_COV_PATH}
|
||||||
gcovr --html --html-details --html-syntax-highlighting --filter src --output ${HTML_COV_PATH}/${HTML_START_FILE}
|
gcovr --html --html-details --html-syntax-highlighting --filter src --output ${HTML_COV_PATH}/${HTML_START_FILE}
|
||||||
|
|
||||||
|
mkdir -p ${XML_COV_PATH}
|
||||||
|
gcovr --xml-pretty --filter src --output ${XML_COV_PATH}/cov.xml
|
||||||
|
|
||||||
if [ $? ]
|
if [ $? ]
|
||||||
then
|
then
|
||||||
echo "Coverage report successful generated!"
|
echo "Coverage report successful generated!"
|
||||||
echo "Open: file://${SCRIPT_PATH}/${HTML_COV_PATH}/${HTML_START_FILE}"
|
echo "Open: file://${SCRIPT_PATH}/${HTML_COV_PATH}/${HTML_START_FILE}"
|
||||||
else
|
else
|
||||||
echo "Error generating coverage report!"
|
echo "Error generating coverage report!"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
rm *.gcov
|
29
meson.build
29
meson.build
@@ -1,7 +1,22 @@
|
|||||||
project('ptprnt', 'cpp',
|
project(
|
||||||
version: 'v0.1.0-'+run_command('git', 'rev-parse', '--short', 'HEAD', check: true).stdout().strip(),
|
'ptprnt',
|
||||||
|
'cpp',
|
||||||
|
version: 'v0.1.0-' + run_command(
|
||||||
|
'git',
|
||||||
|
'rev-parse',
|
||||||
|
'--short',
|
||||||
|
'HEAD',
|
||||||
|
check: true,
|
||||||
|
).stdout().strip(),
|
||||||
license: 'GPLv3',
|
license: 'GPLv3',
|
||||||
default_options : ['c_std=c11', 'cpp_std=c++17']
|
default_options: [
|
||||||
|
'c_std=c11',
|
||||||
|
'cpp_std=c++20',
|
||||||
|
'b_sanitize=none',
|
||||||
|
'b_lto=true',
|
||||||
|
'b_lto_mode=thin',
|
||||||
|
'b_thinlto_cache=true',
|
||||||
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
usb_dep = dependency('libusb-1.0')
|
usb_dep = dependency('libusb-1.0')
|
||||||
@@ -21,13 +36,13 @@ incdir = include_directories('src')
|
|||||||
subdir('src')
|
subdir('src')
|
||||||
|
|
||||||
ptprnt_exe = executable(
|
ptprnt_exe = executable(
|
||||||
'ptprnt',
|
'ptprnt',
|
||||||
'src/main.cpp',
|
'src/main.cpp',
|
||||||
install: true,
|
install: true,
|
||||||
dependencies : [usb_dep, log_dep, fmt_dep, pangocairo_dep, cli11_dep],
|
dependencies: [usb_dep, log_dep, fmt_dep, pangocairo_dep, cli11_dep],
|
||||||
include_directories: incdir,
|
include_directories: incdir,
|
||||||
sources: [ptprnt_srcs],
|
sources: [ptprnt_srcs],
|
||||||
cpp_args : ['-DPROJ_VERSION="'+meson.project_version()+'"'],
|
cpp_args: ['-DPROJ_VERSION="' + meson.project_version() + '"'],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -40,4 +55,4 @@ if not gtest_dep.found()
|
|||||||
error('MESON_SKIP_TEST: gtest not installed.')
|
error('MESON_SKIP_TEST: gtest not installed.')
|
||||||
endif
|
endif
|
||||||
|
|
||||||
subdir('tests')
|
subdir('tests')
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
/*
|
/*
|
||||||
ptrnt - print labels on linux
|
ptrnt - print labels on linux
|
||||||
Copyright (C) 2023 Moritz Martinius
|
Copyright (C) 2023 Moritz Martinius
|
||||||
|
|
||||||
@@ -19,35 +19,32 @@
|
|||||||
|
|
||||||
#include "P700Printer.hpp"
|
#include "P700Printer.hpp"
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <spdlog/spdlog.h>
|
#include <spdlog/spdlog.h>
|
||||||
|
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <iostream>
|
|
||||||
#include <iterator>
|
#include <iterator>
|
||||||
#include <ratio>
|
#include <memory>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include "graphics/Bitmap.hpp"
|
#include "graphics/Bitmap.hpp"
|
||||||
#include "graphics/Image.hpp"
|
|
||||||
#include "graphics/Monochrome.hpp"
|
#include "graphics/Monochrome.hpp"
|
||||||
#include "libusb.h"
|
|
||||||
#include "libusbwrap/LibUsbTypes.hpp"
|
#include "libusbwrap/LibUsbTypes.hpp"
|
||||||
#include "spdlog/fmt/bin_to_hex.h"
|
#include "spdlog/fmt/bin_to_hex.h"
|
||||||
|
|
||||||
// as long as DRYRUN is defined, no data is actually send to the printer, we need to save some tape ;)
|
// as long as DRYRUN is defined, no data is actually send to the printer, we need to save some tape ;)
|
||||||
//#define DRYRUN
|
#define DRYRUN
|
||||||
|
|
||||||
namespace ptprnt::printer {
|
namespace ptprnt::printer {
|
||||||
|
|
||||||
const PrinterInfo P700Printer::mInfo = {.driverName = "P700",
|
const PrinterInfo P700Printer::mInfo = {.driverName = "P700",
|
||||||
.name = "Brother P-touch P700",
|
.name = "Brother P-touch P700",
|
||||||
.version = "v1.0",
|
.version = "v1.0",
|
||||||
.usbId{0x04f9, 0x2061}};
|
.usbId{0x04f9, 0x2061},
|
||||||
|
.pixelLines = 128};
|
||||||
|
|
||||||
P700Printer::~P700Printer() {
|
P700Printer::~P700Printer() {
|
||||||
detachUsbDevice();
|
P700Printer::detachUsbDevice();
|
||||||
if (mUsbHndl) {
|
if (mUsbHndl) {
|
||||||
mUsbHndl->close();
|
mUsbHndl->close();
|
||||||
}
|
}
|
||||||
@@ -71,15 +68,14 @@ const PrinterInfo P700Printer::getPrinterInfo() {
|
|||||||
|
|
||||||
const PrinterStatus P700Printer::getPrinterStatus() {
|
const PrinterStatus P700Printer::getPrinterStatus() {
|
||||||
using namespace std::chrono_literals;
|
using namespace std::chrono_literals;
|
||||||
std::vector<uint8_t> getStatusCmd({0x1b, 0x69, 0x53}); // status info request
|
send(p700::commands::GET_STATUS);
|
||||||
send(getStatusCmd);
|
|
||||||
|
|
||||||
int tx = 0;
|
int tx = 0;
|
||||||
int tries = 0;
|
int tries = 0;
|
||||||
std::vector<uint8_t> recvBuf(32);
|
std::vector<uint8_t> recvBuf(32);
|
||||||
while (tries++ < MAX_TRIES_GET_STATUS) {
|
while (tries++ < MAX_TRIES_GET_STATUS) {
|
||||||
std::this_thread::sleep_for(100ms);
|
std::this_thread::sleep_for(100ms);
|
||||||
mUsbHndl->bulkTransfer(commands["printerinfo"][0], recvBuf, &tx, 0);
|
mUsbHndl->bulkTransfer(p700::commands::PRINTER_INFO[0], recvBuf, &tx, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
return PrinterStatus{.tapeWidthMm = recvBuf[10]};
|
return PrinterStatus{.tapeWidthMm = recvBuf[10]};
|
||||||
@@ -96,6 +92,7 @@ bool P700Printer::attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHnd
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!usbHndl->detachKernelDriver(0)) {
|
if (!usbHndl->detachKernelDriver(0)) {
|
||||||
|
|
||||||
spdlog::error("Device is already in use or couldn't be detached from kernel: {}",
|
spdlog::error("Device is already in use or couldn't be detached from kernel: {}",
|
||||||
usbHndl->getLastErrorString());
|
usbHndl->getLastErrorString());
|
||||||
return false;
|
return false;
|
||||||
@@ -123,78 +120,83 @@ bool P700Printer::detachUsbDevice() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) {
|
bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) {
|
||||||
auto bm = graphics::Bitmap<graphics::ALPHA8>(512, 128);
|
// Convert bitmap to MonochromeData and delegate to printMonochromeData
|
||||||
{
|
auto pixels = bitmap.getPixelsCpy();
|
||||||
auto img = graphics::Image();
|
auto mono = graphics::Monochrome(pixels, bitmap.getWidth(), bitmap.getHeight());
|
||||||
bm.setPixels(std::vector<uint8_t>(img.getRaw(), img.getRaw() + 512 * 128));
|
auto monoData = mono.getMonochromeData();
|
||||||
}
|
|
||||||
|
return printMonochromeData(monoData);
|
||||||
send(commands["rasterstart"]);
|
}
|
||||||
|
|
||||||
|
bool P700Printer::printMonochromeData(const graphics::MonochromeData& data) {
|
||||||
|
#ifdef DRYRUN
|
||||||
|
spdlog::debug("DRYRUN enabled");
|
||||||
|
data.visualize();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
send(p700::commands::RASTER_START);
|
||||||
std::vector<uint8_t> rastercmd(4);
|
std::vector<uint8_t> rastercmd(4);
|
||||||
rastercmd[0] = 0x47;
|
rastercmd[0] = 0x47;
|
||||||
rastercmd[1] = 0x00; // size +1
|
rastercmd[1] = 0x00; // size +1
|
||||||
rastercmd[2] = 0x00;
|
rastercmd[2] = 0x00;
|
||||||
rastercmd[3] = 0x00; // size -1
|
rastercmd[3] = 0x00; // size -1
|
||||||
for (unsigned int i = 0; i < bm.getWidth(); i++) {
|
|
||||||
auto bmcol = bm.getCol(i);
|
// Process data column by column for the printer
|
||||||
if (!bmcol) {
|
for (uint32_t col = 0; col < data.width; col++) {
|
||||||
spdlog::error("Out of bounds bitmap access");
|
std::vector<uint8_t> columnData;
|
||||||
|
|
||||||
|
// Extract column data bit by bit
|
||||||
|
for (uint32_t row = 0; row < data.height; row += 8) {
|
||||||
|
uint8_t byte = 0;
|
||||||
|
for (int bit = 0; bit < 8 && (row + bit) < data.height; bit++) {
|
||||||
|
if (data.getBit(col, row + bit)) {
|
||||||
|
byte |= (1 << (7 - bit));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
columnData.push_back(byte);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<uint8_t> buf;
|
||||||
|
buf.insert(buf.begin(), rastercmd.begin(), rastercmd.end());
|
||||||
|
buf.insert(std::next(buf.begin(), 4), columnData.begin(), columnData.end());
|
||||||
|
buf[1] = columnData.size() + 1;
|
||||||
|
buf[3] = columnData.size() - 1;
|
||||||
|
|
||||||
|
if (!send(buf)) {
|
||||||
|
spdlog::error("Error sending buffer to printer");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
auto monocol = graphics::Monochrome(*bmcol);
|
|
||||||
auto col = monocol.get();
|
|
||||||
|
|
||||||
std::vector<uint8_t> buf(0);
|
|
||||||
buf.insert(buf.begin(), rastercmd.begin(), rastercmd.end());
|
|
||||||
buf.insert(std::next(buf.begin(), 4), col.begin(), col.end());
|
|
||||||
|
|
||||||
buf[1] = col.size() + 1;
|
|
||||||
buf[3] = col.size() - 1;
|
|
||||||
if (!send(buf)) {
|
|
||||||
break;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
send(commands["eject"]);
|
send(p700::commands::EJECT);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool P700Printer::setText(const std::string& text) {
|
bool P700Printer::printLabel(std::unique_ptr<graphics::ILabel> label) {
|
||||||
return true;
|
// Convert label directly to MonochromeData
|
||||||
};
|
auto pixels = label->getRaw();
|
||||||
|
auto mono = graphics::Monochrome(pixels, label->getWidth(), label->getHeight());
|
||||||
bool P700Printer::setFont(const std::string& text) {
|
auto monoData = mono.getMonochromeData();
|
||||||
return true;
|
|
||||||
};
|
spdlog::debug("Label has {}x{}px size", label->getWidth(), label->getHeight());
|
||||||
|
return printMonochromeData(monoData);
|
||||||
bool P700Printer::setFontSize(uint8_t fontSize) {
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
|
|
||||||
bool P700Printer::setHAlign(HAlignPosition hpos) {
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
|
|
||||||
bool P700Printer::setVAlign(VAlignPosition vpos) {
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool P700Printer::print() {
|
bool P700Printer::print() {
|
||||||
send(commands["lf"]);
|
send(p700::commands::LF);
|
||||||
send(commands["ff"]);
|
send(p700::commands::FF);
|
||||||
send(commands["eject"]);
|
send(p700::commands::EJECT);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool P700Printer::send(std::vector<uint8_t>& data) {
|
bool P700Printer::send(const std::vector<uint8_t>& data) {
|
||||||
|
|
||||||
if (mUsbHndl == nullptr || data.size() > 128) {
|
if (mUsbHndl == nullptr || data.size() > 128) {
|
||||||
spdlog::error("Invalid device handle or invalid data.");
|
spdlog::error("Invalid device handle or invalid data.");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
int tx = 0;
|
size_t tx = 0;
|
||||||
|
|
||||||
#ifndef DRYRUN
|
#ifndef DRYRUN
|
||||||
if (!mUsbHndl->bulkTransfer(0x02, data, &tx, 0)) {
|
if (!mUsbHndl->bulkTransfer(0x02, data, &tx, 0)) {
|
||||||
@@ -203,12 +205,11 @@ bool P700Printer::send(std::vector<uint8_t>& data) {
|
|||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
tx = data.size();
|
tx = data.size();
|
||||||
spdlog::debug("USB raw data(len {}): {}", data.size(), spdlog::to_hex(data));
|
spdlog::trace("USB raw data(len {}): {}", data.size(), spdlog::to_hex(data));
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
if (tx != static_cast<int>(data.size())) {
|
if (tx != data.size()) {
|
||||||
spdlog::error("Could not transfer all data via USB bulk transfer. Only send {} of {} bytes",
|
spdlog::error("Could not transfer all data via USB bulk transfer. Only sent {} of {} bytes", tx, data.size());
|
||||||
tx, data.size());
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,4 +222,4 @@ bool P700Printer::init() {
|
|||||||
cmd[101] = 0x40; /* @ */
|
cmd[101] = 0x40; /* @ */
|
||||||
return send(cmd);
|
return send(cmd);
|
||||||
}
|
}
|
||||||
} // namespace ptprnt::printer
|
} // namespace ptprnt::printer
|
||||||
|
@@ -17,9 +17,9 @@
|
|||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#include <spdlog/spdlog.h>
|
||||||
#include <sys/types.h>
|
#include <sys/types.h>
|
||||||
|
|
||||||
#include <map>
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
@@ -31,13 +31,26 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
namespace ptprnt::printer {
|
namespace ptprnt::printer {
|
||||||
|
namespace p700::commands {
|
||||||
|
const cmd_T GET_STATUS{0x1b, 0x69, 0x53};
|
||||||
|
const cmd_T RASTER_START{0x1b, 0x69, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
||||||
|
const cmd_T INFO{0x1b, 0x69, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
|
||||||
|
const cmd_T PACKBITSON{0x02};
|
||||||
|
const cmd_T LF{0x5a};
|
||||||
|
const cmd_T FF{0x0c};
|
||||||
|
const cmd_T EJECT{0x1a};
|
||||||
|
const cmd_T PRINTER_INFO{0x81};
|
||||||
|
} // namespace p700::commands
|
||||||
|
|
||||||
constexpr uint8_t MAX_TRIES_GET_STATUS = 10;
|
constexpr uint8_t MAX_TRIES_GET_STATUS = 10;
|
||||||
|
|
||||||
|
// TODO:
|
||||||
|
// Remove Text-layout specific parts, add them to label
|
||||||
|
|
||||||
class P700Printer : public ::ptprnt::IPrinterDriver {
|
class P700Printer : public ::ptprnt::IPrinterDriver {
|
||||||
public:
|
public:
|
||||||
P700Printer() = default;
|
P700Printer() = default;
|
||||||
~P700Printer();
|
~P700Printer() override;
|
||||||
|
|
||||||
// delete copy ctor and assignment
|
// delete copy ctor and assignment
|
||||||
P700Printer(const P700Printer&) = default;
|
P700Printer(const P700Printer&) = default;
|
||||||
@@ -57,29 +70,15 @@ class P700Printer : public ::ptprnt::IPrinterDriver {
|
|||||||
[[nodiscard]] const PrinterStatus getPrinterStatus() override;
|
[[nodiscard]] const PrinterStatus getPrinterStatus() override;
|
||||||
bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) override;
|
bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) override;
|
||||||
bool detachUsbDevice() override;
|
bool detachUsbDevice() override;
|
||||||
bool setText(const std::string& text) override;
|
|
||||||
bool setFont(const std::string& text) override;
|
|
||||||
bool setFontSize(uint8_t fontSize) override;
|
|
||||||
bool setHAlign(HAlignPosition hpos) override;
|
|
||||||
bool setVAlign(VAlignPosition vpos) override;
|
|
||||||
bool printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) override;
|
bool printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) override;
|
||||||
|
bool printMonochromeData(const graphics::MonochromeData& data) override;
|
||||||
|
bool printLabel(const std::unique_ptr<graphics::ILabel> label) override;
|
||||||
bool print() override;
|
bool print() override;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
bool send(std::vector<uint8_t>& data);
|
bool send(const std::vector<uint8_t>& data);
|
||||||
bool init();
|
bool init();
|
||||||
|
|
||||||
std::shared_ptr<libusbwrap::IUsbDevice> mUsbHndl{nullptr};
|
std::shared_ptr<libusbwrap::IUsbDevice> mUsbHndl{nullptr};
|
||||||
std::map<std::string, std::vector<uint8_t>> commands{
|
|
||||||
{"rasterstart",
|
|
||||||
{0x1b, 0x69, 0x61,
|
|
||||||
0x01}}, // unique for P700, other printers have the 2 byte set to 0x52 instead of 0x61
|
|
||||||
{"info", {0x1b, 0x69, 0x7a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
|
|
||||||
{"packbitson", {0x02}},
|
|
||||||
{"lf", {0x5a}},
|
|
||||||
{"ff", {0x0c}},
|
|
||||||
{"eject", {0x1a}},
|
|
||||||
{"printerinfo", {0x81}}};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace ptprnt::printer
|
} // namespace ptprnt::printer
|
@@ -16,12 +16,10 @@
|
|||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
*/
|
*/
|
||||||
#include <cstdint>
|
#include "PtouchPrint.hpp"
|
||||||
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE
|
|
||||||
#define SPDLOG_DEBUG_ON
|
|
||||||
#define SPDLOG_TRACE_ON
|
|
||||||
|
|
||||||
#include <CLI/App.hpp>
|
#include <CLI/App.hpp>
|
||||||
|
#include <algorithm>
|
||||||
#include <fmt/core.h>
|
#include <fmt/core.h>
|
||||||
#include <spdlog/common.h>
|
#include <spdlog/common.h>
|
||||||
#include <spdlog/details/synchronous_factory.h>
|
#include <spdlog/details/synchronous_factory.h>
|
||||||
@@ -31,14 +29,16 @@
|
|||||||
#include <spdlog/sinks/stdout_color_sinks.h>
|
#include <spdlog/sinks/stdout_color_sinks.h>
|
||||||
#include <spdlog/spdlog.h>
|
#include <spdlog/spdlog.h>
|
||||||
|
|
||||||
|
#include <cctype>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <unordered_set>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include "CLI/Option.hpp"
|
#include "CLI/Option.hpp"
|
||||||
#include "PrinterDriverFactory.hpp"
|
#include "PrinterDriverFactory.hpp"
|
||||||
#include "PtouchPrint.hpp"
|
#include "graphics/Label.hpp"
|
||||||
#include "graphics/Bitmap.hpp"
|
#include "graphics/interface/ILabel.hpp"
|
||||||
#include "libusbwrap/UsbDeviceFactory.hpp"
|
#include "libusbwrap/UsbDeviceFactory.hpp"
|
||||||
|
|
||||||
namespace ptprnt {
|
namespace ptprnt {
|
||||||
@@ -58,7 +58,7 @@ int PtouchPrint::init(int argc, char** argv) {
|
|||||||
if (mVerboseFlag) {
|
if (mVerboseFlag) {
|
||||||
setupLogger(spdlog::level::debug);
|
setupLogger(spdlog::level::debug);
|
||||||
} else {
|
} else {
|
||||||
setupLogger(spdlog::level::err);
|
setupLogger(spdlog::level::warn);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!mUsbDeviceFactory.init()) {
|
if (!mUsbDeviceFactory.init()) {
|
||||||
@@ -74,8 +74,7 @@ int PtouchPrint::run() {
|
|||||||
mDetectedPrinters = getCompatiblePrinters();
|
mDetectedPrinters = getCompatiblePrinters();
|
||||||
auto numFoundPrinters = mDetectedPrinters.size();
|
auto numFoundPrinters = mDetectedPrinters.size();
|
||||||
if (numFoundPrinters == 0) {
|
if (numFoundPrinters == 0) {
|
||||||
spdlog::error(
|
spdlog::error("No compatible printers found, please make sure that they are turned on and connected");
|
||||||
"No compatible printers found, please make sure that they are turned on and connected");
|
|
||||||
return -1;
|
return -1;
|
||||||
} else if (numFoundPrinters > 1) {
|
} else if (numFoundPrinters > 1) {
|
||||||
spdlog::warn("Found more than one compatible printer. Currently not supported.");
|
spdlog::warn("Found more than one compatible printer. Currently not supported.");
|
||||||
@@ -84,52 +83,78 @@ int PtouchPrint::run() {
|
|||||||
|
|
||||||
auto printer = mDetectedPrinters[0];
|
auto printer = mDetectedPrinters[0];
|
||||||
const auto printerUsbId = printer->getUsbId();
|
const auto printerUsbId = printer->getUsbId();
|
||||||
auto devices = mUsbDeviceFactory.findDevices(printerUsbId.first, printerUsbId.second);
|
auto devices = mUsbDeviceFactory.findDevices(printerUsbId.first, printerUsbId.second);
|
||||||
if (devices.size() != 1) {
|
if (devices.size() != 1) {
|
||||||
spdlog::warn(
|
spdlog::warn("Found more than one device of the same printer on bus. Currently not supported");
|
||||||
"Found more than one device of the same printer on bus. Currently not supported");
|
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
printer->attachUsbDevice(devices[0]);
|
printer->attachUsbDevice(std::move(devices[0]));
|
||||||
auto status = printer->getPrinterStatus();
|
auto status = printer->getPrinterStatus();
|
||||||
spdlog::info("Detected tape width is {}mm", status.tapeWidthMm);
|
spdlog::info("Detected tape width is {}mm", status.tapeWidthMm);
|
||||||
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(512, 128);
|
|
||||||
//printer->printBitmap(bm);
|
|
||||||
//printer->printText("wurst", 1);
|
|
||||||
|
|
||||||
for (auto& cmd : mCommands) {
|
if (0 == mCommands.size()) {
|
||||||
switch (cmd.first) {
|
spdlog::warn("No command specified, nothing to do...");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto label = std::make_unique<graphics::Label>(printer->getPrinterInfo().pixelLines);
|
||||||
|
std::string labelText{};
|
||||||
|
// TODO: refactor
|
||||||
|
for (const auto& [cmd, value] : mCommands) {
|
||||||
|
switch (cmd) {
|
||||||
case CliCmdType::Text:
|
case CliCmdType::Text:
|
||||||
spdlog::debug("Setting text to {}", cmd.second);
|
if (labelText.empty()) {
|
||||||
printer->setText(cmd.second);
|
labelText = value;
|
||||||
|
} else {
|
||||||
|
labelText = labelText + '\n' + value;
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
case CliCmdType::Font:;
|
case CliCmdType::Font:
|
||||||
spdlog::debug("Setting font to {}", cmd.second);
|
spdlog::debug("Setting font to {}", value);
|
||||||
printer->setFont(cmd.second);
|
label->setFontFamily(value);
|
||||||
break;
|
break;
|
||||||
case CliCmdType::FontSize:;
|
case CliCmdType::FontSize:
|
||||||
spdlog::debug("Setting font size to {}", cmd.second);
|
spdlog::debug("Setting font size to {}", std::stod(value));
|
||||||
printer->setFontSize(static_cast<uint8_t>(std::atoi(cmd.second.c_str())));
|
label->setFontSize(std::stod(value));
|
||||||
break;
|
break;
|
||||||
case CliCmdType::HAlign:;
|
case CliCmdType::HAlign:
|
||||||
spdlog::debug("[Not implemented] Setting text horizontal alignment to {}",
|
spdlog::debug("Setting text horizontal alignment to {}", value);
|
||||||
cmd.second);
|
{
|
||||||
|
auto hPos = HALignPositionMap.find(value);
|
||||||
|
if (hPos == HALignPositionMap.end()) {
|
||||||
|
spdlog::warn("Invalid horizontal alignment specified!");
|
||||||
|
label->setHAlign(HAlignPosition::UNKNOWN);
|
||||||
|
} else {
|
||||||
|
label->setHAlign(hPos->second);
|
||||||
|
}
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
case CliCmdType::VAlign:;
|
case CliCmdType::VAlign:
|
||||||
spdlog::debug("[Not implemented] Setting text vertical alignment to {}",
|
spdlog::debug("Setting text vertical alignment to {}", value);
|
||||||
cmd.second);
|
{
|
||||||
|
auto vPos = VALignPositionMap.find(value);
|
||||||
|
if (vPos == VALignPositionMap.end()) {
|
||||||
|
spdlog::warn("Invalid verical alignment specified!");
|
||||||
|
label->setVAlign(VAlignPosition::UNKNOWN);
|
||||||
|
} else {
|
||||||
|
label->setVAlign(vPos->second);
|
||||||
|
}
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
case CliCmdType::None:;
|
case CliCmdType::None:
|
||||||
[[fallthrough]];
|
[[fallthrough]];
|
||||||
default:
|
default:
|
||||||
spdlog::warn("This command is currently not supported.");
|
spdlog::warn("This command is currently not supported.");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!printer->print()) {
|
label->create(labelText);
|
||||||
|
label->writeToPng("./testlabel.png");
|
||||||
|
/*if (!printer->printLabel(std::move(label))) {
|
||||||
spdlog::error("An error occured while printing");
|
spdlog::error("An error occured while printing");
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}*/
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,7 +164,7 @@ std::vector<std::shared_ptr<IPrinterDriver>> PtouchPrint::getCompatiblePrinters(
|
|||||||
auto driverFactory = std::make_unique<PrinterDriverFactory>();
|
auto driverFactory = std::make_unique<PrinterDriverFactory>();
|
||||||
std::vector<std::shared_ptr<IPrinterDriver>> foundPrinterDrivers{};
|
std::vector<std::shared_ptr<IPrinterDriver>> foundPrinterDrivers{};
|
||||||
|
|
||||||
for (auto usbDev : usbDevs) {
|
for (auto& usbDev : usbDevs) {
|
||||||
auto driver = driverFactory->create(usbDev->getUsbId());
|
auto driver = driverFactory->create(usbDev->getUsbId());
|
||||||
if (driver != nullptr) {
|
if (driver != nullptr) {
|
||||||
foundPrinterDrivers.push_back(driver);
|
foundPrinterDrivers.push_back(driver);
|
||||||
@@ -151,7 +176,13 @@ std::vector<std::shared_ptr<IPrinterDriver>> PtouchPrint::getCompatiblePrinters(
|
|||||||
void PtouchPrint::setupLogger(spdlog::level::level_enum lvl) {
|
void PtouchPrint::setupLogger(spdlog::level::level_enum lvl) {
|
||||||
auto consoleSink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
|
auto consoleSink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
|
||||||
consoleSink->set_level(lvl);
|
consoleSink->set_level(lvl);
|
||||||
consoleSink->set_pattern("%^%L:%$ %v");
|
if (spdlog::level::level_enum::debug == lvl || spdlog::level::level_enum::trace == lvl) {
|
||||||
|
// This will enable file and line number for debug and trace macros
|
||||||
|
// TODO: line number and functions only work with macros
|
||||||
|
consoleSink->set_pattern("%^%L:%$ %v");
|
||||||
|
} else {
|
||||||
|
consoleSink->set_pattern("%^%L:%$ %v");
|
||||||
|
}
|
||||||
|
|
||||||
auto fileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("ptprnt.log", true);
|
auto fileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("ptprnt.log", true);
|
||||||
fileSink->set_level(spdlog::level::trace);
|
fileSink->set_level(spdlog::level::trace);
|
||||||
@@ -162,6 +193,7 @@ void PtouchPrint::setupLogger(spdlog::level::level_enum lvl) {
|
|||||||
spdlog::set_default_logger(logger);
|
spdlog::set_default_logger(logger);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: CLI parsing should be a seperate class/file
|
||||||
void PtouchPrint::setupCliParser() {
|
void PtouchPrint::setupCliParser() {
|
||||||
auto printVersion = [this](std::size_t) {
|
auto printVersion = [this](std::size_t) {
|
||||||
fmt::print("ptprnt version: {}\n", mVersionString);
|
fmt::print("ptprnt version: {}\n", mVersionString);
|
||||||
@@ -181,27 +213,42 @@ void PtouchPrint::setupCliParser() {
|
|||||||
->each([this](std::string text) { mCommands.emplace_back(CliCmdType::Text, text); });
|
->each([this](std::string text) { mCommands.emplace_back(CliCmdType::Text, text); });
|
||||||
mApp.add_option("-f,--font", "Font used for the following text occurences")
|
mApp.add_option("-f,--font", "Font used for the following text occurences")
|
||||||
->group("Text printing ")
|
->group("Text printing ")
|
||||||
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
|
->multi_option_policy(CLI::MultiOptionPolicy::TakeFirst)
|
||||||
->trigger_on_parse()
|
->trigger_on_parse()
|
||||||
->each([this](std::string font) { mCommands.emplace_back(CliCmdType::Font, font); });
|
->each([this](std::string font) { mCommands.emplace_back(CliCmdType::Font, font); });
|
||||||
mApp.add_option("-s,--fontsize", "Font size of the following text occurences")
|
mApp.add_option("-s,--fontsize", "Font size of the following text occurences")
|
||||||
->group("Text printing ")
|
->group("Text printing ")
|
||||||
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
|
->multi_option_policy(CLI::MultiOptionPolicy::TakeFirst)
|
||||||
->trigger_on_parse()
|
->trigger_on_parse()
|
||||||
->each([this](std::string size) { mCommands.emplace_back(CliCmdType::FontSize, size); });
|
->each([this](std::string size) { mCommands.emplace_back(CliCmdType::FontSize, size); });
|
||||||
mApp.add_option("--valign", "Vertical alignment of the following text occurences")
|
mApp.add_option("--valign", "Vertical alignment of the following text occurences")
|
||||||
->group("Text printing ")
|
->group("Text printing ")
|
||||||
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
|
->multi_option_policy(CLI::MultiOptionPolicy::TakeFirst)
|
||||||
->trigger_on_parse()
|
->trigger_on_parse()
|
||||||
|
->transform([](std::string in) -> std::string {
|
||||||
|
std::unordered_set<std::string> validValignOptions{"top", "middle", "bottom"};
|
||||||
|
std::transform(in.begin(), in.end(), in.begin(), [](unsigned char c) { return std::tolower(c); });
|
||||||
|
if (validValignOptions.find(in) == validValignOptions.end()) {
|
||||||
|
return {""};
|
||||||
|
}
|
||||||
|
return in;
|
||||||
|
})
|
||||||
->each([this](std::string valign) { mCommands.emplace_back(CliCmdType::VAlign, valign); });
|
->each([this](std::string valign) { mCommands.emplace_back(CliCmdType::VAlign, valign); });
|
||||||
mApp.add_option("--halign", "Vertical alignment of the following text occurences")
|
mApp.add_option("--halign", "Vertical alignment of the following text occurences")
|
||||||
->group("Text printing ")
|
->group("Text printing ")
|
||||||
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
|
->multi_option_policy(CLI::MultiOptionPolicy::TakeFirst)
|
||||||
->trigger_on_parse()
|
->trigger_on_parse()
|
||||||
|
->transform([](std::string in) -> std::string {
|
||||||
|
std::unordered_set<std::string> validValignOptions{"left", "center", "right", "justify"};
|
||||||
|
std::transform(in.begin(), in.end(), in.begin(), [](unsigned char c) { return std::tolower(c); });
|
||||||
|
if (validValignOptions.find(in) == validValignOptions.end()) {
|
||||||
|
return {""};
|
||||||
|
}
|
||||||
|
return in;
|
||||||
|
})
|
||||||
->each([this](std::string halign) { mCommands.emplace_back(CliCmdType::HAlign, halign); });
|
->each([this](std::string halign) { mCommands.emplace_back(CliCmdType::HAlign, halign); });
|
||||||
|
|
||||||
// Image options
|
// Image options
|
||||||
mApp.add_option("-i,--image", "Image to print. Excludes all text printing ")
|
mApp.add_option("-i,--image", "Image to print. Excludes all text printing ")->group("Image printing");
|
||||||
->group("Image printing");
|
|
||||||
}
|
}
|
||||||
} // namespace ptprnt
|
} // namespace ptprnt
|
@@ -19,32 +19,30 @@
|
|||||||
|
|
||||||
#include "Bitmap.hpp"
|
#include "Bitmap.hpp"
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <spdlog/spdlog.h>
|
#include <spdlog/spdlog.h>
|
||||||
|
|
||||||
#include <iterator>
|
#include <ranges>
|
||||||
#include <optional>
|
#include <stdexcept>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace ptprnt::graphics {
|
namespace ptprnt::graphics {
|
||||||
template <class T>
|
template <class T>
|
||||||
Bitmap<T>::Bitmap(uint16_t width, uint16_t height)
|
Bitmap<T>::Bitmap(uint16_t width, uint16_t height) : mWidth{width}, mHeight{height}, mPixels(width * height) {}
|
||||||
: mWidth{width}, mHeight{height}, mPixels(width * height) {}
|
|
||||||
|
|
||||||
template <class T>
|
template <class T>
|
||||||
uint16_t Bitmap<T>::getWidth() {
|
[[nodiscard]] uint16_t Bitmap<T>::getWidth() const {
|
||||||
return mWidth;
|
return mWidth;
|
||||||
}
|
}
|
||||||
|
|
||||||
template <class T>
|
template <class T>
|
||||||
uint16_t Bitmap<T>::getHeight() {
|
[[nodiscard]] uint16_t Bitmap<T>::getHeight() const {
|
||||||
return mHeight;
|
return mHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
template <class T>
|
template <class T>
|
||||||
bool Bitmap<T>::setPixels(const std::vector<T>& pixels) {
|
bool Bitmap<T>::setPixels(const std::vector<T>& pixels) {
|
||||||
if (pixels.size() != mPixels.size()) {
|
if (pixels.size() != mPixels.size()) {
|
||||||
spdlog::error("Invalid pixel buffer size.");
|
spdlog::error("Invalid pixel buffer size (got {} vs. {} bitmap size).", pixels.size(), mPixels.size());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,39 +51,34 @@ bool Bitmap<T>::setPixels(const std::vector<T>& pixels) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
template <class T>
|
template <class T>
|
||||||
std::vector<T> Bitmap<T>::getPixelsCpy() {
|
[[nodiscard]] std::vector<T> Bitmap<T>::getPixelsCpy() const {
|
||||||
return mPixels;
|
return mPixels;
|
||||||
}
|
}
|
||||||
|
|
||||||
template <class T>
|
template <class T>
|
||||||
std::optional<std::vector<T>> Bitmap<T>::getLine(uint16_t line) {
|
[[nodiscard]] std::vector<T> Bitmap<T>::getLine(const uint16_t lineNo) const {
|
||||||
if (line >= mHeight) {
|
if (lineNo >= mHeight) {
|
||||||
// out of bound
|
throw(std::out_of_range("Line is out of range!"));
|
||||||
return std::nullopt;
|
|
||||||
}
|
}
|
||||||
|
auto lineStart = mPixels.begin() + (lineNo * mWidth);
|
||||||
auto lineStart = mPixels.begin() + (line * mWidth);
|
auto lineEnd = mPixels.begin() + ((lineNo + 1) * mWidth);
|
||||||
auto lineEnd = mPixels.begin() + ((line + 1) * mWidth);
|
|
||||||
return std::vector<T>(lineStart, lineEnd);
|
return std::vector<T>(lineStart, lineEnd);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: I guess this is borked
|
||||||
template <class T>
|
template <class T>
|
||||||
std::optional<std::vector<T>> Bitmap<T>::getCol(uint16_t col) {
|
[[nodiscard]] std::vector<T> Bitmap<T>::getCol(const uint16_t colNo) const {
|
||||||
if (col >= mWidth) {
|
if (colNo >= mWidth) {
|
||||||
// out of bound
|
throw(std::out_of_range("Col is out of range!"));
|
||||||
return std::nullopt;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// first pixel is always beginning of the col
|
std::vector<T> col{};
|
||||||
std::vector<T> colPixels(mHeight);
|
col.reserve(mHeight);
|
||||||
auto it = std::next(mPixels.begin(), col);
|
for (size_t i{0}; i <= mPixels.size(); i++) {
|
||||||
|
if (i % mWidth == colNo) {
|
||||||
for (auto& colElement : colPixels) {
|
col.push_back(mPixels[i]);
|
||||||
colElement = *it;
|
}
|
||||||
std::advance(it, mWidth);
|
|
||||||
}
|
}
|
||||||
|
return col;
|
||||||
return colPixels;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace ptprnt::graphics
|
} // namespace ptprnt::graphics
|
@@ -19,19 +19,17 @@
|
|||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <stdint.h>
|
|
||||||
|
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <optional>
|
#include <span>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace ptprnt::graphics {
|
namespace ptprnt::graphics {
|
||||||
|
|
||||||
typedef uint8_t ALPHA8; // Alpha only, 8 bit per pixel
|
using ALPHA8 = std::uint8_t; // Alpha only, 8 bit per pixel
|
||||||
typedef uint32_t RGBX8; // RGB, least significant byte unused, 8 bit per channel
|
using RGBX8 = std::uint32_t; // RGB, least significant byte unused, 8 bit per channel
|
||||||
typedef uint32_t RGBA8; // RGB, least significant byte alpha, 8 bit per channel
|
using RGBA8 = std::uint32_t; // RGB, least significant byte alpha, 8 bit per channel
|
||||||
typedef uint32_t ARGB8; // RGB, most significant byte alpha, 8 bit per channel
|
using ARGB8 = std::uint32_t; // RGB, most significant byte alpha, 8 bit per channel
|
||||||
|
|
||||||
template <class T>
|
template <class T>
|
||||||
class Bitmap {
|
class Bitmap {
|
||||||
@@ -39,12 +37,18 @@ class Bitmap {
|
|||||||
Bitmap(uint16_t width, uint16_t height);
|
Bitmap(uint16_t width, uint16_t height);
|
||||||
~Bitmap() = default;
|
~Bitmap() = default;
|
||||||
|
|
||||||
uint16_t getWidth();
|
Bitmap(const Bitmap&) = default;
|
||||||
uint16_t getHeight();
|
Bitmap& operator=(const Bitmap&) = default;
|
||||||
|
Bitmap(Bitmap&&) = default;
|
||||||
|
Bitmap& operator=(Bitmap&&) = default;
|
||||||
|
|
||||||
|
[[nodiscard]] uint16_t getWidth() const;
|
||||||
|
[[nodiscard]] uint16_t getHeight() const;
|
||||||
bool setPixels(const std::vector<T>& pixels);
|
bool setPixels(const std::vector<T>& pixels);
|
||||||
std::vector<T> getPixelsCpy();
|
[[nodiscard]] std::vector<T> getPixelsCpy() const;
|
||||||
std::optional<std::vector<T>> getLine(uint16_t line);
|
[[nodiscard]] std::vector<T> getLine(uint16_t line) const;
|
||||||
std::optional<std::vector<T>> getCol(uint16_t col);
|
[[nodiscard]] std::vector<T> getCol(uint16_t col) const;
|
||||||
|
void visualize() const;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
uint16_t mWidth;
|
uint16_t mWidth;
|
||||||
|
@@ -1,57 +0,0 @@
|
|||||||
/*
|
|
||||||
ptrnt - print labels on linux
|
|
||||||
Copyright (C) 2023 Moritz Martinius
|
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
|
||||||
it under the terms of the GNU General Public License as published by
|
|
||||||
the Free Software Foundation, either version 3 of the License, or
|
|
||||||
(at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
GNU General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU General Public License
|
|
||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "Image.hpp"
|
|
||||||
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
#include "pango/pango-font.h"
|
|
||||||
|
|
||||||
namespace ptprnt::graphics {
|
|
||||||
Image::Image() {
|
|
||||||
mSurface = cairo_image_surface_create(CAIRO_FORMAT_A8, 512, 128);
|
|
||||||
cairo_t* cr = cairo_create(mSurface);
|
|
||||||
mFontDescription = pango_font_description_new();
|
|
||||||
pango_font_description_set_family(mFontDescription, "sans");
|
|
||||||
pango_font_description_set_weight(mFontDescription, PANGO_WEIGHT_SEMIBOLD);
|
|
||||||
pango_font_description_set_size(mFontDescription, 60 * PANGO_SCALE);
|
|
||||||
|
|
||||||
std::string printThis("Mist 💩");
|
|
||||||
|
|
||||||
mLayout = pango_cairo_create_layout(cr);
|
|
||||||
pango_layout_set_font_description(mLayout, mFontDescription);
|
|
||||||
pango_layout_set_text(mLayout, printThis.c_str(), -1);
|
|
||||||
|
|
||||||
cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
|
|
||||||
cairo_move_to(cr, 0.0, 94.0);
|
|
||||||
pango_cairo_show_layout_line(cr, pango_layout_get_line(mLayout, 0));
|
|
||||||
|
|
||||||
cairo_surface_write_to_png(mSurface, "hello.png");
|
|
||||||
}
|
|
||||||
|
|
||||||
uint8_t* Image::getRaw() {
|
|
||||||
cairo_surface_flush(mSurface);
|
|
||||||
return cairo_image_surface_get_data(mSurface);
|
|
||||||
}
|
|
||||||
|
|
||||||
Image::~Image() {
|
|
||||||
g_object_unref(mLayout);
|
|
||||||
pango_font_description_free(mFontDescription);
|
|
||||||
}
|
|
||||||
} // namespace ptprnt::graphics
|
|
@@ -1,38 +0,0 @@
|
|||||||
/*
|
|
||||||
ptrnt - print labels on linux
|
|
||||||
Copyright (C) 2023 Moritz Martinius
|
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
|
||||||
it under the terms of the GNU General Public License as published by
|
|
||||||
the Free Software Foundation, either version 3 of the License, or
|
|
||||||
(at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful,
|
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
||||||
GNU General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU General Public License
|
|
||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include <pango/pangocairo.h>
|
|
||||||
|
|
||||||
#include <cstdint>
|
|
||||||
|
|
||||||
namespace ptprnt::graphics {
|
|
||||||
class Image {
|
|
||||||
public:
|
|
||||||
Image();
|
|
||||||
~Image();
|
|
||||||
uint8_t* getRaw();
|
|
||||||
|
|
||||||
private:
|
|
||||||
PangoLayout* mLayout;
|
|
||||||
PangoFontDescription* mFontDescription;
|
|
||||||
cairo_surface_t* mSurface;
|
|
||||||
};
|
|
||||||
} // namespace ptprnt::graphics
|
|
186
src/graphics/Label.cpp
Normal file
186
src/graphics/Label.cpp
Normal file
@@ -0,0 +1,186 @@
|
|||||||
|
/*
|
||||||
|
ptrnt - print labels on linux
|
||||||
|
Copyright (C) 2023 Moritz Martinius
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "graphics/Label.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <spdlog/spdlog.h>
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "cairo.h"
|
||||||
|
#include "graphics/interface/ILabel.hpp"
|
||||||
|
#include "pango/pango-font.h"
|
||||||
|
#include "pango/pango-layout.h"
|
||||||
|
#include "pango/pango-types.h"
|
||||||
|
#include "pango/pangocairo.h"
|
||||||
|
|
||||||
|
namespace ptprnt::graphics {
|
||||||
|
Label::Label(const uint16_t heightPixel)
|
||||||
|
: mCairoCtx(cairo_create(mSurface)),
|
||||||
|
mPangoCtx(pango_cairo_create_context(mCairoCtx)),
|
||||||
|
mPangoLyt(pango_layout_new(mPangoCtx)),
|
||||||
|
mFontMap(pango_cairo_font_map_new()),
|
||||||
|
mPrinterHeight(heightPixel) {}
|
||||||
|
|
||||||
|
std::vector<uint8_t> Label::getRaw() {
|
||||||
|
assert(mSurface != nullptr);
|
||||||
|
size_t len = mPrinterHeight * mLayoutWidth;
|
||||||
|
|
||||||
|
cairo_surface_flush(mSurface);
|
||||||
|
auto data = cairo_image_surface_get_data(mSurface);
|
||||||
|
return {data, data + len};
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t Label::getNumLines(std::string_view strv) {
|
||||||
|
return std::count(strv.begin(), strv.end(), '\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
int Label::getWidth() {
|
||||||
|
return mPrinterHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
int Label::getHeight() {
|
||||||
|
return getLayoutWidth();
|
||||||
|
}
|
||||||
|
|
||||||
|
int Label::getLayoutHeight() {
|
||||||
|
return mLayoutHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
int Label::getLayoutWidth() {
|
||||||
|
return mLayoutWidth;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Label::create(PrintableText printableText) {
|
||||||
|
setFontFamily(printableText.fontFamily);
|
||||||
|
setFontSize(printableText.fontSize);
|
||||||
|
|
||||||
|
return create(printableText.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Label::create(const std::string& labelText) {
|
||||||
|
// TODO: we need to create a custom fontconfig here so that Noto Emoji does not load the systems default
|
||||||
|
// fontconfig here. For this, we need to create a PangoFcFontMap and a custom FcConfig
|
||||||
|
// see: https://docs.gtk.org/PangoFc/method.FontMap.set_config.html
|
||||||
|
// see: https://gist.github.com/CallumDev/7c66b3f9cf7a876ef75f
|
||||||
|
PangoFontDescription* regularFont = pango_font_description_new();
|
||||||
|
pango_font_description_set_size(regularFont, static_cast<int>(mFontSize * PANGO_SCALE));
|
||||||
|
pango_font_description_set_family(regularFont, mFontFamily.c_str());
|
||||||
|
//pango_layout_set_single_paragraph_mode(mPangoLyt, true); // this will force a single line in the label width width -1
|
||||||
|
pango_layout_set_height(mPangoLyt, getNumLines(labelText) * -1);
|
||||||
|
pango_layout_set_font_description(mPangoLyt, regularFont);
|
||||||
|
pango_layout_set_text(mPangoLyt, labelText.c_str(), static_cast<int>(labelText.length()));
|
||||||
|
|
||||||
|
// Set horizontal alignment
|
||||||
|
switch (mHAlign) {
|
||||||
|
case HAlignPosition::LEFT:
|
||||||
|
pango_layout_set_alignment(mPangoLyt, PANGO_ALIGN_LEFT);
|
||||||
|
break;
|
||||||
|
case HAlignPosition::RIGHT:
|
||||||
|
pango_layout_set_alignment(mPangoLyt, PANGO_ALIGN_RIGHT);
|
||||||
|
break;
|
||||||
|
case HAlignPosition::JUSTIFY:
|
||||||
|
pango_layout_set_alignment(mPangoLyt, PANGO_ALIGN_LEFT); // not sure if needed
|
||||||
|
pango_layout_set_justify(mPangoLyt, true);
|
||||||
|
// only enabled in pango 1.50 and greater
|
||||||
|
#if PANGO_VERSION_MAJOR >= 1 && PANGO_VERSION_MINOR >= 50
|
||||||
|
pango_layout_set_justify_last_line(mPangoLyt, true);
|
||||||
|
#endif
|
||||||
|
break;
|
||||||
|
case HAlignPosition::CENTER:
|
||||||
|
[[fallthrough]];
|
||||||
|
default:
|
||||||
|
pango_layout_set_alignment(mPangoLyt, PANGO_ALIGN_CENTER);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// calculate label size for Cairo surface creation
|
||||||
|
pango_layout_get_size(mPangoLyt, &mLayoutWidth, &mLayoutHeight);
|
||||||
|
mLayoutWidth /= PANGO_SCALE;
|
||||||
|
mLayoutHeight /= PANGO_SCALE;
|
||||||
|
|
||||||
|
spdlog::debug("Layout width: {}, height: {}", mLayoutWidth, mLayoutHeight);
|
||||||
|
auto alignedWidth = mLayoutWidth + (8 - (mLayoutWidth % 8));
|
||||||
|
|
||||||
|
mSurface = cairo_image_surface_create(CAIRO_FORMAT_A8, alignedWidth, mPrinterHeight);
|
||||||
|
cairo_t* cr = cairo_create(mSurface);
|
||||||
|
|
||||||
|
// Adjust Cairo cursor position to respect the vertical alignment
|
||||||
|
switch (mVAlign) {
|
||||||
|
case VAlignPosition::TOP:
|
||||||
|
break;
|
||||||
|
case VAlignPosition::BOTTOM:
|
||||||
|
cairo_move_to(cr, 0.0, mPrinterHeight - mLayoutHeight);
|
||||||
|
break;
|
||||||
|
case VAlignPosition::MIDDLE:
|
||||||
|
cairo_move_to(cr, 0.0, (mPrinterHeight - mLayoutHeight) / 2);
|
||||||
|
[[fallthrough]];
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finally show the layout on the Cairo surface
|
||||||
|
pango_cairo_show_layout(cr, mPangoLyt);
|
||||||
|
|
||||||
|
cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
|
||||||
|
cairo_surface_flush(mSurface);
|
||||||
|
cairo_destroy(cr);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Label::writeToPng(const std::string& file) {
|
||||||
|
if (mSurface) {
|
||||||
|
cairo_surface_flush(mSurface);
|
||||||
|
cairo_surface_write_to_png(mSurface, file.c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void Label::setFontSize(const double fontSize) {
|
||||||
|
mFontSize = fontSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Label::setFontFamily(const std::string& fontFamily) {
|
||||||
|
mFontFamily = fontFamily;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Label::setHAlign(HAlignPosition hAlign) {
|
||||||
|
mHAlign = hAlign;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Label::setVAlign(VAlignPosition vAlign) {
|
||||||
|
mVAlign = vAlign;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Label::setText(const std::string& text) {
|
||||||
|
mText = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
Label::~Label() {
|
||||||
|
spdlog::debug("Image dtor...");
|
||||||
|
g_object_unref(mPangoCtx);
|
||||||
|
g_object_unref(mPangoLyt);
|
||||||
|
g_object_unref(mFontMap);
|
||||||
|
cairo_surface_destroy(mSurface);
|
||||||
|
}
|
||||||
|
} // namespace ptprnt::graphics
|
78
src/graphics/Label.hpp
Normal file
78
src/graphics/Label.hpp
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
/*
|
||||||
|
ptrnt - print labels on linux
|
||||||
|
Copyright (C) 2023 Moritz Martinius
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <pango/pangocairo.h>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "cairo.h"
|
||||||
|
#include "graphics/interface/ILabel.hpp"
|
||||||
|
#include "pango/pango-types.h"
|
||||||
|
|
||||||
|
namespace ptprnt::graphics {
|
||||||
|
|
||||||
|
class Label : public ILabel {
|
||||||
|
public:
|
||||||
|
Label(const uint16_t heightPixel);
|
||||||
|
~Label() override;
|
||||||
|
|
||||||
|
Label(const Label&) = delete;
|
||||||
|
Label& operator=(const Label&) = delete;
|
||||||
|
Label(Label&&) = delete;
|
||||||
|
Label& operator=(Label&&) = delete;
|
||||||
|
|
||||||
|
bool create(PrintableText printableText) override;
|
||||||
|
bool create(const std::string& labelText) override;
|
||||||
|
void writeToPng(const std::string& file);
|
||||||
|
[[nodiscard]] int getWidth() override;
|
||||||
|
[[nodiscard]] int getHeight() override;
|
||||||
|
[[nodiscard]] int getLayoutWidth() override;
|
||||||
|
[[nodiscard]] int getLayoutHeight() override;
|
||||||
|
[[nodiscard]] std::vector<uint8_t> getRaw() override;
|
||||||
|
void setFontSize(const double fontSize) override;
|
||||||
|
void setFontFamily(const std::string& fontFamily) override;
|
||||||
|
|
||||||
|
void setText(const std::string& text) override;
|
||||||
|
void setHAlign(HAlignPosition hpos) override;
|
||||||
|
void setVAlign(VAlignPosition vpos) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
// methods
|
||||||
|
[[nodiscard]] uint8_t getNumLines(std::string_view str);
|
||||||
|
[[nodiscard]] PangoFontMap* createCustomFontMap();
|
||||||
|
// members
|
||||||
|
// TODO: convert raw pointers here into std::unique_ptr with custom deleters, calling g_object_unref()
|
||||||
|
cairo_surface_t* mSurface{nullptr};
|
||||||
|
cairo_t* mCairoCtx{nullptr};
|
||||||
|
PangoContext* mPangoCtx{nullptr};
|
||||||
|
PangoLayout* mPangoLyt{nullptr};
|
||||||
|
PangoFontMap* mFontMap{nullptr};
|
||||||
|
double mFontSize{DEFAULT_FONT_SIZE};
|
||||||
|
std::string mFontFamily{DEFAULT_FONT_FAMILY};
|
||||||
|
HAlignPosition mHAlign = HAlignPosition::LEFT;
|
||||||
|
VAlignPosition mVAlign = VAlignPosition::MIDDLE;
|
||||||
|
std::string mText{""};
|
||||||
|
int mLayoutWidth = 0, mLayoutHeight = 0;
|
||||||
|
int mPrinterHeight = 0;
|
||||||
|
};
|
||||||
|
} // namespace ptprnt::graphics
|
@@ -21,11 +21,15 @@
|
|||||||
|
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
|
|
||||||
#include <cstdint>
|
#include <iostream>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace ptprnt::graphics {
|
namespace ptprnt::graphics {
|
||||||
Monochrome::Monochrome(const std::vector<uint8_t>& grayscale) : mPixels(std::move(grayscale)) {}
|
Monochrome::Monochrome(const std::vector<uint8_t>& grayscale, uint32_t width, uint32_t height)
|
||||||
|
: mPixels(grayscale), mWidth(width), mHeight(height) {}
|
||||||
|
|
||||||
|
Monochrome::Monochrome(const std::span<uint8_t> grayscale, uint32_t width, uint32_t height)
|
||||||
|
: mPixels(grayscale.begin(), grayscale.end()), mWidth(width), mHeight(height) {}
|
||||||
|
|
||||||
void Monochrome::setThreshold(uint8_t threshhold) {
|
void Monochrome::setThreshold(uint8_t threshhold) {
|
||||||
mThreshhold = threshhold;
|
mThreshhold = threshhold;
|
||||||
@@ -36,24 +40,206 @@ void Monochrome::invert(bool shouldInvert) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> Monochrome::get() {
|
std::vector<uint8_t> Monochrome::get() {
|
||||||
std::vector<uint8_t> outPixels(
|
// Calculate output size for packed format: (width + 7) / 8 bytes per row
|
||||||
(static_cast<unsigned int>((mPixels.size() / 8)) + (std::floor(mPixels.size() % 8 + 0.9))));
|
uint32_t stride = (mWidth + 7) / 8;
|
||||||
|
size_t outputSize = stride * mHeight;
|
||||||
|
std::vector<uint8_t> outPixels(outputSize, 0);
|
||||||
|
|
||||||
unsigned int outIndex = 0;
|
// Pack pixels row by row for correct 2D layout
|
||||||
|
for (uint32_t y = 0; y < mHeight; ++y) {
|
||||||
|
for (uint32_t x = 0; x < mWidth; ++x) {
|
||||||
|
size_t pixelIndex = y * mWidth + x; // Row-major index in input
|
||||||
|
size_t byteIndex = y * stride + x / 8; // Byte index in packed output
|
||||||
|
size_t bitIndex = 7 - (x % 8); // MSB first
|
||||||
|
|
||||||
for (unsigned int byteNum = 0; byteNum < mPixels.size(); byteNum += 8) {
|
// Convert grayscale pixel to bit based on threshold
|
||||||
for (unsigned int bitNo = 0; bitNo < 8; bitNo++) {
|
bool pixelOn = mPixels[pixelIndex] > mThreshhold;
|
||||||
if (mPixels[byteNum + bitNo] > mThreshhold) {
|
if (mShouldInvert) {
|
||||||
outPixels[outIndex] |= (1 << (7 - bitNo));
|
pixelOn = !pixelOn;
|
||||||
} else {
|
}
|
||||||
outPixels[outIndex] &= ~(1 << (7 - bitNo));
|
|
||||||
|
if (pixelOn) {
|
||||||
|
outPixels[byteIndex] |= (1 << bitIndex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (mShouldInvert) {
|
|
||||||
outPixels[outIndex] = ~outPixels[outIndex];
|
|
||||||
}
|
|
||||||
outIndex++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return outPixels;
|
return outPixels;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void Monochrome::visualize() {
|
||||||
|
auto mono = get();
|
||||||
|
for (unsigned char pix : mono) {
|
||||||
|
std::cout << ((pix & (1 << 7)) == 0 ? "." : "x");
|
||||||
|
std::cout << ((pix & (1 << 6)) == 0 ? "." : "x");
|
||||||
|
std::cout << ((pix & (1 << 5)) == 0 ? "." : "x");
|
||||||
|
std::cout << ((pix & (1 << 4)) == 0 ? "." : "x");
|
||||||
|
std::cout << ((pix & (1 << 3)) == 0 ? "." : "x");
|
||||||
|
std::cout << ((pix & (1 << 2)) == 0 ? "." : "x");
|
||||||
|
std::cout << ((pix & (1 << 1)) == 0 ? "." : "x");
|
||||||
|
std::cout << ((pix & (1 << 0)) == 0 ? "." : "x");
|
||||||
|
}
|
||||||
|
std::cout << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
MonochromeData Monochrome::getMonochromeData() {
|
||||||
|
auto processedBytes = get();
|
||||||
|
// Calculate stride based on packed monochrome data (1 bit per pixel, 8 pixels per byte)
|
||||||
|
auto stride = static_cast<uint32_t>((mWidth + 7) / 8);
|
||||||
|
return {std::move(processedBytes), stride, Orientation::LANDSCAPE, mWidth, mHeight};
|
||||||
|
}
|
||||||
|
|
||||||
|
// MonochromeData transformation methods implementation
|
||||||
|
void MonochromeData::transformTo(Orientation targetOrientation) {
|
||||||
|
if (orientation == targetOrientation) {
|
||||||
|
return; // No transformation needed
|
||||||
|
}
|
||||||
|
|
||||||
|
auto rotatedData = createRotatedData(targetOrientation);
|
||||||
|
bytes = std::move(rotatedData);
|
||||||
|
|
||||||
|
// Update dimensions and stride based on rotation
|
||||||
|
switch (targetOrientation) {
|
||||||
|
case Orientation::PORTRAIT:
|
||||||
|
case Orientation::PORTRAIT_FLIPPED:
|
||||||
|
// Swap width and height for portrait orientations
|
||||||
|
std::swap(width, height);
|
||||||
|
stride = (width + 7) / 8; // Recalculate stride for new width
|
||||||
|
break;
|
||||||
|
case Orientation::LANDSCAPE:
|
||||||
|
case Orientation::LANDSCAPE_FLIPPED:
|
||||||
|
// Keep original stride calculation
|
||||||
|
stride = (width + 7) / 8;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
orientation = targetOrientation;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool MonochromeData::getBit(uint32_t x, uint32_t y) const {
|
||||||
|
if (x >= width || y >= height) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t byteIndex = y * stride + x / 8;
|
||||||
|
uint32_t bitIndex = 7 - (x % 8); // MSB first
|
||||||
|
|
||||||
|
if (byteIndex >= bytes.size()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (bytes[byteIndex] >> bitIndex) & 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
void MonochromeData::setBit(uint32_t x, uint32_t y, bool value) {
|
||||||
|
if (x >= width || y >= height) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t byteIndex = y * stride + x / 8;
|
||||||
|
uint32_t bitIndex = 7 - (x % 8); // MSB first
|
||||||
|
|
||||||
|
if (byteIndex >= bytes.size()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value) {
|
||||||
|
bytes[byteIndex] |= (1 << bitIndex);
|
||||||
|
} else {
|
||||||
|
bytes[byteIndex] &= ~(1 << bitIndex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<uint8_t> MonochromeData::createRotatedData(Orientation targetOrientation) const {
|
||||||
|
uint32_t newWidth, newHeight;
|
||||||
|
|
||||||
|
// Determine new dimensions
|
||||||
|
switch (targetOrientation) {
|
||||||
|
case Orientation::PORTRAIT:
|
||||||
|
case Orientation::PORTRAIT_FLIPPED:
|
||||||
|
newWidth = height;
|
||||||
|
newHeight = width;
|
||||||
|
break;
|
||||||
|
case Orientation::LANDSCAPE:
|
||||||
|
case Orientation::LANDSCAPE_FLIPPED:
|
||||||
|
default:
|
||||||
|
newWidth = width;
|
||||||
|
newHeight = height;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t newStride = (newWidth + 7) / 8;
|
||||||
|
std::vector<uint8_t> newBytes(newStride * newHeight, 0);
|
||||||
|
|
||||||
|
// Create a temporary MonochromeData for the new image
|
||||||
|
MonochromeData tempData;
|
||||||
|
tempData.bytes = std::move(newBytes);
|
||||||
|
tempData.stride = newStride;
|
||||||
|
tempData.width = newWidth;
|
||||||
|
tempData.height = newHeight;
|
||||||
|
tempData.orientation = targetOrientation;
|
||||||
|
|
||||||
|
// Copy pixels with appropriate transformation
|
||||||
|
for (uint32_t y = 0; y < height; ++y) {
|
||||||
|
for (uint32_t x = 0; x < width; ++x) {
|
||||||
|
bool pixel = getBit(x, y);
|
||||||
|
uint32_t newX, newY;
|
||||||
|
|
||||||
|
switch (targetOrientation) {
|
||||||
|
case Orientation::LANDSCAPE:
|
||||||
|
newX = x;
|
||||||
|
newY = y;
|
||||||
|
break;
|
||||||
|
case Orientation::PORTRAIT: // 90 degrees clockwise
|
||||||
|
newX = height - 1 - y;
|
||||||
|
newY = x;
|
||||||
|
break;
|
||||||
|
case Orientation::LANDSCAPE_FLIPPED: // 180 degrees
|
||||||
|
newX = width - 1 - x;
|
||||||
|
newY = height - 1 - y;
|
||||||
|
break;
|
||||||
|
case Orientation::PORTRAIT_FLIPPED: // 270 degrees clockwise
|
||||||
|
newX = y;
|
||||||
|
newY = width - 1 - x;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
tempData.setBit(newX, newY, pixel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return std::move(tempData.bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MonochromeData::visualize() const {
|
||||||
|
std::cout << "MonochromeData visualization (" << width << "x" << height << ", orientation: ";
|
||||||
|
|
||||||
|
switch (orientation) {
|
||||||
|
case Orientation::LANDSCAPE:
|
||||||
|
std::cout << "LANDSCAPE";
|
||||||
|
break;
|
||||||
|
case Orientation::PORTRAIT:
|
||||||
|
std::cout << "PORTRAIT";
|
||||||
|
break;
|
||||||
|
case Orientation::LANDSCAPE_FLIPPED:
|
||||||
|
std::cout << "LANDSCAPE_FLIPPED";
|
||||||
|
break;
|
||||||
|
case Orientation::PORTRAIT_FLIPPED:
|
||||||
|
std::cout << "PORTRAIT_FLIPPED";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::cout << "):" << std::endl;
|
||||||
|
|
||||||
|
// Print the image row by row
|
||||||
|
for (uint32_t y = 0; y < height; ++y) {
|
||||||
|
for (uint32_t x = 0; x < width; ++x) {
|
||||||
|
bool pixel = getBit(x, y);
|
||||||
|
std::cout << (pixel ? "█" : ".");
|
||||||
|
}
|
||||||
|
std::cout << std::endl;
|
||||||
|
}
|
||||||
|
std::cout << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace ptprnt::graphics
|
} // namespace ptprnt::graphics
|
@@ -20,22 +20,62 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
|
#include <span>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#include "graphics/Bitmap.hpp"
|
#include "graphics/Bitmap.hpp"
|
||||||
|
|
||||||
namespace ptprnt::graphics {
|
namespace ptprnt::graphics {
|
||||||
|
|
||||||
|
enum class Orientation {
|
||||||
|
LANDSCAPE = 0, // 0 degrees
|
||||||
|
PORTRAIT = 1, // 90 degrees clockwise
|
||||||
|
LANDSCAPE_FLIPPED = 2, // 180 degrees
|
||||||
|
PORTRAIT_FLIPPED = 3 // 270 degrees clockwise (90 counter-clockwise)
|
||||||
|
};
|
||||||
|
|
||||||
|
struct MonochromeData {
|
||||||
|
std::vector<uint8_t> bytes;
|
||||||
|
uint32_t stride;
|
||||||
|
Orientation orientation;
|
||||||
|
uint32_t width; // Width in pixels
|
||||||
|
uint32_t height; // Height in pixels
|
||||||
|
|
||||||
|
MonochromeData() : stride(0), orientation(Orientation::LANDSCAPE), width(0), height(0) {}
|
||||||
|
|
||||||
|
MonochromeData(std::vector<uint8_t> data, uint32_t stride_bytes, Orientation orient = Orientation::LANDSCAPE,
|
||||||
|
uint32_t w = 0, uint32_t h = 0)
|
||||||
|
: bytes(std::move(data)), stride(stride_bytes), orientation(orient), width(w), height(h) {}
|
||||||
|
|
||||||
|
// Transform the image data to the target orientation
|
||||||
|
void transformTo(Orientation targetOrientation);
|
||||||
|
|
||||||
|
// Visualize the monochrome data on stdout
|
||||||
|
void visualize() const;
|
||||||
|
|
||||||
|
// Helper methods for orientation transformations
|
||||||
|
[[nodiscard]] bool getBit(uint32_t x, uint32_t y) const;
|
||||||
|
void setBit(uint32_t x, uint32_t y, bool value);
|
||||||
|
[[nodiscard]] std::vector<uint8_t> createRotatedData(Orientation targetOrientation) const;
|
||||||
|
};
|
||||||
|
|
||||||
class Monochrome {
|
class Monochrome {
|
||||||
public:
|
public:
|
||||||
Monochrome(const std::vector<uint8_t>& grayscale);
|
Monochrome(const std::vector<uint8_t>& grayscale, uint32_t width, uint32_t height);
|
||||||
|
Monochrome(const std::span<uint8_t> grayscale, uint32_t width, uint32_t height);
|
||||||
~Monochrome() = default;
|
~Monochrome() = default;
|
||||||
|
|
||||||
void setThreshold(uint8_t);
|
void setThreshold(uint8_t);
|
||||||
void invert(bool shouldInvert);
|
void invert(bool shouldInvert);
|
||||||
|
void visualize();
|
||||||
std::vector<uint8_t> get();
|
std::vector<uint8_t> get();
|
||||||
|
MonochromeData getMonochromeData();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
const std::vector<uint8_t>& mPixels;
|
std::vector<uint8_t> mPixels;
|
||||||
uint8_t mThreshhold = 127;
|
uint32_t mWidth;
|
||||||
|
uint32_t mHeight;
|
||||||
|
uint8_t mThreshhold = UINT8_MAX / 2;
|
||||||
bool mShouldInvert = false;
|
bool mShouldInvert = false;
|
||||||
};
|
};
|
||||||
} // namespace ptprnt::graphics
|
} // namespace ptprnt::graphics
|
82
src/graphics/interface/ILabel.hpp
Normal file
82
src/graphics/interface/ILabel.hpp
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
/*
|
||||||
|
ptrnt - print labels on linux
|
||||||
|
Copyright (C) 2023 Moritz Martinius
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
constexpr const char* DEFAULT_FONT_FAMILY = "sans";
|
||||||
|
constexpr const double DEFAULT_FONT_SIZE = 32.0;
|
||||||
|
|
||||||
|
enum class HAlignPosition {
|
||||||
|
UNKNOWN = 0,
|
||||||
|
LEFT = 1,
|
||||||
|
CENTER = 2,
|
||||||
|
RIGHT = 3,
|
||||||
|
JUSTIFY = 4,
|
||||||
|
};
|
||||||
|
const std::map<std::string, HAlignPosition> HALignPositionMap{{"", HAlignPosition::UNKNOWN},
|
||||||
|
{"left", HAlignPosition::LEFT},
|
||||||
|
{"center", HAlignPosition::CENTER},
|
||||||
|
{"right", HAlignPosition::RIGHT},
|
||||||
|
{"justify", HAlignPosition::JUSTIFY}};
|
||||||
|
|
||||||
|
enum class VAlignPosition {
|
||||||
|
UNKNOWN = 0,
|
||||||
|
TOP = 1,
|
||||||
|
MIDDLE = 2,
|
||||||
|
BOTTOM = 3,
|
||||||
|
};
|
||||||
|
|
||||||
|
const std::map<std::string, VAlignPosition> VALignPositionMap{{"", VAlignPosition::UNKNOWN},
|
||||||
|
{"top", VAlignPosition::TOP},
|
||||||
|
{"middle", VAlignPosition::MIDDLE},
|
||||||
|
{"bottom", VAlignPosition::BOTTOM}};
|
||||||
|
|
||||||
|
struct PrintableText {
|
||||||
|
std::string text{""};
|
||||||
|
std::string fontFamily{DEFAULT_FONT_FAMILY};
|
||||||
|
double fontSize{DEFAULT_FONT_SIZE};
|
||||||
|
HAlignPosition hAlign{HAlignPosition::LEFT};
|
||||||
|
VAlignPosition vAlign{VAlignPosition::MIDDLE};
|
||||||
|
};
|
||||||
|
|
||||||
|
namespace ptprnt::graphics {
|
||||||
|
class ILabel {
|
||||||
|
public:
|
||||||
|
virtual ~ILabel() = default;
|
||||||
|
|
||||||
|
virtual bool create(PrintableText printableText) = 0;
|
||||||
|
virtual bool create(const std::string& labelText) = 0;
|
||||||
|
virtual std::vector<uint8_t> getRaw() = 0;
|
||||||
|
virtual int getWidth() = 0;
|
||||||
|
virtual int getHeight() = 0;
|
||||||
|
virtual int getLayoutWidth() = 0;
|
||||||
|
virtual int getLayoutHeight() = 0;
|
||||||
|
|
||||||
|
virtual void setText(const std::string& text) = 0;
|
||||||
|
virtual void setFontSize(const double fontSize) = 0;
|
||||||
|
virtual void setFontFamily(const std::string& fontFamily) = 0;
|
||||||
|
virtual void setHAlign(HAlignPosition hpos) = 0;
|
||||||
|
virtual void setVAlign(VAlignPosition vpos) = 0;
|
||||||
|
};
|
||||||
|
} // namespace ptprnt::graphics
|
@@ -19,16 +19,16 @@
|
|||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <cstdint>
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
|
||||||
#include "graphics/Bitmap.hpp"
|
#include "graphics/Bitmap.hpp"
|
||||||
|
#include "graphics/Monochrome.hpp"
|
||||||
|
#include "graphics/interface/ILabel.hpp"
|
||||||
#include "interface/IPrinterTypes.hpp"
|
#include "interface/IPrinterTypes.hpp"
|
||||||
#include "libusbwrap/interface/IUsbDevice.hpp"
|
#include "libusbwrap/interface/IUsbDevice.hpp"
|
||||||
|
|
||||||
namespace ptprnt {
|
namespace ptprnt {
|
||||||
|
|
||||||
class IPrinterDriver {
|
class IPrinterDriver {
|
||||||
public:
|
public:
|
||||||
virtual ~IPrinterDriver() = default;
|
virtual ~IPrinterDriver() = default;
|
||||||
@@ -40,12 +40,9 @@ class IPrinterDriver {
|
|||||||
[[nodiscard]] virtual const PrinterStatus getPrinterStatus() = 0;
|
[[nodiscard]] virtual const PrinterStatus getPrinterStatus() = 0;
|
||||||
virtual bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) = 0;
|
virtual bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) = 0;
|
||||||
virtual bool detachUsbDevice() = 0;
|
virtual bool detachUsbDevice() = 0;
|
||||||
virtual bool setText(const std::string& text) = 0;
|
|
||||||
virtual bool setFont(const std::string& text) = 0;
|
|
||||||
virtual bool setFontSize(uint8_t fontSize) = 0;
|
|
||||||
virtual bool setHAlign(HAlignPosition hpos) = 0;
|
|
||||||
virtual bool setVAlign(VAlignPosition vpos) = 0;
|
|
||||||
virtual bool printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) = 0;
|
virtual bool printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) = 0;
|
||||||
|
virtual bool printMonochromeData(const graphics::MonochromeData& data) = 0;
|
||||||
|
virtual bool printLabel(const std::unique_ptr<graphics::ILabel> label) = 0;
|
||||||
virtual bool print() = 0;
|
virtual bool print() = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@@ -22,6 +22,7 @@
|
|||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#include "libusbwrap/LibUsbTypes.hpp"
|
#include "libusbwrap/LibUsbTypes.hpp"
|
||||||
|
|
||||||
@@ -32,6 +33,7 @@ struct PrinterInfo {
|
|||||||
std::string_view name = "";
|
std::string_view name = "";
|
||||||
std::string_view version = "";
|
std::string_view version = "";
|
||||||
libusbwrap::usbId usbId{0x00, 0x00};
|
libusbwrap::usbId usbId{0x00, 0x00};
|
||||||
|
uint16_t pixelLines = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct PrinterStatus {
|
struct PrinterStatus {
|
||||||
@@ -39,27 +41,6 @@ struct PrinterStatus {
|
|||||||
unsigned int tapeWidthMm = 0.0;
|
unsigned int tapeWidthMm = 0.0;
|
||||||
};
|
};
|
||||||
|
|
||||||
enum class HAlignPosition {
|
using cmd_T = std::vector<uint8_t>;
|
||||||
UNKNOWN = 0,
|
|
||||||
LEFT = 1,
|
|
||||||
CENTER = 2,
|
|
||||||
RIGHT = 3,
|
|
||||||
JUSTIFY = 4,
|
|
||||||
};
|
|
||||||
|
|
||||||
enum class VAlignPosition {
|
|
||||||
UNKNOWN = 0,
|
|
||||||
TOP = 1,
|
|
||||||
MIDDLE = 2,
|
|
||||||
BOTTOM = 3,
|
|
||||||
};
|
|
||||||
|
|
||||||
struct PrintableText {
|
|
||||||
std::string text{""};
|
|
||||||
std::string font{"Noto"};
|
|
||||||
uint8_t fontSize{0};
|
|
||||||
HAlignPosition hAlign{HAlignPosition::LEFT};
|
|
||||||
VAlignPosition vAlign{VAlignPosition::MIDDLE};
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace ptprnt
|
} // namespace ptprnt
|
@@ -27,12 +27,12 @@
|
|||||||
#include "libusbwrap/interface/IUsbDevice.hpp"
|
#include "libusbwrap/interface/IUsbDevice.hpp"
|
||||||
|
|
||||||
namespace libusbwrap {
|
namespace libusbwrap {
|
||||||
UsbDevice::UsbDevice(libusb_context* ctx, libusb_device* dev) : mLibusbCtx(ctx), mLibusbDev(dev) {
|
UsbDevice::UsbDevice(libusb_context* ctx, usbDevice_ptr dev) : mLibusbCtx(ctx), mLibusbDev(std::move(dev)) {
|
||||||
if (mLibusbCtx == nullptr || mLibusbDev == nullptr) {
|
if (mLibusbCtx == nullptr || mLibusbDev == nullptr) {
|
||||||
throw std::invalid_argument("ctx or device are nullptr");
|
throw std::invalid_argument("ctx or device are nullptr");
|
||||||
}
|
}
|
||||||
|
|
||||||
libusb_get_device_descriptor(dev, &mLibusbDevDesc);
|
libusb_get_device_descriptor(mLibusbDev.get(), &mLibusbDevDesc);
|
||||||
}
|
}
|
||||||
|
|
||||||
UsbDevice::~UsbDevice() {
|
UsbDevice::~UsbDevice() {
|
||||||
@@ -44,7 +44,7 @@ UsbDevice::~UsbDevice() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool UsbDevice::open() {
|
bool UsbDevice::open() {
|
||||||
int openStatus = libusb_open(mLibusbDev, &mLibusbDevHandle);
|
int openStatus = libusb_open(mLibusbDev.get(), &mLibusbDevHandle);
|
||||||
if (openStatus != 0) {
|
if (openStatus != 0) {
|
||||||
mLastError = static_cast<Error>(openStatus);
|
mLastError = static_cast<Error>(openStatus);
|
||||||
return false;
|
return false;
|
||||||
@@ -90,13 +90,12 @@ bool UsbDevice::releaseInterface(int interfaceNo) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool UsbDevice::bulkTransfer(uint8_t endpoint, std::vector<uint8_t>& data, int* tx,
|
bool UsbDevice::bulkTransfer(uint8_t endpoint, const std::vector<uint8_t>& data, int* tx, unsigned int timeout) {
|
||||||
unsigned int timeout) {
|
|
||||||
// TODO: implement error handling for incomplete transactions (tx length != data length)
|
// TODO: implement error handling for incomplete transactions (tx length != data length)
|
||||||
int bulkTransferStatus = 0;
|
int bulkTransferStatus = 0;
|
||||||
|
|
||||||
bulkTransferStatus =
|
bulkTransferStatus = libusb_bulk_transfer(mLibusbDevHandle, endpoint, const_cast<unsigned char*>(data.data()),
|
||||||
libusb_bulk_transfer(mLibusbDevHandle, endpoint, data.data(), data.size(), tx, timeout);
|
data.size(), tx, timeout);
|
||||||
if (bulkTransferStatus != 0) {
|
if (bulkTransferStatus != 0) {
|
||||||
mLastError = static_cast<Error>(bulkTransferStatus);
|
mLastError = static_cast<Error>(bulkTransferStatus);
|
||||||
return false;
|
return false;
|
||||||
@@ -109,15 +108,15 @@ const usbId UsbDevice::getUsbId() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const device::Speed UsbDevice::getSpeed() {
|
const device::Speed UsbDevice::getSpeed() {
|
||||||
return static_cast<device::Speed>(libusb_get_device_speed(mLibusbDev));
|
return static_cast<device::Speed>(libusb_get_device_speed(mLibusbDev.get()));
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t UsbDevice::getBusNumber() {
|
const uint8_t UsbDevice::getBusNumber() {
|
||||||
return libusb_get_bus_number(mLibusbDev);
|
return libusb_get_bus_number(mLibusbDev.get());
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t UsbDevice::getPortNumber() {
|
const uint8_t UsbDevice::getPortNumber() {
|
||||||
return libusb_get_port_number(mLibusbDev);
|
return libusb_get_port_number(mLibusbDev.get());
|
||||||
}
|
}
|
||||||
|
|
||||||
const Error UsbDevice::getLastError() {
|
const Error UsbDevice::getLastError() {
|
||||||
|
@@ -20,21 +20,34 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <cstddef>
|
#include <memory>
|
||||||
|
|
||||||
#include "libusb.h"
|
#include "libusb.h"
|
||||||
#include "libusbwrap/LibUsbTypes.hpp"
|
#include "libusbwrap/LibUsbTypes.hpp"
|
||||||
#include "libusbwrap/interface/IUsbDevice.hpp"
|
#include "libusbwrap/interface/IUsbDevice.hpp"
|
||||||
|
|
||||||
namespace libusbwrap {
|
namespace libusbwrap {
|
||||||
|
|
||||||
|
struct usbDevice_deleter {
|
||||||
|
void operator()(libusb_device* dev_ptr) const {
|
||||||
|
if (nullptr != dev_ptr) {
|
||||||
|
libusb_unref_device(dev_ptr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
using usbDevice_ptr = std::unique_ptr<libusb_device, usbDevice_deleter>;
|
||||||
|
|
||||||
class UsbDevice : public IUsbDevice {
|
class UsbDevice : public IUsbDevice {
|
||||||
public:
|
public:
|
||||||
explicit UsbDevice(libusb_context* ctx, libusb_device* dev);
|
explicit UsbDevice(libusb_context* ctx, usbDevice_ptr dev);
|
||||||
~UsbDevice() override;
|
~UsbDevice() override;
|
||||||
|
|
||||||
// delete copy ctor and assignment
|
// delete copy ctor and assignment
|
||||||
UsbDevice(const UsbDevice&) = delete;
|
UsbDevice(const UsbDevice&) = delete;
|
||||||
UsbDevice& operator=(UsbDevice&) = delete;
|
UsbDevice& operator=(const UsbDevice&) = delete;
|
||||||
|
UsbDevice(UsbDevice&&) = delete;
|
||||||
|
UsbDevice& operator=(UsbDevice&&) = delete;
|
||||||
|
|
||||||
bool open() override;
|
bool open() override;
|
||||||
void close() override;
|
void close() override;
|
||||||
@@ -43,8 +56,7 @@ class UsbDevice : public IUsbDevice {
|
|||||||
bool detachKernelDriver(int interfaceNo) override;
|
bool detachKernelDriver(int interfaceNo) override;
|
||||||
bool claimInterface(int interfaceNo) override;
|
bool claimInterface(int interfaceNo) override;
|
||||||
bool releaseInterface(int interfaceNo) override;
|
bool releaseInterface(int interfaceNo) override;
|
||||||
bool bulkTransfer(uint8_t endpoint, std::vector<uint8_t>& data, int* tx,
|
bool bulkTransfer(uint8_t endpoint, const std::vector<uint8_t>& data, int* tx, unsigned int timeout) override;
|
||||||
unsigned int timeout) override;
|
|
||||||
|
|
||||||
// getters
|
// getters
|
||||||
const usbId getUsbId() override;
|
const usbId getUsbId() override;
|
||||||
@@ -58,9 +70,9 @@ class UsbDevice : public IUsbDevice {
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
libusb_context* mLibusbCtx{nullptr};
|
libusb_context* mLibusbCtx{nullptr};
|
||||||
libusb_device* mLibusbDev{nullptr};
|
usbDevice_ptr mLibusbDev{nullptr};
|
||||||
libusb_device_handle* mLibusbDevHandle{nullptr};
|
libusb_device_handle* mLibusbDevHandle{nullptr};
|
||||||
libusb_device_descriptor mLibusbDevDesc;
|
libusb_device_descriptor mLibusbDevDesc{0};
|
||||||
std::atomic<bool> mIsOpen = false;
|
std::atomic<bool> mIsOpen = false;
|
||||||
Error mLastError = Error::SUCCESS;
|
Error mLastError = Error::SUCCESS;
|
||||||
};
|
};
|
||||||
|
@@ -20,9 +20,11 @@
|
|||||||
#include "libusbwrap/UsbDeviceFactory.hpp"
|
#include "libusbwrap/UsbDeviceFactory.hpp"
|
||||||
|
|
||||||
#include <spdlog/spdlog.h>
|
#include <spdlog/spdlog.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#include "libusb.h"
|
#include "libusb.h"
|
||||||
#include "libusbwrap/UsbDevice.hpp"
|
#include "libusbwrap/UsbDevice.hpp"
|
||||||
@@ -31,49 +33,56 @@
|
|||||||
namespace libusbwrap {
|
namespace libusbwrap {
|
||||||
|
|
||||||
UsbDeviceFactory::~UsbDeviceFactory() {
|
UsbDeviceFactory::~UsbDeviceFactory() {
|
||||||
if (mDeviceListInitialized) {
|
if (mLibusbCtx) {
|
||||||
libusb_free_device_list(mLibusbDeviceList, 1);
|
libusb_exit(mLibusbCtx);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
std::vector<std::shared_ptr<IUsbDevice>> UsbDeviceFactory::findAllDevices() {
|
std::vector<std::unique_ptr<IUsbDevice>> UsbDeviceFactory::findAllDevices() {
|
||||||
refreshDeviceList();
|
refreshDeviceList();
|
||||||
return buildMaskedDeviceVector(0x0, 0x0, 0x0, 0x0);
|
return buildMaskedDeviceVector(0x0, 0x0, 0x0, 0x0);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<std::shared_ptr<IUsbDevice>> UsbDeviceFactory::findDevices(uint16_t vid, uint16_t pid) {
|
std::vector<std::unique_ptr<IUsbDevice>> UsbDeviceFactory::findDevices(uint16_t vid, uint16_t pid) {
|
||||||
refreshDeviceList();
|
refreshDeviceList();
|
||||||
return buildMaskedDeviceVector(0xffff, 0xffff, vid, pid);
|
return buildMaskedDeviceVector(LIBUSB_BITMASK_ALL, LIBUSB_BITMASK_ALL, vid, pid);
|
||||||
}
|
}
|
||||||
|
|
||||||
int UsbDeviceFactory::refreshDeviceList() {
|
ssize_t UsbDeviceFactory::refreshDeviceList() {
|
||||||
int ret = libusb_get_device_list(mLibusbCtx, &mLibusbDeviceList);
|
libusb_device** list{nullptr};
|
||||||
|
|
||||||
|
ssize_t ret = libusb_get_device_list(mLibusbCtx, &list);
|
||||||
|
mLibusbDeviceList.clear();
|
||||||
if (ret < 0) {
|
if (ret < 0) {
|
||||||
spdlog::error("Error enumarating USB devices");
|
spdlog::error("Error enumarating USB devices");
|
||||||
} else if (ret == 0) {
|
} else if (ret == 0) {
|
||||||
spdlog::warn("No USB devices found");
|
spdlog::warn("No USB devices found");
|
||||||
}
|
}
|
||||||
mDeviceListInitialized = true;
|
|
||||||
|
for (ssize_t i = 0; i < ret; i++) {
|
||||||
|
mLibusbDeviceList.emplace_back(list[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
libusb_free_device_list(list, false);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<std::shared_ptr<IUsbDevice>> UsbDeviceFactory::buildMaskedDeviceVector(uint16_t vidMask,
|
std::vector<std::unique_ptr<IUsbDevice>> UsbDeviceFactory::buildMaskedDeviceVector(uint16_t vidMask,
|
||||||
uint16_t pidMask,
|
uint16_t pidMask,
|
||||||
uint16_t vid,
|
uint16_t vid,
|
||||||
uint16_t pid) {
|
uint16_t pid) {
|
||||||
std::vector<std::shared_ptr<IUsbDevice>> matchedDevices;
|
std::vector<std::unique_ptr<IUsbDevice>> matchedDevices;
|
||||||
// see libusb/examples/listdevs.c
|
// see libusb/examples/listdevs.c
|
||||||
int i = 0;
|
for (auto& currDev : mLibusbDeviceList) {
|
||||||
libusb_device* currDev = nullptr;
|
struct libusb_device_descriptor currDevDesc {};
|
||||||
while ((currDev = mLibusbDeviceList[i++]) != nullptr) {
|
|
||||||
struct libusb_device_descriptor currDevDesc;
|
int ret = libusb_get_device_descriptor(currDev.get(), &currDevDesc);
|
||||||
int ret = libusb_get_device_descriptor(currDev, &currDevDesc);
|
|
||||||
if (ret < 0) {
|
if (ret < 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (((currDevDesc.idVendor & vidMask) == vid) &&
|
if (((currDevDesc.idVendor & vidMask) == vid) &&
|
||||||
((currDevDesc.idProduct & pidMask) == pid)) {
|
((currDevDesc.idProduct & pidMask) == pid)) {
|
||||||
matchedDevices.push_back(std::make_shared<UsbDevice>(mLibusbCtx, currDev));
|
matchedDevices.push_back(std::make_unique<UsbDevice>(mLibusbCtx, std::move(currDev)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return matchedDevices;
|
return matchedDevices;
|
||||||
|
@@ -19,9 +19,16 @@
|
|||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
#include "libusb.h"
|
||||||
|
#include "libusbwrap/UsbDevice.hpp"
|
||||||
#include "libusbwrap/interface/IUsbDeviceFactory.hpp"
|
#include "libusbwrap/interface/IUsbDeviceFactory.hpp"
|
||||||
|
|
||||||
namespace libusbwrap {
|
namespace libusbwrap {
|
||||||
|
|
||||||
|
constexpr const uint16_t LIBUSB_BITMASK_ALL = 0xffff;
|
||||||
|
|
||||||
class UsbDeviceFactory : public IUsbDeviceFactory {
|
class UsbDeviceFactory : public IUsbDeviceFactory {
|
||||||
public:
|
public:
|
||||||
UsbDeviceFactory() = default;
|
UsbDeviceFactory() = default;
|
||||||
@@ -39,7 +46,7 @@ class UsbDeviceFactory : public IUsbDeviceFactory {
|
|||||||
*
|
*
|
||||||
* @return std::vector<std::shared_ptr<IUsbDevice>> Vector of all detected USB devices
|
* @return std::vector<std::shared_ptr<IUsbDevice>> Vector of all detected USB devices
|
||||||
*/
|
*/
|
||||||
std::vector<std::shared_ptr<IUsbDevice>> findAllDevices() override;
|
std::vector<std::unique_ptr<IUsbDevice>> findAllDevices() override;
|
||||||
/**
|
/**
|
||||||
* @brief Gets all devices with certain vid/pid combination.
|
* @brief Gets all devices with certain vid/pid combination.
|
||||||
* If only one device of certain type is connected, vector is usually only one element
|
* If only one device of certain type is connected, vector is usually only one element
|
||||||
@@ -48,17 +55,17 @@ class UsbDeviceFactory : public IUsbDeviceFactory {
|
|||||||
* @param pid ProductId of the devices to find
|
* @param pid ProductId of the devices to find
|
||||||
* @return std::vector<std::shared_ptr<IUsbDevice>> Vector of detected USB devices based on vid/pid
|
* @return std::vector<std::shared_ptr<IUsbDevice>> Vector of detected USB devices based on vid/pid
|
||||||
*/
|
*/
|
||||||
std::vector<std::shared_ptr<IUsbDevice>> findDevices(uint16_t vid, uint16_t pid) override;
|
std::vector<std::unique_ptr<IUsbDevice>> findDevices(uint16_t vid, uint16_t pid) override;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// methods
|
// methods
|
||||||
int refreshDeviceList();
|
ssize_t refreshDeviceList();
|
||||||
std::vector<std::shared_ptr<IUsbDevice>> buildMaskedDeviceVector(uint16_t vidMask,
|
std::vector<std::unique_ptr<IUsbDevice>> buildMaskedDeviceVector(uint16_t vidMask,
|
||||||
uint16_t pidMask, uint16_t vid,
|
uint16_t pidMask, uint16_t vid,
|
||||||
uint16_t pid);
|
uint16_t pid);
|
||||||
// members
|
// members
|
||||||
libusb_context* mLibusbCtx{nullptr};
|
libusb_context* mLibusbCtx{nullptr};
|
||||||
libusb_device** mLibusbDeviceList{};
|
std::vector<usbDevice_ptr> mLibusbDeviceList{};
|
||||||
bool mDeviceListInitialized = false;
|
bool mDeviceListInitialized = false;
|
||||||
};
|
};
|
||||||
} // namespace libusbwrap
|
} // namespace libusbwrap
|
@@ -29,11 +29,10 @@ class IUsbDevice {
|
|||||||
virtual void close() = 0;
|
virtual void close() = 0;
|
||||||
|
|
||||||
// libusb wrappers
|
// libusb wrappers
|
||||||
virtual bool detachKernelDriver(int interfaceNo) = 0;
|
virtual bool detachKernelDriver(int interfaceNo) = 0;
|
||||||
virtual bool claimInterface(int interfaceNo) = 0;
|
virtual bool claimInterface(int interfaceNo) = 0;
|
||||||
virtual bool releaseInterface(int interfaceNo) = 0;
|
virtual bool releaseInterface(int interfaceNo) = 0;
|
||||||
virtual bool bulkTransfer(uint8_t endpoint, std::vector<uint8_t>& data, int* tx,
|
virtual bool bulkTransfer(uint8_t endpoint, const std::vector<uint8_t>& data, int* tx, unsigned int timeout) = 0;
|
||||||
unsigned int timeout) = 0;
|
|
||||||
|
|
||||||
// getters
|
// getters
|
||||||
virtual const usbId getUsbId() = 0;
|
virtual const usbId getUsbId() = 0;
|
||||||
|
@@ -10,7 +10,7 @@ namespace libusbwrap {
|
|||||||
class IUsbDeviceFactory {
|
class IUsbDeviceFactory {
|
||||||
public:
|
public:
|
||||||
virtual ~IUsbDeviceFactory() = default;
|
virtual ~IUsbDeviceFactory() = default;
|
||||||
virtual std::vector<std::shared_ptr<IUsbDevice>> findAllDevices() = 0;
|
virtual std::vector<std::unique_ptr<IUsbDevice>> findAllDevices() = 0;
|
||||||
virtual std::vector<std::shared_ptr<IUsbDevice>> findDevices(uint16_t vid, uint16_t pid) = 0;
|
virtual std::vector<std::unique_ptr<IUsbDevice>> findDevices(uint16_t vid, uint16_t pid) = 0;
|
||||||
};
|
};
|
||||||
} // namespace libusbwrap
|
} // namespace libusbwrap
|
@@ -10,7 +10,7 @@ ptprnt_hpps = files (
|
|||||||
'PtouchPrint.hpp',
|
'PtouchPrint.hpp',
|
||||||
'PrinterDriverFactory.hpp',
|
'PrinterDriverFactory.hpp',
|
||||||
'graphics/Bitmap.hpp',
|
'graphics/Bitmap.hpp',
|
||||||
'graphics/Image.hpp',
|
'graphics/Label.hpp',
|
||||||
'graphics/Monochrome.hpp'
|
'graphics/Monochrome.hpp'
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ ptprnt_srcs = files (
|
|||||||
'PtouchPrint.cpp',
|
'PtouchPrint.cpp',
|
||||||
'PrinterDriverFactory.cpp',
|
'PrinterDriverFactory.cpp',
|
||||||
'P700Printer.cpp',
|
'P700Printer.cpp',
|
||||||
'graphics/Image.cpp',
|
'graphics/Label.cpp',
|
||||||
'graphics/Bitmap.cpp',
|
'graphics/Bitmap.cpp',
|
||||||
'graphics/Monochrome.cpp',
|
'graphics/Monochrome.cpp',
|
||||||
'libusbwrap/UsbDeviceFactory.cpp',
|
'libusbwrap/UsbDeviceFactory.cpp',
|
||||||
|
0
src/ptprnt.log
Normal file
0
src/ptprnt.log
Normal file
@@ -22,7 +22,6 @@
|
|||||||
#include <gtest/gtest.h>
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <optional>
|
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
TEST(basic_test, Bitmap_createBitmapWithCertainSize_yieldsSpecifiedSize) {
|
TEST(basic_test, Bitmap_createBitmapWithCertainSize_yieldsSpecifiedSize) {
|
||||||
@@ -36,34 +35,28 @@ TEST(basic_test, Bitmap_createBitmapWithCertainSize_yieldsSpecifiedSize) {
|
|||||||
TEST(basic_test, Bitmap_getBitmapLineOutsideOfImage_yieldsNullopt) {
|
TEST(basic_test, Bitmap_getBitmapLineOutsideOfImage_yieldsNullopt) {
|
||||||
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
|
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
|
||||||
// line 8 is out of bounds, count begins with 0
|
// line 8 is out of bounds, count begins with 0
|
||||||
auto outOfBoundsLine = bm.getLine(8);
|
EXPECT_ANY_THROW(auto outOfBoundsLine = bm.getLine(8));
|
||||||
ASSERT_EQ(std::nullopt, outOfBoundsLine);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST(basic_test, Bitmap_getBitmapLineInsideOfImage_yieldsValidLineSize) {
|
TEST(basic_test, Bitmap_getBitmapLineInsideOfImage_yieldsValidLineSize) {
|
||||||
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
|
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
|
||||||
auto line = bm.getLine(7);
|
auto line = bm.getLine(7);
|
||||||
if (!line) {
|
auto lineSize = line.size();
|
||||||
FAIL() << "Returned line is invalid";
|
|
||||||
}
|
|
||||||
auto lineSize = line->size();
|
|
||||||
ASSERT_EQ(16, lineSize);
|
ASSERT_EQ(16, lineSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST(basic_test, Bitmap_getBitmapColOutsideOfImage_yieldsNullopt) {
|
TEST(basic_test, Bitmap_getBitmapColOutsideOfImage_yieldsNullopt) {
|
||||||
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
|
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
|
||||||
// col 16 is out of bounds, count begins with 0
|
// col 16 is out of bounds, count begins with 0
|
||||||
auto outOfBoundsCol = bm.getCol(16);
|
|
||||||
ASSERT_EQ(std::nullopt, outOfBoundsCol);
|
EXPECT_ANY_THROW(auto outOfBoundsCol = bm.getCol(16));
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST(basic_test, Bitmap_getBitmapColInsideOfImage_yieldsValidColSize) {
|
TEST(basic_test, Bitmap_getBitmapColInsideOfImage_yieldsValidColSize) {
|
||||||
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
|
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
|
||||||
auto col = bm.getCol(15);
|
auto col = bm.getCol(15);
|
||||||
if (!col) {
|
|
||||||
FAIL() << "Returned Col is invalid";
|
auto colSize = col.size();
|
||||||
}
|
|
||||||
auto colSize = col->size();
|
|
||||||
ASSERT_EQ(8, colSize);
|
ASSERT_EQ(8, colSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -17,10 +17,10 @@
|
|||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "graphics/Image.hpp"
|
#include "graphics/Label.hpp"
|
||||||
|
|
||||||
#include <gtest/gtest.h>
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
TEST(basic_test, Image_smokeTest_succeeds) {
|
TEST(basic_test, Label_smokeTest_succeeds) {
|
||||||
auto im = ptprnt::graphics::Image();
|
auto im = ptprnt::graphics::Label(4711);
|
||||||
}
|
}
|
@@ -5,9 +5,9 @@ tests = [
|
|||||||
['../src/graphics/Bitmap.cpp', 'bitmap_test/bitmap_test.cpp'],
|
['../src/graphics/Bitmap.cpp', 'bitmap_test/bitmap_test.cpp'],
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'image_test',
|
'label_test',
|
||||||
'image_test_exe',
|
'label_test_exe',
|
||||||
['../src/graphics/Image.cpp', 'image_test/image_test.cpp'],
|
['../src/graphics/Label.cpp', 'label_test/label_test.cpp'],
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'monochrome_test',
|
'monochrome_test',
|
||||||
@@ -36,3 +36,5 @@ foreach test : tests
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
endforeach
|
endforeach
|
||||||
|
|
||||||
|
|
||||||
|
@@ -22,22 +22,22 @@
|
|||||||
#include <gtest/gtest.h>
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
TEST(basic_test, Monochrome_convertGrayscale_yieldsMonochrome) {
|
TEST(basic_test, Monochrome_convertGrayscale_yieldsMonochrome) {
|
||||||
const std::vector<uint8_t> pixels({0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00,
|
const std::vector<uint8_t> pixels(
|
||||||
0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00});
|
{0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00});
|
||||||
|
|
||||||
const std::vector<uint8_t> expected({0b10101010, 0b10101010});
|
const std::vector<uint8_t> expected({0b10101010, 0b10101010});
|
||||||
auto mono = ptprnt::graphics::Monochrome(pixels);
|
auto mono = ptprnt::graphics::Monochrome(pixels, 16, 1);
|
||||||
auto out = mono.get();
|
auto out = mono.get();
|
||||||
|
|
||||||
EXPECT_EQ(out, expected);
|
EXPECT_EQ(out, expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST(basic_test, Monochrome_convertInvertedGrayscale_yieldsInvertedMonochrome) {
|
TEST(basic_test, Monochrome_convertInvertedGrayscale_yieldsInvertedMonochrome) {
|
||||||
const std::vector<uint8_t> pixels({0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00,
|
const std::vector<uint8_t> pixels(
|
||||||
0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00});
|
{0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00});
|
||||||
|
|
||||||
const std::vector<uint8_t> expected({0b01010101, 0b01010101});
|
const std::vector<uint8_t> expected({0b01010101, 0b01010101});
|
||||||
auto mono = ptprnt::graphics::Monochrome(pixels);
|
auto mono = ptprnt::graphics::Monochrome(pixels, 16, 1);
|
||||||
mono.invert(true);
|
mono.invert(true);
|
||||||
auto out = mono.get();
|
auto out = mono.get();
|
||||||
|
|
||||||
@@ -45,11 +45,11 @@ TEST(basic_test, Monochrome_convertInvertedGrayscale_yieldsInvertedMonochrome) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
TEST(basic_test, Monochrome_convertWithCustomThreshhold_yieldsMonochromeRespectingThreshhold) {
|
TEST(basic_test, Monochrome_convertWithCustomThreshhold_yieldsMonochromeRespectingThreshhold) {
|
||||||
const std::vector<uint8_t> pixels({0x0F, 0x11, 0x0F, 0x11, 0x0F, 0x11, 0x0F, 0x11, 0x0F, 0x11,
|
const std::vector<uint8_t> pixels(
|
||||||
0x0F, 0x11, 0x0F, 0x11, 0x0F, 0x11});
|
{0x0F, 0x11, 0x0F, 0x11, 0x0F, 0x11, 0x0F, 0x11, 0x0F, 0x11, 0x0F, 0x11, 0x0F, 0x11, 0x0F, 0x11});
|
||||||
|
|
||||||
const std::vector<uint8_t> expected({0b01010101, 0b01010101});
|
const std::vector<uint8_t> expected({0b01010101, 0b01010101});
|
||||||
auto mono = ptprnt::graphics::Monochrome(pixels);
|
auto mono = ptprnt::graphics::Monochrome(pixels, 16, 1);
|
||||||
mono.setThreshold(16);
|
mono.setThreshold(16);
|
||||||
auto out = mono.get();
|
auto out = mono.get();
|
||||||
|
|
||||||
@@ -60,12 +60,104 @@ TEST(basic_test, Monochrome_convertNonAlignedPixels_spillsOverIntoNewByte) {
|
|||||||
// TODO: We need to find to access the vector without the possiblity of out-of-bounds access
|
// TODO: We need to find to access the vector without the possiblity of out-of-bounds access
|
||||||
// Ideas: constexpr? compile time check?
|
// Ideas: constexpr? compile time check?
|
||||||
GTEST_SKIP() << "Skipping this test, as ASAN will halt as this is an out-of-bounds access";
|
GTEST_SKIP() << "Skipping this test, as ASAN will halt as this is an out-of-bounds access";
|
||||||
const std::vector<uint8_t> pixels({0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00,
|
const std::vector<uint8_t> pixels(
|
||||||
0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF});
|
{0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF});
|
||||||
|
|
||||||
const std::vector<uint8_t> expected({0b10101010, 0b10101010, 0b10000000});
|
const std::vector<uint8_t> expected({0b10101010, 0b10101010, 0b10000000});
|
||||||
auto mono = ptprnt::graphics::Monochrome(pixels);
|
auto mono = ptprnt::graphics::Monochrome(pixels, 17, 1);
|
||||||
auto out = mono.get();
|
auto out = mono.get();
|
||||||
|
|
||||||
EXPECT_EQ(out, expected);
|
EXPECT_EQ(out, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(MonochromeData_test, MonochromeData_getMonochromeData_returnsStructWithCorrectData) {
|
||||||
|
const std::vector<uint8_t> pixels({0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00});
|
||||||
|
|
||||||
|
auto mono = ptprnt::graphics::Monochrome(pixels, 8, 1);
|
||||||
|
auto monoData = mono.getMonochromeData();
|
||||||
|
|
||||||
|
EXPECT_EQ(monoData.bytes.size(), 1);
|
||||||
|
EXPECT_EQ(monoData.bytes[0], 0b10101010);
|
||||||
|
EXPECT_EQ(monoData.width, 8);
|
||||||
|
EXPECT_EQ(monoData.height, 1);
|
||||||
|
EXPECT_EQ(monoData.stride, 1);
|
||||||
|
EXPECT_EQ(monoData.orientation, ptprnt::graphics::Orientation::LANDSCAPE);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(MonochromeData_test, MonochromeData2x2_transformToPortrait_rotatesCorrectly) {
|
||||||
|
// Create a 2x2 image with a specific pattern
|
||||||
|
// Pixels are laid out row-major: row0_col0, row0_col1, row1_col0, ...
|
||||||
|
const std::vector<uint8_t> pixels({0xFF, 0x00, 0x00, 0xFF});
|
||||||
|
|
||||||
|
auto mono = ptprnt::graphics::Monochrome(pixels, 2, 2);
|
||||||
|
auto monoData = mono.getMonochromeData();
|
||||||
|
|
||||||
|
monoData.transformTo(ptprnt::graphics::Orientation::PORTRAIT);
|
||||||
|
|
||||||
|
// After 90° clockwise rotation:
|
||||||
|
// Original: █ . -> Rotated: . █
|
||||||
|
// . █ █ .
|
||||||
|
EXPECT_EQ(monoData.width, 2);
|
||||||
|
EXPECT_EQ(monoData.height, 2);
|
||||||
|
EXPECT_EQ(monoData.orientation, ptprnt::graphics::Orientation::PORTRAIT);
|
||||||
|
|
||||||
|
// check pixel data ...................................... x,y = value
|
||||||
|
EXPECT_EQ(monoData.getBit(0, 0), false); // 0,0 = white
|
||||||
|
EXPECT_EQ(monoData.getBit(1, 0), true); // 0,1 = black
|
||||||
|
EXPECT_EQ(monoData.getBit(0, 1), true); // 1,0 = black
|
||||||
|
EXPECT_EQ(monoData.getBit(1, 1), false); // 1,1 = white
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(MonochromeData_test, MonochromeData3x2_transformToPortrait_rotatesCorrectly) {
|
||||||
|
// Create a 2x3 image with a specific pattern
|
||||||
|
// Pixels are laid out row-major: row0_col0, row0_col1, row0_col2, row1_col0, ...
|
||||||
|
const std::vector<uint8_t> pixels({0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF});
|
||||||
|
|
||||||
|
auto mono = ptprnt::graphics::Monochrome(pixels, 3, 2);
|
||||||
|
auto monoData = mono.getMonochromeData();
|
||||||
|
|
||||||
|
monoData.transformTo(ptprnt::graphics::Orientation::PORTRAIT);
|
||||||
|
|
||||||
|
// After 90° clockwise rotation:
|
||||||
|
// Original: █ . . -> Rotated: █ █
|
||||||
|
// █ . █ . .
|
||||||
|
// █ .
|
||||||
|
EXPECT_EQ(monoData.width, 2);
|
||||||
|
EXPECT_EQ(monoData.height, 3);
|
||||||
|
EXPECT_EQ(monoData.orientation, ptprnt::graphics::Orientation::PORTRAIT);
|
||||||
|
|
||||||
|
// check pixel data ...................................... x,y = value
|
||||||
|
EXPECT_EQ(monoData.getBit(0, 0), true); // 1,1 = black
|
||||||
|
EXPECT_EQ(monoData.getBit(1, 0), true); // 1,2 = black
|
||||||
|
EXPECT_EQ(monoData.getBit(0, 1), false); // 2,1 = white
|
||||||
|
EXPECT_EQ(monoData.getBit(1, 1), false); // 2,2 = white
|
||||||
|
EXPECT_EQ(monoData.getBit(0, 2), true); // 3,1 = black
|
||||||
|
EXPECT_EQ(monoData.getBit(1, 2), false); // 3,2 = white
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(MonochromeData_test, MonochromeData3x2_transformToPortrait_rotatesCorrectlyCounterclockwise) {
|
||||||
|
// Create a 2x3 image with a specific pattern
|
||||||
|
// Pixels are laid out row-major: row0_col0, row0_col1, row0_col2, row1_col0, ...
|
||||||
|
const std::vector<uint8_t> pixels({0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF});
|
||||||
|
|
||||||
|
auto mono = ptprnt::graphics::Monochrome(pixels, 3, 2);
|
||||||
|
auto monoData = mono.getMonochromeData();
|
||||||
|
|
||||||
|
monoData.transformTo(ptprnt::graphics::Orientation::PORTRAIT_FLIPPED);
|
||||||
|
|
||||||
|
// After 90° anti-clockwise rotation:
|
||||||
|
// Original: █ . . -> Rotated: . █
|
||||||
|
// █ . █ . .
|
||||||
|
// █ █
|
||||||
|
EXPECT_EQ(monoData.width, 2);
|
||||||
|
EXPECT_EQ(monoData.height, 3);
|
||||||
|
EXPECT_EQ(monoData.orientation, ptprnt::graphics::Orientation::PORTRAIT_FLIPPED);
|
||||||
|
|
||||||
|
// check pixel data ...................................... x,y = value
|
||||||
|
EXPECT_EQ(monoData.getBit(0, 0), false); // 1,1 = white
|
||||||
|
EXPECT_EQ(monoData.getBit(1, 0), true); // 1,2 = black
|
||||||
|
EXPECT_EQ(monoData.getBit(0, 1), false); // 2,1 = white
|
||||||
|
EXPECT_EQ(monoData.getBit(1, 1), false); // 2,2 = white
|
||||||
|
EXPECT_EQ(monoData.getBit(0, 2), true); // 3,1 = black
|
||||||
|
EXPECT_EQ(monoData.getBit(1, 2), true); // 3,2 = black
|
||||||
}
|
}
|
Reference in New Issue
Block a user