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()
42 self._mainWindow = None
44 self._fullscreenAction = QtGui.QAction(None)
45 self._fullscreenAction.setText("Fullscreen")
46 self._fullscreenAction.setCheckable(True)
47 self._fullscreenAction.setShortcut(QtGui.QKeySequence("CTRL+Enter"))
48 self._fullscreenAction.toggled.connect(self._on_toggle_fullscreen)
50 self._logAction = QtGui.QAction(None)
51 self._logAction.setText("Log")
52 self._logAction.setShortcut(QtGui.QKeySequence("CTRL+l"))
53 self._logAction.triggered.connect(self._on_log)
55 self._quitAction = QtGui.QAction(None)
56 self._quitAction.setText("Quit")
57 self._quitAction.setShortcut(QtGui.QKeySequence("CTRL+q"))
58 self._quitAction.triggered.connect(self._on_quit)
60 self._app.lastWindowClosed.connect(self._on_app_quit)
61 self._mainWindow = MainWindow(None, self)
62 self._mainWindow.window.destroyed.connect(self._on_child_close)
66 self._mainWindow.show()
67 self._idleDelay = QtCore.QTimer()
68 self._idleDelay.setSingleShot(True)
69 self._idleDelay.setInterval(0)
70 self._idleDelay.timeout.connect(lambda: self._mainWindow.start())
71 self._idleDelay.start()
73 def load_settings(self):
75 config = ConfigParser.SafeConfigParser()
76 config.read(constants._user_settings_)
78 _moduleLogger.info("No settings")
81 _moduleLogger.info("Settings were corrupt")
83 except ConfigParser.MissingSectionHeaderError:
84 _moduleLogger.info("Settings were corrupt")
87 _moduleLogger.exception("Unknown loading error")
94 config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
95 for i in xrange(len(self._mainWindow.get_default_credentials()))
97 isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
98 tabIndex = config.getint(constants.__pretty_app_name__, "tab")
99 except ConfigParser.NoOptionError, e:
101 "Settings file %s is missing option %s" % (
102 constants._user_settings_,
106 except ConfigParser.NoSectionError, e:
108 "Settings file %s is missing section %s" % (
109 constants._user_settings_,
115 _moduleLogger.exception("Unknown loading error")
119 base64.b64decode(blob)
122 self._mainWindow.set_default_credentials(*creds)
123 self._fullscreenAction.setChecked(isFullscreen)
124 self._mainWindow.set_current_tab(tabIndex)
125 self._mainWindow.load_settings(config)
127 def save_settings(self):
128 _moduleLogger.info("Saving settings")
129 config = ConfigParser.SafeConfigParser()
131 config.add_section(constants.__pretty_app_name__)
132 config.set(constants.__pretty_app_name__, "tab", str(self._mainWindow.get_current_tab()))
133 config.set(constants.__pretty_app_name__, "fullscreen", str(self._fullscreenAction.isChecked()))
134 for i, value in enumerate(self._mainWindow.get_default_credentials()):
135 blob = base64.b64encode(value)
136 config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
138 self._mainWindow.save_settings(config)
140 with open(constants._user_settings_, "wb") as configFile:
141 config.write(configFile)
143 def get_icon(self, name):
144 if self._dataPath is None:
145 for path in self._DATA_PATHS:
146 if os.path.exists(os.path.join(path, name)):
147 self._dataPath = path
149 if self._dataPath is not None:
150 icon = QtGui.QIcon(os.path.join(self._dataPath, name))
156 def fsContactsPath(self):
157 return os.path.join(constants._data_path_, "contacts")
160 def fullscreenAction(self):
161 return self._fullscreenAction
165 return self._logAction
168 def quitAction(self):
169 return self._quitAction
171 def _close_windows(self):
172 if self._mainWindow is not None:
174 self._mainWindow.window.destroyed.disconnect(self._on_child_close)
175 self._mainWindow.close()
176 self._mainWindow = None
179 @QtCore.pyqtSlot(bool)
180 @misc_utils.log_exception(_moduleLogger)
181 def _on_app_quit(self, checked = False):
182 if self._mainWindow is not None:
184 self._mainWindow.destroy()
186 @QtCore.pyqtSlot(QtCore.QObject)
187 @misc_utils.log_exception(_moduleLogger)
188 def _on_child_close(self, obj = None):
189 if self._mainWindow is not None:
191 self._mainWindow = None
194 @QtCore.pyqtSlot(bool)
195 @misc_utils.log_exception(_moduleLogger)
196 def _on_toggle_fullscreen(self, checked = False):
197 for window in self._walk_children():
198 window.set_fullscreen(checked)
201 @QtCore.pyqtSlot(bool)
202 @misc_utils.log_exception(_moduleLogger)
203 def _on_log(self, checked = False):
204 with open(constants._user_logpath_, "r") as f:
205 logLines = f.xreadlines()
206 log = "".join(logLines)
207 self._clipboard.setText(log)
210 @QtCore.pyqtSlot(bool)
211 @misc_utils.log_exception(_moduleLogger)
212 def _on_quit(self, checked = False):
213 self._close_windows()
216 class DelayedWidget(object):
218 def __init__(self, app, settingsNames):
219 self._layout = QtGui.QVBoxLayout()
220 self._layout.setContentsMargins(0, 0, 0, 0)
221 self._widget = QtGui.QWidget()
222 self._widget.setContentsMargins(0, 0, 0, 0)
223 self._widget.setLayout(self._layout)
224 self._settings = dict((name, "") for name in settingsNames)
227 self._isEnabled = True
234 return self._child is not None
236 def set_child(self, child):
237 if self._child is not None:
238 self._layout.removeWidget(self._child.toplevel)
240 if self._child is not None:
241 self._layout.addWidget(self._child.toplevel)
243 self._child.set_settings(self._settings)
248 self._child.disable()
251 self._isEnabled = True
252 if self._child is not None:
256 self._isEnabled = False
257 if self._child is not None:
258 self._child.disable()
261 if self._child is not None:
264 def refresh(self, force=True):
265 if self._child is not None:
266 self._child.refresh(force)
268 def get_settings(self):
269 if self._child is not None:
270 return self._child.get_settings()
272 return self._settings
274 def set_settings(self, settings):
275 if self._child is not None:
276 self._child.set_settings(settings)
278 self._settings = settings
281 def _tab_factory(tab, app, session, errorLog):
283 return gv_views.__dict__[tab](app, session, errorLog)
286 class MainWindow(object):
300 assert len(_TAB_TITLES) == MAX_TABS
308 assert len(_TAB_ICONS) == MAX_TABS
311 functools.partial(_tab_factory, "Dialpad"),
312 functools.partial(_tab_factory, "History"),
313 functools.partial(_tab_factory, "Messages"),
314 functools.partial(_tab_factory, "Contacts"),
316 assert len(_TAB_CLASS) == MAX_TABS
318 # Hack to allow delay importing/loading of tabs
319 _TAB_SETTINGS_NAMES = [
323 ("selectedAddressbook", ),
325 assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
327 def __init__(self, parent, app):
329 self._session = session.Session(constants._data_path_)
330 self._session.error.connect(self._on_session_error)
331 self._session.loggedIn.connect(self._on_login)
332 self._session.loggedOut.connect(self._on_logout)
333 self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
334 self._defaultCredentials = "", ""
335 self._curentCredentials = "", ""
338 self._credentialsDialog = None
339 self._smsEntryDialog = None
340 self._accountDialog = None
342 self._errorLog = qui_utils.QErrorLog()
343 self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
345 self._tabsContents = [
346 DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
347 for i in xrange(self.MAX_TABS)
349 for tab in self._tabsContents:
352 self._tabWidget = QtGui.QTabWidget()
353 if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
354 self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
356 self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
357 for tabIndex, (tabTitle, tabIcon) in enumerate(
358 zip(self._TAB_TITLES, self._TAB_ICONS)
361 icon = self._app.get_icon(tabIcon)
363 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
365 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, "")
367 icon = self._app.get_icon(tabIcon)
368 self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
369 self._tabWidget.currentChanged.connect(self._on_tab_changed)
370 self._tabWidget.setContentsMargins(0, 0, 0, 0)
372 self._layout = QtGui.QVBoxLayout()
373 self._layout.setContentsMargins(0, 0, 0, 0)
374 self._layout.addWidget(self._errorDisplay.toplevel)
375 self._layout.addWidget(self._tabWidget)
377 centralWidget = QtGui.QWidget()
378 centralWidget.setLayout(self._layout)
379 centralWidget.setContentsMargins(0, 0, 0, 0)
381 self._window = QtGui.QMainWindow(parent)
382 self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
383 qui_utils.set_autorient(self._window, True)
384 qui_utils.set_stackable(self._window, True)
385 self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
386 self._window.setCentralWidget(centralWidget)
388 self._loginTabAction = QtGui.QAction(None)
389 self._loginTabAction.setText("Login")
390 self._loginTabAction.triggered.connect(self._on_login_requested)
392 self._importTabAction = QtGui.QAction(None)
393 self._importTabAction.setText("Import")
394 self._importTabAction.triggered.connect(self._on_import)
396 self._accountTabAction = QtGui.QAction(None)
397 self._accountTabAction.setText("Account")
398 self._accountTabAction.triggered.connect(self._on_account)
400 self._refreshTabAction = QtGui.QAction(None)
401 self._refreshTabAction.setText("Refresh")
402 self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
403 self._refreshTabAction.triggered.connect(self._on_refresh)
405 self._closeWindowAction = QtGui.QAction(None)
406 self._closeWindowAction.setText("Close")
407 self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
408 self._closeWindowAction.triggered.connect(self._on_close_window)
411 fileMenu = self._window.menuBar().addMenu("&File")
412 fileMenu.addAction(self._loginTabAction)
413 fileMenu.addAction(self._refreshTabAction)
415 toolsMenu = self._window.menuBar().addMenu("&Tools")
416 toolsMenu.addAction(self._accountTabAction)
417 toolsMenu.addAction(self._importTabAction)
419 self._window.addAction(self._closeWindowAction)
420 self._window.addAction(self._app.quitAction)
421 self._window.addAction(self._app.fullscreenAction)
423 fileMenu = self._window.menuBar().addMenu("&File")
424 fileMenu.addAction(self._loginTabAction)
425 fileMenu.addAction(self._refreshTabAction)
426 fileMenu.addAction(self._closeWindowAction)
427 fileMenu.addAction(self._app.quitAction)
429 viewMenu = self._window.menuBar().addMenu("&View")
430 viewMenu.addAction(self._app.fullscreenAction)
432 toolsMenu = self._window.menuBar().addMenu("&Tools")
433 toolsMenu.addAction(self._accountTabAction)
434 toolsMenu.addAction(self._importTabAction)
436 self._window.addAction(self._app.logAction)
438 self._initialize_tab(self._tabWidget.currentIndex())
439 self.set_fullscreen(self._app.fullscreenAction.isChecked())
445 def set_default_credentials(self, username, password):
446 self._defaultCredentials = username, password
448 def get_default_credentials(self):
449 return self._defaultCredentials
451 def walk_children(self):
455 assert self._session.state == self._session.LOGGEDOUT_STATE
456 if self._defaultCredentials != ("", ""):
457 username, password = self._defaultCredentials[0], self._defaultCredentials[1]
458 self._curentCredentials = username, password
459 self._session.login(username, password)
461 self._prompt_for_login()
464 for child in self.walk_children():
465 child.window.destroyed.disconnect(self._on_child_close)
470 if self._session.state != self._session.LOGGEDOUT_STATE:
471 self._session.logout()
473 def get_current_tab(self):
474 return self._currentTab
476 def set_current_tab(self, tabIndex):
477 self._tabWidget.setCurrentIndex(tabIndex)
479 def load_settings(self, config):
480 backendId = 2 # For backwards compatibility
481 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
482 sectionName = "%s - %s" % (backendId, tabTitle)
483 settings = self._tabsContents[tabIndex].get_settings()
484 for settingName in settings.iterkeys():
486 settingValue = config.get(sectionName, settingName)
487 except ConfigParser.NoOptionError, e:
489 "Settings file %s is missing section %s" % (
490 constants._user_settings_,
495 except ConfigParser.NoSectionError, e:
497 "Settings file %s is missing section %s" % (
498 constants._user_settings_,
504 _moduleLogger.exception("Unknown loading error")
506 settings[settingName] = settingValue
507 self._tabsContents[tabIndex].set_settings(settings)
509 def save_settings(self, config):
510 backendId = 2 # For backwards compatibility
511 for tabIndex, tabTitle in enumerate(self._TAB_TITLES):
512 sectionName = "%s - %s" % (backendId, tabTitle)
513 config.add_section(sectionName)
514 tabSettings = self._tabsContents[tabIndex].get_settings()
515 for settingName, settingValue in tabSettings.iteritems():
516 config.set(sectionName, settingName, settingValue)
520 for child in self.walk_children():
524 for child in self.walk_children():
528 def set_fullscreen(self, isFullscreen):
530 self._window.showFullScreen()
532 self._window.showNormal()
533 for child in self.walk_children():
534 child.set_fullscreen(isFullscreen)
536 def _initialize_tab(self, index):
537 assert index < self.MAX_TABS
538 if not self._tabsContents[index].has_child():
539 tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
540 self._tabsContents[index].set_child(tab)
541 self._tabsContents[index].refresh(force=False)
543 def _prompt_for_login(self):
544 if self._credentialsDialog is None:
546 self._credentialsDialog = dialogs.CredentialsDialog(self._app)
547 username, password = self._credentialsDialog.run(
548 self._defaultCredentials[0], self._defaultCredentials[1], self.window
550 self._curentCredentials = username, password
551 self._session.login(username, password)
553 def _show_account_dialog(self):
554 if self._accountDialog is None:
556 self._accountDialog = dialogs.AccountDialog(self._app)
557 self._accountDialog.set_callbacks(
558 self._session.get_callback_numbers(), self._session.get_callback_number()
560 self._accountDialog.accountNumber = self._session.get_account_number()
561 response = self._accountDialog.run()
562 if response == QtGui.QDialog.Accepted:
563 if self._accountDialog.doClear:
564 self._session.logout_and_clear()
566 callbackNumber = self._accountDialog.selectedCallback
567 self._session.set_callback_number(callbackNumber)
568 elif response == QtGui.QDialog.Rejected:
569 _moduleLogger.info("Cancelled")
571 _moduleLogger.info("Unknown response")
573 @QtCore.pyqtSlot(str)
574 @misc_utils.log_exception(_moduleLogger)
575 def _on_session_error(self, message):
576 self._errorLog.push_message(message)
579 @misc_utils.log_exception(_moduleLogger)
581 if self._defaultCredentials != self._curentCredentials:
582 self._show_account_dialog()
583 self._defaultCredentials = self._curentCredentials
584 for tab in self._tabsContents:
588 @misc_utils.log_exception(_moduleLogger)
589 def _on_logout(self):
590 for tab in self._tabsContents:
594 @misc_utils.log_exception(_moduleLogger)
595 def _on_recipients_changed(self):
596 if self._session.draft.get_num_contacts() == 0:
599 if self._smsEntryDialog is None:
601 self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
605 @QtCore.pyqtSlot(bool)
606 @misc_utils.log_exception(_moduleLogger)
607 def _on_login_requested(self, checked = True):
608 self._prompt_for_login()
610 @QtCore.pyqtSlot(int)
611 @misc_utils.log_exception(_moduleLogger)
612 def _on_tab_changed(self, index):
613 self._currentTab = index
614 self._initialize_tab(index)
617 @QtCore.pyqtSlot(bool)
618 @misc_utils.log_exception(_moduleLogger)
619 def _on_refresh(self, checked = True):
620 self._tabsContents[self._currentTab].refresh(force=True)
623 @QtCore.pyqtSlot(bool)
624 @misc_utils.log_exception(_moduleLogger)
625 def _on_import(self, checked = True):
626 csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
630 shutil.copy2(csvName, self._app.fsContactsPath)
631 self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
634 @QtCore.pyqtSlot(bool)
635 @misc_utils.log_exception(_moduleLogger)
636 def _on_account(self, checked = True):
637 self._show_account_dialog()
640 @QtCore.pyqtSlot(bool)
641 @misc_utils.log_exception(_moduleLogger)
642 def _on_close_window(self, checked = True):
647 app = QtGui.QApplication([])
648 handle = Dialcentral(app)
653 if __name__ == "__main__":
656 logFormat = '(%(relativeCreated)5d) %(levelname)-5s %(threadName)s.%(name)s.%(funcName)s: %(message)s'
657 logging.basicConfig(level=logging.DEBUG, format=logFormat)
659 os.makedirs(constants._data_path_)