Fixing an issue of escaping spaces which meant no line breaks, bad bad bad on my...
[gc-dialer] / src / dialcentral_qt.py
index 3afa873..20c3bf5 100755 (executable)
@@ -14,6 +14,7 @@ from PyQt4 import QtCore
 
 import constants
 from util import qtpie
+from util import qwrappers
 from util import qui_utils
 from util import misc as misc_utils
 
@@ -23,7 +24,30 @@ import session
 _moduleLogger = logging.getLogger(__name__)
 
 
-class Dialcentral(object):
+class LedWrapper(object):
+
+       def __init__(self):
+               self._ledHandler = None
+               self._init = False
+
+       def off(self):
+               self._lazy_init()
+               if self._ledHandler is not None:
+                       self._ledHandler.off()
+
+       def _lazy_init(self):
+               if self._init:
+                       return
+               self._init = True
+               try:
+                       import led_handler
+                       self._ledHandler = led_handler.LedHandler()
+               except Exception, e:
+                       _moduleLogger.exception('Unable to initialize LED Handling: "%s"' % str(e))
+                       self._ledHandler = None
+
+
+class Dialcentral(qwrappers.ApplicationWrapper):
 
        _DATA_PATHS = [
                os.path.join(os.path.dirname(__file__), "../share"),
@@ -31,38 +55,13 @@ class Dialcentral(object):
        ]
 
        def __init__(self, app):
-               self._app = app
-               self._recent = []
-               self._hiddenCategories = set()
-               self._hiddenUnits = {}
-               self._clipboard = QtGui.QApplication.clipboard()
                self._dataPath = None
+               self._aboutDialog = None
+               self._ledHandler = LedWrapper()
                self.notifyOnMissed = False
                self.notifyOnVoicemail = False
                self.notifyOnSms = False
 
-               self._mainWindow = None
-
-               self._fullscreenAction = QtGui.QAction(None)
-               self._fullscreenAction.setText("Fullscreen")
-               self._fullscreenAction.setCheckable(True)
-               self._fullscreenAction.setShortcut(QtGui.QKeySequence("CTRL+Enter"))
-               self._fullscreenAction.toggled.connect(self._on_toggle_fullscreen)
-
-               self._logAction = QtGui.QAction(None)
-               self._logAction.setText("Log")
-               self._logAction.setShortcut(QtGui.QKeySequence("CTRL+l"))
-               self._logAction.triggered.connect(self._on_log)
-
-               self._quitAction = QtGui.QAction(None)
-               self._quitAction.setText("Quit")
-               self._quitAction.setShortcut(QtGui.QKeySequence("CTRL+q"))
-               self._quitAction.triggered.connect(self._on_quit)
-
-               self._app.lastWindowClosed.connect(self._on_app_quit)
-               self._mainWindow = MainWindow(None, self)
-               self._mainWindow.window.destroyed.connect(self._on_child_close)
-
                try:
                        import alarm_handler
                        if alarm_handler.AlarmHandler is not alarm_handler._NoneAlarmHandler:
@@ -77,14 +76,7 @@ class Dialcentral(object):
                if self._alarmHandler is None:
                        _moduleLogger.info("No notification support")
 
-               self.load_settings()
-
-               self._mainWindow.show()
-               self._idleDelay = QtCore.QTimer()
-               self._idleDelay.setSingleShot(True)
-               self._idleDelay.setInterval(0)
-               self._idleDelay.timeout.connect(lambda: self._mainWindow.start())
-               self._idleDelay.start()
+               qwrappers.ApplicationWrapper.__init__(self, app, constants)
 
        def load_settings(self):
                try:
@@ -104,14 +96,16 @@ class Dialcentral(object):
 
                blobs = "", ""
                isFullscreen = False
+               isPortrait = qui_utils.screen_orientation() == QtCore.Qt.Vertical
                tabIndex = 0
                try:
