2 #include "bitcoinaddressvalidator.h"
3 #include "walletmodel.h"
4 #include "bitcoinunits.h"
10 #include <QDoubleValidator>
14 #include <QTextDocument> // For Qt::escape
15 #include <QAbstractItemView>
16 #include <QApplication>
18 #include <QFileDialog>
19 #include <QDesktopServices>
22 #include <boost/filesystem.hpp>
23 #include <boost/filesystem/fstream.hpp>
29 #define _WIN32_WINNT 0x0501
33 #define _WIN32_IE 0x0501
34 #define WIN32_LEAN_AND_MEAN 1
45 QString dateTimeStr(const QDateTime &date)
47 return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
50 QString dateTimeStr(qint64 nTime)
52 return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
55 QFont bitcoinAddressFont()
57 QFont font("Monospace");
58 font.setStyleHint(QFont::TypeWriter);
62 void setupAddressWidget(QLineEdit *widget, QWidget *parent)
64 widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
65 widget->setValidator(new BitcoinAddressValidator(parent));
66 widget->setFont(bitcoinAddressFont());
69 void setupAmountWidget(QLineEdit *widget, QWidget *parent)
71 QDoubleValidator *amountValidator = new QDoubleValidator(parent);
72 amountValidator->setDecimals(8);
73 amountValidator->setBottom(0.0);
74 widget->setValidator(amountValidator);
75 widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
78 bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
80 if(uri.scheme() != QString("bitcoin"))
83 SendCoinsRecipient rv;
84 rv.address = uri.path();
86 QList<QPair<QString, QString> > items = uri.queryItems();
87 for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
89 bool fShouldReturnFalse = false;
90 if (i->first.startsWith("req-"))
92 i->first.remove(0, 4);
93 fShouldReturnFalse = true;
96 if (i->first == "label")
99 fShouldReturnFalse = false;
101 else if (i->first == "amount")
103 if(!i->second.isEmpty())
105 if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
110 fShouldReturnFalse = false;
113 if (fShouldReturnFalse)
123 bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
125 // Convert bitcoin:// to bitcoin:
127 // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
128 // which will lower-case it (and thus invalidate the address).
129 if(uri.startsWith("bitcoin://"))
131 uri.replace(0, 10, "bitcoin:");
133 QUrl uriInstance(uri);
134 return parseBitcoinURI(uriInstance, out);
137 QString HtmlEscape(const QString& str, bool fMultiLine)
139 QString escaped = Qt::escape(str);
142 escaped = escaped.replace("\n", "<br>\n");
147 QString HtmlEscape(const std::string& str, bool fMultiLine)
149 return HtmlEscape(QString::fromStdString(str), fMultiLine);
152 void copyEntryData(QAbstractItemView *view, int column, int role)
154 if(!view || !view->selectionModel())
156 QModelIndexList selection = view->selectionModel()->selectedRows(column);
158 if(!selection.isEmpty())
161 QApplication::clipboard()->setText(selection.at(0).data(role).toString());
165 QString getSaveFileName(QWidget *parent, const QString &caption,
167 const QString &filter,
168 QString *selectedSuffixOut)
170 QString selectedFilter;
172 if(dir.isEmpty()) // Default to user documents location
174 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
180 QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
182 /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
183 QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
184 QString selectedSuffix;
185 if(filter_re.exactMatch(selectedFilter))
187 selectedSuffix = filter_re.cap(1);
190 /* Add suffix if needed */
191 QFileInfo info(result);
192 if(!result.isEmpty())
194 if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
196 /* No suffix specified, add selected suffix */
197 if(!result.endsWith("."))
199 result.append(selectedSuffix);
203 /* Return selected suffix if asked to */
204 if(selectedSuffixOut)
206 *selectedSuffixOut = selectedSuffix;
211 Qt::ConnectionType blockingGUIThreadConnection()
213 if(QThread::currentThread() != QCoreApplication::instance()->thread())
215 return Qt::BlockingQueuedConnection;
219 return Qt::DirectConnection;
223 bool checkPoint(const QPoint &p, const QWidget *w)
225 QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
226 if (!atW) return false;
227 return atW->topLevelWidget() == w;
230 bool isObscured(QWidget *w)
232 return !(checkPoint(QPoint(0, 0), w)
233 && checkPoint(QPoint(w->width() - 1, 0), w)
234 && checkPoint(QPoint(0, w->height() - 1), w)
235 && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
236 && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
239 void openDebugLogfile()
241 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
243 /* Open debug.log with the associated application */
244 if (boost::filesystem::exists(pathDebug))
245 QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
248 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
249 QObject(parent), size_threshold(size_threshold)
254 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
256 if(evt->type() == QEvent::ToolTipChange)
258 QWidget *widget = static_cast<QWidget*>(obj);
259 QString tooltip = widget->toolTip();
260 if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
262 // Prefix <qt/> to make sure Qt detects this as rich text
263 // Escape the current message as HTML and replace \n by <br>
264 tooltip = "<qt/>" + HtmlEscape(tooltip, true);
265 widget->setToolTip(tooltip);
269 return QObject::eventFilter(obj, evt);
273 boost::filesystem::path static StartupShortcutPath()
275 return GetSpecialFolderPath(CSIDL_STARTUP) / "NovaCoin.lnk";
278 bool GetStartOnSystemStartup()
280 // check for Bitcoin.lnk
281 return boost::filesystem::exists(StartupShortcutPath());
284 bool SetStartOnSystemStartup(bool fAutoStart)
286 // If the shortcut exists already, remove it for updating
287 boost::filesystem::remove(StartupShortcutPath());
293 // Get a pointer to the IShellLink interface.
294 IShellLink* psl = NULL;
295 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
296 CLSCTX_INPROC_SERVER, IID_IShellLink,
297 reinterpret_cast<void**>(&psl));
301 // Get the current executable path
302 TCHAR pszExePath[MAX_PATH];
303 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
305 TCHAR pszArgs[5] = TEXT("-min");
307 // Set the path to the shortcut target
308 psl->SetPath(pszExePath);
309 PathRemoveFileSpec(pszExePath);
310 psl->SetWorkingDirectory(pszExePath);
311 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
312 psl->SetArguments(pszArgs);
314 // Query IShellLink for the IPersistFile interface for
315 // saving the shortcut in persistent storage.
316 IPersistFile* ppf = NULL;
317 hres = psl->QueryInterface(IID_IPersistFile,
318 reinterpret_cast<void**>(&ppf));
321 WCHAR pwsz[MAX_PATH];
322 // Ensure that the string is ANSI.
323 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
324 // Save the link by calling IPersistFile::Save.
325 hres = ppf->Save(pwsz, TRUE);
341 // Follow the Desktop Application Autostart Spec:
342 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
344 boost::filesystem::path static GetAutostartDir()
346 namespace fs = boost::filesystem;
348 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
349 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
350 char* pszHome = getenv("HOME");
351 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
355 boost::filesystem::path static GetAutostartFilePath()
357 return GetAutostartDir() / "novacoin.desktop";
360 bool GetStartOnSystemStartup()
362 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
363 if (!optionFile.good())
365 // Scan through file for "Hidden=true":
367 while (!optionFile.eof())
369 getline(optionFile, line);
370 if (line.find("Hidden") != std::string::npos &&
371 line.find("true") != std::string::npos)
379 bool SetStartOnSystemStartup(bool fAutoStart)
382 boost::filesystem::remove(GetAutostartFilePath());
385 char pszExePath[MAX_PATH+1];
386 memset(pszExePath, 0, sizeof(pszExePath));
387 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
390 boost::filesystem::create_directories(GetAutostartDir());
392 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
393 if (!optionFile.good())
395 // Write a bitcoin.desktop file to the autostart directory:
396 optionFile << "[Desktop Entry]\n";
397 optionFile << "Type=Application\n";
398 optionFile << "Name=NovaCoin\n";
399 optionFile << "Exec=" << pszExePath << " -min\n";
400 optionFile << "Terminal=false\n";
401 optionFile << "Hidden=false\n";
408 // TODO: OSX startup stuff; see:
409 // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
411 bool GetStartOnSystemStartup() { return false; }
412 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
416 HelpMessageBox::HelpMessageBox(QWidget *parent) :
419 header = tr("NovaCoin-Qt") + " " + tr("version") + " " +
420 QString::fromStdString(FormatFullVersion()) + "\n\n" +
421 tr("Usage:") + "\n" +
422 " novacoin-qt [" + tr("command-line options") + "] " + "\n";
424 coreOptions = QString::fromStdString(HelpMessage());
426 uiOptions = tr("UI options") + ":\n" +
427 " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
428 " -min " + tr("Start minimized") + "\n" +
429 " -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
431 setWindowTitle(tr("NovaCoin-Qt"));
432 setTextFormat(Qt::PlainText);
433 // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
434 setText(header + QString(QChar(0x2003)).repeated(50));
435 setDetailedText(coreOptions + "\n" + uiOptions);
438 void HelpMessageBox::printToConsole()
440 // On other operating systems, the expected action is to print the message to the console.
441 QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
442 fprintf(stdout, "%s", strUsage.toStdString().c_str());
445 void HelpMessageBox::showOrPrint()
448 // On Windows, show a message box, as there is no stderr/stdout in windowed applications
451 // On other operating systems, print help text to console
456 } // namespace GUIUtil