Removing another page download from startup for GOogleVoice
[gc-dialer] / src / gc_views.py
1 #!/usr/bin/python2.5
2
3 # DialCentral - Front end for Google's Grand Central service.
4 # Copyright (C) 2008  Mark Bergman bergman AT merctech DOT com
5
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2.1 of the License, or (at your option) any later version.
10
11 # This library is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # Lesser General Public License for more details.
15
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19
20 import threading
21 import time
22 import warnings
23 import traceback
24
25 import gobject
26 import gtk
27
28
29 def make_ugly(prettynumber):
30         """
31         function to take a phone number and strip out all non-numeric
32         characters
33
34         >>> make_ugly("+012-(345)-678-90")
35         '01234567890'
36         """
37         import re
38         uglynumber = re.sub('\D', '', prettynumber)
39         return uglynumber
40
41
42 def make_pretty(phonenumber):
43         """
44         Function to take a phone number and return the pretty version
45         pretty numbers:
46                 if phonenumber begins with 0:
47                         ...-(...)-...-....
48                 if phonenumber begins with 1: ( for gizmo callback numbers )
49                         1 (...)-...-....
50                 if phonenumber is 13 digits:
51                         (...)-...-....
52                 if phonenumber is 10 digits:
53                         ...-....
54         >>> make_pretty("12")
55         '12'
56         >>> make_pretty("1234567")
57         '123-4567'
58         >>> make_pretty("2345678901")
59         '(234)-567-8901'
60         >>> make_pretty("12345678901")
61         '1 (234)-567-8901'
62         >>> make_pretty("01234567890")
63         '+012-(345)-678-90'
64         """
65         if phonenumber is None or phonenumber is "":
66                 return ""
67
68         phonenumber = make_ugly(phonenumber)
69
70         if len(phonenumber) < 3:
71                 return phonenumber
72
73         if phonenumber[0] == "0":
74                 prettynumber = ""
75                 prettynumber += "+%s" % phonenumber[0:3]
76                 if 3 < len(phonenumber):
77                         prettynumber += "-(%s)" % phonenumber[3:6]
78                         if 6 < len(phonenumber):
79                                 prettynumber += "-%s" % phonenumber[6:9]
80                                 if 9 < len(phonenumber):
81                                         prettynumber += "-%s" % phonenumber[9:]
82                 return prettynumber
83         elif len(phonenumber) <= 7:
84                 prettynumber = "%s-%s" % (phonenumber[0:3], phonenumber[3:])
85         elif len(phonenumber) > 8 and phonenumber[0] == "1":
86                 prettynumber = "1 (%s)-%s-%s" % (phonenumber[1:4], phonenumber[4:7], phonenumber[7:])
87         elif len(phonenumber) > 7:
88                 prettynumber = "(%s)-%s-%s" % (phonenumber[0:3], phonenumber[3:6], phonenumber[6:])
89         return prettynumber
90
91
92 def make_idler(func):
93         """
94         Decorator that makes a generator-function into a function that will continue execution on next call
95         """
96         a = []
97
98         def decorated_func(*args, **kwds):
99                 if not a:
100                         a.append(func(*args, **kwds))
101                 try:
102                         a[0].next()
103                         return True
104                 except StopIteration:
105                         del a[:]
106                         return False
107
108         decorated_func.__name__ = func.__name__
109         decorated_func.__doc__ = func.__doc__
110         decorated_func.__dict__.update(func.__dict__)
111
112         return decorated_func
113
114
115 class DummyAddressBook(object):
116         """
117         Minimal example of both an addressbook factory and an addressbook
118         """
119
120         def clear_caches(self):
121                 pass
122
123         def get_addressbooks(self):
124                 """
125                 @returns Iterable of (Address Book Factory, Book Id, Book Name)
126                 """
127                 yield self, "", "None"
128
129         def open_addressbook(self, bookId):
130                 return self
131
132         @staticmethod
133         def contact_source_short_name(contactId):
134                 return ""
135
136         @staticmethod
137         def factory_name():
138                 return ""
139
140         @staticmethod
141         def get_contacts():
142                 """
143                 @returns Iterable of (contact id, contact name)
144                 """
145                 return []
146
147         @staticmethod
148         def get_contact_details(contactId):
149                 """
150                 @returns Iterable of (Phone Type, Phone Number)
151                 """
152                 return []
153
154
155 class MergedAddressBook(object):
156         """
157         Merger of all addressbooks
158         """
159
160         def __init__(self, addressbookFactories, sorter = None):
161                 self.__addressbookFactories = addressbookFactories
162                 self.__addressbooks = None
163                 self.__sort_contacts = sorter if sorter is not None else self.null_sorter
164
165         def clear_caches(self):
166                 self.__addressbooks = None
167                 for factory in self.__addressbookFactories:
168                         factory.clear_caches()
169
170         def get_addressbooks(self):
171                 """
172                 @returns Iterable of (Address Book Factory, Book Id, Book Name)
173                 """
174                 yield self, "", ""
175
176         def open_addressbook(self, bookId):
177                 return self
178
179         def contact_source_short_name(self, contactId):
180                 if self.__addressbooks is None:
181                         return ""
182                 bookIndex, originalId = contactId.split("-", 1)
183                 return self.__addressbooks[int(bookIndex)].contact_source_short_name(originalId)
184
185         @staticmethod
186         def factory_name():
187                 return "All Contacts"
188
189         def get_contacts(self):
190                 """
191                 @returns Iterable of (contact id, contact name)
192                 """
193                 if self.__addressbooks is None:
194                         self.__addressbooks = list(
195                                 factory.open_addressbook(id)
196                                 for factory in self.__addressbookFactories
197                                 for (f, id, name) in factory.get_addressbooks()
198                         )
199                 contacts = (
200                         ("-".join([str(bookIndex), contactId]), contactName)
201                                 for (bookIndex, addressbook) in enumerate(self.__addressbooks)
202                                         for (contactId, contactName) in addressbook.get_contacts()
203                 )
204                 sortedContacts = self.__sort_contacts(contacts)
205                 return sortedContacts
206
207         def get_contact_details(self, contactId):
208                 """
209                 @returns Iterable of (Phone Type, Phone Number)
210                 """
211                 if self.__addressbooks is None:
212                         return []
213                 bookIndex, originalId = contactId.split("-", 1)
214                 return self.__addressbooks[int(bookIndex)].get_contact_details(originalId)
215
216         @staticmethod
217         def null_sorter(contacts):
218                 """
219                 Good for speed/low memory
220                 """
221                 return contacts
222
223         @staticmethod
224         def basic_firtname_sorter(contacts):
225                 """
226                 Expects names in "First Last" format
227                 """
228                 contactsWithKey = [
229                         (contactName.rsplit(" ", 1)[0], (contactId, contactName))
230                                 for (contactId, contactName) in contacts
231                 ]
232                 contactsWithKey.sort()
233                 return (contactData for (lastName, contactData) in contactsWithKey)
234
235         @staticmethod
236         def basic_lastname_sorter(contacts):
237                 """
238                 Expects names in "First Last" format
239                 """
240                 contactsWithKey = [
241                         (contactName.rsplit(" ", 1)[-1], (contactId, contactName))
242                                 for (contactId, contactName) in contacts
243                 ]
244                 contactsWithKey.sort()
245                 return (contactData for (lastName, contactData) in contactsWithKey)
246
247         @staticmethod
248         def reversed_firtname_sorter(contacts):
249                 """
250                 Expects names in "Last, First" format
251                 """
252                 contactsWithKey = [
253                         (contactName.split(", ", 1)[-1], (contactId, contactName))
254                                 for (contactId, contactName) in contacts
255                 ]
256                 contactsWithKey.sort()
257                 return (contactData for (lastName, contactData) in contactsWithKey)
258
259         @staticmethod
260         def reversed_lastname_sorter(contacts):
261                 """
262                 Expects names in "Last, First" format
263                 """
264                 contactsWithKey = [
265                         (contactName.split(", ", 1)[0], (contactId, contactName))
266                                 for (contactId, contactName) in contacts
267                 ]
268                 contactsWithKey.sort()
269                 return (contactData for (lastName, contactData) in contactsWithKey)
270
271         @staticmethod
272         def guess_firstname(name):
273                 if ", " in name:
274                         return name.split(", ", 1)[-1]
275                 else:
276                         return name.rsplit(" ", 1)[0]
277
278         @staticmethod
279         def guess_lastname(name):
280                 if ", " in name:
281                         return name.split(", ", 1)[0]
282                 else:
283                         return name.rsplit(" ", 1)[-1]
284
285         @classmethod
286         def advanced_firstname_sorter(cls, contacts):
287                 contactsWithKey = [
288                         (cls.guess_firstname(contactName), (contactId, contactName))
289                                 for (contactId, contactName) in contacts
290                 ]
291                 contactsWithKey.sort()
292                 return (contactData for (lastName, contactData) in contactsWithKey)
293
294         @classmethod
295         def advanced_lastname_sorter(cls, contacts):
296                 contactsWithKey = [
297                         (cls.guess_lastname(contactName), (contactId, contactName))
298                                 for (contactId, contactName) in contacts
299                 ]
300                 contactsWithKey.sort()
301                 return (contactData for (lastName, contactData) in contactsWithKey)
302
303
304 class PhoneTypeSelector(object):
305
306         def __init__(self, widgetTree, gcBackend):
307                 self._gcBackend = gcBackend
308                 self._widgetTree = widgetTree
309                 self._dialog = self._widgetTree.get_widget("phonetype_dialog")
310
311                 self._selectButton = self._widgetTree.get_widget("select_button")
312                 self._selectButton.connect("clicked", self._on_phonetype_select)
313
314                 self._cancelButton = self._widgetTree.get_widget("cancel_button")
315                 self._cancelButton.connect("clicked", self._on_phonetype_cancel)
316
317                 self._typemodel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING)
318                 self._typeviewselection = None
319
320                 typeview = self._widgetTree.get_widget("phonetypes")
321                 typeview.connect("row-activated", self._on_phonetype_select)
322                 typeview.set_model(self._typemodel)
323                 textrenderer = gtk.CellRendererText()
324
325                 # Add the column to the treeview
326                 column = gtk.TreeViewColumn("Phone Numbers", textrenderer, text=1)
327                 column.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
328
329                 typeview.append_column(column)
330
331                 self._typeviewselection = typeview.get_selection()
332                 self._typeviewselection.set_mode(gtk.SELECTION_SINGLE)
333
334         def run(self, contactDetails):
335                 self._typemodel.clear()
336
337                 for phoneType, phoneNumber in contactDetails:
338                         self._typemodel.append((phoneNumber, "%s - %s" % (make_pretty(phoneNumber), phoneType)))
339
340                 userResponse = self._dialog.run()
341
342                 if userResponse == gtk.RESPONSE_OK:
343                         model, itr = self._typeviewselection.get_selected()
344                         if itr:
345                                 phoneNumber = self._typemodel.get_value(itr, 0)
346                 else:
347                         phoneNumber = ""
348
349                 self._typeviewselection.unselect_all()
350                 self._dialog.hide()
351                 return phoneNumber
352
353         def _on_phonetype_select(self, *args):
354                 self._dialog.response(gtk.RESPONSE_OK)
355
356         def _on_phonetype_cancel(self, *args):
357                 self._dialog.response(gtk.RESPONSE_CANCEL)
358
359
360 class Dialpad(object):
361
362         def __init__(self, widgetTree, errorDisplay):
363                 self._errorDisplay = errorDisplay
364                 self._numberdisplay = widgetTree.get_widget("numberdisplay")
365                 self._dialButton = widgetTree.get_widget("dial")
366                 self._phonenumber = ""
367                 self._prettynumber = ""
368                 self._clearall_id = None
369
370                 callbackMapping = {
371                         "on_dial_clicked": self._on_dial_clicked,
372                         "on_digit_clicked": self._on_digit_clicked,
373                         "on_clear_number": self._on_clear_number,
374                         "on_back_clicked": self._on_backspace,
375                         "on_back_pressed": self._on_back_pressed,
376                         "on_back_released": self._on_back_released,
377                 }
378                 widgetTree.signal_autoconnect(callbackMapping)
379
380         def enable(self):
381                 self._dialButton.grab_focus()
382
383         def disable(self):
384                 pass
385
386         def dial(self, number):
387                 """
388                 @note Actual dial function is patched in later
389                 """
390                 raise NotImplementedError
391
392         def get_number(self):
393                 return self._phonenumber
394
395         def set_number(self, number):
396                 """
397                 Set the callback phonenumber
398                 """
399                 try:
400                         self._phonenumber = make_ugly(number)
401                         self._prettynumber = make_pretty(self._phonenumber)
402                         self._numberdisplay.set_label("<span size='30000' weight='bold'>%s</span>" % (self._prettynumber))
403                 except TypeError, e:
404                         warnings.warn(traceback.format_exc())
405                         self._errorDisplay.push_message(e.message)
406
407         def clear(self):
408                 self.set_number("")
409
410         def _on_dial_clicked(self, widget):
411                 self.dial(self.get_number())
412
413         def _on_clear_number(self, *args):
414                 self.clear()
415
416         def _on_digit_clicked(self, widget):
417                 self.set_number(self._phonenumber + widget.get_name()[-1])
418
419         def _on_backspace(self, widget):
420                 self.set_number(self._phonenumber[:-1])
421
422         def _on_clearall(self):
423                 self.clear()
424                 return False
425
426         def _on_back_pressed(self, widget):
427                 self._clearall_id = gobject.timeout_add(1000, self._on_clearall)
428
429         def _on_back_released(self, widget):
430                 if self._clearall_id is not None:
431                         gobject.source_remove(self._clearall_id)
432                 self._clearall_id = None
433
434
435 class AccountInfo(object):
436
437         def __init__(self, widgetTree, backend, errorDisplay):
438                 self._errorDisplay = errorDisplay
439                 self._backend = backend
440
441                 self._callbackList = gtk.ListStore(gobject.TYPE_STRING)
442                 self._accountViewNumberDisplay = widgetTree.get_widget("gcnumber_display")
443                 self._callbackCombo = widgetTree.get_widget("callbackcombo")
444                 self._onCallbackentryChangedId = 0
445
446         def enable(self):
447                 assert self._backend.is_authed()
448                 self._accountViewNumberDisplay.set_use_markup(True)
449                 self.set_account_number("")
450                 self._callbackList.clear()
451                 self.update()
452                 self._onCallbackentryChangedId = self._callbackCombo.get_child().connect("changed", self._on_callbackentry_changed)
453
454         def disable(self):
455                 self._callbackCombo.get_child().disconnect(self._onCallbackentryChangedId)
456                 self.clear()
457                 self._callbackList.clear()
458
459         def get_selected_callback_number(self):
460                 return make_ugly(self._callbackCombo.get_child().get_text())
461
462         def set_account_number(self, number):
463                 """
464                 Displays current account number
465                 """
466                 self._accountViewNumberDisplay.set_label("<span size='23000' weight='bold'>%s</span>" % (number))
467
468         def update(self):
469                 self.populate_callback_combo()
470                 self.set_account_number(self._backend.get_account_number())
471
472         def clear(self):
473                 self._callbackCombo.get_child().set_text("")
474                 self.set_account_number("")
475
476         def populate_callback_combo(self):
477                 self._callbackList.clear()
478                 try:
479                         callbackNumbers = self._backend.get_callback_numbers()
480                 except RuntimeError, e:
481                         warnings.warn(traceback.format_exc())
482                         self._errorDisplay.push_message(e.message)
483                         return
484
485                 for number, description in callbackNumbers.iteritems():
486                         self._callbackList.append((make_pretty(number),))
487
488                 self._callbackCombo.set_model(self._callbackList)
489                 self._callbackCombo.set_text_column(0)
490                 try:
491                         callbackNumber = self._backend.get_callback_number()
492                 except RuntimeError, e:
493                         warnings.warn(traceback.format_exc())
494                         self._errorDisplay.push_message(e.message)
495                         return
496                 self._callbackCombo.get_child().set_text(make_pretty(callbackNumber))
497
498         def _on_callbackentry_changed(self, *args):
499                 """
500                 @todo Potential blocking on web access, maybe we should defer this or put up a dialog?
501                 """
502                 try:
503                         text = self.get_selected_callback_number()
504                         if not self._backend.is_valid_syntax(text):
505                                 self._errorDisplay.push_message("%s is not a valid callback number" % text)
506                         elif text == self._backend.get_callback_number():
507                                 warnings.warn("Callback number already is %s" % self._backend.get_callback_number(), UserWarning, 2)
508                         else:
509                                 self._backend.set_callback_number(text)
510                 except RuntimeError, e:
511                         warnings.warn(traceback.format_exc())
512                         self._errorDisplay.push_message(e.message)
513
514
515 class RecentCallsView(object):
516
517         def __init__(self, widgetTree, backend, errorDisplay):
518                 self._errorDisplay = errorDisplay
519                 self._backend = backend
520
521                 self._recenttime = 0.0
522                 self._recentmodel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING)
523                 self._recentview = widgetTree.get_widget("recentview")
524                 self._recentviewselection = None
525                 self._onRecentviewRowActivatedId = 0
526
527                 textrenderer = gtk.CellRendererText()
528                 self._recentviewColumn = gtk.TreeViewColumn("Calls", textrenderer, text=1)
529                 self._recentviewColumn.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
530
531         def enable(self):
532                 assert self._backend.is_authed()
533                 self._recentview.set_model(self._recentmodel)
534
535                 self._recentview.append_column(self._recentviewColumn)
536                 self._recentviewselection = self._recentview.get_selection()
537                 self._recentviewselection.set_mode(gtk.SELECTION_SINGLE)
538
539                 self._onRecentviewRowActivatedId = self._recentview.connect("row-activated", self._on_recentview_row_activated)
540
541         def disable(self):
542                 self._recentview.disconnect(self._onRecentviewRowActivatedId)
543                 self._recentview.remove_column(self._recentviewColumn)
544                 self._recentview.set_model(None)
545
546         def number_selected(self, number):
547                 """
548                 @note Actual dial function is patched in later
549                 """
550                 raise NotImplementedError
551
552         def update(self):
553                 if (time.time() - self._recenttime) < 300:
554                         return
555                 backgroundPopulate = threading.Thread(target=self._idly_populate_recentview)
556                 backgroundPopulate.setDaemon(True)
557                 backgroundPopulate.start()
558
559         def clear(self):
560                 self._recenttime = 0.0
561                 self._recentmodel.clear()
562
563         def _idly_populate_recentview(self):
564                 self._recenttime = time.time()
565                 self._recentmodel.clear()
566
567                 try:
568                         recentItems = self._backend.get_recent()
569                 except RuntimeError, e:
570                         warnings.warn(traceback.format_exc())
571                         gtk.gdk.threads_enter()
572                         try:
573                                 self._errorDisplay.push_message(e.message)
574                         finally:
575                                 gtk.gdk.threads_leave()
576                         self._recenttime = 0.0
577                         recentItems = []
578
579                 for personsName, phoneNumber, date, action in recentItems:
580                         description = "%s on %s from/to %s - %s" % (action.capitalize(), date, personsName, phoneNumber)
581                         item = (phoneNumber, description)
582                         gtk.gdk.threads_enter()
583                         try:
584                                 self._recentmodel.append(item)
585                         finally:
586                                 gtk.gdk.threads_leave()
587
588                 return False
589
590         def _on_recentview_row_activated(self, treeview, path, view_column):
591                 model, itr = self._recentviewselection.get_selected()
592                 if not itr:
593                         return
594
595                 self.number_selected(self._recentmodel.get_value(itr, 0))
596                 self._recentviewselection.unselect_all()
597
598
599 class ContactsView(object):
600
601         def __init__(self, widgetTree, backend, errorDisplay):
602                 self._errorDisplay = errorDisplay
603                 self._backend = backend
604
605                 self._addressBook = None
606                 self._addressBookFactories = [DummyAddressBook()]
607
608                 self._booksList = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
609                 self._booksSelectionBox = widgetTree.get_widget("addressbook_combo")
610
611                 self._contactstime = 0.0
612                 self._contactsmodel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
613                 self._contactsviewselection = None
614                 self._contactsview = widgetTree.get_widget("contactsview")
615
616                 self._contactColumn = gtk.TreeViewColumn("Contact")
617                 displayContactSource = True
618                 if displayContactSource:
619                         textrenderer = gtk.CellRendererText()
620                         self._contactColumn.pack_start(textrenderer, expand=False)
621                         self._contactColumn.add_attribute(textrenderer, 'text', 0)
622                 textrenderer = gtk.CellRendererText()
623                 self._contactColumn.pack_start(textrenderer, expand=True)
624                 self._contactColumn.add_attribute(textrenderer, 'text', 1)
625                 textrenderer = gtk.CellRendererText()
626                 self._contactColumn.pack_start(textrenderer, expand=True)
627                 self._contactColumn.add_attribute(textrenderer, 'text', 4)
628                 self._contactColumn.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
629                 self._contactColumn.set_sort_column_id(1)
630                 self._contactColumn.set_visible(True)
631
632                 self._onContactsviewRowActivatedId = 0
633                 self._onAddressbookComboChangedId = 0
634                 self._phoneTypeSelector = PhoneTypeSelector(widgetTree, self._backend)
635
636         def enable(self):
637                 assert self._backend.is_authed()
638
639                 self._contactsview.set_model(self._contactsmodel)
640                 self._contactsview.append_column(self._contactColumn)
641                 self._contactsviewselection = self._contactsview.get_selection()
642                 self._contactsviewselection.set_mode(gtk.SELECTION_SINGLE)
643
644                 self._booksList.clear()
645                 for (factoryId, bookId), (factoryName, bookName) in self.get_addressbooks():
646                         if factoryName and bookName:
647                                 entryName = "%s: %s" % (factoryName, bookName)
648                         elif factoryName:
649                                 entryName = factoryName
650                         elif bookName:
651                                 entryName = bookName
652                         else:
653                                 entryName = "Bad name (%d)" % factoryId
654                         row = (str(factoryId), bookId, entryName)
655                         self._booksList.append(row)
656
657                 self._booksSelectionBox.set_model(self._booksList)
658                 cell = gtk.CellRendererText()
659                 self._booksSelectionBox.pack_start(cell, True)
660                 self._booksSelectionBox.add_attribute(cell, 'text', 2)
661                 self._booksSelectionBox.set_active(0)
662
663                 self._onContactsviewRowActivatedId = self._contactsview.connect("row-activated", self._on_contactsview_row_activated)
664                 self._onAddressbookComboChangedId = self._booksSelectionBox.connect("changed", self._on_addressbook_combo_changed)
665
666         def disable(self):
667                 self._contactsview.disconnect(self._onContactsviewRowActivatedId)
668                 self._booksSelectionBox.disconnect(self._onAddressbookComboChangedId)
669
670                 self._booksSelectionBox.clear()
671                 self._booksSelectionBox.set_model(None)
672                 self._contactsview.set_model(None)
673                 self._contactsview.remove_column(self._contactColumn)
674
675         def number_selected(self, number):
676                 """
677                 @note Actual dial function is patched in later
678                 """
679                 raise NotImplementedError
680
681         def get_addressbooks(self):
682                 """
683                 @returns Iterable of ((Factory Id, Book Id), (Factory Name, Book Name))
684                 """
685                 for i, factory in enumerate(self._addressBookFactories):
686                         for bookFactory, bookId, bookName in factory.get_addressbooks():
687                                 yield (i, bookId), (factory.factory_name(), bookName)
688
689         def open_addressbook(self, bookFactoryId, bookId):
690                 self._addressBook = self._addressBookFactories[bookFactoryId].open_addressbook(bookId)
691                 self._contactstime = 0
692                 backgroundPopulate = threading.Thread(target=self._idly_populate_contactsview)
693                 backgroundPopulate.setDaemon(True)
694                 backgroundPopulate.start()
695
696         def update(self):
697                 if (time.time() - self._contactstime) < 300:
698                         return
699                 backgroundPopulate = threading.Thread(target=self._idly_populate_contactsview)
700                 backgroundPopulate.setDaemon(True)
701                 backgroundPopulate.start()
702
703         def clear(self):
704                 self._contactstime = 0.0
705                 self._contactsmodel.clear()
706
707         def clear_caches(self):
708                 for factory in self._addressBookFactories:
709                         factory.clear_caches()
710                 self._addressBook.clear_caches()
711
712         def append(self, book):
713                 self._addressBookFactories.append(book)
714
715         def extend(self, books):
716                 self._addressBookFactories.extend(books)
717
718         def _idly_populate_contactsview(self):
719                 #@todo Add a lock so only one code path can be in here at a time
720                 self.clear()
721
722                 # completely disable updating the treeview while we populate the data
723                 self._contactsview.freeze_child_notify()
724                 self._contactsview.set_model(None)
725
726                 addressBook = self._addressBook
727                 try:
728                         contacts = addressBook.get_contacts()
729                 except RuntimeError, e:
730                         warnings.warn(traceback.format_exc())
731                         contacts = []
732                         self._contactstime = 0.0
733                         gtk.gdk.threads_enter()
734                         try:
735                                 self._errorDisplay.push_message(e.message)
736                         finally:
737                                 gtk.gdk.threads_leave()
738                 for contactId, contactName in contacts:
739                         contactType = (addressBook.contact_source_short_name(contactId),)
740                         self._contactsmodel.append(contactType + (contactName, "", contactId) + ("",))
741
742                 # restart the treeview data rendering
743                 self._contactsview.set_model(self._contactsmodel)
744                 self._contactsview.thaw_child_notify()
745                 return False
746
747         def _on_addressbook_combo_changed(self, *args, **kwds):
748                 itr = self._booksSelectionBox.get_active_iter()
749                 if itr is None:
750                         return
751                 factoryId = int(self._booksList.get_value(itr, 0))
752                 bookId = self._booksList.get_value(itr, 1)
753                 self.open_addressbook(factoryId, bookId)
754
755         def _on_contactsview_row_activated(self, treeview, path, view_column):
756                 model, itr = self._contactsviewselection.get_selected()
757                 if not itr:
758                         return
759
760                 contactId = self._contactsmodel.get_value(itr, 3)
761                 try:
762                         contactDetails = self._addressBook.get_contact_details(contactId)
763                 except RuntimeError, e:
764                         warnings.warn(traceback.format_exc())
765                         contactDetails = []
766                         self._contactstime = 0.0
767                         self._errorDisplay.push_message(e.message)
768                 contactDetails = [phoneNumber for phoneNumber in contactDetails]
769
770                 if len(contactDetails) == 0:
771                         phoneNumber = ""
772                 elif len(contactDetails) == 1:
773                         phoneNumber = contactDetails[0][1]
774                 else:
775                         phoneNumber = self._phoneTypeSelector.run(contactDetails)
776
777                 if 0 < len(phoneNumber):
778                         self.number_selected(phoneNumber)
779
780                 self._contactsviewselection.unselect_all()