"Fossies" - the Fresh Open Source Software Archive

Member "MP3Diags-unstable-1.5.01/src/Helpers.h" (16 Feb 2019, 15522 Bytes) of package /linux/privat/MP3Diags-unstable-1.5.01.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "Helpers.h" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 1.3.04_vs_1.5.01.

    1 /***************************************************************************
    2  *   MP3 Diags - diagnosis, repairs and tag editing for MP3 files          *
    3  *                                                                         *
    4  *   Copyright (C) 2009 by Marian Ciobanu                                  *
    5  *   ciobi@inbox.com                                                       *
    6  *                                                                         *
    7  *   This program is free software; you can redistribute it and/or modify  *
    8  *   it under the terms of the GNU General Public License version 2 as     *
    9  *   published by the Free Software Foundation.                            *
   10  *                                                                         *
   11  *   This program is distributed in the hope that it will be useful,       *
   12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
   13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
   14  *   GNU General Public License for more details.                          *
   15  *                                                                         *
   16  *   You should have received a copy of the GNU General Public License     *
   17  *   along with this program; if not, write to the                         *
   18  *   Free Software Foundation, Inc.,                                       *
   19  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
   20  ***************************************************************************/
   21 
   22 
   23 #ifndef HelpersH
   24 #define HelpersH
   25 
   26 
   27 #include  <ios>
   28 #include  <iostream>
   29 #include  <string>
   30 #include  <stdexcept>
   31 #include  <cstdlib> // for exit()
   32 #include  <set>
   33 #include  <vector>
   34 
   35 //#include  <QString>
   36 #include  <QStringList>  // ttt2 what we really want is QString; however, by including QString directly, lots of warnings get displayed; perhaps some defines are needed but don't know which; so we just include QStringList to avoid the warnings
   37 
   38 class QTableView;
   39 
   40 #include  "CbException.h"
   41 
   42 ////#include  <CbLibCall.h>
   43 
   44 
   45 
   46 
   47 #define CB_LIB_CALL
   48 
   49 void assertBreakpoint();
   50 
   51 
   52 /*
   53 
   54 Protocol for reading from files:
   55     - the file is always left in good state, no eof or fail
   56     - initializing objects with from a file:
   57         - the starting position is not passed, but it is the current position
   58         - if an error occurs and the constructor fails, the read pointer is restored (and the error flags are cleared); StreamStateRestorer can be used to do this
   59         - on success, the read pointer is left after the last byte that was used; (that may be EOF, but the eof flag should still be clear, because no attempt is made to actually read it after moving the pointer)
   60 
   61     - relying on a stream's flags should be avoided; (the flags are cleared most of the time anyway); the test should normally be to check if a desired number of bytes could be read;
   62 
   63 */
   64 
   65 // !!! readsome seems to do the job but it only returns whatever is in buffer, without waiting for new data to be brought in. Therefore it is not usable in this case.
   66 // !!! doesn't leave the file with fail or eof set; the caller should check the returned value;
   67 inline std::streamsize read(std::istream& in, char* bfr, std::streamsize nCount)
   68 {
   69     in.read(bfr, nCount);
   70     std::streamsize nRes (in.gcount());
   71     in.clear();
   72 
   73     return nRes;
   74 }
   75 
   76 
   77 
   78 /*
   79 Usage: declare a StreamStateRestorer. Before it goes out of scope, call setOk() if everything went OK. On the destructor it checks if setOk() was called. If it wasn't, the read position is set to whatever was on the constructor. All flags of the stream are cleared in either case.
   80 */
   81 class StreamStateRestorer
   82 {
   83     std::istream& m_in;
   84     std::streampos m_pos;
   85     bool m_bOk;
   86 public:
   87     StreamStateRestorer(std::istream& in);
   88     ~StreamStateRestorer();
   89     void setOk() { m_bOk = true; }
   90 };
   91 
   92 
   93 
   94 // on its destructor restores the value of the variable passed on the constructor unless setOk() gets called
   95 template <typename T>
   96 class ValueRestorer
   97 {
   98     T m_val;
   99     T& m_ref;
  100     bool m_bRestore;
  101 public:
  102     ValueRestorer(T& ref) : m_val(ref), m_ref(ref), m_bRestore(true) {}
  103     ~ValueRestorer()
  104     {
  105         if (m_bRestore)
  106         {
  107             m_ref = m_val;
  108         }
  109     }
  110 
  111     void setOk(bool b = true) { m_bRestore = !b; }
  112 };
  113 
  114 
  115 template<typename T>
  116 void CB_LIB_CALL releasePtr(T*& p)
  117 {
  118     delete p;
  119     p = 0;
  120 }
  121 
  122 
  123 
  124 
  125 #define TRACE(A) { std::ostringstream sTrM; sTrM << A; ::trace(sTrM.str()); }
  126 void trace(const std::string& s);
  127 
  128 void logAssert(const char* szFile, int nLine, const char* szCond);
  129 void logAssert(const char* szFile, int nLine, const char* szCond, const std::string& strAddtlInfo);
  130 
  131 
  132 namespace pearl {
  133 
  134 template<class T> void CB_LIB_CALL clearPtrContainer(T& c) // calls delete on all the elements of a container of pointers, then sets its size to 0; shouldn't be used on sets
  135 {
  136     for (typename T::iterator it = c.begin(), end = c.end(); it != end; ++it)
  137     {
  138         delete *it;
  139     }
  140     c.clear();
  141 }
  142 
  143 template<typename T> void CB_LIB_CALL clearPtrContainer(std::set<T*>& c) // specialization for sets
  144 {
  145     while (!c.empty())
  146     {
  147         T* p;
  148         p = *c.begin(); //ddd see if it's better to remove from end / middle instead of front
  149 
  150         c.erase(c.begin());
  151         delete p;
  152     }
  153 }
  154 
  155 
  156 // to make sure that an array is deallocated even when exceptions are thrown; similar to auto_ptr
  157 template<typename T>
  158 class ArrayPtrRelease
  159 {
  160     T* m_pArray;
  161 
  162     ArrayPtrRelease();
  163     ArrayPtrRelease(const ArrayPtrRelease&);
  164     ArrayPtrRelease& operator=(const ArrayPtrRelease&);
  165 
  166 public:
  167     ArrayPtrRelease(T* pArray) : m_pArray(pArray) {}
  168     ~ArrayPtrRelease() { delete[] m_pArray; }
  169 
  170     T* get() { return m_pArray; }
  171     const T* get() const { return m_pArray; }
  172 };
  173 
  174 } // namespace pearl
  175 
  176 
  177 template<class T> int CB_LIB_CALL cSize(const T& c) // returns the size of a container as an int
  178 {
  179     return (int)c.size();
  180 }
  181 
  182 
  183 
  184 DEFINE_CB_EXCP(EndOfFile);
  185 DEFINE_CB_EXCP(WriteError);
  186 
  187 // throws WriteError or EndOfFile
  188 void appendFilePart(std::istream& in, std::ostream& out, std::streampos pos, std::streamoff nSize);
  189 
  190 
  191 // prints to cout the content of a memory location, as ASCII and hex;
  192 // GDB has a tendency to not see char arrays and other local variables; actually GCC seems to be the culprit (bug 34767);
  193 void inspect(const void* p, int nSize);
  194 
  195 template <typename T>
  196 void inspect(const T& x)
  197 {
  198     if (sizeof(x) == 1001) { return; }
  199 }
  200 
  201 
  202 // prints the elements of a container
  203 template <typename T>
  204 void printContainer(const T& s, std::ostream& out, const std::string& strSep = " ")
  205 {
  206     for (typename T::const_iterator it = s.begin(); it != s.end(); ++it)
  207     {
  208         out << *it << strSep;
  209     }
  210     out << std::endl;
  211 }
  212 
  213 
  214 std::string asHex(const char* p, int nSize);
  215 
  216 
  217 inline bool CB_LIB_CALL beginsWith(const std::string& strMain, const std::string& strSubstr)
  218 {
  219     if (strSubstr.size() > strMain.size()) return false;
  220     return strMain.substr(0, strSubstr.size()) == strSubstr;
  221 }
  222 
  223 
  224 inline bool CB_LIB_CALL endsWith(const std::string& strMain, const std::string& strSubstr)
  225 {
  226     if (strSubstr.size() > strMain.size()) return false; // !!! otherwise the next line might incorrectly return true if
  227                                                          // strMain.size() = strSubstr.size() - 1
  228 
  229     return strMain.rfind(strSubstr) == strMain.size() - strSubstr.size();
  230 }
  231 
  232 
  233 bool CB_LIB_CALL rtrim(std::string& s); // removes whitespaces at the end of the string
  234 bool CB_LIB_CALL ltrim(std::string& s); // removes whitespaces at the beginning of the string
  235 bool CB_LIB_CALL trim(std::string& s);
  236 
  237 
  238 int get32BitBigEndian(const char*);
  239 void put32BitBigEndian(int n, char*);
  240 
  241 
  242 // The reference that is passed in the constructor (the "guard") should be accessible to all parties interested; it should be initialized to "false" first. When a piece of code wants access to resources protected by the guard, it should declare an NonblockingGuard variable, initialize it with the guard and then check if it went OK, by calling "operator()"; if "operator()" returns true, it means the guard was acquired, so it can proceed.
  243 // The major point is that it's a non-blocking call.
  244 // The intended use is with single-threaded applications (or rather to not share a guard among threads). This is useful to handle the situation where function f() may call g() and g() may call f(), but with the restriction that f() may call g() only if f() wasn't already called by g(). As this isn't designed for multi-threading, it doesn't need any system-specific code or porting.
  245 class NonblockingGuard
  246 {
  247     bool& m_bLock;
  248     bool m_bInitialState;
  249 
  250 public:
  251     CB_LIB_CALL NonblockingGuard(bool& bLock) : m_bLock(bLock), m_bInitialState(m_bLock)
  252     {
  253         m_bLock = true; // doesn't matter if it was true
  254     }
  255 
  256     CB_LIB_CALL ~NonblockingGuard()
  257     {
  258         m_bLock = m_bInitialState;
  259     }
  260 
  261     operator bool () const { return !m_bInitialState; }
  262 };
  263 
  264 
  265 // takes a Latin1 string and converts it to UTF8
  266 std::string utf8FromLatin1(const std::string&);
  267 
  268 // the total memory currently used by the current process, in kB
  269 long getMemUsage();
  270 
  271 std::string decodeMpegFrame(unsigned int n, const char* szSep, bool* pbIsValid = 0); // on error doesn't throw, but returns an error string; szSep is used as separator for the output string
  272 std::string decodeMpegFrame(const char* bfr, const char* szSep, bool* pbIsValid = 0);
  273 std::string decodeMpegFrameAsXml(const char* bfr, bool* pbIsValid = 0);
  274 
  275 
  276 inline const char* boolAsYesNo(bool b) { return b ? QT_TRANSLATE_NOOP("GlobalTranslHlp", "yes") : QT_TRANSLATE_NOOP("GlobalTranslHlp", "no"); }
  277 
  278 char getPathSep();
  279 const std::string& getPathSepAsStr();
  280 
  281 std::streampos getSize(std::istream& in);
  282 
  283 // throws WriteError or EndOfFile
  284 void writeZeros(std::ostream& out, int nCnt);
  285 
  286 
  287 // needed because gdb has trouble setting breakpoints in template code
  288 inline void templateBreakpoint()
  289 {
  290     qDebug("breakpoint");
  291 }
  292 
  293 // by including this as a member the compiler generated constructor / copy op. are disabled
  294 class NoDefaults
  295 {
  296     CB_LIB_CALL NoDefaults();
  297     CB_LIB_CALL NoDefaults(const NoDefaults&);
  298     NoDefaults& CB_LIB_CALL operator=(NoDefaults&); //ttt2 see if there are other generated operations and include them all
  299 public:
  300     CB_LIB_CALL NoDefaults(int) {}
  301 };
  302 
  303 
  304 class QWidget;
  305 void listWidget(QWidget* p, int nIndent = 0); //ttt2 move this elsewhere
  306 
  307 std::string escapeHttp(const std::string& s); // replaces invalid HTTP characters like ' ' or '"' with their hex code (%20 or %22)
  308 
  309 inline QString convStr(const std::string& s) { return QString::fromUtf8(s.c_str(), cSize(s)); } //ttt2 perhaps move
  310 inline std::string convStr(const QString& qs) { const QByteArray& b (qs.toUtf8()); return std::string(b.constData(), b.size()); } //ttt2 perhaps move
  311 
  312 std::vector<std::string> convStr(const std::vector<QString>&);
  313 std::vector<QString> convStr(const std::vector<std::string>&);
  314 
  315 
  316 Qt::WindowFlags getMainWndFlags();   // minimize, maximize, no "what's this"
  317 Qt::WindowFlags getDialogWndFlags(); // maximize, no "what's this"
  318 Qt::WindowFlags getNoResizeWndFlags(); // no "what's this"; the window may be resizable, but the min/max icons aren't shown
  319 
  320 bool getDefaultForShowCustomCloseButtons();
  321 
  322 QString getSystemInfo();
  323 
  324 
  325 class QGradient;
  326 class QColor;
  327 
  328 // sets colors at various points to emulate a non-linear gradient that better suits our needs;
  329 // dStart and dEnd should be between 0 and 1, with dStart < dEnd; they may also be both -1, in which case the gradient will have a solid color
  330 void configureGradient(QGradient& grad, const QColor& col, double dStart, double dEnd);
  331 
  332 // opens a web page from the documentation in the default browser;
  333 // first looks in several places on the local computer; if the file can't be found there, it goes to SourceForge
  334 void openHelp(const std::string& strFileName);
  335 
  336 
  337 // meant for displaying tooltips; converts some spaces to \n, so the tooltips have several short lines instead of a single wide line
  338 QString makeMultiline(const QString& qstrDescr);
  339 
  340 QString toNativeSeparators(const QString&);
  341 QString fromNativeSeparators(const QString&);
  342 inline std::string toNativeSeparators(const std::string& s) { return convStr(toNativeSeparators(convStr(s))); }
  343 inline std::string fromNativeSeparators(const std::string& s) { return convStr(fromNativeSeparators(convStr(s))); }
  344 
  345 QString getTempDir();
  346 
  347 
  348 struct ShellIntegration
  349 {
  350     static bool isShellIntegrationEditable();
  351     static std::string getShellIntegrationError();
  352 
  353     static void enableTempSession(bool);
  354     static bool isTempSessionEnabled();
  355     static void enableVisibleSession(bool);
  356     static bool isVisibleSessionEnabled();
  357     static void enableHiddenSession(bool);
  358     static bool isHiddenSessionEnabled();
  359 };
  360 
  361 //======================================================================================================
  362 //======================================================================================================
  363 //======================================================================================================
  364 
  365 
  366 void traceToFile(const std::string& s, int nLevelChange);
  367 
  368 struct Tracer
  369 {
  370     const std::string m_s;
  371 
  372     Tracer(const std::string& s);
  373     ~Tracer();
  374 };
  375 
  376 #define TRACER(X) Tracer FiLeTrAcEr (X)
  377 #define TRACER1(X, N) Tracer FiLeTrAcEr##N (X)
  378 #define TRACER1A(X, N) Tracer FiLeTrAcEr##N (X#N)
  379 
  380 
  381 void traceLastStep(const std::string& s, int nLevelChange);
  382 
  383 struct LastStepTracer
  384 {
  385     const std::string m_s;
  386 
  387     LastStepTracer(const std::string& s);
  388     ~LastStepTracer();
  389 };
  390 
  391 
  392 #define LAST_STEP(X) LastStepTracer LaStStEp (X);
  393 #define LAST_STEP1(X, N) LastStepTracer LaStStEp##N (X);
  394 
  395 
  396 
  397 //======================================================================================================
  398 //======================================================================================================
  399 //======================================================================================================
  400 
  401 
  402 class Timer
  403 {
  404     int64_t m_nStart;
  405     int64_t m_nFinish;
  406     int64_t* m_pStoredDuration;
  407 
  408 #ifdef _WIN32
  409     int64_t m_nDurMul; // multiply by this to get a duration in nanoseconds from a duration in ticks
  410 #endif
  411 
  412 public:
  413     CB_LIB_CALL Timer(bool bStart = true);
  414 
  415     CB_LIB_CALL Timer(int64_t& storedDuration, bool bStart = true);
  416 
  417     ~Timer();
  418 
  419     void CB_LIB_CALL start() { m_nStart = getCrtTime(); }
  420     int64_t CB_LIB_CALL stop() { m_nFinish = getCrtTime(); return getDuration(); }
  421 
  422     int64_t CB_LIB_CALL getDuration() const { return m_nFinish - m_nStart; } // duration in nanoseconds; may return invalid values if no counter is present or if start/stop haven't been called
  423 
  424     int64_t CB_LIB_CALL fromStart() const { return getCrtTime() - m_nStart; }
  425 
  426     int64_t CB_LIB_CALL getCrtTime() const; // returns time in nanoseconds
  427 
  428     static std::string CB_LIB_CALL addThSep(int64_t nTime); // to be used when converting to milli- / micro- seconds
  429 
  430     std::string CB_LIB_CALL getFmtDuration() const { return addThSep(getDuration()); } // "formatted" duration, in nanoseconds using thousands separator
  431 
  432     std::string CB_LIB_CALL getFmtDuration(int64_t nCnt) const { return addThSep(getDuration()/nCnt); } // "formatted" individual duration for a repeated task, in nanoseconds using thousands separator
  433 
  434     static std::string getLongFmt(int64_t dur);
  435 };
  436 
  437 
  438 // On Windows with QT5 there is a big padding and the headers are truncated. This resizes the font, so things fit
  439 void decreaseRowHeaderFont(QTableView&);
  440 
  441 #endif // ifndef HelpersH
  442