Oops, didn't mean to commit this stuff marked as markup
[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")
529                 self._recentviewColumn.pack_start(textrenderer, expand=True)
530                 self._recentviewColumn.add_attribute(textrenderer, "text", 1)
531                 self._recentviewColumn.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
532
533         def enable(self):
534                 assert self._backend.is_authed()
535                 self._recentview.set_model(self._recentmodel)
536
537                 self._recentview.append_column(self._recentviewColumn)
538                 self._recentviewselection = self._recentview.get_selection()
539                 self._recentviewselection.set_mode(gtk.SELECTION_SINGLE)
540
541                 self._onRecentviewRowActivatedId = self._recentview.connect("row-activated", self._on_recentview_row_activated)
542
543         def disable(self):
544                 self._recentview.disconnect(self._onRecentviewRowActivatedId)
545                 self._recentview.remove_column(self._recentviewColumn)
546                 self._recentview.set_model(None)
547
548         def number_selected(self, number):
549                 """
550                 @note Actual dial function is patched in later
551                 """
552                 raise NotImplementedError
553
554         def update(self):
555                 if (time.time() - self._recenttime) < 300:
556                         return
557                 backgroundPopulate = threading.Thread(target=self._idly_populate_recentview)
558                 backgroundPopulate.setDaemon(True)
559                 backgroundPopulate.start()
560
561         def clear(self):
562                 self._recenttime = 0.0
563                 self._recentmodel.clear()
564
565         def _idly_populate_recentview(self):
566                 self._recenttime = time.time()
567                 self._recentmodel.clear()
568
569                 try:
570                         recentItems = self._backend.get_recent()
571                 except RuntimeError, e:
572                         warnings.warn(traceback.format_exc())
573                         gtk.gdk.threads_enter()
574                         try:
575                                 self._errorDisplay.push_message(e.message)
576                         finally:
577                                 gtk.gdk.threads_leave()
578                         self._recenttime = 0.0
579                         recentItems = []
580
581                 for personsName, phoneNumber, date, action in recentItems:
582                         description = "%s on %s from/to %s - %s" % (action.capitalize(), date, personsName, phoneNumber)
583                         item = (phoneNumber, description)
584                         gtk.gdk.threads_enter()
585                         try:
586                                 self._recentmodel.append(item)
587                         finally:
588                                 gtk.gdk.threads_leave()
589
590                 return False
591
592         def _on_recentview_row_activated(self, treeview, path, view_column):
593                 model, itr = self._recentviewselection.get_selected()
594                 if not itr:
595                         return
596
597                 self.number_selected(self._recentmodel.get_value(itr, 0))
598                 self._recentviewselection.unselect_all()
599
600
601 class ContactsView(object):
602
603         def __init__(self, widgetTree, backend, errorDisplay):
604                 self._errorDisplay = errorDisplay
605                 self._backend = backend
606
607                 self._addressBook = None
608                 self._addressBookFactories = [DummyAddressBook()]
609
610                 self._booksList = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
611                 self._booksSelectionBox = widgetTree.get_widget("addressbook_combo")
612
613                 self._contactstime = 0.0
614                 self._contactsmodel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
615                 self._contactsviewselection = None
616                 self._contactsview = widgetTree.get_widget("contactsview")
617
618                 self._contactColumn = gtk.TreeViewColumn("Contact")
619                 displayContactSource = False
620                 if displayContactSource:
621                         textrenderer = gtk.CellRendererText()
622                         self._contactColumn.pack_start(textrenderer, expand=False)
623                         self._contactColumn.add_attribute(textrenderer, 'text', 0)
624                 textrenderer = gtk.CellRendererText()
625                 self._contactColumn.pack_start(textrenderer, expand=True)
626                 self._contactColumn.add_attribute(textrenderer, 'text', 1)
627                 textrenderer = gtk.CellRendererText()
628                 self._contactColumn.pack_start(textrenderer, expand=True)
629                 self._contactColumn.add_attribute(textrenderer, 'text', 4)
630                 self._contactColumn.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
631                 self._contactColumn.set_sort_column_id(1)
632                 self._contactColumn.set_visible(True)
633
634                 self._onContactsviewRowActivatedId = 0
635                 self._onAddressbookComboChangedId = 0
636                 self._phoneTypeSelector = PhoneTypeSelector(widgetTree, self._backend)
637
638         def enable(self):
639                 assert self._backend.is_authed()
640
641                 self._contactsview.set_model(self._contactsmodel)
642                 self._contactsview.append_column(self._contactColumn)
643                 self._contactsviewselection = self._contactsview.get_selection()
644                 self._contactsviewselection.set_mode(gtk.SELECTION_SINGLE)
645
646                 self._booksList.clear()
647                 for (factoryId, bookId), (factoryName, bookName) in self.get_addressbooks():
648                         if factoryName and bookName:
649                                 entryName = "%s: %s" % (factoryName, bookName)
650                         elif factoryName:
651                                 entryName = factoryName
652                         elif bookName:
653                                 entryName = bookName
654                         else:
655                                 entryName = "Bad name (%d)" % factoryId
656                         row = (str(factoryId), bookId, entryName)
657                         self._booksList.append(row)
658
659                 self._booksSelectionBox.set_model(self._booksList)
660                 cell = gtk.CellRendererText()
661                 self._booksSelectionBox.pack_start(cell, True)
662                 self._booksSelectionBox.add_attribute(cell, 'text', 2)
663                 self._booksSelectionBox.set_active(0)
664
665                 self._onContactsviewRowActivatedId = self._contactsview.connect("row-activated", self._on_contactsview_row_activated)
666                 self._onAddressbookComboChangedId = self._booksSelectionBox.connect("changed", self._on_addressbook_combo_changed)
667
668         def disable(self):
669                 self._contactsview.disconnect(self._onContactsviewRowActivatedId)
670                 self._booksSelectionBox.disconnect(self._onAddressbookComboChangedId)
671
672                 self._booksSelectionBox.clear()
673                 self._booksSelectionBox.set_model(None)
674                 self._contactsview.set_model(None)
675                 self._contactsview.remove_column(self._contactColumn)
676
677         def number_selected(self, number):
678                 """
679                 @note Actual dial function is patched in later
680                 """
681                 raise NotImplementedError
682
683         def get_addressbooks(self):
684                 """
685                 @returns Iterable of ((Factory Id, Book Id), (Factory Name, Book Name))
686                 """
687                 for i, factory in enumerate(self._addressBookFactories):
688                         for bookFactory, bookId, bookName in factory.get_addressbooks():
689                                 yield (i, bookId), (factory.factory_name(), bookName)
690
691         def open_addressbook(self, bookFactoryId, bookId):
692                 self._addressBook = self._addressBookFactories[bookFactoryId].open_addressbook(bookId)
693                 self._contactstime = 0
694                 backgroundPopulate = threading.Thread(target=self._idly_populate_contactsview)
695                 backgroundPopulate.setDaemon(True)
696                 backgroundPopulate.start()
697
698         def update(self):
699                 if (time.time() - self._contactstime) < 300:
700                         return
701                 backgroundPopulate = threading.Thread(target=self._idly_populate_contactsview)
702                 backgroundPopulate.setDaemon(True)
703                 backgroundPopulate.start()
704
705         def clear(self):
706                 self._contactstime = 0.0
707                 self._contactsmodel.clear()
708
709         def clear_caches(self):
710                 for factory in self._addressBookFactories:
711                         factory.clear_caches()
712                 self._addressBook.clear_caches()
713
714         def append(self, book):
715                 self._addressBookFactories.append(book)
716
717         def extend(self, books):
718                 self._addressBookFactories.extend(books)
719
720         def _idly_populate_contactsview(self):
721                 #@todo Add a lock so only one code path can be in here at a time
722                 self.clear()
723
724                 # completely disable updating the treeview while we populate the data
725                 self._contactsview.freeze_child_notify()
726                 self._contactsview.set_model(None)
727
728                 addressBook = self._addressBook
729                 try:
730                         contacts = addressBook.get_contacts()
731                 except RuntimeError, e:
732                         warnings.warn(traceback.format_exc())
733                         contacts = []
734                         self._contactstime = 0.0
735                         gtk.gdk.threads_enter()
736                         try:
737                                 self._errorDisplay.push_message(e.message)
738                         finally:
739                                 gtk.gdk.threads_leave()
740                 for contactId, contactName in contacts:
741                         contactType = (addressBook.contact_source_short_name(contactId), )
742                         self._contactsmodel.append(contactType + (contactName, "", contactId) + ("", ))
743
744                 # restart the treeview data rendering
745                 self._contactsview.set_model(self._contactsmodel)
746                 self._contactsview.thaw_child_notify()
747                 return False
748
749         def _on_addressbook_combo_changed(self, *args, **kwds):
750                 itr = self._booksSelectionBox.get_active_iter()
751                 if itr is None:
752                         return
753                 factoryId = int(self._booksList.get_value(itr, 0))
754                 bookId = self._booksList.get_value(itr, 1)
755                 self.open_addressbook(factoryId, bookId)
756
757         def _on_contactsview_row_activated(self, treeview, path, view_column):
758                 model, itr = self._contactsviewselection.get_selected()
759                 if not itr:
760                         return
761
762                 contactId = self._contactsmodel.get_value(itr, 3)
763                 try:
764                         contactDetails = self._addressBook.get_contact_details(contactId)
765                 except RuntimeError, e:
766                         warnings.warn(traceback.format_exc())
767                         contactDetails = []
768                         self._contactstime = 0.0
769                         self._errorDisplay.push_message(e.message)
770                 contactDetails = [phoneNumber for phoneNumber in contactDetails]
771
772                 if len(contactDetails) == 0:
773                         phoneNumber = ""
774                 elif len(contactDetails) == 1:
775                         phoneNumber = contactDetails[0][1]
776                 else:
777                         phoneNumber = self._phoneTypeSelector.run(contactDetails)
778
779                 if 0 < len(phoneNumber):
780                         self.number_selected(phoneNumber)
781
782                 self._contactsviewselection.unselect_all()