ctkUtils.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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)
  146. {
  147. QString number = QString::number(value, 'f', 16);
  148. QString fractional = number.section('.', 1, 1);
  149. Q_ASSERT(fractional.length() == 16);
  150. QChar previous;
  151. int previousRepeat=0;
  152. bool only0s = true;
  153. for (int i = 0; i < fractional.length(); ++i)
  154. {
  155. QChar digit = fractional.at(i);
  156. if (digit != '0')
  157. {
  158. only0s = false;
  159. }
  160. // Has the digit been repeated too many times ?
  161. if (digit == previous && previousRepeat == 2 &&
  162. !only0s)
  163. {
  164. if (digit == '0' || digit == '9')
  165. {
  166. return i - previousRepeat;
  167. }
  168. return i;
  169. }
  170. // Last digit
  171. if (i == fractional.length() - 1)
  172. {
  173. if (previousRepeat > 2)
  174. {
  175. return i - previousRepeat;
  176. }
  177. return fractional.length();
  178. }
  179. // get ready for next
  180. if (previous != digit)
  181. {
  182. previous = digit;
  183. previousRepeat = 1;
  184. }
  185. else
  186. {
  187. ++previousRepeat;
  188. }
  189. }
  190. Q_ASSERT(false);
  191. return fractional.length();
  192. }
  193. //-----------------------------------------------------------------------------
  194. int ctk::orderOfMagnitude(double value)
  195. {
  196. value = qAbs(value);
  197. if (value == 0.)
  198. {
  199. return std::numeric_limits<int>::min();
  200. }
  201. double magnitude = 1.00000000000000001;
  202. int magnitudeOrder = 0;
  203. int magnitudeStep = 1;
  204. double magnitudeFactor = 10;
  205. if (value < 1.)
  206. {
  207. magnitudeOrder = -1;
  208. magnitudeStep = -1;
  209. magnitudeFactor = 0.1;
  210. }
  211. while ( (magnitudeStep > 0 && value >= magnitude) ||
  212. (magnitudeStep < 0 && value < magnitude - std::numeric_limits<double>::epsilon()))
  213. {
  214. magnitude *= magnitudeFactor;
  215. magnitudeOrder += magnitudeStep;
  216. }
  217. // we went 1 order too far, so decrement it
  218. return magnitudeOrder - magnitudeStep;
  219. }
  220. //-----------------------------------------------------------------------------
  221. double ctk::closestPowerOfTen(double value)
  222. {
  223. double sign = value >= 0. ? 1 : -1;
  224. value = qAbs(value);
  225. if (value == 0.)
  226. {
  227. return 0.;
  228. }
  229. double magnitude = 1.;
  230. double nextMagnitude = magnitude;
  231. if (value >= 1.)
  232. {
  233. do
  234. {
  235. magnitude = nextMagnitude;
  236. nextMagnitude *= 10.;
  237. }
  238. while ( (value - magnitude) > (nextMagnitude - value) );
  239. }
  240. else
  241. {
  242. do
  243. {
  244. magnitude = nextMagnitude;
  245. nextMagnitude /= 10.;
  246. }
  247. while ( (value - magnitude) < (nextMagnitude - value) );
  248. }
  249. return magnitude * sign;
  250. }
  251. //-----------------------------------------------------------------------------
  252. bool ctk::removeDirRecursively(const QString & dirName)
  253. {
  254. bool result = false;
  255. QDir dir(dirName);
  256. if (dir.exists(dirName))
  257. {
  258. foreach (QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst))
  259. {
  260. if (info.isDir())
  261. {
  262. result = ctk::removeDirRecursively(info.absoluteFilePath());
  263. }
  264. else
  265. {
  266. result = QFile::remove(info.absoluteFilePath());
  267. }
  268. if (!result)
  269. {
  270. return result;
  271. }
  272. }
  273. result = dir.rmdir(dirName);
  274. }
  275. return result;
  276. }
  277. //-----------------------------------------------------------------------------
  278. bool ctk::copyDirRecursively(const QString &srcPath, const QString &dstPath)
  279. {
  280. // See http://stackoverflow.com/questions/2536524/copy-directory-using-qt
  281. if (!QFile::exists(srcPath))
  282. {
  283. qCritical() << "ctk::copyDirRecursively: Failed to copy nonexistent directory" << srcPath;
  284. return false;
  285. }
  286. QDir srcDir(srcPath);
  287. if (!srcDir.relativeFilePath(dstPath).startsWith(".."))
  288. {
  289. qCritical() << "ctk::copyDirRecursively: Cannot copy directory" << srcPath << "into itself" << dstPath;
  290. return false;
  291. }
  292. QDir parentDstDir(QFileInfo(dstPath).path());
  293. if (!QFile::exists(dstPath) && !parentDstDir.mkdir(QFileInfo(dstPath).fileName()))
  294. {
  295. qCritical() << "ctk::copyDirRecursively: Failed to create destination directory" << QFileInfo(dstPath).fileName();
  296. return false;
  297. }
  298. foreach(const QFileInfo &info, srcDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot))
  299. {
  300. QString srcItemPath = srcPath + "/" + info.fileName();
  301. QString dstItemPath = dstPath + "/" + info.fileName();
  302. if (info.isDir())
  303. {
  304. if (!ctk::copyDirRecursively(srcItemPath, dstItemPath))
  305. {
  306. qCritical() << "ctk::copyDirRecursively: Failed to copy files from " << srcItemPath << " into " << dstItemPath;
  307. return false;
  308. }
  309. }
  310. else if (info.isFile())
  311. {
  312. if (!QFile::copy(srcItemPath, dstItemPath))
  313. {
  314. return false;
  315. }
  316. }
  317. else
  318. {
  319. qWarning() << "ctk::copyDirRecursively: Unhandled item" << info.filePath();
  320. }
  321. }
  322. return true;
  323. }
  324. //-----------------------------------------------------------------------------
  325. QString ctk::qtHandleToString(Qt::HANDLE handle)
  326. {
  327. QString str;
  328. QTextStream s(&str);
  329. s << handle;
  330. return str;
  331. }
  332. //-----------------------------------------------------------------------------
  333. qint64 ctk::msecsTo(const QDateTime& t1, const QDateTime& t2)
  334. {
  335. QDateTime utcT1 = t1.toUTC();
  336. QDateTime utcT2 = t2.toUTC();
  337. return static_cast<qint64>(utcT1.daysTo(utcT2)) * static_cast<qint64>(1000*3600*24)
  338. + static_cast<qint64>(utcT1.time().msecsTo(utcT2.time()));
  339. }