Further cleanups after removing GrandCentral support
[gc-dialer] / src / dc_glade.py
index 87ab87e..bcefda0 100755 (executable)
@@ -17,14 +17,6 @@ Lesser General Public License for more details.
 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
-
-@todo Figure out how to integrate with the Maemo contacts app
-@todo Look into an actor system
-@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
 """
 
 
@@ -39,16 +31,11 @@ import ConfigParser
 import itertools
 import warnings
 
-import gobject
 import gtk
 import gtk.glade
 
-try:
-       import hildon
-except ImportError:
-       hildon = None
-
 import constants
+import hildonize
 import gtk_toolbox
 
 
@@ -71,9 +58,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
@@ -83,12 +70,8 @@ class Dialcentral(object):
        ACCOUNT_TAB = 4
 
        NULL_BACKEND = 0
-       GC_BACKEND = 1
        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
+       BACKENDS = (NULL_BACKEND, GV_BACKEND)
 
        def __init__(self):
                self._initDone = False
@@ -96,17 +79,18 @@ class Dialcentral(object):
                self._osso = None
                self._clipboard = gtk.clipboard_get()
 
-               self._deviceIsOnline = True
                self._credentials = ("", "")
                self._selectedBackendId = self.NULL_BACKEND
-               self._defaultBackendId = self.GC_BACKEND
+               self._defaultBackendId = self.GV_BACKEND
                self._phoneBackends = None
                self._dialpads = None
                self._accountViews = None
                self._messagesViews = None
                self._recentViews = None
                self._contactsViews = None
-               self._tabHoldTimeoutId = None
+               self._alarmHandler = None
+               self._ledHandler = None
+               self._originalCurrentLabels = []
 
                for path in self._glade_files:
                        if os.path.isfile(path):
@@ -122,40 +106,33 @@ class Dialcentral(object):
                self._errorDisplay = gtk_toolbox.ErrorDisplay(self._widgetTree)
                self._credentialsDialog = gtk_toolbox.LoginWindow(self._widgetTree)
 
-               self._app = None
                self._isFullScreen = False
-               if hildon is not None:
-                       self._app = hildon.Program()
-                       oldWindow = self._window
-                       self._window = hildon.Window()
-                       oldWindow.get_child().reparent(self._window)
-                       self._app.add_window(self._window)
+               self._app = hildonize.get_app_class()()
+               self._window = hildonize.hildonize_window(self._app, self._window)
+               hildonize.hildonize_text_entry(self._widgetTree.get_widget("usernameentry"))
+               hildonize.hildonize_password_entry(self._widgetTree.get_widget("passwordentry"))
+               hildonize.hildonize_combo_entry(self._widgetTree.get_widget("callbackcombo").get_child())
+
+               for scrollingWidget in (
+                       'recent_scrolledwindow',
+                       'message_scrolledwindow',
+                       'contacts_scrolledwindow',
+                       "phoneSelectionMessage_scrolledwindow",
+                       "phonetypes_scrolledwindow",
+                       "smsMessage_scrolledwindow",
+                       "smsMessage_scrolledEntry",
+               ):
+                       hildonize.set_thumb_scrollbar(self._widgetTree.get_widget(scrollingWidget))
 
-                       try:
-                               self._widgetTree.get_widget("usernameentry").set_property('hildon-input-mode', 7)
-                               self._widgetTree.get_widget("passwordentry").set_property('hildon-input-mode', 7|(1 << 29))
-                               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)
-
-                       gtkMenu = self._widgetTree.get_widget("dialpad_menubar")
-                       menu = gtk.Menu()
-                       for child in gtkMenu.get_children():
-                               child.reparent(menu)
-                       self._window.set_menu(menu)
-                       gtkMenu.destroy()
+               hildonize.hildonize_menu(self._window, self._widgetTree.get_widget("dialpad_menubar"))
 
+               if hildonize.IS_HILDON:
                        self._window.connect("key-press-event", self._on_key_press)
                        self._window.connect("window-state-event", self._on_window_state_change)
                else:
                        pass # warnings.warn("No Hildon", UserWarning, 2)
 
-               # If under hildon, rely on the application name being shown
-               if hildon is None:
-                       self._window.set_title("%s" % constants.__pretty_app_name__)
+               hildonize.set_application_title(self._window, "%s" % constants.__pretty_app_name__)
 
                callbackMapping = {
                        "on_dialpad_quit": self._on_close,
@@ -213,6 +190,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 hildonize.IS_HILDON:
+                               import led_handler
+                               self._ledHandler = led_handler.LedHandler()
+
                        # Setup maemo specifics
                        try:
                                import conic
@@ -228,83 +218,62 @@ class Dialcentral(object):
 
                        # Setup costly backends
                        import gv_backend
-                       import gc_backend
                        import file_backend
-                       import evo_backend
-                       import gc_views
+                       import gv_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")
-                       self._defaultBackendId = self._guess_preferred_backend((
-                               (self.GC_BACKEND, gcCookiePath),
-                               (self.GV_BACKEND, gvCookiePath),
-                       ))
+                       gvCookiePath = os.path.join(constants._data_path_, "gv_cookies.txt")
 
                        self._phoneBackends.update({
-                               self.GC_BACKEND: gc_backend.GCDialer(gcCookiePath),
                                self.GV_BACKEND: gv_backend.GVDialer(gvCookiePath),
                        })
                        with gtk_toolbox.gtk_lock():
-                               unifiedDialpad = gc_views.Dialpad(self._widgetTree, self._errorDisplay)
-                               unifiedDialpad.set_number("")
+                               unifiedDialpad = gv_views.Dialpad(self._widgetTree, self._errorDisplay)
                                self._dialpads.update({
-                                       self.GC_BACKEND: unifiedDialpad,
                                        self.GV_BACKEND: unifiedDialpad,
                                })
                                self._accountViews.update({
-                                       self.GC_BACKEND: gc_views.AccountInfo(
-                                               self._widgetTree, self._phoneBackends[self.GC_BACKEND], self._errorDisplay
-                                       ),
-                                       self.GV_BACKEND: gc_views.AccountInfo(
-                                               self._widgetTree, self._phoneBackends[self.GV_BACKEND], self._errorDisplay
+                                       self.GV_BACKEND: gv_views.AccountInfo(
+                                               self._widgetTree, self._phoneBackends[self.GV_BACKEND], self._alarmHandler, self._errorDisplay
                                        ),
                                })
+                               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
-                                       ),
-                                       self.GV_BACKEND: gc_views.RecentCallsView(
+                                       self.GV_BACKEND: gv_views.RecentCallsView(
                                                self._widgetTree, self._phoneBackends[self.GV_BACKEND], self._errorDisplay
                                        ),
                                })
                                self._messagesViews.update({
-                                       self.GC_BACKEND: null_views.MessagesView(self._widgetTree),
-                                       self.GV_BACKEND: gc_views.MessagesView(
+                                       self.GV_BACKEND: gv_views.MessagesView(
                                                self._widgetTree, self._phoneBackends[self.GV_BACKEND], self._errorDisplay
                                        ),
                                })
                                self._contactsViews.update({
-                                       self.GC_BACKEND: gc_views.ContactsView(
-                                               self._widgetTree, self._phoneBackends[self.GC_BACKEND], self._errorDisplay
-                                       ),
-                                       self.GV_BACKEND: gc_views.ContactsView(
+                                       self.GV_BACKEND: gv_views.ContactsView(
                                                self._widgetTree, self._phoneBackends[self.GV_BACKEND], self._errorDisplay
                                        ),
                                })
 
-                       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
-                               self._recentViews[backendId].number_selected = self._select_action
-                               self._messagesViews[backendId].number_selected = self._select_action
-                               self._contactsViews[backendId].number_selected = self._select_action
-
-                               addressBooks = [
-                                       self._phoneBackends[backendId],
-                                       evoBackend,
-                                       fileBackend,
-                               ]
-                               mergedBook = gc_views.MergedAddressBook(addressBooks, gc_views.MergedAddressBook.advanced_lastname_sorter)
-                               self._contactsViews[backendId].append(mergedBook)
-                               self._contactsViews[backendId].extend(addressBooks)
-                               self._contactsViews[backendId].open_addressbook(*self._contactsViews[backendId].get_addressbooks().next()[0][0:2])
+
+                       self._dialpads[self.GV_BACKEND].number_selected = self._select_action
+                       self._recentViews[self.GV_BACKEND].number_selected = self._select_action
+                       self._messagesViews[self.GV_BACKEND].number_selected = self._select_action
+                       self._contactsViews[self.GV_BACKEND].number_selected = self._select_action
+
+                       addressBooks = [
+                               self._phoneBackends[self.GV_BACKEND],
+                               fileBackend,
+                       ]
+                       mergedBook = gv_views.MergedAddressBook(addressBooks, gv_views.MergedAddressBook.advanced_lastname_sorter)
+                       self._contactsViews[self.GV_BACKEND].append(mergedBook)
+                       self._contactsViews[self.GV_BACKEND].extend(addressBooks)
+                       self._contactsViews[self.GV_BACKEND].open_addressbook(*self._contactsViews[self.GV_BACKEND].get_addressbooks().next()[0][0:2])
 
                        callbackMapping = {
                                "on_paste": self._on_paste,
@@ -314,24 +283,30 @@ class Dialcentral(object):
                                "on_about_activate": self._on_about_activate,
                        }
                        self._widgetTree.signal_autoconnect(callbackMapping)
-                       self._notebook.connect("button-press-event", self._on_tab_press)
-                       self._notebook.connect("button-release-event", self._on_tab_release)
+
+                       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)
 
                        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
+               except Exception, e:
+                       with gtk_toolbox.gtk_lock():
+                               self._errorDisplay.push_exception()
 
        def attempt_login(self, numOfAttempts = 10, force = False):
                """
