9 Commits

Author SHA1 Message Date
2d54e583b7 commands restructured to be const vectors
Some checks failed
Build ptprnt / build (push) Failing after 1m1s
2024-04-20 12:03:20 +02:00
b42e866a49 Got it almost working...
All checks were successful
Build ptprnt / build (push) Successful in 2m29s
2023-12-03 22:08:59 +01:00
3e9c3267e2 Removing files that shouldn't have been staged 2023-12-03 13:23:58 +01:00
46cc16e431 Some side tracking fixing undefined behaviour and memory vulnurabilities
All checks were successful
Build ptprnt / build (push) Successful in 3m23s
2023-12-03 13:20:30 +01:00
0704081326 Rename Image class to Label
All checks were successful
Build ptprnt / build (push) Successful in 5m1s
2023-12-03 11:13:52 +01:00
f0812d3166 Remove debug output as build pipeline does not have pango >=v1.5.0
All checks were successful
Build ptprnt / build (push) Successful in 1m57s
2023-11-21 21:14:27 +01:00
c3110ff32a Fix typo
Some checks failed
Build ptprnt / build (push) Failing after 41s
2023-11-21 21:05:48 +01:00
f4036e6a83 Width is no automatically chosen based on image width
Some checks failed
Build ptprnt / build (push) Failing after 38s
2023-11-21 20:46:52 +01:00
778a01429c A somewhat working state, but still struggeling with pangocairo
Some checks failed
Build ptprnt / build (push) Failing after 43s
2023-11-21 19:25:12 +01:00
32 changed files with 305 additions and 931 deletions

View File

@@ -2,6 +2,7 @@
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

View File

