Bug with entering a text
[gc-dialer] / src / dialcentral_qt.py
index 4ca626f..bb377c4 100755 (executable)
@@ -21,7 +21,30 @@ import session
 
 
 _moduleLogger = logging.getLogger(__name__)
-IS_MAEMO = True
+
+
+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(object):
@@ -37,6 +60,11 @@ class Dialcentral(object):
                self._hiddenCategories = set()
                self._hiddenUnits = {}
                self._clipboard = QtGui.QApplication.clipboard()
+               self._dataPath = None
+               self._ledHandler = LedWrapper()
+               self.notifyOnMissed = False
+               self.notifyOnVoicemail = False
+               self.notifyOnSms = False
 
                self._mainWindow = None
 
@@ -60,6 +88,20 @@ class Dialcentral(object):
                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:
+                               self._alarmHandler = alarm_handler.AlarmHandler()
+                       else:
+                               self._alarmHandler = None
+               except (ImportError, OSError):
+                       self._alarmHandler = None
+               except Exception:
+                       _moduleLogger.exception("Notification failure")
+                       self._alarmHandler = None
+               if self._alarmHandler is None:
+                       _moduleLogger.info("No notification support")
+
                self.load_settings()
 
                self._mainWindow.show()
@@ -89,10 +131,10 @@ class Dialcentral(object):
                isFullscreen = False
                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")
                except ConfigParser.NoOptionError, e:
@@ -109,10 +151,31 @@ class Dialcentral(object):
                                        e.section,
                                ),
                        )
-                       return
                except Exception:
                        _moduleLogger.exception("Unknown loading error")
-                       return
+
+               if self._alarmHandler is not None:
+                       try:
+                               self._alarmHandler.load_settings(config, "alarm")
+                               self.notifyOnMissed = config.getboolean("2 - Account Info", "notifyOnMissed")
+                               self.notifyOnVoicemail = config.getboolean("2 - Account Info", "notifyOnVoicemail")
+                               self.notifyOnSms = config.getboolean("2 - Account Info", "notifyOnSms")
+                       except ConfigParser.NoOptionError, e:
+                               _moduleLogger.info(
+                                       "Settings file %s is missing option %s" % (
+                                               constants._user_settings_,
+                                               e.option,
+                                       ),
+                               )
+                       except ConfigParser.NoSectionError, e:
+                               _moduleLogger.info(
+                                       "Settings file %s is missing section %s" % (
+                                               constants._user_settings_,
+                                               e.section,
+                                       ),
+                               )
+                       except Exception:
+                               _moduleLogger.exception("Unknown loading error")
 
                creds = (
                        base64.b64decode(blob)
@@ -124,6 +187,7 @@ class Dialcentral(object):
                self._mainWindow.load_settings(config)
 
        def save_settings(self):
+               _moduleLogger.info("Saving settings")
                config = ConfigParser.SafeConfigParser()
 
                config.add_section(constants.__pretty_app_name__)
@@ -133,11 +197,31 @@ class Dialcentral(object):
                        blob = base64.b64encode(value)
                        config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
 
+               if self._alarmHandler is not None:
+                       config.add_section("alarm")
+                       self._alarmHandler.save_settings(config, "alarm")
+               config.add_section("2 - Account Info")
+               config.set("2 - Account Info", "notifyOnMissed", repr(self.notifyOnMissed))
+               config.set("2 - Account Info", "notifyOnVoicemail", repr(self.notifyOnVoicemail))
+               config.set("2 - Account Info", "notifyOnSms", repr(self.notifyOnSms))
+
                self._mainWindow.save_settings(config)
 
                with open(constants._user_settings_, "wb") as configFile:
                        config.write(configFile)
 
+       def get_icon(self, name):
+               if self._dataPath is None:
+                       for path in self._DATA_PATHS:
+                               if os.path.exists(os.path.join(path, name)):
+                                       self._dataPath = path
+                                       break
+               if self._dataPath is not None:
+                       icon = QtGui.QIcon(os.path.join(self._dataPath, name))
+                       return icon
+               else:
+                       return None
+
        @property
        def fsContactsPath(self):
                return os.path.join(constants._data_path_, "contacts")
@@ -154,8 +238,23 @@ class Dialcentral(object):
        def quitAction(self):
                return self._quitAction
 
+       @property
+       def alarmHandler(self):
+               return self._alarmHandler
+
+       @property
+       def ledHandler(self):
+               return self._ledHandler
+
+       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
@@ -164,13 +263,16 @@ class Dialcentral(object):
        @QtCore.pyqtSlot(bool)
        @misc_utils.log_exception(_moduleLogger)
        def _on_app_quit(self, checked = False):
-               self.save_settings()
-               self._mainWindow.destroy()
+               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):
-               self._mainWindow = None
+               if self._mainWindow is not None:
+                       self.save_settings()
+                       self._mainWindow = None
 
        @QtCore.pyqtSlot()
        @QtCore.pyqtSlot(bool)
@@ -199,7 +301,9 @@ class DelayedWidget(object):
 
        def __init__(self, app, settingsNames):
                self._layout = QtGui.QVBoxLayout()
+               self._layout.setContentsMargins(0, 0, 0, 0)
                self._widget = QtGui.QWidget()
+               self._widget.setContentsMargins(0, 0, 0, 0)
                self._widget.setLayout(self._layout)
                self._settings = dict((name, "") for name in settingsNames)
 
@@ -306,20 +410,23 @@ class MainWindow(object):
 
        def __init__(self, parent, app):
                self._app = app
-               self._session = session.Session(constants._data_path_)
+
+               self._errorLog = qui_utils.QErrorLog()
+               self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
+
+               self._session = session.Session(self._errorLog, constants._data_path_)
                self._session.error.connect(self._on_session_error)
                self._session.loggedIn.connect(self._on_login)
                self._session.loggedOut.connect(self._on_logout)
                self._session.draft.recipientsChanged.connect(self._on_recipients_changed)
                self._defaultCredentials = "", ""
                self._curentCredentials = "", ""
+               self._currentTab = 0
 
                self._credentialsDialog = None
                self._smsEntryDialog = None
                self._accountDialog = None
-
-               self._errorLog = qui_utils.QErrorLog()
-               self._errorDisplay = qui_utils.ErrorDisplay(self._errorLog)
+               self._aboutDialog = None
 
                self._tabsContents = [
                        DelayedWidget(self._app, self._TAB_SETTINGS_NAMES[i])
@@ -328,38 +435,41 @@ class MainWindow(object):
                for tab in self._tabsContents:
                        tab.disable()
 
-               # @bug Tab names too long, switch to icons
                self._tabWidget = QtGui.QTabWidget()
                if qui_utils.screen_orientation() == QtCore.Qt.Vertical:
                        self._tabWidget.setTabPosition(QtGui.QTabWidget.South)
                else:
                        self._tabWidget.setTabPosition(QtGui.QTabWidget.West)
-               _dataPath = None
+               defaultTabIconSize = self._tabWidget.iconSize()
+               defaultTabIconWidth, defaultTabIconHeight = defaultTabIconSize.width(), defaultTabIconSize.height()
                for tabIndex, (tabTitle, tabIcon) in enumerate(
                        zip(self._TAB_TITLES, self._TAB_ICONS)
                ):
-                       if _dataPath is None:
-                               for path in self._app._DATA_PATHS:
-                                       if os.path.exists(os.path.join(path, tabIcon)):
-                                               _dataPath = path
-                                               break
-                       if IS_MAEMO:
-                               if _dataPath is None:
-                                       self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
-                               else:
-                                       icon = QtGui.QIcon(os.path.join(_dataPath, tabIcon))
-                                       self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, "")
+                       icon = self._app.get_icon(tabIcon)
+                       if constants.IS_MAEMO and icon is not None:
+                               tabTitle = ""
+
+                       if icon is None:
+                               self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, tabTitle)
                        else:
-                               icon = QtGui.QIcon(os.path.join(_dataPath, tabIcon))
+                               iconSize = icon.availableSizes()[0]
+                               defaultTabIconWidth = max(defaultTabIconWidth, iconSize.width())
+                               defaultTabIconHeight = max(defaultTabIconHeight, iconSize.height())
                                self._tabWidget.addTab(self._tabsContents[tabIndex].toplevel, icon, tabTitle)
+               defaultTabIconWidth = max(defaultTabIconWidth, 32)
+               defaultTabIconHeight = max(defaultTabIconHeight, 32)
+               self._tabWidget.setIconSize(QtCore.QSize(defaultTabIconWidth, defaultTabIconHeight))
                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)
@@ -385,12 +495,16 @@ 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)
 
-               if IS_MAEMO:
+               if constants.IS_MAEMO:
                        fileMenu = self._window.menuBar().addMenu("&File")
                        fileMenu.addAction(self._loginTabAction)
                        fileMenu.addAction(self._refreshTabAction)
@@ -398,6 +512,7 @@ class MainWindow(object):
                        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)
@@ -415,6 +530,7 @@ class MainWindow(object):
                        toolsMenu = self._window.menuBar().addMenu("&Tools")
                        toolsMenu.addAction(self._accountTabAction)
                        toolsMenu.addAction(self._importTabAction)
+                       toolsMenu.addAction(self._aboutAction)
 
                self._window.addAction(self._app.logAction)
 
@@ -435,7 +551,7 @@ class MainWindow(object):
                return ()
 
        def start(self):
-               assert self._session.state == self._session.LOGGEDOUT_STATE
+               assert self._session.state == self._session.LOGGEDOUT_STATE, "Initialization messed up"
                if self._defaultCredentials != ("", ""):
                        username, password = self._defaultCredentials[0], self._defaultCredentials[1]
                        self._curentCredentials = username, password
@@ -447,6 +563,14 @@ class MainWindow(object):
                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()
                self._window.close()
 
        def destroy(self):
@@ -454,7 +578,7 @@ class MainWindow(object):
                        self._session.logout()
 
        def get_current_tab(self):
-               return self._tabWidget.currentIndex()
+               return self._currentTab
 
        def set_current_tab(self, tabIndex):
                self._tabWidget.setCurrentIndex(tabIndex)
@@ -517,7 +641,7 @@ class MainWindow(object):
                        child.set_fullscreen(isFullscreen)
 
        def _initialize_tab(self, index):
-               assert index < self.MAX_TABS
+               assert index < self.MAX_TABS, "Invalid tab"
                if not self._tabsContents[index].has_child():
                        tab = self._TAB_CLASS[index](self._app, self._session, self._errorLog)
                        self._tabsContents[index].set_child(tab)
@@ -537,11 +661,30 @@ class MainWindow(object):
                if self._accountDialog is None:
                        import dialogs
                        self._accountDialog = dialogs.AccountDialog(self._app)
