Adding some todos and bugs
[gc-dialer] / src / dc_glade.py
index 4b86a93..e9e30c6 100755 (executable)
@@ -18,12 +18,16 @@ You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 
-@bug Need to add unit tests
-@todo Look into an actor system
+@todo Try gogol's bigger tree view items
+@todo Try gogol's wrapping for messages
+@bug Does special notifiers even work?
+@bug Messaging UI is bad(?)
+@bug Not logging back in on network reconnect
+
+@todo Figure out how to integrate with the Maemo contacts app
 @bug Session timeouts are bad, possible solutions:
        @li For every X minutes, if logged in, attempt login
        @li Restructure so code handling login/dial/sms is beneath everything else and login attempts are made if those fail
-@todo Can't text from dialpad (so can't do any arbitrary number texts)
 @todo Add logging support to make debugging issues for people a lot easier
 """
 
@@ -70,9 +74,9 @@ def display_error_message(msg):
 class Dialcentral(object):
 
        _glade_files = [
-               '/usr/lib/dialcentral/dialcentral.glade',
                os.path.join(os.path.dirname(__file__), "dialcentral.glade"),
                os.path.join(os.path.dirname(__file__), "../lib/dialcentral.glade"),
+               '/usr/lib/dialcentral/dialcentral.glade',
        ]
 
        KEYPAD_TAB = 0
@@ -86,16 +90,12 @@ class Dialcentral(object):
        GV_BACKEND = 2
        BACKENDS = (NULL_BACKEND, GC_BACKEND, GV_BACKEND)
 
-       _data_path = os.path.join(os.path.expanduser("~"), ".dialcentral")
-       _user_settings = "%s/settings.ini" % _data_path
-
        def __init__(self):
                self._initDone = False
                self._connection = None
                self._osso = None
                self._clipboard = gtk.clipboard_get()
 
-               self._deviceIsOnline = True
                self._credentials = ("", "")
                self._selectedBackendId = self.NULL_BACKEND
                self._defaultBackendId = self.GC_BACKEND
@@ -105,6 +105,9 @@ class Dialcentral(object):
                self._messagesViews = None
                self._recentViews = None
                self._contactsViews = None
+               self._alarmHandler = None
+               self._ledHandler = None
+               self._originalCurrentLabels = []
 
                for path in self._glade_files:
                        if os.path.isfile(path):
@@ -135,9 +138,16 @@ class Dialcentral(object):
                                self._widgetTree.get_widget("callbackcombo").get_child().set_property('hildon-input-mode', (1 << 4))
                        except TypeError, e:
                                warnings.warn(e.message)
-                       hildon.hildon_helper_set_thumb_scrollbar(self._widgetTree.get_widget('recent_scrolledwindow'), True)
-                       hildon.hildon_helper_set_thumb_scrollbar(self._widgetTree.get_widget('message_scrolledwindow'), True)
-                       hildon.hildon_helper_set_thumb_scrollbar(self._widgetTree.get_widget('contacts_scrolledwindow'), True)
+                       for scrollingWidget in (
+                               'recent_scrolledwindow',
+                               'message_scrolledwindow',
+                               'contacts_scrolledwindow',
+                               "phoneSelectionMessage_scrolledwindow",
+                               "phonetypes_scrolledwindow",
+                               "smsMessage_scrolledwindow",
+                               "smsMessage_scrolledEntry",
+                       ):
+                               hildon.hildon_helper_set_thumb_scrollbar(self._widgetTree.get_widget(scrollingWidget), True)
 
                        gtkMenu = self._widgetTree.get_widget("dialpad_menubar")
                        menu = gtk.Menu()
@@ -151,10 +161,9 @@ class Dialcentral(object):
                else:
                        pass # warnings.warn("No Hildon", UserWarning, 2)
 
-               if hildon is not None:
-                       self._window.set_title("Keypad")
-               else:
-                       self._window.set_title("%s - Keypad" % constants.__pretty_app_name__)
+               # If under hildon, rely on the application name being shown
+               if hildon is None:
+                       self._window.set_title("%s" % constants.__pretty_app_name__)
 
                callbackMapping = {
                        "on_dialpad_quit": self._on_close,
@@ -165,6 +174,13 @@ class Dialcentral(object):
                self._window.set_default_size(800, 300)
                self._window.show_all()
 
+               self._loginSink = gtk_toolbox.threaded_stage(
+                       gtk_toolbox.comap(
+                               self.attempt_login,
+                               gtk_toolbox.null_sink(),
+                       )
+               )
+
                backgroundSetup = threading.Thread(target=self._idle_setup)
                backgroundSetup.setDaemon(True)
                backgroundSetup.start()
@@ -205,6 +221,19 @@ class Dialcentral(object):
                        else:
                                pass # warnings.warn("No OSSO", UserWarning, 2)
 
+                       try:
+                               import alarm_handler
+                               self._alarmHandler = alarm_handler.AlarmHandler()
+                       except ImportError:
+                               alarm_handler = None
+                       except Exception:
+                               with gtk_toolbox.gtk_lock():
+                                       self._errorDisplay.push_exception()
+                               alarm_handler = None
+                       if hildon is not None:
+                               import led_handler
+                               self._ledHandler = led_handler.LedHandler()
+
                        # Setup maemo specifics
                        try:
                                import conic
@@ -222,16 +251,15 @@ class Dialcentral(object):
                        import gv_backend
                        import gc_backend
                        import file_backend
-                       import evo_backend
                        import gc_views
 
                        try:
-                               os.makedirs(self._data_path)
+                               os.makedirs(constants._data_path_)
                        except OSError, e:
                                if e.errno != 17:
                                        raise
-                       gcCookiePath = os.path.join(self._data_path, "gc_cookies.txt")
-                       gvCookiePath = os.path.join(self._data_path, "gv_cookies.txt")
+                       gcCookiePath = os.path.join(constants._data_path_, "gc_cookies.txt")
+                       gvCookiePath = os.path.join(constants._data_path_, "gv_cookies.txt")
                        self._defaultBackendId = self._guess_preferred_backend((
                                (self.GC_BACKEND, gcCookiePath),
                                (self.GV_BACKEND, gvCookiePath),
@@ -250,12 +278,14 @@ class Dialcentral(object):
                                })
                                self._accountViews.update({
                                        self.GC_BACKEND: gc_views.AccountInfo(
-                                               self._widgetTree, self._phoneBackends[self.GC_BACKEND], self._errorDisplay
+                                               self._widgetTree, self._phoneBackends[self.GC_BACKEND], None, self._errorDisplay
                                        ),
                                        self.GV_BACKEND: gc_views.AccountInfo(
-                                               self._widgetTree, self._phoneBackends[self.GV_BACKEND], self._errorDisplay
+                                               self._widgetTree, self._phoneBackends[self.GV_BACKEND], self._alarmHandler, self._errorDisplay
                                        ),
                                })
+                               self._accountViews[self.GC_BACKEND].save_everything = lambda *args: None
+                               self._accountViews[self.GV_BACKEND].save_everything = self._save_settings
                                self._recentViews.update({
                                        self.GC_BACKEND: gc_views.RecentCallsView(
                                                self._widgetTree, self._phoneBackends[self.GC_BACKEND], self._errorDisplay
@@ -279,8 +309,7 @@ class Dialcentral(object):
                                        ),
                                })
 
-                       evoBackend = evo_backend.EvolutionAddressBook()
-                       fsContactsPath = os.path.join(self._data_path, "contacts")
+                       fsContactsPath = os.path.join(constants._data_path_, "contacts")
                        fileBackend = file_backend.FilesystemAddressBookFactory(fsContactsPath)
                        for backendId in (self.GV_BACKEND, self.GC_BACKEND):
                                self._dialpads[backendId].number_selected = self._select_action
@@ -290,7 +319,6 @@ class Dialcentral(object):
 
                                addressBooks = [
                                        self._phoneBackends[backendId],
-                                       evoBackend,
                                        fileBackend,
                                ]
                                mergedBook = gc_views.MergedAddressBook(addressBooks, gc_views.MergedAddressBook.advanced_lastname_sorter)
@@ -300,28 +328,36 @@ class Dialcentral(object):
 
                        callbackMapping = {
                                "on_paste": self._on_paste,
-                               "on_refresh": self._on_refresh,
+                               "on_refresh": self._on_menu_refresh,
                                "on_clearcookies_clicked": self._on_clearcookies_clicked,
                                "on_notebook_switch_page": self._on_notebook_switch_page,
                                "on_about_activate": self._on_about_activate,
                        }
                        self._widgetTree.signal_autoconnect(callbackMapping)
 
+                       with gtk_toolbox.gtk_lock():
+                               self._originalCurrentLabels = [
+                                       self._notebook.get_tab_label(self._notebook.get_nth_page(pageIndex)).get_text()
+                                       for pageIndex in xrange(self._notebook.get_n_pages())
+                               ]
+                               self._notebookTapHandler = gtk_toolbox.TapOrHold(self._notebook)
+                               self._notebookTapHandler.enable()
+                       self._notebookTapHandler.on_tap = self._reset_tab_refresh
+                       self._notebookTapHandler.on_hold = self._on_tab_refresh
+                       self._notebookTapHandler.on_holding = self._set_tab_refresh
+                       self._notebookTapHandler.on_cancel = self._reset_tab_refresh
+
                        self._initDone = True
 
                        config = ConfigParser.SafeConfigParser()
-                       config.read(self._user_settings)
+                       config.read(constants._user_settings_)
                        with gtk_toolbox.gtk_lock():
                                self.load_settings(config)
 
-                       gtk_toolbox.asynchronous_gtk_message(self._spawn_attempt_login)(2)
-               except StandardError, e:
-                       warnings.warn(e.message, UserWarning, 2)
-               except BaseException, e:
-                       try:
-                               warnings.warn(e.message, UserWarning, 2)
-                       finally:
-                               raise
+                       self._spawn_attempt_login(2)
+               except Exception, e:
+                       with gtk_toolbox.gtk_lock():
+                               self._errorDisplay.push_exception()
 
        def attempt_login(self, numOfAttempts = 10, force = False):
                """