@@ -15,40 +15,13 @@ jobs:
run: apt-get -yq install meson run: apt-get -yq install meson
- name: Install build dependencies - name: Install build dependencies
run: apt-get -yq install libusb-1.0-0-dev libspdlog-dev libfmt-dev libpango1.0-dev libcairo2-dev gcovr run: apt-get -yq install libusb-1.0-0-dev libspdlog-dev libfmt-dev libpango1.0-dev libcairo2-dev gcovr
- name: get build environment versions
run: |
echo "=== Start meson version ==="
gcc --version
echo "=== End meson version ==="
echo "=== Start supported c/cpp standards: ==="
gcc -v --help 2> /dev/null | sed -n '/^ *-std=\([^<][^ ]\+\).*/ {s//\1/p}'
echo "=== End supported c/cpp standards ==="
echo "=== Start meson version ==="
meson --version
echo "=== End meson version ==="
echo "=== Start ninja version ==="
ninja --version
echo "=== End ninja version ==="
echo "=== Start dependency package version ==="
apt-cache policy libpango1.0-dev
apt-cache policy libcairo2-dev
apt-cache policy libfmt-dev
apt-cache policy libspdlog-dev
apt-cache policy libusb-1.0-0-dev
echo "=== End dependency package version ==="
- name: setup builddir - name: setup builddir
run: meson setup builddir -Db_coverage=true run: meson setup builddir -Db_coverage=true
- name: build and test dist package - name: build all targets
run: ninja -C builddir dist run: ninja -C builddir
- name: run unit tests - name: run unit tests
run: ninja -C builddir test run: ninja -C builddir test
- name: calculate coverage - name: calculate coverage
run: ninja -C builddir coverage-text run: ninja -C builddir coverage-text
- name: Coverage report - name: Coverage report
run: cat ./builddir/meson-logs/coverage.txt run: cat ./builddir/meson-logs/coverage.txt
- name: upload dist package
uses: actions/upload-artifact@v3
with:
name: ptprnt-dist
path: ./builddir/meson-dist/*
if-no-files-found: error

1
.gitignore vendored
View File

@@ -6,7 +6,6 @@ subprojects/*
coverageReport/ coverageReport/
# Files # Files
ptprnt.log
!subprojects/*.wrap !subprojects/*.wrap
.vscode/* .vscode/*
!.vscode/c_cpp_properties.json !.vscode/c_cpp_properties.json

View File

@@ -4,7 +4,7 @@
"name": "Linux", "name": "Linux",
"compilerPath": "/usr/bin/clang", "compilerPath": "/usr/bin/clang",
"cStandard": "c11", "cStandard": "c11",
"cppStandard": "c++20", "cppStandard": "c++17",
"compileCommands": "${workspaceFolder}/builddir/compile_commands.json", "compileCommands": "${workspaceFolder}/builddir/compile_commands.json",
"browse": { "browse": {
"path": ["${workspaceFolder}"] "path": ["${workspaceFolder}"]

2
.vscode/launch.json vendored
View File

@@ -14,7 +14,7 @@
"cwd": "${fileDirname}", "cwd": "${fileDirname}",
"environment": [], "environment": [],
"externalConsole": false, "externalConsole": false,
"MIMode": "lldb", "MIMode": "gdb",
"setupCommands": [ "setupCommands": [
{ {
"description": "Automatische Strukturierung und Einrückung für \"gdb\" aktivieren", "description": "Automatische Strukturierung und Einrückung für \"gdb\" aktivieren",

View File

@@ -83,5 +83,11 @@
"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",
"gcovViewer.buildDirectories": [
"/home/moritz/Projekte/ptouch-prnt/builddir"
],
"C_Cpp.default.configurationProvider": "mesonbuild.mesonbuild"
} }

View File

@@ -1,22 +1,7 @@
project( project('ptprnt', 'cpp',
'ptprnt', version: 'v0.1.0-'+run_command('git', 'rev-parse', '--short', 'HEAD', check: true).stdout().strip(),
'cpp',
version: 'v0.1.0-' + run_command(
'git',
'rev-parse',
'--short',
'HEAD',
check: true,
).stdout().strip(),
license: 'GPLv3', license: 'GPLv3',
default_options: [ default_options : ['c_std=c11', 'cpp_std=c++20', 'b_sanitize=none', 'b_lto=true', 'b_lto_mode=thin', 'b_thinlto_cache=true']
'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')
@@ -36,13 +21,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()+'"'],
) )
@@ -55,4 +40,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')

View File

@@ -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,16 +19,20 @@
#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 <memory> #include <ratio>
#include <thread> #include <thread>
#include <vector> #include <vector>
#include "graphics/Bitmap.hpp" #include "graphics/Bitmap.hpp"
#include "graphics/Label.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"
@@ -37,14 +41,8 @@
namespace ptprnt::printer { namespace ptprnt::printer {
const PrinterInfo P700Printer::mInfo = {.driverName = "P700",
.name = "Brother P-touch P700",
.version = "v1.0",
.usbId{0x04f9, 0x2061},
.pixelLines = 128};
P700Printer::~P700Printer() { P700Printer::~P700Printer() {
P700Printer::detachUsbDevice(); detachUsbDevice();
if (mUsbHndl) { if (mUsbHndl) {
mUsbHndl->close(); mUsbHndl->close();
} }
@@ -75,14 +73,18 @@ const PrinterStatus P700Printer::getPrinterStatus() {
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(p700::commands::PRINTER_INFO[0], recvBuf, &tx, 0); mUsbHndl->bulkTransfer(p700::commands::INFO[0], recvBuf, &tx, 0);
} }
return PrinterStatus{.tapeWidthMm = recvBuf[10]}; return PrinterStatus{.tapeWidthMm = recvBuf[10]};
} }
const libusbwrap::usbId P700Printer::getUsbId() { const uint16_t P700Printer::getVid() {
return mInfo.usbId; return mInfo.vid;
}
const uint16_t P700Printer::getPid() {
return mInfo.pid;
} }
bool P700Printer::attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) { bool P700Printer::attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) {
@@ -92,7 +94,6 @@ 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;
@@ -120,69 +121,47 @@ bool P700Printer::detachUsbDevice() {
} }
bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) { bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) {
// Convert bitmap to MonochromeData and delegate to printMonochromeData
auto pixels = bitmap.getPixelsCpy();
auto mono = graphics::Monochrome(pixels, bitmap.getWidth(), bitmap.getHeight());
auto monoData = mono.getMonochromeData();
return printMonochromeData(monoData);
}
bool P700Printer::printMonochromeData(const graphics::MonochromeData& data) {
#ifdef DRYRUN #ifdef DRYRUN
spdlog::debug("DRYRUN enabled"); SPDLOG_DEBUG("DRYRUN enabled");
data.visualize(); for (unsigned int lineNo = 0; lineNo < bitmap.getHeight(); lineNo++) {
auto line = bitmap.getLine(lineNo);
auto monoLine = graphics::Monochrome(*line);
monoLine.visualize();
}
#endif #endif
send(p700::commands::RASTER_START); 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 < bitmap.getWidth(); i++) {
// Process data column by column for the printer auto bmcol = bitmap.getCol(i);
for (uint32_t col = 0; col < data.width; col++) { if (!bmcol) {
std::vector<uint8_t> columnData; spdlog::error("Out of bounds bitmap access");
break;
// 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);
} }
auto monocol = graphics::Monochrome(*bmcol);
std::vector<uint8_t> buf; auto col = monocol.get();
std::vector<uint8_t> buf(0);
buf.insert(buf.begin(), rastercmd.begin(), rastercmd.end()); buf.insert(buf.begin(), rastercmd.begin(), rastercmd.end());
buf.insert(std::next(buf.begin(), 4), columnData.begin(), columnData.end()); buf.insert(std::next(buf.begin(), 4), col.begin(), col.end());
buf[1] = columnData.size() + 1;
buf[3] = columnData.size() - 1; buf[1] = col.size() + 1;
buf[3] = col.size() - 1;
if (!send(buf)) { if (!send(buf)) {
spdlog::error("Error sending buffer to printer"); spdlog::error("Error sending buffer to printer");
break; break;
} };
} }
send(p700::commands::EJECT); send(p700::commands::EJECT);
return true; return true;
} }
bool P700Printer::printLabel(std::unique_ptr<graphics::ILabel> label) { bool P700Printer::printText(const std::string& text, uint16_t fontSize) {
// Convert label directly to MonochromeData
auto pixels = label->getRaw();
auto mono = graphics::Monochrome(pixels, label->getWidth(), label->getHeight());
auto monoData = mono.getMonochromeData();
spdlog::debug("Label has {}x{}px size", label->getWidth(), label->getHeight());
return printMonochromeData(monoData);
}
bool P700Printer::print() {
send(p700::commands::LF); send(p700::commands::LF);
send(p700::commands::FF); send(p700::commands::FF);
send(p700::commands::EJECT); send(p700::commands::EJECT);
@@ -196,7 +175,7 @@ bool P700Printer::send(const std::vector<uint8_t>& data) {
return false; return false;
} }
size_t tx = 0; int tx = 0;
#ifndef DRYRUN #ifndef DRYRUN
if (!mUsbHndl->bulkTransfer(0x02, data, &tx, 0)) { if (!mUsbHndl->bulkTransfer(0x02, data, &tx, 0)) {
@@ -205,10 +184,10 @@ bool P700Printer::send(const std::vector<uint8_t>& data) {
} }
#else #else
tx = data.size(); tx = data.size();
spdlog::trace("USB raw data(len {}): {}", data.size(), spdlog::to_hex(data)); spdlog::info("USB raw data(len {}): {}", data.size(), spdlog::to_hex(data));
#endif #endif
if (tx != data.size()) { if (tx != static_cast<int>(data.size())) {
spdlog::error("Could not transfer all data via USB bulk transfer. Only sent {} of {} bytes", tx, data.size()); spdlog::error("Could not transfer all data via USB bulk transfer. Only sent {} of {} bytes", tx, data.size());
return false; return false;
} }
@@ -222,4 +201,4 @@ bool P700Printer::init() {
cmd[101] = 0x40; /* @ */ cmd[101] = 0x40; /* @ */
return send(cmd); return send(cmd);
} }
} // namespace ptprnt::printer } // namespace ptprnt::printer

View File

