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>
35 #define _WIN32_WINNT 0x0501
39 #define _WIN32_IE 0x0501
40 #define WIN32_LEAN_AND_MEAN 1
51 QString dateTimeStr(const QDateTime &date)
53 return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
56 QString dateTimeStr(qint64 nTime)
58 return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
61 QFont bitcoinAddressFont()
63 QFont font("Monospace");
64 font.setStyleHint(QFont::TypeWriter);
68 void setupAddressWidget(QLineEdit *widget, QWidget *parent)
70 widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
71 widget->setValidator(new BitcoinAddressValidator(parent));
72 widget->setFont(bitcoinAddressFont());
75 void setupAmountWidget(QLineEdit *widget, QWidget *parent)
77 QDoubleValidator *amountValidator = new QDoubleValidator(parent);
78 amountValidator->setDecimals(8);
79 amountValidator->setBottom(0.0);
80 widget->setValidator(amountValidator);
81 widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
84 bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
86 // NovaCoin: check prefix
87 if(uri.scheme() != QString("novacoin"))
90 SendCoinsRecipient rv;
91 rv.address = uri.path();
93 #if QT_VERSION < 0x050000
94 QList<QPair<QString, QString> > items = uri.queryItems();
96 QUrlQuery uriQuery(uri);
97 QList<QPair<QString, QString> > items = uriQuery.queryItems();
99 for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
101 bool fShouldReturnFalse = false;
102 if (i->first.startsWith("req-"))
104 i->first.remove(0, 4);
105 fShouldReturnFalse = true;
108 if (i->first == "label")
110 rv.label = i->second;
111 fShouldReturnFalse = false;
113 else if (i->first == "amount")
115 if(!i->second.isEmpty())
117 if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
122 fShouldReturnFalse = false;
125 if (fShouldReturnFalse)
135 bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
137 // Convert novacoin:// to novacoin:
139 // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
140 // which will lower-case it (and thus invalidate the address).
141 if(uri.startsWith("novacoin://"))
143 uri.replace(0, 10, "novacoin:");
145 QUrl uriInstance(uri);
146 return parseBitcoinURI(uriInstance, out);
149 QString HtmlEscape(const QString& str, bool fMultiLine)
151 #if QT_VERSION < 0x050000
152 QString escaped = Qt::escape(str);
154 QString escaped = str.toHtmlEscaped();
158 escaped = escaped.replace("\n", "<br>\n");
163 QString HtmlEscape(const std::string& str, bool fMultiLine)
165 return HtmlEscape(QString::fromStdString(str), fMultiLine);
168 void copyEntryData(QAbstractItemView *view, int column, int role)
170 if(!view || !view->selectionModel())
172 QModelIndexList selection = view->selectionModel()->selectedRows(column);
174 if(!selection.isEmpty())
177 QApplication::clipboard()->setText(selection.at(0).data(role).toString());
181 QString getSaveFileName(QWidget *parent, const QString &caption,
183 const QString &filter,
184 QString *selectedSuffixOut)
186 QString selectedFilter;
188 if(dir.isEmpty()) // Default to user documents location
190 #if QT_VERSION < 0x050000
191 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
193 myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
200 QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
202 /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
203 QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
204 QString selectedSuffix;
205 if(filter_re.exactMatch(selectedFilter))
207 selectedSuffix = filter_re.cap(1);
210 /* Add suffix if needed */
211 QFileInfo info(result);
212 if(!result.isEmpty())
214 if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
216 /* No suffix specified, add selected suffix */
217 if(!result.endsWith("."))
219 result.append(selectedSuffix);
223 /* Return selected suffix if asked to */
224 if(selectedSuffixOut)
226 *selectedSuffixOut = selectedSuffix;
231 Qt::ConnectionType blockingGUIThreadConnection()
233 if(QThread::currentThread() != QCoreApplication::instance()->thread())
235 return Qt::BlockingQueuedConnection;
239 return Qt::DirectConnection;
243 bool checkPoint(const QPoint &p, const QWidget *w)
245 QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
246 if (!atW) return false;
247 return atW->topLevelWidget() == w;
250 bool isObscured(QWidget *w)
252 return !(checkPoint(QPoint(0, 0), w)
253 && checkPoint(QPoint(w->width() - 1, 0), w)
254 && checkPoint(QPoint(0, w->height() - 1), w)
255 && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
256 && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
259 void openDebugLogfile()
261 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
263 /* Open debug.log with the associated application */
264 if (boost::filesystem::exists(pathDebug))
265 QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
268 void openConfigfile()
270 boost::filesystem::path pathConfig = GetConfigFile();
272 /* Open novacoin.conf with the associated application */
273 if (boost::filesystem::exists(pathConfig))
274 QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathConfig.string())));
277 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
278 QObject(parent), size_threshold(size_threshold)
283 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
285 if(evt->type() == QEvent::ToolTipChange)
287 QWidget *widget = static_cast<QWidget*>(obj);
288 QString tooltip = widget->toolTip();
289 if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip))
291 // Prefix <qt/> to make sure Qt detects this as rich text
292 // Escape the current message as HTML and replace \n by <br>
293 tooltip = "<qt>" + HtmlEscape(tooltip, true) + "<qt/>";
294 widget->setToolTip(tooltip);
298 return QObject::eventFilter(obj, evt);
302 boost::filesystem::path static StartupShortcutPath()
304 return GetSpecialFolderPath(CSIDL_STARTUP) / "NovaCoin.lnk";
307 bool GetStartOnSystemStartup()
309 // check for Bitcoin.lnk
310 return boost::filesystem::exists(StartupShortcutPath());
313 bool SetStartOnSystemStartup(bool fAutoStart)
315 // If the shortcut exists already, remove it for updating
316 boost::filesystem::remove(StartupShortcutPath());
322 // Get a pointer to the IShellLink interface.
323 IShellLink* psl = NULL;
324 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
325 CLSCTX_INPROC_SERVER, IID_IShellLink,
326 reinterpret_cast<void**>(&psl));
330 // Get the current executable path
331 TCHAR pszExePath[MAX_PATH];
332 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
334 TCHAR pszArgs[5] = TEXT("-min");
336 // Set the path to the shortcut target
337 psl->SetPath(pszExePath);
338 PathRemoveFileSpec(pszExePath);
339 psl->SetWorkingDirectory(pszExePath);
340 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
341 psl->SetArguments(pszArgs);
343 // Query IShellLink for the IPersistFile interface for
344 // saving the shortcut in persistent storage.
345 IPersistFile* ppf = NULL;
346 hres = psl->QueryInterface(IID_IPersistFile,
347 reinterpret_cast<void**>(&ppf));
350 WCHAR pwsz[MAX_PATH];
351 // Ensure that the string is ANSI.
352 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
353 // Save the link by calling IPersistFile::Save.
354 hres = ppf->Save(pwsz, TRUE);
370 // Follow the Desktop Application Autostart Spec:
371 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
373 boost::filesystem::path static GetAutostartDir()
375 namespace fs = boost::filesystem;
377 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
378 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
379 char* pszHome = getenv("HOME");
380 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
384 boost::filesystem::path static GetAutostartFilePath()
386 return GetAutostartDir() / "novacoin.desktop";
389 bool GetStartOnSystemStartup()
391 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
392 if (!optionFile.good())
394 // Scan through file for "Hidden=true":
396 while (!optionFile.eof())
398 getline(optionFile, line);
399 if (line.find("Hidden") != std::string::npos &&
400 line.find("true") != std::string::npos)
408 bool SetStartOnSystemStartup(bool fAutoStart)
411 boost::filesystem::remove(GetAutostartFilePath());
414 char pszExePath[MAX_PATH+1];
415 memset(pszExePath, 0, sizeof(pszExePath));
416 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
419 boost::filesystem::create_directories(GetAutostartDir());
421 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
422 if (!optionFile.good())
424 // Write a bitcoin.desktop file to the autostart directory:
425 optionFile << "[Desktop Entry]\n";
426 optionFile << "Type=Application\n";
427 optionFile << "Name=NovaCoin\n";
428 optionFile << "Exec=" << pszExePath << " -min\n";
429 optionFile << "Terminal=false\n";
430 optionFile << "Hidden=false\n";
437 // TODO: OSX startup stuff; see:
438 // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
440 bool GetStartOnSystemStartup() { return false; }
441 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
445 HelpMessageBox::HelpMessageBox(QWidget *parent) :
448 header = tr("NovaCoin-Qt") + " " + tr("version") + " " +
449 QString::fromStdString(FormatFullVersion()) + "\n\n" +
450 tr("Usage:") + "\n" +
451 " novacoin-qt [" + tr("command-line options") + "] " + "\n";
453 coreOptions = QString::fromStdString(HelpMessage());
455 uiOptions = tr("UI options") + ":\n" +
456 " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
457 " -min " + tr("Start minimized") + "\n" +
458 " -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
460 setWindowTitle(tr("NovaCoin-Qt"));
461 setTextFormat(Qt::PlainText);
462 // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
463 setText(header + QString(QChar(0x2003)).repeated(50));
464 setDetailedText(coreOptions + "\n" + uiOptions);
465 addButton("OK", QMessageBox::RejectRole); //кнопка OK будет справа от кнопки "Скрыть подробности"
466 //addButton("OK", QMessageBox::NoRole); //кнопка OK будет слева от кнопки "Скрыть подробности"
467 setMouseTracking(true);
468 setSizeGripEnabled(true);
471 void HelpMessageBox::printToConsole()
473 // On other operating systems, the expected action is to print the message to the console.
474 QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
475 fprintf(stdout, "%s", strUsage.toStdString().c_str());
478 void HelpMessageBox::showOrPrint()
481 // On Windows, show a message box, as there is no stderr/stdout in windowed applications
484 // On other operating systems, print help text to console
489 QString formatDurationStr(int secs)
492 int days = secs / 86400;
493 int hours = (secs % 86400) / 3600;
494 int mins = (secs % 3600) / 60;
495 int seconds = secs % 60;
498 strList.append(QString(QObject::tr("%1 d")).arg(days));
500 strList.append(QString(QObject::tr("%1 h")).arg(hours));
502 strList.append(QString(QObject::tr("%1 m")).arg(mins));
503 if (seconds || (!days && !hours && !mins))
504 strList.append(QString(QObject::tr("%1 s")).arg(seconds));
506 return strList.join(" ");
509 } // namespace GUIUtil