-                       blobs = (
+                       blobs = [
                                config.get(constants.__pretty_app_name__, "bin_blob_%i" % i)
                                for i in xrange(len(self._mainWindow.get_default_credentials()))
-                       )
+                       ]
                        isFullscreen = config.getboolean(constants.__pretty_app_name__, "fullscreen")
                        tabIndex = config.getint(constants.__pretty_app_name__, "tab")
+                       isPortrait = config.getboolean(constants.__pretty_app_name__, "portrait")
                except ConfigParser.NoOptionError, e:
                        _moduleLogger.info(
                                "Settings file %s is missing option %s" % (
@@ -126,10 +120,8 @@ class Dialcentral(object):
                                        e.section,
                                ),
                        )
-                       return
                except Exception:
                        _moduleLogger.exception("Unknown loading error")
-                       return
 
                if self._alarmHandler is not None:
                        try:
@@ -151,10 +143,8 @@ class Dialcentral(object):
                                                e.section,
                                        ),
                                )
-                               return
                        except Exception:
                                _moduleLogger.exception("Unknown loading error")
-                               return
 
                creds = (
                        base64.b64decode(blob)
@@ -162,6 +152,7 @@ class Dialcentral(object):
                )
                self._mainWindow.set_default_credentials(*creds)
                self._fullscreenAction.setChecked(isFullscreen)
+               self._orientationAction.setChecked(isPortrait)
                self._mainWindow.set_current_tab(tabIndex)
                self._mainWindow.load_settings(config)
 
@@ -172,6 +163,7 @@ class Dialcentral(object):
                config.add_section(constants.__pretty_app_name__)
                config.set(constants.__pretty_app_name__, "tab", str(self._mainWindow.get_current_tab()))
                config.set(constants.__pretty_app_name__, "fullscreen", str(self._fullscreenAction.isChecked()))
+               config.set(constants.__pretty_app_name__, "portrait", str(self._orientationAction.isChecked()))
                for i, value in enumerate(self._mainWindow.get_default_credentials()):
                        blob = base64.b64encode(value)
                        config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
@@ -201,75 +193,35 @@ class Dialcentral(object):
                else:
                        return None
 
+       def _close_windows(self):
+               qwrappers.ApplicationWrapper._close_windows(self)
+               if self._aboutDialog  is not None:
+                       self._aboutDialog.close()
+
        @property
        def fsContactsPath(self):
                return os.path.join(constants._data_path_, "contacts")
 
        @property
-       def fullscreenAction(self):
-               return self._fullscreenAction
-
-       @property
-       def logAction(self):
-               return self._logAction
-
-       @property
-       def quitAction(self):
-               return self._quitAction
-
-       @property
        def alarmHandler(self):
                return self._alarmHandler
 
-       def _walk_children(self):
-               if self._mainWindow is not None:
-                       return (self._mainWindow, )
-               else:
-                       return ()
-
-       def _close_windows(self):
-               if self._mainWindow is not None:
-                       self.save_settings()
-                       self._mainWindow.window.destroyed.disconnect(self._on_child_close)
-                       self._mainWindow.close()
-                       self._mainWindow = None
-
-       @QtCore.pyqtSlot()
-       @QtCore.pyqtSlot(bool)
-       @misc_utils.log_exception(_moduleLogger)
-       def _on_app_quit(self, checked = False):
-               if self._mainWindow is not None:
-                       self.save_settings()
-                       self._mainWindow.destroy()
-
-       @QtCore.pyqtSlot(QtCore.QObject)
-       @misc_utils.log_exception(_moduleLogger)
-       def _on_child_close(self, obj = None):
-               if self._mainWindow is not None:
-                       self.save_settings()
-                       self._mainWindow = None
-
-       @QtCore.pyqtSlot()
-       @QtCore.pyqtSlot(bool)
-       @misc_utils.log_exception(_moduleLogger)
-       def _on_toggle_fullscreen(self, checked = False):
-               for window in self._walk_children():
-                       window.set_fullscreen(checked)
+       @property
+       def ledHandler(self):
+               return self._ledHandler
 
