/src/qt/guiutil.cpp

https://gitlab.com/AirTank/primecoin · C++ · 461 lines · 366 code · 62 blank · 33 comment · 55 complexity · f8f0179e184e38d025b54a0c4b4eefa8 MD5 · raw file

  1. #include <QApplication>
  2. #include "guiutil.h"
  3. #include "bitcoinaddressvalidator.h"
  4. #include "walletmodel.h"
  5. #include "bitcoinunits.h"
  6. #include "util.h"
  7. #include "init.h"
  8. #include <QDateTime>
  9. #include <QDoubleValidator>
  10. #include <QFont>
  11. #include <QLineEdit>
  12. #include <QUrl>
  13. #include <QTextDocument> // For Qt::escape
  14. #include <QAbstractItemView>
  15. #include <QClipboard>
  16. #include <QFileDialog>
  17. #include <QDesktopServices>
  18. #include <QThread>
  19. #include <boost/filesystem.hpp>
  20. #include <boost/filesystem/fstream.hpp>
  21. #ifdef WIN32
  22. #ifdef _WIN32_WINNT
  23. #undef _WIN32_WINNT
  24. #endif
  25. #define _WIN32_WINNT 0x0501
  26. #ifdef _WIN32_IE
  27. #undef _WIN32_IE
  28. #endif
  29. #define _WIN32_IE 0x0501
  30. #define WIN32_LEAN_AND_MEAN 1
  31. #ifndef NOMINMAX
  32. #define NOMINMAX
  33. #endif
  34. #include "shlwapi.h"
  35. #include "shlobj.h"
  36. #include "shellapi.h"
  37. #endif
  38. namespace GUIUtil {
  39. QString dateTimeStr(const QDateTime &date)
  40. {
  41. return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
  42. }
  43. QString dateTimeStr(qint64 nTime)
  44. {
  45. return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
  46. }
  47. QFont bitcoinAddressFont()
  48. {
  49. QFont font("Monospace");
  50. font.setStyleHint(QFont::TypeWriter);
  51. return font;
  52. }
  53. void setupAddressWidget(QLineEdit *widget, QWidget *parent)
  54. {
  55. widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
  56. widget->setValidator(new BitcoinAddressValidator(parent));
  57. widget->setFont(bitcoinAddressFont());
  58. }
  59. void setupAmountWidget(QLineEdit *widget, QWidget *parent)
  60. {
  61. QDoubleValidator *amountValidator = new QDoubleValidator(parent);
  62. amountValidator->setDecimals(8);
  63. amountValidator->setBottom(0.0);
  64. widget->setValidator(amountValidator);
  65. widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
  66. }
  67. bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
  68. {
  69. // return if URI is not valid or is no bitcoin URI
  70. if(!uri.isValid() || uri.scheme() != QString("primecoin"))
  71. return false;
  72. SendCoinsRecipient rv;
  73. rv.address = uri.path();
  74. rv.amount = 0;
  75. QList<QPair<QString, QString> > items = uri.queryItems();
  76. for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
  77. {
  78. bool fShouldReturnFalse = false;
  79. if (i->first.startsWith("req-"))
  80. {
  81. i->first.remove(0, 4);
  82. fShouldReturnFalse = true;
  83. }
  84. if (i->first == "label")
  85. {
  86. rv.label = i->second;
  87. fShouldReturnFalse = false;
  88. }
  89. else if (i->first == "amount")
  90. {
  91. if(!i->second.isEmpty())
  92. {
  93. if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
  94. {
  95. return false;
  96. }
  97. }
  98. fShouldReturnFalse = false;
  99. }
  100. if (fShouldReturnFalse)
  101. return false;
  102. }
  103. if(out)
  104. {
  105. *out = rv;
  106. }
  107. return true;
  108. }
  109. bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
  110. {
  111. // Convert bitcoin:// to bitcoin:
  112. //
  113. // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
  114. // which will lower-case it (and thus invalidate the address).
  115. if(uri.startsWith("primecoin://"))
  116. {
  117. uri.replace(0, 12, "primecoin:");
  118. }
  119. QUrl uriInstance(uri);
  120. return parseBitcoinURI(uriInstance, out);
  121. }
  122. QString HtmlEscape(const QString& str, bool fMultiLine)
  123. {
  124. QString escaped = Qt::escape(str);
  125. if(fMultiLine)
  126. {
  127. escaped = escaped.replace("\n", "<br>\n");
  128. }
  129. return escaped;
  130. }
  131. QString HtmlEscape(const std::string& str, bool fMultiLine)
  132. {
  133. return HtmlEscape(QString::fromStdString(str), fMultiLine);
  134. }
  135. void copyEntryData(QAbstractItemView *view, int column, int role)
  136. {
  137. if(!view || !view->selectionModel())
  138. return;
  139. QModelIndexList selection = view->selectionModel()->selectedRows(column);
  140. if(!selection.isEmpty())
  141. {
  142. // Copy first item (global clipboard)
  143. QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard);
  144. // Copy first item (global mouse selection for e.g. X11 - NOP on Windows)
  145. QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection);
  146. }
  147. }
  148. QString getSaveFileName(QWidget *parent, const QString &caption,
  149. const QString &dir,
  150. const QString &filter,
  151. QString *selectedSuffixOut)
  152. {
  153. QString selectedFilter;
  154. QString myDir;
  155. if(dir.isEmpty()) // Default to user documents location
  156. {
  157. myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
  158. }
  159. else
  160. {
  161. myDir = dir;
  162. }
  163. QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
  164. /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
  165. QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
  166. QString selectedSuffix;
  167. if(filter_re.exactMatch(selectedFilter))
  168. {
  169. selectedSuffix = filter_re.cap(1);
  170. }
  171. /* Add suffix if needed */
  172. QFileInfo info(result);
  173. if(!result.isEmpty())
  174. {
  175. if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
  176. {
  177. /* No suffix specified, add selected suffix */
  178. if(!result.endsWith("."))
  179. result.append(".");
  180. result.append(selectedSuffix);
  181. }
  182. }
  183. /* Return selected suffix if asked to */
  184. if(selectedSuffixOut)
  185. {
  186. *selectedSuffixOut = selectedSuffix;
  187. }
  188. return result;
  189. }
  190. Qt::ConnectionType blockingGUIThreadConnection()
  191. {
  192. if(QThread::currentThread() != qApp->thread())
  193. {
  194. return Qt::BlockingQueuedConnection;
  195. }
  196. else
  197. {
  198. return Qt::DirectConnection;
  199. }
  200. }
  201. bool checkPoint(const QPoint &p, const QWidget *w)
  202. {
  203. QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
  204. if (!atW) return false;
  205. return atW->topLevelWidget() == w;
  206. }
  207. bool isObscured(QWidget *w)
  208. {
  209. return !(checkPoint(QPoint(0, 0), w)
  210. && checkPoint(QPoint(w->width() - 1, 0), w)
  211. && checkPoint(QPoint(0, w->height() - 1), w)
  212. && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
  213. && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
  214. }
  215. void openDebugLogfile()
  216. {
  217. boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
  218. /* Open debug.log with the associated application */
  219. if (boost::filesystem::exists(pathDebug))
  220. QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
  221. }
  222. ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
  223. QObject(parent), size_threshold(size_threshold)
  224. {
  225. }
  226. bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
  227. {
  228. if(evt->type() == QEvent::ToolTipChange)
  229. {
  230. QWidget *widget = static_cast<QWidget*>(obj);
  231. QString tooltip = widget->toolTip();
  232. if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
  233. {
  234. // Prefix <qt/> to make sure Qt detects this as rich text
  235. // Escape the current message as HTML and replace \n by <br>
  236. tooltip = "<qt/>" + HtmlEscape(tooltip, true);
  237. widget->setToolTip(tooltip);
  238. return true;
  239. }
  240. }
  241. return QObject::eventFilter(obj, evt);
  242. }
  243. #ifdef WIN32
  244. boost::filesystem::path static StartupShortcutPath()
  245. {
  246. return GetSpecialFolderPath(CSIDL_STARTUP) / "Primecoin.lnk";
  247. }
  248. bool GetStartOnSystemStartup()
  249. {
  250. // check for Bitcoin.lnk
  251. return boost::filesystem::exists(StartupShortcutPath());
  252. }
  253. bool SetStartOnSystemStartup(bool fAutoStart)
  254. {
  255. // If the shortcut exists already, remove it for updating
  256. boost::filesystem::remove(StartupShortcutPath());
  257. if (fAutoStart)
  258. {
  259. CoInitialize(NULL);
  260. // Get a pointer to the IShellLink interface.
  261. IShellLink* psl = NULL;
  262. HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
  263. CLSCTX_INPROC_SERVER, IID_IShellLink,
  264. reinterpret_cast<void**>(&psl));
  265. if (SUCCEEDED(hres))
  266. {
  267. // Get the current executable path
  268. TCHAR pszExePath[MAX_PATH];
  269. GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
  270. TCHAR pszArgs[5] = TEXT("-min");
  271. // Set the path to the shortcut target
  272. psl->SetPath(pszExePath);
  273. PathRemoveFileSpec(pszExePath);
  274. psl->SetWorkingDirectory(pszExePath);
  275. psl->SetShowCmd(SW_SHOWMINNOACTIVE);
  276. psl->SetArguments(pszArgs);
  277. // Query IShellLink for the IPersistFile interface for
  278. // saving the shortcut in persistent storage.
  279. IPersistFile* ppf = NULL;
  280. hres = psl->QueryInterface(IID_IPersistFile,
  281. reinterpret_cast<void**>(&ppf));
  282. if (SUCCEEDED(hres))
  283. {
  284. WCHAR pwsz[MAX_PATH];
  285. // Ensure that the string is ANSI.
  286. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
  287. // Save the link by calling IPersistFile::Save.
  288. hres = ppf->Save(pwsz, TRUE);
  289. ppf->Release();
  290. psl->Release();
  291. CoUninitialize();
  292. return true;
  293. }
  294. psl->Release();
  295. }
  296. CoUninitialize();
  297. return false;
  298. }
  299. return true;
  300. }
  301. #elif defined(LINUX)
  302. // Follow the Desktop Application Autostart Spec:
  303. // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
  304. boost::filesystem::path static GetAutostartDir()
  305. {
  306. namespace fs = boost::filesystem;
  307. char* pszConfigHome = getenv("XDG_CONFIG_HOME");
  308. if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
  309. char* pszHome = getenv("HOME");
  310. if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
  311. return fs::path();
  312. }
  313. boost::filesystem::path static GetAutostartFilePath()
  314. {
  315. return GetAutostartDir() / "primecoin.desktop";
  316. }
  317. bool GetStartOnSystemStartup()
  318. {
  319. boost::filesystem::ifstream optionFile(GetAutostartFilePath());
  320. if (!optionFile.good())
  321. return false;
  322. // Scan through file for "Hidden=true":
  323. std::string line;
  324. while (!optionFile.eof())
  325. {
  326. getline(optionFile, line);
  327. if (line.find("Hidden") != std::string::npos &&
  328. line.find("true") != std::string::npos)
  329. return false;
  330. }
  331. optionFile.close();
  332. return true;
  333. }
  334. bool SetStartOnSystemStartup(bool fAutoStart)
  335. {
  336. if (!fAutoStart)
  337. boost::filesystem::remove(GetAutostartFilePath());
  338. else
  339. {
  340. char pszExePath[MAX_PATH+1];
  341. memset(pszExePath, 0, sizeof(pszExePath));
  342. if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
  343. return false;
  344. boost::filesystem::create_directories(GetAutostartDir());
  345. boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
  346. if (!optionFile.good())
  347. return false;
  348. // Write a primecoin.desktop file to the autostart directory:
  349. optionFile << "[Desktop Entry]\n";
  350. optionFile << "Type=Application\n";
  351. optionFile << "Name=Primecoin\n";
  352. optionFile << "Exec=" << pszExePath << " -min\n";
  353. optionFile << "Terminal=false\n";
  354. optionFile << "Hidden=false\n";
  355. optionFile.close();
  356. }
  357. return true;
  358. }
  359. #else
  360. // TODO: OSX startup stuff; see:
  361. // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
  362. bool GetStartOnSystemStartup() { return false; }
  363. bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
  364. #endif
  365. HelpMessageBox::HelpMessageBox(QWidget *parent) :
  366. QMessageBox(parent)
  367. {
  368. header = tr("Primecoin-Qt") + " " + tr("version") + " " +
  369. QString::fromStdString(FormatFullVersion()) + "\n\n" +
  370. tr("Usage:") + "\n" +
  371. " primecoin-qt [" + tr("command-line options") + "] " + "\n";
  372. coreOptions = QString::fromStdString(HelpMessage());
  373. uiOptions = tr("UI options") + ":\n" +
  374. " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
  375. " -min " + tr("Start minimized") + "\n" +
  376. " -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
  377. setWindowTitle(tr("Primecoin-Qt"));
  378. setTextFormat(Qt::PlainText);
  379. // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
  380. setText(header + QString(QChar(0x2003)).repeated(50));
  381. setDetailedText(coreOptions + "\n" + uiOptions);
  382. }
  383. void HelpMessageBox::printToConsole()
  384. {
  385. // On other operating systems, the expected action is to print the message to the console.
  386. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
  387. fprintf(stdout, "%s", strUsage.toStdString().c_str());
  388. }
  389. void HelpMessageBox::showOrPrint()
  390. {
  391. #if defined(WIN32)
  392. // On Windows, show a message box, as there is no stderr/stdout in windowed applications
  393. exec();
  394. #else
  395. // On other operating systems, print help text to console
  396. printToConsole();
  397. #endif
  398. }
  399. } // namespace GUIUtil