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):
30 os.path.join(os.path.dirname(__file__), "../share"),
31 os.path.join(os.path.dirname(__file__), "../data"),
34 def __init__(self, app):
37 self._hiddenCategories = set()
38 self._hiddenUnits = {}
39 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)
143 def fsContactsPath(self):
144 return os.path.join(constants._data_path_, "contacts")
147 def fullscreenAction(self):
148 return self._fullscreenAction
152 return self._logAction
155 def quitAction(self):
156 return self._quitAction
158 def _close_windows(self):
159 if self._mainWindow is not None:
161 self._mainWindow.window.destroyed.disconnect(self._on_child_close)
162 self._mainWindow.close()
163 self._mainWindow = None
166 @QtCore.pyqtSlot(bool)
167 @misc_utils.log_exception(_moduleLogger)
168 def _on_app_quit(self, checked = False):
169 if self._mainWindow is not None:
171 self._mainWindow.destroy()
173 @QtCore.pyqtSlot(QtCore.QObject)
174 @misc_utils.log_exception(_moduleLogger)
175 def _on_child_close(self, obj = None):
176 if self._mainWindow is not None:
178 self._mainWindow = None
181 @QtCore.pyqtSlot(bool)
182 @misc_utils.log_exception(_moduleLogger)
183 def _on_toggle_fullscreen(self, checked = False):
184 for window in self._walk_children():
185 window.set_fullscreen(checked)
188 @QtCore.pyqtSlot(bool)
189 @misc_utils.log_exception(_moduleLogger)
190 def _on_log(self, checked = False):
191 with open(constants._user_logpath_, "r") as f:
192 logLines = f.xreadlines()
193 log = "".join(logLines)
194 self._clipboard.setText(log)
197 @QtCore.pyqtSlot(bool)
198 @misc_utils.log_exception(_moduleLogger)
199 def _on_quit(self, checked = False):
200 self._close_windows()
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()
238 self._isEnabled = True
239 if self._child is not None:
243 self._isEnabled = False
244 if self._child is not None:
245 self._child.disable()
248 if self._child is not None:
251 def refresh(self, force=True):
252 if self._child is not None:
253 self._child.refresh(force)
255 def get_settings(self):
256 if self._child is not None:
257 return self._child.get_settings()
259 return self._settings
261 def set_settings(self, settings):
262 if self._child is not None:
263 self._child.set_settings(settings)
265 self._settings = settings
268 def _tab_factory(tab, app, session, errorLog):
270 return gv_views.__dict__[tab](app, session, errorLog)
273 class MainWindow(object):
287 assert len(_TAB_TITLES) == MAX_TABS
295 assert len(_TAB_ICONS) == MAX_TABS
298 functools.partial(_tab_factory, "Dialpad"),
299 functools.partial(_tab_factory, "History"),
300 functools.partial(_tab_factory, "Messages"),
301 functools.partial(_tab_factory, "Contacts"),
303 assert len(_TAB_CLASS) == MAX_TABS
305 # Hack to allow delay importing/loading of tabs
306 _TAB_SETTINGS_NAMES = [
310 ("selectedAddressbook", ),
312 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
314 def __init__(self, parent, app):
316 self._session = session.Session(constants._data_path_)
317 self._session.error.connect(self._on_session_error)
318 self._session.loggedIn.connect(self._on_login)
319 self._session.loggedOut.connect(self._on_logout)
320 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
321 self._defaultCredentials = "", ""
322 self._curentCredentials = "", ""
325 self._credentialsDialog = None
326 self._smsEntryDialog = None
327 self._accountDialog = None
329 self._errorLog = qui_utils.QErrorLog()
330 self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
332 self._tabsContents = [
333 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
334 for i in xrange(self.MAX_TABS)
336 for tab in self._tabsContents:
339 self._tabWidget = QtGui.QTabWidget()
340 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
341 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
343 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
345 for tabIndex, (tabTitle, tabIcon) in enumerate(
346 zip(self._TAB_TITLES, self._TAB_ICONS)
348 if _dataPath is None:
349 for path in self._app._DATA_PATHS:
350 if os.path.exists(os.path.join(path, tabIcon)):
354 if _dataPath is None:
355 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
357 icon = QtGui.QIcon(os.path.join(_dataPath, tabIcon))
358 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, "")
360 icon = QtGui.QIcon(os.path.join(_dataPath, tabIcon))
361 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
362 self._tabWidget.currentChanged.connect(self._on_tab_changed)
363 self._tabWidget.setContentsMargins(0, 0, 0, 0)
365 self._layout = QtGui.QVBoxLayout()
366 self._layout.setContentsMargins(0, 0, 0, 0)
367 self._layout.addWidget(self._errorDisplay.toplevel)
368 self._layout.addWidget(self._tabWidget)
370 centralWidget = QtGui.QWidget()
371 centralWidget.setLayout(self._layout)
372 centralWidget.setContentsMargins(0, 0, 0, 0)
374 self._window = QtGui.QMainWindow(parent)
375 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
376 qui_utils.set_autorient(self._window, True)
377 qui_utils.set_stackable(self._window, True)
378 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
379 self._window.setCentralWidget(centralWidget)
381 self._loginTabAction = QtGui.QAction(None)
382 self._loginTabAction.setText("Login")
383 self._loginTabAction.triggered.connect(self._on_login_requested)
385 self._importTabAction = QtGui.QAction(None)
386 self._importTabAction.setText("Import")
387 self._importTabAction.triggered.connect(self._on_import)
389 self._accountTabAction = QtGui.QAction(None)
390 self._accountTabAction.setText("Account")
391 self._accountTabAction.triggered.connect(self._on_account)
393 self._refreshTabAction = QtGui.QAction(None)
394 self._refreshTabAction.setText("Refresh")
395 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
396 self._refreshTabAction.triggered.connect(self._on_refresh)
398 self._closeWindowAction = QtGui.QAction(None)
399 self._closeWindowAction.setText("Close")
400 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
401 self._closeWindowAction.triggered.connect(self._on_close_window)
404 fileMenu = self._window.menuBar().addMenu("&File")
405 fileMenu.addAction(self._loginTabAction)
406 fileMenu.addAction(self._refreshTabAction)
408 toolsMenu = self._window.menuBar().addMenu("&Tools")
409 toolsMenu.addAction(self._accountTabAction)
410 toolsMenu.addAction(self._importTabAction)
412 self._window.addAction(self._closeWindowAction)
413 self._window.addAction(self._app.quitAction)
414 self._window.addAction(self._app.fullscreenAction)
416 fileMenu = self._window.menuBar().addMenu("&File")
417 fileMenu.addAction(self._loginTabAction)
418 fileMenu.addAction(self._refreshTabAction)
419 fileMenu.addAction(self._closeWindowAction)
420 fileMenu.addAction(self._app.quitAction)
422 viewMenu = self._window.menuBar().addMenu("&View")
423 viewMenu.addAction(self._app.fullscreenAction)
425 toolsMenu = self._window.menuBar().addMenu("&Tools")
426 toolsMenu.addAction(self._accountTabAction)
427 toolsMenu.addAction(self._importTabAction)
429 self._window.addAction(self._app.logAction)
431 self._initialize_tab(self._tabWidget.currentIndex())
432 self.set_fullscreen(self._app.fullscreenAction.isChecked())
438 def set_default_credentials(self, username, password):
439 self._defaultCredentials = username, password
441 def get_default_credentials(self):
442 return self._defaultCredentials
444 def walk_children(self):
448 assert self._session.state == self._session.LOGGEDOUT_STATE
449 if self._defaultCredentials != ("", ""):
450 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
451 self._curentCredentials = username, password
452 self._session.login(username, password)
454 self._prompt_for_login()
457 for child in self.walk_children():
458 child.window.destroyed.disconnect(self._on_child_close)
463 if self._session.state != self._session.LOGGEDOUT_STATE:
464 self._session.logout()
466 def get_current_tab(self):
467 return self._currentTab
469 def set_current_tab(self, tabIndex):
470 self._tabWidget.setCurrentIndex(tabIndex)
472 def load_settings(self, config):
473 backendId = 2 # For backwards compatibility
474 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
475 sectionName = "%s - %s" % (backendId, tabTitle)
476 settings = self._tabsContents[tabIndex].get_settings()
477 for settingName in settings.iterkeys():
479 settingValue = config.get(sectionName, settingName)
480 except ConfigParser.NoOptionError, e:
482 "Settings file %s is missing section %s" % (
483 constants._user_settings_,
488 except ConfigParser.NoSectionError, e:
490 "Settings file %s is missing section %s" % (
491 constants._user_settings_,
497 _moduleLogger.exception("Unknown loading error")
499 settings[settingName] = settingValue
500 self._tabsContents[tabIndex].set_settings(settings)
502 def save_settings(self, config):
503 backendId = 2 # For backwards compatibility
504 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
505 sectionName = "%s - %s" % (backendId, tabTitle)
506 config.add_section(sectionName)
507 tabSettings = self._tabsContents[tabIndex].get_settings()
508 for settingName, settingValue in tabSettings.iteritems():
509 config.set(sectionName, settingName, settingValue)
513 for child in self.walk_children():
517 for child in self.walk_children():
521 def set_fullscreen(self, isFullscreen):
523 self._window.showFullScreen()
525 self._window.showNormal()
526 for child in self.walk_children():
527 child.set_fullscreen(isFullscreen)
529 def _initialize_tab(self, index):
530 assert index < self.MAX_TABS
531 if not self._tabsContents[index].has_child():
532 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
533 self._tabsContents[index].set_child(tab)
534 self._tabsContents[index].refresh(force=False)
536 def _prompt_for_login(self):
537 if self._credentialsDialog is None:
539 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
540 username, password = self._credentialsDialog.run(
541 self._defaultCredentials[0], self._defaultCredentials[1], self.window
543 self._curentCredentials = username, password
544 self._session.login(username, password)
546 def _show_account_dialog(self):
547 if self._accountDialog is None:
549 self._accountDialog = dialogs.AccountDialog(self._app)
550 self._accountDialog.accountNumber = self._session.get_account_number()
551 response = self._accountDialog.run()
552 if response == QtGui.QDialog.Accepted:
553 if self._accountDialog.doClear:
554 self._session.logout_and_clear()
555 elif response == QtGui.QDialog.Rejected:
556 _moduleLogger.info("Cancelled")
558 _moduleLogger.info("Unknown response")
560 @QtCore.pyqtSlot(str)
561 @misc_utils.log_exception(_moduleLogger)
562 def _on_session_error(self, message):
563 self._errorLog.push_message(message)
566 @misc_utils.log_exception(_moduleLogger)
568 if self._defaultCredentials != self._curentCredentials:
569 self._show_account_dialog()
570 self._defaultCredentials = self._curentCredentials
571 for tab in self._tabsContents:
575 @misc_utils.log_exception(_moduleLogger)
576 def _on_logout(self):
577 for tab in self._tabsContents:
581 @misc_utils.log_exception(_moduleLogger)
582 def _on_recipients_changed(self):
583 if self._session.draft.get_num_contacts() == 0:
586 if self._smsEntryDialog is None:
588 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
592 @QtCore.pyqtSlot(bool)
593 @misc_utils.log_exception(_moduleLogger)
594 def _on_login_requested(self, checked = True):
595 self._prompt_for_login()
597 @QtCore.pyqtSlot(int)
598 @misc_utils.log_exception(_moduleLogger)
599 def _on_tab_changed(self, index):
600 self._currentTab = index
601 self._initialize_tab(index)
604 @QtCore.pyqtSlot(bool)
605 @misc_utils.log_exception(_moduleLogger)
606 def _on_refresh(self, checked = True):
607 self._tabsContents[self._currentTab].refresh(force=True)
610 @QtCore.pyqtSlot(bool)
611 @misc_utils.log_exception(_moduleLogger)
612 def _on_import(self, checked = True):
613 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
617 shutil.copy2(csvName, self._app.fsContactsPath)
618 self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
621 @QtCore.pyqtSlot(bool)
622 @misc_utils.log_exception(_moduleLogger)
623 def _on_account(self, checked = True):
624 self._show_account_dialog()
627 @QtCore.pyqtSlot(bool)
628 @misc_utils.log_exception(_moduleLogger)
629 def _on_close_window(self, checked = True):
634 app = QtGui.QApplication([])
635 handle = Dialcentral(app)
640 if __name__ == "__main__":
643 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
644 logging.basicConfig(level=logging.DEBUG, format=logFormat)
646 os.makedirs(constants._data_path_)