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 0x0601
39 #define WIN32_LEAN_AND_MEAN 1
48 #if BOOST_FILESYSTEM_VERSION >= 3
49 static boost::filesystem::detail::utf8_codecvt_facet utf8;
54 #if BOOST_FILESYSTEM_VERSION >= 3
55 boost::filesystem::path qstringToBoostPath(const QString &path)
57 return boost::filesystem::path(path.toStdString(), utf8);
59 QString boostPathToQString(const boost::filesystem::path &path)
61 return QString::fromStdString(path.string(utf8));
64 #warning Conversion between boost path and QString can use invalid character encoding with boost_filesystem v2 and older
65 boost::filesystem::path qstringToBoostPath(const QString &path)
67 return boost::filesystem::path(path.toStdString());
69 QString boostPathToQString(const boost::filesystem::path &path)
71 return QString::fromStdString(path.string());
75 QString dateTimeStr(const QDateTime &date)
77 return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
80 QString dateTimeStr(qint64 nTime)
82 return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
85 QFont bitcoinAddressFont()
87 QFont font("Monospace");
88 font.setStyleHint(QFont::TypeWriter);
92 void setupAddressWidget(QLineEdit *widget, QWidget *parent)
94 widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
95 widget->setValidator(new BitcoinAddressValidator(parent));
96 widget->setFont(bitcoinAddressFont());
99 void setupAmountWidget(QLineEdit *widget, QWidget *parent)
101 QDoubleValidator *amountValidator = new QDoubleValidator(parent);
102 amountValidator->setDecimals(8);
103 amountValidator->setBottom(0.0);
104 widget->setValidator(amountValidator);
105 widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
108 bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
110 // NovaCoin: check prefix
111 if(uri.scheme() != QString("novacoin"))
114 SendCoinsRecipient rv;
115 rv.address = uri.path();
117 #if QT_VERSION < 0x050000
118 QList<QPair<QString, QString> > items = uri.queryItems();
120 QUrlQuery uriQuery(uri);
121 QList<QPair<QString, QString> > items = uriQuery.queryItems();
123 for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
125 bool fShouldReturnFalse = false;
126 if (i->first.startsWith("req-"))
128 i->first.remove(0, 4);
129 fShouldReturnFalse = true;
132 if (i->first == "label")
134 rv.label = i->second;
135 fShouldReturnFalse = false;
137 else if (i->first == "amount")
139 if(!i->second.isEmpty())
141 if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
146 fShouldReturnFalse = false;
149 if (fShouldReturnFalse)
159 bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
161 // Convert novacoin:// to novacoin:
163 // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
164 // which will lower-case it (and thus invalidate the address).
165 if(uri.startsWith("novacoin://"))
167 uri.replace(0, 10, "novacoin:");
169 QUrl uriInstance(uri);
170 return parseBitcoinURI(uriInstance, out);
173 QString HtmlEscape(const QString& str, bool fMultiLine)
175 #if QT_VERSION < 0x050000
176 QString escaped = Qt::escape(str);
178 QString escaped = str.toHtmlEscaped();
182 escaped = escaped.replace("\n", "<br>\n");
187 QString HtmlEscape(const std::string& str, bool fMultiLine)
189 return HtmlEscape(QString::fromStdString(str), fMultiLine);
192 void copyEntryData(QAbstractItemView *view, int column, int role)
194 if(!view || !view->selectionModel())
196 QModelIndexList selection = view->selectionModel()->selectedRows(column);
198 if(!selection.isEmpty())
201 QApplication::clipboard()->setText(selection.at(0).data(role).toString());
205 QString getSaveFileName(QWidget *parent, const QString &caption,
207 const QString &filter,
208 QString *selectedSuffixOut)
210 QString selectedFilter;
212 if(dir.isEmpty()) // Default to user documents location
214 #if QT_VERSION < 0x050000
215 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
217 myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
224 QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
226 /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
227 QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
228 QString selectedSuffix;
229 if(filter_re.exactMatch(selectedFilter))
231 selectedSuffix = filter_re.cap(1);
234 /* Add suffix if needed */
235 QFileInfo info(result);
236 if(!result.isEmpty())
238 if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
240 /* No suffix specified, add selected suffix */
241 if(!result.endsWith("."))
243 result.append(selectedSuffix);
247 /* Return selected suffix if asked to */
248 if(selectedSuffixOut)
250 *selectedSuffixOut = selectedSuffix;
255 Qt::ConnectionType blockingGUIThreadConnection()
257 if(QThread::currentThread() != QCoreApplication::instance()->thread())
259 return Qt::BlockingQueuedConnection;
263 return Qt::DirectConnection;
267 bool checkPoint(const QPoint &p, const QWidget *w)
269 QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
270 if (!atW) return false;
271 return atW->topLevelWidget() == w;
274 bool isObscured(QWidget *w)
276 return !(checkPoint(QPoint(0, 0), w)
277 && checkPoint(QPoint(w->width() - 1, 0), w)
278 && checkPoint(QPoint(0, w->height() - 1), w)
279 && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
280 && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
283 void openDebugLogfile()
285 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
287 /* Open debug.log with the associated application */
288 if (boost::filesystem::exists(pathDebug))
289 QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
292 void openConfigfile()
294 boost::filesystem::path pathConfig = GetConfigFile();
296 /* Open novacoin.conf with the associated application */
297 if (boost::filesystem::exists(pathConfig))
298 QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathConfig.string())));
301 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
302 QObject(parent), size_threshold(size_threshold)
307 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
309 if(evt->type() == QEvent::ToolTipChange)
311 QWidget *widget = static_cast<QWidget*>(obj);
312 QString tooltip = widget->toolTip();
313 if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip))
315 // Prefix <qt/> to make sure Qt detects this as rich text
316 // Escape the current message as HTML and replace \n by <br>
317 tooltip = "<qt>" + HtmlEscape(tooltip, true) + "<qt/>";
318 widget->setToolTip(tooltip);
322 return QObject::eventFilter(obj, evt);
326 boost::filesystem::path static StartupShortcutPath()
328 return GetSpecialFolderPath(CSIDL_STARTUP) / "NovaCoin.lnk";
331 bool GetStartOnSystemStartup()
333 // check for Bitcoin.lnk
334 return boost::filesystem::exists(StartupShortcutPath());
337 bool SetStartOnSystemStartup(bool fAutoStart)
339 // If the shortcut exists already, remove it for updating
340 boost::filesystem::remove(StartupShortcutPath());
346 // Get a pointer to the IShellLink interface.
347 IShellLink* psl = NULL;
348 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
349 CLSCTX_INPROC_SERVER, IID_IShellLink,
350 reinterpret_cast<void**>(&psl));
354 // Get the current executable path
355 TCHAR pszExePath[MAX_PATH];
356 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
358 TCHAR pszArgs[5] = TEXT("-min");
360 // Set the path to the shortcut target
361 psl->SetPath(pszExePath);
362 PathRemoveFileSpec(pszExePath);
363 psl->SetWorkingDirectory(pszExePath);
364 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
365 psl->SetArguments(pszArgs);
367 // Query IShellLink for the IPersistFile interface for
368 // saving the shortcut in persistent storage.
369 IPersistFile* ppf = NULL;
370 hres = psl->QueryInterface(IID_IPersistFile,
371 reinterpret_cast<void**>(&ppf));
374 WCHAR pwsz[MAX_PATH];
375 // Ensure that the string is ANSI.
376 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
377 // Save the link by calling IPersistFile::Save.
378 hres = ppf->Save(pwsz, TRUE);
394 // Follow the Desktop Application Autostart Spec:
395 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
397 boost::filesystem::path static GetAutostartDir()
399 namespace fs = boost::filesystem;
401 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
402 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
403 char* pszHome = getenv("HOME");
404 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
408 boost::filesystem::path static GetAutostartFilePath()
410 return GetAutostartDir() / "novacoin.desktop";
413 bool GetStartOnSystemStartup()
415 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
416 if (!optionFile.good())
418 // Scan through file for "Hidden=true":
420 while (!optionFile.eof())
422 getline(optionFile, line);
423 if (line.find("Hidden") != std::string::npos &&
424 line.find("true") != std::string::npos)
432 bool SetStartOnSystemStartup(bool fAutoStart)
435 boost::filesystem::remove(GetAutostartFilePath());
438 char pszExePath[MAX_PATH+1];
439 memset(pszExePath, 0, sizeof(pszExePath));
440 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
443 boost::filesystem::create_directories(GetAutostartDir());
445 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
446 if (!optionFile.good())
448 // Write a bitcoin.desktop file to the autostart directory:
449 optionFile << "[Desktop Entry]\n";
450 optionFile << "Type=Application\n";
451 optionFile << "Name=NovaCoin\n";
452 optionFile << "Exec=" << pszExePath << " -min\n";
453 optionFile << "Terminal=false\n";
454 optionFile << "Hidden=false\n";
461 // TODO: OSX startup stuff; see:
462 // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
464 bool GetStartOnSystemStartup() { return false; }
465 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
469 HelpMessageBox::HelpMessageBox(QWidget *parent) :
472 header = tr("NovaCoin-Qt") + " " + tr("version") + " " +
473 QString::fromStdString(FormatFullVersion()) + "\n\n" +
474 tr("Usage:") + "\n" +
475 " novacoin-qt [" + tr("command-line options") + "] " + "\n";
477 coreOptions = QString::fromStdString(HelpMessage());
479 uiOptions = tr("UI options") + ":\n" +
480 " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
481 " -min " + tr("Start minimized") + "\n" +
482 " -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
484 setWindowTitle(tr("NovaCoin-Qt"));
485 setFont(bitcoinAddressFont());
486 setTextFormat(Qt::PlainText);
487 // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
488 setText(header + QString(QChar(0x2003)).repeated(50));
489 setDetailedText(coreOptions + "\n" + uiOptions);
490 addButton("OK", QMessageBox::RejectRole); //кнопка OK будет справа от кнопки "Скрыть подробности"
491 //addButton("OK", QMessageBox::NoRole); //кнопка OK будет слева от кнопки "Скрыть подробности"
492 setMouseTracking(true);
493 setSizeGripEnabled(true);
496 void HelpMessageBox::printToConsole()
498 // On other operating systems, the expected action is to print the message to the console.
499 QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
500 fprintf(stdout, "%s", strUsage.toStdString().c_str());
503 void HelpMessageBox::showOrPrint()
506 // On Windows, show a message box, as there is no stderr/stdout in windowed applications
509 // On other operating systems, print help text to console
514 QString formatDurationStr(int secs)
517 int days = secs / 86400;
518 int hours = (secs % 86400) / 3600;
519 int mins = (secs % 3600) / 60;
520 int seconds = secs % 60;
523 strList.append(QString(QObject::tr("%1 d")).arg(days));
525 strList.append(QString(QObject::tr("%1 h")).arg(hours));
527 strList.append(QString(QObject::tr("%1 m")).arg(mins));
528 if (seconds || (!days && !hours && !mins))
529 strList.append(QString(QObject::tr("%1 s")).arg(seconds));
531 return strList.join(" ");
534 } // namespace GUIUtil