@@ -342,8 +317,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
@@ -362,7 +335,7 @@ 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):
                self._loginSink.send(args)
@@ -372,8 +345,6 @@ class Dialcentral(object):
                @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:
@@ -419,13 +390,9 @@ class Dialcentral(object):
                for attemptCount in xrange(numOfAttempts):
                        if loggedIn:
                                break
-                       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
+                               credentials = self._credentialsDialog.request_credentials(
+                                       defaultCredentials = self._credentials
                                )
                        tmpServiceId, username, password = credentials
                        loggedIn = self._phoneBackends[tmpServiceId].login(username, password)
@@ -492,10 +459,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
@@ -511,10 +489,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
@@ -529,6 +515,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(),
@@ -540,32 +530,28 @@ class Dialcentral(object):
                        config.add_section(sectionName)
                        view.save_settings(config, sectionName)
 
-       def _guess_preferred_backend(self, backendAndCookiePaths):
-               modTimeAndPath = [
-                       (getmtime_nothrow(path), backendId, path)
-                       for backendId, path in backendAndCookiePaths
-               ]
-               modTimeAndPath.sort()
-               return modTimeAndPath[-1][1]
-
        def _save_settings(self):
                """
                @note Thread Agnostic
                """
                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):
-               page_num = self._notebook.get_current_page()
-               if page_num == self.CONTACTS_TAB:
+               pageIndex = self._notebook.get_current_page()
+               if pageIndex == self.CONTACTS_TAB:
                        self._contactsViews[self._selectedBackendId].update(force=True)
