Compare commits
3 Commits
3dc5da6fc8
...
59b3b34edc
| Author | SHA1 | Date | |
|---|---|---|---|
|
59b3b34edc
|
|||
|
6e3a5bd12f
|
|||
|
0b8ff28a60
|
9
.vscode/launch.json
vendored
9
.vscode/launch.json
vendored
@@ -9,12 +9,15 @@
|
||||
"type": "cppdbg",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/builddir/ptprnt",
|
||||
"args": ["-t Hello"],
|
||||
"args": [
|
||||
"-t i"
|
||||
],
|
||||
"stopAtEntry": false,
|
||||
"cwd": "${fileDirname}",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"environment": [],
|
||||
"externalConsole": false,
|
||||
"MIMode": "lldb",
|
||||
"MIMode": "gdb",
|
||||
"miDebuggerPath": "/usr/bin/gdb",
|
||||
"setupCommands": [
|
||||
{
|
||||
"description": "Automatische Strukturierung und Einrückung für \"gdb\" aktivieren",
|
||||
|
||||
8
.vscode/settings.json
vendored
8
.vscode/settings.json
vendored
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"clangd.arguments": ["-background-index", "-compile-commands-dir=builddir/"],
|
||||
"clangd.arguments": [
|
||||
"-background-index",
|
||||
"-compile-commands-dir=builddir/"
|
||||
],
|
||||
"editor.formatOnType": false,
|
||||
"editor.formatOnSave": true,
|
||||
"files.associations": {
|
||||
@@ -84,4 +87,7 @@
|
||||
"*.ipp": "cpp"
|
||||
},
|
||||
"clangd.onConfigChanged": "restart",
|
||||
"cSpell.words": [
|
||||
"ptrnt"
|
||||
],
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "P700Printer.hpp"
|
||||
#include "printers/P700Printer.hpp"
|
||||
#include "printers/FakePrinter.hpp"
|
||||
#include "libusbwrap/LibUsbTypes.hpp"
|
||||
|
||||
namespace ptprnt {
|
||||
@@ -20,4 +21,33 @@ std::shared_ptr<IPrinterDriver> PrinterDriverFactory::create(libusbwrap::usbId i
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::shared_ptr<IPrinterDriver> PrinterDriverFactory::createFakePrinter() {
|
||||
spdlog::info("Creating FakePrinter (virtual test printer)");
|
||||
return std::make_shared<printer::FakePrinter>();
|
||||
}
|
||||
|
||||
std::shared_ptr<IPrinterDriver> PrinterDriverFactory::createByName(const std::string& driverName) {
|
||||
// Convert to lowercase for case-insensitive comparison
|
||||
std::string nameLower = driverName;
|
||||
std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(),
|
||||
[](unsigned char c) { return std::tolower(c); });
|
||||
|
||||
if (nameLower == "p700" || nameLower == "p700printer") {
|
||||
spdlog::info("Creating P700 printer driver by name");
|
||||
return std::make_shared<printer::P700Printer>();
|
||||
} else if (nameLower == "fakeprinter" || nameLower == "fake") {
|
||||
return createFakePrinter();
|
||||
}
|
||||
|
||||
spdlog::warn("Unknown printer driver name: {}", driverName);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::vector<std::string> PrinterDriverFactory::listAllDrivers() const {
|
||||
return {
|
||||
std::string(printer::P700Printer::mInfo.driverName),
|
||||
std::string(printer::FakePrinter::mInfo.driverName)
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace ptprnt
|
||||
@@ -1,4 +1,6 @@
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include "interface/IPrinterDriver.hpp"
|
||||
#include "libusbwrap/LibUsbTypes.hpp"
|
||||
|
||||
@@ -14,8 +16,32 @@ class PrinterDriverFactory {
|
||||
PrinterDriverFactory(PrinterDriverFactory&&) = delete;
|
||||
PrinterDriverFactory& operator=(PrinterDriverFactory&&) = delete;
|
||||
|
||||
/**
|
||||
* @brief Create a printer driver based on USB ID
|
||||
* @param id USB vendor and product ID
|
||||
* @return Printer driver instance or nullptr if no match
|
||||
*/
|
||||
std::shared_ptr<IPrinterDriver> create(libusbwrap::usbId id);
|
||||
|
||||
/**
|
||||
* @brief Create a virtual FakePrinter for testing without hardware
|
||||
* @return FakePrinter instance
|
||||
*/
|
||||
std::shared_ptr<IPrinterDriver> createFakePrinter();
|
||||
|
||||
/**
|
||||
* @brief Create a printer driver by name
|
||||
* @param driverName Name of the driver (from PrinterInfo.driverName)
|
||||
* @return Printer driver instance or nullptr if no match
|
||||
*/
|
||||
std::shared_ptr<IPrinterDriver> createByName(const std::string& driverName);
|
||||
|
||||
/**
|
||||
* @brief Get list of all available printer driver names
|
||||
* @return Vector of driver names
|
||||
*/
|
||||
std::vector<std::string> listAllDrivers() const;
|
||||
|
||||
private:
|
||||
};
|
||||
|
||||
|
||||
@@ -71,24 +71,87 @@ int PtouchPrint::init(int argc, char** argv) {
|
||||
int PtouchPrint::run() {
|
||||
spdlog::info("ptprnt version {}", mVersionString);
|
||||
SPDLOG_TRACE("testing trace");
|
||||
mDetectedPrinters = getCompatiblePrinters();
|
||||
auto numFoundPrinters = mDetectedPrinters.size();
|
||||
if (numFoundPrinters == 0) {
|
||||
spdlog::error("No compatible printers found, please make sure that they are turned on and connected");
|
||||
return -1;
|
||||
} else if (numFoundPrinters > 1) {
|
||||
spdlog::warn("Found more than one compatible printer. Currently not supported.");
|
||||
return -1;
|
||||
|
||||
// Handle --list-all-drivers flag
|
||||
if (mListDriversFlag) {
|
||||
auto driverFactory = std::make_unique<PrinterDriverFactory>();
|
||||
auto drivers = driverFactory->listAllDrivers();
|
||||
|
||||
fmt::print("Available printer drivers:\n");
|
||||
for (const auto& driver : drivers) {
|
||||
fmt::print(" - {}\n", driver);
|
||||
}
|
||||
fmt::print("\nUse with: -p <driver_name> or --printer <driver_name>\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
auto printer = mDetectedPrinters[0];
|
||||
const auto printerUsbId = printer->getUsbId();
|
||||
auto devices = mUsbDeviceFactory.findDevices(printerUsbId.first, printerUsbId.second);
|
||||
if (devices.size() != 1) {
|
||||
spdlog::warn("Found more than one device of the same printer on bus. Currently not supported");
|
||||
return -1;
|
||||
// Determine which printer to use
|
||||
std::shared_ptr<IPrinterDriver> printer = nullptr;
|
||||
|
||||
if (mPrinterSelection != "auto") {
|
||||
// Explicit printer selection by name
|
||||
auto driverFactory = std::make_unique<PrinterDriverFactory>();
|
||||
printer = driverFactory->createByName(mPrinterSelection);
|
||||
|
||||
if (!printer) {
|
||||
spdlog::error("Failed to create printer driver '{}'", mPrinterSelection);
|
||||
spdlog::info("Use --list-all-drivers to see available drivers");
|
||||
return -1;
|
||||
}
|
||||
|
||||
spdlog::info("Using explicitly selected printer: {}", mPrinterSelection);
|
||||
|
||||
// FakePrinter doesn't need USB device attachment
|
||||
if (mPrinterSelection == "FakePrinter" || mPrinterSelection == "fake") {
|
||||
printer->attachUsbDevice(nullptr);
|
||||
} else {
|
||||
// Real printer needs USB device
|
||||
const auto printerUsbId = printer->getUsbId();
|
||||
auto devices = mUsbDeviceFactory.findDevices(printerUsbId.first, printerUsbId.second);
|
||||
|
||||
if (devices.empty()) {
|
||||
spdlog::error("No USB device found for printer {}. Is it connected and powered on?", mPrinterSelection);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (devices.size() > 1) {
|
||||
spdlog::warn("Found more than one device of the same printer on bus. Using first one.");
|
||||
}
|
||||
|
||||
if (!printer->attachUsbDevice(std::move(devices[0]))) {
|
||||
spdlog::error("Failed to attach USB device to printer");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Auto-detect printer from USB devices
|
||||
mDetectedPrinters = getCompatiblePrinters();
|
||||
auto numFoundPrinters = mDetectedPrinters.size();
|
||||
|
||||
if (numFoundPrinters == 0) {
|
||||
spdlog::error("No compatible printers found, please make sure that they are turned on and connected");
|
||||
spdlog::info("Tip: Use -p FakePrinter for testing without hardware");
|
||||
return -1;
|
||||
} else if (numFoundPrinters > 1) {
|
||||
spdlog::warn("Found more than one compatible printer. Use -p to select explicitly.");
|
||||
return -1;
|
||||
}
|
||||
|
||||
printer = mDetectedPrinters[0];
|
||||
const auto printerUsbId = printer->getUsbId();
|
||||
auto devices = mUsbDeviceFactory.findDevices(printerUsbId.first, printerUsbId.second);
|
||||
|
||||
if (devices.size() != 1) {
|
||||
spdlog::warn("Found more than one device of the same printer on bus. Currently not supported");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!printer->attachUsbDevice(std::move(devices[0]))) {
|
||||
spdlog::error("Failed to attach USB device to printer");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
printer->attachUsbDevice(std::move(devices[0]));
|
||||
|
||||
auto status = printer->getPrinterStatus();
|
||||
spdlog::info("Detected tape width is {}mm", status.tapeWidthMm);
|
||||
|
||||
@@ -150,10 +213,10 @@ int PtouchPrint::run() {
|
||||
}
|
||||
label->create(labelText);
|
||||
label->writeToPng("./testlabel.png");
|
||||
/*if (!printer->printLabel(std::move(label))) {
|
||||
if (!printer->printLabel(std::move(label))) {
|
||||
spdlog::error("An error occured while printing");
|
||||
return -1;
|
||||
}*/
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -203,6 +266,13 @@ void PtouchPrint::setupCliParser() {
|
||||
mApp.add_flag("-v,--verbose", mVerboseFlag, "Enable verbose output");
|
||||
mApp.add_flag("-V,--version", printVersion, "Prints the ptprnt's version");
|
||||
|
||||
// Printer selection
|
||||
mApp.add_option("-p,--printer", mPrinterSelection,
|
||||
"Select printer driver (default: auto). Use --list-all-drivers to see available options")
|
||||
->default_val("auto");
|
||||
|
||||
mApp.add_flag("--list-all-drivers", mListDriversFlag, "List all available printer drivers and exit");
|
||||
|
||||
// Text printing options
|
||||
mApp.add_option("-t,--text",
|
||||
"Text to print (can be used multple times, use formatting options before to "
|
||||
@@ -227,7 +297,7 @@ void PtouchPrint::setupCliParser() {
|
||||
->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); });
|
||||
std::ranges::transform(in, in.begin(), [](unsigned char c) { return std::tolower(c); });
|
||||
if (validValignOptions.find(in) == validValignOptions.end()) {
|
||||
return {""};
|
||||
}
|
||||
|
||||
@@ -58,7 +58,9 @@ class PtouchPrint {
|
||||
std::vector<CliCmd> mCommands{};
|
||||
std::string mVersionString = "";
|
||||
|
||||
// CLI flags
|
||||
// CLI flags and options
|
||||
bool mVerboseFlag = false;
|
||||
std::string mPrinterSelection = "auto";
|
||||
bool mListDriversFlag = false;
|
||||
};
|
||||
} // namespace ptprnt
|
||||
@@ -37,19 +37,43 @@
|
||||
|
||||
namespace ptprnt::graphics {
|
||||
Label::Label(const uint16_t heightPixel)
|
||||
: mCairoCtx(cairo_create(mSurface)),
|
||||
mPangoCtx(pango_cairo_create_context(mCairoCtx)),
|
||||
mPangoLyt(pango_layout_new(mPangoCtx)),
|
||||
mFontMap(pango_cairo_font_map_new()),
|
||||
mPrinterHeight(heightPixel) {}
|
||||
: mPrinterHeight(heightPixel) {
|
||||
// Initialize resources in correct order with RAII
|
||||
mFontMap.reset(pango_cairo_font_map_new());
|
||||
}
|
||||
|
||||
std::vector<uint8_t> Label::getRaw() {
|
||||
assert(mSurface != nullptr);
|
||||
size_t len = mPrinterHeight * mLayoutWidth;
|
||||
auto* surface = mSurface.get();
|
||||
|
||||
cairo_surface_flush(mSurface);
|
||||
auto data = cairo_image_surface_get_data(mSurface);
|
||||
return {data, data + len};
|
||||
cairo_surface_flush(surface);
|
||||
assert(cairo_image_surface_get_format(surface) == CAIRO_FORMAT_A8);
|
||||
|
||||
int width = cairo_image_surface_get_width(surface);
|
||||
int height = cairo_image_surface_get_height(surface);
|
||||
int stride = cairo_image_surface_get_stride(surface);
|
||||
|
||||
spdlog::debug("Cairo Surface data: W: {}; H: {}; S:{}", width, height, stride);
|
||||
|
||||
auto data = cairo_image_surface_get_data(surface);
|
||||
|
||||
// If stride equals width, we can return data directly
|
||||
if (stride == width) {
|
||||
size_t len = height * stride;
|
||||
return {data, data + len};
|
||||
}
|
||||
|
||||
// Otherwise, we need to copy row by row, removing stride padding
|
||||
std::vector<uint8_t> result;
|
||||
result.reserve(width * height);
|
||||
|
||||
for (int y = 0; y < height; ++y) {
|
||||
uint8_t* row_start = data + (y * stride);
|
||||
result.insert(result.end(), row_start, row_start + width);
|
||||
}
|
||||
|
||||
spdlog::debug("getRaw: Removed stride padding, returning {} bytes ({}x{})", result.size(), width, height);
|
||||
return result;
|
||||
}
|
||||
|
||||
uint8_t Label::getNumLines(std::string_view strv) {
|
||||
@@ -57,11 +81,13 @@ uint8_t Label::getNumLines(std::string_view strv) {
|
||||
}
|
||||
|
||||
int Label::getWidth() {
|
||||
return mPrinterHeight;
|
||||
// Return the actual Cairo surface width (which is the layout width)
|
||||
return mLayoutWidth;
|
||||
}
|
||||
|
||||
int Label::getHeight() {
|
||||
return getLayoutWidth();
|
||||
// Return the actual Cairo surface height (which is the printer height)
|
||||
return mPrinterHeight;
|
||||
}
|
||||
|
||||
int Label::getLayoutHeight() {
|
||||
@@ -72,6 +98,35 @@ int Label::getLayoutWidth() {
|
||||
return mLayoutWidth;
|
||||
}
|
||||
|
||||
void Label::configureLayout(PangoLayout* layout, const std::string& text, PangoFontDescription* fontDesc) {
|
||||
pango_layout_set_font_description(layout, fontDesc);
|
||||
pango_layout_set_text(layout, text.c_str(), static_cast<int>(text.length()));
|
||||
pango_layout_set_height(layout, getNumLines(text) * -1);
|
||||
}
|
||||
|
||||
void Label::applyHorizontalAlignment(PangoLayout* layout) {
|
||||
switch (mHAlign) {
|
||||
case HAlignPosition::LEFT:
|
||||
pango_layout_set_alignment(layout, PANGO_ALIGN_LEFT);
|
||||
break;
|
||||
case HAlignPosition::RIGHT:
|
||||
pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);
|
||||
break;
|
||||
case HAlignPosition::JUSTIFY:
|
||||
pango_layout_set_alignment(layout, PANGO_ALIGN_LEFT);
|
||||
pango_layout_set_justify(layout, true);
|
||||
#if PANGO_VERSION_MAJOR >= 1 && PANGO_VERSION_MINOR >= 50
|
||||
pango_layout_set_justify_last_line(layout, true);
|
||||
#endif
|
||||
break;
|
||||
case HAlignPosition::CENTER:
|
||||
[[fallthrough]];
|
||||
default:
|
||||
pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
bool Label::create(PrintableText printableText) {
|
||||
setFontFamily(printableText.fontFamily);
|
||||
setFontSize(printableText.fontSize);
|
||||
@@ -80,79 +135,78 @@ bool Label::create(PrintableText printableText) {
|
||||
}
|
||||
|
||||
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
|
||||
// TODO: we need to create a custom font config here so that Noto Emoji does not load the systems default
|
||||
// font config 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
|
||||
|
||||
// Create a temporary surface for layout size calculations
|
||||
auto* tempSurface = cairo_image_surface_create(CAIRO_FORMAT_A8, 1, 1);
|
||||
auto* tempCr = cairo_create(tempSurface);
|
||||
auto* tempPangoCtx = pango_cairo_create_context(tempCr);
|
||||
auto* tempPangoLyt = pango_layout_new(tempPangoCtx);
|
||||
|
||||
PangoFontDescription* regularFont = pango_font_description_new();
|
||||
pango_font_description_set_size(regularFont, static_cast<int>(mFontSize * PANGO_SCALE));
|
||||
pango_font_description_set_family(regularFont, mFontFamily.c_str());
|
||||
//pango_layout_set_single_paragraph_mode(mPangoLyt, true); // this will force a single line in the label width width -1
|
||||
pango_layout_set_height(mPangoLyt, getNumLines(labelText) * -1);
|
||||
pango_layout_set_font_description(mPangoLyt, regularFont);
|
||||
pango_layout_set_text(mPangoLyt, labelText.c_str(), static_cast<int>(labelText.length()));
|
||||
|
||||
// Set horizontal alignment
|
||||
switch (mHAlign) {
|
||||
case HAlignPosition::LEFT:
|
||||
pango_layout_set_alignment(mPangoLyt, PANGO_ALIGN_LEFT);
|
||||
break;
|
||||
case HAlignPosition::RIGHT:
|
||||
pango_layout_set_alignment(mPangoLyt, PANGO_ALIGN_RIGHT);
|
||||
break;
|
||||
case HAlignPosition::JUSTIFY:
|
||||
pango_layout_set_alignment(mPangoLyt, PANGO_ALIGN_LEFT); // not sure if needed
|
||||
pango_layout_set_justify(mPangoLyt, true);
|
||||
// only enabled in pango 1.50 and greater
|
||||
#if PANGO_VERSION_MAJOR >= 1 && PANGO_VERSION_MINOR >= 50
|
||||
pango_layout_set_justify_last_line(mPangoLyt, true);
|
||||
#endif
|
||||
break;
|
||||
case HAlignPosition::CENTER:
|
||||
[[fallthrough]];
|
||||
default:
|
||||
pango_layout_set_alignment(mPangoLyt, PANGO_ALIGN_CENTER);
|
||||
break;
|
||||
}
|
||||
// Configure temporary layout for size calculation
|
||||
configureLayout(tempPangoLyt, labelText, regularFont);
|
||||
applyHorizontalAlignment(tempPangoLyt);
|
||||
|
||||
// calculate label size for Cairo surface creation
|
||||
pango_layout_get_size(mPangoLyt, &mLayoutWidth, &mLayoutHeight);
|
||||
// Calculate label size from temporary layout
|
||||
pango_layout_get_size(tempPangoLyt, &mLayoutWidth, &mLayoutHeight);
|
||||
mLayoutWidth /= PANGO_SCALE;
|
||||
mLayoutHeight /= PANGO_SCALE;
|
||||
|
||||
spdlog::debug("Layout width: {}, height: {}", mLayoutWidth, mLayoutHeight);
|
||||
auto alignedWidth = mLayoutWidth + (8 - (mLayoutWidth % 8));
|
||||
//auto alignedWidth = mLayoutWidth + (8 - (mLayoutWidth % 8));
|
||||
//spdlog::debug("Aligned Layout width: {}, height: {}", alignedWidth, mLayoutHeight);
|
||||
|
||||
mSurface = cairo_image_surface_create(CAIRO_FORMAT_A8, alignedWidth, mPrinterHeight);
|
||||
cairo_t* cr = cairo_create(mSurface);
|
||||
// Clean up temporary resources
|
||||
g_object_unref(tempPangoLyt);
|
||||
g_object_unref(tempPangoCtx);
|
||||
cairo_destroy(tempCr);
|
||||
cairo_surface_destroy(tempSurface);
|
||||
|
||||
// Now create the final surface and Pango context for actual rendering
|
||||
mSurface.reset(cairo_image_surface_create(CAIRO_FORMAT_A8, mLayoutWidth, mPrinterHeight));
|
||||
cairo_t* cr = cairo_create(mSurface.get());
|
||||
mCairoCtx.reset(cr);
|
||||
mPangoCtx.reset(pango_cairo_create_context(cr));
|
||||
mPangoLyt.reset(pango_layout_new(mPangoCtx.get()));
|
||||
|
||||
// Configure final layout with same settings
|
||||
configureLayout(mPangoLyt.get(), labelText, regularFont);
|
||||
applyHorizontalAlignment(mPangoLyt.get());
|
||||
|
||||
// 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);
|
||||
cairo_move_to(mCairoCtx.get(), 0.0, mPrinterHeight - mLayoutHeight);
|
||||
break;
|
||||
case VAlignPosition::MIDDLE:
|
||||
cairo_move_to(cr, 0.0, (mPrinterHeight - mLayoutHeight) / 2);
|
||||
cairo_move_to(mCairoCtx.get(), 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(mCairoCtx.get(), mPangoLyt.get());
|
||||
|
||||
cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
|
||||
cairo_surface_flush(mSurface);
|
||||
cairo_destroy(cr);
|
||||
cairo_set_source_rgb(mCairoCtx.get(), 0.0, 0.0, 0.0);
|
||||
cairo_surface_flush(mSurface.get());
|
||||
// mCairoCtx smart pointer will handle cleanup
|
||||
return true;
|
||||
}
|
||||
|
||||
void Label::writeToPng(const std::string& file) {
|
||||
if (mSurface) {
|
||||
cairo_surface_flush(mSurface);
|
||||
cairo_surface_write_to_png(mSurface, file.c_str());
|
||||
cairo_surface_flush(mSurface.get());
|
||||
cairo_surface_write_to_png(mSurface.get(), file.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,9 +232,6 @@ void Label::setText(const std::string& text) {
|
||||
|
||||
Label::~Label() {
|
||||
spdlog::debug("Image dtor...");
|
||||
g_object_unref(mPangoCtx);
|
||||
g_object_unref(mPangoLyt);
|
||||
g_object_unref(mFontMap);
|
||||
cairo_surface_destroy(mSurface);
|
||||
// RAII smart pointers handle cleanup automatically
|
||||
}
|
||||
} // namespace ptprnt::graphics
|
||||
@@ -22,6 +22,7 @@
|
||||
#include <pango/pangocairo.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -31,6 +32,28 @@
|
||||
|
||||
namespace ptprnt::graphics {
|
||||
|
||||
// Custom deleters for Cairo/Pango resources
|
||||
struct CairoSurfaceDeleter {
|
||||
void operator()(cairo_surface_t* surface) const {
|
||||
if (surface)
|
||||
cairo_surface_destroy(surface);
|
||||
}
|
||||
};
|
||||
|
||||
struct CairoDeleter {
|
||||
void operator()(cairo_t* cr) const {
|
||||
if (cr)
|
||||
cairo_destroy(cr);
|
||||
}
|
||||
};
|
||||
|
||||
struct GObjectDeleter {
|
||||
void operator()(gpointer obj) const {
|
||||
if (obj)
|
||||
g_object_unref(obj);
|
||||
}
|
||||
};
|
||||
|
||||
class Label : public ILabel {
|
||||
public:
|
||||
Label(const uint16_t heightPixel);
|
||||
@@ -60,13 +83,14 @@ class Label : public ILabel {
|
||||
// methods
|
||||
[[nodiscard]] uint8_t getNumLines(std::string_view str);
|
||||
[[nodiscard]] PangoFontMap* createCustomFontMap();
|
||||
// members
|
||||
// TODO: convert raw pointers here into std::unique_ptr with custom deleters, calling g_object_unref()
|
||||
cairo_surface_t* mSurface{nullptr};
|
||||
cairo_t* mCairoCtx{nullptr};
|
||||
PangoContext* mPangoCtx{nullptr};
|
||||
PangoLayout* mPangoLyt{nullptr};
|
||||
PangoFontMap* mFontMap{nullptr};
|
||||
void configureLayout(PangoLayout* layout, const std::string& text, PangoFontDescription* fontDesc);
|
||||
void applyHorizontalAlignment(PangoLayout* layout);
|
||||
|
||||
std::unique_ptr<cairo_surface_t, CairoSurfaceDeleter> mSurface{nullptr};
|
||||
std::unique_ptr<cairo_t, CairoDeleter> mCairoCtx{nullptr};
|
||||
std::unique_ptr<PangoContext, GObjectDeleter> mPangoCtx{nullptr};
|
||||
std::unique_ptr<PangoLayout, GObjectDeleter> mPangoLyt{nullptr};
|
||||
std::unique_ptr<PangoFontMap, GObjectDeleter> mFontMap{nullptr};
|
||||
double mFontSize{DEFAULT_FONT_SIZE};
|
||||
std::string mFontFamily{DEFAULT_FONT_FAMILY};
|
||||
HAlignPosition mHAlign = HAlignPosition::LEFT;
|
||||
|
||||
@@ -25,71 +25,85 @@
|
||||
#include <vector>
|
||||
|
||||
namespace ptprnt::graphics {
|
||||
Monochrome::Monochrome(const std::vector<uint8_t>& grayscale, uint32_t width, uint32_t height)
|
||||
: mPixels(grayscale), mWidth(width), mHeight(height) {}
|
||||
// Constructor from grayscale data
|
||||
MonochromeData::MonochromeData(const std::vector<uint8_t>& grayscale, uint32_t width, uint32_t height,
|
||||
Orientation orient)
|
||||
: stride(0),
|
||||
orientation(orient),
|
||||
width(width),
|
||||
height(height),
|
||||
mPixels(grayscale),
|
||||
mIsProcessed(false) {}
|
||||
|
||||
Monochrome::Monochrome(const std::span<uint8_t> grayscale, uint32_t width, uint32_t height)
|
||||
: mPixels(grayscale.begin(), grayscale.end()), mWidth(width), mHeight(height) {}
|
||||
MonochromeData::MonochromeData(const std::span<uint8_t> grayscale, uint32_t width, uint32_t height,
|
||||
Orientation orient)
|
||||
: stride(0),
|
||||
orientation(orient),
|
||||
width(width),
|
||||
height(height),
|
||||
mPixels(grayscale.begin(), grayscale.end()),
|
||||
mIsProcessed(false) {}
|
||||
|
||||
void Monochrome::setThreshold(uint8_t threshhold) {
|
||||
mThreshhold = threshhold;
|
||||
void MonochromeData::setThreshold(uint8_t threshold) {
|
||||
mThreshold = threshold;
|
||||
mIsProcessed = false; // Mark as needing reprocessing
|
||||
}
|
||||
|
||||
void Monochrome::invert(bool shouldInvert) {
|
||||
void MonochromeData::invert(bool shouldInvert) {
|
||||
mShouldInvert = shouldInvert;
|
||||
mIsProcessed = false; // Mark as needing reprocessing
|
||||
}
|
||||
|
||||
std::vector<uint8_t> Monochrome::get() {
|
||||
// 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);
|
||||
MonochromeData MonochromeData::get() {
|
||||
if (!mIsProcessed) {
|
||||
processGrayscaleToMonochrome();
|
||||
mIsProcessed = true;
|
||||
}
|
||||
|
||||
// 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
|
||||
// Return a copy of the processed data
|
||||
MonochromeData result;
|
||||
result.bytes = bytes;
|
||||
result.stride = stride;
|
||||
result.orientation = orientation;
|
||||
result.width = width;
|
||||
result.height = height;
|
||||
result.mIsProcessed = true;
|
||||
return result;
|
||||
}
|
||||
|
||||
// Convert grayscale pixel to bit based on threshold
|
||||
bool pixelOn = mPixels[pixelIndex] > mThreshhold;
|
||||
if (mShouldInvert) {
|
||||
pixelOn = !pixelOn;
|
||||
}
|
||||
void MonochromeData::processGrayscaleToMonochrome() {
|
||||
// Calculate stride based on packed monochrome data (1 bit per pixel, 8 pixels per byte)
|
||||
stride = static_cast<uint32_t>((width + 7) / 8);
|
||||
|
||||
if (pixelOn) {
|
||||
outPixels[byteIndex] |= (1 << bitIndex);
|
||||
// Create the monochrome byte array
|
||||
bytes.clear();
|
||||
bytes.resize(stride * height, 0);
|
||||
|
||||
// Convert grayscale to monochrome
|
||||
for (uint32_t y = 0; y < height; ++y) {
|
||||
for (uint32_t x = 0; x < width; ++x) {
|
||||
uint32_t pixelIndex = y * width + x;
|
||||
if (pixelIndex < mPixels.size()) {
|
||||
uint8_t pixelValue = mPixels[pixelIndex];
|
||||
|
||||
// Apply threshold
|
||||
bool isSet = pixelValue >= mThreshold;
|
||||
|
||||
// Apply inversion if needed
|
||||
if (mShouldInvert) {
|
||||
isSet = !isSet;
|
||||
}
|
||||
|
||||
// Set the bit in the monochrome data
|
||||
if (isSet) {
|
||||
setBit(x, y, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return outPixels;
|
||||
}
|
||||
|
||||
void Monochrome::visualize() {
|
||||
auto mono = get();
|
||||
for (unsigned char pix : mono) {
|
||||
std::cout << ((pix & (1 << 7)) == 0 ? "." : "x");
|
||||
std::cout << ((pix & (1 << 6)) == 0 ? "." : "x");
|
||||
std::cout << ((pix & (1 << 5)) == 0 ? "." : "x");
|
||||
std::cout << ((pix & (1 << 4)) == 0 ? "." : "x");
|
||||
std::cout << ((pix & (1 << 3)) == 0 ? "." : "x");
|
||||
std::cout << ((pix & (1 << 2)) == 0 ? "." : "x");
|
||||
std::cout << ((pix & (1 << 1)) == 0 ? "." : "x");
|
||||
std::cout << ((pix & (1 << 0)) == 0 ? "." : "x");
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
MonochromeData Monochrome::getMonochromeData() {
|
||||
auto processedBytes = get();
|
||||
// Calculate stride based on packed monochrome data (1 bit per pixel, 8 pixels per byte)
|
||||
auto stride = static_cast<uint32_t>((mWidth + 7) / 8);
|
||||
return {std::move(processedBytes), stride, Orientation::LANDSCAPE, mWidth, mHeight};
|
||||
}
|
||||
|
||||
// MonochromeData transformation methods implementation
|
||||
// Transformation methods implementation
|
||||
void MonochromeData::transformTo(Orientation targetOrientation) {
|
||||
if (orientation == targetOrientation) {
|
||||
return; // No transformation needed
|
||||
@@ -151,7 +165,7 @@ void MonochromeData::setBit(uint32_t x, uint32_t y, bool value) {
|
||||
}
|
||||
|
||||
std::vector<uint8_t> MonochromeData::createRotatedData(Orientation targetOrientation) const {
|
||||
uint32_t newWidth, newHeight;
|
||||
uint32_t newWidth = 0, newHeight = 0;
|
||||
|
||||
// Determine new dimensions
|
||||
switch (targetOrientation) {
|
||||
@@ -182,8 +196,8 @@ std::vector<uint8_t> MonochromeData::createRotatedData(Orientation targetOrienta
|
||||
// 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;
|
||||
bool pixel = getBit(x, y);
|
||||
uint32_t newX = 0, newY = 0;
|
||||
|
||||
switch (targetOrientation) {
|
||||
case Orientation::LANDSCAPE:
|
||||
|
||||
@@ -34,19 +34,38 @@ enum class Orientation {
|
||||
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
|
||||
|
||||
class MonochromeData {
|
||||
public:
|
||||
// Constructors
|
||||
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) {}
|
||||
|
||||
// Constructor from grayscale data (replaces old Monochrome class)
|
||||
MonochromeData(const std::vector<uint8_t>& grayscale, uint32_t width, uint32_t height,
|
||||
Orientation orient = Orientation::LANDSCAPE);
|
||||
MonochromeData(const std::span<uint8_t> grayscale, uint32_t width, uint32_t height,
|
||||
Orientation orient = Orientation::LANDSCAPE);
|
||||
|
||||
~MonochromeData() = default;
|
||||
|
||||
// Copy constructor and assignment
|
||||
MonochromeData(const MonochromeData&) = default;
|
||||
MonochromeData& operator=(const MonochromeData&) = default;
|
||||
|
||||
// Move constructor and assignment
|
||||
MonochromeData(MonochromeData&&) = default;
|
||||
MonochromeData& operator=(MonochromeData&&) = default;
|
||||
|
||||
// Configuration methods
|
||||
void setThreshold(uint8_t threshold);
|
||||
void invert(bool shouldInvert);
|
||||
|
||||
// Get processed monochrome data
|
||||
MonochromeData get();
|
||||
|
||||
// Transform the image data to the target orientation
|
||||
void transformTo(Orientation targetOrientation);
|
||||
|
||||
@@ -57,25 +76,25 @@ struct MonochromeData {
|
||||
[[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, 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();
|
||||
// Public member access for backward compatibility
|
||||
std::vector<uint8_t> bytes;
|
||||
uint32_t stride;
|
||||
Orientation orientation;
|
||||
uint32_t width; // Width in pixels
|
||||
uint32_t height; // Height in pixels
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> mPixels;
|
||||
uint32_t mWidth;
|
||||
uint32_t mHeight;
|
||||
uint8_t mThreshhold = UINT8_MAX / 2;
|
||||
bool mShouldInvert = false;
|
||||
// Processing parameters (for old Monochrome class compatibility)
|
||||
std::vector<uint8_t> mPixels; // Original grayscale pixels
|
||||
uint8_t mThreshold = UINT8_MAX / 2;
|
||||
bool mShouldInvert = false;
|
||||
bool mIsProcessed = false; // Flag to indicate if conversion has been done
|
||||
|
||||
// Helper method to convert grayscale to monochrome
|
||||
void processGrayscaleToMonochrome();
|
||||
};
|
||||
|
||||
// For backward compatibility, create a type alias
|
||||
using Monochrome = MonochromeData;
|
||||
} // namespace ptprnt::graphics
|
||||
@@ -6,7 +6,8 @@ ptprnt_hpps = files (
|
||||
'libusbwrap/UsbDevice.hpp',
|
||||
'interface/IPrinterDriver.hpp',
|
||||
'interface/IPrinterTypes.hpp',
|
||||
'P700Printer.hpp',
|
||||
'printers/P700Printer.hpp',
|
||||
'printers/FakePrinter.hpp',
|
||||
'PtouchPrint.hpp',
|
||||
'PrinterDriverFactory.hpp',
|
||||
'graphics/Bitmap.hpp',
|
||||
@@ -17,7 +18,8 @@ ptprnt_hpps = files (
|
||||
ptprnt_srcs = files (
|
||||
'PtouchPrint.cpp',
|
||||
'PrinterDriverFactory.cpp',
|
||||
'P700Printer.cpp',
|
||||
'printers/P700Printer.cpp',
|
||||
'printers/FakePrinter.cpp',
|
||||
'graphics/Label.cpp',
|
||||
'graphics/Bitmap.cpp',
|
||||
'graphics/Monochrome.cpp',
|
||||
|
||||
264
src/printers/FakePrinter.cpp
Normal file
264
src/printers/FakePrinter.cpp
Normal file
@@ -0,0 +1,264 @@
|
||||
/*
|
||||
ptrnt - print labels on linux
|
||||
Copyright (C) 2023 Moritz Martinius
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
*/
|
||||
|
||||
#include "FakePrinter.hpp"
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <cairo.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
|
||||
#include "../graphics/Monochrome.hpp"
|
||||
|
||||
namespace ptprnt::printer {
|
||||
|
||||
const PrinterInfo FakePrinter::mInfo = {
|
||||
.driverName = "FakePrinter",
|
||||
.name = "Virtual Test Printer",
|
||||
.version = "v1.0",
|
||||
.usbId{0x0000, 0x0000}, // No USB ID - virtual printer created explicitly
|
||||
.pixelLines = 128
|
||||
};
|
||||
|
||||
const std::string_view FakePrinter::getDriverName() {
|
||||
return mInfo.driverName;
|
||||
}
|
||||
|
||||
const std::string_view FakePrinter::getName() {
|
||||
return mInfo.name;
|
||||
}
|
||||
|
||||
const std::string_view FakePrinter::getVersion() {
|
||||
return mInfo.version;
|
||||
}
|
||||
|
||||
const PrinterInfo FakePrinter::getPrinterInfo() {
|
||||
return mInfo;
|
||||
}
|
||||
|
||||
const PrinterStatus FakePrinter::getPrinterStatus() {
|
||||
return mStatus;
|
||||
}
|
||||
|
||||
const libusbwrap::usbId FakePrinter::getUsbId() {
|
||||
return mInfo.usbId;
|
||||
}
|
||||
|
||||
bool FakePrinter::attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) {
|
||||
// FakePrinter doesn't need a real USB device
|
||||
mHasAttachedDevice = true;
|
||||
spdlog::debug("FakePrinter: Simulated USB device attachment");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FakePrinter::detachUsbDevice() {
|
||||
mHasAttachedDevice = false;
|
||||
spdlog::debug("FakePrinter: Simulated USB device detachment");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FakePrinter::printBitmap(const graphics::Bitmap<graphics::ALPHA8>& bitmap) {
|
||||
// Convert bitmap to MonochromeData and delegate
|
||||
auto pixels = bitmap.getPixelsCpy();
|
||||
auto mono = graphics::Monochrome(pixels, bitmap.getWidth(), bitmap.getHeight());
|
||||
auto monoData = mono.get();
|
||||
|
||||
return printMonochromeData(monoData);
|
||||
}
|
||||
|
||||
bool FakePrinter::printMonochromeData(const graphics::MonochromeData& data) {
|
||||
spdlog::debug("FakePrinter: Simulating printing of {}x{} bitmap", data.width, data.height);
|
||||
|
||||
// Simulate the printing process by reconstructing the bitmap
|
||||
auto printed = simulatePrinting(data);
|
||||
mLastPrint = std::make_unique<graphics::Bitmap<graphics::ALPHA8>>(std::move(printed));
|
||||
|
||||
spdlog::info("FakePrinter: Successfully 'printed' label ({}x{} pixels)",
|
||||
mLastPrint->getWidth(), mLastPrint->getHeight());
|
||||
|
||||
// Save to timestamped PNG file
|
||||
std::string filename = generateTimestampedFilename();
|
||||
if (saveBitmapToPng(*mLastPrint, filename)) {
|
||||
spdlog::info("FakePrinter: Saved output to {}", filename);
|
||||
} else {
|
||||
spdlog::error("FakePrinter: Failed to save output to {}", filename);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FakePrinter::printLabel(const std::unique_ptr<graphics::ILabel> label) {
|
||||
// Convert label directly to MonochromeData
|
||||
// getRaw() returns data in Cairo surface coordinates matching getWidth() × getHeight()
|
||||
auto pixels = label->getRaw();
|
||||
|
||||
// Create monochrome data in landscape orientation (as stored in Cairo surface)
|
||||
auto mono = graphics::Monochrome(pixels, label->getWidth(), label->getHeight(), graphics::Orientation::LANDSCAPE);
|
||||
auto monoData = mono.get();
|
||||
|
||||
// Transform to portrait orientation for printing
|
||||
monoData.transformTo(graphics::Orientation::PORTRAIT);
|
||||
|
||||
spdlog::debug("FakePrinter: Label surface is {}x{}, transformed to portrait", label->getWidth(), label->getHeight());
|
||||
|
||||
return printMonochromeData(monoData);
|
||||
}
|
||||
|
||||
bool FakePrinter::print() {
|
||||
spdlog::debug("FakePrinter: Print command (no-op for virtual printer)");
|
||||
return true;
|
||||
}
|
||||
|
||||
graphics::Bitmap<graphics::ALPHA8> FakePrinter::simulatePrinting(const graphics::MonochromeData& data) {
|
||||
spdlog::debug("FakePrinter: Simulating column-by-column printing like real hardware");
|
||||
|
||||
// Create output bitmap with same dimensions
|
||||
graphics::Bitmap<graphics::ALPHA8> result(data.width, data.height);
|
||||
std::vector<uint8_t> pixels(data.width * data.height, 0);
|
||||
|
||||
// Simulate printer behavior: process column by column
|
||||
// This mimics how label printers physically print one vertical line at a time
|
||||
for (uint32_t col = 0; col < data.width; col++) {
|
||||
spdlog::trace("FakePrinter: Processing column {}/{}", col + 1, data.width);
|
||||
|
||||
// Extract column data bit by bit (simulating what would be sent to printer)
|
||||
std::vector<uint8_t> columnBytes;
|
||||
|
||||
for (uint32_t row = 0; row < data.height; row += 8) {
|
||||
uint8_t byte = 0;
|
||||
|
||||
// Pack 8 vertical pixels into one byte (printer data format)
|
||||
for (int bit = 0; bit < 8 && (row + bit) < data.height; bit++) {
|
||||
if (data.getBit(col, row + bit)) {
|
||||
byte |= (1 << (7 - bit));
|
||||
}
|
||||
}
|
||||
|
||||
columnBytes.push_back(byte);
|
||||
}
|
||||
|
||||
// Now "print" this column by unpacking the bytes back to pixels
|
||||
// This simulates the printer head physically printing this column
|
||||
for (size_t byteIdx = 0; byteIdx < columnBytes.size(); byteIdx++) {
|
||||
uint8_t byte = columnBytes[byteIdx];
|
||||
uint32_t baseRow = byteIdx * 8;
|
||||
|
||||
for (int bit = 0; bit < 8 && (baseRow + bit) < data.height; bit++) {
|
||||
bool pixelOn = (byte & (1 << (7 - bit))) != 0;
|
||||
uint32_t row = baseRow + bit;
|
||||
|
||||
// Write to output bitmap
|
||||
size_t pixelIdx = row * data.width + col;
|
||||
pixels[pixelIdx] = pixelOn ? 255 : 0; // 255 = black, 0 = white
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Set the pixels in the result bitmap
|
||||
result.setPixels(pixels);
|
||||
|
||||
spdlog::debug("FakePrinter: Simulation complete, reconstructed {}x{} bitmap",
|
||||
result.getWidth(), result.getHeight());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
const graphics::Bitmap<graphics::ALPHA8>& FakePrinter::getLastPrint() const {
|
||||
if (!mLastPrint) {
|
||||
throw std::runtime_error("FakePrinter: No print data available");
|
||||
}
|
||||
return *mLastPrint;
|
||||
}
|
||||
|
||||
bool FakePrinter::saveLastPrintToPng(const std::string& filename) const {
|
||||
if (!mLastPrint || mLastPrint->getWidth() == 0 || mLastPrint->getHeight() == 0) {
|
||||
spdlog::error("FakePrinter: No print data available to save");
|
||||
return false;
|
||||
}
|
||||
|
||||
return saveBitmapToPng(*mLastPrint, filename);
|
||||
}
|
||||
|
||||
bool FakePrinter::saveBitmapToPng(const graphics::Bitmap<graphics::ALPHA8>& bitmap, const std::string& filename) const {
|
||||
// Create Cairo surface from bitmap data
|
||||
auto pixels = bitmap.getPixelsCpy();
|
||||
uint16_t width = bitmap.getWidth();
|
||||
uint16_t height = bitmap.getHeight();
|
||||
|
||||
// Cairo expects ARGB32 format, but we have ALPHA8
|
||||
// Convert ALPHA8 (grayscale) to ARGB32
|
||||
std::vector<uint32_t> argbPixels(width * height);
|
||||
|
||||
for (size_t i = 0; i < pixels.size(); i++) {
|
||||
uint8_t gray = pixels[i];
|
||||
// ARGB32 format: 0xAARRGGBB
|
||||
// For grayscale: use gray value for R, G, B and 255 for alpha
|
||||
argbPixels[i] = 0xFF000000 | (gray << 16) | (gray << 8) | gray;
|
||||
}
|
||||
|
||||
// Create Cairo surface
|
||||
int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width);
|
||||
cairo_surface_t* surface = cairo_image_surface_create_for_data(
|
||||
reinterpret_cast<unsigned char*>(argbPixels.data()),
|
||||
CAIRO_FORMAT_ARGB32,
|
||||
width,
|
||||
height,
|
||||
stride
|
||||
);
|
||||
|
||||
if (cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS) {
|
||||
spdlog::error("FakePrinter: Failed to create Cairo surface: {}",
|
||||
cairo_status_to_string(cairo_surface_status(surface)));
|
||||
cairo_surface_destroy(surface);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Write to PNG file
|
||||
cairo_status_t status = cairo_surface_write_to_png(surface, filename.c_str());
|
||||
|
||||
cairo_surface_destroy(surface);
|
||||
|
||||
if (status != CAIRO_STATUS_SUCCESS) {
|
||||
spdlog::error("FakePrinter: Failed to write PNG file: {}", cairo_status_to_string(status));
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string FakePrinter::generateTimestampedFilename() const {
|
||||
// Get current time
|
||||
auto now = std::chrono::system_clock::now();
|
||||
auto time = std::chrono::system_clock::to_time_t(now);
|
||||
|
||||
// Format: fakelabel_YYYYMMDD_HHMMSS.png
|
||||
std::stringstream ss;
|
||||
ss << "fakelabel_"
|
||||
<< std::put_time(std::localtime(&time), "%Y%m%d_%H%M%S")
|
||||
<< ".png";
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
} // namespace ptprnt::printer
|
||||
108
src/printers/FakePrinter.hpp
Normal file
108
src/printers/FakePrinter.hpp
Normal file
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
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 <memory>
|
||||
#include <vector>
|
||||
#include <cstdint>
|
||||
|
||||
#include "../interface/IPrinterDriver.hpp"
|
||||
#include "../interface/IPrinterTypes.hpp"
|
||||
#include "../libusbwrap/LibUsbTypes.hpp"
|
||||
#include "../libusbwrap/interface/IUsbDevice.hpp"
|
||||
#include "../graphics/Bitmap.hpp"
|
||||
|
||||
namespace ptprnt::printer {
|
||||
|
||||
/**
|
||||
* @brief Virtual printer driver for testing without hardware
|
||||
*
|
||||
* FakePrinter simulates a real label printer by processing bitmap data
|
||||
* column by column and reconstructing it into a new bitmap, mimicking
|
||||
* the physical printing process of label printers.
|
||||
*/
|
||||
class FakePrinter : public ::ptprnt::IPrinterDriver {
|
||||
public:
|
||||
FakePrinter() = default;
|
||||
~FakePrinter() override = default;
|
||||
|
||||
FakePrinter(const FakePrinter&) = delete;
|
||||
FakePrinter& operator=(const FakePrinter&) = delete;
|
||||
FakePrinter(FakePrinter&&) = default;
|
||||
FakePrinter& operator=(FakePrinter&&) = default;
|
||||
|
||||
// Printer info - static to be accessed without instantiation
|
||||
static const PrinterInfo mInfo;
|
||||
|
||||
// IPrinterDriver interface
|
||||
[[nodiscard]] const std::string_view getDriverName() override;
|
||||
[[nodiscard]] const std::string_view getName() override;
|
||||
[[nodiscard]] const libusbwrap::usbId getUsbId() override;
|
||||
[[nodiscard]] const std::string_view getVersion() override;
|
||||
[[nodiscard]] const PrinterInfo getPrinterInfo() override;
|
||||
[[nodiscard]] const PrinterStatus getPrinterStatus() override;
|
||||
bool attachUsbDevice(std::shared_ptr<libusbwrap::IUsbDevice> usbHndl) override;
|
||||
bool detachUsbDevice() 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;
|
||||
|
||||
/**
|
||||
* @brief Get the last printed bitmap
|
||||
* @return The reconstructed bitmap from simulated printing
|
||||
*/
|
||||
[[nodiscard]] const graphics::Bitmap<graphics::ALPHA8>& getLastPrint() const;
|
||||
|
||||
/**
|
||||
* @brief Save the last print to a PNG file
|
||||
* @param filename Path to save the PNG
|
||||
* @return true if successful
|
||||
*/
|
||||
bool saveLastPrintToPng(const std::string& filename) const;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Simulate printing by reconstructing bitmap column by column
|
||||
* @param data Monochrome data to "print"
|
||||
* @return Reconstructed bitmap
|
||||
*/
|
||||
graphics::Bitmap<graphics::ALPHA8> simulatePrinting(const graphics::MonochromeData& data);
|
||||
|
||||
/**
|
||||
* @brief Save bitmap to PNG file using Cairo
|
||||
* @param bitmap The bitmap to save
|
||||
* @param filename Output filename
|
||||
* @return true if successful
|
||||
*/
|
||||
bool saveBitmapToPng(const graphics::Bitmap<graphics::ALPHA8>& bitmap, const std::string& filename) const;
|
||||
|
||||
/**
|
||||
* @brief Generate timestamped filename for fake label output
|
||||
* @return Filename like "fakelabel_20231011_123456.png"
|
||||
*/
|
||||
std::string generateTimestampedFilename() const;
|
||||
|
||||
std::unique_ptr<graphics::Bitmap<graphics::ALPHA8>> mLastPrint;
|
||||
bool mHasAttachedDevice = false;
|
||||
PrinterStatus mStatus{.tapeWidthMm = 12}; // Default to 12mm tape
|
||||
};
|
||||
|
||||
} // namespace ptprnt::printer
|
||||
@@ -27,9 +27,9 @@
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "graphics/Bitmap.hpp"
|
||||
#include "graphics/Monochrome.hpp"
|
||||
#include "libusbwrap/LibUsbTypes.hpp"
|
||||
#include "../graphics/Bitmap.hpp"
|
||||
#include "../graphics/Monochrome.hpp"
|
||||
#include "../libusbwrap/LibUsbTypes.hpp"
|
||||
#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 ;)
|
||||
@@ -121,17 +121,16 @@ bool P700Printer::detachUsbDevice() {
|
||||
|
||||
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();
|
||||
auto pixels = bitmap.getPixelsCpy();
|
||||
auto mono = graphics::Monochrome(pixels, bitmap.getWidth(), bitmap.getHeight());
|
||||
auto monoData = mono.get();
|
||||
|
||||
return printMonochromeData(monoData);
|
||||
}
|
||||
|
||||
bool P700Printer::printMonochromeData(const graphics::MonochromeData& data) {
|
||||
#ifdef DRYRUN
|
||||
spdlog::debug("DRYRUN enabled");
|
||||
data.visualize();
|
||||
spdlog::debug("DRYRUN enabled, printing nothing");
|
||||
#endif
|
||||
|
||||
send(p700::commands::RASTER_START);
|
||||
@@ -174,11 +173,19 @@ bool P700Printer::printMonochromeData(const graphics::MonochromeData& data) {
|
||||
|
||||
bool P700Printer::printLabel(std::unique_ptr<graphics::ILabel> label) {
|
||||
// Convert label directly to MonochromeData
|
||||
// getRaw() returns data in Cairo surface coordinates matching getWidth() × getHeight()
|
||||
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());
|
||||
// Create monochrome data in landscape orientation (as stored in Cairo surface)
|
||||
auto mono = graphics::Monochrome(pixels, label->getWidth(), label->getHeight(), graphics::Orientation::LANDSCAPE);
|
||||
auto monoData = mono.get();
|
||||
|
||||
// Transform to portrait orientation for printing
|
||||
monoData.transformTo(graphics::Orientation::PORTRAIT);
|
||||
|
||||
spdlog::debug("Label surface is {}x{}, transformed to portrait", label->getWidth(), label->getHeight());
|
||||
monoData.visualize();
|
||||
|
||||
return printMonochromeData(monoData);
|
||||
}
|
||||
|
||||
@@ -23,10 +23,10 @@
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "interface/IPrinterDriver.hpp"
|
||||
#include "interface/IPrinterTypes.hpp"
|
||||
#include "libusbwrap/LibUsbTypes.hpp"
|
||||
#include "libusbwrap/interface/IUsbDevice.hpp"
|
||||
#include "../interface/IPrinterDriver.hpp"
|
||||
#include "../interface/IPrinterTypes.hpp"
|
||||
#include "../libusbwrap/LibUsbTypes.hpp"
|
||||
#include "../libusbwrap/interface/IUsbDevice.hpp"
|
||||
|
||||
#pragma once
|
||||
|
||||
@@ -29,7 +29,7 @@ TEST(basic_test, Monochrome_convertGrayscale_yieldsMonochrome) {
|
||||
auto mono = ptprnt::graphics::Monochrome(pixels, 16, 1);
|
||||
auto out = mono.get();
|
||||
|
||||
EXPECT_EQ(out, expected);
|
||||
EXPECT_EQ(out.bytes, expected);
|
||||
}
|
||||
|
||||
TEST(basic_test, Monochrome_convertInvertedGrayscale_yieldsInvertedMonochrome) {
|
||||
@@ -41,7 +41,7 @@ TEST(basic_test, Monochrome_convertInvertedGrayscale_yieldsInvertedMonochrome) {
|
||||
mono.invert(true);
|
||||
auto out = mono.get();
|
||||
|
||||
EXPECT_EQ(out, expected);
|
||||
EXPECT_EQ(out.bytes, expected);
|
||||
}
|
||||
|
||||
TEST(basic_test, Monochrome_convertWithCustomThreshhold_yieldsMonochromeRespectingThreshhold) {
|
||||
@@ -53,7 +53,7 @@ TEST(basic_test, Monochrome_convertWithCustomThreshhold_yieldsMonochromeRespecti
|
||||
mono.setThreshold(16);
|
||||
auto out = mono.get();
|
||||
|
||||
EXPECT_EQ(out, expected);
|
||||
EXPECT_EQ(out.bytes, expected);
|
||||
}
|
||||
|
||||
TEST(basic_test, Monochrome_convertNonAlignedPixels_spillsOverIntoNewByte) {
|
||||
@@ -67,14 +67,14 @@ TEST(basic_test, Monochrome_convertNonAlignedPixels_spillsOverIntoNewByte) {
|
||||
auto mono = ptprnt::graphics::Monochrome(pixels, 17, 1);
|
||||
auto out = mono.get();
|
||||
|
||||
EXPECT_EQ(out, expected);
|
||||
EXPECT_EQ(out.bytes, 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();
|
||||
auto monoData = mono.get();
|
||||
|
||||
EXPECT_EQ(monoData.bytes.size(), 1);
|
||||
EXPECT_EQ(monoData.bytes[0], 0b10101010);
|
||||
@@ -90,7 +90,7 @@ TEST(MonochromeData_test, MonochromeData2x2_transformToPortrait_rotatesCorrectly
|
||||
const std::vector<uint8_t> pixels({0xFF, 0x00, 0x00, 0xFF});
|
||||
|
||||
auto mono = ptprnt::graphics::Monochrome(pixels, 2, 2);
|
||||
auto monoData = mono.getMonochromeData();
|
||||
auto monoData = mono.get();
|
||||
|
||||
monoData.transformTo(ptprnt::graphics::Orientation::PORTRAIT);
|
||||
|
||||
@@ -114,7 +114,7 @@ TEST(MonochromeData_test, MonochromeData3x2_transformToPortrait_rotatesCorrectly
|
||||
const std::vector<uint8_t> pixels({0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF});
|
||||
|
||||
auto mono = ptprnt::graphics::Monochrome(pixels, 3, 2);
|
||||
auto monoData = mono.getMonochromeData();
|
||||
auto monoData = mono.get();
|
||||
|
||||
monoData.transformTo(ptprnt::graphics::Orientation::PORTRAIT);
|
||||
|
||||
@@ -141,7 +141,7 @@ TEST(MonochromeData_test, MonochromeData3x2_transformToPortrait_rotatesCorrectly
|
||||
const std::vector<uint8_t> pixels({0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF});
|
||||
|
||||
auto mono = ptprnt::graphics::Monochrome(pixels, 3, 2);
|
||||
auto monoData = mono.getMonochromeData();
|
||||
auto monoData = mono.get();
|
||||
|
||||
monoData.transformTo(ptprnt::graphics::Orientation::PORTRAIT_FLIPPED);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user