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._ledHandler = led_handler.LedHandler()
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 alarmHandler(self):
184 return self._alarmHandler
187 def ledHandler(self):
188 return self._ledHandler
190 def _new_main_window(self):
191 return MainWindow(None, self)
194 @QtCore.pyqtSlot(bool)
195 @misc_utils.log_exception(_moduleLogger)
196 def _on_about(self, checked = True):
197 with qui_utils.notify_error(self._errorLog):
198 if self._aboutDialog is None:
200 self._aboutDialog = dialogs.AboutDialog(self)
201 response = self._aboutDialog.run(self._mainWindow.window)
204 class DelayedWidget(object):
206 def __init__(self, app, settingsNames):
207 self._layout = QtGui.QVBoxLayout()
208 self._layout.setContentsMargins(0, 0, 0, 0)
209 self._widget = QtGui.QWidget()
210 self._widget.setContentsMargins(0, 0, 0, 0)
211 self._widget.setLayout(self._layout)
212 self._settings = dict((name, "") for name in settingsNames)
215 self._isEnabled = True
222 return self._child is not None
224 def set_child(self, child):
225 if self._child is not None:
226 self._layout.removeWidget(self._child.toplevel)
228 if self._child is not None:
229 self._layout.addWidget(self._child.toplevel)
231 self._child.set_settings(self._settings)
236 self._child.disable()
243 self._isEnabled = True
244 if self._child is not None:
248 self._isEnabled = False
249 if self._child is not None:
250 self._child.disable()
253 if self._child is not None:
256 def refresh(self, force=True):
257 if self._child is not None:
258 self._child.refresh(force)
260 def get_settings(self):
261 if self._child is not None:
262 return self._child.get_settings()
264 return self._settings
266 def set_settings(self, settings):
267 if self._child is not None:
268 self._child.set_settings(settings)
270 self._settings = settings
273 def _tab_factory(tab, app, session, errorLog):
275 return gv_views.__dict__[tab](app, session, errorLog)
278 class MainWindow(qwrappers.WindowWrapper):
292 assert len(_TAB_TITLES) == MAX_TABS
300 assert len(_TAB_ICONS) == MAX_TABS
303 functools.partial(_tab_factory, "Dialpad"),
304 functools.partial(_tab_factory, "History"),
305 functools.partial(_tab_factory, "Messages"),
306 functools.partial(_tab_factory, "Contacts"),
308 assert len(_TAB_CLASS) == MAX_TABS
310 # Hack to allow delay importing/loading of tabs
311 _TAB_SETTINGS_NAMES = [
315 ("selectedAddressbook", ),
317 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
319 def __init__(self, parent, app):
320 qwrappers.WindowWrapper.__init__(self, parent, app)
321 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
322 self._errorLog = self._app.errorLog
324 self._session = session.Session(self._errorLog, constants._data_path_)
325 self._session.error.connect(self._on_session_error)
326 self._session.loggedIn.connect(self._on_login)
327 self._session.loggedOut.connect(self._on_logout)
328 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
329 self._session.newMessages.connect(self._on_new_message_alert)
330 self._app.alarmHandler.applicationNotifySignal.connect(self._on_app_alert)
331 self._defaultCredentials = "", ""
332 self._curentCredentials = "", ""
335 self._credentialsDialog = None
336 self._smsEntryDialog = None
337 self._accountDialog = None
339 self._tabsContents = [
340 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
341 for i in xrange(self.MAX_TABS)
343 for tab in self._tabsContents:
346 self._tabWidget = QtGui.QTabWidget()
347 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
348 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
350 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
351 defaultTabIconSize = self._tabWidget.iconSize()
352 defaultTabIconWidth, defaultTabIconHeight = defaultTabIconSize.width(), defaultTabIconSize.height()
353 for tabIndex, (tabTitle, tabIcon) in enumerate(
354 zip(self._TAB_TITLES, self._TAB_ICONS)
356 icon = self._app.get_icon(tabIcon)
357 if constants.IS_MAEMO and icon is not None:
361 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
363 iconSize = icon.availableSizes()[0]
364 defaultTabIconWidth = max(defaultTabIconWidth, iconSize.width())
365 defaultTabIconHeight = max(defaultTabIconHeight, iconSize.height())
366 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
367 defaultTabIconWidth = max(defaultTabIconWidth, 32)
368 defaultTabIconHeight = max(defaultTabIconHeight, 32)
369 self._tabWidget.setIconSize(QtCore.QSize(defaultTabIconWidth, defaultTabIconHeight))
370 self._tabWidget.currentChanged.connect(self._on_tab_changed)
371 self._tabWidget.setContentsMargins(0, 0, 0, 0)
373 self._layout.addWidget(self._tabWidget)
375 self._loginTabAction = QtGui.QAction(None)
376 self._loginTabAction.setText("Login")
377 self._loginTabAction.triggered.connect(self._on_login_requested)
379 self._importTabAction = QtGui.QAction(None)
380 self._importTabAction.setText("Import")
381 self._importTabAction.triggered.connect(self._on_import)
383 self._accountTabAction = QtGui.QAction(None)
384 self._accountTabAction.setText("Account")
385 self._accountTabAction.triggered.connect(self._on_account)
387 self._refreshTabAction = QtGui.QAction(None)
388 self._refreshTabAction.setText("Refresh")
389 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
390 self._refreshTabAction.triggered.connect(self._on_refresh)
392 fileMenu = self._window.menuBar().addMenu("&File")
393 fileMenu.addAction(self._loginTabAction)
394 fileMenu.addAction(self._refreshTabAction)
396 toolsMenu = self._window.menuBar().addMenu("&Tools")
397 toolsMenu.addAction(self._accountTabAction)
398 toolsMenu.addAction(self._importTabAction)
399 toolsMenu.addAction(self._app.aboutAction)
401 self._initialize_tab(self._tabWidget.currentIndex())
402 self.set_fullscreen(self._app.fullscreenAction.isChecked())
403 self.set_orientation(self._app.orientationAction.isChecked())
405 def set_default_credentials(self, username, password):
406 self._defaultCredentials = username, password
408 def get_default_credentials(self):
409 return self._defaultCredentials
411 def walk_children(self):
412 if self._smsEntryDialog is not None:
413 return (self._smsEntryDialog, )
418 qwrappers.WindowWrapper.start(self)
419 assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
420 if self._defaultCredentials != ("", ""):
421 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
422 self._curentCredentials = username, password
423 self._session.login(username, password)
425 self._prompt_for_login()
429 self._credentialsDialog,
434 for child in self.walk_children():
435 child.window.destroyed.disconnect(self._on_child_close)
436 child.window.closed.disconnect(self._on_child_close)
441 qwrappers.WindowWrapper.destroy(self)
442 if self._session.state != self._session.LOGGEDOUT_STATE:
443 self._session.logout()
445 def get_current_tab(self):
446 return self._currentTab
448 def set_current_tab(self, tabIndex):
449 self._tabWidget.setCurrentIndex(tabIndex)
451 def load_settings(self, config):
452 backendId = 2 # For backwards compatibility
453 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
454 sectionName = "%s - %s" % (backendId, tabTitle)
455 settings = self._tabsContents[tabIndex].get_settings()
456 for settingName in settings.iterkeys():
458 settingValue = config.get(sectionName, settingName)
459 except ConfigParser.NoOptionError, e:
461 "Settings file %s is missing section %s" % (
462 constants._user_settings_,
467 except ConfigParser.NoSectionError, e:
469 "Settings file %s is missing section %s" % (
470 constants._user_settings_,
476 _moduleLogger.exception("Unknown loading error")
478 settings[settingName] = settingValue
479 self._tabsContents[tabIndex].set_settings(settings)
481 def save_settings(self, config):
482 backendId = 2 # For backwards compatibility
483 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
484 sectionName = "%s - %s" % (backendId, tabTitle)
485 config.add_section(sectionName)
486 tabSettings = self._tabsContents[tabIndex].get_settings()
487 for settingName, settingValue in tabSettings.iteritems():
488 config.set(sectionName, settingName, settingValue)
490 def set_orientation(self, isPortrait):
491 qwrappers.WindowWrapper.set_orientation(self, isPortrait)
493 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
495 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
497 def _initialize_tab(self, index):
498 assert index < self.MAX_TABS, "Invalid tab"
499 if not self._tabsContents[index].has_child():
500 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
501 self._tabsContents[index].set_child(tab)
502 self._tabsContents[index].refresh(force=False)
504 def _prompt_for_login(self):
505 if self._credentialsDialog is None:
507 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
508 credentials = self._credentialsDialog.run(
509 self._defaultCredentials[0], self._defaultCredentials[1], self.window
511 if credentials is None:
513 username, password = credentials
514 self._curentCredentials = username, password
515 self._session.login(username, password)
517 def _show_account_dialog(self):
518 if self._accountDialog is None:
520 self._accountDialog = dialogs.AccountDialog(self._app)
521 self._accountDialog.setIfNotificationsSupported(self._app.alarmHandler.backgroundNotificationsSupported)
522 self._accountDialog.notifications = self._app.alarmHandler.alarmType
523 self._accountDialog.notificationTime = self._app.alarmHandler.recurrence
524 self._accountDialog.notifyOnMissed = self._app.notifyOnMissed
525 self._accountDialog.notifyOnVoicemail = self._app.notifyOnVoicemail
526 self._accountDialog.notifyOnSms = self._app.notifyOnSms
527 self._accountDialog.set_callbacks(
528 self._session.get_callback_numbers(), self._session.get_callback_number()
530 accountNumberToDisplay = self._session.get_account_number()
531 if not accountNumberToDisplay:
532 accountNumberToDisplay = "Not Available (%s)" % self._session.state
533 self._accountDialog.set_account_number(accountNumberToDisplay)
534 response = self._accountDialog.run(self.window)
535 if response == QtGui.QDialog.Accepted:
536 if self._accountDialog.doClear:
537 self._session.logout_and_clear()
538 self._defaultCredentials = "", ""
539 self._curentCredentials = "", ""
540 for tab in self._tabsContents:
543 callbackNumber = self._accountDialog.selectedCallback
544 self._session.set_callback_number(callbackNumber)
547 self._accountDialog.notifyOnMissed or
548 self._accountDialog.notifyOnVoicemail or
549 self._accountDialog.notifyOnSms
551 notifications = self._accountDialog.notifications
553 notifications = self._accountDialog.ALARM_NONE
554 self._app.alarmHandler.apply_settings(notifications, self._accountDialog.notificationTime)
556 self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
557 self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
558 self._app.notifyOnSms = self._accountDialog.notifyOnSms
559 self._app.save_settings()
560 elif response == QtGui.QDialog.Rejected:
561 _moduleLogger.info("Cancelled")
563 _moduleLogger.info("Unknown response")
566 @misc_utils.log_exception(_moduleLogger)
567 def _on_new_message_alert(self):
568 with qui_utils.notify_error(self._errorLog):
569 if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
570 if self._currentTab == self.MESSAGES_TAB or not self._app.ledHandler.isReal:
571 self._errorLog.push_message("New messages available")
573 self._app.ledHandler.on()
575 @QtCore.pyqtSlot(str)
576 @misc_utils.log_exception(_moduleLogger)
577 def _on_session_error(self, message):
578 with qui_utils.notify_error(self._errorLog):
579 self._errorLog.push_error(message)
582 @misc_utils.log_exception(_moduleLogger)
584 with qui_utils.notify_error(self._errorLog):
585 changedAccounts = self._defaultCredentials != self._curentCredentials
586 noCallback = not self._session.get_callback_number()
587 if changedAccounts or noCallback:
588 self._show_account_dialog()
590 self._defaultCredentials = self._curentCredentials
592 for tab in self._tabsContents:
594 self._initialize_tab(self._currentTab)
597 @misc_utils.log_exception(_moduleLogger)
598 def _on_logout(self):
599 with qui_utils.notify_error(self._errorLog):
600 for tab in self._tabsContents:
604 @misc_utils.log_exception(_moduleLogger)
605 def _on_app_alert(self):
606 with qui_utils.notify_error(self._errorLog):
607 if self._session.state == self._session.LOGGEDIN_STATE:
609 (True, True): self._session.MESSAGE_ALL,
610 (True, False): self._session.MESSAGE_TEXTS,
611 (False, True): self._session.MESSAGE_VOICEMAILS,
612 }[(self._app.notifyOnSms, self._app.notifyOnVoicemail)]
613 self._session.update_messages(messageType, force=True)
616 @misc_utils.log_exception(_moduleLogger)
617 def _on_recipients_changed(self):
618 with qui_utils.notify_error(self._errorLog):
619 if self._session.draft.get_num_contacts() == 0:
622 if self._smsEntryDialog is None:
624 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
625 self._smsEntryDialog.window.destroyed.connect(self._on_child_close)
626 self._smsEntryDialog.window.closed.connect(self._on_child_close)
627 self._smsEntryDialog.window.show()
629 @misc_utils.log_exception(_moduleLogger)
630 def _on_child_close(self, obj = None):
631 self._smsEntryDialog = None
634 @QtCore.pyqtSlot(bool)
635 @misc_utils.log_exception(_moduleLogger)
636 def _on_login_requested(self, checked = True):
637 with qui_utils.notify_error(self._errorLog):
638 self._prompt_for_login()
640 @QtCore.pyqtSlot(int)
641 @misc_utils.log_exception(_moduleLogger)
642 def _on_tab_changed(self, index):
643 with qui_utils.notify_error(self._errorLog):
644 self._currentTab = index
645 self._initialize_tab(index)
646 if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
647 self._app.ledHandler.off()
650 @QtCore.pyqtSlot(bool)
651 @misc_utils.log_exception(_moduleLogger)
652 def _on_refresh(self, checked = True):
653 with qui_utils.notify_error(self._errorLog):
654 self._tabsContents[self._currentTab].refresh(force=True)
657 @QtCore.pyqtSlot(bool)
658 @misc_utils.log_exception(_moduleLogger)
659 def _on_import(self, checked = True):
660 with qui_utils.notify_error(self._errorLog):
661 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
662 csvName = unicode(csvName)
666 shutil.copy2(csvName, self._app.fsContactsPath)
667 if self._tabsContents[self.CONTACTS_TAB].has_child:
668 self._tabsContents[self.CONTACTS_TAB].child.update_addressbooks()
671 @QtCore.pyqtSlot(bool)
672 @misc_utils.log_exception(_moduleLogger)
673 def _on_account(self, checked = True):
674 with qui_utils.notify_error(self._errorLog):
675 assert self._session.state == self._session.LOGGEDIN_STATE, "Must be logged in for settings"
676 self._show_account_dialog()
681 os.makedirs(constants._data_path_)
686 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
687 logging.basicConfig(level=logging.DEBUG, format=logFormat)
688 rotating = logging.handlers.RotatingFileHandler(constants._user_logpath_, maxBytes=512*1024, backupCount=1)
689 rotating.setFormatter(logging.Formatter(logFormat))
690 root = logging.getLogger()
691 root.addHandler(rotating)
692 _moduleLogger.info("%s %s-%s" % (constants.__app_name__, constants.__version__, constants.__build__))
693 _moduleLogger.info("OS: %s" % (os.uname()[0], ))
694 _moduleLogger.info("Kernel: %s (%s) for %s" % os.uname()[2:])
695 _moduleLogger.info("Hostname: %s" % os.uname()[1])
697 app = QtGui.QApplication([])
698 handle = Dialcentral(app)
703 if __name__ == "__main__":