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__)
26 class Dialcentral(object):
29 os.path.join(os.path.dirname(__file__), "../share"),
30 os.path.join(os.path.dirname(__file__), "../data"),
33 def __init__(self, app):
36 self._hiddenCategories = set()
37 self._hiddenUnits = {}
38 self._clipboard = QtGui.QApplication.clipboard()
40 self.notifyOnMissed = False
41 self.notifyOnVoicemail = False
42 self.notifyOnSms = False
44 self._mainWindow = None
46 self._fullscreenAction = QtGui.QAction(None)
47 self._fullscreenAction.setText("Fullscreen")
48 self._fullscreenAction.setCheckable(True)
49 self._fullscreenAction.setShortcut(QtGui.QKeySequence("CTRL+Enter"))
50 self._fullscreenAction.toggled.connect(self._on_toggle_fullscreen)
52 self._logAction = QtGui.QAction(None)
53 self._logAction.setText("Log")
54 self._logAction.setShortcut(QtGui.QKeySequence("CTRL+l"))
55 self._logAction.triggered.connect(self._on_log)
57 self._quitAction = QtGui.QAction(None)
58 self._quitAction.setText("Quit")
59 self._quitAction.setShortcut(QtGui.QKeySequence("CTRL+q"))
60 self._quitAction.triggered.connect(self._on_quit)
62 self._app.lastWindowClosed.connect(self._on_app_quit)
63 self._mainWindow = MainWindow(None, self)
64 self._mainWindow.window.destroyed.connect(self._on_child_close)
68 if alarm_handler.AlarmHandler is not alarm_handler._NoneAlarmHandler:
69 self._alarmHandler = alarm_handler.AlarmHandler()
71 self._alarmHandler = None
72 except (ImportError, OSError):
73 self._alarmHandler = None
75 _moduleLogger.exception("Notification failure")
76 self._alarmHandler = None
77 if self._alarmHandler is None:
78 _moduleLogger.info("No notification support")
82 self._mainWindow.show()
83 self._idleDelay = QtCore.QTimer()
84 self._idleDelay.setSingleShot(True)
85 self._idleDelay.setInterval(0)
86 self._idleDelay.timeout.connect(lambda: self._mainWindow.start())
87 self._idleDelay.start()
89 def load_settings(self):
91 config = ConfigParser.SafeConfigParser()
92 config.read(constants._user_settings_)
94 _moduleLogger.info("No settings")
97 _moduleLogger.info("Settings were corrupt")
99 except ConfigParser.MissingSectionHeaderError:
100 _moduleLogger.info("Settings were corrupt")
103 _moduleLogger.exception("Unknown loading error")
110 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
111 for i in xrange(len(self._mainWindow.get_default_credentials()))
113 isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
114 tabIndex = config.getint(constants.__pretty_app_name__, "tab")
115 except ConfigParser.NoOptionError, e:
117 "Settings file %s is missing option %s" % (
118 constants._user_settings_,
122 except ConfigParser.NoSectionError, e:
124 "Settings file %s is missing section %s" % (
125 constants._user_settings_,
131 _moduleLogger.exception("Unknown loading error")
134 if self._alarmHandler is not None:
136 self._alarmHandler.load_settings(config, "alarm")
137 self.notifyOnMissed = config.getboolean("2 - Account Info", "notifyOnMissed")
138 self.notifyOnVoicemail = config.getboolean("2 - Account Info", "notifyOnVoicemail")
139 self.notifyOnSms = config.getboolean("2 - Account Info", "notifyOnSms")
140 except ConfigParser.NoOptionError, e:
142 "Settings file %s is missing option %s" % (
143 constants._user_settings_,
147 except ConfigParser.NoSectionError, e:
149 "Settings file %s is missing section %s" % (
150 constants._user_settings_,
156 _moduleLogger.exception("Unknown loading error")
160 base64.b64decode(blob)
163 self._mainWindow.set_default_credentials(*creds)
164 self._fullscreenAction.setChecked(isFullscreen)
165 self._mainWindow.set_current_tab(tabIndex)
166 self._mainWindow.load_settings(config)
168 def save_settings(self):
169 _moduleLogger.info("Saving settings")
170 config = ConfigParser.SafeConfigParser()
172 config.add_section(constants.__pretty_app_name__)
173 config.set(constants.__pretty_app_name__, "tab", str(self._mainWindow.get_current_tab()))
174 config.set(constants.__pretty_app_name__, "fullscreen", str(self._fullscreenAction.isChecked()))
175 for i, value in enumerate(self._mainWindow.get_default_credentials()):
176 blob = base64.b64encode(value)
177 config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
179 if self._alarmHandler is not None:
180 config.add_section("alarm")
181 self._alarmHandler.save_settings(config, "alarm")
182 config.add_section("2 - Account Info")
183 config.set("2 - Account Info", "notifyOnMissed", repr(self.notifyOnMissed))
184 config.set("2 - Account Info", "notifyOnVoicemail", repr(self.notifyOnVoicemail))
185 config.set("2 - Account Info", "notifyOnSms", repr(self.notifyOnSms))
187 self._mainWindow.save_settings(config)
189 with open(constants._user_settings_, "wb") as configFile:
190 config.write(configFile)
192 def get_icon(self, name):
193 if self._dataPath is None:
194 for path in self._DATA_PATHS:
195 if os.path.exists(os.path.join(path, name)):
196 self._dataPath = path
198 if self._dataPath is not None:
199 icon = QtGui.QIcon(os.path.join(self._dataPath, name))
205 def fsContactsPath(self):
206 return os.path.join(constants._data_path_, "contacts")
209 def fullscreenAction(self):
210 return self._fullscreenAction
214 return self._logAction
217 def quitAction(self):
218 return self._quitAction
221 def alarmHandler(self):
222 return self._alarmHandler
224 def _walk_children(self):
225 if self._mainWindow is not None:
226 return (self._mainWindow, )
230 def _close_windows(self):
231 if self._mainWindow is not None:
233 self._mainWindow.window.destroyed.disconnect(self._on_child_close)
234 self._mainWindow.close()
235 self._mainWindow = None
238 @QtCore.pyqtSlot(bool)
239 @misc_utils.log_exception(_moduleLogger)
240 def _on_app_quit(self, checked = False):
241 if self._mainWindow is not None:
243 self._mainWindow.destroy()
245 @QtCore.pyqtSlot(QtCore.QObject)
246 @misc_utils.log_exception(_moduleLogger)
247 def _on_child_close(self, obj = None):
248 if self._mainWindow is not None:
250 self._mainWindow = None
253 @QtCore.pyqtSlot(bool)
254 @misc_utils.log_exception(_moduleLogger)
255 def _on_toggle_fullscreen(self, checked = False):
256 for window in self._walk_children():
257 window.set_fullscreen(checked)
260 @QtCore.pyqtSlot(bool)
261 @misc_utils.log_exception(_moduleLogger)
262 def _on_log(self, checked = False):
263 with open(constants._user_logpath_, "r") as f:
264 logLines = f.xreadlines()
265 log = "".join(logLines)
266 self._clipboard.setText(log)
269 @QtCore.pyqtSlot(bool)
270 @misc_utils.log_exception(_moduleLogger)
271 def _on_quit(self, checked = False):
272 self._close_windows()
275 class DelayedWidget(object):
277 def __init__(self, app, settingsNames):
278 self._layout = QtGui.QVBoxLayout()
279 self._layout.setContentsMargins(0, 0, 0, 0)
280 self._widget = QtGui.QWidget()
281 self._widget.setContentsMargins(0, 0, 0, 0)
282 self._widget.setLayout(self._layout)
283 self._settings = dict((name, "") for name in settingsNames)
286 self._isEnabled = True
293 return self._child is not None
295 def set_child(self, child):
296 if self._child is not None:
297 self._layout.removeWidget(self._child.toplevel)
299 if self._child is not None:
300 self._layout.addWidget(self._child.toplevel)
302 self._child.set_settings(self._settings)
307 self._child.disable()
310 self._isEnabled = True
311 if self._child is not None:
315 self._isEnabled = False
316 if self._child is not None:
317 self._child.disable()
320 if self._child is not None:
323 def refresh(self, force=True):
324 if self._child is not None:
325 self._child.refresh(force)
327 def get_settings(self):
328 if self._child is not None:
329 return self._child.get_settings()
331 return self._settings
333 def set_settings(self, settings):
334 if self._child is not None:
335 self._child.set_settings(settings)
337 self._settings = settings
340 def _tab_factory(tab, app, session, errorLog):
342 return gv_views.__dict__[tab](app, session, errorLog)
345 class MainWindow(object):
359 assert len(_TAB_TITLES) == MAX_TABS
367 assert len(_TAB_ICONS) == MAX_TABS
370 functools.partial(_tab_factory, "Dialpad"),
371 functools.partial(_tab_factory, "History"),
372 functools.partial(_tab_factory, "Messages"),
373 functools.partial(_tab_factory, "Contacts"),
375 assert len(_TAB_CLASS) == MAX_TABS
377 # Hack to allow delay importing/loading of tabs
378 _TAB_SETTINGS_NAMES = [
382 ("selectedAddressbook", ),
384 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
386 def __init__(self, parent, app):
389 self._errorLog = qui_utils.QErrorLog()
390 self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
392 self._session = session.Session(self._errorLog, constants._data_path_)
393 self._session.error.connect(self._on_session_error)
394 self._session.loggedIn.connect(self._on_login)
395 self._session.loggedOut.connect(self._on_logout)
396 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
397 self._defaultCredentials = "", ""
398 self._curentCredentials = "", ""
401 self._credentialsDialog = None
402 self._smsEntryDialog = None
403 self._accountDialog = None
404 self._aboutDialog = None
406 self._tabsContents = [
407 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
408 for i in xrange(self.MAX_TABS)
410 for tab in self._tabsContents:
413 self._tabWidget = QtGui.QTabWidget()
414 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
415 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
417 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
418 defaultTabIconSize = self._tabWidget.iconSize()
419 defaultTabIconWidth, defaultTabIconHeight = defaultTabIconSize.width(), defaultTabIconSize.height()
420 for tabIndex, (tabTitle, tabIcon) in enumerate(
421 zip(self._TAB_TITLES, self._TAB_ICONS)
423 icon = self._app.get_icon(tabIcon)
424 if constants.IS_MAEMO and icon is not None:
428 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
430 iconSize = icon.availableSizes()[0]
431 defaultTabIconWidth = max(defaultTabIconWidth, iconSize.width())
432 defaultTabIconHeight = max(defaultTabIconHeight, iconSize.height())
433 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
434 defaultTabIconWidth = max(defaultTabIconWidth, 32)
435 defaultTabIconHeight = max(defaultTabIconHeight, 32)
436 self._tabWidget.setIconSize(QtCore.QSize(defaultTabIconWidth, defaultTabIconHeight))
437 self._tabWidget.currentChanged.connect(self._on_tab_changed)
438 self._tabWidget.setContentsMargins(0, 0, 0, 0)
440 self._layout = QtGui.QVBoxLayout()
441 self._layout.setContentsMargins(0, 0, 0, 0)
442 self._layout.addWidget(self._errorDisplay.toplevel)
443 self._layout.addWidget(self._tabWidget)
445 centralWidget = QtGui.QWidget()
446 centralWidget.setLayout(self._layout)
447 centralWidget.setContentsMargins(0, 0, 0, 0)
449 self._window = QtGui.QMainWindow(parent)
450 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
451 qui_utils.set_autorient(self._window, True)
452 qui_utils.set_stackable(self._window, True)
453 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
454 self._window.setCentralWidget(centralWidget)
456 self._loginTabAction = QtGui.QAction(None)
457 self._loginTabAction.setText("Login")
458 self._loginTabAction.triggered.connect(self._on_login_requested)
460 self._importTabAction = QtGui.QAction(None)
461 self._importTabAction.setText("Import")
462 self._importTabAction.triggered.connect(self._on_import)
464 self._accountTabAction = QtGui.QAction(None)
465 self._accountTabAction.setText("Account")
466 self._accountTabAction.triggered.connect(self._on_account)
468 self._refreshTabAction = QtGui.QAction(None)
469 self._refreshTabAction.setText("Refresh")
470 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
471 self._refreshTabAction.triggered.connect(self._on_refresh)
473 self._aboutAction = QtGui.QAction(None)
474 self._aboutAction.setText("About")
475 self._aboutAction.triggered.connect(self._on_about)
477 self._closeWindowAction = QtGui.QAction(None)
478 self._closeWindowAction.setText("Close")
479 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
480 self._closeWindowAction.triggered.connect(self._on_close_window)
482 if constants.IS_MAEMO:
483 fileMenu = self._window.menuBar().addMenu("&File")
484 fileMenu.addAction(self._loginTabAction)
485 fileMenu.addAction(self._refreshTabAction)
487 toolsMenu = self._window.menuBar().addMenu("&Tools")
488 toolsMenu.addAction(self._accountTabAction)
489 toolsMenu.addAction(self._importTabAction)
490 toolsMenu.addAction(self._aboutAction)
492 self._window.addAction(self._closeWindowAction)
493 self._window.addAction(self._app.quitAction)
494 self._window.addAction(self._app.fullscreenAction)
496 fileMenu = self._window.menuBar().addMenu("&File")
497 fileMenu.addAction(self._loginTabAction)
498 fileMenu.addAction(self._refreshTabAction)
499 fileMenu.addAction(self._closeWindowAction)
500 fileMenu.addAction(self._app.quitAction)
502 viewMenu = self._window.menuBar().addMenu("&View")
503 viewMenu.addAction(self._app.fullscreenAction)
505 toolsMenu = self._window.menuBar().addMenu("&Tools")
506 toolsMenu.addAction(self._accountTabAction)
507 toolsMenu.addAction(self._importTabAction)
508 toolsMenu.addAction(self._aboutAction)
510 self._window.addAction(self._app.logAction)
512 self._initialize_tab(self._tabWidget.currentIndex())
513 self.set_fullscreen(self._app.fullscreenAction.isChecked())
519 def set_default_credentials(self, username, password):
520 self._defaultCredentials = username, password
522 def get_default_credentials(self):
523 return self._defaultCredentials
525 def walk_children(self):
529 assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
530 if self._defaultCredentials != ("", ""):
531 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
532 self._curentCredentials = username, password
533 self._session.login(username, password)
535 self._prompt_for_login()
538 for child in self.walk_children():
539 child.window.destroyed.disconnect(self._on_child_close)
542 self._credentialsDialog,
543 self._smsEntryDialog,
552 if self._session.state != self._session.LOGGEDOUT_STATE:
553 self._session.logout()
555 def get_current_tab(self):
556 return self._currentTab
558 def set_current_tab(self, tabIndex):
559 self._tabWidget.setCurrentIndex(tabIndex)
561 def load_settings(self, config):
562 backendId = 2 # For backwards compatibility
563 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
564 sectionName = "%s - %s" % (backendId, tabTitle)
565 settings = self._tabsContents[tabIndex].get_settings()
566 for settingName in settings.iterkeys():
568 settingValue = config.get(sectionName, settingName)
569 except ConfigParser.NoOptionError, e:
571 "Settings file %s is missing section %s" % (
572 constants._user_settings_,
577 except ConfigParser.NoSectionError, e:
579 "Settings file %s is missing section %s" % (
580 constants._user_settings_,
586 _moduleLogger.exception("Unknown loading error")
588 settings[settingName] = settingValue
589 self._tabsContents[tabIndex].set_settings(settings)
591 def save_settings(self, config):
592 backendId = 2 # For backwards compatibility
593 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
594 sectionName = "%s - %s" % (backendId, tabTitle)
595 config.add_section(sectionName)
596 tabSettings = self._tabsContents[tabIndex].get_settings()
597 for settingName, settingValue in tabSettings.iteritems():
598 config.set(sectionName, settingName, settingValue)
602 for child in self.walk_children():
606 for child in self.walk_children():
610 def set_fullscreen(self, isFullscreen):
612 self._window.showFullScreen()
614 self._window.showNormal()
615 for child in self.walk_children():
616 child.set_fullscreen(isFullscreen)
618 def _initialize_tab(self, index):
619 assert index < self.MAX_TABS, "Invalid tab"
620 if not self._tabsContents[index].has_child():
621 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
622 self._tabsContents[index].set_child(tab)
623 self._tabsContents[index].refresh(force=False)
625 def _prompt_for_login(self):
626 if self._credentialsDialog is None:
628 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
629 username, password = self._credentialsDialog.run(
630 self._defaultCredentials[0], self._defaultCredentials[1], self.window
632 self._curentCredentials = username, password
633 self._session.login(username, password)
635 def _show_account_dialog(self):
636 if self._accountDialog is None:
638 self._accountDialog = dialogs.AccountDialog(self._app)
639 if self._app.alarmHandler is None:
640 self._accountDialog.setIfNotificationsSupported(False)
641 if self._app.alarmHandler is not None:
642 self._accountDialog.notifications = self._app.alarmHandler.isEnabled
643 self._accountDialog.notificationTime = self._app.alarmHandler.recurrence
644 self._accountDialog.notifyOnMissed = self._app.notifyOnMissed
645 self._accountDialog.notifyOnVoicemail = self._app.notifyOnVoicemail
646 self._accountDialog.notifyOnSms = self._app.notifyOnSms
647 self._accountDialog.set_callbacks(
648 self._session.get_callback_numbers(), self._session.get_callback_number()
650 self._accountDialog.accountNumber = self._session.get_account_number()
651 response = self._accountDialog.run()
652 if response == QtGui.QDialog.Accepted:
653 if self._accountDialog.doClear:
654 self._session.logout_and_clear()
656 callbackNumber = self._accountDialog.selectedCallback
657 self._session.set_callback_number(callbackNumber)
658 if self._app.alarmHandler is not None:
659 self._app.alarmHandler.apply_settings(self._accountDialog.notifications, self._accountDialog.notificationTime)
660 self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
661 self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
662 self._app.notifyOnSms = self._accountDialog.notifyOnSms
663 elif response == QtGui.QDialog.Rejected:
664 _moduleLogger.info("Cancelled")
666 _moduleLogger.info("Unknown response")
668 @QtCore.pyqtSlot(str)
669 @misc_utils.log_exception(_moduleLogger)
670 def _on_session_error(self, message):
671 with qui_utils.notify_error(self._errorLog):
672 self._errorLog.push_error(message)
675 @misc_utils.log_exception(_moduleLogger)
677 with qui_utils.notify_error(self._errorLog):
678 changedAccounts = self._defaultCredentials != self._curentCredentials
679 noCallback = not self._session.get_callback_number()
680 if changedAccounts or noCallback:
681 self._show_account_dialog()
683 self._defaultCredentials = self._curentCredentials
685 for tab in self._tabsContents:
689 @misc_utils.log_exception(_moduleLogger)
690 def _on_logout(self):
691 with qui_utils.notify_error(self._errorLog):
692 for tab in self._tabsContents:
696 @misc_utils.log_exception(_moduleLogger)
697 def _on_recipients_changed(self):
698 with qui_utils.notify_error(self._errorLog):
699 if self._session.draft.get_num_contacts() == 0:
702 if self._smsEntryDialog is None:
704 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
707 @QtCore.pyqtSlot(bool)
708 @misc_utils.log_exception(_moduleLogger)
709 def _on_login_requested(self, checked = True):
710 with qui_utils.notify_error(self._errorLog):
711 self._prompt_for_login()
713 @QtCore.pyqtSlot(int)
714 @misc_utils.log_exception(_moduleLogger)
715 def _on_tab_changed(self, index):
716 with qui_utils.notify_error(self._errorLog):
717 self._currentTab = index
718 self._initialize_tab(index)
721 @QtCore.pyqtSlot(bool)
722 @misc_utils.log_exception(_moduleLogger)
723 def _on_refresh(self, checked = True):
724 with qui_utils.notify_error(self._errorLog):
725 self._tabsContents[self._currentTab].refresh(force=True)
728 @QtCore.pyqtSlot(bool)
729 @misc_utils.log_exception(_moduleLogger)
730 def _on_import(self, checked = True):
731 with qui_utils.notify_error(self._errorLog):
732 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
736 shutil.copy2(csvName, self._app.fsContactsPath)
737 self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
740 @QtCore.pyqtSlot(bool)
741 @misc_utils.log_exception(_moduleLogger)
742 def _on_account(self, checked = True):
743 with qui_utils.notify_error(self._errorLog):
744 self._show_account_dialog()
747 @QtCore.pyqtSlot(bool)
748 @misc_utils.log_exception(_moduleLogger)
749 def _on_about(self, checked = True):
750 with qui_utils.notify_error(self._errorLog):
751 if self._aboutDialog is None:
753 self._aboutDialog = dialogs.AboutDialog(self._app)
754 response = self._aboutDialog.run()
757 @QtCore.pyqtSlot(bool)
758 @misc_utils.log_exception(_moduleLogger)
759 def _on_close_window(self, checked = True):
764 app = QtGui.QApplication([])
765 handle = Dialcentral(app)
770 if __name__ == "__main__":
773 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
774 logging.basicConfig(level=logging.DEBUG, format=logFormat)
776 os.makedirs(constants._data_path_)