2 #include "bitcoinaddressvalidator.h"
3 #include "walletmodel.h"
4 #include "bitcoinunits.h"
10 #include <QDoubleValidator>
13 #if QT_VERSION >= 0x050000
18 #include <QTextDocument> // For Qt::mightBeRichText
19 #include <QAbstractItemView>
20 #include <QApplication>
22 #include <QFileDialog>
23 #include <QDesktopServices>
27 #include <boost/filesystem.hpp>
28 #include <boost/filesystem/fstream.hpp>
29 #if BOOST_FILESYSTEM_VERSION >= 3
30 #include <boost/filesystem/detail/utf8_codecvt_facet.hpp>
38 #define _WIN32_WINNT 0x0501
42 #define _WIN32_IE 0x0501
43 #define WIN32_LEAN_AND_MEAN 1
52 #if BOOST_FILESYSTEM_VERSION >= 3
53 static boost::filesystem::detail::utf8_codecvt_facet utf8;
58 #if BOOST_FILESYSTEM_VERSION >= 3
59 boost::filesystem::path qstringToBoostPath(const QString &path)
61 return boost::filesystem::path(path.toStdString(), utf8);
63 QString boostPathToQString(const boost::filesystem::path &path)
65 return QString::fromStdString(path.string(utf8));
68 #warning Conversion between boost path and QString can use invalid character encoding with boost_filesystem v2 and older
69 boost::filesystem::path qstringToBoostPath(const QString &path)
71 return boost::filesystem::path(path.toStdString());
73 QString boostPathToQString(const boost::filesystem::path &path)
75 return QString::fromStdString(path.string());
79 QString dateTimeStr(const QDateTime &date)
81 return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
84 QString dateTimeStr(qint64 nTime)
86 return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
89 QFont bitcoinAddressFont()
91 QFont font("Monospace");
92 font.setStyleHint(QFont::TypeWriter);
96 void setupAddressWidget(QLineEdit *widget, QWidget *parent)
98 widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
99 widget->setValidator(new BitcoinAddressValidator(parent));
100 widget->setFont(bitcoinAddressFont());
103 void setupAmountWidget(QLineEdit *widget, QWidget *parent)
105 QDoubleValidator *amountValidator = new QDoubleValidator(parent);
106 amountValidator->setDecimals(8);
107 amountValidator->setBottom(0.0);
108 widget->setValidator(amountValidator);
109 widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
112 bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
114 // NovaCoin: check prefix
115 if(uri.scheme() != QString("novacoin"))
118 SendCoinsRecipient rv;
119 rv.address = uri.path();
121 #if QT_VERSION < 0x050000
122 QList<QPair<QString, QString> > items = uri.queryItems();
124 QUrlQuery uriQuery(uri);
125 QList<QPair<QString, QString> > items = uriQuery.queryItems();
127 for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
129 bool fShouldReturnFalse = false;
130 if (i->first.startsWith("req-"))
132 i->first.remove(0, 4);
133 fShouldReturnFalse = true;
136 if (i->first == "label")
138 rv.label = i->second;
139 fShouldReturnFalse = false;
141 else if (i->first == "amount")
143 if(!i->second.isEmpty())
145 if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
150 fShouldReturnFalse = false;
153 if (fShouldReturnFalse)
163 bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
165 // Convert novacoin:// to novacoin:
167 // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
168 // which will lower-case it (and thus invalidate the address).
169 if(uri.startsWith("novacoin://"))
171 uri.replace(0, 10, "novacoin:");
173 QUrl uriInstance(uri);
174 return parseBitcoinURI(uriInstance, out);
177 QString HtmlEscape(const QString& str, bool fMultiLine)
179 #if QT_VERSION < 0x050000
180 QString escaped = Qt::escape(str);
182 QString escaped = str.toHtmlEscaped();
186 escaped = escaped.replace("\n", "<br>\n");
191 QString HtmlEscape(const std::string& str, bool fMultiLine)
193 return HtmlEscape(QString::fromStdString(str), fMultiLine);
196 void copyEntryData(QAbstractItemView *view, int column, int role)
198 if(!view || !view->selectionModel())
200 QModelIndexList selection = view->selectionModel()->selectedRows(column);
202 if(!selection.isEmpty())
205 QApplication::clipboard()->setText(selection.at(0).data(role).toString());
209 QString getSaveFileName(QWidget *parent, const QString &caption,
211 const QString &filter,
212 QString *selectedSuffixOut)
214 QString selectedFilter;
216 if(dir.isEmpty()) // Default to user documents location
218 #if QT_VERSION < 0x050000
219 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
221 myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
228 QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
230 /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
231 QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
232 QString selectedSuffix;
233 if(filter_re.exactMatch(selectedFilter))
235 selectedSuffix = filter_re.cap(1);
238 /* Add suffix if needed */
239 QFileInfo info(result);
240 if(!result.isEmpty())
242 if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
244 /* No suffix specified, add selected suffix */
245 if(!result.endsWith("."))
247 result.append(selectedSuffix);
251 /* Return selected suffix if asked to */
252 if(selectedSuffixOut)
254 *selectedSuffixOut = selectedSuffix;
259 Qt::ConnectionType blockingGUIThreadConnection()
261 if(QThread::currentThread() != QCoreApplication::instance()->thread())
263 return Qt::BlockingQueuedConnection;
267 return Qt::DirectConnection;
271 bool checkPoint(const QPoint &p, const QWidget *w)
273 QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
274 if (!atW) return false;
275 return atW->topLevelWidget() == w;
278 bool isObscured(QWidget *w)
280 return !(checkPoint(QPoint(0, 0), w)
281 && checkPoint(QPoint(w->width() - 1, 0), w)
282 && checkPoint(QPoint(0, w->height() - 1), w)
283 && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
284 && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
287 void openDebugLogfile()
289 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
291 /* Open debug.log with the associated application */
292 if (boost::filesystem::exists(pathDebug))
293 QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
296 void openConfigfile()
298 boost::filesystem::path pathConfig = GetConfigFile();
300 /* Open novacoin.conf with the associated application */
301 if (boost::filesystem::exists(pathConfig))
302 QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathConfig.string())));
305 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
306 QObject(parent), size_threshold(size_threshold)
311 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
313 if(evt->type() == QEvent::ToolTipChange)
315 QWidget *widget = static_cast<QWidget*>(obj);
316 QString tooltip = widget->toolTip();
317 if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip))
319 // Prefix <qt/> to make sure Qt detects this as rich text
320 // Escape the current message as HTML and replace \n by <br>
321 tooltip = "<qt>" + HtmlEscape(tooltip, true) + "<qt/>";
322 widget->setToolTip(tooltip);
326 return QObject::eventFilter(obj, evt);
330 boost::filesystem::path static StartupShortcutPath()
332 return GetSpecialFolderPath(CSIDL_STARTUP) / "NovaCoin.lnk";
335 bool GetStartOnSystemStartup()
337 // check for Bitcoin.lnk
338 return boost::filesystem::exists(StartupShortcutPath());
341 bool SetStartOnSystemStartup(bool fAutoStart)
343 // If the shortcut exists already, remove it for updating
344 boost::filesystem::remove(StartupShortcutPath());
350 // Get a pointer to the IShellLink interface.
351 IShellLink* psl = NULL;
352 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
353 CLSCTX_INPROC_SERVER, IID_IShellLink,
354 reinterpret_cast<void**>(&psl));
358 // Get the current executable path
359 TCHAR pszExePath[MAX_PATH];
360 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
362 TCHAR pszArgs[5] = TEXT("-min");
364 // Set the path to the shortcut target
365 psl->SetPath(pszExePath);
366 PathRemoveFileSpec(pszExePath);
367 psl->SetWorkingDirectory(pszExePath);
368 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
369 psl->SetArguments(pszArgs);
371 // Query IShellLink for the IPersistFile interface for
372 // saving the shortcut in persistent storage.
373 IPersistFile* ppf = NULL;
374 hres = psl->QueryInterface(IID_IPersistFile,
375 reinterpret_cast<void**>(&ppf));
378 WCHAR pwsz[MAX_PATH];
379 // Ensure that the string is ANSI.
380 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
381 // Save the link by calling IPersistFile::Save.
382 hres = ppf->Save(pwsz, TRUE);
398 // Follow the Desktop Application Autostart Spec:
399 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
401 boost::filesystem::path static GetAutostartDir()
403 namespace fs = boost::filesystem;
405 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
406 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
407 char* pszHome = getenv("HOME");
408 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
412 boost::filesystem::path static GetAutostartFilePath()
414 return GetAutostartDir() / "novacoin.desktop";
417 bool GetStartOnSystemStartup()
419 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
420 if (!optionFile.good())
422 // Scan through file for "Hidden=true":
424 while (!optionFile.eof())
426 getline(optionFile, line);
427 if (line.find("Hidden") != std::string::npos &&
428 line.find("true") != std::string::npos)
436 bool SetStartOnSystemStartup(bool fAutoStart)
439 boost::filesystem::remove(GetAutostartFilePath());
442 char pszExePath[MAX_PATH+1];
443 memset(pszExePath, 0, sizeof(pszExePath));
444 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
447 boost::filesystem::create_directories(GetAutostartDir());
449 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
450 if (!optionFile.good())
452 // Write a bitcoin.desktop file to the autostart directory:
453 optionFile << "[Desktop Entry]\n";
454 optionFile << "Type=Application\n";
455 optionFile << "Name=NovaCoin\n";
456 optionFile << "Exec=" << pszExePath << " -min\n";
457 optionFile << "Terminal=false\n";
458 optionFile << "Hidden=false\n";
465 // TODO: OSX startup stuff; see:
466 // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
468 bool GetStartOnSystemStartup() { return false; }
469 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
473 HelpMessageBox::HelpMessageBox(QWidget *parent) :
476 header = tr("NovaCoin-Qt") + " " + tr("version") + " " +
477 QString::fromStdString(FormatFullVersion()) + "\n\n" +
478 tr("Usage:") + "\n" +
479 " novacoin-qt [" + tr("command-line options") + "] " + "\n";
481 coreOptions = QString::fromStdString(HelpMessage());
483 uiOptions = tr("UI options") + ":\n" +
484 " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
485 " -min " + tr("Start minimized") + "\n" +
486 " -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
488 setWindowTitle(tr("NovaCoin-Qt"));
489 setFont(bitcoinAddressFont());
490 setTextFormat(Qt::PlainText);
491 // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
492 setText(header + QString(QChar(0x2003)).repeated(50));
493 setDetailedText(coreOptions + "\n" + uiOptions);
494 addButton("OK", QMessageBox::RejectRole); //кнопка OK будет справа от кнопки "Скрыть подробности"
495 //addButton("OK", QMessageBox::NoRole); //кнопка OK будет слева от кнопки "Скрыть подробности"
496 setMouseTracking(true);
497 setSizeGripEnabled(true);
500 void HelpMessageBox::printToConsole()
502 // On other operating systems, the expected action is to print the message to the console.
503 QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
504 fprintf(stdout, "%s", strUsage.toStdString().c_str());
507 void HelpMessageBox::showOrPrint()
510 // On Windows, show a message box, as there is no stderr/stdout in windowed applications
513 // On other operating systems, print help text to console
518 QString formatDurationStr(int secs)
521 int days = secs / 86400;
522 int hours = (secs % 86400) / 3600;
523 int mins = (secs % 3600) / 60;
524 int seconds = secs % 60;
527 strList.append(QString(QObject::tr("%1 d")).arg(days));
529 strList.append(QString(QObject::tr("%1 h")).arg(hours));
531 strList.append(QString(QObject::tr("%1 m")).arg(mins));
532 if (seconds || (!days && !hours && !mins))
533 strList.append(QString(QObject::tr("%1 s")).arg(seconds));
535 return strList.join(" ");
538 } // namespace GUIUtil