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 // NovaCoin: check prefix
81 if(uri.scheme() != QString("novacoin"))
84 SendCoinsRecipient rv;
85 rv.address = uri.path();
87 QList<QPair<QString, QString> > items = uri.queryItems();
88 for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
90 bool fShouldReturnFalse = false;
91 if (i->first.startsWith("req-"))
93 i->first.remove(0, 4);
94 fShouldReturnFalse = true;
97 if (i->first == "label")
100 fShouldReturnFalse = false;
102 else if (i->first == "amount")
104 if(!i->second.isEmpty())
106 if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
111 fShouldReturnFalse = false;
114 if (fShouldReturnFalse)
124 bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
126 // Convert novacoin:// to novacoin:
128 // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
129 // which will lower-case it (and thus invalidate the address).
130 if(uri.startsWith("novacoin://"))
132 uri.replace(0, 10, "novacoin:");
134 QUrl uriInstance(uri);
135 return parseBitcoinURI(uriInstance, out);
138 QString HtmlEscape(const QString& str, bool fMultiLine)
140 QString escaped = Qt::escape(str);
143 escaped = escaped.replace("\n", "<br>\n");
148 QString HtmlEscape(const std::string& str, bool fMultiLine)
150 return HtmlEscape(QString::fromStdString(str), fMultiLine);
153 void copyEntryData(QAbstractItemView *view, int column, int role)
155 if(!view || !view->selectionModel())
157 QModelIndexList selection = view->selectionModel()->selectedRows(column);
159 if(!selection.isEmpty())
162 QApplication::clipboard()->setText(selection.at(0).data(role).toString());
166 QString getSaveFileName(QWidget *parent, const QString &caption,
168 const QString &filter,
169 QString *selectedSuffixOut)
171 QString selectedFilter;
173 if(dir.isEmpty()) // Default to user documents location
175 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
181 QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
183 /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
184 QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
185 QString selectedSuffix;
186 if(filter_re.exactMatch(selectedFilter))
188 selectedSuffix = filter_re.cap(1);
191 /* Add suffix if needed */
192 QFileInfo info(result);
193 if(!result.isEmpty())
195 if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
197 /* No suffix specified, add selected suffix */
198 if(!result.endsWith("."))
200 result.append(selectedSuffix);
204 /* Return selected suffix if asked to */
205 if(selectedSuffixOut)
207 *selectedSuffixOut = selectedSuffix;
212 Qt::ConnectionType blockingGUIThreadConnection()
214 if(QThread::currentThread() != QCoreApplication::instance()->thread())
216 return Qt::BlockingQueuedConnection;
220 return Qt::DirectConnection;
224 bool checkPoint(const QPoint &p, const QWidget *w)
226 QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
227 if (!atW) return false;
228 return atW->topLevelWidget() == w;
231 bool isObscured(QWidget *w)
233 return !(checkPoint(QPoint(0, 0), w)
234 && checkPoint(QPoint(w->width() - 1, 0), w)
235 && checkPoint(QPoint(0, w->height() - 1), w)
236 && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
237 && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
240 void openDebugLogfile()
242 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
244 /* Open debug.log with the associated application */
245 if (boost::filesystem::exists(pathDebug))
246 QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
249 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
250 QObject(parent), size_threshold(size_threshold)
255 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
257 if(evt->type() == QEvent::ToolTipChange)
259 QWidget *widget = static_cast<QWidget*>(obj);
260 QString tooltip = widget->toolTip();
261 if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
263 // Prefix <qt/> to make sure Qt detects this as rich text
264 // Escape the current message as HTML and replace \n by <br>
265 tooltip = "<qt/>" + HtmlEscape(tooltip, true);
266 widget->setToolTip(tooltip);
270 return QObject::eventFilter(obj, evt);
274 boost::filesystem::path static StartupShortcutPath()
276 return GetSpecialFolderPath(CSIDL_STARTUP) / "NovaCoin.lnk";
279 bool GetStartOnSystemStartup()
281 // check for Bitcoin.lnk
282 return boost::filesystem::exists(StartupShortcutPath());
285 bool SetStartOnSystemStartup(bool fAutoStart)
287 // If the shortcut exists already, remove it for updating
288 boost::filesystem::remove(StartupShortcutPath());
294 // Get a pointer to the IShellLink interface.
295 IShellLink* psl = NULL;
296 HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
297 CLSCTX_INPROC_SERVER, IID_IShellLink,
298 reinterpret_cast<void**>(&psl));
302 // Get the current executable path
303 TCHAR pszExePath[MAX_PATH];
304 GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
306 TCHAR pszArgs[5] = TEXT("-min");
308 // Set the path to the shortcut target
309 psl->SetPath(pszExePath);
310 PathRemoveFileSpec(pszExePath);
311 psl->SetWorkingDirectory(pszExePath);
312 psl->SetShowCmd(SW_SHOWMINNOACTIVE);
313 psl->SetArguments(pszArgs);
315 // Query IShellLink for the IPersistFile interface for
316 // saving the shortcut in persistent storage.
317 IPersistFile* ppf = NULL;
318 hres = psl->QueryInterface(IID_IPersistFile,
319 reinterpret_cast<void**>(&ppf));
322 WCHAR pwsz[MAX_PATH];
323 // Ensure that the string is ANSI.
324 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
325 // Save the link by calling IPersistFile::Save.
326 hres = ppf->Save(pwsz, TRUE);
342 // Follow the Desktop Application Autostart Spec:
343 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
345 boost::filesystem::path static GetAutostartDir()
347 namespace fs = boost::filesystem;
349 char* pszConfigHome = getenv("XDG_CONFIG_HOME");
350 if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
351 char* pszHome = getenv("HOME");
352 if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
356 boost::filesystem::path static GetAutostartFilePath()
358 return GetAutostartDir() / "novacoin.desktop";
361 bool GetStartOnSystemStartup()
363 boost::filesystem::ifstream optionFile(GetAutostartFilePath());
364 if (!optionFile.good())
366 // Scan through file for "Hidden=true":
368 while (!optionFile.eof())
370 getline(optionFile, line);
371 if (line.find("Hidden") != std::string::npos &&
372 line.find("true") != std::string::npos)
380 bool SetStartOnSystemStartup(bool fAutoStart)
383 boost::filesystem::remove(GetAutostartFilePath());
386 char pszExePath[MAX_PATH+1];
387 memset(pszExePath, 0, sizeof(pszExePath));
388 if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
391 boost::filesystem::create_directories(GetAutostartDir());
393 boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
394 if (!optionFile.good())
396 // Write a bitcoin.desktop file to the autostart directory:
397 optionFile << "[Desktop Entry]\n";
398 optionFile << "Type=Application\n";
399 optionFile << "Name=NovaCoin\n";
400 optionFile << "Exec=" << pszExePath << " -min\n";
401 optionFile << "Terminal=false\n";
402 optionFile << "Hidden=false\n";
409 // TODO: OSX startup stuff; see:
410 // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
412 bool GetStartOnSystemStartup() { return false; }
413 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
417 HelpMessageBox::HelpMessageBox(QWidget *parent) :
420 header = tr("NovaCoin-Qt") + " " + tr("version") + " " +
421 QString::fromStdString(FormatFullVersion()) + "\n\n" +
422 tr("Usage:") + "\n" +
423 " novacoin-qt [" + tr("command-line options") + "] " + "\n";
425 coreOptions = QString::fromStdString(HelpMessage());
427 uiOptions = tr("UI options") + ":\n" +
428 " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
429 " -min " + tr("Start minimized") + "\n" +
430 " -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
432 setWindowTitle(tr("NovaCoin-Qt"));
433 setTextFormat(Qt::PlainText);
434 // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
435 setText(header + QString(QChar(0x2003)).repeated(50));
436 setDetailedText(coreOptions + "\n" + uiOptions);
439 void HelpMessageBox::printToConsole()
441 // On other operating systems, the expected action is to print the message to the console.
442 QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
443 fprintf(stdout, "%s", strUsage.toStdString().c_str());
446 void HelpMessageBox::showOrPrint()
449 // On Windows, show a message box, as there is no stderr/stdout in windowed applications
452 // On other operating systems, print help text to console
457 } // namespace GUIUtil