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 #include <cmath>
11 #include <iostream>
12 
13 #include <queue>
14 #include <algorithm>
15 #include <thread>
16 
17 using namespace std;
18 
19 #include "config.h"
20 #include "mythcontext.h"
21 #include "exitcodes.h"
22 #include "mythdate.h"
23 #include "remotefile.h"
24 #include "backendselect.h"
25 #include "dbsettings.h"
26 #include "langsettings.h"
27 #include "mythtranslation.h"
28 #include "mythxdisplay.h"
29 #include "mythevent.h"
30 #include "dbutil.h"
31 #include "DisplayRes.h"
32 #include "mythmediamonitor.h"
33 
34 #include "mythdb.h"
35 #include "mythdirs.h"
36 #include "mythversion.h"
37 #include "mythdialogbox.h"
38 #include "mythmainwindow.h"
39 #include "mythuihelper.h"
40 #include "mythimage.h"
41 #include "mythxmlclient.h"
42 #include "upnp.h"
43 #include "mythlogging.h"
44 #include "mythsystemlegacy.h"
45 #include "mythmiscutil.h"
46 
47 #include "mythplugin.h"
48 #include "portchecker.h"
49 #include "guistartup.h"
50 
51 #include <unistd.h> // for usleep(), gethostname
52 
53 #ifdef _WIN32
54 #include "compat.h"
55 #endif
56 
57 #define LOC QString("MythContext: ")
58 
60 
61 static const QString _Location = "MythContext";
62 
63 class MythContextPrivate : public QObject
64 {
65  friend class MythContextSlotHandler;
66 
67  public:
70 
71  bool Init (const bool gui,
72  const bool prompt, const bool noPrompt,
73  const bool ignoreDB);
74  bool FindDatabase(const bool prompt, const bool noPrompt);
75 
76  void TempMainWindow(bool languagePrompt = true);
77  void EndTempWindow(void);
78 
79  bool LoadDatabaseSettings(void);
80  bool SaveDatabaseParams(const DatabaseParams &params, bool force);
81 
82  bool PromptForDatabaseParams(const QString &error);
83  QString TestDBconnection(bool prompt=true);
84  void SilenceDBerrors(void);
85  void EnableDBerrors(void);
86  void ResetDatabase(void);
87 
88  int ChooseBackend(const QString &error);
89  int UPnPautoconf(const int milliSeconds = 2000);
90  bool DefaultUPnP(QString &error);
91  bool UPnPconnect(const DeviceLocation *device, const QString &PIN);
92  void ShowGuiStartup(void);
93  bool checkPort(QString &host, int port, int wakeupTime);
94  void processEvents(void);
95  bool saveSettingsCache(void);
96  void loadSettingsCacheOverride(void);
97  void clearSettingsCacheOverride(void);
98 
99 
100  protected:
101  bool event(QEvent*);
102 
103  void ShowConnectionFailurePopup(bool persistent);
104  void HideConnectionFailurePopup(void);
105 
106  void ShowVersionMismatchPopup(uint remoteVersion);
107 
108  public slots:
109  void OnCloseDialog();
110 
111  public:
113 
114  bool m_gui;
115 
117 
119  QString m_DBhostCp;
120 
122 
124 
128  QEventLoop *m_loop;
131 
132  private:
135  QDateTime m_lastCheck;
136  QTcpSocket *m_socket;
137  static const QString settingsToSave[];
138 };
139 
140 static void exec_program_cb(const QString &cmd)
141 {
142  myth_system(cmd);
143 }
144 
145 static void exec_program_tv_cb(const QString &cmd)
146 {
147  QString s = cmd;
148  QStringList tokens = cmd.simplified().split(" ");
149  QStringList strlist;
150 
151  bool cardidok;
152  int wantcardid = tokens[0].toInt(&cardidok, 10);
153 
154  if (cardidok && wantcardid > 0)
155  {
156  strlist << QString("LOCK_TUNER %1").arg(wantcardid);
157  s = s.replace(0, tokens[0].length() + 1, "");
158  }
159  else
160  strlist << "LOCK_TUNER";
161 
163  int cardid = strlist[0].toInt();
164 
165  if (cardid >= 0)
166  {
167  s = s.sprintf(qPrintable(s),
168  qPrintable(strlist[1]),
169  qPrintable(strlist[2]),
170  qPrintable(strlist[3]));
171 
172  myth_system(s);
173 
174  strlist = QStringList(QString("FREE_TUNER %1").arg(cardid));
176  QString ret = strlist[0];
177  }
178  else
179  {
180  QString label;
181 
182  if (cardidok)
183  {
184  if (cardid == -1)
185  label = QObject::tr("Could not find specified tuner (%1).")
186  .arg(wantcardid);
187  else
188  label = QObject::tr("Specified tuner (%1) is already in use.")
189  .arg(wantcardid);
190  }
191  else
192  {
193  label = QObject::tr("All tuners are currently in use. If you want "
194  "to watch TV, you can cancel one of the "
195  "in-progress recordings from the delete menu");
196  }
197 
198  LOG(VB_GENERAL, LOG_ALERT, QString("exec_program_tv: ") + label);
199 
200  ShowOkPopup(label);
201  }
202 }
203 
204 static void configplugin_cb(const QString &cmd)
205 {
207  if (!pmanager)
208  return;
209 
210  if (GetNotificationCenter() && pmanager->config_plugin(cmd.trimmed()))
211  {
213  QObject::tr("Failed to configure plugin"));
214  }
215 }
216 
217 static void plugin_cb(const QString &cmd)
218 {
220  if (!pmanager)
221  return;
222 
223  if (GetNotificationCenter() && pmanager->run_plugin(cmd.trimmed()))
224  {
225  ShowNotificationError(QObject::tr("Plugin failure"),
226  _Location,
227  QObject::tr("%1 failed to run for some reason").arg(cmd));
228  }
229 }
230 
231 static void eject_cb(void)
232 {
234 }
235 
237  : parent(lparent),
238  m_gui(false),
239  m_pConfig(NULL),
240  disableeventpopup(false),
241  m_ui(NULL),
242  m_sh(new MythContextSlotHandler(this)),
243  m_guiStartup(0),
244  needsBackend(false),
245  m_settingsCacheDirty(false),
246  MBEversionPopup(NULL),
247  m_registration(-1),
248  m_socket(0)
249 {
250  m_loop = new QEventLoop(this);
252 }
253 
255 {
256  if (m_pConfig)
257  delete m_pConfig;
259  {
261  }
262 
263  if (m_loop)
264  {
265  delete m_loop;
266  }
267 
268  if (m_ui)
269  DestroyMythUI();
270  if (m_sh)
271  m_sh->deleteLater();
272 }
273 
284 void MythContextPrivate::TempMainWindow(bool languagePrompt)
285 {
286  if (HasMythMainWindow())
287  return;
288 
289  SilenceDBerrors();
290 
292 
293 #ifdef Q_OS_MAC
294  // Qt 4.4 has window-focus problems
295  gCoreContext->OverrideSettingForSession("RunFrontendInWindow", "1");
296 #endif
297  GetMythUI()->Init();
298  GetMythUI()->LoadQtConfig();
299 
300  MythMainWindow *mainWindow = MythMainWindow::getMainWindow(false);
301  mainWindow->Init();
302 
303  if (languagePrompt)
304  {
305  // ask user for language settings
307  MythTranslation::load("mythfrontend");
308  }
309 }
310 
312 {
313  if (HasMythMainWindow())
314  {
316  {
318  if (mainStack) {
319  mainStack->PopScreen(m_guiStartup, false);
320  m_guiStartup = 0;
321  }
322  }
323  }
324  EnableDBerrors();
325 }
326 
336 bool MythContextPrivate::checkPort(QString &host, int port, int timeLimit)
337 {
338  PortChecker checker;
339  if (m_guiStartup)
340  QObject::connect(m_guiStartup,SIGNAL(cancelPortCheck()),&checker,SLOT(cancelPortCheck()));
341  return checker.checkPort(host, port, timeLimit*1000);
342 }
343 
344 
345 bool MythContextPrivate::Init(const bool gui,
346  const bool promptForBackend,
347  const bool noPrompt,
348  const bool ignoreDB)
349 {
350  gCoreContext->GetDB()->IgnoreDatabase(ignoreDB);
351  m_gui = gui;
352 
353  if (gCoreContext->IsFrontend())
354  needsBackend = true;
355 
356  // We don't have a database yet, so lets use the config.xml file.
357  m_pConfig = new XmlConfiguration("config.xml");
358 
359  // Creates screen saver control if we will have a GUI
360  if (gui)
361  m_ui = GetMythUI();
362 
363  // ---- database connection stuff ----
364 
365  if (!ignoreDB && !FindDatabase(promptForBackend, noPrompt))
366  {
367  EndTempWindow();
368  return false;
369  }
370 
371  // ---- keep all DB-using stuff below this line ----
372 
373  // Prompt for language if this is a first time install and
374  // we didn't already do so.
375  if (m_gui && !gCoreContext->GetDB()->HaveSchema())
376  {
377  TempMainWindow(false);
379  MythTranslation::load("mythfrontend");
380  }
383 
384  // Close GUI Startup Window.
385  if (m_guiStartup) {
387  if (mainStack)
388  mainStack->PopScreen(m_guiStartup, false);
389  m_guiStartup=0;
390  }
391  EndTempWindow();
392 
393  if (gui)
394  {
399  cbs.plugin = plugin_cb;
400  cbs.eject = eject_cb;
401 
402  m_ui->Init(cbs);
403  }
404 
405  return true;
406 }
407 
420 bool MythContextPrivate::FindDatabase(bool prompt, bool noAutodetect)
421 {
422  // We can only prompt if autodiscovery is enabled..
423  bool manualSelect = prompt && !noAutodetect;
424 
425  QString failure;
426 
427  // 1. Either load config.xml or use sensible "localhost" defaults:
428  bool loaded = LoadDatabaseSettings();
429  DatabaseParams dbParamsFromFile = m_DBparams;
430 
431  // In addition to the UI chooser, we can also try to autoSelect later,
432  // but only if we're not doing manualSelect and there was no
433  // valid config.xml
434  bool autoSelect = !manualSelect && !loaded && !noAutodetect;
435 
436  // 2. If the user isn't forcing up the chooser UI, look for a default
437  // backend in config.xml, then test DB settings we've got so far:
438  if (!manualSelect)
439  {
440  // config.xml may contain a backend host UUID and PIN.
441  // If so, try to AutoDiscover UPnP server, and use its DB settings:
442 
443  if (DefaultUPnP(failure)) // Probably a valid backend,
444  autoSelect = manualSelect = false; // so disable any further UPnP
445  else
446  if (failure.length())
447  LOG(VB_GENERAL, LOG_ALERT, failure);
448 
449  failure = TestDBconnection(loaded);
450  if (failure.isEmpty())
451  goto DBfound;
453  return false;
455  autoSelect=true;
456  }
457 
458  // 3. Try to automatically find the single backend:
459  if (autoSelect)
460  {
461  int count = UPnPautoconf();
462 
463  if (count == 0)
464  failure = QObject::tr("No UPnP backends found", "Backend Setup");
465 
466  if (count == 1)
467  {
468  failure = TestDBconnection();
469  if (failure.isEmpty())
470  goto DBfound;
472  return false;
473  }
474 
475  // Multiple BEs, or needs PIN.
476  manualSelect |= (count > 1 || count == -1);
477  // Search requested
479  manualSelect=true;
480  }
481 
482  manualSelect &= m_gui; // no interactive command-line chooser yet
483 
484  // Queries the user for the DB info
485  do
486  {
487  if (manualSelect)
488  {
489  // Get the user to select a backend from a possible list:
491  ChooseBackend(failure);
492  switch (d)
493  {
495  break;
497  manualSelect = false;
498  break;
500  goto NoDBfound;
501  }
502  }
503 
504  if (!manualSelect)
505  {
506  if (!PromptForDatabaseParams(failure))
507  goto NoDBfound;
508  }
509  failure = TestDBconnection();
510  if (!failure.isEmpty())
511  LOG(VB_GENERAL, LOG_ALERT, failure);
513  return false;
515  manualSelect=true;
517  manualSelect=false;
518  }
519  while (!failure.isEmpty());
520 
521 DBfound:
522  LOG(VB_GENERAL, LOG_DEBUG, "FindDatabase() - Success!");
523  // If we got the database from UPNP then the wakeup settings are lost.
524  // Restore them.
525  m_DBparams.wolEnabled = dbParamsFromFile.wolEnabled;
526  m_DBparams.wolReconnect = dbParamsFromFile.wolReconnect;
527  m_DBparams.wolRetry = dbParamsFromFile.wolRetry;
528  m_DBparams.wolCommand = dbParamsFromFile.wolCommand;
529 
531  !loaded || m_DBparams.forceSave ||
532  dbParamsFromFile != m_DBparams);
533  EnableDBerrors();
534  ResetDatabase();
535  return true;
536 
537 NoDBfound:
538  LOG(VB_GENERAL, LOG_DEBUG, "FindDatabase() - failed");
539  return false;
540 }
541 
546 {
547  // try new format first
549 
550  m_DBparams.localHostName = m_pConfig->GetValue("LocalHostName", "");
551  m_DBparams.dbHostPing = m_pConfig->GetValue(kDefaultDB + "PingHost", true);
553  m_DBparams.dbUserName = m_pConfig->GetValue(kDefaultDB + "UserName", "");
554  m_DBparams.dbPassword = m_pConfig->GetValue(kDefaultDB + "Password", "");
555  m_DBparams.dbName = m_pConfig->GetValue(kDefaultDB + "DatabaseName", "");
557 
559  m_pConfig->GetValue(kDefaultWOL + "Enabled", false);
561  m_pConfig->GetValue(kDefaultWOL + "SQLReconnectWaitTime", 0);
563  m_pConfig->GetValue(kDefaultWOL + "SQLConnectRetry", 5);
565  m_pConfig->GetValue(kDefaultWOL + "Command", "");
566 
567  bool ok = m_DBparams.IsValid("config.xml");
568  if (!ok) // if new format fails, try legacy format
569  {
572  kDefaultMFE + "DBHostName", "");
574  kDefaultMFE + "DBUserName", "");
576  kDefaultMFE + "DBPassword", "");
578  kDefaultMFE + "DBName", "");
580  kDefaultMFE + "DBPort", 0);
581  m_DBparams.forceSave = true;
582  ok = m_DBparams.IsValid("config.xml");
583  }
584  if (!ok)
586 
587  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
588 
590  if (hostname.isEmpty() ||
591  hostname == "my-unique-identifier-goes-here")
592  {
593  char localhostname[1024];
594  if (gethostname(localhostname, 1024))
595  {
596  LOG(VB_GENERAL, LOG_ALERT,
597  "MCP: Error, could not determine host name." + ENO);
598  localhostname[0] = '\0';
599  }
600  hostname = localhostname;
601  LOG(VB_GENERAL, LOG_NOTICE, "Empty LocalHostName.");
602  }
603  else
604  {
605  m_DBparams.localEnabled = true;
606  }
607 
608  LOG(VB_GENERAL, LOG_INFO, QString("Using localhost value of %1")
609  .arg(hostname));
610  gCoreContext->SetLocalHostname(hostname);
611 
612  return ok;
613 }
614 
616  const DatabaseParams &params, bool force)
617 {
618  bool ret = true;
619 
620  // only rewrite file if it has changed
621  if (params != m_DBparams || force)
622  {
624  "LocalHostName", params.localHostName);
625 
627  kDefaultDB + "PingHost", params.dbHostPing);
628 
629  // If dbHostName is an IPV6 address with scope,
630  // remove the scope. Unescaped % signs are an
631  // xml violation
632  QString dbHostName(params.dbHostName);
633  QHostAddress addr;
634  if (addr.setAddress(dbHostName))
635  {
636  addr.setScopeId(QString());
637  dbHostName = addr.toString();
638  }
640  kDefaultDB + "Host", dbHostName);
642  kDefaultDB + "UserName", params.dbUserName);
644  kDefaultDB + "Password", params.dbPassword);
646  kDefaultDB + "DatabaseName", params.dbName);
648  kDefaultDB + "Port", params.dbPort);
649 
651  kDefaultWOL + "Enabled", params.wolEnabled);
653  kDefaultWOL + "SQLReconnectWaitTime", params.wolReconnect);
655  kDefaultWOL + "SQLConnectRetry", params.wolRetry);
657  kDefaultWOL + "Command", params.wolCommand);
658 
659  // clear out any legacy nodes..
660  m_pConfig->ClearValue(kDefaultMFE + "DBHostName");
661  m_pConfig->ClearValue(kDefaultMFE + "DBUserName");
662  m_pConfig->ClearValue(kDefaultMFE + "DBPassword");
663  m_pConfig->ClearValue(kDefaultMFE + "DBName");
664  m_pConfig->ClearValue(kDefaultMFE + "DBPort");
665  m_pConfig->ClearValue(kDefaultMFE + "DBHostPing");
666 
667  // actually save the file
668  m_pConfig->Save();
669 
670  // Save the new settings:
671  m_DBparams = params;
672  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
673 
674  // If database has changed, force its use:
675  ResetDatabase();
676  }
677  return ret;
678 }
679 
681 {
682  if (d && d->m_loop
683  && d->m_loop->isRunning())
684  d->m_loop->exit();
685 }
686 
687 
689 {
690  bool accepted = false;
691  if (m_gui)
692  {
693  TempMainWindow();
694 
695  // Tell the user what went wrong:
696  if (error.length())
697  ShowOkPopup(error);
698 
699  // ask user for database parameters
700 
701  EnableDBerrors();
703  DatabaseSettings *dbsetting = new DatabaseSettings();
704  StandardSettingDialog *ssd =
705  new StandardSettingDialog(mainStack, "databasesettings",
706  dbsetting);
707  if (ssd->Create())
708  {
709  mainStack->AddScreen(ssd);
710  connect(dbsetting, &DatabaseSettings::isClosing,
712  if (!m_loop->isRunning())
713  m_loop->exec();
714  }
715  else
716  delete ssd;
717  SilenceDBerrors();
718  EndTempWindow();
719  accepted = true;
720  }
721  else
722  {
724  QString response;
725  std::this_thread::sleep_for(std::chrono::seconds(1));
726  // give user chance to skip config
727  cout << endl << error.toLocal8Bit().constData() << endl << endl;
728  response = getResponse("Would you like to configure the database "
729  "connection now?",
730  "no");
731  if (!response.startsWith('y', Qt::CaseInsensitive))
732  return false;
733 
734  params.dbHostName = getResponse("Database host name:",
735  params.dbHostName);
736  response = getResponse("Should I test connectivity to this host "
737  "using the ping command?", "yes");
738  params.dbHostPing = response.startsWith('y', Qt::CaseInsensitive);
739 
740  params.dbPort = intResponse("Database non-default port:",
741  params.dbPort);
742  params.dbName = getResponse("Database name:",
743  params.dbName);
744  params.dbUserName = getResponse("Database user name:",
745  params.dbUserName);
746  params.dbPassword = getResponse("Database password:",
747  params.dbPassword);
748 
749  params.localHostName = getResponse("Unique identifier for this machine "
750  "(if empty, the local host name "
751  "will be used):",
752  params.localHostName);
753  params.localEnabled = !params.localHostName.isEmpty();
754 
755  response = getResponse("Would you like to use Wake-On-LAN to retry "
756  "database connections?",
757  (params.wolEnabled ? "yes" : "no"));
758  params.wolEnabled = response.startsWith('y', Qt::CaseInsensitive);
759 
760  if (params.wolEnabled)
761  {
762  params.wolReconnect = intResponse("Seconds to wait for "
763  "reconnection:",
764  params.wolReconnect);
765  params.wolRetry = intResponse("Number of times to retry:",
766  params.wolRetry);
767  params.wolCommand = getResponse("Command to use to wake server:",
768  params.wolCommand);
769  }
770 
771  accepted = parent->SaveDatabaseParams(params);
772  }
773  return accepted;
774 }
775 
782 {
783  QString err = QString::null;
784  QString host;
785 
786  // Jan 20, 2017
787  // Changed to use port check instead of ping
788 
789  int port = 0;
790 
791  // 1 = db awake, 2 = db listening, 3 = db connects,
792  // 4 = backend awake, 5 = backend listening
793  // 9 = all ok, 10 = quit
794 
795  enum startupStates {
796  st_start = 0,
797  st_dbAwake = 1,
798  st_dbStarted = 2,
799  st_dbConnects = 3,
800  st_beWOL = 4,
801  st_beAwake = 5,
802  st_success = 6
803  } startupState = st_start;
804 
805  static const QString guiStatuses[7] =
806  {"start","dbAwake","dbStarted","dbConnects","beWOL","beAwake",
807  "success" };
808 
809  do
810  {
811  if (m_DBparams.dbHostName.isNull() && m_DBhostCp.length())
812  host = m_DBhostCp;
813  else
814  host = m_DBparams.dbHostName;
815  port = m_DBparams.dbPort;
816  if (port == 0)
817  port = 3306;
818  int wakeupTime = 3;
819  int attempts = 11;
820  if (m_DBparams.wolEnabled) {
821  wakeupTime = m_DBparams.wolReconnect;
822  attempts = m_DBparams.wolRetry + 1;
823  startupState = st_start;
824  }
825  else
826  startupState = st_dbAwake;
827  if (attempts < 6)
828  attempts = 6;
829  if (!prompt)
830  attempts=1;
831  if (wakeupTime < 5)
832  wakeupTime = 5;
833 
834  int progressTotal = wakeupTime * attempts;
835 
837  m_guiStartup->setTotal(progressTotal);
838 
839  QString beWOLCmd = QString();
840  QString backendIP = QString();
841  int backendPort = 0;
842  QString masterserver;
843 
844  for (int attempt = 0;
845  attempt < attempts && startupState != st_success;
846  ++attempt)
847  {
848  // The first time do everything with minimum timeout and
849  // no GUI, for the normal case where all is OK
850  // After that show the GUI (if this is a GUI program)
851 
852  LOG(VB_GENERAL, LOG_INFO,
853  QString("Start up testing connections. DB %1, BE %2, attempt %3, status %4")
854  .arg(host).arg(backendIP).arg(attempt).arg(guiStatuses[startupState]));
855 
856  int useTimeout = wakeupTime;
857  if (attempt == 0)
858  useTimeout=1;
859 
860  if (m_gui && !m_guiStartup)
861  {
862  if (attempt > 0)
863  {
864  ShowGuiStartup();
865  if (m_guiStartup)
866  m_guiStartup->setTotal(progressTotal);
867  }
868  }
870  {
871  if (attempt > 0)
872  m_guiStartup->setStatusState(guiStatuses[startupState]);
873  m_guiStartup->setMessageState("empty");
874  processEvents();
875  }
876  switch (startupState) {
877  case st_start:
879  {
880  if (attempt > 0)
882  if (!checkPort(host, port, useTimeout))
883  break;
884  }
885  startupState = st_dbAwake;
886  [[clang::fallthrough]];
887  case st_dbAwake:
888  if (!checkPort(host, port, useTimeout))
889  break;
890  startupState = st_dbStarted;
891  [[clang::fallthrough]];
892  case st_dbStarted:
893  // If the database is connecting with link-local
894  // address, it may have changed
895  if (m_DBparams.dbHostName != host)
896  {
897  m_DBparams.dbHostName = host;
898  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
899  }
900  EnableDBerrors();
901  ResetDatabase();
903  {
904  for (int temp = 0; temp < useTimeout * 2 ; temp++)
905  {
906  processEvents();
907  std::this_thread::sleep_for(std::chrono::milliseconds(500));
908  }
909  break;
910  }
911  startupState = st_dbConnects;
912  [[clang::fallthrough]];
913  case st_dbConnects:
914  if (needsBackend)
915  {
916  beWOLCmd = gCoreContext->GetSetting("WOLbackendCommand", "");
917  if (!beWOLCmd.isEmpty())
918  {
919  wakeupTime += gCoreContext->GetNumSetting
920  ("WOLbackendReconnectWaitTime", 0);
921  attempts += gCoreContext->GetNumSetting
922  ("WOLbackendConnectRetry", 0);
923  useTimeout = wakeupTime;
924  if (m_gui && !m_guiStartup && attempt == 0)
925  useTimeout=1;
926  progressTotal = wakeupTime * attempts;
928  m_guiStartup->setTotal(progressTotal);
929  startupState = st_beWOL;
930  }
931  }
932  else {
933  startupState = st_success;
934  break;
935  }
936  masterserver = gCoreContext->GetSetting
937  ("MasterServerName");
938  backendIP = gCoreContext->GetSettingOnHost
939  ("BackendServerAddr", masterserver);
940  backendPort = gCoreContext->GetMasterServerPort();
941  [[clang::fallthrough]];
942  case st_beWOL:
943  if (!beWOLCmd.isEmpty()) {
944  if (attempt > 0)
945  myth_system(beWOLCmd);
946  if (!checkPort(backendIP, backendPort, useTimeout))
947  break;
948  }
949  startupState = st_beAwake;
950  [[clang::fallthrough]];
951  case st_beAwake:
952  if (!checkPort(backendIP, backendPort, useTimeout))
953  break;
954  startupState = st_success;
955  [[clang::fallthrough]];
956  case st_success:
957  // Quiet compiler warning.
958  break;
959  }
960  if (m_guiStartup)
961  {
962  if (m_guiStartup->m_Exit
965  || m_guiStartup->m_Retry)
966  break;
967  }
968  processEvents();
969  }
970  if (startupState == st_success)
971  break;
972 
973  QString stateMsg = guiStatuses[startupState];
974  stateMsg.append("Fail");
975  LOG(VB_GENERAL, LOG_INFO,
976  QString("Start up failure. host %1, status %2")
977  .arg(host).arg(stateMsg));
978 
979  if (m_guiStartup
980  && !m_guiStartup->m_Exit
981  && !m_guiStartup->m_Setup
983  && !m_guiStartup->m_Retry)
984  {
986  m_guiStartup->setStatusState(stateMsg);
987  m_guiStartup->setMessageState("makeselection");
988  m_loop->exec();
989  }
990  }
991  while (m_guiStartup && m_guiStartup->m_Retry);
992 
993  if (startupState < st_dbAwake)
994  {
995  LOG(VB_GENERAL, LOG_WARNING, QString("Pinging to %1 failed, database will be unavailable").arg(host));
996  SilenceDBerrors();
997  err = QObject::tr(
998  "Cannot find (ping) database host %1 on the network",
999  "Backend Setup");
1000  return err.arg(host);
1001  }
1002 
1003  if (startupState < st_dbConnects)
1004  {
1005  SilenceDBerrors();
1006  return QObject::tr("Cannot login to database", "Backend Setup");
1007  }
1008 
1009  if (startupState < st_success)
1010  {
1011  return QObject::tr("Cannot connect to backend", "Backend Setup");
1012  }
1013 
1014  // Current DB connection may have been silenced (invalid):
1015  EnableDBerrors();
1016  ResetDatabase();
1017 
1018  return QString::null;
1019 }
1020 
1021 // Show the Gui Startup window.
1022 // This is called if there is a delay in startup for any reason
1023 // such as the database being unavailable
1025 {
1026  if (!m_gui)
1027  return;
1028  TempMainWindow(false);
1029  MythMainWindow *mainWindow = GetMythMainWindow();
1030  MythScreenStack *mainStack = mainWindow->GetMainStack();
1031  if (mainStack) {
1032  if (!m_guiStartup) {
1033  m_guiStartup = new GUIStartup(mainStack,m_loop);
1034  if (!m_guiStartup->Create()) {
1035  delete m_guiStartup;
1036  m_guiStartup = 0;
1037  }
1038  if (m_guiStartup) {
1039  mainStack->AddScreen(m_guiStartup, false);
1040  processEvents();
1041  }
1042  }
1043  }
1044 }
1045 
1055 {
1056  // This silences any DB errors from Get*Setting(),
1057  // (which is the vast majority of them)
1058  gCoreContext->GetDB()->SetSuppressDBMessages(true);
1059 
1060  // Save the configured hostname, so that we can
1061  // still display it in the DatabaseSettings screens
1062  if (m_DBparams.dbHostName.length())
1064 
1065  m_DBparams.dbHostName.clear();
1066  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1067 }
1068 
1070 {
1071  // Restore (possibly) blanked hostname
1072  if (m_DBparams.dbHostName.isNull() && m_DBhostCp.length())
1073  {
1075  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1076  }
1077 
1078  gCoreContext->GetDB()->SetSuppressDBMessages(false);
1079 }
1080 
1081 
1094 {
1096  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1098 }
1099 
1104 {
1105  TempMainWindow();
1106 
1107  // Tell the user what went wrong:
1108  if (!error.isEmpty())
1109  {
1110  LOG(VB_GENERAL, LOG_ERR, QString("Error: %1").arg(error));
1111  ShowOkPopup(error);
1112  }
1113 
1114  LOG(VB_GENERAL, LOG_INFO, "Putting up the UPnP backend chooser");
1115 
1118 
1119  EndTempWindow();
1120 
1121  return (int)ret;
1122 }
1123 
1130 int MythContextPrivate::UPnPautoconf(const int milliSeconds)
1131 {
1132  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search %1 secs")
1133  .arg(milliSeconds / 1000));
1134 
1135  SSDP::Instance()->PerformSearch(gBackendURI, milliSeconds / 1000);
1136 
1137  // Search for a total of 'milliSeconds' ms, sending new search packet
1138  // about every 250 ms until less than one second remains.
1139  MythTimer totalTime; totalTime.start();
1140  MythTimer searchTime; searchTime.start();
1141  while (totalTime.elapsed() < milliSeconds)
1142  {
1143  usleep(25000);
1144  int ttl = milliSeconds - totalTime.elapsed();
1145  if ((searchTime.elapsed() > 249) && (ttl > 1000))
1146  {
1147  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search %1 secs")
1148  .arg(ttl / 1000));
1149  SSDP::Instance()->PerformSearch(gBackendURI, ttl / 1000);
1150  searchTime.start();
1151  }
1152  }
1153 
1155 
1156  if (!backends)
1157  {
1158  LOG(VB_GENERAL, LOG_INFO, "No UPnP backends found");
1159  return 0;
1160  }
1161 
1162  int count = backends->Count();
1163  if (count)
1164  {
1165  LOG(VB_GENERAL, LOG_INFO,
1166  QString("Found %1 UPnP backends").arg(count));
1167  }
1168  else
1169  {
1170  LOG(VB_GENERAL, LOG_ERR,
1171  "No UPnP backends found, but SSDP::Find() not NULL");
1172  }
1173 
1174  if (count != 1)
1175  {
1176  backends->DecrRef();
1177  return count;
1178  }
1179 
1180  // Get this backend's location:
1181  DeviceLocation *BE = backends->GetFirst();
1182  backends->DecrRef();
1183  backends = NULL;
1184 
1185  // We don't actually know the backend's access PIN, so this will
1186  // only work for ones that have PIN access disabled (i.e. 0000)
1187  int ret = (UPnPconnect(BE, QString::null)) ? 1 : -1;
1188 
1189  BE->DecrRef();
1190 
1191  return ret;
1192 }
1193 
1200 {
1201  QString loc = "DefaultUPnP() - ";
1202  QString PIN = m_pConfig->GetValue(kDefaultPIN, "");
1203  QString USN = m_pConfig->GetValue(kDefaultUSN, "");
1204 
1205  if (USN.isEmpty())
1206  {
1207  LOG(VB_UPNP, LOG_INFO, loc + "No default UPnP backend");
1208  return false;
1209  }
1210 
1211  LOG(VB_UPNP, LOG_INFO, loc + "config.xml has default " +
1212  QString("PIN '%1' and host USN: %2") .arg(PIN).arg(USN));
1213 
1214  // ----------------------------------------------------------------------
1215 
1216  int timeout_ms = 2000;
1217  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search up to %1 secs")
1218  .arg(timeout_ms / 1000));
1219  SSDP::Instance()->PerformSearch(gBackendURI, timeout_ms / 1000);
1220 
1221  // ----------------------------------------------------------------------
1222  // We need to give the server time to respond...
1223  // ----------------------------------------------------------------------
1224 
1225  DeviceLocation *pDevLoc = NULL;
1226  MythTimer totalTime; totalTime.start();
1227  MythTimer searchTime; searchTime.start();
1228  while (totalTime.elapsed() < timeout_ms)
1229  {
1230  pDevLoc = SSDP::Instance()->Find( gBackendURI, USN );
1231 
1232  if (pDevLoc)
1233  break;
1234 
1235  usleep(25000);
1236 
1237  int ttl = timeout_ms - totalTime.elapsed();
1238  if ((searchTime.elapsed() > 249) && (ttl > 1000))
1239  {
1240  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search up to %1 secs")
1241  .arg(ttl / 1000));
1242  SSDP::Instance()->PerformSearch(gBackendURI, ttl / 1000);
1243  searchTime.start();
1244  }
1245  }
1246 
1247  // ----------------------------------------------------------------------
1248 
1249  if (!pDevLoc)
1250  {
1251  error = "Cannot find default UPnP backend";
1252  return false;
1253  }
1254 
1255  if (UPnPconnect(pDevLoc, PIN))
1256  {
1257  pDevLoc->DecrRef();
1258  return true;
1259  }
1260 
1261  pDevLoc->DecrRef();
1262 
1263  error = "Cannot connect to default backend via UPnP. Wrong saved PIN?";
1264  return false;
1265 }
1266 
1271  const QString &PIN)
1272 {
1273  QString error;
1274  QString loc = "UPnPconnect() - ";
1275  QString URL = backend->m_sLocation;
1276  MythXMLClient client(URL);
1277 
1278  LOG(VB_UPNP, LOG_INFO, loc + QString("Trying host at %1").arg(URL));
1279  switch (client.GetConnectionInfo(PIN, &m_DBparams, error))
1280  {
1281  case UPnPResult_Success:
1282  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1283  LOG(VB_UPNP, LOG_INFO, loc +
1284  "Got database hostname: " + m_DBparams.dbHostName);
1285  return true;
1286 
1288  // The stored PIN is probably not correct.
1289  // We could prompt for the PIN and try again, but that needs a UI.
1290  // Easier to fail for now, and put up the full UI selector later
1291  LOG(VB_UPNP, LOG_ERR, loc + "Wrong PIN?");
1292  return false;
1293 
1294  default:
1295  LOG(VB_UPNP, LOG_ERR, loc + error);
1296  break;
1297  }
1298 
1299  // This backend may have a local DB with the default user/pass/DBname.
1300  // For whatever reason, we have failed to get anything back via UPnP,
1301  // so we might as well try the database directly as a last resort.
1302  QUrl theURL(URL);
1303  URL = theURL.host();
1304  if (URL.isEmpty())
1305  return false;
1306 
1307  LOG(VB_UPNP, LOG_INFO, "Trying default DB credentials at " + URL);
1309 
1310  return true;
1311 }
1312 
1314 {
1315  if (e->type() == (QEvent::Type) MythEvent::MythEventMessage)
1316  {
1317  if (disableeventpopup)
1318  return true;
1319 
1321  {
1323  }
1324 
1325  MythEvent *me = (MythEvent*)e;
1326  if (me->Message() == "VERSION_MISMATCH" && (1 == me->ExtraDataCount()))
1327  ShowVersionMismatchPopup(me->ExtraData(0).toUInt());
1328  else if (me->Message() == "CONNECTION_FAILURE")
1330  else if (me->Message() == "PERSISTENT_CONNECTION_FAILURE")
1332  else if (me->Message() == "CONNECTION_RESTABLISHED")
1334  return true;
1335  }
1336 
1337  return QObject::event(e);
1338 }
1339 
1341 {
1342  QDateTime now = MythDate::current();
1343 
1344  if (!GetNotificationCenter() || !m_ui || !m_ui->IsScreenSetup())
1345  return;
1346 
1347  if (m_lastCheck.isValid() && now < m_lastCheck)
1348  return;
1349 
1350  // When WOL is disallowed, standy mode,
1351  // we should not show connection failures.
1352  if (!gCoreContext->IsWOLAllowed())
1353  return;
1354 
1355  m_lastCheck = now.addMSecs(5000); // don't refresh notification more than every 5s
1356 
1357  QString description = (persistent) ?
1358  QObject::tr(
1359  "The connection to the master backend "
1360  "server has gone away for some reason. "
1361  "Is it running?") :
1362  QObject::tr(
1363  "Could not connect to the master backend server. Is "
1364  "it running? Is the IP address set for it in "
1365  "mythtv-setup correct?");
1366 
1367  QString message = QObject::tr("Could not connect to master backend");
1368  MythErrorNotification n(message, _Location, description);
1369  n.SetId(m_registration);
1370  n.SetParent(this);
1372 }
1373 
1375 {
1376  if (!GetNotificationCenter())
1377  return;
1378 
1379  if (!m_lastCheck.isValid())
1380  return;
1381 
1382  MythCheckNotification n(QObject::tr("Backend is online"), _Location);
1383  n.SetId(m_registration);
1384  n.SetParent(this);
1385  n.SetDuration(5);
1387  m_lastCheck = QDateTime();
1388 }
1389 
1391 {
1392  if (MBEversionPopup)
1393  return;
1394 
1395  QString message =
1396  QObject::tr(
1397  "The server uses network protocol version %1, "
1398  "but this client only understands version %2. "
1399  "Make sure you are running compatible versions of "
1400  "the backend and frontend.")
1401  .arg(remote_version).arg(MYTH_PROTO_VERSION);
1402 
1403  if (HasMythMainWindow() && m_ui && m_ui->IsScreenSetup())
1404  {
1406  message, m_sh, SLOT(VersionMismatchPopupClosed()));
1407  }
1408  else
1409  {
1410  LOG(VB_GENERAL, LOG_ERR, LOC + message);
1411  qApp->exit(GENERIC_EXIT_SOCKET_ERROR);
1412  }
1413 }
1414 
1415 // Process Events while waiting for connection
1416 // return true if progress is 100%
1418 {
1419 // bool ret = false;
1420 // if (m_guiStartup)
1421 // ret = m_guiStartup->updateProgress();
1422  qApp->processEvents(QEventLoop::AllEvents, 250);
1423  qApp->processEvents(QEventLoop::AllEvents, 250);
1424 // return ret;
1425 }
1426 
1427 // cache some settings in cache/contextcache.xml
1428 // only call this if the database is available.
1429 
1430 const QString MythContextPrivate::settingsToSave[] =
1431 { "Theme", "Language", "Country", "GuiHeight",
1432  "GuiOffsetX", "GuiOffsetY", "GuiWidth", "RunFrontendInWindow",
1433  "AlwaysOnTop", "HideMouseCursor", "ThemePainter", "libCECEnabled" };
1434 
1435 
1437 {
1438  if (!m_gui)
1439  return true;
1440  QString cacheDirName = GetConfDir() + "/cache/";
1441  QDir dir(cacheDirName);
1442  dir.mkpath(cacheDirName);
1443  XmlConfiguration config = XmlConfiguration("cache/contextcache.xml");
1444  static const int arraySize = sizeof(settingsToSave)/sizeof(settingsToSave[0]);
1445  for (int ix = 0; ix < arraySize; ix++)
1446  {
1447  QString cacheValue = config.GetValue("Settings/"+settingsToSave[ix],QString());
1449  QString value = gCoreContext->GetSetting(settingsToSave[ix],QString());
1450  if (value != cacheValue)
1451  {
1452  config.SetValue("Settings/"+settingsToSave[ix],value);
1453  m_settingsCacheDirty = true;
1454  }
1455  }
1457  return config.Save();
1458 }
1459 
1461 {
1462  if (!m_gui)
1463  return;
1464  XmlConfiguration config = XmlConfiguration("cache/contextcache.xml");
1465  static const int arraySize = sizeof(settingsToSave)/sizeof(settingsToSave[0]);
1466  for (int ix = 0; ix < arraySize; ix++)
1467  {
1468  if (!gCoreContext->GetSetting(settingsToSave[ix],QString()).isEmpty())
1469  continue;
1470  QString value = config.GetValue("Settings/"+settingsToSave[ix],QString());
1471  if (!value.isEmpty())
1473  }
1474  // Prevent power off TV after temporary window
1475  gCoreContext->OverrideSettingForSession("PowerOffTVAllowed", 0);
1476 
1477  QString language = gCoreContext->GetSetting("Language",QString());
1478  MythTranslation::load("mythfrontend");
1479 }
1480 
1482 {
1483  QString language = gCoreContext->GetSetting("Language",QString());
1484  static const int arraySize = sizeof(settingsToSave)/sizeof(settingsToSave[0]);
1485  for (int ix = 0; ix < arraySize; ix++)
1486  {
1488  }
1489  // Restore power off TV setting
1490  gCoreContext->ClearOverrideSettingForSession("PowerOffTVAllowed");
1491 
1492  if (language != gCoreContext->GetSetting("Language",QString()))
1493  MythTranslation::load("mythfrontend");
1494 }
1495 
1496 
1498 {
1499  d->MBEversionPopup = NULL;
1500  qApp->exit(GENERIC_EXIT_SOCKET_ERROR);
1501 }
1502 
1503 MythContext::MythContext(const QString &binversion, bool needsBackend)
1504  : d(NULL), app_binary_version(binversion)
1505 {
1506 #ifdef _WIN32
1507  static bool WSAStarted = false;
1508  if (!WSAStarted) {
1509  WSADATA wsadata;
1510  int res = WSAStartup(MAKEWORD(2, 0), &wsadata);
1511  LOG(VB_SOCKET, LOG_INFO,
1512  QString("WSAStartup returned %1").arg(res));
1513  }
1514 #endif
1515 
1516  d = new MythContextPrivate(this);
1517  d->needsBackend = needsBackend;
1518 
1520 
1521  if (!gCoreContext || !gCoreContext->Init())
1522  {
1523  LOG(VB_GENERAL, LOG_EMERG, LOC + "Unable to allocate MythCoreContext");
1524  qApp->exit(GENERIC_EXIT_NO_MYTHCONTEXT);
1525  }
1526 }
1527 
1528 bool MythContext::Init(const bool gui,
1529  const bool promptForBackend,
1530  const bool disableAutoDiscovery,
1531  const bool ignoreDB)
1532 {
1533  if (!d)
1534  {
1535  LOG(VB_GENERAL, LOG_EMERG, LOC + "Init() Out-of-memory");
1536  return false;
1537  }
1538 
1539  SetDisableEventPopup(true);
1540 
1542  {
1543  LOG(VB_GENERAL, LOG_EMERG,
1544  QString("Application binary version (%1) does not "
1545  "match libraries (%2)")
1547 
1548  QString warning = QObject::tr(
1549  "This application is not compatible "
1550  "with the installed MythTV libraries.");
1551  if (gui)
1552  {
1553  d->TempMainWindow(false);
1554  ShowOkPopup(warning);
1555  }
1556  LOG(VB_GENERAL, LOG_WARNING, warning);
1557 
1558  return false;
1559  }
1560 
1561 #ifdef _WIN32
1562  // HOME environment variable might not be defined
1563  // some libraries will fail without it
1564  QString home = getenv("HOME");
1565  if (home.isEmpty())
1566  {
1567  home = getenv("LOCALAPPDATA"); // Vista
1568  if (home.isEmpty())
1569  home = getenv("APPDATA"); // XP
1570  if (home.isEmpty())
1571  home = QString("."); // getenv("TEMP")?
1572 
1573  _putenv(QString("HOME=%1").arg(home).toLocal8Bit().constData());
1574  }
1575 #endif
1576 
1577  // If HOME isn't defined, we won't be able to use default confdir of
1578  // $HOME/.mythtv nor can we rely on a MYTHCONFDIR that references $HOME
1579  QString homedir = QDir::homePath();
1580  QString confdir = getenv("MYTHCONFDIR");
1581  if ((homedir.isEmpty() || homedir == "/") &&
1582  (confdir.isEmpty() || confdir.contains("$HOME")))
1583  {
1584  QString warning = "Cannot locate your home directory."
1585  " Please set the environment variable HOME";
1586  if (gui)
1587  {
1588  d->TempMainWindow(false);
1589  ShowOkPopup(warning);
1590  }
1591  LOG(VB_GENERAL, LOG_WARNING, warning);
1592 
1593  return false;
1594  }
1595 
1596  if (!d->Init(gui, promptForBackend, disableAutoDiscovery, ignoreDB))
1597  {
1598  return false;
1599  }
1600 
1601  SetDisableEventPopup(false);
1603  if (d->m_settingsCacheDirty)
1604  {
1606  d->m_settingsCacheDirty = false;
1607  }
1609 
1610  return true;
1611 }
1612 
1614 {
1615  if (MThreadPool::globalInstance()->activeThreadCount())
1616  LOG(VB_GENERAL, LOG_INFO, "Waiting for threads to exit.");
1617 
1619  logStop();
1620 
1621  SSDP::Shutdown();
1623 
1624  delete gCoreContext;
1625  gCoreContext = NULL;
1626 
1627  delete d;
1628 }
1629 
1631 {
1632  d->disableeventpopup = check;
1633 }
1634 
1636 {
1637  return d->m_DBparams;
1638 }
1639 
1641 {
1642  return d->SaveDatabaseParams(params, false);
1643 }
1644 
1646 {
1647  return d->saveSettingsCache();
1648 }
1649 
1650 /* 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:59
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:35
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:47
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:885
void(* configplugin)(const QString &cmd)
Definition: mythuihelper.h:37
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:61
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:232
#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:39
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:38
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:15
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:36
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)
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:57
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?