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._ledHandler = None
44 self._alarmHandler = alarm_handler.AlarmHandler()
46 qwrappers.ApplicationWrapper.__init__(self, app, constants)
48 def load_settings(self):
50 config = ConfigParser.SafeConfigParser()
51 config.read(constants._user_settings_)
53 _moduleLogger.info("No settings")
56 _moduleLogger.info("Settings were corrupt")
58 except ConfigParser.MissingSectionHeaderError:
59 _moduleLogger.info("Settings were corrupt")
62 _moduleLogger.exception("Unknown loading error")
66 isPortrait = qui_utils.screen_orientation() == QtCore.Qt.Vertical
70 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
71 for i in xrange(len(self._mainWindow.get_default_credentials()))
73 isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
74 tabIndex = config.getint(constants.__pretty_app_name__, "tab")
75 isPortrait = config.getboolean(constants.__pretty_app_name__, "portrait")
76 except ConfigParser.NoOptionError, e:
78 "Settings file %s is missing option %s" % (
79 constants._user_settings_,
83 except ConfigParser.NoSectionError, e:
85 "Settings file %s is missing section %s" % (
86 constants._user_settings_,
91 _moduleLogger.exception("Unknown loading error")
94 self._alarmHandler.load_settings(config, "alarm")
95 self.notifyOnMissed = config.getboolean("2 - Account Info", "notifyOnMissed")
96 self.notifyOnVoicemail = config.getboolean("2 - Account Info", "notifyOnVoicemail")
97 self.notifyOnSms = config.getboolean("2 - Account Info", "notifyOnSms")
98 except ConfigParser.NoOptionError, e:
100 "Settings file %s is missing option %s" % (
101 constants._user_settings_,
105 except ConfigParser.NoSectionError, e:
107 "Settings file %s is missing section %s" % (
108 constants._user_settings_,
113 _moduleLogger.exception("Unknown loading error")
116 base64.b64decode(blob)
119 self._mainWindow.set_default_credentials(*creds)
120 self._fullscreenAction.setChecked(isFullscreen)
121 self._orientationAction.setChecked(isPortrait)
122 self._mainWindow.set_current_tab(tabIndex)
123 self._mainWindow.load_settings(config)
125 def save_settings(self):
126 _moduleLogger.info("Saving settings")
127 config = ConfigParser.SafeConfigParser()
129 config.add_section(constants.__pretty_app_name__)
130 config.set(constants.__pretty_app_name__, "tab", str(self._mainWindow.get_current_tab()))
131 config.set(constants.__pretty_app_name__, "fullscreen", str(self._fullscreenAction.isChecked()))
132 config.set(constants.__pretty_app_name__, "portrait", str(self._orientationAction.isChecked()))
133 for i, value in enumerate(self._mainWindow.get_default_credentials()):
134 blob = base64.b64encode(value)
135 config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
137 config.add_section("alarm")
138 self._alarmHandler.save_settings(config, "alarm")
139 config.add_section("2 - Account Info")
140 config.set("2 - Account Info", "notifyOnMissed", repr(self.notifyOnMissed))
141 config.set("2 - Account Info", "notifyOnVoicemail", repr(self.notifyOnVoicemail))
142 config.set("2 - Account Info", "notifyOnSms", repr(self.notifyOnSms))
144 self._mainWindow.save_settings(config)
146 with open(constants._user_settings_, "wb") as configFile:
147 config.write(configFile)
149 def get_icon(self, name):
150 if self._dataPath is None:
151 for path in self._DATA_PATHS:
152 if os.path.exists(os.path.join(path, name)):
153 self._dataPath = path
155 if self._dataPath is not None:
156 icon = QtGui.QIcon(os.path.join(self._dataPath, name))
161 def get_resource(self, name):
162 if self._dataPath is None:
163 for path in self._DATA_PATHS:
164 if os.path.exists(os.path.join(path, name)):
165 self._dataPath = path
167 if self._dataPath is not None:
168 return os.path.join(self._dataPath, name)
172 def _close_windows(self):
173 qwrappers.ApplicationWrapper._close_windows(self)
174 if self._aboutDialog is not None:
175 self._aboutDialog.close()
178 def fsContactsPath(self):
179 return os.path.join(constants._data_path_, "contacts")
182 def alarmHandler(self):
183 return self._alarmHandler
186 def ledHandler(self):
187 if self._ledHandler is None:
189 self._ledHandler = led_handler.LedHandler()
190 return self._ledHandler
192 def _new_main_window(self):
193 return MainWindow(None, self)
196 @QtCore.pyqtSlot(bool)
197 @misc_utils.log_exception(_moduleLogger)
198 def _on_about(self, checked = True):
199 with qui_utils.notify_error(self._errorLog):
200 if self._aboutDialog is None:
202 self._aboutDialog = dialogs.AboutDialog(self)
203 response = self._aboutDialog.run(self._mainWindow.window)
206 class DelayedWidget(object):
208 def __init__(self, app, settingsNames):
209 self._layout = QtGui.QVBoxLayout()
210 self._layout.setContentsMargins(0, 0, 0, 0)
211 self._widget = QtGui.QWidget()
212 self._widget.setContentsMargins(0, 0, 0, 0)
213 self._widget.setLayout(self._layout)
214 self._settings = dict((name, "") for name in settingsNames)
217 self._isEnabled = True
224 return self._child is not None
226 def set_child(self, child):
227 if self._child is not None:
228 self._layout.removeWidget(self._child.toplevel)
230 if self._child is not None:
231 self._layout.addWidget(self._child.toplevel)
233 self._child.set_settings(self._settings)
238 self._child.disable()
245 self._isEnabled = True
246 if self._child is not None:
250 self._isEnabled = False
251 if self._child is not None:
252 self._child.disable()
255 if self._child is not None:
258 def refresh(self, force=True):
259 if self._child is not None:
260 self._child.refresh(force)
262 def get_settings(self):
263 if self._child is not None:
264 return self._child.get_settings()
266 return self._settings
268 def set_settings(self, settings):
269 if self._child is not None:
270 self._child.set_settings(settings)
272 self._settings = settings
275 def _tab_factory(tab, app, session, errorLog):
277 return gv_views.__dict__[tab](app, session, errorLog)
280 class MainWindow(qwrappers.WindowWrapper):
294 assert len(_TAB_TITLES) == MAX_TABS
302 assert len(_TAB_ICONS) == MAX_TABS
305 functools.partial(_tab_factory, "Dialpad"),
306 functools.partial(_tab_factory, "History"),
307 functools.partial(_tab_factory, "Messages"),
308 functools.partial(_tab_factory, "Contacts"),
310 assert len(_TAB_CLASS) == MAX_TABS
312 # Hack to allow delay importing/loading of tabs
313 _TAB_SETTINGS_NAMES = [
317 ("selectedAddressbook", ),
319 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
321 def __init__(self, parent, app):
322 qwrappers.WindowWrapper.__init__(self, parent, app)
323 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
324 self._errorLog = self._app.errorLog
326 self._session = session.Session(self._errorLog, constants._data_path_)
327 self._session.error.connect(self._on_session_error)
328 self._session.loggedIn.connect(self._on_login)
329 self._session.loggedOut.connect(self._on_logout)
330 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
331 self._session.newMessages.connect(self._on_new_message_alert)
332 self._app.alarmHandler.applicationNotifySignal.connect(self._on_app_alert)
333 self._defaultCredentials = "", ""
334 self._curentCredentials = "", ""
337 self._credentialsDialog = None
338 self._smsEntryDialog = None
339 self._accountDialog = None
341 self._tabsContents = [
342 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
343 for i in xrange(self.MAX_TABS)
345 for tab in self._tabsContents:
348 self._tabWidget = QtGui.QTabWidget()
349 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
350 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
352 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
353 defaultTabIconSize = self._tabWidget.iconSize()
354 defaultTabIconWidth, defaultTabIconHeight = defaultTabIconSize.width(), defaultTabIconSize.height()
355 for tabIndex, (tabTitle, tabIcon) in enumerate(
356 zip(self._TAB_TITLES, self._TAB_ICONS)
358 icon = self._app.get_icon(tabIcon)
359 if constants.IS_MAEMO and icon is not None:
363 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
365 iconSize = icon.availableSizes()[0]
366 defaultTabIconWidth = max(defaultTabIconWidth, iconSize.width())
367 defaultTabIconHeight = max(defaultTabIconHeight, iconSize.height())
368 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
369 defaultTabIconWidth = max(defaultTabIconWidth, 32)
370 defaultTabIconHeight = max(defaultTabIconHeight, 32)
371 self._tabWidget.setIconSize(QtCore.QSize(defaultTabIconWidth, defaultTabIconHeight))
372 self._tabWidget.currentChanged.connect(self._on_tab_changed)
373 self._tabWidget.setContentsMargins(0, 0, 0, 0)
375 self._layout.addWidget(self._tabWidget)
377 self._loginAction = QtGui.QAction(None)
378 self._loginAction.setText("Login")
379 self._loginAction.triggered.connect(self._on_login_requested)
381 self._importAction = QtGui.QAction(None)
382 self._importAction.setText("Import")
383 self._importAction.triggered.connect(self._on_import)
385 self._accountAction = QtGui.QAction(None)
386 self._accountAction.setText("Account")
387 self._accountAction.triggered.connect(self._on_account)
389 self._refreshConnectionAction = QtGui.QAction(None)
390 self._refreshConnectionAction.setText("Refresh Connection")
391 self._refreshConnectionAction.setShortcut(QtGui.QKeySequence("CTRL+a"))
392 self._refreshConnectionAction.triggered.connect(self._on_refresh_connection)
394 self._refreshTabAction = QtGui.QAction(None)
395 self._refreshTabAction.setText("Refresh Tab")
396 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
397 self._refreshTabAction.triggered.connect(self._on_refresh)
399 fileMenu = self._window.menuBar().addMenu("&File")
400 fileMenu.addAction(self._loginAction)
401 fileMenu.addAction(self._refreshTabAction)
402 fileMenu.addAction(self._refreshConnectionAction)
404 toolsMenu = self._window.menuBar().addMenu("&Tools")
405 toolsMenu.addAction(self._accountAction)
406 toolsMenu.addAction(self._importAction)
407 toolsMenu.addAction(self._app.aboutAction)
409 self._initialize_tab(self._tabWidget.currentIndex())
410 self.set_fullscreen(self._app.fullscreenAction.isChecked())
411 self.set_orientation(self._app.orientationAction.isChecked())
413 def set_default_credentials(self, username, password):
414 self._defaultCredentials = username, password
416 def get_default_credentials(self):
417 return self._defaultCredentials
419 def walk_children(self):
420 if self._smsEntryDialog is not None:
421 return (self._smsEntryDialog, )
426 qwrappers.WindowWrapper.start(self)
427 assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
428 if self._defaultCredentials != ("", ""):
429 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
430 self._curentCredentials = username, password
431 self._session.login(username, password)
433 self._prompt_for_login()
437 self._credentialsDialog,
442 for child in self.walk_children():
443 child.window.destroyed.disconnect(self._on_child_close)
444 child.window.closed.disconnect(self._on_child_close)
449 qwrappers.WindowWrapper.destroy(self)
450 if self._session.state != self._session.LOGGEDOUT_STATE:
451 self._session.logout()
453 def get_current_tab(self):
454 return self._currentTab
456 def set_current_tab(self, tabIndex):
457 self._tabWidget.setCurrentIndex(tabIndex)
459 def load_settings(self, config):
460 backendId = 2 # For backwards compatibility
461 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
462 sectionName = "%s - %s" % (backendId, tabTitle)
463 settings = self._tabsContents[tabIndex].get_settings()
464 for settingName in settings.iterkeys():
466 settingValue = config.get(sectionName, settingName)
467 except ConfigParser.NoOptionError, e:
469 "Settings file %s is missing section %s" % (
470 constants._user_settings_,
475 except ConfigParser.NoSectionError, e:
477 "Settings file %s is missing section %s" % (
478 constants._user_settings_,
484 _moduleLogger.exception("Unknown loading error")
486 settings[settingName] = settingValue
487 self._tabsContents[tabIndex].set_settings(settings)
489 def save_settings(self, config):
490 backendId = 2 # For backwards compatibility
491 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
492 sectionName = "%s - %s" % (backendId, tabTitle)
493 config.add_section(sectionName)
494 tabSettings = self._tabsContents[tabIndex].get_settings()
495 for settingName, settingValue in tabSettings.iteritems():
496 config.set(sectionName, settingName, settingValue)
498 def set_orientation(self, isPortrait):
499 qwrappers.WindowWrapper.set_orientation(self, isPortrait)
501 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
503 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
505 def _initialize_tab(self, index):
506 assert index < self.MAX_TABS, "Invalid tab"
507 if not self._tabsContents[index].has_child():
508 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
509 self._tabsContents[index].set_child(tab)
510 self._tabsContents[index].refresh(force=False)
512 def _prompt_for_login(self):
513 if self._credentialsDialog is None:
515 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
516 credentials = self._credentialsDialog.run(
517 self._defaultCredentials[0], self._defaultCredentials[1], self.window
519 if credentials is None:
521 username, password = credentials
522 self._curentCredentials = username, password
523 self._session.login(username, password)
525 def _show_account_dialog(self):
526 if self._accountDialog is None:
528 self._accountDialog = dialogs.AccountDialog(self._app)
529 self._accountDialog.setIfNotificationsSupported(self._app.alarmHandler.backgroundNotificationsSupported)
530 self._accountDialog.notifications = self._app.alarmHandler.alarmType
531 self._accountDialog.notificationTime = self._app.alarmHandler.recurrence
532 self._accountDialog.notifyOnMissed = self._app.notifyOnMissed
533 self._accountDialog.notifyOnVoicemail = self._app.notifyOnVoicemail
534 self._accountDialog.notifyOnSms = self._app.notifyOnSms
535 self._accountDialog.set_callbacks(
536 self._session.get_callback_numbers(), self._session.get_callback_number()
538 accountNumberToDisplay = self._session.get_account_number()
539 if not accountNumberToDisplay:
540 accountNumberToDisplay = "Not Available (%s)" % self._session.state
541 self._accountDialog.set_account_number(accountNumberToDisplay)
542 response = self._accountDialog.run(self.window)
543 if response == QtGui.QDialog.Accepted:
544 if self._accountDialog.doClear:
545 self._session.logout_and_clear()
546 self._defaultCredentials = "", ""
547 self._curentCredentials = "", ""
548 for tab in self._tabsContents:
551 callbackNumber = self._accountDialog.selectedCallback
552 self._session.set_callback_number(callbackNumber)
555 self._accountDialog.notifyOnMissed or
556 self._accountDialog.notifyOnVoicemail or
557 self._accountDialog.notifyOnSms
559 notifications = self._accountDialog.notifications
561 notifications = self._accountDialog.ALARM_NONE
562 self._app.alarmHandler.apply_settings(notifications, self._accountDialog.notificationTime)
564 self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
565 self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
566 self._app.notifyOnSms = self._accountDialog.notifyOnSms
567 self._app.save_settings()
568 elif response == QtGui.QDialog.Rejected:
569 _moduleLogger.info("Cancelled")
571 _moduleLogger.info("Unknown response")
574 @misc_utils.log_exception(_moduleLogger)
575 def _on_new_message_alert(self):
576 with qui_utils.notify_error(self._errorLog):
577 if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
578 if self._currentTab == self.MESSAGES_TAB or not self._app.ledHandler.isReal:
579 self._errorLog.push_message("New messages available")
581 self._app.ledHandler.on()
583 @QtCore.pyqtSlot(str)
584 @misc_utils.log_exception(_moduleLogger)
585 def _on_session_error(self, message):
586 with qui_utils.notify_error(self._errorLog):
587 self._errorLog.push_error(message)
590 @misc_utils.log_exception(_moduleLogger)
592 with qui_utils.notify_error(self._errorLog):
593 changedAccounts = self._defaultCredentials != self._curentCredentials
594 noCallback = not self._session.get_callback_number()
595 if changedAccounts or noCallback:
596 self._show_account_dialog()
598 self._defaultCredentials = self._curentCredentials
600 for tab in self._tabsContents:
602 self._initialize_tab(self._currentTab)
605 @misc_utils.log_exception(_moduleLogger)
606 def _on_logout(self):
607 with qui_utils.notify_error(self._errorLog):
608 for tab in self._tabsContents:
612 @misc_utils.log_exception(_moduleLogger)
613 def _on_app_alert(self):
614 with qui_utils.notify_error(self._errorLog):
615 if self._session.state == self._session.LOGGEDIN_STATE:
617 (True, True): self._session.MESSAGE_ALL,
618 (True, False): self._session.MESSAGE_TEXTS,
619 (False, True): self._session.MESSAGE_VOICEMAILS,
620 }[(self._app.notifyOnSms, self._app.notifyOnVoicemail)]
621 self._session.update_messages(messageType, force=True)
624 @misc_utils.log_exception(_moduleLogger)
625 def _on_recipients_changed(self):
626 with qui_utils.notify_error(self._errorLog):
627 if self._session.draft.get_num_contacts() == 0:
630 if self._smsEntryDialog is None:
632 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
633 self._smsEntryDialog.window.destroyed.connect(self._on_child_close)
634 self._smsEntryDialog.window.closed.connect(self._on_child_close)
635 self._smsEntryDialog.window.show()
637 @misc_utils.log_exception(_moduleLogger)
638 def _on_child_close(self, obj = None):
639 self._smsEntryDialog = None
642 @QtCore.pyqtSlot(bool)
643 @misc_utils.log_exception(_moduleLogger)
644 def _on_login_requested(self, checked = True):
645 with qui_utils.notify_error(self._errorLog):
646 self._prompt_for_login()
648 @QtCore.pyqtSlot(int)
649 @misc_utils.log_exception(_moduleLogger)
650 def _on_tab_changed(self, index):
651 with qui_utils.notify_error(self._errorLog):
652 self._currentTab = index
653 self._initialize_tab(index)
654 if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
655 self._app.ledHandler.off()
658 @QtCore.pyqtSlot(bool)
659 @misc_utils.log_exception(_moduleLogger)
660 def _on_refresh(self, checked = True):
661 with qui_utils.notify_error(self._errorLog):
662 self._tabsContents[self._currentTab].refresh(force=True)
665 @QtCore.pyqtSlot(bool)
666 @misc_utils.log_exception(_moduleLogger)
667 def _on_refresh_connection(self, checked = True):
668 with qui_utils.notify_error(self._errorLog):
669 self._session.refresh_connection()
672 @QtCore.pyqtSlot(bool)
673 @misc_utils.log_exception(_moduleLogger)
674 def _on_import(self, checked = True):
675 with qui_utils.notify_error(self._errorLog):
676 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
677 csvName = unicode(csvName)
681 shutil.copy2(csvName, self._app.fsContactsPath)
682 if self._tabsContents[self.CONTACTS_TAB].has_child:
683 self._tabsContents[self.CONTACTS_TAB].child.update_addressbooks()
686 @QtCore.pyqtSlot(bool)
687 @misc_utils.log_exception(_moduleLogger)
688 def _on_account(self, checked = True):
689 with qui_utils.notify_error(self._errorLog):
690 assert self._session.state == self._session.LOGGEDIN_STATE, "Must be logged in for settings"
691 self._show_account_dialog()
696 os.makedirs(constants._data_path_)
701 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
702 logging.basicConfig(level=logging.DEBUG, format=logFormat)
703 rotating = logging.handlers.RotatingFileHandler(constants._user_logpath_, maxBytes=512*1024, backupCount=1)
704 rotating.setFormatter(logging.Formatter(logFormat))
705 root = logging.getLogger()
706 root.addHandler(rotating)
707 _moduleLogger.info("%s %s-%s" % (constants.__app_name__, constants.__version__, constants.__build__))
708 _moduleLogger.info("OS: %s" % (os.uname()[0], ))
709 _moduleLogger.info("Kernel: %s (%s) for %s" % os.uname()[2:])
710 _moduleLogger.info("Hostname: %s" % os.uname()[1])
712 app = QtGui.QApplication([])
713 handle = Dialcentral(app)
718 if __name__ == "__main__":