⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 util.cc

📁 c++的guiQt做的开发
💻 CC
字号:
/** @file Various utility functions (string processing, file loading, debugging, etc ...) @author Martin Petricek \brief Utility functions*/#include "util.h"#include <iostream>#include <QDateTime>#include <QFile>#include <QMap>#ifdef QT_GUI_LIB#include <QMessageBox>#endif#include <QObject>#include <QRegExp>#include <QString>#include <QStringList>#include <QThread>#include <QTextCodec>#include <QTextStream>namespace util {using namespace std;/** Prints error message and terminates application @param message Error message to show*/void fatalError(const QString &message) {#ifdef QT_GUI_LIB //GUI version - messageboxed error message QMessageBox::critical(0,QObject::tr("Fatal Error")+"!",message);#else //Console version - spit the mesage to STDERR cerr << endl << QObject::tr("Fatal Error").toLocal8Bit().data() << "!" << endl << message.toLocal8Bit().data() << endl;#endif exit(-1);}/** Prints error message to console and terminates application @param message Error message to show*/void fatalErrorConsole(const QString &message) { //Console version - spit the mesage to STDERR cerr << endl << QObject::tr("Fatal Error").toLocal8Bit().data() << "!" << endl << message.toLocal8Bit().data() << endl; exit(-1);}/** Convert < > and & characters to corresponding html entities (&gt; &lt; &amp;) @param str String to convert @return Converted string*/QString htmlEnt(const QString &str) { QString res=str; res.replace('&',"&amp;"); res.replace('>',"&gt;"); res.replace('<',"&lt;"); return res;}/** Replace two backslashes followed by any character (escaped character) with that character @param line String in which to remove extra backslashes (in,out)*/void escapeSlash(QString &line) { static QRegExp slash("\\\\(.)"); line.replace(slash,"\\1");}/** Find first occurence of separator in string and return its position, ignoring backslash-escaped separators If separator is not found, -1 is returned @param start Start searching from this position in string @param separator Separator of string elements @param line String to look for separator @return position of first separator from start position, ignoring backslash-escaped separators*/int findSep(int start,const QString &line,char separator) { int pos=line.indexOf(separator,start); while(true) {  if (pos==-1) {   return -1;  } else { //Found   if (pos>start) { //Want escaped character and this is not first character    if (line.at(pos-1)=='\\') { //Preceding character is a backslash -> need to track back     int count=0;     while(pos>count && line.at(pos-count-1)=='\\') {      count++;     }     if (!(count&1)) {      // Even number of backslashes -> not escaped character, only escaped backslash      return pos;     }     pos=line.indexOf(separator,pos+1);//Look for next character     continue;//Restart loop    }   }   return pos;  } }}/** splits QString containing elements separated with given character All whitespaces from beginning and end of elements are trimmed @param separator Separator of elements @param line String containing elements separated with separator @param escape If true, "\\" will be converted to "\" and \(separator) will be converted to (separator) and not treated as separator @return QStringlist with elements*/QStringList explode(char separator,const QString &line,bool escape/*=false*/) { QStringList qs; if (escape) {  int pos=0;  QString add;  while(true) {   int nPos=findSep(pos,line,separator);   if (nPos<0) {    add=line.mid(pos);//rest of string   } else {    add=line.mid(pos,nPos-pos);//Part of string   }   escapeSlash(add);   qs+=add;   if (nPos<0) break;   pos=nPos+1;//Skip separatr and look for next  } } else {  qs=line.split(separator); } for (int i=0;i<qs.count();i++) {  qs[i]=qs[i].trimmed(); } return qs;}/** Load content of file to string. NULL string is returned if file does not exist or is unreadable. It is assumed that the file is in utf8 encoding @param name Filename of file to load @return file contents in string.*/QString loadFromFile(const QString &name) { QFile f(name); if (!f.open(QIODevice::ReadOnly)) {  //Failure  return QString::null; } QByteArray qb=f.readAll(); f.close(); QTextCodec *codec=QTextCodec::codecForName("utf8"); QString res=codec->toUnicode(qb); return res;}/** Save string into file with utf8 encoding. @param name Filename of file to write to. It will be overwritten. @param content String to write. @return true in case of success, false in case of failure*/bool saveToFile(const QString &name,const QString &content) { QFile f(name); if (!f.open(QIODevice::WriteOnly)) {  //Failure  return false; } QTextCodec *codec=QTextCodec::codecForName("utf8"); QByteArray qb=codec->fromUnicode(content); f.write(qb); f.close(); return true;}/** Write line to specified logfile @param message Line to write to logfile @param fileName Name of log file. If this is null or empty string, nothing is done*/void consoleLog(const QString &message,const QString &fileName) { if (fileName.isNull()) return; if (fileName=="") return; QFile con(fileName); con.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream conOut(&con); conOut << message << "\n"; con.close();}/** Return correctly localized string telling count of some items. Some languages (for example Czech) have more plural forms (2-4 items / 5 or more items), which is handled here @param count Count of items @param singular English signular form of the noun, without space before the word @param plural English plural form of the noun @return Localized string*/QString countString(int count,QString singular,QString plural) { QString str=QString::number(count)+" "; if (count==1) str+=QObject::tr(singular.toUtf8(),"1"); else if (count>=2 && count<=4) str+=QObject::tr(plural.toUtf8(),"2-4"); else str+=QObject::tr(plural.toUtf8(),"5+"); return str;}/** Return string from line up to first separator character and remove that string and the separator from the line. If separator is not found, entire string is returned and the line is set to empty string @param separator Separator of string elements @param line line to get from and remove first element @param escape If true, "\\" will be converted to "\" and \(separator) will be converted to (separator) and not treated as separator @return first string element (contents of string until separator)*/QString getUntil(char separator,QString &line,bool escape/*=false*/) { int pos=line.indexOf(separator); while(true) {  if (pos==-1) { //Not found   QString _line=line;   line="";   if (escape) escapeSlash(_line);   return _line;  } else { //Found   if (escape && pos>0) { //Want escaped character and this is not first character    if (line.at(pos-1)=='\\') { //Preceding character is a backslash     pos=line.indexOf(separator,pos+1);//Look for next character     continue;//Restart loop    }   }   QString first=line.left(pos);   line=line.mid(pos+1);   if (escape) escapeSlash(first);   return first;  } }}/** Issue a warning to user @param text Warning text*/void warn(const QString &text) { cerr << text.toLocal8Bit().data() << endl;}/** Strip and return one string element from line @param line Line from which to chop parameters @return first element from line*/QString stripParam(QString &line) { int i=0,start=0,end=0; //Skip whitespace; while (i<line.length() && line[i].isSpace()) i++; if (i<line.length()) {  QChar c=line[i];  if (c=='"' || c=='\'') {   i++;   start=i;   end=line.indexOf(c,start);   if (end==-1) {    QString ret=line.mid(start);    line=QString::null;    return ret;   }   QString ret=line.mid(start,end-start);   line=line.mid(end+1);   return ret;  } else {   start=i;   while (i<line.length() && !line[i].isSpace()) i++;   end=i;   QString ret=line.mid(start,end-start);   line=line.mid(end);   return ret;  } } return QString::null;}/** Base datetime (for tick counter) */static QDateTime basetime=QDateTime::currentDateTime();/** Return current tick counter (msecs since some arbitrary point in time, usually application start. Reference point will not change while running the application, but can (and probably will) change across different application runs. May overflow in time*/int tick() { QDateTime now=QDateTime::currentDateTime(); int dt=basetime.date().daysTo(now.date()); int tt=basetime.time().msecsTo(now.time()); return dt*(1000*3600*24)+tt;}/** QThread with msleep made public */class SleepyThread : public QThread {public: /**  Sleep for given amount of miliseconds  @param delay amount of ms to sleep */ void msleep(int delay) {  QThread::msleep(delay); }};/** Sleep for given amount of miliseconds @param delay amount of ms to sleep*/void msleep(int delay) { static_cast<SleepyThread*>(QThread::currentThread())->msleep(delay);}} //namespace util

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -