4 from __future__ import with_statement
11 import logging.handlers
13 from PyQt4 import QtGui
14 from PyQt4 import QtCore
19 from util import qtpie
20 from util import qwrappers
21 from util import qui_utils
22 from util import misc as misc_utils
27 _moduleLogger = logging.getLogger(__name__)
30 class Dialcentral(qwrappers.ApplicationWrapper):
33 os.path.join(os.path.dirname(__file__), "../share"),
34 os.path.join(os.path.dirname(__file__), "../data"),
37 def __init__(self, app):
39 self._aboutDialog = None
40 self.notifyOnMissed = False
41 self.notifyOnVoicemail = False
42 self.notifyOnSms = False
44 self._streamHandler = None
45 self._ledHandler = None
46 self._alarmHandler = alarm_handler.AlarmHandler()
48 qwrappers.ApplicationWrapper.__init__(self, app, constants)
50 def load_settings(self):
52 config = ConfigParser.SafeConfigParser()
53 config.read(constants._user_settings_)
55 _moduleLogger.info("No settings")
58 _moduleLogger.info("Settings were corrupt")
60 except ConfigParser.MissingSectionHeaderError:
61 _moduleLogger.info("Settings were corrupt")
64 _moduleLogger.exception("Unknown loading error")
66 self._mainWindow.load_settings(config)
68 def save_settings(self):
69 _moduleLogger.info("Saving settings")
70 config = ConfigParser.SafeConfigParser()
72 self._mainWindow.save_settings(config)
74 with open(constants._user_settings_, "wb") as configFile:
75 config.write(configFile)
77 def get_icon(self, name):
78 if self._dataPath is None:
79 for path in self._DATA_PATHS:
80 if os.path.exists(os.path.join(path, name)):
83 if self._dataPath is not None:
84 icon = QtGui.QIcon(os.path.join(self._dataPath, name))
89 def get_resource(self, name):
90 if self._dataPath is None:
91 for path in self._DATA_PATHS:
92 if os.path.exists(os.path.join(path, name)):
95 if self._dataPath is not None:
96 return os.path.join(self._dataPath, name)
100 def _close_windows(self):
101 qwrappers.ApplicationWrapper._close_windows(self)
102 if self._aboutDialog is not None:
103 self._aboutDialog.close()
106 def fsContactsPath(self):
107 return os.path.join(constants._data_path_, "contacts")
110 def streamHandler(self):
111 if self._streamHandler is None:
112 import stream_handler
113 self._streamHandler = stream_handler.StreamHandler()
114 return self._streamHandler
117 def alarmHandler(self):
118 return self._alarmHandler
121 def ledHandler(self):
122 if self._ledHandler is None:
124 self._ledHandler = led_handler.LedHandler()
125 return self._ledHandler
127 def _new_main_window(self):
128 return MainWindow(None, self)
131 @QtCore.pyqtSlot(bool)
132 @misc_utils.log_exception(_moduleLogger)
133 def _on_about(self, checked = True):
134 with qui_utils.notify_error(self._errorLog):
135 if self._aboutDialog is None:
137 self._aboutDialog = dialogs.AboutDialog(self)
138 response = self._aboutDialog.run(self._mainWindow.window)
141 class DelayedWidget(object):
143 def __init__(self, app, settingsNames):
144 self._layout = QtGui.QVBoxLayout()
145 self._layout.setContentsMargins(0, 0, 0, 0)
146 self._widget = QtGui.QWidget()
147 self._widget.setContentsMargins(0, 0, 0, 0)
148 self._widget.setLayout(self._layout)
149 self._settings = dict((name, "") for name in settingsNames)
152 self._isEnabled = True
159 return self._child is not None
161 def set_child(self, child):
162 if self._child is not None:
163 self._layout.removeWidget(self._child.toplevel)
165 if self._child is not None:
166 self._layout.addWidget(self._child.toplevel)
168 self._child.set_settings(self._settings)
173 self._child.disable()
180 self._isEnabled = True
181 if self._child is not None:
185 self._isEnabled = False
186 if self._child is not None:
187 self._child.disable()
190 if self._child is not None:
193 def refresh(self, force=True):
194 if self._child is not None:
195 self._child.refresh(force)
197 def get_settings(self):
198 if self._child is not None:
199 return self._child.get_settings()
201 return self._settings
203 def set_settings(self, settings):
204 if self._child is not None:
205 self._child.set_settings(settings)
207 self._settings = settings
210 def _tab_factory(tab, app, session, errorLog):
212 return gv_views.__dict__[tab](app, session, errorLog)
215 class MainWindow(qwrappers.WindowWrapper):
229 assert len(_TAB_TITLES) == MAX_TABS
237 assert len(_TAB_ICONS) == MAX_TABS
240 functools.partial(_tab_factory, "Dialpad"),
241 functools.partial(_tab_factory, "History"),
242 functools.partial(_tab_factory, "Messages"),
243 functools.partial(_tab_factory, "Contacts"),
245 assert len(_TAB_CLASS) == MAX_TABS
247 # Hack to allow delay importing/loading of tabs
248 _TAB_SETTINGS_NAMES = [
252 ("selectedAddressbook", ),
254 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
256 def __init__(self, parent, app):
257 qwrappers.WindowWrapper.__init__(self, parent, app)
258 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
259 self._errorLog = self._app.errorLog
261 self._session = session.Session(self._errorLog, constants._data_path_)
262 self._session.error.connect(self._on_session_error)
263 self._session.loggedIn.connect(self._on_login)
264 self._session.loggedOut.connect(self._on_logout)
265 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
266 self._session.newMessages.connect(self._on_new_message_alert)
267 self._app.alarmHandler.applicationNotifySignal.connect(self._on_app_alert)
268 self._voicemailRefreshDelay = QtCore.QTimer()
269 self._voicemailRefreshDelay.setInterval(30 * 1000)
270 self._voicemailRefreshDelay.timeout.connect(self._on_call_missed)
271 self._voicemailRefreshDelay.setSingleShot(True)
272 self._callHandler = call_handler.MissedCallWatcher()
273 self._callHandler.callMissed.connect(self._voicemailRefreshDelay.start)
275 self._defaultCredentials = "", ""
276 self._curentCredentials = "", ""
279 self._credentialsDialog = None
280 self._smsEntryDialog = None
281 self._accountDialog = None
283 self._tabsContents = [
284 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
285 for i in xrange(self.MAX_TABS)
287 for tab in self._tabsContents:
290 self._tabWidget = QtGui.QTabWidget()
291 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
292 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
294 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
295 defaultTabIconSize = self._tabWidget.iconSize()
296 defaultTabIconWidth, defaultTabIconHeight = defaultTabIconSize.width(), defaultTabIconSize.height()
297 for tabIndex, (tabTitle, tabIcon) in enumerate(
298 zip(self._TAB_TITLES, self._TAB_ICONS)
300 icon = self._app.get_icon(tabIcon)
301 if constants.IS_MAEMO and icon is not None:
305 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
307 iconSize = icon.availableSizes()[0]
308 defaultTabIconWidth = max(defaultTabIconWidth, iconSize.width())
309 defaultTabIconHeight = max(defaultTabIconHeight, iconSize.height())
310 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
311 defaultTabIconWidth = max(defaultTabIconWidth, 32)
312 defaultTabIconHeight = max(defaultTabIconHeight, 32)
313 self._tabWidget.setIconSize(QtCore.QSize(defaultTabIconWidth, defaultTabIconHeight))
314 self._tabWidget.currentChanged.connect(self._on_tab_changed)
315 self._tabWidget.setContentsMargins(0, 0, 0, 0)
317 self._layout.addWidget(self._tabWidget)
319 self._loginAction = QtGui.QAction(None)
320 self._loginAction.setText("Login")
321 self._loginAction.triggered.connect(self._on_login_requested)
323 self._importAction = QtGui.QAction(None)
324 self._importAction.setText("Import")
325 self._importAction.triggered.connect(self._on_import)
327 self._accountAction = QtGui.QAction(None)
328 self._accountAction.setText("Account")
329 self._accountAction.triggered.connect(self._on_account)
331 self._refreshConnectionAction = QtGui.QAction(None)
332 self._refreshConnectionAction.setText("Refresh Connection")
333 self._refreshConnectionAction.setShortcut(QtGui.QKeySequence("CTRL+a"))
334 self._refreshConnectionAction.triggered.connect(self._on_refresh_connection)
336 self._refreshTabAction = QtGui.QAction(None)
337 self._refreshTabAction.setText("Refresh Tab")
338 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
339 self._refreshTabAction.triggered.connect(self._on_refresh)
341 fileMenu = self._window.menuBar().addMenu("&File")
342 fileMenu.addAction(self._loginAction)
343 fileMenu.addAction(self._refreshTabAction)
344 fileMenu.addAction(self._refreshConnectionAction)
346 toolsMenu = self._window.menuBar().addMenu("&Tools")
347 toolsMenu.addAction(self._accountAction)
348 toolsMenu.addAction(self._importAction)
349 toolsMenu.addAction(self._app.aboutAction)
351 self._initialize_tab(self._tabWidget.currentIndex())
352 self.set_fullscreen(self._app.fullscreenAction.isChecked())
353 self.set_orientation(self._app.orientationAction.isChecked())
355 def set_default_credentials(self, username, password):
356 self._defaultCredentials = username, password
358 def get_default_credentials(self):
359 return self._defaultCredentials
361 def walk_children(self):
362 if self._smsEntryDialog is not None:
363 return (self._smsEntryDialog, )
368 qwrappers.WindowWrapper.start(self)
369 assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
370 if self._defaultCredentials != ("", ""):
371 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
372 self._curentCredentials = username, password
373 self._session.login(username, password)
375 self._prompt_for_login()
379 self._credentialsDialog,
384 for child in self.walk_children():
385 child.window.destroyed.disconnect(self._on_child_close)
386 child.window.closed.disconnect(self._on_child_close)
391 qwrappers.WindowWrapper.destroy(self)
392 if self._session.state != self._session.LOGGEDOUT_STATE:
393 self._session.logout()
395 def get_current_tab(self):
396 return self._currentTab
398 def set_current_tab(self, tabIndex):
399 self._tabWidget.setCurrentIndex(tabIndex)
401 def load_settings(self, config):
404 isPortrait = qui_utils.screen_orientation() == QtCore.Qt.Vertical
408 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
409 for i in xrange(len(self.get_default_credentials()))
411 isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
412 tabIndex = config.getint(constants.__pretty_app_name__, "tab")
413 isPortrait = config.getboolean(constants.__pretty_app_name__, "portrait")
414 except ConfigParser.NoOptionError, e:
416 "Settings file %s is missing option %s" % (
417 constants._user_settings_,
421 except ConfigParser.NoSectionError, e:
423 "Settings file %s is missing section %s" % (
424 constants._user_settings_,
429 _moduleLogger.exception("Unknown loading error")
432 self._app.alarmHandler.load_settings(config, "alarm")
433 self._app.notifyOnMissed = config.getboolean("2 - Account Info", "notifyOnMissed")
434 self._app.notifyOnVoicemail = config.getboolean("2 - Account Info", "notifyOnVoicemail")
435 self._app.notifyOnSms = config.getboolean("2 - Account Info", "notifyOnSms")
436 except ConfigParser.NoOptionError, e:
438 "Settings file %s is missing option %s" % (
439 constants._user_settings_,
443 except ConfigParser.NoSectionError, e:
445 "Settings file %s is missing section %s" % (
446 constants._user_settings_,
451 _moduleLogger.exception("Unknown loading error")
454 base64.b64decode(blob)
457 self.set_default_credentials(*creds)
458 self._app.fullscreenAction.setChecked(isFullscreen)
459 self._app.orientationAction.setChecked(isPortrait)
460 self.set_current_tab(tabIndex)
462 backendId = 2 # For backwards compatibility
463 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
464 sectionName = "%s - %s" % (backendId, tabTitle)
465 settings = self._tabsContents[tabIndex].get_settings()
466 for settingName in settings.iterkeys():
468 settingValue = config.get(sectionName, settingName)
469 except ConfigParser.NoOptionError, e:
471 "Settings file %s is missing section %s" % (
472 constants._user_settings_,
477 except ConfigParser.NoSectionError, e:
479 "Settings file %s is missing section %s" % (
480 constants._user_settings_,
486 _moduleLogger.exception("Unknown loading error")
488 settings[settingName] = settingValue
489 self._tabsContents[tabIndex].set_settings(settings)
491 def save_settings(self, config):
492 config.add_section(constants.__pretty_app_name__)
493 config.set(constants.__pretty_app_name__, "tab", str(self.get_current_tab()))
494 config.set(constants.__pretty_app_name__, "fullscreen", str(self._app.fullscreenAction.isChecked()))
495 config.set(constants.__pretty_app_name__, "portrait", str(self._app.orientationAction.isChecked()))
496 for i, value in enumerate(self.get_default_credentials()):
497 blob = base64.b64encode(value)
498 config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
500 config.add_section("alarm")
501 self._app.alarmHandler.save_settings(config, "alarm")
502 config.add_section("2 - Account Info")
503 config.set("2 - Account Info", "notifyOnMissed", repr(self._app.notifyOnMissed))
504 config.set("2 - Account Info", "notifyOnVoicemail", repr(self._app.notifyOnVoicemail))
505 config.set("2 - Account Info", "notifyOnSms", repr(self._app.notifyOnSms))
507 backendId = 2 # For backwards compatibility
508 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
509 sectionName = "%s - %s" % (backendId, tabTitle)
510 config.add_section(sectionName)
511 tabSettings = self._tabsContents[tabIndex].get_settings()
512 for settingName, settingValue in tabSettings.iteritems():
513 config.set(sectionName, settingName, settingValue)
515 def set_orientation(self, isPortrait):
516 qwrappers.WindowWrapper.set_orientation(self, isPortrait)
518 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
520 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
522 def _initialize_tab(self, index):
523 assert index < self.MAX_TABS, "Invalid tab"
524 if not self._tabsContents[index].has_child():
525 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
526 self._tabsContents[index].set_child(tab)
527 self._tabsContents[index].refresh(force=False)
529 def _prompt_for_login(self):
530 if self._credentialsDialog is None:
532 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
533 credentials = self._credentialsDialog.run(
534 self._defaultCredentials[0], self._defaultCredentials[1], self.window
536 if credentials is None:
538 username, password = credentials
539 self._curentCredentials = username, password
540 self._session.login(username, password)
542 def _show_account_dialog(self):
543 if self._accountDialog is None:
545 self._accountDialog = dialogs.AccountDialog(self._app)
546 self._accountDialog.setIfNotificationsSupported(self._app.alarmHandler.backgroundNotificationsSupported)
547 self._accountDialog.notifications = self._app.alarmHandler.alarmType
548 self._accountDialog.notificationTime = self._app.alarmHandler.recurrence
549 self._accountDialog.notifyOnMissed = self._app.notifyOnMissed
550 self._accountDialog.notifyOnVoicemail = self._app.notifyOnVoicemail
551 self._accountDialog.notifyOnSms = self._app.notifyOnSms
552 self._accountDialog.set_callbacks(
553 self._session.get_callback_numbers(), self._session.get_callback_number()
555 accountNumberToDisplay = self._session.get_account_number()
556 if not accountNumberToDisplay:
557 accountNumberToDisplay = "Not Available (%s)" % self._session.state
558 self._accountDialog.set_account_number(accountNumberToDisplay)
559 response = self._accountDialog.run(self.window)
560 if response == QtGui.QDialog.Accepted:
561 if self._accountDialog.doClear:
562 self._session.logout_and_clear()
563 self._defaultCredentials = "", ""
564 self._curentCredentials = "", ""
565 for tab in self._tabsContents:
568 callbackNumber = self._accountDialog.selectedCallback
569 self._session.set_callback_number(callbackNumber)
572 self._accountDialog.notifyOnMissed or
573 self._accountDialog.notifyOnVoicemail or
574 self._accountDialog.notifyOnSms
576 notifications = self._accountDialog.notifications
578 notifications = self._accountDialog.ALARM_NONE
579 self._app.alarmHandler.apply_settings(notifications, self._accountDialog.notificationTime)
581 self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
582 self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
583 self._app.notifyOnSms = self._accountDialog.notifyOnSms
584 self._app.save_settings()
585 elif response == QtGui.QDialog.Rejected:
586 _moduleLogger.info("Cancelled")
588 _moduleLogger.info("Unknown response")
591 @misc_utils.log_exception(_moduleLogger)
592 def _on_new_message_alert(self):
593 with qui_utils.notify_error(self._errorLog):
594 if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
595 if self._currentTab == self.MESSAGES_TAB or not self._app.ledHandler.isReal:
596 self._errorLog.push_message("New messages available")
598 self._app.ledHandler.on()
601 @misc_utils.log_exception(_moduleLogger)
602 def _on_call_missed(self):
603 with qui_utils.notify_error(self._errorLog):
604 self._session.update_messages(self._session.MESSAGE_VOICEMAILS, force=True)
606 @QtCore.pyqtSlot(str)
607 @misc_utils.log_exception(_moduleLogger)
608 def _on_session_error(self, message):
609 with qui_utils.notify_error(self._errorLog):
610 self._errorLog.push_error(message)
613 @misc_utils.log_exception(_moduleLogger)
615 with qui_utils.notify_error(self._errorLog):
616 changedAccounts = self._defaultCredentials != self._curentCredentials
617 noCallback = not self._session.get_callback_number()
618 if changedAccounts or noCallback:
619 self._show_account_dialog()
621 self._defaultCredentials = self._curentCredentials
623 for tab in self._tabsContents:
625 self._initialize_tab(self._currentTab)
626 self._callHandler.start()
629 @misc_utils.log_exception(_moduleLogger)
630 def _on_logout(self):
631 with qui_utils.notify_error(self._errorLog):
632 for tab in self._tabsContents:
634 self._callHandler.stop()
637 @misc_utils.log_exception(_moduleLogger)
638 def _on_app_alert(self):
639 with qui_utils.notify_error(self._errorLog):
640 if self._session.state == self._session.LOGGEDIN_STATE:
642 (True, True): self._session.MESSAGE_ALL,
643 (True, False): self._session.MESSAGE_TEXTS,
644 (False, True): self._session.MESSAGE_VOICEMAILS,
645 }[(self._app.notifyOnSms, self._app.notifyOnVoicemail)]
646 self._session.update_messages(messageType, force=True)
649 @misc_utils.log_exception(_moduleLogger)
650 def _on_recipients_changed(self):
651 with qui_utils.notify_error(self._errorLog):
652 if self._session.draft.get_num_contacts() == 0:
655 if self._smsEntryDialog is None:
657 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
658 self._smsEntryDialog.window.destroyed.connect(self._on_child_close)
659 self._smsEntryDialog.window.closed.connect(self._on_child_close)
660 self._smsEntryDialog.window.show()
662 @misc_utils.log_exception(_moduleLogger)
663 def _on_child_close(self, obj = None):
664 self._smsEntryDialog = None
667 @QtCore.pyqtSlot(bool)
668 @misc_utils.log_exception(_moduleLogger)
669 def _on_login_requested(self, checked = True):
670 with qui_utils.notify_error(self._errorLog):
671 self._prompt_for_login()
673 @QtCore.pyqtSlot(int)
674 @misc_utils.log_exception(_moduleLogger)
675 def _on_tab_changed(self, index):
676 with qui_utils.notify_error(self._errorLog):
677 self._currentTab = index
678 self._initialize_tab(index)
679 if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
680 self._app.ledHandler.off()
683 @QtCore.pyqtSlot(bool)
684 @misc_utils.log_exception(_moduleLogger)
685 def _on_refresh(self, checked = True):
686 with qui_utils.notify_error(self._errorLog):
687 self._tabsContents[self._currentTab].refresh(force=True)
690 @QtCore.pyqtSlot(bool)
691 @misc_utils.log_exception(_moduleLogger)
692 def _on_refresh_connection(self, checked = True):
693 with qui_utils.notify_error(self._errorLog):
694 self._session.refresh_connection()
697 @QtCore.pyqtSlot(bool)
698 @misc_utils.log_exception(_moduleLogger)
699 def _on_import(self, checked = True):
700 with qui_utils.notify_error(self._errorLog):
701 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
702 csvName = unicode(csvName)
706 shutil.copy2(csvName, self._app.fsContactsPath)
707 if self._tabsContents[self.CONTACTS_TAB].has_child:
708 self._tabsContents[self.CONTACTS_TAB].child.update_addressbooks()
711 @QtCore.pyqtSlot(bool)
712 @misc_utils.log_exception(_moduleLogger)
713 def _on_account(self, checked = True):
714 with qui_utils.notify_error(self._errorLog):
715 assert self._session.state == self._session.LOGGEDIN_STATE, "Must be logged in for settings"
716 self._show_account_dialog()
721 os.makedirs(constants._data_path_)
726 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
727 logging.basicConfig(level=logging.DEBUG, format=logFormat)
728 rotating = logging.handlers.RotatingFileHandler(constants._user_logpath_, maxBytes=512*1024, backupCount=1)
729 rotating.setFormatter(logging.Formatter(logFormat))
730 root = logging.getLogger()
731 root.addHandler(rotating)
732 _moduleLogger.info("%s %s-%s" % (constants.__app_name__, constants.__version__, constants.__build__))
733 _moduleLogger.info("OS: %s" % (os.uname()[0], ))
734 _moduleLogger.info("Kernel: %s (%s) for %s" % os.uname()[2:])
735 _moduleLogger.info("Hostname: %s" % os.uname()[1])
739 gobject.threads_init()
741 _moduleLogger.info("GObject support not available")
745 from dbus.mainloop.qt import DBusQtMainLoop
746 DBusQtMainLoop(set_as_default=True)
747 _moduleLogger.info("Using Qt mainloop")
750 from dbus.mainloop.glib import DBusGMainLoop
751 DBusGMainLoop(set_as_default=True)
752 _moduleLogger.info("Using GObject mainloop")
754 _moduleLogger.info("Mainloop not available")
756 _moduleLogger.info("DBus support not available")
758 app = QtGui.QApplication([])
759 handle = Dialcentral(app)
764 if __name__ == "__main__":