Repository navigation
Expand file tree
/
Copy pathprinter.cc
More file actions
2887 lines (2557 loc) · 72.9 KB
/
Copy pathprinter.cc
File metadata and controls
2887 lines (2557 loc) · 72.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright ViewTouch, Inc., 1995, 1996, 1997, 1998, 2025, 2026
* 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 <http://www.gnu.org/licenses/>.
*
* printer.cc - revision 66 (10/13/98)
* Implementation of printer device class
*/
#include "manager.hh"
#include "printer.hh"
#include "socket.hh"
#include "settings.hh"
#include "terminal.hh"
#include "src/utils/vt_logger.hh"
#include "safe_string_utils.hh"
#include "src/utils/cpp23_utils.hh"
#include "src/core/thread_pool.hh"
#include <errno.h>
#include <iostream>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <cstring>
#include <cctype>
#ifdef DMALLOC
#include <dmalloc.h>
#endif
#ifdef BSD
#define PRINTER_PORT "lpt0"
#endif
#ifdef LINUX
#define PRINTER_PORT "lp0"
#endif
#define END_PAGE 8
/**** Global Data ****/
const genericChar* PrinterModelName[] = {
"No Printer", "Epson", "Star", "HP", "Toshiba", "Ithaca",
"HTML", "PostScript", "PDF", "Receipt Text",
"Report Text", "QuickBooks CSV", nullptr};
int PrinterModelValue[] = {
MODEL_NONE, MODEL_EPSON, MODEL_STAR, MODEL_HP, MODEL_TOSHIBA, MODEL_ITHACA,
MODEL_HTML, MODEL_POSTSCRIPT, MODEL_PDF, MODEL_RECEIPT_TEXT,
MODEL_REPORT_TEXT, MODEL_QUICKBOOKS_CSV, -1};
// const genericChar* ReceiptPrinterModelName[] = {
// "No Printer", "Epson", "Star", "Ithaca", "Text", NULL};
// int ReceiptPrinterModelValue[] = {
// MODEL_NONE, MODEL_EPSON, MODEL_STAR, MODEL_ITHACA, MODEL_RECEIPT_TEXT, -1};
const genericChar* ReceiptPrinterModelName[] = {
"No Printer", "Epson", "Star", "HP", "Toshiba", "Ithaca",
"HTML", "PostScript", "PDF", "Receipt Text",
"Report Text", "QuickBooks CSV", nullptr};
int ReceiptPrinterModelValue[] = {
MODEL_NONE, MODEL_EPSON, MODEL_STAR, MODEL_HP, MODEL_TOSHIBA, MODEL_ITHACA,
MODEL_HTML, MODEL_POSTSCRIPT, MODEL_PDF, MODEL_RECEIPT_TEXT,
MODEL_REPORT_TEXT, MODEL_QUICKBOOKS_CSV, -1};
const genericChar* ReportPrinterModelName[] = {
"No Printer", "HP", "Toshiba", "HTML", "PostScript",
"PDF", "Text", "QuickBooks CSV", nullptr};
int ReportPrinterModelValue[] = {
MODEL_NONE, MODEL_HP, MODEL_TOSHIBA, MODEL_HTML, MODEL_POSTSCRIPT,
MODEL_PDF, MODEL_REPORT_TEXT, MODEL_QUICKBOOKS_CSV, -1};
#define GENERIC_TITLE "ViewTouch POS Report" // page title when not otherwise specified
const genericChar* PortName[] = {
"XCD Parallel", "XCD Serial", "Explora Parallel", "Explora Serial",
"VT Daemon", "Device On Server", nullptr};
int PortValue[] = {
PORT_XCD_PARALLEL, PORT_XCD_SERIAL, PORT_EXPLORA_PARALLEL, PORT_EXPLORA_SERIAL,
PORT_VT_DAEMON, PORT_SERVER_DEVICE, -1};
/*********************************************************************
* THE NEW PRINTER OBJECT -- These methods should never need to be
* subclassed.
********************************************************************/
Printer::Printer()
{
next = nullptr;
fore = nullptr;
parent = nullptr;
last_mode = 0;
last_color = 0;
last_uni = 0;
last_uline = 0;
last_large = 0;
last_narrow = 0;
last_bold = 0;
port_no = 0;
active_flags = 0;
temp_fd = -1;
temp_name.Set("");
target.Set("");
target_type = TARGET_NONE;
host_name.Set("");
port_no = 0;
kitchen_mode = PRINT_LARGE | PRINT_NARROW;
pulse = -1;
term_name.Set("");
}
Printer::Printer(const genericChar* host, int port, const genericChar* targetstr, int type)
{
next = nullptr;
fore = nullptr;
parent = nullptr;
last_mode = 0;
last_color = 0;
last_uni = 0;
last_uline = 0;
last_large = 0;
last_narrow = 0;
last_bold = 0;
port_no = 0;
active_flags = 0;
temp_fd = -1;
temp_name.Set("");
target.Set(targetstr);
target_type = type;
host_name.Set(host);
port_no = port;
kitchen_mode = PRINT_LARGE | PRINT_NARROW;
pulse = -1;
term_name.Set("");
}
Printer::~Printer()
= default;
/****
* MatchHost: This is fairly rudimentary. It only checks the hostname. I can only
* think of one situation in which this should matter: If there are multiple vt_print
* instances on the same server, accessing different printers, listening on different
* ports. But this should not happen as the new code allows for lpd, which will avoid
* the problem while also providing more versatility.
****/
int Printer::MatchHost(const genericChar* host, int /*port*/)
{
FnTrace("Printer::MatchHost()");
int retval = 1;
if (strcmp(host_name.Value(), host) != 0)
retval = 0;
return retval;
}
int Printer::MatchTerminal(const genericChar* termname)
{
FnTrace("Printer::MatchTerminal()");
int retval = 1;
if (strcmp(term_name.Value(), termname) != 0)
retval = 0;
return retval;
}
/****
* SetKitchenMode:
****/
int Printer::SetKitchenMode(int mode)
{
FnTrace("Printer::SetKitchenMode()");
int retval = kitchen_mode;
kitchen_mode = mode;
return retval;
}
/****
* SetType: Returns the previous type.
****/
int Printer::SetType(int type)
{
FnTrace("Printer::SetType()");
int retval = printer_type;
printer_type = type;
return retval;
}
int Printer::IsType(int type)
{
FnTrace("Printer::IsType()");
int retval = 0;
if (printer_type == type)
retval = 1;
return retval;
}
int Printer::SetTitle(const std::string &title)
{
page_title = title;
have_title = true;
return 0;
}
int Printer::Open()
{
FnTrace("Printer::Open()");
int retval = 0;
genericChar filename[STRLENGTH] = "/tmp/viewtouchXXXXXX";
temp_fd = mkstemp(filename);
if (filename[0] != '\0')
{
temp_name.Set(filename);
vt::Logger::debug("Printer opened successfully - temp file: {}", filename);
}
else
{
temp_name.Set("");
temp_fd = -1;
retval = 1;
vt::Logger::error("Failed to create temporary file for printer");
}
return retval;
}
/****
* Close: Need to close out the resulting file and send it off to the
* destination.
****/
int Printer::Close()
{
FnTrace("Printer::Close()");
// LPD and socket printing block the calling thread (system() / connect()).
// Delegate to CloseAsync() which dispatches to a thread pool so the main
// event loop is never stalled waiting for CUPS or a network printer.
// CloseAsync() owns temp_fd/temp_name cleanup for these two types.
if (target_type == TARGET_LPD || target_type == TARGET_SOCKET)
{
CloseAsync();
return 0;
}
// For all other target types: close the file handle, dispatch, then clean up.
if (temp_fd > 0)
close(temp_fd);
switch (target_type)
{
case TARGET_PARALLEL:
ParallelPrint();
break;
case TARGET_FILE:
FilePrint();
break;
case TARGET_EMAIL:
EmailPrint();
break;
default:
break;
}
// delete the temp file unless printing to the parallel port might still need it
if (target_type != TARGET_PARALLEL)
unlink(temp_name.Value());
temp_name.Set("");
temp_fd = -1;
return 0;
}
/****
* CloseAsync: Non-blocking version of Close() for use when UI responsiveness
* is critical. Spawns the print job to a background thread.
* Note: Only works for socket and LPD printing where the temp file can be
* safely copied and processed asynchronously.
****/
void Printer::CloseAsync()
{
FnTrace("Printer::CloseAsync()");
// Close the temp file handle first
if (temp_fd > 0)
close(temp_fd);
temp_fd = -1;
// For parallel printing, we still use synchronous (it already forks)
// For file/email, use sync since they're local operations
if (target_type == TARGET_PARALLEL || target_type == TARGET_FILE ||
target_type == TARGET_EMAIL)
{
// Fall back to sync for these
switch (target_type)
{
case TARGET_PARALLEL:
ParallelPrint();
break;
case TARGET_FILE:
FilePrint();
break;
case TARGET_EMAIL:
EmailPrint();
break;
default:
break;
}
unlink(temp_name.Value());
temp_name.Set("");
return;
}
// For socket and LPD, run async
// Capture temp file name for async operation
std::string temp_file = temp_name.Value();
std::string target_str = target.Value();
int port = port_no;
int type = target_type;
temp_name.Set(""); // Clear so printer can be reused
// Queue the print job to the thread pool
bool queued = vt::ThreadPool::instance().enqueue_detached(
[temp_file, target_str, port, type]() {
vt::Logger::debug("Async print starting: {} -> {}:{}", temp_file, target_str, port);
if (type == TARGET_SOCKET)
{
// Socket printing logic (duplicated to avoid this pointer issues)
ssize_t bytesread;
ssize_t byteswritten = 1;
char buffer[4096];
struct hostent *he;
struct sockaddr_in their_addr;
he = gethostbyname(target_str.c_str());
if (he == nullptr)
{
vt::Logger::error("Async SocketPrint: Failed to resolve host '{}'", target_str);
unlink(temp_file.c_str());
return;
}
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
vt::Logger::error("Async SocketPrint: Failed to create socket");
unlink(temp_file.c_str());
return;
}
their_addr.sin_family = AF_INET;
their_addr.sin_port = htons(static_cast<uint16_t>(port));
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
memset(&(their_addr.sin_zero), '\0', 8);
if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1)
{
vt::Logger::error("Async SocketPrint: Failed to connect to {}:{}", target_str, port);
close(sockfd);
unlink(temp_file.c_str());
return;
}
int fd = open(temp_file.c_str(), O_RDONLY, 0);
if (fd <= 0)
{
vt::Logger::error("Async SocketPrint: Failed to open temp file '{}'", temp_file);
close(sockfd);
unlink(temp_file.c_str());
return;
}
bytesread = read(fd, buffer, sizeof(buffer));
while (bytesread > 0 && byteswritten > 0)
{
byteswritten = write(sockfd, buffer, static_cast<size_t>(bytesread));
bytesread = read(fd, buffer, sizeof(buffer));
}
close(fd);
close(sockfd);
vt::Logger::info("Async SocketPrint: Successfully printed to {}:{}", target_str, port);
}
else if (type == TARGET_LPD)
{
// LPD printing
char cmd[512];
vt::cpp23::format_to_buffer(cmd, sizeof(cmd), "cat {} | /usr/bin/lpr -P{}",
temp_file.c_str(), target_str.c_str());
int result = system(cmd);
if (result != 0)
vt::Logger::error("Async LPDPrint: Command failed with code {}", result);
else
vt::Logger::info("Async LPDPrint: Successfully sent to {}", target_str);
}
// Clean up temp file
unlink(temp_file.c_str());
}
);
if (!queued) {
// Thread pool is full. The temp file will be orphaned in the printqueue
// directory but the operator needs to know so they can reprint.
ReportError("Print job dropped: thread pool queue full. Please reprint.");
unlink(temp_file.c_str()); // clean up the temp file we won't be sending
}
}
/****
* ParallelPrint: I've been experiencing severe slowdowns with parallel printing.
* Apparently, we have to wait until the whole job is done. So I'm spawning
* a child process that will do the printing. The parent should be able to continue
* as if nothing else is going on. //NOTE this may create timing issues if
* multiple print jobs are spooled, so we'll have to handle that situation
* (I don't know that I'll worry about order so much as making sure every job
* gets through).
****/
int Printer::ParallelPrint()
{
pid_t pid;
genericChar buffer[STRLENGTH];
int lockfd;
int infd;
int outfd;
ssize_t bytes;
unsigned char buff[STRLENGTH];
struct timeval timeout;
vt::cpp23::format_to_buffer(buffer, STRLENGTH, "cat {} >>{}", temp_name.Value(), target.Value());
if (debug_mode)
printf("Forking for ParallelPrint\n");
pid = fork();
if (pid == 0)
{ // child process, handle the print job
// Do a loop with a select() call for a brief pause between
// each write to the parallel port. On my FreeBSD system,
// at least, writing to the parallel port seems to lock the
// entire system (I'm guessing the printer has a very small buffer,
// and possibly I have something misconfigured).
lockfd = LockDevice(target.Value());
if (lockfd > 0)
{
infd = open(temp_name.Value(), O_RDONLY);
outfd = open(target.Value(), O_WRONLY | O_NONBLOCK);
if (infd > 0 && outfd > 0)
{
timeout.tv_sec = 0;
timeout.tv_usec = 100;
bytes = read(infd, buff, STRLENGTH);
while (bytes > 0)
{
bytes = write(outfd, buff, static_cast<size_t>(bytes));
select(0, nullptr, nullptr, nullptr, &timeout);
if (bytes > 0)
bytes = read(infd, buff, STRLENGTH);
}
if (infd > 0)
close(infd);
if (outfd > 0)
close(outfd);
}
else
{
if (infd < 0)
{
vt::cpp23::format_to_buffer(buffer, STRLENGTH, "ParallelPrint Error {} opening {} for read",
errno, temp_name.Value());
ReportError(buffer);
}
if (outfd < 0)
{
vt::cpp23::format_to_buffer(buffer, STRLENGTH, "ParallelPrint Error {} opening {} for write",
errno, target.Value());
ReportError(buffer);
}
}
UnlockDevice(lockfd);
}
else
{ // couldn't open one of the files, try cat
system(buffer);
}
unlink(temp_name.Value());
exit(0);
}
else if (pid < 0)
{ // error, just copy the temp file to the printer without forking
system(buffer);
unlink(temp_name.Value());
}
temp_name.Set("");
temp_fd = -1;
return 0;
}
int Printer::LPDPrint()
{
FnTrace("Printer::LPDPrint()");
genericChar buffer[STRLONG];
vt::cpp23::format_to_buffer(buffer, STRLONG, "cat {} | /usr/bin/lpr -P{}", temp_name.Value(), target.Value());
system(buffer);
return 0;
}
int Printer::SocketPrint()
{
FnTrace("Printer::SocketPrint()");
vt::Logger::debug("Starting socket print to {}:{}", target.Value(), port_no);
ssize_t bytesread;
ssize_t byteswritten = 1; // set it to one to ensure one while loop
genericChar buffer[STRLENGTH];
int sockfd;
struct hostent *he;
struct sockaddr_in their_addr; // connector's address information
he = gethostbyname(target.Value()); // get the host info
if (he == nullptr)
{
vt::Logger::error("SocketPrint: Failed to resolve host '{}'", target.Value());
perror("gethostbyname");
return 1;
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
vt::Logger::error("SocketPrint: Failed to create socket");
perror("socket");
return 1;
}
// Set socket timeouts (5 seconds for printer connections)
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
their_addr.sin_family = AF_INET; // host byte order
their_addr.sin_port = htons(port_no); // short, network byte order
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
memset(&(their_addr.sin_zero), '\0', 8); // zero the rest of the struct
if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1)
{
vt::Logger::error("SocketPrint: Failed to connect to {}:{}", target.Value(), port_no);
perror("connect");
fprintf(stderr, "Is vt_print running?\n");
close(sockfd);
return 1;
}
temp_fd = open(temp_name.Value(), O_RDONLY, 0);
if (temp_fd <= 0)
{
close(sockfd);
vt::Logger::error("SocketPrint: Failed to open temp file '{}' (errno: {})", temp_name.Value(), errno);
vt::cpp23::format_to_buffer(buffer, STRLENGTH, "SocketPrint Error {} opening {}",
errno, temp_name.Value());
ReportError(buffer);
return 1;
}
vt::Logger::debug("SocketPrint: Sending data to printer");
bytesread = read(temp_fd, buffer, STRLENGTH);
while (bytesread > 0 && byteswritten > 0)
{
byteswritten = write(sockfd, buffer, static_cast<size_t>(bytesread));
bytesread = read(temp_fd, buffer, STRLENGTH);
}
close(sockfd);
close(temp_fd); // Critical fix: Always close temp_fd before returning
if (byteswritten <= 0) {
vt::Logger::error("SocketPrint: Failed to write all data to printer");
return 1;
}
vt::Logger::info("SocketPrint: Successfully printed to {}:{}", target.Value(), port_no);
return 0;
}
/****
* ValidChar: For filenames, we'll only allow 0-9, a-z, and A-Z.
****/
int Printer::ValidChar(genericChar c)
{
FnTrace("Printer::ValidChar()");
int valid = 0;
int ch = (int) c;
if (ch >= 48 && ch <= 57) // 0-9
valid = 1;
else if (ch >= 65 && ch <= 90) // A-Z
valid = 1;
else if (ch >= 97 && ch <= 122) // a-z
valid = 1;
else if (ch >= 45 && ch <= 46) // - and .
valid = 1;
return valid;
}
/****
* MakeFileName: Remove spaces and other characters that could cause problems.
* Most modern OSs will handle just about any character fine, but that
* doesn't mean we need to beg for trouble.
****/
int Printer::MakeFileName(genericChar* buffer, const genericChar* source, const genericChar* ext, int max_len)
{
FnTrace("Printer::MakeFileName()");
int idx = 0;
int buffidx = 0;
TimeInfo now;
const genericChar* title_source;
// Select the source string without copying
if (source != nullptr)
title_source = source;
else if (have_title)
title_source = page_title.c_str();
else
title_source = GENERIC_TITLE;
// Filter characters directly into buffer
while (title_source[idx] != '\0' && buffidx < max_len - 20) // Leave room for date and extension
{
if (ValidChar(title_source[idx]))
{
buffer[buffidx] = title_source[idx];
buffidx += 1;
}
idx += 1;
}
buffer[buffidx] = '\0';
if (buffidx < max_len)
{
// append the date directly to buffer
now.Set();
buffidx += vt::cpp23::format_to_buffer(buffer + buffidx, max_len - buffidx, "-{:02d}-{:02d}-{}",
now.Day(), now.Month(), now.Year());
if (ext == nullptr)
{
// append an extension
switch (Model())
{
case MODEL_HTML:
vt_safe_string::safe_concat(buffer, max_len, ".html");
break;
case MODEL_POSTSCRIPT:
vt_safe_string::safe_concat(buffer, max_len, ".ps");
break;
case MODEL_PDF:
vt_safe_string::safe_concat(buffer, max_len, ".pdf");
break;
case MODEL_RECEIPT_TEXT:
case MODEL_REPORT_TEXT:
vt_safe_string::safe_concat(buffer, max_len, ".txt");
break;
case MODEL_QUICKBOOKS_CSV:
vt_safe_string::safe_concat(buffer, max_len, ".csv");
break;
default:
vt_safe_string::safe_concat(buffer, max_len, ".prn");
break;
}
}
else
{
vt_safe_string::safe_concat(buffer, max_len, ext);
}
}
return 0;
}
int Printer::IsDirectory(const genericChar* path)
{
FnTrace("Printer::IsDirectory()");
struct stat sb;
int isdir = 0;
if (lstat(path, &sb) >= 0)
{
if ((sb.st_mode & S_IFMT) == S_IFDIR) // Fixed: use bitwise AND and comparison, not logical AND
isdir = 1;
}
return isdir;
}
/****
* FilePrint: If the target specifies a directory, create a filename out of the
* page_title, or GENERIC_TITLE if page_title has not been set, and add that
* to the target for the full path.
****/
int Printer::FilePrint()
{
FnTrace("Printer::FilePrint()");
int retval = 0;
int renval = 0;
genericChar fullpath[STRLENGTH];
genericChar command[STRLONG];
GetFilePath(fullpath);
vt::cpp23::format_to_buffer(command, STRLONG, "mv {} {}", temp_name.Value(), fullpath);
renval = system(command);
if (renval < 0)
retval = 1; // return error
else
chmod(fullpath, 0644);
return retval;
}
int Printer::GetFilePath(char* dest)
{
FnTrace("Printer::GetFilePath()");
char filename[STRLENGTH];
if (IsDirectory(target.Value()))
{
MakeFileName(filename, nullptr, nullptr, STRLENGTH);
vt_safe_string::safe_format(dest, STRLENGTH, "%s/%s", target.Value(), filename);
}
else
{
strncpy(dest, target.Value(), STRLENGTH);
}
return 0;
}
/****
* EmailPrint: Need to package the printed file into an email using MIME.
****/
int Printer::EmailPrint()
{
FnTrace("Printer::EmailPrint()");
genericChar buffer[STRLONG];
int buffidx;
ssize_t bytesread;
genericChar line[STRLONG];
int lineidx;
Email email;
int fd;
int sockfd;
Settings *settings = MasterControl->TermList()->GetSettings();
if (settings->email_replyto.empty())
{
ReportError("No ReplyTo address specified for emails");
return 1;
}
email.AddTo(target.Value());
email.AddFrom(settings->email_replyto.Value());
email.AddSubject(page_title.c_str());
// now read in the file and add it to the email
fd = open(temp_name.Value(), O_RDONLY);
if (fd > 0)
{
lineidx = 0;
bytesread = read(fd, buffer, STRLONG);
while (bytesread > 0)
{
buffidx = 0;
while (buffidx < bytesread)
{
if (buffer[buffidx] == '\n' && lineidx > 0)
{
line[lineidx] = '\0';
email.AddBody(line);
lineidx = 0;
buffidx += 1;
}
else
{
line[lineidx] = buffer[buffidx];
buffidx += 1;
lineidx += 1;
}
}
bytesread = read(fd, buffer, STRLONG);
}
close(fd);
}
else if (fd < 0)
{
vt::cpp23::format_to_buffer(buffer, STRLONG, "EmailPrint Error {} opening {}",
errno, temp_name.Value());
ReportError(buffer);
}
// Email the file
sockfd = Connect(settings->email_send_server.Value(), "smtp");
if (sockfd > 0)
{
if (SMTP(sockfd, &email))
ReportError("Failed to send email");
close(sockfd);
}
return 0;
}
/****
* TestPrint: Just print something that will let us know the printer
* is working.
****/
int Printer::TestPrint(Terminal *t)
{
FnTrace("Printer::TestPrint()");
if (Start())
return 1;
genericChar str[256];
NewLine();
vt_safe_string::safe_format(str, 256, "\r** %s **\r", t->Translate("Printer Test"));
Write(str, PRINT_RED | PRINT_BOLD | PRINT_UNDERLINE | PRINT_LARGE | PRINT_NARROW);
vt_safe_string::safe_format(str, 256, "Host: %s\r", target.Value());
Write(str);
t->TimeDate(str, SystemTime, TD0);
Write(str);
return End();
}
int Printer::WriteLR(const genericChar* left, const genericChar* right, int flags)
{
FnTrace("Printer::WriteLR()");
if (WriteFlags(flags))
return 1;
int llen = strlen(left);
int rlen = strlen(right);
int width = Width(flags);
genericChar str[256];
// FIX - stupid truncate-word wrap for now
int pos = 0;
// Handle text that doesn't fit on one line
while ((llen + rlen + 1 - pos) > width && pos < llen)
{
ssize_t write_len = (pos + width > llen) ? (llen - pos) : width;
if (write(temp_fd, &left[pos], write_len) < 0)
{
vt::Logger::error("Printer::WriteLR failed to write truncated left text");
return 1;
}
// Pad with spaces if needed
if (write_len < width)
{
memset(str, ' ', width - write_len);
if (write(temp_fd, str, width - write_len) < 0)
{
vt::Logger::error("Printer::WriteLR failed to write padding spaces");
return 1;
}
}
NewLine();
pos += width;
}
// Fill the final line with spaces
memset(str, ' ', width);
// Copy remaining left text
if (pos < llen)
{
ssize_t left_len = (llen - pos > width - rlen - 1) ? (width - rlen - 1) : (llen - pos);
memcpy(str, &left[pos], left_len);
}
// Copy right text
if (rlen > 0)
{
vt_safe_string::safe_copy(&str[width - rlen], 256 - (width - rlen), right);
}
write(temp_fd, str, width);
NewLine();
return 0;
}
int Printer::Write(const genericChar* my_string, int flags)
{
FnTrace("Printer::Write()");
if (temp_fd <= 0)
return 1;
WriteFlags(flags);
if (write(temp_fd, my_string, strlen(my_string)) < 0) {
vt::Logger::error("Printer::Write failed to write string");
return 1;
}
NewLine();
return 0;
}
int Printer::Put(const genericChar* my_string, int flags)
{
FnTrace("Printer::Put()");
if (WriteFlags(flags))
return 1;
if (write(temp_fd, my_string, strlen(my_string)) < 0) {
vt::Logger::error("Printer::Put failed to write string");
return 1;
}
return 0;
}
int Printer::Put(genericChar c, int flags)
{
FnTrace("Printer::Put()");
if (WriteFlags(flags))
return 1;
genericChar str[] = {c};
if (write(temp_fd, str, sizeof(str)) < 0) {
vt::Logger::error("Printer::Put failed to write character");
return 1;
}
return 0;
}
/****
* DebugPrint: Exclusively for debugging.
****/
void Printer::DebugPrint(int printall)
{
FnTrace("Printer::DebugPrint()");
printf("Printer:\n");
printf(" Temp Name: %s\n", temp_name.Value());
printf(" Target: %s\n", target.Value());
printf(" Host Name: %s\n", host_name.Value());
printf(" Page Title: %s\n", page_title.c_str());
printf(" Last Mode: %d\n", last_mode);
printf(" Last Color: %d\n", last_color);
printf(" Last Uni: %d\n", last_uni);
printf(" Last Uline: %d\n", last_uline);
printf(" Last Large: %d\n", last_large);
printf(" Last Narrow: %d\n", last_narrow);
printf(" Last Bold: %d\n", last_bold);
printf(" Temp FD: %d\n", temp_fd);
printf(" Target Type: %d\n", target_type);
printf(" Port No: %d\n", port_no);
printf(" Active Flags: %d\n", active_flags);
printf(" Printer Type: %d\n", printer_type);
printf(" Have Title: %d\n", have_title);
printf(" Kitchen Mode: %d\n", kitchen_mode);
if (printall && next != nullptr)
next->DebugPrint(printall);
}
/*********************************************************************
* ITHACA PRINTERS
********************************************************************/
PrinterIthaca::PrinterIthaca(const genericChar* host, int port, const genericChar* targetstr, int type)
{
next = nullptr;
fore = nullptr;
parent = nullptr;
last_mode = 0;
last_color = 0;
last_uni = 0;
last_uline = 0;
last_large = 0;
last_narrow = 0;
last_bold = 0;
port_no = 0;