3 # DialCentral - Front end for Google's Grand Central service.
4 # Copyright (C) 2008 Mark Bergman bergman AT merctech DOT com
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.
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.
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
29 def make_ugly(prettynumber):
31 function to take a phone number and strip out all non-numeric
34 >>> make_ugly("+012-(345)-678-90")
38 uglynumber = re.sub('\D', '', prettynumber)
42 def make_pretty(phonenumber):
44 Function to take a phone number and return the pretty version
46 if phonenumber begins with 0:
48 if phonenumber begins with 1: ( for gizmo callback numbers )
50 if phonenumber is 13 digits:
52 if phonenumber is 10 digits:
56 >>> make_pretty("1234567")
58 >>> make_pretty("2345678901")
60 >>> make_pretty("12345678901")
62 >>> make_pretty("01234567890")
65 if phonenumber is None or phonenumber is "":
68 phonenumber = make_ugly(phonenumber)
70 if len(phonenumber) < 3:
73 if phonenumber[0] == "0":
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:]
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:])
94 Decorator that makes a generator-function into a function that will continue execution on next call
98 def decorated_func(*args, **kwds):
100 a.append(func(*args, **kwds))
104 except StopIteration:
108 decorated_func.__name__ = func.__name__
109 decorated_func.__doc__ = func.__doc__
110 decorated_func.__dict__.update(func.__dict__)
112 return decorated_func
115 class DummyAddressBook(object):
117 Minimal example of both an addressbook factory and an addressbook
120 def clear_caches(self):
123 def get_addressbooks(self):
125 @returns Iterable of (Address Book Factory, Book Id, Book Name)
127 yield self, "", "None"
129 def open_addressbook(self, bookId):
133 def contact_source_short_name(contactId):
143 @returns Iterable of (contact id, contact name)
148 def get_contact_details(contactId):
150 @returns Iterable of (Phone Type, Phone Number)
155 class MergedAddressBook(object):
157 Merger of all addressbooks
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
165 def clear_caches(self):
166 self.__addressbooks = None
167 for factory in self.__addressbookFactories:
168 factory.clear_caches()
170 def get_addressbooks(self):
172 @returns Iterable of (Address Book Factory, Book Id, Book Name)
176 def open_addressbook(self, bookId):
179 def contact_source_short_name(self, contactId):
180 if self.__addressbooks is None:
182 bookIndex, originalId = contactId.split("-", 1)
183 return self.__addressbooks[int(bookIndex)].contact_source_short_name(originalId)
187 return "All Contacts"
189 def get_contacts(self):
191 @returns Iterable of (contact id, contact name)
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()
200 ("-".join([str(bookIndex), contactId]), contactName)
201 for (bookIndex, addressbook) in enumerate(self.__addressbooks)
202 for (contactId, contactName) in addressbook.get_contacts()
204 sortedContacts = self.__sort_contacts(contacts)
205 return sortedContacts
207 def get_contact_details(self, contactId):
209 @returns Iterable of (Phone Type, Phone Number)
211 if self.__addressbooks is None:
213 bookIndex, originalId = contactId.split("-", 1)
214 return self.__addressbooks[int(bookIndex)].get_contact_details(originalId)
217 def null_sorter(contacts):
219 Good for speed/low memory
224 def basic_firtname_sorter(contacts):
226 Expects names in "First Last" format
229 (contactName.rsplit(" ", 1)[0], (contactId, contactName))
230 for (contactId, contactName) in contacts
232 contactsWithKey.sort()
233 return (contactData for (lastName, contactData) in contactsWithKey)
236 def basic_lastname_sorter(contacts):
238 Expects names in "First Last" format
241 (contactName.rsplit(" ", 1)[-1], (contactId, contactName))
242 for (contactId, contactName) in contacts
244 contactsWithKey.sort()
245 return (contactData for (lastName, contactData) in contactsWithKey)
248 def reversed_firtname_sorter(contacts):
250 Expects names in "Last, First" format
253 (contactName.split(", ", 1)[-1], (contactId, contactName))
254 for (contactId, contactName) in contacts
256 contactsWithKey.sort()
257 return (contactData for (lastName, contactData) in contactsWithKey)
260 def reversed_lastname_sorter(contacts):
262 Expects names in "Last, First" format
265 (contactName.split(", ", 1)[0], (contactId, contactName))
266 for (contactId, contactName) in contacts
268 contactsWithKey.sort()
269 return (contactData for (lastName, contactData) in contactsWithKey)
272 def guess_firstname(name):
274 return name.split(", ", 1)[-1]
276 return name.rsplit(" ", 1)[0]
279 def guess_lastname(name):
281 return name.split(", ", 1)[0]
283 return name.rsplit(" ", 1)[-1]
286 def advanced_firstname_sorter(cls, contacts):
288 (cls.guess_firstname(contactName), (contactId, contactName))
289 for (contactId, contactName) in contacts
291 contactsWithKey.sort()
292 return (contactData for (lastName, contactData) in contactsWithKey)
295 def advanced_lastname_sorter(cls, contacts):
297 (cls.guess_lastname(contactName), (contactId, contactName))
298 for (contactId, contactName) in contacts
300 contactsWithKey.sort()
301 return (contactData for (lastName, contactData) in contactsWithKey)
304 class PhoneTypeSelector(object):
306 def __init__(self, widgetTree, gcBackend):
307 self._gcBackend = gcBackend
308 self._widgetTree = widgetTree
309 self._dialog = self._widgetTree.get_widget("phonetype_dialog")
311 self._selectButton = self._widgetTree.get_widget("select_button")
312 self._selectButton.connect("clicked", self._on_phonetype_select)
314 self._cancelButton = self._widgetTree.get_widget("cancel_button")
315 self._cancelButton.connect("clicked", self._on_phonetype_cancel)
317 self._typemodel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING)
318 self._typeviewselection = None
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()
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)
329 typeview.append_column(column)
331 self._typeviewselection = typeview.get_selection()
332 self._typeviewselection.set_mode(gtk.SELECTION_SINGLE)
334 def run(self, contactDetails):
335 self._typemodel.clear()
337 for phoneType, phoneNumber in contactDetails:
338 self._typemodel.append((phoneNumber, "%s - %s" % (make_pretty(phoneNumber), phoneType)))
340 userResponse = self._dialog.run()
342 if userResponse == gtk.RESPONSE_OK:
343 model, itr = self._typeviewselection.get_selected()
345 phoneNumber = self._typemodel.get_value(itr, 0)
349 self._typeviewselection.unselect_all()
353 def _on_phonetype_select(self, *args):
354 self._dialog.response(gtk.RESPONSE_OK)
356 def _on_phonetype_cancel(self, *args):
357 self._dialog.response(gtk.RESPONSE_CANCEL)
360 class Dialpad(object):
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
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,
378 widgetTree.signal_autoconnect(callbackMapping)
381 self._dialButton.grab_focus()
386 def dial(self, number):
388 @note Actual dial function is patched in later
390 raise NotImplementedError
392 def get_number(self):
393 return self._phonenumber
395 def set_number(self, number):
397 Set the callback phonenumber
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))
404 warnings.warn(traceback.format_exc())
405 self._errorDisplay.push_message(e.message)
410 def _on_dial_clicked(self, widget):
411 self.dial(self.get_number())
413 def _on_clear_number(self, *args):
416 def _on_digit_clicked(self, widget):
417 self.set_number(self._phonenumber + widget.get_name()[-1])
419 def _on_backspace(self, widget):
420 self.set_number(self._phonenumber[:-1])
422 def _on_clearall(self):
426 def _on_back_pressed(self, widget):
427 self._clearall_id = gobject.timeout_add(1000, self._on_clearall)
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
435 class AccountInfo(object):
437 def __init__(self, widgetTree, backend, errorDisplay):
438 self._errorDisplay = errorDisplay
439 self._backend = backend
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
447 assert self._backend.is_authed()
448 self._accountViewNumberDisplay.set_use_markup(True)
449 self.set_account_number("")
450 self._callbackList.clear()
452 self._onCallbackentryChangedId = self._callbackCombo.get_child().connect("changed", self._on_callbackentry_changed)
455 self._callbackCombo.get_child().disconnect(self._onCallbackentryChangedId)
457 self._callbackList.clear()
459 def get_selected_callback_number(self):
460 return make_ugly(self._callbackCombo.get_child().get_text())
462 def set_account_number(self, number):
464 Displays current account number
466 self._accountViewNumberDisplay.set_label("<span size='23000' weight='bold'>%s</span>" % (number))
469 self.populate_callback_combo()
470 self.set_account_number(self._backend.get_account_number())
473 self._callbackCombo.get_child().set_text("")
474 self.set_account_number("")
476 def populate_callback_combo(self):
477 self._callbackList.clear()
479 callbackNumbers = self._backend.get_callback_numbers()
480 except RuntimeError, e:
481 warnings.warn(traceback.format_exc())
482 self._errorDisplay.push_message(e.message)
485 for number, description in callbackNumbers.iteritems():
486 self._callbackList.append((make_pretty(number),))
488 self._callbackCombo.set_model(self._callbackList)
489 self._callbackCombo.set_text_column(0)
491 callbackNumber = self._backend.get_callback_number()
492 except RuntimeError, e:
493 warnings.warn(traceback.format_exc())
494 self._errorDisplay.push_message(e.message)
496 self._callbackCombo.get_child().set_text(make_pretty(callbackNumber))
498 def _on_callbackentry_changed(self, *args):
500 @todo Potential blocking on web access, maybe we should defer this or put up a dialog?
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)
509 self._backend.set_callback_number(text)
510 except RuntimeError, e:
511 warnings.warn(traceback.format_exc())
512 self._errorDisplay.push_message(e.message)
515 class RecentCallsView(object):
517 def __init__(self, widgetTree, backend, errorDisplay):
518 self._errorDisplay = errorDisplay
519 self._backend = backend
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
527 textrenderer = gtk.CellRendererText()
528 self._recentviewColumn = gtk.TreeViewColumn("Calls", textrenderer, text=1)
529 self._recentviewColumn.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
532 assert self._backend.is_authed()
533 self._recentview.set_model(self._recentmodel)
535 self._recentview.append_column(self._recentviewColumn)
536 self._recentviewselection = self._recentview.get_selection()
537 self._recentviewselection.set_mode(gtk.SELECTION_SINGLE)
539 self._onRecentviewRowActivatedId = self._recentview.connect("row-activated", self._on_recentview_row_activated)
542 self._recentview.disconnect(self._onRecentviewRowActivatedId)
543 self._recentview.remove_column(self._recentviewColumn)
544 self._recentview.set_model(None)
546 def number_selected(self, number):
548 @note Actual dial function is patched in later
550 raise NotImplementedError
553 if (time.time() - self._recenttime) < 300:
555 backgroundPopulate = threading.Thread(target=self._idly_populate_recentview)
556 backgroundPopulate.setDaemon(True)
557 backgroundPopulate.start()
560 self._recenttime = 0.0
561 self._recentmodel.clear()
563 def _idly_populate_recentview(self):
564 self._recenttime = time.time()
565 self._recentmodel.clear()
568 recentItems = self._backend.get_recent()
569 except RuntimeError, e:
570 warnings.warn(traceback.format_exc())
571 gtk.gdk.threads_enter()
573 self._errorDisplay.push_message(e.message)
575 gtk.gdk.threads_leave()
576 self._recenttime = 0.0
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()
584 self._recentmodel.append(item)
586 gtk.gdk.threads_leave()
590 def _on_recentview_row_activated(self, treeview, path, view_column):
591 model, itr = self._recentviewselection.get_selected()
595 self.number_selected(self._recentmodel.get_value(itr, 0))
596 self._recentviewselection.unselect_all()
599 class ContactsView(object):
601 def __init__(self, widgetTree, backend, errorDisplay):
602 self._errorDisplay = errorDisplay
603 self._backend = backend
605 self._addressBook = None
606 self._addressBookFactories = [DummyAddressBook()]
608 self._booksList = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING)
609 self._booksSelectionBox = widgetTree.get_widget("addressbook_combo")
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")
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)
632 self._onContactsviewRowActivatedId = 0
633 self._onAddressbookComboChangedId = 0
634 self._phoneTypeSelector = PhoneTypeSelector(widgetTree, self._backend)
637 assert self._backend.is_authed()
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)
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)
649 entryName = factoryName
653 entryName = "Bad name (%d)" % factoryId
654 row = (str(factoryId), bookId, entryName)
655 self._booksList.append(row)
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)
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)
667 self._contactsview.disconnect(self._onContactsviewRowActivatedId)
668 self._booksSelectionBox.disconnect(self._onAddressbookComboChangedId)
670 self._booksSelectionBox.clear()
671 self._booksSelectionBox.set_model(None)
672 self._contactsview.set_model(None)
673 self._contactsview.remove_column(self._contactColumn)
675 def number_selected(self, number):
677 @note Actual dial function is patched in later
679 raise NotImplementedError
681 def get_addressbooks(self):
683 @returns Iterable of ((Factory Id, Book Id), (Factory Name, Book Name))
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)
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()
697 if (time.time() - self._contactstime) < 300:
699 backgroundPopulate = threading.Thread(target=self._idly_populate_contactsview)
700 backgroundPopulate.setDaemon(True)
701 backgroundPopulate.start()
704 self._contactstime = 0.0
705 self._contactsmodel.clear()
707 def clear_caches(self):
708 for factory in self._addressBookFactories:
709 factory.clear_caches()
710 self._addressBook.clear_caches()
712 def append(self, book):
713 self._addressBookFactories.append(book)
715 def extend(self, books):
716 self._addressBookFactories.extend(books)
718 def _idly_populate_contactsview(self):
719 #@todo Add a lock so only one code path can be in here at a time
722 # completely disable updating the treeview while we populate the data
723 self._contactsview.freeze_child_notify()
724 self._contactsview.set_model(None)
726 addressBook = self._addressBook
728 contacts = addressBook.get_contacts()
729 except RuntimeError, e:
730 warnings.warn(traceback.format_exc())
732 self._contactstime = 0.0
733 gtk.gdk.threads_enter()
735 self._errorDisplay.push_message(e.message)
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) + ("",))
742 # restart the treeview data rendering
743 self._contactsview.set_model(self._contactsmodel)
744 self._contactsview.thaw_child_notify()
747 def _on_addressbook_combo_changed(self, *args, **kwds):
748 itr = self._booksSelectionBox.get_active_iter()
751 factoryId = int(self._booksList.get_value(itr, 0))
752 bookId = self._booksList.get_value(itr, 1)
753 self.open_addressbook(factoryId, bookId)
755 def _on_contactsview_row_activated(self, treeview, path, view_column):
756 model, itr = self._contactsviewselection.get_selected()
760 contactId = self._contactsmodel.get_value(itr, 3)
762 contactDetails = self._addressBook.get_contact_details(contactId)
763 except RuntimeError, e:
764 warnings.warn(traceback.format_exc())
766 self._contactstime = 0.0
767 self._errorDisplay.push_message(e.message)
768 contactDetails = [phoneNumber for phoneNumber in contactDetails]
770 if len(contactDetails) == 0:
772 elif len(contactDetails) == 1:
773 phoneNumber = contactDetails[0][1]
775 phoneNumber = self._phoneTypeSelector.run(contactDetails)
777 if 0 < len(phoneNumber):
778 self.number_selected(phoneNumber)
780 self._contactsviewselection.unselect_all()