-       @QtCore.pyqtSlot()
-       @QtCore.pyqtSlot(bool)
-       @misc_utils.log_exception(_moduleLogger)
-       def _on_log(self, checked = False):
-               with open(constants._user_logpath_, "r") as f:
-                       logLines = f.xreadlines()
-                       log = "".join(logLines)
-                       self._clipboard.setText(log)
+       def _new_main_window(self):
+               return MainWindow(None, self)
 
        @QtCore.pyqtSlot()
        @QtCore.pyqtSlot(bool)
        @misc_utils.log_exception(_moduleLogger)
-       def _on_quit(self, checked = False):
-               self._close_windows()
+       def _on_about(self, checked = True):
+               with qui_utils.notify_error(self._errorLog):
+                       if self._aboutDialog is None:
+                               import dialogs
+                               self._aboutDialog = dialogs.AboutDialog(self)
+                       response = self._aboutDialog.run(self._mainWindow.window)
 
 
 class DelayedWidget(object):
@@ -306,6 +258,10 @@ class DelayedWidget(object):
                else:
                        self._child.disable()
 
+       @property
+       def child(self):
+               return self._child
+
        def enable(self):
                self._isEnabled = True
                if self._child is not None:
@@ -342,7 +298,7 @@ def _tab_factory(tab, app, session, errorLog):
        return gv_views.__dict__[tab](app, session, errorLog)
 
 
-class MainWindow(object):
+class MainWindow(qwrappers.WindowWrapper):
 
        KEYPAD_TAB = 0
        RECENT_TAB = 1
@@ -384,10 +340,10 @@ class MainWindow(object):
        assert len(_TAB_SETTINGS_NAMES) == MAX_TABS
 
        def __init__(self, parent, app):
-               self._app = app
-
-               self._errorLog = qui_utils.QErrorLog()
-               self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
+               qwrappers.WindowWrapper.__init__(self, parent, app)
+               self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
+               #self._freezer = qwrappers.AutoFreezeWindowFeature(self._app, self._window)
+               self._errorLog = self._app.errorLog
 
                self._session = session.Session(self._errorLog, constants._data_path_)
                self._session.error.connect(self._on_session_error)
@@ -401,7 +357,6 @@ class MainWindow(object):
                self._credentialsDialog = None
                self._smsEntryDialog = None
                self._accountDialog = None