-               elif page_num == self.RECENT_TAB:
+               elif pageIndex == self.RECENT_TAB:
                        self._recentViews[self._selectedBackendId].update(force=True)
-               elif page_num == self.MESSAGES_TAB:
+               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:
@@ -604,11 +590,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)
@@ -642,37 +626,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()
 
-       def _on_tab_press(self, *args):
-               self._tabHoldTimeoutId = gobject.timeout_add(1000, self._on_tab_refresh)
+               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 _on_tab_release(self, *args):
-               if self._tabHoldTimeoutId is not None:
-                       gobject.source_remove(self._tabHoldTimeoutId)
-               self._tabHoldTimeoutId = None
+       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._tabHoldTimeoutId = None
                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 StandardError, e:
                        loggedIn = False
-                       self._errorDisplay.push_exception(e)
+                       self._errorDisplay.push_exception()
                        return
 
                if not loggedIn:
@@ -686,9 +683,12 @@ class Dialcentral(object):
                        self._phoneBackends[self._selectedBackendId].send_sms(number, message)
                        dialed = True
                except StandardError, e:
-                       self._errorDisplay.push_exception(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, "No number to call"
@@ -696,7 +696,7 @@ class Dialcentral(object):
                        loggedIn = self._phoneBackends[self._selectedBackendId].is_authed()
                except StandardError, e:
                        loggedIn = False
-                       self._errorDisplay.push_exception(e)
+                       self._errorDisplay.push_exception()
                        return
 
                if not loggedIn:
@@ -711,9 +711,9 @@ class Dialcentral(object):
                        self._phoneBackends[self._selectedBackendId].dial(number)
                        dialed = True
                except StandardError, e:
-                       self._errorDisplay.push_exception(e)
+                       self._errorDisplay.push_exception()
                except ValueError, e:
-                       self._errorDisplay.push_exception(e)
+                       self._errorDisplay.push_exception()
 
                if dialed:
                        self._dialpads[self._selectedBackendId].clear()
@@ -749,8 +749,11 @@ 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:
+
+       if hildonize.IS_HILDON:
                gtk.set_application_name(constants.__pretty_app_name__)
        handle = Dialcentral()
        gtk.main()