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_INFO, "Empty LocalHostName. This is typical.");
643  }
644  else
645  {
646  m_DBparams.localEnabled = true;
647  }
648 
649  LOG(VB_GENERAL, LOG_INFO, QString("Using a profile name of: '%1' (Usually the "
650  "same as this host's name.)")
651  .arg(hostname));
652  gCoreContext->SetLocalHostname(hostname);
653 
654  return ok;
655 }
656 
658  const DatabaseParams &params, bool force)
659 {
660  bool ret = true;
661 
662  // only rewrite file if it has changed
663  if (params != m_DBparams || force)
664  {
666  "LocalHostName", params.localHostName);
667 
669  kDefaultDB + "PingHost", params.dbHostPing);
670 
671  // If dbHostName is an IPV6 address with scope,
672  // remove the scope. Unescaped % signs are an
673  // xml violation
674  QString dbHostName(params.dbHostName);
675  QHostAddress addr;
676  if (addr.setAddress(dbHostName))
677  {
678  addr.setScopeId(QString());
679  dbHostName = addr.toString();
680  }
682  kDefaultDB + "Host", dbHostName);
684  kDefaultDB + "UserName", params.dbUserName);
686  kDefaultDB + "Password", params.dbPassword);
688  kDefaultDB + "DatabaseName", params.dbName);
690  kDefaultDB + "Port", params.dbPort);
691 
693  kDefaultWOL + "Enabled", params.wolEnabled);
695  kDefaultWOL + "SQLReconnectWaitTime", params.wolReconnect);
697  kDefaultWOL + "SQLConnectRetry", params.wolRetry);
699  kDefaultWOL + "Command", params.wolCommand);
700 
701  // clear out any legacy nodes..
702  m_pConfig->ClearValue(kDefaultMFE + "DBHostName");
703  m_pConfig->ClearValue(kDefaultMFE + "DBUserName");
704  m_pConfig->ClearValue(kDefaultMFE + "DBPassword");
705  m_pConfig->ClearValue(kDefaultMFE + "DBName");
706  m_pConfig->ClearValue(kDefaultMFE + "DBPort");
707  m_pConfig->ClearValue(kDefaultMFE + "DBHostPing");
708 
709  // actually save the file
710  m_pConfig->Save();
711 
712  // Save the new settings:
713  m_DBparams = params;
714  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
715 
716  // If database has changed, force its use:
717  ResetDatabase();
718  }
719  return ret;
720 }
721 
723 {
724  if (d && d->m_loop
725  && d->m_loop->isRunning())
726  d->m_loop->exit();
727 }
728 
729 
731 {
732  bool accepted = false;
733  if (m_gui)
734  {
735  TempMainWindow();
736 
737  // Tell the user what went wrong:
738  if (error.length())
739  ShowOkPopup(error);
740 
741  // ask user for database parameters
742 
743  EnableDBerrors();
745  DatabaseSettings *dbsetting = new DatabaseSettings();
746  StandardSettingDialog *ssd =
747  new StandardSettingDialog(mainStack, "databasesettings",
748  dbsetting);
749  if (ssd->Create())
750  {
751  mainStack->AddScreen(ssd);
752  connect(dbsetting, &DatabaseSettings::isClosing,
754  if (!m_loop->isRunning())
755  m_loop->exec();
756  }
757  else
758  delete ssd;
759  SilenceDBerrors();
760  EndTempWindow();
761  accepted = true;
762  }
763  else
764  {
766  QString response;
767  std::this_thread::sleep_for(std::chrono::seconds(1));
768  // give user chance to skip config
769  cout << endl << error.toLocal8Bit().constData() << endl << endl;
770  response = getResponse("Would you like to configure the database "
771  "connection now?",
772  "no");
773  if (!response.startsWith('y', Qt::CaseInsensitive))
774  return false;
775 
776  params.dbHostName = getResponse("Database host name:",
777  params.dbHostName);
778  response = getResponse("Should I test connectivity to this host "
779  "using the ping command?", "yes");
780  params.dbHostPing = response.startsWith('y', Qt::CaseInsensitive);
781 
782  params.dbPort = intResponse("Database non-default port:",
783  params.dbPort);
784  params.dbName = getResponse("Database name:",
785  params.dbName);
786  params.dbUserName = getResponse("Database user name:",
787  params.dbUserName);
788  params.dbPassword = getResponse("Database password:",
789  params.dbPassword);
790 
791  params.localHostName = getResponse("Unique identifier for this machine "
792  "(if empty, the local host name "
793  "will be used):",
794  params.localHostName);
795  params.localEnabled = !params.localHostName.isEmpty();
796 
797  response = getResponse("Would you like to use Wake-On-LAN to retry "
798  "database connections?",
799  (params.wolEnabled ? "yes" : "no"));
800  params.wolEnabled = response.startsWith('y', Qt::CaseInsensitive);
801 
802  if (params.wolEnabled)
803  {
804  params.wolReconnect = intResponse("Seconds to wait for "
805  "reconnection:",
806  params.wolReconnect);
807  params.wolRetry = intResponse("Number of times to retry:",
808  params.wolRetry);
809  params.wolCommand = getResponse("Command to use to wake server:",
810  params.wolCommand);
811  }
812 
813  accepted = parent->SaveDatabaseParams(params);
814  }
815  return accepted;
816 }
817 
824 {
825  QString err;
826  QString host;
827 
828  // Jan 20, 2017
829  // Changed to use port check instead of ping
830 
831  int port = 0;
832 
833  // 1 = db awake, 2 = db listening, 3 = db connects,
834  // 4 = backend awake, 5 = backend listening
835  // 9 = all ok, 10 = quit
836 
837  enum startupStates {
838  st_start = 0,
839  st_dbAwake = 1,
840  st_dbStarted = 2,
841  st_dbConnects = 3,
842  st_beWOL = 4,
843  st_beAwake = 5,
844  st_success = 6
845  } startupState = st_start;
846 
847  static const QString guiStatuses[7] =
848  {"start","dbAwake","dbStarted","dbConnects","beWOL","beAwake",
849  "success" };
850 
851  do
852  {
853  if (m_DBparams.dbHostName.isNull() && m_DBhostCp.length())
854  host = m_DBhostCp;
855  else
856  host = m_DBparams.dbHostName;
857  port = m_DBparams.dbPort;
858  if (port == 0)
859  port = 3306;
860  int wakeupTime = 3;
861  int attempts = 11;
862  if (m_DBparams.wolEnabled) {
863  wakeupTime = m_DBparams.wolReconnect;
864  attempts = m_DBparams.wolRetry + 1;
865  startupState = st_start;
866  }
867  else
868  startupState = st_dbAwake;
869  if (attempts < 6)
870  attempts = 6;
871  if (!prompt)
872  attempts=1;
873  if (wakeupTime < 5)
874  wakeupTime = 5;
875 
876  int progressTotal = wakeupTime * attempts;
877 
879  m_guiStartup->setTotal(progressTotal);
880 
881  QString beWOLCmd = QString();
882  QString backendIP = QString();
883  int backendPort = 0;
884  QString masterserver;
885 
886  for (int attempt = 0;
887  attempt < attempts && startupState != st_success;
888  ++attempt)
889  {
890  // The first time do everything with minimum timeout and
891  // no GUI, for the normal case where all is OK
892  // After that show the GUI (if this is a GUI program)
893 
894  LOG(VB_GENERAL, LOG_INFO,
895  QString("Start up testing connections. DB %1, BE %2, attempt %3, status %4")
896  .arg(host).arg(backendIP).arg(attempt).arg(guiStatuses[startupState]));
897 
898  int useTimeout = wakeupTime;
899  if (attempt == 0)
900  useTimeout=1;
901 
902  if (m_gui && !m_guiStartup)
903  {
904  if (attempt > 0)
905  {
906  ShowGuiStartup();
907  if (m_guiStartup)
908  m_guiStartup->setTotal(progressTotal);
909  }
910  }
912  {
913  if (attempt > 0)
914  m_guiStartup->setStatusState(guiStatuses[startupState]);
915  m_guiStartup->setMessageState("empty");
916  processEvents();
917  }
918  switch (startupState) {
919  case st_start:
921  {
922  if (attempt > 0)
924  if (!checkPort(host, port, useTimeout))
925  break;
926  }
927  startupState = st_dbAwake;
928  [[clang::fallthrough]];
929  case st_dbAwake:
930  if (!checkPort(host, port, useTimeout))
931  break;
932  startupState = st_dbStarted;
933  [[clang::fallthrough]];
934  case st_dbStarted:
935  // If the database is connecting with link-local
936  // address, it may have changed
937  if (m_DBparams.dbHostName != host)
938  {
939  m_DBparams.dbHostName = host;
940  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
941  }
942  EnableDBerrors();
943  ResetDatabase();
945  {
946  for (int temp = 0; temp < useTimeout * 2 ; temp++)
947  {
948  processEvents();
949  std::this_thread::sleep_for(std::chrono::milliseconds(500));
950  }
951  break;
952  }
953  startupState = st_dbConnects;
954  [[clang::fallthrough]];
955  case st_dbConnects:
956  if (needsBackend)
957  {
958  beWOLCmd = gCoreContext->GetSetting("WOLbackendCommand", "");
959  if (!beWOLCmd.isEmpty())
960  {
961  wakeupTime += gCoreContext->GetNumSetting
962  ("WOLbackendReconnectWaitTime", 0);
963  attempts += gCoreContext->GetNumSetting
964  ("WOLbackendConnectRetry", 0);
965  useTimeout = wakeupTime;
966  if (m_gui && !m_guiStartup && attempt == 0)
967  useTimeout=1;
968  progressTotal = wakeupTime * attempts;
970  m_guiStartup->setTotal(progressTotal);
971  startupState = st_beWOL;
972  }
973  }
974  else {
975  startupState = st_success;
976  break;
977  }
978  masterserver = gCoreContext->GetSetting
979  ("MasterServerName");
980  backendIP = gCoreContext->GetSettingOnHost
981  ("BackendServerAddr", masterserver);
982  backendPort = gCoreContext->GetMasterServerPort();
983  [[clang::fallthrough]];
984  case st_beWOL:
985  if (!beWOLCmd.isEmpty()) {
986  if (attempt > 0)
987  myth_system(beWOLCmd);
988  if (!checkPort(backendIP, backendPort, useTimeout))
989  break;
990  }
991  startupState = st_beAwake;
992  [[clang::fallthrough]];
993  case st_beAwake:
994  if (!checkPort(backendIP, backendPort, useTimeout))
995  break;
996  startupState = st_success;
997  [[clang::fallthrough]];
998  case st_success:
999  // Quiet compiler warning.
1000  break;
1001  }
1002  if (m_guiStartup)
1003  {
1004  if (m_guiStartup->m_Exit
1005  || m_guiStartup->m_Setup
1007  || m_guiStartup->m_Retry)
1008  break;
1009  }
1010  processEvents();
1011  }
1012  if (startupState == st_success)
1013  break;
1014 
1015  QString stateMsg = guiStatuses[startupState];
1016  stateMsg.append("Fail");
1017  LOG(VB_GENERAL, LOG_INFO,
1018  QString("Start up failure. host %1, status %2")
1019  .arg(host).arg(stateMsg));
1020 
1021  if (m_guiStartup
1022  && !m_guiStartup->m_Exit
1023  && !m_guiStartup->m_Setup
1024  && !m_guiStartup->m_Search
1025  && !m_guiStartup->m_Retry)
1026  {
1028  m_guiStartup->setStatusState(stateMsg);
1029  m_guiStartup->setMessageState("makeselection");
1030  m_loop->exec();
1031  }
1032  }
1033  while (m_guiStartup && m_guiStartup->m_Retry);
1034 
1035  if (startupState < st_dbAwake)
1036  {
1037  LOG(VB_GENERAL, LOG_WARNING, QString("Pinging to %1 failed, database will be unavailable").arg(host));
1038  SilenceDBerrors();
1039  err = QObject::tr(
1040  "Cannot find (ping) database host %1 on the network",
1041  "Backend Setup");
1042  return err.arg(host);
1043  }
1044 
1045  if (startupState < st_dbConnects)
1046  {
1047  SilenceDBerrors();
1048  return QObject::tr("Cannot login to database", "Backend Setup");
1049  }
1050 
1051  if (startupState < st_success)
1052  {
1053  return QObject::tr("Cannot connect to backend", "Backend Setup");
1054  }
1055 
1056  // Current DB connection may have been silenced (invalid):
1057  EnableDBerrors();
1058  ResetDatabase();
1059 
1060  return QString();
1061 }
1062 
1063 // Show the Gui Startup window.
1064 // This is called if there is a delay in startup for any reason
1065 // such as the database being unavailable
1067 {
1068  if (!m_gui)
1069  return;
1070  TempMainWindow(false);
1071  MythMainWindow *mainWindow = GetMythMainWindow();
1072  MythScreenStack *mainStack = mainWindow->GetMainStack();
1073  if (mainStack) {
1074  if (!m_guiStartup) {
1075  m_guiStartup = new GUIStartup(mainStack,m_loop);
1076  if (!m_guiStartup->Create()) {
1077  delete m_guiStartup;
1078  m_guiStartup = 0;
1079  }
1080  if (m_guiStartup) {
1081  mainStack->AddScreen(m_guiStartup, false);
1082  processEvents();
1083  }
1084  }
1085  }
1086 }
1087 
1097 {
1098  // This silences any DB errors from Get*Setting(),
1099  // (which is the vast majority of them)
1100  gCoreContext->GetDB()->SetSuppressDBMessages(true);
1101 
1102  // Save the configured hostname, so that we can
1103  // still display it in the DatabaseSettings screens
1104  if (m_DBparams.dbHostName.length())
1106 
1107  m_DBparams.dbHostName.clear();
1108  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1109 }
1110 
1112 {
1113  // Restore (possibly) blanked hostname
1114  if (m_DBparams.dbHostName.isNull() && m_DBhostCp.length())
1115  {
1117  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1118  }
1119 
1120  gCoreContext->GetDB()->SetSuppressDBMessages(false);
1121 }
1122 
1123 
1136 {
1138  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1140 }
1141 
1146 {
1147  TempMainWindow();
1148 
1149  // Tell the user what went wrong:
1150  if (!error.isEmpty())
1151  {
1152  LOG(VB_GENERAL, LOG_ERR, QString("Error: %1").arg(error));
1153  ShowOkPopup(error);
1154  }
1155 
1156  LOG(VB_GENERAL, LOG_INFO, "Putting up the UPnP backend chooser");
1157 
1160 
1161  EndTempWindow();
1162 
1163  return (int)ret;
1164 }
1165 
1172 int MythContextPrivate::UPnPautoconf(const int milliSeconds)
1173 {
1174  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search %1 secs")
1175  .arg(milliSeconds / 1000));
1176 
1177  SSDP::Instance()->PerformSearch(gBackendURI, milliSeconds / 1000);
1178 
1179  // Search for a total of 'milliSeconds' ms, sending new search packet
1180  // about every 250 ms until less than one second remains.
1181  MythTimer totalTime; totalTime.start();
1182  MythTimer searchTime; searchTime.start();
1183  while (totalTime.elapsed() < milliSeconds)
1184  {
1185  usleep(25000);
1186  int ttl = milliSeconds - totalTime.elapsed();
1187  if ((searchTime.elapsed() > 249) && (ttl > 1000))
1188  {
1189  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search %1 secs")
1190  .arg(ttl / 1000));
1191  SSDP::Instance()->PerformSearch(gBackendURI, ttl / 1000);
1192  searchTime.start();
1193  }
1194  }
1195 
1197 
1198  if (!backends)
1199  {
1200  LOG(VB_GENERAL, LOG_INFO, "No UPnP backends found");
1201  return 0;
1202  }
1203 
1204  int count = backends->Count();
1205  if (count)
1206  {
1207  LOG(VB_GENERAL, LOG_INFO,
1208  QString("Found %1 UPnP backends").arg(count));
1209  }
1210  else
1211  {
1212  LOG(VB_GENERAL, LOG_ERR,
1213  "No UPnP backends found, but SSDP::Find() not NULL");
1214  }
1215 
1216  if (count != 1)
1217  {
1218  backends->DecrRef();
1219  return count;
1220  }
1221 
1222  // Get this backend's location:
1223  DeviceLocation *BE = backends->GetFirst();
1224  backends->DecrRef();
1225  backends = NULL;
1226 
1227  // We don't actually know the backend's access PIN, so this will
1228  // only work for ones that have PIN access disabled (i.e. 0000)
1229  int ret = (UPnPconnect(BE, QString())) ? 1 : -1;
1230 
1231  BE->DecrRef();
1232 
1233  return ret;
1234 }
1235 
1242 {
1243  QString loc = "DefaultUPnP() - ";
1244  QString PIN = m_pConfig->GetValue(kDefaultPIN, "");
1245  QString USN = m_pConfig->GetValue(kDefaultUSN, "");
1246 
1247  if (USN.isEmpty())
1248  {
1249  LOG(VB_UPNP, LOG_INFO, loc + "No default UPnP backend");
1250  return false;
1251  }
1252 
1253  LOG(VB_UPNP, LOG_INFO, loc + "config.xml has default " +
1254  QString("PIN '%1' and host USN: %2") .arg(PIN).arg(USN));
1255 
1256  // ----------------------------------------------------------------------
1257 
1258  int timeout_ms = 2000;
1259  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search up to %1 secs")
1260  .arg(timeout_ms / 1000));
1261  SSDP::Instance()->PerformSearch(gBackendURI, timeout_ms / 1000);
1262 
1263  // ----------------------------------------------------------------------
1264  // We need to give the server time to respond...
1265  // ----------------------------------------------------------------------
1266 
1267  DeviceLocation *pDevLoc = NULL;
1268  MythTimer totalTime; totalTime.start();
1269  MythTimer searchTime; searchTime.start();
1270  while (totalTime.elapsed() < timeout_ms)
1271  {
1272  pDevLoc = SSDP::Instance()->Find( gBackendURI, USN );
1273 
1274  if (pDevLoc)
1275  break;
1276 
1277  usleep(25000);
1278 
1279  int ttl = timeout_ms - totalTime.elapsed();
1280  if ((searchTime.elapsed() > 249) && (ttl > 1000))
1281  {
1282  LOG(VB_GENERAL, LOG_INFO, QString("UPNP Search up to %1 secs")
1283  .arg(ttl / 1000));
1284  SSDP::Instance()->PerformSearch(gBackendURI, ttl / 1000);
1285  searchTime.start();
1286  }
1287  }
1288 
1289  // ----------------------------------------------------------------------
1290 
1291  if (!pDevLoc)
1292  {
1293  error = "Cannot find default UPnP backend";
1294  return false;
1295  }
1296 
1297  if (UPnPconnect(pDevLoc, PIN))
1298  {
1299  pDevLoc->DecrRef();
1300  return true;
1301  }
1302 
1303  pDevLoc->DecrRef();
1304 
1305  error = "Cannot connect to default backend via UPnP. Wrong saved PIN?";
1306  return false;
1307 }
1308 
1313  const QString &PIN)
1314 {
1315  QString error;
1316  QString loc = "UPnPconnect() - ";
1317  QString URL = backend->m_sLocation;
1318  MythXMLClient client(URL);
1319 
1320  LOG(VB_UPNP, LOG_INFO, loc + QString("Trying host at %1").arg(URL));
1321  switch (client.GetConnectionInfo(PIN, &m_DBparams, error))
1322  {
1323  case UPnPResult_Success:
1324  gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
1325  LOG(VB_UPNP, LOG_INFO, loc +
1326  "Got database hostname: " + m_DBparams.dbHostName);
1327  return true;
1328 
1330  // The stored PIN is probably not correct.
1331  // We could prompt for the PIN and try again, but that needs a UI.
1332  // Easier to fail for now, and put up the full UI selector later
1333  LOG(VB_UPNP, LOG_ERR, loc + "Wrong PIN?");
1334  return false;
1335 
1336  default:
1337  LOG(VB_UPNP, LOG_ERR, loc + error);
1338  break;
1339  }
1340 
1341  // This backend may have a local DB with the default user/pass/DBname.
1342  // For whatever reason, we have failed to get anything back via UPnP,
1343  // so we might as well try the database directly as a last resort.
1344  QUrl theURL(URL);
1345  URL = theURL.host();
1346  if (URL.isEmpty())
1347  return false;
1348 
1349  LOG(VB_UPNP, LOG_INFO, "Trying default DB credentials at " + URL);
1351 
1352  return true;
1353 }
1354 
1356 {
1357  if (e->type() == (QEvent::Type) MythEvent::MythEventMessage)
1358  {
1359  if (disableeventpopup)
1360  return true;
1361 
1363  {
1365  }
1366 
1367  MythEvent *me = (MythEvent*)e;
1368  if (me->Message() == "VERSION_MISMATCH" && (1 == me->ExtraDataCount()))
1369  ShowVersionMismatchPopup(me->ExtraData(0).toUInt());
1370  else if (me->Message() == "CONNECTION_FAILURE")
1372  else if (me->Message() == "PERSISTENT_CONNECTION_FAILURE")
1374  else if (me->Message() == "CONNECTION_RESTABLISHED")
1376  return true;
1377  }
1378 
1379  return QObject::event(e);
1380 }
1381 
1383 {
1384  QDateTime now = MythDate::current();
1385 
1386  if (!GetNotificationCenter() || !m_ui || !m_ui->IsScreenSetup())
1387  return;
1388 
1389  if (m_lastCheck.isValid() && now < m_lastCheck)
1390  return;
1391 
1392  // When WOL is disallowed, standy mode,
1393  // we should not show connection failures.
1394  if (!gCoreContext->IsWOLAllowed())
1395  return;
1396 
1397  m_lastCheck = now.addMSecs(5000); // don't refresh notification more than every 5s
1398 
1399  QString description = (persistent) ?
1400  QObject::tr(
1401  "The connection to the master backend "
1402  "server has gone away for some reason. "
1403  "Is it running?") :
1404  QObject::tr(
1405  "Could not connect to the master backend server. Is "
1406  "it running? Is the IP address set for it in "
1407  "mythtv-setup correct?");
1408 
1409  QString message = QObject::tr("Could not connect to master backend");
1410  MythErrorNotification n(message, _Location, description);
1411  n.SetId(m_registration);
1412  n.SetParent(this);
1414 }
1415 
1417 {
1418  if (!GetNotificationCenter())
1419  return;
1420 
1421  if (!m_lastCheck.isValid())
1422  return;
1423 
1424  MythCheckNotification n(QObject::tr("Backend is online"), _Location);
1425  n.SetId(m_registration);
1426  n.SetParent(this);
1427  n.SetDuration(5);
1429  m_lastCheck = QDateTime();
1430 }
1431 
1433 {
1434  if (MBEversionPopup)
1435  return;
1436 
1437  QString message =
1438  QObject::tr(
1439  "The server uses network protocol version %1, "
1440  "but this client only understands version %2. "
1441  "Make sure you are running compatible versions of "
1442  "the backend and frontend.")
1443  .arg(remote_version).arg(MYTH_PROTO_VERSION);
1444 
1445  if (HasMythMainWindow() && m_ui && m_ui->IsScreenSetup())
1446  {
1448  message, m_sh, SLOT(VersionMismatchPopupClosed()));
1449  }
1450  else
1451  {
1452  LOG(VB_GENERAL, LOG_ERR, LOC + message);
1453  qApp->exit(GENERIC_EXIT_SOCKET_ERROR);
1454  }
1455 }
1456 
1457 // Process Events while waiting for connection
1458 // return true if progress is 100%
1460 {
1461 // bool ret = false;
1462 // if (m_guiStartup)
1463 // ret = m_guiStartup->updateProgress();
1464  qApp->processEvents(QEventLoop::AllEvents, 250);
1465  qApp->processEvents(QEventLoop::AllEvents, 250);
1466 // return ret;
1467 }
1468 
1469 // cache some settings in cache/contextcache.xml
1470 // only call this if the database is available.
1471 
1472 const QString MythContextPrivate::settingsToSave[] =
1473 { "Theme", "Language", "Country", "GuiHeight",
1474  "GuiOffsetX", "GuiOffsetY", "GuiWidth", "RunFrontendInWindow",
1475  "AlwaysOnTop", "HideMouseCursor", "ThemePainter", "libCECEnabled" };
1476 
1477 
1479 {
1480  if (!m_gui)
1481  return true;
1482  QString cacheDirName = GetConfDir() + "/cache/";
1483  QDir dir(cacheDirName);
1484  dir.mkpath(cacheDirName);
1485  XmlConfiguration config = XmlConfiguration("cache/contextcache.xml");
1486  static const int arraySize = sizeof(settingsToSave)/sizeof(settingsToSave[0]);
1487  for (int ix = 0; ix < arraySize; ix++)
1488  {
1489  QString cacheValue = config.GetValue("Settings/"+settingsToSave[ix],QString());
1491  QString value = gCoreContext->GetSetting(settingsToSave[ix],QString());
1492  if (value != cacheValue)
1493  {
1494  config.SetValue("Settings/"+settingsToSave[ix],value);
1495  m_settingsCacheDirty = true;
1496  }
1497  }
1499  return config.Save();
1500 }
1501 
1503 {
1504  if (!m_gui)
1505  return;
1506  XmlConfiguration config = XmlConfiguration("cache/contextcache.xml");
1507  static const int arraySize = sizeof(settingsToSave)/sizeof(settingsToSave[0]);
1508  for (int ix = 0; ix < arraySize; ix++)
1509  {
1510  if (!gCoreContext->GetSetting(settingsToSave[ix],QString()).isEmpty())
1511  continue;
1512  QString value = config.GetValue("Settings/"+settingsToSave[ix],QString());
1513  if (!value.isEmpty())
1515  }
1516  // Prevent power off TV after temporary window
1517  gCoreContext->OverrideSettingForSession("PowerOffTVAllowed", 0);
1518 
1519  QString language = gCoreContext->GetSetting("Language",QString());
1520  MythTranslation::load("mythfrontend");
1521 }
1522 
1524 {
1525  QString language = gCoreContext->GetSetting("Language",QString());
1526  static const int arraySize = sizeof(settingsToSave)/sizeof(settingsToSave[0]);
1527  for (int ix = 0; ix < arraySize; ix++)
1528  {
1530  }
1531  // Restore power off TV setting
1532  gCoreContext->ClearOverrideSettingForSession("PowerOffTVAllowed");
1533 
1534  if (language != gCoreContext->GetSetting("Language",QString()))
1535  MythTranslation::load("mythfrontend");
1536 }
1537 
1538 
1540 {
1541  d->MBEversionPopup = NULL;
1542  qApp->exit(GENERIC_EXIT_SOCKET_ERROR);
1543 }
1544 
1545 MythContext::MythContext(const QString &binversion, bool needsBackend)
1546  : d(NULL), app_binary_version(binversion)
1547 {
1548 #ifdef _WIN32
1549  static bool WSAStarted = false;
1550  if (!WSAStarted) {
1551  WSADATA wsadata;
1552  int res = WSAStartup(MAKEWORD(2, 0), &wsadata);
1553  LOG(VB_SOCKET, LOG_INFO,
1554  QString("WSAStartup returned %1").arg(res));
1555  }
1556 #endif
1557 
1558  d = new MythContextPrivate(this);
1559  d->needsBackend = needsBackend;
1560 
1562 
1563  if (!gCoreContext || !gCoreContext->Init())
1564  {
1565  LOG(VB_GENERAL, LOG_EMERG, LOC + "Unable to allocate MythCoreContext");
1566  qApp->exit(GENERIC_EXIT_NO_MYTHCONTEXT);
1567  }
1568 }
1569 
1570 bool MythContext::Init(const bool gui,
1571  const bool promptForBackend,
1572  const bool disableAutoDiscovery,
1573  const bool ignoreDB)
1574 {
1575  if (!d)
1576  {
1577  LOG(VB_GENERAL, LOG_EMERG, LOC + "Init() Out-of-memory");
1578  return false;
1579  }
1580 
1581  SetDisableEventPopup(true);
1582 
1584  {
1585  LOG(VB_GENERAL, LOG_EMERG,
1586  QString("Application binary version (%1) does not "
1587  "match libraries (%2)")
1589 
1590  QString warning = QObject::tr(
1591  "This application is not compatible "
1592  "with the installed MythTV libraries.");
1593  if (gui)
1594  {
1595  d->TempMainWindow(false);
1596  ShowOkPopup(warning);
1597  }
1598  LOG(VB_GENERAL, LOG_WARNING, warning);
1599 
1600  return false;
1601  }
1602 
1603 #ifdef _WIN32
1604  // HOME environment variable might not be defined
1605  // some libraries will fail without it
1606  QString home = getenv("HOME");
1607  if (home.isEmpty())
1608  {
1609  home = getenv("LOCALAPPDATA"); // Vista
1610  if (home.isEmpty())
1611  home = getenv("APPDATA"); // XP
1612  if (home.isEmpty())
1613  home = QString("."); // getenv("TEMP")?
1614 
1615  _putenv(QString("HOME=%1").arg(home).toLocal8Bit().constData());
1616  }
1617 #endif
1618 
1619  // If HOME isn't defined, we won't be able to use default confdir of
1620  // $HOME/.mythtv nor can we rely on a MYTHCONFDIR that references $HOME
1621  QString homedir = QDir::homePath();
1622  QString confdir = getenv("MYTHCONFDIR");
1623  if ((homedir.isEmpty() || homedir == "/") &&
1624  (confdir.isEmpty() || confdir.contains("$HOME")))
1625  {
1626  QString warning = "Cannot locate your home directory."
1627  " Please set the environment variable HOME";
1628  if (gui)
1629  {
1630  d->TempMainWindow(false);
1631  ShowOkPopup(warning);
1632  }
1633  LOG(VB_GENERAL, LOG_WARNING, warning);
1634 
1635  return false;
1636  }
1637 
1638  if (!d->Init(gui, promptForBackend, disableAutoDiscovery, ignoreDB))
1639  {
1640  return false;
1641  }
1642 
1643  SetDisableEventPopup(false);
1645  if (d->m_settingsCacheDirty)
1646  {
1648  d->m_settingsCacheDirty = false;
1649  }
1651 
1652  return true;
1653 }
1654 
1656 {
1657  if (MThreadPool::globalInstance()->activeThreadCount())
1658  LOG(VB_GENERAL, LOG_INFO, "Waiting for threads to exit.");
1659 
1661  logStop();
1662 
1663  SSDP::Shutdown();
1665 
1666  delete gCoreContext;
1667  gCoreContext = NULL;
1668 
1669  delete d;
1670 }
1671 
1673 {
1674  d->disableeventpopup = check;
1675 }
1676 
1678 {
1679  return d->m_DBparams;
1680 }
1681 
1683 {
1684  return d->SaveDatabaseParams(params, false);
1685 }
1686 
1688 {
1689  return d->saveSettingsCache();
1690 }
1691 
1692 /* 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:73
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?