4 from __future__ import with_statement
12 from PyQt4 import QtGui
13 from PyQt4 import QtCore
15 import dbus.mainloop.glib
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 LedWrapper(object):
33 self._ledHandler = None
38 if self._ledHandler is not None:
39 self._ledHandler.off()
47 self._ledHandler = led_handler.LedHandler()
49 _moduleLogger.exception('Unable to initialize LED Handling: "%s"' % str(e))
50 self._ledHandler = None
53 class Dialcentral(qwrappers.ApplicationWrapper):
56 os.path.join(os.path.dirname(__file__), "../share"),
57 os.path.join(os.path.dirname(__file__), "../data"),
60 def __init__(self, app):
62 self._aboutDialog = None
63 self._ledHandler = LedWrapper()
64 self.notifyOnMissed = False
65 self.notifyOnVoicemail = False
66 self.notifyOnSms = False
70 if alarm_handler.AlarmHandler is not alarm_handler._NoneAlarmHandler:
71 self._alarmHandler = alarm_handler.AlarmHandler()
73 self._alarmHandler = None
74 except (ImportError, OSError):
75 self._alarmHandler = None
77 _moduleLogger.exception("Notification failure")
78 self._alarmHandler = None
79 if self._alarmHandler is None:
80 _moduleLogger.info("No notification support")
82 qwrappers.ApplicationWrapper.__init__(self, app, constants)
84 def load_settings(self):
86 config = ConfigParser.SafeConfigParser()
87 config.read(constants._user_settings_)
89 _moduleLogger.info("No settings")
92 _moduleLogger.info("Settings were corrupt")
94 except ConfigParser.MissingSectionHeaderError:
95 _moduleLogger.info("Settings were corrupt")
98 _moduleLogger.exception("Unknown loading error")
102 isPortrait = qui_utils.screen_orientation() == QtCore.Qt.Vertical
106 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
107 for i in xrange(len(self._mainWindow.get_default_credentials()))
109 isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
110 tabIndex = config.getint(constants.__pretty_app_name__, "tab")
111 isPortrait = config.getboolean(constants.__pretty_app_name__, "portrait")
112 except ConfigParser.NoOptionError, e:
114 "Settings file %s is missing option %s" % (
115 constants._user_settings_,
119 except ConfigParser.NoSectionError, e:
121 "Settings file %s is missing section %s" % (
122 constants._user_settings_,
127 _moduleLogger.exception("Unknown loading error")
129 if self._alarmHandler is not None:
131 self._alarmHandler.load_settings(config, "alarm")
132 self.notifyOnMissed = config.getboolean("2 - Account Info", "notifyOnMissed")
133 self.notifyOnVoicemail = config.getboolean("2 - Account Info", "notifyOnVoicemail")
134 self.notifyOnSms = config.getboolean("2 - Account Info", "notifyOnSms")
135 except ConfigParser.NoOptionError, e:
137 "Settings file %s is missing option %s" % (
138 constants._user_settings_,
142 except ConfigParser.NoSectionError, e:
144 "Settings file %s is missing section %s" % (
145 constants._user_settings_,
150 _moduleLogger.exception("Unknown loading error")
153 base64.b64decode(blob)
156 self._mainWindow.set_default_credentials(*creds)
157 self._fullscreenAction.setChecked(isFullscreen)
158 self._orientationAction.setChecked(isPortrait)
159 self._mainWindow.set_current_tab(tabIndex)
160 self._mainWindow.load_settings(config)
162 def save_settings(self):
163 _moduleLogger.info("Saving settings")
164 config = ConfigParser.SafeConfigParser()
166 config.add_section(constants.__pretty_app_name__)
167 config.set(constants.__pretty_app_name__, "tab", str(self._mainWindow.get_current_tab()))
168 config.set(constants.__pretty_app_name__, "fullscreen", str(self._fullscreenAction.isChecked()))
169 config.set(constants.__pretty_app_name__, "portrait", str(self._orientationAction.isChecked()))
170 for i, value in enumerate(self._mainWindow.get_default_credentials()):
171 blob = base64.b64encode(value)
172 config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
174 if self._alarmHandler is not None:
175 config.add_section("alarm")
176 self._alarmHandler.save_settings(config, "alarm")
177 config.add_section("2 - Account Info")
178 config.set("2 - Account Info", "notifyOnMissed", repr(self.notifyOnMissed))
179 config.set("2 - Account Info", "notifyOnVoicemail", repr(self.notifyOnVoicemail))
180 config.set("2 - Account Info", "notifyOnSms", repr(self.notifyOnSms))
182 self._mainWindow.save_settings(config)
184 with open(constants._user_settings_, "wb") as configFile:
185 config.write(configFile)
187 def get_icon(self, name):
188 if self._dataPath is None:
189 for path in self._DATA_PATHS:
190 if os.path.exists(os.path.join(path, name)):
191 self._dataPath = path
193 if self._dataPath is not None:
194 icon = QtGui.QIcon(os.path.join(self._dataPath, name))
199 def get_resource(self, name):
200 if self._dataPath is None:
201 for path in self._DATA_PATHS:
202 if os.path.exists(os.path.join(path, name)):
203 self._dataPath = path
205 if self._dataPath is not None:
206 return os.path.join(self._dataPath, name)
210 def _close_windows(self):
211 qwrappers.ApplicationWrapper._close_windows(self)
212 if self._aboutDialog is not None:
213 self._aboutDialog.close()
216 def fsContactsPath(self):
217 return os.path.join(constants._data_path_, "contacts")
220 def alarmHandler(self):
221 return self._alarmHandler
224 def ledHandler(self):
225 return self._ledHandler
227 def _new_main_window(self):
228 return MainWindow(None, self)
231 @QtCore.pyqtSlot(bool)
232 @misc_utils.log_exception(_moduleLogger)
233 def _on_about(self, checked = True):
234 with qui_utils.notify_error(self._errorLog):
235 if self._aboutDialog is None:
237 self._aboutDialog = dialogs.AboutDialog(self)
238 response = self._aboutDialog.run(self._mainWindow.window)
241 class DelayedWidget(object):
243 def __init__(self, app, settingsNames):
244 self._layout = QtGui.QVBoxLayout()
245 self._layout.setContentsMargins(0, 0, 0, 0)
246 self._widget = QtGui.QWidget()
247 self._widget.setContentsMargins(0, 0, 0, 0)
248 self._widget.setLayout(self._layout)
249 self._settings = dict((name, "") for name in settingsNames)
252 self._isEnabled = True
259 return self._child is not None
261 def set_child(self, child):
262 if self._child is not None:
263 self._layout.removeWidget(self._child.toplevel)
265 if self._child is not None:
266 self._layout.addWidget(self._child.toplevel)
268 self._child.set_settings(self._settings)
273 self._child.disable()
280 self._isEnabled = True
281 if self._child is not None:
285 self._isEnabled = False
286 if self._child is not None:
287 self._child.disable()
290 if self._child is not None:
293 def refresh(self, force=True):
294 if self._child is not None:
295 self._child.refresh(force)
297 def get_settings(self):
298 if self._child is not None:
299 return self._child.get_settings()
301 return self._settings
303 def set_settings(self, settings):
304 if self._child is not None:
305 self._child.set_settings(settings)
307 self._settings = settings
310 def _tab_factory(tab, app, session, errorLog):
312 return gv_views.__dict__[tab](app, session, errorLog)
315 class MainWindow(qwrappers.WindowWrapper):
329 assert len(_TAB_TITLES) == MAX_TABS
337 assert len(_TAB_ICONS) == MAX_TABS
340 functools.partial(_tab_factory, "Dialpad"),
341 functools.partial(_tab_factory, "History"),
342 functools.partial(_tab_factory, "Messages"),
343 functools.partial(_tab_factory, "Contacts"),
345 assert len(_TAB_CLASS) == MAX_TABS
347 # Hack to allow delay importing/loading of tabs
348 _TAB_SETTINGS_NAMES = [
352 ("selectedAddressbook", ),
354 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
356 def __init__(self, parent, app):
357 qwrappers.WindowWrapper.__init__(self, parent, app)
358 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
359 self._errorLog = self._app.errorLog
361 self._session = session.Session(self._errorLog, constants._data_path_)
362 self._session.error.connect(self._on_session_error)
363 self._session.loggedIn.connect(self._on_login)
364 self._session.loggedOut.connect(self._on_logout)
365 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
366 self._voicemailRefreshDelay = QtCore.QTimer()
367 self._voicemailRefreshDelay.setInterval(30 * 1000)
368 self._voicemailRefreshDelay.timeout.connect(self._on_call_missed)
369 self._voicemailRefreshDelay.setSingleShot(True)
370 self._callHandler = call_handler.MissedCallWatcher()
371 self._callHandler.callMissed.connect(self._voicemailRefreshDelay.start)
372 self._alertSoundPath = self._app.get_resource("bell.wav")
373 if QtGui.QSound.isAvailable():
374 self._session.newMessages.connect(self._on_new_message_alert)
376 _moduleLogger.info("No sound support available")
377 self._defaultCredentials = "", ""
378 self._curentCredentials = "", ""
381 self._credentialsDialog = None
382 self._smsEntryDialog = None
383 self._accountDialog = None
385 self._tabsContents = [
386 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
387 for i in xrange(self.MAX_TABS)
389 for tab in self._tabsContents:
392 self._tabWidget = QtGui.QTabWidget()
393 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
394 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
396 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
397 defaultTabIconSize = self._tabWidget.iconSize()
398 defaultTabIconWidth, defaultTabIconHeight = defaultTabIconSize.width(), defaultTabIconSize.height()
399 for tabIndex, (tabTitle, tabIcon) in enumerate(
400 zip(self._TAB_TITLES, self._TAB_ICONS)
402 icon = self._app.get_icon(tabIcon)
403 if constants.IS_MAEMO and icon is not None:
407 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
409 iconSize = icon.availableSizes()[0]
410 defaultTabIconWidth = max(defaultTabIconWidth, iconSize.width())
411 defaultTabIconHeight = max(defaultTabIconHeight, iconSize.height())
412 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
413 defaultTabIconWidth = max(defaultTabIconWidth, 32)
414 defaultTabIconHeight = max(defaultTabIconHeight, 32)
415 self._tabWidget.setIconSize(QtCore.QSize(defaultTabIconWidth, defaultTabIconHeight))
416 self._tabWidget.currentChanged.connect(self._on_tab_changed)
417 self._tabWidget.setContentsMargins(0, 0, 0, 0)
419 self._layout.addWidget(self._tabWidget)
421 self._loginTabAction = QtGui.QAction(None)
422 self._loginTabAction.setText("Login")
423 self._loginTabAction.triggered.connect(self._on_login_requested)
425 self._importTabAction = QtGui.QAction(None)
426 self._importTabAction.setText("Import")
427 self._importTabAction.triggered.connect(self._on_import)
429 self._accountTabAction = QtGui.QAction(None)
430 self._accountTabAction.setText("Account")
431 self._accountTabAction.triggered.connect(self._on_account)
433 self._refreshTabAction = QtGui.QAction(None)
434 self._refreshTabAction.setText("Refresh")
435 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
436 self._refreshTabAction.triggered.connect(self._on_refresh)
438 fileMenu = self._window.menuBar().addMenu("&File")
439 fileMenu.addAction(self._loginTabAction)
440 fileMenu.addAction(self._refreshTabAction)
442 toolsMenu = self._window.menuBar().addMenu("&Tools")
443 toolsMenu.addAction(self._accountTabAction)
444 toolsMenu.addAction(self._importTabAction)
445 toolsMenu.addAction(self._app.aboutAction)
447 self._initialize_tab(self._tabWidget.currentIndex())
448 self.set_fullscreen(self._app.fullscreenAction.isChecked())
449 self.set_orientation(self._app.orientationAction.isChecked())
451 def set_default_credentials(self, username, password):
452 self._defaultCredentials = username, password
454 def get_default_credentials(self):
455 return self._defaultCredentials
457 def walk_children(self):
458 if self._smsEntryDialog is not None:
459 return (self._smsEntryDialog, )
464 qwrappers.WindowWrapper.start(self)
465 assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
466 if self._defaultCredentials != ("", ""):
467 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
468 self._curentCredentials = username, password
469 self._session.login(username, password)
471 self._prompt_for_login()
475 self._credentialsDialog,
480 for child in self.walk_children():
481 child.window.destroyed.disconnect(self._on_child_close)
482 child.window.closed.disconnect(self._on_child_close)
487 qwrappers.WindowWrapper.destroy(self)
488 if self._session.state != self._session.LOGGEDOUT_STATE:
489 self._session.logout()
491 def get_current_tab(self):
492 return self._currentTab
494 def set_current_tab(self, tabIndex):
495 self._tabWidget.setCurrentIndex(tabIndex)
497 def load_settings(self, config):
498 backendId = 2 # For backwards compatibility
499 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
500 sectionName = "%s - %s" % (backendId, tabTitle)
501 settings = self._tabsContents[tabIndex].get_settings()
502 for settingName in settings.iterkeys():
504 settingValue = config.get(sectionName, settingName)
505 except ConfigParser.NoOptionError, e:
507 "Settings file %s is missing section %s" % (
508 constants._user_settings_,
513 except ConfigParser.NoSectionError, e:
515 "Settings file %s is missing section %s" % (
516 constants._user_settings_,
522 _moduleLogger.exception("Unknown loading error")
524 settings[settingName] = settingValue
525 self._tabsContents[tabIndex].set_settings(settings)
527 def save_settings(self, config):
528 backendId = 2 # For backwards compatibility
529 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
530 sectionName = "%s - %s" % (backendId, tabTitle)
531 config.add_section(sectionName)
532 tabSettings = self._tabsContents[tabIndex].get_settings()
533 for settingName, settingValue in tabSettings.iteritems():
534 config.set(sectionName, settingName, settingValue)
536 def set_orientation(self, isPortrait):
537 qwrappers.WindowWrapper.set_orientation(self, isPortrait)
539 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
541 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
543 def _initialize_tab(self, index):
544 assert index < self.MAX_TABS, "Invalid tab"
545 if not self._tabsContents[index].has_child():
546 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
547 self._tabsContents[index].set_child(tab)
548 self._tabsContents[index].refresh(force=False)
550 def _prompt_for_login(self):
551 if self._credentialsDialog is None:
553 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
554 credentials = self._credentialsDialog.run(
555 self._defaultCredentials[0], self._defaultCredentials[1], self.window
557 if credentials is None:
559 username, password = credentials
560 self._curentCredentials = username, password
561 self._session.login(username, password)
563 def _show_account_dialog(self):
564 if self._accountDialog is None:
566 self._accountDialog = dialogs.AccountDialog(self._app)
567 if self._app.alarmHandler is None:
568 self._accountDialog.setIfNotificationsSupported(False)
569 if self._app.alarmHandler is not None:
570 self._accountDialog.notifications = self._app.alarmHandler.isEnabled
571 self._accountDialog.notificationTime = self._app.alarmHandler.recurrence
572 self._accountDialog.notifyOnMissed = self._app.notifyOnMissed
573 self._accountDialog.notifyOnVoicemail = self._app.notifyOnVoicemail
574 self._accountDialog.notifyOnSms = self._app.notifyOnSms
575 self._accountDialog.set_callbacks(
576 self._session.get_callback_numbers(), self._session.get_callback_number()
578 accountNumberToDisplay = self._session.get_account_number()
579 if not accountNumberToDisplay:
580 accountNumberToDisplay = "Not Available (%s)" % self._session.state
581 self._accountDialog.set_account_number(accountNumberToDisplay)
582 response = self._accountDialog.run(self.window)
583 if response == QtGui.QDialog.Accepted:
584 if self._accountDialog.doClear:
585 self._session.logout_and_clear()
586 self._defaultCredentials = "", ""
587 self._curentCredentials = "", ""
588 for tab in self._tabsContents:
591 callbackNumber = self._accountDialog.selectedCallback
592 self._session.set_callback_number(callbackNumber)
593 if self._app.alarmHandler is not None:
594 self._app.alarmHandler.apply_settings(self._accountDialog.notifications, self._accountDialog.notificationTime)
595 self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
596 self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
597 self._app.notifyOnSms = self._accountDialog.notifyOnSms
598 self._app.save_settings()
599 elif response == QtGui.QDialog.Rejected:
600 _moduleLogger.info("Cancelled")
602 _moduleLogger.info("Unknown response")
605 @misc_utils.log_exception(_moduleLogger)
606 def _on_call_missed(self):
607 with qui_utils.notify_error(self._errorLog):
608 self._session.update_messages(True)
611 @misc_utils.log_exception(_moduleLogger)
612 def _on_new_message_alert(self):
613 with qui_utils.notify_error(self._errorLog):
614 if self._alertSoundPath is not None:
615 QtGui.QSound.play(self._alertSoundPath)
617 _moduleLogger.info("Alert but alas I am missing my voice")
619 @QtCore.pyqtSlot(str)
620 @misc_utils.log_exception(_moduleLogger)
621 def _on_session_error(self, message):
622 with qui_utils.notify_error(self._errorLog):
623 self._errorLog.push_error(message)
626 @misc_utils.log_exception(_moduleLogger)
628 with qui_utils.notify_error(self._errorLog):
629 changedAccounts = self._defaultCredentials != self._curentCredentials
630 noCallback = not self._session.get_callback_number()
631 if changedAccounts or noCallback:
632 self._show_account_dialog()
634 self._defaultCredentials = self._curentCredentials
636 for tab in self._tabsContents:
638 self._initialize_tab(self._currentTab)
639 self._callHandler.start()
642 @misc_utils.log_exception(_moduleLogger)
643 def _on_logout(self):
644 with qui_utils.notify_error(self._errorLog):
645 for tab in self._tabsContents:
647 self._callHandler.stop()
650 @misc_utils.log_exception(_moduleLogger)
651 def _on_recipients_changed(self):
652 with qui_utils.notify_error(self._errorLog):
653 if self._session.draft.get_num_contacts() == 0:
656 if self._smsEntryDialog is None:
658 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
659 self._smsEntryDialog.window.destroyed.connect(self._on_child_close)
660 self._smsEntryDialog.window.closed.connect(self._on_child_close)
661 self._smsEntryDialog.window.show()
663 @misc_utils.log_exception(_moduleLogger)
664 def _on_child_close(self, obj = None):
665 self._smsEntryDialog = None
668 @QtCore.pyqtSlot(bool)
669 @misc_utils.log_exception(_moduleLogger)
670 def _on_login_requested(self, checked = True):
671 with qui_utils.notify_error(self._errorLog):
672 self._prompt_for_login()
674 @QtCore.pyqtSlot(int)
675 @misc_utils.log_exception(_moduleLogger)
676 def _on_tab_changed(self, index):
677 with qui_utils.notify_error(self._errorLog):
678 self._currentTab = index
679 self._initialize_tab(index)
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_import(self, checked = True):
692 with qui_utils.notify_error(self._errorLog):
693 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
694 csvName = unicode(csvName)
698 shutil.copy2(csvName, self._app.fsContactsPath)
699 if self._tabsContents[self.CONTACTS_TAB].has_child:
700 self._tabsContents[self.CONTACTS_TAB].child.update_addressbooks()
703 @QtCore.pyqtSlot(bool)
704 @misc_utils.log_exception(_moduleLogger)
705 def _on_account(self, checked = True):
706 with qui_utils.notify_error(self._errorLog):
707 assert self._session.state == self._session.LOGGEDIN_STATE, "Must be logged in for settings"
708 self._show_account_dialog()
712 app = QtGui.QApplication([])
713 l = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
714 handle = Dialcentral(app)
719 if __name__ == "__main__":
722 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
723 logging.basicConfig(level=logging.DEBUG, format=logFormat)
725 os.makedirs(constants._data_path_)