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__)
27 class Dialcentral(object):
29 def __init__(self, app):
32 self._hiddenCategories = set()
33 self._hiddenUnits = {}
34 self._clipboard = QtGui.QApplication.clipboard()
36 self._mainWindow = None
38 self._fullscreenAction = QtGui.QAction(None)
39 self._fullscreenAction.setText("Fullscreen")
40 self._fullscreenAction.setCheckable(True)
41 self._fullscreenAction.setShortcut(QtGui.QKeySequence("CTRL+Enter"))
42 self._fullscreenAction.toggled.connect(self._on_toggle_fullscreen)
44 self._logAction = QtGui.QAction(None)
45 self._logAction.setText("Log")
46 self._logAction.setShortcut(QtGui.QKeySequence("CTRL+l"))
47 self._logAction.triggered.connect(self._on_log)
49 self._quitAction = QtGui.QAction(None)
50 self._quitAction.setText("Quit")
51 self._quitAction.setShortcut(QtGui.QKeySequence("CTRL+q"))
52 self._quitAction.triggered.connect(self._on_quit)
54 self._app.lastWindowClosed.connect(self._on_app_quit)
55 self._mainWindow = MainWindow(None, self)
56 self._mainWindow.window.destroyed.connect(self._on_child_close)
60 self._mainWindow.show()
61 self._idleDelay = QtCore.QTimer()
62 self._idleDelay.setSingleShot(True)
63 self._idleDelay.setInterval(0)
64 self._idleDelay.timeout.connect(lambda: self._mainWindow.start())
65 self._idleDelay.start()
67 def load_settings(self):
69 config = ConfigParser.SafeConfigParser()
70 config.read(constants._user_settings_)
72 _moduleLogger.info("No settings")
75 _moduleLogger.info("Settings were corrupt")
77 except ConfigParser.MissingSectionHeaderError:
78 _moduleLogger.info("Settings were corrupt")
81 _moduleLogger.exception("Unknown loading error")
88 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
89 for i in xrange(len(self._mainWindow.get_default_credentials()))
91 isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
92 tabIndex = config.getint(constants.__pretty_app_name__, "tab")
93 except ConfigParser.NoOptionError, e:
95 "Settings file %s is missing option %s" % (
96 constants._user_settings_,
100 except ConfigParser.NoSectionError, e:
102 "Settings file %s is missing section %s" % (
103 constants._user_settings_,
109 _moduleLogger.exception("Unknown loading error")
113 base64.b64decode(blob)
116 self._mainWindow.set_default_credentials(*creds)
117 self._fullscreenAction.setChecked(isFullscreen)
118 self._mainWindow.set_current_tab(tabIndex)
119 self._mainWindow.load_settings(config)
121 def save_settings(self):
122 config = ConfigParser.SafeConfigParser()
124 config.add_section(constants.__pretty_app_name__)
125 config.set(constants.__pretty_app_name__, "tab", str(self._mainWindow.get_current_tab()))
126 config.set(constants.__pretty_app_name__, "fullscreen", str(self._fullscreenAction.isChecked()))
127 for i, value in enumerate(self._mainWindow.get_default_credentials()):
128 blob = base64.b64encode(value)
129 config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
131 self._mainWindow.save_settings(config)
133 with open(constants._user_settings_, "wb") as configFile:
134 config.write(configFile)
137 def fsContactsPath(self):
138 return os.path.join(constants._data_path_, "contacts")
141 def fullscreenAction(self):
142 return self._fullscreenAction
146 return self._logAction
149 def quitAction(self):
150 return self._quitAction
152 def _close_windows(self):
153 if self._mainWindow is not None:
154 self._mainWindow.window.destroyed.disconnect(self._on_child_close)
155 self._mainWindow.close()
156 self._mainWindow = None
159 @QtCore.pyqtSlot(bool)
160 @misc_utils.log_exception(_moduleLogger)
161 def _on_app_quit(self, checked = False):
163 self._mainWindow.destroy()
165 @QtCore.pyqtSlot(QtCore.QObject)
166 @misc_utils.log_exception(_moduleLogger)
167 def _on_child_close(self, obj = None):
168 self._mainWindow = None
171 @QtCore.pyqtSlot(bool)
172 @misc_utils.log_exception(_moduleLogger)
173 def _on_toggle_fullscreen(self, checked = False):
174 for window in self._walk_children():
175 window.set_fullscreen(checked)
178 @QtCore.pyqtSlot(bool)
179 @misc_utils.log_exception(_moduleLogger)
180 def _on_log(self, checked = False):
181 with open(constants._user_logpath_, "r") as f:
182 logLines = f.xreadlines()
183 log = "".join(logLines)
184 self._clipboard.setText(log)
187 @QtCore.pyqtSlot(bool)
188 @misc_utils.log_exception(_moduleLogger)
189 def _on_quit(self, checked = False):
190 self._close_windows()
193 class DelayedWidget(object):
195 def __init__(self, app, settingsNames):
196 self._layout = QtGui.QVBoxLayout()
197 self._widget = QtGui.QWidget()
198 self._widget.setLayout(self._layout)
199 self._settings = dict((name, "") for name in settingsNames)
202 self._isEnabled = True
209 return self._child is not None
211 def set_child(self, child):
212 if self._child is not None:
213 self._layout.removeWidget(self._child.toplevel)
215 if self._child is not None:
216 self._layout.addWidget(self._child.toplevel)
218 self._child.set_settings(self._settings)
223 self._child.disable()
226 self._isEnabled = True
227 if self._child is not None:
231 self._isEnabled = False
232 if self._child is not None:
233 self._child.disable()
236 if self._child is not None:
239 def refresh(self, force=True):
240 if self._child is not None:
241 self._child.refresh(force)
243 def get_settings(self):
244 if self._child is not None:
245 return self._child.get_settings()
247 return self._settings
249 def set_settings(self, settings):
250 if self._child is not None:
251 self._child.set_settings(settings)
253 self._settings = settings
256 def _tab_factory(tab, app, session, errorLog):
258 return gv_views.__dict__[tab](app, session, errorLog)
261 class MainWindow(object):
275 assert len(_TAB_TITLES) == MAX_TABS
278 functools.partial(_tab_factory, "Dialpad"),
279 functools.partial(_tab_factory, "History"),
280 functools.partial(_tab_factory, "Messages"),
281 functools.partial(_tab_factory, "Contacts"),
283 assert len(_TAB_CLASS) == MAX_TABS
285 # Hack to allow delay importing/loading of tabs
286 _TAB_SETTINGS_NAMES = [
290 ("selectedAddressbook", ),
292 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
294 def __init__(self, parent, app):
296 self._session = session.Session(constants._data_path_)
297 self._session.error.connect(self._on_session_error)
298 self._session.loggedIn.connect(self._on_login)
299 self._session.loggedOut.connect(self._on_logout)
300 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
301 self._defaultCredentials = "", ""
302 self._curentCredentials = "", ""
304 self._credentialsDialog = None
305 self._smsEntryDialog = None
306 self._accountDialog = None
308 self._errorLog = qui_utils.QErrorLog()
309 self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
311 self._tabsContents = [
312 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
313 for i in xrange(self.MAX_TABS)
315 for tab in self._tabsContents:
318 self._tabWidget = QtGui.QTabWidget()
319 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
320 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
322 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
323 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
324 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
325 self._tabWidget.currentChanged.connect(self._on_tab_changed)
327 self._layout = QtGui.QVBoxLayout()
328 self._layout.addWidget(self._errorDisplay.toplevel)
329 self._layout.addWidget(self._tabWidget)
331 centralWidget = QtGui.QWidget()
332 centralWidget.setLayout(self._layout)
334 self._window = QtGui.QMainWindow(parent)
335 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
336 qui_utils.set_autorient(self._window, True)
337 qui_utils.set_stackable(self._window, True)
338 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
339 self._window.setCentralWidget(centralWidget)
341 self._loginTabAction = QtGui.QAction(None)
342 self._loginTabAction.setText("Login")
343 self._loginTabAction.triggered.connect(self._on_login_requested)
345 self._importTabAction = QtGui.QAction(None)
346 self._importTabAction.setText("Import")
347 self._importTabAction.triggered.connect(self._on_import)
349 self._accountTabAction = QtGui.QAction(None)
350 self._accountTabAction.setText("Account")
351 self._accountTabAction.triggered.connect(self._on_account)
353 self._refreshTabAction = QtGui.QAction(None)
354 self._refreshTabAction.setText("Refresh")
355 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
356 self._refreshTabAction.triggered.connect(self._on_refresh)
358 self._closeWindowAction = QtGui.QAction(None)
359 self._closeWindowAction.setText("Close")
360 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
361 self._closeWindowAction.triggered.connect(self._on_close_window)
364 fileMenu = self._window.menuBar().addMenu("&File")
365 fileMenu.addAction(self._loginTabAction)
366 fileMenu.addAction(self._refreshTabAction)
368 toolsMenu = self._window.menuBar().addMenu("&Tools")
369 toolsMenu.addAction(self._accountTabAction)
370 toolsMenu.addAction(self._importTabAction)
372 self._window.addAction(self._closeWindowAction)
373 self._window.addAction(self._app.quitAction)
374 self._window.addAction(self._app.fullscreenAction)
376 fileMenu = self._window.menuBar().addMenu("&File")
377 fileMenu.addAction(self._loginTabAction)
378 fileMenu.addAction(self._refreshTabAction)
379 fileMenu.addAction(self._closeWindowAction)
380 fileMenu.addAction(self._app.quitAction)
382 viewMenu = self._window.menuBar().addMenu("&View")
383 viewMenu.addAction(self._app.fullscreenAction)
385 toolsMenu = self._window.menuBar().addMenu("&Tools")
386 toolsMenu.addAction(self._accountTabAction)
387 toolsMenu.addAction(self._importTabAction)
389 self._window.addAction(self._app.logAction)
391 self._initialize_tab(self._tabWidget.currentIndex())
392 self.set_fullscreen(self._app.fullscreenAction.isChecked())
398 def set_default_credentials(self, username, password):
399 self._defaultCredentials = username, password
401 def get_default_credentials(self):
402 return self._defaultCredentials
404 def walk_children(self):
408 assert self._session.state == self._session.LOGGEDOUT_STATE
409 if self._defaultCredentials != ("", ""):
410 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
411 self._curentCredentials = username, password
412 self._session.login(username, password)
414 self._prompt_for_login()
417 for child in self.walk_children():
418 child.window.destroyed.disconnect(self._on_child_close)
423 if self._session.state != self._session.LOGGEDOUT_STATE:
424 self._session.logout()
426 def get_current_tab(self):
427 return self._tabWidget.currentIndex()
429 def set_current_tab(self, tabIndex):
430 self._tabWidget.setCurrentIndex(tabIndex)
432 def load_settings(self, config):
433 backendId = 2 # For backwards compatibility
434 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
435 sectionName = "%s - %s" % (backendId, tabTitle)
436 settings = self._tabsContents[tabIndex].get_settings()
437 for settingName in settings.iterkeys():
439 settingValue = config.get(sectionName, settingName)
440 except ConfigParser.NoOptionError, e:
442 "Settings file %s is missing section %s" % (
443 constants._user_settings_,
448 except ConfigParser.NoSectionError, e:
450 "Settings file %s is missing section %s" % (
451 constants._user_settings_,
457 _moduleLogger.exception("Unknown loading error")
459 settings[settingName] = settingValue
460 self._tabsContents[tabIndex].set_settings(settings)
462 def save_settings(self, config):
463 backendId = 2 # For backwards compatibility
464 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
465 sectionName = "%s - %s" % (backendId, tabTitle)
466 config.add_section(sectionName)
467 tabSettings = self._tabsContents[tabIndex].get_settings()
468 for settingName, settingValue in tabSettings.iteritems():
469 config.set(sectionName, settingName, settingValue)
473 for child in self.walk_children():
477 for child in self.walk_children():
481 def set_fullscreen(self, isFullscreen):
483 self._window.showFullScreen()
485 self._window.showNormal()
486 for child in self.walk_children():
487 child.set_fullscreen(isFullscreen)
489 def _initialize_tab(self, index):
490 assert index < self.MAX_TABS
491 if not self._tabsContents[index].has_child():
492 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
493 self._tabsContents[index].set_child(tab)
494 self._tabsContents[index].refresh(force=False)
496 def _prompt_for_login(self):
497 if self._credentialsDialog is None:
499 self._credentialsDialog = dialogs.CredentialsDialog()
500 username, password = self._credentialsDialog.run(
501 self._defaultCredentials[0], self._defaultCredentials[1], self.window
503 self._curentCredentials = username, password
504 self._session.login(username, password)
506 def _show_account_dialog(self):
507 if self._accountDialog is None:
509 self._accountDialog = dialogs.AccountDialog()
510 self._accountDialog.accountNumber = self._session.get_account_number()
511 response = self._accountDialog.run()
512 if response == QtGui.QDialog.Accepted:
513 if self._accountDialog.doClear():
514 self._session.logout_and_clear()
515 elif response == QtGui.QDialog.Rejected:
516 _moduleLogger.info("Cancelled")
518 _moduleLogger.info("Unknown response")
520 @QtCore.pyqtSlot(str)
521 @misc_utils.log_exception(_moduleLogger)
522 def _on_session_error(self, message):
523 self._errorLog.push_message(message)
526 @misc_utils.log_exception(_moduleLogger)
528 if self._defaultCredentials != self._curentCredentials:
529 self._show_account_dialog()
530 self._defaultCredentials = self._curentCredentials
531 for tab in self._tabsContents:
535 @misc_utils.log_exception(_moduleLogger)
536 def _on_logout(self):
537 for tab in self._tabsContents:
541 @misc_utils.log_exception(_moduleLogger)
542 def _on_recipients_changed(self):
543 if self._session.draft.get_num_contacts() == 0:
546 if self._smsEntryDialog is None:
548 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
552 @QtCore.pyqtSlot(bool)
553 @misc_utils.log_exception(_moduleLogger)
554 def _on_login_requested(self, checked = True):
555 self._prompt_for_login()
557 @QtCore.pyqtSlot(int)
558 @misc_utils.log_exception(_moduleLogger)
559 def _on_tab_changed(self, index):
560 self._initialize_tab(index)
563 @QtCore.pyqtSlot(bool)
564 @misc_utils.log_exception(_moduleLogger)
565 def _on_refresh(self, checked = True):
566 index = self._tabWidget.currentIndex()
567 self._tabsContents[index].refresh(force=True)
570 @QtCore.pyqtSlot(bool)
571 @misc_utils.log_exception(_moduleLogger)
572 def _on_import(self, checked = True):
573 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
577 shutil.copy2(csvName, self._app.fsContactsPath)
578 self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
581 @QtCore.pyqtSlot(bool)
582 @misc_utils.log_exception(_moduleLogger)
583 def _on_account(self, checked = True):
584 self._show_account_dialog()
587 @QtCore.pyqtSlot(bool)
588 @misc_utils.log_exception(_moduleLogger)
589 def _on_close_window(self, checked = True):
594 app = QtGui.QApplication([])
595 handle = Dialcentral(app)
600 if __name__ == "__main__":
603 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
604 logging.basicConfig(level=logging.DEBUG, format=logFormat)
606 os.makedirs(constants._data_path_)