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)
59 def load_settings(self):
61 config = ConfigParser.SafeConfigParser()
62 config.read(constants._user_settings_)
64 _moduleLogger.info("No settings")
67 _moduleLogger.info("Settings were corrupt")
69 except ConfigParser.MissingSectionHeaderError:
70 _moduleLogger.info("Settings were corrupt")
75 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
76 for i in xrange(len(self._mainWindow.get_default_credentials()))
78 isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
79 except ConfigParser.NoOptionError, e:
80 _moduleLogger.exception(
81 "Settings file %s is missing section %s" % (
82 constants._user_settings_,
87 except ConfigParser.NoSectionError, e:
88 _moduleLogger.exception(
89 "Settings file %s is missing section %s" % (
90 constants._user_settings_,
97 base64.b64decode(blob)
100 self._mainWindow.set_default_credentials(*creds)
101 self._fullscreenAction.setChecked(isFullscreen)
103 def save_settings(self):
104 config = ConfigParser.SafeConfigParser()
106 config.add_section(constants.__pretty_app_name__)
107 config.set(constants.__pretty_app_name__, "fullscreen", str(self._fullscreenAction.isChecked()))
108 for i, value in enumerate(self._mainWindow.get_default_credentials()):
109 blob = base64.b64encode(value)
110 config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
112 with open(constants._user_settings_, "wb") as configFile:
113 config.write(configFile)
116 def fsContactsPath(self):
117 return os.path.join(constants._data_path_, "contacts")
120 def fullscreenAction(self):
121 return self._fullscreenAction
125 return self._logAction
128 def quitAction(self):
129 return self._quitAction
131 def _close_windows(self):
132 if self._mainWindow is not None:
133 self._mainWindow.window.destroyed.disconnect(self._on_child_close)
134 self._mainWindow.close()
135 self._mainWindow = None
138 @QtCore.pyqtSlot(bool)
139 @misc_utils.log_exception(_moduleLogger)
140 def _on_app_quit(self, checked = False):
142 self._mainWindow.destroy()
144 @QtCore.pyqtSlot(QtCore.QObject)
145 @misc_utils.log_exception(_moduleLogger)
146 def _on_child_close(self, obj = None):
147 self._mainWindow = None
150 @QtCore.pyqtSlot(bool)
151 @misc_utils.log_exception(_moduleLogger)
152 def _on_toggle_fullscreen(self, checked = False):
153 for window in self._walk_children():
154 window.set_fullscreen(checked)
157 @QtCore.pyqtSlot(bool)
158 @misc_utils.log_exception(_moduleLogger)
159 def _on_log(self, checked = False):
160 with open(constants._user_logpath_, "r") as f:
161 logLines = f.xreadlines()
162 log = "".join(logLines)
163 self._clipboard.setText(log)
166 @QtCore.pyqtSlot(bool)
167 @misc_utils.log_exception(_moduleLogger)
168 def _on_quit(self, checked = False):
169 self._close_windows()
172 class DelayedWidget(object):
174 def __init__(self, app):
175 self._layout = QtGui.QVBoxLayout()
176 self._widget = QtGui.QWidget()
177 self._widget.setLayout(self._layout)
180 self._isEnabled = True
187 return self._child is not None
189 def set_child(self, child):
190 if self._child is not None:
191 self._layout.removeWidget(self._child.toplevel)
193 if self._child is not None:
194 self._layout.addWidget(self._child.toplevel)
199 self._child.disable()
202 self._isEnabled = True
203 if self._child is not None:
207 self._isEnabled = False
208 if self._child is not None:
209 self._child.disable()
212 if self._child is not None:
215 def refresh(self, force=True):
216 if self._child is not None:
217 self._child.refresh(force)
220 def _tab_factory(tab, app, session, errorLog):
222 return gv_views.__dict__[tab](app, session, errorLog)
225 class MainWindow(object):
239 assert len(_TAB_TITLES) == MAX_TABS
242 functools.partial(_tab_factory, "Dialpad"),
243 functools.partial(_tab_factory, "History"),
244 functools.partial(_tab_factory, "Messages"),
245 functools.partial(_tab_factory, "Contacts"),
247 assert len(_TAB_CLASS) == MAX_TABS
249 def __init__(self, parent, app):
251 self._session = session.Session(constants._data_path_)
252 self._session.error.connect(self._on_session_error)
253 self._session.loggedIn.connect(self._on_login)
254 self._session.loggedOut.connect(self._on_logout)
255 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
256 self._defaultCredentials = "", ""
257 self._curentCredentials = "", ""
259 self._credentialsDialog = None
260 self._smsEntryDialog = None
261 self._accountDialog = None
263 self._errorLog = qui_utils.QErrorLog()
264 self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
266 self._tabsContents = [
267 DelayedWidget(self._app)
268 for i in xrange(self.MAX_TABS)
270 for tab in self._tabsContents:
273 self._tabWidget = QtGui.QTabWidget()
274 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
275 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
277 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
278 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
279 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
280 self._tabWidget.currentChanged.connect(self._on_tab_changed)
282 self._layout = QtGui.QVBoxLayout()
283 self._layout.addWidget(self._errorDisplay.toplevel)
284 self._layout.addWidget(self._tabWidget)
286 centralWidget = QtGui.QWidget()
287 centralWidget.setLayout(self._layout)
289 self._window = QtGui.QMainWindow(parent)
290 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
291 qui_utils.set_autorient(self._window, True)
292 qui_utils.set_stackable(self._window, True)
293 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
294 self._window.setCentralWidget(centralWidget)
296 self._loginTabAction = QtGui.QAction(None)
297 self._loginTabAction.setText("Login")
298 self._loginTabAction.triggered.connect(self._on_login_requested)
300 self._importTabAction = QtGui.QAction(None)
301 self._importTabAction.setText("Import")
302 self._importTabAction.triggered.connect(self._on_import)
304 self._accountTabAction = QtGui.QAction(None)
305 self._accountTabAction.setText("Account")
306 self._accountTabAction.triggered.connect(self._on_account)
308 self._refreshTabAction = QtGui.QAction(None)
309 self._refreshTabAction.setText("Refresh")
310 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
311 self._refreshTabAction.triggered.connect(self._on_refresh)
313 self._closeWindowAction = QtGui.QAction(None)
314 self._closeWindowAction.setText("Close")
315 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
316 self._closeWindowAction.triggered.connect(self._on_close_window)
319 fileMenu = self._window.menuBar().addMenu("&File")
320 fileMenu.addAction(self._loginTabAction)
321 fileMenu.addAction(self._refreshTabAction)
323 toolsMenu = self._window.menuBar().addMenu("&Tools")
324 toolsMenu.addAction(self._accountTabAction)
325 toolsMenu.addAction(self._importTabAction)
327 self._window.addAction(self._closeWindowAction)
328 self._window.addAction(self._app.quitAction)
329 self._window.addAction(self._app.fullscreenAction)
331 fileMenu = self._window.menuBar().addMenu("&File")
332 fileMenu.addAction(self._loginTabAction)
333 fileMenu.addAction(self._refreshTabAction)
334 fileMenu.addAction(self._closeWindowAction)
335 fileMenu.addAction(self._app.quitAction)
337 viewMenu = self._window.menuBar().addMenu("&View")
338 viewMenu.addAction(self._app.fullscreenAction)
340 toolsMenu = self._window.menuBar().addMenu("&Tools")
341 toolsMenu.addAction(self._accountTabAction)
342 toolsMenu.addAction(self._importTabAction)
344 self._window.addAction(self._app.logAction)
346 self._initialize_tab(self._tabWidget.currentIndex())
347 self.set_fullscreen(self._app.fullscreenAction.isChecked())
354 def set_default_credentials(self, username, password):
355 self._defaultCredentials = username, password
357 def get_default_credentials(self):
358 return self._defaultCredentials
360 def walk_children(self):
365 for child in self.walk_children():
369 for child in self.walk_children():
374 for child in self.walk_children():
375 child.window.destroyed.disconnect(self._on_child_close)
380 if self._session.state != self._session.LOGGEDOUT_STATE:
381 self._session.logout()
383 def set_fullscreen(self, isFullscreen):
385 self._window.showFullScreen()
387 self._window.showNormal()
388 for child in self.walk_children():
389 child.set_fullscreen(isFullscreen)
391 def _initialize_tab(self, index):
392 assert index < self.MAX_TABS
393 if not self._tabsContents[index].has_child():
394 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
395 self._tabsContents[index].set_child(tab)
396 self._tabsContents[index].refresh(force=False)
398 def _show_account_dialog(self):
399 if self._accountDialog is None:
401 self._accountDialog = dialogs.AccountDialog()
402 self._accountDialog.accountNumber = self._session.get_account_number()
403 response = self._accountDialog.run()
404 if response == QtGui.QDialog.Accepted:
405 if self._accountDialog.doClear():
406 self._session.logout_and_clear()
407 elif response == QtGui.QDialog.Rejected:
408 _moduleLogger.info("Cancelled")
410 _moduleLogger.info("Unknown response")
412 @QtCore.pyqtSlot(str)
413 @misc_utils.log_exception(_moduleLogger)
414 def _on_session_error(self, message):
415 self._errorLog.push_message(message)
418 @misc_utils.log_exception(_moduleLogger)
420 if self._defaultCredentials != self._curentCredentials:
421 self._show_account_dialog()
422 self._defaultCredentials = self._curentCredentials
423 for tab in self._tabsContents:
427 @misc_utils.log_exception(_moduleLogger)
428 def _on_logout(self):
429 for tab in self._tabsContents:
433 @misc_utils.log_exception(_moduleLogger)
434 def _on_recipients_changed(self):
435 if self._session.draft.get_num_contacts() == 0:
438 if self._smsEntryDialog is None:
440 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
444 @QtCore.pyqtSlot(bool)
445 @misc_utils.log_exception(_moduleLogger)
446 def _on_login_requested(self, checked = True):
447 if self._credentialsDialog is None:
449 self._credentialsDialog = dialogs.CredentialsDialog()
450 username, password = self._credentialsDialog.run(
451 self._defaultCredentials[0], self._defaultCredentials[1], self.window
453 self._curentCredentials = username, password
454 self._session.login(username, password)
456 @QtCore.pyqtSlot(int)
457 @misc_utils.log_exception(_moduleLogger)
458 def _on_tab_changed(self, index):
459 self._initialize_tab(index)
462 @QtCore.pyqtSlot(bool)
463 @misc_utils.log_exception(_moduleLogger)
464 def _on_refresh(self, checked = True):
465 index = self._tabWidget.currentIndex()
466 self._tabsContents[index].refresh(force=True)
469 @QtCore.pyqtSlot(bool)
470 @misc_utils.log_exception(_moduleLogger)
471 def _on_import(self, checked = True):
472 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
476 shutil.copy2(csvName, self._app.fsContactsPath)
477 self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
480 @QtCore.pyqtSlot(bool)
481 @misc_utils.log_exception(_moduleLogger)
482 def _on_account(self, checked = True):
483 self._show_account_dialog()
486 @QtCore.pyqtSlot(bool)
487 @misc_utils.log_exception(_moduleLogger)
488 def _on_close_window(self, checked = True):
493 app = QtGui.QApplication([])
494 handle = Dialcentral(app)
499 if __name__ == "__main__":
502 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
503 logging.basicConfig(level=logging.DEBUG, format=logFormat)
505 os.makedirs(constants._data_path_)