Feathercoin  0.5.0
P2P Digital Currency
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros
guiutil.cpp
Go to the documentation of this file.
1 #include <QApplication>
2 
3 #include "guiutil.h"
4 
6 #include "walletmodel.h"
7 #include "bitcoinunits.h"
8 
9 #include "util.h"
10 #include "init.h"
11 
12 #include <QDateTime>
13 #include <QDoubleValidator>
14 #include <QFont>
15 #include <QLineEdit>
16 #if QT_VERSION >= 0x050000
17 #include <QUrlQuery>
18 #else
19 #include <QUrl>
20 #endif
21 #include <QTextDocument> // for Qt::mightBeRichText
22 #include <QAbstractItemView>
23 #include <QClipboard>
24 #include <QFileDialog>
25 #include <QDesktopServices>
26 #include <QThread>
27 
28 #include <boost/filesystem.hpp>
29 #include <boost/filesystem/fstream.hpp>
30 
31 #ifdef WIN32
32 #ifdef _WIN32_WINNT
33 #undef _WIN32_WINNT
34 #endif
35 #define _WIN32_WINNT 0x0501
36 #ifdef _WIN32_IE
37 #undef _WIN32_IE
38 #endif
39 #define _WIN32_IE 0x0501
40 #define WIN32_LEAN_AND_MEAN 1
41 #ifndef NOMINMAX
42 #define NOMINMAX
43 #endif
44 #include "shlwapi.h"
45 #include "shlobj.h"
46 #include "shellapi.h"
47 #endif
48 
49 namespace GUIUtil {
50 
51 QString dateTimeStr(const QDateTime &date)
52 {
53  return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
54 }
55 
56 QString dateTimeStr(qint64 nTime)
57 {
58  return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
59 }
60 
62 {
63  QFont font("Monospace");
64  font.setStyleHint(QFont::TypeWriter);
65  return font;
66 }
67 
68 void setupAddressWidget(QLineEdit *widget, QWidget *parent)
69 {
70  widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
71  widget->setValidator(new BitcoinAddressValidator(parent));
72  widget->setFont(bitcoinAddressFont());
73 }
74 
75 void setupAmountWidget(QLineEdit *widget, QWidget *parent)
76 {
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);
82 }
83 
84 bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
85 {
86  // return if URI is not valid or is no bitcoin URI
87  if(!uri.isValid() || uri.scheme() != QString("feathercoin"))
88  return false;
89 
91  rv.address = uri.path();
92  rv.amount = 0;
93 
94 #if QT_VERSION < 0x050000
95  QList<QPair<QString, QString> > items = uri.queryItems();
96 #else
97  QUrlQuery uriQuery(uri);
98  QList<QPair<QString, QString> > items = uriQuery.queryItems();
99 #endif
100  for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
101  {
102  bool fShouldReturnFalse = false;
103  if (i->first.startsWith("req-"))
104  {
105  i->first.remove(0, 4);
106  fShouldReturnFalse = true;
107  }
108 
109  if (i->first == "label")
110  {
111  rv.label = i->second;
112  fShouldReturnFalse = false;
113  }
114  else if (i->first == "amount")
115  {
116  if(!i->second.isEmpty())
117  {
118  if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
119  {
120  return false;
121  }
122  }
123  fShouldReturnFalse = false;
124  }
125 
126  if (fShouldReturnFalse)
127  return false;
128  }
129  if(out)
130  {
131  *out = rv;
132  }
133  return true;
134 }
135 
136 bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
137 {
138  // Convert bitcoin:// to bitcoin:
139  //
140  // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
141  // which will lower-case it (and thus invalidate the address).
142  if(uri.startsWith("feathercoin://"))
143  {
144  uri.replace(0, 14, "feathercoin:");
145  }
146  QUrl uriInstance(uri);
147  return parseBitcoinURI(uriInstance, out);
148 }
149 
150 QString HtmlEscape(const QString& str, bool fMultiLine)
151 {
152 #if QT_VERSION < 0x050000
153  QString escaped = Qt::escape(str);
154 #else
155  QString escaped = str.toHtmlEscaped();
156 #endif
157  if(fMultiLine)
158  {
159  escaped = escaped.replace("\n", "<br>\n");
160  }
161  return escaped;
162 }
163 
164 QString HtmlEscape(const std::string& str, bool fMultiLine)
165 {
166  return HtmlEscape(QString::fromStdString(str), fMultiLine);
167 }
168 
169 void copyEntryData(QAbstractItemView *view, int column, int role)
170 {
171  if(!view || !view->selectionModel())
172  return;
173  QModelIndexList selection = view->selectionModel()->selectedRows(column);
174 
175  if(!selection.isEmpty())
176  {
177  // Copy first item (global clipboard)
178  QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard);
179  // Copy first item (global mouse selection for e.g. X11 - NOP on Windows)
180  QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection);
181  }
182 }
183 
184 void setClipboard(const QString& str)
185 {
186  QApplication::clipboard()->setText(str, QClipboard::Clipboard);
187  QApplication::clipboard()->setText(str, QClipboard::Selection);
188 }
189 
190 QString getSaveFileName(QWidget *parent, const QString &caption,
191  const QString &dir,
192  const QString &filter,
193  QString *selectedSuffixOut)
194 {
195  QString selectedFilter;
196  QString myDir;
197  if(dir.isEmpty()) // Default to user documents location
198  {
199 #if QT_VERSION < 0x050000
200  myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
201 #else
202  myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
203 #endif
204  }
205  else
206  {
207  myDir = dir;
208  }
209  QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
210 
211  /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
212  QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
213  QString selectedSuffix;
214  if(filter_re.exactMatch(selectedFilter))
215  {
216  selectedSuffix = filter_re.cap(1);
217  }
218 
219  /* Add suffix if needed */
220  QFileInfo info(result);
221  if(!result.isEmpty())
222  {
223  if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
224  {
225  /* No suffix specified, add selected suffix */
226  if(!result.endsWith("."))
227  result.append(".");
228  result.append(selectedSuffix);
229  }
230  }
231 
232  /* Return selected suffix if asked to */
233  if(selectedSuffixOut)
234  {
235  *selectedSuffixOut = selectedSuffix;
236  }
237  return result;
238 }
239 
240 Qt::ConnectionType blockingGUIThreadConnection()
241 {
242  if(QThread::currentThread() != qApp->thread())
243  {
244  return Qt::BlockingQueuedConnection;
245  }
246  else
247  {
248  return Qt::DirectConnection;
249  }
250 }
251 
252 bool checkPoint(const QPoint &p, const QWidget *w)
253 {
254  QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
255  if (!atW) return false;
256  return atW->topLevelWidget() == w;
257 }
258 
259 bool isObscured(QWidget *w)
260 {
261  return !(checkPoint(QPoint(0, 0), w)
262  && checkPoint(QPoint(w->width() - 1, 0), w)
263  && checkPoint(QPoint(0, w->height() - 1), w)
264  && checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
265  && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
266 }
267 
269 {
270  boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
271 
272  /* Open debug.log with the associated application */
273  if (boost::filesystem::exists(pathDebug))
274  QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
275 }
276 
277 ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
278  QObject(parent), size_threshold(size_threshold)
279 {
280 
281 }
282 
283 bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
284 {
285  if(evt->type() == QEvent::ToolTipChange)
286  {
287  QWidget *widget = static_cast<QWidget*>(obj);
288  QString tooltip = widget->toolTip();
289  if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
290  {
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);
294  widget->setToolTip(tooltip);
295  return true;
296  }
297  }
298  return QObject::eventFilter(obj, evt);
299 }
300 
301 #ifdef WIN32
302 boost::filesystem::path static StartupShortcutPath()
303 {
304  return GetSpecialFolderPath(CSIDL_STARTUP) / "Feathercoin.lnk";
305 }
306 
308 {
309  // check for Bitcoin.lnk
310  return boost::filesystem::exists(StartupShortcutPath());
311 }
312 
313 bool SetStartOnSystemStartup(bool fAutoStart)
314 {
315  // If the shortcut exists already, remove it for updating
316  boost::filesystem::remove(StartupShortcutPath());
317 
318  if (fAutoStart)
319  {
320  CoInitialize(NULL);
321 
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));
327 
328  if (SUCCEEDED(hres))
329  {
330  // Get the current executable path
331  TCHAR pszExePath[MAX_PATH];
332  GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
333 
334  TCHAR pszArgs[5] = TEXT("-min");
335 
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);
342 
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));
348  if (SUCCEEDED(hres))
349  {
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);
355  ppf->Release();
356  psl->Release();
357  CoUninitialize();
358  return true;
359  }
360  psl->Release();
361  }
362  CoUninitialize();
363  return false;
364  }
365  return true;
366 }
367 
368 #elif defined(LINUX)
369 
370 // Follow the Desktop Application Autostart Spec:
371 // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
372 
373 boost::filesystem::path static GetAutostartDir()
374 {
375  namespace fs = boost::filesystem;
376 
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";
381  return fs::path();
382 }
383 
384 boost::filesystem::path static GetAutostartFilePath()
385 {
386  return GetAutostartDir() / "feathercoin.desktop";
387 }
388 
390 {
391  boost::filesystem::ifstream optionFile(GetAutostartFilePath());
392  if (!optionFile.good())
393  return false;
394  // Scan through file for "Hidden=true":
395  std::string line;
396  while (!optionFile.eof())
397  {
398  getline(optionFile, line);
399  if (line.find("Hidden") != std::string::npos &&
400  line.find("true") != std::string::npos)
401  return false;
402  }
403  optionFile.close();
404 
405  return true;
406 }
407 
408 bool SetStartOnSystemStartup(bool fAutoStart)
409 {
410  if (!fAutoStart)
411  boost::filesystem::remove(GetAutostartFilePath());
412  else
413  {
414  char pszExePath[MAX_PATH+1];
415  memset(pszExePath, 0, sizeof(pszExePath));
416  if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
417  return false;
418 
419  boost::filesystem::create_directories(GetAutostartDir());
420 
421  boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
422  if (!optionFile.good())
423  return false;
424  // Write a bitcoin.desktop file to the autostart directory:
425  optionFile << "[Desktop Entry]\n";
426  optionFile << "Type=Application\n";
427  optionFile << "Name=Feathercoin\n";
428  optionFile << "Exec=" << pszExePath << " -min\n";
429  optionFile << "Terminal=false\n";
430  optionFile << "Hidden=false\n";
431  optionFile.close();
432  }
433  return true;
434 }
435 
436 #elif defined(Q_OS_MAC)
437 // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
438 
439 #include <CoreFoundation/CoreFoundation.h>
440 #include <CoreServices/CoreServices.h>
441 
442 LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);
443 LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)
444 {
445  // loop through the list of startup items and try to find the bitcoin app
446  CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL);
447  for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
448  LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
449  UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
450  CFURLRef currentItemURL = NULL;
451  LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL);
452  if(currentItemURL && CFEqual(currentItemURL, findUrl)) {
453  // found
454  CFRelease(currentItemURL);
455  return item;
456  }
457  if(currentItemURL) {
458  CFRelease(currentItemURL);
459  }
460  }
461  return NULL;
462 }
463 
465 {
466  CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
467  LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
468  LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
469  return !!foundItem; // return boolified object
470 }
471 
472 bool SetStartOnSystemStartup(bool fAutoStart)
473 {
474  CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
475  LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
476  LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
477 
478  if(fAutoStart && !foundItem) {
479  // add bitcoin app to startup item list
480  LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL);
481  }
482  else if(!fAutoStart && foundItem) {
483  // remove item
484  LSSharedFileListItemRemove(loginItems, foundItem);
485  }
486  return true;
487 }
488 #else
489 
490 bool GetStartOnSystemStartup() { return false; }
491 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
492 
493 #endif
494 
496  QMessageBox(parent)
497 {
498  header = tr("Feathercoin-Qt") + " " + tr("version") + " " +
499  QString::fromStdString(FormatFullVersion()) + "\n\n" +
500  tr("Usage:") + "\n" +
501  " feathercoin-qt [" + tr("command-line options") + "] " + "\n";
502 
503  coreOptions = QString::fromStdString(HelpMessage());
504 
505  uiOptions = tr("UI options") + ":\n" +
506  " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
507  " -min " + tr("Start minimized") + "\n" +
508  " -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
509 
510  setWindowTitle(tr("Feathercoin-Qt"));
511  setTextFormat(Qt::PlainText);
512  // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
513  setText(header + QString(QChar(0x2003)).repeated(50));
514  setDetailedText(coreOptions + "\n" + uiOptions);
515 }
516 
518 {
519  // On other operating systems, the expected action is to print the message to the console.
520  QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
521  fprintf(stdout, "%s", strUsage.toStdString().c_str());
522 }
523 
525 {
526 #if defined(WIN32)
527  // On Windows, show a message box, as there is no stderr/stdout in windowed applications
528  exec();
529 #else
530  // On other operating systems, print help text to console
531  printToConsole();
532 #endif
533 }
534 
535 } // namespace GUIUtil
const boost::filesystem::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:1060
void openDebugLogfile()
Definition: guiutil.cpp:268
Utility functions used by the Bitcoin Qt UI.
Definition: guiutil.cpp:49
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:75
QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut)
Get save filename, mimics QFileDialog::getSaveFileName, except that it appends a default suffix when ...
Definition: guiutil.cpp:190
HelpMessageBox(QWidget *parent=0)
Definition: guiutil.cpp:495
QString dateTimeStr(const QDateTime &date)
Definition: guiutil.cpp:51
Qt::ConnectionType blockingGUIThreadConnection()
Get connection type to call object slot in GUI thread with invokeMethod.
Definition: guiutil.cpp:240
bool GetStartOnSystemStartup()
Definition: guiutil.cpp:490
ToolTipToRichTextFilter(int size_threshold, QObject *parent=0)
Definition: guiutil.cpp:277
QString HtmlEscape(const QString &str, bool fMultiLine)
Definition: guiutil.cpp:150
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
Definition: guiutil.cpp:68
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
Definition: guiutil.cpp:84
Base58 entry widget validator.
bool isObscured(QWidget *w)
Definition: guiutil.cpp:259
bool eventFilter(QObject *obj, QEvent *evt)
Definition: guiutil.cpp:283
void setClipboard(const QString &str)
Definition: guiutil.cpp:184
#define MAX_PATH
Definition: util.h:103
void printToConsole()
Print help message to console.
Definition: guiutil.cpp:517
void showOrPrint()
Show message box or print help message to standard output, based on operating system.
Definition: guiutil.cpp:524
string FormatFullVersion()
Definition: util.cpp:1404
static bool parse(int unit, const QString &value, qint64 *val_out)
Parse string to coin amount.
bool checkPoint(const QPoint &p, const QWidget *w)
Definition: guiutil.cpp:252
bool SetStartOnSystemStartup(bool fAutoStart)
Definition: guiutil.cpp:491
std::string HelpMessage()
Definition: init.cpp:299
void copyEntryData(QAbstractItemView *view, int column, int role)
Copy a field of the currently selected entry of a view to the clipboard.
Definition: guiutil.cpp:169
QFont bitcoinAddressFont()
Definition: guiutil.cpp:61