4 from __future__ import with_statement
12 from PyQt4 import QtGui
13 from PyQt4 import QtCore
16 from util import qtpie
17 from util import qui_utils
18 from util import misc as misc_utils
23 _moduleLogger = logging.getLogger(__name__)
27 class Dialcentral(object):
30 os.path.join(os.path.dirname(__file__), "../share"),
31 os.path.join(os.path.dirname(__file__), "../data"),
34 def __init__(self, app):
37 self._hiddenCategories = set()
38 self._hiddenUnits = {}
39 self._clipboard = QtGui.QApplication.clipboard()
41 self._mainWindow = None
43 self._fullscreenAction = QtGui.QAction(None)
44 self._fullscreenAction.setText("Fullscreen")
45 self._fullscreenAction.setCheckable(True)
46 self._fullscreenAction.setShortcut(QtGui.QKeySequence("CTRL+Enter"))
47 self._fullscreenAction.toggled.connect(self._on_toggle_fullscreen)
49 self._logAction = QtGui.QAction(None)
50 self._logAction.setText("Log")
51 self._logAction.setShortcut(QtGui.QKeySequence("CTRL+l"))
52 self._logAction.triggered.connect(self._on_log)
54 self._quitAction = QtGui.QAction(None)
55 self._quitAction.setText("Quit")
56 self._quitAction.setShortcut(QtGui.QKeySequence("CTRL+q"))
57 self._quitAction.triggered.connect(self._on_quit)
59 self._app.lastWindowClosed.connect(self._on_app_quit)
60 self._mainWindow = MainWindow(None, self)
61 self._mainWindow.window.destroyed.connect(self._on_child_close)
65 self._mainWindow.show()
66 self._idleDelay = QtCore.QTimer()
67 self._idleDelay.setSingleShot(True)
68 self._idleDelay.setInterval(0)
69 self._idleDelay.timeout.connect(lambda: self._mainWindow.start())
70 self._idleDelay.start()
72 def load_settings(self):
74 config = ConfigParser.SafeConfigParser()
75 config.read(constants._user_settings_)
77 _moduleLogger.info("No settings")
80 _moduleLogger.info("Settings were corrupt")
82 except ConfigParser.MissingSectionHeaderError:
83 _moduleLogger.info("Settings were corrupt")
86 _moduleLogger.exception("Unknown loading error")
93 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
94 for i in xrange(len(self._mainWindow.get_default_credentials()))
96 isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
97 tabIndex = config.getint(constants.__pretty_app_name__, "tab")
98 except ConfigParser.NoOptionError, e:
100 "Settings file %s is missing option %s" % (
101 constants._user_settings_,
105 except ConfigParser.NoSectionError, e:
107 "Settings file %s is missing section %s" % (
108 constants._user_settings_,
114 _moduleLogger.exception("Unknown loading error")
118 base64.b64decode(blob)
121 self._mainWindow.set_default_credentials(*creds)
122 self._fullscreenAction.setChecked(isFullscreen)
123 self._mainWindow.set_current_tab(tabIndex)
124 self._mainWindow.load_settings(config)
126 def save_settings(self):
127 config = ConfigParser.SafeConfigParser()
129 config.add_section(constants.__pretty_app_name__)
130 config.set(constants.__pretty_app_name__, "tab", str(self._mainWindow.get_current_tab()))
131 config.set(constants.__pretty_app_name__, "fullscreen", str(self._fullscreenAction.isChecked()))
132 for i, value in enumerate(self._mainWindow.get_default_credentials()):
133 blob = base64.b64encode(value)
134 config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
136 self._mainWindow.save_settings(config)
138 with open(constants._user_settings_, "wb") as configFile:
139 config.write(configFile)
142 def fsContactsPath(self):
143 return os.path.join(constants._data_path_, "contacts")
146 def fullscreenAction(self):
147 return self._fullscreenAction
151 return self._logAction
154 def quitAction(self):
155 return self._quitAction
157 def _close_windows(self):
158 if self._mainWindow is not None:
159 self._mainWindow.window.destroyed.disconnect(self._on_child_close)
160 self._mainWindow.close()
161 self._mainWindow = None
164 @QtCore.pyqtSlot(bool)
165 @misc_utils.log_exception(_moduleLogger)
166 def _on_app_quit(self, checked = False):
168 self._mainWindow.destroy()
170 @QtCore.pyqtSlot(QtCore.QObject)
171 @misc_utils.log_exception(_moduleLogger)
172 def _on_child_close(self, obj = None):
173 self._mainWindow = None
176 @QtCore.pyqtSlot(bool)
177 @misc_utils.log_exception(_moduleLogger)
178 def _on_toggle_fullscreen(self, checked = False):
179 for window in self._walk_children():
180 window.set_fullscreen(checked)
183 @QtCore.pyqtSlot(bool)
184 @misc_utils.log_exception(_moduleLogger)
185 def _on_log(self, checked = False):
186 with open(constants._user_logpath_, "r") as f:
187 logLines = f.xreadlines()
188 log = "".join(logLines)
189 self._clipboard.setText(log)
192 @QtCore.pyqtSlot(bool)
193 @misc_utils.log_exception(_moduleLogger)
194 def _on_quit(self, checked = False):
195 self._close_windows()
198 class DelayedWidget(object):
200 def __init__(self, app, settingsNames):
201 self._layout = QtGui.QVBoxLayout()
202 self._widget = QtGui.QWidget()
203 self._widget.setLayout(self._layout)
204 self._settings = dict((name, "") for name in settingsNames)
207 self._isEnabled = True
214 return self._child is not None
216 def set_child(self, child):
217 if self._child is not None:
218 self._layout.removeWidget(self._child.toplevel)
220 if self._child is not None:
221 self._layout.addWidget(self._child.toplevel)
223 self._child.set_settings(self._settings)
228 self._child.disable()
231 self._isEnabled = True
232 if self._child is not None:
236 self._isEnabled = False
237 if self._child is not None:
238 self._child.disable()
241 if self._child is not None:
244 def refresh(self, force=True):
245 if self._child is not None:
246 self._child.refresh(force)
248 def get_settings(self):
249 if self._child is not None:
250 return self._child.get_settings()
252 return self._settings
254 def set_settings(self, settings):
255 if self._child is not None:
256 self._child.set_settings(settings)
258 self._settings = settings
261 def _tab_factory(tab, app, session, errorLog):
263 return gv_views.__dict__[tab](app, session, errorLog)
266 class MainWindow(object):
280 assert len(_TAB_TITLES) == MAX_TABS
288 assert len(_TAB_ICONS) == MAX_TABS
291 functools.partial(_tab_factory, "Dialpad"),
292 functools.partial(_tab_factory, "History"),
293 functools.partial(_tab_factory, "Messages"),
294 functools.partial(_tab_factory, "Contacts"),
296 assert len(_TAB_CLASS) == MAX_TABS
298 # Hack to allow delay importing/loading of tabs
299 _TAB_SETTINGS_NAMES = [
303 ("selectedAddressbook", ),
305 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
307 def __init__(self, parent, app):
309 self._session = session.Session(constants._data_path_)
310 self._session.error.connect(self._on_session_error)
311 self._session.loggedIn.connect(self._on_login)
312 self._session.loggedOut.connect(self._on_logout)
313 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
314 self._defaultCredentials = "", ""
315 self._curentCredentials = "", ""
317 self._credentialsDialog = None
318 self._smsEntryDialog = None
319 self._accountDialog = None
321 self._errorLog = qui_utils.QErrorLog()
322 self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
324 self._tabsContents = [
325 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
326 for i in xrange(self.MAX_TABS)
328 for tab in self._tabsContents:
331 self._tabWidget = QtGui.QTabWidget()
332 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
333 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
335 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
337 for tabIndex, (tabTitle, tabIcon) in enumerate(
338 zip(self._TAB_TITLES, self._TAB_ICONS)
340 if _dataPath is None:
341 for path in self._app._DATA_PATHS:
342 if os.path.exists(os.path.join(path, tabIcon)):
346 if _dataPath is None:
347 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
349 icon = QtGui.QIcon(os.path.join(_dataPath, tabIcon))
350 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, "")
352 icon = QtGui.QIcon(os.path.join(_dataPath, tabIcon))
353 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
354 self._tabWidget.currentChanged.connect(self._on_tab_changed)
355 self._tabWidget.setContentsMargins(0, 0, 0, 0)
357 self._layout = QtGui.QVBoxLayout()
358 self._layout.setContentsMargins(0, 0, 0, 0)
359 self._layout.addWidget(self._errorDisplay.toplevel)
360 self._layout.addWidget(self._tabWidget)
362 centralWidget = QtGui.QWidget()
363 centralWidget.setLayout(self._layout)
364 centralWidget.setContentsMargins(0, 0, 0, 0)
366 self._window = QtGui.QMainWindow(parent)
367 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
368 qui_utils.set_autorient(self._window, True)
369 qui_utils.set_stackable(self._window, True)
370 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
371 self._window.setCentralWidget(centralWidget)
373 self._loginTabAction = QtGui.QAction(None)
374 self._loginTabAction.setText("Login")
375 self._loginTabAction.triggered.connect(self._on_login_requested)
377 self._importTabAction = QtGui.QAction(None)
378 self._importTabAction.setText("Import")
379 self._importTabAction.triggered.connect(self._on_import)
381 self._accountTabAction = QtGui.QAction(None)
382 self._accountTabAction.setText("Account")
383 self._accountTabAction.triggered.connect(self._on_account)
385 self._refreshTabAction = QtGui.QAction(None)
386 self._refreshTabAction.setText("Refresh")
387 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
388 self._refreshTabAction.triggered.connect(self._on_refresh)
390 self._closeWindowAction = QtGui.QAction(None)
391 self._closeWindowAction.setText("Close")
392 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
393 self._closeWindowAction.triggered.connect(self._on_close_window)
396 fileMenu = self._window.menuBar().addMenu("&File")
397 fileMenu.addAction(self._loginTabAction)
398 fileMenu.addAction(self._refreshTabAction)
400 toolsMenu = self._window.menuBar().addMenu("&Tools")
401 toolsMenu.addAction(self._accountTabAction)
402 toolsMenu.addAction(self._importTabAction)
404 self._window.addAction(self._closeWindowAction)
405 self._window.addAction(self._app.quitAction)
406 self._window.addAction(self._app.fullscreenAction)
408 fileMenu = self._window.menuBar().addMenu("&File")
409 fileMenu.addAction(self._loginTabAction)
410 fileMenu.addAction(self._refreshTabAction)
411 fileMenu.addAction(self._closeWindowAction)
412 fileMenu.addAction(self._app.quitAction)
414 viewMenu = self._window.menuBar().addMenu("&View")
415 viewMenu.addAction(self._app.fullscreenAction)
417 toolsMenu = self._window.menuBar().addMenu("&Tools")
418 toolsMenu.addAction(self._accountTabAction)
419 toolsMenu.addAction(self._importTabAction)
421 self._window.addAction(self._app.logAction)
423 self._initialize_tab(self._tabWidget.currentIndex())
424 self.set_fullscreen(self._app.fullscreenAction.isChecked())
430 def set_default_credentials(self, username, password):
431 self._defaultCredentials = username, password
433 def get_default_credentials(self):
434 return self._defaultCredentials
436 def walk_children(self):
440 assert self._session.state == self._session.LOGGEDOUT_STATE
441 if self._defaultCredentials != ("", ""):
442 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
443 self._curentCredentials = username, password
444 self._session.login(username, password)
446 self._prompt_for_login()
449 for child in self.walk_children():
450 child.window.destroyed.disconnect(self._on_child_close)
455 if self._session.state != self._session.LOGGEDOUT_STATE:
456 self._session.logout()
458 def get_current_tab(self):
459 return self._tabWidget.currentIndex()
461 def set_current_tab(self, tabIndex):
462 self._tabWidget.setCurrentIndex(tabIndex)
464 def load_settings(self, config):
465 backendId = 2 # For backwards compatibility
466 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
467 sectionName = "%s - %s" % (backendId, tabTitle)
468 settings = self._tabsContents[tabIndex].get_settings()
469 for settingName in settings.iterkeys():
471 settingValue = config.get(sectionName, settingName)
472 except ConfigParser.NoOptionError, e:
474 "Settings file %s is missing section %s" % (
475 constants._user_settings_,
480 except ConfigParser.NoSectionError, e:
482 "Settings file %s is missing section %s" % (
483 constants._user_settings_,
489 _moduleLogger.exception("Unknown loading error")
491 settings[settingName] = settingValue
492 self._tabsContents[tabIndex].set_settings(settings)
494 def save_settings(self, config):
495 backendId = 2 # For backwards compatibility
496 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
497 sectionName = "%s - %s" % (backendId, tabTitle)
498 config.add_section(sectionName)
499 tabSettings = self._tabsContents[tabIndex].get_settings()
500 for settingName, settingValue in tabSettings.iteritems():
501 config.set(sectionName, settingName, settingValue)
505 for child in self.walk_children():
509 for child in self.walk_children():
513 def set_fullscreen(self, isFullscreen):
515 self._window.showFullScreen()
517 self._window.showNormal()
518 for child in self.walk_children():
519 child.set_fullscreen(isFullscreen)
521 def _initialize_tab(self, index):
522 assert index < self.MAX_TABS
523 if not self._tabsContents[index].has_child():
524 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
525 self._tabsContents[index].set_child(tab)
526 self._tabsContents[index].refresh(force=False)
528 def _prompt_for_login(self):
529 if self._credentialsDialog is None:
531 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
532 username, password = self._credentialsDialog.run(
533 self._defaultCredentials[0], self._defaultCredentials[1], self.window
535 self._curentCredentials = username, password
536 self._session.login(username, password)
538 def _show_account_dialog(self):
539 if self._accountDialog is None:
541 self._accountDialog = dialogs.AccountDialog(self._app)
542 self._accountDialog.accountNumber = self._session.get_account_number()
543 response = self._accountDialog.run()
544 if response == QtGui.QDialog.Accepted:
545 if self._accountDialog.doClear:
546 self._session.logout_and_clear()
547 elif response == QtGui.QDialog.Rejected:
548 _moduleLogger.info("Cancelled")
550 _moduleLogger.info("Unknown response")
552 @QtCore.pyqtSlot(str)
553 @misc_utils.log_exception(_moduleLogger)
554 def _on_session_error(self, message):
555 self._errorLog.push_message(message)
558 @misc_utils.log_exception(_moduleLogger)
560 if self._defaultCredentials != self._curentCredentials:
561 self._show_account_dialog()
562 self._defaultCredentials = self._curentCredentials
563 for tab in self._tabsContents:
567 @misc_utils.log_exception(_moduleLogger)
568 def _on_logout(self):
569 for tab in self._tabsContents:
573 @misc_utils.log_exception(_moduleLogger)
574 def _on_recipients_changed(self):
575 if self._session.draft.get_num_contacts() == 0:
578 if self._smsEntryDialog is None:
580 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
584 @QtCore.pyqtSlot(bool)
585 @misc_utils.log_exception(_moduleLogger)
586 def _on_login_requested(self, checked = True):
587 self._prompt_for_login()
589 @QtCore.pyqtSlot(int)
590 @misc_utils.log_exception(_moduleLogger)
591 def _on_tab_changed(self, index):
592 self._initialize_tab(index)
595 @QtCore.pyqtSlot(bool)
596 @misc_utils.log_exception(_moduleLogger)
597 def _on_refresh(self, checked = True):
598 index = self._tabWidget.currentIndex()
599 self._tabsContents[index].refresh(force=True)
602 @QtCore.pyqtSlot(bool)
603 @misc_utils.log_exception(_moduleLogger)
604 def _on_import(self, checked = True):
605 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
609 shutil.copy2(csvName, self._app.fsContactsPath)
610 self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
613 @QtCore.pyqtSlot(bool)
614 @misc_utils.log_exception(_moduleLogger)
615 def _on_account(self, checked = True):
616 self._show_account_dialog()
619 @QtCore.pyqtSlot(bool)
620 @misc_utils.log_exception(_moduleLogger)
621 def _on_close_window(self, checked = True):
626 app = QtGui.QApplication([])
627 handle = Dialcentral(app)
632 if __name__ == "__main__":
635 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
636 logging.basicConfig(level=logging.DEBUG, format=logFormat)
638 os.makedirs(constants._data_path_)