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 # @bug Tab names too long, switch to icons
319 self._tabWidget = QtGui.QTabWidget()
320 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
321 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
323 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
324 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
325 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
326 self._tabWidget.currentChanged.connect(self._on_tab_changed)
328 self._layout = QtGui.QVBoxLayout()
329 self._layout.addWidget(self._errorDisplay.toplevel)
330 self._layout.addWidget(self._tabWidget)
332 centralWidget = QtGui.QWidget()
333 centralWidget.setLayout(self._layout)
335 self._window = QtGui.QMainWindow(parent)
336 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
337 qui_utils.set_autorient(self._window, True)
338 qui_utils.set_stackable(self._window, True)
339 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
340 self._window.setCentralWidget(centralWidget)
342 self._loginTabAction = QtGui.QAction(None)
343 self._loginTabAction.setText("Login")
344 self._loginTabAction.triggered.connect(self._on_login_requested)
346 self._importTabAction = QtGui.QAction(None)
347 self._importTabAction.setText("Import")
348 self._importTabAction.triggered.connect(self._on_import)
350 self._accountTabAction = QtGui.QAction(None)
351 self._accountTabAction.setText("Account")
352 self._accountTabAction.triggered.connect(self._on_account)
354 self._refreshTabAction = QtGui.QAction(None)
355 self._refreshTabAction.setText("Refresh")
356 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
357 self._refreshTabAction.triggered.connect(self._on_refresh)
359 self._closeWindowAction = QtGui.QAction(None)
360 self._closeWindowAction.setText("Close")
361 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
362 self._closeWindowAction.triggered.connect(self._on_close_window)
365 fileMenu = self._window.menuBar().addMenu("&File")
366 fileMenu.addAction(self._loginTabAction)
367 fileMenu.addAction(self._refreshTabAction)
369 toolsMenu = self._window.menuBar().addMenu("&Tools")
370 toolsMenu.addAction(self._accountTabAction)
371 toolsMenu.addAction(self._importTabAction)
373 self._window.addAction(self._closeWindowAction)
374 self._window.addAction(self._app.quitAction)
375 self._window.addAction(self._app.fullscreenAction)
377 fileMenu = self._window.menuBar().addMenu("&File")
378 fileMenu.addAction(self._loginTabAction)
379 fileMenu.addAction(self._refreshTabAction)
380 fileMenu.addAction(self._closeWindowAction)
381 fileMenu.addAction(self._app.quitAction)
383 viewMenu = self._window.menuBar().addMenu("&View")
384 viewMenu.addAction(self._app.fullscreenAction)
386 toolsMenu = self._window.menuBar().addMenu("&Tools")
387 toolsMenu.addAction(self._accountTabAction)
388 toolsMenu.addAction(self._importTabAction)
390 self._window.addAction(self._app.logAction)
392 self._initialize_tab(self._tabWidget.currentIndex())
393 self.set_fullscreen(self._app.fullscreenAction.isChecked())
399 def set_default_credentials(self, username, password):
400 self._defaultCredentials = username, password
402 def get_default_credentials(self):
403 return self._defaultCredentials
405 def walk_children(self):
409 assert self._session.state == self._session.LOGGEDOUT_STATE
410 if self._defaultCredentials != ("", ""):
411 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
412 self._curentCredentials = username, password
413 self._session.login(username, password)
415 self._prompt_for_login()
418 for child in self.walk_children():
419 child.window.destroyed.disconnect(self._on_child_close)
424 if self._session.state != self._session.LOGGEDOUT_STATE:
425 self._session.logout()
427 def get_current_tab(self):
428 return self._tabWidget.currentIndex()
430 def set_current_tab(self, tabIndex):
431 self._tabWidget.setCurrentIndex(tabIndex)
433 def load_settings(self, config):
434 backendId = 2 # For backwards compatibility
435 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
436 sectionName = "%s - %s" % (backendId, tabTitle)
437 settings = self._tabsContents[tabIndex].get_settings()
438 for settingName in settings.iterkeys():
440 settingValue = config.get(sectionName, settingName)
441 except ConfigParser.NoOptionError, e:
443 "Settings file %s is missing section %s" % (
444 constants._user_settings_,
449 except ConfigParser.NoSectionError, e:
451 "Settings file %s is missing section %s" % (
452 constants._user_settings_,
458 _moduleLogger.exception("Unknown loading error")
460 settings[settingName] = settingValue
461 self._tabsContents[tabIndex].set_settings(settings)
463 def save_settings(self, config):
464 backendId = 2 # For backwards compatibility
465 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
466 sectionName = "%s - %s" % (backendId, tabTitle)
467 config.add_section(sectionName)
468 tabSettings = self._tabsContents[tabIndex].get_settings()
469 for settingName, settingValue in tabSettings.iteritems():
470 config.set(sectionName, settingName, settingValue)
474 for child in self.walk_children():
478 for child in self.walk_children():
482 def set_fullscreen(self, isFullscreen):
484 self._window.showFullScreen()
486 self._window.showNormal()
487 for child in self.walk_children():
488 child.set_fullscreen(isFullscreen)
490 def _initialize_tab(self, index):
491 assert index < self.MAX_TABS
492 if not self._tabsContents[index].has_child():
493 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
494 self._tabsContents[index].set_child(tab)
495 self._tabsContents[index].refresh(force=False)
497 def _prompt_for_login(self):
498 if self._credentialsDialog is None:
500 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
501 username, password = self._credentialsDialog.run(
502 self._defaultCredentials[0], self._defaultCredentials[1], self.window
504 self._curentCredentials = username, password
505 self._session.login(username, password)
507 def _show_account_dialog(self):
508 if self._accountDialog is None:
510 self._accountDialog = dialogs.AccountDialog(self._app)
511 self._accountDialog.accountNumber = self._session.get_account_number()
512 response = self._accountDialog.run()
513 if response == QtGui.QDialog.Accepted:
514 if self._accountDialog.doClear:
515 self._session.logout_and_clear()
516 elif response == QtGui.QDialog.Rejected:
517 _moduleLogger.info("Cancelled")
519 _moduleLogger.info("Unknown response")
521 @QtCore.pyqtSlot(str)
522 @misc_utils.log_exception(_moduleLogger)
523 def _on_session_error(self, message):
524 self._errorLog.push_message(message)
527 @misc_utils.log_exception(_moduleLogger)
529 if self._defaultCredentials != self._curentCredentials:
530 self._show_account_dialog()
531 self._defaultCredentials = self._curentCredentials
532 for tab in self._tabsContents:
536 @misc_utils.log_exception(_moduleLogger)
537 def _on_logout(self):
538 for tab in self._tabsContents:
542 @misc_utils.log_exception(_moduleLogger)
543 def _on_recipients_changed(self):
544 if self._session.draft.get_num_contacts() == 0:
547 if self._smsEntryDialog is None:
549 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
553 @QtCore.pyqtSlot(bool)
554 @misc_utils.log_exception(_moduleLogger)
555 def _on_login_requested(self, checked = True):
556 self._prompt_for_login()
558 @QtCore.pyqtSlot(int)
559 @misc_utils.log_exception(_moduleLogger)
560 def _on_tab_changed(self, index):
561 self._initialize_tab(index)
564 @QtCore.pyqtSlot(bool)
565 @misc_utils.log_exception(_moduleLogger)
566 def _on_refresh(self, checked = True):
567 index = self._tabWidget.currentIndex()
568 self._tabsContents[index].refresh(force=True)
571 @QtCore.pyqtSlot(bool)
572 @misc_utils.log_exception(_moduleLogger)
573 def _on_import(self, checked = True):
574 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
578 shutil.copy2(csvName, self._app.fsContactsPath)
579 self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
582 @QtCore.pyqtSlot(bool)
583 @misc_utils.log_exception(_moduleLogger)
584 def _on_account(self, checked = True):
585 self._show_account_dialog()
588 @QtCore.pyqtSlot(bool)
589 @misc_utils.log_exception(_moduleLogger)
590 def _on_close_window(self, checked = True):
595 app = QtGui.QApplication([])
596 handle = Dialcentral(app)
601 if __name__ == "__main__":
604 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
605 logging.basicConfig(level=logging.DEBUG, format=logFormat)
607 os.makedirs(constants._data_path_)