-               self._aboutDialog = None
 
                self._tabsContents = [
                        DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
@@ -437,22 +392,8 @@ class MainWindow(object):
                self._tabWidget.currentChanged.connect(self._on_tab_changed)
                self._tabWidget.setContentsMargins(0, 0, 0, 0)
 
-               self._layout = QtGui.QVBoxLayout()
-               self._layout.setContentsMargins(0, 0, 0, 0)
-               self._layout.addWidget(self._errorDisplay.toplevel)
                self._layout.addWidget(self._tabWidget)
 
-               centralWidget = QtGui.QWidget()
-               centralWidget.setLayout(self._layout)
-               centralWidget.setContentsMargins(0, 0, 0, 0)
-
-               self._window = QtGui.QMainWindow(parent)
-               self._window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
-               qui_utils.set_autorient(self._window, True)
-               qui_utils.set_stackable(self._window, True)
-               self._window.setWindowTitle("%s" % constants.__pretty_app_name__)
-               self._window.setCentralWidget(centralWidget)
-
                self._loginTabAction = QtGui.QAction(None)
                self._loginTabAction.setText("Login")
                self._loginTabAction.triggered.connect(self._on_login_requested)
@@ -470,51 +411,18 @@ class MainWindow(object):
                self._refreshTabAction.setShortcut(QtGui.QKeySequence("CTRL+r"))
                self._refreshTabAction.triggered.connect(self._on_refresh)
 
-               self._aboutAction = QtGui.QAction(None)
-               self._aboutAction.setText("About")
-               self._aboutAction.triggered.connect(self._on_about)
-
-               self._closeWindowAction = QtGui.QAction(None)
-               self._closeWindowAction.setText("Close")
-               self._closeWindowAction.setShortcut(QtGui.QKeySequence("CTRL+w"))
-               self._closeWindowAction.triggered.connect(self._on_close_window)
+               fileMenu = self._window.menuBar().addMenu("&File")
+               fileMenu.addAction(self._loginTabAction)
+               fileMenu.addAction(self._refreshTabAction)
 
-               if constants.IS_MAEMO:
-                       fileMenu = self._window.menuBar().addMenu("&File")
-                       fileMenu.addAction(self._loginTabAction)
-                       fileMenu.addAction(self._refreshTabAction)
-
-                       toolsMenu = self._window.menuBar().addMenu("&Tools")
-                       toolsMenu.addAction(self._accountTabAction)
-                       toolsMenu.addAction(self._importTabAction)
-                       toolsMenu.addAction(self._aboutAction)
-
-                       self._window.addAction(self._closeWindowAction)
-                       self._window.addAction(self._app.quitAction)
-                       self._window.addAction(self._app.fullscreenAction)
-               else:
-                       fileMenu = self._window.menuBar().addMenu("&File")
-                       fileMenu.addAction(self._loginTabAction)
-                       fileMenu.addAction(self._refreshTabAction)
-                       fileMenu.addAction(self._closeWindowAction)
-                       fileMenu.addAction(self._app.quitAction)
-
-                       viewMenu = self._window.menuBar().addMenu("&View")
-                       viewMenu.addAction(self._app.fullscreenAction)
-
-                       toolsMenu = self._window.menuBar().addMenu("&Tools")
-                       toolsMenu.addAction(self._accountTabAction)
-                       toolsMenu.addAction(self._importTabAction)
-                       toolsMenu.addAction(self._aboutAction)
-
-               self._window.addAction(self._app.logAction)
+               toolsMenu = self._window.menuBar().addMenu("&Tools")
+               toolsMenu.addAction(self._accountTabAction)
+               toolsMenu.addAction(self._importTabAction)
+               toolsMenu.addAction(self._app.aboutAction)
 
                self._initialize_tab(self._tabWidget.currentIndex())
                self.set_fullscreen(self._app.fullscreenAction.isChecked())
-
-       @property
-       def window(self):
-               return self._window
+               self.set_orientation(self._app.orientationAction.isChecked())
 
        def set_default_credentials(self, username, password):
                self._defaultCredentials = username, password
@@ -523,9 +431,13 @@ class MainWindow(object):
                return self._defaultCredentials
 
        def walk_children(self):
-               return ()
+               if self._smsEntryDialog is not None:
+                       return (self._smsEntryDialog, )
+               else:
+                       return ()
 
        def start(self):
+               qwrappers.WindowWrapper.start(self)
                assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
                if self._defaultCredentials != ("", ""):
                        username, password = self._defaultCredentials[0], self._defaultCredentials[1]
@@ -535,20 +447,20 @@ class MainWindow(object):
                        self._prompt_for_login()
 
        def close(self):
-               for child in self.walk_children():
-                       child.window.destroyed.disconnect(self._on_child_close)
-                       child.close()
                for diag in (
                        self._credentialsDialog,
-                       self._smsEntryDialog,
                        self._accountDialog,
-                       self._aboutDialog,
                ):
                        if diag is not None:
                                diag.close()
+               for child in self.walk_children():
+                       child.window.destroyed.disconnect(self._on_child_close)
+                       child.window.closed.disconnect(self._on_child_close)
+                       child.close()
                self._window.close()
 
        def destroy(self):
+               qwrappers.WindowWrapper.destroy(self)
                if self._session.state != self._session.LOGGEDOUT_STATE:
                        self._session.logout()
 
@@ -597,23 +509,12 @@ class MainWindow(object):
                        for settingName, settingValue in tabSettings.iteritems():
                                config.set(sectionName, settingName, settingValue)
 
-       def show(self):
-               self._window.show()
-               for child in self.walk_children():
-                       child.show()
-
-       def hide(self):
-               for child in self.walk_children():
-                       child.hide()
-               self._window.hide()
-
-       def set_fullscreen(self, isFullscreen):
-               if isFullscreen:
-                       self._window.showFullScreen()
+       def set_orientation(self, isPortrait):
+               qwrappers.WindowWrapper.set_orientation(self, isPortrait)
+               if isPortrait:
+                       self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
                else:
-                       self._window.showNormal()
-               for child in self.walk_children():
-                       child.set_fullscreen(isFullscreen)
+                       self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
 
        def _initialize_tab(self, index):
                assert index < self.MAX_TABS, "Invalid tab"
@@ -626,9 +527,12 @@ class MainWindow(object):
                if self._credentialsDialog is None:
                        import dialogs
                        self._credentialsDialog = dialogs.CredentialsDialog(self._app)
-               username, password = self._credentialsDialog.run(
+               credentials = self._credentialsDialog.run(
                        self._defaultCredentials[0], self._defaultCredentials[1], self.window
                )
+               if credentials is None:
+                       return
+               username, password = credentials
                self._curentCredentials = username, password
                self._session.login(username, password)
 
@@ -648,10 +552,14 @@ class MainWindow(object):
                        self._session.get_callback_numbers(), self._session.get_callback_number()
                )
                self._accountDialog.accountNumber = self._session.get_account_number()
-               response = self._accountDialog.run()
+               response = self._accountDialog.run(self.window)
                if response == QtGui.QDialog.Accepted:
                        if self._accountDialog.doClear:
                                self._session.logout_and_clear()
+                               self._defaultCredentials = "", ""
+                               self._curentCredentials = "", ""
+                               for tab in self._tabsContents:
+                                       tab.disable()
                        else:
                                callbackNumber = self._accountDialog.selectedCallback
                                self._session.set_callback_number(callbackNumber)
@@ -660,6 +568,7 @@ class MainWindow(object):
                                self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
                                self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
                                self._app.notifyOnSms = self._accountDialog.notifyOnSms
+                               self._app.save_settings()
                elif response == QtGui.QDialog.Rejected:
                        _moduleLogger.info("Cancelled")
                else:
@@ -702,6 +611,13 @@ class MainWindow(object):
                        if self._smsEntryDialog is None:
                                import dialogs
                                self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
+                               self._smsEntryDialog.window.destroyed.connect(self._on_child_close)
+                               self._smsEntryDialog.window.closed.connect(self._on_child_close)
+                               self._smsEntryDialog.window.show()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_child_close(self, obj = None):
+               self._smsEntryDialog = None
 
        @QtCore.pyqtSlot()
        @QtCore.pyqtSlot(bool)
@@ -730,11 +646,13 @@ class MainWindow(object):
        def _on_import(self, checked = True):
                with qui_utils.notify_error(self._errorLog):
                        csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
+                       csvName = unicode(csvName)
                        if not csvName:
                                return
                        import shutil
                        shutil.copy2(csvName, self._app.fsContactsPath)
-                       self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
+                       if self._tabsContents[self.CONTACTS_TAB].has_child:
+                               self._tabsContents[self.CONTACTS_TAB].child.update_addressbooks()
 
        @QtCore.pyqtSlot()
        @QtCore.pyqtSlot(bool)
@@ -743,22 +661,6 @@ class MainWindow(object):
                with qui_utils.notify_error(self._errorLog):
                        self._show_account_dialog()
 
-       @QtCore.pyqtSlot()
-       @QtCore.pyqtSlot(bool)
-       @misc_utils.log_exception(_moduleLogger)
-       def _on_about(self, checked = True):
-               with qui_utils.notify_error(self._errorLog):
-                       if self._aboutDialog is None:
-                               import dialogs
-                               self._aboutDialog = dialogs.AboutDialog(self._app)
-                       response = self._aboutDialog.run()
-
-       @QtCore.pyqtSlot()
-       @QtCore.pyqtSlot(bool)
-       @misc_utils.log_exception(_moduleLogger)
-       def _on_close_window(self, checked = True):
-               self.close()
-
 
 def run():
        app = QtGui.QApplication([])