@@ -332,8 +368,6 @@ class Dialcentral(object):
                try:
                        assert 0 <= numOfAttempts, "That was pointless having 0 or less login attempts"
                        assert self._initDone, "Attempting login before app is fully loaded"
-                       if not self._deviceIsOnline:
-                               raise RuntimeError("Unable to login, device is not online")
 
                        serviceId = self.NULL_BACKEND
                        loggedIn = False
@@ -352,20 +386,16 @@ class Dialcentral(object):
                                self._change_loggedin_status(serviceId)
                except StandardError, e:
                        with gtk_toolbox.gtk_lock():
-                               self._errorDisplay.push_exception(e)
+                               self._errorDisplay.push_exception()
 
        def _spawn_attempt_login(self, *args):
-               backgroundLogin = threading.Thread(target=self.attempt_login, args=args)
-               backgroundLogin.setDaemon(True)
-               backgroundLogin.start()
+               self._loginSink.send(args)
 
        def refresh_session(self):
                """
                @note Thread agnostic
                """
                assert self._initDone, "Attempting login before app is fully loaded"
-               if not self._deviceIsOnline:
-                       raise RuntimeError("Unable to login, device is not online")
 
                loggedIn = False
                if not loggedIn:
@@ -411,10 +441,10 @@ class Dialcentral(object):
                for attemptCount in xrange(numOfAttempts):
                        if loggedIn:
                                break