@@ -20,12 +20,12 @@
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
#include <sys/types.h> #include <sys/types.h>
#include <map>
#include <memory> #include <memory>
#include <vector> #include <vector>
#include "interface/IPrinterDriver.hpp" #include "interface/IPrinterDriver.hpp"
#include "interface/IPrinterTypes.hpp" #include "interface/IPrinterTypes.hpp"
#include "libusbwrap/LibUsbTypes.hpp"
#include "libusbwrap/interface/IUsbDevice.hpp" #include "libusbwrap/interface/IUsbDevice.hpp"
#pragma once #pragma once
@@ -44,9 +44,6 @@ const cmd_T PRINTER_INFO{0x81};
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;
@@ -58,27 +55,31 @@ class P700Printer : public ::ptprnt::IPrinterDriver {
P700Printer(P700Printer&&) = default; P700Printer(P700Printer&&) = default;
P700Printer& operator=(P700Printer&&) = default; P700Printer& operator=(P700Printer&&) = default;
// Printer info has to be static to be accessed without instantiation
static const PrinterInfo mInfo;
// IPrinterDriver // IPrinterDriver
[[nodiscard]] const std::string_view getDriverName() override; const std::string_view getDriverName() override;
[[nodiscard]] const std::string_view getName() override; const std::string_view getName() override;
[[nodiscard]] const libusbwrap::usbId getUsbId() override; const uint16_t getPid() override;
[[nodiscard]] const std::string_view getVersion() override; const uint16_t getVid() override;
[[nodiscard]] const PrinterInfo getPrinterInfo() override; const std::string_view getVersion() override;
[[nodiscard]] const PrinterStatus getPrinterStatus() override; const PrinterInfo getPrinterInfo() override;
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 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 printText(const std::string& text, uint16_t fontSize) override;
bool printLabel(const std::unique_ptr<graphics::ILabel> label) override;
bool print() override;
private: private:
bool send(const 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};
static constexpr PrinterInfo mInfo{.driverName = "P700",
.name = "Brother P-touch P700",
.version = "v1.0",
.vid = 0x04f9,
.pid = 0x2061,
.pixelLines = 128};
}; };
} // namespace ptprnt::printer } // namespace ptprnt::printer

View File

@@ -1,23 +0,0 @@
#include "PrinterDriverFactory.hpp"
#include <spdlog/spdlog.h>
#include <memory>
#include "P700Printer.hpp"
#include "libusbwrap/LibUsbTypes.hpp"
namespace ptprnt {
std::shared_ptr<IPrinterDriver> PrinterDriverFactory::create(libusbwrap::usbId id) {
if (printer::P700Printer::mInfo.usbId == id) {
spdlog::info("Found printer P700!");
return std::make_shared<printer::P700Printer>();
} else {
spdlog::trace("{:04x}:{:04x} is not a compatible printer", id.first, id.second);
}
return nullptr;
}
} // namespace ptprnt

View File

@@ -1,22 +0,0 @@
#include <memory>
#include "interface/IPrinterDriver.hpp"
#include "libusbwrap/LibUsbTypes.hpp"
namespace ptprnt {
class PrinterDriverFactory {
public:
PrinterDriverFactory() = default;
~PrinterDriverFactory() = default;
PrinterDriverFactory(const PrinterDriverFactory&) = delete;
PrinterDriverFactory& operator=(const PrinterDriverFactory&) = delete;
PrinterDriverFactory(PrinterDriverFactory&&) = delete;
PrinterDriverFactory& operator=(PrinterDriverFactory&&) = delete;
std::shared_ptr<IPrinterDriver> create(libusbwrap::usbId id);
private:
};
}

View File

