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")
68 isPortrait = qui_utils.screen_orientation() == QtCore.Qt.Vertical
72 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
73 for i in xrange(len(self._mainWindow.get_default_credentials()))
75 isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
76 tabIndex = config.getint(constants.__pretty_app_name__, "tab")
77 isPortrait = config.getboolean(constants.__pretty_app_name__, "portrait")
78 except ConfigParser.NoOptionError, e:
80 "Settings file %s is missing option %s" % (
81 constants._user_settings_,
85 except ConfigParser.NoSectionError, e:
87 "Settings file %s is missing section %s" % (
88 constants._user_settings_,
93 _moduleLogger.exception("Unknown loading error")
96 self._alarmHandler.load_settings(config, "alarm")
97 self.notifyOnMissed = config.getboolean("2 - Account Info", "notifyOnMissed")
98 self.notifyOnVoicemail = config.getboolean("2 - Account Info", "notifyOnVoicemail")
99 self.notifyOnSms = config.getboolean("2 - Account Info", "notifyOnSms")
100 except ConfigParser.NoOptionError, e:
102 "Settings file %s is missing option %s" % (
103 constants._user_settings_,
107 except ConfigParser.NoSectionError, e:
109 "Settings file %s is missing section %s" % (
110 constants._user_settings_,
115 _moduleLogger.exception("Unknown loading error")
118 base64.b64decode(blob)
121 self._mainWindow.set_default_credentials(*creds)
122 self._fullscreenAction.setChecked(isFullscreen)
123 self._orientationAction.setChecked(isPortrait)
124 self._mainWindow.set_current_tab(tabIndex)
125 self._mainWindow.load_settings(config)
127 def save_settings(self):
128 _moduleLogger.info("Saving settings")
129 config = ConfigParser.SafeConfigParser()
131 config.add_section(constants.__pretty_app_name__)
132 config.set(constants.__pretty_app_name__, "tab", str(self._mainWindow.get_current_tab()))
133 config.set(constants.__pretty_app_name__, "fullscreen", str(self._fullscreenAction.isChecked()))
134 config.set(constants.__pretty_app_name__, "portrait", str(self._orientationAction.isChecked()))
135 for i, value in enumerate(self._mainWindow.get_default_credentials()):
136 blob = base64.b64encode(value)
137 config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
139 config.add_section("alarm")
140 self._alarmHandler.save_settings(config, "alarm")
141 config.add_section("2 - Account Info")
142 config.set("2 - Account Info", "notifyOnMissed", repr(self.notifyOnMissed))
143 config.set("2 - Account Info", "notifyOnVoicemail", repr(self.notifyOnVoicemail))
144 config.set("2 - Account Info", "notifyOnSms", repr(self.notifyOnSms))
146 self._mainWindow.save_settings(config)
148 with open(constants._user_settings_, "wb") as configFile:
149 config.write(configFile)
151 def get_icon(self, name):
152 if self._dataPath is None:
153 for path in self._DATA_PATHS:
154 if os.path.exists(os.path.join(path, name)):
155 self._dataPath = path
157 if self._dataPath is not None:
158 icon = QtGui.QIcon(os.path.join(self._dataPath, name))
163 def get_resource(self, name):
164 if self._dataPath is None:
165 for path in self._DATA_PATHS:
166 if os.path.exists(os.path.join(path, name)):
167 self._dataPath = path
169 if self._dataPath is not None:
170 return os.path.join(self._dataPath, name)
174 def _close_windows(self):
175 qwrappers.ApplicationWrapper._close_windows(self)
176 if self._aboutDialog is not None:
177 self._aboutDialog.close()
180 def fsContactsPath(self):
181 return os.path.join(constants._data_path_, "contacts")
184 def streamHandler(self):
185 if self._streamHandler is None:
186 import stream_handler
187 self._streamHandler = stream_handler.StreamHandler()
188 return self._streamHandler
191 def alarmHandler(self):
192 return self._alarmHandler
195 def ledHandler(self):
196 if self._ledHandler is None:
198 self._ledHandler = led_handler.LedHandler()
199 return self._ledHandler
201 def _new_main_window(self):
202 return MainWindow(None, self)
205 @QtCore.pyqtSlot(bool)
206 @misc_utils.log_exception(_moduleLogger)
207 def _on_about(self, checked = True):
208 with qui_utils.notify_error(self._errorLog):
209 if self._aboutDialog is None:
211 self._aboutDialog = dialogs.AboutDialog(self)
212 response = self._aboutDialog.run(self._mainWindow.window)
215 class DelayedWidget(object):
217 def __init__(self, app, settingsNames):
218 self._layout = QtGui.QVBoxLayout()
219 self._layout.setContentsMargins(0, 0, 0, 0)
220 self._widget = QtGui.QWidget()
221 self._widget.setContentsMargins(0, 0, 0, 0)
222 self._widget.setLayout(self._layout)
223 self._settings = dict((name, "") for name in settingsNames)
226 self._isEnabled = True
233 return self._child is not None
235 def set_child(self, child):
236 if self._child is not None:
237 self._layout.removeWidget(self._child.toplevel)
239 if self._child is not None:
240 self._layout.addWidget(self._child.toplevel)
242 self._child.set_settings(self._settings)
247 self._child.disable()
254 self._isEnabled = True
255 if self._child is not None:
259 self._isEnabled = False
260 if self._child is not None:
261 self._child.disable()
264 if self._child is not None:
267 def refresh(self, force=True):
268 if self._child is not None:
269 self._child.refresh(force)
271 def get_settings(self):
272 if self._child is not None:
273 return self._child.get_settings()
275 return self._settings
277 def set_settings(self, settings):
278 if self._child is not None:
279 self._child.set_settings(settings)
281 self._settings = settings
284 def _tab_factory(tab, app, session, errorLog):
286 return gv_views.__dict__[tab](app, session, errorLog)
289 class MainWindow(qwrappers.WindowWrapper):
303 assert len(_TAB_TITLES) == MAX_TABS
311 assert len(_TAB_ICONS) == MAX_TABS
314 functools.partial(_tab_factory, "Dialpad"),
315 functools.partial(_tab_factory, "History"),
316 functools.partial(_tab_factory, "Messages"),
317 functools.partial(_tab_factory, "Contacts"),
319 assert len(_TAB_CLASS) == MAX_TABS
321 # Hack to allow delay importing/loading of tabs
322 _TAB_SETTINGS_NAMES = [
326 ("selectedAddressbook", ),
328 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
330 def __init__(self, parent, app):
331 qwrappers.WindowWrapper.__init__(self, parent, app)
332 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
333 self._errorLog = self._app.errorLog
335 self._session = session.Session(self._errorLog, constants._data_path_)
336 self._session.error.connect(self._on_session_error)
337 self._session.loggedIn.connect(self._on_login)
338 self._session.loggedOut.connect(self._on_logout)
339 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
340 self._session.newMessages.connect(self._on_new_message_alert)
341 self._app.alarmHandler.applicationNotifySignal.connect(self._on_app_alert)
342 self._voicemailRefreshDelay = QtCore.QTimer()
343 self._voicemailRefreshDelay.setInterval(30 * 1000)
344 self._voicemailRefreshDelay.timeout.connect(self._on_call_missed)
345 self._voicemailRefreshDelay.setSingleShot(True)
346 self._callHandler = call_handler.MissedCallWatcher()
347 self._callHandler.callMissed.connect(self._voicemailRefreshDelay.start)
349 self._defaultCredentials = "", ""
350 self._curentCredentials = "", ""
353 self._credentialsDialog = None
354 self._smsEntryDialog = None
355 self._accountDialog = None
357 self._tabsContents = [
358 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
359 for i in xrange(self.MAX_TABS)
361 for tab in self._tabsContents:
364 self._tabWidget = QtGui.QTabWidget()
365 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
366 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
368 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
369 defaultTabIconSize = self._tabWidget.iconSize()
370 defaultTabIconWidth, defaultTabIconHeight = defaultTabIconSize.width(), defaultTabIconSize.height()
371 for tabIndex, (tabTitle, tabIcon) in enumerate(
372 zip(self._TAB_TITLES, self._TAB_ICONS)
374 icon = self._app.get_icon(tabIcon)
375 if constants.IS_MAEMO and icon is not None:
379 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
381 iconSize = icon.availableSizes()[0]
382 defaultTabIconWidth = max(defaultTabIconWidth, iconSize.width())
383 defaultTabIconHeight = max(defaultTabIconHeight, iconSize.height())
384 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
385 defaultTabIconWidth = max(defaultTabIconWidth, 32)
386 defaultTabIconHeight = max(defaultTabIconHeight, 32)
387 self._tabWidget.setIconSize(QtCore.QSize(defaultTabIconWidth, defaultTabIconHeight))
388 self._tabWidget.currentChanged.connect(self._on_tab_changed)
389 self._tabWidget.setContentsMargins(0, 0, 0, 0)
391 self._layout.addWidget(self._tabWidget)
393 self._loginAction = QtGui.QAction(None)
394 self._loginAction.setText("Login")
395 self._loginAction.triggered.connect(self._on_login_requested)
397 self._importAction = QtGui.QAction(None)
398 self._importAction.setText("Import")
399 self._importAction.triggered.connect(self._on_import)
401 self._accountAction = QtGui.QAction(None)
402 self._accountAction.setText("Account")
403 self._accountAction.triggered.connect(self._on_account)
405 self._refreshConnectionAction = QtGui.QAction(None)
406 self._refreshConnectionAction.setText("Refresh Connection")
407 self._refreshConnectionAction.setShortcut(QtGui.QKeySequence("CTRL+a"))
408 self._refreshConnectionAction.triggered.connect(self._on_refresh_connection)
410 self._refreshTabAction = QtGui.QAction(None)
411 self._refreshTabAction.setText("Refresh Tab")
412 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
413 self._refreshTabAction.triggered.connect(self._on_refresh)
415 fileMenu = self._window.menuBar().addMenu("&File")
416 fileMenu.addAction(self._loginAction)
417 fileMenu.addAction(self._refreshTabAction)
418 fileMenu.addAction(self._refreshConnectionAction)
420 toolsMenu = self._window.menuBar().addMenu("&Tools")
421 toolsMenu.addAction(self._accountAction)
422 toolsMenu.addAction(self._importAction)
423 toolsMenu.addAction(self._app.aboutAction)
425 self._initialize_tab(self._tabWidget.currentIndex())
426 self.set_fullscreen(self._app.fullscreenAction.isChecked())
427 self.set_orientation(self._app.orientationAction.isChecked())
429 def set_default_credentials(self, username, password):
430 self._defaultCredentials = username, password
432 def get_default_credentials(self):
433 return self._defaultCredentials
435 def walk_children(self):
436 if self._smsEntryDialog is not None:
437 return (self._smsEntryDialog, )
442 qwrappers.WindowWrapper.start(self)
443 assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
444 if self._defaultCredentials != ("", ""):
445 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
446 self._curentCredentials = username, password
447 self._session.login(username, password)
449 self._prompt_for_login()
453 self._credentialsDialog,
458 for child in self.walk_children():
459 child.window.destroyed.disconnect(self._on_child_close)
460 child.window.closed.disconnect(self._on_child_close)
465 qwrappers.WindowWrapper.destroy(self)
466 if self._session.state != self._session.LOGGEDOUT_STATE:
467 self._session.logout()
469 def get_current_tab(self):
470 return self._currentTab
472 def set_current_tab(self, tabIndex):
473 self._tabWidget.setCurrentIndex(tabIndex)
475 def load_settings(self, config):
476 backendId = 2 # For backwards compatibility
477 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
478 sectionName = "%s - %s" % (backendId, tabTitle)
479 settings = self._tabsContents[tabIndex].get_settings()
480 for settingName in settings.iterkeys():
482 settingValue = config.get(sectionName, settingName)
483 except ConfigParser.NoOptionError, e:
485 "Settings file %s is missing section %s" % (
486 constants._user_settings_,
491 except ConfigParser.NoSectionError, e:
493 "Settings file %s is missing section %s" % (
494 constants._user_settings_,
500 _moduleLogger.exception("Unknown loading error")
502 settings[settingName] = settingValue
503 self._tabsContents[tabIndex].set_settings(settings)
505 def save_settings(self, config):
506 backendId = 2 # For backwards compatibility
507 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
508 sectionName = "%s - %s" % (backendId, tabTitle)
509 config.add_section(sectionName)
510 tabSettings = self._tabsContents[tabIndex].get_settings()
511 for settingName, settingValue in tabSettings.iteritems():
512 config.set(sectionName, settingName, settingValue)
514 def set_orientation(self, isPortrait):
515 qwrappers.WindowWrapper.set_orientation(self, isPortrait)
517 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
519 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
521 def _initialize_tab(self, index):
522 assert index < self.MAX_TABS, "Invalid tab"
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 credentials = self._credentialsDialog.run(
533 self._defaultCredentials[0], self._defaultCredentials[1], self.window
535 if credentials is None:
537 username, password = credentials
538 self._curentCredentials = username, password
539 self._session.login(username, password)
541 def _show_account_dialog(self):
542 if self._accountDialog is None:
544 self._accountDialog = dialogs.AccountDialog(self._app)
545 self._accountDialog.setIfNotificationsSupported(self._app.alarmHandler.backgroundNotificationsSupported)
546 self._accountDialog.notifications = self._app.alarmHandler.alarmType
547 self._accountDialog.notificationTime = self._app.alarmHandler.recurrence
548 self._accountDialog.notifyOnMissed = self._app.notifyOnMissed
549 self._accountDialog.notifyOnVoicemail = self._app.notifyOnVoicemail
550 self._accountDialog.notifyOnSms = self._app.notifyOnSms
551 self._accountDialog.set_callbacks(
552 self._session.get_callback_numbers(), self._session.get_callback_number()
554 accountNumberToDisplay = self._session.get_account_number()
555 if not accountNumberToDisplay:
556 accountNumberToDisplay = "Not Available (%s)" % self._session.state
557 self._accountDialog.set_account_number(accountNumberToDisplay)
558 response = self._accountDialog.run(self.window)
559 if response == QtGui.QDialog.Accepted:
560 if self._accountDialog.doClear:
561 self._session.logout_and_clear()
562 self._defaultCredentials = "", ""
563 self._curentCredentials = "", ""
564 for tab in self._tabsContents:
567 callbackNumber = self._accountDialog.selectedCallback
568 self._session.set_callback_number(callbackNumber)
571 self._accountDialog.notifyOnMissed or
572 self._accountDialog.notifyOnVoicemail or
573 self._accountDialog.notifyOnSms
575 notifications = self._accountDialog.notifications
577 notifications = self._accountDialog.ALARM_NONE
578 self._app.alarmHandler.apply_settings(notifications, self._accountDialog.notificationTime)
580 self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
581 self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
582 self._app.notifyOnSms = self._accountDialog.notifyOnSms
583 self._app.save_settings()
584 elif response == QtGui.QDialog.Rejected:
585 _moduleLogger.info("Cancelled")
587 _moduleLogger.info("Unknown response")
590 @misc_utils.log_exception(_moduleLogger)
591 def _on_new_message_alert(self):
592 with qui_utils.notify_error(self._errorLog):
593 if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
594 if self._currentTab == self.MESSAGES_TAB or not self._app.ledHandler.isReal:
595 self._errorLog.push_message("New messages available")
597 self._app.ledHandler.on()
600 @misc_utils.log_exception(_moduleLogger)
601 def _on_call_missed(self):
602 with qui_utils.notify_error(self._errorLog):
603 self._session.update_messages(self._session.MESSAGE_VOICEMAILS, force=True)
605 @QtCore.pyqtSlot(str)
606 @misc_utils.log_exception(_moduleLogger)
607 def _on_session_error(self, message):
608 with qui_utils.notify_error(self._errorLog):
609 self._errorLog.push_error(message)
612 @misc_utils.log_exception(_moduleLogger)
614 with qui_utils.notify_error(self._errorLog):
615 changedAccounts = self._defaultCredentials != self._curentCredentials
616 noCallback = not self._session.get_callback_number()
617 if changedAccounts or noCallback:
618 self._show_account_dialog()
620 self._defaultCredentials = self._curentCredentials
622 for tab in self._tabsContents:
624 self._initialize_tab(self._currentTab)
625 self._callHandler.start()
628 @misc_utils.log_exception(_moduleLogger)
629 def _on_logout(self):
630 with qui_utils.notify_error(self._errorLog):
631 for tab in self._tabsContents:
633 self._callHandler.stop()
636 @misc_utils.log_exception(_moduleLogger)
637 def _on_app_alert(self):
638 with qui_utils.notify_error(self._errorLog):
639 if self._session.state == self._session.LOGGEDIN_STATE:
641 (True, True): self._session.MESSAGE_ALL,
642 (True, False): self._session.MESSAGE_TEXTS,
643 (False, True): self._session.MESSAGE_VOICEMAILS,
644 }[(self._app.notifyOnSms, self._app.notifyOnVoicemail)]
645 self._session.update_messages(messageType, force=True)
648 @misc_utils.log_exception(_moduleLogger)
649 def _on_recipients_changed(self):
650 with qui_utils.notify_error(self._errorLog):
651 if self._session.draft.get_num_contacts() == 0:
654 if self._smsEntryDialog is None:
656 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
657 self._smsEntryDialog.window.destroyed.connect(self._on_child_close)
658 self._smsEntryDialog.window.closed.connect(self._on_child_close)
659 self._smsEntryDialog.window.show()
661 @misc_utils.log_exception(_moduleLogger)
662 def _on_child_close(self, obj = None):
663 self._smsEntryDialog = None
666 @QtCore.pyqtSlot(bool)
667 @misc_utils.log_exception(_moduleLogger)
668 def _on_login_requested(self, checked = True):
669 with qui_utils.notify_error(self._errorLog):
670 self._prompt_for_login()
672 @QtCore.pyqtSlot(int)
673 @misc_utils.log_exception(_moduleLogger)
674 def _on_tab_changed(self, index):
675 with qui_utils.notify_error(self._errorLog):
676 self._currentTab = index
677 self._initialize_tab(index)
678 if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
679 self._app.ledHandler.off()
682 @QtCore.pyqtSlot(bool)
683 @misc_utils.log_exception(_moduleLogger)
684 def _on_refresh(self, checked = True):
685 with qui_utils.notify_error(self._errorLog):
686 self._tabsContents[self._currentTab].refresh(force=True)
689 @QtCore.pyqtSlot(bool)
690 @misc_utils.log_exception(_moduleLogger)
691 def _on_refresh_connection(self, checked = True):
692 with qui_utils.notify_error(self._errorLog):
693 self._session.refresh_connection()
696 @QtCore.pyqtSlot(bool)
697 @misc_utils.log_exception(_moduleLogger)
698 def _on_import(self, checked = True):
699 with qui_utils.notify_error(self._errorLog):
700 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
701 csvName = unicode(csvName)
705 shutil.copy2(csvName, self._app.fsContactsPath)
706 if self._tabsContents[self.CONTACTS_TAB].has_child:
707 self._tabsContents[self.CONTACTS_TAB].child.update_addressbooks()
710 @QtCore.pyqtSlot(bool)
711 @misc_utils.log_exception(_moduleLogger)
712 def _on_account(self, checked = True):
713 with qui_utils.notify_error(self._errorLog):
714 assert self._session.state == self._session.LOGGEDIN_STATE, "Must be logged in for settings"
715 self._show_account_dialog()
720 os.makedirs(constants._data_path_)
725 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
726 logging.basicConfig(level=logging.DEBUG, format=logFormat)
727 rotating = logging.handlers.RotatingFileHandler(constants._user_logpath_, maxBytes=512*1024, backupCount=1)
728 rotating.setFormatter(logging.Formatter(logFormat))
729 root = logging.getLogger()
730 root.addHandler(rotating)
731 _moduleLogger.info("%s %s-%s" % (constants.__app_name__, constants.__version__, constants.__build__))
732 _moduleLogger.info("OS: %s" % (os.uname()[0], ))
733 _moduleLogger.info("Kernel: %s (%s) for %s" % os.uname()[2:])
734 _moduleLogger.info("Hostname: %s" % os.uname()[1])
738 gobject.threads_init()
740 _moduleLogger.info("GObject support not available")
744 from dbus.mainloop.qt import DBusQtMainLoop
745 DBusQtMainLoop(set_as_default=True)
746 _moduleLogger.info("Using Qt mainloop")
749 from dbus.mainloop.glib import DBusGMainLoop
750 DBusGMainLoop(set_as_default=True)
751 _moduleLogger.info("Using GObject mainloop")
753 _moduleLogger.info("Mainloop not available")
755 _moduleLogger.info("DBus support not available")
757 app = QtGui.QApplication([])
758 handle = Dialcentral(app)
763 if __name__ == "__main__":