-                       availableServices = {
-                               self.GV_BACKEND: "Google Voice",
-                               self.GC_BACKEND: "Grand Central",
-                       }
+                       availableServices = (
+                               (self.GV_BACKEND, "Google Voice"),
+                               (self.GC_BACKEND, "Grand Central"),
+                       )
                        with gtk_toolbox.gtk_lock():
                                credentials = self._credentialsDialog.request_credentials_from(
                                        availableServices, defaultCredentials = self._credentials
@@ -484,10 +514,21 @@ class Dialcentral(object):
                                for blob in blobs
                        )
                        self._credentials = tuple(creds)
+
+                       if self._alarmHandler is not None:
+                               self._alarmHandler.load_settings(config, "alarm")
+               except ConfigParser.NoOptionError, e:
+                       warnings.warn(
+                               "Settings file %s is missing section %s" % (
+                                       constants._user_settings_,
+                                       e.section,
+                               ),
+                               stacklevel=2
+                       )
                except ConfigParser.NoSectionError, e:
                        warnings.warn(
                                "Settings file %s is missing section %s" % (
-                                       self._user_settings,
+                                       constants._user_settings_,
                                        e.section,
                                ),
                                stacklevel=2
@@ -503,10 +544,18 @@ class Dialcentral(object):
                        sectionName = "%s - %s" % (backendId, view.name())
                        try:
                                view.load_settings(config, sectionName)
+                       except ConfigParser.NoOptionError, e:
+                               warnings.warn(
+                                       "Settings file %s is missing section %s" % (
+                                               constants._user_settings_,
+                                               e.section,
+                                       ),
+                                       stacklevel=2
+                               )
                        except ConfigParser.NoSectionError, e:
                                warnings.warn(
                                        "Settings file %s is missing section %s" % (
-                                               self._user_settings,
+                                               constants._user_settings_,
                                                e.section,
                                        ),
                                        stacklevel=2
@@ -521,6 +570,10 @@ class Dialcentral(object):
                for i, value in enumerate(self._credentials):
                        blob = base64.b64encode(value)
                        config.set(constants.__pretty_app_name__, "bin_blob_%i" % i, blob)
+               config.add_section("alarm")
+               if self._alarmHandler is not None:
+                       self._alarmHandler.save_settings(config, "alarm")
+
                for backendId, view in itertools.chain(
                        self._dialpads.iteritems(),
                        self._accountViews.iteritems(),
@@ -546,9 +599,22 @@ class Dialcentral(object):
                """
                config = ConfigParser.SafeConfigParser()
                self.save_settings(config)
-               with open(self._user_settings, "wb") as configFile:
+               with open(constants._user_settings_, "wb") as configFile:
                        config.write(configFile)
 
+       def _refresh_active_tab(self):
+               pageIndex = self._notebook.get_current_page()
+               if pageIndex == self.CONTACTS_TAB:
+                       self._contactsViews[self._selectedBackendId].update(force=True)
+               elif pageIndex == self.RECENT_TAB:
+                       self._recentViews[self._selectedBackendId].update(force=True)
+               elif pageIndex == self.MESSAGES_TAB:
+                       self._messagesViews[self._selectedBackendId].update(force=True)
+
+               if pageIndex in (self.RECENT_TAB, self.MESSAGES_TAB):
+                       if self._ledHandler is not None:
+                               self._ledHandler.off()
+
        def _on_close(self, *args, **kwds):
                try:
                        if self._osso is not None:
@@ -587,11 +653,9 @@ class Dialcentral(object):
                bearer = event.get_bearer_type()
 
                if status == conic.STATUS_CONNECTED:
-                       self._deviceIsOnline = True
                        if self._initDone:
                                self._spawn_attempt_login(2)
                elif status == conic.STATUS_DISCONNECTED:
-                       self._deviceIsOnline = False
                        if self._initDone:
                                self._defaultBackendId = self._selectedBackendId
                                self._change_loggedin_status(self.NULL_BACKEND)
@@ -625,30 +689,50 @@ class Dialcentral(object):
 
                self._spawn_attempt_login(2, True)
 
-       def _on_notebook_switch_page(self, notebook, page, page_num):
-               if page_num == self.RECENT_TAB:
-                       self._recentViews[self._selectedBackendId].update()
-               elif page_num == self.MESSAGES_TAB:
-                       self._messagesViews[self._selectedBackendId].update()
-               elif page_num == self.CONTACTS_TAB:
+       def _on_notebook_switch_page(self, notebook, page, pageIndex):
+               self._reset_tab_refresh()
+
+               didRecentUpdate = False
+               didMessagesUpdate = False
+
+               if pageIndex == self.RECENT_TAB:
+                       didRecentUpdate = self._recentViews[self._selectedBackendId].update()
+               elif pageIndex == self.MESSAGES_TAB:
+                       didMessagesUpdate = self._messagesViews[self._selectedBackendId].update()
+               elif pageIndex == self.CONTACTS_TAB:
                        self._contactsViews[self._selectedBackendId].update()
-               elif page_num == self.ACCOUNT_TAB:
+               elif pageIndex == self.ACCOUNT_TAB:
                        self._accountViews[self._selectedBackendId].update()
 
-               tabTitle = self._notebook.get_tab_label(self._notebook.get_nth_page(page_num)).get_text()
-               if hildon is not None:
-                       self._window.set_title(tabTitle)
-               else:
-                       self._window.set_title("%s - %s" % (constants.__pretty_app_name__, tabTitle))
+               if didRecentUpdate or didMessagesUpdate:
+                       if self._ledHandler is not None:
+                               self._ledHandler.off()
+
+       def _set_tab_refresh(self, *args):
+               pageIndex = self._notebook.get_current_page()
+               child = self._notebook.get_nth_page(pageIndex)
+               self._notebook.get_tab_label(child).set_text("Refresh?")
+               return False
+
+       def _reset_tab_refresh(self, *args):
+               pageIndex = self._notebook.get_current_page()
+               child = self._notebook.get_nth_page(pageIndex)
+               self._notebook.get_tab_label(child).set_text(self._originalCurrentLabels[pageIndex])
+               return False
+
+       def _on_tab_refresh(self, *args):
+               self._refresh_active_tab()
+               self._reset_tab_refresh()
+               return False
 
        def _on_sms_clicked(self, number, message):
-               assert number
-               assert message
+               assert number, "No number specified"
+               assert message, "Empty message"
                try:
                        loggedIn = self._phoneBackends[self._selectedBackendId].is_authed()
-               except RuntimeError, e:
+               except StandardError, e:
                        loggedIn = False
-                       self._errorDisplay.push_exception(e)
+                       self._errorDisplay.push_exception()
                        return
 
                if not loggedIn:
@@ -661,18 +745,21 @@ class Dialcentral(object):
                try:
                        self._phoneBackends[self._selectedBackendId].send_sms(number, message)
                        dialed = True
-               except RuntimeError, e:
-                       self._errorDisplay.push_exception(e)
+               except StandardError, e:
+                       self._errorDisplay.push_exception()
                except ValueError, e:
-                       self._errorDisplay.push_exception(e)
+                       self._errorDisplay.push_exception()
+
+               if dialed:
+                       self._dialpads[self._selectedBackendId].clear()
 
        def _on_dial_clicked(self, number):
-               assert number
+               assert number, "No number to call"
                try:
                        loggedIn = self._phoneBackends[self._selectedBackendId].is_authed()
-               except RuntimeError, e:
+               except StandardError, e:
                        loggedIn = False
-                       self._errorDisplay.push_exception(e)
+                       self._errorDisplay.push_exception()
                        return
 
                if not loggedIn:
@@ -683,25 +770,19 @@ class Dialcentral(object):
 
                dialed = False
                try:
-                       assert self._phoneBackends[self._selectedBackendId].get_callback_number() != ""
+                       assert self._phoneBackends[self._selectedBackendId].get_callback_number() != "", "No callback number specified"
                        self._phoneBackends[self._selectedBackendId].dial(number)
                        dialed = True
-               except RuntimeError, e:
-                       self._errorDisplay.push_exception(e)
+               except StandardError, e:
+                       self._errorDisplay.push_exception()
                except ValueError, e:
-                       self._errorDisplay.push_exception(e)
+                       self._errorDisplay.push_exception()
 
                if dialed:
                        self._dialpads[self._selectedBackendId].clear()
 
-       def _on_refresh(self, *args):
-               page_num = self._notebook.get_current_page()
-               if page_num == self.CONTACTS_TAB:
-                       self._contactsViews[self._selectedBackendId].update(force=True)
-               elif page_num == self.RECENT_TAB:
-                       self._recentViews[self._selectedBackendId].update(force=True)
-               elif page_num == self.MESSAGES_TAB:
-                       self._messagesViews[self._selectedBackendId].update(force=True)
+       def _on_menu_refresh(self, *args):
+               self._refresh_active_tab()
 
        def _on_paste(self, *args):
                contents = self._clipboard.wait_for_text()
@@ -712,7 +793,7 @@ class Dialcentral(object):
                dlg.set_name(constants.__pretty_app_name__)
                dlg.set_version(constants.__version__)
                dlg.set_copyright("Copyright 2008 - LGPL")
-               dlg.set_comments("Dialer is designed to interface with your Google Grandcentral account.  This application is not affiliated with Google or Grandcentral in any way")
+               dlg.set_comments("Dialcentral is a touch screen enhanced interface to your GoogleVoice/Grandcentral account.  This application is not affiliated with Google in any way")
                dlg.set_website("http://gc-dialer.garage.maemo.org/")
                dlg.set_authors(["<z2n@merctech.com>", "Eric Warnke <ericew@gmail.com>", "Ed Page <edpage@byu.net>"])
                dlg.run()
@@ -731,7 +812,10 @@ def run_doctest():
 
 
 def run_dialpad():
+       _lock_file = os.path.join(constants._data_path_, ".lock")
+       #with gtk_toolbox.flock(_lock_file, 0):
        gtk.gdk.threads_init()
+
        if hildon is not None:
                gtk.set_application_name(constants.__pretty_app_name__)
        handle = Dialcentral()