8 Commits

Author SHA1 Message Date
3dc5da6fc8 Fix Monochrome class with new data structure, unit tests. There is work to be done still
All checks were successful
Build ptprnt / build (push) Successful in 3m51s
2025-09-11 10:02:43 +02:00
5132eab6fa Merge branch 'master' into generate-text-part-one
All checks were successful
Build ptprnt / build (push) Successful in 2m34s
2024-05-01 11:27:54 +02:00
eaf566ff28 Improve actions pipeline (#12)
All checks were successful
Build ptprnt / build (push) Successful in 1m54s
Act runner upgraded, let's see what the versions are...

Reviewed-on: #12
2024-05-01 09:23:12 +00:00
77c6b7bc7b Fix for the old dependency code in the CI
All checks were successful
Build ptprnt / build (push) Successful in 2m31s
2024-04-28 20:49:10 +02:00
f702ec5473 Small Todos for the next session, some clean up
Some checks failed
Build ptprnt / build (push) Failing after 32s
2024-04-28 20:44:13 +02:00
59ef4189c4 Implement Label printing interface for PrinterDriver
Some checks failed
Build ptprnt / build (push) Failing after 32s
2024-04-28 20:02:07 +02:00
bb7ab6239d Implement basic layouting
Some checks failed
Build ptprnt / build (push) Failing after 37s
2024-04-28 17:38:56 +02:00
37ee7c10f1 c++ standard needs to be c++2a as c++20 is not possible with CI
All checks were successful
Build ptprnt / build (push) Successful in 1m23s
2024-04-20 14:03:51 +02:00
22 changed files with 758 additions and 249 deletions

View File

@@ -2,7 +2,6 @@
Checks: "clang-diagnostic-*,clang-analyzer-*,cppcoreguidelines-*,modernize-*,-modernize-use-trailing-return-type"
WarningsAsErrors: true
HeaderFilterRegex: ""
AnalyzeTemporaryDtors: false
FormatStyle: google
CheckOptions:
- key: cert-dcl16-c.NewSuffixes

View File

@@ -15,13 +15,40 @@ jobs:
run: apt-get -yq install meson
- name: Install build dependencies
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
run: meson setup builddir -Db_coverage=true
- name: build all targets
run: ninja -C builddir
- name: build and test dist package
run: ninja -C builddir dist
- name: run unit tests
run: ninja -C builddir test
- name: calculate coverage
run: ninja -C builddir coverage-text
- name: Coverage report
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

View File

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

2
.vscode/launch.json vendored
View File

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

View File

@@ -83,11 +83,5 @@
"charconv": "cpp",
"*.ipp": "cpp"
},
"clang-tidy.buildPath": "builddir/",
"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,7 +1,22 @@
project('ptprnt', 'cpp',
version: 'v0.1.0-'+run_command('git', 'rev-parse', '--short', 'HEAD', check: true).stdout().strip(),
project(
'ptprnt',
'cpp',
version: 'v0.1.0-' + run_command(
'git',
'rev-parse',
'--short',
'HEAD',
check: true,
).stdout().strip(),
license: 'GPLv3',
default_options : ['c_std=c11', 'cpp_std=c++20', 'b_sanitize=none', 'b_lto=true', 'b_lto_mode=thin', 'b_thinlto_cache=true']
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')
@@ -21,13 +36,13 @@ incdir = include_directories('src')
subdir('src')
ptprnt_exe = executable(
'ptprnt',
'ptprnt',
'src/main.cpp',
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,
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.')
endif
subdir('tests')
subdir('tests')

View File

@@ -1,4 +1,4 @@
/*
/*
ptrnt - print labels on linux
Copyright (C) 2023 Moritz Martinius
@@ -23,6 +23,7 @@
#include <cstdint>
#include <iterator>
#include <memory>
#include <thread>
#include <vector>
@@ -32,7 +33,7 @@
#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 ;)
//#define DRYRUN
#define DRYRUN
namespace ptprnt::printer {
@@ -43,7 +44,7 @@ const PrinterInfo P700Printer::mInfo = {.driverName = "P700",
.pixelLines = 128};
P700Printer::~P700Printer() {
detachUsbDevice();
P700Printer::detachUsbDevice();
if (mUsbHndl) {
mUsbHndl->close();
}
@@ -91,6 +92,7 @@ bool P700Printer::attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHnd
}
if (!usbHndl->detachKernelDriver(0)) {
spdlog::error("Device is already in use or couldn't be detached from kernel: {}",
usbHndl->getLastErrorString());
return false;
@@ -118,64 +120,66 @@ bool P700Printer::detachUsbDevice() {
}
bool P700Printer::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) {
#ifdef DRYRUN
SPDLOG_DEBUG("DRYRUN enabled");
for (unsigned int lineNo = 0; lineNo < bitmap.getHeight(); lineNo++) {
auto line = bitmap.getLine(lineNo);
auto monoLine = graphics::Monochrome(*line);
monoLine.visualize();
}
#endif
// 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
spdlog::debug("DRYRUN enabled");
data.visualize();
#endif
send(p700::commands::RASTER_START);
std::vector<uint8_t> rastercmd(4);
rastercmd[0] = 0x47;
rastercmd[1] = 0x00; // size +1
rastercmd[2] = 0x00;
rastercmd[3] = 0x00; // size -1
for (unsigned int i = 0; i < bitmap.getWidth(); i++) {
auto bmcol = bitmap.getCol(i);
if (!bmcol) {
spdlog::error("Out of bounds bitmap access");
break;
// Process data column by column for the printer
for (uint32_t col = 0; col < data.width; col++) {
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);
}
auto monocol = graphics::Monochrome(*bmcol);
auto col = monocol.get();
std::vector<uint8_t> buf(0);
std::vector<uint8_t> buf;
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;
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;
};
}
}
send(p700::commands::EJECT);
return true;
}
bool P700Printer::setText(const std::string& text) {
return true;
};
bool P700Printer::setFont(const std::string& text) {
return true;
};
bool P700Printer::setFontSize(uint8_t fontSize) {
return true;
};
bool P700Printer::setHAlign(HAlignPosition hpos) {
return true;
};
bool P700Printer::setVAlign(VAlignPosition vpos) {
return true;
bool P700Printer::printLabel(std::unique_ptr<graphics::ILabel> label) {
// 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() {
@@ -192,7 +196,7 @@ bool P700Printer::send(const std::vector<uint8_t>& data) {
return false;
}
int tx = 0;
size_t tx = 0;
#ifndef DRYRUN
if (!mUsbHndl->bulkTransfer(0x02, data, &tx, 0)) {
@@ -201,10 +205,10 @@ bool P700Printer::send(const std::vector<uint8_t>& data) {
}
#else
tx = data.size();
spdlog::info("USB raw data(len {}): {}", data.size(), spdlog::to_hex(data));
spdlog::trace("USB raw data(len {}): {}", data.size(), spdlog::to_hex(data));
#endif
if (tx != static_cast<int>(data.size())) {
if (tx != data.size()) {
spdlog::error("Could not transfer all data via USB bulk transfer. Only sent {} of {} bytes", tx, data.size());
return false;
}
@@ -218,4 +222,4 @@ bool P700Printer::init() {
cmd[101] = 0x40; /* @ */
return send(cmd);
}
} // namespace ptprnt::printer
} // namespace ptprnt::printer

