4 from __future__ import with_statement
11 import logging.handlers
13 from PyQt4 import QtGui
14 from PyQt4 import QtCore
18 from util import qtpie
19 from util import qwrappers
20 from util import qui_utils
21 from util import misc as misc_utils
26 _moduleLogger = logging.getLogger(__name__)
29 class Dialcentral(qwrappers.ApplicationWrapper):
32 os.path.join(os.path.dirname(__file__), "../share"),
33 os.path.join(os.path.dirname(__file__), "../data"),
36 def __init__(self, app):
38 self._aboutDialog = None
39 self.notifyOnMissed = False
40 self.notifyOnVoicemail = False
41 self.notifyOnSms = False
43 self._streamHandler = None
44 self._ledHandler = None
45 self._alarmHandler = alarm_handler.AlarmHandler()
47 qwrappers.ApplicationWrapper.__init__(self, app, constants)
49 def load_settings(self):
51 config = ConfigParser.SafeConfigParser()
52 config.read(constants._user_settings_)
54 _moduleLogger.info("No settings")
57 _moduleLogger.info("Settings were corrupt")
59 except ConfigParser.MissingSectionHeaderError:
60 _moduleLogger.info("Settings were corrupt")
63 _moduleLogger.exception("Unknown loading error")
67 isPortrait = qui_utils.screen_orientation() == QtCore.Qt.Vertical
71 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
72 for i in xrange(len(self._mainWindow.get_default_credentials()))
74 isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
75 tabIndex = config.getint(constants.__pretty_app_name__, "tab")
76 isPortrait = config.getboolean(constants.__pretty_app_name__, "portrait")
77 except ConfigParser.NoOptionError, e:
79 "Settings file %s is missing option %s" % (
80 constants._user_settings_,
84 except ConfigParser.NoSectionError, e:
86 "Settings file %s is missing section %s" % (
87 constants._user_settings_,
92 _moduleLogger.exception("Unknown loading error")
95 self._alarmHandler.load_settings(config, "alarm")
96 self.notifyOnMissed = config.getboolean("2 - Account Info", "notifyOnMissed")
97 self.notifyOnVoicemail = config.getboolean("2 - Account Info", "notifyOnVoicemail")
98 self.notifyOnSms = config.getboolean("2 - Account Info", "notifyOnSms")
99 except ConfigParser.NoOptionError, e:
101 "Settings file %s is missing option %s" % (
102 constants._user_settings_,
106 except ConfigParser.NoSectionError, e:
108 "Settings file %s is missing section %s" % (
109 constants._user_settings_,
114 _moduleLogger.exception("Unknown loading error")
117 base64.b64decode(blob)
120 self._mainWindow.set_default_credentials(*creds)
121 self._fullscreenAction.setChecked(isFullscreen)
122 self._orientationAction.setChecked(isPortrait)
123 self._mainWindow.set_current_tab(tabIndex)
124 self._mainWindow.load_settings(config)
126 def save_settings(self):
127 _moduleLogger.info("Saving settings")
128 config = ConfigParser.SafeConfigParser()
130 config.add_section(constants.__pretty_app_name__)
131 config.set(constants.__pretty_app_name__, "tab", str(self._mainWindow.get_current_tab()))
132 config.set(constants.__pretty_app_name__, "fullscreen", str(self._fullscreenAction.isChecked()))
133 config.set(constants.__pretty_app_name__, "portrait", str(self._orientationAction.isChecked()))
134 for i, value in enumerate(self._mainWindow.get_default_credentials()):
135 blob = base64.b64encode(value)
136 config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
138 config.add_section("alarm")
139 self._alarmHandler.save_settings(config, "alarm")
140 config.add_section("2 - Account Info")
141 config.set("2 - Account Info", "notifyOnMissed", repr(self.notifyOnMissed))
142 config.set("2 - Account Info", "notifyOnVoicemail", repr(self.notifyOnVoicemail))
143 config.set("2 - Account Info", "notifyOnSms", repr(self.notifyOnSms))
145 self._mainWindow.save_settings(config)
147 with open(constants._user_settings_, "wb") as configFile:
148 config.write(configFile)
150 def get_icon(self, name):
151 if self._dataPath is None:
152 for path in self._DATA_PATHS:
153 if os.path.exists(os.path.join(path, name)):
154 self._dataPath = path
156 if self._dataPath is not None:
157 icon = QtGui.QIcon(os.path.join(self._dataPath, name))
162 def get_resource(self, name):
163 if self._dataPath is None:
164 for path in self._DATA_PATHS:
165 if os.path.exists(os.path.join(path, name)):
166 self._dataPath = path
168 if self._dataPath is not None:
169 return os.path.join(self._dataPath, name)
173 def _close_windows(self):
174 qwrappers.ApplicationWrapper._close_windows(self)
175 if self._aboutDialog is not None:
176 self._aboutDialog.close()
179 def fsContactsPath(self):
180 return os.path.join(constants._data_path_, "contacts")
183 def streamHandler(self):
184 if self._streamHandler is None:
185 import stream_handler
186 self._streamHandler = stream_handler.StreamHandler()
187 return self._streamHandler
190 def alarmHandler(self):
191 return self._alarmHandler
194 def ledHandler(self):
195 if self._ledHandler is None:
197 self._ledHandler = led_handler.LedHandler()
198 return self._ledHandler
200 def _new_main_window(self):
201 return MainWindow(None, self)
204 @QtCore.pyqtSlot(bool)
205 @misc_utils.log_exception(_moduleLogger)
206 def _on_about(self, checked = True):
207 with qui_utils.notify_error(self._errorLog):
208 if self._aboutDialog is None:
210 self._aboutDialog = dialogs.AboutDialog(self)
211 response = self._aboutDialog.run(self._mainWindow.window)
214 class DelayedWidget(object):
216 def __init__(self, app, settingsNames):
217 self._layout = QtGui.QVBoxLayout()
218 self._layout.setContentsMargins(0, 0, 0, 0)
219 self._widget = QtGui.QWidget()
220 self._widget.setContentsMargins(0, 0, 0, 0)
221 self._widget.setLayout(self._layout)
222 self._settings = dict((name, "") for name in settingsNames)
225 self._isEnabled = True
232 return self._child is not None
234 def set_child(self, child):
235 if self._child is not None:
236 self._layout.removeWidget(self._child.toplevel)
238 if self._child is not None:
239 self._layout.addWidget(self._child.toplevel)
241 self._child.set_settings(self._settings)
246 self._child.disable()
253 self._isEnabled = True
254 if self._child is not None:
258 self._isEnabled = False
259 if self._child is not None:
260 self._child.disable()
263 if self._child is not None:
266 def refresh(self, force=True):
267 if self._child is not None:
268 self._child.refresh(force)
270 def get_settings(self):
271 if self._child is not None:
272 return self._child.get_settings()
274 return self._settings
276 def set_settings(self, settings):
277 if self._child is not None:
278 self._child.set_settings(settings)
280 self._settings = settings
283 def _tab_factory(tab, app, session, errorLog):
285 return gv_views.__dict__[tab](app, session, errorLog)
288 class MainWindow(qwrappers.WindowWrapper):
302 assert len(_TAB_TITLES) == MAX_TABS
310 assert len(_TAB_ICONS) == MAX_TABS
313 functools.partial(_tab_factory, "Dialpad"),
314 functools.partial(_tab_factory, "History"),
315 functools.partial(_tab_factory, "Messages"),
316 functools.partial(_tab_factory, "Contacts"),
318 assert len(_TAB_CLASS) == MAX_TABS
320 # Hack to allow delay importing/loading of tabs
321 _TAB_SETTINGS_NAMES = [
325 ("selectedAddressbook", ),
327 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
329 def __init__(self, parent, app):
330 qwrappers.WindowWrapper.__init__(self, parent, app)
331 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
332 self._errorLog = self._app.errorLog
334 self._session = session.Session(self._errorLog, constants._data_path_)
335 self._session.error.connect(self._on_session_error)
336 self._session.loggedIn.connect(self._on_login)
337 self._session.loggedOut.connect(self._on_logout)
338 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
339 self._session.newMessages.connect(self._on_new_message_alert)
340 self._app.alarmHandler.applicationNotifySignal.connect(self._on_app_alert)
341 self._defaultCredentials = "", ""
342 self._curentCredentials = "", ""
345 self._credentialsDialog = None
346 self._smsEntryDialog = None
347 self._accountDialog = None
349 self._tabsContents = [
350 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
351 for i in xrange(self.MAX_TABS)
353 for tab in self._tabsContents:
356 self._tabWidget = QtGui.QTabWidget()
357 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
358 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
360 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
361 defaultTabIconSize = self._tabWidget.iconSize()
362 defaultTabIconWidth, defaultTabIconHeight = defaultTabIconSize.width(), defaultTabIconSize.height()
363 for tabIndex, (tabTitle, tabIcon) in enumerate(
364 zip(self._TAB_TITLES, self._TAB_ICONS)
366 icon = self._app.get_icon(tabIcon)
367 if constants.IS_MAEMO and icon is not None:
371 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
373 iconSize = icon.availableSizes()[0]
374 defaultTabIconWidth = max(defaultTabIconWidth, iconSize.width())
375 defaultTabIconHeight = max(defaultTabIconHeight, iconSize.height())
376 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
377 defaultTabIconWidth = max(defaultTabIconWidth, 32)
378 defaultTabIconHeight = max(defaultTabIconHeight, 32)
379 self._tabWidget.setIconSize(QtCore.QSize(defaultTabIconWidth, defaultTabIconHeight))
380 self._tabWidget.currentChanged.connect(self._on_tab_changed)
381 self._tabWidget.setContentsMargins(0, 0, 0, 0)
383 self._layout.addWidget(self._tabWidget)
385 self._loginAction = QtGui.QAction(None)
386 self._loginAction.setText("Login")
387 self._loginAction.triggered.connect(self._on_login_requested)
389 self._importAction = QtGui.QAction(None)
390 self._importAction.setText("Import")
391 self._importAction.triggered.connect(self._on_import)
393 self._accountAction = QtGui.QAction(None)
394 self._accountAction.setText("Account")
395 self._accountAction.triggered.connect(self._on_account)
397 self._refreshConnectionAction = QtGui.QAction(None)
398 self._refreshConnectionAction.setText("Refresh Connection")
399 self._refreshConnectionAction.setShortcut(QtGui.QKeySequence("CTRL+a"))
400 self._refreshConnectionAction.triggered.connect(self._on_refresh_connection)
402 self._refreshTabAction = QtGui.QAction(None)
403 self._refreshTabAction.setText("Refresh Tab")
404 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
405 self._refreshTabAction.triggered.connect(self._on_refresh)
407 fileMenu = self._window.menuBar().addMenu("&File")
408 fileMenu.addAction(self._loginAction)
409 fileMenu.addAction(self._refreshTabAction)
410 fileMenu.addAction(self._refreshConnectionAction)
412 toolsMenu = self._window.menuBar().addMenu("&Tools")
413 toolsMenu.addAction(self._accountAction)
414 toolsMenu.addAction(self._importAction)
415 toolsMenu.addAction(self._app.aboutAction)
417 self._initialize_tab(self._tabWidget.currentIndex())
418 self.set_fullscreen(self._app.fullscreenAction.isChecked())
419 self.set_orientation(self._app.orientationAction.isChecked())
421 def set_default_credentials(self, username, password):
422 self._defaultCredentials = username, password
424 def get_default_credentials(self):
425 return self._defaultCredentials
427 def walk_children(self):
428 if self._smsEntryDialog is not None:
429 return (self._smsEntryDialog, )
434 qwrappers.WindowWrapper.start(self)
435 assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
436 if self._defaultCredentials != ("", ""):
437 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
438 self._curentCredentials = username, password
439 self._session.login(username, password)
441 self._prompt_for_login()
445 self._credentialsDialog,
450 for child in self.walk_children():
451 child.window.destroyed.disconnect(self._on_child_close)
452 child.window.closed.disconnect(self._on_child_close)
457 qwrappers.WindowWrapper.destroy(self)
458 if self._session.state != self._session.LOGGEDOUT_STATE:
459 self._session.logout()
461 def get_current_tab(self):
462 return self._currentTab
464 def set_current_tab(self, tabIndex):
465 self._tabWidget.setCurrentIndex(tabIndex)
467 def load_settings(self, config):
468 backendId = 2 # For backwards compatibility
469 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
470 sectionName = "%s - %s" % (backendId, tabTitle)
471 settings = self._tabsContents[tabIndex].get_settings()
472 for settingName in settings.iterkeys():
474 settingValue = config.get(sectionName, settingName)
475 except ConfigParser.NoOptionError, e:
477 "Settings file %s is missing section %s" % (
478 constants._user_settings_,
483 except ConfigParser.NoSectionError, e:
485 "Settings file %s is missing section %s" % (
486 constants._user_settings_,
492 _moduleLogger.exception("Unknown loading error")
494 settings[settingName] = settingValue
495 self._tabsContents[tabIndex].set_settings(settings)
497 def save_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 config.add_section(sectionName)
502 tabSettings = self._tabsContents[tabIndex].get_settings()
503 for settingName, settingValue in tabSettings.iteritems():
504 config.set(sectionName, settingName, settingValue)
506 def set_orientation(self, isPortrait):
507 qwrappers.WindowWrapper.set_orientation(self, isPortrait)
509 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
511 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
513 def _initialize_tab(self, index):
514 assert index < self.MAX_TABS, "Invalid tab"
515 if not self._tabsContents[index].has_child():
516 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
517 self._tabsContents[index].set_child(tab)
518 self._tabsContents[index].refresh(force=False)
520 def _prompt_for_login(self):
521 if self._credentialsDialog is None:
523 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
524 credentials = self._credentialsDialog.run(
525 self._defaultCredentials[0], self._defaultCredentials[1], self.window
527 if credentials is None:
529 username, password = credentials
530 self._curentCredentials = username, password
531 self._session.login(username, password)
533 def _show_account_dialog(self):
534 if self._accountDialog is None:
536 self._accountDialog = dialogs.AccountDialog(self._app)
537 self._accountDialog.setIfNotificationsSupported(self._app.alarmHandler.backgroundNotificationsSupported)
538 self._accountDialog.notifications = self._app.alarmHandler.alarmType
539 self._accountDialog.notificationTime = self._app.alarmHandler.recurrence
540 self._accountDialog.notifyOnMissed = self._app.notifyOnMissed
541 self._accountDialog.notifyOnVoicemail = self._app.notifyOnVoicemail
542 self._accountDialog.notifyOnSms = self._app.notifyOnSms
543 self._accountDialog.set_callbacks(
544 self._session.get_callback_numbers(), self._session.get_callback_number()
546 accountNumberToDisplay = self._session.get_account_number()
547 if not accountNumberToDisplay:
548 accountNumberToDisplay = "Not Available (%s)" % self._session.state
549 self._accountDialog.set_account_number(accountNumberToDisplay)
550 response = self._accountDialog.run(self.window)
551 if response == QtGui.QDialog.Accepted:
552 if self._accountDialog.doClear:
553 self._session.logout_and_clear()
554 self._defaultCredentials = "", ""
555 self._curentCredentials = "", ""
556 for tab in self._tabsContents:
559 callbackNumber = self._accountDialog.selectedCallback
560 self._session.set_callback_number(callbackNumber)
563 self._accountDialog.notifyOnMissed or
564 self._accountDialog.notifyOnVoicemail or
565 self._accountDialog.notifyOnSms
567 notifications = self._accountDialog.notifications
569 notifications = self._accountDialog.ALARM_NONE
570 self._app.alarmHandler.apply_settings(notifications, self._accountDialog.notificationTime)
572 self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
573 self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
574 self._app.notifyOnSms = self._accountDialog.notifyOnSms
575 self._app.save_settings()
576 elif response == QtGui.QDialog.Rejected:
577 _moduleLogger.info("Cancelled")
579 _moduleLogger.info("Unknown response")
582 @misc_utils.log_exception(_moduleLogger)
583 def _on_new_message_alert(self):
584 with qui_utils.notify_error(self._errorLog):
585 if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
586 if self._currentTab == self.MESSAGES_TAB or not self._app.ledHandler.isReal:
587 self._errorLog.push_message("New messages available")
589 self._app.ledHandler.on()
591 @QtCore.pyqtSlot(str)
592 @misc_utils.log_exception(_moduleLogger)
593 def _on_session_error(self, message):
594 with qui_utils.notify_error(self._errorLog):
595 self._errorLog.push_error(message)
598 @misc_utils.log_exception(_moduleLogger)
600 with qui_utils.notify_error(self._errorLog):
601 changedAccounts = self._defaultCredentials != self._curentCredentials
602 noCallback = not self._session.get_callback_number()
603 if changedAccounts or noCallback:
604 self._show_account_dialog()
606 self._defaultCredentials = self._curentCredentials
608 for tab in self._tabsContents:
610 self._initialize_tab(self._currentTab)
613 @misc_utils.log_exception(_moduleLogger)
614 def _on_logout(self):
615 with qui_utils.notify_error(self._errorLog):
616 for tab in self._tabsContents:
620 @misc_utils.log_exception(_moduleLogger)
621 def _on_app_alert(self):
622 with qui_utils.notify_error(self._errorLog):
623 if self._session.state == self._session.LOGGEDIN_STATE:
625 (True, True): self._session.MESSAGE_ALL,
626 (True, False): self._session.MESSAGE_TEXTS,
627 (False, True): self._session.MESSAGE_VOICEMAILS,
628 }[(self._app.notifyOnSms, self._app.notifyOnVoicemail)]
629 self._session.update_messages(messageType, force=True)
632 @misc_utils.log_exception(_moduleLogger)
633 def _on_recipients_changed(self):
634 with qui_utils.notify_error(self._errorLog):
635 if self._session.draft.get_num_contacts() == 0:
638 if self._smsEntryDialog is None:
640 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
641 self._smsEntryDialog.window.destroyed.connect(self._on_child_close)
642 self._smsEntryDialog.window.closed.connect(self._on_child_close)
643 self._smsEntryDialog.window.show()
645 @misc_utils.log_exception(_moduleLogger)
646 def _on_child_close(self, obj = None):
647 self._smsEntryDialog = None
650 @QtCore.pyqtSlot(bool)
651 @misc_utils.log_exception(_moduleLogger)
652 def _on_login_requested(self, checked = True):
653 with qui_utils.notify_error(self._errorLog):
654 self._prompt_for_login()
656 @QtCore.pyqtSlot(int)
657 @misc_utils.log_exception(_moduleLogger)
658 def _on_tab_changed(self, index):
659 with qui_utils.notify_error(self._errorLog):
660 self._currentTab = index
661 self._initialize_tab(index)
662 if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
663 self._app.ledHandler.off()
666 @QtCore.pyqtSlot(bool)
667 @misc_utils.log_exception(_moduleLogger)
668 def _on_refresh(self, checked = True):
669 with qui_utils.notify_error(self._errorLog):
670 self._tabsContents[self._currentTab].refresh(force=True)
673 @QtCore.pyqtSlot(bool)
674 @misc_utils.log_exception(_moduleLogger)
675 def _on_refresh_connection(self, checked = True):
676 with qui_utils.notify_error(self._errorLog):
677 self._session.refresh_connection()
680 @QtCore.pyqtSlot(bool)
681 @misc_utils.log_exception(_moduleLogger)
682 def _on_import(self, checked = True):
683 with qui_utils.notify_error(self._errorLog):
684 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
685 csvName = unicode(csvName)
689 shutil.copy2(csvName, self._app.fsContactsPath)
690 if self._tabsContents[self.CONTACTS_TAB].has_child:
691 self._tabsContents[self.CONTACTS_TAB].child.update_addressbooks()
694 @QtCore.pyqtSlot(bool)
695 @misc_utils.log_exception(_moduleLogger)
696 def _on_account(self, checked = True):
697 with qui_utils.notify_error(self._errorLog):
698 assert self._session.state == self._session.LOGGEDIN_STATE, "Must be logged in for settings"
699 self._show_account_dialog()
704 os.makedirs(constants._data_path_)
711 gobject.threads_init()
715 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
716 logging.basicConfig(level=logging.DEBUG, format=logFormat)
717 rotating = logging.handlers.RotatingFileHandler(constants._user_logpath_, maxBytes=512*1024, backupCount=1)
718 rotating.setFormatter(logging.Formatter(logFormat))
719 root = logging.getLogger()
720 root.addHandler(rotating)
721 _moduleLogger.info("%s %s-%s" % (constants.__app_name__, constants.__version__, constants.__build__))
722 _moduleLogger.info("OS: %s" % (os.uname()[0], ))
723 _moduleLogger.info("Kernel: %s (%s) for %s" % os.uname()[2:])
724 _moduleLogger.info("Hostname: %s" % os.uname()[1])
726 app = QtGui.QApplication([])
727 handle = Dialcentral(app)
732 if __name__ == "__main__":