diff --git a/arcdist.cc b/arcdist.cc index cd0349a2a..f126bf523 100644 --- a/arcdist.cc +++ b/arcdist.cc @@ -22,7 +22,7 @@ #include "arcdist.h" #include // for round -#include // for printf, sscanf +#include // for sscanf #include // for tie, tuple #include // for QByteArray @@ -37,7 +37,6 @@ #if FILTERS_ENABLED -#define MYNAME "Arc filter" #define BADVAL 999999 @@ -66,10 +65,10 @@ void ArcDistanceFilter::arcdist_arc_disp_wpt_cb(const Waypoint* arcpt2) frac = 1.0; } else { if (waypointp == nullptr) { - fatal(FatalMsg() << "Internal error. Attempt to project through a waypoint that doesn't exist"); + gbFatal(FatalMsg() << "Internal error. Attempt to project through a waypoint that doesn't exist"); } if (arcpt1 == nullptr) { - fatal(FatalMsg() << "Internal error: Attempt to project waypoint without predecessor"); + gbFatal(FatalMsg() << "Internal error: Attempt to project waypoint without predecessor"); } std::tie(dist, prjpos, frac) = linedistprj(arcpt1->position(), @@ -112,7 +111,7 @@ void ArcDistanceFilter::process() QString line; gpsbabel::TextStream stream; - stream.open(arcfileopt, QIODevice::ReadOnly, MYNAME); + stream.open(arcfileopt, QIODevice::ReadOnly); auto* arcpt1 = new Waypoint; auto* arcpt2 = new Waypoint; @@ -134,7 +133,7 @@ void ArcDistanceFilter::process() int argsfound = sscanf(CSTR(line), "%lf %lf", &arcpt2->latitude, &arcpt2->longitude); if ((argsfound != 2) && (line.trimmed().size() > 0)) { - warning(MYNAME ": Warning: Arc file contains unusable vertex on line %d.\n", fileline); + gbWarning("Warning: Arc file contains unusable vertex on line %d.\n", fileline); } else { Waypoint* arcpttmp = arcpt1; arcdist_arc_disp_wpt_cb(arcpt2); @@ -190,8 +189,8 @@ void ArcDistanceFilter::process() } } if (global_opts.debug_level >= 1) { - warning("Including waypoint %s at dist:%f lat:%f lon:%f\n", - qPrintable(wp->shortname), ed->distance, wp->latitude, wp->longitude); + gbWarning("Including waypoint %s at dist:%f lat:%f lon:%f\n", + gbLogCStr(wp->shortname), ed->distance, wp->latitude, wp->longitude); } } delete ed; @@ -199,7 +198,7 @@ void ArcDistanceFilter::process() } del_marked_wpts(); if (global_opts.verbose_status > 0) { - printf(MYNAME "-arc: %u waypoint(s) removed.\n", removed); + gbInfo("%u waypoint(s) removed.\n", removed); } } @@ -208,14 +207,14 @@ void ArcDistanceFilter::init() if ((!arcfileopt && !rteopt && !trkopt) || (arcfileopt && (rteopt || trkopt)) || (rteopt && trkopt)) { - fatal(MYNAME ": Incompatible or incomplete option values!\n"); + gbFatal("Incompatible or incomplete option values!\n"); } pos_dist = 0.0; if (distopt) { - if (parse_distance(distopt, &pos_dist, kMetersPerMile, MYNAME) == 0) { - fatal(MYNAME ": No distance specified with distance option.\n"); + if (parse_distance(distopt, &pos_dist, kMetersPerMile) == 0) { + gbFatal("No distance specified with distance option.\n"); } } } diff --git a/bend.cc b/bend.cc index 4f7abc2cb..ec1d3e544 100644 --- a/bend.cc +++ b/bend.cc @@ -33,8 +33,6 @@ #include "grtcirc.h" // for RAD, heading_true_degrees, gcdist, linepart, radtometers, DEG -#define MYNAME "bend" - #if FILTERS_ENABLED void BendFilter::init() diff --git a/csv_util.cc b/csv_util.cc index 0fde1d128..68c3a954f 100644 --- a/csv_util.cc +++ b/csv_util.cc @@ -35,8 +35,6 @@ #include "src/core/logging.h" // for Warning -#define MYNAME "CSV_UTIL" - /*********************************************************************/ /* csv_stringclean() - remove any unwanted characters from string. */ /* returns copy of string. */ @@ -229,7 +227,7 @@ csv_linesplit(const QString& string, const QString& delimited_by, } if (enclosed) { - Warning() << MYNAME":" << + Warning() << "Warning- Unbalanced Field Enclosures" << enclosed_in << "on line" << @@ -528,7 +526,7 @@ dec_to_human(const char* format, const char* dirs, double val) case 'x': case 'X': if (index>2) { - fatal(MYNAME ": too many format specifiers\n"); + gbFatal("too many format specifiers\n"); } buff += QString::asprintf(subformat, intvals[index]); index++; @@ -539,7 +537,7 @@ dec_to_human(const char* format, const char* dirs, double val) case 'g': case 'G': if (index>2) { - fatal(MYNAME ": too many format specifiers\n"); + gbFatal("too many format specifiers\n"); } buff += QString::asprintf(subformat, dblvals[index]); index++; @@ -548,7 +546,7 @@ dec_to_human(const char* format, const char* dirs, double val) buff += subformat; break; default: - fatal(MYNAME ": invalid format specifier\n"); + gbFatal("invalid format specifier\n"); break; } diff --git a/defs.h b/defs.h index 879a0f257..95072fdb5 100644 --- a/defs.h +++ b/defs.h @@ -51,6 +51,7 @@ #include "src/core/datetime.h" // for DateTime +#define gbLogCStr(qstr) qUtf8Printable(qstr) #define CSTR(qstr) ((qstr).toUtf8().constData()) #define CSTRc(qstr) ((qstr).toLatin1().constData()) @@ -571,7 +572,9 @@ WaypointList::waypt_disp_session(const session_t* se, T cb) } } if (global_opts.verbose_status) { - fprintf(stdout, "\r\n"); + // Terminate the progress line from waypt_status_disp. + fprintf(stderr, "\n"); + fflush(stderr); } } @@ -907,8 +910,8 @@ enum ff_cap { #define FF_CAP_RW_WPT \ { (ff_cap) (ff_cap_read | ff_cap_write), ff_cap_none, ff_cap_none} -[[noreturn]] void fatal(QDebug& msginstance); -// cppcheck 2.10.3 fails to assign noreturn attribute to fatal if +[[noreturn]] void gbFatal(QDebug& msginstance); +// cppcheck 2.10.3 fails to assign noreturn attribute to gbFatal if // the noreturn attribute is listed before the gnu::format attribute. // A PR to resolve this is https://github.com/danmar/cppcheck/pull/4971, // but cppcheck works if the noreturn attribute follows the gnu::format @@ -916,8 +919,12 @@ enum ff_cap { // This can have a large effect on codacy issues from cppcheck // nullPointerRedundantCheck, nullPointerArithmeticRedundantCheck, // negativeIndex, arrayIndexOutOfBoundsCond. -[[gnu::format(printf, 1, 2)]] [[noreturn]] void fatal(const char* fmt, ...); -[[gnu::format(printf, 1, 2)]] void warning(const char* fmt, ...); +[[gnu::format(printf, 1, 2)]] [[noreturn]] void gbFatal(const char* fmt, ...); +[[gnu::format(printf, 1, 2)]] void gbWarning(const char* fmt, ...); +[[gnu::format(printf, 1, 2)]] void gbInfo(const char* fmt, ...); +[[gnu::format(printf, 1, 2)]] void gbDebug(const char* fmt, ...); + +void gbVLegacyLog(QtMsgType type, const char* fmt, va_list args1); void printposn(double c, bool is_lat); @@ -927,7 +934,7 @@ void* xrealloc(void* p, size_t s); void xfree(const void* mem); char* xstrdup(const char* s); -FILE* xfopen(const QString& fname, const char* type, const QString& errtxt); +FILE* xfopen(const QString& fname, const char* type); // Thin wrapper around fopen() that supports Unicode fname on all platforms. FILE* ufopen(const QString& fname, const char* mode); @@ -1028,11 +1035,11 @@ int xstrtoi(const char* str, char** str_end, int base); int parse_integer(const QString& str, const QString& id, bool* ok = nullptr, QString* end = nullptr, int base = 10); double parse_double(const QString& str, const QString& id, bool* ok = nullptr, QString* end = nullptr); int parse_coordinates(const char* str, int datum, grid_type grid, - double* latitude, double* longitude, const char* module); + double* latitude, double* longitude); int parse_coordinates(const QString& str, int datum, grid_type grid, - double* latitude, double* longitude, const char* module); -int parse_distance(const QString& str, double* val, double scale, const char* module); -int parse_speed(const QString& str, double* val, double scale, const char* module); + double* latitude, double* longitude); +int parse_distance(const QString& str, double* val, double scale); +int parse_speed(const QString& str, double* val, double scale); /* * Color helpers. diff --git a/dg-100.cc b/dg-100.cc index 5594ef24f..3cd1932c3 100644 --- a/dg-100.cc +++ b/dg-100.cc @@ -32,7 +32,7 @@ #include // for assert #include // for va_end, va_list, va_start #include // for uint8_t, uint16_t, int16_t -#include // for fprintf, stderr, size_t, vfprintf +#include // for size_t, va_list #include // for abs #include // for memcpy, memcmp, strcmp @@ -52,8 +52,6 @@ #include "gbser.h" // for gbser_deinit, gbser_flush, gbser_init, gbser_read_wait, gbser_readc_wait, gbser_set_speed, gbser_write, gbser_ERROR, gbser_OK, gbser_NOTHING -#define MYNAME "DG-100" - const Dg100Format::dg100_command Dg100Format::dg100_commands[] = { { dg100cmd_getfile, 2, 1024, 2, "getfile" }, /* the getfileheader answer has variable length, -1 is a dummy value */ @@ -81,7 +79,7 @@ const Dg100Format::dg100_command Dg100Format::dg200_commands[] = { /* helper functions */ const Dg100Format::dg100_command* -Dg100Format::dg100_findcmd(int id) const +Dg100Format::dg100_findcmd(int id) { /* linear search should be OK as long as dg100_numcommands is small */ for (unsigned int i = 0; i < model->numcommands; i++) { @@ -120,26 +118,26 @@ Dg100Format::dg100_debug(const char* hdr, int include_nl, size_t sz, unsigned ch return; } - fprintf(stderr, "%s", hdr); + gbDebug("%s", hdr); for (unsigned int i = 0; i < sz; i++) { - fprintf(stderr, "%02x ", buf[i]); + gbDebug("%02x ", buf[i]); } if (include_nl) { - fprintf(stderr, "\n"); + gbDebug("\n"); } } void Dg100Format::dg100_log(const char* fmt, ...) { - va_list ap; - va_start(ap, fmt); if (global_opts.debug_level > 0) { - vfprintf(stderr, fmt, ap); + va_list ap; + va_start(ap, fmt); + gbVLegacyLog(QtDebugMsg, fmt, ap); + va_end(ap); } - va_end(ap); } @@ -168,7 +166,7 @@ Dg100Format::bin2deg(int val) } void -Dg100Format::process_gpsfile(uint8_t data[], route_head** track) const +Dg100Format::process_gpsfile(uint8_t data[], route_head** track) { const int recordsizes[3] = {8, 20, 32}; @@ -176,7 +174,7 @@ Dg100Format::process_gpsfile(uint8_t data[], route_head** track) const * determines the format of all subsequent records in the file */ int style = be_read32(data + 28); if (style > 2) { - fprintf(stderr, "unknown GPS record style %d", style); + gbWarning("unknown GPS record style %d\n", style); return; } int recsize = recordsizes[style]; @@ -258,7 +256,7 @@ Dg100Format::dg100_checksum(const uint8_t buf[], int count) /* communication functions */ size_t -Dg100Format::dg100_send(uint8_t cmd, const void* payload, size_t param_len) const +Dg100Format::dg100_send(uint8_t cmd, const void* payload, size_t param_len) { uint8_t frame[FRAME_MAXLEN]; @@ -295,10 +293,10 @@ Dg100Format::dg100_send(uint8_t cmd, const void* payload, size_t param_len) cons if (isfile) { QScopedArrayPointer buf(new uint8_t[framelen]); if (gbfread(buf.data(), 1, framelen, fin) != framelen) { - fatal("failed to get data to compare to sent data.\n"); + gbFatal("failed to get data to compare to sent data.\n"); } if (memcmp(frame, buf.data(), framelen) != 0) { - fatal("sent data does not match expected value.\n"); + gbFatal("sent data does not match expected value.\n"); } n = gbser_OK; @@ -316,19 +314,19 @@ Dg100Format::dg100_send(uint8_t cmd, const void* payload, size_t param_len) cons } if (n == gbser_ERROR) { - fatal("dg_100_send: write failed\n"); + gbFatal("dg_100_send: write failed\n"); } return (n); } int -Dg100Format::dg100_recv_byte() const +Dg100Format::dg100_recv_byte() { int result; if (isfile) { result = gbfgetc(fin); if (result < 0) { - fatal("dg100_recv_byte(): read error\n"); + gbFatal("dg100_recv_byte(): read error\n"); } } else { /* allow for a delay of 40s; @@ -337,16 +335,16 @@ Dg100Format::dg100_recv_byte() const result = gbser_readc_wait(serial_handle, 40000); switch (result) { case gbser_ERROR: - fatal("dg100_recv_byte(): error reading one byte\n"); + gbFatal("dg100_recv_byte(): error reading one byte\n"); case gbser_NOTHING: - fatal("dg100_recv_byte(): read timeout\n"); + gbFatal("dg100_recv_byte(): read timeout\n"); } } return result; } int -Dg100Format::dg100_read_wait(void* handle, void* buf, unsigned len, unsigned ms) const +Dg100Format::dg100_read_wait(void* handle, void* buf, unsigned len, unsigned ms) { if (isfile) { return gbfread(buf, 1, len, fin); @@ -359,7 +357,7 @@ Dg100Format::dg100_read_wait(void* handle, void* buf, unsigned len, unsigned ms) * framing around the data), so the caller must copy the data before calling * this function again */ int -Dg100Format::dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** payload) const +Dg100Format::dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** payload) { static uint8_t buf[FRAME_MAXLEN]; uint16_t payload_end_seq; @@ -399,7 +397,7 @@ Dg100Format::dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** pa /* read Payload Length, Command ID, and two further bytes */ int i = dg100_read_wait(serial_handle, &buf[2], 5, 1000); if (i < 5) { - fatal("Expected to read 5 bytes, but got %d\n", i); + gbFatal("Expected to read 5 bytes, but got %d\n", i); } dg100_debug("", 0, 5, &buf[2]); @@ -420,7 +418,7 @@ Dg100Format::dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** pa if (!cmdinfo) { /* TODO: consume data until frame end signature, * then report failure to the caller? */ - fatal("unknown answer ID %02x\n", cmd); + gbFatal("unknown answer ID %02x\n", cmd); } int param_len = cmdinfo->recvsize; @@ -445,13 +443,13 @@ Dg100Format::dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** pa int frame_len = 2 + 2 + 1 + param_len + ((model->has_payload_end_seq) ? 2 : 0) + 2 + 2; if (frame_len > FRAME_MAXLEN) { - fatal("frame too large (frame_len=%d, FRAME_MAXLEN=%d)\n", + gbFatal("frame too large (frame_len=%d, FRAME_MAXLEN=%d)\n", frame_len, FRAME_MAXLEN); } i = dg100_read_wait(serial_handle, &buf[7], frame_len - 7, 1000); if (i < frame_len - 7) { - fatal("Expected to read %d bytes, but got %d\n", + gbFatal("Expected to read %d bytes, but got %d\n", frame_len - 7, i); } dg100_debug("", 0, frame_len - 7, &buf[7]); @@ -472,7 +470,7 @@ Dg100Format::dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** pa /* calculate checksum */ uint16_t sum = dg100_checksum(buf + 4, frame_len - 8); if (sum != payload_checksum) { - fatal("checksum mismatch: data sum is 0x%04x, checksum received is 0x%04x\n", + gbFatal("checksum mismatch: data sum is 0x%04x, checksum received is 0x%04x\n", sum, payload_checksum); } @@ -489,7 +487,7 @@ Dg100Format::dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** pa /* return value: number of bytes copied into buf, -1 on error */ int -Dg100Format::dg100_recv(uint8_t expected_id, void* buf, unsigned int len) const +Dg100Format::dg100_recv(uint8_t expected_id, void* buf, unsigned int len) { const dg100_command* cmdinfo; uint8_t* data; @@ -498,7 +496,7 @@ Dg100Format::dg100_recv(uint8_t expected_id, void* buf, unsigned int len) const /* check whether the received frame matches the expected answer type */ if (cmdinfo->id != expected_id) { - fprintf(stderr, "ERROR: answer type %02x, expecting %02x", cmdinfo->id, expected_id); + gbWarning("ERROR: answer type %02x, expecting %02x\n", cmdinfo->id, expected_id); return -1; } @@ -507,7 +505,7 @@ Dg100Format::dg100_recv(uint8_t expected_id, void* buf, unsigned int len) const /* check for buffer overflow */ if (len < copysize) { - fprintf(stderr, "ERROR: buffer too small, size=%u, need=%u", len, copysize); + gbWarning("ERROR: buffer too small, size=%u, need=%u\n", len, copysize); return -1; } @@ -518,7 +516,7 @@ Dg100Format::dg100_recv(uint8_t expected_id, void* buf, unsigned int len) const /* the number of bytes to be sent is determined by cmd, * count is the size of recvbuf */ int -Dg100Format::dg100_request(uint8_t cmd, const void* sendbuf, void* recvbuf, size_t count) const +Dg100Format::dg100_request(uint8_t cmd, const void* sendbuf, void* recvbuf, size_t count) { const dg100_command* cmdinfo = dg100_findcmd(cmd); assert(cmdinfo != nullptr); @@ -541,7 +539,7 @@ Dg100Format::dg100_request(uint8_t cmd, const void* sendbuf, void* recvbuf, size /* higher level communication functions */ QList -Dg100Format::dg100_getfileheaders() const +Dg100Format::dg100_getfileheaders() { QList headers; uint8_t request[2]; @@ -582,7 +580,7 @@ Dg100Format::dg100_getfileheaders() const } void -Dg100Format::dg100_getconfig() const +Dg100Format::dg100_getconfig() { uint8_t answer[45]; @@ -590,7 +588,7 @@ Dg100Format::dg100_getconfig() const } void -Dg100Format::dg100_getfile(int16_t num, route_head** track) const +Dg100Format::dg100_getfile(int16_t num, route_head** track) { uint8_t request[2]; uint8_t answer[2048]; @@ -601,7 +599,7 @@ Dg100Format::dg100_getfile(int16_t num, route_head** track) const } void -Dg100Format::dg100_getfiles() const +Dg100Format::dg100_getfiles() { route_head* track = nullptr; @@ -624,14 +622,14 @@ Dg100Format::dg100_getfiles() const } int -Dg100Format::dg100_erase() const +Dg100Format::dg100_erase() { uint8_t request[2] = { 0xFF, 0xFF }; uint8_t answer[4]; dg100_request(dg100cmd_erase, request, answer, sizeof(answer)); if (be_read32(answer) != 1) { - fprintf(stderr, "dg100_erase() FAILED\n"); + gbWarning("dg100_erase() FAILED\n"); return(-1); } return(0); @@ -645,13 +643,13 @@ void Dg100Format::common_rd_init(const QString& fname) { if (isfile) { - fin = gbfopen(fname, "rb", MYNAME); + fin = gbfopen(fname, "rb"); } else { if (serial_handle = gbser_init(qPrintable(fname)), nullptr == serial_handle) { - fatal(MYNAME ": Can't open port '%s'\n", qPrintable(fname)); + gbFatal("Can't open port '%s'\n", gbLogCStr(fname)); } if (gbser_set_speed(serial_handle, model->speed) != gbser_OK) { - fatal(MYNAME ": Can't configure port '%s'\n", qPrintable(fname)); + gbFatal("Can't configure port '%s'\n", gbLogCStr(fname)); } // Toss anything that came in before our speed was set, particularly // for the bluetooth BT-335 product. diff --git a/dg-100.h b/dg-100.h index be51c8f5c..fec4a3314 100644 --- a/dg-100.h +++ b/dg-100.h @@ -108,24 +108,24 @@ class Dg100Format : public Format /* Member Functions */ - const dg100_command* dg100_findcmd(int id) const; + const dg100_command* dg100_findcmd(int id); static QDateTime bintime2utc(int date, int time); static void dg100_debug(const char* hdr, int include_nl, size_t sz, unsigned char* buf); [[gnu::format(printf, 1, 2)]] static void dg100_log(const char* fmt, ...); static float bin2deg(int val); - void process_gpsfile(uint8_t* data, route_head** track) const; + void process_gpsfile(uint8_t* data, route_head** track); static uint16_t dg100_checksum(const uint8_t* buf, int count); - size_t dg100_send(uint8_t cmd, const void* payload, size_t param_len) const; - int dg100_recv_byte() const; - int dg100_read_wait(void* handle, void* buf, unsigned int len, unsigned int ms) const; - int dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** payload) const; - int dg100_recv(uint8_t expected_id, void* buf, unsigned int len) const; - int dg100_request(uint8_t cmd, const void* sendbuf, void* recvbuf, size_t count) const; - QList dg100_getfileheaders() const; - void dg100_getconfig() const; - void dg100_getfile(int16_t num, route_head** track) const; - void dg100_getfiles() const; - int dg100_erase() const; + size_t dg100_send(uint8_t cmd, const void* payload, size_t param_len); + int dg100_recv_byte(); + int dg100_read_wait(void* handle, void* buf, unsigned int len, unsigned int ms); + int dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** payload); + int dg100_recv(uint8_t expected_id, void* buf, unsigned int len); + int dg100_request(uint8_t cmd, const void* sendbuf, void* recvbuf, size_t count); + QList dg100_getfileheaders(); + void dg100_getconfig(); + void dg100_getfile(int16_t num, route_head** track); + void dg100_getfiles(); + int dg100_erase(); void common_rd_init(const QString& fname); void dg100_rd_init(const QString& fname, bool is_file); void dg200_rd_init(const QString& fname, bool is_file); diff --git a/discard.cc b/discard.cc index 39a7960e6..675fe9a10 100644 --- a/discard.cc +++ b/discard.cc @@ -24,7 +24,7 @@ #include // for QDebug #include // for QRegularExpression, QRegularExpression::CaseInsensitiveOption, QRegularExpressionMatch -#include "defs.h" // for Waypoint, fatal, route_head (ptr only), del_marked_wpts, route_del_marked_wpts, route_disp_all, track_del_marked_wpts, track_disp_all, waypt_disp_all, fix_none, fix_unknown +#include "defs.h" // for Waypoint, gbFatal, route_head (ptr only), del_marked_wpts, route_del_marked_wpts, route_disp_all, track_del_marked_wpts, track_disp_all, waypt_disp_all, fix_none, fix_unknown #include "src/core/logging.h" // for FatalMsg @@ -157,25 +157,25 @@ void DiscardFilter::init() if (nameopt) { name_regex = generateRegExp(nameopt); if (!name_regex.isValid()) { - fatal(FatalMsg() << "discard: matchname option is an invalid expression."); + gbFatal(FatalMsg() << "discard: matchname option is an invalid expression."); } } if (descopt) { desc_regex = generateRegExp(descopt); if (!desc_regex.isValid()) { - fatal(FatalMsg() << "discard: matchdesc option is an invalid expression."); + gbFatal(FatalMsg() << "discard: matchdesc option is an invalid expression."); } } if (cmtopt) { cmt_regex = generateRegExp(cmtopt); if (!cmt_regex.isValid()) { - fatal(FatalMsg() << "discard: matchcmt option is an invalid expression."); + gbFatal(FatalMsg() << "discard: matchcmt option is an invalid expression."); } } if (iconopt) { icon_regex = generateRegExp(iconopt); if (!icon_regex.isValid()) { - fatal(FatalMsg() << "discard: matchicon option is an invalid expression."); + gbFatal(FatalMsg() << "discard: matchicon option is an invalid expression."); } } } diff --git a/duplicate.cc b/duplicate.cc index 32378b319..6bdaacd7d 100644 --- a/duplicate.cc +++ b/duplicate.cc @@ -31,12 +31,10 @@ #if FILTERS_ENABLED -#define MYNAME "duplicate" - void DuplicateFilter::init() { if (!lcopt && !snopt) { - fatal(MYNAME ": one or both of the shortname and location options are required.\n"); + gbFatal("one or both of the shortname and location options are required.\n"); } } diff --git a/exif.cc b/exif.cc index e0bfbfec3..64ce413b2 100644 --- a/exif.cc +++ b/exif.cc @@ -61,20 +61,18 @@ #include // for DBL_EPSILON #include // for fabs, modf, copysign, round, fmax #include // for uint32_t, int32_t, uint16_t, int16_t, uint8_t, INT32_MAX -#include // for printf, SEEK_SET, snprintf, SEEK_CUR +#include // for SEEK_SET, SEEK_CUR, snprintf #include // for abs #include // for memcmp, strlen #include // for as_const -#include "defs.h" // for Waypoint, fatal, warning, global_options, global_opts, unknown_alt, xfree, route_disp_all, track_disp_all, waypt_disp_all, wp_flags, KNOTS_TO_MPS, KPH_TO_MPS, MPH_TO_MPS, MPS_TO_KPH, WAYPT_HAS, case_ignore_strcmp, waypt_add, fix_2d +#include "defs.h" // for Waypoint, gbFatal, gbWarning, global_options, global_opts, unknown_alt, xfree, route_disp_all, track_disp_all, waypt_disp_all, wp_flags, KNOTS_TO_MPS, KPH_TO_MPS, MPH_TO_MPS, MPS_TO_KPH, WAYPT_HAS, case_ignore_strcmp, waypt_add, fix_2d #include "garmin_tables.h" // for gt_lookup_datum_index #include "gbfile.h" // for gbfputuint32, gbfputuint16, gbfgetuint16, gbfgetuint32, gbfseek, gbftell, gbfile, gbfclose, gbfcopyfrom, gbfwrite, gbfopen_be, gbfread, gbfrewind, gbfgetflt, gbfgetint16, gbfopen, gbfputc, gbfputflt, gbsize_t, gbfeof, gbfgetdbl, gbfputdbl, gbfile::(anonymous) #include "jeeps/gpsmath.h" // for GPS_Math_WGS84_To_Known_Datum_M #include "src/core/datetime.h" // for DateTime -#define MYNAME "exif" - #define IFD0 0 #define IFD1 1 #define EXIF_IFD 2 /* dummy index */ @@ -138,9 +136,9 @@ ExifFormat::print_buff(const char* buf, int sz, const char* cmt) { int i; - printf("%s: ", cmt); + gbDebug("%s: ", cmt); for (i = 0; i < sz; i++) { - printf("%02x ", buf[i] & 0xFF); + gbDebug("%02x ", buf[i] & 0xFF); } for (i = 0; i < sz; i++) { char c = buf[i]; @@ -149,7 +147,7 @@ ExifFormat::print_buff(const char* buf, int sz, const char* cmt) } else if (! isprint(c)) { c = '.'; } - printf("%c", c); + gbDebug("%c", c); } } @@ -189,7 +187,7 @@ ExifFormat::exif_type_size(const uint16_t type) break; default: - fatal(MYNAME ": Unknown data type %d! Please report.\n", type); + gbFatal("Unknown data type %d! Please report.\n", type); } return size; } @@ -317,17 +315,17 @@ ExifFormat::exif_load_apps() while (! gbfeof(fin_)) { exif_apps->append(new ExifApp); ExifApp* app = exif_apps->last(); - app->fcache = gbfopen(nullptr, "wb", MYNAME); + app->fcache = gbfopen(nullptr, "wb"); app->marker = gbfgetuint16(fin_); app->len = gbfgetuint16(fin_); if (global_opts.debug_level >= 3) { - printf(MYNAME ": api = %02X, len = %u (0x%04x), offs = 0x%08X\n", app->marker & 0xFF, app->len, app->len, gbftell(fin_)); + gbDebug("api = %02X, len = %u (0x%04x), offs = 0x%08X\n", app->marker & 0xFF, app->len, app->len, gbftell(fin_)); } if (exif_app_ || (app->marker == 0xFFDA)) { /* compressed data */ gbfcopyfrom(app->fcache, fin_, 0x7FFFFFFF); if (global_opts.debug_level >= 3) { - printf(MYNAME ": compressed data size = %u\n", gbftell(app->fcache)); + gbDebug("compressed data size = %u\n", gbftell(app->fcache)); } } else { gbfcopyfrom(app->fcache, fin_, app->len - 2); @@ -403,7 +401,7 @@ ExifFormat::exif_read_ifd(ExifApp* app, const uint16_t ifd_nr, const gbsize_t of name = "private"; break; } - printf(MYNAME "-offs 0x%08X: Number of items in IFD%d \"%s\" = %d (0x%04x)\n", + gbDebug("offs 0x%08X: Number of items in IFD%d \"%s\" = %d (0x%04x)\n", offs, ifd_nr, name, ifd->count, ifd->count); } if (ifd->count == 0) { @@ -446,7 +444,7 @@ ExifFormat::exif_read_ifd(ExifApp* app, const uint16_t ifd_nr, const gbsize_t of tag->data.append(gbfgetflt(fin)); } } else { - fatal(MYNAME "Unknown type %d has size <= 4! Please report.\n", tag->type); + gbFatal("Unknown type %d has size <= 4! Please report.\n", tag->type); } int skip_bytes = 4 - tag->size; if (skip_bytes > 0) { @@ -522,49 +520,49 @@ ExifFormat::exif_read_ifd(ExifApp* app, const uint16_t ifd_nr, const gbsize_t of } } if (global_opts.debug_level >= 3) { - printf(MYNAME "-offs 0x%08X: ifd=%d id=0x%04X t=0x%04X c=%4u s=%4u", + gbDebug("offs 0x%08X: ifd=%d id=0x%04X t=0x%04X c=%4u s=%4u", tag->tag_offset, ifd->nr, tag->id, tag->type, tag->count, tag->size); if (tag->size > 4) { - printf(" o=0x%08X", tag->offset); + gbDebug(" o=0x%08X", tag->offset); } else { - printf(" v=0x%02X%02X%02X%02X", tag->raw[0], tag->raw[1], tag->raw[2], tag->raw[3]); + gbDebug(" v=0x%02X%02X%02X%02X", tag->raw[0], tag->raw[1], tag->raw[2], tag->raw[3]); } if (tag->type == EXIF_TYPE_ASCII) { QByteArray str = exif_read_str(tag); - printf(" \"%s\"", str.constData()); + gbDebug(" \"%s\"", str.constData()); } else { for (unsigned idx = 0; idx < std::min(tag->count, 4u); ++idx) { if (tag->type == EXIF_TYPE_BYTE) { - printf(" %u", tag->data.at(0).toByteArray().at(idx)); + gbDebug(" %u", tag->data.at(0).toByteArray().at(idx)); } else if (tag->type == EXIF_TYPE_SBYTE) { - printf(" %d", tag->data.at(0).toByteArray().at(idx)); + gbDebug(" %d", tag->data.at(0).toByteArray().at(idx)); } else if (tag->type == EXIF_TYPE_UNK) { - printf(" 0x%02X", tag->data.at(0).toByteArray().at(idx)); + gbDebug(" 0x%02X", tag->data.at(0).toByteArray().at(idx)); } else if (tag->type == EXIF_TYPE_RAT) { - printf(" %+#g(%u/%u)", exif_read_double(tag, idx), tag->data.at(idx * 2).value(), tag->data.at((idx * 2) + 1).value()); + gbDebug(" %+#g(%u/%u)", exif_read_double(tag, idx), tag->data.at(idx * 2).value(), tag->data.at((idx * 2) + 1).value()); } else if (tag->type == EXIF_TYPE_SRAT) { - printf(" %+#g(%d/%d)", exif_read_double(tag, idx), tag->data.at(idx * 2).value(), tag->data.at((idx * 2) + 1).value()); + gbDebug(" %+#g(%d/%d)", exif_read_double(tag, idx), tag->data.at(idx * 2).value(), tag->data.at((idx * 2) + 1).value()); } else if (tag->type == EXIF_TYPE_SHORT) { - printf(" %u", tag->data.at(idx).value()); + gbDebug(" %u", tag->data.at(idx).value()); } else if (tag->type == EXIF_TYPE_SSHORT) { - printf(" %d", tag->data.at(idx).value()); + gbDebug(" %d", tag->data.at(idx).value()); } else if (tag->type == EXIF_TYPE_LONG) { - printf(" %u", tag->data.at(idx).value()); + gbDebug(" %u", tag->data.at(idx).value()); } else if (tag->type == EXIF_TYPE_SLONG) { - printf(" %d", tag->data.at(idx).value()); + gbDebug(" %d", tag->data.at(idx).value()); } else if (tag->type == EXIF_TYPE_FLOAT) { - printf(" %+#g", tag->data.at(idx).value()); + gbDebug(" %+#g", tag->data.at(idx).value()); } else if (tag->type == EXIF_TYPE_DOUBLE) { - printf(" %+#g", tag->data.at(idx).value()); + gbDebug(" %+#g", tag->data.at(idx).value()); } else { - printf(" 0x%0*X", 2 * exif_type_size(tag->type), tag->data.at(idx).value()); + gbDebug(" 0x%0*X", 2 * exif_type_size(tag->type), tag->data.at(idx).value()); } } if (tag->count > 4) { - printf(" ..."); + gbDebug(" ..."); } } - printf("\n"); + gbDebug("\n"); } #ifndef NDEBUG exif_validate_tag_structure(tag); @@ -572,7 +570,7 @@ ExifFormat::exif_read_ifd(ExifApp* app, const uint16_t ifd_nr, const gbsize_t of } if (global_opts.debug_level >= 3) { - printf(MYNAME "-offs 0x%08X: Next IFD=0x%08X\n", next_ifd_offs, ifd->next_ifd); + gbDebug("offs 0x%08X: Next IFD=0x%08X\n", next_ifd_offs, ifd->next_ifd); } return ifd; @@ -589,9 +587,9 @@ ExifFormat::exif_read_app(ExifApp* app) gbfile* fin = app->fexif; if (global_opts.debug_level >= 3) { - printf(MYNAME ": read_app...\n"); - print_buff((const char*)fin->handle.mem, 8, MYNAME "-offs 0x00000000: Image File Header"); - printf("\n"); + gbDebug("read_app...\n"); + print_buff((const char*)fin->handle.mem, 8, "offs 0x00000000: Image File Header"); + gbDebug("\n"); } exif_ifd_ofs = gps_ifd_ofs = inter_ifd_ofs = 0; @@ -627,26 +625,26 @@ ExifFormat::exif_examine_app(ExifApp* app) gbfrewind(ftmp); uint32_t ident = gbfgetuint32(ftmp); if (ident != 0x66697845) { - fatal(MYNAME ": Invalid EXIF header magic."); + gbFatal("Invalid EXIF header magic.\n"); } if (gbfgetint16(ftmp) != 0) { - fatal(MYNAME ": Error in EXIF header."); + gbFatal("Error in EXIF header.\n"); } uint16_t endianness = gbfgetint16(ftmp); if (global_opts.debug_level >= 3) { - printf(MYNAME ": endianness = 0x%04X\n", endianness); + gbDebug("endianness = 0x%04X\n", endianness); } if (endianness == 0x4949) { ftmp->big_endian = 0; } else if (endianness == 0x4D4D) { ftmp->big_endian = 1; } else { - fatal(MYNAME ": Invalid endianness identifier 0x%04X!\n", endianness); + gbFatal("Invalid endianness identifier 0x%04X!\n", endianness); } gbfseek(ftmp, 6, SEEK_SET); - app->fexif = gbfopen(nullptr, "wb", MYNAME); + app->fexif = gbfopen(nullptr, "wb"); app->fexif->big_endian = ftmp->big_endian; gbfcopyfrom(app->fexif, ftmp, 0x7FFFFFFF); @@ -682,7 +680,7 @@ ExifFormat::exif_find_tag(ExifApp* app, const uint16_t ifd_nr, const uint16_t ta } QDateTime -ExifFormat::exif_get_exif_time(ExifApp* app) const +ExifFormat::exif_get_exif_time(ExifApp* app) { QDateTime res; @@ -739,7 +737,7 @@ ExifFormat::exif_get_exif_time(ExifApp* app) const } else if (opt_offsettime) { // Only warn for user supplied offsets. // Offset tags may indicate the offset was unknown, e.g. " : ". - warning(MYNAME ": OffsetTime is expected to be +HH:MM or -HH:MM, but was %s.\n", qPrintable(time_tag)); + gbWarning("OffsetTime is expected to be +HH:MM or -HH:MM, but was %s.\n", gbLogCStr(time_tag)); } } @@ -757,7 +755,7 @@ ExifFormat::exif_get_exif_time(ExifApp* app) const } Waypoint* -ExifFormat::exif_waypt_from_exif_app(ExifApp* app) const +ExifFormat::exif_waypt_from_exif_app(ExifApp* app) { ExifTag* tag; char lat_ref = '\0'; @@ -834,29 +832,29 @@ ExifFormat::exif_waypt_from_exif_app(ExifApp* app) const } if ((wpt->latitude == unknown_alt) || (wpt->longitude == unknown_alt)) { - fatal(MYNAME ": Missing GPSLatitude and/or GPSLongitude!\n"); + gbFatal("Missing GPSLatitude and/or GPSLongitude!\n"); } if (lat_ref == 'S') { wpt->latitude *= -1; } else if (lat_ref != 'N') { - warning(MYNAME ": GPSLatitudeRef not set! Using N(orth).\n"); + gbWarning("GPSLatitudeRef not set! Using N(orth).\n"); } if (lon_ref == 'W') { wpt->longitude *= -1; } else if (lon_ref != 'E') { - warning(MYNAME ": GPSLongitudeRef not set! Using E(ast).\n"); + gbWarning("GPSLongitudeRef not set! Using E(ast).\n"); } if (global_opts.debug_level >= 3) { - printf(MYNAME "-GPSLatitude = %12.7f\n", wpt->latitude); - printf(MYNAME "-GPSLongitude = %12.7f\n", wpt->longitude); + gbDebug("GPSLatitude = %12.7f\n", wpt->latitude); + gbDebug("GPSLongitude = %12.7f\n", wpt->longitude); } if (!datum.isEmpty()) { - int idatum = gt_lookup_datum_index(datum, MYNAME); + int idatum = gt_lookup_datum_index(datum); if (idatum < 0) { - fatal(MYNAME ": Unknown GPSMapDatum \"%s\"!\n", datum.constData()); + gbFatal("Unknown GPSMapDatum \"%s\"!\n", datum.constData()); } if (idatum != kDatumWGS84) { GPS_Math_WGS84_To_Known_Datum_M(wpt->latitude, wpt->longitude, 0.0, @@ -876,12 +874,12 @@ ExifFormat::exif_waypt_from_exif_app(ExifApp* app) const break; default: - warning(MYNAME ": Invalid GPSAltitudeRef (%d)! Using default value 0 (= Sea level).\n", alt_ref); + gbWarning("Invalid GPSAltitudeRef (%d)! Using default value 0 (= Sea level).\n", alt_ref); sign = 1.0; } wpt->altitude = sign * alt; if (global_opts.debug_level >= 3) { - printf(MYNAME "-GPSAltitude = %12.7f m\n", wpt->altitude); + gbDebug("GPSAltitude = %12.7f m\n", wpt->altitude); } } @@ -898,11 +896,11 @@ ExifFormat::exif_waypt_from_exif_app(ExifApp* app) const break; default: wpt->reset_speed(); - warning(MYNAME ": Unknown GPSSpeedRef unit %c (0x%02x)!\n", speed_ref, speed_ref); + gbWarning("Unknown GPSSpeedRef unit %c (0x%02x)!\n", speed_ref, speed_ref); } if (global_opts.debug_level >= 3) { if (wpt->speed_has_value()) { - printf(MYNAME "-GPSSpeed = %12.2f m/s\n", wpt->speed_value()); + gbDebug("GPSSpeed = %12.2f m/s\n", wpt->speed_value()); } } } @@ -922,7 +920,7 @@ ExifFormat::exif_waypt_from_exif_app(ExifApp* app) const gps_datetime = QDateTime(datestamp, timestamp, QtUTC); if (gps_datetime.isValid()) { if (global_opts.debug_level >= 3) { - printf(MYNAME "-GPSTimeStamp = %s\n", qPrintable(gps_datetime.toString(Qt::ISODateWithMs))); + gbDebug("GPSTimeStamp = %s\n", gbLogCStr(gps_datetime.toString(Qt::ISODateWithMs))); } wpt->SetCreationTime(gps_datetime); } else { @@ -966,7 +964,7 @@ ExifFormat::Rational ExifFormat::exif_dec2frac(double val, double toler if (pval < lower_limit) { return Rational(0, upper_limit); } else if (pval > upper_limit) { - fatal(MYNAME ": Value (%f) to big for a rational representation!\n", val); + gbFatal("Value (%f) to big for a rational representation!\n", val); return Rational(copysign(upper_limit, val), 1); } @@ -1007,7 +1005,7 @@ ExifFormat::Rational ExifFormat::exif_dec2frac(double val, double toler } ExifFormat::ExifTag* -ExifFormat::exif_put_value(const int ifd_nr, const uint16_t tag_id, const uint16_t type, const int count, const int index, const void* data) const +ExifFormat::exif_put_value(const int ifd_nr, const uint16_t tag_id, const uint16_t type, const int count, const int index, const void* data) { ExifTag* tag = nullptr; uint16_t size; @@ -1084,7 +1082,7 @@ ExifFormat::exif_put_value(const int ifd_nr, const uint16_t tag_id, const uint16 double val = *static_cast(data); if ((val < 0.0) && (type == EXIF_TYPE_RAT)) { - fatal(MYNAME ": A negative value cannot be stored as type RATIONAL."); + gbFatal("A negative value cannot be stored as type RATIONAL.\n"); } Rational rat = exif_dec2frac(val, 1e-11); @@ -1102,7 +1100,7 @@ ExifFormat::exif_put_value(const int ifd_nr, const uint16_t tag_id, const uint16 tag->data[index] = *static_cast(data); break; default: - fatal(MYNAME ": Unknown data type %u!\n", type); + gbFatal("Unknown data type %u!\n", type); } } return tag; @@ -1110,7 +1108,7 @@ ExifFormat::exif_put_value(const int ifd_nr, const uint16_t tag_id, const uint16 void -ExifFormat::exif_put_double(const int ifd_nr, const int tag_id, const int index, const double val) const +ExifFormat::exif_put_double(const int ifd_nr, const int tag_id, const int index, const double val) { // TODO: It seems wrong to throw away the sign. double d = fabs(val); @@ -1119,14 +1117,14 @@ ExifFormat::exif_put_double(const int ifd_nr, const int tag_id, const int index, void -ExifFormat::exif_put_str(const int ifd_nr, const int tag_id, const char* val) const +ExifFormat::exif_put_str(const int ifd_nr, const int tag_id, const char* val) { int len = (val) ? strlen(val) + 1 : 0; exif_put_value(ifd_nr, tag_id, EXIF_TYPE_ASCII, len, 0, val); } void -ExifFormat::exif_put_coord(const int ifd_nr, const int tag_id, const double val) const +ExifFormat::exif_put_coord(const int ifd_nr, const int tag_id, const double val) { double vdeg; double vmin; @@ -1142,19 +1140,19 @@ ExifFormat::exif_put_coord(const int ifd_nr, const int tag_id, const double val) } void -ExifFormat::exif_put_long(const int ifd_nr, const int tag_id, const int index, const int32_t val) const +ExifFormat::exif_put_long(const int ifd_nr, const int tag_id, const int index, const int32_t val) { exif_put_value(ifd_nr, tag_id, EXIF_TYPE_LONG, 1, index, &val); } void -ExifFormat::exif_put_short(const int ifd_nr, const int tag_id, const int index, const int16_t val) const +ExifFormat::exif_put_short(const int ifd_nr, const int tag_id, const int index, const int16_t val) { exif_put_value(ifd_nr, tag_id, EXIF_TYPE_SHORT, 1, index, &val); } void -ExifFormat::exif_remove_tag(const int ifd_nr, const int tag_id) const +ExifFormat::exif_remove_tag(const int ifd_nr, const int tag_id) { exif_put_value(ifd_nr, tag_id, EXIF_TYPE_BYTE, 0, 0, nullptr); } @@ -1223,7 +1221,7 @@ ExifFormat::exif_write_value(ExifTag* tag, gbfile* fout) gbfputflt(tag->data.at(0).value(), fout); } } else { - fatal(MYNAME ": Unknown data type %d or wrong tag size %d!\n", tag->type, tag->size); + gbFatal("Unknown data type %d or wrong tag size %d!\n", tag->type, tag->size); } int fill_bytes = 4 - tag->size; for (int idx = 0; idx < fill_bytes; ++idx) { @@ -1309,7 +1307,7 @@ ExifFormat::exif_write_ifd(ExifIfd* ifd, const char next, gbfile* fout) } void -ExifFormat::exif_write_apps() const +ExifFormat::exif_write_apps() { gbfputuint16(0xFFD8, fout_); @@ -1351,7 +1349,7 @@ ExifFormat::exif_write_apps() const // IFD1_TAG_COMPRESSION should be 6 indicating JPEG compressed image data. tag_size = exif_find_tag(app, IFD1, IFD1_TAG_JPEG_SIZE); if (tag_size == nullptr) { - fatal(MYNAME ": Invalid image file, in IFD1 both JPEGInterchangeFormat and JPEGInterchangeFormatLength must exist for compressed thumbnails."); + gbFatal("Invalid image file, in IFD1 both JPEGInterchangeFormat and JPEGInterchangeFormatLength must exist for compressed thumbnails.\n"); } auto offset = tag_offset->data.at(0).value(); auto size = tag_size->data.at(0).value(); @@ -1362,7 +1360,7 @@ ExifFormat::exif_write_apps() const // IFD1_TAG_COMPRESSION should be 1 indicating uncompressed image data. tag_size = exif_find_tag(app, IFD1, IFD1_TAG_STRIP_BYTE_COUNTS); if ((tag_size == nullptr) || (tag_size->count != tag_offset->count)) { - fatal(MYNAME ": Invalid image file, in IFD1 both StripOffsets and StripByteCounts must exist and have equal counts for uncompressed thumbnails."); + gbFatal("Invalid image file, in IFD1 both StripOffsets and StripByteCounts must exist and have equal counts for uncompressed thumbnails.\n"); } for (unsigned idx = 0; idx < tag_offset->count; idx++) { auto offset = tag_offset->data.at(idx).value(); @@ -1382,7 +1380,7 @@ ExifFormat::exif_write_apps() const std::sort(ifd->tags.begin(), ifd->tags.end(), exif_sort_tags_cb); } - gbfile* ftmp = gbfopen_be(nullptr, "wb", MYNAME); + gbfile* ftmp = gbfopen_be(nullptr, "wb"); ftmp->big_endian = app->fcache->big_endian; gbfwrite((ftmp->big_endian) ? "MM" : "II", 2, 1, ftmp); @@ -1427,7 +1425,7 @@ ExifFormat::exif_write_apps() const void ExifFormat::rd_init(const QString& fname) { - fin_ = gbfopen_be(fname, "rb", MYNAME); + fin_ = gbfopen_be(fname, "rb"); exif_apps = new QList; } @@ -1444,12 +1442,12 @@ ExifFormat::read() uint16_t soi = gbfgetuint16(fin_); /* only jpeg for now */ if (soi != 0xFFD8) { - fatal(MYNAME ": Unknown image file."); + gbFatal("Unknown image file.\n"); } exif_app_ = exif_load_apps(); if (exif_app_ == nullptr) { - fatal(MYNAME ": No EXIF header in source file \"%s\".", qPrintable(fin_->name)); + gbFatal("No EXIF header in source file \"%s\".\n", gbLogCStr(fin_->name)); } exif_examine_app(exif_app_); @@ -1467,30 +1465,30 @@ ExifFormat::wr_init(const QString& fname) exif_apps = new QList; - fin_ = gbfopen_be(fname, "rb", MYNAME); + fin_ = gbfopen_be(fname, "rb"); if (fin_->is_pipe) { - fatal(MYNAME ": Sorry, this format cannot be used with pipes!"); + gbFatal("Sorry, this format cannot be used with pipes!\n"); } uint16_t soi = gbfgetuint16(fin_); if (soi != 0xFFD8) { - fatal(MYNAME ": Unknown image file."); + gbFatal("Unknown image file.\n"); } exif_app_ = exif_load_apps(); if (exif_app_ == nullptr) { - fatal(MYNAME ": No EXIF header found in source file \"%s\".", qPrintable(fin_->name)); + gbFatal("No EXIF header found in source file \"%s\".\n", gbLogCStr(fin_->name)); } exif_examine_app(exif_app_); gbfclose(fin_); exif_time_ref = exif_get_exif_time(exif_app_); if (!exif_time_ref.isValid()) { - fatal(MYNAME ": No valid timestamp found in picture!\n"); + gbFatal("No valid timestamp found in picture!\n"); } QString filename(fname); filename += ".jpg"; - fout_ = gbfopen_be(filename, "wb", MYNAME); + fout_ = gbfopen_be(filename, "wb"); } void @@ -1530,7 +1528,7 @@ ExifFormat::write() track_disp_all(nullptr, nullptr, exif_find_wpt_by_name_lambda); } if (exif_wpt_ref == nullptr) { - warning(MYNAME ": No matching point with name \"%s\" found.\n", qPrintable(opt_name)); + gbWarning("No matching point with name \"%s\" found.\n", gbLogCStr(opt_name)); } } else { auto exif_find_wpt_by_time_lambda = [this](const Waypoint* waypointp)->void { @@ -1543,14 +1541,14 @@ ExifFormat::write() qint64 frame = opt_frame.get_result(); if (exif_wpt_ref == nullptr) { - warning(MYNAME ": No point with a valid timestamp found.\n"); + gbWarning("No point with a valid timestamp found.\n"); } else if (std::abs(exif_time_ref.secsTo(exif_wpt_ref->creation_time)) > frame) { QString time_str = exif_time_str(exif_time_ref); - warning(MYNAME ": No matching point found for image date %s!\n", qPrintable(time_str)); + gbWarning("No matching point found for image date %s!\n", gbLogCStr(time_str)); if (exif_wpt_ref != nullptr) { QString str = exif_time_str(exif_wpt_ref->creation_time); - warning(MYNAME ": Best is from %s, %lld second(s) away.\n", - qPrintable(str), std::abs(exif_time_ref.secsTo(exif_wpt_ref->creation_time))); + gbWarning("Best is from %s, %lld second(s) away.\n", + gbLogCStr(str), std::abs(exif_time_ref.secsTo(exif_wpt_ref->creation_time))); } exif_wpt_ref = nullptr; } diff --git a/exif.h b/exif.h index 050acfb4c..fc572aa55 100644 --- a/exif.h +++ b/exif.h @@ -174,23 +174,23 @@ class ExifFormat : public Format static void exif_examine_app(ExifApp* app); static ExifIfd* exif_find_ifd(ExifApp* app, uint16_t ifd_nr); static ExifTag* exif_find_tag(ExifApp* app, uint16_t ifd_nr, uint16_t tag_id); - QDateTime exif_get_exif_time(ExifApp* app) const; - Waypoint* exif_waypt_from_exif_app(ExifApp* app) const; + QDateTime exif_get_exif_time(ExifApp* app); + Waypoint* exif_waypt_from_exif_app(ExifApp* app); static Rational exif_dec2frac(double val, double tolerance); - ExifTag* exif_put_value(int ifd_nr, uint16_t tag_id, uint16_t type, int count, int index, const void* data) const; - void exif_put_double(int ifd_nr, int tag_id, int index, double val) const; - void exif_put_str(int ifd_nr, int tag_id, const char* val) const; - void exif_put_coord(int ifd_nr, int tag_id, double val) const; - void exif_put_long(int ifd_nr, int tag_id, int index, int32_t val) const; - void exif_put_short(int ifd_nr, int tag_id, int index, int16_t val) const; - void exif_remove_tag(int ifd_nr, int tag_id) const; + ExifTag* exif_put_value(int ifd_nr, uint16_t tag_id, uint16_t type, int count, int index, const void* data); + void exif_put_double(int ifd_nr, int tag_id, int index, double val); + void exif_put_str(int ifd_nr, int tag_id, const char* val); + void exif_put_coord(int ifd_nr, int tag_id, double val); + void exif_put_long(int ifd_nr, int tag_id, int index, int32_t val); + void exif_put_short(int ifd_nr, int tag_id, int index, int16_t val); + void exif_remove_tag(int ifd_nr, int tag_id); void exif_find_wpt_by_time(const Waypoint* wpt); void exif_find_wpt_by_name(const Waypoint* wpt); static bool exif_sort_tags_cb(const ExifTag& A, const ExifTag& B); static bool exif_sort_ifds_cb(const ExifIfd& A, const ExifIfd& B); static void exif_write_value(ExifTag* tag, gbfile* fout); static void exif_write_ifd(ExifIfd* ifd, char next, gbfile* fout); - void exif_write_apps() const; + void exif_write_apps(); /* Data Members */ diff --git a/fatal.cc b/fatal.cc index 7ddff28a0..e7a1deda0 100644 --- a/fatal.cc +++ b/fatal.cc @@ -1,7 +1,7 @@ /* Functions to indicate inconsistent or fatal conditions. - Copyright (C) 2002-2014 Robert Lipe, robertlipe+source@gpsbabel.org + Copyright (C) 2002-2014,2024 Robert Lipe, robertlipe+source@gpsbabel.org 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 @@ -20,14 +20,33 @@ */ #include // for va_end, va_list, va_start -#include // for vfprintf, stderr, fflush, fprintf, stdout +#include // for fprintf, stderr, fflush #include // for exit -#include "defs.h" // for Fatal, debug_print, fatal, warning +#include // for QDebug +#include // for QtMsgType, QMessageLogContext, qFormatLogMessage +#include // for QString +#include // for qPrintable + +#include "defs.h" // for gbFatal, gbDebug, gbInfo, gbVLegacyLog, gbWarning #include "src/core/logging.h" // for FatalMsg +#ifdef PIGS_FLY +static QByteArray xvasprintf(const char* fmt, va_list args) +{ + va_list args2; + va_copy(args2, args); + auto cbufsz = 1 + vsnprintf(nullptr, 0, fmt, args); + char* cbuf = new char[cbufsz]; + vsnprintf(cbuf, cbufsz, fmt, args2); + va_end(args2); + QByteArray rval(cbuf); + delete[] cbuf; + return rval; +} +#endif -[[noreturn]] void fatal(QDebug& msginstance) +[[noreturn]] void gbFatal(QDebug& msginstance) { auto* myinstance = new FatalMsg; myinstance->swap(msginstance); @@ -36,23 +55,67 @@ } [[noreturn]] void -fatal(const char* fmt, ...) +gbFatal(const char* fmt, ...) { - /* flush any buffered standard output */ - fflush(stdout); - - va_list ap; - va_start(ap, fmt); - vfprintf(stderr, fmt, ap); - va_end(ap); + va_list args; + va_start(args, fmt); + gbVLegacyLog(QtCriticalMsg, fmt, args); + va_end(args); exit(1); } void -warning(const char* fmt, ...) +gbWarning(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + gbVLegacyLog(QtWarningMsg, fmt, args); + va_end(args); +} + +void +gbInfo(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + gbVLegacyLog(QtInfoMsg, fmt, args); + va_end(args); +} + +void +gbDebug(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + gbVLegacyLog(QtDebugMsg, fmt, args); + va_end(args); +} + +static void LegacyLogMessageHandler(QtMsgType type, const QString& msg) { - va_list ap; - va_start(ap, fmt); - vfprintf(stderr, fmt, ap); - va_end(ap); + static bool lineInProgress = false; + + if (lineInProgress) { + fprintf(stderr, "%s", qPrintable(msg)); + } else { + QString message = qFormatLogMessage(type, QMessageLogContext(), msg); + fprintf(stderr, "%s", qPrintable(message)); + } + fflush(stderr); + + lineInProgress = !msg.endsWith('\n'); +} + +void gbVLegacyLog(QtMsgType type, const char* fmt, va_list args) +{ + QString logString(QString::vasprintf(fmt, args)); + + for (auto idx = logString.indexOf('\n'); idx >= 0; idx = logString.indexOf('\n')) { + QString msg = logString.sliced(0, idx + 1); + LegacyLogMessageHandler(type, msg); + logString.remove(0, idx + 1); + } + if (!logString.isEmpty()) { + LegacyLogMessageHandler(type, logString); + } } diff --git a/filter_vecs.cc b/filter_vecs.cc index 0741a84b2..f8f180fd9 100644 --- a/filter_vecs.cc +++ b/filter_vecs.cc @@ -35,7 +35,7 @@ #include "arcdist.h" // for ArcDistanceFilter #include "bend.h" // for BendFilter -#include "defs.h" // for arglist_t, CSTR, xfree, ARGTYPE_HIDDEN, fatal, global_options, global_opts, ARGTYPE_REQUIRED +#include "defs.h" // for arglist_t, CSTR, xfree, ARGTYPE_HIDDEN, gbFatal, global_options, global_opts, ARGTYPE_REQUIRED #include "discard.h" // for DiscardFilter #include "duplicate.h" // for DuplicateFilter #include "filter.h" // for Filter @@ -247,7 +247,7 @@ FilterVecs::fltinfo_t FilterVecs::find_filter_vec(const QString& fltargstring) { QStringList options = fltargstring.split(','); if (options.isEmpty()) { - fatal("A filter name is required.\n"); + gbFatal("A filter name is required.\n"); } const QString fltname = options.takeFirst(); diff --git a/format.h b/format.h index 01e887b82..f08c5e2db 100644 --- a/format.h +++ b/format.h @@ -65,8 +65,8 @@ class Format virtual void rd_init(const QString& /* fname */) { - fatal("Format does not support reading.\n"); -// fin = gbfopen(fname, "r", MYNAME); + gbFatal("Format does not support reading.\n"); +// fin = gbfopen(fname, "r"); } virtual void rd_deinit() @@ -110,8 +110,8 @@ class Format virtual void wr_init(const QString& /* fname */) { - fatal("Format does not support writing.\n"); -// fout = gbfopen(fname, "w", MYNAME); + gbFatal("Format does not support writing.\n"); +// fout = gbfopen(fname, "w"); } virtual void wr_deinit() @@ -133,7 +133,7 @@ class Format virtual void rd_position_init(const QString& /* fname */) { - fatal("Realtime tracking (-T) is not supported by this input type.\n"); + gbFatal("Realtime tracking (-T) is not supported by this input type.\n"); } virtual Waypoint* rd_position(posn_status* /* status */) @@ -151,7 +151,7 @@ class Format virtual void wr_position(Waypoint* /* wpt */) { - fatal("This output format does not support output of realtime positioning.\n"); + gbFatal("This output format does not support output of realtime positioning.\n"); } virtual void wr_position_deinit() diff --git a/format_skeleton.cc b/format_skeleton.cc index 07e33f9d6..493d31138 100644 --- a/format_skeleton.cc +++ b/format_skeleton.cc @@ -38,8 +38,6 @@ #include "defs.h" -#define MYNAME "format_skeleton" - // Any arg in this list will appear in command line help and will be // populated for you. @@ -58,7 +56,7 @@ QVector format_skeleton_args = { static void format_skeleton_rd_init(const char* fname) { -// fin = gbfopen(fname, "r", MYNAME); +// fin = gbfopen(fname, "r"); } static void @@ -105,7 +103,7 @@ format_skeleton_read() static void format_skeleton_wr_init(const char* fname) { -// fout = gbfopen(fname, "w", MYNAME); +// fout = gbfopen(fname, "w"); } static void diff --git a/garmin.cc b/garmin.cc index 1f686f67a..50e7f10b5 100644 --- a/garmin.cc +++ b/garmin.cc @@ -23,7 +23,7 @@ #include // for INT_MAX #include // for atan2, modf, sqrt -#include // for fprintf, fflush, snprintf, snprintf +#include // for snprintf, size_t #include // for int32_t #include // for memcpy, strlen, strncpy, strchr #include // for time_t @@ -52,8 +52,6 @@ #include "mkshort.h" // for MakeShort -#define MYNAME "GARMIN" - #define MILITANT_VALID_WAYPT_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" @@ -113,12 +111,12 @@ GarminFormat::rw_init(const QString& fname) case 115200: break; default: - fatal("Baud rate %d is not supported\n", baud); + gbFatal("Baud rate %d is not supported\n", baud); } } if (GPS_Init(qPrintable(fname)) < 0) { - fatal(MYNAME ":Can't init %s\n", qPrintable(fname)); + gbFatal("Can't init %s\n", gbLogCStr(fname)); } /* @@ -152,7 +150,7 @@ GarminFormat::rw_init(const QString& fname) switch (gps_waypt_type) { /* waypoint type as defined by jeeps */ case 0: - fatal("Garmin unit %d does not support waypoint xfer.", + gbFatal("Garmin unit %d does not support waypoint xfer.\n", gps_save_id); break; @@ -242,12 +240,10 @@ GarminFormat::rw_init(const QString& fname) } if (global_opts.debug_level > 0) { - fprintf(stderr, "Waypoint type: %d\n" - "Chosen waypoint length %d\n", - gps_waypt_type, receiver_short_length); + gbDebug("Waypoint type: %d\n", gps_waypt_type); + gbDebug("Chosen waypoint length %d\n", receiver_short_length); if (gps_category_type) { - fprintf(stderr, "Waypoint category type: %d\n", - gps_category_type); + gbDebug("Waypoint category type: %d\n", gps_category_type); } } @@ -290,7 +286,7 @@ GarminFormat::rw_init(const QString& fname) } codec = get_codec(receiver_charset); if (global_opts.verbose_status) { - fprintf(stdout, "receiver charset detected as %s.\r\n", receiver_charset.constData()); + gbInfo("receiver charset detected as %s.\n", receiver_charset.constData()); } valid_chars = valid_waypt_chars; @@ -350,7 +346,7 @@ GarminFormat::waypt_read() } if ((n = GPS_Command_Get_Waypoint(portname, &way, waypt_read_cb)) < 0) { - fatal(MYNAME ":Can't get waypoint from %s\n", portname); + gbFatal("Can't get waypoint from %s\n", portname); } for (int i = 0; i < n; i++) { @@ -671,7 +667,7 @@ GarminFormat::rd_position(posn_status* posn_status) * error, do it now. */ if (gps_errno) { - fatal(MYNAME ": Fatal error reading position.\n"); + gbFatal("Fatal error reading position.\n"); } delete wpt; @@ -698,7 +694,7 @@ GarminFormat::read() } if (!(global_opts.masked_objective & (WPTDATAMASK | TRKDATAMASK | RTEDATAMASK | POSNDATAMASK))) { - fatal(MYNAME ": Nothing to do.\n"); + gbFatal("Nothing to do.\n"); } } @@ -707,7 +703,7 @@ GarminFormat::sane_GPS_Way_New() { GPS_PWay way = GPS_Way_New(); if (!way) { - fatal(MYNAME ":not enough memory\n"); + gbFatal("not enough memory\n"); } /* @@ -892,15 +888,14 @@ GarminFormat::waypoint_write() int n = waypoint_prepare(); if (int32_t ret = GPS_Command_Send_Waypoint(portname, tx_waylist, n, waypt_write_cb); ret < 0) { - fatal(MYNAME ":communication error sending waypoints..\n"); + gbFatal("communication error sending waypoints..\n"); } for (int i = 0; i < n; ++i) { GPS_Way_Del(&tx_waylist[i]); } if (global_opts.verbose_status) { - fprintf(stdout, "\r\n"); - fflush(stdout); + gbInfo("\n"); } xfree(tx_waylist); } diff --git a/garmin_fit.cc b/garmin_fit.cc index a2061d95a..0824c93af 100644 --- a/garmin_fit.cc +++ b/garmin_fit.cc @@ -44,8 +44,6 @@ #include "src/core/logging.h" // for Warning, Fatal -#define MYNAME "fit" - /******************************************************************************* * %%% global callbacks called by gpsbabel main process %%% * *******************************************************************************/ @@ -53,7 +51,7 @@ void GarminFitFormat::rd_init(const QString& fname) { - fin = gbfopen_le(fname, "rb", MYNAME); + fin = gbfopen_le(fname, "rb"); } void @@ -67,7 +65,7 @@ GarminFitFormat::rd_deinit() void GarminFitFormat::wr_init(const QString& fname) { - fout = gbfopen_le(fname, "w+b", MYNAME); + fout = gbfopen_le(fname, "w+b"); } void @@ -86,18 +84,18 @@ GarminFitFormat::fit_parse_header() int len = gbfgetc(fin); if (len == EOF || len < 12) { - fatal(MYNAME ": Bad header\n"); + gbFatal("Bad header\n"); } if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME ": header len=" << len; + Debug(1) << "header len=" << len; } int ver = gbfgetc(fin); if (ver == EOF || (ver >> 4) > 2) - fatal(MYNAME ": Unsupported protocol version %d.%d\n", + gbFatal("Unsupported protocol version %d.%d\n", ver >> 4, ver & 0xf); if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME ": protocol version=" << ver; + Debug(1) << "protocol version=" << ver; } // profile version @@ -106,15 +104,15 @@ GarminFitFormat::fit_parse_header() fit_data.len = gbfgetuint32(fin); // File signature if (gbfread(sig, 4, 1, fin) != 1) { - fatal(MYNAME ": Unexpected end of file\n"); + gbFatal("Unexpected end of file\n"); } if (sig[0] != '.' || sig[1] != 'F' || sig[2] != 'I' || sig[3] != 'T') { - fatal(MYNAME ": .FIT signature missing\n"); + gbFatal(".FIT signature missing\n"); } if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME ": profile version=" << ver; - Debug(1) << MYNAME ": fit_data.len=" << fit_data.len; + Debug(1) << "profile version=" << ver; + Debug(1) << "fit_data.len=" << fit_data.len; } // Header CRC may be omitted entirely @@ -128,17 +126,17 @@ GarminFitFormat::fit_parse_header() for (unsigned int i = 0; i < kReadHeaderCrcLen; ++i) { int data = gbfgetc(fin); if (data == EOF) { - fatal(MYNAME ": File %s truncated\n", qPrintable(fin->name)); + gbFatal("File %s truncated\n", gbLogCStr(fin->name)); } crc = fit_crc16(data, crc); } if (crc != 0) { - Warning().nospace() << MYNAME ": Header CRC mismatch in file " << fin->name << "."; + Warning().nospace() << "Header CRC mismatch in file " << fin->name << "."; if (!opt_recoverymode) { - fatal(FatalMsg().nospace() << MYNAME ": File " << fin->name << " is corrupt. Use recoverymode option at your risk."); + gbFatal(FatalMsg().nospace() << "File " << fin->name << " is corrupt. Use recoverymode option at your risk."); } } else if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME ": Header CRC verified."; + Debug(1) << "Header CRC verified."; } } } @@ -146,9 +144,9 @@ GarminFitFormat::fit_parse_header() QFileInfo fi(fin->name); qint64 size = fi.size(); if ((len + fit_data.len + 2) != size) { - Warning().nospace() << MYNAME ": File size " << size << " is not expected given header len " << len << ", data length " << fit_data.len << " and a 2 byte file CRC."; + Warning().nospace() << "File size " << size << " is not expected given header len " << len << ", data length " << fit_data.len << " and a 2 byte file CRC."; } else if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME ": File size matches expectations from information in the header."; + Debug(1) << "File size matches expectations from information in the header."; } gbfseek(fin, len, SEEK_SET); @@ -248,7 +246,7 @@ GarminFitFormat::fit_parse_definition_message(uint8_t header) // byte 5 has the number of records in the remainder of the definition message int num_fields = fit_getuint8(); if (global_opts.debug_level >= 8) { - Debug(8) << MYNAME ": definition message contains " << num_fields << " records"; + Debug(8) << "definition message contains " << num_fields << " records"; } // remainder of the definition message is data at one byte per field * 3 fields @@ -258,7 +256,7 @@ GarminFitFormat::fit_parse_definition_message(uint8_t header) int type = fit_getuint8(); fit_field_t field = {id, size, type}; if (global_opts.debug_level >= 8) { - Debug(8) << MYNAME ": record " << i << " ID: " << field.id << " SIZE: " + Debug(8) << "record " << i << " ID: " << field.id << " SIZE: " << field.size << " TYPE: " << field.type << " fit_data.len=" << fit_data.len; } @@ -290,7 +288,7 @@ GarminFitFormat::fit_parse_definition_message(uint8_t header) if (hasDevFields) { int numOfDevFields = fit_getuint8(); if (global_opts.debug_level >= 8) { - Debug(8) << MYNAME ": definition message contains " << numOfDevFields << " developer records"; + Debug(8) << "definition message contains " << numOfDevFields << " developer records"; } if (numOfDevFields > 0) { int numOfFields = num_fields + numOfDevFields; @@ -300,7 +298,7 @@ GarminFitFormat::fit_parse_definition_message(uint8_t header) int type = fit_getuint8(); fit_field_t field = {id, size, type}; if (global_opts.debug_level >= 8) { - Debug(8) << MYNAME ": developer record " << i - num_fields << + Debug(8) << "developer record " << i - num_fields << " ID: " << field.id << " SIZE: " << field.size << " TYPE: " << field.type << " fit_data.len=" << fit_data.len; } @@ -329,7 +327,7 @@ GarminFitFormat::fit_read_field(const fit_field_t& f) // otherwise we just skip over the data. if (global_opts.debug_level >= 8) { - Debug(8) << MYNAME ": fit_read_field: read data field with f.type=0x" << + Debug(8) << "fit_read_field: read data field with f.type=0x" << Qt::hex << f.type << " and f.size=" << Qt::dec << f.size << " fit_data.len=" << fit_data.len; } @@ -344,7 +342,7 @@ GarminFitFormat::fit_read_field(const fit_field_t& f) fit_getuint8(); } if (global_opts.debug_level >= 8) { - Debug(8) << MYNAME ": fit_read_field: skipping 1-byte array data"; + Debug(8) << "fit_read_field: skipping 1-byte array data"; } return -1; } @@ -360,7 +358,7 @@ GarminFitFormat::fit_read_field(const fit_field_t& f) fit_getuint8(); } if (global_opts.debug_level >= 8) { - Debug(8) << MYNAME ": fit_read_field: skipping 2-byte array data"; + Debug(8) << "fit_read_field: skipping 2-byte array data"; } return -1; } @@ -373,7 +371,7 @@ GarminFitFormat::fit_read_field(const fit_field_t& f) fit_getuint8(); } if (global_opts.debug_level >= 8) { - Debug(8) << MYNAME ": fit_read_field: skipping 4-byte array data"; + Debug(8) << "fit_read_field: skipping 4-byte array data"; } return -1; } @@ -382,7 +380,7 @@ GarminFitFormat::fit_read_field(const fit_field_t& f) fit_getuint8(); } if (global_opts.debug_level >= 8) { - Debug(8) << MYNAME ": fit_read_field: skipping unrecognized data type"; + Debug(8) << "fit_read_field: skipping unrecognized data type"; } return -1; } @@ -411,11 +409,11 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) QString description; if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data ID " << def.global_id << " with num_fields=" << def.fields.size(); + Debug(7) << "parsing fit data ID " << def.global_id << " with num_fields=" << def.fields.size(); } for (int i = 0; i < def.fields.size(); ++i) { if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing field " << i; + Debug(7) << "parsing field " << i; } const fit_field_t& f = def.fields.at(i); QVariant field = fit_read_field(f); @@ -425,7 +423,7 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) } if (f.id == kFieldTimestamp) { if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: timestamp=" << static_cast(val); + Debug(7) << "parsing fit data: timestamp=" << static_cast(val); } timestamp = val; // if the timestamp is < 0x10000000, this value represents @@ -440,13 +438,13 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) switch (f.id) { case kFieldGlobalUtcOffset: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: global utc_offset=" << static_cast(val); + Debug(7) << "parsing fit data: global utc_offset=" << static_cast(val); } fit_data.global_utc_offset = val; break; default: if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME ": unrecognized data type in GARMIN FIT device settings: f.id=" << f.id; + Debug(1) << "unrecognized data type in GARMIN FIT device settings: f.id=" << f.id; } break; } // switch (f.id) @@ -457,19 +455,19 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) switch (f.id) { case kFieldLatitude: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: lat=" << static_cast(val); + Debug(7) << "parsing fit data: lat=" << static_cast(val); } lat = val; break; case kFieldLongitude: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: lon=" << static_cast(val); + Debug(7) << "parsing fit data: lon=" << static_cast(val); } lon = val; break; case kFieldAltitude: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: alt=" << static_cast(val); + Debug(7) << "parsing fit data: alt=" << static_cast(val); } if (val != 0xffff) { alt = val; @@ -477,25 +475,25 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) break; case kFieldHeartRate: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: heartrate=" << static_cast(val); + Debug(7) << "parsing fit data: heartrate=" << static_cast(val); } heartrate = val; break; case kFieldCadence: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: cadence=" << static_cast(val); + Debug(7) << "parsing fit data: cadence=" << static_cast(val); } cadence = val; break; case kFieldDistance: // NOTE: 5 is DISTANCE in cm ... unused. if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": unrecognized data type in GARMIN FIT record: f.id=" << f.id; + Debug(7) << "unrecognized data type in GARMIN FIT record: f.id=" << f.id; } break; case kFieldSpeed: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: speed=" << static_cast(val); + Debug(7) << "parsing fit data: speed=" << static_cast(val); } if (val != 0xffff) { speed = val; @@ -503,19 +501,19 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) break; case kFieldPower: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: power=" << static_cast(val); + Debug(7) << "parsing fit data: power=" << static_cast(val); } power = val; break; case kFieldTemperature: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: temperature=" << static_cast(val); + Debug(7) << "parsing fit data: temperature=" << static_cast(val); } temperature = val; break; case kFieldEnhancedSpeed: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: enhanced_speed=" << static_cast(val); + Debug(7) << "parsing fit data: enhanced_speed=" << static_cast(val); } if (val != 0xffff) { speed = val; @@ -523,7 +521,7 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) break; case kFieldEnhancedAltitude: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: enhanced_altitude=" << static_cast(val); + Debug(7) << "parsing fit data: enhanced_altitude=" << static_cast(val); } if (val != 0xffff) { alt = val; @@ -531,7 +529,7 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) break; default: if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME ": unrecognized data type in GARMIN FIT record: f.id=" << f.id; + Debug(1) << "unrecognized data type in GARMIN FIT record: f.id=" << f.id; } break; } // switch (f.id) @@ -542,49 +540,49 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) switch (f.id) { case kFieldStartTime: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: starttime=" << static_cast(val); + Debug(7) << "parsing fit data: starttime=" << static_cast(val); } //starttime = val; break; case kFieldStartLatitude: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: startlat=" << static_cast(val); + Debug(7) << "parsing fit data: startlat=" << static_cast(val); } //startlat = val; break; case kFieldStartLongitude: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: startlon=" << static_cast(val); + Debug(7) << "parsing fit data: startlon=" << static_cast(val); } //startlon = val; break; case kFieldEndLatitude: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: endlat=" << static_cast(val); + Debug(7) << "parsing fit data: endlat=" << static_cast(val); } endlat = val; break; case kFieldEndLongitude: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: endlon=" << static_cast(val); + Debug(7) << "parsing fit data: endlon=" << static_cast(val); } endlon = val; break; case kFieldElapsedTime: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: elapsedtime=" << static_cast(val); + Debug(7) << "parsing fit data: elapsedtime=" << static_cast(val); } //elapsedtime = val; break; case kFieldTotalDistance: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: totaldistance=" << static_cast(val); + Debug(7) << "parsing fit data: totaldistance=" << static_cast(val); } //totaldistance = val; break; default: if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME ": unrecognized data type in GARMIN FIT lap: f.id=" << f.id; + Debug(1) << "unrecognized data type in GARMIN FIT lap: f.id=" << f.id; } break; } // switch (f.id) @@ -595,13 +593,13 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) switch (f.id) { case kFieldEvent: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: event=" << static_cast(val); + Debug(7) << "parsing fit data: event=" << static_cast(val); } event = val; break; case kFieldEventType: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: eventtype=" << static_cast(val); + Debug(7) << "parsing fit data: eventtype=" << static_cast(val); } eventtype = val; break; @@ -613,19 +611,19 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) switch (f.id) { case kFieldLocLatitude: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: lat=" << static_cast(val); + Debug(7) << "parsing fit data: lat=" << static_cast(val); } lat = val; break; case kFieldLocLongitude: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: lon=" << static_cast(val); + Debug(7) << "parsing fit data: lon=" << static_cast(val); } lon = val; break; case kFieldLocAltitude: if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: alt=" << static_cast(val); + Debug(7) << "parsing fit data: alt=" << static_cast(val); } if (val != 0xffff) { alt = val; @@ -634,18 +632,18 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) case kFieldLocationName: name = field.toString(); if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: location name=" << name; + Debug(7) << "parsing fit data: location name=" << name; } break; case kFieldLocationDescription: description = field.toString(); if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": parsing fit data: location description=" << description; + Debug(7) << "parsing fit data: location description=" << description; } break; default: if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME ": unrecognized data type in GARMIN FIT locations: f.id=" << f.id; + Debug(1) << "unrecognized data type in GARMIN FIT locations: f.id=" << f.id; } break; } // switch (f.id) @@ -653,7 +651,7 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) break; default: if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME ": unrecognized/unhandled global ID for GARMIN FIT: " << def.global_id; + Debug(1) << "unrecognized/unhandled global ID for GARMIN FIT: " << def.global_id; } break; } // switch (def.global_id) @@ -661,7 +659,7 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) } if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": storing fit data with num_fields=" << def.fields.size(); + Debug(7) << "storing fit data with num_fields=" << def.fields.size(); } switch (def.global_id) { case kIdLap: { // lap message @@ -669,7 +667,7 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) break; } if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": storing fit data LAP " << def.global_id; + Debug(7) << "storing fit data LAP " << def.global_id; } auto* lappt = new Waypoint; lappt->latitude = GPS_Math_Semi_To_Deg(endlat); @@ -730,7 +728,7 @@ GarminFitFormat::fit_parse_data(const fit_message_def& def, int time_offset) break; } if (global_opts.debug_level >= 7) { - Debug(7) << MYNAME ": storing fit data location " << def.global_id; + Debug(7) << "storing fit data location " << def.global_id; } auto* locpt = new Waypoint; locpt->latitude = GPS_Math_Semi_To_Deg(lat); @@ -790,21 +788,21 @@ GarminFitFormat::fit_parse_record() // bits 3..0 -> local message type if (header & 0x80) { if (global_opts.debug_level >= 6) { - Debug(6) << MYNAME ": got compressed message at file position 0x" << + Debug(6) << "got compressed message at file position 0x" << Qt::hex << position << ", fit_data.len=" << Qt::dec << fit_data.len << " ...local message type 0x" << Qt::hex << (header & 0x0f); } fit_parse_compressed_message(header); } else if (header & 0x40) { if (global_opts.debug_level >= 6) { - Debug(6) << MYNAME ": got definition message at file position 0x" << + Debug(6) << "got definition message at file position 0x" << Qt::hex << position << ", fit_data.len=" << Qt::dec << fit_data.len << " ...local message type 0x" << Qt::hex << (header & 0x0f); } fit_parse_definition_message(header); } else { if (global_opts.debug_level >= 6) { - Debug(6) << MYNAME ": got data message at file position 0x" << + Debug(6) << "got data message at file position 0x" << Qt::hex << position << ", fit_data.len=" << Qt::dec << fit_data.len << " ...local message type 0x" << Qt::hex << (header & 0x0f); } @@ -829,12 +827,12 @@ GarminFitFormat::fit_check_file_crc() const crc = fit_crc16(data, crc); } if (crc != 0) { - Warning().nospace() << MYNAME ": File CRC mismatch in file " << fin->name << "."; + Warning().nospace() << "File CRC mismatch in file " << fin->name << "."; if (!opt_recoverymode) { - fatal(FatalMsg().nospace() << MYNAME ": File " << fin->name << " is corrupt. Use recoverymode option at your risk."); + gbFatal(FatalMsg().nospace() << "File " << fin->name << " is corrupt. Use recoverymode option at your risk."); } } else if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME ": File CRC verified."; + Debug(1) << "File CRC verified."; } gbfseek(fin, position, SEEK_SET); @@ -855,7 +853,7 @@ GarminFitFormat::read() fit_data.track = new route_head; track_add_head(fit_data.track); if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME ": starting to read data with fit_data.len=" << fit_data.len; + Debug(1) << "starting to read data with fit_data.len=" << fit_data.len; } try { while (fit_data.len) { @@ -863,10 +861,10 @@ GarminFitFormat::read() } } catch (ReaderException& e) { if (opt_recoverymode) { - warning(MYNAME ": %s\n",e.what()); - warning(MYNAME ": Aborting read and continuing processing.\n"); + gbWarning("%s\n",e.what()); + gbWarning("Aborting read and continuing processing.\n"); } else { - fatal(MYNAME ": %s Use recoverymode option at your risk.\n",e.what()); + gbFatal("%s Use recoverymode option at your risk.\n",e.what()); } } } @@ -1095,7 +1093,7 @@ GarminFitFormat::fit_write_file_finish() const // Update data records size in file header gbsize_t file_size = gbftell(fout); if (file_size < kWriteHeaderCrcLen) { - fatal(MYNAME ": File %s truncated\n", qPrintable(fout->name)); + gbFatal("File %s truncated\n", gbLogCStr(fout->name)); } gbfseek(fout, 0, SEEK_SET); fit_write_file_header(file_size - kWriteHeaderCrcLen, 0); @@ -1106,7 +1104,7 @@ GarminFitFormat::fit_write_file_finish() const for (unsigned int i = 0; i < kWriteHeaderLen; ++i) { int data = gbfgetc(fout); if (data == EOF) { - fatal(MYNAME ": File %s truncated\n", qPrintable(fout->name)); + gbFatal("File %s truncated\n", gbLogCStr(fout->name)); } crc = fit_crc16(data, crc); } diff --git a/garmin_gpi.cc b/garmin_gpi.cc index 00b79e304..0717a1060 100644 --- a/garmin_gpi.cc +++ b/garmin_gpi.cc @@ -46,8 +46,6 @@ #include "jeeps/gpsmath.h" // for GPS_Math_Deg_To_Semi, GPS_Math_Semi_To_Deg -#define MYNAME "garmin_gpi" - #define DEFAULT_ICON "Waypoint" #define WAYPOINTS_PER_BLOCK 128 @@ -61,7 +59,7 @@ #define GPI_BITMAP_SIZE sizeof(gpi_bitmap) #define GPI_DBG global_opts.debug_level >= 3 -#define PP if (GPI_DBG) warning("@%1$6x (%1$8d): ", gbftell(fin)) +#define PP if (GPI_DBG) gbDebug("@%6x (%8d): ", gbftell(fin), gbftell(fin)) /******************************************************************************* * %%% gpi reader %%% * @@ -72,7 +70,7 @@ garmin_fs_t* GarminGPIFormat::gpi_gmsd_init(Waypoint* wpt) { if (wpt == nullptr) { - fatal(MYNAME ": Error in file structure.\n"); + gbFatal("Error in file structure.\n"); } garmin_fs_t* gmsd = garmin_fs_t::find(wpt); if (gmsd == nullptr) { @@ -83,7 +81,7 @@ GarminGPIFormat::gpi_gmsd_init(Waypoint* wpt) } GarminGPIFormat::lc_string -GarminGPIFormat::gpi_read_lc_string() const +GarminGPIFormat::gpi_read_lc_string() { lc_string result; @@ -91,7 +89,7 @@ GarminGPIFormat::gpi_read_lc_string() const gbfread(result.lc.data(), 1, 2, fin); if ((result.lc.at(0) < 'A') || (result.lc.at(0) > 'Z') || (result.lc.at(1) < 'A') || (result.lc.at(1) > 'Z')) { - fatal(MYNAME ": Invalid language code %s!\n", result.lc.constData()); + gbFatal("Invalid language code %s!\n", result.lc.constData()); } result.strlen = gbfgetint16(fin); @@ -107,7 +105,7 @@ GarminGPIFormat::gpi_read_lc_string() const /* read a standard string with or without 'EN' (or whatever) header */ QString -GarminGPIFormat::gpi_read_string(const char* field) const +GarminGPIFormat::gpi_read_string(const char* field) { QByteArray string; @@ -117,25 +115,25 @@ GarminGPIFormat::gpi_read_string(const char* field) const if (first == 0) { if (gbfgetc(fin) != 0) { - fatal(MYNAME ": Error reading field '%s'!", field); + gbFatal("Error reading field '%s'!\n", field); } lc_string res1 = gpi_read_lc_string(); if ((res1.strlen + 4) < l0) { // dual language? lc_string res2 = gpi_read_lc_string(); if (res1.strlen + 4 + res2.strlen + 4 != l0) { - fatal(MYNAME ": Error out of sync (wrong size %d/%d/%d) on field '%s'!", l0, res1.strlen, res2.strlen, field); + gbFatal("Error out of sync (wrong size %d/%d/%d) on field '%s'!\n", l0, res1.strlen, res2.strlen, field); } if (opt_lang && (opt_lang.get().toUtf8() == res1.lc)) { string = res1.str; } else if (opt_lang && (opt_lang.get().toUtf8() == res2.lc)) { string = res2.str; } else { - fatal(MYNAME ": Must select language code, %s and %s found.\n", res1.lc.constData(), res2.lc.constData()); + gbFatal("Must select language code, %s and %s found.\n", res1.lc.constData(), res2.lc.constData()); } } else { // normal case, single language if (res1.strlen + 4 != l0) { - fatal(MYNAME ": Error out of sync (wrong size %d/%d) on field '%s'!", l0, res1.strlen, field); + gbFatal("Error out of sync (wrong size %d/%d) on field '%s'!\n", l0, res1.strlen, field); } string = res1.str; } @@ -151,7 +149,7 @@ GarminGPIFormat::gpi_read_string(const char* field) const QString result = str_to_unicode(string).trimmed(); if (GPI_DBG) { - warning("%s: \"%s\"\n", field, result.isNull() ? "" : qPrintable(result)); + gbDebug("%s: \"%s\"\n", field, result.isNull() ? "" : gbLogCStr(result)); } return result; } @@ -170,14 +168,14 @@ GarminGPIFormat::read_header() gbfread(&rdata->S3, 1, sizeof(rdata->S3) - 1, fin); /* GRMRECnn */ if (strncmp(rdata->S3, "GRMREC", 6) != 0) { - fatal(MYNAME ": No GPI file!\n"); + gbFatal("No GPI file!\n"); } PP; rdata->crdate = gbfgetint32(fin); if (GPI_DBG) { time_t crdate = GPS_Math_Gtime_To_Utime(rdata->crdate); - warning("crdate = %lld (%s)\n", (long long) rdata->crdate, + gbDebug("crdate = %lld (%s)\n", (long long) rdata->crdate, CSTR(QDateTime::fromSecsSinceEpoch(crdate, QtUTC).toString(Qt::ISODate))); } @@ -200,7 +198,7 @@ GarminGPIFormat::read_header() gbfread(&rdata->POI, 1, sizeof(rdata->POI) - 1, fin); if (strncmp(rdata->POI, "POI", 3) != 0) { - fatal(MYNAME ": Wrong or unsupported GPI file!\n"); + gbFatal("Wrong or unsupported GPI file!\n"); } for (i = 0; i < 3; i++) { @@ -211,14 +209,14 @@ GarminGPIFormat::read_header() codepage = gbfgetuint16(fin); if (GPI_DBG) { PP; - warning("Code Page: %d\n",codepage); + gbDebug("Code Page: %d\n",codepage); } (void) gbfgetint16(fin); /* typically 0, but 0x11 in Garminonline.de files. */ if (GPI_DBG) { PP; - warning("< leaving header\n"); + gbDebug("< leaving header\n"); } } @@ -228,7 +226,7 @@ GarminGPIFormat::read_poi(const int sz, const int tag) { if (GPI_DBG) { PP; - warning("> reading poi (size %d)\n", sz); + gbDebug("> reading poi (size %d)\n", sz); } PP; int len = 0; @@ -236,7 +234,7 @@ GarminGPIFormat::read_poi(const int sz, const int tag) len = gbfgetint32(fin); /* sub-header size */ } if (GPI_DBG) { - warning("poi sublen = %d (0x%x)\n", len, len); + gbDebug("poi sublen = %d (0x%x)\n", len, len); } (void) len; int pos = gbftell(fin); @@ -269,7 +267,7 @@ GarminGPIFormat::read_poi(const int sz, const int tag) if (GPI_DBG) { PP; - warning("< leaving poi\n"); + gbDebug("< leaving poi\n"); } } @@ -280,12 +278,12 @@ GarminGPIFormat::read_poi_list(const int sz) int pos = gbftell(fin); if (GPI_DBG) { PP; - warning("> reading poi list (-> %x / %d )\n", pos + sz, pos + sz); + gbDebug("> reading poi list (-> %x / %d )\n", pos + sz, pos + sz); } PP; int i = gbfgetint32(fin); /* mostly 23 (0x17) */ if (GPI_DBG) { - warning("list sublen = %d (0x%x)\n", i, i); + gbDebug("list sublen = %d (0x%x)\n", i, i); } (void) i; @@ -308,7 +306,7 @@ GarminGPIFormat::read_poi_list(const int sz) } if (GPI_DBG) { PP; - warning("< leaving poi list\n"); + gbDebug("< leaving poi list\n"); } } @@ -318,13 +316,13 @@ GarminGPIFormat::read_poi_group(const int sz, const int tag) int pos = gbftell(fin); if (GPI_DBG) { PP; - warning("> reading poi group (-> %x / %d)\n", pos + sz, pos + sz); + gbDebug("> reading poi group (-> %x / %d)\n", pos + sz, pos + sz); } if (tag == 0x80009) { PP; int subsz = gbfgetint32(fin); /* ? offset to category data ? */ if (GPI_DBG) { - warning("group sublen = %d (-> %x / %d)\n", subsz, pos + subsz + 4, pos + subsz + 4); + gbDebug("group sublen = %d (-> %x / %d)\n", subsz, pos + subsz + 4, pos + subsz + 4); } (void)subsz; } @@ -339,7 +337,7 @@ GarminGPIFormat::read_poi_group(const int sz, const int tag) if (GPI_DBG) { PP; - warning("< leaving poi group\n"); + gbDebug("< leaving poi group\n"); } } @@ -365,7 +363,7 @@ GarminGPIFormat::read_tag(const char* caller, const int tag, Waypoint* wpt) if (GPI_DBG) { PP; - warning("%s: tag = 0x%x (size %d)\n", caller, tag, sz); + gbDebug("%s: tag = 0x%x (size %d)\n", caller, tag, sz); } if ((tag >= 0x80000) && (tag <= 0x800ff)) { sz += 4; @@ -458,7 +456,7 @@ GarminGPIFormat::read_tag(const char* caller, const int tag, Waypoint* wpt) PP; mask = gbfgetint16(fin); /* address fields mask */ if (GPI_DBG) { - warning("GPI Address field mask: %d (0x%02x)\n", mask, mask); + gbDebug("GPI Address field mask: %d (0x%02x)\n", mask, mask); } if ((mask & GPI_ADDR_CITY) && !(str = gpi_read_string("City")).isEmpty()) { gmsd = gpi_gmsd_init(wpt); @@ -511,7 +509,7 @@ GarminGPIFormat::read_tag(const char* caller, const int tag, Waypoint* wpt) mask = gbfgetint16(fin); /* phone fields mask */ if (GPI_DBG) { - warning("GPI Phone field mask: %d (0x%02x)\n", mask, mask); + gbDebug("GPI Phone field mask: %d (0x%02x)\n", mask, mask); } if ((mask & 1) && !(str = gpi_read_string("Phone")).isEmpty()) { gmsd = gpi_gmsd_init(wpt); @@ -532,21 +530,21 @@ GarminGPIFormat::read_tag(const char* caller, const int tag, Waypoint* wpt) if (GPI_DBG) { int x; std::unique_ptr b(new unsigned char[sz]); - fprintf(stderr, "Tag: %x\n", tag); + gbDebug("Tag: %x\n", tag); gbfread(b.get(), 1, sz, fin); - fprintf(stderr, "\n"); + gbDebug("\n"); for (x = 0; x < sz; x++) { - fprintf(stderr, "%02x ", b[x]); + gbDebug("%02x ", b[x]); } - fprintf(stderr, "\n"); + gbDebug("\n"); for (x = 0; x < sz; x++) { - fprintf(stderr, "%c", isalnum(b[x]) ? b[x] : '.'); + gbDebug("%c", isalnum(b[x]) ? b[x] : '.'); } - fprintf(stderr, "\n"); + gbDebug("\n"); } break; default: - warning(MYNAME ": Unknown tag (0x%x). Please report!\n", tag); + gbWarning("Unknown tag (0x%x). Please report!\n", tag); return 0; } gbfseek(fin, pos + sz, SEEK_SET); @@ -722,7 +720,7 @@ GarminGPIFormat::wdata_compute_size(writer_data_t* data) const scale = KPH_TO_MPS(1); } double speed = 0; - parse_speed(wpt->shortname.mid(pidx + 1), &speed, scale, MYNAME); + parse_speed(wpt->shortname.mid(pidx + 1), &speed, scale); if (speed > 0) { wpt->set_speed(speed); } @@ -1063,9 +1061,9 @@ GarminGPIFormat::load_bitmap_from_file(const QString& fname, const unsigned char gpi_bitmap_header_t* dest_h; unsigned char* ptr; - gbfile* f = gbfopen_le(fname, "rb", MYNAME); + gbfile* f = gbfopen_le(fname, "rb"); if (gbfgetint16(f) != 0x4d42) { - fatal(MYNAME ": No BMP image."); + gbFatal("No BMP image.\n"); } /* read a standard bmp file header */ @@ -1091,31 +1089,31 @@ GarminGPIFormat::load_bitmap_from_file(const QString& fname, const unsigned char } if (GPI_DBG) { - printf("data size: 0x%x (%d)\n", src_h.size, src_h.size); - printf("image data offset: 0x%x (%d)\n", src_h.image_offset, src_h.image_offset); - printf("header size: 0x%x (%d)\n", src_h.header_size, src_h.header_size); - printf("image width: 0x%x (%d)\n", src_h.width, src_h.width); - printf("image height: 0x%x (%d)\n", src_h.height, src_h.height); - printf("number of planes: 0x%x (%d)\n", src_h.planes, src_h.planes); - printf("bits per pixel: 0x%x (%d)\n", src_h.bpp, src_h.bpp); - printf("compression type: 0x%x (%d)\n", src_h.compression_type, src_h.compression_type); - printf("image size: 0x%x (%d)\n", src_h.image_data_size, src_h.image_data_size); - printf("horizontal resolution: 0x%x (%d)\n", src_h.resolution_h, src_h.resolution_h); - printf("vertical resolution: 0x%x (%d)\n", src_h.resolution_v, src_h.resolution_v); - printf("number of colors: 0x%x (%d)\n", src_h.used_colors, src_h.used_colors); - printf("important colors: 0x%x (%d)\n", src_h.important_colors, src_h.important_colors); + gbDebug("data size: 0x%x (%d)\n", src_h.size, src_h.size); + gbDebug("image data offset: 0x%x (%d)\n", src_h.image_offset, src_h.image_offset); + gbDebug("header size: 0x%x (%d)\n", src_h.header_size, src_h.header_size); + gbDebug("image width: 0x%x (%d)\n", src_h.width, src_h.width); + gbDebug("image height: 0x%x (%d)\n", src_h.height, src_h.height); + gbDebug("number of planes: 0x%x (%d)\n", src_h.planes, src_h.planes); + gbDebug("bits per pixel: 0x%x (%d)\n", src_h.bpp, src_h.bpp); + gbDebug("compression type: 0x%x (%d)\n", src_h.compression_type, src_h.compression_type); + gbDebug("image size: 0x%x (%d)\n", src_h.image_data_size, src_h.image_data_size); + gbDebug("horizontal resolution: 0x%x (%d)\n", src_h.resolution_h, src_h.resolution_h); + gbDebug("vertical resolution: 0x%x (%d)\n", src_h.resolution_v, src_h.resolution_v); + gbDebug("number of colors: 0x%x (%d)\n", src_h.used_colors, src_h.used_colors); + gbDebug("important colors: 0x%x (%d)\n", src_h.important_colors, src_h.important_colors); } /* sort out unsupported files */ if (!((src_h.width <= 24) && (src_h.height <= 24) && (src_h.width > 0) && (src_h.height > 0))) { - fatal(MYNAME ": Unsupported format (%dx%d)!\n", src_h.width, src_h.height); + gbFatal("Unsupported format (%dx%d)!\n", src_h.width, src_h.height); } if (!((src_h.bpp == 8) || (src_h.bpp == 24) || (src_h.bpp == 32))) { - fatal(MYNAME ": Unsupported color depth (%d)!\n", src_h.bpp); + gbFatal("Unsupported color depth (%d)!\n", src_h.bpp); } if (!(src_h.compression_type == 0)) { - fatal(MYNAME ": Sorry, we don't support compressed bitmaps.\n"); + gbFatal("Sorry, we don't support compressed bitmaps.\n"); } std::unique_ptr color_table; @@ -1215,7 +1213,7 @@ char GarminGPIFormat::parse_units(const QString& str) } else if (str.startsWith('s', Qt::CaseInsensitive)) { result = 's'; } else { - fatal(MYNAME ": Unknown units parameter (%s).\n", qPrintable(str)); + gbFatal("Unknown units parameter (%s).\n", gbLogCStr(str)); } return result; } @@ -1227,7 +1225,7 @@ char GarminGPIFormat::parse_units(const QString& str) void GarminGPIFormat::rd_init(const QString& fname) { - fin = gbfopen_le(fname, "rb", MYNAME); + fin = gbfopen_le(fname, "rb"); rdata = new reader_data_t; read_header(); @@ -1238,7 +1236,7 @@ GarminGPIFormat::rd_init(const QString& fname) } else if (codepage == 65001) { codec = get_codec("utf8"); } else { - fatal(MYNAME ": Unsupported code page (%d). File is likely encrypted.\n", codepage); + gbFatal("Unsupported code page (%d). File is likely encrypted.\n", codepage); } units = parse_units(opt_units); @@ -1258,7 +1256,7 @@ GarminGPIFormat::wr_init(const QString& fname) gpi_timestamp = gpsbabel_time; } - fout = gbfopen_le(fname, "wb", MYNAME); + fout = gbfopen_le(fname, "wb"); short_h = new MakeShort; @@ -1285,8 +1283,8 @@ GarminGPIFormat::wr_init(const QString& fname) } if (! codepage) { - warning(MYNAME ": Unsupported character set (%s)!\n", qPrintable(opt_writecodec)); - fatal(MYNAME ": Valid values are windows-1250 to windows-1257 and utf8.\n"); + gbWarning("Unsupported character set (%s)!\n", gbLogCStr(opt_writecodec)); + gbFatal("Valid values are windows-1250 to windows-1257 and utf8.\n"); } codec = get_codec(opt_writecodec.get().toUtf8()); @@ -1303,7 +1301,7 @@ GarminGPIFormat::wr_init(const QString& fname) } else { scale = KPH_TO_MPS(1); } - parse_speed(opt_speed, &defspeed, scale, MYNAME); + parse_speed(opt_speed, &defspeed, scale); } if (opt_proximity) { @@ -1314,7 +1312,7 @@ GarminGPIFormat::wr_init(const QString& fname) } else { scale = 1000.0; /* one kilometer in meters */ } - parse_distance(opt_proximity, &defproximity, scale, MYNAME); + parse_distance(opt_proximity, &defproximity, scale); } wdata = wdata_alloc(); } @@ -1367,7 +1365,7 @@ GarminGPIFormat::write() int image_sz; if (opt_cat.isEmpty()) { - fatal(MYNAME ": Can't write empty category!\n"); + gbFatal("Can't write empty category!\n"); } if (opt_hide_bitmap) { diff --git a/garmin_gpi.h b/garmin_gpi.h index b8ddd9587..6ed5d3e78 100644 --- a/garmin_gpi.h +++ b/garmin_gpi.h @@ -283,8 +283,8 @@ class GarminGPIFormat : public Format /* Member Functions */ static garmin_fs_t* gpi_gmsd_init(Waypoint* wpt); - lc_string gpi_read_lc_string() const; - QString gpi_read_string(const char* field) const; + lc_string gpi_read_lc_string(); + QString gpi_read_string(const char* field); void read_header(); void read_poi(int sz, int tag); void read_poi_list(int sz); diff --git a/garmin_tables.cc b/garmin_tables.cc index 0560b96c3..241ae8356 100644 --- a/garmin_tables.cc +++ b/garmin_tables.cc @@ -33,8 +33,6 @@ #include "jeeps/gpsmath.h" // for GPS_Lookup_Datum_Index, GPS_Math_Get_Datum_Name #include "src/core/logging.h" // for Fatal -#define MYNAME "garmin_tables" - // these tables are in an include file so they can be shared with mkicondoc. #include "garmin_icon_tables.h" // for garmin_icon_table, garmin_smart_icon_table @@ -452,7 +450,7 @@ gt_find_desc_from_icon_number(const int icon, garmin_formats_e garmin_format) } break; default: - fatal(MYNAME ": unknown garmin format.\n"); + gbFatal("unknown garmin format.\n"); } } return DEFAULT_ICON_DESCR; @@ -501,7 +499,7 @@ int gt_find_icon_number_from_desc(const QString& desc, garmin_formats_e garmin_f case GARMIN_SERIAL: return icon_mapping.pcxsymnum; default: - fatal(MYNAME ": unknown garmin format.\n"); + gbFatal("unknown garmin format.\n"); } } } @@ -516,7 +514,7 @@ int gt_find_icon_number_from_desc(const QString& desc, garmin_formats_e garmin_f case GARMIN_SERIAL: return icon_mapping.pcxsymnum; default: - fatal(MYNAME ": unknown garmin format.\n"); + gbFatal("unknown garmin format.\n"); } } } @@ -648,7 +646,7 @@ gt_get_icao_cc(const QString& country, const QString& shortname) } grid_type -gt_lookup_grid_type(const QString& grid_name, const QString& module) +gt_lookup_grid_type(const QString& grid_name) { for (const auto& grid_mapping : gt_mps_grid_names) { if (QString::compare(grid_name, grid_mapping.shortname, Qt::CaseInsensitive) == 0 || @@ -657,19 +655,19 @@ gt_lookup_grid_type(const QString& grid_name, const QString& module) } } - fatal(FatalMsg().nospace().noquote() << module << - ": Unsupported grid (" << grid_name << + gbFatal(FatalMsg().nospace().noquote() << + "Unsupported grid (" << grid_name << "). See GPSBabel help for supported grids."); return grid_unknown; /* (warnings) */ } QString -gt_get_mps_grid_longname(const grid_type grid, const QString& module) +gt_get_mps_grid_longname(const grid_type grid) { if ((grid < GRID_INDEX_MIN) || (grid > GRID_INDEX_MAX)) { - fatal(FatalMsg().nospace().noquote() << module << - ": Grid index out of range " << grid << + gbFatal(FatalMsg().nospace().noquote() << + "Grid index out of range " << grid << " (" << GRID_INDEX_MIN << ".." << GRID_INDEX_MAX << ")!"); } return gt_mps_grid_names[grid].longname; @@ -690,7 +688,7 @@ gt_get_mps_datum_name(const int datum_index) } int -gt_lookup_datum_index(const QString& datum_str, const QString& module) +gt_lookup_datum_index(const QString& datum_str) { QString name = datum_str; @@ -710,8 +708,8 @@ gt_lookup_datum_index(const QString& datum_str, const QString& module) } if (result < 0) { - fatal(FatalMsg().nospace().noquote() << module << - ": Unsupported datum (" << datum_str << + gbFatal(FatalMsg().nospace().noquote() << + "Unsupported datum (" << datum_str << "). See GPSBabel help for supported datums."); } return result; diff --git a/garmin_tables.h b/garmin_tables.h index 303fa1287..b46cef330 100644 --- a/garmin_tables.h +++ b/garmin_tables.h @@ -71,9 +71,9 @@ enum gt_gdb_display_modes_e { unsigned char gt_switch_display_mode_value(unsigned char display_mode, int protoid, char device); -grid_type gt_lookup_grid_type(const QString& grid_name, const QString& module); -QString gt_get_mps_grid_longname(grid_type grid, const QString& module); -int gt_lookup_datum_index(const QString& datum_str, const QString& module); +grid_type gt_lookup_grid_type(const QString& grid_name); +QString gt_get_mps_grid_longname(grid_type grid); +int gt_lookup_datum_index(const QString& datum_str); QString gt_get_mps_datum_name(int datum_index); uint32_t gt_color_value(unsigned int garmin_index); uint32_t gt_color_value_by_name(const QString& name); diff --git a/garmin_txt.cc b/garmin_txt.cc index e9a7bfdc9..1671a16e8 100644 --- a/garmin_txt.cc +++ b/garmin_txt.cc @@ -27,7 +27,7 @@ #include // for toupper #include // for fabs, floor #include // for uint16_t -#include // for sscanf, fprintf, snprintf, stderr +#include // for snprintf, sscanf #include // for abs #include // for strstr, strlen #include // for gmtime, time_t, localtime, strftime, tm @@ -59,8 +59,6 @@ #include "src/core/textstream.h" // for TextStream -#define MYNAME "garmin_txt" - const QVector GarminTxtFormat::headers = { "Name\tDescription\tType\tPosition\tAltitude\tDepth\tProximity\tTemperature\t" "Display Mode\tColor\tSymbol\tFacility\tCity\tState\tCountry\t" @@ -245,15 +243,15 @@ GarminTxtFormat::print_position(const Waypoint* wpt) break; default: - fatal("ToDo\n"); + gbFatal("ToDo\n"); } if (! valid) { *fout << "#####\n"; - fatal(MYNAME ": %s (%s) is outside of convertible area \"%s\"!\n", - wpt->shortname.isEmpty() ? "Waypoint" : qPrintable(wpt->shortname), - qPrintable(pretty_deg_format(wpt->latitude, wpt->longitude, 'd', nullptr, false)), - qPrintable(gt_get_mps_grid_longname(grid_index, MYNAME))); + gbFatal("%s (%s) is outside of convertible area \"%s\"!\n", + wpt->shortname.isEmpty() ? "Waypoint" : gbLogCStr(wpt->shortname), + gbLogCStr(pretty_deg_format(wpt->latitude, wpt->longitude, 'd', nullptr, false)), + gbLogCStr(gt_get_mps_grid_longname(grid_index))); } } @@ -269,8 +267,7 @@ GarminTxtFormat::print_date_and_time(const time_t time, const bool time_only) } if (time_only) { tm = *gmtime(&time); - snprintf(tbuf, sizeof(tbuf), "%d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec); - *fout << QString::asprintf("%s", tbuf); + *fout << QString::asprintf("%d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec); } else if (time != 0) { if (gtxt_flags.utc) { time_t t = time + utc_offs; @@ -636,7 +633,7 @@ GarminTxtFormat::wr_init(const QString& fname) gtxt_flags = {}; fout = new gpsbabel::TextStream; - fout->open(fname, QIODevice::WriteOnly, MYNAME, "windows-1252"); + fout->open(fname, QIODevice::WriteOnly, "windows-1252"); gtxt_flags.metric = opt_dist.get().startsWith("m", Qt::CaseInsensitive); gtxt_flags.celsius = opt_temp.get().startsWith("c", Qt::CaseInsensitive); @@ -644,7 +641,7 @@ GarminTxtFormat::wr_init(const QString& fname) if (opt_precision) { precision = opt_precision.get_result(); if (precision < 0) { - fatal(MYNAME ": Invalid precision (%s)!", qPrintable(opt_precision)); + gbFatal("Invalid precision (%s)!\n", gbLogCStr(opt_precision)); } } @@ -655,10 +652,10 @@ GarminTxtFormat::wr_init(const QString& fname) if (int i = opt_grid.toInt(&ok); ok) { grid_index = (grid_type) i; if ((grid_index < GRID_INDEX_MIN) || (grid_index > GRID_INDEX_MAX)) - fatal(MYNAME ": Grid index out of range (%d..%d)!\n", + gbFatal("Grid index out of range (%d..%d)!\n", (int)GRID_INDEX_MIN, (int)GRID_INDEX_MAX); } else { - grid_index = gt_lookup_grid_type(opt_grid, MYNAME); + grid_index = gt_lookup_grid_type(opt_grid); } } @@ -670,7 +667,7 @@ GarminTxtFormat::wr_init(const QString& fname) datum_index = kDatumWGS84; break; default: - datum_index = gt_lookup_datum_index(opt_datum, MYNAME); + datum_index = gt_lookup_datum_index(opt_datum); } garmin_txt_utc_option(); @@ -720,7 +717,7 @@ GarminTxtFormat::write() track_disp_wpt_cb(waypointp); }; - QString grid_str = gt_get_mps_grid_longname(grid_index, MYNAME); + QString grid_str = gt_get_mps_grid_longname(grid_index); grid_str = grid_str.replace('*', u'°'); *fout << "Grid\t" << grid_str << "\r\n"; @@ -846,7 +843,7 @@ GarminTxtFormat::strftime_to_timespec(const char* s) q += "AP"; continue; default: - warning(MYNAME ": omitting unknown strptime conversion \"%%%c\" in \"%s\"\n", s[i], s); + gbWarning("omitting unknown strptime conversion \"%%%c\" in \"%s\"\n", s[i], s); break; } } @@ -879,7 +876,7 @@ GarminTxtFormat::parse_categories(const QString& str) const QString cin = catstring.trimmed(); if (!cin.isEmpty()) { if (std::optional cat = garmin_fs_t::convert_category(cin); !cat.has_value()) { - warning(MYNAME ": Unable to convert category \"%s\" at line %d!\n", qPrintable(cin), current_line); + gbWarning("Unable to convert category \"%s\" at line %d!\n", gbLogCStr(cin), current_line); } else { res = res | *cat; } @@ -908,11 +905,11 @@ GarminTxtFormat::parse_temperature(const QString& str, double* temperature) cons *temperature = FAHRENHEIT_TO_CELSIUS(value); break; default: - fatal(MYNAME ": Unknown temperature unit \"%c\" at line %d!\n", unit, current_line); + gbFatal("Unknown temperature unit \"%c\" at line %d!\n", unit, current_line); } return true; } else { - fatal(MYNAME ": Invalid temperature \"%s\" at line %d!\n", qPrintable(str), current_line); + gbFatal("Invalid temperature \"%s\" at line %d!\n", gbLogCStr(str), current_line); } return false; } @@ -939,7 +936,7 @@ GarminTxtFormat::parse_display(const QString& str, int* val) const return true; } } - warning(MYNAME ": Unknown display mode \"%s\" at line %d.\n", qPrintable(str), current_line); + gbWarning("Unknown display mode \"%s\" at line %d.\n", gbLogCStr(str), current_line); return false; } @@ -947,7 +944,7 @@ void GarminTxtFormat::bind_fields(const header_type ht) { if ((grid_index < 0) || (datum_index < 0)) { - fatal(MYNAME ": Incomplete or invalid file header!"); + gbFatal("Incomplete or invalid file header!\n"); } if (header_column_names.isEmpty()) { @@ -967,10 +964,10 @@ GarminTxtFormat::bind_fields(const header_type ht) int field_no = field_idx + 1; header_mapping_info[ht].append(std::make_pair(name, field_no)); if (global_opts.debug_level >= 2) { - fprintf(stderr, MYNAME ": Binding field \"%s\" to internal number %d (%d,%d)\n", qPrintable(name), field_no, ht, i); + gbDebug("Binding field \"%s\" to internal number %d (%d,%d)\n", gbLogCStr(name), field_no, ht, i); } } else { - warning(MYNAME ": Field %s not recognized!\n", qPrintable(name)); + gbWarning("Field %s not recognized!\n", gbLogCStr(name)); } } header_column_names.clear(); @@ -980,7 +977,7 @@ void GarminTxtFormat::parse_grid(const QStringList& lineparts) { if (lineparts.empty()) { - fatal(MYNAME ": Missing grid headline!\n"); + gbFatal("Missing grid headline!\n"); } const QString str = lineparts.at(0); @@ -991,7 +988,7 @@ GarminTxtFormat::parse_grid(const QStringList& lineparts) } else if (str.contains("mm'ss.s")) { grid_index = grid_lat_lon_dms; } else { - grid_index = gt_lookup_grid_type(str, MYNAME); + grid_index = gt_lookup_grid_type(str); } } @@ -999,11 +996,11 @@ void GarminTxtFormat::parse_datum(const QStringList& lineparts) { if (lineparts.empty()) { - fatal(MYNAME ": Missing GPS datum headline!\n"); + gbFatal("Missing GPS datum headline!\n"); } const auto& str = lineparts.at(0); - datum_index = gt_lookup_datum_index(str, MYNAME); + datum_index = gt_lookup_datum_index(str); } void @@ -1019,7 +1016,7 @@ GarminTxtFormat::parse_waypoint(const QStringList& lineparts) for (const auto& str : lineparts) { if (++column >= header_mapping_info[waypt_header].size()) { - warning(MYNAME ": too many fields in Waypoint record!\n"); + gbWarning("too many fields in Waypoint record!\n"); break; } int i; @@ -1047,20 +1044,20 @@ GarminTxtFormat::parse_waypoint(const QStringList& lineparts) break; case 4: parse_coordinates(str, datum_index, grid_index, - &wpt->latitude, &wpt->longitude, MYNAME); + &wpt->latitude, &wpt->longitude); break; case 5: - if (parse_distance(str, &d, 1, MYNAME)) { + if (parse_distance(str, &d, 1)) { wpt->altitude = d; } break; case 6: - if (parse_distance(str, &d, 1, MYNAME)) { + if (parse_distance(str, &d, 1)) { wpt->set_depth(d); } break; case 7: - if (parse_distance(str, &d, 1, MYNAME)) { + if (parse_distance(str, &d, 1)) { wpt->set_proximity(d); } break; @@ -1124,7 +1121,7 @@ GarminTxtFormat::parse_route_header(const QStringList& lineparts) bind_fields(route_header); for (const auto& str : lineparts) { if (++column >= header_mapping_info[route_header].size()) { - warning(MYNAME ": too many fields in Route record!\n"); + gbWarning("too many fields in Route record!\n"); break; } const auto& [name, field_no] = header_mapping_info[route_header].at(column); @@ -1152,7 +1149,7 @@ GarminTxtFormat::parse_track_header(const QStringList& lineparts) auto* trk = new route_head; for (const auto& str : lineparts) { if (++column >= header_mapping_info[track_header].size()) { - warning(MYNAME ": too many fields in Track record!\n"); + gbWarning("too many fields in Track record!\n"); break; } const auto& [name, field_no] = header_mapping_info[track_header].at(column); @@ -1182,18 +1179,18 @@ GarminTxtFormat::parse_route_waypoint(const QStringList& lineparts) for (const auto& str : lineparts) { if (++column >= header_mapping_info[rtept_header].size()) { - warning(MYNAME ": too many fields in Route Waypoint record!\n"); + gbWarning("too many fields in Route Waypoint record!\n"); break; } const auto& [name, field_no] = header_mapping_info[rtept_header].at(column); switch (field_no) { case 1: if (str.isEmpty()) { - fatal(MYNAME ": Route waypoint without name at line %d!\n", current_line); + gbFatal("Route waypoint without name at line %d!\n", current_line); } wpt = find_waypt_by_name(str); if (wpt == nullptr) { - fatal(FatalMsg() << MYNAME << ": Route waypoint " << str << " not in waypoint list (line " << current_line<< ")!\n"); + gbFatal(FatalMsg() << "Route waypoint " << str << " not in waypoint list (line " << current_line<< ")!\n"); } wpt = new Waypoint(*wpt); break; @@ -1214,7 +1211,7 @@ GarminTxtFormat::parse_track_waypoint(const QStringList& lineparts) for (const auto& str : lineparts) { if (++column >= header_mapping_info[trkpt_header].size()) { - warning(MYNAME ": too many fields in Trackpoint record!\n"); + gbWarning("too many fields in Trackpoint record!\n"); break; } double x; @@ -1228,7 +1225,7 @@ GarminTxtFormat::parse_track_waypoint(const QStringList& lineparts) switch (field_no) { case 1: parse_coordinates(str, datum_index, grid_index, - &wpt->latitude, &wpt->longitude, MYNAME); + &wpt->latitude, &wpt->longitude); break; case 2: if (QDateTime dt = parse_date_and_time(str); dt.isValid()) { @@ -1237,12 +1234,12 @@ GarminTxtFormat::parse_track_waypoint(const QStringList& lineparts) } break; case 3: - if (parse_distance(str, &x, 1, MYNAME)) { + if (parse_distance(str, &x, 1)) { wpt->altitude = x; } break; case 4: - if (parse_distance(str, &x, 1, MYNAME)) { + if (parse_distance(str, &x, 1)) { wpt->set_depth(x); } break; @@ -1252,7 +1249,7 @@ GarminTxtFormat::parse_track_waypoint(const QStringList& lineparts) } break; case 8: - if (parse_speed(str, &x, 1, MYNAME)) { + if (parse_speed(str, &x, 1)) { wpt->set_speed(x); } break; @@ -1272,7 +1269,7 @@ GarminTxtFormat::rd_init(const QString& fname) gtxt_flags = {}; fin = new gpsbabel::TextStream; - fin->open(fname, QIODevice::ReadOnly, MYNAME, "windows-1252"); + fin->open(fname, QIODevice::ReadOnly, "windows-1252"); free_headers(); header_column_names.clear(); @@ -1336,7 +1333,7 @@ GarminTxtFormat::read() parse_track_header(lineparts); } else if (linetype.compare(u"Map", Qt::CaseInsensitive) == 0) /* do nothing */ ; else { - fatal(MYNAME ": Unknown identifier (%s) at line %d!\n", qPrintable(linetype), current_line); + gbFatal("Unknown identifier (%s) at line %d!\n", gbLogCStr(linetype), current_line); } } diff --git a/garmin_xt.cc b/garmin_xt.cc index 8e221139e..344b93260 100644 --- a/garmin_xt.cc +++ b/garmin_xt.cc @@ -35,7 +35,6 @@ #include "gbfile.h" // for gbfread, gbfgetuint16, gbfseek, gbfgetc, gbfgetuint32, gbfclose, gbfeof, gbfopen -#define MYNAME "Garmin_XT" #define GARMIN_XT_ELE 31500/65536 #define DATABLOCKSIZE 1 #define STRK_BLOCK_SIZE 97 @@ -50,7 +49,7 @@ void GarminXTFormat::rd_init(const QString& fname) { - fin = gbfopen(fname, "rb", MYNAME); + fin = gbfopen(fname, "rb"); } void diff --git a/gbfile.cc b/gbfile.cc index 6b7039fd4..66c76a39f 100644 --- a/gbfile.cc +++ b/gbfile.cc @@ -46,8 +46,7 @@ # define SET_BINARY_MODE(file) #endif -#define MYNAME "gbfile" -#define NO_ZLIB MYNAME ": No zlib support.\n" +#define NO_ZLIB "No zlib support.\n" /* About the ZLIB_INHIBITED stuff: * @@ -103,10 +102,9 @@ gzapi_open(gbfile* self, const char* mode) } if (self->handle.gz == nullptr) { - fatal("%s: Cannot %s file '%s'!\n", - qPrintable(self->module), + gbFatal("Cannot %s file '%s'!\n", (self->mode == 'r') ? "open" : "create", - qPrintable(self->name)); + gbLogCStr(self->name)); } return self; @@ -131,9 +129,9 @@ gzapi_seek(gbfile* self, int32_t offset, int whence) if (result < 0) { if (self->is_pipe) { - fatal("%s: This format cannot be used in piped commands!\n", qPrintable(self->module)); + gbFatal("This format cannot be used in piped commands!\n"); } - fatal("%s: online compression not yet supported for this format!", qPrintable(self->module)); + gbFatal("online compression not yet supported for this format!\n"); } return 0; } @@ -155,7 +153,7 @@ gzapi_read(void* buf, const gbsize_t size, const gbsize_t members, gbfile* self) /* Check for an incomplete READ */ if ((members == 1) && (size > 1) && (result > 0) && (result < (int)size)) { - fatal("%s: Unexpected end of file (EOF)!\n", qPrintable(self->module)); + gbFatal("Unexpected end of file (EOF)!\n"); } result /= size; @@ -170,8 +168,8 @@ gzapi_read(void* buf, const gbsize_t size, const gbsize_t members, gbfile* self) return (gbsize_t) 0; } if ((errnum != Z_STREAM_END) && (errnum != 0)) - fatal("%s: zlib returned error %d ('%s')!\n", - qPrintable(self->module), errnum, errtxt); + gbFatal("zlib returned error %d ('%s')!\n", + errnum, errtxt); } return (gbsize_t) result; } @@ -220,7 +218,7 @@ gzapi_eof(gbfile* self) if (global_opts.debug_level > 0) { /* now gzeof() should return 1 */ if (!gzeof(self->handle.gz)) { - fatal("zlib gzeof error!\n"); + gbFatal("zlib gzeof error!\n"); } } res = 1; @@ -235,7 +233,7 @@ gzapi_ungetc(const int c, gbfile* self) if (self->back == -1) { self->back = c; } else { - fatal(MYNAME ": Cannot store more than one byte back!\n"); + gbFatal("Cannot store more than one byte back!\n"); } return c; } @@ -265,7 +263,7 @@ gzapi_error(gbfile* self) static gbfile* stdapi_open(gbfile* self, const char* mode) { - self->handle.std = xfopen(self->name, mode, self->module); + self->handle.std = xfopen(self->name, mode); return self; } @@ -295,11 +293,11 @@ stdapi_seek(gbfile* self, int32_t offset, int whence) pos = offset; break; default: - fatal("%s: Unknown seek operation (%d) for file %s!\n", - qPrintable(self->module), whence, qPrintable(self->name)); + gbFatal("Unknown seek operation (%d) for file %s!\n", + whence, gbLogCStr(self->name)); } - fatal("%s: Unable to set file (%s) to position (%llu)!\n", - qPrintable(self->module), qPrintable(self->name), (long long unsigned) pos); + gbFatal("Unable to set file (%s) to position (%llu)!\n", + gbLogCStr(self->name), (long long unsigned) pos); } return 0; } @@ -311,8 +309,8 @@ stdapi_read(void* buf, const gbsize_t size, const gbsize_t members, gbfile* self gbsize_t result = fread(buf, size, members, self->handle.std); if ((result < members) && (error_number = ferror(self->handle.std))) { - fatal("%s: Error %d occurred during read of file '%s'!\n", - qPrintable(self->module), error_number, qPrintable(self->name)); + gbFatal("Error %d occurred during read of file '%s'!\n", + error_number, gbLogCStr(self->name)); } return result; } @@ -497,15 +495,14 @@ memapi_error(gbfile* self) /* GPSBabel 'file' standard calls */ /* - * gbfopen: (as xfopen) plus the name of the calling GPSBabel module (MYNAME) + * gbfopen: (as xfopen) */ gbfile* -gbfopen(const QString& filename, const char* mode, const QString& module) +gbfopen(const QString& filename, const char* mode) { auto* file = new gbfile; - file->module = module; file->mode = 'r'; // default file->binary = (strchr(mode, 'b') != nullptr); file->back = -1; @@ -550,7 +547,7 @@ gbfopen(const QString& filename, const char* mode, const QString& module) /* force gzipped files on output */ file->gzapi = 1; #else - fatal(NO_ZLIB); + gbFatal(NO_ZLIB); #endif } @@ -570,7 +567,7 @@ gbfopen(const QString& filename, const char* mode, const QString& module) file->filewrite = gzapi_write; #else /* This is the only runtime test we make */ - fatal("%s: Zlib was not included in this build.\n", qPrintable(file->module)); + gbFatal("Zlib was not included in this build.\n"); #endif } else { file->fileclearerr = stdapi_clearerr; @@ -600,9 +597,9 @@ gbfopen(const QString& filename, const char* mode, const QString& module) */ gbfile* -gbfopen_be(const QString& filename, const char* mode, const QString& module) +gbfopen_be(const QString& filename, const char* mode) { - gbfile* result = gbfopen(filename, mode, module); + gbfile* result = gbfopen(filename, mode); result->big_endian = 1; return result; @@ -710,7 +707,7 @@ QByteArray gbfreadbuf(gbsize_t size, gbfile* file) { gbsize_t nbytes = gbfread(tmp.data(), 1, size, file); if (nbytes != size) { - fatal(FatalMsg() << file->module << "Attempted to read " << size << + gbFatal(FatalMsg() << "Attempted to read " << size << "bytes, but only " << nbytes << "were available."); } return tmp; @@ -811,10 +808,9 @@ gbfwrite(const void* buf, const gbsize_t size, const gbsize_t members, gbfile* f { unsigned int result = file->filewrite(buf, size, members, file); if (result != members) { - fatal("%s: Could not write %lld bytes to %s (result %d)!\n", - qPrintable(file->module), + gbFatal("Could not write %lld bytes to %s (result %d)!\n", (long long int)(members - result) * size, - qPrintable(file->name), + gbLogCStr(file->name), result); } @@ -881,8 +877,8 @@ gbftell(gbfile* file) { gbsize_t result = file->filetell(file); if ((signed) result == -1) - fatal("%s: Could not determine position of file '%s'!\n", - qPrintable(file->module), qPrintable(file->name)); + gbFatal("Could not determine position of file '%s'!\n", + gbLogCStr(file->name)); return result; } @@ -918,7 +914,7 @@ gbfgetint32(gbfile* file) char buf[4]; if (gbfread(&buf, 1, sizeof(buf), file) != sizeof(buf)) { - fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name)); + gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name)); } if (file->big_endian) { @@ -938,7 +934,7 @@ gbfgetint16(gbfile* file) char buf[2]; if (gbfread(&buf, 1, sizeof(buf), file) != sizeof(buf)) { - fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name)); + gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name)); } if (file->big_endian) { @@ -958,7 +954,7 @@ gbfgetdbl(gbfile* file) char buf[8]; if (gbfread(&buf, 1, sizeof(buf), file) != sizeof(buf)) { - fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name)); + gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name)); } return endian_read_double(buf, ! file->big_endian); @@ -974,7 +970,7 @@ gbfgetflt(gbfile* file) char buf[4]; if (gbfread(&buf, 1, sizeof(buf), file) != sizeof(buf)) { - fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name)); + gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name)); } return endian_read_float(buf, ! file->big_endian); @@ -999,7 +995,7 @@ gbfgetcstr_old(gbfile* file) } if (c == EOF) { - fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name)); + gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name)); } if (len == file->buffsz) { @@ -1046,12 +1042,12 @@ gbfgetpstr(gbfile* file) { int len = gbfgetc(file); if (len == EOF) { - fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name)); + gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name)); } QByteArray ba; ba.resize(len); if (gbfread(ba.data(), 1, len, file) != (gbsize_t) len) { - fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name)); + gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name)); } return QString(ba); @@ -1068,8 +1064,7 @@ gbfgetutf16char(gbfile* file) int c1 = gbfgetc(file); if (c1 == EOF) { - fatal("%s: Incomplete unicode (UTF-16%cE) character at EOF!\n", - qPrintable(file->module), + gbFatal("Incomplete unicode (UTF-16%cE) character at EOF!\n", file->big_endian ? 'B' : 'L'); } @@ -1117,8 +1112,7 @@ gbfgetutf16str(gbfile* file) QChar qch2 = gbfgetutf16char(file); if (qch2 != u'\n') { // including qch2.isNull() // Putting back two chars may not be supported, e.g. with gzapi_ungetc. - fatal("%s: Invalid unicode (UTF-16%cE) line break!\n", - qPrintable(file->module), + gbFatal("Invalid unicode (UTF-16%cE) line break!\n", file->big_endian ? 'B' : 'L'); } break; @@ -1127,8 +1121,7 @@ gbfgetutf16str(gbfile* file) } if (qch.isLowSurrogate()) { - fatal("%s: Leading unicode (UTF-16%cE) low surrogate!\n", - qPrintable(file->module), + gbFatal("Leading unicode (UTF-16%cE) low surrogate!\n", file->big_endian ? 'B' : 'L'); } @@ -1136,8 +1129,7 @@ gbfgetutf16str(gbfile* file) if (qch.isHighSurrogate()) { QChar qch2 = gbfgetutf16char(file); if (!qch2.isLowSurrogate()) { // including qch2.isNull() - fatal("%s: Missing unicode (UTF-16%cE) low surrogate!\n", - qPrintable(file->module), + gbFatal("Missing unicode (UTF-16%cE) low surrogate!\n", file->big_endian ? 'B' : 'L'); } str.append(qch2); diff --git a/gbfile.h b/gbfile.h index 5d24d5b29..c96ce8f1d 100644 --- a/gbfile.h +++ b/gbfile.h @@ -60,7 +60,6 @@ struct gbfile { #endif } handle{nullptr}; QString name; - QString module; char* buff{nullptr}; /* static growing buffer, primary used by gbprintf */ int buffsz{0}; char mode{0}; @@ -89,11 +88,11 @@ struct gbfile { }; -gbfile* gbfopen(const QString& filename, const char* mode, const QString& module); -gbfile* gbfopen_be(const QString& filename, const char* mode, const QString& module); -inline gbfile* gbfopen_le(const QString& filename, const char* mode, const QString& module) +gbfile* gbfopen(const QString& filename, const char* mode); +gbfile* gbfopen_be(const QString& filename, const char* mode); +inline gbfile* gbfopen_le(const QString& filename, const char* mode) { - return gbfopen(filename, mode, module); + return gbfopen(filename, mode); } void gbfclose(gbfile* file); diff --git a/gbser.cc b/gbser.cc index 0f9e98423..4cd512eaa 100644 --- a/gbser.cc +++ b/gbser.cc @@ -29,12 +29,12 @@ void gbser_db(int l, const char* msg, ...) { - va_list ap; - va_start(ap, msg); if (global_opts.debug_level >= l) { + va_list ap; + va_start(ap, msg); vprintf(msg, ap); + va_end(ap); } - va_end(ap); } /* Set the serial port speed. diff --git a/gbser_posix.cc b/gbser_posix.cc index 1ea54808e..7b3cc8f84 100644 --- a/gbser_posix.cc +++ b/gbser_posix.cc @@ -79,7 +79,7 @@ speed_t mkspeed(unsigned br) return B230400; #endif default: - fatal("Unsupported serial speed: %d\n", br); + gbFatal("Unsupported serial speed: %d\n", br); return 0; /* keep compiler happy */ } } @@ -143,17 +143,17 @@ void* gbser_init(const char* port_name) h->fd = 0; return h; } else if (h->fd = open(port_name, O_RDWR | O_NOCTTY), h->fd == -1) { - warning("Failed to open port (%s)\n", strerror(errno)); + gbWarning("Failed to open port (%s)\n", strerror(errno)); goto failed; } if (!isatty(h->fd)) { - warning("%s is not a TTY\n", port_name); + gbWarning("%s is not a TTY\n", port_name); goto failed; } if (gbser_set_port(h, 4800, 8, 0, 1)) { - warning("gbser_set_port() failed\n"); + gbWarning("gbser_set_port() failed\n"); goto failed; } @@ -191,15 +191,15 @@ int gbser_set_port(void* handle, unsigned speed, unsigned bits, unsigned parity, }; if (bits < 5 || bits > 8) { - fatal("Unsupported bits setting: %d\n", bits); + gbFatal("Unsupported bits setting: %d\n", bits); } if (parity > 2) { - fatal("Unsupported parity setting: %d\n", parity); + gbFatal("Unsupported parity setting: %d\n", parity); } if (stop < 1 || stop > 2) { - fatal("Unsupported stop setting: %d\n", stop); + gbFatal("Unsupported stop setting: %d\n", stop); } s = mkspeed(speed); diff --git a/gbser_win.cc b/gbser_win.cc index 0fd08e719..13ccb8979 100644 --- a/gbser_win.cc +++ b/gbser_win.cc @@ -81,7 +81,7 @@ DWORD mkspeed(unsigned br) return 230400; #endif default: - fatal("Unsupported serial speed: %d\n", br); + gbFatal("Unsupported serial speed: %d\n", br); return 0; /* keep compiler happy */ } } @@ -227,15 +227,15 @@ int gbser_set_port(void* handle, unsigned speed, unsigned bits, unsigned parity, DCB tio; if (bits < 5 || bits > 8) { - fatal("Unsupported bits setting: %d\n", bits); + gbFatal("Unsupported bits setting: %d\n", bits); } if (parity > 2) { - fatal("Unsupported parity setting: %d\n", parity); + gbFatal("Unsupported parity setting: %d\n", parity); } if (stop < 1 || stop > 2) { - fatal("Unsupported stop setting: %d\n", stop); + gbFatal("Unsupported stop setting: %d\n", stop); } tio.DCBlength = sizeof(DCB); diff --git a/gdb.cc b/gdb.cc index 95d4af222..1878c1f37 100644 --- a/gdb.cc +++ b/gdb.cc @@ -35,11 +35,11 @@ #include // for Q_UNUSED, qPrintable, foreach #include // for fabs -#include // for printf, SEEK_SET +#include // for SEEK_SET #include // for memset, strstr, strcmp #include // for next -#include "defs.h" // for Waypoint, warning, route_head, fatal, UrlLink, bounds, UrlList, unknown_alt, xfree, waypt_add_to_bounds, waypt_init_bounds, route_add_wpt, route_disp_all, waypt_bounds_valid, xmalloc, gb_color, WaypointList, find_wa... +#include "defs.h" // for Waypoint, gbWarning, route_head, gbFatal, UrlLink, bounds, UrlList, unknown_alt, xfree, waypt_add_to_bounds, waypt_init_bounds, route_add_wpt, route_disp_all, waypt_bounds_valid, xmalloc, gb_color, WaypointList, find_wa... #include "formspec.h" // for FormatSpecificDataList #include "garmin_fs.h" // for garmin_fs_t, garmin_ilink_t #include "garmin_tables.h" // for gt_waypt_class_map_point, gt_color_index_by_rgb, gt_color_value, gt_waypt_classes_e, gt_find_desc_from_icon_number, gt_find_icon_number_from_desc, gt_gdb_display_mode_symbol, gt_get_icao_country, gt_waypt_class_user_waypoint, GDB, gt_display_mode_symbol @@ -50,8 +50,6 @@ #include "src/core/datetime.h" // for DateTime -#define MYNAME "gdb" - #define GDB_DEF_CLASS gt_waypt_class_user_waypoint #define GDB_DEF_HIDDEN_CLASS gt_waypt_class_map_point @@ -103,30 +101,21 @@ void GdbFormat::disp_summary(const gbfile* f) const { if constexpr(GDB_DEBUG) { - int len = strlen(qPrintable(f->name)); + int len = strlen(gbLogCStr(f->name)); - warning(MYNAME ": ====================="); - for (int i = 0; i < len; i++) { - warning("="); - } - warning("\n" MYNAME ": %s summary for \"%s\"\n", - (f->mode == 'r') ? "Reader" : "Writer", qPrintable(f->name)); + gbWarning("%s\n", QByteArray(len + 21, '=').constData()); - warning(MYNAME ": ---------------------"); - for (int i = 0; i < len; i++) { - warning("-"); - } + gbWarning("%s summary for \"%s\"\n", + (f->mode == 'r') ? "Reader" : "Writer", gbLogCStr(f->name)); - warning("\n" MYNAME ": %d waypoint(s)\n", waypt_ct - waypth_ct); - warning(MYNAME ": %d hidden waypoint(s)\n", waypth_ct); - warning(MYNAME ": %d route(s) with total %d point(s)\n", rte_ct, rtept_ct); - warning(MYNAME ": %d track(s) with total %d point(s)\n", trk_ct, trkpt_ct); - warning(MYNAME ": ---------------------"); + gbWarning("%s\n", QByteArray(len + 21, '-').constData()); - for (int i = 0; i < len; i++) { - warning("-"); - } - warning("\n"); + gbWarning("%d waypoint(s)\n", waypt_ct - waypth_ct); + gbWarning("%d hidden waypoint(s)\n", waypth_ct); + gbWarning("%d route(s) with total %d point(s)\n", rte_ct, rtept_ct); + gbWarning("%d track(s) with total %d point(s)\n", trk_ct, trkpt_ct); + + gbWarning("%s\n", QByteArray(len + 21, '-').constData()); } else { Q_UNUSED(f); } @@ -255,10 +244,10 @@ GdbFormat::gdb_add_route_waypt(route_head* rte, Waypoint* ref, const int wpt_cla double dist = radtometers(gcdist(ref->position(), tmp->position())); if (fabs(dist) > 100) { - fatal(MYNAME ": Route point mismatch!\n" \ + gbFatal("Route point mismatch!\n" \ " \"%s\" from waypoints differs to \"%s\"\n" \ " from route table by more than %0.1f meters!\n", \ - qPrintable(tmp->shortname), qPrintable(ref->shortname), dist); + gbLogCStr(tmp->shortname), gbLogCStr(ref->shortname), dist); } } Waypoint* res = nullptr; @@ -377,28 +366,28 @@ GdbFormat::read_file_header() misinterpreted. */ if (strcmp(buf, "MsRcf") != 0) { - fatal(MYNAME ": Invalid file \"%s\"!", qPrintable(fin->name)); + gbFatal("Invalid file \"%s\"!\n", gbLogCStr(fin->name)); } int reclen = FREAD_i32; Q_UNUSED(reclen); QByteArray drec = FREAD_STR(); if (drec.at(0) != 'D') { - fatal(MYNAME ": Invalid file \"%s\"!", qPrintable(fin->name)); + gbFatal("Invalid file \"%s\"!\n", gbLogCStr(fin->name)); } gdb_ver = drec.at(1) - 'k' + 1; if ((gdb_ver < kGDBVerMin) || (gdb_ver > kGDBVerMax)) { - fatal(MYNAME ": Unknown or/and unsupported GDB version (%d.0)!", gdb_ver); + gbFatal("Unknown or/and unsupported GDB version (%d.0)!\n", gdb_ver); } if (global_opts.verbose_status > 0) { - printf(MYNAME ": Reading Garmin GPS Database version %d.0\n", gdb_ver); + gbInfo("Reading Garmin GPS Database version %d.0\n", gdb_ver); } reclen = FREAD_i32; if (reclen + 1 > int(sizeof(buf))) { - fatal(MYNAME ": Invalid record length\n"); + gbFatal("Invalid record length\n"); } (void) FREAD(buf, reclen + 1); if (global_opts.verbose_status > 0) { @@ -408,12 +397,12 @@ GdbFormat::read_file_header() } else if (strstr(name, "neaderhi") == nullptr) { name = "MapSource BETA"; } - warning(MYNAME ": File created with \"%s\"\n", name); + gbWarning("File created with \"%s\"\n", name); } QByteArray applicationField = FREAD_STR(); if (!((applicationField == "MapSource") || (applicationField == "BaseCamp"))) { - fatal(MYNAME ": Not a recognized signature in header"); + gbFatal("Not a recognized signature in header\n"); } } @@ -461,38 +450,38 @@ GdbFormat::read_waypoint(gt_waypt_classes_e* waypt_class_out) res->altitude = alt; if constexpr(GDB_DEBUG) { DBG(GDB_DBG_WPTe, true) - printf(MYNAME "-wpt \"%s\" (%d): Altitude = %.1f\n", - qPrintable(res->shortname), wpt_class, alt); + gbDebug("wpt \"%s\" (%d): Altitude = %.1f\n", + gbLogCStr(res->shortname), wpt_class, alt); } } } if constexpr(GDB_DEBUG) { DBG(GDB_DBG_WPT, true) - printf(MYNAME "-wpt \"%s\": coordinates = %c%0.6f %c%0.6f\n", - qPrintable(res->shortname), + gbDebug("wpt \"%s\": coordinates = %c%0.6f %c%0.6f\n", + gbLogCStr(res->shortname), res->latitude < 0 ? 'S' : 'N', res->latitude, res->longitude < 0 ? 'W' : 'E', res->longitude); } res->notes = fread_cstr(); if constexpr(GDB_DEBUG) { DBG(GDB_DBG_WPTe, !res->notes.isNull()) - printf(MYNAME "-wpt \"%s\" (%d): notes = %s\n", - qPrintable(res->shortname), wpt_class, - qPrintable(QString(res->notes).replace("\r\n", ", "))); + gbDebug("wpt \"%s\" (%d): notes = %s\n", + gbLogCStr(res->shortname), wpt_class, + gbLogCStr(QString(res->notes).replace("\r\n", ", "))); } if (FREAD_C == 1) { res->set_proximity(FREAD_DBL); if constexpr(GDB_DEBUG) { DBG(GDB_DBG_WPTe, res->proximity_has_value()) - printf(MYNAME "-wpt \"%s\" (%d): Proximity = %.1f\n", - qPrintable(res->shortname), wpt_class, res->proximity_value() / 1000); + gbDebug("wpt \"%s\" (%d): Proximity = %.1f\n", + gbLogCStr(res->shortname), wpt_class, res->proximity_value() / 1000); } } int display = FREAD_i32; if constexpr(GDB_DEBUG) { DBG(GDB_DBG_WPTe, true) - printf(MYNAME "-wpt \"%s\" (%d): display = %d\n", - qPrintable(res->shortname), wpt_class, display); + gbDebug("wpt \"%s\" (%d): display = %d\n", + gbLogCStr(res->shortname), wpt_class, display); } switch (display) { /* display value */ case gt_gdb_display_mode_symbol: @@ -520,8 +509,8 @@ GdbFormat::read_waypoint(gt_waypt_classes_e* waypt_class_out) res->set_depth(FREAD_DBL); if constexpr(GDB_DEBUG) { DBG(GDB_DBG_WPTe, res->depth_has_value()) - printf(MYNAME "-wpt \"%s\" (%d): Depth = %.1f\n", - qPrintable(res->shortname), wpt_class, res->depth_value()); + gbDebug("wpt \"%s\" (%d): Depth = %.1f\n", + gbLogCStr(res->shortname), wpt_class, res->depth_value()); } } @@ -540,8 +529,8 @@ GdbFormat::read_waypoint(gt_waypt_classes_e* waypt_class_out) if constexpr(GDB_DEBUG) { QString temp = FREAD_CSTR_AS_QSTR; /* undocumented & unused string */ DBG(GDB_DBG_WPTe, !temp.isEmpty()) - printf(MYNAME "-wpt \"%s\" (%d): Unknown string = %s\n", - qPrintable(res->shortname), wpt_class, qPrintable(temp)); + gbDebug("wpt \"%s\" (%d): Unknown string = %s\n", + gbLogCStr(res->shortname), wpt_class, gbLogCStr(temp)); } else { (void) FREAD_CSTR_AS_QSTR; /* undocumented & unused string */ } @@ -569,8 +558,8 @@ GdbFormat::read_waypoint(gt_waypt_classes_e* waypt_class_out) res->notes = QStringLiteral("[%1]").arg(gdb_to_ISO8601_duration(duration)); if constexpr(GDB_DEBUG) { DBG(GDB_DBG_WPTe, true) - printf(MYNAME "-wpt \"%s\" (%d): duration = %u\n", - qPrintable(res->shortname), wpt_class, duration); + gbDebug("wpt \"%s\" (%d): duration = %u\n", + gbLogCStr(res->shortname), wpt_class, duration); } } int url_ct = FREAD_i32; @@ -580,8 +569,8 @@ GdbFormat::read_waypoint(gt_waypt_classes_e* waypt_class_out) waypt_add_url(res, str, nullptr); if constexpr(GDB_DEBUG) { DBG(GDB_DBG_WPTe, true) - printf(MYNAME "-wpt \"%s\" (%d): url(%d) = %s\n", - qPrintable(res->shortname), wpt_class, url_ct - i, qPrintable(str)); + gbDebug("wpt \"%s\" (%d): url(%d) = %s\n", + gbLogCStr(res->shortname), wpt_class, url_ct - i, gbLogCStr(str)); } } } @@ -589,11 +578,11 @@ GdbFormat::read_waypoint(gt_waypt_classes_e* waypt_class_out) if constexpr(GDB_DEBUG) { DBG(GDB_DBG_WPTe, !res->description.isNull()) - printf(MYNAME "-wpt \"%s\" (%d): description = %s\n", - qPrintable(res->shortname), wpt_class, qPrintable(res->description)); + gbDebug("wpt \"%s\" (%d): description = %s\n", + gbLogCStr(res->shortname), wpt_class, gbLogCStr(res->description)); DBG(GDB_DBG_WPTe, res->urls.HasUrlLink()) - printf(MYNAME "-wpt \"%s\" (%d): url = %s\n", - qPrintable(res->shortname), wpt_class, qPrintable(res->urls.GetUrlLink().url_)); + gbDebug("wpt \"%s\" (%d): url = %s\n", + gbLogCStr(res->shortname), wpt_class, gbLogCStr(res->urls.GetUrlLink().url_)); } int category = FREAD_i16; if (category != 0) { @@ -601,16 +590,16 @@ GdbFormat::read_waypoint(gt_waypt_classes_e* waypt_class_out) } if constexpr(GDB_DEBUG) { DBG(GDB_DBG_WPTe, category) - printf(MYNAME "-wpt \"%s\" (%d): category = %d\n", - qPrintable(res->shortname), wpt_class, category); + gbDebug("wpt \"%s\" (%d): category = %d\n", + gbLogCStr(res->shortname), wpt_class, category); } if (FREAD_C == 1) { res->set_temperature(FREAD_DBL); if constexpr(GDB_DEBUG) { DBG(GDB_DBG_WPTe, res->temperature_has_value()) - printf(MYNAME "-wpt \"%s\" (%d): temperature = %.1f\n", - qPrintable(res->shortname), wpt_class, res->temperature_value()); + gbDebug("wpt \"%s\" (%d): temperature = %.1f\n", + gbLogCStr(res->shortname), wpt_class, res->temperature_value()); } } @@ -638,8 +627,8 @@ GdbFormat::read_waypoint(gt_waypt_classes_e* waypt_class_out) if constexpr(GDB_DEBUG) { DBG(GDB_DBG_WPTe, icon != kGDBDefIcon) - printf(MYNAME "-wpt \"%s\" (%d): icon = \"%s\" (MapSource symbol %d)\n", - qPrintable(res->shortname), wpt_class, qPrintable(res->icon_descr), icon); + gbDebug("wpt \"%s\" (%d): icon = \"%s\" (MapSource symbol %d)\n", + gbLogCStr(res->shortname), wpt_class, gbLogCStr(res->icon_descr), icon); } QString str; if (!(str = garmin_fs_t::get_cc(gmsd, nullptr)).isEmpty()) { @@ -691,8 +680,8 @@ GdbFormat::read_route() if constexpr(GDB_DEBUG) { DBG(GDB_DBG_RTE, true) - printf(MYNAME "-rte \"%s\": loading route with %d point(s)...\n", - qPrintable(rte->rte_name), points); + gbDebug("rte \"%s\": loading route with %d point(s)...\n", + gbLogCStr(rte->rte_name), points); } for (int i = 0; i < points; i++) { @@ -719,22 +708,22 @@ GdbFormat::read_route() if ((buf[0] != 0x00) && (buf[0] != 0x01) && (buf[0] != 0x03)) { warnings++; if (warnings > 3) { - fatal(MYNAME "-rte_pt \"%s\": too many warnings!\n", qPrintable(wpt->shortname)); + gbFatal("rte_pt \"%s\": too many warnings!\n", gbLogCStr(wpt->shortname)); } - warning(MYNAME "-rte_pt \"%s\" (class %d): possible error in route.\n", qPrintable(wpt->shortname), wpt_class); - warning(MYNAME "-rte_pt (dump):"); + gbWarning("rte_pt \"%s\" (class %d): possible error in route.\n", gbLogCStr(wpt->shortname), wpt_class); + gbWarning("rte_pt (dump):"); for (int idx = 0; idx < 18; idx++) { - warning(" %02x", (unsigned char)buf[idx]); + gbWarning(" %02x", (unsigned char)buf[idx]); } - warning("\n"); + gbWarning("\n"); } int links = FREAD_i32; QList il_list; if constexpr(GDB_DEBUG) { DBG(GDB_DBG_RTE, links) - printf(MYNAME "-rte_pt \"%s\" (%d): %d interlink step(s)\n", - qPrintable(wpt->shortname), wpt_class, links); + gbDebug("rte_pt \"%s\" (%d): %d interlink step(s)\n", + gbLogCStr(wpt->shortname), wpt_class, links); } for (int j = 0; j < links; j++) { garmin_ilink_t il_step; @@ -757,8 +746,8 @@ GdbFormat::read_route() if constexpr(GDB_DEBUG) { DBG(GDB_DBG_RTEe, true) { - printf(MYNAME "-rte_il \"%s\" (%d of %d): %c%0.6f %c%0.6f\n", - qPrintable(wpt->shortname), j + 1, links, + gbDebug("rte_il \"%s\" (%d of %d): %c%0.6f %c%0.6f\n", + gbLogCStr(wpt->shortname), j + 1, links, il_step.lat < 0 ? 'S' : 'N', il_step.lat, il_step.lon < 0 ? 'W' : 'E', il_step.lon); } @@ -789,11 +778,11 @@ GdbFormat::read_route() wpt = new Waypoint(*tmp); } else { if (waypt_bounds_valid(&bounds)) { - warning(MYNAME ": (has bounds)\n"); + gbWarning("(has bounds)\n"); } - warning(MYNAME ": Data corruption detected!\n"); - fatal(MYNAME ": Sleeping route point without coordinates!\n"); + gbWarning("Data corruption detected!\n"); + gbFatal("Sleeping route point without coordinates!\n"); } } @@ -806,8 +795,8 @@ GdbFormat::read_route() } if constexpr(GDB_DEBUG) { DBG(GDB_DBG_RTE, true) - printf(MYNAME "-rte_pt \"%s\": coordinates = %c%0.6f, %c%0.6f\n", - qPrintable(wpt->shortname), + gbDebug("rte_pt \"%s\": coordinates = %c%0.6f, %c%0.6f\n", + gbLogCStr(wpt->shortname), wpt->latitude < 0 ? 'S' : 'N', wpt->latitude, wpt->longitude < 0 ? 'W' : 'E', wpt->longitude); } @@ -848,7 +837,7 @@ GdbFormat::read_route() FREAD(tbuf, 8); /* unknown bytes */ if constexpr(GDB_DEBUG) { DBG(GDB_DBG_RTE, true) - printf(MYNAME "-rte_pt: autoroute info: route style %d, calculation type %d, vehicle type %d, road selection %d\n" + gbDebug("rte_pt: autoroute info: route style %d, calculation type %d, vehicle type %d, road selection %d\n" " driving speeds (kph) %.0f, %.0f, %.0f, %.0f, %.0f\n", route_style, calc_type, vehicle_type, road_selection, driving_speed[0], driving_speed[1], driving_speed[2], driving_speed[3], driving_speed[4]); @@ -929,8 +918,8 @@ GdbFormat::read_track() } if constexpr(GDB_DEBUG) { DBG(GDB_DBG_TRK, res->rte_urls.HasUrlLink()) - printf(MYNAME "-trk \"%s\": url = %s\n", - qPrintable(res->rte_name), qPrintable(res->rte_urls.GetUrlLink().url_)); + gbDebug("trk \"%s\": url = %s\n", + gbLogCStr(res->rte_name), gbLogCStr(res->rte_urls.GetUrlLink().url_)); } return res; } @@ -940,8 +929,8 @@ GdbFormat::read_track() void GdbFormat::rd_init(const QString& fname) { - fin = gbfopen_le(fname, "rb", MYNAME); - ftmp = gbfopen_le(nullptr, "wb", MYNAME); + fin = gbfopen_le(fname, "rb"); + ftmp = gbfopen_le(nullptr, "wb"); read_file_header(); waypt_nameposn_in_hash.clear(); @@ -989,7 +978,7 @@ GdbFormat::read() int len = FREAD_i32; if (FREAD(&typ, 1) < 1) { - fatal(MYNAME ": Attempt to read past EOF."); + gbFatal("Attempt to read past EOF.\n"); } if (typ == 'V') { break; /* break the loop */ @@ -1038,7 +1027,7 @@ GdbFormat::read() int delta = len - gbftell(ftmp); if (delta > 1000000) { - fatal("Internal consistency error. Delta too big"); + gbFatal("Internal consistency error. Delta too big\n"); } // Avoid finite loop on bogus beta files from '06. @@ -1047,26 +1036,26 @@ GdbFormat::read() if (dump && delta) { if (! incomplete++) { - warning(MYNAME ":==========================================\n"); - warning(MYNAME ":=== W A R N I N G ===\n"); + gbWarning("==========================================\n"); + gbWarning("=== W A R N I N G ===\n"); } if (typ == 'W') - warning(MYNAME ":(%d%c-%02d): delta = %d (flag=%3d/%02x)-", + gbWarning("(%d%c-%02d): delta = %d (flag=%3d/%02x)-", gdb_ver, typ, wpt_class, delta, waypt_flag, waypt_flag); else { - warning(MYNAME ":(%d%c): delta = %d -", gdb_ver, typ, delta); + gbWarning("(%d%c): delta = %d -", gdb_ver, typ, delta); } if (delta > 0) { char* buf = (char*) xmalloc(delta); if (FREAD(buf, delta) < 1) { - fatal(MYNAME ": Attempt to read past EOF.\n"); + gbFatal("Attempt to read past EOF.\n"); } for (int i = 0; i < delta; i++) { - warning(" %02x", (unsigned char)buf[i]); + gbWarning(" %02x", (unsigned char)buf[i]); } xfree(buf); } - warning("\n"); + gbWarning("\n"); } fin = fsave; @@ -1074,13 +1063,13 @@ GdbFormat::read() if (incomplete) { - warning(MYNAME ":------------------------------------------\n"); - warning(MYNAME ": \"%s\"\n", qPrintable(fin->name)); - warning(MYNAME ":------------------------------------------\n"); - warning(MYNAME ": Please mail this information\n"); - warning(MYNAME " and, if you can, the used GDB file\n"); - warning(MYNAME ": to gpsbabel-misc@lists.sourceforge.net\n"); - warning(MYNAME ":==========================================\n"); + gbWarning("------------------------------------------\n"); + gbWarning("\"%s\"\n", gbLogCStr(fin->name)); + gbWarning("------------------------------------------\n"); + gbWarning("Please mail this information\n"); + gbWarning("and, if you can, the used GDB file\n"); + gbWarning("to gpsbabel-misc@lists.sourceforge.net\n"); + gbWarning("==========================================\n"); } } @@ -1349,7 +1338,7 @@ GdbFormat::write_route(const route_head* rte, const QString& rte_name) if (test != nullptr) { wpt = test; } else { - fatal(MYNAME ": Sorry, that should never happen!!!\n"); + gbFatal("Sorry, that should never happen!!!\n"); } const garmin_fs_t* gmsd = garmin_fs_t::find(wpt); @@ -1631,15 +1620,15 @@ GdbFormat::write_track_cb(const route_head* trk) void GdbFormat::wr_init(const QString& fname) { - fout = gbfopen_le(fname, "wb", MYNAME); - ftmp = gbfopen_le(nullptr, "wb", MYNAME); + fout = gbfopen_le(fname, "wb"); + ftmp = gbfopen_le(nullptr, "wb"); gdb_category = gdb_opt_category ? gdb_opt_category.get_result() : 0; gdb_ver = gdb_opt_ver.get_result(); if (gdb_category) { if ((gdb_category < 1) || (gdb_category > 16)) { - fatal(MYNAME ": cat must be between 1 and 16!"); + gbFatal("cat must be between 1 and 16!\n"); } gdb_category = 1 << (gdb_category - 1); } diff --git a/geo.cc b/geo.cc index 15eab8623..3f084bc2c 100644 --- a/geo.cc +++ b/geo.cc @@ -31,8 +31,6 @@ #include "src/core/file.h" // for File -#define MYNAME "geo" - void GeoFormat::GeoReadLoc(QXmlStreamReader& reader) { Waypoint* wpt = nullptr; @@ -92,9 +90,9 @@ void GeoFormat::read() GeoReadLoc(reader); if (reader.hasError()) { - fatal(MYNAME ":Read error: %s (%s, line %ld, col %ld)\n", - qPrintable(reader.errorString()), - qPrintable(ifile.fileName()), + gbFatal("Read error: %s (%s, line %ld, col %ld)\n", + gbLogCStr(reader.errorString()), + gbLogCStr(ifile.fileName()), (long) reader.lineNumber(), (long) reader.columnNumber()); } diff --git a/geojson.cc b/geojson.cc index c6dc6eb0a..90ef631ab 100644 --- a/geojson.cc +++ b/geojson.cc @@ -147,7 +147,7 @@ GeoJsonFormat::read() QJsonParseError error{}; QJsonDocument document = QJsonDocument::fromJson(file_content.toUtf8(), &error); if (error.error != QJsonParseError::NoError) { - fatal(FatalMsg().nospace() << MYNAME << ": GeoJSON parse error in " << ifd->fileName() << ": " << error.errorString()); + gbFatal(FatalMsg().nospace() << "GeoJSON parse error in " << ifd->fileName() << ": " << error.errorString()); } QJsonObject rootObject = document.object(); diff --git a/geojson.h b/geojson.h index 38cf471f2..6a1d23395 100644 --- a/geojson.h +++ b/geojson.h @@ -71,7 +71,6 @@ class GeoJsonFormat : public Format gpsbabel::File* ifd{nullptr}; gpsbabel::File* ofd{nullptr}; - const char* MYNAME = "geojson"; OptionBool compact_opt; QJsonObject* track_object = nullptr; QJsonArray* track_coords = nullptr; diff --git a/globalsat_sport.cc b/globalsat_sport.cc index 6a192b6d6..6e35abae0 100644 --- a/globalsat_sport.cc +++ b/globalsat_sport.cc @@ -36,7 +36,6 @@ */ #include -#include // for printf #include // for free, malloc #include // for QByteArray @@ -45,7 +44,6 @@ #include // for QString #include // for QTime #include // for QTimeZone -#include // for LocalTime #include // for qPrintable #include "defs.h" @@ -55,16 +53,14 @@ #include "src/core/datetime.h" // for DateTime -#define MYNAME "GlobalsatSport" - void GlobalsatSportFormat::serial_init(const char* fname) { if (serial_handle = gbser_init(fname), nullptr == serial_handle) { - fatal(MYNAME ": Can't open port '%s'\n", fname); + gbFatal("Can't open port '%s'\n", fname); } if (gbser_set_speed(serial_handle, 115200) != gbser_OK) { - fatal(MYNAME ": Can't configure port '%s'\n", fname); + gbFatal("Can't configure port '%s'\n", fname); } // Toss anything that came in before our speed was set gbser_flush(serial_handle); @@ -74,12 +70,12 @@ void GlobalsatSportFormat::serial_deinit() { if (global_opts.debug_level > 1) { - printf(MYNAME " serial_deinit()\n"); + gbDebug("serial_deinit()\n"); } gbser_deinit(serial_handle); serial_handle = nullptr; if (global_opts.debug_level > 1) { - printf(MYNAME " serial_deinit() Done\n"); + gbDebug("serial_deinit() Done\n"); } } @@ -90,25 +86,25 @@ GlobalsatSportFormat::serial_recv_byte() const int result = gbser_readc_wait(serial_handle, 4000); switch (result) { case gbser_ERROR: - fatal("serial_recv_byte(): error reading one byte\n"); + gbFatal("serial_recv_byte(): error reading one byte\n"); break; case gbser_NOTHING: - fatal("serial_recv_byte(): read timeout\n"); + gbFatal("serial_recv_byte(): read timeout\n"); break; } return result; } void -GlobalsatSportFormat::serial_write_byte(uint8_t byte) const +GlobalsatSportFormat::serial_write_byte(uint8_t byte) { if (global_opts.debug_level > 1) { - printf("0x%02x (%d), ", byte, byte); + gbDebug("0x%02x (%d), ", byte, byte); } int n = gbser_writec(serial_handle, byte); if (n == gbser_ERROR) { - fatal("globalsat_probe_device(): write failed\n"); + gbFatal("globalsat_probe_device(): write failed\n"); } } @@ -122,7 +118,7 @@ GlobalsatSportFormat::recv_byte() } else { result = gbfgetc(in_file); if (result < 0) { - fatal(MYNAME ": read error"); + gbFatal("read error\n"); } } // Check if byte should be dumped also into a file @@ -177,7 +173,7 @@ GlobalsatSportFormat::globalsat_write_package(uint8_t* payload, uint32_t size) } write_byte(crc); if (global_opts.debug_level > 1) { - printf("\n"); + gbDebug("\n"); } } @@ -189,7 +185,7 @@ GlobalsatSportFormat::globalsat_read_package(int* out_length, uint8_t* out_Devic uint8_t DeviceCommand = recv_byte(); if (global_opts.debug_level > 1) { - printf("DeviceCommand: 0x%02x ", DeviceCommand); + gbDebug("DeviceCommand: 0x%02x ", DeviceCommand); } uint8_t len_h = recv_byte(); calc_crc ^= len_h; @@ -198,7 +194,7 @@ GlobalsatSportFormat::globalsat_read_package(int* out_length, uint8_t* out_Devic int length = (len_h << 8) + len_l; if (global_opts.debug_level > 1) { - printf("len=%d Payload:", length); + gbDebug("len=%d Payload:", length); } auto* payload = (uint8_t*) malloc(length); @@ -213,7 +209,7 @@ GlobalsatSportFormat::globalsat_read_package(int* out_length, uint8_t* out_Devic crc = recv_byte(); if (global_opts.debug_level > 1) { - printf("crc=0x%x should be=0x%x\n", crc, calc_crc); + gbDebug("crc=0x%x should be=0x%x\n", crc, calc_crc); } if (crc == calc_crc) { *out_DeviceCommand = DeviceCommand; @@ -251,7 +247,7 @@ GlobalsatSportFormat::globalsat_probe_device() uint8_t* payload = globalsat_read_package(&len, &DeviceCommand); if ((len > 0) && (payload != nullptr)) { if (global_opts.debug_level > 1) { - printf("Got package!!!\n"); + gbDebug("Got package!!!\n"); } //TODO figure out what device it is if we start to support more devices then gh625XT } @@ -265,15 +261,15 @@ void GlobalsatSportFormat::rd_init(const QString& fname) { if (global_opts.debug_level > 1) { - printf(MYNAME " rd_init()\n"); + gbDebug("rd_init()\n"); } if (opt_dump_file) { - dumpfile = gbfopen(opt_dump_file, "wb", MYNAME); + dumpfile = gbfopen(opt_dump_file, "wb"); if (!dumpfile) { - printf(MYNAME " rd_init() creating dumpfile %s FAILED continue anyway\n", qPrintable(opt_dump_file)); + gbWarning("rd_init() creating dumpfile %s FAILED continue anyway\n", gbLogCStr(opt_dump_file)); } else { if (global_opts.debug_level > 1) { - printf(MYNAME " rd_init() creating dumpfile %s for writing binary copy of serial stream\n", qPrintable(opt_dump_file)); + gbDebug("rd_init() creating dumpfile %s for writing binary copy of serial stream\n", gbLogCStr(opt_dump_file)); } } } @@ -281,9 +277,9 @@ GlobalsatSportFormat::rd_init(const QString& fname) serial_init(qPrintable(fname)); } else { // read from dump-file instead of serial - in_file = gbfopen(fname, "rb", MYNAME); + in_file = gbfopen(fname, "rb"); if (!in_file) { - fatal("Could not open dumpfile for input: %s", qPrintable(fname)); + gbFatal("Could not open dumpfile for input: %s\n", gbLogCStr(fname)); } } @@ -292,7 +288,7 @@ GlobalsatSportFormat::rd_init(const QString& fname) timezn = new QTimeZone(opt_timezone.get().toUtf8()); } else { list_timezones(); - fatal(MYNAME ": Requested time zone \"%s\" not available.\n", qPrintable(opt_timezone)); + gbFatal("Requested time zone \"%s\" not available.\n", gbLogCStr(opt_timezone)); } } else { timezn = nullptr; @@ -304,7 +300,7 @@ void GlobalsatSportFormat::rd_deinit() { if (global_opts.debug_level > 1) { - printf(MYNAME " rd_deinit()\n"); + gbDebug("rd_deinit()\n"); } if (!opt_input_dump_file) { serial_deinit(); @@ -322,7 +318,7 @@ GlobalsatSportFormat::rd_deinit() timezn = nullptr; } if (global_opts.debug_level > 1) { - printf(MYNAME " rd_deinit() Done\n"); + gbDebug("rd_deinit() Done\n"); } } @@ -330,7 +326,7 @@ void GlobalsatSportFormat::waypoint_read() { if (global_opts.debug_level > 1) { - printf(MYNAME " waypoint_read()\n"); + gbDebug(" waypoint_read()\n"); } //CommandGetTrackFileHeaders globalsat_send_simple(CommandGetWaypoints); @@ -340,7 +336,7 @@ GlobalsatSportFormat::waypoint_read() uint8_t* in_payload = globalsat_read_package(&len, &DeviceCommand); if ((len > 0) && (in_payload != nullptr)) { if (global_opts.debug_level > 1) { - printf("Got package!!!\n"); + gbDebug("Got package!!!\n"); } } if (in_payload) { @@ -353,12 +349,12 @@ void GlobalsatSportFormat::track_read() { if (global_opts.debug_level > 1) { - printf(MYNAME " track_read()\n"); + gbDebug(" track_read()\n"); } //CommandGetTrackFileHeaders globalsat_send_simple(CommandGetTrackFileHeaders); if (global_opts.debug_level > 1) { - printf("Sent...\n"); + gbDebug("Sent...\n"); } int length; @@ -366,12 +362,12 @@ GlobalsatSportFormat::track_read() uint8_t* payload = globalsat_read_package(&length, &DeviceCommand); if ((length > 0) && (payload != nullptr)) { if (global_opts.debug_level > 1) { - printf("Got package!!! headers\n"); + gbDebug("Got package!!! headers\n"); } //payload is packed with a number of trainingheaders with the size of 29bytes each int number_headers = length / 29; //29=packed sizeof(gh_trainheader) if (global_opts.debug_level > 1) { - printf("length=%d sizeof(gh_trainheader)=%d number_headers=%d\n", length, 29, number_headers); + gbDebug("length=%d sizeof(gh_trainheader)=%d number_headers=%d\n", length, 29, number_headers); } for (int i = 0; i < number_headers; i++) { @@ -393,17 +389,17 @@ GlobalsatSportFormat::track_read() th_header.DataType = th_hdr[28]; if (showlist || global_opts.debug_level > 1) { - printf("Track[%02i]: %02d-%02d-%02d ", i, th_header.dateStart.Year, th_header.dateStart.Month, th_header.dateStart.Day); - printf("%02d:%02d:%02d ", th_header.timeStart.Hour, th_header.timeStart.Minute, th_header.timeStart.Second); + gbDebug("Track[%02i]: %02d-%02d-%02d ", i, th_header.dateStart.Year, th_header.dateStart.Month, th_header.dateStart.Day); + gbDebug("%02d:%02d:%02d ", th_header.timeStart.Hour, th_header.timeStart.Minute, th_header.timeStart.Second); int time_s=th_header.TotalTime / 10; int time_h=time_s/(60*60); time_s-=time_h*(60*60); int time_m=time_s/60; time_s-=time_m*60; - printf("Points:%6u Time:%02d:%02d:%02d Dist:%9um LapCnts:%5d ", th_header.TotalPoint, time_h, time_m, time_s, th_header.TotalDistance, th_header.LapCnts); - printf("Index/StartPt:%u ", th_header.gh_ptrec.Index); - printf("LapIndex/EndPt:%u ", th_header.gh_laprec.LapIndex); - printf("DataType:0x%x\n", th_header.DataType); + gbDebug("Points:%6u Time:%02d:%02d:%02d Dist:%9um LapCnts:%5d ", th_header.TotalPoint, time_h, time_m, time_s, th_header.TotalDistance, th_header.LapCnts); + gbDebug("Index/StartPt:%u ", th_header.gh_ptrec.Index); + gbDebug("LapIndex/EndPt:%u ", th_header.gh_laprec.LapIndex); + gbDebug("DataType:0x%x\n", th_header.DataType); } if (!showlist) { @@ -432,7 +428,7 @@ GlobalsatSportFormat::track_read() int track_length; uint8_t* track_payload = globalsat_read_package(&track_length, &trackDeviceCommand); if ((track_length == 0) || (track_payload == nullptr)) { - fatal(MYNAME ": track length is 0 bytes or payload nonexistent.\n"); + gbFatal("track length is 0 bytes or payload nonexistent.\n"); } // printf("Got track package!!! Train data\n"); @@ -470,12 +466,12 @@ GlobalsatSportFormat::track_read() db_train.Sport5 = dbtrain[57]; if (global_opts.debug_level > 1) { - printf("\nTrainData:%02d-%02d-%02d ", db_train.dateStart.Year, db_train.dateStart.Month, db_train.dateStart.Day); - printf("%02d:%02d:%02d ", db_train.timeStart.Hour, db_train.timeStart.Minute, db_train.timeStart.Second); - printf("Total(points:%6u time:%6us dist:%9um) LapCnts:%5d ", db_train.TotalPoint, db_train.TotalTime / 10, db_train.TotalDistance, db_train.LapCnts); - printf("Index/StartPt:%u ", db_train.gh_ptrec.Index); - printf("LapIndex/EndPt:%u ", db_train.gh_laprec.LapIndex); - printf("MultiSport:0x%x ", db_train.MultiSport); + gbDebug("\nTrainData:%02d-%02d-%02d ", db_train.dateStart.Year, db_train.dateStart.Month, db_train.dateStart.Day); + gbDebug("%02d:%02d:%02d ", db_train.timeStart.Hour, db_train.timeStart.Minute, db_train.timeStart.Second); + gbDebug("Total(points:%6u time:%6us dist:%9um) LapCnts:%5d ", db_train.TotalPoint, db_train.TotalTime / 10, db_train.TotalDistance, db_train.LapCnts); + gbDebug("Index/StartPt:%u ", db_train.gh_ptrec.Index); + gbDebug("LapIndex/EndPt:%u ", db_train.gh_laprec.LapIndex); + gbDebug("MultiSport:0x%x ", db_train.MultiSport); } int total_laps = db_train.LapCnts; int total_laps_left = total_laps; @@ -489,7 +485,7 @@ GlobalsatSportFormat::track_read() globalsat_send_simple(CommandGetNextTrackSection); track_payload = globalsat_read_package(&track_length, &trackDeviceCommand); if ((track_length == 0) || (track_payload == nullptr)) { - fatal(MYNAME ": track length is 0 bytes or payload nonexistent.\n"); + gbFatal("track length is 0 bytes or payload nonexistent.\n"); } // printf("Got track package!!! Laps data\n"); @@ -511,12 +507,12 @@ GlobalsatSportFormat::track_read() if (global_opts.debug_level > 1) { - printf("Lap Trainheader: %02d-%02d-%02d ", header.dateStart.Year, header.dateStart.Month, header.dateStart.Day); - printf("%02d:%02d:%02d ", header.timeStart.Hour, header.timeStart.Minute, header.timeStart.Second); - printf("Total(points:%6u time:%6us dist:%9um) LapCnts:%5d ", header.TotalPoint, header.TotalTime / 10, header.TotalDistance, header.LapCnts); - printf("Index/StartPt:%u ", header.gh_ptrec.Index); - printf("LapIndex/EndPt:%u ", header.gh_laprec.LapIndex); - printf("DataType:0x%x\n", header.DataType); + gbDebug("Lap Trainheader: %02d-%02d-%02d ", header.dateStart.Year, header.dateStart.Month, header.dateStart.Day); + gbDebug("%02d:%02d:%02d ", header.timeStart.Hour, header.timeStart.Minute, header.timeStart.Second); + gbDebug("Total(points:%6u time:%6us dist:%9um) LapCnts:%5d ", header.TotalPoint, header.TotalTime / 10, header.TotalDistance, header.LapCnts); + gbDebug("Index/StartPt:%u ", header.gh_ptrec.Index); + gbDebug("LapIndex/EndPt:%u ", header.gh_laprec.LapIndex); + gbDebug("DataType:0x%x\n", header.DataType); } /* @@ -557,13 +553,13 @@ GlobalsatSportFormat::track_read() db_lap.EndPt = be_read32(dblap+37); if (global_opts.debug_level > 1) { - printf(" lap[%d] AccruedTime:%us TotalTime:%us TotalDist:%um", lap, db_lap.AccruedTime, db_lap.TotalTime / 10, db_lap.TotalDistance); - printf(" Calory:%d MaxSpeed:%u Hearth max:%d avg:%d ", db_lap.Calory, db_lap.MaxSpeed, db_lap.MaxHeart, db_lap.AvgHeart); - printf(" Alt min:%d max:%d", db_lap.MinAlti, db_lap.MaxAlti); - printf(" Cadns avg:%d best:%d", db_lap.AvgCadns, db_lap.BestCadns); - printf(" Power avg:%d Max:%d", db_lap.AvgPower, db_lap.MaxPower); - printf(" MultisportIndex:%d", db_lap.MultiSportIndex); - printf(" StartPt:%u EndPt:%u\n", db_lap.StartPt, db_lap.EndPt); + gbDebug(" lap[%d] AccruedTime:%us TotalTime:%us TotalDist:%um", lap, db_lap.AccruedTime, db_lap.TotalTime / 10, db_lap.TotalDistance); + gbDebug(" Calory:%d MaxSpeed:%u Hearth max:%d avg:%d ", db_lap.Calory, db_lap.MaxSpeed, db_lap.MaxHeart, db_lap.AvgHeart); + gbDebug(" Alt min:%d max:%d", db_lap.MinAlti, db_lap.MaxAlti); + gbDebug(" Cadns avg:%d best:%d", db_lap.AvgCadns, db_lap.BestCadns); + gbDebug(" Power avg:%d Max:%d", db_lap.AvgPower, db_lap.MaxPower); + gbDebug(" MultisportIndex:%d", db_lap.MultiSportIndex); + gbDebug(" StartPt:%u EndPt:%u\n", db_lap.StartPt, db_lap.EndPt); } } free(track_payload); @@ -601,12 +597,12 @@ GlobalsatSportFormat::track_read() if (global_opts.debug_level > 1) { - printf("Lap Trainheader: %02d-%02d-%02d ", laptrain_header.dateStart.Year, laptrain_header.dateStart.Month, laptrain_header.dateStart.Day); - printf("%02d:%02d:%02d ", laptrain_header.timeStart.Hour, laptrain_header.timeStart.Minute, laptrain_header.timeStart.Second); - printf("Total(points:%6u time:%6us dist:%9um) LapCnts:%5d ", laptrain_header.TotalPoint, laptrain_header.TotalTime / 10, laptrain_header.TotalDistance, laptrain_header.LapCnts); - printf("StartPt:%u ", laptrain_header.gh_ptrec.StartPt); - printf("EndPt:%u ", laptrain_header.gh_laprec.EndPt); - printf("DataType:0x%x\n", laptrain_header.DataType); + gbDebug("Lap Trainheader: %02d-%02d-%02d ", laptrain_header.dateStart.Year, laptrain_header.dateStart.Month, laptrain_header.dateStart.Day); + gbDebug("%02d:%02d:%02d ", laptrain_header.timeStart.Hour, laptrain_header.timeStart.Minute, laptrain_header.timeStart.Second); + gbDebug("Total(points:%6u time:%6us dist:%9um) LapCnts:%5d ", laptrain_header.TotalPoint, laptrain_header.TotalTime / 10, laptrain_header.TotalDistance, laptrain_header.LapCnts); + gbDebug("StartPt:%u ", laptrain_header.gh_ptrec.StartPt); + gbDebug("EndPt:%u ", laptrain_header.gh_laprec.EndPt); + gbDebug("DataType:0x%x\n", laptrain_header.DataType); } int recpoints_in_package = laptrain_header.gh_laprec.EndPt - laptrain_header.gh_ptrec.StartPt + 1; @@ -633,10 +629,10 @@ GlobalsatSportFormat::track_read() // qDebug() << "DateTime2:" << gpsDateTime.toString(); // } if (global_opts.debug_level > 1) { - printf(" recpoint[%2d] Lat:%f Long:%f Alt:%dm", recpoint, (double)((int32_t) point.Latitude) / 1000000.0, (double)((int32_t) point.Longitude) / 1000000.0, point.Altitude); - printf(" Speed:%f HR:%d", (double) point.Speed / 100, point.HeartRate); - printf(" Time:%u Cadence:%d", point.IntervalTime, point.Cadence); - printf(" PwrCadense:%d Power:%d\n", point.PwrCadence, point.Power); + gbDebug(" recpoint[%2d] Lat:%f Long:%f Alt:%dm", recpoint, (double)((int32_t) point.Latitude) / 1000000.0, (double)((int32_t) point.Longitude) / 1000000.0, point.Altitude); + gbDebug(" Speed:%f HR:%d", (double) point.Speed / 100, point.HeartRate); + gbDebug(" Time:%u Cadence:%d", point.IntervalTime, point.Cadence); + gbDebug(" PwrCadense:%d Power:%d\n", point.PwrCadence, point.Power); } auto* wpt = new Waypoint(); // waypt_new(); @@ -668,7 +664,7 @@ void GlobalsatSportFormat::route_read() { if (global_opts.debug_level > 1) { - printf(MYNAME " route_read() TODO\n"); + gbDebug("route_read() TODO\n"); } } @@ -676,7 +672,7 @@ void GlobalsatSportFormat::read() { if (global_opts.debug_level > 1) { - printf(MYNAME " read()\n"); + gbDebug("read()\n"); } if (global_opts.masked_objective & WPTDATAMASK) { @@ -690,6 +686,6 @@ GlobalsatSportFormat::read() } if (!(global_opts.masked_objective & (WPTDATAMASK | TRKDATAMASK | RTEDATAMASK | POSNDATAMASK))) { - fatal(MYNAME ": Nothing to do.\n"); + gbFatal("Nothing to do.\n"); } } diff --git a/globalsat_sport.h b/globalsat_sport.h index bdebca4c5..c2f2688de 100644 --- a/globalsat_sport.h +++ b/globalsat_sport.h @@ -213,7 +213,7 @@ class GlobalsatSportFormat : public Format void serial_init(const char* fname); void serial_deinit(); int serial_recv_byte() const; - void serial_write_byte(uint8_t byte) const; + void serial_write_byte(uint8_t byte); int recv_byte(); void write_byte(uint8_t byte); void globalsat_write_package(uint8_t* payload, uint32_t size); diff --git a/googletakeout.cc b/googletakeout.cc index 5ba243c83..b00e86f28 100644 --- a/googletakeout.cc +++ b/googletakeout.cc @@ -42,11 +42,11 @@ void GoogleTakeoutFormat::takeout_fatal(const QString& message) { - fatal(FatalMsg() << MYNAME << ": " << message); + gbFatal(FatalMsg() << message); } void GoogleTakeoutFormat::takeout_warning(const QString& message) { - Warning() << MYNAME << ": " << message; + Warning() << message; } /* create a waypoint from late7/lone7 and optional metadata */ @@ -264,7 +264,7 @@ GoogleTakeoutFormat::read() } } if (global_opts.debug_level >= 1) { - Debug(1) << MYNAME << ": Processed " << items << " items: " << + Debug(1) << "Processed " << items << " items: " << place_visits << " " << PLACE_VISIT << ", " << activity_segments << " " << ACTIVITY_SEGMENT << " (" << points << " points total)"; } diff --git a/googletakeout.h b/googletakeout.h index 3d805562a..f1aa6ae32 100644 --- a/googletakeout.h +++ b/googletakeout.h @@ -66,7 +66,6 @@ class GoogleTakeoutFormat : public Format private: /* Constants */ - static constexpr char MYNAME[] = "Google Takeout"; static constexpr char TIMELINE_OBJECTS[] = "timelineObjects"; static constexpr char16_t PLACE_VISIT[] = u"placeVisit"; static constexpr char16_t ACTIVITY_SEGMENT[] = u"activitySegment"; @@ -126,8 +125,8 @@ class GoogleTakeoutFormat : public Format static Waypoint* takeout_waypoint(int lat_e7, int lon_e7, const QString* shortname, const QString* description, const QString* start_str); static bool track_maybe_add_wpt(route_head* route, Waypoint* waypoint); static void title_case(QString& title); - void add_place_visit(const QJsonObject& placeVisit); - int add_activity_segment(const QJsonObject& activitySegment); + static void add_place_visit(const QJsonObject& placeVisit); + static int add_activity_segment(const QJsonObject& activitySegment); /* Data Members */ diff --git a/gpx.cc b/gpx.cc index c401df853..58662d11b 100644 --- a/gpx.cc +++ b/gpx.cc @@ -60,7 +60,6 @@ #include "src/core/xmltag.h" // for xml_tag, fs_xml, fs_xml_alloc, free_gpx_extras -#define MYNAME "GPX" #ifndef CREATOR_NAME_URL # define CREATOR_NAME_URL "GPSBabel - https://www.gpsbabel.org" #endif @@ -254,7 +253,7 @@ GpxFormat::tag_garmin_fs(tag_type tag, const QString& text, Waypoint* waypt) // but that feature is so obscure and used in so few outputs that // there's no reason to alarm the user. Just silently disregard // category names that don't map cleanly. - // warning(MYNAME ": Unable to convert category \"%s\"!\n", CSTR(text)); + // gbWarning("Unable to convert category \"%s\"!\n", CSTR(text)); } break; case tag_type::garmin_wpt_addr: @@ -1000,7 +999,7 @@ GpxFormat::wr_init(const QString& fname) // It's a good thing 0, 0.0, 0.0.0 aren't valid gpx versions, // normalization makes them null. if (gpx_write_version.isNull() || (gpx_write_version < gpx_1_0)) { - fatal(FatalMsg() << MYNAME ": gpx version number" + gbFatal(FatalMsg() << "gpx version number" << gpx_write_version.toString() << "not valid."); } @@ -1173,7 +1172,7 @@ GpxFormat::read() } if (reader->hasError()) { - fatal(FatalMsg() << MYNAME << "Read error:" << reader->errorString() + gbFatal(FatalMsg() << "Read error:" << reader->errorString() << "File:" << iqfile->fileName() << "Line:" << reader->lineNumber() << "Column:" << reader->columnNumber()); diff --git a/gtm.cc b/gtm.cc index cb309c506..488cca96e 100644 --- a/gtm.cc +++ b/gtm.cc @@ -38,7 +38,6 @@ #include "src/core/datetime.h" // for DateTime -#define MYNAME "GTM" #define EPOCH89DIFF 631065600 /* was 631076400 but that seems to include a three-hour bias */ #define WAYPOINTSTYLES \ @@ -166,7 +165,7 @@ void GtmFormat::set_datum(int n) } if (indatum == -1) { - warning(MYNAME ": Unsupported datum (%d), won't convert to WGS84\n", n); + gbWarning("Unsupported datum (%d), won't convert to WGS84\n", n); } } @@ -184,17 +183,17 @@ void GtmFormat::convert_datum(double* lat, double* lon) const void GtmFormat::rd_init(const QString& fname) { - file_in = gbfopen_le(fname, "rb", MYNAME); + file_in = gbfopen_le(fname, "rb"); int version = fread_integer(file_in); QString name = fread_fixedstring(file_in, 10); if (version == -29921) { - fatal(MYNAME ": Uncompress the file first\n"); + gbFatal("Uncompress the file first\n"); } if (name != "TrackMaker") { - fatal(MYNAME ": Invalid file format\n"); + gbFatal("Invalid file format\n"); } if (version != 211) { - fatal(MYNAME ": Invalid format version\n"); + gbFatal("Invalid format version\n"); } /* Header */ @@ -247,7 +246,7 @@ GtmFormat::wr_init(const QString& fname) }; track_disp_all(count_track_styles_lambda, nullptr, nullptr); - file_out = gbfopen_le(fname, "wb", MYNAME); /* little endian */ + file_out = gbfopen_le(fname, "wb"); /* little endian */ /* Header */ fwrite_integer(file_out, 211); @@ -384,7 +383,7 @@ GtmFormat::read() // If ts_count != real_track_list.size() we don't know how to line up // the tracklogs, and the real tracks, with the tracklog styles. if (ts_count != real_track_list.size()) { - warning(MYNAME ": The number of tracklog entries with the new flag " + gbWarning("The number of tracklog entries with the new flag " "set doesn't match the number of tracklog style entries.\n" " This is unexpected and may indicate a malformed input file.\n" " As a result the track names may be incorrect.\n"); diff --git a/gtrnctr.cc b/gtrnctr.cc index 65e866adf..7d2d81db6 100644 --- a/gtrnctr.cc +++ b/gtrnctr.cc @@ -41,8 +41,6 @@ #include "xmlgeneric.h" // for xml_deinit, xml_init, xml_read -#define MYNAME "gtc" - const QStringList GtrnctrFormat::gtc_tags_to_ignore = { "TrainingCenterDatabase", "CourseFolder", @@ -75,7 +73,7 @@ GtrnctrFormat::rd_deinit() void GtrnctrFormat::wr_init(const QString& fname) { - ofd = gbfopen(fname, "w", MYNAME); + ofd = gbfopen(fname, "w"); if (opt_sport) { for (unsigned int i = 0; i < std::size(gtc_sportlist); i++) { diff --git a/height.cc b/height.cc index 778424afb..7e1aa3f10 100644 --- a/height.cc +++ b/height.cc @@ -27,7 +27,6 @@ #include // for floor #include // for int8_t -#define MYNAME "height" #if FILTERS_ENABLED @@ -53,10 +52,10 @@ double HeightFilter::wgs84_separation(double lat, double lon) { /* sanity checks to prevent segfault on bad data */ if ((lat > 90.0) || (lat < -90.0)) { - fatal(MYNAME ": Invalid latitude value (%f)\n", lat); + gbFatal("Invalid latitude value (%f)\n", lat); } if ((lon > 180.0) || (lon < -180.0)) { - fatal(MYNAME ": Invalid longitude value (%f)\n", lon); + gbFatal("Invalid longitude value (%f)\n", lon); } auto ilat = static_cast(floor((90.0+lat)/geoid_grid_deg)); @@ -97,8 +96,8 @@ void HeightFilter::init() { addf = 0.0; if (addopt) { - if (parse_distance(addopt, &addf, 1.0, MYNAME) == 0) { - fatal(MYNAME ": No height specified with add option."); + if (parse_distance(addopt, &addf, 1.0) == 0) { + gbFatal("No height specified with add option.\n"); } } } diff --git a/html.cc b/html.cc index 5df1998a4..02300900f 100644 --- a/html.cc +++ b/html.cc @@ -41,13 +41,11 @@ #include "src/core/xmltag.h" // for xml_findfirst, xml_tag, xml_attribute, fs_xml, xml_findnext -#define MYNAME "HTML" - void HtmlFormat::wr_init(const QString& fname) { file_out = new gpsbabel::TextStream; - file_out->open(fname, QIODevice::WriteOnly, MYNAME); + file_out->open(fname, QIODevice::WriteOnly); mkshort_handle = new MakeShort; static const QRegularExpression re("^(?:ddd|dmm|dms)$"); @@ -55,7 +53,7 @@ HtmlFormat::wr_init(const QString& fname) if (re.match(opt_degformat).hasMatch()) { degformat = opt_degformat.get().at(2).toLatin1(); } else { - fatal(MYNAME ": Unrecognized degformat %s, expected 'ddd', 'dmm' or 'dms'.\n", qPrintable(opt_degformat)); + gbFatal("Unrecognized degformat %s, expected 'ddd', 'dmm' or 'dms'.\n", gbLogCStr(opt_degformat)); } if (opt_altunits.get().startsWith('f')) { @@ -63,7 +61,7 @@ HtmlFormat::wr_init(const QString& fname) } else if (opt_altunits.get().startsWith('m')) { altunits = 'm'; } else { - fatal(MYNAME ": Unrecognized altunits %s, expected 'f' for feet or 'm' for meters.\n", qPrintable(opt_altunits)); + gbFatal("Unrecognized altunits %s, expected 'f' for feet or 'm' for meters.\n", gbLogCStr(opt_altunits)); } } diff --git a/humminbird.cc b/humminbird.cc index 05e379c4a..f721c76d4 100644 --- a/humminbird.cc +++ b/humminbird.cc @@ -30,13 +30,11 @@ #include // for strncpy #include // for inv_pi, pi -#include "defs.h" // for Waypoint, be_read32, be_read16, be_write32, fatal, be_write16, route_head, track_add_wpt +#include "defs.h" // for Waypoint, be_read32, be_read16, be_write32, gbFatal, be_write16, route_head, track_add_wpt #include "mkshort.h" // for MakeShort #include "src/core/datetime.h" // for DateTime -#define MYNAME "humminbird" - #define WPT_NAME_LEN 12 #define RTE_NAME_LEN 20 #define TRK_NAME_LEN 20 @@ -207,7 +205,7 @@ HumminbirdBase::inverse_gudermannian_i1924(const double x) void HumminbirdBase::humminbird_rd_init(const QString& fname) { - fin_ = gbfopen_be(fname, "rb", MYNAME); + fin_ = gbfopen_be(fname, "rb"); wpt_num_to_wpt_hash.clear(); } @@ -225,7 +223,7 @@ HumminbirdBase::humminbird_read_wpt(gbfile* fin) static_assert(sizeof(w) == 32); if (! gbfread(&w, 1, sizeof(w), fin)) { - fatal(MYNAME ": Unexpected end of file!\n"); + gbFatal("Unexpected end of file!\n"); } /* Fix endianness - these are now BE */ @@ -287,7 +285,7 @@ HumminbirdBase::humminbird_read_route(gbfile* fin) const static_assert(sizeof(hrte) == 132); if (! gbfread(&hrte, 1, sizeof(hrte), fin)) { - fatal(MYNAME ": Unexpected end of file!\n"); + gbFatal("Unexpected end of file!\n"); } hrte.time = be_read32(&hrte.time); @@ -319,7 +317,7 @@ HumminbirdBase::humminbird_read_track(gbfile* fin) static_assert(sizeof(th) == 64); if (! gbfread(&th, 1, sizeof(th), fin)) { - fatal(MYNAME ": Unexpected end of file reading header!\n"); + gbFatal("Unexpected end of file reading header!\n"); } th.trk_num = be_read16(&th.trk_num); @@ -343,7 +341,7 @@ HumminbirdBase::humminbird_read_track(gbfile* fin) } if (th.num_points > max_points) { - fatal(MYNAME ": Too many track points! (%d)\n", th.num_points); + gbFatal("Too many track points! (%d)\n", th.num_points); } /* num_points is actually one too big, because it includes the value in @@ -351,7 +349,7 @@ HumminbirdBase::humminbird_read_track(gbfile* fin) freak-value filter below looks at points[i+1] */ auto* points = new humminbird_trk_point_t[th.num_points](); if (! gbfread(points, sizeof(humminbird_trk_point_t), th.num_points-1, fin)) { - fatal(MYNAME ": Unexpected end of file reading points!\n"); + gbFatal("Unexpected end of file reading points!\n"); } int32_t accum_east = th.start_east; @@ -428,7 +426,7 @@ HumminbirdBase::humminbird_read_track_old(gbfile* fin) char namebuf[TRK_NAME_LEN]; if (! gbfread(&th, 1, sizeof(th), fin)) { - fatal(MYNAME ": Unexpected end of file reading header!\n"); + gbFatal("Unexpected end of file reading header!\n"); } th.trk_num = be_read16(&th.trk_num); @@ -445,7 +443,7 @@ HumminbirdBase::humminbird_read_track_old(gbfile* fin) int max_points = (file_len - (sizeof(th) + sizeof(uint32_t) + TRK_NAME_LEN)) / sizeof(humminbird_trk_point_old_t); if (th.num_points > max_points) { - fatal(MYNAME ": Too many track points! (%d)\n", th.num_points); + gbFatal("Too many track points! (%d)\n", th.num_points); } /* num_points is actually one too big, because it includes the value in @@ -453,7 +451,7 @@ HumminbirdBase::humminbird_read_track_old(gbfile* fin) freak-value filter below looks at points[i+1] */ auto* points = new humminbird_trk_point_old_t[th.num_points](); if (! gbfread(points, sizeof(humminbird_trk_point_old_t), th.num_points-1, fin)) { - fatal(MYNAME ": Unexpected end of file reading points!\n"); + gbFatal("Unexpected end of file reading points!\n"); } int32_t accum_east = th.start_east; @@ -544,7 +542,7 @@ HumminbirdBase::humminbird_read() humminbird_read_track_old(fin_); return; /* Don't continue. The rest of the file is all zeores */ default: - fatal(MYNAME ": Invalid record header \"0x%08X\" (no or unknown humminbird file)!\n", signature); + gbFatal("Invalid record header \"0x%08X\" (no or unknown humminbird file)!\n", signature); } } } @@ -555,7 +553,7 @@ HumminbirdBase::humminbird_read() void HumminbirdBase::humminbird_wr_init(const QString& fname) { - fout_ = gbfopen_be(fname, "wb", MYNAME); + fout_ = gbfopen_be(fname, "wb"); wptname_sh = new MakeShort; @@ -846,7 +844,7 @@ HumminbirdFormat::humminbird_write_rtept(const Waypoint* wpt) const if (!wpt_id_to_wpt_num_hash.contains(id)) { // This should not occur, we just scanned all waypoints and routes. - warning("Missing waypoint reference in route, point dropped from route."); + gbWarning("Missing waypoint reference in route, point dropped from route.\n"); return; } @@ -854,8 +852,8 @@ HumminbirdFormat::humminbird_write_rtept(const Waypoint* wpt) const humrte->points[humrte->count] = wpt_id_to_wpt_num_hash.value(id); humrte->count++; } else { - warning(MYNAME ": Sorry, routes are limited to %d points!\n", MAX_RTE_POINTS); - fatal(MYNAME ": You can use our simplify filter to reduce the number of route points.\n"); + gbWarning("Sorry, routes are limited to %d points!\n", MAX_RTE_POINTS); + gbFatal("You can use our simplify filter to reduce the number of route points.\n"); } } diff --git a/igc.cc b/igc.cc index c414e07bc..e7e24b293 100644 --- a/igc.cc +++ b/igc.cc @@ -54,7 +54,6 @@ -#define MYNAME "IGC" #define HDRMAGIC "IGCHDRS" #define HDRDELIM "~" #define DATEMAGIC "IGCDATE" @@ -99,7 +98,7 @@ IgcFormat::igc_rec_type_t IgcFormat::get_record(char** rec) const } if (len < 3 || c[0] < 'A' || c[0] > 'Z') { - warning(MYNAME " bad input record: '%s'\n", c); + gbWarning("bad input record: '%s'\n", c); return rec_bad; } return (igc_rec_type_t) c[0]; @@ -109,10 +108,10 @@ void IgcFormat::rd_init(const QString& fname) { char* ibuf; - file_in = gbfopen(fname, "r", MYNAME); + file_in = gbfopen(fname, "r"); // File must begin with a manufacturer/ID record if (get_record(&ibuf) != rec_manuf_id || sscanf(ibuf, "A%3[A-Z]", manufacturer) != 1) { - fatal(MYNAME ": %s is not an IGC file\n", qPrintable(fname)); + gbFatal("%s is not an IGC file\n", gbLogCStr(fname)); } } @@ -154,7 +153,7 @@ void IgcFormat::TaskRecordReader::igc_task_rec(const char* rec) &day, &month, &year, &hour, &minute, &second, flight_date, task_num, &num_tp, task_desc) < 9) { - fatal(MYNAME ": task id (C) record parse error A. \n'%s'", rec); + gbFatal("task id (C) record parse error A. \n'%s'\n", rec); } task_num[4] = '\0'; if (year < 70) { @@ -164,7 +163,7 @@ void IgcFormat::TaskRecordReader::igc_task_rec(const char* rec) } creation = QDateTime(QDate(year, month, day), QTime(hour, minute, second), QtUTC); if (!creation.isValid()) { - fatal(MYNAME ": bad date time\n%s\n", rec); + gbFatal("bad date time\n%s\n", rec); } // Create a route to store the task data in. @@ -180,7 +179,7 @@ void IgcFormat::TaskRecordReader::igc_task_rec(const char* rec) if (sscanf(rec, "C%2u%2u%3u%1[NS]%3u%2u%3u%1[WE]%78[^\r]\r\n", &lat_deg, &lat_min, &lat_frac, lat_hemi, &lon_deg, &lon_min, &lon_frac, lon_hemi, tmp_str) < 8) { - fatal(MYNAME ": task waypoint (C) record parse error\n%s", rec); + gbFatal("task waypoint (C) record parse error\n%s\n", rec); } auto* wpt = new Waypoint; @@ -224,7 +223,7 @@ void IgcFormat::TaskRecordReader::igc_task_rec(const char* rec) break; default: - fatal(MYNAME ": task id (C) record internal error B\n%s", rec); + gbFatal("task id (C) record internal error B\n%s\n", rec); break; } @@ -273,7 +272,7 @@ void IgcFormat::read() while (true) { if (global_opts.debug_level >= 8) { - printf(MYNAME ": Processing IGC file line %i\n", current_line); + gbDebug("Processing IGC file line %i\n", current_line); } igc_rec_type_t rec_type = get_record(&ibuf); current_line++; @@ -281,13 +280,13 @@ void IgcFormat::read() switch (rec_type) { case rec_manuf_id: // Manufacturer/ID record already found in rd_init(). - warning(MYNAME ": duplicate manufacturer/ID record\n"); + gbWarning("duplicate manufacturer/ID record\n"); break; case rec_header: // Get the header sub type if (sscanf(ibuf, "H%*1[FOPS]%3s", tmp_str) != 1) { - fatal(MYNAME ": header (H) record parse error\n%s\n%s\n", ibuf, tmp_str); + gbFatal("header (H) record parse error\n%s\n%s\n", ibuf, tmp_str); } // Optional long name of record sub type is followed by a // colon. Actual header data follows that. @@ -303,7 +302,7 @@ void IgcFormat::read() int month; int year; if (sscanf(hdr_data, "%2d%2d%2d", &day, &month, &year) != 3) { - fatal(MYNAME ": date (H) record parse error\n'%s'\n", ibuf); + gbFatal("date (H) record parse error\n'%s'\n", ibuf); } if (year < 70) { year += 2000; @@ -312,7 +311,7 @@ void IgcFormat::read() } date = QDate(year, month, day); if (!date.isValid()) { - fatal(MYNAME ": bad date\n%s\n", ibuf); + gbFatal("bad date\n%s\n", ibuf); } } else { // Store other header data in the track descriptions @@ -328,7 +327,7 @@ void IgcFormat::read() case rec_fix: { // Date must appear in file before the first fix record if (!date.isValid()) { - fatal(MYNAME ": bad date\n"); + gbFatal("bad date\n"); } // Create a track for pressure altitude waypoints if (!pres_head) { @@ -350,7 +349,7 @@ void IgcFormat::read() &hours, &mins, &secs, &lat_deg, &lat_min, &lat_frac, lat_hemi, &lon_deg, &lon_min, &lon_frac, lon_hemi, &validity, &pres_alt, &gnss_alt) != 14) { - fatal(MYNAME ": fix (B) record parse error\n%s\n", ibuf); + gbFatal("fix (B) record parse error\n%s\n", ibuf); } pres_wpt = new Waypoint; @@ -362,7 +361,7 @@ void IgcFormat::read() tod = QTime(hours, mins, secs); if (!tod.isValid()) { - fatal(MYNAME ": bad time\n%s\n", ibuf); + gbFatal("bad time\n%s\n", ibuf); } // Increment date if we pass midnight UTC @@ -379,21 +378,21 @@ void IgcFormat::read() if (!ext_types_list.isEmpty()) { auto* fsdata = new igc_fsdata; if (global_opts.debug_level >= 7) { - printf(MYNAME ": Record: %s\n",qPrintable(ibuf_q)); + gbDebug("Record: %s\n",gbLogCStr(ibuf_q)); } if (global_opts.debug_level >= 6) { - printf(MYNAME ": Adding extension data:"); + gbDebug("Adding extension data:"); } for (const auto& [name, ext, start, len, factor] : ext_types_list) { double ext_data = ibuf_q.mid(start,len).toInt() / factor; fsdata->set_value(ext, ext_data, pres_wpt); if (global_opts.debug_level >= 6) { - printf(" %s:%f", qPrintable(name), ext_data); + gbDebug(" %s:%f", gbLogCStr(name), ext_data); } } if (global_opts.debug_level >= 6) { - printf("\n"); + gbDebug("\n"); } pres_wpt->fs.FsChainAdd(fsdata); } @@ -430,7 +429,7 @@ void IgcFormat::read() case rec_log_book: // Get the log book sub type if (sscanf(ibuf, "L%3s", tmp_str) != 1) { - fatal(MYNAME ": log book (L) record parse error\n'%s'\n", ibuf); + gbFatal("log book (L) record parse error\n'%s'\n", ibuf); } if (strcmp(tmp_str, "PFC") == 0) { @@ -439,13 +438,13 @@ void IgcFormat::read() break; } else if (global_opts.debug_level >= 5) { if (strcmp(tmp_str, "OOI") == 0) { - printf(MYNAME ": Observer Input> %s\n", ibuf + 4); + gbDebug("Observer Input> %s\n", ibuf + 4); } else if (strcmp(tmp_str, "PLT") == 0) { - printf(MYNAME ": Pilot Input> %s\n", ibuf + 4); + gbDebug("Pilot Input> %s\n", ibuf + 4); } else if (strcmp(tmp_str, manufacturer) == 0) { - printf(MYNAME ": Manufacturer Input> %s\n", ibuf + 4); + gbDebug("Manufacturer Input> %s\n", ibuf + 4); } else { - printf(MYNAME ": Anonymous Input> %s\n", ibuf + 1); + gbDebug("Anonymous Input> %s\n", ibuf + 1); } } break; @@ -488,20 +487,20 @@ void IgcFormat::read() } } if (global_opts.debug_level >= 1) { - printf(MYNAME ": I record: %s\n" MYNAME ": Extensions present: %s\n", qPrintable(ibuf_q), - qPrintable(present_extensions.join(' '))); + gbDebug("I record: %s\n", gbLogCStr(ibuf_q)); + gbDebug("Extensions present: %s\n", gbLogCStr(present_extensions.join(' '))); } if (global_opts.debug_level >= 2) { - printf(MYNAME ": Non-excluded extensions defined in I record:\n"); - printf(MYNAME ": (Note: IGC records are one-initialized. QStrings are zero-initialized.)\n"); + gbDebug("Non-excluded extensions defined in I record:\n"); + gbDebug("(Note: IGC records are one-initialized. QStrings are zero-initialized.)\n"); for (const auto& [name, ext, begin, len, factor] : ext_types_list) { - printf(MYNAME ": Extension %s (%i): Begin: %i; Length: %i\n", qPrintable(name), int(ext), begin, len); + gbDebug(" Extension %s (%i): Begin: %i; Length: %i\n", gbLogCStr(name), int(ext), begin, len); } if (global_opts.debug_level >= 3) { - printf(MYNAME ": Unsupported extensions (I will not ingest these, they are unsupported):\t%s\n", - qPrintable(unsupported_extensions.join(' '))); - printf(MYNAME ": Supported extensions (These are present in the I record and supported):\t%s\n", - qPrintable(supported_extensions.join(' '))); + gbDebug("Unsupported extensions (I will not ingest these, they are unsupported):\t%s\n", + gbLogCStr(unsupported_extensions.join(' '))); + gbDebug("Supported extensions (These are present in the I record and supported):\t%s\n", + gbLogCStr(supported_extensions.join(' '))); } } } @@ -535,7 +534,7 @@ void IgcFormat::read() default: case rec_bad: - fatal(MYNAME ": failure reading file\n"); + gbFatal("failure reading file\n"); break; } } @@ -639,7 +638,7 @@ QByteArray IgcFormat::latlon2str(const Waypoint* wpt) char str[18]; if (snprintf(str, sizeof(str), "%02ld%05ld%c%03ld%05ld%c", lat_digits.quot, lat_digits.rem, lat_hemi, lon_digits.quot, lon_digits.rem, lon_hemi) != 17) { - fatal(MYNAME ": Bad waypoint format '%s'\n", str); + gbFatal("Bad waypoint format '%s'\n", str); } return str; } @@ -648,7 +647,7 @@ QByteArray IgcFormat::date2str(const gpsbabel::DateTime& dt) { QByteArray str = dt.toUTC().toString(u"ddMMyy").toUtf8(); if (str.size() != 6) { - fatal(MYNAME ": Bad date format '%s'\n", str.constData()); + gbFatal("Bad date format '%s'\n", str.constData()); } return str; } @@ -657,7 +656,7 @@ QByteArray IgcFormat::tod2str(const gpsbabel::DateTime& tod) { QByteArray str = tod.toUTC().toString(u"hhmmss").toUtf8(); if (str.size() != 6) { - fatal(MYNAME ": Bad time of day format '%s'\n", str.constData()); + gbFatal("Bad time of day format '%s'\n", str.constData()); } return str; } @@ -680,7 +679,7 @@ void IgcFormat::wr_header() // Date in header record is that of the first fix record date = track->waypoint_list.front()->GetCreationTime(); if (!date.isValid()) { - fatal(MYNAME ": Bad track timestamp\n"); + gbFatal("Bad track timestamp\n"); } } else { // This is a bit silly, there aren't any tracks! @@ -733,7 +732,7 @@ void IgcFormat::wr_task_hdr(const route_head* rte, unsigned int task_num) int num_tps = rte->rte_waypt_ct() - 2; if (num_tps < 0) { - fatal(MYNAME ": Empty task route\n"); + gbFatal("Empty task route\n"); } // See if the takeoff and landing waypoints are there or if we need to // generate them. @@ -747,9 +746,9 @@ void IgcFormat::wr_task_hdr(const route_head* rte, unsigned int task_num) num_tps--; } if (num_tps < 0) { - fatal(MYNAME ": Too few waypoints in task route\n"); + gbFatal("Too few waypoints in task route\n"); } else if (num_tps > 99) { - fatal(MYNAME ": Too much waypoints (more than 99) in task route.\n"); + gbFatal("Too much waypoints (more than 99) in task route.\n"); } // Gather data to write to the task identification (first) record gpsbabel::DateTime rte_time = wpt->GetCreationTime().isValid() ? wpt->GetCreationTime() : current_time(); @@ -809,7 +808,7 @@ void IgcFormat::wr_fix_record(const Waypoint* wpt, int pres_alt, int gnss_alt) { gpsbabel::DateTime tt = wpt->GetCreationTime(); if (!tt.isValid()) { - fatal(MYNAME ": Bad track timestamp\n"); + gbFatal("Bad track timestamp\n"); } if (unknown_alt == pres_alt) { @@ -853,7 +852,7 @@ int IgcFormat::correlate_tracks(const route_head* pres_track, const route_head* } while (alt_diff > -10.0); gpsbabel::DateTime pres_time = (*std::prev(wpt_rit))->GetCreationTime(); if (global_opts.debug_level >= 1) { - printf(MYNAME ": pressure landing time %s\n", CSTR(pres_time.toPrettyString())); + gbDebug("pressure landing time %s\n", CSTR(pres_time.toPrettyString())); } // Deduce the landing time from the GNSS altitude track based on @@ -872,17 +871,17 @@ int IgcFormat::correlate_tracks(const route_head* pres_track, const route_head* radtometers(gcdist(wpt->position(), (*wpt_rit)->position())) / (0.001 * deltat_msec); if (global_opts.debug_level >= 2) { - printf(MYNAME ": speed=%.2fm/s\n", speed); + gbDebug("speed=%.2fm/s\n", speed); } } while (speed < 2.5); gpsbabel::DateTime gnss_time = (*std::prev(wpt_rit))->GetCreationTime(); if (global_opts.debug_level >= 1) { - printf(MYNAME ": gnss landing time %s\n", CSTR(gnss_time.toPrettyString())); + gbDebug("gnss landing time %s\n", CSTR(gnss_time.toPrettyString())); } // Time adjustment is difference between the two estimated landing times int time_diff = gnss_time.secsTo(pres_time); if (15 * 60 < abs(time_diff)) { - warning(MYNAME ": excessive time adjustment %ds\n", time_diff); + gbWarning("excessive time adjustment %ds\n", time_diff); } return time_diff; } @@ -956,7 +955,7 @@ void IgcFormat::wr_track() time_adj = 0; } if (global_opts.debug_level >= 1) { - printf(MYNAME ": adjusting time by %ds\n", time_adj); + gbDebug("adjusting time by %ds\n", time_adj); } // Iterate through waypoints in both tracks simultaneously Interpolater interpolater; @@ -986,7 +985,7 @@ void IgcFormat::wr_track() void IgcFormat::wr_init(const QString& fname) { - file_out = gbfopen(fname, "wb", MYNAME); + file_out = gbfopen(fname, "wb"); } void IgcFormat::wr_deinit() diff --git a/igc.h b/igc.h index ff0ca964e..3a7b2f269 100644 --- a/igc.h +++ b/igc.h @@ -229,7 +229,7 @@ class IgcFormat : public Format ret = 1; break; default: - warning("igc.h: IgcFormat::get_ext_factor(): unknown extension (%i), returning factor of zero.\n",int(type)); + gbWarning("igc.h: IgcFormat::get_ext_factor(): unknown extension (%i), returning factor of zero.\n",int(type)); break; } return ret; @@ -454,7 +454,7 @@ struct igc_fsdata : public FormatSpecificData { ret = gfo; break; default: - fatal("igc.h: igc_fsdata::get_value(IgcFormat::igc_ext_type_t defn_type): Invalid igc_ext_type\n"); + gbFatal("igc.h: igc_fsdata::get_value(IgcFormat::igc_ext_type_t defn_type): Invalid igc_ext_type\n"); break; } return ret; @@ -494,7 +494,7 @@ struct igc_fsdata : public FormatSpecificData { ret = gfo; break; default: - fatal("igc.h: igc_fsdata::get_value(KmlFormat::wp_field defn_type): Invalid wp_field\n"); + gbFatal("igc.h: igc_fsdata::get_value(KmlFormat::wp_field defn_type): Invalid wp_field\n"); break; } return ret; diff --git a/inifile.cc b/inifile.cc index bae2d49ae..02e6e6ea0 100644 --- a/inifile.cc +++ b/inifile.cc @@ -18,7 +18,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -#include "defs.h" // for fatal, warning +#include "defs.h" // for gbFatal, gbWarning #include "inifile.h" #include "src/core/file.h" // for File #include // for QByteArray @@ -32,7 +32,6 @@ #include // for qEnvironmentVariable, qPrintable #include -#define MYNAME "inifile" struct inifile_t { QHash sections; @@ -77,7 +76,7 @@ open_gpsbabel_inifile() if (QFile(envstr).open(QIODevice::ReadOnly)) { return envstr; } - warning("WARNING: GPSBabel-inifile, defined in environment, NOT found!\n"); + gbWarning("WARNING: GPSBabel-inifile, defined in environment, NOT found!\n"); return res; } QString name = find_gpsbabel_inifile(""); // Check in current directory first. @@ -104,7 +103,7 @@ open_gpsbabel_inifile() } static void -inifile_load_file(QTextStream* stream, inifile_t* inifile, const char* myname) +inifile_load_file(QTextStream* stream, inifile_t* inifile) { QString buf; InifileSection section; @@ -125,8 +124,8 @@ inifile_load_file(QTextStream* stream, inifile_t* inifile, const char* myname) section_name = buf.mid(1, buf.indexOf(']') - 1).trimmed(); } if (section_name.isEmpty()) { - fatal("%s: invalid section header '%s' in '%s'.\n", myname, qPrintable(section_name), - qPrintable(inifile->source)); + gbFatal("invalid section header '%s' in '%s'.\n", gbLogCStr(section_name), + gbLogCStr(inifile->source)); } // form lowercase key to implement CaseInsensitive matching. @@ -135,8 +134,8 @@ inifile_load_file(QTextStream* stream, inifile_t* inifile, const char* myname) section = inifile->sections.value(section_name); } else { if (section.name.isEmpty()) { - fatal("%s: missing section header in '%s'.\n", myname, - qPrintable(inifile->source)); + gbFatal("missing section header in '%s'.\n", + gbLogCStr(inifile->source)); } // Store key in lower case to implement CaseInsensitive matching. @@ -170,12 +169,11 @@ inifile_find_value(const inifile_t* inifile, const QString& sec_name, const QStr /* inifile_init: reads inifile filename into memory - myname represents the calling module filename == NULL: try to open global gpsbabel.ini */ inifile_t* -inifile_init(const QString& filename, const char* myname) +inifile_init(const QString& filename) { QString name; @@ -197,7 +195,7 @@ inifile_init(const QString& filename, const char* myname) auto* result = new inifile_t; QFileInfo fileinfo(file); result->source = fileinfo.absoluteFilePath(); - inifile_load_file(&stream, result, myname); + inifile_load_file(&stream, result); file.close(); return result; diff --git a/inifile.h b/inifile.h index 4444ee184..885f4594b 100644 --- a/inifile.h +++ b/inifile.h @@ -30,9 +30,8 @@ struct inifile_t; // forward declare, opaque to users. /* inifile_init: reads inifile filename into memory - myname represents the calling module */ -inifile_t* inifile_init(const QString& filename, const char* myname); +inifile_t* inifile_init(const QString& filename); void inifile_done(inifile_t* inifile); bool inifile_has_section(const inifile_t* inifile, const QString& section); diff --git a/interpolate.cc b/interpolate.cc index 22b851e37..371153d39 100644 --- a/interpolate.cc +++ b/interpolate.cc @@ -36,12 +36,11 @@ #if FILTERS_ENABLED -#define MYNAME "Interpolate filter" void InterpolateFilter::process() { if ((opt_route && (route_count() == 0)) || (!opt_route && (track_count() == 0))) { - fatal(FatalMsg() << MYNAME ": Found no routes or tracks to operate on."); + gbFatal(FatalMsg() << "Found no routes or tracks to operate on."); } auto process_rte_lambda = [this](const route_head* rte)->void { @@ -86,7 +85,7 @@ void InterpolateFilter::process_rte(route_head* rte) double npts = 0; if (opt_time) { if (!timespan.has_value()) { - fatal(FatalMsg() << MYNAME ": points must have valid times to interpolate by time!"); + gbFatal(FatalMsg() << "points must have valid times to interpolate by time!"); } // interpolate even if time is running backwards. npts = std::abs(*timespan) / max_time_step; @@ -95,7 +94,7 @@ void InterpolateFilter::process_rte(route_head* rte) npts = distspan / max_dist_step; } if (!std::isfinite(npts) || (npts >= INT_MAX)) { - fatal(FatalMsg() << MYNAME ": interpolation interval too small!"); + gbFatal(FatalMsg() << "interpolation interval too small!"); } // Insert the required points @@ -143,23 +142,23 @@ void InterpolateFilter::process_rte(route_head* rte) void InterpolateFilter::init() { if (opt_time && opt_dist) { - fatal(FatalMsg() << MYNAME ": Can't interpolate on both time and distance."); + gbFatal(FatalMsg() << "Can't interpolate on both time and distance."); } else if (opt_time && opt_route) { - fatal(FatalMsg() << MYNAME ": Can't interpolate routes on time."); + gbFatal(FatalMsg() << "Can't interpolate routes on time."); } else if (opt_time) { max_time_step = 1000 * opt_time.get_result(); // milliseconds if (max_time_step <= 0) { - fatal(FatalMsg() << MYNAME ": interpolation time should be positive!"); + gbFatal(FatalMsg() << "interpolation time should be positive!"); } } else if (opt_dist) { - if (parse_distance(opt_dist, &max_dist_step, kMetersPerMile, MYNAME) == 0) { - fatal(FatalMsg() << MYNAME ": no distance specified with distance option!"); + if (parse_distance(opt_dist, &max_dist_step, kMetersPerMile) == 0) { + gbFatal(FatalMsg() << "no distance specified with distance option!"); } if (max_dist_step <= 0) { - fatal(FatalMsg() << MYNAME ": interpolation distance should be positive!"); + gbFatal(FatalMsg() << "interpolation distance should be positive!"); } } else { - fatal(FatalMsg() << MYNAME ": No interval specified."); + gbFatal(FatalMsg() << "No interval specified."); } } diff --git a/jeeps/gpsapp.cc b/jeeps/gpsapp.cc index e810c9f3c..46ef95409 100644 --- a/jeeps/gpsapp.cc +++ b/jeeps/gpsapp.cc @@ -356,7 +356,7 @@ static int32_t GPS_A000(const char* port) i = 0; } } - fatal("Failed to find a product inquiry response.\n"); + gbFatal("Failed to find a product inquiry response.\n"); } carry_on: diff --git a/jeeps/gpscom.cc b/jeeps/gpscom.cc index dcc56634d..522897a62 100644 --- a/jeeps/gpscom.cc +++ b/jeeps/gpscom.cc @@ -93,7 +93,7 @@ int32_t GPS_Command_Get_Waypoint(const char* port, GPS_PWay** way, pcb_fn cb) if (gps_category_transfer) { ret = GPS_A101_Get(port); if (!ret) { - fatal("blah"); + gbFatal("blah\n"); return PROTOCOL_ERROR; } @@ -1254,7 +1254,7 @@ int32_t GPS_Command_Send_Track_As_Course(const char* port, GPS_PTrack* trk, int3 continue; } if (wpt[i] == nullptr || ctk[j] == nullptr) { - fatal("Internal error in GPS_Command_Send_Track_As_Course"); + gbFatal("Internal error in GPS_Command_Send_Track_As_Course\n"); } dist = gcgeodist(wpt[i]->lat, wpt[i]->lon, ctk[j]->lat, ctk[j]->lon); if (dist < min_dist) { @@ -1265,7 +1265,7 @@ int32_t GPS_Command_Send_Track_As_Course(const char* port, GPS_PTrack* trk, int3 } if (wpt[i] == nullptr) { - fatal("Internal error in GPS_Command_Send_Track_As_Course: no wpt"); + gbFatal("Internal error in GPS_Command_Send_Track_As_Course: no wpt\n"); } cpt[i+n_cpt] = GPS_Course_Point_New(); strncpy(cpt[i+n_cpt]->name, wpt[i]->cmnt, diff --git a/jeeps/gpslibusb.cc b/jeeps/gpslibusb.cc index 80e6f0f1d..75813651a 100644 --- a/jeeps/gpslibusb.cc +++ b/jeeps/gpslibusb.cc @@ -90,11 +90,11 @@ gusb_libusb_send(const garmin_usb_packet* opkt, size_t sz) int ret = libusb_bulk_transfer(udev, gusb_bulk_out_ep, buf, sz, &transferred, TMOUT_B); if (ret != LIBUSB_SUCCESS) { - fatal("libusb_bulk_transfer failed. '%s'\n", + gbFatal("libusb_bulk_transfer failed. '%s'\n", libusb_strerror(static_cast(ret))); } if (transferred != (int) sz) { - warning("Bad cmdsend transferred %d sz %zu\n", transferred, sz); + gbWarning("Bad cmdsend transferred %d sz %zu\n", transferred, sz); } return transferred; @@ -141,7 +141,7 @@ gusb_teardown(gpsdevh* dh, bool exit_lib) if (udev != nullptr) { int ret = libusb_release_interface(udev, 0); if (ret != LIBUSB_SUCCESS) { - warning("libusb_release_interface failed: %s\n", + gbWarning("libusb_release_interface failed: %s\n", libusb_strerror(static_cast(ret))); } libusb_close(udev); @@ -238,7 +238,7 @@ gusb_reset_toggles() break; } if (t-- <= 0) { - fatal("Could not start session in a reasonable number of tries.\n"); + gbFatal("Could not start session in a reasonable number of tries.\n"); } } @@ -266,7 +266,7 @@ gusb_reset_toggles() return rv; } if (t-- <= 0) { - fatal("Could not start session in a reasonable number of tries.\n"); + gbFatal("Could not start session in a reasonable number of tries.\n"); } } return 0; @@ -283,7 +283,7 @@ garmin_usb_start(struct libusb_device* dev, } ret = libusb_open(dev, &udev); if (ret != LIBUSB_SUCCESS) { - fatal("libusb_open failed: %s\n", + gbFatal("libusb_open failed: %s\n", libusb_strerror(static_cast(ret))); } assert(udev != nullptr); @@ -297,7 +297,7 @@ garmin_usb_start(struct libusb_device* dev, // devices will work only the first time after a reset. ret = libusb_set_configuration(udev, 1); if (ret != LIBUSB_SUCCESS) { - fatal("libusb_set_configuration failed: %s\n", + gbFatal("libusb_set_configuration failed: %s\n", libusb_strerror(static_cast(ret))); } #endif @@ -312,17 +312,17 @@ garmin_usb_start(struct libusb_device* dev, * kernel driver that bonds with the hardware. */ usb_get_driver_np(udev, 0, drvnm, sizeof(drvnm)-1); - fatal("usb_set_configuration failed, probably because kernel driver '%s'\n is blocking our access to the USB device.\n" + gbFatal("usb_set_configuration failed, probably because kernel driver '%s'\n is blocking our access to the USB device.\n" "For more information see https://www.gpsbabel.org/os/Linux_Hotplug.html\n", drvnm); #else - fatal("usb_set_configuration failed: %s\n", usb_strerror()); + gbFatal("usb_set_configuration failed: %s\n", usb_strerror()); #endif } #endif ret = libusb_claim_interface(udev, 0); if (ret != LIBUSB_SUCCESS) { - fatal("libusb_claim_interface failed: %s\n", + gbFatal("libusb_claim_interface failed: %s\n", libusb_strerror(static_cast(ret))); } @@ -342,17 +342,17 @@ garmin_usb_start(struct libusb_device* dev, * * Rather than crash, we at least print * a nastygram. Experiments with retrying various USB ops brought - * no joy, so just call fatal and move on. + * no joy, so just call gbFatal and move on. */ struct libusb_config_descriptor* config; ret = libusb_get_active_config_descriptor(dev, &config); if (ret != LIBUSB_SUCCESS) { - fatal("libusb_get_active_config_descriptor failed: %s\n", + gbFatal("libusb_get_active_config_descriptor failed: %s\n", libusb_strerror(static_cast(ret))); } if (config == nullptr) { - fatal("Found USB device with no configuration.\n"); + gbFatal("Found USB device with no configuration.\n"); } for (int i = 0; i < config->bNumInterfaces; ++i) { @@ -421,7 +421,7 @@ garmin_usb_start(struct libusb_device* dev, return; } - fatal("Could not identify endpoints on USB device.\n" + gbFatal("Could not identify endpoints on USB device.\n" "Found endpoints Intr In 0x%x Bulk Out 0x%x Bulk In %0xx\n", gusb_intr_in_ep, gusb_bulk_out_ep, gusb_bulk_in_ep); } @@ -446,7 +446,7 @@ int garmin_usb_scan(libusb_unit_data* lud, int req_unit_number) struct libusb_device_descriptor desc; int ret = libusb_get_device_descriptor(devs[i], &desc); if (ret != LIBUSB_SUCCESS) { - fatal("libusb_get_device_descriptor failed: %s\n", + gbFatal("libusb_get_device_descriptor failed: %s\n", libusb_strerror(static_cast(ret))); } if ((desc.idVendor == GARMIN_VID) && @@ -475,9 +475,9 @@ int garmin_usb_scan(libusb_unit_data* lud, int req_unit_number) } if (0 == found_devices) { - fatal("Found no Garmin USB devices.\n"); + gbFatal("Found no Garmin USB devices.\n"); } else if (req_unit_number >= found_devices) { - fatal("usb unit number(%d) too high.\n" + gbFatal("usb unit number(%d) too high.\n" "The unit number must be either\n" "1) nonnegative and less than the number of garmin devices found(%d), or\n" "2) negative to list the garmin devices found.\n", @@ -501,7 +501,7 @@ gusb_init(const char* portname, gpsdevh** dh) // libusb_set_option(nullptr, LIBUSB_OPTION_LOG_LEVEL, 99); int ret = libusb_init(nullptr); if (ret != LIBUSB_SUCCESS) { - fatal("libusb_init failed: %s\n", + gbFatal("libusb_init failed: %s\n", libusb_strerror(static_cast(ret))); } libusb_successfully_initialized = true; diff --git a/jeeps/gpsmath.cc b/jeeps/gpsmath.cc index 69680c1b2..d7338a585 100644 --- a/jeeps/gpsmath.cc +++ b/jeeps/gpsmath.cc @@ -32,7 +32,7 @@ #include // for QString -#include "defs.h" // for case_ignore_strcmp, fatal, CSTR +#include "defs.h" // for case_ignore_strcmp, gbFatal, CSTR #include "jeeps/gpsdatum.h" // for GPS_ODatum, GPS_OEllipse, GPS_Datums, GPS_Ellipses, UKNG, GPS_SDatum_Alias, GPS_SDatum, GPS_DatumAliases, GPS_PDatum, GPS_PDatum_Alias static constexpr bool use_exact_helmert_inverse = false; @@ -1106,7 +1106,7 @@ int32_t GPS_Math_WGS84_To_ICS_EN(double lat, double lon, double* E, int32_t datum = GPS_Lookup_Datum_Index("Palestine 1923"); if (datum < 0) { - fatal("Unable to find Palestine 1923 in internal tables"); + gbFatal("Unable to find Palestine 1923 in internal tables\n"); } int32_t ellipse = GPS_Datums[datum].ellipse; @@ -1142,7 +1142,7 @@ void GPS_Math_ICS_EN_To_WGS84(double E, double N, double* lat, double* lon) double phi, lambda, alt, a, b; int32_t datum = GPS_Lookup_Datum_Index("Palestine 1923"); if (datum < 0) { - fatal("Unable to find Palestine 1923 in internal tables"); + gbFatal("Unable to find Palestine 1923 in internal tables\n"); } int32_t ellipse = GPS_Datums[datum].ellipse; diff --git a/jeeps/gpsserial.cc b/jeeps/gpsserial.cc index 6e20b5574..26cba541a 100644 --- a/jeeps/gpsserial.cc +++ b/jeeps/gpsserial.cc @@ -215,7 +215,7 @@ int32_t GPS_Serial_Write(gpsdevh* dh, const void* obuf, int size) } WriteFile(wsd->comport, obuf, size, &len, NULL); if (len != (DWORD) size) { - fatal("Write error. Wrote %d of %d bytes.\n", (int)len, size); + gbFatal("Write error. Wrote %d of %d bytes.\n", (int)len, size); } return len; } diff --git a/jeeps/gpsusbcommon.cc b/jeeps/gpsusbcommon.cc index 5c91c4760..ae363ccf7 100644 --- a/jeeps/gpsusbcommon.cc +++ b/jeeps/gpsusbcommon.cc @@ -93,7 +93,7 @@ gusb_cmd_get(garmin_usb_packet* ibuf, size_t sz) rv = gusb_llops->llop_get_bulk(ibuf, sz); break; default: - fatal("Unknown receiver state %d\n", receive_state); + gbFatal("Unknown receiver state %d\n", receive_state); } pkt_id = le_read16(&ibuf->gusb_pkt.pkt_id); @@ -236,7 +236,7 @@ gusb_id_unit(garmin_unit_info_t* gu) return; } } - fatal("Unable to sync with Garmin USB device in %d attempts.", i); + gbFatal("Unable to sync with Garmin USB device in %d attempts.\n", i); } void @@ -272,5 +272,5 @@ gusb_syncup() return; } } - fatal("Unable to establish USB syncup\n"); + gbFatal("Unable to establish USB syncup\n"); } diff --git a/jeeps/gpsusbwin.cc b/jeeps/gpsusbwin.cc index 6ed6e6854..3ee24b850 100644 --- a/jeeps/gpsusbwin.cc +++ b/jeeps/gpsusbwin.cc @@ -80,7 +80,7 @@ gusb_win_get(garmin_usb_packet* ibuf, size_t sz) if (!DeviceIoControl(usb_handle, IOCTL_GARMIN_USB_INTERRUPT_IN, NULL, 0, buf, GARMIN_USB_INTERRUPT_DATA_SIZE, &rxed, NULL)) { GPS_Serial_Error("Ioctl"); - fatal("ioctl\n"); + gbFatal("ioctl\n"); } buf += rxed; sz -= rxed; @@ -117,7 +117,7 @@ gusb_win_send(const garmin_usb_packet* opkt, size_t sz) WriteFile(usb_handle, obuf, sz, &rsz, NULL); if (rsz != sz) { - fatal("Error sending %zu bytes. Successfully sent %ld\n", sz, rsz); + gbFatal("Error sending %zu bytes. Successfully sent %ld\n", sz, rsz); } return rsz; @@ -155,14 +155,14 @@ HANDLE garmin_usb_start(HDEVINFO hdevinfo, SP_DEVICE_INTERFACE_DATA* infodata) pdd->DevicePath); if (usb_handle != INVALID_HANDLE_VALUE) { - fatal("garmin_usb_start called while device already started.\n"); + gbFatal("garmin_usb_start called while device already started.\n"); } usb_handle = CreateFile(pdd->DevicePath, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (usb_handle == INVALID_HANDLE_VALUE) { if (GetLastError() == ERROR_ACCESS_DENIED) { - warning( + gbWarning( "Exclusive access is denied. It's likely that something else such as\n" "Garmin Lifetime Updater, Communicator, Basecamp, Nroute, Spanner,\n" "Google Earth, or GPSGate already has control of the device\n"); @@ -174,7 +174,7 @@ HANDLE garmin_usb_start(HDEVINFO hdevinfo, SP_DEVICE_INTERFACE_DATA* infodata) if (!DeviceIoControl(usb_handle, IOCTL_GARMIN_USB_BULK_OUT_PACKET_SIZE, NULL, 0, &usb_tx_packet_size, GARMIN_USB_INTERRUPT_DATA_SIZE, &size, NULL)) { - fatal("Couldn't get USB packet size.\n"); + gbFatal("Couldn't get USB packet size.\n"); } win_llops.max_tx_size = usb_tx_packet_size; @@ -215,7 +215,7 @@ gusb_init(const char* pname, gpsdevh** dh) if (hdevinfo == INVALID_HANDLE_VALUE) { GPS_Serial_Error("SetupDiGetClassDevs failed"); - warning("Is the Garmin USB driver installed?\n"); + gbWarning("Is the Garmin USB driver installed?\n"); return 0; } @@ -226,7 +226,7 @@ gusb_init(const char* pname, gpsdevh** dh) &GARMIN_GUID, req_unit_number, &devinterface)) { GPS_Serial_Error("SetupDiEnumDeviceInterfaces"); - warning("Is the Garmin USB unit number %d powered up and connected?\nIs it really a USB unit? If it's serial, don't choose USB, choose serial.\nAre the Garmin USB drivers installed and functioning with other programs?\nIs it a storage based device like Nuvi, CO, or OR?\n If so, send GPX files to it, don't use this module.\n", un); + gbWarning("Is the Garmin USB unit number %d powered up and connected?\nIs it really a USB unit? If it's serial, don't choose USB, choose serial.\nAre the Garmin USB drivers installed and functioning with other programs?\nIs it a storage based device like Nuvi, CO, or OR?\n If so, send GPX files to it, don't use this module.\n", un); return 0; } /* We've matched. Now start the specific unit. */ @@ -247,7 +247,7 @@ gusb_init(const char* pname, gpsdevh** dh) } else { GPS_Serial_Error("SetupDiEnumDeviceInterfaces"); - warning("Is the Garmin USB unit number %d powered up and connected?\n", un); + gbWarning("Is the Garmin USB unit number %d powered up and connected?\n", un); return 0; } } diff --git a/kml.cc b/kml.cc index cce73048c..00e708d8d 100644 --- a/kml.cc +++ b/kml.cc @@ -23,7 +23,7 @@ #include "kml.h" #include // for fabs -#include // for sscanf, printf +#include // for sscanf, EOF #include // for optional #include // for tuple, make_tuple @@ -66,7 +66,6 @@ #define ICON_MULTI_TRK ICON_BASE "track-directional/track-0.png" #define ICON_DIR ICON_BASE "track-directional/track-%1.png" // format string where next arg is rotational degrees. -#define MYNAME "kml" const QStringList KmlFormat::kml_tags_to_ignore = { "kml", @@ -122,7 +121,7 @@ void KmlFormat::kml_step_color() // Note that color_seq may be outside this range if the cast from float to int fails. int color_seq = static_cast(kml_color_sequencer.seq) % (kml_color_limit * 6); if (global_opts.debug_level >= 1) { - printf(MYNAME ": kml_color_sequencer seq %f %d, step %f\n", kml_color_sequencer.seq, color_seq, kml_color_sequencer.step); + gbDebug("kml_color_sequencer seq %f %d, step %f\n", kml_color_sequencer.seq, color_seq, kml_color_sequencer.step); } if ((color_seq >= (0*kml_color_limit)) && (color_seq < (1*kml_color_limit))) { kml_color_sequencer.color.bbggrr = kml_bgr_to_color(0, color_seq, kml_color_limit); @@ -137,7 +136,7 @@ void KmlFormat::kml_step_color() } else if ((color_seq >= (5*kml_color_limit)) && (color_seq < (6*kml_color_limit))) { kml_color_sequencer.color.bbggrr = kml_bgr_to_color(6*kml_color_limit-color_seq, 0, kml_color_limit); } else { // should not occur, but to be safe generate a legal color. - warning(MYNAME ": Error in color conversion - using default color.\n"); + gbWarning("Error in color conversion - using default color.\n"); kml_color_sequencer.color.bbggrr = kml_bgr_to_color(102, 102, 102); } // compute next color. @@ -147,7 +146,7 @@ void KmlFormat::kml_step_color() void KmlFormat::wpt_s(const QString& /*args*/, const QXmlStreamAttributes* /*attrs*/) { if (wpt_tmp) { - fatal(MYNAME ": wpt_s: invalid kml file\n"); + gbFatal("wpt_s: invalid kml file\n"); } wpt_tmp = new Waypoint; wpt_tmp_queued = false; @@ -161,7 +160,7 @@ void KmlFormat::wpt_s(const QString& /*args*/, const QXmlStreamAttributes* /*att void KmlFormat::wpt_e(const QString& /*args*/, const QXmlStreamAttributes* /*attrs*/) { if (!wpt_tmp) { - fatal(MYNAME ": wpt_e: invalid kml file\n"); + gbFatal("wpt_e: invalid kml file\n"); } if (wpt_tmp_queued) { waypt_add(wpt_tmp); @@ -176,7 +175,7 @@ void KmlFormat::wpt_e(const QString& /*args*/, const QXmlStreamAttributes* /*att void KmlFormat::wpt_name(const QString& args, const QXmlStreamAttributes* /*attrs*/) { if (!wpt_tmp) { - fatal(MYNAME ": wpt_name: invalid kml file\n"); + gbFatal("wpt_name: invalid kml file\n"); } wpt_tmp->shortname = args; } @@ -184,7 +183,7 @@ void KmlFormat::wpt_name(const QString& args, const QXmlStreamAttributes* /*attr void KmlFormat::wpt_desc(const QString& args, const QXmlStreamAttributes* /*attrs*/) { if (!wpt_tmp) { - fatal(MYNAME ": wpt_desc: invalid kml file\n"); + gbFatal("wpt_desc: invalid kml file\n"); } wpt_tmp->description += args.trimmed(); } @@ -192,7 +191,7 @@ void KmlFormat::wpt_desc(const QString& args, const QXmlStreamAttributes* /*attr void KmlFormat::wpt_time(const QString& args, const QXmlStreamAttributes* /*attrs*/) { if (!wpt_tmp) { - fatal(MYNAME ": wpt_time: invalid kml file\n"); + gbFatal("wpt_time: invalid kml file\n"); } wpt_tmp->SetCreationTime(xml_parse_time(args)); } @@ -255,7 +254,7 @@ void KmlFormat::trk_coord(const QString& args, const QXmlStreamAttributes* /*att trkpt->latitude = coords[1].toDouble(); trkpt->longitude = coords[0].toDouble(); } else { - Warning() << MYNAME << ": malformed coordinates " << vec; + Warning() << "malformed coordinates " << vec; } track_add_wpt(trk_head, trkpt); } @@ -275,7 +274,7 @@ void KmlFormat::trk_coord(const QString& args, const QXmlStreamAttributes* /*att if (!trk_head->rte_waypt_empty()) { qint64 timespan_ms = wpt_timespan_begin.msecsTo(wpt_timespan_end); if (trk_head->rte_waypt_ct() < 2) { - fatal(MYNAME ": attempt to interpolate TimeSpan with too few points."); + gbFatal("attempt to interpolate TimeSpan with too few points.\n"); } qint64 ms_per_waypoint = timespan_ms / (trk_head->rte_waypt_ct() - 1); foreach (Waypoint* trackpoint, trk_head->waypoint_list) { @@ -307,7 +306,7 @@ void KmlFormat::gx_trk_e(const QString& /*args*/, const QXmlStreamAttributes* /* // Check that for every temporal value (kml:when) in a kml:Track there is a position (kml:coord) value. // Check that for every temporal value (kml:when) in a gx:Track there is a position (gx:coord) value. if (gx_trk_times->size() != gx_trk_coords->size()) { - fatal(MYNAME ": There were more coord elements than the number of when elements.\n"); + gbFatal("There were more coord elements than the number of when elements.\n"); } // In KML 2.3 kml:Track elements kml:coord and kml:when elements are not required to be in any order. @@ -346,7 +345,7 @@ void KmlFormat::gx_trk_e(const QString& /*args*/, const QXmlStreamAttributes* /* void KmlFormat::gx_trk_when(const QString& args, const QXmlStreamAttributes* /*attrs*/) { if (! gx_trk_times) { - fatal(MYNAME ": gx_trk_when: invalid kml file\n"); + gbFatal("gx_trk_when: invalid kml file\n"); } gx_trk_times->append(xml_parse_time(args)); } @@ -354,7 +353,7 @@ void KmlFormat::gx_trk_when(const QString& args, const QXmlStreamAttributes* /*a void KmlFormat::gx_trk_coord(const QString& args, const QXmlStreamAttributes* /*attrs*/) { if (! gx_trk_coords) { - fatal(MYNAME ": gx_trk_coord: invalid kml file\n"); + gbFatal("gx_trk_coord: invalid kml file\n"); } double lat; @@ -362,7 +361,7 @@ void KmlFormat::gx_trk_coord(const QString& args, const QXmlStreamAttributes* /* double alt; int n = sscanf(CSTR(args), "%lf %lf %lf", &lon, &lat, &alt); if (EOF != n && 2 != n && 3 != n) { - fatal(MYNAME ": coord field decode failure on \"%s\".\n", qPrintable(args)); + gbFatal("coord field decode failure on \"%s\".\n", gbLogCStr(args)); } gx_trk_coords->append(std::make_tuple(n, lat, lon, alt)); } @@ -407,7 +406,7 @@ void KmlFormat::wr_init(const QString& fname) unitsformatter->setunits(UnitsFormatter::units_t::aviation); break; default: - fatal("Units argument '%s' should be 's' for statute units, 'm' for metric, 'n' for nautical or 'a' for aviation.\n", qPrintable(opt_units)); + gbFatal("Units argument '%s' should be 's' for statute units, 'm' for metric, 'n' for nautical or 'a' for aviation.\n", gbLogCStr(opt_units)); break; } /* @@ -545,7 +544,7 @@ void KmlFormat::kml_write_bitmap_style(kml_point_type pt_type, const QString& bi force_heading = true; break; default: - fatal("kml_output_point: unknown point type"); + gbFatal("kml_output_point: unknown point type\n"); break; } @@ -860,7 +859,7 @@ void KmlFormat::kml_output_point(const Waypoint* waypointp, kml_point_type pt_ty style = "#route"; break; default: - fatal("kml_output_point: unknown point type"); + gbFatal("kml_output_point: unknown point type\n"); break; } @@ -1226,7 +1225,7 @@ QString KmlFormat::kml_gc_mkstar(int rating) QString star_content; if (rating < 0 || rating > 50 || rating % 5 != 0) { - fatal("Bogus difficulty or terrain rating."); + gbFatal("Bogus difficulty or terrain rating.\n"); } if (0 == rating % 10) { @@ -1508,7 +1507,7 @@ void KmlFormat::kml_mt_simple_array(const route_head* header, writer->writeStartElement(QStringLiteral("gx:SimpleArrayData")); writer->writeAttribute(QStringLiteral("name"), name); if (global_opts.debug_level >= 3) { - printf(MYNAME ": New KML SimpleArray: %s\n", qPrintable(name)); + gbDebug("New KML SimpleArray: %s\n", gbLogCStr(name)); } foreach (const Waypoint* wpt, header->waypoint_list) { const auto* fs_igc = reinterpret_cast(wpt->fs.FsChainFind(kFsIGC)); @@ -1550,20 +1549,20 @@ void KmlFormat::kml_mt_simple_array(const route_head* header, if (fs_igc && fs_igc->get_value(member).has_value()) { double value = fs_igc->get_value(member).value(); if (global_opts.debug_level >= 6) { - printf(MYNAME ": Writing KML SimpleArray data: %s of %f\n", qPrintable(name), value); + gbDebug("Writing KML SimpleArray data: %s of %f\n", gbLogCStr(name), value); } writer->writeTextElement(QStringLiteral("gx:value"), QString::number(value)); // No igc_fsdata present, but we still need to write out the SimpleArray. // This can happen when merging tracks with different sets of IGC extensions. } else { if (global_opts.debug_level >= 7) { - printf(MYNAME ": Writing empty KML SimpleArray data for %s\n", qPrintable(name)); + gbDebug("Writing empty KML SimpleArray data for %s\n", gbLogCStr(name)); } writer->writeTextElement(QStringLiteral("gx:value"), QString()); } break; default: - fatal("Bad member type"); + gbFatal("Bad member type\n"); } } writer->writeEndElement(); // Close SimpleArrayData tag diff --git a/lowranceusr.cc b/lowranceusr.cc index cdf1b1e27..27c2b29d2 100644 --- a/lowranceusr.cc +++ b/lowranceusr.cc @@ -89,7 +89,7 @@ #include // for PRId64 #include // for round, atan, exp, log, tan -#include // for printf, sprintf, SEEK_CUR +#include // for SEEK_CUR #include // for int64_t #include // for abs #include // for pi @@ -118,8 +118,6 @@ /* from waypt.c, we need to iterate over waypoints when extracting routes */ extern WaypointList* global_waypoint_list; -#define MYNAME "Lowrance USR" - /* below couple of functions mostly borrowed from raymarine.c */ /* make waypoint shortnames unique */ @@ -133,7 +131,7 @@ LowranceusrFormat::same_points(const Waypoint* A, const Waypoint* B) } void -LowranceusrFormat::register_waypt(const Waypoint* wpt) const +LowranceusrFormat::register_waypt(const Waypoint* wpt) { for (const Waypoint* cmp : std::as_const(*waypt_table)) { if (same_points(wpt, cmp)) { @@ -142,8 +140,8 @@ LowranceusrFormat::register_waypt(const Waypoint* wpt) const } if (global_opts.debug_level >= 2) { - printf(MYNAME " adding waypt %s (%s) to table at index %s\n", - qPrintable(wpt->shortname), qPrintable(wpt->description), QByteArray::number(waypt_table->size()).constData()); + gbDebug("adding waypt %s (%s) to table at index %s\n", + gbLogCStr(wpt->shortname), gbLogCStr(wpt->description), QByteArray::number(waypt_table->size()).constData()); } waypt_table->append(wpt); @@ -166,7 +164,7 @@ LowranceusrFormat::lowranceusr4_find_waypt(uint uid_unit, int uid_seq_low, int u } if (global_opts.debug_level >= 1) { - printf(MYNAME " lowranceusr4_find_waypt: warning, failed finding waypoint with ids %u %d %d\n", + gbDebug("lowranceusr4_find_waypt: warning, failed finding waypoint with ids %u %d %d\n", uid_unit, uid_seq_low, uid_seq_high); } return nullptr; @@ -188,7 +186,7 @@ LowranceusrFormat::lowranceusr4_find_global_waypt(uint id1, uint id2, uint id3, } if (global_opts.debug_level >= 1) { - printf(MYNAME " lowranceusr4_find_global_waypt: warning, failed finding waypoint with ids %08x %08x %08x %08x\n", + gbDebug("lowranceusr4_find_global_waypt: warning, failed finding waypoint with ids %08x %08x %08x %08x\n", id1, id2, id3, id4); } return nullptr; @@ -329,7 +327,7 @@ LowranceusrFormat::lowranceusr4_find_index_from_icon_desc_and_color_desc(const Q void LowranceusrFormat::rd_init(const QString& fname) { - file_in = gbfopen_le(fname, "rb", MYNAME); + file_in = gbfopen_le(fname, "rb"); utf16le_codec = QTextCodec::codecForName("UTF-16LE"); } @@ -343,12 +341,12 @@ LowranceusrFormat::rd_deinit() void LowranceusrFormat::wr_init(const QString& fname) { - file_out = gbfopen_le(fname, "wb", MYNAME); + file_out = gbfopen_le(fname, "wb"); mkshort_handle = new MakeShort; waypt_out_count = 0; writing_version = opt_wversion.get_result(); if ((writing_version < 2) || (writing_version > 4)) { - fatal(MYNAME " wversion value %s is not supported !!\n", qPrintable(opt_wversion)); + gbFatal("wversion value %s is not supported !!\n", gbLogCStr(opt_wversion)); } utf16le_codec = QTextCodec::codecForName("UTF-16LE"); waypt_table = new QList; @@ -394,13 +392,13 @@ LowranceusrFormat::lat_deg_to_mm(double x) } void -LowranceusrFormat::lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_present) const +LowranceusrFormat::lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_present) { /* Object num */ if (object_num_present) { short object_num = gbfgetint16(file_in); if (global_opts.debug_level == 99) { - printf(MYNAME " parse_waypt: %5d", object_num); + gbDebug("parse_waypt: %5d", object_num); } } @@ -436,23 +434,23 @@ LowranceusrFormat::lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_pre if (global_opts.debug_level > 1) { if (global_opts.debug_level == 99) { if (wpt_tmp->shortname.length() > 16) { - printf(" %.13s...", qPrintable(wpt_tmp->shortname)); + gbDebug(" %.13s...", gbLogCStr(wpt_tmp->shortname)); } else { - printf(" %16.16s", qPrintable(wpt_tmp->shortname)); + gbDebug(" %16.16s", gbLogCStr(wpt_tmp->shortname)); } - printf(" %+15.10f %+15.10f", wpt_tmp->latitude, wpt_tmp->longitude); + gbDebug(" %+15.10f %+15.10f", wpt_tmp->latitude, wpt_tmp->longitude); if (wpt_tmp->altitude == unknown_alt) { - printf(" %13s", "UNKNOWN ALT"); + gbDebug(" %13s", "UNKNOWN ALT"); } else { - printf(" %5d %7.1f", (int)METERS_TO_FEET(wpt_tmp->altitude), wpt_tmp->altitude); + gbDebug(" %5d %7.1f", (int)METERS_TO_FEET(wpt_tmp->altitude), wpt_tmp->altitude); } } else { - printf(MYNAME " parse_waypt: Waypt name = '%s' Lat = %+f Lon = %+f alt = ", - qPrintable(wpt_tmp->shortname), wpt_tmp->latitude, wpt_tmp->longitude); + gbDebug("parse_waypt: Waypt name = '%s' Lat = %+f Lon = %+f alt = ", + gbLogCStr(wpt_tmp->shortname), wpt_tmp->latitude, wpt_tmp->longitude); if (wpt_tmp->altitude == unknown_alt) { - printf("UNKNOWN ALT\n"); + gbDebug("UNKNOWN ALT\n"); } else { - printf("%d (%f)\n", (int)METERS_TO_FEET(wpt_tmp->altitude), wpt_tmp->altitude); + gbDebug("%d (%f)\n", (int)METERS_TO_FEET(wpt_tmp->altitude), wpt_tmp->altitude); } } } @@ -472,10 +470,10 @@ LowranceusrFormat::lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_pre if (global_opts.debug_level > 2) { if (global_opts.debug_level == 99) { - printf(" '%s'", qPrintable(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss"))); + gbDebug(" '%s'", gbLogCStr(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss"))); } else { - printf(MYNAME " parse_waypt: creation time '%s', waypt_time %" PRId64 "\n", - qPrintable(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss")), waypt_time); + gbDebug("parse_waypt: creation time '%s', waypt_time %" PRId64 "\n", + gbLogCStr(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss")), waypt_time); } } @@ -486,7 +484,7 @@ LowranceusrFormat::lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_pre icon_number = gbfgetint32(file_in); } if (global_opts.debug_level == 99) { - printf(" %08x (%d)", icon_number, icon_number); + gbDebug(" %08x (%d)", icon_number, icon_number); } wpt_tmp->icon_descr = lowranceusr_find_desc_from_icon_number(icon_number); @@ -494,9 +492,9 @@ LowranceusrFormat::lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_pre short waypt_type = gbfgetint16(file_in); if (global_opts.debug_level > 2) { if (global_opts.debug_level == 99) { - printf(" %04x (%d)", (int)waypt_type, (int)waypt_type); + gbDebug(" %04x (%d)", (int)waypt_type, (int)waypt_type); } else { - printf(MYNAME " parse_waypt: waypt_type = %d\n",waypt_type); + gbDebug("parse_waypt: waypt_type = %d\n",waypt_type); } } @@ -506,22 +504,22 @@ LowranceusrFormat::lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_pre if (std::abs(depth_feet - 99999.0) > .1) { wpt_tmp->set_depth(FEET_TO_METERS(depth_feet)); if (global_opts.debug_level == 99) { - printf(" %10.1f", depth_feet); + gbDebug(" %10.1f", depth_feet); } } else { if (global_opts.debug_level == 99) { - printf(" UNKNOWN"); + gbDebug(" UNKNOWN"); } } } if (global_opts.debug_level == 99) { - printf("\n"); + gbDebug("\n"); } } void -LowranceusrFormat::lowranceusr4_parse_waypt(Waypoint* wpt_tmp) const +LowranceusrFormat::lowranceusr4_parse_waypt(Waypoint* wpt_tmp) { auto* fsdata = new lowranceusr4_fsdata; wpt_tmp->fs.FsChainAdd(fsdata); @@ -606,37 +604,37 @@ LowranceusrFormat::lowranceusr4_parse_waypt(Waypoint* wpt_tmp) const if (global_opts.debug_level > 1) { if (global_opts.debug_level == 99) { - printf(MYNAME " parse_waypoints: "); + gbDebug("parse_waypoints: "); if (reading_version > 4) { - printf("%08x %08x %08x %08x ", + gbDebug("%08x %08x %08x %08x ", fsdata->UUID1, fsdata->UUID2, fsdata->UUID3, fsdata->UUID4); } - printf(" %10u %8d %8d %8d %6s", + gbDebug(" %10u %8d %8d %8d %6s", fsdata->uid_unit, fsdata->uid_seq_low, fsdata->uid_seq_high, waypoint_version, QByteArray::number(name.length()).constData()); if (name.length() > 16) { - printf(" %13.13s...", qPrintable(name)); + gbDebug(" %13.13s...", gbLogCStr(name)); } else { - printf(" %16.16s", qPrintable(name)); + gbDebug(" %16.16s", gbLogCStr(name)); } if (reading_version > 4) { - printf(" %10u ", fsdata->uid_unit2); + gbDebug(" %10u ", fsdata->uid_unit2); } - printf(" %+15.10f %+15.10f", wpt_tmp->longitude, wpt_tmp->latitude); - printf(" %08x %4d %4d %7s", fsdata->flags, fsdata->icon_num, fsdata->color, - (fsdata->color_desc == nullptr ? "unk" : qPrintable(fsdata->color_desc))); + gbDebug(" %+15.10f %+15.10f", wpt_tmp->longitude, wpt_tmp->latitude); + gbDebug(" %08x %4d %4d %7s", fsdata->flags, fsdata->icon_num, fsdata->color, + (fsdata->color_desc == nullptr ? "unk" : gbLogCStr(fsdata->color_desc))); if (desc.length() > 16) { - printf(" %6s %.13s...", QByteArray::number(desc.length()).constData(), qPrintable(desc)); + gbDebug(" %6s %.13s...", QByteArray::number(desc.length()).constData(), gbLogCStr(desc)); } else { - printf(" %6s %16s", QByteArray::number(desc.length()).constData(), qPrintable(desc)); + gbDebug(" %6s %16s", QByteArray::number(desc.length()).constData(), gbLogCStr(desc)); } - printf(" '%s'", qPrintable(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss"))); - printf(" %08x %8.3f %08x %08x %08x\n", + gbDebug(" '%s'", gbLogCStr(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss"))); + gbDebug(" %08x %8.3f %08x %08x %08x\n", unused_byte, fsdata->depth, loran_GRI, loran_Tda, loran_Tdb); } else { - printf(MYNAME " parse_waypoints: version = %d, name = %s, uid_unit = %u, " + gbDebug("parse_waypoints: version = %d, name = %s, uid_unit = %u, " "uid_seq_low = %d, uid_seq_high = %d, lat = %+.10f, lon = %+.10f, depth = %f\n", - waypoint_version, qPrintable(wpt_tmp->shortname), fsdata->uid_unit, + waypoint_version, gbLogCStr(wpt_tmp->shortname), fsdata->uid_unit, fsdata->uid_seq_low, fsdata->uid_seq_high, wpt_tmp->longitude, wpt_tmp->latitude, fsdata->depth); } @@ -644,7 +642,7 @@ LowranceusrFormat::lowranceusr4_parse_waypt(Waypoint* wpt_tmp) const } void -LowranceusrFormat::lowranceusr_parse_waypts() const +LowranceusrFormat::lowranceusr_parse_waypts() { int NumWaypoints; @@ -657,51 +655,51 @@ LowranceusrFormat::lowranceusr_parse_waypts() const } if (global_opts.debug_level >= 1) { - printf(MYNAME " parse_waypts: Num Waypoints = %d\n", NumWaypoints); + gbDebug("parse_waypts: Num Waypoints = %d\n", NumWaypoints); } if (global_opts.debug_level == 99) { if (reading_version > 3) { - printf(MYNAME " parse_waypts: "); + gbDebug("parse_waypts: "); if (reading_version > 4) { - printf("Universal ID "); + gbDebug("Universal ID "); } - printf(" Sequence Number Stream Waypoint\n"); + gbDebug(" Sequence Number Stream Waypoint\n"); - printf(MYNAME " parse_waypoints: "); + gbDebug("parse_waypoints: "); if (reading_version > 4) { - printf(" ID1 ID2 ID3 ID4 "); + gbDebug(" ID1 ID2 ID3 ID4 "); } - printf("Unit Number Low High Version Length Name "); + gbDebug("Unit Number Low High Version Length Name "); if (reading_version > 4) { - printf(" Unit Number2"); + gbDebug(" Unit Number2"); } - printf(" Latitude Longitude Flags ICON Color Length Description "); - printf(" Date Time Unknown Depth LoranGRI LoranTda LoranTdb\n"); + gbDebug(" Latitude Longitude Flags ICON Color Length Description "); + gbDebug(" Date Time Unknown Depth LoranGRI LoranTda LoranTdb\n"); - printf(MYNAME " parse_waypoints: "); + gbDebug("parse_waypoints: "); if (reading_version > 4) { - printf("-------- -------- -------- -------- "); + gbDebug("-------- -------- -------- -------- "); } - printf("----------- -------- -------- -------- ------ ----------------"); + gbDebug("----------- -------- -------- -------- ------ ----------------"); if (reading_version > 4) { - printf(" ------------"); + gbDebug(" ------------"); } - printf(" --------------- --------------- -------- ---- ------------ ------ ----------------"); - printf(" ---------- ----- -------- -------- -------- -------- --------\n"); + gbDebug(" --------------- --------------- -------- ---- ------------ ------ ----------------"); + gbDebug(" ---------- ----- -------- -------- -------- -------- --------\n"); } else { - printf(MYNAME " parse_waypts: Number Name Longitude Latitude Altitude Time "); - printf(" ICON ID (dec) Flag (dec)"); + gbDebug("parse_waypts: Number Name Longitude Latitude Altitude Time "); + gbDebug(" ICON ID (dec) Flag (dec)"); if (reading_version == 3) { - printf(" Depth (ft)"); + gbDebug(" Depth (ft)"); } - printf("\n"); - printf(MYNAME " parse_waypts: ------ --------------- --------------- -------------- -------------- ----------------"); - printf(" ---------------- ----------"); + gbDebug("\n"); + gbDebug("parse_waypts: ------ --------------- --------------- -------------- -------------- ----------------"); + gbDebug(" ---------------- ----------"); if (reading_version == 3) { - printf(" ----------"); + gbDebug(" ----------"); } - printf("\n"); + gbDebug("\n"); } } @@ -719,14 +717,14 @@ LowranceusrFormat::lowranceusr_parse_waypts() const lowranceusr4_parse_waypt(wpt_tmp); break; default: - Warning() << MYNAME << ": Unknown internal version " << reading_version; + Warning() << "Unknown internal version " << reading_version; } waypt_add(wpt_tmp); } } void -LowranceusrFormat::lowranceusr_parse_route() const +LowranceusrFormat::lowranceusr_parse_route() { /* route name */ QString name = lowranceusr4_readstr(file_in, 1); @@ -738,25 +736,25 @@ LowranceusrFormat::lowranceusr_parse_route() const short num_legs = gbfgetint16(file_in); if (global_opts.debug_level > 1) { - printf(MYNAME " parse_route: Route '%s', Num Legs = %d", qPrintable(name), num_legs); + gbDebug("parse_route: Route '%s', Num Legs = %d", gbLogCStr(name), num_legs); } /* route reversed */ char reversed = gbfgetc(file_in); if (global_opts.debug_level > 1) { - printf(", reversed '%x' - %s\n", reversed, (reversed ? "Yes" : "No")); + gbDebug(", reversed '%x' - %s\n", reversed, (reversed ? "Yes" : "No")); } if (global_opts.debug_level == 99) { - printf(MYNAME " parse_route: Name Longitude Latitude Altitude Time Unknown ICON ID (dec) Flag (dec) Depth (ft)\n"); - printf(MYNAME " parse_route: --------------- --------------- -------------- ------------- ---------------- -------- ---------------- ---------- ----------\n"); + gbDebug("parse_route: Name Longitude Latitude Altitude Time Unknown ICON ID (dec) Flag (dec) Depth (ft)\n"); + gbDebug("parse_route: --------------- --------------- -------------- ------------- ---------------- -------- ---------------- ---------- ----------\n"); } /* waypoints */ for (int j = 0; j < num_legs; j++) { auto* wpt_tmp = new Waypoint; if (global_opts.debug_level == 99) { - printf(MYNAME " parse_route:"); + gbDebug("parse_route:"); } lowranceusr_parse_waypt(wpt_tmp, 0); /* Indicate object number missing */ route_add_wpt(rte_head, wpt_tmp); @@ -764,7 +762,7 @@ LowranceusrFormat::lowranceusr_parse_route() const } void -LowranceusrFormat::lowranceusr4_parse_route() const +LowranceusrFormat::lowranceusr4_parse_route() { int UUID1 = 0; int UUID2 = 0; @@ -785,7 +783,7 @@ LowranceusrFormat::lowranceusr4_parse_route() const /* UID unit number */ fsdata->uid_unit = gbfgetint32(file_in); if (global_opts.debug_level > 1) { - printf(MYNAME " parse_route: Unit %u (0x%08x)\n", fsdata->uid_unit, fsdata->uid_unit); + gbDebug("parse_route: Unit %u (0x%08x)\n", fsdata->uid_unit, fsdata->uid_unit); } /* 64-bit UID sequence number */ @@ -795,7 +793,7 @@ LowranceusrFormat::lowranceusr4_parse_route() const /* Route stream version number */ int route_version = gbfgetint16(file_in); if (global_opts.debug_level > 1) { - printf(MYNAME " parse_route: Version = %d\n", route_version); + gbDebug("parse_route: Version = %d\n", route_version); } /* Route name; input is 2 bytes per char, we convert to 1 */ @@ -813,11 +811,11 @@ LowranceusrFormat::lowranceusr4_parse_route() const if (global_opts.debug_level > 1) { if (reading_version >= 5) { - printf(MYNAME " parse_route: route '%s' (UUID %08x %08x %8x %08x) has %d legs\n", - qPrintable(rte_head->rte_name), UUID1, UUID2, UUID3, UUID4, num_legs); + gbDebug("parse_route: route '%s' (UUID %08x %08x %8x %08x) has %d legs\n", + gbLogCStr(rte_head->rte_name), UUID1, UUID2, UUID3, UUID4, num_legs); } else { - printf(MYNAME " parse_route: route '%s' has %d legs\n", - qPrintable(rte_head->rte_name), num_legs); + gbDebug("parse_route: route '%s' has %d legs\n", + gbLogCStr(rte_head->rte_name), num_legs); } } @@ -830,8 +828,8 @@ LowranceusrFormat::lowranceusr4_parse_route() const const Waypoint* wpt_tmp = lowranceusr4_find_waypt(uid_unit, uid_seq_low, uid_seq_high); if (wpt_tmp) { if (global_opts.debug_level >= 2) { - printf(MYNAME " parse_route: added leg #%d routepoint %s (%+.10f, %+.10f)\n", - j, qPrintable(wpt_tmp->shortname), wpt_tmp->longitude, wpt_tmp->latitude); + gbDebug("parse_route: added leg #%d routepoint %s (%+.10f, %+.10f)\n", + j, gbLogCStr(wpt_tmp->shortname), wpt_tmp->longitude, wpt_tmp->latitude); } route_add_wpt(rte_head, new Waypoint(*wpt_tmp)); } @@ -846,8 +844,8 @@ LowranceusrFormat::lowranceusr4_parse_route() const const Waypoint* wpt_tmp = lowranceusr4_find_global_waypt(UUID1, UUID2, UUID3, UUID4); if (wpt_tmp) { if (global_opts.debug_level >= 2) { - printf(MYNAME " parse_route: added leg #%d routepoint %s (%+.10f, %+.10f)\n", - j, qPrintable(wpt_tmp->shortname), wpt_tmp->longitude, wpt_tmp->latitude); + gbDebug("parse_route: added leg #%d routepoint %s (%+.10f, %+.10f)\n", + j, gbLogCStr(wpt_tmp->shortname), wpt_tmp->longitude, wpt_tmp->latitude); } route_add_wpt(rte_head, new Waypoint(*wpt_tmp)); } @@ -863,7 +861,7 @@ LowranceusrFormat::lowranceusr4_parse_route() const /* Mystery byte, discard */ if (global_opts.debug_level == 99) { - printf(MYNAME " parse_route: end of route %02x\n", gbfgetc(file_in)); + gbDebug("parse_route: end of route %02x\n", gbfgetc(file_in)); } else { gbfgetc(file_in); } @@ -883,7 +881,7 @@ LowranceusrFormat::lowranceusr_parse_routes() } if (global_opts.debug_level >= 1) { - printf(MYNAME " parse_routes: Num Routes = %d\n", num_routes); + gbDebug("parse_routes: Num Routes = %d\n", num_routes); } for (int i = 0; i < num_routes; i++) { @@ -904,12 +902,12 @@ LowranceusrFormat::lowranceusr_parse_routes() * option of ignoreicons is used */ void -LowranceusrFormat::lowranceusr_parse_icons() const +LowranceusrFormat::lowranceusr_parse_icons() { short int num_icons = gbfgetint16(file_in); if (global_opts.debug_level >= 1) { - printf(MYNAME " parse_icons: Num Event Marker Icons = %d\n", num_icons); + gbDebug("parse_icons: Num Event Marker Icons = %d\n", num_icons); } for (int i = 0; i < num_icons && !gbfeof(file_in); i++) { @@ -933,8 +931,8 @@ LowranceusrFormat::lowranceusr_parse_icons() const wpt_tmp->icon_descr = lowranceusr_find_desc_from_icon_number(icon_number); if (global_opts.debug_level > 1) { - printf(MYNAME " parse_icons: '%s' %d %16.16s %+15.10f %+15.10f\n", - qPrintable(wpt_tmp->shortname), icon_number, qPrintable(wpt_tmp->icon_descr), wpt_tmp->latitude, wpt_tmp->longitude); + gbDebug("parse_icons: '%s' %d %16.16s %+15.10f %+15.10f\n", + gbLogCStr(wpt_tmp->shortname), icon_number, gbLogCStr(wpt_tmp->icon_descr), wpt_tmp->latitude, wpt_tmp->longitude); } waypt_add(wpt_tmp); } @@ -951,28 +949,28 @@ LowranceusrFormat::lowranceusr_parse_trail(int* trail_num) } if (global_opts.debug_level > 1) { - printf(MYNAME " parse_trails: Trail '%s'\n", qPrintable(trk_head->rte_name)); + gbDebug("parse_trails: Trail '%s'\n", gbLogCStr(trk_head->rte_name)); } /* visible */ char visible = gbfgetc(file_in); if (global_opts.debug_level > 1) { - printf(MYNAME " parse_trails: Visible '%x' - %s\n", visible, (visible ? "Yes" : "No")); + gbDebug("parse_trails: Visible '%x' - %s\n", visible, (visible ? "Yes" : "No")); } /* num trail points */ short num_trail_points = gbfgetint16(file_in); if (global_opts.debug_level > 1) { - printf(MYNAME " parse_trails: Num Trail Points = %d\n", num_trail_points); + gbDebug("parse_trails: Num Trail Points = %d\n", num_trail_points); } /* max trail size */ int itmp = gbfgetint16(file_in); if (global_opts.debug_level > 1) { - printf(MYNAME " parse_trails: Max Trail size = %d\n", itmp); + gbDebug("parse_trails: Max Trail size = %d\n", itmp); } if (num_trail_points) { @@ -982,7 +980,7 @@ LowranceusrFormat::lowranceusr_parse_trail(int* trail_num) num_section_points = gbfgetint16(file_in); if (global_opts.debug_level > 1) { - printf(MYNAME " parse_trails: Num Section Points = %d\n", num_section_points); + gbDebug("parse_trails: Num Section Points = %d\n", num_section_points); } for (int j = 0; j < num_section_points && !gbfeof(file_in); j++, num_trail_points--) { @@ -1010,7 +1008,7 @@ LowranceusrFormat::lowranceusr_parse_trail(int* trail_num) track_add_wpt(trk_head, wpt_tmp); if (global_opts.debug_level > 2) { - printf(MYNAME " parse_trails: Trail pt lat %f lon %f\n", wpt_tmp->latitude, wpt_tmp->longitude); + gbDebug("parse_trails: Trail pt lat %f lon %f\n", wpt_tmp->latitude, wpt_tmp->longitude); } } } @@ -1021,7 +1019,7 @@ LowranceusrFormat::lowranceusr_parse_trail(int* trail_num) } void -LowranceusrFormat::lowranceusr4_parse_trail(int* trail_num) const +LowranceusrFormat::lowranceusr4_parse_trail(int* trail_num) { auto* fsdata = new lowranceusr4_fsdata; trk_head->fs.FsChainAdd(fsdata); @@ -1036,10 +1034,10 @@ LowranceusrFormat::lowranceusr4_parse_trail(int* trail_num) const /* Trail stream version number */ int trail_version = gbfgetint16(file_in); if (global_opts.debug_level == 99) { - printf(MYNAME " parse_trails: trail Version %d\n", trail_version); + gbDebug("parse_trails: trail Version %d\n", trail_version); } if ((trail_version < 3) || (trail_version > 5)) { - fatal(MYNAME " trail version %d not supported!!", trail_version); + gbFatal("trail version %d not supported!!\n", trail_version); } /* Trail name; input is 2 bytes per char, we convert to 1 */ @@ -1048,7 +1046,7 @@ LowranceusrFormat::lowranceusr4_parse_trail(int* trail_num) const trk_head->rte_name = name; } if (global_opts.debug_level >= 2) { - printf(MYNAME " parse_trails: Trail '%s'\n", qPrintable(trk_head->rte_name)); + gbDebug("parse_trails: Trail '%s'\n", gbLogCStr(trk_head->rte_name)); } /* Flags, discard for now */ @@ -1063,7 +1061,7 @@ LowranceusrFormat::lowranceusr4_parse_trail(int* trail_num) const trk_head->rte_desc = desc; } if (global_opts.debug_level == 99) { - printf(MYNAME " parse_trails: Comment '%s'\n", qPrintable(desc)); + gbDebug("parse_trails: Comment '%s'\n", gbLogCStr(desc)); } /* Creation date/time, discard for now */ @@ -1072,12 +1070,12 @@ LowranceusrFormat::lowranceusr4_parse_trail(int* trail_num) const int create_time = gbfgetint32(file_in); if (global_opts.debug_level == 99) { QDateTime qdt = lowranceusr4_get_timestamp(create_date, create_time); - printf(MYNAME " parse_trails: creation date/time = %s\n", qPrintable(qdt.toString(u"yyyy-MM-dd hh:mm:ss AP"))); + gbDebug("parse_trails: creation date/time = %s\n", gbLogCStr(qdt.toString(u"yyyy-MM-dd hh:mm:ss AP"))); } /* Some flag bytes */ if (global_opts.debug_level == 99) { - printf(MYNAME " parse_trails: unknown flag bytes %02x %02x %02x\n", + gbDebug("parse_trails: unknown flag bytes %02x %02x %02x\n", gbfgetc(file_in), gbfgetc(file_in), gbfgetc(file_in)); } else { /* just discard */ @@ -1089,15 +1087,15 @@ LowranceusrFormat::lowranceusr4_parse_trail(int* trail_num) const /* Mysterious attribute "data count" */ int attr_count = gbfgetint32(file_in); if (global_opts.debug_level == 99) { - printf(MYNAME " parse_trails: attribute count %4d : (", attr_count); + gbDebug("parse_trails: attribute count %4d : (", attr_count); for (int i=0; i= 2) { - printf(MYNAME " parse_trails: trail %d name='%s' color=%d flags=%d has %d (%x) trailpoints\n", - *trail_num, qPrintable(trk_head->rte_name), trail_color, trail_flags, num_trail_pts, num_trail_pts); + gbDebug("parse_trails: trail %d name='%s' color=%d flags=%d has %d (%x) trailpoints\n", + *trail_num, gbLogCStr(trk_head->rte_name), trail_color, trail_flags, num_trail_pts, num_trail_pts); if (global_opts.debug_level == 99) { - printf(MYNAME " parse_trails: Longitude Latitude Flag/Value pairs (01=Speed)\n"); - printf(MYNAME " parse_trails: -------------- -------------- -- -------- -- -------- -- --------\n"); + gbDebug("parse_trails: Longitude Latitude Flag/Value pairs (01=Speed)\n"); + gbDebug("parse_trails: -------------- -------------- -- -------- -- -------- -- --------\n"); } } for (int j = 0; j < num_trail_pts; ++j) { @@ -1136,11 +1134,11 @@ LowranceusrFormat::lowranceusr4_parse_trail(int* trail_num) const if (global_opts.debug_level >= 2) { if (global_opts.debug_level == 99) { - printf(MYNAME " parse_trails: %+14.9f %+14.9f", wpt_tmp->longitude, wpt_tmp->latitude); - printf(" '%s'", qPrintable(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss"))); + gbDebug("parse_trails: %+14.9f %+14.9f", wpt_tmp->longitude, wpt_tmp->latitude); + gbDebug(" '%s'", gbLogCStr(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss"))); } else { - printf(MYNAME " parse_trails: added trailpoint %+.9f,%+.9f to trail %s\n", - wpt_tmp->longitude, wpt_tmp->latitude, qPrintable(trk_head->rte_name)); + gbDebug("parse_trails: added trailpoint %+.9f,%+.9f to trail %s\n", + wpt_tmp->longitude, wpt_tmp->latitude, gbLogCStr(trk_head->rte_name)); } } @@ -1152,12 +1150,12 @@ LowranceusrFormat::lowranceusr4_parse_trail(int* trail_num) const int flag = gbfgetc(file_in); float value = gbfgetflt(file_in); if (global_opts.debug_level == 99) { - printf(" %02x %f", flag, value); + gbDebug(" %02x %f", flag, value); } } if (global_opts.debug_level == 99) { - printf("\n"); + gbDebug("\n"); } } } @@ -1177,7 +1175,7 @@ LowranceusrFormat::lowranceusr_parse_trails() } if (global_opts.debug_level >= 1) { - printf(MYNAME " parse_trails: Num Trails = %d\n", num_trails); + gbDebug("parse_trails: Num Trails = %d\n", num_trails); } for (int i = trail_num = 0; i < num_trails && !gbfeof(file_in); i++) { @@ -1199,11 +1197,11 @@ LowranceusrFormat::read() reading_version = gbfgetint16(file_in); rstream_version = gbfgetint16(file_in); if (global_opts.debug_level >= 1) { - printf(MYNAME " input_file: USR File Format %d (Version = %d)\n", reading_version, rstream_version); + gbDebug("input_file: USR File Format %d (Version = %d)\n", reading_version, rstream_version); } if ((reading_version < 2) || (reading_version > 6)) { - fatal(MYNAME " input file is a USR format that is not supported\n"); + gbFatal("input file is a USR format that is not supported\n"); } if (reading_version >= 4) { @@ -1211,19 +1209,19 @@ LowranceusrFormat::read() /* Starting with USR version 4 have an unknown here */ int unknown = gbfgetint32(file_in); if (global_opts.debug_level >= 1) { - printf(MYNAME " input_file: Unknown %d (%x)\n", unknown, unknown); + gbDebug("input_file: Unknown %d (%x)\n", unknown, unknown); } /* USR files also now contain a file title */ QString title = lowranceusr4_readstr(file_in, 1); if (!title.isEmpty() && global_opts.debug_level >= 1) { - printf(MYNAME " file title: '%s'\n", qPrintable(title)); + gbDebug("file title: '%s'\n", gbLogCStr(title)); } /* AND a date created string */ QString creation_date = lowranceusr4_readstr(file_in, 1); if (!creation_date.isEmpty() && global_opts.debug_level >= 1) { - printf(MYNAME " date string: '%s'\n", qPrintable(creation_date)); + gbDebug("date string: '%s'\n", gbLogCStr(creation_date)); } /* Creation date/time, discard for now */ @@ -1232,7 +1230,7 @@ LowranceusrFormat::read() int create_time = gbfgetint32(file_in); if (global_opts.debug_level >= 1) { QDateTime qdt = lowranceusr4_get_timestamp(create_date, create_time); - printf(MYNAME " creation date/time : '%s'\n", qPrintable(qdt.toString(u"yyyy-MM-dd hh:mm:ss AP"))); + gbDebug("creation date/time : '%s'\n", gbLogCStr(qdt.toString(u"yyyy-MM-dd hh:mm:ss AP"))); } unsigned char byte = gbfgetc(file_in); /* unused, apparently */ @@ -1241,13 +1239,13 @@ LowranceusrFormat::read() /* AND the serial number of the unit that created the file */ uint serial_num = gbfgetint32(file_in); if (global_opts.debug_level >= 1) { - printf(MYNAME " device serial number: %u\n", serial_num); + gbDebug("device serial number: %u\n", serial_num); } /* AND a comment on the file contents */ QString comment = lowranceusr4_readstr(file_in, 1); if (!comment.isEmpty() && global_opts.debug_level >= 1) { - printf(MYNAME " content description: '%s'\n", qPrintable(comment)); + gbDebug("content description: '%s'\n", gbLogCStr(comment)); } } @@ -1263,7 +1261,7 @@ LowranceusrFormat::read() } void -LowranceusrFormat::lowranceusr_waypt_disp(const Waypoint* wpt) const +LowranceusrFormat::lowranceusr_waypt_disp(const Waypoint* wpt) { int SymbolId; int alt; @@ -1304,8 +1302,8 @@ LowranceusrFormat::lowranceusr_waypt_disp(const Waypoint* wpt) const if (global_opts.debug_level > 2) { /* print lat/lon/alt on one easily greppable line */ - printf(MYNAME " waypt_disp: Waypt name = '%s' Lat = %+16.10f Lon = %+16.10f Alt = %f\n", - qPrintable(wpt->shortname), wpt->latitude, wpt->longitude, wpt->altitude); + gbDebug("waypt_disp: Waypt name = '%s' Lat = %+16.10f Lon = %+16.10f Alt = %f\n", + gbLogCStr(wpt->shortname), wpt->latitude, wpt->longitude, wpt->altitude); } QByteArray name_qba = name.toLatin1(); @@ -1317,7 +1315,7 @@ LowranceusrFormat::lowranceusr_waypt_disp(const Waypoint* wpt) const gbfwrite(name_qba.constData(), 1, text_len, file_out); if (global_opts.debug_level > 1) { - printf(MYNAME " waypt_disp: Waypt name = '%s' ", qPrintable(name)); + gbDebug("waypt_disp: Waypt name = '%s' ", gbLogCStr(name)); } /** @@ -1343,13 +1341,13 @@ LowranceusrFormat::lowranceusr_waypt_disp(const Waypoint* wpt) const /* Lowrance needs it as seconds since Jan 1, 2000 */ waypt_time -= base_time_secs; if (global_opts.debug_level >= 2) { - printf("creation_time %" PRId64 ", '%s'", waypt_time, qPrintable(wpt->GetCreationTime().toString(u"yyyy-MM-dd hh:mm:ss"))); + gbDebug("creation_time %" PRId64 ", '%s'", waypt_time, gbLogCStr(wpt->GetCreationTime().toString(u"yyyy-MM-dd hh:mm:ss"))); } } else { /* If false, make sure it is an unknown time value */ waypt_time = 0; if (global_opts.debug_level >= 2) { - printf("creation_time UNKNOWN"); + gbDebug("creation_time UNKNOWN"); } } @@ -1379,7 +1377,7 @@ LowranceusrFormat::lowranceusr_waypt_disp(const Waypoint* wpt) const } if (global_opts.debug_level > 1) { - printf("\n"); + gbDebug("\n"); } } @@ -1477,7 +1475,7 @@ LowranceusrFormat::lowranceusr_waypt_pr(const Waypoint* wpt) gbfputint16(waypt_out_count, file_out); if (global_opts.debug_level >= 3) { - printf(MYNAME " waypt_pr: waypoint #%d\n",waypt_out_count); + gbDebug("waypt_pr: waypoint #%d\n",waypt_out_count); } waypt_out_count++; @@ -1497,15 +1495,15 @@ LowranceusrFormat::lowranceusr4_write_waypoints() route_disp_all(nullptr, nullptr, register_waypt_lambda); if (global_opts.debug_level >= 1) { - printf(MYNAME " writing %s waypoints\n", QByteArray::number(waypt_table->size()).constData()); + gbDebug("writing %s waypoints\n", QByteArray::number(waypt_table->size()).constData()); } gbfputint32(waypt_table->size(), file_out); waypt_uid = 0; for (int i = 0; i < waypt_table->size(); ++i) { if (global_opts.debug_level >= 2) { - printf(MYNAME " writing out waypt %d (%s - %s)\n", - i, qPrintable(waypt_table->at(i)->shortname), qPrintable(waypt_table->at(i)->description)); + gbDebug("writing out waypt %d (%s - %s)\n", + i, gbLogCStr(waypt_table->at(i)->shortname), gbLogCStr(waypt_table->at(i)->description)); } lowranceusr4_waypt_disp((waypt_table->at(i))); } @@ -1520,7 +1518,7 @@ LowranceusrFormat::lowranceusr4_write_waypoints() * 4 bytes symbol */ void -LowranceusrFormat::lowranceusr_write_icon(const Waypoint* wpt) const +LowranceusrFormat::lowranceusr_write_icon(const Waypoint* wpt) { int latmm = lat_deg_to_mm(wpt->latitude); int lonmm = lon_deg_to_mm(wpt->longitude); @@ -1569,7 +1567,7 @@ LowranceusrFormat::lowranceusr_trail_hdr(const route_head* trk) text_len = MAXUSRSTRINGSIZE; } if (global_opts.debug_level >= 1) { - printf(MYNAME " trail_hdr: trail name '%s' ", qPrintable(trk->rte_name)); + gbDebug("trail_hdr: trail name '%s' ", gbLogCStr(trk->rte_name)); } gbfputint32(text_len, file_out); gbfwrite(CSTR(name), 1, text_len, file_out); @@ -1582,11 +1580,11 @@ LowranceusrFormat::lowranceusr_trail_hdr(const route_head* trk) num_section_points = num_trail_points; if (global_opts.debug_level) { - printf("num_trail_points = %d ", num_trail_points); + gbDebug("num_trail_points = %d ", num_trail_points); if (global_opts.debug_level > 1) { - printf("max_trail_size = %d num_section_points = %d\n", max_trail_size, num_section_points); + gbDebug("max_trail_size = %d num_section_points = %d\n", max_trail_size, num_section_points); } else { - printf("\n"); + gbDebug("\n"); } } @@ -1622,16 +1620,16 @@ LowranceusrFormat::lowranceusr_route_hdr(const route_head* rte) gbfwrite(&route_reversed, 1, 1, file_out); if (global_opts.debug_level >= 1) - printf(MYNAME " route_hdr: route name \"%s\" num_legs = %d\n", - qPrintable(rte->rte_name), num_legs); + gbDebug("route_hdr: route name \"%s\" num_legs = %d\n", + gbLogCStr(rte->rte_name), num_legs); } void LowranceusrFormat::lowranceusr4_route_hdr(const route_head* rte) { if (global_opts.debug_level >= 1) { - printf(MYNAME " writing route #%d (%s) with %d waypts\n", - route_uid, qPrintable(rte->rte_name), rte->rte_waypt_ct()); + gbDebug("writing route #%d (%s) with %d waypts\n", + route_uid, gbLogCStr(rte->rte_name), rte->rte_waypt_ct()); } const auto* fs = reinterpret_cast(rte->fs.FsChainFind(kFsLowranceusr4)); @@ -1660,7 +1658,7 @@ LowranceusrFormat::lowranceusr4_route_hdr(const route_head* rte) } void -LowranceusrFormat::lowranceusr4_route_leg_disp(const Waypoint* wpt) const +LowranceusrFormat::lowranceusr4_route_leg_disp(const Waypoint* wpt) { for (int i = 0; i < waypt_table->size(); i++) { const Waypoint* cmp = waypt_table->at(i); @@ -1677,7 +1675,7 @@ LowranceusrFormat::lowranceusr4_route_leg_disp(const Waypoint* wpt) const gbfputint32(i, file_out); // Sequence Low gbfputint32(0, file_out); // Sequence High if (global_opts.debug_level > 1) { - printf(MYNAME " wrote route leg with waypt '%s'\n", qPrintable(wpt->shortname)); + gbDebug("wrote route leg with waypt '%s'\n", gbLogCStr(wpt->shortname)); } break; } @@ -1685,7 +1683,7 @@ LowranceusrFormat::lowranceusr4_route_leg_disp(const Waypoint* wpt) const } void -LowranceusrFormat::lowranceusr4_route_trl(const route_head* /*unused*/) const +LowranceusrFormat::lowranceusr4_route_trl(const route_head* /*unused*/) { /* Mystery byte */ gbfputc(0x01, file_out); // end of Route info ?? @@ -1700,7 +1698,7 @@ LowranceusrFormat::lowranceusr_trail_disp(const Waypoint* wpt) int lon = lon_deg_to_mm(wpt->longitude); if (global_opts.debug_level > 1) { - printf(MYNAME " trail_disp: Trail point #%d lat = %f long = %f\n",trail_point_count, wpt->latitude, wpt->longitude); + gbDebug("trail_disp: Trail point #%d lat = %f long = %f\n",trail_point_count, wpt->latitude, wpt->longitude); } gbfputint32(lat, file_out); @@ -1735,7 +1733,7 @@ LowranceusrFormat::lowranceusr_merge_trail_hdr(const route_head* trk) gbfputs(name, file_out); if (global_opts.debug_level >= 1) { - printf(MYNAME " trail_hdr: trail name = %s\n", CSTR(name)); + gbDebug("trail_hdr: trail name = %s\n", CSTR(name)); } } @@ -1754,7 +1752,7 @@ LowranceusrFormat::lowranceusr_merge_trail_tlr(const route_head* /*unused*/) num_section_points = num_trail_points; if (global_opts.debug_level >= 1) - printf(MYNAME " merge_trail_tlr: num_trail_points = %d\nmax_trail_size = %d\nnum_section_points = %d\n", + gbDebug("merge_trail_tlr: num_trail_points = %d\nmax_trail_size = %d\nnum_section_points = %d\n", num_trail_points, max_trail_size, num_section_points); const char visible=1; @@ -1774,8 +1772,8 @@ void LowranceusrFormat::lowranceusr4_trail_hdr(const route_head* trail) { if (global_opts.debug_level >= 1) { - printf(MYNAME " writing trail %d (%s) with %d trailpoints\n", - trail_uid, qPrintable(trail->rte_name), trail->rte_waypt_ct()); + gbDebug("writing trail %d (%s) with %d trailpoints\n", + trail_uid, gbLogCStr(trail->rte_name), trail->rte_waypt_ct()); } /* UID unit number */ @@ -1826,7 +1824,7 @@ LowranceusrFormat::lowranceusr4_trail_hdr(const route_head* trail) } void -LowranceusrFormat::lowranceusr4_trail_disp(const Waypoint* wpt) const +LowranceusrFormat::lowranceusr4_trail_disp(const Waypoint* wpt) { /* Some unknown bytes */ gbfputint16(0, file_out); @@ -1855,7 +1853,7 @@ LowranceusrFormat::write() int NumWaypoints = waypt_count(); if (global_opts.debug_level >= 1) { - printf(MYNAME " data_write: Num Waypoints = %d\n", NumWaypoints); + gbDebug("data_write: Num Waypoints = %d\n", NumWaypoints); } // If writeasicons option specified then all Waypoints processed are written as @@ -1885,7 +1883,7 @@ LowranceusrFormat::write() buf = opt_title.isEmpty()? QStringLiteral("GPSBabel generated USR data file") : opt_title; if (global_opts.debug_level >= 1) { - printf(MYNAME " data_write: Title = '%s'\n", qPrintable(buf)); + gbDebug("data_write: Title = '%s'\n", gbLogCStr(buf)); } lowranceusr4_writestr(buf, file_out, 1); @@ -1909,7 +1907,7 @@ LowranceusrFormat::write() buf = opt_content_descr.isEmpty()? QStringLiteral("Waypoints, routes, and trails") : opt_content_descr; if (global_opts.debug_level >= 1) { - printf(MYNAME " data_write: Description = '%s'\n", qPrintable(buf)); + gbDebug("data_write: Description = '%s'\n", gbLogCStr(buf)); } lowranceusr4_writestr(buf, file_out, 1); @@ -1926,7 +1924,7 @@ LowranceusrFormat::write() lowrance_route_count=0; if (global_opts.debug_level >= 1) { - printf(MYNAME " data_write: Num routes = %d\n", NumRoutes); + gbDebug("data_write: Num routes = %d\n", NumRoutes); } if ((writing_version == 2) || (writing_version == 3)) { @@ -2024,12 +2022,12 @@ LowranceusrFormat::write() track_disp_all(lowranceusr_merge_trail_hdr_2_lambda, nullptr, lowranceusr_trail_disp_lambda); } else { /* MERGE NEEDS SOME MORE WORK */ - fatal(MYNAME " output file USR %d format is not supported with merge option\n", writing_version); + gbFatal("output file USR %d format is not supported with merge option\n", writing_version); } } else { if (global_opts.debug_level >= 1) { - printf(MYNAME " data_write: Num trails = %d\n", NumTrails); + gbDebug("data_write: Num trails = %d\n", NumTrails); } if ((writing_version == 2) || (writing_version == 3)) { // USR version 2 & 3 use 16-bit count diff --git a/lowranceusr.h b/lowranceusr.h index 1ac7bd8cf..e2e284764 100644 --- a/lowranceusr.h +++ b/lowranceusr.h @@ -388,7 +388,7 @@ class LowranceusrFormat : public Format /* Member Functions */ static bool same_points(const Waypoint* A, const Waypoint* B); - void register_waypt(const Waypoint* wpt) const; + void register_waypt(const Waypoint* wpt); static const Waypoint* lowranceusr4_find_waypt(uint uid_unit, int uid_seq_low, int uid_seq_high); static const Waypoint* lowranceusr4_find_global_waypt(uint id1, uint id2, uint id3, uint id4); QString lowranceusr4_readstr(gbfile* file, int bytes_per_char) const; @@ -405,32 +405,32 @@ class LowranceusrFormat : public Format static double lat_mm_to_deg(double x); static long int lon_deg_to_mm(double x); static long int lat_deg_to_mm(double x); - void lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_present) const; - void lowranceusr4_parse_waypt(Waypoint* wpt_tmp) const; - void lowranceusr_parse_waypts() const; - void lowranceusr_parse_route() const; - void lowranceusr4_parse_route() const; + void lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_present); + void lowranceusr4_parse_waypt(Waypoint* wpt_tmp); + void lowranceusr_parse_waypts(); + void lowranceusr_parse_route(); + void lowranceusr4_parse_route(); void lowranceusr_parse_routes(); - void lowranceusr_parse_icons() const; + void lowranceusr_parse_icons(); void lowranceusr_parse_trail(int* trail_num); - void lowranceusr4_parse_trail(int* trail_num) const; + void lowranceusr4_parse_trail(int* trail_num); void lowranceusr_parse_trails(); - void lowranceusr_waypt_disp(const Waypoint* wpt) const; + void lowranceusr_waypt_disp(const Waypoint* wpt); void lowranceusr4_waypt_disp(const Waypoint* wpt); void lowranceusr_waypt_pr(const Waypoint* wpt); void lowranceusr4_write_waypoints(); - void lowranceusr_write_icon(const Waypoint* wpt) const; + void lowranceusr_write_icon(const Waypoint* wpt); void lowranceusr_trail_hdr(const route_head* trk); void lowranceusr_route_hdr(const route_head* rte); void lowranceusr4_route_hdr(const route_head* rte); - void lowranceusr4_route_leg_disp(const Waypoint* wpt) const; - void lowranceusr4_route_trl(const route_head* /*unused*/) const; + void lowranceusr4_route_leg_disp(const Waypoint* wpt); + void lowranceusr4_route_trl(const route_head* /*unused*/); void lowranceusr_trail_disp(const Waypoint* wpt); void lowranceusr_merge_trail_hdr(const route_head* trk); void lowranceusr_merge_trail_tlr(const route_head* /*unused*/); void lowranceusr_merge_trail_hdr_2(const route_head* /*unused*/); void lowranceusr4_trail_hdr(const route_head* trail); - void lowranceusr4_trail_disp(const Waypoint* wpt) const; + void lowranceusr4_trail_disp(const Waypoint* wpt); /* Data Members */ diff --git a/main.cc b/main.cc index 426ea549d..4edced7b8 100644 --- a/main.cc +++ b/main.cc @@ -24,6 +24,8 @@ #include // for strcmp #include // for QCoreApplication +#include // for QDateTime +#include // for QDebug #include // for QElapsedTimer #include // for QFile #include // for QIODevice::ReadOnly @@ -59,7 +61,6 @@ static constexpr bool DEBUG_LOCALE = false; -#define MYNAME "main" // be careful not to advance argn passed the end of the list, i.e. ensure argn < qargs.size() #define FETCH_OPTARG qargs.at(argn).size() > 2 ? QString(qargs.at(argn)).remove(0,2) : qargs.size()>(argn+1) ? qargs.at(++argn) : QString() @@ -193,11 +194,13 @@ print_extended_info() "\n"); } -static void MessageHandler(QtMsgType /* type */, const QMessageLogContext& /* context */, const QString& msg) +static void setMessagePattern(const QString& id = QString()) { - /* flush any buffered standard output */ - fflush(stdout); - fprintf(stderr, "%s\n", qPrintable(msg)); + if (id.isEmpty()) { + qSetMessagePattern("%{if-category}%{category}: %{endif}main: %{message}"); + } else { + qSetMessagePattern(QStringLiteral("%{if-category}%{category}: %{endif}%1: %{message}").arg(id)); + } } static void @@ -243,6 +246,7 @@ run_reader(Vecs::fmtinfo_t& ivecs, const QString& fname) timer.start(); } start_session(ivecs.fmtname, fname); + setMessagePattern(ivecs.fmtname); if (ivecs.isDynamic()) { ivecs.fmt = ivecs.factory(fname); Vecs::init_vec(ivecs.fmt, ivecs.fmtname); @@ -263,9 +267,10 @@ run_reader(Vecs::fmtinfo_t& ivecs, const QString& fname) ivecs->read(); ivecs->rd_deinit(); } + setMessagePattern(); if (global_opts.debug_level > 0) { - Warning().noquote() << QStringLiteral("%1: reader %2 took %3 seconds.") - .arg(MYNAME, ivecs.fmtname, QString::number(timer.elapsed()/1000.0, 'f', 3)); + qDebug().noquote() << QStringLiteral("reader %1 took %2 seconds.") + .arg(ivecs.fmtname, QString::number(timer.elapsed()/1000.0, 'f', 3)); } } @@ -275,6 +280,7 @@ run_writer(Vecs::fmtinfo_t& ovecs, const QString& ofname) if (global_opts.debug_level > 0) { timer.start(); } + setMessagePattern(ovecs.fmtname); if (ovecs.isDynamic()) { ovecs.fmt = ovecs.factory(ofname); Vecs::init_vec(ovecs.fmt, ovecs.fmtname); @@ -295,9 +301,10 @@ run_writer(Vecs::fmtinfo_t& ovecs, const QString& ofname) ovecs->write(); ovecs->wr_deinit(); } + setMessagePattern(); if (global_opts.debug_level > 0) { - Warning().noquote() << QStringLiteral("%1: writer %2 took %3 seconds.") - .arg(MYNAME, ovecs.fmtname, QString::number(timer.elapsed()/1000.0, 'f', 3)); + qDebug().noquote() << QStringLiteral("writer %1 took %2 seconds.") + .arg(ovecs.fmtname, QString::number(timer.elapsed()/1000.0, 'f', 3)); } } @@ -368,27 +375,27 @@ run(const char* prog_name) argument = FETCH_OPTARG; ivecs = Vecs::Instance().find_vec(argument); if (!ivecs) { - fatal("Input type '%s' not recognized\n", qPrintable(argument)); + gbFatal("Input type '%s' not recognized\n", gbLogCStr(argument)); } break; case 'o': if (!ivecs) { - warning("-o appeared before -i. This is probably not what you want to do.\n"); + gbWarning("-o appeared before -i. This is probably not what you want to do.\n"); } argument = FETCH_OPTARG; ovecs = Vecs::Instance().find_vec(argument); if (!ovecs) { - fatal("Output type '%s' not recognized\n", qPrintable(argument)); + gbFatal("Output type '%s' not recognized\n", gbLogCStr(argument)); } break; case 'f': argument = FETCH_OPTARG; fname = argument; if (fname.isEmpty()) { - fatal("No file or device name specified.\n"); + gbFatal("No file or device name specified.\n"); } if (!ivecs) { - fatal("No valid input type specified\n"); + gbFatal("No valid input type specified\n"); } if (global_opts.masked_objective & POSNDATAMASK) { did_something = true; @@ -407,7 +414,7 @@ run(const char* prog_name) argument = FETCH_OPTARG; ofname = argument; if (ofname.isEmpty()) { - fatal("No output file or device name specified.\n"); + gbFatal("No output file or device name specified.\n"); } if (ovecs && (!(global_opts.masked_objective & POSNDATAMASK))) { /* simulates the default behaviour of waypoints */ @@ -460,6 +467,7 @@ run(const char* prog_name) if (global_opts.debug_level > 0) { timer.start(); } + setMessagePattern(filter.fltname); if (filter.isDynamic()) { filter.flt = filter.factory(); FilterVecs::init_filter_vec(filter.flt, filter.fltname); @@ -480,12 +488,13 @@ run(const char* prog_name) filter->deinit(); FilterVecs::free_filter_vec(filter.flt); } + setMessagePattern(); if (global_opts.debug_level > 0) { - Warning().noquote() << QStringLiteral("%1: filter %2 took %3 seconds.") - .arg(MYNAME, filter.fltname, QString::number(timer.elapsed()/1000.0, 'f', 3)); + qDebug().noquote() << QStringLiteral("filter %1 took %2 seconds.") + .arg(filter.fltname, QString::number(timer.elapsed()/1000.0, 'f', 3)); } } else { - fatal("Unknown filter '%s'\n",qPrintable(argument)); + gbFatal("Unknown filter '%s'\n",gbLogCStr(argument)); } break; case 'D': @@ -494,33 +503,33 @@ run(const char* prog_name) bool ok; global_opts.debug_level = argument.toInt(&ok); if (!ok) { - fatal("the -D option requires an integer value to specify the debug level, i.e. -D level\n"); + gbFatal("the -D option requires an integer value to specify the debug level, i.e. -D level\n"); } } /* * When debugging, announce version. */ if (global_opts.debug_level > 0) { - warning("GPSBabel Version: %s\n", gpsbabel_version); + gbInfo("GPSBabel Version: %s\n", gpsbabel_version); if(sizeof(kVersionSHA) > 1) { - warning(MYNAME ": Repository SHA: %s\n", kVersionSHA); + gbInfo("Repository SHA: %s\n", kVersionSHA); } if(sizeof(kVersionDate) > 1) { QDateTime date = QDateTime::fromString(kVersionDate, Qt::ISODate); if (date.isValid()) { - warning(MYNAME ": Date: %s\n", qPrintable(date.toUTC().toString(Qt::ISODate))); + gbInfo("Date: %s\n", gbLogCStr(date.toUTC().toString(Qt::ISODate))); } } - warning(MYNAME ": Compiled with Qt %s for architecture %s\n", + gbInfo("Compiled with Qt %s for architecture %s\n", QT_VERSION_STR, - qPrintable(QSysInfo::buildAbi())); - warning(MYNAME ": Running with Qt %s on %s, %s\n", qVersion(), - qPrintable(QSysInfo::prettyProductName()), - qPrintable(QSysInfo::currentCpuArchitecture())); - warning(MYNAME ": QLocale::system() is %s\n", qPrintable(QLocale::system().name())); - warning(MYNAME ": QLocale() is %s\n", qPrintable(QLocale().name())); + gbLogCStr(QSysInfo::buildAbi())); + gbInfo("Running with Qt %s on %s, %s\n", qVersion(), + gbLogCStr(QSysInfo::prettyProductName()), + gbLogCStr(QSysInfo::currentCpuArchitecture())); + gbInfo("QLocale::system() is %s\n", gbLogCStr(QLocale::system().name())); + gbInfo("QLocale() is %s\n", gbLogCStr(QLocale().name())); QTextCodec* defaultcodec = QTextCodec::codecForLocale(); - warning(MYNAME ": QTextCodec::codecForLocale() is %s, mib %d\n", + gbInfo("QTextCodec::codecForLocale() is %s, mib %d\n", defaultcodec->name().constData(),defaultcodec->mibEnum()); } break; @@ -568,7 +577,7 @@ run(const char* prog_name) if (argument.isEmpty()) { /* from GUI to preserve inconsistent options */ global_opts.inifile = nullptr; } else { - global_opts.inifile = inifile_init(argument, MYNAME); + global_opts.inifile = inifile_init(argument); } break; case 'b': @@ -585,7 +594,7 @@ run(const char* prog_name) break; default: - fatal("Unknown option '%s'.\n", qPrintable(qargs.at(argn))); + gbFatal("Unknown option '%s'.\n", gbLogCStr(qargs.at(argn))); break; } @@ -605,7 +614,7 @@ run(const char* prog_name) qargs.removeFirst(); } if (qargs.size() > 2) { - fatal("Extra arguments on command line\n"); + gbFatal("Extra arguments on command line\n"); } else if ((!qargs.isEmpty()) && ivecs) { did_something = true; /* simulates the default behaviour of waypoints */ @@ -641,48 +650,59 @@ run(const char* prog_name) if (global_opts.masked_objective & POSNDATAMASK) { if (!ivecs) { - fatal("Realtime tracking (-T) requires an input type (-t)i such as Garmin or NMEA.\n"); + gbFatal("Realtime tracking (-T) requires an input type (-t)i such as Garmin or NMEA.\n"); } if (fname.isEmpty()) { - fatal("An input file (-f) must be specified.\n"); + gbFatal("An input file (-f) must be specified.\n"); } if (ivecs.isDynamic()) { + setMessagePattern(ivecs.fmtname); ivecs.fmt = ivecs.factory(fname); Vecs::init_vec(ivecs.fmt, ivecs.fmtname); + setMessagePattern(); } if (ovecs && ovecs.isDynamic()) { + setMessagePattern(ovecs.fmtname); ovecs.fmt = ovecs.factory(ofname); Vecs::init_vec(ovecs.fmt, ovecs.fmtname); + setMessagePattern(); } start_session(ivecs.fmtname, fname); + setMessagePattern(ivecs.fmtname); Vecs::prepare_format(ivecs); ivecs->rd_position_init(fname); + setMessagePattern(); if (global_opts.masked_objective & ~POSNDATAMASK) { - fatal("Realtime tracking (-T) is exclusive of other modes.\n"); + gbFatal("Realtime tracking (-T) is exclusive of other modes.\n"); } if (signal(SIGINT, signal_handler) == SIG_ERR) { - fatal("Couldn't install the exit signal handler.\n"); + gbFatal("Couldn't install the exit signal handler.\n"); } if (ovecs) { + setMessagePattern(ovecs.fmtname); Vecs::prepare_format(ovecs); ovecs->wr_position_init(ofname); + setMessagePattern(); } tracking_status.request_terminate = 0; while (!tracking_status.request_terminate) { + setMessagePattern(ivecs.fmtname); Waypoint* wpt = ivecs->rd_position(&tracking_status); + setMessagePattern(); if (tracking_status.request_terminate) { delete wpt; break; } if (wpt) { + setMessagePattern(ovecs.fmtname); if (ovecs) { // ovecs->wr_position_init(ofname); ovecs->wr_position(wpt); @@ -692,13 +712,18 @@ run(const char* prog_name) fbOutput.waypt_disp(wpt); } delete wpt; + setMessagePattern(); } } + setMessagePattern(ivecs.fmtname); Vecs::prepare_format(ivecs); ivecs->rd_position_deinit(); + setMessagePattern(); if (ovecs) { + setMessagePattern(ovecs.fmtname); Vecs::prepare_format(ovecs); ovecs->wr_position_deinit(); + setMessagePattern(); } if (ovecs && ovecs.isDynamic()) { @@ -716,7 +741,7 @@ run(const char* prog_name) if (!did_something) { - fatal("Nothing to do! Use '%s -h' for command-line options.\n", prog_name); + gbFatal("Nothing to do! Use '%s -h' for command-line options.\n", prog_name); } return 0; @@ -742,8 +767,10 @@ main(int argc, char* argv[]) #error Visual Studio 2017 and earlier are not supported. Please use Visual Studio 2019 or 2022. #endif + setMessagePattern(); + if constexpr (DEBUG_LOCALE) { - printf("Initial locale: %s\n",setlocale(LC_ALL, nullptr)); + gbDebug("Initial locale: %s\n",setlocale(LC_ALL, nullptr)); } // Create a QCoreApplication object to handle application initialization. @@ -760,7 +787,7 @@ main(int argc, char* argv[]) // as opposed to the initial default "C" locale. // This was demonstrated with Qt5 on Mac OS X. if constexpr (DEBUG_LOCALE) { - printf("Locale after initial setup: %s\n",setlocale(LC_ALL, nullptr)); + gbDebug("Locale after initial setup: %s\n",setlocale(LC_ALL, nullptr)); } // As recommended in QCoreApplication reset the locale to the default. // Note the documentation says to set LC_NUMERIC, but QCoreApplicationPrivate::initLocale() @@ -768,24 +795,23 @@ main(int argc, char* argv[]) // Perhaps we should restore LC_ALL instead of only LC_NUMERIC. if (strcmp(setlocale(LC_NUMERIC,nullptr), "C") != 0) { if constexpr (DEBUG_LOCALE) { - printf("Resetting LC_NUMERIC\n"); + gbDebug("Resetting LC_NUMERIC\n"); } setlocale(LC_NUMERIC,"C"); if constexpr (DEBUG_LOCALE) { - printf("LC_ALL: %s\n",setlocale(LC_ALL, nullptr)); + gbDebug("LC_ALL: %s\n",setlocale(LC_ALL, nullptr)); } } /* reset LC_TIME for strftime */ if (strcmp(setlocale(LC_TIME,nullptr), "C") != 0) { if constexpr (DEBUG_LOCALE) { - printf("Resetting LC_TIME\n"); + gbDebug("Resetting LC_TIME\n"); } setlocale(LC_TIME,"C"); if constexpr (DEBUG_LOCALE) { - printf("LC_ALL: %s\n",setlocale(LC_ALL, nullptr)); + gbDebug("LC_ALL: %s\n",setlocale(LC_ALL, nullptr)); } } - qInstallMessageHandler(MessageHandler); (void) new gpsbabel::UsAsciiCodec(); /* make sure a US-ASCII codec is available */ @@ -796,7 +822,7 @@ main(int argc, char* argv[]) gpsbabel_time = current_time().toTime_t(); /* frozen in testmode */ if (!gpsbabel_testmode()) { /* within testo ? */ - global_opts.inifile = inifile_init(QString(), MYNAME); + global_opts.inifile = inifile_init(QString()); } assert(GPS_Lookup_Datum_Index("OSGB36") == kDatumOSGB36); diff --git a/mkshort.cc b/mkshort.cc index 92b3416b4..4cf415218 100644 --- a/mkshort.cc +++ b/mkshort.cc @@ -70,7 +70,7 @@ void MakeShort::mkshort_add_to_list(QByteArray& name, bool is_utf8) name.append(suffix); } } else { - fatal("mkshort failure, the specified short length is insufficient.\n"); + gbFatal("mkshort failure, the specified short length is insufficient.\n"); } } @@ -130,7 +130,7 @@ void MakeShort::replace_constants(QByteArray& s) void MakeShort::set_length(int l) { if (l < 0) { - fatal("mkshort: short length must be non-negative.\n"); + gbFatal("mkshort: short length must be non-negative.\n"); } else if (l == 0) { target_len_ = default_target_len; } else { @@ -164,7 +164,7 @@ void MakeShort::set_repeating_whitespace_ok(bool ok) void MakeShort::set_defname(const char* s) { if (s == nullptr) { - fatal("set_defname called without a valid name."); + gbFatal("set_defname called without a valid name.\n"); } defname_ = s; } diff --git a/mtk_logger.cc b/mtk_logger.cc index 31afa0d54..5db9163ca 100644 --- a/mtk_logger.cc +++ b/mtk_logger.cc @@ -83,8 +83,6 @@ #include "src/core/datetime.h" // for DateTime -#define MYNAME "mtk_logger" - #define MTK_EVT_BITMASK (1<<0x02) #define MTK_EVT_PERIOD (1<<0x03) #define MTK_EVT_DISTANCE (1<<0x04) @@ -101,13 +99,12 @@ void MtkLoggerBase::dbg(int l, const char* msg, ...) { - va_list ap; - va_start(ap, msg); if (global_opts.debug_level >= l) { - vfprintf(stderr,msg, ap); - fflush(stderr); + va_list ap; + va_start(ap, msg); + gbVLegacyLog(QtDebugMsg, msg, ap); + va_end(ap); } - va_end(ap); } // Returns a fully qualified pathname to a temporary file that is a copy @@ -130,7 +127,7 @@ int MtkLoggerBase::do_send_cmd(const char* cmd, int cmdLen) dbg(6, "Send %s ", cmd); int rc = gbser_print(fd, cmd); if (rc != gbser_OK) { - fatal(MYNAME ": Write error (%d)\n", rc); + gbFatal("Write error (%d)\n", rc); } return cmdLen; @@ -161,12 +158,12 @@ int MtkLoggerBase::do_cmd(const char* cmd, const char* expect, char** rslt, time if (strncmp(cmd, CMD_LOG_ERASE, 12) == 0) { cmd_erase = 1; if (global_opts.verbose_status || global_opts.debug_level > 0) { - fprintf(stderr, "Erasing "); + gbDebug("Erasing "); } } // dbg(6, "## Send '%s' -- Expect '%s' in %d sec\n", cmd, expect, timeout_sec); - do_send_cmd(cmd, strlen(cmd)); // success or fatal()... + do_send_cmd(cmd, strlen(cmd)); // success or gbFatal()... int done = 0; int loops = 0; @@ -177,7 +174,7 @@ int MtkLoggerBase::do_cmd(const char* cmd, const char* expect, char** rslt, time if (rc == gbser_TIMEOUT && time(nullptr) > tout) { dbg(2, "NMEA command '%s' timeout !\n", cmd); return -1; - // fatal(MYNAME "do_cmd(): Read error (%d)\n", rc); + // gbFatal("do_cmd(): Read error (%d)\n", rc); } len = -1; } else { @@ -187,13 +184,12 @@ int MtkLoggerBase::do_cmd(const char* cmd, const char* expect, char** rslt, time dbg(8, "Read %d bytes: '%s'\n", len, line); if (cmd_erase && (global_opts.verbose_status || (global_opts.debug_level > 0 && global_opts.debug_level <= 3))) { // erase cmd progress wheel -- only for debug level 1-3 - fprintf(stderr,"\b%c", LIVE_CHAR[loops%4]); - fflush(stderr); + gbDebug("\b%c", LIVE_CHAR[loops%4]); } if (len > 5 && line[0] == '$') { if (expect_len > 0 && strncmp(&line[1], expect, expect_len) == 0) { if (cmd_erase && (global_opts.verbose_status || global_opts.debug_level > 0)) { - fprintf(stderr,"\n"); + gbDebug("\n"); } dbg(6, "NMEA command success !\n"); if ((len - 4) > expect_len) { // alloc and copy data segment... @@ -252,7 +248,7 @@ void MtkLoggerBase::mtk_rd_init(const QString& fname) errno = 0; dbg(1, "Opening port %s...\n", port); if ((fd = gbser_init(port)) == nullptr) { - fatal(MYNAME ": Can't initialise port \"%s\" (%s)\n", port, strerror(errno)); + gbFatal("Can't initialise port \"%s\" (%s)\n", port, strerror(errno)); } // verify that we have a MTK based logger... @@ -272,12 +268,12 @@ void MtkLoggerBase::mtk_rd_init(const QString& fname) } if (rc) { dbg(1, "Set baud rate to %d failed (%d)\n", MTK_BAUDRATE, rc); - fatal(MYNAME ": Failed to set baudrate !\n"); + gbFatal("Failed to set baudrate !\n"); } rc = do_cmd("$PMTK605*31\r\n", "PMTK705,", &model, 10); if (rc != 0) { - fatal(MYNAME ": This is not a MTK based GPS ! (or is device turned off ?)\n"); + gbFatal("This is not a MTK based GPS ! (or is device turned off ?)\n"); } // say hello to GR245 to make it display "USB PROCESSING" @@ -366,19 +362,19 @@ void MtkLoggerBase::mtk_read() if (dout == nullptr) { dout = ufopen(TEMP_DATA_BIN, "wb"); if (dout == nullptr) { - fatal(MYNAME ": Can't create temporary file %s", - qPrintable(TEMP_DATA_BIN)); + gbFatal("Can't create temporary file %s\n", + gbLogCStr(TEMP_DATA_BIN)); } } fseek(dout, 0L,SEEK_END); unsigned long dsize = ftell(dout); if (dsize > 1024) { - dbg(1, "Temp %s file exists. with size %lu\n", qPrintable(TEMP_DATA_BIN), + dbg(1, "Temp %s file exists. with size %lu\n", gbLogCStr(TEMP_DATA_BIN), dsize); dpos = 0; init_scan = 1; } - dbg(1, "Download %s -> %s\n", port, qPrintable(TEMP_DATA_BIN)); + dbg(1, "Download %s -> %s\n", port, gbLogCStr(TEMP_DATA_BIN)); // check log status - is logging disabled ? do_cmd(CMD_LOG_STATUS, "PMTK182,3,7,", &fusage, 2); @@ -414,15 +410,15 @@ void MtkLoggerBase::mtk_read() dbg(1, "Download %dkB from device\n", (addr_max+1) >> 10); if (dsize > addr_max) { - dbg(1, "Temp %s file (%ld) is larger than data size %d. Data erased since last download !\n", qPrintable(TEMP_DATA_BIN), dsize, addr_max); + dbg(1, "Temp %s file (%ld) is larger than data size %d. Data erased since last download !\n", gbLogCStr(TEMP_DATA_BIN), dsize, addr_max); fclose(dout); dsize = 0; init_scan = 0; QFile::rename(TEMP_DATA_BIN, TEMP_DATA_BIN_OLD); dout = ufopen(TEMP_DATA_BIN, "wb"); if (dout == nullptr) { - fatal(MYNAME ": Can't create temporary file %s", - qPrintable(TEMP_DATA_BIN)); + gbFatal("Can't create temporary file %s\n", + gbLogCStr(TEMP_DATA_BIN)); } } @@ -441,10 +437,10 @@ void MtkLoggerBase::mtk_read() unsigned int line_size = 2*read_bsize + 32; // logdata as nmea/hex. unsigned int data_size = read_bsize + 32; if ((line = (char*) xmalloc(line_size)) == nullptr) { - fatal(MYNAME ": Can't allocate %u bytes for NMEA buffer\n", line_size); + gbFatal("Can't allocate %u bytes for NMEA buffer\n", line_size); } if ((data = (unsigned char*) xmalloc(data_size)) == nullptr) { - fatal(MYNAME ": Can't allocate %u bytes for data buffer\n", data_size); + gbFatal("Can't allocate %u bytes for data buffer\n", data_size); } memset(line, '\0', line_size); memset(data, '\0', data_size); @@ -472,7 +468,7 @@ void MtkLoggerBase::mtk_read() retry_cnt++; goto mtk_retry; } // else - fatal(MYNAME "mtk_read(): Read error (%d)\n", rc); + gbFatal("mtk_read(): Read error (%d)\n", rc); } int len = strlen(line); dbg(8, "Read %d bytes: '%s'\n", len, line); @@ -510,7 +506,7 @@ void MtkLoggerBase::mtk_read() } } else { if (null_len == chunk_size) { // 0x00 block - bad block.... - fprintf(stderr, "FIXME -- read bad block at 0x%.6x - retry ? skip ?\n%s\n", data_addr, line); + gbWarning("FIXME -- read bad block at 0x%.6x - retry ? skip ?\n%s\n", data_addr, line); } if (ff_len == chunk_size) { // 0xff block - read complete... len = ff_len; @@ -539,9 +535,9 @@ void MtkLoggerBase::mtk_read() fseek(dout, addr, SEEK_SET); if (fread(line, 1, rcvd_bsize, dout) == rcvd_bsize && memcmp(line, data, rcvd_bsize) == 0) { dpos = addr; - dbg(2, "%s same at %d\n", qPrintable(TEMP_DATA_BIN), addr); + dbg(2, "%s same at %d\n", gbLogCStr(TEMP_DATA_BIN), addr); } else { - dbg(2, "%s differs at %d\n", qPrintable(TEMP_DATA_BIN), addr); + dbg(2, "%s differs at %d\n", gbLogCStr(TEMP_DATA_BIN), addr); init_scan = 0; addr = dpos; bsize = read_bsize; @@ -558,7 +554,7 @@ void MtkLoggerBase::mtk_read() } else { fseek(dout, addr, SEEK_SET); if (fwrite(data, 1, rcvd_bsize, dout) != rcvd_bsize) { - fatal(MYNAME ": Failed to write temp. binary file\n"); + gbFatal("Failed to write temp. binary file\n"); } addr += rcvd_bsize; if (global_opts.verbose_status || (global_opts.debug_level >= 2 && global_opts.debug_level < 5)) { @@ -566,7 +562,7 @@ void MtkLoggerBase::mtk_read() if (addr >= addr_max) { perc = 100; } - fprintf(stderr, "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bReading 0x%.6x %3d %%", addr, perc); + gbDebug("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bReading 0x%.6x %3d %%", addr, perc); } } } @@ -579,7 +575,7 @@ void MtkLoggerBase::mtk_read() fclose(dout); } if (global_opts.verbose_status || (global_opts.debug_level >= 2 && global_opts.debug_level < 5)) { - fprintf(stderr,"\n"); + gbDebug("\n"); } // Fixme - Order or. Enable - parse - erase ?? @@ -733,17 +729,17 @@ void MtkLoggerBase::mtk_csv_init(const QString& csv_fname, unsigned long bitmask { FILE* cf; - dbg(1, "Opening csv output file %s...\n", qPrintable(csv_fname)); + dbg(1, "Opening csv output file %s...\n", gbLogCStr(csv_fname)); - // can't use gbfopen here - it will fatal() if file doesn't exist + // can't use gbfopen here - it will gbFatal() if file doesn't exist if ((cf = ufopen(csv_fname, "r")) != nullptr) { fclose(cf); - warning(MYNAME ": CSV file %s already exist ! Cowardly refusing to overwrite.\n", qPrintable(csv_fname)); + gbWarning("CSV file %s already exist ! Cowardly refusing to overwrite.\n", gbLogCStr(csv_fname)); return; } - if ((cd = gbfopen(csv_fname, "w", MYNAME)) == nullptr) { - fatal(MYNAME ": Can't open csv file '%s'\n", qPrintable(csv_fname)); + if ((cd = gbfopen(csv_fname, "w")) == nullptr) { + gbFatal("Can't open csv file '%s'\n", gbLogCStr(csv_fname)); } /* Add the header line */ @@ -926,12 +922,11 @@ int MtkLoggerBase::mtk_parse(unsigned char* data, int dataLen, unsigned int bmas dbg(5,"Entering mtk_parse, count = %i, dataLen = %i\n", count, dataLen); if (global_opts.debug_level > 5) { - fprintf(stderr,"# Data block:"); + gbDebug("# Data block:"); for (int j = 0; j 0) { - fprintf(stderr,"#!! Invalid INFO block !! %d bytes\n >> ", dataLen); + gbDebug("#!! Invalid INFO block !! %d bytes\n >> ", dataLen); for (bm=0; bm<16; bm++) { - fprintf(stderr, "%.2x ", data[bm]); + gbDebug("%.2x ", data[bm]); } - fprintf(stderr,"\n"); + gbDebug("\n"); } return 0; } @@ -1242,7 +1237,7 @@ int MtkLoggerBase::mtk_log_len(unsigned int bitmask) for (int i = 0; i<32; i++) { if ((1U< DISTANCE && global_opts.debug_level > 0) { - warning(MYNAME ": Unknown size/meaning of bit %d\n", i); + gbWarning("Unknown size/meaning of bit %d\n", i); } if ((i == SID || i == ELEVATION || i == AZIMUTH || i == SNR) && (1U< // for isprint +#include // for assert #include // for fabs #include // for snprintf, sscanf, fprintf, fputc, stderr #include // for strncmp, strchr, strlen, strstr, memset, strrchr @@ -31,12 +31,12 @@ #include // for QDateTime #include // for QDebug #include // for QList +#include // for QRegularExpression #include // for QString #include // for QStringList #include // for hex #include // for QThread #include // for QTime -#include // for UTC #include // for qPrintable, foreach #include "defs.h" @@ -155,8 +155,6 @@ time I have seen this is when the recording stops suddenly, where the last sentence is truncated - and missing part of the line, including the checksum. */ -#define MYNAME "nmea" - /* * Slightly different than the Magellan checksum fn. */ @@ -246,7 +244,7 @@ NmeaFormat::rd_init(const QString& fname) } read_mode = rm_file; - file_in = gbfopen(fname, "rb", MYNAME); + file_in = gbfopen(fname, "rb"); } void @@ -261,7 +259,7 @@ NmeaFormat::rd_deinit() file_in = nullptr; break; default: - fatal("nmea_rd_deinit: illegal read_mode.\n"); + gbFatal("nmea_rd_deinit: illegal read_mode.\n"); break; } @@ -275,7 +273,7 @@ NmeaFormat::rd_deinit() void NmeaFormat::wr_init(const QString& fname) { - file_out = gbfopen(fname, opt_append ? "a+" : "w+", MYNAME); + file_out = gbfopen(fname, opt_append ? "a+" : "w+"); sleepms = -1; if (opt_sleep) { @@ -816,8 +814,8 @@ NmeaFormat::nmea_fix_timestamps(route_head* track) if (!prev_datetime.date().isValid()) { if (!optdate) { - warning(MYNAME ": No date found within track (all points dropped)!\n"); - warning(MYNAME ": Please use option \"date\" to preset a valid date for those tracks.\n"); + gbWarning("No date found within track (all points dropped)!\n"); + gbWarning("Please use option \"date\" to preset a valid date for those tracks.\n"); track_del_head(track); return; } @@ -982,7 +980,7 @@ NmeaFormat::read() if (optdate) { opt_tm = QDate::fromString(optdate, u"yyyyMMdd"); if (!opt_tm.isValid()) { - fatal(MYNAME ": Invalid date \"%s\"!\n", qPrintable(optdate)); + gbFatal("Invalid date \"%s\"!\n", gbLogCStr(optdate)); } } @@ -1011,7 +1009,7 @@ NmeaFormat::read() } datum = GPS_Lookup_Datum_Index(sdatum); if (datum < 0) { - fatal(MYNAME "/SonyGPS: Unsupported datum \"%s\" in source data!\n", sdatum); + gbFatal("/SonyGPS: Unsupported datum \"%s\" in source data!\n", sdatum); } } continue; @@ -1038,26 +1036,27 @@ NmeaFormat::rd_position_init(const QString& fname) read_mode = rm_serial; gbser_set_speed(gbser_handle, 4800); } else { - fatal(MYNAME ": Could not open '%s' for position tracking.\n", qPrintable(fname)); + gbFatal("Could not open '%s' for position tracking.\n", gbLogCStr(fname)); } gbser_flush(gbser_handle); if (opt_baud) { if (!gbser_set_speed(gbser_handle, opt_baud.get_result())) { - fatal(MYNAME ": Unable to set baud rate %s\n", qPrintable(opt_baud)); + gbFatal("Unable to set baud rate %s\n", gbLogCStr(opt_baud)); } } posn_fname = fname; } void -NmeaFormat::safe_print(int cnt, const char* b) +NmeaFormat::safe_print(const QString& b) { - for (int i = 0; i < cnt; i++) { - char c = isprint(b[i]) ? b[i] : '.'; - fputc(c, stderr); - } + static const QRegularExpression re("[^[:print:]]"); + assert(re.isValid()); + + QString str(b); + qDebug().noquote() << str.replace(re, "."); } int NmeaFormat::hunt_sirf() @@ -1069,7 +1068,7 @@ int NmeaFormat::hunt_sirf() for (brp = br; *brp > 0; brp++) { if (global_opts.debug_level > 1) { - fprintf(stderr, "Trying %d\n", *brp); + gbDebug("Trying %d\n", *brp); } /* @@ -1118,12 +1117,12 @@ NmeaFormat::rd_position(posn_status* /*unused*/) ibuf[0] = 0; int rv = gbser_read_line(gbser_handle, ibuf, sizeof(ibuf), 2000, 0x0a, 0x0d); if (global_opts.debug_level > 1) { - safe_print(strlen(ibuf), ibuf); + safe_print(ibuf); } if (rv < 0) { if (am_sirf == 0) { if (global_opts.debug_level > 1) { - warning(MYNAME ": Attempting sirf mode.\n"); + gbWarning("Attempting sirf mode.\n"); } /* This is tacky, we have to change speed * to 9600bps to tell it to speak NMEA at @@ -1135,7 +1134,7 @@ NmeaFormat::rd_position(posn_status* /*unused*/) continue; } } - fatal(MYNAME ": No data received on %s.\n", qPrintable(posn_fname)); + gbFatal("No data received on %s.\n", gbLogCStr(posn_fname)); } nmea_parse_one_line(ibuf); if (lt != last_read_time) { diff --git a/nmea.h b/nmea.h index 495360d89..c7807c58b 100644 --- a/nmea.h +++ b/nmea.h @@ -111,7 +111,7 @@ class NmeaFormat : public Format void nmea_fix_timestamps(route_head* track); static bool notalkerid_strmatch(const QByteArray& s1, const char* sentenceFormatterMnemonicCode); void nmea_parse_one_line(const QByteArray& ibuf); - static void safe_print(int cnt, const char* b); + static void safe_print(const QString& b); int hunt_sirf(); void nmea_wayptpr(const Waypoint* wpt) const; void nmea_track_init(const route_head* unused); diff --git a/nukedata.cc b/nukedata.cc index e2598523d..fea3c4fa1 100644 --- a/nukedata.cc +++ b/nukedata.cc @@ -24,7 +24,6 @@ #include "nukedata.h" #if FILTERS_ENABLED -#define MYNAME "nukedata" void NukeDataFilter::process() { diff --git a/osm.cc b/osm.cc index 06670f403..65ae169c5 100644 --- a/osm.cc +++ b/osm.cc @@ -35,8 +35,6 @@ #include "xmlgeneric.h" // for xml_deinit, xml_init, xml_read -#define MYNAME "osm" - const QStringList OsmFormat::osm_features = { "- dummy -", /* 0 */ "aeroway", /* 1 */ @@ -429,7 +427,7 @@ OsmFormat::osm_node(const QString& /*unused*/, const QXmlStreamAttributes* attrv QString atstr = attrv->value("id").toString(); wpt->description = "osm-id " + atstr; if (waypoints.contains(atstr)) { - warning(MYNAME ": Duplicate osm-id %s!\n", qPrintable(atstr)); + gbWarning("Duplicate osm-id %s!\n", gbLogCStr(atstr)); } else { waypoints.insert(atstr, wpt); wpt->wpt_flags.fmt_use = 1; @@ -526,7 +524,7 @@ OsmFormat::osm_way_nd(const QString& /*unused*/, const QXmlStreamAttributes* att auto* tmp = new Waypoint(*ctmp); route_add_wpt(rte, tmp); } else { - warning(MYNAME ": Way reference id \"%s\" wasn't listed under nodes!\n", qPrintable(atstr)); + gbWarning("Way reference id \"%s\" wasn't listed under nodes!\n", gbLogCStr(atstr)); } } } diff --git a/ozi.cc b/ozi.cc index f0c7e8d91..f7df0a80d 100644 --- a/ozi.cc +++ b/ozi.cc @@ -63,7 +63,6 @@ #include "src/core/textstream.h" // for TextStream -#define MYNAME "OZI" #define BADCHARS ",\r\n" #define DAYS_SINCE_1990 25569 @@ -71,7 +70,7 @@ void OziFormat::ozi_open_io(const QString& fname, QIODevice::OpenModeFlag mode) { stream = new gpsbabel::TextStream; - stream->open(fname, mode, MYNAME, opt_codec.get().toUtf8()); + stream->open(fname, mode, opt_codec.get().toUtf8()); if (mode & QFile::WriteOnly) { stream->setRealNumberNotation(QTextStream::FixedNotation); @@ -329,7 +328,7 @@ OziFormat::ozi_init_units(const int direction) /* 0 = in; 1 = out */ altunit = 'f'; alt_scale = FEET_TO_METERS(1.0); /* feet */ } else { - fatal(MYNAME ": Unknown value (%s) for option 'altunit'!\n", qPrintable(altunit_opt)); + gbFatal("Unknown value (%s) for option 'altunit'!\n", gbLogCStr(altunit_opt)); } if (direction != 0) { alt_scale = 1.0 / alt_scale; @@ -345,7 +344,7 @@ OziFormat::ozi_init_units(const int direction) /* 0 = in; 1 = out */ proxunit = 'k'; prox_scale = 1000.0; /* kilometers */ } else { - fatal(MYNAME ": Unknown value (%s) for option 'proxunit'!\n", qPrintable(proxunit_opt)); + gbFatal("Unknown value (%s) for option 'proxunit'!\n", gbLogCStr(proxunit_opt)); } if (direction != 0) { prox_scale = 1.0 / prox_scale; @@ -400,7 +399,7 @@ OziFormat::wr_init(const QString& fname) } ozi_init_units(1); - parse_distance(proximityarg, &proximity, 1.0 / prox_scale, MYNAME); + parse_distance(proximityarg, &proximity, 1.0 / prox_scale); } void @@ -671,7 +670,7 @@ OziFormat::read() datum = GPS_Lookup_Datum_Index(buff); if (datum < 0) { - fatal(MYNAME ": Unsupported datum '%s'.\n", qPrintable(buff)); + gbFatal("Unsupported datum '%s'.\n", gbLogCStr(buff)); } } else if (linecount == 3) { if (buff.startsWith( "Altitude is in ", Qt::CaseInsensitive)) { @@ -683,7 +682,7 @@ OziFormat::read() altunit = 'm'; alt_scale = 1.0; } else { - fatal(MYNAME ": Unknown unit (%s) used by altitude values!\n", qPrintable(unit)); + gbFatal("Unknown unit (%s) used by altitude values!\n", gbLogCStr(unit)); } } } else if ((linecount == 5) && (ozi_objective == trkdata)) { @@ -722,7 +721,7 @@ OziFormat::read() ozi_parse_waypt(i, s, wpt_tmp, fsdata); break; case posndata: - fatal(MYNAME ": realtime positioning not supported.\n"); + gbFatal("realtime positioning not supported.\n"); break; } i++; @@ -757,7 +756,7 @@ OziFormat::read() } break; case posndata: - fatal(MYNAME ": realtime positioning not supported.\n"); + gbFatal("realtime positioning not supported.\n"); break; } diff --git a/parse.cc b/parse.cc index 2ea5bb63d..d48880c6b 100644 --- a/parse.cc +++ b/parse.cc @@ -28,7 +28,7 @@ #include // for QString #include // for qPrintable -#include "defs.h" // for case_ignore_strcmp, fatal, grid_type, KPH_TO_MPS, MPH_TO_MPS, warning, FEET_TO_METERS, KNOTS_TO_MPS, kDatumWGS84, FATHOMS_TO_METERS, MILES_TO_METERS, NMILES_TO_METERS, parse_coordinates, CSTR, parse_distance, parse_double, parse_integer, parse_speed +#include "defs.h" // for case_ignore_strcmp, gbFatal, grid_type, KPH_TO_MPS, MPH_TO_MPS, gbWarning, FEET_TO_METERS, KNOTS_TO_MPS, kDatumWGS84, FATHOMS_TO_METERS, MILES_TO_METERS, NMILES_TO_METERS, parse_coordinates, CSTR, parse_distance, parse_double, parse_integer, parse_speed #include "jeeps/gpsmath.h" // for GPS_Math_Known_Datum_To_WGS84_M, GPS_Math_Swiss_EN_To_WGS84, GPS_Math_UKOSMap_To_WGS84_H, GPS_Math_UTM_EN_To_Known_Datum @@ -53,24 +53,24 @@ int parse_integer(const QString& str, const QString& id, bool* ok, QString* end, result = stoi(ss, &pos, base); } catch (const std::invalid_argument&) { if (ok == nullptr) { - fatal("%s: conversion to integer failed: invalid argument \"%s\".\n", - qPrintable(id), qPrintable(str)); + gbFatal("%s: conversion to integer failed: invalid argument \"%s\".\n", + gbLogCStr(id), gbLogCStr(str)); } else { *ok = false; return 0; } } catch (const std::out_of_range&) { if (ok == nullptr) { - fatal("%s: conversion to integer failed: out of range \"%s\".\n", - qPrintable(id), qPrintable(str)); + gbFatal("%s: conversion to integer failed: out of range \"%s\".\n", + gbLogCStr(id), gbLogCStr(str)); } else { *ok = false; return 0; } } catch (...) { if (ok == nullptr) { - fatal("%s: conversion to integer failed: unknown exception \"%s\".\n", - qPrintable(id), qPrintable(str)); + gbFatal("%s: conversion to integer failed: unknown exception \"%s\".\n", + gbLogCStr(id), gbLogCStr(str)); } else { *ok = false; return 0; @@ -80,8 +80,8 @@ int parse_integer(const QString& str, const QString& id, bool* ok, QString* end, QString remainder = QString::fromStdString(ss.erase(0, pos)); if ((end == nullptr) && !remainder.trimmed().isEmpty()) { if (ok == nullptr) { - fatal("%s: conversion to integer failed: conversion of \"%s\" failed due to unexpected trailing data \"%s\".\n", - qPrintable(id), qPrintable(str), qPrintable(remainder)); + gbFatal("%s: conversion to integer failed: conversion of \"%s\" failed due to unexpected trailing data \"%s\".\n", + gbLogCStr(id), gbLogCStr(str), gbLogCStr(remainder)); } else { *ok = false; return 0; @@ -120,24 +120,24 @@ double parse_double(const QString& str, const QString& id, bool* ok, QString* en result = stod(ss, &pos); } catch (const std::invalid_argument&) { if (ok == nullptr) { - fatal("%s: conversion to double failed: invalid argument \"%s\".\n", - qPrintable(id), qPrintable(str)); + gbFatal("%s: conversion to double failed: invalid argument \"%s\".\n", + gbLogCStr(id), gbLogCStr(str)); } else { *ok = false; return 0.0; } } catch (const std::out_of_range&) { if (ok == nullptr) { - fatal("%s: conversion to double failed: out of range \"%s\".\n", - qPrintable(id), qPrintable(str)); + gbFatal("%s: conversion to double failed: out of range \"%s\".\n", + gbLogCStr(id), gbLogCStr(str)); } else { *ok = false; return 0.0; } } catch (...) { if (ok == nullptr) { - fatal("%s: conversion to double failed: unknown exception \"%s\".\n", - qPrintable(id), qPrintable(str)); + gbFatal("%s: conversion to double failed: unknown exception \"%s\".\n", + gbLogCStr(id), gbLogCStr(str)); } else { *ok = false; return 0.0; @@ -147,8 +147,8 @@ double parse_double(const QString& str, const QString& id, bool* ok, QString* en QString remainder = QString::fromStdString(ss.erase(0, pos)); if ((end == nullptr) && !remainder.trimmed().isEmpty()) { if (ok == nullptr) { - fatal("%s: conversion to double failed: conversion of \"%s\" failed due to unexpected trailing data \"%s\".\n", - qPrintable(id), qPrintable(str), qPrintable(remainder)); + gbFatal("%s: conversion to double failed: conversion of \"%s\" failed due to unexpected trailing data \"%s\".\n", + gbLogCStr(id), gbLogCStr(str), gbLogCStr(remainder)); } else { *ok = false; return 0.0; @@ -171,11 +171,10 @@ double parse_double(const QString& str, const QString& id, bool* ok, QString* en * str: input string, i.e. "128.2 km" or "22mi" * val: pointer to resulting value * scale: scaling parameter for unit-less values - * module: calling module, i.e. "garmin_txt" */ int -parse_distance(const QString& str, double* val, double scale, const char* module) +parse_distance(const QString& str, double* val, double scale) { if (str.isEmpty()) { return 0; @@ -183,7 +182,7 @@ parse_distance(const QString& str, double* val, double scale, const char* module QString unit; constexpr bool* dieonfailure = nullptr; - *val = parse_double(str, module, dieonfailure, &unit); + *val = parse_double(str, "", dieonfailure, &unit); if (fabs(*val) + 1 >= 1.0e25) { return 0; /* not only Garmin uses this as 'unknown value' */ @@ -212,7 +211,7 @@ parse_distance(const QString& str, double* val, double scale, const char* module } else if (case_ignore_strcmp(unit, "fa") == 0) { *val = FATHOMS_TO_METERS(*val); } else { - fatal("%s: Unsupported distance unit in item '%s'!\n", module, qPrintable(str)); + gbFatal("Unsupported distance unit in item '%s'!\n", gbLogCStr(str)); } return 2; } @@ -223,10 +222,9 @@ parse_distance(const QString& str, double* val, double scale, const char* module * str: input string, i.e. "22.3 km/h" or "40mph" * val: pointer to resulting value * scale: scaling parameter for unit-less values - * module: calling module, i.e. "garmin_txt" */ int -parse_speed(const QString& str, double* val, const double scale, const char* module) +parse_speed(const QString& str, double* val, const double scale) { if (str.isEmpty()) { @@ -235,7 +233,7 @@ parse_speed(const QString& str, double* val, const double scale, const char* mod QString unit; constexpr bool* dieonfailure = nullptr; - *val = parse_double(str, module, dieonfailure, &unit); + *val = parse_double(str, "", dieonfailure, &unit); unit = unit.trimmed(); @@ -263,7 +261,7 @@ parse_speed(const QString& str, double* val, const double scale, const char* mod } else if (case_ignore_strcmp(unit, "mih") == 0) { *val = MPH_TO_MPS(*val); } else { - warning("%s: Unsupported speed unit '%s' in item '%s'!\n", module, qPrintable(unit), qPrintable(str)); + gbWarning("Unsupported speed unit '%s' in item '%s'!\n", gbLogCStr(unit), gbLogCStr(str)); } return 2; @@ -278,7 +276,7 @@ parse_speed(const QString& str, double* val, const double scale, const char* mod int parse_coordinates(const char* str, int datum, const grid_type grid, - double* latitude, double* longitude, const char* module) + double* latitude, double* longitude) { double lat; double lon; @@ -342,8 +340,8 @@ parse_coordinates(const char* str, int datum, const grid_type grid, valid = (ct == 3); if (valid) { if (! GPS_Math_UKOSMap_To_WGS84_H(map, lx, ly, &lat, &lon)) - fatal("%s: Unable to convert BNG coordinates (%s)!\n", - module, str); + gbFatal("Unable to convert BNG coordinates (%s)!\n", + str); } lathemi = lonhemi = '\0'; break; @@ -356,8 +354,8 @@ parse_coordinates(const char* str, int datum, const grid_type grid, valid = (ct == 4); if (valid) { if (! GPS_Math_UTM_EN_To_Known_Datum(&lat, &lon, utme, utmn, utmz, utmc, datum)) - fatal("%s: Unable to convert UTM coordinates (%s)!\n", - module, str); + gbFatal("Unable to convert UTM coordinates (%s)!\n", + str); } lathemi = lonhemi = '\0'; break; @@ -376,14 +374,14 @@ parse_coordinates(const char* str, int datum, const grid_type grid, } default: /* this should never happen in a release version */ - fatal("%s/util: Unknown grid in parse_coordinates (%d)!\n", - module, (int)grid); + gbFatal("Unknown grid in parse_coordinates (%d)!\n", + (int)grid); } if (! valid) { - warning("%s: sscanf error using format \"%s\"!\n", module, format); - warning("%s: parsing has stopped at parameter number %d.\n", module, ct); - fatal("%s: could not convert coordinates \"%s\"!\n", module, str); + gbWarning("sscanf error using format \"%s\"!\n", format); + gbWarning("parsing has stopped at parameter number %d.\n", ct); + gbFatal("could not convert coordinates \"%s\"!\n", str); } if (lathemi == 'S') { @@ -411,8 +409,8 @@ parse_coordinates(const char* str, int datum, const grid_type grid, int parse_coordinates(const QString& str, int datum, const grid_type grid, - double* latitude, double* longitude, const char* module) + double* latitude, double* longitude) { return parse_coordinates(CSTR(str), datum, grid, - latitude, longitude, module); + latitude, longitude); } diff --git a/polygon.cc b/polygon.cc index 713b15fb8..39fea9d8b 100644 --- a/polygon.cc +++ b/polygon.cc @@ -31,7 +31,6 @@ #if FILTERS_ENABLED -#define MYNAME "Polygon filter" /* * This test for insideness is essentially an odd/even test. The @@ -229,7 +228,7 @@ void PolygonFilter::process() QString line; gpsbabel::TextStream stream; - stream.open(polyfileopt, QIODevice::ReadOnly, MYNAME); + stream.open(polyfileopt, QIODevice::ReadOnly); double olat = BADVAL; double olon = BADVAL; @@ -249,8 +248,7 @@ void PolygonFilter::process() int argsfound = sscanf(CSTR(line), "%lf %lf", &lat2, &lon2); if ((argsfound != 2) && (line.trimmed().size() > 0)) { - warning(MYNAME - ": Warning: Polygon file contains unusable vertex on line %d.\n", + gbWarning("Warning: Polygon file contains unusable vertex on line %d.\n", fileline); } else if (lat1 != BADVAL && lon1 != BADVAL && lat2 != BADVAL && lon2 != BADVAL) { diff --git a/position.cc b/position.cc index 45b032bc5..21f116e8d 100644 --- a/position.cc +++ b/position.cc @@ -32,7 +32,6 @@ #include "src/core/datetime.h" // for DateTime #if FILTERS_ENABLED -#define MYNAME "Position filter" /* tear through a waypoint queue, processing points by distance */ void PositionFilter::position_runqueue(const WaypointList& waypt_list, int qtype) @@ -113,8 +112,8 @@ void PositionFilter::init() check_time = false; if (distopt) { - if (parse_distance(distopt, &pos_dist, kMetersPerFoot, MYNAME) == 0) { - fatal(MYNAME ": No distance specified with distance option.\n"); + if (parse_distance(distopt, &pos_dist, kMetersPerFoot) == 0) { + gbFatal("No distance specified with distance option.\n"); } } diff --git a/qstarz_bl_1000.cc b/qstarz_bl_1000.cc index a0aadce00..f43617972 100644 --- a/qstarz_bl_1000.cc +++ b/qstarz_bl_1000.cc @@ -35,9 +35,6 @@ #include "src/core/logging.h" // for Fatal -#define MYNAME "Qstarz BL-1000" - - enum BL1000_POINT_TYPE { BL1000_POINT_TYPE_UNKNOWN = '-', BL1000_POINT_TYPE_WAY_POINT = 'B', // Button push @@ -135,7 +132,7 @@ QstarzBL1000Format::qstarz_bl_1000_read_record(QDataStream& stream, route_head* stream >> unused2; if (stream.status() != QDataStream::Ok) { - fatal(FatalMsg() << MYNAME << ": File format error on " << fname << ". Perhaps this isn't a Qstarz BL-1000 file"); + gbFatal(FatalMsg() << "File format error on " << fname << ". Perhaps this isn't a Qstarz BL-1000 file"); } BL1000_POINT_TYPE type; @@ -171,7 +168,7 @@ QstarzBL1000Format::qstarz_bl_1000_read_record(QDataStream& stream, route_head* default: type = BL1000_POINT_TYPE_UNKNOWN; - fatal(FatalMsg() << MYNAME << ": File format error on " << fname << ". Unexpected value for RCR (record reason): " << rcr); + gbFatal(FatalMsg() << "File format error on " << fname << ". Unexpected value for RCR (record reason): " << rcr); break; } @@ -205,7 +202,7 @@ QstarzBL1000Format::qstarz_bl_1000_read_record(QDataStream& stream, route_head* fix = fix_unknown; if (type != BL1000_POINT_TYPE_UNKNOWN) { - fatal(FatalMsg() << MYNAME << ": File format error on " << fname << ". Unexpected value for fix quality: " << fixQuality); + gbFatal(FatalMsg() << "File format error on " << fname << ". Unexpected value for fix quality: " << fixQuality); } break; @@ -219,11 +216,11 @@ QstarzBL1000Format::qstarz_bl_1000_read_record(QDataStream& stream, route_head* // qDebug(waypoint) if ((waypoint->latitude < -90) || (waypoint->latitude > 90)) { - fatal(FatalMsg() << MYNAME << ": File format error on " << fname << ". Unexpected value for latitude: " << waypoint->latitude); + gbFatal(FatalMsg() << "File format error on " << fname << ". Unexpected value for latitude: " << waypoint->latitude); } if ((waypoint->longitude < -180) || (waypoint->longitude > 180)) { - fatal(FatalMsg() << MYNAME << ": File format error on " << fname << ". Unexpected value for longitude: " << waypoint->longitude); + gbFatal(FatalMsg() << "File format error on " << fname << ". Unexpected value for longitude: " << waypoint->longitude); } waypoint->altitude = altitude; @@ -273,7 +270,7 @@ QstarzBL1000Format::read() { QFile file(fname); if (!file.open(QIODevice::ReadOnly)) { - fatal(FatalMsg() << MYNAME << ": Error opening file " << fname); + gbFatal(FatalMsg() << "Error opening file " << fname); } QDataStream stream(&file); diff --git a/radius.cc b/radius.cc index 64db76e51..bb5ddd5e8 100644 --- a/radius.cc +++ b/radius.cc @@ -31,7 +31,6 @@ #if FILTERS_ENABLED -#define MYNAME "Radius filter" void RadiusFilter::process() { @@ -97,8 +96,8 @@ void RadiusFilter::init() pos_dist = 0; if (distopt) { - if (parse_distance(distopt, &pos_dist, kMetersPerMile, MYNAME) == 0) { - fatal(MYNAME ": No distance specified with distance option.\n"); + if (parse_distance(distopt, &pos_dist, kMetersPerMile) == 0) { + gbFatal("No distance specified with distance option.\n"); } } diff --git a/reference/badopt1.txt b/reference/badopt1.txt index 7fe10b9cc..e1fa43e80 100644 --- a/reference/badopt1.txt +++ b/reference/badopt1.txt @@ -1 +1 @@ -radius(lat): conversion to double failed: conversion of "44x" failed due to unexpected trailing data "x". +radius: radius(lat): conversion to double failed: conversion of "44x" failed due to unexpected trailing data "x". diff --git a/reference/badopt2.txt b/reference/badopt2.txt index 964922217..fde42f052 100644 --- a/reference/badopt2.txt +++ b/reference/badopt2.txt @@ -1 +1 @@ -stack(depth): conversion to integer failed: invalid argument "b". +stack: stack(depth): conversion to integer failed: invalid argument "b". diff --git a/reference/badopt3.txt b/reference/badopt3.txt index 63c3995fa..df52ed927 100644 --- a/reference/badopt3.txt +++ b/reference/badopt3.txt @@ -1 +1 @@ -gdb(bitscategory): conversion to integer failed: conversion of "0x2z" failed due to unexpected trailing data "z". +gdb: gdb(bitscategory): conversion to integer failed: conversion of "0x2z" failed due to unexpected trailing data "z". diff --git a/reference/badopt4.txt b/reference/badopt4.txt index ea153596b..9818c6a53 100644 --- a/reference/badopt4.txt +++ b/reference/badopt4.txt @@ -1 +1 @@ -csv(snlen): conversion to integer failed: invalid argument "a". +csv: csv(snlen): conversion to integer failed: invalid argument "a". diff --git a/reference/dg200erase.log b/reference/dg200erase.log index 706e2cbbc..260d4754c 100644 --- a/reference/dg200erase.log +++ b/reference/dg200erase.log @@ -1,8 +1,12 @@ -TX: Frame Start a0 a2 Payload_Len 0003 Cmd: getfileheader -RX: Start a0a2 Len 0005 Cmd: getfileheader -found 0 headers, nextheader=0 -no further headers, aborting the loop -TX: Frame Start a0 a2 Payload_Len 0001 Cmd: getconfig -RX: Start a0a2 Len 002e Cmd: getconfig -TX: Frame Start a0 a2 Payload_Len 0003 Cmd: erase -RX: Start a0a2 Len 0005 Cmd: erase +dg-200-bin: options: module/option=value: dg-200-bin/erase="1" +dg-200-bin: options: module/option=value: dg-200-bin/erase_only="0" (=default) +dg-200-bin: TX: Frame Start a0 a2 Payload_Len 0003 Cmd: getfileheader +dg-200-bin: RX: Start a0a2 Len 0005 Cmd: getfileheader +dg-200-bin: found 0 headers, nextheader=0 +dg-200-bin: no further headers, aborting the loop +dg-200-bin: TX: Frame Start a0 a2 Payload_Len 0001 Cmd: getconfig +dg-200-bin: RX: Start a0a2 Len 002e Cmd: getconfig +dg-200-bin: TX: Frame Start a0 a2 Payload_Len 0003 Cmd: erase +dg-200-bin: RX: Start a0a2 Len 0005 Cmd: erase +gpx: options: module/option=value: gpx/snlen="32" (=default) +gpx: options: module/option=value: gpx/elevprec="3" (=default) diff --git a/reference/mkshort3.log b/reference/mkshort3.log index 38059e1df..52259c58f 100644 --- a/reference/mkshort3.log +++ b/reference/mkshort3.log @@ -1 +1 @@ -mkshort failure, the specified short length is insufficient. +xcsv: mkshort failure, the specified short length is insufficient. diff --git a/reference/track/trackfilter_discard_err.gpx b/reference/track/trackfilter_discard_err.gpx index 144452dc9..20f95b2db 100644 --- a/reference/track/trackfilter_discard_err.gpx +++ b/reference/track/trackfilter_discard_err.gpx @@ -1 +1 @@ -trackfilter-init: Found track point at -36.720713,142.176768 without time! +track: init: Found track point at -36.720713,142.176768 without time! diff --git a/reference/validate_debug.log b/reference/validate_debug.log index 55630cc0c..343d8f61f 100644 --- a/reference/validate_debug.log +++ b/reference/validate_debug.log @@ -1,13 +1,13 @@ - -Processing waypts -point ct: 2, waypt_count: 2 - -Processing routes -route 0 ct: 2, waypt_count: 2, segments 1 -route head ct: 1, route_count: 1, total segment count: 1 -total route point ct: 2, route_waypt_count: 2 - -Processing tracks -track 0 ct: 2, waypt_count: 2, segments 1 -track head ct: 1, track_count: 1, total segment count: 1 -total track point ct: 2, track_waypt_count: 2 +validate: +validate: Processing waypts +validate: point ct: 2, waypt_count: 2 +validate: +validate: Processing routes +validate: route 0 ct: 2, waypt_count: 2, segments 1 +validate: route head ct: 1, route_count: 1, total segment count: 1 +validate: total route point ct: 2, route_waypt_count: 2 +validate: +validate: Processing tracks +validate: track 0 ct: 2, waypt_count: 2, segments 1 +validate: track head ct: 1, track_count: 1, total segment count: 1 +validate: total track point ct: 2, track_waypt_count: 2 diff --git a/reference/validate_empty.log b/reference/validate_empty.log index 72f1000fe..fd05dd69b 100644 --- a/reference/validate_empty.log +++ b/reference/validate_empty.log @@ -1 +1 @@ -validate:No input +validate: No input diff --git a/resample.cc b/resample.cc index b736ed373..d8b406213 100644 --- a/resample.cc +++ b/resample.cc @@ -32,7 +32,7 @@ #include // for qSetRealNumberPrecision #include // for qDebug, qint64 -#include "defs.h" // for Waypoint, route_head, fatal, WaypointList, track_add_wpt, track_disp_all, RouteList, track_add_head, track_del_wpt, track_swap, UrlList, gb_color, global_options, global_opts +#include "defs.h" // for Waypoint, route_head, gbFatal, WaypointList, track_add_wpt, track_disp_all, RouteList, track_add_head, track_del_wpt, track_swap, UrlList, gb_color, global_options, global_opts #include "src/core/datetime.h" // for DateTime #include "src/core/logging.h" // for FatalMsg #include "src/core/nvector.h" // for NVector @@ -40,8 +40,6 @@ #if FILTERS_ENABLED -#define MYNAME "resample" - void ResampleFilter::average_waypoint(Waypoint* wpt, bool zero_stuffed) { @@ -194,7 +192,7 @@ void ResampleFilter::process() { if (interpolateopt) { if (track_count() == 0) { - fatal(FatalMsg() << MYNAME ": Found no tracks to operate on."); + gbFatal(FatalMsg() << "Found no tracks to operate on."); } auto interpolate_rte_lambda = [this](const route_head* rte)->void { @@ -229,7 +227,7 @@ void ResampleFilter::process() if (decimateopt) { if (track_count() == 0) { - fatal(FatalMsg() << MYNAME ": Found no tracks to operate on."); + gbFatal(FatalMsg() << "Found no tracks to operate on."); } auto decimate_rte_lambda = [this](const route_head* rte)->void { @@ -245,24 +243,24 @@ void ResampleFilter::init() if (averageopt) { average_count = averageopt.get_result(); if (average_count < 2) { - fatal(FatalMsg() << MYNAME ": the average count must be greater than one."); + gbFatal(FatalMsg() << "the average count must be greater than one."); } } if (decimateopt) { decimate_count = decimateopt.get_result(); if (decimate_count < 2) { - fatal(FatalMsg() << MYNAME ": the decimate count must be greater than one."); + gbFatal(FatalMsg() << "the decimate count must be greater than one."); } } if (interpolateopt) { interpolate_count = interpolateopt.get_result(); if (interpolate_count < 2) { - fatal(FatalMsg() << MYNAME ": the interpolate count must be greater than one."); + gbFatal(FatalMsg() << "the interpolate count must be greater than one."); } if (!averageopt || average_count < interpolate_count) { - fatal(FatalMsg() << MYNAME ": the average option must be used with interpolation, and the average count must be greater than or equal to the interpolation count."); + gbFatal(FatalMsg() << "the average option must be used with interpolation, and the average count must be greater than or equal to the interpolation count."); } } } diff --git a/reverse_route.cc b/reverse_route.cc index ebb80d895..56c1e14b5 100644 --- a/reverse_route.cc +++ b/reverse_route.cc @@ -27,8 +27,6 @@ #if FILTERS_ENABLED -#define MYNAME "Route reversal filter" - /* * reverse_route_wpt fixes up the waypoint flag new_trkseg */ @@ -68,8 +66,7 @@ void ReverseRouteFilter::init() case trkdata: break; default: - fatal(MYNAME ": This filter only works in track " - "or route (-t or -r) mode.\n"); + gbFatal("This filter only works in track or route (-t or -r) mode.\n"); } } diff --git a/rgbcolors.cc b/rgbcolors.cc index a7f03dec4..d7ab004e5 100644 --- a/rgbcolors.cc +++ b/rgbcolors.cc @@ -27,7 +27,7 @@ #include // for QString, QTypeInfo<>::isRelocatable #include // for qPrintable -#include "defs.h" // for fatal, color_to_bbggrr +#include "defs.h" // for gbFatal, color_to_bbggrr /* * Colors derived from http://www.w3.org/TR/SVG/types.html#ColorKeywords @@ -227,6 +227,6 @@ color_to_bbggrr(const QString& cname) return (entry.b << 16) + (entry.g << 8) + entry.r; } - fatal("unrecognized color name %s\n", qPrintable(cname)); + gbFatal("unrecognized color name %s\n", gbLogCStr(cname)); return -1; } diff --git a/session.cc b/session.cc index 8f3efc996..d3ebb655c 100644 --- a/session.cc +++ b/session.cc @@ -50,7 +50,7 @@ curr_session() if (!session_list.isEmpty()) { return &session_list.last(); } else { - fatal("Attempt to fetch session outside of session range."); + gbFatal("Attempt to fetch session outside of session range.\n"); } } diff --git a/shape.cc b/shape.cc index 19af063af..6c6433b1e 100644 --- a/shape.cc +++ b/shape.cc @@ -40,8 +40,6 @@ #endif -#define MYNAME "shape" - /************************************************************************/ /* SHPOpenGpsbabel() */ /************************************************************************/ @@ -147,21 +145,21 @@ ShapeFormat::DBFCreateGpsbabel(const QString& pszFilename) [[noreturn]] void ShapeFormat::dump_fields() const { char name[12]; - warning(MYNAME ": Database fields:\n"); + gbWarning("Database fields:\n"); const int nFields = DBFGetFieldCount(ihandledb); for (int i = 0; i < nFields; i++) { DBFFieldType type = DBFGetFieldInfo(ihandledb, i, name, nullptr, nullptr); - warning(MYNAME ": Field Index: %2d, Field Name: %12s, Field Type %d\n", i, name, type); + gbWarning("Field Index: %2d, Field Name: %12s, Field Type %d\n", i, name, type); } - fatal("\n"); + gbFatal("\n"); } void ShapeFormat::check_field_index(const int fieldIdx) const { const int maxFields = DBFGetFieldCount(ihandledb); if (fieldIdx < 0 || fieldIdx >= maxFields) { - warning(MYNAME ": dbf file for %s doesn't have a field index number %d.\n", qPrintable(ifname), fieldIdx); - warning(MYNAME ": the minimum field number is 0 and the maximum field number is %d.\n",maxFields-1); + gbWarning("dbf file for %s doesn't have a field index number %d.\n", gbLogCStr(ifname), fieldIdx); + gbWarning("the minimum field number is 0 and the maximum field number is %d.\n",maxFields-1); dump_fields(); } } @@ -170,7 +168,7 @@ int ShapeFormat::get_field_index(const QString& fieldName) const { const int fieldIdx = DBFGetFieldIndex(ihandledb, CSTR(fieldName)); if (fieldIdx < 0) { - warning(MYNAME ": dbf file for %s doesn't have a field named '%s'.\n", qPrintable(ifname), qPrintable(fieldName)); + gbWarning("dbf file for %s doesn't have a field named '%s'.\n", gbLogCStr(ifname), gbLogCStr(fieldName)); dump_fields(); } return fieldIdx; @@ -183,21 +181,21 @@ ShapeFormat::rd_init(const QString& fname) // TODO: The .prj file can define the the coordinate system and projection information. ihandle = SHPOpenGpsbabel(fname, "rb"); if (ihandle == nullptr) { - fatal(MYNAME ": Cannot open shp file %s for reading\n", qPrintable(ifname)); + gbFatal("Cannot open shp file %s for reading\n", gbLogCStr(ifname)); } ihandledb = DBFOpenGpsbabel(fname, "rb"); if (ihandledb == nullptr) { - fatal(MYNAME ": Cannot open dbf file %s for reading\n", qPrintable(ifname)); + gbFatal("Cannot open dbf file %s for reading\n", gbLogCStr(ifname)); } const char* codepage = DBFGetCodePage(ihandledb); if (codepage) { QString qcodepage(codepage); if (qcodepage.compare(u"UTF-8", Qt::CaseInsensitive)) { - warning(MYNAME ": dbf file %s is in code page %s, but we always process dbf files as UTF-8.\n",qPrintable(ifname),codepage); + gbWarning("dbf file %s is in code page %s, but we always process dbf files as UTF-8.\n",gbLogCStr(ifname),codepage); } } else { - warning(MYNAME ": dbf file %s uses unknown code page, assuming UTF-8.\n", qPrintable(ifname)); + gbWarning("dbf file %s uses unknown code page, assuming UTF-8.\n", gbLogCStr(ifname)); } } @@ -365,7 +363,7 @@ ShapeFormat::read() default: err: - warning("This file contains shapefile geometry type %s that does not naturally convert\nCustom programming is likely required.\n", + gbWarning("This file contains shapefile geometry type %s that does not naturally convert\nCustom programming is likely required.\n", etype); break; } @@ -469,13 +467,13 @@ ShapeFormat::write() ohandle = SHPCreateGpsbabel(ofname, SHPT_POINT); if (ohandle == nullptr) { - fatal(MYNAME ": Cannot open shp file %s for writing\n", - qPrintable(ofname)); + gbFatal("Cannot open shp file %s for writing\n", + gbLogCStr(ofname)); } ohandledb = DBFCreateExGpsbabel(ofname, "UTF-8\n"); if (ohandledb == nullptr) { - fatal(MYNAME ": Cannot open dbf file %s for writing\n", - qPrintable(ofname)); + gbFatal("Cannot open dbf file %s for writing\n", + gbLogCStr(ofname)); } nameFieldIdx=DBFAddField(ohandledb,"name",FTString,100,0); auto write_wpt_lambda = [this](const Waypoint* wpt)->void { @@ -489,13 +487,13 @@ ShapeFormat::write() ohandle = SHPCreateGpsbabel(ofname, SHPT_ARC); if (ohandle == nullptr) { - fatal(MYNAME ": Cannot open shp file %s for writing\n", - qPrintable(ofname)); + gbFatal("Cannot open shp file %s for writing\n", + gbLogCStr(ofname)); } ohandledb = DBFCreateExGpsbabel(ofname, "UTF-8\n"); if (ohandledb == nullptr) { - fatal(MYNAME ": Cannot open dbf file %s for writing\n", - qPrintable(ofname)); + gbFatal("Cannot open dbf file %s for writing\n", + gbLogCStr(ofname)); } nameFieldIdx=DBFAddField(ohandledb,"name",FTString,100,0); auto poly_init_lambda = [this](const route_head* rte)->void { @@ -515,7 +513,7 @@ ShapeFormat::write() break; } case posndata: - fatal(MYNAME ": Realtime positioning not supported\n"); + gbFatal("Realtime positioning not supported\n"); break; } } diff --git a/skytraq.cc b/skytraq.cc index a4b013761..e3098384c 100644 --- a/skytraq.cc +++ b/skytraq.cc @@ -44,8 +44,6 @@ #include "gbser.h" // for gbser_set_speed, gbser_OK, gbser_deinit -#define MYNAME "skytraq" - #define TIMEOUT 5000 #define SECTOR_SIZE 4096 #define FULL_ITEM_LEN 18 @@ -67,43 +65,43 @@ void -SkytraqBase::db(int l, const char* msg, ...) +SkytraqBase::dbg(int l, const char* msg, ...) { - va_list ap; - va_start(ap, msg); if (global_opts.debug_level >= l) { - vprintf(msg, ap); + va_list ap; + va_start(ap, msg); + gbVLegacyLog(QtDebugMsg, msg, ap); + va_end(ap); } - va_end(ap); } void -SkytraqBase::rd_drain() const +SkytraqBase::rd_drain() { if (gbser_flush(serial_handle)) { - db(1, MYNAME ": rd_drain(): Comm error\n"); + dbg(1, "rd_drain(): Comm error\n"); } } int -SkytraqBase::rd_char(int* errors) const +SkytraqBase::rd_char(int* errors) { while (*errors > 0) { int c = gbser_readc_wait(serial_handle, TIMEOUT); if (c < 0) { - db(1, MYNAME ": rd_char(): Got error: %d\n", c); + dbg(1, "rd_char(): Got error: %d\n", c); (*errors)--; } else { - db(4, "rd_char(): Got char: %02x '%c'\n", c, isprint(c) ? c : '.'); + dbg(4, "rd_char(): Got char: %02x '%c'\n", c, isprint(c) ? c : '.'); return c; } } - fatal(MYNAME ": Too many read errors on serial port\n"); + gbFatal("Too many read errors on serial port\n"); return -1; } int -SkytraqBase::rd_buf(uint8_t* buf, int len) const +SkytraqBase::rd_buf(uint8_t* buf, int len) { char dump[16*3+16+2]; @@ -117,15 +115,15 @@ SkytraqBase::rd_buf(uint8_t* buf, int len) const printf("len=%i skytraq_baud=%i timeout=%i\n", len, skytraq_baud, timeout);*/ int rc = gbser_read_wait(serial_handle, (void*)buf, len, timeout); if (rc < 0) { - db(1, MYNAME ": rd_buf(): Read error (%d)\n", rc); + dbg(1, "rd_buf(): Read error (%d)\n", rc); return res_ERROR; } else if (rc < len) { - db(1, MYNAME ": rd_buf(): Read timeout\n"); + dbg(1, "rd_buf(): Read timeout\n"); return res_ERROR; } if (global_opts.debug_level >= 4) { - db(4, "rd_buf(): dump follows:\n"); + dbg(4, "rd_buf(): dump follows:\n"); dump[sizeof(dump)-1] = 0; for (int i = 0; i < (len+15)/16*16; i++) { // count to next 16-byte boundary if (i < len) { @@ -137,7 +135,7 @@ SkytraqBase::rd_buf(uint8_t* buf, int len) const } if ((i+1)%16 == 0) { dump[16*3] = ' '; // gets overwritten with 0 by snprintf - db(4, "%s\n", dump); + dbg(4, "%s\n", dump); } } } @@ -146,7 +144,7 @@ SkytraqBase::rd_buf(uint8_t* buf, int len) const } int -SkytraqBase::rd_word() const +SkytraqBase::rd_word() { int errors = 5; /* allow this many errors */ int c; @@ -154,18 +152,18 @@ SkytraqBase::rd_word() const c = rd_char(&errors); if (c < 0) { - db(1, MYNAME ": rd_word(): Got error: %d\n", c); + dbg(1, "rd_word(): Got error: %d\n", c); return -1; } buffer[0] = c; c = rd_char(&errors); if (c < 0) { - db(1, MYNAME ": rd_word(): Got error: %d\n", c); + dbg(1, "rd_word(): Got error: %d\n", c); return -1; } buffer[1] = c; /* if (rd_buf(buffer, 2) != res_OK) { - db(1, MYNAME ": rd_word(): Read error\n"); + dbg(1, "rd_word(): Read error\n"); return res_ERROR; }*/ @@ -173,17 +171,17 @@ SkytraqBase::rd_word() const } void -SkytraqBase::wr_char(int c) const +SkytraqBase::wr_char(int c) { int rc; - db(4, "Sending: %02x '%c'\n", (unsigned)c, isprint(c) ? c : '.'); + dbg(4, "Sending: %02x '%c'\n", (unsigned)c, isprint(c) ? c : '.'); if (rc = gbser_writec(serial_handle, c), gbser_OK != rc) { - fatal(MYNAME ": Write error (%d)\n", rc); + gbFatal("Write error (%d)\n", rc); } } void -SkytraqBase::wr_buf(const unsigned char* str, int len) const +SkytraqBase::wr_buf(const unsigned char* str, int len) { for (int i = 0; i < len; i++) { wr_char(str[i]); @@ -205,7 +203,7 @@ SkytraqBase::skytraq_calc_checksum(const unsigned char* buf, int len) } int -SkytraqBase::skytraq_rd_msg(void* payload, unsigned int len) const +SkytraqBase::skytraq_rd_msg(void* payload, unsigned int len) { int errors = 5; // Allow this many receiver errors silently. unsigned int c; @@ -224,13 +222,13 @@ SkytraqBase::skytraq_rd_msg(void* payload, unsigned int len) const } } if (state < sizeof(MSG_START)) { - db(1, MYNAME ": Didn't get message start tag\n"); + dbg(1, "Didn't get message start tag\n"); return res_ERROR; } if ((rcv_len = rd_word()) < (signed int)len) { if (rcv_len >= 0) { /* negative values indicate receive errors */ - db(1, MYNAME ": Received message too short (got %i bytes, expected %u)\n", + dbg(1, "Received message too short (got %i bytes, expected %u)\n", rcv_len, len); return res_PROTOCOL_ERR; } @@ -238,7 +236,7 @@ SkytraqBase::skytraq_rd_msg(void* payload, unsigned int len) const } /* at this point, we have rcv_len >= len >= 0 */ - db(2, "Receiving message with %i bytes of payload (expected >=%u)\n", rcv_len, len); + dbg(2, "Receiving message with %i bytes of payload (expected >=%u)\n", rcv_len, len); rd_buf((uint8_t*) payload, len); unsigned int calc_cs = skytraq_calc_checksum((const unsigned char*) payload, len); @@ -249,18 +247,18 @@ SkytraqBase::skytraq_rd_msg(void* payload, unsigned int len) const unsigned int rcv_cs = rd_char(&errors); if (rcv_cs != calc_cs) { - fatal(MYNAME ": Checksum error: got 0x%02x, expected 0x%02x\n", rcv_cs, calc_cs); + gbFatal("Checksum error: got 0x%02x, expected 0x%02x\n", rcv_cs, calc_cs); } if (rd_word() != 0x0D0A) { - fatal(MYNAME ": Didn't get message end tag (CR/LF)\n"); + gbFatal("Didn't get message end tag (CR/LF)\n"); } return res_OK; } void -SkytraqBase::skytraq_wr_msg(const uint8_t* payload, int len) const +SkytraqBase::skytraq_wr_msg(const uint8_t* payload, int len) { rd_drain(); @@ -275,7 +273,7 @@ SkytraqBase::skytraq_wr_msg(const uint8_t* payload, int len) const } int -SkytraqBase::skytraq_expect_ack(uint8_t id) const +SkytraqBase::skytraq_expect_ack(uint8_t id) { uint8_t ack_msg[2]; //int rcv_len; @@ -286,20 +284,20 @@ SkytraqBase::skytraq_expect_ack(uint8_t id) const if (skytraq_rd_msg(ack_msg, sizeof(ack_msg)) == res_OK) { if (ack_msg[0] == 0x83) { if (ack_msg[1] == id) { - db(3, "Got ACK (id=0x%02x)\n", id); + dbg(3, "Got ACK (id=0x%02x)\n", id); return res_OK; } else if (ack_msg[1] == 0) { /* some (all?) devices first send an ACK with id==0, skip that */ continue; } else { - db(1, MYNAME ": Warning: Got unexpected ACK (id=0x%02x)\n", ack_msg[1]); + dbg(1, "Warning: Got unexpected ACK (id=0x%02x)\n", ack_msg[1]); continue; } } else if (ack_msg[0] == 0x84) { - db(3, "Warning: Got NACK (id=0x%02x)\n", ack_msg[1]); + dbg(3, "Warning: Got NACK (id=0x%02x)\n", ack_msg[1]); return res_NACK; } else { - db(3, "Warning: Got unexpected message (id=0x%02x), expected ACK (id=0x%02x)\n", + dbg(3, "Warning: Got unexpected message (id=0x%02x), expected ACK (id=0x%02x)\n", ack_msg[0], id); } } else { @@ -314,7 +312,7 @@ SkytraqBase::skytraq_expect_ack(uint8_t id) const } int -SkytraqBase::skytraq_expect_msg(uint8_t id, uint8_t* payload, int len) const +SkytraqBase::skytraq_expect_msg(uint8_t id, uint8_t* payload, int len) { for (int i = 0; i < MSG_RETRIES; i++) { int rc = skytraq_rd_msg(payload, len); @@ -330,36 +328,36 @@ SkytraqBase::skytraq_expect_msg(uint8_t id, uint8_t* payload, int len) const } int -SkytraqBase::skytraq_wr_msg_verify(const uint8_t* payload, int len) const +SkytraqBase::skytraq_wr_msg_verify(const uint8_t* payload, int len) { for (int i = 0; i < MSG_RETRIES; i++) { if (i > 0) { - db(1, "resending msg (id=0x%02x)...\n", payload[0]); + dbg(1, "resending msg (id=0x%02x)...\n", payload[0]); } skytraq_wr_msg(payload, len); int rc = skytraq_expect_ack(payload[0]); if (rc == res_OK || rc == res_NACK) { return rc; } - db(1, MYNAME ": Got neither ACK nor NACK, "); + dbg(1, "Got neither ACK nor NACK, "); } - db(1, "aborting (msg id was 0x%02x).\n", payload[0]); + dbg(1, "aborting (msg id was 0x%02x).\n", payload[0]); return res_ERROR; } int -SkytraqBase::skytraq_system_restart() const +SkytraqBase::skytraq_system_restart() { uint8_t MSG_SYSTEM_RESTART[15] = { 0x01, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - db(2, "restart system\n"); + dbg(2, "restart system\n"); return skytraq_wr_msg_verify(MSG_SYSTEM_RESTART, sizeof(MSG_SYSTEM_RESTART)); } int -SkytraqBase::skytraq_set_baud(int baud) const +SkytraqBase::skytraq_set_baud(int baud) { /* Note: according to AN0003_v3.pdf, attrib == 0x00 means write to SRAM only, however * it seems to write to flash too. The Windows software sends 0x02 so we do here too. @@ -367,7 +365,7 @@ SkytraqBase::skytraq_set_baud(int baud) const uint8_t MSG_CONFIGURE_SERIAL_PORT[4] = { 0x05, 0x00, 0x00, 0x02 }; - db(2, "Setting baud rate to %i\n", baud); + dbg(2, "Setting baud rate to %i\n", baud); switch (baud) { case 4800: @@ -392,19 +390,19 @@ SkytraqBase::skytraq_set_baud(int baud) const MSG_CONFIGURE_SERIAL_PORT[2] = 6; break; default: - fatal(MYNAME ": Unsupported baud rate: %ibd\n", baud); + gbFatal("Unsupported baud rate: %ibd\n", baud); } int rc = skytraq_wr_msg_verify(MSG_CONFIGURE_SERIAL_PORT, sizeof(MSG_CONFIGURE_SERIAL_PORT)); if (rc != res_OK) { - db(2, "Warning: error setting skytraq device baud rate\n"); + dbg(2, "Warning: error setting skytraq device baud rate\n"); return rc; } - db(3, "Now setting UART baud rate to %i\n", baud); + dbg(3, "Now setting UART baud rate to %i\n", baud); rd_drain(); if (gbser_set_speed(serial_handle, baud) != gbser_OK) { - db(2, "Warning: error setting uart baud rate\n"); + dbg(2, "Warning: error setting uart baud rate\n"); return res_ERROR; } @@ -414,7 +412,7 @@ SkytraqBase::skytraq_set_baud(int baud) const } int -SkytraqBase::skytraq_configure_logging() const +SkytraqBase::skytraq_configure_logging() { // an0008-1.4.14: logs if // (dt > tmin & dd >= dmin & v >= vmin) | dt > tmax | dd > dmax | v > vmax @@ -437,13 +435,13 @@ SkytraqBase::skytraq_configure_logging() const if (!opt_configure_logging.isEmpty()) { unsigned int nn = sscanf(opt_configure_logging.get().toUtf8(), "%u:%u:%u:%u", &tmin, &tmax, &dmin, &dmax); if (nn>3) { - db(0, "Reconfiguring logging to: tmin=%u, tmax=%u, dmin=%u, dmax=%u\n", tmin, tmax, dmin, dmax); + dbg(0, "Reconfiguring logging to: tmin=%u, tmax=%u, dmin=%u, dmax=%u\n", tmin, tmax, dmin, dmax); be_write32(MSG_LOG_CONFIGURE_CONTROL+5, tmin); be_write32(MSG_LOG_CONFIGURE_CONTROL+1, tmax); be_write32(MSG_LOG_CONFIGURE_CONTROL+13, dmin); be_write32(MSG_LOG_CONFIGURE_CONTROL+9, dmax); } else { - db(1, MYNAME "Option usage: configlog=tmin:tmax:dmin:dmax"); + dbg(1, "Option usage: configlog=tmin:tmax:dmin:dmax"); return -1; } } @@ -452,7 +450,7 @@ SkytraqBase::skytraq_configure_logging() const } int -SkytraqBase::skytraq_get_log_buffer_status(uint32_t* log_wr_ptr, uint16_t* sectors_free, uint16_t* sectors_total) const +SkytraqBase::skytraq_get_log_buffer_status(uint32_t* log_wr_ptr, uint16_t* sectors_free, uint16_t* sectors_total) { uint8_t MSG_LOG_STATUS_CONTROL = 0x17; struct { @@ -466,13 +464,13 @@ SkytraqBase::skytraq_get_log_buffer_status(uint32_t* log_wr_ptr, uint16_t* secto unsigned int rc; if ((rc = skytraq_wr_msg_verify(&MSG_LOG_STATUS_CONTROL, 1)) != res_OK) { /* get memory status */ - db(1, MYNAME ": Error sending LOG STATUS CONTROL message (%d)\n", rc); + dbg(1, "Error sending LOG STATUS CONTROL message (%d)\n", rc); return res_ERROR; } rc = skytraq_expect_msg(0x94, (uint8_t*)&MSG_LOG_STATUS_OUTPUT, sizeof(MSG_LOG_STATUS_OUTPUT)); if (rc < sizeof(MSG_LOG_STATUS_OUTPUT)) { - db(1, MYNAME ": Didn't receive expected reply (%d)\n", rc); + dbg(1, "Didn't receive expected reply (%d)\n", rc); return res_ERROR; } @@ -489,7 +487,7 @@ SkytraqBase::skytraq_get_log_buffer_status(uint32_t* log_wr_ptr, uint16_t* secto unsigned int vmin = le_readu32(&MSG_LOG_STATUS_OUTPUT.min_speed); // log_bool = *(MSG_LOG_STATUS_OUTPUT.datalog_enable); // fifo_mode = *(MSG_LOG_STATUS_OUTPUT.log_fifo_mode); - db(1, "#logging: tmin=%u, tmax=%u, dmin=%u, dmax=%u, vmin=%u, vmax=%u\n", tmin, tmax, dmin, dmax, vmin, vmax); + dbg(1, "#logging: tmin=%u, tmax=%u, dmin=%u, dmax=%u, vmin=%u, vmax=%u\n", tmin, tmax, dmin, dmax, vmin, vmax); return res_OK; } @@ -501,7 +499,7 @@ unsigned int SkytraqBase::me_read32(const unsigned char* p) } QDateTime -SkytraqBase::gpstime_to_qdatetime(int week, int sec) const +SkytraqBase::gpstime_to_qdatetime(int week, int sec) { /* Notes: * * week rollover period can be specified using option @@ -602,7 +600,7 @@ SkytraqBase::state_init(read_state* pst) } Waypoint* -SkytraqBase::make_trackpoint(read_state* st, double lat, double lon, double alt) const +SkytraqBase::make_trackpoint(read_state* st, double lat, double lon, double alt) { auto* wpt = new Waypoint; @@ -625,7 +623,7 @@ SkytraqBase::make_trackpoint(read_state* st, double lat, double lon, double alt) #define ITEM_SPEED(item) (item->type_and_speed[1] | ((item->type_and_speed[0] & 0x0F) << 8)) int -SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len) const +SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len) { int res = 0; double lat; @@ -647,7 +645,7 @@ SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len case 0x2: /* Multi HZ item */ if (len < MULTI_HZ_ITEM_LEN) { - db(1, MYNAME ": Not enough bytes in sector for a full item.\n"); + dbg(1, "Not enough bytes in sector for a full item.\n"); return res_ERROR; } m.gps_week = ITEM_WEEK_NUMBER(pitem); @@ -662,7 +660,7 @@ SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len spe = KPH_TO_MPS(be_read16(pitem->multi_hz.v_kmh)); - db(4, "Got multi hz item: week=%i sec=%i lat=%i lon=%i alt=%i speed=%f\n", + dbg(4, "Got multi hz item: week=%i sec=%i lat=%i lon=%i alt=%i speed=%f\n", m.gps_week, m.gps_sec, m.lat, m.lon, m.alt, spe); @@ -684,7 +682,7 @@ SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len case 0x4: /* full item */ if (len < FULL_ITEM_LEN) { - db(1, MYNAME ": Not enough bytes in sector for a full item.\n"); + dbg(1, "Not enough bytes in sector for a full item.\n"); return res_ERROR; } ts = me_read32(pitem->full.ts); @@ -700,7 +698,7 @@ SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len pst->y = f.y; pst->z = f.z; - db(4, "Got %s item: week=%i sec=%i x=%i y=%i z=%i speed=%i\n", + dbg(4, "Got %s item: week=%i sec=%i x=%i y=%i z=%i speed=%i\n", poi ? "POI" : "full", f.gps_week, f.gps_sec, f.x, f.y, f.z, @@ -711,7 +709,7 @@ SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len case 0x8: /* compact item */ if (len < COMPACT_ITEM_LEN) { - db(1, MYNAME ": Not enough bytes in sector for a compact item.\n"); + dbg(1, "Not enough bytes in sector for a compact item.\n"); return res_ERROR; } c.dx = (pitem->comp.dpos[1] >> 6) | (pitem->comp.dpos[0] << 2); @@ -728,7 +726,7 @@ SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len } c.dt = (pitem->comp.dt[0] << 8) | pitem->comp.dt[1]; - db(4, "Got compact item: dt=%i dx=%i dy=%i dz=%i speed=%i uu=%i\n", + dbg(4, "Got compact item: dt=%i dx=%i dy=%i dz=%i speed=%i uu=%i\n", c.dt, c.dx, c.dy, c.dz, ITEM_SPEED(pitem), (pitem->comp.dpos[2] & 0x0F)>>2); @@ -741,7 +739,7 @@ SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len break; default: - db(1, MYNAME ": Unknown item type encountered: 0x%02x\n", ITEM_TYPE(pitem)); + dbg(1, "Unknown item type encountered: 0x%02x\n", ITEM_TYPE(pitem)); return 0; } @@ -756,7 +754,7 @@ SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len } if (nullptr == pst->route_head_) { - db(1, MYNAME ": New Track\n"); + dbg(1, "New Track\n"); pst->route_head_ = new route_head; track_add_head(pst->route_head_); } @@ -768,7 +766,7 @@ SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len } int /* returns number of bytes processed (terminates on 0xFF i.e. empty or padding bytes) */ -SkytraqBase::process_data_sector(read_state* pst, const uint8_t* buf, int len) const +SkytraqBase::process_data_sector(read_state* pst, const uint8_t* buf, int len) { int plen; int ilen; @@ -776,7 +774,7 @@ SkytraqBase::process_data_sector(read_state* pst, const uint8_t* buf, int len) c for (plen = 0; plen < len && buf[plen] != 0xFF; plen += ilen) { ilen = process_data_item(pst, reinterpret_cast(&buf[plen]), len-plen); if (ilen <= 0) { - fatal(MYNAME ": Error %i while processing data item #%i (starts at %i)\n", + gbFatal("Error %i while processing data item #%i (starts at %i)\n", ilen, pst->tpn, plen); } } @@ -786,7 +784,7 @@ SkytraqBase::process_data_sector(read_state* pst, const uint8_t* buf, int len) c /* Note: the buffer is being padded with 0xFFs if necessary so there are always SECTOR_SIZE valid bytes */ int -SkytraqBase::skytraq_read_single_sector(unsigned int sector, uint8_t* buf) const +SkytraqBase::skytraq_read_single_sector(unsigned int sector, uint8_t* buf) { uint8_t MSG_LOG_SECTOR_READ_CONTROL[2] = { 0x1B, (uint8_t)(sector) }; int errors = 5; /* allow this many errors */ @@ -797,13 +795,13 @@ SkytraqBase::skytraq_read_single_sector(unsigned int sector, uint8_t* buf) const uint8_t buffer[16]; if (sector > 0xFF) { - fatal(MYNAME ": Invalid sector number (%i)\n", sector); + gbFatal("Invalid sector number (%i)\n", sector); } - db(2, "Reading sector #%i...\n", sector); + dbg(2, "Reading sector #%i...\n", sector); if (skytraq_wr_msg_verify((uint8_t*)&MSG_LOG_SECTOR_READ_CONTROL, sizeof(MSG_LOG_SECTOR_READ_CONTROL)) != res_OK) { - db(1, MYNAME ": Didn't receive ACK\n"); + dbg(1, "Didn't receive ACK\n"); return res_ERROR; } @@ -820,7 +818,7 @@ SkytraqBase::skytraq_read_single_sector(unsigned int sector, uint8_t* buf) const } } if (j < sizeof(SECTOR_READ_END)) { - db(1, MYNAME ": Didn't get sector end tag\n"); + db(1, "Didn't get sector end tag\n"); return res_ERROR; } c = rd_char(&errors); /* read checksum byte */ @@ -840,7 +838,7 @@ SkytraqBase::skytraq_read_single_sector(unsigned int sector, uint8_t* buf) const } } if (j < sizeof(SECTOR_READ_END)) { - db(1, MYNAME ": Didn't get sector end tag\n"); + dbg(1, "Didn't get sector end tag\n"); return res_ERROR; } if (c < 16) { @@ -851,7 +849,7 @@ SkytraqBase::skytraq_read_single_sector(unsigned int sector, uint8_t* buf) const } #endif i = i-j; - db(3, "Received %i bytes of log data\n", i); + dbg(3, "Received %i bytes of log data\n", i); //#define SINGLE_READ_WORKAROUND #ifdef SINGLE_READ_WORKAROUND @@ -867,7 +865,7 @@ SkytraqBase::skytraq_read_single_sector(unsigned int sector, uint8_t* buf) const cs = skytraq_calc_checksum(buf, i); if (cs != buf[i+sizeof(SECTOR_READ_END)]) { - db(1, MYNAME ": Checksum error while reading sector: got 0x%02x, expected 0x%02x\n", + dbg(1, "Checksum error while reading sector: got 0x%02x, expected 0x%02x\n", buf[i+sizeof(SECTOR_READ_END)], cs); return res_ERROR; } @@ -880,21 +878,21 @@ SkytraqBase::skytraq_read_single_sector(unsigned int sector, uint8_t* buf) const } int -SkytraqBase::skytraq_read_multiple_sectors(int first_sector, unsigned int sector_count, uint8_t* buf) const +SkytraqBase::skytraq_read_multiple_sectors(int first_sector, unsigned int sector_count, uint8_t* buf) { uint8_t MSG_LOG_READ_MULTI_SECTORS[5] = { 0x1D }; unsigned int i; if (first_sector < 0 || first_sector > 0xFFFF) { - fatal(MYNAME ": Invalid sector number (%i)\n", first_sector); + gbFatal("Invalid sector number (%i)\n", first_sector); } be_write16(&MSG_LOG_READ_MULTI_SECTORS[1], first_sector); if (sector_count > 0xFFFF) { - fatal(MYNAME ": Invalid sector count (%i)\n", sector_count); + gbFatal("Invalid sector count (%i)\n", sector_count); } be_write16(&MSG_LOG_READ_MULTI_SECTORS[3], sector_count); - db(2, "Reading %i sectors beginning from #%i...\n", sector_count, first_sector); + dbg(2, "Reading %i sectors beginning from #%i...\n", sector_count, first_sector); unsigned int read_result = skytraq_wr_msg_verify((uint8_t*)&MSG_LOG_READ_MULTI_SECTORS, sizeof(MSG_LOG_READ_MULTI_SECTORS)); if (read_result != res_OK) { @@ -902,7 +900,7 @@ SkytraqBase::skytraq_read_multiple_sectors(int first_sector, unsigned int sector } for (i = 0; i < sector_count; i++) { - db(2, "Receiving data of sector #%i...\n", first_sector+i); + dbg(2, "Receiving data of sector #%i...\n", first_sector+i); rd_buf(buf+i*SECTOR_SIZE, SECTOR_SIZE); } rd_buf(buf+SECTOR_SIZE*sector_count, sizeof(SECTOR_READ_END)+6); @@ -910,7 +908,7 @@ SkytraqBase::skytraq_read_multiple_sectors(int first_sector, unsigned int sector uint8_t* buf_end_tag = buf + SECTOR_SIZE*sector_count; for (i = 0; i < sizeof(SECTOR_READ_END); i++) { if (buf_end_tag[i] != SECTOR_READ_END[i]) { - db(1, MYNAME ": Wrong end tag: got 0x%02x ('%c'), expected 0x%02x ('%c')\n", + dbg(1, "Wrong end tag: got 0x%02x ('%c'), expected 0x%02x ('%c')\n", buf_end_tag[i], isprint(buf_end_tag[i]) ? buf_end_tag[i] : '.', SECTOR_READ_END[i], isprint(SECTOR_READ_END[i]) ? SECTOR_READ_END[i] : '.'); return res_ERROR; @@ -919,7 +917,7 @@ SkytraqBase::skytraq_read_multiple_sectors(int first_sector, unsigned int sector unsigned int cs = skytraq_calc_checksum(buf, SECTOR_SIZE*sector_count); if (cs != buf_end_tag[sizeof(SECTOR_READ_END)]) { - db(1, MYNAME ": Checksum error while reading sector: got 0x%02x, expected 0x%02x\n", + dbg(1, "Checksum error while reading sector: got 0x%02x, expected 0x%02x\n", buf_end_tag[sizeof(SECTOR_READ_END)], cs); return res_ERROR; } @@ -928,7 +926,7 @@ SkytraqBase::skytraq_read_multiple_sectors(int first_sector, unsigned int sector } void -SkytraqBase::skytraq_read_tracks() const +SkytraqBase::skytraq_read_tracks() { read_state st; uint32_t log_wr_ptr; @@ -950,14 +948,14 @@ SkytraqBase::skytraq_read_tracks() const state_init(&st); if (skytraq_get_log_buffer_status(&log_wr_ptr, §ors_free, §ors_total) != res_OK) { - fatal(MYNAME ": Can't get log buffer status\n"); + gbFatal("Can't get log buffer status\n"); } - db(1, MYNAME ": Device status: free sectors: %i / total sectors: %i / %i%% used / write ptr: %i\n", + dbg(1, "Device status: free sectors: %i / total sectors: %i / %i%% used / write ptr: %i\n", sectors_free, sectors_total, 100 - sectors_free*100 / sectors_total, log_wr_ptr); if (opt_first_sector_val >= sectors_total) { - db(1, "Warning: sector# specified by option first-sector (%i) is beyond reported total sector count (%i)", + dbg(1, "Warning: sector# specified by option first-sector (%i) is beyond reported total sector count (%i)", opt_first_sector_val, sectors_total); } /* Workaround: sectors_free is sometimes reported wrong. Tried to use log_wr_ptr as an @@ -979,7 +977,7 @@ SkytraqBase::skytraq_read_tracks() const } else { sectors_used = opt_last_sector_val; if (opt_last_sector_val >= sectors_total) { - db(1, "Warning: sector# specified by option last-sector (%i) is beyond reported total sector count (%i)", + dbg(1, "Warning: sector# specified by option last-sector (%i) is beyond reported total sector count (%i)", opt_last_sector_val, sectors_total); } } @@ -988,12 +986,12 @@ SkytraqBase::skytraq_read_tracks() const // m.ad/090930: removed code that tried reducing read_at_once if necessary since doesn't work with xmalloc if (opt_dump_file) { - dumpfile = gbfopen(opt_dump_file, "w", MYNAME); + dumpfile = gbfopen(opt_dump_file, "w"); } - db(1, MYNAME ": Reading log data from device...\n"); - db(1, MYNAME ": start=%d used=%d\n", opt_first_sector_val, sectors_used); - db(1, MYNAME ": opt_last_sector_val=%d\n", opt_last_sector_val); + dbg(1, "Reading log data from device...\n"); + dbg(1, "start=%d used=%d\n", opt_first_sector_val, sectors_used); + dbg(1, "opt_last_sector_val=%d\n", opt_last_sector_val); for (int i = opt_first_sector_val; i < sectors_used; i += got_sectors) { for (t = 0, got_sectors = 0; (t < SECTOR_RETRIES) && (got_sectors <= 0); t++) { if (opt_read_at_once.get_result() == 0 || multi_read_supported == 0) { @@ -1016,7 +1014,7 @@ SkytraqBase::skytraq_read_tracks() const break; case res_NACK: - db(1, MYNAME ": Device doesn't seem to support reading multiple " + dbg(1, "Device doesn't seem to support reading multiple " "sectors at once, falling back to single read.\n"); multi_read_supported = 0; break; @@ -1028,7 +1026,7 @@ SkytraqBase::skytraq_read_tracks() const } } if (got_sectors <= 0) { - fatal(MYNAME ": Error reading sector %i\n", i); + gbFatal("Error reading sector %i\n", i); } total_sectors_read += got_sectors; @@ -1042,22 +1040,22 @@ SkytraqBase::skytraq_read_tracks() const } for (int s = 0; s < got_sectors; s++) { - db(4, MYNAME ": Decoding sector #%i...\n", i+s); + dbg(4, "Decoding sector #%i...\n", i+s); rc = process_data_sector(&st, buffer+s*SECTOR_SIZE, SECTOR_SIZE); if (rc == 0) { - db(1, MYNAME ": Empty sector encountered: apparently only %i sectors are " + dbg(1, "Empty sector encountered: apparently only %i sectors are " "used but device reported %i.\n", i+s, sectors_used); i = sectors_used; /* terminate to avoid reading stale data still in the logger */ break; } else if (rc >= (4096-FULL_ITEM_LEN) && i+s+1 >= sectors_used && i+s+1 < sectors_total) { - db(1, MYNAME ": Last sector is nearly full, reading one more sector\n"); + dbg(1, "Last sector is nearly full, reading one more sector\n"); sectors_used++; } } } free(buffer); - db(1, MYNAME ": Got %i trackpoints from %i sectors.\n", st.tpn, total_sectors_read); + dbg(1, "Got %i trackpoints from %i sectors.\n", st.tpn, total_sectors_read); if (dumpfile) { gbfclose(dumpfile); @@ -1065,7 +1063,7 @@ SkytraqBase::skytraq_read_tracks() const } int -SkytraqBase::skytraq_probe() const +SkytraqBase::skytraq_probe() { int baud_rates[] = { 9600, 230400, 115200, 57600, 4800, 19200, 38400 }; int baud_rates_count = sizeof(baud_rates)/sizeof(baud_rates[0]); @@ -1088,13 +1086,13 @@ SkytraqBase::skytraq_probe() const } for (int i = 0; i < baud_rates_count; i++) { - db(1, MYNAME ": Probing SkyTraq Venus at %ibaud...\n", baud_rates[i]); + dbg(1, "Probing SkyTraq Venus at %ibaud...\n", baud_rates[i]); rd_drain(); if (int rc = gbser_set_speed(serial_handle, baud_rates[i]); rc != gbser_OK) { - db(1, MYNAME ": Set baud rate to %d failed (%d), retrying...\n", baud_rates[i], rc); + dbg(1, "Set baud rate to %d failed (%d), retrying...\n", baud_rates[i], rc); if (int rc = gbser_set_speed(serial_handle, baud_rates[i]); rc != gbser_OK) { - db(1, MYNAME ": Set baud rate to %d failed (%d)\n", baud_rates[i], rc); + dbg(1, "Set baud rate to %d failed (%d)\n", baud_rates[i], rc); continue; } } @@ -1104,11 +1102,11 @@ SkytraqBase::skytraq_probe() const skytraq_wr_msg(MSG_QUERY_SOFTWARE_VERSION, /* get firmware version */ sizeof(MSG_QUERY_SOFTWARE_VERSION)); if (int rc = skytraq_expect_ack(0x02); rc != res_OK) { - db(2, "Didn't receive ACK (%d), retrying...\n", rc); + dbg(2, "Didn't receive ACK (%d), retrying...\n", rc); skytraq_wr_msg(MSG_QUERY_SOFTWARE_VERSION, /* get firmware version */ sizeof(MSG_QUERY_SOFTWARE_VERSION)); if (int rc = skytraq_expect_ack(0x02); rc != res_OK) { - db(2, "Didn't receive ACK (%d)\n", rc); + dbg(2, "Didn't receive ACK (%d)\n", rc); continue; } } @@ -1120,9 +1118,9 @@ SkytraqBase::skytraq_probe() const }*/ if (int rc = skytraq_expect_msg(0x80, (uint8_t*)&MSG_SOFTWARE_VERSION, sizeof(MSG_SOFTWARE_VERSION)); rc < (int)sizeof(MSG_SOFTWARE_VERSION)) { - db(2, "Didn't receive expected reply (%d)\n", rc); + dbg(2, "Didn't receive expected reply (%d)\n", rc); } else { - db(1, MYNAME ": Venus device found: Kernel version = %i.%i.%i, ODM version = %i.%i.%i, "\ + dbg(1, "Venus device found: Kernel version = %i.%i.%i, ODM version = %i.%i.%i, "\ "revision (Y/M/D) = %02i/%02i/%02i\n", MSG_SOFTWARE_VERSION.kernel_ver[1], MSG_SOFTWARE_VERSION.kernel_ver[2], MSG_SOFTWARE_VERSION.kernel_ver[3], @@ -1139,13 +1137,13 @@ SkytraqBase::skytraq_probe() const } int -SkytraqBase::skytraq_erase() const +SkytraqBase::skytraq_erase() { uint8_t MSG_LOG_ERASE = 0x19; - db(1, MYNAME ": Erasing logger memory...\n"); + dbg(1, "Erasing logger memory...\n"); if (skytraq_wr_msg_verify(&MSG_LOG_ERASE, sizeof(MSG_LOG_ERASE)) != res_OK) { - db(1, MYNAME ": Didn't receive ACK\n"); + dbg(1, "Didn't receive ACK\n"); return res_ERROR; } @@ -1153,24 +1151,24 @@ SkytraqBase::skytraq_erase() const } void -SkytraqBase::skytraq_set_location() const +SkytraqBase::skytraq_set_location() { double lat; double lng; uint8_t MSG_SET_LOCATION[17] = { 0x36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; uint8_t MSG_GET_LOCATION = 0x35; - db(3, MYNAME ": set_location='%s'\n", qPrintable(opt_set_location)); + dbg(3, "set_location='%s'\n", gbLogCStr(opt_set_location)); sscanf(opt_set_location.get().toUtf8(), "%lf:%lf", &lat, &lng); le_write_double(&MSG_SET_LOCATION[1], lat); le_write_double(&MSG_SET_LOCATION[9], lng); for (unsigned char i : MSG_SET_LOCATION) { - db(3, "%02x ", i); + dbg(3, "%02x ", i); } - db(3, "\n"); + dbg(3, "\n"); if (skytraq_wr_msg_verify((uint8_t*)&MSG_SET_LOCATION, sizeof(MSG_SET_LOCATION)) != res_OK) { - fatal(MYNAME ": cannot set new location\n"); + gbFatal("cannot set new location\n"); } { char buf[32]; @@ -1187,10 +1185,10 @@ void SkytraqBase::skytraq_rd_init(const QString& fname) { if ((serial_handle = gbser_init(qPrintable(fname))) == nullptr) { - fatal(MYNAME ": Can't open port '%s'\n", qPrintable(fname)); + gbFatal("Can't open port '%s'\n", gbLogCStr(fname)); } if ((skytraq_baud = skytraq_probe()) <= 0) { - fatal(MYNAME ": Can't find skytraq device on '%s'\n", qPrintable(fname)); + gbFatal("Can't find skytraq device on '%s'\n", gbLogCStr(fname)); } } @@ -1202,7 +1200,7 @@ SkytraqBase::skytraq_rd_deinit() } void -SkytraqBase::skytraq_read() const +SkytraqBase::skytraq_read() { if (opt_set_location) { skytraq_set_location(); @@ -1237,16 +1235,16 @@ SkytraqBase::skytraq_read() const void SkytraqfileFormat::rd_init(const QString& fname) { - db(1, "Opening file...\n"); - if ((file_handle = gbfopen(fname, "rb", MYNAME)) == nullptr) { - fatal(MYNAME ": Can't open file '%s'\n", qPrintable(fname)); + dbg(1, "Opening file...\n"); + if ((file_handle = gbfopen(fname, "rb")) == nullptr) { + gbFatal("Can't open file '%s'\n", gbLogCStr(fname)); } } void SkytraqfileFormat::rd_deinit() { - db(1, "Closing file...\n"); + dbg(1, "Closing file...\n"); gbfclose(file_handle); file_handle = nullptr; } @@ -1263,27 +1261,27 @@ SkytraqfileFormat::read() auto* buffer = (uint8_t*) xmalloc(SECTOR_SIZE); if (opt_first_sector_val > 0) { - db(4, MYNAME ": Seeking to first-sector index %i\n", opt_first_sector_val*SECTOR_SIZE); + dbg(4, "Seeking to first-sector index %i\n", opt_first_sector_val*SECTOR_SIZE); gbfseek(file_handle, opt_first_sector_val*SECTOR_SIZE, SEEK_SET); } - db(1, MYNAME ": Reading log data from file...\n"); + dbg(1, "Reading log data from file...\n"); int sectors_read = 0; while ((got_bytes = gbfread(buffer, 1, SECTOR_SIZE, file_handle)) > 0) { - db(4, MYNAME ": Decoding sector #%i...\n", sectors_read++); + dbg(4, "Decoding sector #%i...\n", sectors_read++); int rc = process_data_sector(&st, buffer, got_bytes); if (opt_last_sector_val < 0) { if (rc < (4096-FULL_ITEM_LEN)) { - db(1, MYNAME ": Empty sector encountered, terminating.\n"); + dbg(1, "Empty sector encountered, terminating.\n"); break; } } else if (sectors_read-1 >= opt_last_sector_val) { - db(1, MYNAME ": desired last-sector #%i reached, terminating.\n", sectors_read-1); + dbg(1, "desired last-sector #%i reached, terminating.\n", sectors_read-1); break; } } xfree(buffer); - db(1, MYNAME ": Got %i trackpoints from %i sectors.\n", st.tpn, sectors_read); + dbg(1, "Got %i trackpoints from %i sectors.\n", st.tpn, sectors_read); } /**************************************************************************/ @@ -1292,10 +1290,6 @@ SkytraqfileFormat::read() * http://navin.com.tw/miniHomer.htm * 2010-10-23 Josef Reisinger */ -#ifdef MYNAME -#undef MYNAME -#endif -#define MYNAME "miniHomer" #define NUMPOI (sizeof poinames/sizeof poinames[0]) #ifdef DEAD_CODE_IS_REBORN int MinihomerFormat::getPoiByName(char* name) @@ -1330,7 +1324,7 @@ void MinihomerFormat::lla2ecef(double lat, double lng, double alt, double* ecef_ *ecef_y = (double)((n+lalt) * cos(llat) * sin(llng)); *ecef_z = (double)((n*(1-esqr) + lalt)* sin(llat)); } -void MinihomerFormat::miniHomer_get_poi() const +void MinihomerFormat::miniHomer_get_poi() { uint8_t MSG_GET_POI[3] = { 0x4D, 0, 0}; uint8_t buf[32]; @@ -1342,7 +1336,7 @@ void MinihomerFormat::miniHomer_get_poi() const MSG_GET_POI[1]=(poi>>8)&0xff; MSG_GET_POI[2]=(poi)&0xff; if (skytraq_wr_msg_verify((uint8_t*)&MSG_GET_POI, sizeof(MSG_GET_POI)) != res_OK) { - warning(MYNAME ": cannot read poi %d '%s'\n", poi, poinames[poi]); + gbWarning("cannot read poi %d '%s'\n", poi, poinames[poi]); } skytraq_rd_msg(buf, 25); double ecef_x = be_read_double(buf+1); @@ -1351,7 +1345,7 @@ void MinihomerFormat::miniHomer_get_poi() const // todo - how to determine not-set POIs ? if (ecef_x < 100.0 && ecef_y < 100.0 && ecef_z < 100.0) { - db(2, MYNAME" : skipped poi %u for X=%f, y=%f, Z=%f\n", poi, ecef_x, ecef_y, ecef_z); + dbg(2, "skipped poi %u for X=%f, y=%f, Z=%f\n", poi, ecef_x, ecef_y, ecef_z); } else { ECEF_to_LLA(ecef_x, ecef_y, ecef_z, &lat, &lng, &alt); @@ -1362,7 +1356,7 @@ void MinihomerFormat::miniHomer_get_poi() const wpt->longitude = lng; wpt->altitude = alt; waypt_add(wpt); - db(1, MYNAME ": got POI[%s]='%f %f %f/%f %f %f'\n", poinames[poi], lat, lng, alt, ecef_x, ecef_y, ecef_z); + dbg(1, "got POI[%s]='%f %f %f/%f %f %f'\n", poinames[poi], lat, lng, alt, ecef_x, ecef_y, ecef_z); } } } @@ -1374,7 +1368,7 @@ void MinihomerFormat::miniHomer_get_poi() const * -1 in case of errors * the number of the POI will not be checked - if it is not correct, miniHome will send NACK */ -int MinihomerFormat::miniHomer_set_poi(uint16_t poinum, const QString& opt_poi) const +int MinihomerFormat::miniHomer_set_poi(uint16_t poinum, const QString& opt_poi) { #define MSG_SET_POI_SIZE (sizeof(uint8_t)+sizeof(uint16_t)+3*sizeof(double)+sizeof(uint8_t)) uint8_t MSG_SET_POI[MSG_SET_POI_SIZE] = { @@ -1401,9 +1395,9 @@ int MinihomerFormat::miniHomer_set_poi(uint16_t poinum, const QString& opt_poi) */ int n = sscanf(opt_poi.toUtf8(), "%lf:%lf:%lf", &lat, &lng, &alt); if (n >= 2) { - db(3, "found %d elems '%s':poi=%s@%d, lat=%f, lng=%f, alt=%f\n", n, qPrintable(opt_poi), poinames[poinum], poinum, lat, lng, alt); + dbg(3, "found %d elems '%s':poi=%s@%d, lat=%f, lng=%f, alt=%f\n", n, gbLogCStr(opt_poi), poinames[poinum], poinum, lat, lng, alt); lla2ecef(lat, lng, alt, &ecef_x, &ecef_y, &ecef_z); - db(1, MYNAME ": set POI[%s]='%f %f %f/%f %f %f'\n", poinames[poinum], lat, lng, alt, ecef_x, ecef_y, ecef_z); + dbg(1, "set POI[%s]='%f %f %f/%f %f %f'\n", poinames[poinum], lat, lng, alt, ecef_x, ecef_y, ecef_z); be_write16(MSG_SET_POI+1, poinum); be_write_double(MSG_SET_POI+3, ecef_x); be_write_double(MSG_SET_POI+11, ecef_y); @@ -1412,11 +1406,11 @@ int MinihomerFormat::miniHomer_set_poi(uint16_t poinum, const QString& opt_poi) if (skytraq_wr_msg_verify((uint8_t*)&MSG_SET_POI, sizeof(MSG_SET_POI)) == res_OK) { result=1; } else { - warning(MYNAME ": cannot set poi %d '%s'\n", poinum, poinames[poinum]); + gbWarning("cannot set poi %d '%s'\n", poinum, poinames[poinum]); result=-1; } } else { - warning(MYNAME ": argument to %s needs to be like :[:]\n", poinames[poinum]); + gbWarning("argument to %s needs to be like :[:]\n", poinames[poinum]); result=-1; } } diff --git a/skytraq.h b/skytraq.h index 4ded87e57..b201c694f 100644 --- a/skytraq.h +++ b/skytraq.h @@ -112,38 +112,38 @@ class SkytraqBase /* Member Functions */ - [[gnu::format(printf, 2, 3)]] static void db(int l, const char* msg, ...); - void rd_drain() const; - int rd_char(int* errors) const; - int rd_buf(uint8_t* buf, int len) const; - int rd_word() const; - void wr_char(int c) const; - void wr_buf(const unsigned char* str, int len) const; + [[gnu::format(printf, 2, 3)]] static void dbg(int l, const char* msg, ...); + void rd_drain(); + int rd_char(int* errors); + int rd_buf(uint8_t* buf, int len); + int rd_word(); + void wr_char(int c); + void wr_buf(const unsigned char* str, int len); static int skytraq_calc_checksum(const unsigned char* buf, int len); - int skytraq_rd_msg(void* payload, unsigned int len) const; - void skytraq_wr_msg(const uint8_t* payload, int len) const; - int skytraq_expect_ack(uint8_t id) const; - int skytraq_expect_msg(uint8_t id, uint8_t* payload, int len) const; - int skytraq_wr_msg_verify(const uint8_t* payload, int len) const; - int skytraq_system_restart() const; - int skytraq_set_baud(int baud) const; - int skytraq_configure_logging() const; - int skytraq_get_log_buffer_status(uint32_t* log_wr_ptr, uint16_t* sectors_free, uint16_t* sectors_total) const; + int skytraq_rd_msg(void* payload, unsigned int len); + void skytraq_wr_msg(const uint8_t* payload, int len); + int skytraq_expect_ack(uint8_t id); + int skytraq_expect_msg(uint8_t id, uint8_t* payload, int len); + int skytraq_wr_msg_verify(const uint8_t* payload, int len); + int skytraq_system_restart(); + int skytraq_set_baud(int baud); + int skytraq_configure_logging(); + int skytraq_get_log_buffer_status(uint32_t* log_wr_ptr, uint16_t* sectors_free, uint16_t* sectors_total); static unsigned int me_read32(const unsigned char* p); - QDateTime gpstime_to_qdatetime(int week, int sec) const; + QDateTime gpstime_to_qdatetime(int week, int sec); static void ECEF_to_LLA(double x, double y, long int z, double* lat, double* lon, double* alt); static void state_init(read_state* pst); - Waypoint* make_trackpoint(read_state* st, double lat, double lon, double alt) const; - int process_data_item(read_state* pst, const item_frame* pitem, int len) const; - int process_data_sector(read_state* pst, const uint8_t* buf, int len) const; - int skytraq_read_single_sector(unsigned int sector, uint8_t* buf) const; - int skytraq_read_multiple_sectors(int first_sector, unsigned int sector_count, uint8_t* buf) const; - void skytraq_read_tracks() const; - int skytraq_probe() const; - int skytraq_erase() const; - void skytraq_set_location() const; + Waypoint* make_trackpoint(read_state* st, double lat, double lon, double alt); + int process_data_item(read_state* pst, const item_frame* pitem, int len); + int process_data_sector(read_state* pst, const uint8_t* buf, int len); + int skytraq_read_single_sector(unsigned int sector, uint8_t* buf); + int skytraq_read_multiple_sectors(int first_sector, unsigned int sector_count, uint8_t* buf); + void skytraq_read_tracks(); + int skytraq_probe(); + int skytraq_erase(); + void skytraq_set_location(); void skytraq_rd_init(const QString& fname); - void skytraq_read() const; + void skytraq_read(); void skytraq_rd_deinit(); /* Data Members */ @@ -336,8 +336,8 @@ class MinihomerFormat : public Format, private SkytraqBase /* Member Functions */ static void lla2ecef(double lat, double lng, double alt, double* ecef_x, double* ecef_y, double* ecef_z); - void miniHomer_get_poi() const; - int miniHomer_set_poi(uint16_t poinum, const QString& opt_poi) const; + void miniHomer_get_poi(); + int miniHomer_set_poi(uint16_t poinum, const QString& opt_poi); /* Data Members */ diff --git a/smplrout.cc b/smplrout.cc index 951696607..1bf54326d 100644 --- a/smplrout.cc +++ b/smplrout.cc @@ -70,7 +70,6 @@ #if FILTERS_ENABLED -#define MYNAME "simplify" inline bool operator<(const SimplifyRouteFilter::trackerror& lhs, const SimplifyRouteFilter::trackerror& rhs) { @@ -160,7 +159,7 @@ void SimplifyRouteFilter::routesimple_head(const route_head* rte) if (metric == metric_t::relative) { // check hdop is available for compute_track_error if (wpt->hdop == 0) { - fatal(MYNAME ": relative needs hdop information.\n"); + gbFatal("relative needs hdop information.\n"); } } @@ -271,7 +270,7 @@ void SimplifyRouteFilter::init() } else if (countopt && !erroropt) { limit_basis = limit_basis_t::count; } else { - fatal(MYNAME ": You must specify either count or error, but not both.\n"); + gbFatal("You must specify either count or error, but not both.\n"); } if (!lenopt && !relopt) { @@ -281,7 +280,7 @@ void SimplifyRouteFilter::init() } else if (!xteopt && !lenopt && relopt) { metric = metric_t::relative; } else { - fatal(MYNAME ": You may specify only one of crosstrack, length, or relative.\n"); + gbFatal("You may specify only one of crosstrack, length, or relative.\n"); } switch (limit_basis) { @@ -292,8 +291,8 @@ void SimplifyRouteFilter::init() if (metric == metric_t::relative) { error = erroropt.get_result(); } else { - if (parse_distance(erroropt, &error, kMetersPerMile, MYNAME) == 0) { - fatal(MYNAME ": No value specified with error option.\n"); + if (parse_distance(erroropt, &error, kMetersPerMile) == 0) { + gbFatal("No value specified with error option.\n"); } } } diff --git a/sort.cc b/sort.cc index 058df4f44..814914007 100644 --- a/sort.cc +++ b/sort.cc @@ -30,8 +30,6 @@ #if FILTERS_ENABLED -#define MYNAME "sort" - bool SortFilter::sort_comp_wpt_by_description(const Waypoint* a, const Waypoint* b) { @@ -86,7 +84,7 @@ void SortFilter::process() waypt_sort(sort_comp_wpt_by_time); break; default: - fatal(MYNAME ": unknown waypoint sort mode."); + gbFatal("unknown waypoint sort mode.\n"); } switch (rte_sort_mode) { @@ -102,7 +100,7 @@ void SortFilter::process() route_sort(sort_comp_rh_by_number); break; default: - fatal(MYNAME ": unknown route sort mode."); + gbFatal("unknown route sort mode.\n"); } switch (trk_sort_mode) { @@ -118,7 +116,7 @@ void SortFilter::process() track_sort(sort_comp_rh_by_number); break; default: - fatal(MYNAME ": unknown track sort mode."); + gbFatal("unknown track sort mode.\n"); } } @@ -136,7 +134,7 @@ void SortFilter::init() } else if (!opt_sm_description && !opt_sm_gcid && !opt_sm_shortname && opt_sm_time) { wpt_sort_mode = SortModeWpt::time; } else { - fatal(MYNAME ": At most one of the options description, gcid, shortname and time may be selected."); + gbFatal("At most one of the options description, gcid, shortname and time may be selected.\n"); } // sort routes by @@ -149,7 +147,7 @@ void SortFilter::init() } else if (!opt_sm_rtedesc && !opt_sm_rtename && opt_sm_rtenum) { rte_sort_mode = SortModeRteHd::number; } else { - fatal(MYNAME ": At most one of the options rtedesc, rtename and rtenum may be selected."); + gbFatal("At most one of the options rtedesc, rtename and rtenum may be selected.\n"); } // sort tracks by @@ -162,7 +160,7 @@ void SortFilter::init() } else if (!opt_sm_trkdesc && !opt_sm_trkname && opt_sm_trknum) { trk_sort_mode = SortModeRteHd::number; } else { - fatal(MYNAME ": At most one of the options trkdesc, trkname and trknum may be selected."); + gbFatal("At most one of the options trkdesc, trkname and trknum may be selected.\n"); } } diff --git a/src/core/codecdevice.cc b/src/core/codecdevice.cc index de63389ef..7a248b2c9 100644 --- a/src/core/codecdevice.cc +++ b/src/core/codecdevice.cc @@ -31,8 +31,8 @@ namespace gpsbabel { -CodecDevice::CodecDevice(const QString& fname, const char* module, const char* codec_name) : - fname_(fname), module_(module), codec_name_(codec_name) +CodecDevice::CodecDevice(const QString& fname, const char* codec_name) : + fname_(fname), codec_name_(codec_name) { } @@ -46,7 +46,7 @@ bool CodecDevice::open(QIODevice::OpenMode mode) codec_ = QTextCodec::codecForName(codec_name_); if (codec_ == nullptr) { list_codecs(); - fatal("%s: Unsupported codec '%s'.\n", module_, codec_name_); + gbFatal("Unsupported codec '%s'.\n", codec_name_); // return false; } diff --git a/src/core/codecdevice.h b/src/core/codecdevice.h index b1ef1b35a..b7e37a589 100644 --- a/src/core/codecdevice.h +++ b/src/core/codecdevice.h @@ -35,7 +35,7 @@ namespace gpsbabel class CodecDevice : public QIODevice { public: - CodecDevice(const QString& fname, const char* module, const char* codec_name); + CodecDevice(const QString& fname, const char* codec_name); ~CodecDevice(); bool open(QIODevice::OpenMode mode) override; bool isSequential() const override; @@ -47,7 +47,6 @@ class CodecDevice : public QIODevice private: QString fname_; - const char* module_; const char* codec_name_; gpsbabel::File* file_{nullptr}; QTextCodec* codec_{nullptr}; diff --git a/src/core/file.h b/src/core/file.h index 47121e75f..e54d05238 100644 --- a/src/core/file.h +++ b/src/core/file.h @@ -53,7 +53,7 @@ class File : public QFile } if (!status) { - fatal(FatalMsg().noquote() << "Cannot open '" % + gbFatal(FatalMsg().noquote() << "Cannot open '" % (gpsbabel_testmode() ? QFileInfo(*this).fileName() : QFileInfo(*this).absoluteFilePath()) % diff --git a/src/core/logging.h b/src/core/logging.h index 64f84ea64..87b19b886 100644 --- a/src/core/logging.h +++ b/src/core/logging.h @@ -33,13 +33,13 @@ class Warning : public QDebug }; /* - * To use a FatalMsg pass it to fatal(), e.g. - * fatal(FatalMsg() << "bye bye"); + * To use a FatalMsg pass it to gbFatal(), e.g. + * gbFatal(FatalMsg() << "bye bye"); * * This - * 1) allows the noreturn attribute on fatal to be use by analysis + * 1) allows the noreturn attribute on gbFatal to be use by analysis * tools such as cppcheck. - * 2) allows fatal to throw an exception instead of calling exit. + * 2) allows gbFatal to throw an exception instead of calling exit. * This could be caught by main for a cleaner exit from a fatal error. */ class FatalMsg : public QDebug diff --git a/src/core/textstream.cc b/src/core/textstream.cc index e3a62cdae..0bb339e13 100644 --- a/src/core/textstream.cc +++ b/src/core/textstream.cc @@ -29,7 +29,7 @@ #include // for optional -#include "defs.h" // for fatal, list_codecs +#include "defs.h" // for gbFatal, list_codecs #include "src/core/textstream.h" #include "src/core/file.h" // for File @@ -37,7 +37,7 @@ namespace gpsbabel { -void TextStream::open(const QString& fname, QIODevice::OpenMode mode, const char* module, const char* codec_name) +void TextStream::open(const QString& fname, QIODevice::OpenMode mode, const char* codec_name) { std::optional encoding = QStringConverter::encodingForName(codec_name); bool use_stringconverter = encoding.has_value(); @@ -77,10 +77,10 @@ void TextStream::open(const QString& fname, QIODevice::OpenMode mode, const char } } } else { - device_ = new gpsbabel::CodecDevice(fname, module, codec_name); + device_ = new gpsbabel::CodecDevice(fname, codec_name); bool status = device_->open(mode); if (!status) { - fatal("%s: device not open %d\n", module, status); + gbFatal("device not open %d\n", status); } setDevice(device_); setEncoding(QStringConverter::Utf16); diff --git a/src/core/textstream.h b/src/core/textstream.h index 93f09bbfe..0fa6b17aa 100644 --- a/src/core/textstream.h +++ b/src/core/textstream.h @@ -35,7 +35,7 @@ namespace gpsbabel class TextStream : public QTextStream { public: - void open(const QString& fname, QIODevice::OpenMode mode, const char* module, const char* codec = "UTF-8"); + void open(const QString& fname, QIODevice::OpenMode mode, const char* codec = "UTF-8"); void close(); private: diff --git a/src/core/xmlstreamwriter.cc b/src/core/xmlstreamwriter.cc index 1ce72f1c3..13ebea630 100644 --- a/src/core/xmlstreamwriter.cc +++ b/src/core/xmlstreamwriter.cc @@ -46,7 +46,7 @@ namespace gpsbabel XmlStreamWriter::xml_stack_list_entry_t& XmlStreamWriter::activeStack() { if (stack_list.isEmpty()) { - fatal("xmlstreamwriter: programming error: the stack* functions are used incorrectly."); + gbFatal("xmlstreamwriter: programming error: the stack* functions are used incorrectly.\n"); } return stack_list.last(); } diff --git a/stackfilter.cc b/stackfilter.cc index 4a9828a90..9ad2050a3 100644 --- a/stackfilter.cc +++ b/stackfilter.cc @@ -24,8 +24,6 @@ #if FILTERS_ENABLED -#define MYNAME "Stack filter" - void StackFilter::process() { stack_elt* tmp_elt = nullptr; @@ -58,7 +56,7 @@ void StackFilter::process() } else if (opt_pop) { tmp_elt = stack; if (!tmp_elt) { - fatal(MYNAME ": stack empty\n"); + gbFatal("stack empty\n"); } if (opt_append) { waypt_append(&(stack->waypts)); @@ -83,7 +81,7 @@ void StackFilter::process() tmp_elt = stack; while (swapdepth > 1) { if (!tmp_elt->next) { - fatal(MYNAME ": swap with nonexistent element\n"); + gbFatal("swap with nonexistent element\n"); } tmp_elt = tmp_elt->next; swapdepth--; @@ -131,7 +129,7 @@ void StackFilter::init() } if (invalid) { - fatal(MYNAME ": invalid combination of options\n"); + gbFatal("invalid combination of options\n"); } } @@ -146,7 +144,7 @@ void StackFilter::exit() stack_elt* tmp_elt = nullptr; if (warnings_enabled && stack) { - warning(MYNAME " Warning: leftover stack entries; " + gbWarning("Warning: leftover stack entries; " "check command line for mistakes\n"); } while (stack) { diff --git a/subrip.cc b/subrip.cc index d9a7f255a..157ef8374 100644 --- a/subrip.cc +++ b/subrip.cc @@ -33,8 +33,6 @@ #include "src/core/logging.h" // for Fatal -#define MYNAME "subrip" - /* internal helper functions */ QTime @@ -84,7 +82,7 @@ SubripFormat::subrip_prevwp_pr(const Waypoint* waypointp) switch (*it) { case '%': if (++it == end) { - fatal("No character after %% in subrip format.\n"); + gbFatal("No character after %% in subrip format.\n"); } switch (*it) { @@ -137,7 +135,7 @@ SubripFormat::subrip_prevwp_pr(const Waypoint* waypointp) case '\\': if (++it == end) { - fatal("No character after \\ in subrip format.\n"); + gbFatal("No character after \\ in subrip format.\n"); } switch (*it) { @@ -206,19 +204,19 @@ SubripFormat::wr_init(const QString& fname) gradient = 0; if (opt_gpstime != opt_gpsdate) { - fatal(FatalMsg() << MYNAME ": Either both or neither of the gps_date and gps_time options must be supplied!"); + gbFatal(FatalMsg() << "Either both or neither of the gps_date and gps_time options must be supplied!"); } gps_datetime = QDateTime(); if (opt_gpstime && opt_gpsdate) { QDate gps_date = QDate::fromString(opt_gpsdate, u"yyyyMMdd"); if (!gps_date.isValid()) { - fatal(FatalMsg().nospace() << MYNAME ": option gps_date value (" << opt_gpsdate.get() << ") is invalid. Expected yyyymmdd."); + gbFatal(FatalMsg().nospace() << "option gps_date value (" << opt_gpsdate.get() << ") is invalid. Expected yyyymmdd."); } QTime gps_time = QTime::fromString(opt_gpstime, u"HHmmss"); if (!gps_time.isValid()) { gps_time = QTime::fromString(opt_gpstime, u"HHmmss.z"); if (!gps_time.isValid()) { - fatal(FatalMsg().nospace() << MYNAME ": option gps_time value (" << opt_gpstime.get() << ") is invalid. Expected hhmmss[.sss]"); + gbFatal(FatalMsg().nospace() << "option gps_time value (" << opt_gpstime.get() << ") is invalid. Expected hhmmss[.sss]"); } } gps_datetime = QDateTime(gps_date, gps_time, QtUTC); @@ -230,7 +228,7 @@ SubripFormat::wr_init(const QString& fname) if (!video_time.isValid()) { video_time = QTime::fromString(opt_videotime, u"HHmmss.z"); if (!video_time.isValid()) { - fatal(FatalMsg().nospace() << MYNAME ": option video_time value (" << opt_videotime.get() << ") is invalid. Expected hhmmss[.sss]."); + gbFatal(FatalMsg().nospace() << "option video_time value (" << opt_videotime.get() << ") is invalid. Expected hhmmss[.sss]."); } } video_offset_ms = video_time.msecsSinceStartOfDay(); @@ -238,7 +236,7 @@ SubripFormat::wr_init(const QString& fname) video_datetime = QDateTime(); - fout = gbfopen(fname, "wb", MYNAME); + fout = gbfopen(fname, "wb"); } void diff --git a/swapdata.cc b/swapdata.cc index c7eaed414..44e1f4b29 100644 --- a/swapdata.cc +++ b/swapdata.cc @@ -24,7 +24,6 @@ #include "swapdata.h" #include // for swap -#define MYNAME "swapdata" #if FILTERS_ENABLED diff --git a/text.cc b/text.cc index 67b380295..5294bc72c 100644 --- a/text.cc +++ b/text.cc @@ -39,8 +39,6 @@ #include "src/core/xmltag.h" // for xml_findfirst, xml_tag, xml_attribute, fs_xml, xml_findnext -#define MYNAME "TEXT" - void TextFormat::wr_init(const QString& fname) { @@ -48,7 +46,7 @@ TextFormat::wr_init(const QString& fname) output_name = fname; if (!split_output) { file_out = new gpsbabel::TextStream; - file_out->open(fname, QIODevice::WriteOnly, MYNAME); + file_out->open(fname, QIODevice::WriteOnly); } mkshort_handle = new MakeShort; @@ -57,7 +55,7 @@ TextFormat::wr_init(const QString& fname) if (re.match(opt_degformat).hasMatch()) { degformat = opt_degformat.get().at(2).toLatin1(); } else { - fatal(MYNAME ": Unrecognized degformat %s, expected 'ddd', 'dmm' or 'dms'.\n", qPrintable(opt_degformat)); + gbFatal("Unrecognized degformat %s, expected 'ddd', 'dmm' or 'dms'.\n", gbLogCStr(opt_degformat)); } if (opt_altunits.get().startsWith('f')) { @@ -65,7 +63,7 @@ TextFormat::wr_init(const QString& fname) } else if (opt_altunits.get().startsWith('m')) { altunits = 'm'; } else { - fatal(MYNAME ": Unrecognized altunits %s, expected 'f' for feet or 'm' for meters.\n", qPrintable(opt_altunits)); + gbFatal("Unrecognized altunits %s, expected 'f' for feet or 'm' for meters.\n", gbLogCStr(opt_altunits)); } } @@ -97,7 +95,7 @@ TextFormat::text_disp(const Waypoint* wpt) QString thisfname(output_name); thisfname += QString::number(waypoint_count); file_out = new gpsbabel::TextStream; - file_out->open(thisfname, QIODevice::WriteOnly, MYNAME); + file_out->open(thisfname, QIODevice::WriteOnly); } GPS_Math_WGS84_To_UTM_EN(wpt->latitude, wpt->longitude, diff --git a/tpg.cc b/tpg.cc index 3e293c851..d18cd50e9 100644 --- a/tpg.cc +++ b/tpg.cc @@ -36,8 +36,6 @@ #include "mkshort.h" // for MakeShort -#define MYNAME "TPG" - #define MAXTPGSTRINGSIZE 256 #define MAXTPGOUTPUTPINS 65535 @@ -61,7 +59,7 @@ TpgFormat::tpg_common_init() { tpg_datum_idx = GPS_Lookup_Datum_Index(tpg_datum_opt); if (tpg_datum_idx < 0) { - fatal(MYNAME ": Datum '%s' is not recognized.\n", qPrintable(tpg_datum_opt)); + gbFatal("Datum '%s' is not recognized.\n", gbLogCStr(tpg_datum_opt)); } } @@ -69,7 +67,7 @@ void TpgFormat::rd_init(const QString& fname) { tpg_common_init(); - tpg_file_in = gbfopen_le(fname, "rb", MYNAME); + tpg_file_in = gbfopen_le(fname, "rb"); } void @@ -82,7 +80,7 @@ void TpgFormat::wr_init(const QString& fname) { tpg_common_init(); - tpg_file_out = gbfopen_le(fname, "wb", MYNAME); + tpg_file_out = gbfopen_le(fname, "wb"); mkshort_handle = new MakeShort; waypt_out_count = 0; } @@ -106,7 +104,7 @@ TpgFormat::read() gbfread(&buff[0], 19, 1, tpg_file_in); if (valid_tpg_header(buff, 19) != 0) { - fatal(MYNAME ": input file does not appear to be a valid .TPG file.\n"); + gbFatal("input file does not appear to be a valid .TPG file.\n"); } @@ -287,7 +285,7 @@ TpgFormat::write() } if (s > MAXTPGOUTPUTPINS) { - fatal(MYNAME ": attempt to output too many points (%d). The max is %d. Sorry.\n", s, MAXTPGOUTPUTPINS); + gbFatal("attempt to output too many points (%d). The max is %d. Sorry.\n", s, MAXTPGOUTPUTPINS); } /* write the waypoint count */ diff --git a/tpo.cc b/tpo.cc index 6b8e43c6a..c0acd7256 100644 --- a/tpo.cc +++ b/tpo.cc @@ -83,14 +83,11 @@ #include // for qMakeStringPrivate, QStringLiteral #include // for qPrintable, Q_UNUSED -#include "defs.h" // for Waypoint, fatal, route_head, le_read32, waypt_add, track_add_wpt, track_add_head, doing_rtes, doing_wpts, gb_color, route_add_head, route_add_wpt, unknown_alt, doing_trks +#include "defs.h" // for Waypoint, gbFatal, route_head, le_read32, waypt_add, track_add_wpt, track_add_head, doing_rtes, doing_wpts, gb_color, route_add_head, route_add_wpt, unknown_alt, doing_trks #include "gbfile.h" // for gbfread, gbfgetc, gbfgetint32, gbfreadbuf, gbfseek, gbfgetdbl, gbfgetint16, gbfclose, gbfgetnativecstr, gbfgetuint16, gbfopen_le #include "jeeps/gpsmath.h" // for GPS_Math_Known_Datum_To_WGS84_M -#define MYNAME "TPO" - - /*******************************************************************************/ /* READ */ /*******************************************************************************/ @@ -111,7 +108,7 @@ TpoFormatBase::tpo_check_version_string() /* check for the presence of a 3.0-style id string */ /* Note this check also finds version 4 id strings, e.g. "TOPO! Ver. 4.5.0" */ if (strncmp(v3_id_string, string_buffer, strlen(v3_id_string)) == 0) { - /* fatal(MYNAME ": gpsbabel can only read TPO version 2.7.7 or below; this file is %s\n", string_buffer); */ + /* gbFatal("gpsbabel can only read TPO version 2.7.7 or below; this file is %s\n", string_buffer); */ //fprintf(stderr,"gpsbabel can only read TPO version 2.7.7 or below; this file is %s\n", string_buffer); gbfseek(tpo_file_in, -(string_size+1), SEEK_CUR); @@ -166,7 +163,7 @@ TpoFormatBase::tpo_read_until_section(const char* section_name, int seek_bytes) while (true) { if (gbfread(&byte, 1, 1, tpo_file_in) < 1) { - fatal(MYNAME ": malformed input file - attempt to read past end"); + gbFatal("malformed input file - attempt to read past end\n"); } header_size++; @@ -330,21 +327,21 @@ int TpoFormatBase::tpo_read_int() case 0xff: // 32-bit value if constexpr(debug) { - printf("Found 32-bit value indicator: %x\n", val); + gbDebug("Found 32-bit value indicator: %x\n", val); } return (gbfgetint32(tpo_file_in)); break; case 0xfe: // 16-bit value if constexpr(debug) { - printf("Found 16-bit value indicator: %x\n", val); + gbDebug("Found 16-bit value indicator: %x\n", val); } return (gbfgetuint16(tpo_file_in)); break; default: // 8-bit value if constexpr(debug) { - printf("Found 8-bit value: %x\n", val); + gbDebug("Found 8-bit value: %x\n", val); } return ((int)val); break; @@ -382,7 +379,7 @@ int TpoFormatBase::tpo_find_block(unsigned int block_desired) // Read record type block_type = gbfgetint32(tpo_file_in); if constexpr(debug) { - printf("Block: %08x\tat offset: %08x\n", block_type, block_offset); + gbDebug("Block: %08x\tat offset: %08x\n", block_type, block_offset); } // Read offset to next record @@ -445,12 +442,12 @@ void TpoFormatBase::tpo_process_tracks() constexpr int debug = 0; // 0-4 for increasingly verbose output in this subroutine) if constexpr(debug) { - printf("Processing Track Styles... (added in 2012 by SRE)\n"); + gbDebug("Processing Track Styles... (added in 2012 by SRE)\n"); } // Find block 0x050000 (definitions of styles for free-hand routes) if (tpo_find_block(0x050000)) { if constexpr(debug) { - printf("Found no track styles, skipping tracks entirely\n"); + gbDebug("Found no track styles, skipping tracks entirely\n"); } return; } @@ -458,7 +455,7 @@ void TpoFormatBase::tpo_process_tracks() unsigned int track_style_count = tpo_read_int(); // 8 bit value if constexpr(debug) { - printf("Unpacking %u track styles...\n",track_style_count); + gbDebug("Unpacking %u track styles...\n",track_style_count); } QScopedArrayPointer styles(new StyleInfo[track_style_count]); @@ -470,7 +467,7 @@ void TpoFormatBase::tpo_process_tracks() unsigned int skipped = (unsigned char) gbfgetc(tpo_file_in); Q_UNUSED(skipped) if constexpr(debug > 1) { - printf("Skipping unknown byte 0x%x (? per-zoom-level visibility ?)\n", skipped); + gbDebug("Skipping unknown byte 0x%x (? per-zoom-level visibility ?)\n", skipped); } } @@ -487,17 +484,17 @@ void TpoFormatBase::tpo_process_tracks() unsigned char tmp = gbfgetc(tpo_file_in); Q_UNUSED(tmp) if constexpr(debug > 2) { - printf("Skipping unknown byte 0x%x after color (? always zero ?)\n",tmp); + gbDebug("Skipping unknown byte 0x%x after color (? always zero ?)\n",tmp); } // byte for track style name length, then name itself tmp = gbfgetc(tpo_file_in); // wrong byte order?? tmp = tpo_read_int(); // 16 bit value if constexpr(debug > 1) { - printf("Track style %u has %d-byte (0x%x) name\n", ii, tmp, tmp); + gbDebug("Track style %u has %d-byte (0x%x) name\n", ii, tmp, tmp); } if (tmp >= TRACKNAMELENGTH) { - printf("ERROR! Found track style name over %d chars, skipping all tracks!\n",TRACKNAMELENGTH); + gbWarning("ERROR! Found track style name over %d chars, skipping all tracks!\n",TRACKNAMELENGTH); return; } if (tmp) { @@ -505,21 +502,9 @@ void TpoFormatBase::tpo_process_tracks() } else { // Assign a generic style name styles[ii].name = QStringLiteral("STYLE %1").arg(ii); } -#ifdef Tracks2012 - //TBD: Should this be TRACKNAMELENGTH? - for (unsigned xx = 0; xx < 3; xx++) { - if (styles[ii].name[xx] == ',') { - styles[ii].name[xx] = '_'; - } - if (styles[ii].name[xx] == '=') { - styles[ii].name[xx] = '_'; - } - } -#else // Should limit be TRACKNAMELENGTH? No! But also should not be '3' like it was. styles[ii].name.replace(',', '_'); styles[ii].name.replace('=', '_'); -#endif // one byte for line width (value 1-4), one byte for 'dashed' boolean styles[ii].wide = (uint8_t) gbfgetc(tpo_file_in); @@ -529,24 +514,24 @@ void TpoFormatBase::tpo_process_tracks() for (unsigned xx = 0; xx < 2; xx++) { tmp = gbfgetc(tpo_file_in); if constexpr(debug > 2) { - printf("Skipping trailing line style byte 0x%x (? always zero ?)\n", tmp); + gbDebug("Skipping trailing line style byte 0x%x (? always zero ?)\n", tmp); } } if constexpr(debug) { - printf("Track style %u: color=#%02x%02x%02x, width=%d, dashed=%d, name=%s\n", - ii, styles[ii].color[0], styles[ii].color[1], styles[ii].color[2], styles[ii].wide, styles[ii].dash, qPrintable(styles[ii].name)); + gbDebug("Track style %u: color=#%02x%02x%02x, width=%d, dashed=%d, name=%s\n", + ii, styles[ii].color[0], styles[ii].color[1], styles[ii].color[2], styles[ii].wide, styles[ii].dash, gbLogCStr(styles[ii].name)); } } if constexpr(debug) { - printf("Done Processing Track Styles... found %u styles\n", track_style_count); + gbDebug("Done Processing Track Styles... found %u styles\n", track_style_count); } // Find block 0x060000 (free-hand routes) (original track code, pre-2012, without styles) if (tpo_find_block(0x060000)) { if constexpr(debug) { - printf("Found no track data block, skipping all tracks!\n"); + gbDebug("Found no track data block, skipping all tracks!\n"); } return; } @@ -555,12 +540,12 @@ void TpoFormatBase::tpo_process_tracks() unsigned int track_count = tpo_read_int(); if constexpr(debug) { - printf("Number of tracks in file: %u\n", track_count); + gbDebug("Number of tracks in file: %u\n", track_count); } if (track_count == 0) { if constexpr(debug) { - printf("Found no track data, even though there was a track data block!\n"); + gbDebug("Found no track data, even though there was a track data block!\n"); } return; } @@ -569,7 +554,7 @@ void TpoFormatBase::tpo_process_tracks() // for (unsigned ii = 0; ii < track_count; ii++) { if constexpr(debug > 1) { - printf("\nStarting Track %u",ii+1); + gbDebug("\nStarting Track %u",ii+1); } int lat = 0; int lon = 0; @@ -594,13 +579,13 @@ void TpoFormatBase::tpo_process_tracks() if (name_length) { gbfread(track_name, 1, name_length, tpo_file_in); if constexpr(debug > 2) { - printf(", length %.0fm?, named %s\n", track_length, qPrintable(track_name)); + gbDebug(", length %.0fm?, named %s\n", track_length, gbLogCStr(track_name)); } } else { // Assign a generic track name track_name = "TRK "; track_name += QString::number(ii + 1); if constexpr(debug > 2) { - printf(", length %.0fm?, inventing name %s\n", track_length, qPrintable(track_name)); + gbDebug(", length %.0fm?, inventing name %s\n", track_length, gbLogCStr(track_name)); } } track_temp->rte_name = track_name; @@ -626,11 +611,11 @@ void TpoFormatBase::tpo_process_tracks() track_temp->line_width = styles[track_style].wide; if constexpr(debug) { - printf("Track Name: %s, ?Type?: %u, Style Name: %s, Width: %d, Dashed: %d, Color: #%s\n", - qPrintable(track_name), line_type, - qPrintable(styles[track_style].name), + gbDebug("Track Name: %s, ?Type?: %u, Style Name: %s, Width: %d, Dashed: %d, Color: #%s\n", + gbLogCStr(track_name), line_type, + gbLogCStr(styles[track_style].name), styles[track_style].wide, styles[track_style].dash, - qPrintable(rgb)); + gbLogCStr(rgb)); } // Track description @@ -704,9 +689,6 @@ void TpoFormatBase::tpo_process_tracks() int latscale = 0; int lonscale = 0; -#ifdef Tracks2012 - int llvalid = 0; // boolean has been replaced with multiple modes -#else #define EndScalePoints 0 #define CheckLonScale 1 #define CheckLatScale 2 @@ -718,7 +700,6 @@ void TpoFormatBase::tpo_process_tracks() int tpmode = GetFullPoint; // prior to 2020 we used "llvalid" (boolean), which did not provide enough flow control #define EndScaleTag 0x00 #define FullPointTag 0x88 -#endif // Process the track bytes - ugly flow control due to many special cases in file structure int cnttp = 0; // just for debug stroking @@ -726,72 +707,8 @@ void TpoFormatBase::tpo_process_tracks() float lastlon = 0.0; for (unsigned int jj = 0; jj < track_byte_count;) { // NO INCREMENT - advance "jj" in the loop Waypoint* waypoint_temp; -#ifdef Tracks2012 - if constexpr(debug > 3) { - printf("%02x %02x %02x %02x - byte %u, track %u, llvallid=%d\n", - buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], jj, ii+1, llvalid); - } - // Time to read a new latlong? - if (!llvalid) { - - lon = le_read32(&buf[jj]); - if constexpr(debug > 3) { - printf("%02x %02x %02x %02x - raw lon = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lon,jj); - } - jj+=4; - - lat = le_read32(&buf[jj]); - if constexpr(debug > 3) { - printf("%02x %02x %02x %02x - raw lat = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lat,jj); - } - jj+=4; - -//printf("L"); - - // Peek to see if next is a lonscale. Note that it - // can begin with 0x88, which is confusing. Here we - // allow up to 16-bits of offset, so two of the - // bytes must be 0x00 for us to recognize it. - if (jj+3 3) { - printf("%02x %02x %02x %02x - raw lon scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lonscale, jj); - } -//printf(" LONSCALE:"); -//printf("%02x%02x%02x%02x", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3]); - jj+=4; - } - // Peek to see if next is a latscale. Note that it - // can begin with 0x88, which is confusing. Here we - // allow up to 16-bits of offset, so two of the - // bytes must be 0x00 for us to recognize it. - if (jj+3 3) { - printf("%02x %02x %02x %02x - raw lat scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], latscale, jj); - } -//printf(" LATSCALE:"); -//printf("%02x%02x%02x%02x ", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3]); - jj+=4; - } - llvalid = 1; - - waypoint_temp = tpo_convert_ll(lat, lon); - track_add_wpt(track_temp, waypoint_temp); - cnttp++; - if constexpr(debug > 3) { - printf("Adding BASIC trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude); - } - } -#else if constexpr(debug > 3) { - printf("%02x %02x %02x %02x = bytes %u-%u (track %u, mode now %s)\n", + gbDebug("%02x %02x %02x %02x = bytes %u-%u (track %u, mode now %s)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], jj, jj+3, ii+1, tpmodeshow[tpmode]); } @@ -799,13 +716,13 @@ void TpoFormatBase::tpo_process_tracks() if (tpmode == GetFullPoint) { lon = le_read32(&buf[jj]); if constexpr(debug > 3) { - printf("%02x %02x %02x %02x - raw lon = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lon,jj); + gbDebug("%02x %02x %02x %02x - raw lon = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lon,jj); } jj+=4; lat = le_read32(&buf[jj]); if constexpr(debug > 3) { - printf("%02x %02x %02x %02x - raw lat = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lat,jj); + gbDebug("%02x %02x %02x %02x - raw lat = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lat,jj); } jj+=4; @@ -813,13 +730,13 @@ void TpoFormatBase::tpo_process_tracks() track_add_wpt(track_temp, waypoint_temp); cnttp++; if (((abs(waypoint_temp->latitude - lastlat) > 1.0) && lastlat) || ((abs(waypoint_temp->longitude - lastlon) > 1.0) && lastlon)) { - printf("WARNING! Track '%s' point #%d is more than 1 degree from the last track point!\n (probably corrupt - try splitting in two at sharp corners)\n", qPrintable(track_name), cnttp); + gbWarning("WARNING! Track '%s' point #%d is more than 1 degree from the last track point!\n (probably corrupt - try splitting in two at sharp corners)\n", gbLogCStr(track_name), cnttp); } lastlat = waypoint_temp->latitude; lastlon = waypoint_temp->longitude; if constexpr(debug > 3) { - printf("Adding BASIC trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude); + gbDebug("Adding BASIC trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude); } // after full point, can have scaling or 0x88 for another full point or single byte to be scaled @@ -838,7 +755,7 @@ void TpoFormatBase::tpo_process_tracks() if ((jj+3 3) { - printf("%02x %02x %02x %02x - raw lon scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lonscale, jj); + gbDebug("%02x %02x %02x %02x - raw lon scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lonscale, jj); } jj+=4; tpmode = CheckLatScale; @@ -857,7 +774,7 @@ void TpoFormatBase::tpo_process_tracks() if ((jj+3 3) { - printf("%02x %02x %02x %02x - raw lat scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], latscale, jj); + gbDebug("%02x %02x %02x %02x - raw lat scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], latscale, jj); } jj+=4; } @@ -866,25 +783,13 @@ void TpoFormatBase::tpo_process_tracks() tpmode = Check0x88Tag; continue; // for jj } -#endif -#ifdef Tracks2012 - // Check whether there's a lonlat coming up instead of - // offsets. - else if (buf[jj] == 0x88) { - if constexpr(debug > 3) { - printf("%02x should mean full lat/lon comes next (byte %u)\n",buf[jj],jj); - } - jj++; - llvalid = 0; - } -#else // Check whether 8 bytes of lon+lat are next, instead of offsets or another scaling spec. // 0x88 is a tag that signals a full trackpoint will follow if (tpmode == Check0x88Tag) { if (buf[jj] == FullPointTag) { if constexpr(debug > 3) { - printf("%02x should mean full lat/lon comes next (byte %u)\n",buf[jj],jj); + gbDebug("%02x should mean full lat/lon comes next (byte %u)\n",buf[jj],jj); } jj++; tpmode = GetFullPoint; @@ -893,56 +798,7 @@ void TpoFormatBase::tpo_process_tracks() tpmode = ScaleOneByte; // only if no 0x88 tag continue; // for jj } -#endif - -#ifdef Tracks2012 - // Check whether there's a lonlat + lonscale/latscale - // combo embedded in this track next. - else if (buf[jj] == 0x00) { - if constexpr(debug > 3) { - printf("%02x should mean full lat/lon or lonscale/latscale comes next (at byte %u)\n",buf[jj],jj); - } -//printf(" ZERO "); - jj++; - llvalid = 0; - } - - // Process the delta - else { - static const int scarray[] = {0,1,2,3,4,5,6,7,-8,-7,-6,-5,-4,-3,-2,-1}; - if constexpr(debug) { - printf("%02x - lat mult = %d, lon mult=%d, byte %u\n", buf[jj], scarray[buf[jj] & 0xf], scarray[buf[jj] >> 4], jj); - } - - - if (buf[jj] == 0) { - fatal(MYNAME ": Found unexpected ZERO\n"); - } - - if (latscale == 0 || lonscale == 0) { - fatal(MYNAME ": Found bad scales lonscale=0x%x latscale=0x%x\n", lonscale, latscale); - } - - if constexpr(debug > 3) { - printf("%02x - adjusting prev lat/lon from %i/%i", buf[jj], lat, lon); - } - lon += lonscale * scarray[buf[jj] >> 4]; - lat += latscale * scarray[(buf[jj] & 0xf)]; - if constexpr(debug > 3) { - printf(" to %i/%i, byte %u\n", lat, lon, jj); - } -//printf("."); - jj++; - - waypoint_temp = tpo_convert_ll(lat, lon); - track_add_wpt(track_temp, waypoint_temp); - cnttp++; - if constexpr(debug > 3) { - printf("Adding ADJUSTED trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude); - } - } -#else // ScaleOneByte applies lonscale and latscale to a single byte to create an 8-byte lat+lon // EndScalePoints (0) is a tag that signals an end to adjusted trackpoints (full point or scale may follow) if (tpmode == ScaleOneByte) { @@ -950,7 +806,7 @@ void TpoFormatBase::tpo_process_tracks() // list of single bytes to be scaled can only end with 0x00, can then have full point or scaling if (buf[jj] == EndScaleTag) { if constexpr(debug > 3) { - printf("%02x should mean full lat/lon or lonscale/latscale comes next (at byte %u)\n",buf[jj],jj); + gbDebug("%02x should mean full lat/lon or lonscale/latscale comes next (at byte %u)\n",buf[jj],jj); } jj++; tpmode = GetFullPoint; @@ -962,7 +818,7 @@ void TpoFormatBase::tpo_process_tracks() if (buf[jj] == FullPointTag) { if constexpr(debug > 3) { - printf("%02x should mean full lat/lon comes next (at byte %u)\n",buf[jj],jj); + gbDebug("%02x should mean full lat/lon comes next (at byte %u)\n",buf[jj],jj); } jj++; tpmode = GetFullPoint; @@ -973,23 +829,23 @@ void TpoFormatBase::tpo_process_tracks() static const int scarray[] = {0,1,2,3,4,5,6,7,-8,-7,-6,-5,-4,-3,-2,-1}; // MAGIC! (no idea where this comes from) if constexpr(debug) { - printf("%02x - lat mult = %d, lon mult=%d, byte %u\n", buf[jj], scarray[buf[jj] & 0xf], scarray[buf[jj] >> 4], jj); + gbDebug("%02x - lat mult = %d, lon mult=%d, byte %u\n", buf[jj], scarray[buf[jj] & 0xf], scarray[buf[jj] >> 4], jj); } if (buf[jj] == 0) { - fatal(MYNAME ": Found unexpected ZERO\n"); + gbFatal("Found unexpected ZERO\n"); } if ((latscale == 0) || (lonscale == 0)) { - fatal(MYNAME ": Found bad scales lonscale=0x%x latscale=0x%x while trying to scale a single byte trackpoint\n", lonscale, latscale); + gbFatal("Found bad scales lonscale=0x%x latscale=0x%x while trying to scale a single byte trackpoint\n", lonscale, latscale); } if constexpr(debug > 3) { - printf("%02x - adjusting prev lat/lon from %i/%i", buf[jj], lat, lon); + gbDebug("%02x - adjusting prev lat/lon from %i/%i", buf[jj], lat, lon); } lon += lonscale * scarray[buf[jj] >> 4]; lat += latscale * scarray[(buf[jj] & 0xf)]; if constexpr(debug > 3) { - printf(" to %i/%i, byte %u\n", lat, lon, jj); + gbDebug(" to %i/%i, byte %u\n", lat, lon, jj); } jj++; @@ -997,16 +853,15 @@ void TpoFormatBase::tpo_process_tracks() track_add_wpt(track_temp, waypoint_temp); cnttp++; if constexpr(debug > 3) { - printf("Adding ADJUSTED trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude); + gbDebug("Adding ADJUSTED trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude); } if (((abs(waypoint_temp->latitude - lastlat) > 1) && lastlat) || ((abs(waypoint_temp->longitude - lastlon) > 1) && lastlon)) { - printf("WARNING! Track '%s' point #%i is more than 1 degree from the last track point!\n (probably corrupt - try splitting in two at sharp corners)\n", qPrintable(track_name), cnttp); + gbWarning("WARNING! Track '%s' point #%i is more than 1 degree from the last track point!\n (probably corrupt - try splitting in two at sharp corners)\n", gbLogCStr(track_name), cnttp); } lastlat = waypoint_temp->latitude; lastlon = waypoint_temp->longitude; } // if ScaleOneByte -#endif } // end for jj track_byte_count } // end for ii track_count @@ -1489,12 +1344,12 @@ void TpoFormatBase::tpo_read_3_x() void TpoFormatBase::tpo_rd_init(const QString& fname) { - tpo_file_in = gbfopen_le(fname, "rb", MYNAME); + tpo_file_in = gbfopen_le(fname, "rb"); tpo_check_version_string(); if (tpo_version == 2.0) { if (doing_wpts || doing_rtes) { - fatal(MYNAME ": this file format only supports tracks, not waypoints or routes.\n"); + gbFatal("this file format only supports tracks, not waypoints or routes.\n"); } /*fprintf(stderr,"Version 2.x, Looking for CTopoRoute\n"); */ @@ -1506,7 +1361,7 @@ TpoFormatBase::tpo_rd_init(const QString& fname) * plus four bytes is the end of the embedded PNG image */ tpo_read_until_section("Red Without Arrow", 17); } else { - fatal(MYNAME ": gpsbabel can only read TPO versions through 3.x.x\n"); + gbFatal("gpsbabel can only read TPO versions through 3.x.x\n"); } } @@ -1527,6 +1382,6 @@ TpoFormatBase::tpo_read() //printf("\nFound a version 3.x file\n"); tpo_read_3_x(); } else { - fatal(MYNAME ": gpsbabel can only read TPO versions through 3.x.x\n"); + gbFatal("gpsbabel can only read TPO versions through 3.x.x\n"); } } diff --git a/trackfilter.cc b/trackfilter.cc index 06fd4a684..1f7ec2dc2 100644 --- a/trackfilter.cc +++ b/trackfilter.cc @@ -25,7 +25,6 @@ static constexpr bool TRACKF_DBG = false; #include // for_each, sort, stable_sort #include // for assert #include // for nan -#include // for printf #include // for abs #include // for gmtime, strftime, time_t, tm #include // for next @@ -55,7 +54,6 @@ static constexpr bool TRACKF_DBG = false; #if FILTERS_ENABLED || MINIMAL_FILTERS -#define MYNAME "trackfilter" /******************************************************************************* * helpers @@ -86,7 +84,7 @@ qint64 TrackFilter::trackfilter_parse_time_opt(const QString& arg) bool ok; qint64 partial = match.captured(idx).toLong(&ok); if (!ok) { - fatal(MYNAME "-time: invalid quantity in move option \"%s\"!\n", qPrintable(match.captured(idx))); + gbFatal("time: invalid quantity in move option \"%s\"!\n", gbLogCStr(match.captured(idx))); } switch (match.captured(idx+1).at(0).toLower().toLatin1()) { @@ -108,7 +106,7 @@ qint64 TrackFilter::trackfilter_parse_time_opt(const QString& arg) case 'z': break; default: - fatal(MYNAME "-time: invalid unit in move option \"%s\"!\n", qPrintable(match.captured(idx+1))); + gbFatal("time: invalid unit in move option \"%s\"!\n", gbLogCStr(match.captured(idx+1))); } result += partial; @@ -116,10 +114,10 @@ qint64 TrackFilter::trackfilter_parse_time_opt(const QString& arg) } if constexpr(TRACKF_DBG) { - qDebug() << MYNAME "-time option: shift =" << result / 1000.0 << "seconds"; + qDebug() << "time option: shift =" << result / 1000.0 << "seconds"; } } else { - fatal(MYNAME "-time: invalid value in move option \"%s\"!\n", qPrintable(arg)); + gbFatal("time: invalid value in move option \"%s\"!\n", gbLogCStr(arg)); } return result; @@ -160,7 +158,7 @@ fix_type TrackFilter::trackfilter_parse_fix(int* nsats) *nsats = 0; return fix_none; } - fatal(MYNAME ": invalid fix type\n"); + gbFatal("invalid fix type\n"); return fix_unknown; } @@ -194,7 +192,7 @@ void TrackFilter::trackfilter_fill_track_list_cb(const route_head* track) /* ca QRegularExpression regex(QRegularExpression::wildcardToRegularExpression(opt_name), QRegularExpression::CaseInsensitiveOption); if (!regex.isValid()) { - fatal(FatalMsg() << "track: name option is an invalid expression."); + gbFatal(FatalMsg() << "track: name option is an invalid expression."); } if (!regex.match(track->rte_name).hasMatch()) { track_del_head(const_cast(track)); @@ -206,7 +204,7 @@ void TrackFilter::trackfilter_fill_track_list_cb(const route_head* track) /* ca foreach (const Waypoint* wpt, track->waypoint_list) { if (!(opt_merge && opt_discard) && need_time && (!wpt->creation_time.isValid())) { - fatal(MYNAME "-init: Found track point at %f,%f without time!\n", + gbFatal("init: Found track point at %f,%f without time!\n", wpt->latitude, wpt->longitude); } @@ -214,7 +212,7 @@ void TrackFilter::trackfilter_fill_track_list_cb(const route_head* track) /* ca if (!opt_merge) { QString t1 = prev->CreationTimeXML(); QString t2 = wpt->CreationTimeXML(); - fatal(MYNAME "-init: Track points badly ordered (timestamp %s > %s)!\n", qPrintable(t1), qPrintable(t2)); + gbFatal("init: Track points badly ordered (timestamp %s > %s)!\n", gbLogCStr(t1), gbLogCStr(t2)); } } prev = wpt; @@ -297,7 +295,7 @@ void TrackFilter::trackfilter_title() } if (opt_title.isEmpty()) { - fatal(MYNAME "-title: Missing your title!\n"); + gbFatal("title: Missing your title!\n"); } for (auto* track : std::as_const(track_list)) { trackfilter_pack_init_rte_name(track, QDateTime::fromMSecsSinceEpoch(0, QtUTC)); @@ -318,9 +316,9 @@ void TrackFilter::trackfilter_pack() auto prev_last_time = trackfilter_get_last_time(track_list.at(j)); auto curr_first_time = trackfilter_get_first_time(track_list.at(i)); if (prev_last_time >= curr_first_time) { - fatal(MYNAME "-pack: Tracks overlap in time! %s >= %s at %d\n", - qPrintable(prev_last_time.toString()), - qPrintable(curr_first_time.toString()), i); + gbFatal("pack: Tracks overlap in time! %s >= %s at %d\n", + gbLogCStr(prev_last_time.toString()), + gbLogCStr(curr_first_time.toString()), i); } } @@ -407,10 +405,10 @@ void TrackFilter::trackfilter_merge() } if (global_opts.verbose_status > 0) { - printf(MYNAME "-merge: %d track point(s) merged, %d dropped.\n", track_waypt_count(), original_waypt_count - track_waypt_count()); + gbInfo("merge: %d track point(s) merged, %d dropped.\n", track_waypt_count(), original_waypt_count - track_waypt_count()); } if ((original_waypt_count > 0) && (track_waypt_count() == 0)) { - warning(MYNAME "-merge: All %d track points have been dropped!\n", original_waypt_count); + gbWarning("merge: All %d track points have been dropped!\n", original_waypt_count); } } } @@ -422,7 +420,7 @@ void TrackFilter::trackfilter_merge() void TrackFilter::trackfilter_split() { if (track_list.size() > 1) { - fatal(MYNAME "-split: Cannot split more than one track, please pack (or merge) before!\n"); + gbFatal("split: Cannot split more than one track, please pack (or merge) before!\n"); } else if (!track_list.isEmpty()) { route_head* master = track_list.first(); if (master->rte_waypt_ct() <= 1) { @@ -443,7 +441,7 @@ void TrackFilter::trackfilter_split() bool ok; interval = match.captured(1).toDouble(&ok); if (!ok || interval <= 0.0) { - fatal(MYNAME ": invalid time interval specified \"%s\", must be a positive number.\n", qPrintable(match.captured(1))); + gbFatal("invalid time interval specified \"%s\", must be a positive number.\n", gbLogCStr(match.captured(1))); } switch (match.captured(2).at(0).toLower().toLatin1()) { @@ -459,14 +457,14 @@ void TrackFilter::trackfilter_split() case 's': break; default: - fatal(MYNAME ": invalid time interval unit specified.\n"); + gbFatal("invalid time interval unit specified.\n"); } if constexpr(TRACKF_DBG) { - printf(MYNAME ": interval %f seconds\n", interval); + gbDebug("interval %f seconds\n", interval); } } else { - fatal(MYNAME ": invalid timer interval specified \"%s\", must be a positive number, followed by 'd' for days, 'h' for hours, 'm' for minutes or 's' for seconds.\n", qPrintable(opt_split)); + gbFatal("invalid timer interval specified \"%s\", must be a positive number, followed by 'd' for days, 'h' for hours, 'm' for minutes or 's' for seconds.\n", gbLogCStr(opt_split)); } } @@ -479,7 +477,7 @@ void TrackFilter::trackfilter_split() bool ok; distance = match.captured(1).toDouble(&ok); if (!ok || distance <= 0.0) { - fatal(MYNAME ": invalid time distance specified \"%s\", must be a positive number.\n", qPrintable(match.captured(1))); + gbFatal("invalid time distance specified \"%s\", must be a positive number.\n", gbLogCStr(match.captured(1))); } switch (match.captured(2).at(0).toLower().toLatin1()) { @@ -490,14 +488,14 @@ void TrackFilter::trackfilter_split() distance *= kMetersPerMile; break; default: - fatal(MYNAME ": invalid distance unit specified.\n"); + gbFatal("invalid distance unit specified.\n"); } if constexpr(TRACKF_DBG) { - printf(MYNAME ": distance %f meters\n", distance); + gbDebug("distance %f meters\n", distance); } } else { - fatal(MYNAME ": invalid distance specified \"%s\", must be a positive number followed by 'k' for kilometers or 'm' for miles.\n", qPrintable(opt_sdistance.get())); + gbFatal("invalid distance specified \"%s\", must be a positive number followed by 'k' for kilometers or 'm' for miles.\n", gbLogCStr(opt_sdistance.get())); } } @@ -525,7 +523,7 @@ void TrackFilter::trackfilter_split() wpt->GetCreationTime().toLocalTime().date(); if constexpr(TRACKF_DBG) { if (new_track_flag) { - printf(MYNAME ": new day %s\n", qPrintable(wpt->GetCreationTime().toLocalTime().date().toString(Qt::ISODate))); + gbDebug("new day %s\n", gbLogCStr(wpt->GetCreationTime().toLocalTime().date().toString(Qt::ISODate))); } } } else { @@ -537,7 +535,7 @@ void TrackFilter::trackfilter_split() if (curdist <= distance) { new_track_flag = false; } else if constexpr(TRACKF_DBG) { - printf(MYNAME ": sdistance, %g > %g\n", curdist, distance); + gbDebug("sdistance, %g > %g\n", curdist, distance); } } @@ -546,14 +544,14 @@ void TrackFilter::trackfilter_split() if (tr_interval <= interval) { new_track_flag = false; } else if constexpr(TRACKF_DBG) { - printf(MYNAME ": split, %g > %g\n", tr_interval, interval); + gbDebug("split, %g > %g\n", tr_interval, interval); } } } if (new_track_flag) { if constexpr(TRACKF_DBG) { - printf(MYNAME ": splitting new track\n"); + gbDebug("splitting new track\n"); } curr = new route_head; trackfilter_split_init_rte_name(curr, wpt->GetCreationTime()); @@ -589,7 +587,7 @@ void TrackFilter::trackfilter_move() } } if (timeless_points > 0) { - warning(MYNAME "-move: %d points out of %d total points didn't have " + gbWarning("move: %d points out of %d total points didn't have " "time information and could not be moved.\n", timeless_points, track_waypt_count()); } @@ -683,14 +681,14 @@ QDateTime TrackFilter::trackfilter_range_check(const QString& timestr) result.setTimeSpec(Qt::UTC); #endif if (!result.isValid()) { - fatal(MYNAME "-range-check: Invalid timestamp \"%s\"!\n", qPrintable(timestr)); + gbFatal("range-check: Invalid timestamp \"%s\"!\n", gbLogCStr(timestr)); } if constexpr(TRACKF_DBG) { - qDebug() << MYNAME "-range-check: " << result; + qDebug() << "range-check: " << result; } } else { - fatal(MYNAME "-range-check: Invalid value for option \"%s\"!\n", qPrintable(timestr)); + gbFatal("range-check: Invalid value for option \"%s\"!\n", gbLogCStr(timestr)); } return result; @@ -743,7 +741,7 @@ void TrackFilter::trackfilter_range() } if ((original_waypt_count > 0) && (track_waypt_count() == 0)) { - warning(MYNAME "-range: All %d track points have been dropped!\n", original_waypt_count); + gbWarning("range: All %d track points have been dropped!\n", original_waypt_count); } } @@ -845,24 +843,24 @@ TrackFilter::faketime_t TrackFilter::trackfilter_faketime_check(const QString& t result.start.setTimeSpec(Qt::UTC); #endif if (!result.start.isValid()) { - fatal(MYNAME "-faketime-check: Invalid timestamp \"%s\"!\n", qPrintable(start)); + gbFatal("faketime-check: Invalid timestamp \"%s\"!\n", gbLogCStr(start)); } if (match.capturedLength(3) > 0) { bool ok; result.step = llround(1000.0 * match.captured(3).toDouble(&ok)); if (!ok) { - fatal(MYNAME "-faketime-check: Invalid step \"%s\"!\n", qPrintable(match.captured(3))); + gbFatal("faketime-check: Invalid step \"%s\"!\n", gbLogCStr(match.captured(3))); } } else { result.step = 0; } if constexpr(TRACKF_DBG) { - qDebug() << MYNAME "-faketime option: force =" << result.force << ", timestamp =" << result.start << ", step =" << result.step << "milliseconds"; + qDebug() << "faketime option: force =" << result.force << ", timestamp =" << result.start << ", step =" << result.step << "milliseconds"; } } else { - fatal(MYNAME "-faketime-check: Invalid value for faketime option \"%s\"!\n", qPrintable(timestr)); + gbFatal("faketime-check: Invalid value for faketime option \"%s\"!\n", gbLogCStr(timestr)); } return result; @@ -1124,7 +1122,7 @@ void TrackFilter::process() if (opt_minpoints) { minimum_points = opt_minpoints.get_result(); if (minimum_points <= 0) { - fatal(MYNAME "-minimum_points: option value must be a positive integer!\n"); + gbFatal("minimum_points: option value must be a positive integer!\n"); } track_disp_all(trackfilter_minpoint_list_cb_f, nullptr, nullptr); } diff --git a/transform.cc b/transform.cc index bb5c98e94..dade70d93 100644 --- a/transform.cc +++ b/transform.cc @@ -31,8 +31,6 @@ #if FILTERS_ENABLED -#define MYNAME "transform" - void TransformFilter::transform_waypoints() { auto* rte = new route_head; @@ -155,7 +153,7 @@ void TransformFilter::process() route_flush_all_tracks(); } } else { - fatal(MYNAME ": Invalid option value (%s)!\n", qPrintable(opt_waypts)); + gbFatal("Invalid option value (%s)!\n", gbLogCStr(opt_waypts)); } } if (opt_routes) { @@ -171,7 +169,7 @@ void TransformFilter::process() route_flush_all_tracks(); } } else { - fatal(MYNAME ": Invalid option value (%s)!\n", qPrintable(opt_routes)); + gbFatal("Invalid option value (%s)!\n", gbLogCStr(opt_routes)); } } if (opt_tracks) { @@ -187,7 +185,7 @@ void TransformFilter::process() route_flush_all_routes(); } } else { - fatal(MYNAME ": Invalid option value (%s)!\n", qPrintable(opt_tracks)); + gbFatal("Invalid option value (%s)!\n", gbLogCStr(opt_tracks)); } } } diff --git a/unicsv.cc b/unicsv.cc index bae0737dd..34b557ef7 100644 --- a/unicsv.cc +++ b/unicsv.cc @@ -54,8 +54,6 @@ #include "src/core/textstream.h" // for TextStream -#define MYNAME "unicsv" - /* * ! Please use always underscores in field names ! * we check a second time after replacing underscores with spaces @@ -243,7 +241,7 @@ UnicsvFormat::unicsv_parse_date(const char* str, int* consumed) *consumed = 0; /* for a possible date */ return {}; } - fatal(FatalMsg() << MYNAME << ": Could not parse date string (" << str << ")."); + gbFatal(FatalMsg() << "Could not parse date string (" << str << ")."); } if ((p1 > 99) || (sep[0] == '-')) { /* Y-M-D (iso like) */ @@ -272,12 +270,12 @@ UnicsvFormat::unicsv_parse_date(const char* str, int* consumed) *consumed = 0; return {}; /* don't stop here */ } - fatal(FatalMsg() << MYNAME << ": Could not parse date string (" << str << ")."); + gbFatal(FatalMsg() << "Could not parse date string (" << str << ")."); } QDate result{tm.tm_year, tm.tm_mon, tm.tm_mday}; if (!result.isValid()) { - fatal(FatalMsg() << MYNAME << ": Invalid date parsed from string (" << str << ")."); + gbFatal(FatalMsg() << "Invalid date parsed from string (" << str << ")."); } return result; } @@ -302,7 +300,7 @@ UnicsvFormat::unicsv_parse_time(const char* str, QDate& date) } int ct = sscanf(str, "%d%*1[.://]%d%*1[.://]%d%lf", &hour, &min, &sec, &frac_sec); if (ct < 3) { - fatal(FatalMsg() << MYNAME << ": Could not parse time string (" << str << ")."); + gbFatal(FatalMsg() << "Could not parse time string (" << str << ")."); } if (ct >= 4) { // Don't round up and ripple through seconds, minutes, hours. @@ -314,7 +312,7 @@ UnicsvFormat::unicsv_parse_time(const char* str, QDate& date) QTime result{hour, min, sec, msec}; if (!result.isValid()) { - fatal(FatalMsg() << MYNAME << ": Invalid time parsed from string (" << str << ")."); + gbFatal(FatalMsg() << "Invalid time parsed from string (" << str << ")."); } return result; } @@ -417,14 +415,14 @@ UnicsvFormat::unicsv_fondle_header(QString header) if (it == fields_def.cend()) { // not found if (global_opts.debug_level) { - warning(MYNAME ": Unhandled column \"%s\".\n", qPrintable(value)); + gbWarning("Unhandled column \"%s\".\n", gbLogCStr(value)); } } else { // found const field_t f = *it; unicsv_fields_tab.last() = f.type; if (global_opts.debug_level) { - warning(MYNAME ": Interpreting column \"%s\" as %s(%d).\n", qPrintable(value), qPrintable(f.name), f.type); + gbWarning("Interpreting column \"%s\" as %s(%d).\n", gbLogCStr(value), gbLogCStr(f.name), f.type); } /* handle some special items */ @@ -465,10 +463,10 @@ UnicsvFormat::rd_init(const QString& fname) unicsv_detect = (!(global_opts.masked_objective & (WPTDATAMASK | TRKDATAMASK | RTEDATAMASK | POSNDATAMASK))); unicsv_track = unicsv_route = nullptr; - unicsv_datum_idx = gt_lookup_datum_index(opt_datum, MYNAME); + unicsv_datum_idx = gt_lookup_datum_index(opt_datum); fin = new gpsbabel::TextStream; - fin->open(fname, QIODevice::ReadOnly, MYNAME, opt_codec.get().toUtf8()); + fin->open(fname, QIODevice::ReadOnly, opt_codec.get().toUtf8()); unicsv_lineno = 0; if (opt_fields) { QString fields = opt_fields; @@ -580,7 +578,7 @@ UnicsvFormat::unicsv_parse_one_line(const QString& ibuf) break; case fld_altitude: - if (parse_distance(value, &d, unicsv_altscale, MYNAME)) { + if (parse_distance(value, &d, unicsv_altscale)) { if (fabs(d) < fabs(unknown_alt)) { wpt->altitude = d; } @@ -605,7 +603,7 @@ UnicsvFormat::unicsv_parse_one_line(const QString& ibuf) case fld_utm: parse_coordinates(value, unicsv_datum_idx, grid_utm, - &wpt->latitude, &wpt->longitude, MYNAME); + &wpt->latitude, &wpt->longitude); /* coordinates from parse_coordinates are in WGS84 don't convert a second time */ src_datum = kDatumWGS84; @@ -613,7 +611,7 @@ UnicsvFormat::unicsv_parse_one_line(const QString& ibuf) case fld_bng: parse_coordinates(value, kDatumOSGB36, grid_bng, - &wpt->latitude, &wpt->longitude, MYNAME); + &wpt->latitude, &wpt->longitude); /* coordinates from parse_coordinates are in WGS84 don't convert a second time */ src_datum = kDatumWGS84; @@ -633,7 +631,7 @@ UnicsvFormat::unicsv_parse_one_line(const QString& ibuf) case fld_swiss: parse_coordinates(value, kDatumWGS84, grid_swiss, - &wpt->latitude, &wpt->longitude, MYNAME); + &wpt->latitude, &wpt->longitude); /* coordinates from parse_coordinates are in WGS84 don't convert a second time */ src_datum = kDatumWGS84; @@ -707,7 +705,7 @@ UnicsvFormat::unicsv_parse_one_line(const QString& ibuf) break; case fld_speed: - if (parse_speed(value, &d, 1.0, MYNAME)) { + if (parse_speed(value, &d, 1.0)) { wpt->set_speed(d); if (unicsv_detect) { unicsv_data_type = trkdata; @@ -758,13 +756,13 @@ UnicsvFormat::unicsv_parse_one_line(const QString& ibuf) break; case fld_proximity: - if (parse_distance(value, &d, unicsv_proximityscale, MYNAME)) { + if (parse_distance(value, &d, unicsv_proximityscale)) { wpt->set_proximity(d); } break; case fld_depth: - if (parse_distance(value, &d, unicsv_depthscale, MYNAME)) { + if (parse_distance(value, &d, unicsv_depthscale)) { wpt->set_depth(d); } break; @@ -1015,19 +1013,19 @@ UnicsvFormat::unicsv_parse_one_line(const QString& ibuf) if (! GPS_Math_EN_To_UKOSNG_Map( bng_easting, bng_northing, &bnge, &bngn, bngz)) { - fatal(MYNAME ": Unable to convert BNG coordinates (%.f %.f)!\n", + gbFatal("Unable to convert BNG coordinates (%.f %.f)!\n", bng_easting, bng_northing); } if (! GPS_Math_UKOSMap_To_WGS84_H( bngz, bnge, bngn, &wpt->latitude, &wpt->longitude)) - fatal(MYNAME ": Unable to convert BNG coordinates (%s %.f %.f)!\n", + gbFatal("Unable to convert BNG coordinates (%s %.f %.f)!\n", bngz, bnge, bngn); } else { // traditional zone easting northing if (! GPS_Math_UKOSMap_To_WGS84_H( CSTR(bng_zone), bng_easting, bng_northing, &wpt->latitude, &wpt->longitude)) - fatal(MYNAME ": Unable to convert BNG coordinates (%s %.f %.f)!\n", + gbFatal("Unable to convert BNG coordinates (%s %.f %.f)!\n", CSTR(bng_zone), bng_easting, bng_northing); } src_datum = kDatumWGS84; /* don't convert afterwards */ @@ -1089,10 +1087,10 @@ UnicsvFormat::read() [[noreturn]] void UnicsvFormat::unicsv_fatal_outside(const Waypoint* wpt) const { *fout << "#####\n"; - fatal(MYNAME ": %s (%s) is outside of convertible area of grid \"%s\"!\n", - wpt->shortname.isEmpty() ? "Waypoint" : qPrintable(wpt->shortname), - qPrintable(pretty_deg_format(wpt->latitude, wpt->longitude, 'd', nullptr, false)), - qPrintable(gt_get_mps_grid_longname(unicsv_grid_idx, MYNAME))); + gbFatal("%s (%s) is outside of convertible area of grid \"%s\"!\n", + wpt->shortname.isEmpty() ? "Waypoint" : gbLogCStr(wpt->shortname), + gbLogCStr(pretty_deg_format(wpt->latitude, wpt->longitude, 'd', nullptr, false)), + gbLogCStr(gt_get_mps_grid_longname(unicsv_grid_idx))); } void @@ -1676,11 +1674,11 @@ void UnicsvFormat::wr_init(const QString& fname) { if (opt_fields) { - fatal(FatalMsg() << MYNAME << - ": option 'fields' is not supported on output"); + gbFatal(FatalMsg() << + "option 'fields' is not supported on output"); } fout = new gpsbabel::TextStream; - fout->open(fname, QIODevice::WriteOnly, MYNAME, opt_codec.get().toUtf8()); + fout->open(fname, QIODevice::WriteOnly, opt_codec.get().toUtf8()); fout->setRealNumberNotation(QTextStream::FixedNotation); unicsv_outp_flags.reset(); @@ -1695,10 +1693,10 @@ UnicsvFormat::wr_init(const QString& fname) if (int i = opt_grid.toInt(&ok); ok) { unicsv_grid_idx = (grid_type) i; if ((unicsv_grid_idx < GRID_INDEX_MIN) || (unicsv_grid_idx > GRID_INDEX_MAX)) - fatal(MYNAME ": Grid index out of range (%d..%d)!\n", + gbFatal("Grid index out of range (%d..%d)!\n", (int)GRID_INDEX_MIN, (int)GRID_INDEX_MAX); } else { - unicsv_grid_idx = gt_lookup_grid_type(opt_grid, MYNAME); + unicsv_grid_idx = gt_lookup_grid_type(opt_grid); } } @@ -1712,7 +1710,7 @@ UnicsvFormat::wr_init(const QString& fname) { unicsv_datum_idx = kDatumWGS84; /* internal, becomes CH1903 */ } else { - unicsv_datum_idx = gt_lookup_datum_index(opt_datum, MYNAME); + unicsv_datum_idx = gt_lookup_datum_index(opt_datum); } llprec = opt_prec.get_result(); @@ -1736,8 +1734,8 @@ void UnicsvFormat::unicsv_check_modes(bool test) { if (test) { - fatal(FatalMsg() << MYNAME << - " : Invalid combination of -w, -t, -r selected. Use only one."); + gbFatal(FatalMsg() << + "Invalid combination of -w, -t, -r selected. Use only one."); } } @@ -1762,7 +1760,7 @@ UnicsvFormat::write() route_disp_all(nullptr, nullptr, unicsv_waypt_enum_cb_lambda); break; case posndata: - fatal(FatalMsg() << MYNAME << ": Realtime positioning not supported."); + gbFatal(FatalMsg() << "Realtime positioning not supported."); } *fout << "No" << unicsv_fieldsep; diff --git a/units.cc b/units.cc index 74a51abe5..72c29994e 100644 --- a/units.cc +++ b/units.cc @@ -34,7 +34,7 @@ UnitsFormatter::setunits(units_t u) units = u; break; default: - fatal("not done yet"); + gbFatal("not done yet\n"); break; } } @@ -71,7 +71,7 @@ UnitsFormatter::fmt_distance(const double distance_meters) const break; default: - fatal("not done yet"); + gbFatal("not done yet\n"); break; } @@ -100,7 +100,7 @@ UnitsFormatter::fmt_altitude(const double distance_meters) const break; default: - fatal("not done yet"); + gbFatal("not done yet\n"); break; } @@ -132,7 +132,7 @@ UnitsFormatter::fmt_speed(const double speed_meters_per_sec) const } break; default: - fatal("not done yet"); + gbFatal("not done yet\n"); } return {d, tag}; diff --git a/util.cc b/util.cc index bf54ad498..61c7cddbf 100644 --- a/util.cc +++ b/util.cc @@ -66,7 +66,7 @@ xmalloc(size_t size) void* obj = malloc(size); if (!obj) { - fatal("gpsbabel: Unable to allocate %zu bytes of memory.\n", size); + gbFatal("gpsbabel: Unable to allocate %zu bytes of memory.\n", size); } return obj; @@ -78,7 +78,7 @@ xcalloc(size_t nmemb, size_t size) void* obj = calloc(nmemb, size); if (!obj) { - fatal("gpsbabel: Unable to allocate %zu units of %zu bytes of memory.\n", nmemb, size); + gbFatal("gpsbabel: Unable to allocate %zu units of %zu bytes of memory.\n", nmemb, size); } return obj; @@ -96,7 +96,7 @@ xstrdup(const char* s) char* o = s ? strdup(s) : strdup(""); if (!o) { - fatal("gpsbabel: Unable to allocate %zu bytes of memory.\n", strlen(s)); + gbFatal("gpsbabel: Unable to allocate %zu bytes of memory.\n", strlen(s)); } return o; @@ -108,7 +108,7 @@ xrealloc(void* p, size_t s) char* o = (char*) realloc(p, s); if (!o) { - fatal("gpsbabel: Unable to realloc %zu bytes of memory.\n", s); + gbFatal("gpsbabel: Unable to realloc %zu bytes of memory.\n", s); } return o; @@ -118,13 +118,13 @@ xrealloc(void* p, size_t s) * Wrapper for open that honours - for stdin, stdout, unifies error text. */ FILE* -xfopen(const QString& fname, const char* type, const QString& errtxt) +xfopen(const QString& fname, const char* type) { bool am_writing = strchr(type, 'w') != nullptr; if (fname.isEmpty()) { - fatal("%s must have a filename specified for %s.\n", - qPrintable(errtxt), am_writing ? "write" : "read"); + gbFatal("must have a filename specified for %s.\n", + am_writing ? "write" : "read"); } if (fname == "-") { @@ -136,8 +136,8 @@ xfopen(const QString& fname, const char* type, const QString& errtxt) // vs. the STD C library used for the actual file I/O. It's worth it // to get a better error message. QFileInfo info(fname); - fatal("%s cannot open '%s' for %s. Error was '%s'.\n", - qPrintable(errtxt), qPrintable(info.absoluteFilePath()), + gbFatal("cannot open '%s' for %s. Error was '%s'.\n", + gbLogCStr(info.absoluteFilePath()), am_writing ? "write" : "read", strerror(errno)); } @@ -623,7 +623,7 @@ convert_human_date_format(const QString& human_datef) } if (!okay) { - fatal(FatalMsg().nospace() << "Invalid character " << cin << " in date format " << human_datef << "!"); + gbFatal(FatalMsg().nospace() << "Invalid character " << cin << " in date format " << human_datef << "!"); } } return result; @@ -708,7 +708,7 @@ convert_human_time_format(const QString& human_timef) } if (!okay) { - fatal(FatalMsg().nospace() << "Invalid character " << cin << " in time format " << human_timef << "!"); + gbFatal(FatalMsg().nospace() << "Invalid character " << cin << " in time format " << human_timef << "!"); } } return result; @@ -860,7 +860,7 @@ QTextCodec* get_codec(const QByteArray& cs_name) { QTextCodec* codec = QTextCodec::codecForName(cs_name); if (codec == nullptr) { - fatal(FatalMsg().nospace() << "Unsupported character set " << cs_name << "."); + gbFatal(FatalMsg().nospace() << "Unsupported character set " << cs_name << "."); } return codec; } diff --git a/v900.cc b/v900.cc index baf5a326b..bcc248aa7 100644 --- a/v900.cc +++ b/v900.cc @@ -75,7 +75,7 @@ for a little more info, see structures: #include // for assert #include // for va_end, va_start -#include // for fclose, fgets, fread, vfprintf, stderr, va_list +#include // for fclose, fgets, fread, va_list #include // for strtod #include // for strncmp, strcat, strcpy, strstr @@ -91,28 +91,25 @@ for a little more info, see structures: void V900Format::v900_log(const char* fmt, ...) { - va_list ap; - - if (global_opts.debug_level < 1) { - return; + if (global_opts.debug_level >= 1) { + va_list ap; + va_start(ap, fmt); + gbVLegacyLog(QtDebugMsg, fmt, ap); + va_end(ap); } - - va_start(ap, fmt); - vfprintf(stderr, fmt, ap); - va_end(ap); } void V900Format::rd_init(const QString& fname) { - v900_log("%s(%s)\n",__func__,qPrintable(fname)); + v900_log("%s(%s)\n",__func__,gbLogCStr(fname)); /* note: file is opened in binary mode, since lines end with \r\n, and in windows text mode that will be translated to a single \n, making the line len one character shorter than on linux machines. */ fin = ufopen(fname, "rb"); if (!fin) { - fatal("v900: could not open '%s'.\n", qPrintable(fname)); + gbFatal("v900: could not open '%s'.\n", gbLogCStr(fname)); } } @@ -166,7 +163,7 @@ V900Format::read() /* first, determine if this is advanced mode by reading the first line. since the first line does not contain any nulls, it can be safely read by fgets(). */ if (!fgets(line.text, sizeof(line), fin)) { - fatal("v900: error reading header (first) line from input file\n"); + gbFatal("v900: error reading header (first) line from input file\n"); } int is_advanced_mode = (nullptr != strstr(line.text,"PDOP")); /* PDOP field appears only in advanced mode */ @@ -200,7 +197,7 @@ V900Format::read() bad |= (line.bas.common.comma9 != ','); if (bad) { - warning("v900: skipping malformed record at line %d\n", lc); + gbWarning("v900: skipping malformed record at line %d\n", lc); } line.bas.common.comma1 = 0; @@ -216,7 +213,7 @@ V900Format::read() /* change all "," characters to NULLs. so every field is null terminated. */ - assert(line.adv.comma10==','); // TODO: abort with fatal() + assert(line.adv.comma10==','); // TODO: abort with gbFatal() assert(line.adv.comma11==','); assert(line.adv.comma12==','); assert(line.adv.comma13==','); diff --git a/validate.cc b/validate.cc index e28e4a497..fd177d282 100644 --- a/validate.cc +++ b/validate.cc @@ -22,10 +22,8 @@ #include "defs.h" #include "validate.h" -#include #if FILTERS_ENABLED -#define MYNAME "validate" void ValidateFilter::validate_head(const route_head* /*unused*/) { @@ -38,11 +36,11 @@ void ValidateFilter::validate_head_trl(const route_head* header) { total_point_ct += point_ct; total_segment_ct += segment_ct; - if (debug) { - fprintf(stderr, "%s %d ct: %d, waypt_count: %d, segments %d\n", segment_type, header->rte_num, point_ct, header->rte_waypt_ct(), segment_ct); + if (opt_debug) { + gbDebug("%s %d ct: %d, waypt_count: %d, segments %d\n", segment_type, header->rte_num, point_ct, header->rte_waypt_ct(), segment_ct); } - if (!debug && (point_ct != header->rte_waypt_ct())) { - fatal(MYNAME ":%s %d count mismatch, expected %d, actual %d\n", segment_type, header->rte_num, header->rte_waypt_ct(), point_ct); + if (!opt_debug && (point_ct != header->rte_waypt_ct())) { + gbFatal("%s %d count mismatch, expected %d, actual %d\n", segment_type, header->rte_num, header->rte_waypt_ct(), point_ct); } } @@ -60,62 +58,59 @@ void ValidateFilter::process() RteHdFunctor validate_head_f(this, &ValidateFilter::validate_head); RteHdFunctor validate_head_trl_f(this, &ValidateFilter::validate_head_trl); - debug = opt_debug; - checkempty = opt_checkempty; - point_ct = 0; - if (debug) { - fprintf(stderr, "\nProcessing waypts\n"); + if (opt_debug) { + gbDebug("\nProcessing waypts\n"); } waypt_disp_all(validate_point_f); - if (debug) { - fprintf(stderr, "point ct: %d, waypt_count: %d\n", point_ct, waypt_count()); + if (opt_debug) { + gbDebug("point ct: %d, waypt_count: %d\n", point_ct, waypt_count()); } - if (!debug && (point_ct != waypt_count())) { - fatal(MYNAME ":Waypoint count mismatch, expected %d, actual %d\n", waypt_count(), point_ct); + if (!opt_debug && (point_ct != waypt_count())) { + gbFatal("Waypoint count mismatch, expected %d, actual %d\n", waypt_count(), point_ct); } head_ct = 0; total_point_ct = 0; total_segment_ct = 0; segment_type = "route"; - if (debug) { - fprintf(stderr, "\nProcessing routes\n"); + if (opt_debug) { + gbDebug("\nProcessing routes\n"); } route_disp_all(validate_head_f, validate_head_trl_f, validate_point_f); - if (debug) { - fprintf(stderr, "route head ct: %d, route_count: %d, total segment count: %d\n", head_ct, route_count(), total_segment_ct); - fprintf(stderr, "total route point ct: %d, route_waypt_count: %d\n", total_point_ct, route_waypt_count()); + if (opt_debug) { + gbDebug("route head ct: %d, route_count: %d, total segment count: %d\n", head_ct, route_count(), total_segment_ct); + gbDebug("total route point ct: %d, route_waypt_count: %d\n", total_point_ct, route_waypt_count()); } - if (!debug && (head_ct != route_count())) { - fatal(MYNAME ":Route count mismatch, expected %d, actual %d\n", route_count(), head_ct); + if (!opt_debug && (head_ct != route_count())) { + gbFatal("Route count mismatch, expected %d, actual %d\n", route_count(), head_ct); } - if (!debug && (total_point_ct != route_waypt_count())) { - fatal(MYNAME ":Total route waypoint count mismatch, expected %d, actual %d\n", route_waypt_count(), total_point_ct); + if (!opt_debug && (total_point_ct != route_waypt_count())) { + gbFatal("Total route waypoint count mismatch, expected %d, actual %d\n", route_waypt_count(), total_point_ct); } head_ct = 0; total_point_ct = 0; total_segment_ct = 0; segment_type = "track"; - if (debug) { - fprintf(stderr, "\nProcessing tracks\n"); + if (opt_debug) { + gbDebug("\nProcessing tracks\n"); } track_disp_all(validate_head_f, validate_head_trl_f, validate_point_f); - if (debug) { - fprintf(stderr, "track head ct: %d, track_count: %d, total segment count: %d\n", head_ct, track_count(), total_segment_ct); - fprintf(stderr, "total track point ct: %d, track_waypt_count: %d\n", total_point_ct, track_waypt_count()); + if (opt_debug) { + gbDebug("track head ct: %d, track_count: %d, total segment count: %d\n", head_ct, track_count(), total_segment_ct); + gbDebug("total track point ct: %d, track_waypt_count: %d\n", total_point_ct, track_waypt_count()); } - if (!debug && (head_ct != track_count())) { - fatal(MYNAME ":Track count mismatch, expected %d, actual %d\n", track_count(), head_ct); + if (!opt_debug && (head_ct != track_count())) { + gbFatal("Track count mismatch, expected %d, actual %d\n", track_count(), head_ct); } - if (!debug && (total_point_ct != track_waypt_count())) { - fatal(MYNAME ":Total track waypoint count mismatch, expected %d, actual %d\n", track_waypt_count(), total_point_ct); + if (!opt_debug && (total_point_ct != track_waypt_count())) { + gbFatal("Total track waypoint count mismatch, expected %d, actual %d\n", track_waypt_count(), total_point_ct); } - if (checkempty) { + if (opt_checkempty) { if (waypt_count()==0 && route_waypt_count()==0 && track_waypt_count()==0) { - fatal(MYNAME ":No input\n"); + gbFatal("No input\n"); } } } diff --git a/validate.h b/validate.h index f12c99aa7..e543bfa0b 100644 --- a/validate.h +++ b/validate.h @@ -44,9 +44,7 @@ class ValidateFilter:public Filter private: OptionBool opt_debug; - bool debug{}; OptionBool opt_checkempty; - bool checkempty{}; int point_ct{}; int total_point_ct{}; int segment_ct{}; diff --git a/vcf.cc b/vcf.cc index 491095504..6ce822766 100644 --- a/vcf.cc +++ b/vcf.cc @@ -31,13 +31,10 @@ #include "geocache.h" // for Geocache, Geocache::UtfString -#define MYNAME "VCF" - - void VcfFormat::wr_init(const QString& fname) { - file_out = gbfopen(fname, "w", MYNAME); + file_out = gbfopen(fname, "w"); } void diff --git a/vecs.cc b/vecs.cc index 6b07eaa60..1617d02a6 100644 --- a/vecs.cc +++ b/vecs.cc @@ -39,7 +39,7 @@ #include // for is_base_of #include // for as_const -#include "defs.h" // for arglist_t, CSTR, fatal, ff_cap, ARGTYPE_TYPEMASK, ff_type, ARGTYPE_BOOL, case_ignore_strcmp, gpsdata_type, warning, ff_cap_array, global_options, global_opts, ARGTYPE_FLOAT, ARGTYPE_HIDDEN, ARGTYPE_INT, ARGTYPE_REQUIRED +#include "defs.h" // for arglist_t, CSTR, gbFatal, ff_cap, ARGTYPE_TYPEMASK, ff_type, ARGTYPE_BOOL, case_ignore_strcmp, gpsdata_type, gbWarning, ff_cap_array, global_options, global_opts, ARGTYPE_FLOAT, ARGTYPE_HIDDEN, ARGTYPE_INT, ARGTYPE_REQUIRED #include "dg-100.h" // for Dg100FileFormat, Dg100SerialFormat, Dg200FileFormat, Dg200SerialFormat #include "exif.h" // for ExifFormat #include "format.h" // for Format @@ -566,7 +566,7 @@ void Vecs::assign_option(const QString& module, arglist_t& arg, const QString& v QString id = QStringLiteral("%1(%2)").arg(module, arg.argstring); if (arg.argval == nullptr) { - fatal("%s: Program error - No local variable defined for option.\n", qPrintable(id)); + gbFatal("%s: Program error - No local variable defined for option.\n", gbLogCStr(id)); } arg.argval->reset(); @@ -602,7 +602,7 @@ void Vecs::assign_option(const QString& module, arglist_t& arg, const QString& v rval = '1'; } } else { - warning("%s: Invalid logical value \"%s\".\n", qPrintable(id), qPrintable(val)); + gbWarning("%s: Invalid logical value \"%s\".\n", gbLogCStr(id), gbLogCStr(val)); rval = '0'; } } @@ -617,12 +617,12 @@ void Vecs::disp_vec_options(const QString& vecname, const QVector* ar if (args) { for (const auto& arg : *args) { if ((arg.argval != nullptr) && !arg.argval->isEmpty()) { - printf("options: module/option=value: %s/%s=\"%s\"", - qPrintable(vecname), qPrintable(arg.argstring), qPrintable(arg.argval->get())); + gbDebug("options: module/option=value: %s/%s=\"%s\"", + gbLogCStr(vecname), gbLogCStr(arg.argstring), gbLogCStr(arg.argval->get())); if (case_ignore_strcmp(arg.defaultvalue, arg.argval->get()) == 0) { - printf(" (=default)"); + gbDebug(" (=default)"); } - printf("\n"); + gbDebug("\n"); } } } @@ -642,7 +642,7 @@ void Vecs::validate_options(const QStringList& options, const QVector } } if (!valid) { - warning("'%s' is an unknown option to %s.\n", qPrintable(option_name), qPrintable(name)); + gbWarning("'%s' is an unknown option to %s.\n", gbLogCStr(option_name), gbLogCStr(name)); } } } @@ -695,7 +695,7 @@ Vecs::fmtinfo_t Vecs::find_vec(const QString& fmtargstring) { QStringList options = fmtargstring.split(','); if (options.isEmpty()) { - fatal("A format name is required.\n"); + gbFatal("A format name is required.\n"); } const QString fmtname = options.takeFirst(); @@ -761,7 +761,7 @@ QVector Vecs::create_style_vec() QString styledir(":/style"); QDir dir(styledir); if (!dir.isReadable()) { - fatal(FatalMsg() << "style directory" << QFileInfo(styledir).absoluteFilePath() << "not readable."); + gbFatal(FatalMsg() << "style directory" << QFileInfo(styledir).absoluteFilePath() << "not readable."); } dir.setNameFilters(QStringList("*.style")); @@ -771,7 +771,7 @@ QVector Vecs::create_style_vec() QVector slist; for (const auto& fileinfo : fileinfolist) { if (!fileinfo.isReadable()) { - fatal(FatalMsg() << "Cannot open style file" << fileinfo.absoluteFilePath() << "."); + gbFatal(FatalMsg() << "Cannot open style file" << fileinfo.absoluteFilePath() << "."); } style_vec_t entry; diff --git a/waypt.cc b/waypt.cc index 1d476c3d7..3a6a94090 100644 --- a/waypt.cc +++ b/waypt.cc @@ -82,8 +82,10 @@ waypt_count() void waypt_status_disp(int total_ct, int myct) { - fprintf(stdout, "%d/%d/%d\r", myct*100/total_ct, myct, total_ct); - fflush(stdout); + // If we use logging the first update will have this info trailing the + // "id: " output by qFormatLogMessage but subsequent updates will not. + fprintf(stderr, "%d/%d/%d\r", myct*100/total_ct, myct, total_ct); + fflush(stderr); } void @@ -592,11 +594,11 @@ void Waypoint::NormalizePosition() } if ((this->latitude < -90) || (this->latitude > 90.0)) - fatal(FatalMsg() << this->session->name + gbFatal(FatalMsg() << this->session->name << "Invalid latitude" << lat_orig << "in waypoint" << this->shortname); if ((this->longitude < -180) || (this->longitude > 180.0)) - fatal(FatalMsg() << "Invalid longitude" << lon_orig << "in waypoint" + gbFatal(FatalMsg() << "Invalid longitude" << lon_orig << "in waypoint" << this->shortname); } diff --git a/xcsv.cc b/xcsv.cc index 7b3008c41..b4066891e 100644 --- a/xcsv.cc +++ b/xcsv.cc @@ -65,8 +65,6 @@ #include "strptime.h" // for strptime -#define MYNAME "XCSV" - const QHash XcsvStyle::xcsv_tokens { { "ALT_FEET", XT_ALT_FEET }, { "ALT_METERS", XT_ALT_METERS }, @@ -199,14 +197,14 @@ QString XcsvStyle::dequote(const QString& in) void XcsvStyle::validate_fieldmap(const field_map& fmp, bool is_output) { if (fmp.key.isEmpty()) { - fatal(FatalMsg() << MYNAME << ": xcsv style is missing" << + gbFatal(FatalMsg() << "xcsv style is missing" << (is_output ? "output" : "input") << "field type."); } if (fmp.val.isNull()) { - fatal(FatalMsg() << MYNAME << ": xcsv style" << fmp.key.constData() << "is missing default."); + gbFatal(FatalMsg() << "xcsv style" << fmp.key.constData() << "is missing default."); } if (is_output && fmp.printfc.isNull()) { - fatal(FatalMsg() << MYNAME << ": xcsv style" << fmp.key.constData() << "output is missing format specifier."); + gbFatal(FatalMsg() << "xcsv style" << fmp.key.constData() << "output is missing format specifier."); } } @@ -287,7 +285,7 @@ XcsvFormat::sscanftime(const char* s, const char* format, QDate& date, QTime& ti bad_time_parse = true; } if ((time_result.has_value() && !time_result->isValid()) || bad_time_parse) { - fatal(MYNAME ": couldn't parse time from string '%s' with format '%s'.\n", + gbFatal("couldn't parse time from string '%s' with format '%s'.\n", s, format); } if (time_result.has_value()) { @@ -307,7 +305,7 @@ XcsvFormat::sscanftime(const char* s, const char* format, QDate& date, QTime& ti bad_date_parse = true; } if ((date_result.has_value() && !date_result->isValid()) || bad_date_parse) { - fatal(MYNAME ": couldn't parse date from string '%s' with format '%s'.\n", + gbFatal("couldn't parse date from string '%s' with format '%s'.\n", s, format); } if (date_result.has_value()) { @@ -316,7 +314,7 @@ XcsvFormat::sscanftime(const char* s, const char* format, QDate& date, QTime& ti } else { // Don't fuss for empty strings. if (*s) { - warning("date parse of string '%s' with format '%s' failed.\n", + gbWarning("date parse of string '%s' with format '%s' failed.\n", s, format); } } @@ -379,7 +377,7 @@ XcsvFormat::xcsv_parse_val(const QString& value, Waypoint* wpt, const XcsvStyle: Geocache* gc_data = nullptr; if (fmp.printfc.isNull()) { - fatal(MYNAME ": xcsv style '%s' is missing format specifier", fmp.key.constData()); + gbFatal("xcsv style '%s' is missing format specifier\n", fmp.key.constData()); } if (0 == strcmp(fmp.printfc.constData(), "\"%s\"")) { @@ -488,7 +486,7 @@ XcsvFormat::xcsv_parse_val(const QString& value, Waypoint* wpt, const XcsvStyle: } else if (*s == 's' || *s == 'S') { parse_data->lat_dir_positive = false; } else { - warning("parse of string '%s' on line number %d as LAT_DIR failed. Expected 'n', 'N', 's' or 'S'.\n", s, line_no); + gbWarning("parse of string '%s' on line number %d as LAT_DIR failed. Expected 'n', 'N', 's' or 'S'.\n", s, line_no); } break; case XcsvStyle::XT_LON_DIR: @@ -498,13 +496,13 @@ XcsvFormat::xcsv_parse_val(const QString& value, Waypoint* wpt, const XcsvStyle: } else if (*s == 'w' || *s == 'W') { parse_data->lon_dir_positive = false; } else { - warning("parse of string '%s' on line number %d as LON_DIR failed. Expected 'e', 'E', 'w' or 'W'.\n", s, line_no); + gbWarning("parse of string '%s' on line number %d as LON_DIR failed. Expected 'e', 'E', 'w' or 'W'.\n", s, line_no); } break; /* SPECIAL COORDINATES/GRID */ case XcsvStyle::XT_MAP_EN_BNG: parse_coordinates(s, kDatumOSGB36, grid_bng, - &wpt->latitude, &wpt->longitude, MYNAME); + &wpt->latitude, &wpt->longitude); break; case XcsvStyle::XT_UTM_ZONE: parse_data->utm_zone = xstrtoi(s, nullptr, 10); @@ -590,7 +588,7 @@ XcsvFormat::xcsv_parse_val(const QString& value, Waypoint* wpt, const XcsvStyle: wpt->SetCreationTime(0, excel_to_timetms(et)); parse_data->need_datetime = false; } else if (!value.isEmpty()) { - warning("parse of string '%s' on line number %d as EXCEL_TIME failed.\n", s, line_no); + gbWarning("parse of string '%s' on line number %d as EXCEL_TIME failed.\n", s, line_no); } } break; @@ -602,7 +600,7 @@ XcsvFormat::xcsv_parse_val(const QString& value, Waypoint* wpt, const XcsvStyle: wpt->SetCreationTime(tt); parse_data->need_datetime = false; } else if (!value.isEmpty()) { - warning("parse of string '%s' on line number %d as TIMET_TIME failed.\n", s, line_no); + gbWarning("parse of string '%s' on line number %d as TIMET_TIME failed.\n", s, line_no); } } break; @@ -614,7 +612,7 @@ XcsvFormat::xcsv_parse_val(const QString& value, Waypoint* wpt, const XcsvStyle: wpt->SetCreationTime(0, tt); parse_data->need_datetime = false; } else if (!value.isEmpty()) { - warning("parse of string '%s' on line number %d as TIMET_TIME_MS failed.\n", s, line_no); + gbWarning("parse of string '%s' on line number %d as TIMET_TIME_MS failed.\n", s, line_no); } } break; @@ -639,7 +637,7 @@ XcsvFormat::xcsv_parse_val(const QString& value, Waypoint* wpt, const XcsvStyle: wpt->SetCreationTime(dotnet_time_to_qdatetime(dnt)); parse_data->need_datetime = false; } else if (!value.isEmpty()) { - warning("parse of string '%s' on line number %d as NET_TIME failed.\n", s, line_no); + gbWarning("parse of string '%s' on line number %d as NET_TIME failed.\n", s, line_no); } } break; @@ -805,12 +803,12 @@ XcsvFormat::xcsv_parse_val(const QString& value, Waypoint* wpt, const XcsvStyle: } else if (strncmp(fmp.key.constData(), "LAT_10E", 7) == 0) { wpt->latitude = strtod(s, nullptr) / pow(10.0, strtod(fmp.key.constData()+7, nullptr)); } else { - warning(MYNAME ": Unknown style directive: %s\n", fmp.key.constData()); + gbWarning("Unknown style directive: %s\n", fmp.key.constData()); } break; default: - fatal("Unknown style directive: %s - %d\n", fmp.key.constData(), fmp.hashed_key); + gbFatal("Unknown style directive: %s - %d\n", fmp.key.constData(), fmp.hashed_key); break; } } @@ -863,7 +861,7 @@ XcsvFormat::read() xcsv_style->field_encloser, linecount); if (xcsv_style->ifields.isEmpty()) { - fatal(MYNAME ": attempt to read, but style '%s' has no IFIELDs in it.\n", qPrintable(xcsv_style->description)? qPrintable(xcsv_style->description) : "unknown"); + gbFatal("attempt to read, but style '%s' has no IFIELDs in it.\n", gbLogCStr(xcsv_style->description)? gbLogCStr(xcsv_style->description) : "unknown"); } int ifield_idx = 0; @@ -1226,7 +1224,7 @@ XcsvFormat::xcsv_waypt_pr(const Waypoint* wpt) double north; double east; if (! GPS_Math_WGS84_To_UKOSMap_H(wpt->latitude, wpt->longitude, &east, &north, map)) - fatal(MYNAME ": Position (%.5f/%.5f) outside of BNG.\n", + gbFatal("Position (%.5f/%.5f) outside of BNG.\n", wpt->latitude, wpt->longitude); buff = QString::asprintf(fmp.printfc.constData(), map, qRound(east), qRound(north)); } @@ -1590,7 +1588,7 @@ XcsvFormat::xcsv_waypt_pr(const Waypoint* wpt) } break; default: - warning(MYNAME ": Unknown style directive: %s\n", fmp.key.constData()); + gbWarning("Unknown style directive: %s\n", fmp.key.constData()); break; } QString obuff = csv_stringclean(buff, xcsv_style->badchars); @@ -1789,12 +1787,12 @@ XcsvStyle::xcsv_parse_style_line(XcsvStyle* style, QString line) } else if (p == u"WAYPOINT") { style->datatype = wptdata; } else { - fatal(FatalMsg() << MYNAME << ": Unknown data type" << p); + gbFatal(FatalMsg() << "Unknown data type" << p); } } else if (op == u"IFIELD") { if (tokens.size() < 3) { - fatal(FatalMsg() << "Invalid IFIELD line: " << tokenstr); + gbFatal(FatalMsg() << "Invalid IFIELD line: " << tokenstr); } // The key ("LAT_DIR") should never contain quotes. @@ -1813,7 +1811,7 @@ XcsvStyle::xcsv_parse_style_line(XcsvStyle* style, QString line) unsigned options = 0; // Note: simplified() has to run after split(). if (tokens.size() < 3) { - fatal(FatalMsg() << "Invalid OFIELD line: " << tokenstr); + gbFatal(FatalMsg() << "Invalid OFIELD line: " << tokenstr); } // The key ("LAT_DIR") should never contain quotes. @@ -1847,7 +1845,7 @@ XcsvStyle::xcsv_read_style(const QString& fname) XcsvStyle style; gpsbabel::TextStream stream; - stream.open(fname, QIODevice::ReadOnly, MYNAME); + stream.open(fname, QIODevice::ReadOnly); QString sbuff; while (stream.readLineInto(&sbuff)) { xcsv_parse_style_line(&style, sbuff.trimmed()); @@ -1879,7 +1877,7 @@ XcsvFormat::rd_init(const QString& fname) xcsv_style = new XcsvStyle(XcsvStyle::xcsv_read_style(intstylefile)); } else { if (!styleopt) { - fatal(MYNAME ": XCSV input style not declared. Use ... -i xcsv,style=path/to/file.style\n"); + gbFatal("XCSV input style not declared. Use ... -i xcsv,style=path/to/file.style\n"); } xcsv_style = new XcsvStyle(XcsvStyle::xcsv_read_style(styleopt)); @@ -1887,15 +1885,15 @@ XcsvFormat::rd_init(const QString& fname) if ((xcsv_style->datatype == 0) || (xcsv_style->datatype == wptdata)) { if (global_opts.masked_objective & (TRKDATAMASK|RTEDATAMASK)) { - warning(MYNAME " attempt to read %s as a track or route, but this format only supports waypoints on read. Reading as waypoints instead.\n", qPrintable(fname)); + gbWarning("attempt to read %s as a track or route, but this format only supports waypoints on read. Reading as waypoints instead.\n", gbLogCStr(fname)); } } xcsv_file = new XcsvFile; if (xcsv_style->codecname.isEmpty()) { - xcsv_file->stream.open(fname, QIODevice::ReadOnly, MYNAME); + xcsv_file->stream.open(fname, QIODevice::ReadOnly); } else { - xcsv_file->stream.open(fname, QIODevice::ReadOnly, MYNAME, CSTR(xcsv_style->codecname)); + xcsv_file->stream.open(fname, QIODevice::ReadOnly, CSTR(xcsv_style->codecname)); } xcsv_file->fname = fname; @@ -1909,7 +1907,7 @@ XcsvFormat::rd_init(const QString& fname) } xcsv_file->gps_datum_idx = GPS_Lookup_Datum_Index(datum_name); if (xcsv_file->gps_datum_idx < 0) { - fatal(MYNAME ": datum \"%s\" is not supported.", qPrintable(datum_name)); + gbFatal("datum \"%s\" is not supported.\n", gbLogCStr(datum_name)); } utc_offset = opt_utc? opt_utc.get_result() * SECONDS_PER_HOUR : 0; @@ -1937,7 +1935,7 @@ XcsvFormat::wr_init(const QString& fname) xcsv_style = new XcsvStyle(XcsvStyle::xcsv_read_style(intstylefile)); } else { if (!styleopt) { - fatal(MYNAME ": XCSV output style not declared. Use ... -o xcsv,style=path/to/file.style\n"); + gbFatal("XCSV output style not declared. Use ... -o xcsv,style=path/to/file.style\n"); } xcsv_style = new XcsvStyle(XcsvStyle::xcsv_read_style(styleopt)); @@ -1945,9 +1943,9 @@ XcsvFormat::wr_init(const QString& fname) xcsv_file = new XcsvFile; if (xcsv_style->codecname.isEmpty()) { - xcsv_file->stream.open(fname, QIODevice::WriteOnly | QIODevice::Text, MYNAME); + xcsv_file->stream.open(fname, QIODevice::WriteOnly | QIODevice::Text); } else { - xcsv_file->stream.open(fname, QIODevice::WriteOnly | QIODevice::Text, MYNAME, CSTR(xcsv_style->codecname)); + xcsv_file->stream.open(fname, QIODevice::WriteOnly | QIODevice::Text, CSTR(xcsv_style->codecname)); } xcsv_file->fname = fname; @@ -1991,7 +1989,7 @@ XcsvFormat::wr_init(const QString& fname) } xcsv_file->gps_datum_idx = GPS_Lookup_Datum_Index(datum_name); if (xcsv_file->gps_datum_idx < 0) { - fatal(MYNAME ": datum \"%s\" is not supported.", qPrintable(datum_name)); + gbFatal("datum \"%s\" is not supported.\n", gbLogCStr(datum_name)); } } diff --git a/xmlgeneric.cc b/xmlgeneric.cc index 8d4d3e755..70177fd65 100644 --- a/xmlgeneric.cc +++ b/xmlgeneric.cc @@ -35,12 +35,10 @@ //#include // for QHash, QIODeviceBase::ReadOnly #include // for qPrintable -#include "defs.h" // for fatal +#include "defs.h" // for gbFatal #include "src/core/file.h" // for File -#define MYNAME "XML Reader" - /*********************************************************************** * These implement a simple interface for "generic" XML that * maps reasonably close to 1:1 between XML tags and internal data @@ -74,7 +72,7 @@ XmlGenericReader::xml_common_init(const QString& fname, const char* encoding, if (encoding != nullptr) { codec = QTextCodec::codecForName(encoding); if (codec == nullptr) { - fatal(MYNAME " : codec \"%s\" is not available.\n", encoding); + gbFatal("codec \"%s\" is not available.\n", encoding); } } else { codec = QTextCodec::codecForName("UTF-8"); @@ -190,9 +188,9 @@ void XmlGenericReader::xml_read() xml_run_parser(reader); if (reader.hasError()) { - fatal(MYNAME " :Read error: %s (%s, line %lld, col %lld)\n", - qPrintable(reader.errorString()), - qPrintable(file.fileName()), + gbFatal("Read error: %s (%s, line %lld, col %lld)\n", + gbLogCStr(reader.errorString()), + gbLogCStr(file.fileName()), reader.lineNumber(), reader.columnNumber()); } @@ -215,8 +213,8 @@ void XmlGenericReader::xml_readstring(const char* str) xml_run_parser(reader); if (reader.hasError()) { - fatal(MYNAME " :Read error: %s (%s, line %lld, col %lld)\n", - qPrintable(reader.errorString()), + gbFatal("Read error: %s (%s, line %lld, col %lld)\n", + gbLogCStr(reader.errorString()), "unknown", reader.lineNumber(), reader.columnNumber());