ctkUtils.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0.txt
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QDebug>
  16. #include <QDir>
  17. #include <QRegExp>
  18. #include <QString>
  19. #include <QStringList>
  20. #include "ctkUtils.h"
  21. // STD includes
  22. #include <algorithm>
  23. #include <limits>
  24. #ifdef _MSC_VER
  25. #pragma warning(disable: 4996)
  26. #endif
  27. //------------------------------------------------------------------------------
  28. void ctk::qListToSTLVector(const QStringList& list,
  29. std::vector<char*>& vector)
  30. {
  31. // Resize if required
  32. if (list.count() != static_cast<int>(vector.size()))
  33. {
  34. vector.resize(list.count());
  35. }
  36. for (int i = 0; i < list.count(); ++i)
  37. {
  38. // Allocate memory
  39. char* str = new char[list[i].size()+1];
  40. strcpy(str, list[i].toLatin1());
  41. vector[i] = str;
  42. }
  43. }
  44. //------------------------------------------------------------------------------
  45. namespace
  46. {
  47. /// Convert QString to std::string
  48. static std::string qStringToSTLString(const QString& qstring)
  49. {
  50. return qstring.toStdString();
  51. }
  52. }
  53. //------------------------------------------------------------------------------
  54. void ctk::qListToSTLVector(const QStringList& list,
  55. std::vector<std::string>& vector)
  56. {
  57. // To avoid unnessesary relocations, let's reserve the required amount of space
  58. vector.reserve(list.size());
  59. std::transform(list.begin(),list.end(),std::back_inserter(vector),&qStringToSTLString);
  60. }
  61. //------------------------------------------------------------------------------
  62. void ctk::stlVectorToQList(const std::vector<std::string>& vector,
  63. QStringList& list)
  64. {
  65. std::transform(vector.begin(),vector.end(),std::back_inserter(list),&QString::fromStdString);
  66. }
  67. //-----------------------------------------------------------------------------
  68. const char *ctkNameFilterRegExp =
  69. "^(.*)\\(([a-zA-Z0-9_.*? +;#\\-\\[\\]@\\{\\}/!<>\\$%&=^~:\\|]*)\\)$";
  70. const char *ctkValidWildCard =
  71. "^[\\w\\s\\.\\*\\_\\~\\$\\[\\]]+$";
  72. //-----------------------------------------------------------------------------
  73. QStringList ctk::nameFilterToExtensions(const QString& nameFilter)
  74. {
  75. QRegExp regexp(QString::fromLatin1(ctkNameFilterRegExp));
  76. int i = regexp.indexIn(nameFilter);
  77. if (i < 0)
  78. {
  79. QRegExp isWildCard(QString::fromLatin1(ctkValidWildCard));
  80. if (isWildCard.indexIn(nameFilter) >= 0)
  81. {
  82. return QStringList(nameFilter);
  83. }
  84. return QStringList();
  85. }
  86. QString f = regexp.cap(2);
  87. return f.split(QLatin1Char(' '), QString::SkipEmptyParts);
  88. }
  89. //-----------------------------------------------------------------------------
  90. QStringList ctk::nameFiltersToExtensions(const QStringList& nameFilters)
  91. {
  92. QStringList extensions;
  93. foreach(const QString& nameFilter, nameFilters)
  94. {
  95. extensions << nameFilterToExtensions(nameFilter);
  96. }
  97. return extensions;
  98. }
  99. //-----------------------------------------------------------------------------
  100. QString ctk::extensionToRegExp(const QString& extension)
  101. {
  102. // typically *.jpg
  103. QRegExp extensionExtractor("\\*\\.(\\w+)");
  104. int pos = extensionExtractor.indexIn(extension);
  105. if (pos < 0)
  106. {
  107. return QString();
  108. }
  109. return ".*\\." + extensionExtractor.cap(1) + "?$";
  110. }
  111. //-----------------------------------------------------------------------------
  112. QRegExp ctk::nameFiltersToRegExp(const QStringList& nameFilters)
  113. {
  114. QString pattern;
  115. foreach(const QString& nameFilter, nameFilters)
  116. {
  117. foreach(const QString& extension, nameFilterToExtensions(nameFilter))
  118. {
  119. QString regExpExtension = extensionToRegExp(extension);
  120. if (!regExpExtension.isEmpty())
  121. {
  122. if (pattern.isEmpty())
  123. {
  124. pattern = "(";
  125. }
  126. else
  127. {
  128. pattern += "|";
  129. }
  130. pattern +=regExpExtension;
  131. }
  132. }
  133. }
  134. if (pattern.isEmpty())
  135. {
  136. pattern = ".+";
  137. }
  138. else
  139. {
  140. pattern += ")";
  141. }
  142. return QRegExp(pattern);
  143. }
  144. //-----------------------------------------------------------------------------
  145. int ctk::significantDecimals(double value, int defaultDecimals)
  146. {
  147. if (value == 0.
  148. || qAbs(value) == std::numeric_limits<double>::infinity())
  149. {
  150. return 0;
  151. }
  152. if (value != value) // is NaN
  153. {
  154. return -1;
  155. }
  156. QString number = QString::number(value, 'f', 16);
  157. QString fractional = number.section('.', 1, 1);
  158. Q_ASSERT(fractional.length() == 16);
  159. QChar previous;
  160. int previousRepeat=0;
  161. bool only0s = true;
  162. bool isUnit = value > -1. && value < 1.;
  163. for (int i = 0; i < fractional.length(); ++i)
  164. {
  165. QChar digit = fractional.at(i);
  166. if (digit != '0')
  167. {
  168. only0s = false;
  169. }
  170. // Has the digit been repeated too many times ?
  171. if (digit == previous && previousRepeat == 2 &&
  172. !only0s)
  173. {
  174. if (digit == '0' || digit == '9')
  175. {
  176. return i - previousRepeat;
  177. }
  178. return i;
  179. }
  180. // Last digit
  181. if (i == fractional.length() - 1)
  182. {
  183. // If we are here, that means that the right number of significant
  184. // decimals for the number has not been figured out yet.
  185. if (previousRepeat > 2 && !(only0s && isUnit) )
  186. {
  187. return i - previousRepeat;
  188. }
  189. // If defaultDecimals has been provided, just use it.
  190. if (defaultDecimals >= 0)
  191. {
  192. return defaultDecimals;
  193. }
  194. return fractional.length();
  195. }
  196. // get ready for next
  197. if (previous != digit)
  198. {
  199. previous = digit;
  200. previousRepeat = 1;
  201. }
  202. else
  203. {
  204. ++previousRepeat;
  205. }
  206. }
  207. Q_ASSERT(false);
  208. return fractional.length();
  209. }
  210. //-----------------------------------------------------------------------------
  211. int ctk::orderOfMagnitude(double value)
  212. {
  213. value = qAbs(value);
  214. if (value == 0.
  215. || value == std::numeric_limits<double>::infinity()
  216. || value != value // is NaN
  217. || value < std::numeric_limits<double>::epsilon() // is tool small to compute
  218. )
  219. {
  220. return std::numeric_limits<int>::min();
  221. }
  222. double magnitude = 1.00000000000000001;
  223. int magnitudeOrder = 0;
  224. int magnitudeStep = 1;
  225. double magnitudeFactor = 10;
  226. if (value < 1.)
  227. {
  228. magnitudeOrder = -1;
  229. magnitudeStep = -1;
  230. magnitudeFactor = 0.1;
  231. }
  232. double epsilon = std::numeric_limits<double>::epsilon();
  233. while ( (magnitudeStep > 0 && value >= magnitude) ||
  234. (magnitudeStep < 0 && value < magnitude - epsilon))
  235. {
  236. magnitude *= magnitudeFactor;
  237. magnitudeOrder += magnitudeStep;
  238. }
  239. // we went 1 order too far, so decrement it
  240. return magnitudeOrder - magnitudeStep;
  241. }
  242. //-----------------------------------------------------------------------------
  243. double ctk::closestPowerOfTen(double _value)
  244. {
  245. const double sign = _value >= 0. ? 1 : -1;
  246. const double value = qAbs(_value);
  247. if (value == 0.
  248. || value == std::numeric_limits<double>::infinity()
  249. || value != value // is NaN
  250. || value < std::numeric_limits<double>::epsilon() // is denormalized
  251. )
  252. {
  253. return _value;
  254. }
  255. double magnitude = 1.;
  256. double nextMagnitude = magnitude;
  257. if (value >= 1.)
  258. {
  259. do
  260. {
  261. magnitude = nextMagnitude;
  262. nextMagnitude *= 10.;
  263. }
  264. while ( (value - magnitude) > (nextMagnitude - value) );
  265. }
  266. else
  267. {
  268. do
  269. {
  270. magnitude = nextMagnitude;
  271. nextMagnitude /= 10.;
  272. }
  273. while ( (value - magnitude) < (nextMagnitude - value) );
  274. }
  275. return magnitude * sign;
  276. }
  277. //-----------------------------------------------------------------------------
  278. bool ctk::removeDirRecursively(const QString & dirName)
  279. {
  280. bool result = false;
  281. QDir dir(dirName);
  282. if (dir.exists())
  283. {
  284. foreach (QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst))
  285. {
  286. if (info.isDir())
  287. {
  288. result = ctk::removeDirRecursively(info.absoluteFilePath());
  289. }
  290. else
  291. {
  292. result = QFile::remove(info.absoluteFilePath());
  293. }
  294. if (!result)
  295. {
  296. return result;
  297. }
  298. }
  299. QDir parentDir(QFileInfo(dirName).absolutePath());
  300. result = parentDir.rmdir(dirName);
  301. }
  302. return result;
  303. }
  304. //-----------------------------------------------------------------------------
  305. bool ctk::copyDirRecursively(const QString &srcPath, const QString &dstPath)
  306. {
  307. // See http://stackoverflow.com/questions/2536524/copy-directory-using-qt
  308. if (!QFile::exists(srcPath))
  309. {
  310. qCritical() << "ctk::copyDirRecursively: Failed to copy nonexistent directory" << srcPath;
  311. return false;
  312. }
  313. QDir srcDir(srcPath);
  314. if (!srcDir.relativeFilePath(dstPath).startsWith(".."))
  315. {
  316. qCritical() << "ctk::copyDirRecursively: Cannot copy directory" << srcPath << "into itself" << dstPath;
  317. return false;
  318. }
  319. QDir parentDstDir(QFileInfo(dstPath).path());
  320. if (!QFile::exists(dstPath) && !parentDstDir.mkdir(QFileInfo(dstPath).fileName()))
  321. {
  322. qCritical() << "ctk::copyDirRecursively: Failed to create destination directory" << QFileInfo(dstPath).fileName();
  323. return false;
  324. }
  325. foreach(const QFileInfo &info, srcDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot))
  326. {
  327. QString srcItemPath = srcPath + "/" + info.fileName();
  328. QString dstItemPath = dstPath + "/" + info.fileName();
  329. if (info.isDir())
  330. {
  331. if (!ctk::copyDirRecursively(srcItemPath, dstItemPath))
  332. {
  333. qCritical() << "ctk::copyDirRecursively: Failed to copy files from " << srcItemPath << " into " << dstItemPath;
  334. return false;
  335. }
  336. }
  337. else if (info.isFile())
  338. {
  339. if (!QFile::copy(srcItemPath, dstItemPath))
  340. {
  341. return false;
  342. }
  343. }
  344. else
  345. {
  346. qWarning() << "ctk::copyDirRecursively: Unhandled item" << info.filePath();
  347. }
  348. }
  349. return true;
  350. }
  351. //-----------------------------------------------------------------------------
  352. QString ctk::qtHandleToString(Qt::HANDLE handle)
  353. {
  354. QString str;
  355. QTextStream s(&str);
  356. s << handle;
  357. return str;
  358. }
  359. //-----------------------------------------------------------------------------
  360. qint64 ctk::msecsTo(const QDateTime& t1, const QDateTime& t2)
  361. {
  362. QDateTime utcT1 = t1.toUTC();
  363. QDateTime utcT2 = t2.toUTC();
  364. return static_cast<qint64>(utcT1.daysTo(utcT2)) * static_cast<qint64>(1000*3600*24)
  365. + static_cast<qint64>(utcT1.time().msecsTo(utcT2.time()));
  366. }