4 from __future__ import with_statement
12 from PyQt4 import QtGui
13 from PyQt4 import QtCore
16 from util import qtpie
17 from util import qui_utils
18 from util import misc as misc_utils
23 _moduleLogger = logging.getLogger(__name__)
26 class Dialcentral(object):
29 os.path.join(os.path.dirname(__file__), "../share"),
30 os.path.join(os.path.dirname(__file__), "../data"),
33 def __init__(self, app):
36 self._hiddenCategories = set()
37 self._hiddenUnits = {}
38 self._clipboard = QtGui.QApplication.clipboard()
40 self.notifyOnMissed = False
41 self.notifyOnVoicemail = False
42 self.notifyOnSms = False
44 self._mainWindow = None
46 self._fullscreenAction = QtGui.QAction(None)
47 self._fullscreenAction.setText("Fullscreen")
48 self._fullscreenAction.setCheckable(True)
49 self._fullscreenAction.setShortcut(QtGui.QKeySequence("CTRL+Enter"))
50 self._fullscreenAction.toggled.connect(self._on_toggle_fullscreen)
52 self._logAction = QtGui.QAction(None)
53 self._logAction.setText("Log")
54 self._logAction.setShortcut(QtGui.QKeySequence("CTRL+l"))
55 self._logAction.triggered.connect(self._on_log)
57 self._quitAction = QtGui.QAction(None)
58 self._quitAction.setText("Quit")
59 self._quitAction.setShortcut(QtGui.QKeySequence("CTRL+q"))
60 self._quitAction.triggered.connect(self._on_quit)
62 self._app.lastWindowClosed.connect(self._on_app_quit)
63 self._mainWindow = MainWindow(None, self)
64 self._mainWindow.window.destroyed.connect(self._on_child_close)
68 if alarm_handler.AlarmHandler is not alarm_handler._NoneAlarmHandler:
69 self._alarmHandler = alarm_handler.AlarmHandler()
71 self._alarmHandler = None
72 except (ImportError, OSError):
73 self._alarmHandler = None
75 _moduleLogger.exception("Notification failure")
76 self._alarmHandler = None
77 if self._alarmHandler is None:
78 _moduleLogger.info("No notification support")
82 self._mainWindow.show()
83 self._idleDelay = QtCore.QTimer()
84 self._idleDelay.setSingleShot(True)
85 self._idleDelay.setInterval(0)
86 self._idleDelay.timeout.connect(lambda: self._mainWindow.start())
87 self._idleDelay.start()
89 def load_settings(self):
91 config = ConfigParser.SafeConfigParser()
92 config.read(constants._user_settings_)
94 _moduleLogger.info("No settings")
97 _moduleLogger.info("Settings were corrupt")
99 except ConfigParser.MissingSectionHeaderError:
100 _moduleLogger.info("Settings were corrupt")
103 _moduleLogger.exception("Unknown loading error")
110 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
111 for i in xrange(len(self._mainWindow.get_default_credentials()))
113 isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
114 tabIndex = config.getint(constants.__pretty_app_name__, "tab")
115 except ConfigParser.NoOptionError, e:
117 "Settings file %s is missing option %s" % (
118 constants._user_settings_,
122 except ConfigParser.NoSectionError, e:
124 "Settings file %s is missing section %s" % (
125 constants._user_settings_,
130 _moduleLogger.exception("Unknown loading error")
132 if self._alarmHandler is not None:
134 self._alarmHandler.load_settings(config, "alarm")
135 self.notifyOnMissed = config.getboolean("2 - Account Info", "notifyOnMissed")
136 self.notifyOnVoicemail = config.getboolean("2 - Account Info", "notifyOnVoicemail")
137 self.notifyOnSms = config.getboolean("2 - Account Info", "notifyOnSms")
138 except ConfigParser.NoOptionError, e:
140 "Settings file %s is missing option %s" % (
141 constants._user_settings_,
145 except ConfigParser.NoSectionError, e:
147 "Settings file %s is missing section %s" % (
148 constants._user_settings_,
153 _moduleLogger.exception("Unknown loading error")
156 base64.b64decode(blob)
159 self._mainWindow.set_default_credentials(*creds)
160 self._fullscreenAction.setChecked(isFullscreen)
161 self._mainWindow.set_current_tab(tabIndex)
162 self._mainWindow.load_settings(config)
164 def save_settings(self):
165 _moduleLogger.info("Saving settings")
166 config = ConfigParser.SafeConfigParser()
168 config.add_section(constants.__pretty_app_name__)
169 config.set(constants.__pretty_app_name__, "tab", str(self._mainWindow.get_current_tab()))
170 config.set(constants.__pretty_app_name__, "fullscreen", str(self._fullscreenAction.isChecked()))
171 for i, value in enumerate(self._mainWindow.get_default_credentials()):
172 blob = base64.b64encode(value)
173 config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
175 if self._alarmHandler is not None:
176 config.add_section("alarm")
177 self._alarmHandler.save_settings(config, "alarm")
178 config.add_section("2 - Account Info")
179 config.set("2 - Account Info", "notifyOnMissed", repr(self.notifyOnMissed))
180 config.set("2 - Account Info", "notifyOnVoicemail", repr(self.notifyOnVoicemail))
181 config.set("2 - Account Info", "notifyOnSms", repr(self.notifyOnSms))
183 self._mainWindow.save_settings(config)
185 with open(constants._user_settings_, "wb") as configFile:
186 config.write(configFile)
188 def get_icon(self, name):
189 if self._dataPath is None:
190 for path in self._DATA_PATHS:
191 if os.path.exists(os.path.join(path, name)):
192 self._dataPath = path
194 if self._dataPath is not None:
195 icon = QtGui.QIcon(os.path.join(self._dataPath, name))
201 def fsContactsPath(self):
202 return os.path.join(constants._data_path_, "contacts")
205 def fullscreenAction(self):
206 return self._fullscreenAction
210 return self._logAction
213 def quitAction(self):
214 return self._quitAction
217 def alarmHandler(self):
218 return self._alarmHandler
220 def _walk_children(self):
221 if self._mainWindow is not None:
222 return (self._mainWindow, )
226 def _close_windows(self):
227 if self._mainWindow is not None:
229 self._mainWindow.window.destroyed.disconnect(self._on_child_close)
230 self._mainWindow.close()
231 self._mainWindow = None
234 @QtCore.pyqtSlot(bool)
235 @misc_utils.log_exception(_moduleLogger)
236 def _on_app_quit(self, checked = False):
237 if self._mainWindow is not None:
239 self._mainWindow.destroy()
241 @QtCore.pyqtSlot(QtCore.QObject)
242 @misc_utils.log_exception(_moduleLogger)
243 def _on_child_close(self, obj = None):
244 if self._mainWindow is not None:
246 self._mainWindow = None
249 @QtCore.pyqtSlot(bool)
250 @misc_utils.log_exception(_moduleLogger)
251 def _on_toggle_fullscreen(self, checked = False):
252 for window in self._walk_children():
253 window.set_fullscreen(checked)
256 @QtCore.pyqtSlot(bool)
257 @misc_utils.log_exception(_moduleLogger)
258 def _on_log(self, checked = False):
259 with open(constants._user_logpath_, "r") as f:
260 logLines = f.xreadlines()
261 log = "".join(logLines)
262 self._clipboard.setText(log)
265 @QtCore.pyqtSlot(bool)
266 @misc_utils.log_exception(_moduleLogger)
267 def _on_quit(self, checked = False):
268 self._close_windows()
271 class DelayedWidget(object):
273 def __init__(self, app, settingsNames):
274 self._layout = QtGui.QVBoxLayout()
275 self._layout.setContentsMargins(0, 0, 0, 0)
276 self._widget = QtGui.QWidget()
277 self._widget.setContentsMargins(0, 0, 0, 0)
278 self._widget.setLayout(self._layout)
279 self._settings = dict((name, "") for name in settingsNames)
282 self._isEnabled = True
289 return self._child is not None
291 def set_child(self, child):
292 if self._child is not None:
293 self._layout.removeWidget(self._child.toplevel)
295 if self._child is not None:
296 self._layout.addWidget(self._child.toplevel)
298 self._child.set_settings(self._settings)
303 self._child.disable()
306 self._isEnabled = True
307 if self._child is not None:
311 self._isEnabled = False
312 if self._child is not None:
313 self._child.disable()
316 if self._child is not None:
319 def refresh(self, force=True):
320 if self._child is not None:
321 self._child.refresh(force)
323 def get_settings(self):
324 if self._child is not None:
325 return self._child.get_settings()
327 return self._settings
329 def set_settings(self, settings):
330 if self._child is not None:
331 self._child.set_settings(settings)
333 self._settings = settings
336 def _tab_factory(tab, app, session, errorLog):
338 return gv_views.__dict__[tab](app, session, errorLog)
341 class MainWindow(object):
355 assert len(_TAB_TITLES) == MAX_TABS
363 assert len(_TAB_ICONS) == MAX_TABS
366 functools.partial(_tab_factory, "Dialpad"),
367 functools.partial(_tab_factory, "History"),
368 functools.partial(_tab_factory, "Messages"),
369 functools.partial(_tab_factory, "Contacts"),
371 assert len(_TAB_CLASS) == MAX_TABS
373 # Hack to allow delay importing/loading of tabs
374 _TAB_SETTINGS_NAMES = [
378 ("selectedAddressbook", ),
380 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
382 def __init__(self, parent, app):
385 self._errorLog = qui_utils.QErrorLog()
386 self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
388 self._session = session.Session(self._errorLog, constants._data_path_)
389 self._session.error.connect(self._on_session_error)
390 self._session.loggedIn.connect(self._on_login)
391 self._session.loggedOut.connect(self._on_logout)
392 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
393 self._defaultCredentials = "", ""
394 self._curentCredentials = "", ""
397 self._credentialsDialog = None
398 self._smsEntryDialog = None
399 self._accountDialog = None
400 self._aboutDialog = None
402 self._tabsContents = [
403 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
404 for i in xrange(self.MAX_TABS)
406 for tab in self._tabsContents:
409 self._tabWidget = QtGui.QTabWidget()
410 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
411 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
413 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
414 defaultTabIconSize = self._tabWidget.iconSize()
415 defaultTabIconWidth, defaultTabIconHeight = defaultTabIconSize.width(), defaultTabIconSize.height()
416 for tabIndex, (tabTitle, tabIcon) in enumerate(
417 zip(self._TAB_TITLES, self._TAB_ICONS)
419 icon = self._app.get_icon(tabIcon)
420 if constants.IS_MAEMO and icon is not None:
424 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
426 iconSize = icon.availableSizes()[0]
427 defaultTabIconWidth = max(defaultTabIconWidth, iconSize.width())
428 defaultTabIconHeight = max(defaultTabIconHeight, iconSize.height())
429 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
430 defaultTabIconWidth = max(defaultTabIconWidth, 32)
431 defaultTabIconHeight = max(defaultTabIconHeight, 32)
432 self._tabWidget.setIconSize(QtCore.QSize(defaultTabIconWidth, defaultTabIconHeight))
433 self._tabWidget.currentChanged.connect(self._on_tab_changed)
434 self._tabWidget.setContentsMargins(0, 0, 0, 0)
436 self._layout = QtGui.QVBoxLayout()
437 self._layout.setContentsMargins(0, 0, 0, 0)
438 self._layout.addWidget(self._errorDisplay.toplevel)
439 self._layout.addWidget(self._tabWidget)
441 centralWidget = QtGui.QWidget()
442 centralWidget.setLayout(self._layout)
443 centralWidget.setContentsMargins(0, 0, 0, 0)
445 self._window = QtGui.QMainWindow(parent)
446 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
447 qui_utils.set_autorient(self._window, True)
448 qui_utils.set_stackable(self._window, True)
449 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
450 self._window.setCentralWidget(centralWidget)
452 self._loginTabAction = QtGui.QAction(None)
453 self._loginTabAction.setText("Login")
454 self._loginTabAction.triggered.connect(self._on_login_requested)
456 self._importTabAction = QtGui.QAction(None)
457 self._importTabAction.setText("Import")
458 self._importTabAction.triggered.connect(self._on_import)
460 self._accountTabAction = QtGui.QAction(None)
461 self._accountTabAction.setText("Account")
462 self._accountTabAction.triggered.connect(self._on_account)
464 self._refreshTabAction = QtGui.QAction(None)
465 self._refreshTabAction.setText("Refresh")
466 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
467 self._refreshTabAction.triggered.connect(self._on_refresh)
469 self._aboutAction = QtGui.QAction(None)
470 self._aboutAction.setText("About")
471 self._aboutAction.triggered.connect(self._on_about)
473 self._closeWindowAction = QtGui.QAction(None)
474 self._closeWindowAction.setText("Close")
475 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
476 self._closeWindowAction.triggered.connect(self._on_close_window)
478 if constants.IS_MAEMO:
479 fileMenu = self._window.menuBar().addMenu("&File")
480 fileMenu.addAction(self._loginTabAction)
481 fileMenu.addAction(self._refreshTabAction)
483 toolsMenu = self._window.menuBar().addMenu("&Tools")
484 toolsMenu.addAction(self._accountTabAction)
485 toolsMenu.addAction(self._importTabAction)
486 toolsMenu.addAction(self._aboutAction)
488 self._window.addAction(self._closeWindowAction)
489 self._window.addAction(self._app.quitAction)
490 self._window.addAction(self._app.fullscreenAction)
492 fileMenu = self._window.menuBar().addMenu("&File")
493 fileMenu.addAction(self._loginTabAction)
494 fileMenu.addAction(self._refreshTabAction)
495 fileMenu.addAction(self._closeWindowAction)
496 fileMenu.addAction(self._app.quitAction)
498 viewMenu = self._window.menuBar().addMenu("&View")
499 viewMenu.addAction(self._app.fullscreenAction)
501 toolsMenu = self._window.menuBar().addMenu("&Tools")
502 toolsMenu.addAction(self._accountTabAction)
503 toolsMenu.addAction(self._importTabAction)
504 toolsMenu.addAction(self._aboutAction)
506 self._window.addAction(self._app.logAction)
508 self._initialize_tab(self._tabWidget.currentIndex())
509 self.set_fullscreen(self._app.fullscreenAction.isChecked())
515 def set_default_credentials(self, username, password):
516 self._defaultCredentials = username, password
518 def get_default_credentials(self):
519 return self._defaultCredentials
521 def walk_children(self):
525 assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
526 if self._defaultCredentials != ("", ""):
527 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
528 self._curentCredentials = username, password
529 self._session.login(username, password)
531 self._prompt_for_login()
534 for child in self.walk_children():
535 child.window.destroyed.disconnect(self._on_child_close)
538 self._credentialsDialog,
539 self._smsEntryDialog,
548 if self._session.state != self._session.LOGGEDOUT_STATE:
549 self._session.logout()
551 def get_current_tab(self):
552 return self._currentTab
554 def set_current_tab(self, tabIndex):
555 self._tabWidget.setCurrentIndex(tabIndex)
557 def load_settings(self, config):
558 backendId = 2 # For backwards compatibility
559 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
560 sectionName = "%s - %s" % (backendId, tabTitle)
561 settings = self._tabsContents[tabIndex].get_settings()
562 for settingName in settings.iterkeys():
564 settingValue = config.get(sectionName, settingName)
565 except ConfigParser.NoOptionError, e:
567 "Settings file %s is missing section %s" % (
568 constants._user_settings_,
573 except ConfigParser.NoSectionError, e:
575 "Settings file %s is missing section %s" % (
576 constants._user_settings_,
582 _moduleLogger.exception("Unknown loading error")
584 settings[settingName] = settingValue
585 self._tabsContents[tabIndex].set_settings(settings)
587 def save_settings(self, config):
588 backendId = 2 # For backwards compatibility
589 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
590 sectionName = "%s - %s" % (backendId, tabTitle)
591 config.add_section(sectionName)
592 tabSettings = self._tabsContents[tabIndex].get_settings()
593 for settingName, settingValue in tabSettings.iteritems():
594 config.set(sectionName, settingName, settingValue)
598 for child in self.walk_children():
602 for child in self.walk_children():
606 def set_fullscreen(self, isFullscreen):
608 self._window.showFullScreen()
610 self._window.showNormal()
611 for child in self.walk_children():
612 child.set_fullscreen(isFullscreen)
614 def _initialize_tab(self, index):
615 assert index < self.MAX_TABS, "Invalid tab"
616 if not self._tabsContents[index].has_child():
617 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
618 self._tabsContents[index].set_child(tab)
619 self._tabsContents[index].refresh(force=False)
621 def _prompt_for_login(self):
622 if self._credentialsDialog is None:
624 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
625 username, password = self._credentialsDialog.run(
626 self._defaultCredentials[0], self._defaultCredentials[1], self.window
628 self._curentCredentials = username, password
629 self._session.login(username, password)
631 def _show_account_dialog(self):
632 if self._accountDialog is None:
634 self._accountDialog = dialogs.AccountDialog(self._app)
635 if self._app.alarmHandler is None:
636 self._accountDialog.setIfNotificationsSupported(False)
637 if self._app.alarmHandler is not None:
638 self._accountDialog.notifications = self._app.alarmHandler.isEnabled
639 self._accountDialog.notificationTime = self._app.alarmHandler.recurrence
640 self._accountDialog.notifyOnMissed = self._app.notifyOnMissed
641 self._accountDialog.notifyOnVoicemail = self._app.notifyOnVoicemail
642 self._accountDialog.notifyOnSms = self._app.notifyOnSms
643 self._accountDialog.set_callbacks(
644 self._session.get_callback_numbers(), self._session.get_callback_number()
646 self._accountDialog.accountNumber = self._session.get_account_number()
647 response = self._accountDialog.run()
648 if response == QtGui.QDialog.Accepted:
649 if self._accountDialog.doClear:
650 self._session.logout_and_clear()
652 callbackNumber = self._accountDialog.selectedCallback
653 self._session.set_callback_number(callbackNumber)
654 if self._app.alarmHandler is not None:
655 self._app.alarmHandler.apply_settings(self._accountDialog.notifications, self._accountDialog.notificationTime)
656 self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
657 self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
658 self._app.notifyOnSms = self._accountDialog.notifyOnSms
659 elif response == QtGui.QDialog.Rejected:
660 _moduleLogger.info("Cancelled")
662 _moduleLogger.info("Unknown response")
664 @QtCore.pyqtSlot(str)
665 @misc_utils.log_exception(_moduleLogger)
666 def _on_session_error(self, message):
667 with qui_utils.notify_error(self._errorLog):
668 self._errorLog.push_error(message)
671 @misc_utils.log_exception(_moduleLogger)
673 with qui_utils.notify_error(self._errorLog):
674 changedAccounts = self._defaultCredentials != self._curentCredentials
675 noCallback = not self._session.get_callback_number()
676 if changedAccounts or noCallback:
677 self._show_account_dialog()
679 self._defaultCredentials = self._curentCredentials
681 for tab in self._tabsContents:
685 @misc_utils.log_exception(_moduleLogger)
686 def _on_logout(self):
687 with qui_utils.notify_error(self._errorLog):
688 for tab in self._tabsContents:
692 @misc_utils.log_exception(_moduleLogger)
693 def _on_recipients_changed(self):
694 with qui_utils.notify_error(self._errorLog):
695 if self._session.draft.get_num_contacts() == 0:
698 if self._smsEntryDialog is None:
700 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
703 @QtCore.pyqtSlot(bool)
704 @misc_utils.log_exception(_moduleLogger)
705 def _on_login_requested(self, checked = True):
706 with qui_utils.notify_error(self._errorLog):
707 self._prompt_for_login()
709 @QtCore.pyqtSlot(int)
710 @misc_utils.log_exception(_moduleLogger)
711 def _on_tab_changed(self, index):
712 with qui_utils.notify_error(self._errorLog):
713 self._currentTab = index
714 self._initialize_tab(index)
717 @QtCore.pyqtSlot(bool)
718 @misc_utils.log_exception(_moduleLogger)
719 def _on_refresh(self, checked = True):
720 with qui_utils.notify_error(self._errorLog):
721 self._tabsContents[self._currentTab].refresh(force=True)
724 @QtCore.pyqtSlot(bool)
725 @misc_utils.log_exception(_moduleLogger)
726 def _on_import(self, checked = True):
727 with qui_utils.notify_error(self._errorLog):
728 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
732 shutil.copy2(csvName, self._app.fsContactsPath)
733 self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
736 @QtCore.pyqtSlot(bool)
737 @misc_utils.log_exception(_moduleLogger)
738 def _on_account(self, checked = True):
739 with qui_utils.notify_error(self._errorLog):
740 self._show_account_dialog()
743 @QtCore.pyqtSlot(bool)
744 @misc_utils.log_exception(_moduleLogger)
745 def _on_about(self, checked = True):
746 with qui_utils.notify_error(self._errorLog):
747 if self._aboutDialog is None:
749 self._aboutDialog = dialogs.AboutDialog(self._app)
750 response = self._aboutDialog.run()
753 @QtCore.pyqtSlot(bool)
754 @misc_utils.log_exception(_moduleLogger)
755 def _on_close_window(self, checked = True):
760 app = QtGui.QApplication([])
761 handle = Dialcentral(app)
766 if __name__ == "__main__":
769 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
770 logging.basicConfig(level=logging.DEBUG, format=logFormat)
772 os.makedirs(constants._data_path_)