4 from __future__ import with_statement
12 from PyQt4 import QtGui
13 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 = led_handler.LedHandler()
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 return self._ledHandler
189 def _new_main_window(self):
190 return MainWindow(None, self)
193 @QtCore.pyqtSlot(bool)
194 @misc_utils.log_exception(_moduleLogger)
195 def _on_about(self, checked = True):
196 with qui_utils.notify_error(self._errorLog):
197 if self._aboutDialog is None:
199 self._aboutDialog = dialogs.AboutDialog(self)
200 response = self._aboutDialog.run(self._mainWindow.window)
203 class DelayedWidget(object):
205 def __init__(self, app, settingsNames):
206 self._layout = QtGui.QVBoxLayout()
207 self._layout.setContentsMargins(0, 0, 0, 0)
208 self._widget = QtGui.QWidget()
209 self._widget.setContentsMargins(0, 0, 0, 0)
210 self._widget.setLayout(self._layout)
211 self._settings = dict((name, "") for name in settingsNames)
214 self._isEnabled = True
221 return self._child is not None
223 def set_child(self, child):
224 if self._child is not None:
225 self._layout.removeWidget(self._child.toplevel)
227 if self._child is not None:
228 self._layout.addWidget(self._child.toplevel)
230 self._child.set_settings(self._settings)
235 self._child.disable()
242 self._isEnabled = True
243 if self._child is not None:
247 self._isEnabled = False
248 if self._child is not None:
249 self._child.disable()
252 if self._child is not None:
255 def refresh(self, force=True):
256 if self._child is not None:
257 self._child.refresh(force)
259 def get_settings(self):
260 if self._child is not None:
261 return self._child.get_settings()
263 return self._settings
265 def set_settings(self, settings):
266 if self._child is not None:
267 self._child.set_settings(settings)
269 self._settings = settings
272 def _tab_factory(tab, app, session, errorLog):
274 return gv_views.__dict__[tab](app, session, errorLog)
277 class MainWindow(qwrappers.WindowWrapper):
291 assert len(_TAB_TITLES) == MAX_TABS
299 assert len(_TAB_ICONS) == MAX_TABS
302 functools.partial(_tab_factory, "Dialpad"),
303 functools.partial(_tab_factory, "History"),
304 functools.partial(_tab_factory, "Messages"),
305 functools.partial(_tab_factory, "Contacts"),
307 assert len(_TAB_CLASS) == MAX_TABS
309 # Hack to allow delay importing/loading of tabs
310 _TAB_SETTINGS_NAMES = [
314 ("selectedAddressbook", ),
316 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
318 def __init__(self, parent, app):
319 qwrappers.WindowWrapper.__init__(self, parent, app)
320 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
321 self._errorLog = self._app.errorLog
323 self._session = session.Session(self._errorLog, constants._data_path_)
324 self._session.error.connect(self._on_session_error)
325 self._session.loggedIn.connect(self._on_login)
326 self._session.loggedOut.connect(self._on_logout)
327 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
328 self._session.newMessages.connect(self._on_new_message_alert)
329 self._app.alarmHandler.applicationNotifySignal.connect(self._on_app_alert)
330 self._defaultCredentials = "", ""
331 self._curentCredentials = "", ""
334 self._credentialsDialog = None
335 self._smsEntryDialog = None
336 self._accountDialog = None
338 self._tabsContents = [
339 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
340 for i in xrange(self.MAX_TABS)
342 for tab in self._tabsContents:
345 self._tabWidget = QtGui.QTabWidget()
346 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
347 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
349 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
350 defaultTabIconSize = self._tabWidget.iconSize()
351 defaultTabIconWidth, defaultTabIconHeight = defaultTabIconSize.width(), defaultTabIconSize.height()
352 for tabIndex, (tabTitle, tabIcon) in enumerate(
353 zip(self._TAB_TITLES, self._TAB_ICONS)
355 icon = self._app.get_icon(tabIcon)
356 if constants.IS_MAEMO and icon is not None:
360 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
362 iconSize = icon.availableSizes()[0]
363 defaultTabIconWidth = max(defaultTabIconWidth, iconSize.width())
364 defaultTabIconHeight = max(defaultTabIconHeight, iconSize.height())
365 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
366 defaultTabIconWidth = max(defaultTabIconWidth, 32)
367 defaultTabIconHeight = max(defaultTabIconHeight, 32)
368 self._tabWidget.setIconSize(QtCore.QSize(defaultTabIconWidth, defaultTabIconHeight))
369 self._tabWidget.currentChanged.connect(self._on_tab_changed)
370 self._tabWidget.setContentsMargins(0, 0, 0, 0)
372 self._layout.addWidget(self._tabWidget)
374 self._loginTabAction = QtGui.QAction(None)
375 self._loginTabAction.setText("Login")
376 self._loginTabAction.triggered.connect(self._on_login_requested)
378 self._importTabAction = QtGui.QAction(None)
379 self._importTabAction.setText("Import")
380 self._importTabAction.triggered.connect(self._on_import)
382 self._accountTabAction = QtGui.QAction(None)
383 self._accountTabAction.setText("Account")
384 self._accountTabAction.triggered.connect(self._on_account)
386 self._refreshTabAction = QtGui.QAction(None)
387 self._refreshTabAction.setText("Refresh")
388 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
389 self._refreshTabAction.triggered.connect(self._on_refresh)
391 fileMenu = self._window.menuBar().addMenu("&File")
392 fileMenu.addAction(self._loginTabAction)
393 fileMenu.addAction(self._refreshTabAction)
395 toolsMenu = self._window.menuBar().addMenu("&Tools")
396 toolsMenu.addAction(self._accountTabAction)
397 toolsMenu.addAction(self._importTabAction)
398 toolsMenu.addAction(self._app.aboutAction)
400 self._initialize_tab(self._tabWidget.currentIndex())
401 self.set_fullscreen(self._app.fullscreenAction.isChecked())
402 self.set_orientation(self._app.orientationAction.isChecked())
404 def set_default_credentials(self, username, password):
405 self._defaultCredentials = username, password
407 def get_default_credentials(self):
408 return self._defaultCredentials
410 def walk_children(self):
411 if self._smsEntryDialog is not None:
412 return (self._smsEntryDialog, )
417 qwrappers.WindowWrapper.start(self)
418 assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
419 if self._defaultCredentials != ("", ""):
420 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
421 self._curentCredentials = username, password
422 self._session.login(username, password)
424 self._prompt_for_login()
428 self._credentialsDialog,
433 for child in self.walk_children():
434 child.window.destroyed.disconnect(self._on_child_close)
435 child.window.closed.disconnect(self._on_child_close)
440 qwrappers.WindowWrapper.destroy(self)
441 if self._session.state != self._session.LOGGEDOUT_STATE:
442 self._session.logout()
444 def get_current_tab(self):
445 return self._currentTab
447 def set_current_tab(self, tabIndex):
448 self._tabWidget.setCurrentIndex(tabIndex)
450 def load_settings(self, config):
451 backendId = 2 # For backwards compatibility
452 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
453 sectionName = "%s - %s" % (backendId, tabTitle)
454 settings = self._tabsContents[tabIndex].get_settings()
455 for settingName in settings.iterkeys():
457 settingValue = config.get(sectionName, settingName)
458 except ConfigParser.NoOptionError, e:
460 "Settings file %s is missing section %s" % (
461 constants._user_settings_,
466 except ConfigParser.NoSectionError, e:
468 "Settings file %s is missing section %s" % (
469 constants._user_settings_,
475 _moduleLogger.exception("Unknown loading error")
477 settings[settingName] = settingValue
478 self._tabsContents[tabIndex].set_settings(settings)
480 def save_settings(self, config):
481 backendId = 2 # For backwards compatibility
482 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
483 sectionName = "%s - %s" % (backendId, tabTitle)
484 config.add_section(sectionName)
485 tabSettings = self._tabsContents[tabIndex].get_settings()
486 for settingName, settingValue in tabSettings.iteritems():
487 config.set(sectionName, settingName, settingValue)
489 def set_orientation(self, isPortrait):
490 qwrappers.WindowWrapper.set_orientation(self, isPortrait)
492 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
494 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
496 def _initialize_tab(self, index):
497 assert index < self.MAX_TABS, "Invalid tab"
498 if not self._tabsContents[index].has_child():
499 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
500 self._tabsContents[index].set_child(tab)
501 self._tabsContents[index].refresh(force=False)
503 def _prompt_for_login(self):
504 if self._credentialsDialog is None:
506 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
507 credentials = self._credentialsDialog.run(
508 self._defaultCredentials[0], self._defaultCredentials[1], self.window
510 if credentials is None:
512 username, password = credentials
513 self._curentCredentials = username, password
514 self._session.login(username, password)
516 def _show_account_dialog(self):
517 if self._accountDialog is None:
519 self._accountDialog = dialogs.AccountDialog(self._app)
520 self._accountDialog.setIfNotificationsSupported(self._app.alarmHandler.backgroundNotificationsSupported)
521 self._accountDialog.notifications = self._app.alarmHandler.alarmType
522 self._accountDialog.notificationTime = self._app.alarmHandler.recurrence
523 self._accountDialog.notifyOnMissed = self._app.notifyOnMissed
524 self._accountDialog.notifyOnVoicemail = self._app.notifyOnVoicemail
525 self._accountDialog.notifyOnSms = self._app.notifyOnSms
526 self._accountDialog.set_callbacks(
527 self._session.get_callback_numbers(), self._session.get_callback_number()
529 accountNumberToDisplay = self._session.get_account_number()
530 if not accountNumberToDisplay:
531 accountNumberToDisplay = "Not Available (%s)" % self._session.state
532 self._accountDialog.set_account_number(accountNumberToDisplay)
533 response = self._accountDialog.run(self.window)
534 if response == QtGui.QDialog.Accepted:
535 if self._accountDialog.doClear:
536 self._session.logout_and_clear()
537 self._defaultCredentials = "", ""
538 self._curentCredentials = "", ""
539 for tab in self._tabsContents:
542 callbackNumber = self._accountDialog.selectedCallback
543 self._session.set_callback_number(callbackNumber)
544 self._app.alarmHandler.apply_settings(self._accountDialog.notifications, self._accountDialog.notificationTime)
545 self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
546 self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
547 self._app.notifyOnSms = self._accountDialog.notifyOnSms
548 self._app.save_settings()
549 elif response == QtGui.QDialog.Rejected:
550 _moduleLogger.info("Cancelled")
552 _moduleLogger.info("Unknown response")
555 @misc_utils.log_exception(_moduleLogger)
556 def _on_new_message_alert(self):
557 with qui_utils.notify_error(self._errorLog):
558 if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
559 if self._currentTab == self.MESSAGES_TAB or not self._app.ledHandler.isReal:
560 self._errorLog.push_message("New messages available")
562 self._app.ledHandler.on()
564 @QtCore.pyqtSlot(str)
565 @misc_utils.log_exception(_moduleLogger)
566 def _on_session_error(self, message):
567 with qui_utils.notify_error(self._errorLog):
568 self._errorLog.push_error(message)
571 @misc_utils.log_exception(_moduleLogger)
573 with qui_utils.notify_error(self._errorLog):
574 changedAccounts = self._defaultCredentials != self._curentCredentials
575 noCallback = not self._session.get_callback_number()
576 if changedAccounts or noCallback:
577 self._show_account_dialog()
579 self._defaultCredentials = self._curentCredentials
581 for tab in self._tabsContents:
583 self._initialize_tab(self._currentTab)
586 @misc_utils.log_exception(_moduleLogger)
587 def _on_logout(self):
588 with qui_utils.notify_error(self._errorLog):
589 for tab in self._tabsContents:
593 @misc_utils.log_exception(_moduleLogger)
594 def _on_app_alert(self):
595 with qui_utils.notify_error(self._errorLog):
596 if self._session.state == self._session.LOGGEDIN_STATE:
597 self._session.update_messages(force=True)
600 @misc_utils.log_exception(_moduleLogger)
601 def _on_recipients_changed(self):
602 with qui_utils.notify_error(self._errorLog):
603 if self._session.draft.get_num_contacts() == 0:
606 if self._smsEntryDialog is None:
608 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
609 self._smsEntryDialog.window.destroyed.connect(self._on_child_close)
610 self._smsEntryDialog.window.closed.connect(self._on_child_close)
611 self._smsEntryDialog.window.show()
613 @misc_utils.log_exception(_moduleLogger)
614 def _on_child_close(self, obj = None):
615 self._smsEntryDialog = None
618 @QtCore.pyqtSlot(bool)
619 @misc_utils.log_exception(_moduleLogger)
620 def _on_login_requested(self, checked = True):
621 with qui_utils.notify_error(self._errorLog):
622 self._prompt_for_login()
624 @QtCore.pyqtSlot(int)
625 @misc_utils.log_exception(_moduleLogger)
626 def _on_tab_changed(self, index):
627 with qui_utils.notify_error(self._errorLog):
628 self._currentTab = index
629 self._initialize_tab(index)
630 if self._app.alarmHandler.alarmType == self._app.alarmHandler.ALARM_APPLICATION:
631 self._app.ledHandler.off()
634 @QtCore.pyqtSlot(bool)
635 @misc_utils.log_exception(_moduleLogger)
636 def _on_refresh(self, checked = True):
637 with qui_utils.notify_error(self._errorLog):
638 self._tabsContents[self._currentTab].refresh(force=True)
641 @QtCore.pyqtSlot(bool)
642 @misc_utils.log_exception(_moduleLogger)
643 def _on_import(self, checked = True):
644 with qui_utils.notify_error(self._errorLog):
645 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
646 csvName = unicode(csvName)
650 shutil.copy2(csvName, self._app.fsContactsPath)
651 if self._tabsContents[self.CONTACTS_TAB].has_child:
652 self._tabsContents[self.CONTACTS_TAB].child.update_addressbooks()
655 @QtCore.pyqtSlot(bool)
656 @misc_utils.log_exception(_moduleLogger)
657 def _on_account(self, checked = True):
658 with qui_utils.notify_error(self._errorLog):
659 assert self._session.state == self._session.LOGGEDIN_STATE, "Must be logged in for settings"
660 self._show_account_dialog()
664 app = QtGui.QApplication([])
665 handle = Dialcentral(app)
670 if __name__ == "__main__":
673 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
674 logging.basicConfig(level=logging.DEBUG, format=logFormat)
676 os.makedirs(constants._data_path_)