update to 0.4 preview
[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     if(uri.scheme() != QString("bitcoin"))
81         return false;
82
83     SendCoinsRecipient rv;
84     rv.address = uri.path();
85     rv.amount = 0;
86     QList<QPair<QString, QString> > items = uri.queryItems();
87     for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
88     {
89         bool fShouldReturnFalse = false;
90         if (i->first.startsWith("req-"))
91         {
92             i->first.remove(0, 4);
93             fShouldReturnFalse = true;
94         }
95
96         if (i->first == "label")
97         {
98             rv.label = i->second;
99             fShouldReturnFalse = false;
100         }
101         else if (i->first == "amount")
102         {
103             if(!i->second.isEmpty())
104             {
105                 if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
106                 {
107                     return false;
108                 }
109             }
110             fShouldReturnFalse = false;
111         }
112
113         if (fShouldReturnFalse)
114             return false;
115     }
116     if(out)
117     {
118         *out = rv;
119     }
120     return true;
121 }
122
123 bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
124 {
125     // Convert bitcoin:// to bitcoin:
126     //
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://"))
130     {
131         uri.replace(0, 10, "bitcoin:");
132     }
133     QUrl uriInstance(uri);
134     return parseBitcoinURI(uriInstance, out);
135 }
136
137 QString HtmlEscape(const QString& str, bool fMultiLine)
138 {
139     QString escaped = Qt::escape(str);
140     if(fMultiLine)
141     {
142         escaped = escaped.replace("\n", "<br>\n");
143     }
144     return escaped;
145 }
146
147 QString HtmlEscape(const std::string& str, bool fMultiLine)
148 {
149     return HtmlEscape(QString::fromStdString(str), fMultiLine);
150 }
151
152 void copyEntryData(QAbstractItemView *view, int column, int role)
153 {
154     if(!view || !view->selectionModel())
155         return;
156     QModelIndexList selection = view->selectionModel()->selectedRows(column);
157
158     if(!selection.isEmpty())
159     {
160         // Copy first item
161         QApplication::clipboard()->setText(selection.at(0).data(role).toString());
162     }
163 }
164
165 QString getSaveFileName(QWidget *parent, const QString &caption,
166                                  const QString &dir,
167                                  const QString &filter,
168                                  QString *selectedSuffixOut)
169 {
170     QString selectedFilter;
171     QString myDir;
172     if(dir.isEmpty()) // Default to user documents location
173     {
174         myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
175     }
176     else
177     {
178         myDir = dir;
179     }
180     QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
181
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))
186     {
187         selectedSuffix = filter_re.cap(1);
188     }
189
190     /* Add suffix if needed */
191     QFileInfo info(result);
192     if(!result.isEmpty())
193     {
194         if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
195         {
196             /* No suffix specified, add selected suffix */
197             if(!result.endsWith("."))
198                 result.append(".");
199             result.append(selectedSuffix);
200         }
201     }
202
203     /* Return selected suffix if asked to */
204     if(selectedSuffixOut)
205     {
206         *selectedSuffixOut = selectedSuffix;
207     }
208     return result;
209 }
210
211 Qt::ConnectionType blockingGUIThreadConnection()
212 {
213     if(QThread::currentThread() != QCoreApplication::instance()->thread())
214     {
215         return Qt::BlockingQueuedConnection;
216     }
217     else
218     {
219         return Qt::DirectConnection;
220     }
221 }
222
223 bool checkPoint(const QPoint &p, const QWidget *w)
224 {
225     QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
226     if (!atW) return false;
227     return atW->topLevelWidget() == w;
228 }
229
230 bool isObscured(QWidget *w)
231 {
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));
237 }
238
239 void openDebugLogfile()
240 {
241     boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
242
243     /* Open debug.log with the associated application */
244     if (boost::filesystem::exists(pathDebug))
245         QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
246 }
247
248 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
249     QObject(parent), size_threshold(size_threshold)
250 {
251
252 }
253
254 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
255 {
256     if(evt->type() == QEvent::ToolTipChange)
257     {
258         QWidget *widget = static_cast<QWidget*>(obj);
259         QString tooltip = widget->toolTip();
260         if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
261         {
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);
266             return true;
267         }
268     }
269     return QObject::eventFilter(obj, evt);
270 }
271
272 #ifdef WIN32
273 boost::filesystem::path static StartupShortcutPath()
274 {
275     return GetSpecialFolderPath(CSIDL_STARTUP) / "NovaCoin.lnk";
276 }
277
278 bool GetStartOnSystemStartup()
279 {
280     // check for Bitcoin.lnk
281     return boost::filesystem::exists(StartupShortcutPath());
282 }
283
284 bool SetStartOnSystemStartup(bool fAutoStart)
285 {
286     // If the shortcut exists already, remove it for updating
287     boost::filesystem::remove(StartupShortcutPath());
288
289     if (fAutoStart)
290     {
291         CoInitialize(NULL);
292
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));
298
299         if (SUCCEEDED(hres))
300         {
301             // Get the current executable path
302             TCHAR pszExePath[MAX_PATH];
303             GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
304
305             TCHAR pszArgs[5] = TEXT("-min");
306
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);
313
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));
319             if (SUCCEEDED(hres))
320             {
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);
326                 ppf->Release();
327                 psl->Release();
328                 CoUninitialize();
329                 return true;
330             }
331             psl->Release();
332         }
333         CoUninitialize();
334         return false;
335     }
336     return true;
337 }
338
339 #elif defined(LINUX)
340
341 // Follow the Desktop Application Autostart Spec:
342 //  http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
343
344 boost::filesystem::path static GetAutostartDir()
345 {
346     namespace fs = boost::filesystem;
347
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";
352     return fs::path();
353 }
354
355 boost::filesystem::path static GetAutostartFilePath()
356 {
357     return GetAutostartDir() / "novacoin.desktop";
358 }
359
360 bool GetStartOnSystemStartup()
361 {
362     boost::filesystem::ifstream optionFile(GetAutostartFilePath());
363     if (!optionFile.good())
364         return false;
365     // Scan through file for "Hidden=true":
366     std::string line;
367     while (!optionFile.eof())
368     {
369         getline(optionFile, line);
370         if (line.find("Hidden") != std::string::npos &&
371             line.find("true") != std::string::npos)
372             return false;
373     }
374     optionFile.close();
375
376     return true;
377 }
378
379 bool SetStartOnSystemStartup(bool fAutoStart)
380 {
381     if (!fAutoStart)
382         boost::filesystem::remove(GetAutostartFilePath());
383     else
384     {
385         char pszExePath[MAX_PATH+1];
386         memset(pszExePath, 0, sizeof(pszExePath));
387         if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
388             return false;
389
390         boost::filesystem::create_directories(GetAutostartDir());
391
392         boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
393         if (!optionFile.good())
394             return false;
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";
402         optionFile.close();
403     }
404     return true;
405 }
406 #else
407
408 // TODO: OSX startup stuff; see:
409 // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
410
411 bool GetStartOnSystemStartup() { return false; }
412 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
413
414 #endif
415
416 HelpMessageBox::HelpMessageBox(QWidget *parent) :
417     QMessageBox(parent)
418 {
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";
423
424     coreOptions = QString::fromStdString(HelpMessage());
425
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";
430
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);
436 }
437
438 void HelpMessageBox::printToConsole()
439 {
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());
443 }
444
445 void HelpMessageBox::showOrPrint()
446 {
447 #if defined(WIN32)
448         // On Windows, show a message box, as there is no stderr/stdout in windowed applications
449         exec();
450 #else
451         // On other operating systems, print help text to console
452         printToConsole();
453 #endif
454 }
455
456 } // namespace GUIUtil
457