View File

@@ -44,6 +44,9 @@ const cmd_T PRINTER_INFO{0x81};
constexpr uint8_t MAX_TRIES_GET_STATUS = 10;
// TODO:
// Remove Text-layout specific parts, add them to label
class P700Printer : public ::ptprnt::IPrinterDriver {
public:
P700Printer() = default;
@@ -67,12 +70,9 @@ class P700Printer : public ::ptprnt::IPrinterDriver {
[[nodiscard]] const PrinterStatus getPrinterStatus() override;
bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) 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 printMonochromeData(const graphics::MonochromeData& data) override;
bool printLabel(const std::unique_ptr<graphics::ILabel> label) override;
bool print() override;
private:

View File

@@ -16,12 +16,10 @@
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cstdint>
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE
#define SPDLOG_DEBUG_ON
#define SPDLOG_TRACE_ON
#include "PtouchPrint.hpp"
#include <CLI/App.hpp>
#include <algorithm>
#include <fmt/core.h>
#include <spdlog/common.h>
#include <spdlog/details/synchronous_factory.h>
@@ -31,15 +29,16 @@
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h>
#include <cctype>
#include <functional>
#include <memory>
#include <unordered_set>
#include <vector>
#include "CLI/Option.hpp"
#include "PrinterDriverFactory.hpp"
#include "PtouchPrint.hpp"
#include "graphics/Bitmap.hpp"
#include "graphics/Label.hpp"
#include "graphics/interface/ILabel.hpp"
#include "libusbwrap/UsbDeviceFactory.hpp"
namespace ptprnt {
@@ -98,37 +97,64 @@ int PtouchPrint::run() {
return 0;
}
for (auto& cmd : mCommands) {
switch (cmd.first) {
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:
spdlog::debug("Setting text to {}", cmd.second);
printer->setText(cmd.second);
if (labelText.empty()) {
labelText = value;
} else {
labelText = labelText + '\n' + value;
}
break;
case CliCmdType::Font:;
spdlog::debug("Setting font to {}", cmd.second);
printer->setFont(cmd.second);
case CliCmdType::Font:
spdlog::debug("Setting font to {}", value);
label->setFontFamily(value);
break;
case CliCmdType::FontSize:;
spdlog::debug("Setting font size to {}", cmd.second);
printer->setFontSize(static_cast<uint8_t>(std::atoi(cmd.second.c_str())));
case CliCmdType::FontSize:
spdlog::debug("Setting font size to {}", std::stod(value));
label->setFontSize(std::stod(value));
break;
case CliCmdType::HAlign:;
spdlog::debug("[Not implemented] Setting text horizontal alignment to {}", cmd.second);
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("[Not implemented] Setting text vertical alignment to {}", cmd.second);
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:;
case CliCmdType::None:
[[fallthrough]];
default:
spdlog::warn("This command is currently not supported.");
break;
}
}
/*if (!printer->print()) {
label->create(labelText);
label->writeToPng("./testlabel.png");
/*if (!printer->printLabel(std::move(label))) {
spdlog::error("An error occured while printing");
return -1;
}*/
return 0;
}
@@ -152,7 +178,8 @@ void PtouchPrint::setupLogger(spdlog::level::level_enum lvl) {
consoleSink->set_level(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
consoleSink->set_pattern("%^%L:%$ %v (%s:%#)");
// TODO: line number and functions only work with macros
consoleSink->set_pattern("%^%L:%$ %v");
} else {
consoleSink->set_pattern("%^%L:%$ %v");
}
@@ -166,6 +193,7 @@ void PtouchPrint::setupLogger(spdlog::level::level_enum lvl) {
spdlog::set_default_logger(logger);
}
// TODO: CLI parsing should be a seperate class/file
void PtouchPrint::setupCliParser() {
auto printVersion = [this](std::size_t) {
fmt::print("ptprnt version: {}\n", mVersionString);
@@ -185,23 +213,39 @@ void PtouchPrint::setupCliParser() {
->each([this](std::string text) { mCommands.emplace_back(CliCmdType::Text, text); });
mApp.add_option("-f,--font", "Font used for the following text occurences")
->group("Text printing ")
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->multi_option_policy(CLI::MultiOptionPolicy::TakeFirst)
->trigger_on_parse()
->each([this](std::string font) { mCommands.emplace_back(CliCmdType::Font, font); });
mApp.add_option("-s,--fontsize", "Font size of the following text occurences")
->group("Text printing ")
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->multi_option_policy(CLI::MultiOptionPolicy::TakeFirst)
->trigger_on_parse()
->each([this](std::string size) { mCommands.emplace_back(CliCmdType::FontSize, size); });
mApp.add_option("--valign", "Vertical alignment of the following text occurences")
->group("Text printing ")
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->multi_option_policy(CLI::MultiOptionPolicy::TakeFirst)
->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); });
mApp.add_option("--halign", "Vertical alignment of the following text occurences")
->group("Text printing ")
->multi_option_policy(CLI::MultiOptionPolicy::TakeAll)
->multi_option_policy(CLI::MultiOptionPolicy::TakeFirst)
->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); });
// Image options