@@ -16,10 +16,14 @@
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 "PtouchPrint.hpp" #include <cstdint>
#include "graphics/Monochrome.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>
@@ -29,16 +33,15 @@
#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 "P700Printer.hpp"
#include "PtouchPrint.hpp"
#include "graphics/Bitmap.hpp"
#include "graphics/Label.hpp" #include "graphics/Label.hpp"
#include "graphics/interface/ILabel.hpp"
#include "libusbwrap/UsbDeviceFactory.hpp" #include "libusbwrap/UsbDeviceFactory.hpp"
namespace ptprnt { namespace ptprnt {
@@ -65,27 +68,28 @@ int PtouchPrint::init(int argc, char** argv) {
spdlog::error("Could not initialize libusb"); spdlog::error("Could not initialize libusb");
return -1; return -1;
} }
mCompatiblePrinters = {std::make_shared<ptprnt::printer::P700Printer>()};
return 0; return 0;
} }
int PtouchPrint::run() { int PtouchPrint::run() {
spdlog::info("ptprnt version {}", mVersionString); SPDLOG_DEBUG("ptprnt version {}", mVersionString);
SPDLOG_TRACE("testing trace"); SPDLOG_TRACE("testing trace");
mDetectedPrinters = getCompatiblePrinters(); auto numFoundPrinters = getCompatiblePrinters();
auto numFoundPrinters = mDetectedPrinters.size();
if (numFoundPrinters == 0) { if (numFoundPrinters == 0) {
spdlog::error("No compatible printers found, please make sure that they are turned on and connected"); spdlog::error(
"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.");
return -1; return -1;
} }
auto printer = mDetectedPrinters[0]; auto printer = mCompatiblePrinters[0];
const auto printerUsbId = printer->getUsbId(); auto devices = mUsbDeviceFactory.findDevices(printer->getVid(), printer->getPid());
auto devices = mUsbDeviceFactory.findDevices(printerUsbId.first, printerUsbId.second);
if (devices.size() != 1) { if (devices.size() != 1) {
spdlog::warn("Found more than one device of the same printer on bus. Currently not supported"); spdlog::warn(
"Found more than one device of the same printer on bus. Currently not supported");
return -1; return -1;
} }
printer->attachUsbDevice(std::move(devices[0])); printer->attachUsbDevice(std::move(devices[0]));
@@ -97,80 +101,45 @@ int PtouchPrint::run() {
return 0; return 0;
} }
auto label = std::make_unique<graphics::Label>(printer->getPrinterInfo().pixelLines); for (auto& cmd : mCommands) {
std::string labelText{}; SPDLOG_DEBUG("Command: {}", cmd.second);
// TODO: refactor if (cmd.first == CliCmdType::Text) {
for (const auto& [cmd, value] : mCommands) { auto label{graphics::Label()};
switch (cmd) { label.create(cmd.second, printer->getPrinterInfo().pixelLines);
case CliCmdType::Text: auto bm = graphics::Bitmap<graphics::ALPHA8>(label.getLayoutWidth(),
if (labelText.empty()) { printer->getPrinterInfo().pixelLines);
labelText = value; if (!bm.setPixels(label.getRaw())) {
} else { spdlog::error("Non-matching bitmap size");
labelText = labelText + '\n' + value; return -1;
} }
break; label.writeToPng("salat.png");
case CliCmdType::Font: //printer->printBitmap(bm);
spdlog::debug("Setting font to {}", value);
label->setFontFamily(value);
break;
case CliCmdType::FontSize:
spdlog::debug("Setting font size to {}", std::stod(value));
label->setFontSize(std::stod(value));
break;
case CliCmdType::HAlign:
spdlog::debug("Setting text horizontal alignment to {}", value);
{
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;
case CliCmdType::VAlign:
spdlog::debug("Setting text vertical alignment to {}", value);
{
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;
case CliCmdType::None:
[[fallthrough]];
default:
spdlog::warn("This command is currently not supported.");
break;
} }
} }
label->create(labelText);
label->writeToPng("./testlabel.png");
/*if (!printer->printLabel(std::move(label))) {
spdlog::error("An error occured while printing");
return -1;
}*/
return 0; return 0;
} }
std::vector<std::shared_ptr<IPrinterDriver>> PtouchPrint::getCompatiblePrinters() { unsigned int PtouchPrint::getCompatiblePrinters() {
auto usbDevs = mUsbDeviceFactory.findAllDevices();
auto usbDevs = mUsbDeviceFactory.findAllDevices();
auto driverFactory = std::make_unique<PrinterDriverFactory>();
std::vector<std::shared_ptr<IPrinterDriver>> foundPrinterDrivers{};
for (auto& usbDev : usbDevs) { for (auto& usbDev : usbDevs) {
auto driver = driverFactory->create(usbDev->getUsbId()); auto foundPrinterIt =
if (driver != nullptr) { std::find_if(mCompatiblePrinters.begin(), mCompatiblePrinters.end(),
foundPrinterDrivers.push_back(driver); [&usbDev](const std::shared_ptr<ptprnt::IPrinterDriver>& printer) {
return printer->getPid() == usbDev->getPid() &&
printer->getVid() == usbDev->getVid();
});
if (foundPrinterIt == mCompatiblePrinters.end()) {
continue;
} }
auto foundPrinter = *foundPrinterIt;
spdlog::info("Found Printer {}", foundPrinter->getName());
mDetectedPrinters.push_back(foundPrinter);
} }
return foundPrinterDrivers; // we can delete all instantiated printers that are not compatible
mCompatiblePrinters.clear();
return mDetectedPrinters.size();
} }
void PtouchPrint::setupLogger(spdlog::level::level_enum lvl) { void PtouchPrint::setupLogger(spdlog::level::level_enum lvl) {
@@ -178,8 +147,7 @@ void PtouchPrint::setupLogger(spdlog::level::level_enum lvl) {
consoleSink->set_level(lvl); consoleSink->set_level(lvl);
if (spdlog::level::level_enum::debug == lvl || spdlog::level::level_enum::trace == lvl) { 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 // 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 (%s:%#)");
consoleSink->set_pattern("%^%L:%$ %v");
} else { } else {
consoleSink->set_pattern("%^%L:%$ %v"); consoleSink->set_pattern("%^%L:%$ %v");
} }
@@ -193,7 +161,6 @@ 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);
@@ -213,42 +180,27 @@ 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::TakeFirst) ->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->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::TakeFirst) ->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->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::TakeFirst) ->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->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::TakeFirst) ->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->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 ")->group("Image printing"); mApp.add_option("-i,--image", "Image to print. Excludes all text printing ")
->group("Image printing");
} }
} // namespace ptprnt } // namespace ptprnt

View File

