ab20bca81d4eebd352d9586f8d4f10f630da01ca
[novacoin.git] / src / qt / guiutil.cpp
1 #include "guiutil.h"
2 #include "bitcoinaddressvalidator.h"
3 #include "walletmodel.h"
4 #include "bitcoinunits.h"
5 #include "util.h"
6 #include "init.h"
7
8 #include <QString>
9 #include <QDateTime>
10 #include <QDoubleValidator>
11 #include <QFont>
12 #include <QLineEdit>
13 #include <QUrl>
14 #include <QTextDocument> // For Qt::escape
15 #include <QAbstractItemView>
16 #include <QApplication>
17 #include <QClipboard>
18 #include <QFileDialog>
19 #include <QDesktopServices>
20 #include <QThread>
21
22 #include <boost/filesystem.hpp>
23 #include <boost/filesystem/fstream.hpp>
24
25 #ifdef WIN32
26 #ifdef _WIN32_WINNT
27 #undef _WIN32_WINNT
28 #endif
29 #define _WIN32_WINNT 0x0501
30 #ifdef _WIN32_IE
31 #undef _WIN32_IE
32 #endif
33 #define _WIN32_IE 0x0501
34 #define WIN32_LEAN_AND_MEAN 1
35 #ifndef NOMINMAX
36 #define NOMINMAX
37 #endif
38 #include "shlwapi.h"
39 #include "shlobj.h"
40 #include "shellapi.h"
41 #endif
42
43 namespace GUIUtil {
44
45 QString dateTimeStr(const QDateTime &date)
46 {
47     return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
48 }
49
50 QString dateTimeStr(qint64 nTime)
51 {
52     return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
53 }
54
55 QFont bitcoinAddressFont()
56 {
57     QFont font("Monospace");
58     font.setStyleHint(QFont::TypeWriter);
59     return font;
60 }
61
62 void setupAddressWidget(QLineEdit *widget, QWidget *parent)
63 {
64     widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
65     widget->setValidator(new BitcoinAddressValidator(parent));
66     widget->setFont(bitcoinAddressFont());
67 }
68
69 void setupAmountWidget(QLineEdit *widget, QWidget *parent)
70 {
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);
76 }
77
78 bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
79 {
80     // NovaCoin: check prefix
81     if(uri.scheme() != QString("novacoin"))
82         return false;
83
84     SendCoinsRecipient rv;
85     rv.address = uri.path();
86     rv.amount = 0;
87     QList<QPair<QString, QString> > items = uri.queryItems();
88     for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
89     {
90         bool fShouldReturnFalse = false;
91         if (i->first.startsWith("req-"))
92         {
93             i->first.remove(0, 4);
94             fShouldReturnFalse = true;
95         }
96
97         if (i->first == "label")
98         {
99             rv.label = i->second;
100             fShouldReturnFalse = false;
101         }
102         else if (i->first == "amount")
103         {
104             if(!i->second.isEmpty())
105             {
106                 if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
107                 {
108                     return false;
109                 }
110             }
111             fShouldReturnFalse = false;
112         }
113
114         if (fShouldReturnFalse)
115             return false;
116     }
117     if(out)
118     {
119         *out = rv;
120     }
121     return true;
122 }
123
124 bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
125 {
126     // Convert novacoin:// to novacoin:
127     //
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://"))
131     {
132         uri.replace(0, 10, "novacoin:");
133     }
134     QUrl uriInstance(uri);
135     return parseBitcoinURI(uriInstance, out);
136 }
137
138 QString HtmlEscape(const QString& str, bool fMultiLine)
139 {
140     QString escaped = Qt::escape(str);
141     if(fMultiLine)
142     {
143         escaped = escaped.replace("\n", "<br>\n");
144     }
145     return escaped;
146 }
147
148 QString HtmlEscape(const std::string& str, bool fMultiLine)
149 {
150     return HtmlEscape(QString::fromStdString(str), fMultiLine);
151 }
152
153 void copyEntryData(QAbstractItemView *view, int column, int role)
154 {
155     if(!view || !view->selectionModel())
156         return;
157     QModelIndexList selection = view->selectionModel()->selectedRows(column);
158
159     if(!selection.isEmpty())
160     {
161         // Copy first item
162         QApplication::clipboard()->setText(selection.at(0).data(role).toString());
163     }
164 }
165
166 QString getSaveFileName(QWidget *parent, const QString &caption,
167                                  const QString &dir,
168                                  const QString &filter,
169                                  QString *selectedSuffixOut)
170 {
171     QString selectedFilter;
172     QString myDir;
173     if(dir.isEmpty()) // Default to user documents location
174     {
175         myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
176     }
177     else
178     {
179         myDir = dir;
180     }
181     QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
182
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))
187     {
188         selectedSuffix = filter_re.cap(1);
189     }
190
191     /* Add suffix if needed */
192     QFileInfo info(result);
193     if(!result.isEmpty())
194     {
195         if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
196         {
197             /* No suffix specified, add selected suffix */
198             if(!result.endsWith("."))
199                 result.append(".");
200             result.append(selectedSuffix);
201         }
202     }
203
204     /* Return selected suffix if asked to */
205     if(selectedSuffixOut)
206     {
207         *selectedSuffixOut = selectedSuffix;
208     }
209     return result;
210 }
211
212 Qt::ConnectionType blockingGUIThreadConnection()
213 {
214     if(QThread::currentThread() != QCoreApplication::instance()->thread())
215     {
216         return Qt::BlockingQueuedConnection;
217     }
218     else
219     {
220         return Qt::DirectConnection;
221     }
222 }
223
224 bool checkPoint(const QPoint &p, const QWidget *w)
225 {
226     QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
227     if (!atW) return false;
228     return atW->topLevelWidget() == w;
229 }
230
231 bool isObscured(QWidget *w)
232 {
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));
238 }
239
240 void openDebugLogfile()
241 {
242     boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
243
244     /* Open debug.log with the associated application */
245     if (boost::filesystem::exists(pathDebug))
246         QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
247 }
248
249 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
250     QObject(parent), size_threshold(size_threshold)
251 {
252
253 }
254
255 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
256 {
257     if(evt->type() == QEvent::ToolTipChange)
258     {
259         QWidget *widget = static_cast<QWidget*>(obj);
260         QString tooltip = widget->toolTip();
261         if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip))
262         {
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) + "<qt/>";
266             widget->setToolTip(tooltip);
267             return true;
268         }
269     }
270     return QObject::eventFilter(obj, evt);
271 }
272
273 #ifdef WIN32
274 boost::filesystem::path static StartupShortcutPath()
275 {
276     return GetSpecialFolderPath(CSIDL_STARTUP) / "NovaCoin.lnk";
277 }
278
279 bool GetStartOnSystemStartup()
280 {
281     // check for Bitcoin.lnk
282     return boost::filesystem::exists(StartupShortcutPath());
283 }
284
285 bool SetStartOnSystemStartup(bool fAutoStart)
286 {
287     // If the shortcut exists already, remove it for updating
288     boost::filesystem::remove(StartupShortcutPath());
289
290     if (fAutoStart)
291     {
292         CoInitialize(NULL);
293
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));
299
300         if (SUCCEEDED(hres))
301         {
302             // Get the current executable path
303             TCHAR pszExePath[MAX_PATH];
304             GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
305
306             TCHAR pszArgs[5] = TEXT("-min");
307
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);
314
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));
320             if (SUCCEEDED(hres))
321             {
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);
327                 ppf->Release();
328                 psl->Release();
329                 CoUninitialize();
330                 return true;
331             }
332             psl->Release();
333         }
334         CoUninitialize();
335         return false;
336     }
337     return true;
338 }
339
340 #elif defined(LINUX)
341
342 // Follow the Desktop Application Autostart Spec:
343 //  http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
344
345 boost::filesystem::path static GetAutostartDir()
346 {
347     namespace fs = boost::filesystem;
348
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";
353     return fs::path();
354 }
355
356 boost::filesystem::path static GetAutostartFilePath()
357 {
358     return GetAutostartDir() / "novacoin.desktop";
359 }
360
361 bool GetStartOnSystemStartup()
362 {
363     boost::filesystem::ifstream optionFile(GetAutostartFilePath());
364     if (!optionFile.good())
365         return false;
366     // Scan through file for "Hidden=true":
367     std::string line;
368     while (!optionFile.eof())
369     {
370         getline(optionFile, line);
371         if (line.find("Hidden") != std::string::npos &&
372             line.find("true") != std::string::npos)
373             return false;
374     }
375     optionFile.close();
376
377     return true;
378 }
379
380 bool SetStartOnSystemStartup(bool fAutoStart)
381 {
382     if (!fAutoStart)
383         boost::filesystem::remove(GetAutostartFilePath());
384     else
385     {
386         char pszExePath[MAX_PATH+1];
387         memset(pszExePath, 0, sizeof(pszExePath));
388         if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
389             return false;
390
391         boost::filesystem::create_directories(GetAutostartDir());
392
393         boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
394         if (!optionFile.good())
395             return false;
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";
403         optionFile.close();
404     }
405     return true;
406 }
407 #else
408
409 // TODO: OSX startup stuff; see:
410 // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
411
412 bool GetStartOnSystemStartup() { return false; }
413 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
414
415 #endif
416
417 HelpMessageBox::HelpMessageBox(QWidget *parent) :
418     QMessageBox(parent)
419 {
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";
424
425     coreOptions = QString::fromStdString(HelpMessage());
426
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";
431
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);
437 }
438
439 void HelpMessageBox::printToConsole()
440 {
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());
444 }
445
446 void HelpMessageBox::showOrPrint()
447 {
448 #if defined(WIN32)
449         // On Windows, show a message box, as there is no stderr/stdout in windowed applications
450         exec();
451 #else
452         // On other operating systems, print help text to console
453         printToConsole();
454 #endif
455 }
456
457 } // namespace GUIUtil
458