MythTV  master
mythcontext.cpp
Go to the documentation of this file.
1 #include <QCoreApplication>
2 #include <QDir>
3 #include <QFileInfo>
4 #include <QDebug>
5 #include <QMutex>
6 #include <QDateTime>
7 #include <QTcpSocket>
8 #include <QEventLoop>
9 
10 #ifdef Q_OS_ANDROID
11 #include <QtAndroidExtras>
12 #endif
13 
14 #include <cmath>
15 #include <iostream>
16 
17 #include <queue>
18 #include <algorithm>
19 #include <thread>
20 
21 using namespace std;
22 
23 #include "config.h"
24 #include "mythcontext.h"
25 #include "exitcodes.h"
26 #include "mythdate.h"
27 #include "remotefile.h"
28 #include "backendselect.h"
29 #include "dbsettings.h"
30 #include "langsettings.h"
31 #include "mythtranslation.h"
32 #include "mythxdisplay.h"
33 #include "mythevent.h"
34 #include "dbutil.h"
35 #include "DisplayRes.h"
36 #include "mythmediamonitor.h"
37 
38 #include "mythdb.h"
39 #include "mythdirs.h"
40 #include "mythversion.h"
41 #include "mythdialogbox.h"
42 #include "mythmainwindow.h"
43 #include "mythuihelper.h"
44 #include "mythimage.h"
45 #include "mythxmlclient.h"
46 #include "upnp.h"
47 #include "mythlogging.h"
48 #include "mythsystemlegacy.h"
49 #include "mythmiscutil.h"
50 
51 #include "mythplugin.h"
52 #include "portchecker.h"
53 #include "guistartup.h"
54 
55 #include <unistd.h> // for usleep(), gethostname
56 
57 #ifdef _WIN32
58 #include "compat.h"
59 #endif
60 
61 #define LOC QString("MythContext: ")
62 
64 
65 static const QString _Location = "MythContext";
66 
67 class MythContextPrivate : public QObject
68 {
69  friend class MythContextSlotHandler;
70 
71  public:
74 
75  bool Init (const bool gui,
76  const bool prompt, const bool noPrompt,
77  const bool ignoreDB);
78  bool FindDatabase(const bool prompt, const bool noPrompt);
79 
80  void TempMainWindow(bool languagePrompt = true);
81  void EndTempWindow(void);
82 
83  bool LoadDatabaseSettings(void);
84  bool SaveDatabaseParams(const DatabaseParams &params, bool force);
85 
86  bool PromptForDatabaseParams(const QString &error);
87  QString TestDBconnection(bool prompt=true);
88  void SilenceDBerrors(void);
89  void EnableDBerrors(void);
90  void ResetDatabase(void);
91 
92  int ChooseBackend(const QString &error);
93  int UPnPautoconf(const int milliSeconds = 2000);
94  bool DefaultUPnP(QString &error);
95  bool UPnPconnect(const DeviceLocation *device, const QString &PIN);
96  void ShowGuiStartup(void);
97  bool checkPort(QString &host, int port, int wakeupTime);
98  void processEvents(void);
99  bool saveSettingsCache(void);
100  void loadSettingsCacheOverride(void);
101  void clearSettingsCacheOverride(void);
102 
103 
104  protected:
105  bool event(QEvent*);
106 
107  void ShowConnectionFailurePopup(bool persistent);
108  void HideConnectionFailurePopup(void);
109 
110  void ShowVersionMismatchPopup(uint remoteVersion);
111 
112  public slots:
113  void OnCloseDialog();
114 
115  public:
117 
118  bool m_gui;
119 
121 
123  QString m_DBhostCp;
124 
126 
128 
132  QEventLoop *m_loop;
135 
136  private:
139  QDateTime m_lastCheck;
140  QTcpSocket *m_socket;
141  static const QString settingsToSave[];
142 };
143 
144 static void exec_program_cb(const QString &cmd)
145 {
146  myth_system(cmd);
147 }
148 
149 static void exec_program_tv_cb(const QString &cmd)
150 {
151  QString s = cmd;
152  QStringList tokens = cmd.simplified().split(" ");
153  QStringList strlist;
154 
155  bool cardidok;
156  int wantcardid = tokens[0].toInt(&cardidok, 10);
157 
158  if (cardidok && wantcardid > 0)
159  {
160  strlist << QString("LOCK_TUNER %1").arg(wantcardid);
161  s = s.replace(0, tokens[0].length() + 1, "");
162  }
163  else
164  strlist << "LOCK_TUNER";
165 
167  int cardid = strlist[0].toInt();
168 
169  if (cardid >= 0)
170  {
171  s = s.sprintf(qPrintable(s),
172  qPrintable(strlist[1]),
173  qPrintable(strlist[2]),
174  qPrintable(strlist[3]));
175 
176  myth_system(s);
177 
178  strlist = QStringList(QString("FREE_TUNER %1").arg(cardid));
180  QString ret = strlist[0];
181  }
182  else
183  {
184  QString label;
185 
186  if (cardidok)
187  {
188  if (cardid == -1)
189  label = QObject::tr("Could not find specified tuner (%1).")
190  .arg(wantcardid);
191  else
192  label = QObject::tr("Specified tuner (%1) is already in use.")
193  .arg(wantcardid);
194  }
195  else
196  {
197  label = QObject::tr("All tuners are currently in use. If you want "
198  "to watch TV, you can cancel one of the "
199  "in-progress recordings from the delete menu");
200  }
201 
202  LOG(VB_GENERAL, LOG_ALERT, QString("exec_program_tv: ") + label);
203 
204  ShowOkPopup(label);
205  }
206 }
207 
208 static void configplugin_cb(const QString &cmd)
209 {
211  if (!pmanager)
212  return;
213 
214  if (GetNotificationCenter() && pmanager->config_plugin(cmd.trimmed()))
215  {
217  QObject::tr("Failed to configure plugin"));
218  }
219 }
220 
221 static void plugin_cb(const QString &cmd)
222 {
224  if (!pmanager)
225  return;
226 
227  if (GetNotificationCenter() && pmanager->run_plugin(cmd.trimmed()))
228  {
229  ShowNotificationError(QObject::tr("Plugin failure"),
230  _Location,
231  QObject::tr("%1 failed to run for some reason").arg(cmd));
232  }
233 }
234 
235 static void eject_cb(void)
236 {
238 }
239 
241  : parent(lparent),
242  m_gui(false),
243  m_pConfig(NULL),
244  disableeventpopup(false),
245  m_ui(NULL),
246  m_sh(new MythContextSlotHandler(this)),
247  m_guiStartup(0),
248  needsBackend(false),
249  m_settingsCacheDirty(false),
250  MBEversionPopup(NULL),
251  m_registration(-1),
252  m_socket(0)
253 {
254  m_loop = new QEventLoop(this);
256 }
257 
259 {
260  if (m_pConfig)
261  delete m_pConfig;
263  {
265  }
266 
267  if (m_loop)
268  {
269  delete m_loop;
270  }
271 
272  if (m_ui)
273  DestroyMythUI();
274  if (m_sh)
275  m_sh->deleteLater();
276 }
277 
288 void MythContextPrivate::TempMainWindow(bool languagePrompt)
289 {
290  if (HasMythMainWindow())
291  return;
292 
293  SilenceDBerrors();
294 
296 
297 #ifdef Q_OS_MAC
298  // Qt 4.4 has window-focus problems
299  gCoreContext->OverrideSettingForSession("RunFrontendInWindow", "1");
300 #endif
301  GetMythUI()->Init();
302  GetMythUI()->LoadQtConfig();
303 
304  MythMainWindow *mainWindow = MythMainWindow::getMainWindow(false);
305  mainWindow->Init();
306 
307  if (languagePrompt)
308  {
309  // ask user for language settings
311  MythTranslation::load("mythfrontend");
312  }
313 }
314 
316 {
317  if (HasMythMainWindow())
318  {
320  {
322  if (mainStack) {
323  mainStack->PopScreen(m_guiStartup, false);
324  m_guiStartup = 0;
325  }
326  }
327  }
328  EnableDBerrors();
329 }
330 
340 bool MythContextPrivate::checkPort(QString &host, int port, int timeLimit)
341 {
342  PortChecker checker;
343  if (m_guiStartup)
344  QObject::connect(m_guiStartup,SIGNAL(cancelPortCheck()),&checker,SLOT(cancelPortCheck()));
345  return checker.checkPort(host, port, timeLimit*1000);
346 }
347 
348 
349 bool MythContextPrivate::Init(const bool gui,
350  const bool promptForBackend,
351  const bool noPrompt,
352  const bool ignoreDB)
353 {
354  gCoreContext->GetDB()->IgnoreDatabase(ignoreDB);
355  m_gui = gui;
356 
357  if (gCoreContext->IsFrontend())
358  needsBackend = true;
359 
360  // We don't have a database yet, so lets use the config.xml file.
361  m_pConfig = new XmlConfiguration("config.xml");
362 
363  // Creates screen saver control if we will have a GUI
364  if (gui)
365  m_ui = GetMythUI();
366 
367  // ---- database connection stuff ----
368 
369  if (!ignoreDB && !FindDatabase(promptForBackend, noPrompt))
370  {
371  EndTempWindow();
372  return false;
373  }
374 
375  // ---- keep all DB-using stuff below this line ----
376 
377  // Prompt for language if this is a first time install and
378  // we didn't already do so.
379  if (m_gui && !gCoreContext->GetDB()->HaveSchema())
380  {
381  TempMainWindow(false);
383  MythTranslation::load("mythfrontend");
384  }
387 
388  // Close GUI Startup Window.
389  if (m_guiStartup) {
391  if (mainStack)
392  mainStack->PopScreen(m_guiStartup, false);
393  m_guiStartup=0;
394  }
395  EndTempWindow();
396 
397  if (gui)
398  {
403  cbs.plugin = plugin_cb;
404  cbs.eject = eject_cb;
405 
406  m_ui->Init(cbs);
407  }
408 
409  return true;
410 }
411 
424 bool MythContextPrivate::FindDatabase(bool prompt, bool noAutodetect)
425 {
426  // We can only prompt if autodiscovery is enabled..
427  bool manualSelect = prompt && !noAutodetect;
428 
429  QString failure;
430 
431  // 1. Either load config.xml or use sensible "localhost" defaults:
432  bool loaded = LoadDatabaseSettings();
433  DatabaseParams dbParamsFromFile = m_DBparams;
434 
435  // In addition to the UI chooser, we can also try to autoSelect later,
436  // but only if we're not doing manualSelect and there was no
437  // valid config.xml
438  bool autoSelect = !manualSelect && !loaded && !noAutodetect;
439 
440  // 2. If the user isn't forcing up the chooser UI, look for a default
441  // backend in config.xml, then test DB settings we've got so far:
442  if (!manualSelect)
443  {
444  // config.xml may contain a backend host UUID and PIN.
445  // If so, try to AutoDiscover UPnP server, and use its DB settings:
446 
447  if (DefaultUPnP(failure)) // Probably a valid backend,
448  autoSelect = manualSelect = false; // so disable any further UPnP
449  else
450  if (failure.length())
451  LOG(VB_GENERAL, LOG_ALERT, failure);
452 
453  failure = TestDBconnection(loaded);
454  if (failure.isEmpty())
455  goto DBfound;
457  return false;
459  autoSelect=true;
460  }
461 
462  // 3. Try to automatically find the single backend:
463  if (autoSelect)
464  {
465  int count = UPnPautoconf();
466 
467  if (count == 0)
468  failure = QObject::tr("No UPnP backends found", "Backend Setup");
469 
470  if (count == 1)
471  {
472  failure = TestDBconnection();
473  if (failure.isEmpty())
474  goto DBfound;
476  return false;
477  }
478 
479  // Multiple BEs, or needs PIN.
480  manualSelect |= (count > 1 || count == -1);
481  // Search requested
483  manualSelect=true;
484  }
485 
486  manualSelect &= m_gui; // no interactive command-line chooser yet
487 
488  // Queries the user for the DB info
489  do
490  {
491  if (manualSelect)
492  {
493  // Get the user to select a backend from a possible list:
495  ChooseBackend(failure);
496  switch (d)
497  {
499  break;
501  manualSelect = false;
502  break;
504  goto NoDBfound;
505  }
506  }
507 
508  if (!manualSelect)
509  {
510  if (!PromptForDatabaseParams(failure))
511  goto NoDBfound;
512  }
513  failure = TestDBconnection();
514  if (!failure.isEmpty())
515  LOG(VB_GENERAL, LOG_ALERT, failure);
517  return false;
519  manualSelect=true;
521  manualSelect=false;
522  }
523  while (!failure.isEmpty());
524 
525 DBfound:
526  LOG(VB_GENERAL, LOG_DEBUG, "FindDatabase() - Success!");
527  // If we got the database from UPNP then the wakeup settings are lost.
528  // Restore them.
529  m_DBparams.wolEnabled = dbParamsFromFile.wolEnabled;
530  m_DBparams.wolReconnect = dbParamsFromFile.wolReconnect;
531  m_DBparams.wolRetry = dbParamsFromFile.wolRetry;
532  m_DBparams.wolCommand = dbParamsFromFile.wolCommand;
533 
535  !loaded || m_DBparams.forceSave ||
536  dbParamsFromFile != m_DBparams);
537  EnableDBerrors();
538  ResetDatabase();
539  return true;
540 
541 NoDBfound:
542  LOG(VB_GENERAL, LOG_DEBUG, "FindDatabase() - failed");
543  return false;
544 }
545 
550 {
551  // try new format first
553 
554  m_DBparams.localHostName = m_pConfig->GetValue("LocalHostName", "");
555  m_DBparams.dbHostPing = m_pConfig->GetValue(kDefaultDB + "PingHost", true);
557  m_DBparams.dbUserName = m_pConfig->GetValue(kDefaultDB + "UserName", "");
558  m_DBparams.dbPassword = m_pConfig->GetValue(kDefaultDB + "Password", "");
559  m_DBparams.dbName = m_pConfig->GetValue(kDefaultDB + "DatabaseName", "");
561 
563  m_pConfig->GetValue(kDefaultWOL + "Enabled", false);
565  m_pConfig->GetValue(kDefaultWOL + "SQLReconnectWaitTime", 0);
567  m_pConfig->GetValue(kDefaultWOL + "SQLConnectRetry", 5);
569  m_pConfig->GetValue(kDefaultWOL + "Command", "");
570 
571  bool ok = m_DBparams.IsValid("config.xml");
572  if (!ok) // if new format fails, try legacy format
573  {
576  kDefaultMFE + "DBHostName", "");
578  kDefaultMFE + "DBUserName", "");
580  kDefaultMFE + "DBPassword", "");
582  kDefaultMFE + "DBName", "");
584  kDefaultMFE + "DBPort", 0);
585  m_DBparams.forceSave = true;
586  ok = m_DBparams.IsValid("config.xml");
587  }
588  if (!ok)
590 
591  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
592 
594  if (hostname.isEmpty() ||
595  hostname == "my-unique-identifier-goes-here")
596  {
597  char localhostname[1024];
598  if (gethostname(localhostname, 1024))
599  {
600  LOG(VB_GENERAL, LOG_ALERT,
601  "MCP: Error, could not determine host name." + ENO);
602  localhostname[0] = '\0';
603  }
604 #ifdef Q_OS_ANDROID
605 #define ANDROID_EXCEPTION_CHECK \
606  if (env->ExceptionCheck()) { \
607  env->ExceptionClear(); \
608  exception=true; \
609  }
610  if (strcmp(localhostname, "localhost") == 0
611  || localhostname[0] == '\0')
612  {
613  hostname = "android";
614  bool exception=false;
615  QAndroidJniEnvironment env;
616  QAndroidJniObject myID = QAndroidJniObject::fromString("android_id");
617  QAndroidJniObject activity = QtAndroid::androidActivity();
618  ANDROID_EXCEPTION_CHECK;
619  QAndroidJniObject appctx = activity.callObjectMethod
620  ("getApplicationContext","()Landroid/content/Context;");
621  ANDROID_EXCEPTION_CHECK;
622  QAndroidJniObject contentR = appctx.callObjectMethod
623  ("getContentResolver", "()Landroid/content/ContentResolver;");
624  ANDROID_EXCEPTION_CHECK;
625  QAndroidJniObject androidId = QAndroidJniObject::callStaticObjectMethod
626  ("android/provider/Settings$Secure","getString",
627  "(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;",
628  contentR.object<jobject>(),
629  myID.object<jstring>());
630  ANDROID_EXCEPTION_CHECK;
631  if (exception)
632  LOG(VB_GENERAL, LOG_ALERT,
633  "Java exception looking for android id");
634  else
635  hostname = QString("android-%1").arg(androidId.toString());
636  }
637  else
638  hostname = localhostname;
639 #else
640  hostname = localhostname;
641 #endif
642  LOG(VB_GENERAL, LOG_NOTICE, "Empty LocalHostName.");
643  }
644  else
645  {
646  m_DBparams.localEnabled = true;
647  }
648 
649  LOG(VB_GENERAL, LOG_INFO, QString("Using localhost value of %1")
650  .arg(hostname));
651  gCoreContext->SetLocalHostname(hostname);
652 
653  return ok;
654 }
655 
657  const DatabaseParams &params, bool force)
658 {
659  bool ret = true;
660 
661  // only rewrite file if it has changed
662  if (params != m_DBparams || force)
663  {
665  "LocalHostName", params.localHostName);
666 
668  kDefaultDB + "PingHost", params.dbHostPing);
669 
670  // If dbHostName is an IPV6 address with scope,
671  // remove the scope. Unescaped % signs are an
672  // xml violation
673  QString dbHostName(params.dbHostName);
674  QHostAddress addr;
675  if (addr.setAddress(dbHostName))
676  {
677  addr.setScopeId(QString());
678  dbHostName = addr.toString();
679  }
681  kDefaultDB + "Host", dbHostName);
683  kDefaultDB + "UserName", params.dbUserName);
685  kDefaultDB + "Password", params.dbPassword);
687  kDefaultDB + "DatabaseName", params.dbName);
689  kDefaultDB + "Port", params.dbPort);
690 
692  kDefaultWOL + "Enabled", params.wolEnabled);
694  kDefaultWOL + "SQLReconnectWaitTime", params.wolReconnect);
696  kDefaultWOL + "SQLConnectRetry", params.wolRetry);
698  kDefaultWOL + "Command", params.wolCommand);
699 
700  // clear out any legacy nodes..
701  m_pConfig->ClearValue(kDefaultMFE + "DBHostName");
702  m_pConfig->ClearValue(kDefaultMFE + "DBUserName");
703  m_pConfig->ClearValue(kDefaultMFE + "DBPassword");
704  m_pConfig->ClearValue(kDefaultMFE + "DBName");
705  m_pConfig->ClearValue(kDefaultMFE + "DBPort");
706  m_pConfig->ClearValue(kDefaultMFE + "DBHostPing");
707 
708  // actually save the file
709  m_pConfig->Save();
710 
711  // Save the new settings:
712  m_DBparams = params;
713  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
714 
715  // If database has changed, force its use:
716  ResetDatabase();
717  }
718  return ret;
719 }
720 
722 {
723  if (d && d->m_loop
724  && d->m_loop->isRunning())
725  d->m_loop->exit();
726 }
727 
728 
730 {
731  bool accepted = false;
732  if (m_gui)
733  {
734  TempMainWindow();
735 
736  // Tell the user what went wrong:
737  if (error.length())
738  ShowOkPopup(error);
739 
740  // ask user for database parameters
741 
742  EnableDBerrors();
744  DatabaseSettings *dbsetting = new DatabaseSettings();
745  StandardSettingDialog *ssd =
746  new StandardSettingDialog(mainStack, "databasesettings",
747  dbsetting);
748  if (ssd->Create())
749  {
750  mainStack->AddScreen(ssd);
751  connect(dbsetting, &DatabaseSettings::isClosing,
753  if (!m_loop->isRunning())
754  m_loop->exec();
755  }
756  else
757  delete ssd;
758  SilenceDBerrors();
759  EndTempWindow();
760  accepted = true;
761  }
762  else
763  {
765  QString response;
766  std::this_thread::sleep_for(std::chrono::seconds(1));
767  // give user chance to skip config
768  cout << endl << error.toLocal8Bit().constData() << endl << endl;
769  response = getResponse("Would you like to configure the database "
770  "connection now?",
771  "no");
772  if (!response.startsWith('y', Qt::CaseInsensitive))
773  return false;
774 
775  params.dbHostName = getResponse("Database host name:",
776  params.dbHostName);
777  response = getResponse("Should I test connectivity to this host "
778  "using the ping command?", "yes");
779  params.dbHostPing = response.startsWith('y', Qt::CaseInsensitive);
780 
781  params.dbPort = intResponse("Database non-default port:",
782  params.dbPort);
783  params.dbName = getResponse("Database name:",
784  params.dbName);
785  params.dbUserName = getResponse("Database user name:",
786  params.dbUserName);
787  params.dbPassword = getResponse("Database password:",
788  params.dbPassword);
789 
790  params.localHostName = getResponse("Unique identifier for this machine "
791  "(if empty, the local host name "
792  "will be used):",
793  params.localHostName);
794  params.localEnabled = !params.localHostName.isEmpty();
795 
796  response = getResponse("Would you like to use Wake-On-LAN to retry "
797  "database connections?",
798  (params.wolEnabled ? "yes" : "no"));
799  params.wolEnabled = response.startsWith('y', Qt::CaseInsensitive);
800 
801  if (params.wolEnabled)
802  {
803  params.wolReconnect = intResponse("Seconds to wait for "
804  "reconnection:",
805  params.wolReconnect);
806  params.wolRetry = intResponse("Number of times to retry:",
807  params.wolRetry);
808  params.wolCommand = getResponse("Command to use to wake server:",
809  params.wolCommand);
810  }
811 
812  accepted = parent->SaveDatabaseParams(params);
813  }
814  return accepted;
815 }
816 
823 {
824  QString err;
825  QString host;
826 
827  // Jan 20, 2017
828  // Changed to use port check instead of ping
829 
830  int port = 0;
831 
832  // 1 = db awake, 2 = db listening, 3 = db connects,
833  // 4 = backend awake, 5 = backend listening
834  // 9 = all ok, 10 = quit
835 
836  enum startupStates {
837  st_start = 0,
838  st_dbAwake = 1,
839  st_dbStarted = 2,
840  st_dbConnects = 3,
841  st_beWOL = 4,
842  st_beAwake = 5,
843  st_success = 6
844  } startupState = st_start;
845 
846  static const QString guiStatuses[7] =
847  {"start","dbAwake","dbStarted","dbConnects","beWOL","beAwake",
848  "success" };
849 
850  do
851  {
852  if (m_DBparams.dbHostName.isNull() && m_DBhostCp.length())
853  host = m_DBhostCp;
854  else
855  host = m_DBparams.dbHostName;
856  port = m_DBparams.dbPort;
857  if (port == 0)
858  port = 3306;
859  int wakeupTime = 3;
860  int attempts = 11;
861  if (m_DBparams.wolEnabled) {
862  wakeupTime = m_DBparams.wolReconnect;
863  attempts = m_DBparams.wolRetry + 1;
864  startupState = st_start;
865  }
866  else
867  startupState = st_dbAwake;
868  if (attempts < 6)
869  attempts = 6;
870  if (!prompt)
871  attempts=1;
872  if (wakeupTime < 5)
873  wakeupTime = 5;
874 
875  int progressTotal = wakeupTime * attempts;
876 
878  m_guiStartup->setTotal(progressTotal);
879 
880  QString beWOLCmd = QString();
881  QString backendIP = QString();
882  int backendPort = 0;
883  QString masterserver;
884 
885  for (int attempt = 0;
886  attempt < attempts && startupState != st_success;
887  ++attempt)
888  {
889  // The first time do everything with minimum timeout and
890  // no GUI, for the normal case where all is OK
891  // After that show the GUI (if this is a GUI program)
892 
893  LOG(VB_GENERAL, LOG_INFO,
894  QString("Start up testing connections. DB %1, BE %2, attempt %3, status %4")
895  .arg(host).arg(backendIP).arg(attempt).arg(guiStatuses[startupState]));
896 
897  int useTimeout = wakeupTime;
898  if (attempt == 0)
899  useTimeout=1;
900 
901  if (m_gui && !m_guiStartup)
902  {
903  if (attempt > 0)
904  {
905  ShowGuiStartup();
906  if (m_guiStartup)
907  m_guiStartup->setTotal(progressTotal);
908  }
909  }
911  {
912  if (attempt > 0)
913  m_guiStartup->setStatusState(guiStatuses[startupState]);
914  m_guiStartup->setMessageState("empty");
915  processEvents();
916  }
917  switch (startupState) {
918  case st_start:
920  {
921  if (attempt > 0)
923  if (!checkPort(host, port, useTimeout))
924  break;
925  }
926  startupState = st_dbAwake;
927  [[clang::fallthrough]];
928  case st_dbAwake:
929  if (!checkPort(host, port, useTimeout))
930  break;
931  startupState = st_dbStarted;
932  [[clang::fallthrough]];
933  case st_dbStarted:
934  // If the database is connecting with link-local
935  // address, it may have changed
936  if (m_DBparams.dbHostName != host)
937  {
938  m_DBparams.dbHostName = host;
939  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
940  }
941  EnableDBerrors();
942  ResetDatabase();
944  {
945  for (int temp = 0; temp < useTimeout * 2 ; temp++)
946  {
947  processEvents();
948  std::this_thread::sleep_for(std::chrono::milliseconds(500));
949  }
950  break;
951  }
952  startupState = st_dbConnects;
953  [[clang::fallthrough]];
954  case st_dbConnects:
955  if (needsBackend)
956  {
957  beWOLCmd = gCoreContext->GetSetting("WOLbackendCommand", "");
958  if (!beWOLCmd.isEmpty())
959  {
960  wakeupTime += gCoreContext->GetNumSetting
961  ("WOLbackendReconnectWaitTime", 0);
962  attempts += gCoreContext->GetNumSetting
963  ("WOLbackendConnectRetry", 0);
964  useTimeout = wakeupTime;
965  if (m_gui && !m_guiStartup && attempt == 0)
966  useTimeout=1;
967  progressTotal = wakeupTime * attempts;
969  m_guiStartup->setTotal(progressTotal);
970  startupState = st_beWOL;
971  }
972  }
973  else {
974  startupState = st_success;
975  break;
976  }
977  masterserver = gCoreContext->GetSetting
978  ("MasterServerName");
979  backendIP = gCoreContext->GetSettingOnHost
980  ("BackendServerAddr", masterserver);
981  backendPort = gCoreContext->GetMasterServerPort();
982  [[clang::fallthrough]];
983  case st_beWOL:
984  if (!beWOLCmd.isEmpty()) {
985  if (attempt > 0)
986  myth_system(beWOLCmd);
987  if (!checkPort(backendIP, backendPort, useTimeout))
988  break;
989  }
990  startupState = st_beAwake;
991  [[clang::fallthrough]];
992  case st_beAwake:
993  if (!checkPort(backendIP, backendPort, useTimeout))
994  break;
995  startupState = st_success;
996  [[clang::fallthrough]];
997  case st_success:
998  // Quiet compiler warning.
999  break;
1000  }
1001  if (m_guiStartup)
1002  {
1003  if (m_guiStartup->m_Exit
1004  || m_guiStartup->m_Setup
1006  || m_guiStartup->m_Retry)
1007  break;
1008  }
1009  processEvents();
1010  }
1011  if (startupState == st_success)
1012  break;
1013 
1014  QString stateMsg = guiStatuses[startupState];
1015  stateMsg.append("Fail");
1016  LOG(VB_GENERAL, LOG_INFO,
1017  QString("Start up failure. host %1, status %2")
1018  .arg(host).arg(stateMsg));
1019 
1020  if (m_guiStartup
1021  && !m_guiStartup->m_Exit
1022  && !m_guiStartup->m_Setup
1023  && !m_guiStartup->m_Search
1024  && !m_guiStartup->m_Retry)
1025  {
1027  m_guiStartup->setStatusState(stateMsg);
1028  m_guiStartup->setMessageState("makeselection");
1029  m_loop->exec();
1030  }
1031  }
1032  while (m_guiStartup && m_guiStartup->m_Retry);
1033 
1034  if (startupState < st_dbAwake)
1035  {
1036  LOG(VB_GENERAL, LOG_WARNING, QString("Pinging to %1 failed, database will be unavailable").arg(host));
1037  SilenceDBerrors();
1038  err = QObject::tr(
1039  "Cannot find (ping) database host %1 on the network",
1040  "Backend Setup");
1041  return err.arg(host);
1042  }
1043 
1044  if (startupState < st_dbConnects)
1045  {
1046  SilenceDBerrors();
1047  return QObject::tr("Cannot login to database", "Backend Setup");
1048  }
1049 
1050  if (startupState < st_success)
1051  {
1052  return QObject::tr("Cannot connect to backend", "Backend Setup");
1053  }
1054 
1055  // Current DB connection may have been silenced (invalid):
1056  EnableDBerrors();
1057  ResetDatabase();
1058 
1059  return QString();
1060 }
1061 
1062 // Show the Gui Startup window.
1063 // This is called if there is a delay in startup for any reason
1064 // such as the database being unavailable
1066 {
1067  if (!m_gui)
1068  return;
1069  TempMainWindow(false);
1070  MythMainWindow *mainWindow = GetMythMainWindow();
1071  MythScreenStack *mainStack = mainWindow->GetMainStack();
1072  if (mainStack) {
1073  if (!m_guiStartup) {
1074  m_guiStartup = new GUIStartup(mainStack,m_loop);
1075  if (!m_guiStartup->Create()) {
1076  delete m_guiStartup;
1077  m_guiStartup = 0;
1078  }
1079  if (m_guiStartup) {
1080  mainStack->AddScreen(m_guiStartup, false);
1081  processEvents();
1082  }
1083  }
1084  }
1085 }
1086 
1096 {
1097  // This silences any DB errors from Get*Setting(),
1098  // (which is the vast majority of them)
1099  gCoreContext->GetDB()->SetSuppressDBMessages(true);
1100 
1101  // Save the configured hostname, so that we can
1102  // still display it in the DatabaseSettings screens
1103  if (m_DBparams.dbHostName.length())
1105 
1106  m_DBparams.dbHostName.clear();
1107  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1108 }
1109 
1111 {
1112  // Restore (possibly) blanked hostname
1113  if (m_DBparams.dbHostName.isNull() && m_DBhostCp.length())
1114  {
1116  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1117  }
1118 
1119  gCoreContext->GetDB()->SetSuppressDBMessages(false);
1120 }
1121 
1122 
1135 {
1137  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1139 }
1140 
1145 {
1146  TempMainWindow();
1147 
1148  // Tell the user what went wrong:
1149  if (!error.isEmpty())
1150  {
1151  LOG(VB_GENERAL, LOG_ERR, QString("Error: %1").arg(error));
1152  ShowOkPopup(error);
1153  }
1154 
1155  LOG(VB_GENERAL, LOG_INFO, "Putting up the UPnP backend chooser");
1156 
1159 
1160  EndTempWindow();
1161 
1162  return (int)ret;
1163 }
1164 
1171 int MythContextPrivate::UPnPautoconf(const int milliSeconds)
1172 {
1173  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search %1 secs")
1174  .arg(milliSeconds / 1000));
1175 
1176  SSDP::Instance()->PerformSearch(gBackendURI, milliSeconds / 1000);
1177 
1178  // Search for a total of 'milliSeconds' ms, sending new search packet
1179  // about every 250 ms until less than one second remains.
1180  MythTimer totalTime; totalTime.start();
1181  MythTimer searchTime; searchTime.start();
1182  while (totalTime.elapsed() < milliSeconds)
1183  {
1184  usleep(25000);
1185  int ttl = milliSeconds - totalTime.elapsed();
1186  if ((searchTime.elapsed() > 249) && (ttl > 1000))
1187  {
1188  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search %1 secs")
1189  .arg(ttl / 1000));
1190  SSDP::Instance()->PerformSearch(gBackendURI, ttl / 1000);
1191  searchTime.start();
1192  }
1193  }
1194 
1196 
1197  if (!backends)
1198  {
1199  LOG(VB_GENERAL, LOG_INFO, "No UPnP backends found");
1200  return 0;
1201  }
1202 
1203  int count = backends->Count();
1204  if (count)
1205  {
1206  LOG(VB_GENERAL, LOG_INFO,
1207  QString("Found %1 UPnP backends").arg(count));
1208  }
1209  else
1210  {
1211  LOG(VB_GENERAL, LOG_ERR,
1212  "No UPnP backends found, but SSDP::Find() not NULL");
1213  }
1214 
1215  if (count != 1)
1216  {
1217  backends->DecrRef();
1218  return count;
1219  }
1220 
1221  // Get this backend's location:
1222  DeviceLocation *BE = backends->GetFirst();
1223  backends->DecrRef();
1224  backends = NULL;
1225 
1226  // We don't actually know the backend's access PIN, so this will
1227  // only work for ones that have PIN access disabled (i.e. 0000)
1228  int ret = (UPnPconnect(BE, QString())) ? 1 : -1;
1229 
1230  BE->DecrRef();
1231 
1232  return ret;
1233 }
1234 
1241 {
1242  QString loc = "DefaultUPnP() - ";
1243  QString PIN = m_pConfig->GetValue(kDefaultPIN, "");
1244  QString USN = m_pConfig->GetValue(kDefaultUSN, "");
1245 
1246  if (USN.isEmpty())
1247  {
1248  LOG(VB_UPNP, LOG_INFO, loc + "No default UPnP backend");
1249  return false;
1250  }
1251 
1252  LOG(VB_UPNP, LOG_INFO, loc + "config.xml has default " +
1253  QString("PIN '%1' and host USN: %2") .arg(PIN).arg(USN));
1254 
1255  // ----------------------------------------------------------------------
1256 
1257  int timeout_ms = 2000;
1258  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search up to %1 secs")
1259  .arg(timeout_ms / 1000));
1260  SSDP::Instance()->PerformSearch(gBackendURI, timeout_ms / 1000);
1261 
1262  // ----------------------------------------------------------------------
1263  // We need to give the server time to respond...
1264  // ----------------------------------------------------------------------
1265 
1266  DeviceLocation *pDevLoc = NULL;
1267  MythTimer totalTime; totalTime.start();
1268  MythTimer searchTime; searchTime.start();
1269  while (totalTime.elapsed() < timeout_ms)
1270  {
1271  pDevLoc = SSDP::Instance()->Find( gBackendURI, USN );
1272 
1273  if (pDevLoc)
1274  break;
1275 
1276  usleep(25000);
1277 
1278  int ttl = timeout_ms - totalTime.elapsed();
1279  if ((searchTime.elapsed() > 249) && (ttl > 1000))
1280  {
1281  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search up to %1 secs")
1282  .arg(ttl / 1000));
1283  SSDP::Instance()->PerformSearch(gBackendURI, ttl / 1000);
1284  searchTime.start();
1285  }
1286  }
1287 
1288  // ----------------------------------------------------------------------
1289 
1290  if (!pDevLoc)
1291  {
1292  error = "Cannot find default UPnP backend";
1293  return false;
1294  }
1295 
1296  if (UPnPconnect(pDevLoc, PIN))
1297  {
1298  pDevLoc->DecrRef();
1299  return true;
1300  }
1301 
1302  pDevLoc->DecrRef();
1303 
1304  error = "Cannot connect to default backend via UPnP. Wrong saved PIN?";
1305  return false;
1306 }
1307 
1312  const QString &PIN)
1313 {
1314  QString error;
1315  QString loc = "UPnPconnect() - ";
1316  QString URL = backend->m_sLocation;
1317  MythXMLClient client(URL);
1318 
1319  LOG(VB_UPNP, LOG_INFO, loc + QString("Trying host at %1").arg(URL));
1320  switch (client.GetConnectionInfo(PIN, &m_DBparams, error))
1321  {
1322  case UPnPResult_Success:
1323  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1324  LOG(VB_UPNP, LOG_INFO, loc +
1325  "Got database hostname: " + m_DBparams.dbHostName);
1326  return true;
1327 
1329  // The stored PIN is probably not correct.
1330  // We could prompt for the PIN and try again, but that needs a UI.
1331  // Easier to fail for now, and put up the full UI selector later
1332  LOG(VB_UPNP, LOG_ERR, loc + "Wrong PIN?");
1333  return false;
1334 
1335  default:
1336  LOG(VB_UPNP, LOG_ERR, loc + error);
1337  break;
1338  }
1339 
1340  // This backend may have a local DB with the default user/pass/DBname.
1341  // For whatever reason, we have failed to get anything back via UPnP,
1342  // so we might as well try the database directly as a last resort.
1343  QUrl theURL(URL);
1344  URL = theURL.host();
1345  if (URL.isEmpty())
1346  return false;
1347 
1348  LOG(VB_UPNP, LOG_INFO, "Trying default DB credentials at " + URL);
1350 
1351  return true;
1352 }
1353 
1355 {
1356  if (e->type() == (QEvent::Type) MythEvent::MythEventMessage)
1357  {
1358  if (disableeventpopup)
1359  return true;
1360 
1362  {
1364  }
1365 
1366  MythEvent *me = (MythEvent*)e;
1367  if (me->Message() == "VERSION_MISMATCH" && (1 == me->ExtraDataCount()))
1368  ShowVersionMismatchPopup(me->ExtraData(0).toUInt());
1369  else if (me->Message() == "CONNECTION_FAILURE")
1371  else if (me->Message() == "PERSISTENT_CONNECTION_FAILURE")
1373  else if (me->Message() == "CONNECTION_RESTABLISHED")
1375  return true;
1376  }
1377 
1378  return QObject::event(e);
1379 }
1380 
1382 {
1383  QDateTime now = MythDate::current();
1384 
1385  if (!GetNotificationCenter() || !m_ui || !m_ui->IsScreenSetup())
1386  return;
1387 
1388  if (m_lastCheck.isValid() && now < m_lastCheck)
1389  return;
1390 
1391  // When WOL is disallowed, standy mode,
1392  // we should not show connection failures.
1393  if (!gCoreContext->IsWOLAllowed())
1394  return;
1395 
1396  m_lastCheck = now.addMSecs(5000); // don't refresh notification more than every 5s
1397 
1398  QString description = (persistent) ?
1399  QObject::tr(
1400  "The connection to the master backend "
1401  "server has gone away for some reason. "
1402  "Is it running?") :
1403  QObject::tr(
1404  "Could not connect to the master backend server. Is "
1405  "it running? Is the IP address set for it in "
1406  "mythtv-setup correct?");
1407 
1408  QString message = QObject::tr("Could not connect to master backend");
1409  MythErrorNotification n(message, _Location, description);
1410  n.SetId(m_registration);
1411  n.SetParent(this);
1413 }
1414 
1416 {
1417  if (!GetNotificationCenter())
1418  return;
1419 
1420  if (!m_lastCheck.isValid())
1421  return;
1422 
1423  MythCheckNotification n(QObject::tr("Backend is online"), _Location);
1424  n.SetId(m_registration);
1425  n.SetParent(this);
1426  n.SetDuration(5);
1428  m_lastCheck = QDateTime();
1429 }
1430 
1432 {
1433  if (MBEversionPopup)
1434  return;
1435 
1436  QString message =
1437  QObject::tr(
1438  "The server uses network protocol version %1, "
1439  "but this client only understands version %2. "
1440  "Make sure you are running compatible versions of "
1441  "the backend and frontend.")
1442  .arg(remote_version).arg(MYTH_PROTO_VERSION);
1443 
1444  if (HasMythMainWindow() && m_ui && m_ui->IsScreenSetup())
1445  {
1447  message, m_sh, SLOT(VersionMismatchPopupClosed()));
1448  }
1449  else
1450  {
1451  LOG(VB_GENERAL, LOG_ERR, LOC + message);
1452  qApp->exit(GENERIC_EXIT_SOCKET_ERROR);
1453  }
1454 }
1455 
1456 // Process Events while waiting for connection
1457 // return true if progress is 100%
1459 {
1460 // bool ret = false;
1461 // if (m_guiStartup)
1462 // ret = m_guiStartup->updateProgress();
1463  qApp->processEvents(QEventLoop::AllEvents, 250);
1464  qApp->processEvents(QEventLoop::AllEvents, 250);
1465 // return ret;
1466 }
1467 
1468 // cache some settings in cache/contextcache.xml
1469 // only call this if the database is available.
1470 
1471 const QString MythContextPrivate::settingsToSave[] =
1472 { "Theme", "Language", "Country", "GuiHeight",
1473  "GuiOffsetX", "GuiOffsetY", "GuiWidth", "RunFrontendInWindow",
1474  "AlwaysOnTop", "HideMouseCursor", "ThemePainter", "libCECEnabled" };
1475 
1476 
1478 {
1479  if (!m_gui)
1480  return true;
1481  QString cacheDirName = GetConfDir() + "/cache/";
1482  QDir dir(cacheDirName);
1483  dir.mkpath(cacheDirName);
1484  XmlConfiguration config = XmlConfiguration("cache/contextcache.xml");
1485  static const int arraySize = sizeof(settingsToSave)/sizeof(settingsToSave[0]);
1486  for (int ix = 0; ix < arraySize; ix++)
1487  {
1488  QString cacheValue = config.GetValue("Settings/"+settingsToSave[ix],QString());
1490  QString value = gCoreContext->GetSetting(settingsToSave[ix],QString());
1491  if (value != cacheValue)
1492  {
1493  config.SetValue("Settings/"+settingsToSave[ix],value);
1494  m_settingsCacheDirty = true;
1495  }
1496  }
1498  return config.Save();
1499 }
1500 
1502 {
1503  if (!m_gui)
1504  return;
1505  XmlConfiguration config = XmlConfiguration("cache/contextcache.xml");
1506  static const int arraySize = sizeof(settingsToSave)/sizeof(settingsToSave[0]);
1507  for (int ix = 0; ix < arraySize; ix++)
1508  {
1509  if (!gCoreContext->GetSetting(settingsToSave[ix],QString()).isEmpty())
1510  continue;
1511  QString value = config.GetValue("Settings/"+settingsToSave[ix],QString());
1512  if (!value.isEmpty())
1514  }
1515  // Prevent power off TV after temporary window
1516  gCoreContext->OverrideSettingForSession("PowerOffTVAllowed", 0);
1517 
1518  QString language = gCoreContext->GetSetting("Language",QString());
1519  MythTranslation::load("mythfrontend");
1520 }
1521 
1523 {
1524  QString language = gCoreContext->GetSetting("Language",QString());
1525  static const int arraySize = sizeof(settingsToSave)/sizeof(settingsToSave[0]);
1526  for (int ix = 0; ix < arraySize; ix++)
1527  {
1529  }
1530  // Restore power off TV setting
1531  gCoreContext->ClearOverrideSettingForSession("PowerOffTVAllowed");
1532 
1533  if (language != gCoreContext->GetSetting("Language",QString()))
1534  MythTranslation::load("mythfrontend");
1535 }
1536 
1537 
1539 {
1540  d->MBEversionPopup = NULL;
1541  qApp->exit(GENERIC_EXIT_SOCKET_ERROR);
1542 }
1543 
1544 MythContext::MythContext(const QString &binversion, bool needsBackend)
1545  : d(NULL), app_binary_version(binversion)
1546 {
1547 #ifdef _WIN32
1548  static bool WSAStarted = false;
1549  if (!WSAStarted) {
1550  WSADATA wsadata;
1551  int res = WSAStartup(MAKEWORD(2, 0), &wsadata);
1552  LOG(VB_SOCKET, LOG_INFO,
1553  QString("WSAStartup returned %1").arg(res));
1554  }
1555 #endif
1556 
1557  d = new MythContextPrivate(this);
1558  d->needsBackend = needsBackend;
1559 
1561 
1562  if (!gCoreContext || !gCoreContext->Init())
1563  {
1564  LOG(VB_GENERAL, LOG_EMERG, LOC + "Unable to allocate MythCoreContext");
1565  qApp->exit(GENERIC_EXIT_NO_MYTHCONTEXT);
1566  }
1567 }
1568 
1569 bool MythContext::Init(const bool gui,
1570  const bool promptForBackend,
1571  const bool disableAutoDiscovery,
1572  const bool ignoreDB)
1573 {
1574  if (!d)
1575  {
1576  LOG(VB_GENERAL, LOG_EMERG, LOC + "Init() Out-of-memory");
1577  return false;
1578  }
1579 
1580  SetDisableEventPopup(true);
1581 
1583  {
1584  LOG(VB_GENERAL, LOG_EMERG,
1585  QString("Application binary version (%1) does not "
1586  "match libraries (%2)")
1588 
1589  QString warning = QObject::tr(
1590  "This application is not compatible "
1591  "with the installed MythTV libraries.");
1592  if (gui)
1593  {
1594  d->TempMainWindow(false);
1595  ShowOkPopup(warning);
1596  }
1597  LOG(VB_GENERAL, LOG_WARNING, warning);
1598 
1599  return false;
1600  }
1601 
1602 #ifdef _WIN32
1603  // HOME environment variable might not be defined
1604  // some libraries will fail without it
1605  QString home = getenv("HOME");
1606  if (home.isEmpty())
1607  {
1608  home = getenv("LOCALAPPDATA"); // Vista
1609  if (home.isEmpty())
1610  home = getenv("APPDATA"); // XP
1611  if (home.isEmpty())
1612  home = QString("."); // getenv("TEMP")?
1613 
1614  _putenv(QString("HOME=%1").arg(home).toLocal8Bit().constData());
1615  }
1616 #endif
1617 
1618  // If HOME isn't defined, we won't be able to use default confdir of
1619  // $HOME/.mythtv nor can we rely on a MYTHCONFDIR that references $HOME
1620  QString homedir = QDir::homePath();
1621  QString confdir = getenv("MYTHCONFDIR");
1622  if ((homedir.isEmpty() || homedir == "/") &&
1623  (confdir.isEmpty() || confdir.contains("$HOME")))
1624  {
1625  QString warning = "Cannot locate your home directory."
1626  " Please set the environment variable HOME";
1627  if (gui)
1628  {
1629  d->TempMainWindow(false);
1630  ShowOkPopup(warning);
1631  }
1632  LOG(VB_GENERAL, LOG_WARNING, warning);
1633 
1634  return false;
1635  }
1636 
1637  if (!d->Init(gui, promptForBackend, disableAutoDiscovery, ignoreDB))
1638  {
1639  return false;
1640  }
1641 
1642  SetDisableEventPopup(false);
1644  if (d->m_settingsCacheDirty)
1645  {
1647  d->m_settingsCacheDirty = false;
1648  }
1650 
1651  return true;
1652 }
1653 
1655 {
1656  if (MThreadPool::globalInstance()->activeThreadCount())
1657  LOG(VB_GENERAL, LOG_INFO, "Waiting for threads to exit.");
1658 
1660  logStop();
1661 
1662  SSDP::Shutdown();
1664 
1665  delete gCoreContext;
1666  gCoreContext = NULL;
1667 
1668  delete d;
1669 }
1670 
1672 {
1673  d->disableeventpopup = check;
1674 }
1675 
1677 {
1678  return d->m_DBparams;
1679 }
1680 
1682 {
1683  return d->SaveDatabaseParams(params, false);
1684 }
1685 
1687 {
1688  return d->saveSettingsCache();
1689 }
1690 
1691 /* vim: set expandtab tabstop=4 shiftwidth=4: */
void SaveLocaleDefaults(void)
void ShowGuiStartup(void)
virtual bool Save(void)
Startup context for MythTV.
Definition: mythcontext.h:42
void SetParent(void *parent)
contains the parent address.
bool wolEnabled
true if wake-on-lan params are used
Definition: mythdbparams.h:32
virtual int GetValue(const QString &sSetting, int Default)=0
bool setStatusState(const QString &name)
Definition: guistartup.cpp:123
int intResponse(const QString &query, int def)
In an interactive shell, prompt the user to input a number.
virtual int GetValue(const QString &sSetting, int Default)
unsigned int slots[4]
Definition: element.c:38
A QElapsedTimer based timer to replace use of QTime as a timer.
Definition: mythtimer.h:13
QString wolCommand
command to use for wake-on-lan
Definition: mythdbparams.h:35
static void configplugin_cb(const QString &cmd)
QString dbName
database name
Definition: mythdbparams.h:26
QString app_binary_version
Definition: mythcontext.h:61
void LoadQtConfig(void)
Dialog asking for user confirmation.
int UPnPautoconf(const int milliSeconds=2000)
If there is only a single UPnP backend, use it.
void EndTempWindow(void)
MythConfirmationDialog * ShowOkPopup(const QString &message, QObject *parent, const char *slot, bool showCancel)
Non-blocking version of MythPopupBox::showOkPopup()
virtual void ClearValue(const QString &sSetting)=0
void SetId(int id)
Optional MythNotification elements.
bool setMessageState(const QString &name)
Definition: guistartup.cpp:133
static void exec_program_tv_cb(const QString &cmd)
const QString kDefaultWOL
Definition: backendselect.h:23
static Type MythEventMessage
Definition: mythevent.h:65
static void error(const char *str,...)
Definition: vbi.c:41
virtual void SetValue(const QString &sSetting, int value)
int GetMasterServerPort(void)
Returns the Master Backend control port If no master server port has been defined in the database...
static void ejectOpticalDisc(void)
Eject a disk, unmount a drive, open a tray.
bool Create(void)
Definition: guistartup.cpp:83
static MythMainWindow * getMainWindow(const bool useDB=true)
Return the existing main window, or create one.
const QString gBackendURI
Service type for the backend&#39;s UPnP server.
Definition: backendselect.h:21
void isClosing(void)
static const char URL[]
Definition: cddb.cpp:29
bool m_Retry
Definition: guistartup.h:56
void UnRegister(void *from, int id, bool closeimemdiately=false)
Unregister the client.
bool IsFrontend(void) const
is this process a frontend process
QString GetSettingOnHost(const QString &key, const QString &host, const QString &defaultval="")
bool SaveDatabaseParams(const DatabaseParams &params, bool force)
void DestroyMythMainWindow(void)
void SetDisableEventPopup(bool check)
bool IsScreenSetup(void)
unsigned int uint
Definition: compat.h:136
MythCoreContext * gCoreContext
This global variable contains the MythCoreContext instance for the app.
static Decision Prompt(DatabaseParams *dbParams, Configuration *pConfig)
MythScreenStack * GetMainStack()
DatabaseParams GetDatabaseParams(void)
bool saveSettingsCache(void)
void waitForDone(void)
bool localEnabled
true if localHostName is not default
Definition: mythdbparams.h:29
MythContext * gContext
This global variable contains the MythContext instance for the application.
Definition: mythcontext.cpp:63
bool Init(const bool gui, const bool prompt, const bool noPrompt, const bool ignoreDB)
void DestroyMythUI()
void SetLocalHostname(const QString &hostname)
const QString kDefaultDB
Definition: backendselect.h:22
void(* exec_program)(const QString &cmd)
Definition: mythuihelper.h:34
bool checkPort(QString &host, int port, int wakeupTime)
Check if a port is open and sort out the link-local scope.
QString dbPassword
DB password.
Definition: mythdbparams.h:25
bool checkPort(QString &host, int port, int timeLimit=30000, bool linkLocalOnly=false)
Check if a port is open and sort out the link-local scope.
Definition: portchecker.cpp:82
QString GetConfDir(void)
Definition: mythdirs.cpp:224
static void Shutdown()
Definition: taskqueue.cpp:76
void Init(MythUIMenuCallbacks &cbs)
MythContextPrivate(MythContext *lparent)
static void eject_cb(void)
bool FindDatabase(const bool prompt, const bool noPrompt)
Get database connection settings and test connectivity.
bool config_plugin(const QString &plugname)
Definition: mythplugin.cpp:202
bool SendReceiveStringList(QStringList &strlist, bool quickTimeout=false, bool block=true)
Send a message to the backend and wait for a response.
MythContext * parent
virtual void AddScreen(MythScreenType *screen, bool allowFade=true)
MythContextSlotHandler * m_sh
QString dbUserName
DB user name.
Definition: mythdbparams.h:24
DeviceLocation * GetFirst(void)
Returns random entry in cache, returns NULL when list is empty.
Definition: ssdpcache.cpp:72
bool Init(const bool gui=true, const bool promptForBackend=false, const bool bypassAutoDiscovery=false, const bool ignoreDB=false)
static void plugin_cb(const QString &cmd)
void PerformSearch(const QString &sST, uint timeout_secs=2)
Definition: ssdp.cpp:214
MythPluginManager * GetPluginManager(void)
This class is used as a container for messages.
Definition: mythevent.h:15
void ClearOverrideSettingForSession(const QString &key)
void EnableDBerrors(void)
VERBOSE_PREAMBLE false
Definition: verbosedefs.h:83
void VersionMismatchPopupClosed(void)
void Init(QString forcedpainter=QString(), bool mayReInit=true)
int ChooseBackend(const QString &error)
Search for backends via UPnP, put up a UI for the user to choose one.
QString TestDBconnection(bool prompt=true)
Some quick sanity checks before opening a database connection.
uint Count(void) const
Definition: ssdpcache.h:44
void setTotal(int total)
Definition: guistartup.cpp:144
bool PromptForDatabaseParams(const QString &error)
static const uint16_t * d
void OverrideSettingForSession(const QString &key, const QString &value)
QDateTime current(bool stripped)
Returns current Date and Time in UTC.
Definition: mythdate.cpp:10
QString GetSetting(const QString &key, const QString &defaultval="")
DatabaseParams m_DBparams
Current database host & WOL details.
MythContext(const QString &binversion, bool needsBackend=false)
void SetDuration(int duration)
contains a duration during which the notification will be displayed for.
bool m_Setup
Definition: guistartup.h:55
#define GENERIC_EXIT_SOCKET_ERROR
Socket error.
Definition: exitcodes.h:18
virtual int DecrRef(void)
Decrements reference count and deletes on 0.
virtual bool Save(void)=0
bool updateProgress(bool finished=false)
Definition: guistartup.cpp:161
QEventLoop * m_loop
MythContextPrivate * d
Definition: mythcontext.h:60
static void load(const QString &module_name)
Load a QTranslator for the user&#39;s preferred language.
MythConfirmationDialog * MBEversionPopup
void ShowNotificationError(const QString &msg, const QString &from, const QString &detail, const VNMask visibility, const MythNotification::Priority priority)
convenience utility to display error message as notification
#define MYTH_PROTO_VERSION
Increment this whenever the MythTV network protocol changes.
Definition: mythversion.h:48
Small class to handle TCP port checking and finding link-local context.
Definition: portchecker.h:43
static bool testDBConnection()
Checks DB connection + login (login info via Mythcontext)
Definition: mythdbcon.cpp:903
void(* configplugin)(const QString &cmd)
Definition: mythuihelper.h:36
bool Queue(const MythNotification &notification)
Queue a notification Queue() is thread-safe and can be called from anywhere.
bool dbHostPing
Can we test connectivity using ping?
Definition: mythdbparams.h:22
string hostname
Definition: caa.py:17
void TempMainWindow(bool languagePrompt=true)
Setup a minimal themed main window, and prompt for user&#39;s language.
QString m_masterhostname
master backend hostname
QString m_DBhostCp
dbHostName backup
QString getResponse(const QString &query, const QString &def)
In an interactive shell, prompt the user to input a string.
static bool prompt(bool force=false)
Ask the user for the language to use.
uint myth_system(const QString &command, uint flags, uint timeout)
#define ENO
This can be appended to the LOG args with "+".
Definition: mythlogging.h:98
static const QString _Location
Definition: mythcontext.cpp:65
bool LoadDatabaseSettings(void)
Load database and host settings from config.xml, or set some defaults.
bool IsValid(const QString &source=QString("Unknown")) const
MythUIHelper * GetMythUI()
void SilenceDBerrors(void)
Cause MSqlDatabase::OpenDatabase() and MSqlQuery to fail silently.
int wolReconnect
seconds to wait for reconnect
Definition: mythdbparams.h:33
bool HasMythMainWindow(void)
MythMainWindow * GetMythMainWindow(void)
void clearSettingsCacheOverride(void)
int elapsed(void) const
Returns milliseconds elapsed since last start() or restart()
Definition: mythtimer.cpp:90
bool m_Exit
Definition: guistartup.h:54
static MThreadPool * globalInstance(void)
static void exec_program_cb(const QString &cmd)
bool SaveDatabaseParams(const DatabaseParams &params)
int Register(void *from)
An application can register in which case it will be assigned a reusable screen, which can be modifie...
bool event(QEvent *)
int GetNumSetting(const QString &key, int defaultval=0)
static const QString settingsToSave[]
bool UPnPconnect(const DeviceLocation *device, const QString &PIN)
Query a backend via UPnP for its database connection parameters.
Structure containing the basic Database parameters.
Definition: mythdbparams.h:9
QString m_sLocation
Definition: upnpdevice.h:230
#define LOG(_MASK_, _LEVEL_, _STRING_)
Definition: mythlogging.h:38
QString dbHostName
database server
Definition: mythdbparams.h:21
void LoadDefaults(void)
Load sensible connection defaults.
Definition: mythdbparams.cpp:5
static SSDP * Instance()
Definition: ssdp.cpp:54
bool forceSave
set to true to force a save of the settings file
Definition: mythdbparams.h:37
const QString & ExtraData(int idx=0) const
Definition: mythevent.h:58
void(* eject)(void)
Definition: mythuihelper.h:38
void logStop(void)
Entry point for stopping logging for an application.
Definition: logging.cpp:954
Configuration * m_pConfig
UPnPResultCode GetConnectionInfo(const QString &sPin, DatabaseParams *pParams, QString &sMsg)
QTcpSocket * m_socket
void(* plugin)(const QString &cmd)
Definition: mythuihelper.h:37
const QString kDefaultPIN
Definition: backendselect.h:25
void ClearSettingsCache(const QString &myKey=QString(""))
#define MYTH_BINARY_VERSION
Update this whenever the plug-in ABI changes.
Definition: mythversion.h:16
static MythPluginManager * pmanager
bool IsWOLAllowed() const
bool saveSettingsCache(void)
MythDB * GetDB(void)
MDBManager * GetDBManager(void)
void loadSettingsCacheOverride(void)
void HideConnectionFailurePopup(void)
virtual void PopScreen(MythScreenType *screen=NULL, bool allowFade=true, bool deleteScreen=true)
const QString kDefaultUSN
Definition: backendselect.h:26
int ExtraDataCount() const
Definition: mythevent.h:60
bool m_Search
Definition: guistartup.h:57
MythUIHelper * m_ui
static SSDPCacheEntries * Find(const QString &sURI)
Definition: ssdp.h:129
const QString kDefaultMFE
Definition: backendselect.h:24
#define GENERIC_EXIT_NO_MYTHCONTEXT
No MythContext available.
Definition: exitcodes.h:13
void(* exec_program_tv)(const QString &cmd)
Definition: mythuihelper.h:35
void ResetDatabase(void)
Called when the user changes the DB connection settings.
const QString & Message() const
Definition: mythevent.h:57
QString localHostName
name used for loading/saving settings
Definition: mythdbparams.h:30
void ActivateSettingsCache(bool activate=true)
int dbPort
database port
Definition: mythdbparams.h:23
void processEvents(void)
GUIStartup * m_guiStartup
void ShowConnectionFailurePopup(bool persistent)
QDateTime fromString(const QString &dtstr)
Converts kFilename && kISODate formats to QDateTime.
Definition: mythdate.cpp:30
void ShowVersionMismatchPopup(uint remoteVersion)
void start(void)
starts measuring elapsed time.
Definition: mythtimer.cpp:47
void CloseDatabases(void)
Definition: mythdbcon.cpp:483
virtual ~MythContext()
int wolRetry
times to retry to reconnect
Definition: mythdbparams.h:34
bool DefaultUPnP(QString &error)
Get the default backend from config.xml, use UPnP to find it.
static QString confdir
Definition: mythdirs.cpp:20
This class contains the runtime context for MythTV.
static void Shutdown()
Definition: ssdp.cpp:64
#define LOC
Definition: mythcontext.cpp:61
MythNotificationCenter * GetNotificationCenter(void)
bool run_plugin(const QString &plugname)
Definition: mythplugin.cpp:184
void InitializeMythDirs(void)
Definition: mythdirs.cpp:30
virtual void SetValue(const QString &sSetting, int value)=0
bool m_gui
Should this context use GUI elements?