@@ -49,12 +49,13 @@ class PtouchPrint {
// methods // methods
void setupLogger(spdlog::level::level_enum lvl); void setupLogger(spdlog::level::level_enum lvl);
void setupCliParser(); void setupCliParser();
std::vector<std::shared_ptr<IPrinterDriver>> getCompatiblePrinters(); unsigned int getCompatiblePrinters();
// member variables // member variables
CLI::App mApp{ptprnt::APP_DESC}; CLI::App mApp{ptprnt::APP_DESC};
libusbwrap::UsbDeviceFactory mUsbDeviceFactory{}; libusbwrap::UsbDeviceFactory mUsbDeviceFactory{};
std::vector<std::shared_ptr<IPrinterDriver>> mDetectedPrinters{}; std::vector<std::shared_ptr<ptprnt::IPrinterDriver>> mCompatiblePrinters{};
std::vector<std::shared_ptr<ptprnt::IPrinterDriver>> mDetectedPrinters{};
std::vector<CliCmd> mCommands{}; std::vector<CliCmd> mCommands{};
std::string mVersionString = ""; std::string mVersionString = "";

View File

@@ -19,15 +19,18 @@
#include "Bitmap.hpp" #include "Bitmap.hpp"
#include <algorithm>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
#include <ranges> #include <iostream>
#include <stdexcept> #include <iterator>
#include <optional>
#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) : mWidth{width}, mHeight{height}, mPixels(width * height) {} Bitmap<T>::Bitmap(uint16_t width, uint16_t height)
: mWidth{width}, mHeight{height}, mPixels(width * height) {}
template <class T> template <class T>
[[nodiscard]] uint16_t Bitmap<T>::getWidth() const { [[nodiscard]] uint16_t Bitmap<T>::getWidth() const {
@@ -42,7 +45,8 @@ template <class T>
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 (got {} vs. {} bitmap size).", pixels.size(), mPixels.size()); spdlog::error("Invalid pixel buffer size (got {} vs. {} bitmap size).", pixels.size(),
mPixels.size());
return false; return false;
} }
@@ -56,29 +60,34 @@ template <class T>
} }
template <class T> template <class T>
[[nodiscard]] std::vector<T> Bitmap<T>::getLine(const uint16_t lineNo) const { [[nodiscard]] std::optional<std::vector<T>> Bitmap<T>::getLine(uint16_t line) const {
if (lineNo >= mHeight) { if (line >= mHeight) {
throw(std::out_of_range("Line is out of range!")); // out of bound
return std::nullopt;
} }
auto lineStart = mPixels.begin() + (lineNo * mWidth);
auto lineEnd = mPixels.begin() + ((lineNo + 1) * mWidth); auto lineStart = mPixels.begin() + (line * 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>
[[nodiscard]] std::vector<T> Bitmap<T>::getCol(const uint16_t colNo) const { [[nodiscard]] std::optional<std::vector<T>> Bitmap<T>::getCol(uint16_t col) const {
if (colNo >= mWidth) { if (col >= mWidth) {
throw(std::out_of_range("Col is out of range!")); // out of bound
return std::nullopt;
} }
std::vector<T> col{}; // first pixel is always beginning of the col
col.reserve(mHeight); std::vector<T> colPixels(mHeight);
for (size_t i{0}; i <= mPixels.size(); i++) { auto it = std::next(mPixels.begin(), col);
if (i % mWidth == colNo) {
col.push_back(mPixels[i]); for (auto& colElement : colPixels) {
} colElement = *it;
std::advance(it, mWidth);
} }
return col;
return colPixels;
} }
} // namespace ptprnt::graphics } // namespace ptprnt::graphics

View File

@@ -19,17 +19,19 @@
#pragma once #pragma once
#include <stdint.h>
#include <cstdint> #include <cstdint>
#include <memory> #include <memory>
#include <span> #include <optional>
#include <vector> #include <vector>
namespace ptprnt::graphics { namespace ptprnt::graphics {
using ALPHA8 = std::uint8_t; // Alpha only, 8 bit per pixel typedef uint8_t ALPHA8; // Alpha only, 8 bit per pixel
using RGBX8 = std::uint32_t; // RGB, least significant byte unused, 8 bit per channel typedef uint32_t RGBX8; // RGB, least significant byte unused, 8 bit per channel
using RGBA8 = std::uint32_t; // RGB, least significant byte alpha, 8 bit per channel typedef uint32_t RGBA8; // RGB, least significant byte alpha, 8 bit per channel
using ARGB8 = std::uint32_t; // RGB, most significant byte alpha, 8 bit per channel typedef uint32_t ARGB8; // RGB, most significant byte alpha, 8 bit per channel
template <class T> template <class T>
class Bitmap { class Bitmap {
@@ -46,8 +48,8 @@ class Bitmap {
[[nodiscard]] uint16_t getHeight() const; [[nodiscard]] uint16_t getHeight() const;
bool setPixels(const std::vector<T>& pixels); bool setPixels(const std::vector<T>& pixels);
[[nodiscard]] std::vector<T> getPixelsCpy() const; [[nodiscard]] std::vector<T> getPixelsCpy() const;
[[nodiscard]] std::vector<T> getLine(uint16_t line) const; [[nodiscard]] std::optional<std::vector<T>> getLine(uint16_t line) const;
[[nodiscard]] std::vector<T> getCol(uint16_t col) const; [[nodiscard]] std::optional<std::vector<T>> getCol(uint16_t col) const;
void visualize() const; void visualize() const;
private: private:

View File

@@ -24,24 +24,23 @@
#include <cassert> #include <cassert>
#include <cstddef> #include <cstddef>
#include <cstdint> #include <iostream> // remove me
#include <string> #include <string>
#include <vector> #include <vector>
#include "cairo.h" #include "cairo.h"
#include "graphics/interface/ILabel.hpp" #include "pango/pango-context.h"
#include "pango/pango-font.h" #include "pango/pango-font.h"
#include "pango/pango-fontmap.h"
#include "pango/pango-layout.h" #include "pango/pango-layout.h"
#include "pango/pango-types.h" #include "pango/pango-types.h"
#include "pango/pangocairo.h" #include "pango/pangocairo.h"
namespace ptprnt::graphics { namespace ptprnt::graphics {
Label::Label(const uint16_t heightPixel) Label::Label()
: mCairoCtx(cairo_create(mSurface)), : mPangoCtx(pango_font_map_create_context(pango_cairo_font_map_get_default())),
mPangoCtx(pango_cairo_create_context(mCairoCtx)),
mPangoLyt(pango_layout_new(mPangoCtx)), mPangoLyt(pango_layout_new(mPangoCtx)),
mFontMap(pango_cairo_font_map_new()), mPangoFontDesc(pango_font_description_from_string("Noto sans 32")) {}
mPrinterHeight(heightPixel) {}
std::vector<uint8_t> Label::getRaw() { std::vector<uint8_t> Label::getRaw() {
assert(mSurface != nullptr); assert(mSurface != nullptr);
@@ -56,14 +55,6 @@ uint8_t Label::getNumLines(std::string_view strv) {
return std::count(strv.begin(), strv.end(), '\n'); return std::count(strv.begin(), strv.end(), '\n');
} }
int Label::getWidth() {
return mPrinterHeight;
}
int Label::getHeight() {
return getLayoutWidth();
}
int Label::getLayoutHeight() { int Label::getLayoutHeight() {
return mLayoutHeight; return mLayoutHeight;
} }
@@ -72,81 +63,29 @@ int Label::getLayoutWidth() {
return mLayoutWidth; return mLayoutWidth;
} }
bool Label::create(PrintableText printableText) { void Label::create(const std::string& labelText, const uint16_t heightPixel) {
setFontFamily(printableText.fontFamily); mPrinterHeight = heightPixel;
setFontSize(printableText.fontSize); pango_layout_set_single_paragraph_mode(mPangoLyt, true);
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_height(mPangoLyt, getNumLines(labelText) * -1);
pango_layout_set_font_description(mPangoLyt, regularFont); pango_layout_set_alignment(mPangoLyt, PANGO_ALIGN_CENTER);
pango_layout_set_font_description(mPangoLyt, mPangoFontDesc);
pango_context_load_font(mPangoCtx, mPangoFontDesc);
pango_layout_set_text(mPangoLyt, labelText.c_str(), static_cast<int>(labelText.length())); 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); pango_layout_get_size(mPangoLyt, &mLayoutWidth, &mLayoutHeight);
mLayoutWidth /= PANGO_SCALE; mLayoutWidth /= PANGO_SCALE;
mLayoutHeight /= PANGO_SCALE; mLayoutHeight /= PANGO_SCALE;
spdlog::debug("Layout width: {}, height: {}", mLayoutWidth, mLayoutHeight); SPDLOG_DEBUG("Layout width: {}, height: {}", mLayoutWidth, mLayoutHeight);
auto alignedWidth = mLayoutWidth + (8 - (mLayoutWidth % 8));
mSurface = cairo_image_surface_create(CAIRO_FORMAT_A8, alignedWidth, mPrinterHeight); mSurface = cairo_image_surface_create(CAIRO_FORMAT_A8, mLayoutWidth, mPrinterHeight);
cairo_t* cr = cairo_create(mSurface); 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); pango_cairo_show_layout(cr, mPangoLyt);
cairo_set_source_rgb(cr, 0.0, 0.0, 0.0); cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
cairo_surface_flush(mSurface); cairo_surface_flush(mSurface);
cairo_destroy(cr); cairo_destroy(cr);
return true;
} }
void Label::writeToPng(const std::string& file) { void Label::writeToPng(const std::string& file) {
@@ -156,31 +95,11 @@ void Label::writeToPng(const std::string& file) {
} }
} }
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() { Label::~Label() {
spdlog::debug("Image dtor..."); SPDLOG_DEBUG("Image dtor...");
pango_font_description_free(mPangoFontDesc);
g_object_unref(mPangoCtx); g_object_unref(mPangoCtx);
g_object_unref(mPangoLyt); g_object_unref(mPangoLyt);
g_object_unref(mFontMap);
cairo_surface_destroy(mSurface); cairo_surface_destroy(mSurface);
} }
} // namespace ptprnt::graphics } // namespace ptprnt::graphics

View File

@@ -26,52 +26,38 @@
#include <vector> #include <vector>
#include "cairo.h" #include "cairo.h"
#include "graphics/interface/ILabel.hpp" #include "pango/pango-font.h"
#include "pango/pango-types.h" #include "pango/pango-types.h"
namespace ptprnt::graphics { namespace ptprnt::graphics {
class Label : public ILabel { constexpr const char* DEFAULT_FONT_FAMILY = "sans";
constexpr const uint8_t DEFAULT_FONT_SIZE = 32;
class Label {
public: public:
Label(const uint16_t heightPixel); Label();
~Label() override; ~Label();
Label(const Label&) = delete; Label(const Label&) = delete;
Label& operator=(const Label&) = delete; Label& operator=(const Label&) = delete;
Label(Label&&) = delete; Label(Label&&) = delete;
Label& operator=(Label&&) = delete; Label& operator=(Label&&) = delete;
bool create(PrintableText printableText) override; std::vector<uint8_t> getRaw();
bool create(const std::string& labelText) override; void create(const std::string& labelText, const uint16_t heightPixel);
void writeToPng(const std::string& file); void writeToPng(const std::string& file);
[[nodiscard]] int getWidth() override; int getLayoutWidth();
[[nodiscard]] int getHeight() override; int getLayoutHeight();
[[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: private:
// methods // methods
[[nodiscard]] uint8_t getNumLines(std::string_view str); uint8_t getNumLines(std::string_view str);
[[nodiscard]] PangoFontMap* createCustomFontMap();
// members // 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}; PangoContext* mPangoCtx{nullptr};
PangoLayout* mPangoLyt{nullptr}; PangoLayout* mPangoLyt{nullptr};
PangoFontMap* mFontMap{nullptr}; PangoFontDescription* mPangoFontDesc{nullptr};
double mFontSize{DEFAULT_FONT_SIZE}; cairo_surface_t* mSurface{nullptr};
std::string mFontFamily{DEFAULT_FONT_FAMILY};
HAlignPosition mHAlign = HAlignPosition::LEFT;
VAlignPosition mVAlign = VAlignPosition::MIDDLE;
std::string mText{""};
int mLayoutWidth = 0, mLayoutHeight = 0; int mLayoutWidth = 0, mLayoutHeight = 0;
int mPrinterHeight = 0; int mPrinterHeight = 0;
}; };

View File

@@ -21,15 +21,13 @@
#include <cmath> #include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream> #include <iostream>
#include <vector> #include <vector>
namespace ptprnt::graphics { namespace ptprnt::graphics {
Monochrome::Monochrome(const std::vector<uint8_t>& grayscale, uint32_t width, uint32_t height) Monochrome::Monochrome(const std::vector<uint8_t>& grayscale) : mPixels(std::move(grayscale)) {}
: 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;
@@ -40,30 +38,24 @@ void Monochrome::invert(bool shouldInvert) {
} }
std::vector<uint8_t> Monochrome::get() { std::vector<uint8_t> Monochrome::get() {
// Calculate output size for packed format: (width + 7) / 8 bytes per row std::vector<uint8_t> outPixels(
uint32_t stride = (mWidth + 7) / 8; (static_cast<unsigned int>((mPixels.size() / 8)) + (std::floor(mPixels.size() % 8 + 0.9))));
size_t outputSize = stride * mHeight;
std::vector<uint8_t> outPixels(outputSize, 0);
// Pack pixels row by row for correct 2D layout unsigned int outIndex = 0;
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
// Convert grayscale pixel to bit based on threshold for (unsigned int byteNo = 0; byteNo < mPixels.size(); byteNo += 8) {
bool pixelOn = mPixels[pixelIndex] > mThreshhold; for (unsigned int bitNo = 0; bitNo <= 7 && (byteNo + bitNo < mPixels.size()); bitNo++) {
if (mShouldInvert) { if (mPixels[byteNo + bitNo] > mThreshhold) {
pixelOn = !pixelOn; outPixels[outIndex] |= (1 << (7 - bitNo));
} } else {
outPixels[outIndex] &= ~(1 << (7 - bitNo));
if (pixelOn) {
outPixels[byteIndex] |= (1 << bitIndex);
} }
} }
if (mShouldInvert) {
outPixels[outIndex] = ~outPixels[outIndex];
}
outIndex++;
} }
return outPixels; return outPixels;
} }
@@ -82,164 +74,4 @@ void Monochrome::visualize() {
std::cout << std::endl; 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

View File

@@ -20,61 +20,22 @@
#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, uint32_t width, uint32_t height); Monochrome(const std::vector<uint8_t>& grayscale);
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(); void visualize();
std::vector<uint8_t> get(); std::vector<uint8_t> get();
MonochromeData getMonochromeData();
private: private:
std::vector<uint8_t> mPixels; const std::vector<uint8_t>& mPixels;
uint32_t mWidth;
uint32_t mHeight;
uint8_t mThreshhold = UINT8_MAX / 2; uint8_t mThreshhold = UINT8_MAX / 2;
bool mShouldInvert = false; bool mShouldInvert = false;
}; };

View File

@@ -1,82 +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 <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

7
src/hello.txt Normal file
View File

@@ -0,0 +1,7 @@
{
"text" : " Hello",
"font" : "FreeSans 32",
"single-paragraph" : true,
"alignment" : "center",
"height" : 0
}

View File

@@ -23,8 +23,6 @@
#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"
@@ -32,18 +30,17 @@ namespace ptprnt {
class IPrinterDriver { class IPrinterDriver {
public: public:
virtual ~IPrinterDriver() = default; virtual ~IPrinterDriver() = default;
[[nodiscard]] virtual const std::string_view getDriverName() = 0; virtual const std::string_view getDriverName() = 0;
[[nodiscard]] virtual const std::string_view getName() = 0; virtual const std::string_view getName() = 0;
[[nodiscard]] virtual const std::string_view getVersion() = 0; virtual const std::string_view getVersion() = 0;
[[nodiscard]] virtual const libusbwrap::usbId getUsbId() = 0; virtual const uint16_t getVid() = 0;
[[nodiscard]] virtual const PrinterInfo getPrinterInfo() = 0; virtual const uint16_t getPid() = 0;
[[nodiscard]] virtual const PrinterStatus getPrinterStatus() = 0; virtual const PrinterInfo getPrinterInfo() = 0;
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 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 printText(const std::string& text, uint16_t fontSize) = 0;
virtual bool printLabel(const std::unique_ptr<graphics::ILabel> label) = 0;
virtual bool print() = 0;
}; };
} // namespace ptprnt } // namespace ptprnt

View File

@@ -20,20 +20,18 @@
#pragma once #pragma once
#include <cstdint> #include <cstdint>
#include <string>
#include <string_view> #include <string_view>
#include <vector> #include <vector>
#include "libusbwrap/LibUsbTypes.hpp"
namespace ptprnt { namespace ptprnt {
struct PrinterInfo { struct PrinterInfo {
std::string_view driverName = ""; std::string_view driverName = "";
std::string_view name = ""; std::string_view name = "";
std::string_view version = ""; std::string_view version = "";
libusbwrap::usbId usbId{0x00, 0x00}; uint16_t vid = 0x00;
uint16_t pixelLines = 0; uint16_t pid = 0x00;
uint16_t pixelLines = 0;
}; };
struct PrinterStatus { struct PrinterStatus {

View File

@@ -19,7 +19,7 @@
#pragma once #pragma once
#include <utility> #include <memory>
#include "libusb.h" #include "libusb.h"
@@ -40,7 +40,4 @@ enum class Error {
NOT_SUPPORTED = LIBUSB_ERROR_NOT_SUPPORTED, NOT_SUPPORTED = LIBUSB_ERROR_NOT_SUPPORTED,
OTHER = LIBUSB_ERROR_OTHER OTHER = LIBUSB_ERROR_OTHER
}; };
}
using usbId = std::pair<uint16_t, uint16_t>;
} // namespace libusbwrap

View File

@@ -27,7 +27,8 @@
#include "libusbwrap/interface/IUsbDevice.hpp" #include "libusbwrap/interface/IUsbDevice.hpp"
namespace libusbwrap { namespace libusbwrap {
UsbDevice::UsbDevice(libusb_context* ctx, usbDevice_ptr dev) : mLibusbCtx(ctx), mLibusbDev(std::move(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");
} }
@@ -90,12 +91,13 @@ bool UsbDevice::releaseInterface(int interfaceNo) {
return true; return true;
} }
bool UsbDevice::bulkTransfer(uint8_t endpoint, const std::vector<uint8_t>& data, int* tx, unsigned int timeout) { bool UsbDevice::bulkTransfer(uint8_t endpoint, std::vector<uint8_t>& data, int* tx,
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 = libusb_bulk_transfer(mLibusbDevHandle, endpoint, const_cast<unsigned char*>(data.data()), bulkTransferStatus =
data.size(), tx, timeout); libusb_bulk_transfer(mLibusbDevHandle, endpoint, data.data(), data.size(), tx, timeout);
if (bulkTransferStatus != 0) { if (bulkTransferStatus != 0) {
mLastError = static_cast<Error>(bulkTransferStatus); mLastError = static_cast<Error>(bulkTransferStatus);
return false; return false;
@@ -103,8 +105,12 @@ bool UsbDevice::bulkTransfer(uint8_t endpoint, const std::vector<uint8_t>& data,
return true; return true;
} }
const usbId UsbDevice::getUsbId() { const uint16_t UsbDevice::getVid() {
return {mLibusbDevDesc.idVendor, mLibusbDevDesc.idProduct}; return mLibusbDevDesc.idVendor;
}
const uint16_t UsbDevice::getPid() {
return mLibusbDevDesc.idProduct;
} }
const device::Speed UsbDevice::getSpeed() { const device::Speed UsbDevice::getSpeed() {

View File

@@ -20,7 +20,7 @@
#pragma once #pragma once
#include <atomic> #include <atomic>
#include <memory> #include <cstddef>
#include "libusb.h" #include "libusb.h"
#include "libusbwrap/LibUsbTypes.hpp" #include "libusbwrap/LibUsbTypes.hpp"
@@ -56,10 +56,12 @@ 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, const std::vector<uint8_t>& data, int* tx, unsigned int timeout) override; bool bulkTransfer(uint8_t endpoint, std::vector<uint8_t>& data, int* tx,
unsigned int timeout) override;
// getters // getters
const usbId getUsbId() override; const uint16_t getVid() override;
const uint16_t getPid() override;
const device::Speed getSpeed() override; const device::Speed getSpeed() override;
const uint8_t getBusNumber() override; const uint8_t getBusNumber() override;
const uint8_t getPortNumber() override; const uint8_t getPortNumber() override;

View File

@@ -29,13 +29,15 @@ 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, const std::vector<uint8_t>& data, int* tx, unsigned int timeout) = 0; virtual bool bulkTransfer(uint8_t endpoint, std::vector<uint8_t>& data, int* tx,
unsigned int timeout) = 0;
// getters // getters
virtual const usbId getUsbId() = 0; virtual const uint16_t getVid() = 0;
virtual const uint16_t getPid() = 0;
virtual const device::Speed getSpeed() = 0; virtual const device::Speed getSpeed() = 0;
virtual const uint8_t getBusNumber() = 0; virtual const uint8_t getBusNumber() = 0;
virtual const uint8_t getPortNumber() = 0; virtual const uint8_t getPortNumber() = 0;

View File

@@ -8,7 +8,6 @@ ptprnt_hpps = files (
'interface/IPrinterTypes.hpp', 'interface/IPrinterTypes.hpp',
'P700Printer.hpp', 'P700Printer.hpp',
'PtouchPrint.hpp', 'PtouchPrint.hpp',
'PrinterDriverFactory.hpp',
'graphics/Bitmap.hpp', 'graphics/Bitmap.hpp',
'graphics/Label.hpp', 'graphics/Label.hpp',
'graphics/Monochrome.hpp' 'graphics/Monochrome.hpp'
@@ -16,7 +15,6 @@ ptprnt_hpps = files (
ptprnt_srcs = files ( ptprnt_srcs = files (
'PtouchPrint.cpp', 'PtouchPrint.cpp',
'PrinterDriverFactory.cpp',
'P700Printer.cpp', 'P700Printer.cpp',
'graphics/Label.cpp', 'graphics/Label.cpp',
'graphics/Bitmap.cpp', 'graphics/Bitmap.cpp',

View File

@@ -22,6 +22,7 @@
#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) {
@@ -35,28 +36,34 @@ 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
EXPECT_ANY_THROW(auto outOfBoundsLine = bm.getLine(8)); 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);
auto lineSize = line.size(); if (!line) {
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);
EXPECT_ANY_THROW(auto outOfBoundsCol = bm.getCol(16)); ASSERT_EQ(std::nullopt, outOfBoundsCol);
} }
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) {
auto colSize = col.size(); FAIL() << "Returned Col is invalid";
}
auto colSize = col->size();
ASSERT_EQ(8, colSize); ASSERT_EQ(8, colSize);
} }

View File

@@ -21,6 +21,8 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <optional>
TEST(basic_test, Label_smokeTest_succeeds) { TEST(basic_test, Label_smokeTest_succeeds) {
auto im = ptprnt::graphics::Label(4711); auto im = ptprnt::graphics::Label();
} }

View File

@@ -1,40 +1,14 @@
tests = [ tests = [['bitmap_test', 'bitmap_test_exe', ptprnt_srcs + ['bitmap_test/bitmap_test.cpp']],
[ ['label_test', 'label_test_exe', ptprnt_srcs +['label_test/label_test.cpp']],
'bitmap_test', ['monochrome_test', 'monochrome_test_exe', ptprnt_srcs +['monochrome_test/monochrome_test.cpp']]
'bitmap_test_exe', ]
['../src/graphics/Bitmap.cpp', 'bitmap_test/bitmap_test.cpp'],
],
[
'label_test',
'label_test_exe',
['../src/graphics/Label.cpp', 'label_test/label_test.cpp'],
],
[
'monochrome_test',
'monochrome_test_exe',
[
'../src/graphics/Monochrome.cpp',
'monochrome_test/monochrome_test.cpp',
],
],
]
foreach test : tests foreach test : tests
test( test(test.get(0),
test.get(0), executable(test.get(1),
executable( sources: test.get(2),
test.get(1), include_directories: incdir,
sources: test.get(2), dependencies: [gtest_dep, usb_dep, log_dep, pangocairo_dep, cli11_dep]
include_directories: incdir, )
dependencies: [
gtest_dep,
usb_dep,
log_dep,
pangocairo_dep,
cli11_dep,
],
),
) )
endforeach endforeach

View File

@@ -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( 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, 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, 16, 1); auto mono = ptprnt::graphics::Monochrome(pixels);
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( 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, 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, 16, 1); auto mono = ptprnt::graphics::Monochrome(pixels);
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( 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, 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, 16, 1); auto mono = ptprnt::graphics::Monochrome(pixels);
mono.setThreshold(16); mono.setThreshold(16);
auto out = mono.get(); auto out = mono.get();
@@ -57,107 +57,12 @@ TEST(basic_test, Monochrome_convertWithCustomThreshhold_yieldsMonochromeRespecti
} }
TEST(basic_test, Monochrome_convertNonAlignedPixels_spillsOverIntoNewByte) { TEST(basic_test, Monochrome_convertNonAlignedPixels_spillsOverIntoNewByte) {
// TODO: We need to find to access the vector without the possiblity of out-of-bounds access const std::vector<uint8_t> pixels({0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00,
// Ideas: constexpr? compile time check? 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF});
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, 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, 17, 1); auto mono = ptprnt::graphics::Monochrome(pixels);
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
} }