View File

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

View File

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

View File

@@ -24,23 +24,24 @@
#include <cassert>
#include <cstddef>
#include <iostream> // remove me
#include <cstdint>
#include <string>
#include <vector>
#include "cairo.h"
#include "pango/pango-context.h"
#include "graphics/interface/ILabel.hpp"
#include "pango/pango-font.h"
#include "pango/pango-fontmap.h"
#include "pango/pango-layout.h"
#include "pango/pango-types.h"
#include "pango/pangocairo.h"
namespace ptprnt::graphics {
Label::Label()
: mPangoCtx(pango_font_map_create_context(pango_cairo_font_map_get_default())),
Label::Label(const uint16_t heightPixel)
: mCairoCtx(cairo_create(mSurface)),
mPangoCtx(pango_cairo_create_context(mCairoCtx)),
mPangoLyt(pango_layout_new(mPangoCtx)),
mPangoFontDesc(pango_font_description_from_string("Noto sans 32")) {}
mFontMap(pango_cairo_font_map_new()),
mPrinterHeight(heightPixel) {}
std::vector<uint8_t> Label::getRaw() {
assert(mSurface != nullptr);
@@ -55,6 +56,14 @@ 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;
}
@@ -63,29 +72,81 @@ int Label::getLayoutWidth() {
return mLayoutWidth;
}
void Label::create(const std::string& labelText, const uint16_t heightPixel) {
mPrinterHeight = heightPixel;
pango_layout_set_single_paragraph_mode(mPangoLyt, true);
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_alignment(mPangoLyt, PANGO_ALIGN_CENTER);
pango_layout_set_font_description(mPangoLyt, mPangoFontDesc);
pango_context_load_font(mPangoCtx, mPangoFontDesc);
pango_layout_set_font_description(mPangoLyt, regularFont);
pango_layout_set_text(mPangoLyt, labelText.c_str(), static_cast<int>(labelText.length()));
pango_layout_get_size(mPangoLyt, &mLayoutWidth, &mLayoutHeight);
// 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);
spdlog::debug("Layout width: {}, height: {}", mLayoutWidth, mLayoutHeight);
auto alignedWidth = mLayoutWidth + (8 - (mLayoutWidth % 8));
mSurface = cairo_image_surface_create(CAIRO_FORMAT_A8, mLayoutWidth, mPrinterHeight);
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) {
@@ -95,11 +156,31 @@ 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() {
SPDLOG_DEBUG("Image dtor...");
pango_font_description_free(mPangoFontDesc);
spdlog::debug("Image dtor...");
g_object_unref(mPangoCtx);
g_object_unref(mPangoLyt);
g_object_unref(mFontMap);
cairo_surface_destroy(mSurface);
}
} // namespace ptprnt::graphics

View File

@@ -26,38 +26,52 @@
#include <vector>
#include "cairo.h"
#include "pango/pango-font.h"
#include "graphics/interface/ILabel.hpp"
#include "pango/pango-types.h"
namespace ptprnt::graphics {
constexpr const char* DEFAULT_FONT_FAMILY = "sans";
constexpr const uint8_t DEFAULT_FONT_SIZE = 32;
class Label {
class Label : public ILabel {
public:
Label();
~Label();
Label(const uint16_t heightPixel);
~Label() override;
Label(const Label&) = delete;
Label& operator=(const Label&) = delete;
Label(Label&&) = delete;
Label& operator=(Label&&) = delete;
std::vector<uint8_t> getRaw();
void create(const std::string& labelText, const uint16_t heightPixel);
bool create(PrintableText printableText) override;
bool create(const std::string& labelText) override;
void writeToPng(const std::string& file);
int getLayoutWidth();
int getLayoutHeight();
[[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
uint8_t getNumLines(std::string_view str);
[[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};
PangoFontDescription* mPangoFontDesc{nullptr};
cairo_surface_t* mSurface{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;
};

View File

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

View File

@@ -20,22 +20,61 @@
#pragma once
#include <cstdint>
#include <span>
#include <vector>
#include "graphics/Bitmap.hpp"
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 {
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;
void setThreshold(uint8_t);
void invert(bool shouldInvert);
void visualize();
std::vector<uint8_t> get();
MonochromeData getMonochromeData();
private:
const std::vector<uint8_t>& mPixels;
std::vector<uint8_t> mPixels;
uint32_t mWidth;
uint32_t mHeight;
uint8_t mThreshhold = UINT8_MAX / 2;
bool mShouldInvert = false;
};

View 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

View File

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

View File

@@ -19,11 +19,12 @@
#pragma once
#include <cstdint>
#include <memory>
#include <string_view>
#include "graphics/Bitmap.hpp"
#include "graphics/Monochrome.hpp"
#include "graphics/interface/ILabel.hpp"
#include "interface/IPrinterTypes.hpp"
#include "libusbwrap/interface/IUsbDevice.hpp"
@@ -39,12 +40,9 @@ class IPrinterDriver {
[[nodiscard]] virtual const PrinterStatus getPrinterStatus() = 0;
virtual bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) = 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 printMonochromeData(const graphics::MonochromeData& data) = 0;
virtual bool printLabel(const std::unique_ptr<graphics::ILabel> label) = 0;
virtual bool print() = 0;
};

View File

@@ -43,27 +43,4 @@ struct PrinterStatus {
using cmd_T = std::vector<uint8_t>;
enum class HAlignPosition {
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

View File

@@ -22,7 +22,6 @@
#include <gtest/gtest.h>
#include <cstdint>
#include <optional>
#include <vector>
TEST(basic_test, Bitmap_createBitmapWithCertainSize_yieldsSpecifiedSize) {
@@ -36,34 +35,28 @@ TEST(basic_test, Bitmap_createBitmapWithCertainSize_yieldsSpecifiedSize) {
TEST(basic_test, Bitmap_getBitmapLineOutsideOfImage_yieldsNullopt) {
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
// line 8 is out of bounds, count begins with 0
auto outOfBoundsLine = bm.getLine(8);
ASSERT_EQ(std::nullopt, outOfBoundsLine);
EXPECT_ANY_THROW(auto outOfBoundsLine = bm.getLine(8));
}
TEST(basic_test, Bitmap_getBitmapLineInsideOfImage_yieldsValidLineSize) {
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
auto line = bm.getLine(7);
if (!line) {
FAIL() << "Returned line is invalid";
}
auto lineSize = line->size();
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
auto line = bm.getLine(7);
auto lineSize = line.size();
ASSERT_EQ(16, lineSize);
}
TEST(basic_test, Bitmap_getBitmapColOutsideOfImage_yieldsNullopt) {
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
// 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) {
auto bm = ptprnt::graphics::Bitmap<ptprnt::graphics::ALPHA8>(16, 8);
auto col = bm.getCol(15);
if (!col) {
FAIL() << "Returned Col is invalid";
}
auto colSize = col->size();
auto colSize = col.size();
ASSERT_EQ(8, colSize);
}

View File

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

View File

@@ -22,22 +22,22 @@
#include <gtest/gtest.h>
TEST(basic_test, Monochrome_convertGrayscale_yieldsMonochrome) {
const std::vector<uint8_t> pixels({0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 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});
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();
EXPECT_EQ(out, expected);
}
TEST(basic_test, Monochrome_convertInvertedGrayscale_yieldsInvertedMonochrome) {
const std::vector<uint8_t> pixels({0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 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});
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);
auto out = mono.get();
@@ -45,11 +45,11 @@ TEST(basic_test, Monochrome_convertInvertedGrayscale_yieldsInvertedMonochrome) {
}
TEST(basic_test, Monochrome_convertWithCustomThreshhold_yieldsMonochromeRespectingThreshhold) {
const std::vector<uint8_t> pixels({0x0F, 0x11, 0x0F, 0x11, 0x0F, 0x11, 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});
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);
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
// Ideas: constexpr? compile time check?
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> 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});
auto mono = ptprnt::graphics::Monochrome(pixels);
auto mono = ptprnt::graphics::Monochrome(pixels, 17, 1);
auto out = mono.get();
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
}