+                       if self._app.alarmHandler is None:
+                               self._accountDialog.setIfNotificationsSupported(False)
+               if self._app.alarmHandler is not None:
+                       self._accountDialog.notifications = self._app.alarmHandler.isEnabled
+                       self._accountDialog.notificationTime = self._app.alarmHandler.recurrence
+                       self._accountDialog.notifyOnMissed = self._app.notifyOnMissed
+                       self._accountDialog.notifyOnVoicemail = self._app.notifyOnVoicemail
+                       self._accountDialog.notifyOnSms = self._app.notifyOnSms
+               self._accountDialog.set_callbacks(
+                       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()
+                       else:
+                               callbackNumber = self._accountDialog.selectedCallback
+                               self._session.set_callback_number(callbackNumber)
+                       if self._app.alarmHandler is not None:
+                               self._app.alarmHandler.apply_settings(self._accountDialog.notifications, self._accountDialog.notificationTime)
+                               self._app.notifyOnMissed = self._accountDialog.notifyOnMissed
+                               self._app.notifyOnVoicemail = self._accountDialog.notifyOnVoicemail
+                               self._app.notifyOnSms = self._accountDialog.notifyOnSms
                elif response == QtGui.QDialog.Rejected:
                        _moduleLogger.info("Cancelled")
                else:
@@ -550,68 +693,90 @@ class MainWindow(object):
        @QtCore.pyqtSlot(str)
        @misc_utils.log_exception(_moduleLogger)
        def _on_session_error(self, message):
-               self._errorLog.push_message(message)
+               with qui_utils.notify_error(self._errorLog):
+                       self._errorLog.push_error(message)
 
        @QtCore.pyqtSlot()
        @misc_utils.log_exception(_moduleLogger)
        def _on_login(self):
-               if self._defaultCredentials != self._curentCredentials:
-                       self._show_account_dialog()
-               self._defaultCredentials = self._curentCredentials
-               for tab in self._tabsContents:
-                       tab.enable()
+               with qui_utils.notify_error(self._errorLog):
+                       changedAccounts = self._defaultCredentials != self._curentCredentials
+                       noCallback = not self._session.get_callback_number()
+                       if changedAccounts or noCallback:
+                               self._show_account_dialog()
+
+                       self._defaultCredentials = self._curentCredentials
+
+                       for tab in self._tabsContents:
+                               tab.enable()
 
        @QtCore.pyqtSlot()
        @misc_utils.log_exception(_moduleLogger)
        def _on_logout(self):
-               for tab in self._tabsContents:
-                       tab.disable()
+               with qui_utils.notify_error(self._errorLog):
+                       for tab in self._tabsContents:
+                               tab.disable()
 
        @QtCore.pyqtSlot()
        @misc_utils.log_exception(_moduleLogger)
        def _on_recipients_changed(self):
-               if self._session.draft.get_num_contacts() == 0:
-                       return
+               with qui_utils.notify_error(self._errorLog):
+                       if self._session.draft.get_num_contacts() == 0:
+                               return
 
-               if self._smsEntryDialog is None:
-                       import dialogs
-                       self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
-               pass
+                       if self._smsEntryDialog is None:
+                               import dialogs
+                               self._smsEntryDialog = dialogs.SMSEntryWindow(self.window, self._app, self._session, self._errorLog)
 
        @QtCore.pyqtSlot()
        @QtCore.pyqtSlot(bool)
        @misc_utils.log_exception(_moduleLogger)
        def _on_login_requested(self, checked = True):
-               self._prompt_for_login()
+               with qui_utils.notify_error(self._errorLog):
+                       self._prompt_for_login()
 
        @QtCore.pyqtSlot(int)
        @misc_utils.log_exception(_moduleLogger)
        def _on_tab_changed(self, index):
-               self._initialize_tab(index)
+               with qui_utils.notify_error(self._errorLog):
+                       self._currentTab = index
+                       self._initialize_tab(index)
 
        @QtCore.pyqtSlot()
        @QtCore.pyqtSlot(bool)
        @misc_utils.log_exception(_moduleLogger)
        def _on_refresh(self, checked = True):
-               index = self._tabWidget.currentIndex()
-               self._tabsContents[index].refresh(force=True)
+               with qui_utils.notify_error(self._errorLog):
+                       self._tabsContents[self._currentTab].refresh(force=True)
 
        @QtCore.pyqtSlot()
        @QtCore.pyqtSlot(bool)
        @misc_utils.log_exception(_moduleLogger)
        def _on_import(self, checked = True):
-               csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
-               if not csvName:
-                       return
-               import shutil
-               shutil.copy2(csvName, self._app.fsContactsPath)
-               self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
+               with qui_utils.notify_error(self._errorLog):
+                       csvName = QtGui.QFileDialog.getOpenFileName(self._window, caption="Import", filter="CSV Files (*.csv)")
+                       if not csvName:
+                               return
+                       import shutil
+                       shutil.copy2(csvName, self._app.fsContactsPath)
+                       self._tabsContents[self.CONTACTS_TAB].update_addressbooks()
 
        @QtCore.pyqtSlot()
        @QtCore.pyqtSlot(bool)
        @misc_utils.log_exception(_moduleLogger)
        def _on_account(self, checked = True):
-               self._show_account_dialog()
+               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(self.window)
 
        @QtCore.pyqtSlot()
        @QtCore.pyqtSlot(bool)