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()
41 self._mainWindow = None
43 self._fullscreenAction = QtGui.QAction(None)
44 self._fullscreenAction.setText("Fullscreen")
45 self._fullscreenAction.setCheckable(True)
46 self._fullscreenAction.setShortcut(QtGui.QKeySequence("CTRL+Enter"))
47 self._fullscreenAction.toggled.connect(self._on_toggle_fullscreen)
49 self._logAction = QtGui.QAction(None)
50 self._logAction.setText("Log")
51 self._logAction.setShortcut(QtGui.QKeySequence("CTRL+l"))
52 self._logAction.triggered.connect(self._on_log)
54 self._quitAction = QtGui.QAction(None)
55 self._quitAction.setText("Quit")
56 self._quitAction.setShortcut(QtGui.QKeySequence("CTRL+q"))
57 self._quitAction.triggered.connect(self._on_quit)
59 self._app.lastWindowClosed.connect(self._on_app_quit)
60 self._mainWindow = MainWindow(None, self)
61 self._mainWindow.window.destroyed.connect(self._on_child_close)
65 self._mainWindow.show()
66 self._idleDelay = QtCore.QTimer()
67 self._idleDelay.setSingleShot(True)
68 self._idleDelay.setInterval(0)
69 self._idleDelay.timeout.connect(lambda: self._mainWindow.start())
70 self._idleDelay.start()
72 def load_settings(self):
74 config = ConfigParser.SafeConfigParser()
75 config.read(constants._user_settings_)
77 _moduleLogger.info("No settings")
80 _moduleLogger.info("Settings were corrupt")
82 except ConfigParser.MissingSectionHeaderError:
83 _moduleLogger.info("Settings were corrupt")
86 _moduleLogger.exception("Unknown loading error")
93 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
94 for i in xrange(len(self._mainWindow.get_default_credentials()))
96 isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
97 tabIndex = config.getint(constants.__pretty_app_name__, "tab")
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_,
114 _moduleLogger.exception("Unknown loading error")
118 base64.b64decode(blob)
121 self._mainWindow.set_default_credentials(*creds)
122 self._fullscreenAction.setChecked(isFullscreen)
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 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 self._mainWindow.save_settings(config)
139 with open(constants._user_settings_, "wb") as configFile:
140 config.write(configFile)
142 def get_icon(self, name):
143 if self._dataPath is None:
144 for path in self._DATA_PATHS:
145 if os.path.exists(os.path.join(path, name)):
146 self._dataPath = path
148 if self._dataPath is not None:
149 icon = QtGui.QIcon(os.path.join(self._dataPath, name))
155 def fsContactsPath(self):
156 return os.path.join(constants._data_path_, "contacts")
159 def fullscreenAction(self):
160 return self._fullscreenAction
164 return self._logAction
167 def quitAction(self):
168 return self._quitAction
170 def _walk_children(self):
171 if self._mainWindow is not None:
172 return (self._mainWindow, )
176 def _close_windows(self):
177 if self._mainWindow is not None:
179 self._mainWindow.window.destroyed.disconnect(self._on_child_close)
180 self._mainWindow.close()
181 self._mainWindow = None
184 @QtCore.pyqtSlot(bool)
185 @misc_utils.log_exception(_moduleLogger)
186 def _on_app_quit(self, checked = False):
187 if self._mainWindow is not None:
189 self._mainWindow.destroy()
191 @QtCore.pyqtSlot(QtCore.QObject)
192 @misc_utils.log_exception(_moduleLogger)
193 def _on_child_close(self, obj = None):
194 if self._mainWindow is not None:
196 self._mainWindow = None
199 @QtCore.pyqtSlot(bool)
200 @misc_utils.log_exception(_moduleLogger)
201 def _on_toggle_fullscreen(self, checked = False):
202 for window in self._walk_children():
203 window.set_fullscreen(checked)
206 @QtCore.pyqtSlot(bool)
207 @misc_utils.log_exception(_moduleLogger)
208 def _on_log(self, checked = False):
209 with open(constants._user_logpath_, "r") as f:
210 logLines = f.xreadlines()
211 log = "".join(logLines)
212 self._clipboard.setText(log)
215 @QtCore.pyqtSlot(bool)
216 @misc_utils.log_exception(_moduleLogger)
217 def _on_quit(self, checked = False):
218 self._close_windows()
221 class DelayedWidget(object):
223 def __init__(self, app, settingsNames):
224 self._layout = QtGui.QVBoxLayout()
225 self._layout.setContentsMargins(0, 0, 0, 0)
226 self._widget = QtGui.QWidget()
227 self._widget.setContentsMargins(0, 0, 0, 0)
228 self._widget.setLayout(self._layout)
229 self._settings = dict((name, "") for name in settingsNames)
232 self._isEnabled = True
239 return self._child is not None
241 def set_child(self, child):
242 if self._child is not None:
243 self._layout.removeWidget(self._child.toplevel)
245 if self._child is not None:
246 self._layout.addWidget(self._child.toplevel)
248 self._child.set_settings(self._settings)
253 self._child.disable()
256 self._isEnabled = True
257 if self._child is not None:
261 self._isEnabled = False
262 if self._child is not None:
263 self._child.disable()
266 if self._child is not None:
269 def refresh(self, force=True):
270 if self._child is not None:
271 self._child.refresh(force)
273 def get_settings(self):
274 if self._child is not None:
275 return self._child.get_settings()
277 return self._settings
279 def set_settings(self, settings):
280 if self._child is not None:
281 self._child.set_settings(settings)
283 self._settings = settings
286 def _tab_factory(tab, app, session, errorLog):
288 return gv_views.__dict__[tab](app, session, errorLog)
291 class MainWindow(object):
305 assert len(_TAB_TITLES) == MAX_TABS
313 assert len(_TAB_ICONS) == MAX_TABS
316 functools.partial(_tab_factory, "Dialpad"),
317 functools.partial(_tab_factory, "History"),
318 functools.partial(_tab_factory, "Messages"),
319 functools.partial(_tab_factory, "Contacts"),
321 assert len(_TAB_CLASS) == MAX_TABS
323 # Hack to allow delay importing/loading of tabs
324 _TAB_SETTINGS_NAMES = [
328 ("selectedAddressbook", ),
330 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
332 def __init__(self, parent, app):
335 self._errorLog = qui_utils.QErrorLog()
336 self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
338 self._session = session.Session(self._errorLog, constants._data_path_)
339 self._session.error.connect(self._on_session_error)
340 self._session.loggedIn.connect(self._on_login)
341 self._session.loggedOut.connect(self._on_logout)
342 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
343 self._defaultCredentials = "", ""
344 self._curentCredentials = "", ""
347 self._credentialsDialog = None
348 self._smsEntryDialog = None
349 self._accountDialog = None
350 self._aboutDialog = None
352 self._tabsContents = [
353 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
354 for i in xrange(self.MAX_TABS)
356 for tab in self._tabsContents:
359 self._tabWidget = QtGui.QTabWidget()
360 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
361 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
363 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
364 for tabIndex, (tabTitle, tabIcon) in enumerate(
365 zip(self._TAB_TITLES, self._TAB_ICONS)
367 if constants.IS_MAEMO:
368 icon = self._app.get_icon(tabIcon)
370 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
372 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, "")
374 icon = self._app.get_icon(tabIcon)
375 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
376 self._tabWidget.currentChanged.connect(self._on_tab_changed)
377 self._tabWidget.setContentsMargins(0, 0, 0, 0)
379 self._layout = QtGui.QVBoxLayout()
380 self._layout.setContentsMargins(0, 0, 0, 0)
381 self._layout.addWidget(self._errorDisplay.toplevel)
382 self._layout.addWidget(self._tabWidget)
384 centralWidget = QtGui.QWidget()
385 centralWidget.setLayout(self._layout)
386 centralWidget.setContentsMargins(0, 0, 0, 0)
388 self._window = QtGui.QMainWindow(parent)
389 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
390 qui_utils.set_autorient(self._window, True)
391 qui_utils.set_stackable(self._window, True)
392 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
393 self._window.setCentralWidget(centralWidget)
395 self._loginTabAction = QtGui.QAction(None)
396 self._loginTabAction.setText("Login")
397 self._loginTabAction.triggered.connect(self._on_login_requested)
399 self._importTabAction = QtGui.QAction(None)
400 self._importTabAction.setText("Import")
401 self._importTabAction.triggered.connect(self._on_import)
403 self._accountTabAction = QtGui.QAction(None)
404 self._accountTabAction.setText("Account")
405 self._accountTabAction.triggered.connect(self._on_account)
407 self._refreshTabAction = QtGui.QAction(None)
408 self._refreshTabAction.setText("Refresh")
409 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
410 self._refreshTabAction.triggered.connect(self._on_refresh)
412 self._aboutAction = QtGui.QAction(None)
413 self._aboutAction.setText("About")
414 self._aboutAction.triggered.connect(self._on_about)
416 self._closeWindowAction = QtGui.QAction(None)
417 self._closeWindowAction.setText("Close")
418 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
419 self._closeWindowAction.triggered.connect(self._on_close_window)
421 if constants.IS_MAEMO:
422 fileMenu = self._window.menuBar().addMenu("&File")
423 fileMenu.addAction(self._loginTabAction)
424 fileMenu.addAction(self._refreshTabAction)
426 toolsMenu = self._window.menuBar().addMenu("&Tools")
427 toolsMenu.addAction(self._accountTabAction)
428 toolsMenu.addAction(self._importTabAction)
429 toolsMenu.addAction(self._aboutAction)
431 self._window.addAction(self._closeWindowAction)
432 self._window.addAction(self._app.quitAction)
433 self._window.addAction(self._app.fullscreenAction)
435 fileMenu = self._window.menuBar().addMenu("&File")
436 fileMenu.addAction(self._loginTabAction)
437 fileMenu.addAction(self._refreshTabAction)
438 fileMenu.addAction(self._closeWindowAction)
439 fileMenu.addAction(self._app.quitAction)
441 viewMenu = self._window.menuBar().addMenu("&View")
442 viewMenu.addAction(self._app.fullscreenAction)
444 toolsMenu = self._window.menuBar().addMenu("&Tools")
445 toolsMenu.addAction(self._accountTabAction)
446 toolsMenu.addAction(self._importTabAction)
447 toolsMenu.addAction(self._aboutAction)
449 self._window.addAction(self._app.logAction)
451 self._initialize_tab(self._tabWidget.currentIndex())
452 self.set_fullscreen(self._app.fullscreenAction.isChecked())
458 def set_default_credentials(self, username, password):
459 self._defaultCredentials = username, password
461 def get_default_credentials(self):
462 return self._defaultCredentials
464 def walk_children(self):
465 return (diag for diag in (
466 self._credentialsDialog,
467 self._smsEntryDialog,
475 assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
476 if self._defaultCredentials != ("", ""):
477 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
478 self._curentCredentials = username, password
479 self._session.login(username, password)
481 self._prompt_for_login()
484 for child in self.walk_children():
485 child.window.destroyed.disconnect(self._on_child_close)
490 if self._session.state != self._session.LOGGEDOUT_STATE:
491 self._session.logout()
493 def get_current_tab(self):
494 return self._currentTab
496 def set_current_tab(self, tabIndex):
497 self._tabWidget.setCurrentIndex(tabIndex)
499 def load_settings(self, config):
500 backendId = 2 # For backwards compatibility
501 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
502 sectionName = "%s - %s" % (backendId, tabTitle)
503 settings = self._tabsContents[tabIndex].get_settings()
504 for settingName in settings.iterkeys():
506 settingValue = config.get(sectionName, settingName)
507 except ConfigParser.NoOptionError, e:
509 "Settings file %s is missing section %s" % (
510 constants._user_settings_,
515 except ConfigParser.NoSectionError, e:
517 "Settings file %s is missing section %s" % (
518 constants._user_settings_,
524 _moduleLogger.exception("Unknown loading error")
526 settings[settingName] = settingValue
527 self._tabsContents[tabIndex].set_settings(settings)
529 def save_settings(self, config):
530 backendId = 2 # For backwards compatibility
531 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
532 sectionName = "%s - %s" % (backendId, tabTitle)
533 config.add_section(sectionName)
534 tabSettings = self._tabsContents[tabIndex].get_settings()
535 for settingName, settingValue in tabSettings.iteritems():
536 config.set(sectionName, settingName, settingValue)
540 for child in self.walk_children():
544 for child in self.walk_children():
548 def set_fullscreen(self, isFullscreen):
550 self._window.showFullScreen()
552 self._window.showNormal()
553 for child in self.walk_children():
554 child.set_fullscreen(isFullscreen)
556 def _initialize_tab(self, index):
557 assert index < self.MAX_TABS, "Invalid tab"
558 if not self._tabsContents[index].has_child():
559 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
560 self._tabsContents[index].set_child(tab)
561 self._tabsContents[index].refresh(force=False)
563 def _prompt_for_login(self):
564 if self._credentialsDialog is None:
566 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
567 username, password = self._credentialsDialog.run(
568 self._defaultCredentials[0], self._defaultCredentials[1], self.window
570 self._curentCredentials = username, password
571 self._session.login(username, password)
573 def _show_account_dialog(self):
574 if self._accountDialog is None:
576 self._accountDialog = dialogs.AccountDialog(self._app)
577 self._accountDialog.set_callbacks(
578 self._session.get_callback_numbers(), self._session.get_callback_number()
580 self._accountDialog.accountNumber = self._session.get_account_number()
581 response = self._accountDialog.run()
582 if response == QtGui.QDialog.Accepted:
583 if self._accountDialog.doClear:
584 self._session.logout_and_clear()
586 callbackNumber = self._accountDialog.selectedCallback
587 self._session.set_callback_number(callbackNumber)
588 elif response == QtGui.QDialog.Rejected:
589 _moduleLogger.info("Cancelled")
591 _moduleLogger.info("Unknown response")
593 @QtCore.pyqtSlot(str)
594 @misc_utils.log_exception(_moduleLogger)
595 def _on_session_error(self, message):
596 with qui_utils.notify_error(self._errorLog):
597 self._errorLog.push_error(message)
600 @misc_utils.log_exception(_moduleLogger)
602 with qui_utils.notify_error(self._errorLog):
603 changedAccounts = self._defaultCredentials != self._curentCredentials
604 noCallback = not self._session.get_callback_number()
605 if changedAccounts or noCallback:
606 self._show_account_dialog()
608 self._defaultCredentials = self._curentCredentials
610 for tab in self._tabsContents:
614 @misc_utils.log_exception(_moduleLogger)
615 def _on_logout(self):
616 with qui_utils.notify_error(self._errorLog):
617 for tab in self._tabsContents:
621 @misc_utils.log_exception(_moduleLogger)
622 def _on_recipients_changed(self):
623 with qui_utils.notify_error(self._errorLog):
624 if self._session.draft.get_num_contacts() == 0:
627 if self._smsEntryDialog is None:
629 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
632 @QtCore.pyqtSlot(bool)
633 @misc_utils.log_exception(_moduleLogger)
634 def _on_login_requested(self, checked = True):
635 with qui_utils.notify_error(self._errorLog):
636 self._prompt_for_login()
638 @QtCore.pyqtSlot(int)
639 @misc_utils.log_exception(_moduleLogger)
640 def _on_tab_changed(self, index):
641 with qui_utils.notify_error(self._errorLog):
642 self._currentTab = index
643 self._initialize_tab(index)
646 @QtCore.pyqtSlot(bool)
647 @misc_utils.log_exception(_moduleLogger)
648 def _on_refresh(self, checked = True):
649 with qui_utils.notify_error(self._errorLog):
650 self._tabsContents[self._currentTab].refresh(force=True)
653 @QtCore.pyqtSlot(bool)
654 @misc_utils.log_exception(_moduleLogger)
655 def _on_import(self, checked = True):
656 with qui_utils.notify_error(self._errorLog):
657 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
661 shutil.copy2(csvName, self._app.fsContactsPath)
662 self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
665 @QtCore.pyqtSlot(bool)
666 @misc_utils.log_exception(_moduleLogger)
667 def _on_account(self, checked = True):
668 with qui_utils.notify_error(self._errorLog):
669 self._show_account_dialog()
672 @QtCore.pyqtSlot(bool)
673 @misc_utils.log_exception(_moduleLogger)
674 def _on_about(self, checked = True):
675 with qui_utils.notify_error(self._errorLog):
676 if self._aboutDialog is None:
678 self._aboutDialog = dialogs.AboutDialog(self._app)
679 response = self._aboutDialog.run()
682 @QtCore.pyqtSlot(bool)
683 @misc_utils.log_exception(_moduleLogger)
684 def _on_close_window(self, checked = True):
689 app = QtGui.QApplication([])
690 handle = Dialcentral(app)
695 if __name__ == "__main__":
698 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
699 logging.basicConfig(level=logging.DEBUG, format=logFormat)
701 os.makedirs(constants._data_path_)