individual: Prefer data from personas with writeable properties
[platform/upstream/folks.git] / folks / individual.vala
1 /*
2  * Copyright (C) 2010 Collabora Ltd.
3  * Copyright (C) 2011 Philip Withnall
4  *
5  * This library is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License as published by
7  * the Free Software Foundation, either version 2.1 of the License, or
8  * (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public License
16  * along with this library.  If not, see <http://www.gnu.org/licenses/>.
17  *
18  * Authors:
19  *       Travis Reitter <travis.reitter@collabora.co.uk>
20  *       Philip Withnall <philip@tecnocode.co.uk>
21  */
22
23 using Gee;
24 using GLib;
25
26 /**
27  * Trust level for an {@link Individual} for use in the UI.
28  *
29  * @since 0.1.15
30  */
31 public enum Folks.TrustLevel
32 {
33   /**
34    * The {@link Individual}'s {@link Persona}s aren't trusted at all.
35    *
36    * This is the trust level for an {@link Individual} which contains one or
37    * more {@link Persona}s which cannot be guaranteed to be the same
38    * {@link Persona}s as were originally linked together.
39    *
40    * For example, an {@link Individual} containing a link-local XMPP
41    * {@link Persona} would have this trust level, since someone else could
42    * easily spoof the link-local XMPP {@link Persona}'s identity.
43    *
44    * @since 0.1.15
45    */
46   NONE,
47
48   /**
49    * The {@link Individual}'s {@link Persona}s are trusted.
50    *
51    * This trust level is for {@link Individual}s where it can be guaranteed
52    * that all the {@link Persona}s are the same ones as when they were
53    * originally linked together.
54    *
55    * Note that this doesn't guarantee that the user who behind each
56    * {@link Persona} is who they claim to be.
57    *
58    * @since 0.1.15
59    */
60   PERSONAS
61 }
62
63 /**
64  * A physical person, aggregated from the various {@link Persona}s the person
65  * might have, such as their different IM addresses or vCard entries.
66  *
67  * When choosing the values of single-valued properties (such as
68  * {@link Individual.alias} and {@link Individual.avatar}; but not multi-valued
69  * properties such as {@link Individual.groups} and
70  * {@link Individual.im_addresses}) from the {@link Persona}s in the
71  * individual to present as the values of those properties of the individual,
72  * it is guaranteed that if the individual contains a persona from the primary
73  * persona store (see {@link IndividualAggregator.primary_store}), its property
74  * values will be chosen above all others. This means that any changes to
75  * property values made through folks (which are normally written to the primary
76  * store) will always be used by {@link Individual}s.
77  *
78  * No further guarantees are made about the order of preference used for
79  * choosing which property values to use for the {@link Individual}, other than
80  * that the order may vary between properties, but is guaranteed to be stable
81  * for a given property.
82  */
83 public class Folks.Individual : Object,
84     AliasDetails,
85     AvatarDetails,
86     BirthdayDetails,
87     EmailDetails,
88     FavouriteDetails,
89     GenderDetails,
90     GroupDetails,
91     ImDetails,
92     LocalIdDetails,
93     NameDetails,
94     NoteDetails,
95     PresenceDetails,
96     PhoneDetails,
97     PostalAddressDetails,
98     RoleDetails,
99     UrlDetails,
100     WebServiceDetails
101 {
102   private bool _is_favourite;
103   private string _alias;
104   private HashSet<string> _groups;
105   private Set<string> _groups_ro;
106   /* Stores the Personas contained in this Individual. */
107   private HashSet<Persona> _persona_set;
108   /* Read-only view of the above set */
109   private Set<Persona> _persona_set_ro;
110   /* Mapping from PersonaStore -> number of Personas from that store contained
111    * in this Individual. There shouldn't be any entries with a number < 1.
112    * This is used for working out when to disconnect from store signals. */
113   private HashMap<PersonaStore, uint> _stores;
114   /* The number of Personas in this Individual which have
115    * Persona.is_user == true. Iff this is > 0, Individual.is_user == true. */
116   private uint _persona_user_count = 0;
117   private HashMultiMap<string, ImFieldDetails> _im_addresses;
118   private HashMultiMap<string, WebServiceFieldDetails> _web_service_addresses;
119   private string _nickname = "";
120
121   /**
122    * The trust level of the Individual.
123    *
124    * This specifies how far the Individual can be trusted to be who it claims
125    * to be. See the descriptions for the elements of {@link TrustLevel}.
126    *
127    * Clients should ''not'' allow linking of Individuals who have a trust level
128    * of {@link TrustLevel.NONE}.
129    *
130    * @since 0.1.15
131    */
132   public TrustLevel trust_level { get; private set; }
133
134   private LoadableIcon? _avatar = null;
135
136   /**
137    * {@inheritDoc}
138    *
139    * @since 0.6.0
140    */
141   [CCode (notify = false)]
142   public LoadableIcon? avatar
143     {
144       get { return this._avatar; }
145       set { this.change_avatar.begin (value); } /* not writeable */
146     }
147
148   /*
149    * Change the individual's avatar.
150    *
151    * It's preferred to call this rather than setting {@link Individual.avatar}
152    * directly, as this method gives error notification and will only return once
153    * the avatar has been written to the relevant backing stores (or the
154    * operation's failed).
155    *
156    * Setting this property is only guaranteed to succeed (and be written to
157    * the backing store) if
158    * {@link IndividualAggregator.ensure_individual_property_writeable} has been
159    * called successfully on the individual for the property name `avatar`.
160    *
161    * @param avatar the new avatar (or `null` to unset the avatar)
162    * @throws PropertyError if setting the avatar failed
163    * @since UNRELEASED
164    */
165   public async void change_avatar (LoadableIcon? avatar) throws PropertyError
166     {
167       if ((this._avatar != null && this._avatar.equal (avatar)) ||
168           (this._avatar == null && avatar == null))
169         {
170           return;
171         }
172
173       debug ("Setting avatar of individual '%s' to '%p'…", this.id, avatar);
174
175       PropertyError? persona_error = null;
176       var avatar_changed = false;
177
178       /* Try to write it to only the writeable Personas which have the
179        * "avatar" property as writeable. */
180       foreach (var p in this._persona_set)
181         {
182           var a = p as AvatarDetails;
183           if (a != null && "avatar" in p.writeable_properties)
184             {
185               try
186                 {
187                   yield a.change_avatar (avatar);
188                   debug ("    written to writeable persona '%s'", p.uid);
189                   avatar_changed = true;
190                 }
191               catch (PropertyError e)
192                 {
193                   /* Store the first error so we can throw it if setting the
194                    * avatar fails on every other persona. */
195                   if (persona_error == null)
196                     {
197                       persona_error = e;
198                     }
199                 }
200             }
201         }
202
203       /* Failure? */
204       if (avatar_changed == false)
205         {
206           assert (persona_error != null);
207           throw persona_error;
208         }
209     }
210
211   /**
212    * {@inheritDoc}
213    */
214   public Folks.PresenceType presence_type { get; private set; }
215
216   /**
217    * {@inheritDoc}
218    *
219    * @since 0.6.0
220    */
221   public string presence_status { get; private set; }
222
223   /**
224    * {@inheritDoc}
225    */
226   public string presence_message { get; private set; }
227
228   /**
229    * Whether the Individual is the user.
230    *
231    * Iff the Individual represents the user – the person who owns the
232    * account in the backend for each {@link Persona} in the Individual –
233    * this is `true`.
234    *
235    * It is //not// guaranteed that every {@link Persona} in the Individual has
236    * its {@link Persona.is_user} set to the same value as the Individual. For
237    * example, the user could own two Telepathy accounts, and have added the
238    * other account as a contact in each account. The accounts will expose a
239    * {@link Persona} for the user (which will have {@link Persona.is_user} set
240    * to `true`) //and// a {@link Persona} for the contact for the other account
241    * (which will have {@link Persona.is_user} set to `false`).
242    *
243    * It is guaranteed that iff this property is set to `true` on an Individual,
244    * there will be at least one {@link Persona} in the Individual with its
245    * {@link Persona.is_user} set to `true`.
246    *
247    * It is guaranteed that there will only ever be one Individual with this
248    * property set to `true`.
249    *
250    * @since 0.3.0
251    */
252   public bool is_user { get; private set; }
253
254   /**
255    * A unique identifier for the Individual.
256    *
257    * This uniquely identifies the Individual, and persists across
258    * {@link IndividualAggregator} instances. It may not persist across linking
259    * the Individual with other Individuals.
260    *
261    * This is an opaque string and has no structure.
262    *
263    * If an identifier is required which will be used for a long-lived link
264    * between different stored data, it may be more desirable to use the
265    * {@link Persona.uid} of the most relevant {@link Persona} in the Individual
266    * instead. For example, if storing references to Individuals who are tagged
267    * in a photo, it may be safer to store the UID of the Persona whose backend
268    * provided the photo (e.g. Facebook).
269    */
270   public string id { get; private set; }
271
272   /**
273    * Emitted when the last of the Individual's {@link Persona}s has been
274    * removed.
275    *
276    * At this point, the Individual is invalid, so any client referencing it
277    * should unreference it and remove it from their UI.
278    *
279    * @param replacement_individual the individual which has replaced this one
280    * due to linking, or `null` if this individual was removed for another reason
281    * @since 0.1.13
282    */
283   public signal void removed (Individual? replacement_individual);
284
285   /**
286    * {@inheritDoc}
287    */
288   [CCode (notify = false)]
289   public string alias
290     {
291       get { return this._alias; }
292       set { this.change_alias.begin (value); }
293     }
294
295   /**
296    * {@inheritDoc}
297    *
298    * @since 0.6.2
299    */
300   public async void change_alias (string alias) throws PropertyError
301     {
302       if (this._alias == alias)
303         {
304           return;
305         }
306
307       debug ("Setting alias of individual '%s' to '%s'…", this.id, alias);
308
309       PropertyError? persona_error = null;
310       var alias_changed = false;
311
312       /* Try to write it to only the writeable Personas which have "alias"
313        * as a writeable property. */
314       foreach (var p in this._persona_set)
315         {
316           var a = p as AliasDetails;
317           if (a != null && "alias" in p.writeable_properties)
318             {
319               try
320                 {
321                   yield a.change_alias (alias);
322                   debug ("    written to writeable persona '%s'", p.uid);
323                   alias_changed = true;
324                 }
325               catch (PropertyError e)
326                 {
327                   /* Store the first error so we can throw it if setting the
328                    * alias fails on every other persona. */
329                   if (persona_error == null)
330                     {
331                       persona_error = e;
332                     }
333                 }
334             }
335         }
336
337       /* Failure? */
338       if (alias_changed == false)
339         {
340           assert (persona_error != null);
341           throw persona_error;
342         }
343
344       /* Update our copy of the alias. */
345       this._alias = alias;
346       this.notify_property ("alias");
347     }
348
349   private StructuredName? _structured_name = null;
350
351   /**
352    * {@inheritDoc}
353    */
354   [CCode (notify = false)]
355   public StructuredName? structured_name
356     {
357       get { return this._structured_name; }
358       set { this.change_structured_name.begin (value); } /* not writeable */
359     }
360
361   private string _full_name = "";
362
363   /**
364    * {@inheritDoc}
365    */
366   [CCode (notify = false)]
367   public string full_name
368     {
369       get { return this._full_name; }
370       set { this.change_full_name.begin (value); } /* not writeable */
371     }
372
373   /**
374    * {@inheritDoc}
375    */
376   [CCode (notify = false)]
377   public string nickname
378     {
379       get { return this._nickname; }
380       set { this.change_nickname.begin (value); }
381     }
382
383   /**
384    * {@inheritDoc}
385    *
386    * @since 0.6.2
387    */
388   public async void change_nickname (string nickname) throws PropertyError
389     {
390       // Normalise null values to the empty string
391       if (nickname == null)
392         {
393           nickname = "";
394         }
395
396       if (this._nickname == nickname)
397         {
398           return;
399         }
400
401       debug ("Setting nickname of individual '%s' to '%s'…", this.id, nickname);
402
403       PropertyError? persona_error = null;
404       var nickname_changed = false;
405
406       /* Try to write it to only the writeable Personas which have "nickname"
407        * as a writeable property. */
408       foreach (var p in this._persona_set)
409         {
410           var n = p as NameDetails;
411           if (n != null && "nickname" in p.writeable_properties)
412             {
413               try
414                 {
415                   yield n.change_nickname (nickname);
416                   debug ("    written to writeable persona '%s'", p.uid);
417                   nickname_changed = true;
418                 }
419               catch (PropertyError e)
420                 {
421                   /* Store the first error so we can throw it if setting the
422                    * nickname fails on every other persona. */
423                   if (persona_error == null)
424                     {
425                       persona_error = e;
426                     }
427                 }
428             }
429         }
430
431       /* Failure? */
432       if (nickname_changed == false)
433         {
434           assert (persona_error != null);
435           throw persona_error;
436         }
437
438       /* Update our copy of the nickname. */
439       this._nickname = nickname;
440       this.notify_property ("nickname");
441     }
442
443   private Gender _gender = Gender.UNSPECIFIED;
444   /**
445    * {@inheritDoc}
446    */
447   [CCode (notify = false)]
448   public Gender gender
449     {
450       get { return this._gender; }
451       set { this.change_gender.begin (value); } /* not writeable */
452     }
453
454   private HashSet<UrlFieldDetails> _urls;
455   private Set<UrlFieldDetails> _urls_ro;
456
457   /**
458    * {@inheritDoc}
459    */
460   [CCode (notify = false)]
461   public Set<UrlFieldDetails> urls
462     {
463       get { return this._urls_ro; }
464       set { this.change_urls.begin (value); } /* not writeable */
465     }
466
467   private HashSet<PhoneFieldDetails> _phone_numbers;
468   private Set<PhoneFieldDetails> _phone_numbers_ro;
469
470   /**
471    * {@inheritDoc}
472    */
473   [CCode (notify = false)]
474   public Set<PhoneFieldDetails> phone_numbers
475     {
476       get { return this._phone_numbers_ro; }
477       set { this.change_phone_numbers.begin (value); } /* not writeable */
478     }
479
480   private HashSet<EmailFieldDetails> _email_addresses;
481   private Set<EmailFieldDetails> _email_addresses_ro;
482
483   /**
484    * {@inheritDoc}
485    */
486   [CCode (notify = false)]
487   public Set<EmailFieldDetails> email_addresses
488     {
489       get { return this._email_addresses_ro; }
490       set { this.change_email_addresses.begin (value); } /* not writeable */
491     }
492
493   private HashSet<RoleFieldDetails> _roles;
494   private Set<RoleFieldDetails> _roles_ro;
495
496   /**
497    * {@inheritDoc}
498    */
499   [CCode (notify = false)]
500   public Set<RoleFieldDetails> roles
501     {
502       get { return this._roles_ro; }
503       set { this.change_roles.begin (value); } /* not writeable */
504     }
505
506   private HashSet<string> _local_ids;
507   private Set<string> _local_ids_ro;
508
509   /**
510    * {@inheritDoc}
511    */
512   [CCode (notify = false)]
513   public Set<string> local_ids
514     {
515       get { return this._local_ids_ro; }
516       set { this.change_local_ids.begin (value); } /* not writeable */
517     }
518
519   private DateTime? _birthday = null;
520
521   /**
522    * {@inheritDoc}
523    */
524   [CCode (notify = false)]
525   public DateTime? birthday
526     {
527       get { return this._birthday; }
528       set { this.change_birthday.begin (value); } /* not writeable */
529     }
530
531   private string? _calendar_event_id = null;
532
533   /**
534    * {@inheritDoc}
535    */
536   [CCode (notify = false)]
537   public string? calendar_event_id
538     {
539       get { return this._calendar_event_id; }
540       set { this.change_calendar_event_id.begin (value); } /* not writeable */
541     }
542
543   private HashSet<NoteFieldDetails> _notes;
544   private Set<NoteFieldDetails> _notes_ro;
545
546   /**
547    * {@inheritDoc}
548    */
549   [CCode (notify = false)]
550   public Set<NoteFieldDetails> notes
551     {
552       get { return this._notes_ro; }
553       set { this.change_notes.begin (value); } /* not writeable */
554     }
555
556   private HashSet<PostalAddressFieldDetails> _postal_addresses;
557   private Set<PostalAddressFieldDetails> _postal_addresses_ro;
558
559   /**
560    * {@inheritDoc}
561    */
562   [CCode (notify = false)]
563   public Set<PostalAddressFieldDetails> postal_addresses
564     {
565       get { return this._postal_addresses_ro; }
566       set { this.change_postal_addresses.begin (value); } /* not writeable */
567     }
568
569   /**
570    * Whether this Individual is a user-defined favourite.
571    *
572    * This property is `true` if any of this Individual's {@link Persona}s are
573    * favourites).
574    */
575   [CCode (notify = false)]
576   public bool is_favourite
577     {
578       get { return this._is_favourite; }
579       set { this.change_is_favourite.begin (value); }
580     }
581
582   /**
583    * {@inheritDoc}
584    *
585    * @since 0.6.2
586    */
587   public async void change_is_favourite (bool is_favourite) throws PropertyError
588     {
589       if (this._is_favourite == is_favourite)
590         {
591           return;
592         }
593
594       debug ("Setting '%s' favourite status to %s…", this.id,
595         is_favourite ? "TRUE" : "FALSE");
596
597       PropertyError? persona_error = null;
598       var is_favourite_changed = false;
599
600       /* Try to write it to only the Personas which have "is-favourite" as a
601        * writeable property.
602        *
603        * NOTE: We don't check whether the persona's store is writeable, as we
604        * want is-favourite status to propagate to all stores, if possible. This
605        * is one property which is harmless to propagate. */
606       foreach (var p in this._persona_set)
607         {
608           var a = p as FavouriteDetails;
609           if (a != null && "is-favourite" in p.writeable_properties)
610             {
611               try
612                 {
613                   yield a.change_is_favourite (is_favourite);
614                   debug ("    written to persona '%s'", p.uid);
615                   is_favourite_changed = true;
616                 }
617               catch (PropertyError e)
618                 {
619                   /* Store the first error so we can throw it if setting the
620                    * property fails on every other persona. */
621                   if (persona_error == null)
622                     {
623                       persona_error = e;
624                     }
625                 }
626             }
627         }
628
629       /* Failure? */
630       if (is_favourite_changed == false)
631         {
632           assert (persona_error != null);
633           throw persona_error;
634         }
635
636       /* Update our copy of the property. */
637       this._is_favourite = is_favourite;
638       this.notify_property ("is-favourite");
639     }
640
641   /**
642    * {@inheritDoc}
643    */
644   [CCode (notify = false)]
645   public Set<string> groups
646     {
647       get { return this._groups_ro; }
648       set { this.change_groups.begin (value); }
649     }
650
651   /**
652    * {@inheritDoc}
653    *
654    * @since 0.6.2
655    */
656   public async void change_groups (Set<string> groups) throws PropertyError
657     {
658       debug ("Setting '%s' groups…", this.id);
659
660       PropertyError? persona_error = null;
661       var groups_changed = false;
662
663       /* Try to write it to only the Personas which have "groups" as a
664        * writeable property. */
665       foreach (var p in this._persona_set)
666         {
667           var g = p as GroupDetails;
668           if (g != null && "groups" in p.writeable_properties)
669             {
670               try
671                 {
672                   yield g.change_groups (groups);
673                   debug ("    written to persona '%s'", p.uid);
674                   groups_changed = true;
675                 }
676               catch (PropertyError e)
677                 {
678                   /* Store the first error so we can throw it if setting the
679                    * property fails on every other persona. */
680                   if (persona_error == null)
681                     {
682                       persona_error = e;
683                     }
684                 }
685             }
686         }
687
688       /* Failure? */
689       if (groups_changed == false)
690         {
691           assert (persona_error != null);
692           throw persona_error;
693         }
694
695       /* Update our copy of the property. */
696       this._update_groups ();
697     }
698
699   /**
700    * {@inheritDoc}
701    */
702   [CCode (notify = false)]
703   public MultiMap<string, ImFieldDetails> im_addresses
704     {
705       get { return this._im_addresses; }
706       set { this.change_im_addresses.begin (value); } /* not writeable */
707     }
708
709   /**
710    * {@inheritDoc}
711    */
712   [CCode (notify = false)]
713   public MultiMap<string, WebServiceFieldDetails> web_service_addresses
714     {
715       get { return this._web_service_addresses; }
716       /* Not writeable: */
717       set { this.change_web_service_addresses.begin (value); }
718     }
719
720   /**
721    * The set of {@link Persona}s encapsulated by this Individual.
722    *
723    * No order is specified over the set of personas, as such an order may be
724    * different across each of the properties implemented by the personas (e.g.
725    * should they be ordered by presence, name, star sign, etc.?).
726    *
727    * Changing the set of personas may cause updates to the aggregated properties
728    * provided by the Individual, resulting in property notifications for them.
729    *
730    * Changing the set of personas will not cause permanent linking/unlinking of
731    * the added/removed personas to/from this Individual. To do that, call
732    * {@link IndividualAggregator.link_personas} or
733    * {@link IndividualAggregator.unlink_individual}, which will ensure the link
734    * changes are written to the appropriate backend.
735    *
736    * @since 0.5.1
737    */
738   public Set<Persona> personas
739     {
740       get { return this._persona_set_ro; }
741       set { this._set_personas (value, null); }
742     }
743
744   /**
745    * Emitted when one or more {@link Persona}s are added to or removed from
746    * the Individual. As the parameters are (unordered) sets, the orders of their
747    * elements are undefined.
748    *
749    * @param added a set of {@link Persona}s which have been added
750    * @param removed a set of {@link Persona}s which have been removed
751    *
752    * @since 0.5.1
753    */
754   public signal void personas_changed (Set<Persona> added,
755       Set<Persona> removed);
756
757   private void _notify_alias_cb (Object obj, ParamSpec ps)
758     {
759       this._update_alias ();
760     }
761
762   private void _notify_avatar_cb (Object obj, ParamSpec ps)
763     {
764       this._update_avatar ();
765     }
766
767   private void _notify_full_name_cb ()
768     {
769       this._update_full_name ();
770     }
771
772   private void _notify_structured_name_cb ()
773     {
774       this._update_structured_name ();
775     }
776
777   private void _notify_nickname_cb ()
778     {
779       this._update_nickname ();
780     }
781
782   private void _persona_group_changed_cb (string group, bool is_member)
783     {
784       this._update_groups ();
785     }
786
787   private void _notify_gender_cb ()
788     {
789       this._update_gender ();
790     }
791
792   private void _notify_urls_cb ()
793     {
794       this._update_urls ();
795     }
796
797   private void _notify_phone_numbers_cb ()
798     {
799       this._update_phone_numbers ();
800     }
801
802   private void _notify_postal_addresses_cb ()
803     {
804       this._update_postal_addresses ();
805     }
806
807   private void _notify_email_addresses_cb ()
808     {
809       this._update_email_addresses ();
810     }
811
812   private void _notify_roles_cb ()
813     {
814       this._update_roles ();
815     }
816
817   private void _notify_birthday_cb ()
818     {
819       this._update_birthday ();
820     }
821
822   private void _notify_notes_cb ()
823     {
824       this._update_notes ();
825     }
826
827   private void _notify_local_ids_cb ()
828     {
829       this._update_local_ids ();
830     }
831
832   /**
833    * Add or remove the Individual from the specified group.
834    *
835    * If `is_member` is `true`, the Individual will be added to the `group`. If
836    * it is `false`, they will be removed from the `group`.
837    *
838    * The group membership change will propagate to every {@link Persona} in
839    * the Individual.
840    *
841    * @param group a freeform group identifier
842    * @param is_member whether the Individual should be a member of the group
843    * @since 0.1.11
844    */
845   public async void change_group (string group, bool is_member)
846     {
847       foreach (var p in this._persona_set)
848         {
849           if (p is GroupDetails)
850             ((GroupDetails) p).change_group.begin (group, is_member);
851         }
852
853       /* don't notify, since it hasn't happened in the persona backing stores
854        * yet; react to that directly */
855     }
856
857   private void _notify_presence_cb (Object obj, ParamSpec ps)
858     {
859       this._update_presence ();
860     }
861
862   private void _notify_im_addresses_cb (Object obj, ParamSpec ps)
863     {
864       this._update_im_addresses ();
865     }
866
867   private void _notify_web_service_addresses_cb (Object obj, ParamSpec ps)
868     {
869       this._update_web_service_addresses ();
870     }
871
872   private void _notify_is_favourite_cb (Object obj, ParamSpec ps)
873     {
874       this._update_is_favourite ();
875     }
876
877   /**
878    * Create a new Individual.
879    *
880    * The Individual can optionally be seeded with the {@link Persona}s in
881    * `personas`. Otherwise, it will have to have personas added using the
882    * {@link Folks.Individual.personas} property after construction.
883    *
884    * @param personas a list of {@link Persona}s to initialise the
885    * {@link Individual} with, or `null`
886    * @return a new Individual
887    *
888    * @since 0.5.1
889    */
890   public Individual (Set<Persona>? personas)
891     {
892       debug ("Creating new Individual with %u Personas: %p",
893           (personas != null ? personas.size : 0), this);
894
895       this._im_addresses = new HashMultiMap<string, ImFieldDetails> (
896           null, null, ImFieldDetails.hash, (EqualFunc) ImFieldDetails.equal);
897       this._web_service_addresses =
898         new HashMultiMap<string, WebServiceFieldDetails> (
899             null, null,
900             (GLib.HashFunc) WebServiceFieldDetails.hash,
901             (GLib.EqualFunc) WebServiceFieldDetails.equal);
902       this._persona_set =
903           new HashSet<Persona> (direct_hash, direct_equal);
904       this._persona_set_ro = this._persona_set.read_only_view;
905       this._stores = new HashMap<PersonaStore, uint> (null, null);
906       this._gender = Gender.UNSPECIFIED;
907       this._urls = new HashSet<UrlFieldDetails> (
908           (GLib.HashFunc) UrlFieldDetails.hash,
909           (GLib.EqualFunc) UrlFieldDetails.equal);
910       this._urls_ro = this._urls.read_only_view;
911       this._phone_numbers = new HashSet<PhoneFieldDetails> (
912           (GLib.HashFunc) PhoneFieldDetails.hash,
913           (GLib.EqualFunc) PhoneFieldDetails.equal);
914       this._phone_numbers_ro = this._phone_numbers.read_only_view;
915       this._email_addresses = new HashSet<EmailFieldDetails> (
916           (GLib.HashFunc) EmailFieldDetails.hash,
917           (GLib.EqualFunc) EmailFieldDetails.equal);
918       this._email_addresses_ro = this._email_addresses.read_only_view;
919       this._roles = new HashSet<RoleFieldDetails> (
920           (GLib.HashFunc) RoleFieldDetails.hash,
921           (GLib.EqualFunc) RoleFieldDetails.equal);
922       this._roles_ro = this._roles.read_only_view;
923       this._local_ids = new HashSet<string> ();
924       this._local_ids_ro = this._local_ids.read_only_view;
925       this._postal_addresses = new HashSet<PostalAddressFieldDetails> (
926           (GLib.HashFunc) PostalAddressFieldDetails.hash,
927           (GLib.EqualFunc) PostalAddressFieldDetails.equal);
928       this._postal_addresses_ro = this._postal_addresses.read_only_view;
929       this._notes = new HashSet<NoteFieldDetails> (
930           (GLib.HashFunc) NoteFieldDetails.hash,
931           (GLib.EqualFunc) NoteFieldDetails.equal);
932       this._notes_ro = this._notes.read_only_view;
933
934       this.personas = personas;
935     }
936
937   ~Individual ()
938     {
939       debug ("Destroying Individual '%s': %p", this.id, this);
940     }
941
942   /* Emit the personas-changed signal, turning null parameters into empty sets
943    * and ensuring that the signal is emitted with read-only views of the sets
944    * so that signal handlers can't modify the sets. */
945   private void _emit_personas_changed (Set<Persona>? added,
946       Set<Persona>? removed)
947     {
948       var _added = added;
949       var _removed = removed;
950
951       if ((added == null || added.size == 0) &&
952           (removed == null || removed.size == 0))
953         {
954           /* Emitting it with no added or removed personas is pointless */
955           return;
956         }
957       else if (added == null)
958         {
959           _added = new HashSet<Persona> ();
960         }
961       else if (removed == null)
962         {
963           _removed = new HashSet<Persona> ();
964         }
965
966       this.personas_changed (_added.read_only_view, _removed.read_only_view);
967     }
968
969   private void _store_removed_cb (PersonaStore store)
970     {
971       var remaining_personas = new HashSet<Persona> ();
972
973       /* Build a set of the remaining personas (those which weren't in the
974        * removed store. */
975       foreach (var persona in this._persona_set)
976         {
977           if (persona.store != store)
978             {
979               remaining_personas.add (persona);
980             }
981         }
982
983       this._set_personas (remaining_personas, null);
984     }
985
986   private void _store_personas_changed_cb (PersonaStore store,
987       Set<Persona> added,
988       Set<Persona> removed,
989       string? message,
990       Persona? actor,
991       GroupDetails.ChangeReason reason)
992     {
993       var remaining_personas = new HashSet<Persona> ();
994
995       /* Build a set of the remaining personas (those which aren't in the
996        * set of removed personas). */
997       foreach (var persona in this._persona_set)
998         {
999           if (!removed.contains (persona))
1000             {
1001               remaining_personas.add (persona);
1002             }
1003         }
1004
1005       this._set_personas (remaining_personas, null);
1006     }
1007
1008   private void _update_fields ()
1009     {
1010       this._update_groups ();
1011       this._update_presence ();
1012       this._update_is_favourite ();
1013       this._update_avatar ();
1014       this._update_alias ();
1015       this._update_trust_level ();
1016       this._update_im_addresses ();
1017       this._update_web_service_addresses ();
1018       this._update_structured_name ();
1019       this._update_full_name ();
1020       this._update_nickname ();
1021       this._update_gender ();
1022       this._update_urls ();
1023       this._update_phone_numbers ();
1024       this._update_email_addresses ();
1025       this._update_roles ();
1026       this._update_birthday ();
1027       this._update_notes ();
1028       this._update_postal_addresses ();
1029       this._update_local_ids ();
1030     }
1031
1032   /* Delegate to update the value of a property on this individual from the
1033    * given chosen persona. The chosen_persona may be null, in which case we have
1034    * to set a default value.
1035    *
1036    * Used in _update_single_valued_property(), below. */
1037   private delegate void SingleValuedPropertySetter (Persona? chosen_persona);
1038
1039   /*
1040    * Update a single-valued property from the values in the personas.
1041    *
1042    * Single-valued properties are ones such as {@link Individual.alias} or
1043    * {@link Individual.gender} — as opposed to multi-valued ones (which are
1044    * generally sets) such as {@link Individual.im_addresses} or
1045    * {@link Individual.groups}.
1046    *
1047    * This function uses the given comparison function to order the personas in
1048    * this individual, with the highest-positioned persona (the “greatest”
1049    * persona in the total order) finally being passed to the setter function to
1050    * use in updating the individual's value for the given property. i.e. If
1051    * `compare_func(a, b)` is called and returns > 0, persona `a` will be passed
1052    * to the setter.
1053    *
1054    * At a level above `compare_func`, the function always prefers personas from
1055    * the primary store (see {@link IndividualAggregator.primary_store}) over
1056    * those which aren't.
1057    *
1058    * Note that if a suitable persona isn't found in the individual (if, for
1059    * example, no personas in the individual implement the desired interface),
1060    * `null` will be passed to `setter`, which should then set the individual's
1061    * property to a default value.
1062    *
1063    * @param interface_type the type of interface which all personas under
1064    * consideration must implement ({@link Persona} to select all personas)
1065    * @param compare_func comparison function to order personas for selection
1066    * @param prop_name name of the property being set, as used in
1067    * {@link Persona.writeable_properties}
1068    * @param setter function to update the individual with the chosen value
1069    * @since 0.6.2
1070    */
1071   private void _update_single_valued_property (Type interface_type,
1072       CompareFunc<Persona> compare_func, string prop_name,
1073       SingleValuedPropertySetter setter)
1074     {
1075       CompareDataFunc<Persona> primary_compare_func = (a, b) =>
1076         {
1077           assert (a != null);
1078           assert (b != null);
1079
1080           var a_is_primary = a.store.is_primary_store;
1081           var b_is_primary = b.store.is_primary_store;
1082
1083           if (a_is_primary != b_is_primary)
1084             {
1085               return (a_is_primary ? 1 : 0) - (b_is_primary ? 1 : 0);
1086             }
1087
1088           /* If both personas have the same is-primary value, prefer personas
1089            * which have the given property as writeable over those which
1090            * don't. */
1091           var a_is_writeable = (prop_name in a.writeable_properties);
1092           var b_is_writeable = (prop_name in b.writeable_properties);
1093
1094           if (a_is_writeable != b_is_writeable)
1095             {
1096               return (a_is_writeable ? 1 : 0) - (b_is_writeable ? 1 : 0);
1097             }
1098
1099           /* If both personas have the same writeability for this property, fall
1100            * back to the given comparison function. If the comparison function
1101            * gives them an equal order, we use the personas' UIDs to ensure that
1102            * we end up with a total order over all personas in the individual
1103            * (otherwise we might end up with unstable property values). */
1104           var order = compare_func (a, b);
1105
1106           if (order == 0)
1107             {
1108               order = strcmp (a.uid, b.uid);
1109             }
1110
1111           return order;
1112         };
1113
1114       Persona? candidate_p = null;
1115
1116       foreach (var p in this._persona_set)
1117         {
1118           /* We only care about personas implementing the given interface. */
1119           if (p.get_type ().is_a (interface_type))
1120             {
1121               if (candidate_p == null ||
1122                   primary_compare_func (p, candidate_p) > 0)
1123                 {
1124                   candidate_p = p;
1125                 }
1126             }
1127         }
1128
1129       /* Update the property with the values from the best candidate persona we
1130        * found. Note that it's possible for candidate_p to be null if (e.g.)
1131        * none of this._persona_set implemented the interface. */
1132       setter (candidate_p);
1133     }
1134
1135   private void _update_groups ()
1136     {
1137       var new_groups = new HashSet<string> ();
1138
1139       /* this._groups is null during initial construction */
1140       if (this._groups == null)
1141         {
1142           this._groups = new HashSet<string> ();
1143           this._groups_ro = this._groups.read_only_view;
1144         }
1145
1146       /* FIXME: this should partition the personas by store (maybe we should
1147        * keep that mapping in general in this class), and execute
1148        * "groups-changed" on the store (with the set of personas), to allow the
1149        * back-end to optimize it (like Telepathy will for MembersChanged for the
1150        * groups channel list) */
1151       foreach (var p in this._persona_set)
1152         {
1153           if (p is GroupDetails)
1154             {
1155               var persona = (GroupDetails) p;
1156
1157               foreach (var group in persona.groups)
1158                 {
1159                   new_groups.add (group);
1160                 }
1161             }
1162         }
1163
1164       foreach (var group in new_groups)
1165         {
1166           if (!this._groups.contains (group))
1167             {
1168               this._groups.add (group);
1169               foreach (var g in this._groups)
1170                 {
1171                   debug ("   %s", g);
1172                 }
1173
1174               this.group_changed (group, true);
1175             }
1176         }
1177
1178       /* buffer the removals, so we don't remove while iterating */
1179       var removes = new GLib.List<string> ();
1180       foreach (var group in this._groups)
1181         {
1182           if (!new_groups.contains (group))
1183             removes.prepend (group);
1184         }
1185
1186       removes.foreach ((l) =>
1187         {
1188           unowned string group = (string) l;
1189           this._groups.remove (group);
1190           this.group_changed (group, false);
1191         });
1192     }
1193
1194   private void _update_presence ()
1195     {
1196       this._update_single_valued_property (typeof (PresenceDetails), (a, b) =>
1197         {
1198           var a_presence = (a as PresenceDetails).presence_type;
1199           var b_presence = (b as PresenceDetails).presence_type;
1200
1201           return PresenceDetails.typecmp (a_presence, b_presence);
1202         }, "presence", (p) =>
1203         {
1204           var presence_message = ""; /* must not be null */
1205           var presence_status = ""; /* must not be null */
1206           var presence_type = Folks.PresenceType.UNSET;
1207
1208           if (p != null)
1209             {
1210               presence_type = (p as PresenceDetails).presence_type;
1211               presence_message = (p as PresenceDetails).presence_message;
1212               presence_status = (p as PresenceDetails).presence_status;
1213             }
1214
1215           /* Only notify if any of the values have changed. */
1216           if (this.presence_type != presence_type ||
1217               this.presence_message != presence_message ||
1218               this.presence_status != presence_status)
1219             {
1220               this.freeze_notify ();
1221               this.presence_message = presence_message;
1222               this.presence_type = presence_type;
1223               this.presence_status = presence_status;
1224               this.thaw_notify ();
1225             }
1226         });
1227     }
1228
1229   private void _update_is_favourite ()
1230     {
1231       this._update_single_valued_property (typeof (FavouriteDetails), (a, b) =>
1232         {
1233           var a_is_favourite = (a as FavouriteDetails).is_favourite;
1234           var b_is_favourite = (b as FavouriteDetails).is_favourite;
1235
1236           return ((a_is_favourite == true) ? 1 : 0) -
1237                  ((b_is_favourite == true) ? 1 : 0);
1238         }, "is-favourite", (p) =>
1239         {
1240           var favourite = false;
1241
1242           if (p != null)
1243             {
1244               favourite = (p as FavouriteDetails).is_favourite;
1245             }
1246
1247           /* Only notify if the value has changed. We have to set the private
1248            * member and notify manually, or we'd end up propagating the new
1249            * favourite status back down to all our Personas. */
1250           if (this._is_favourite != favourite)
1251             {
1252               this._is_favourite = favourite;
1253               this.notify_property ("is-favourite");
1254             }
1255         });
1256     }
1257
1258   private void _update_alias ()
1259     {
1260       this._update_single_valued_property (typeof (AliasDetails), (a, b) =>
1261         {
1262           var a_alias = (a as AliasDetails).alias;
1263           var b_alias = (b as AliasDetails).alias;
1264
1265           assert (a_alias != null);
1266           assert (b_alias != null);
1267
1268           var a_is_empty = (a_alias.strip () == "") ? 1 : 0;
1269           var b_is_empty = (b_alias.strip () == "") ? 1 : 0;
1270
1271           /* We prefer to not have an alias which is the same as the Persona's
1272            * display-id, since having such an alias implies that it's the
1273            * default. However, we prefer using such an alias to using the
1274            * Persona's UID, which is our ultimate fallback (below). */
1275           var a_is_display_id = (a_alias == a.display_id) ? 1 : 0;
1276           var b_is_display_id = (b_alias == b.display_id) ? 1 : 0;
1277
1278           return (b_is_empty + b_is_display_id) -
1279                  (a_is_empty + a_is_display_id);
1280         }, "alias", (p) =>
1281         {
1282           string alias = ""; /* must not be null */
1283
1284           if (p != null)
1285             {
1286               alias = (p as AliasDetails).alias.strip ();
1287             }
1288
1289           /* Only notify if the value has changed. We have to set the private
1290            * member and notify manually, or we'd end up propagating the new
1291            * alias back down to all our Personas, even if it's a fallback
1292            * display ID or something else undesirable. */
1293           if (this._alias != alias)
1294             {
1295               this._alias = alias;
1296               this.notify_property ("alias");
1297             }
1298         });
1299     }
1300
1301   private void _update_avatar ()
1302     {
1303       this._update_single_valued_property (typeof (AvatarDetails), (a, b) =>
1304         {
1305           var a_avatar = (a as AvatarDetails).avatar;
1306           var b_avatar = (b as AvatarDetails).avatar;
1307
1308           return ((a_avatar != null) ? 1 : 0) - ((b_avatar != null) ? 1 : 0);
1309         }, "avatar", (p) =>
1310         {
1311           LoadableIcon? avatar = null;
1312
1313           if (p != null)
1314             {
1315               avatar = (p as AvatarDetails).avatar;
1316             }
1317
1318           /* only notify if the value has changed */
1319           if ((this._avatar == null && avatar != null) ||
1320               (this._avatar != null &&
1321                (avatar == null || !this._avatar.equal (avatar))))
1322             {
1323               this._avatar = avatar;
1324               this.notify_property ("avatar");
1325             }
1326         });
1327     }
1328
1329   private void _update_trust_level ()
1330     {
1331       var trust_level = TrustLevel.PERSONAS;
1332
1333       foreach (var p in this._persona_set)
1334         {
1335           if (p.is_user == false &&
1336               p.store.trust_level == PersonaStoreTrust.NONE)
1337             trust_level = TrustLevel.NONE;
1338         }
1339
1340       /* Only notify if the value has changed */
1341       if (this.trust_level != trust_level)
1342         this.trust_level = trust_level;
1343     }
1344
1345   private void _update_im_addresses ()
1346     {
1347       /* populate the IM addresses as the union of our Personas' addresses */
1348       this._im_addresses.clear ();
1349
1350       foreach (var persona in this._persona_set)
1351         {
1352           if (persona is ImDetails)
1353             {
1354               var im_details = (ImDetails) persona;
1355               foreach (var cur_protocol in im_details.im_addresses.get_keys ())
1356                 {
1357                   var cur_addresses =
1358                       im_details.im_addresses.get (cur_protocol);
1359
1360                   foreach (var address in cur_addresses)
1361                     {
1362                       this._im_addresses.set (cur_protocol, address);
1363                     }
1364                 }
1365             }
1366         }
1367       this.notify_property ("im-addresses");
1368     }
1369
1370   private void _update_web_service_addresses ()
1371     {
1372       /* populate the web service addresses as the union of our Personas' addresses */
1373       this._web_service_addresses.clear ();
1374
1375       foreach (var persona in this.personas)
1376         {
1377           if (persona is WebServiceDetails)
1378             {
1379               var web_service_details = (WebServiceDetails) persona;
1380               foreach (var cur_web_service in
1381                   web_service_details.web_service_addresses.get_keys ())
1382                 {
1383                   var cur_addresses =
1384                       web_service_details.web_service_addresses.get (
1385                           cur_web_service);
1386
1387                   foreach (var ws_fd in cur_addresses)
1388                     this._web_service_addresses.set (cur_web_service, ws_fd);
1389                 }
1390             }
1391         }
1392       this.notify_property ("web-service-addresses");
1393     }
1394
1395   private void _connect_to_persona (Persona persona)
1396     {
1397       persona.individual = this;
1398
1399       persona.notify["alias"].connect (this._notify_alias_cb);
1400       persona.notify["avatar"].connect (this._notify_avatar_cb);
1401       persona.notify["presence-message"].connect (this._notify_presence_cb);
1402       persona.notify["presence-type"].connect (this._notify_presence_cb);
1403       persona.notify["im-addresses"].connect (this._notify_im_addresses_cb);
1404       persona.notify["web-service-addresses"].connect
1405               (this._notify_web_service_addresses_cb);
1406       persona.notify["is-favourite"].connect (this._notify_is_favourite_cb);
1407       persona.notify["structured-name"].connect (
1408           this._notify_structured_name_cb);
1409       persona.notify["full-name"].connect (this._notify_full_name_cb);
1410       persona.notify["nickname"].connect (this._notify_nickname_cb);
1411       persona.notify["gender"].connect (this._notify_gender_cb);
1412       persona.notify["urls"].connect (this._notify_urls_cb);
1413       persona.notify["phone-numbers"].connect (this._notify_phone_numbers_cb);
1414       persona.notify["email-addresses"].connect (
1415           this._notify_email_addresses_cb);
1416       persona.notify["roles"].connect (this._notify_roles_cb);
1417       persona.notify["birthday"].connect (this._notify_birthday_cb);
1418       persona.notify["notes"].connect (this._notify_notes_cb);
1419       persona.notify["postal-addresses"].connect
1420           (this._notify_postal_addresses_cb);
1421       persona.notify["local-ids"].connect
1422           (this._notify_local_ids_cb);
1423
1424
1425       if (persona is GroupDetails)
1426         {
1427           ((GroupDetails) persona).group_changed.connect (
1428               this._persona_group_changed_cb);
1429         }
1430     }
1431
1432   private void _update_structured_name ()
1433     {
1434       this._update_single_valued_property (typeof (NameDetails), (a, b) =>
1435         {
1436           var a_name = (a as NameDetails).structured_name;
1437           var b_name = (b as NameDetails).structured_name;
1438
1439           var a_is_set = (a_name != null && !a_name.is_empty ()) ? 1 : 0;
1440           var b_is_set = (b_name != null && !b_name.is_empty ()) ? 1 : 0;
1441
1442           return (a_is_set - b_is_set);
1443         }, "structured-name", (p) =>
1444         {
1445           StructuredName? name = null;
1446
1447           if (p != null)
1448             {
1449               name = (p as NameDetails).structured_name;
1450
1451               if (name != null && name.is_empty ())
1452                 {
1453                   name = null;
1454                 }
1455             }
1456
1457           if ((this._structured_name == null && name != null) ||
1458               (this._structured_name != null &&
1459                (name == null || !this._structured_name.equal (name))))
1460             {
1461               this._structured_name = name;
1462               this.notify_property ("structured-name");
1463             }
1464         });
1465     }
1466
1467   private void _update_full_name ()
1468     {
1469       this._update_single_valued_property (typeof (NameDetails), (a, b) =>
1470         {
1471           var a_name = (a as NameDetails).full_name;
1472           var b_name = (b as NameDetails).full_name;
1473
1474           assert (a_name != null);
1475           assert (b_name != null);
1476
1477           var a_is_set = (a_name.strip () != "") ? 1 : 0;
1478           var b_is_set = (b_name.strip () != "") ? 1 : 0;
1479
1480           return (a_is_set - b_is_set);
1481         }, "full-name", (p) =>
1482         {
1483           string new_full_name = ""; /* must not be null */
1484
1485           if (p != null)
1486             {
1487               new_full_name = (p as NameDetails).full_name.strip ();
1488             }
1489
1490           if (new_full_name != this._full_name)
1491             {
1492               this._full_name = new_full_name;
1493               this.notify_property ("full-name");
1494             }
1495         });
1496     }
1497
1498   private void _update_nickname ()
1499     {
1500       this._update_single_valued_property (typeof (NameDetails), (a, b) =>
1501         {
1502           var a_name = (a as NameDetails).nickname;
1503           var b_name = (b as NameDetails).nickname;
1504
1505           assert (a_name != null);
1506           assert (b_name != null);
1507
1508           var a_is_set = (a_name.strip () != "") ? 1 : 0;
1509           var b_is_set = (b_name.strip () != "") ? 1 : 0;
1510
1511           return (a_is_set - b_is_set);
1512         }, "nickname", (p) =>
1513         {
1514           string new_nickname = ""; /* must not be null */
1515
1516           if (p != null)
1517             {
1518               new_nickname = (p as NameDetails).nickname.strip ();
1519             }
1520
1521           if (new_nickname != this._nickname)
1522             {
1523               this._nickname = new_nickname;
1524               this.notify_property ("nickname");
1525             }
1526         });
1527     }
1528
1529   private void _disconnect_from_persona (Persona persona,
1530       Individual? replacement_individual)
1531     {
1532       persona.notify["alias"].disconnect (this._notify_alias_cb);
1533       persona.notify["avatar"].disconnect (this._notify_avatar_cb);
1534       persona.notify["presence-message"].disconnect (
1535           this._notify_presence_cb);
1536       persona.notify["presence-type"].disconnect (this._notify_presence_cb);
1537       persona.notify["im-addresses"].disconnect (
1538           this._notify_im_addresses_cb);
1539       persona.notify["web-service-addresses"].disconnect (
1540           this._notify_web_service_addresses_cb);
1541       persona.notify["is-favourite"].disconnect (
1542           this._notify_is_favourite_cb);
1543       persona.notify["structured-name"].disconnect (
1544           this._notify_structured_name_cb);
1545       persona.notify["full-name"].disconnect (this._notify_full_name_cb);
1546       persona.notify["nickname"].disconnect (this._notify_nickname_cb);
1547       persona.notify["gender"].disconnect (this._notify_gender_cb);
1548       persona.notify["urls"].disconnect (this._notify_urls_cb);
1549       persona.notify["phone-numbers"].disconnect (
1550           this._notify_phone_numbers_cb);
1551       persona.notify["email-addresses"].disconnect (
1552           this._notify_email_addresses_cb);
1553       persona.notify["roles"].disconnect (this._notify_roles_cb);
1554       persona.notify["birthday"].disconnect (this._notify_birthday_cb);
1555       persona.notify["notes"].disconnect (this._notify_notes_cb);
1556       persona.notify["postal-addresses"].disconnect
1557           (this._notify_postal_addresses_cb);
1558       persona.notify["local-ids"].disconnect (this._notify_local_ids_cb);
1559
1560
1561       if (persona is GroupDetails)
1562         {
1563           ((GroupDetails) persona).group_changed.disconnect (
1564               this._persona_group_changed_cb);
1565         }
1566
1567       /* Don't update the individual if the persona's been added to the new one
1568        * already (and thus the new individual has already changed
1569        * persona.individual).
1570        *
1571        * FIXME: Ideally, we'd assert that a persona can't be added to a new
1572        * individual before it's removed from the old one. However, this
1573        * currently isn't possible due to the way the aggregator works. When the
1574        * aggregator's rewritten, it would be nice to fix this. */
1575       if (persona.individual == this)
1576         {
1577           /* It may be the case that the persona's being removed from the
1578            * individual (i.e. the replacement individual is non-null, but
1579            * doesn't contain this persona). In this case, we need to set the
1580            * persona's individual to null. */
1581           if (replacement_individual != null &&
1582               persona in replacement_individual.personas)
1583             {
1584               persona.individual = replacement_individual;
1585             }
1586           else
1587             {
1588               persona.individual = null;
1589             }
1590         }
1591     }
1592
1593   private void _update_gender ()
1594     {
1595       this._update_single_valued_property (typeof (GenderDetails), (a, b) =>
1596         {
1597           var a_gender = (a as GenderDetails).gender;
1598           var b_gender = (b as GenderDetails).gender;
1599
1600           var a_is_specified = (a_gender != Gender.UNSPECIFIED) ? 1 : 0;
1601           var b_is_specified = (b_gender != Gender.UNSPECIFIED) ? 1 : 0;
1602
1603           return (a_is_specified - b_is_specified);
1604         }, "gender", (p) =>
1605         {
1606           var new_gender = Gender.UNSPECIFIED;
1607
1608           if (p != null)
1609             {
1610               new_gender = (p as GenderDetails).gender;
1611             }
1612
1613           if (new_gender != this.gender)
1614             {
1615               this._gender = new_gender;
1616               this.notify_property ("gender");
1617             }
1618         });
1619     }
1620
1621   private void _update_urls ()
1622     {
1623       /* Populate the URLs as the union of our Personas' URLs.
1624        * If the same URL exists multiple times we merge the parameters. */
1625       var urls_set = new HashMap<unowned string, unowned UrlFieldDetails> (
1626           null, null, (GLib.EqualFunc) UrlFieldDetails.equal);
1627
1628       this._urls.clear ();
1629
1630       foreach (var persona in this._persona_set)
1631         {
1632           var url_details = persona as UrlDetails;
1633           if (url_details != null)
1634             {
1635               foreach (var url_fd in url_details.urls)
1636                 {
1637                   if (url_fd.value == null)
1638                     continue;
1639
1640                   var existing = urls_set.get (url_fd.value);
1641                   if (existing != null)
1642                     existing.extend_parameters (url_fd.parameters);
1643                   else
1644                     {
1645                       var new_url_fd = new UrlFieldDetails (url_fd.value);
1646                       new_url_fd.extend_parameters (url_fd.parameters);
1647                       urls_set.set (url_fd.value, new_url_fd);
1648                       this._urls.add (new_url_fd);
1649                     }
1650                 }
1651             }
1652         }
1653
1654       this.notify_property ("urls");
1655     }
1656
1657   private void _update_phone_numbers ()
1658     {
1659       /* Populate the phone numbers as the union of our Personas' numbers
1660        * If the same number exists multiple times we merge the parameters. */
1661       var phone_numbers_set =
1662           new HashMap<unowned string, unowned PhoneFieldDetails> (
1663               null, null, (GLib.EqualFunc) PhoneFieldDetails.equal);
1664
1665       this._phone_numbers.clear ();
1666
1667       foreach (var persona in this._persona_set)
1668         {
1669           var phone_details = persona as PhoneDetails;
1670           if (phone_details != null)
1671             {
1672               foreach (var phone_fd in phone_details.phone_numbers)
1673                 {
1674                   if (phone_fd.value == null)
1675                     continue;
1676
1677                   var existing = phone_numbers_set.get (phone_fd.value);
1678                   if (existing != null)
1679                     existing.extend_parameters (phone_fd.parameters);
1680                   else
1681                     {
1682                       var new_fd = new PhoneFieldDetails (phone_fd.value);
1683                       new_fd.extend_parameters (phone_fd.parameters);
1684                       phone_numbers_set.set (phone_fd.value, new_fd);
1685                       this._phone_numbers.add (new_fd);
1686                     }
1687                 }
1688             }
1689         }
1690
1691       this.notify_property ("phone-numbers");
1692     }
1693
1694   private void _update_email_addresses ()
1695     {
1696       /* Populate the email addresses as the union of our Personas' addresses.
1697        * If the same address exists multiple times we merge the parameters. */
1698       var emails_set = new HashMap<unowned string, unowned EmailFieldDetails> (
1699           null, null, (GLib.EqualFunc) EmailFieldDetails.equal);
1700
1701       this._email_addresses.clear ();
1702
1703       foreach (var persona in this._persona_set)
1704         {
1705           var email_details = persona as EmailDetails;
1706           if (email_details != null)
1707             {
1708               foreach (var email_fd in email_details.email_addresses)
1709                 {
1710                   if (email_fd.value == null)
1711                     continue;
1712
1713                   var existing = emails_set.get (email_fd.value);
1714                   if (existing != null)
1715                     existing.extend_parameters (email_fd.parameters);
1716                   else
1717                     {
1718                       var new_email_fd = new EmailFieldDetails (email_fd.value,
1719                           email_fd.parameters);
1720                       emails_set.set (email_fd.value, new_email_fd);
1721                       this._email_addresses.add (new_email_fd);
1722                     }
1723                 }
1724             }
1725         }
1726
1727       this.notify_property ("email-addresses");
1728     }
1729
1730   private void _update_roles ()
1731     {
1732       this._roles.clear ();
1733
1734       foreach (var persona in this._persona_set)
1735         {
1736           var role_details = persona as RoleDetails;
1737           if (role_details != null)
1738             {
1739               foreach (var role_fd in role_details.roles)
1740                 {
1741                   this._roles.add (role_fd);
1742                 }
1743             }
1744         }
1745
1746       this.notify_property ("roles");
1747     }
1748
1749   private void _update_local_ids ()
1750     {
1751       this._local_ids.clear ();
1752
1753       foreach (var persona in this._persona_set)
1754         {
1755           var local_ids_details = persona as LocalIdDetails;
1756           if (local_ids_details != null)
1757             {
1758               foreach (var id in local_ids_details.local_ids)
1759                 {
1760                   this._local_ids.add (id);
1761                 }
1762             }
1763         }
1764
1765       this.notify_property ("local-ids");
1766     }
1767
1768   private void _update_postal_addresses ()
1769     {
1770       this._postal_addresses.clear ();
1771
1772       /* FIXME: Detect duplicates somehow? */
1773       foreach (var persona in this._persona_set)
1774         {
1775           var address_details = persona as PostalAddressDetails;
1776           if (address_details != null)
1777             {
1778               foreach (var pafd in address_details.postal_addresses)
1779                 this._postal_addresses.add (pafd);
1780             }
1781         }
1782
1783       this.notify_property ("postal-addresses");
1784     }
1785
1786   private void _update_birthday ()
1787     {
1788       this._update_single_valued_property (typeof (BirthdayDetails), (a, b) =>
1789         {
1790           var a_birthday = (a as BirthdayDetails).birthday;
1791           var b_birthday = (b as BirthdayDetails).birthday;
1792           var a_event_id = (a as BirthdayDetails).calendar_event_id;
1793           var b_event_id = (b as BirthdayDetails).calendar_event_id;
1794
1795           var a_birthday_is_set = (a_birthday != null) ? 1 : 0;
1796           var b_birthday_is_set = (b_birthday != null) ? 1 : 0;
1797
1798           /* We consider the empty string as “set” because it's an opaque ID. */
1799           var a_event_id_is_set = (a_event_id != null) ? 1 : 0;
1800           var b_event_id_is_set = (b_event_id != null) ? 1 : 0;
1801
1802           /* Prefer personas which have both properties set over those who have
1803            * only one set. We don't consider the case where the birthdays from
1804            * different personas don't match, because that's just scary. */
1805           return (a_birthday_is_set + a_event_id_is_set) -
1806                  (b_birthday_is_set + b_event_id_is_set);
1807         }, "birthday", (p) =>
1808         {
1809           unowned DateTime? bday = null;
1810           unowned string? calendar_event_id = null;
1811
1812           if (p != null)
1813             {
1814               bday = (p as BirthdayDetails).birthday;
1815               calendar_event_id = (p as BirthdayDetails).calendar_event_id;
1816             }
1817
1818           if ((this._birthday == null && bday != null) ||
1819               (this._birthday != null &&
1820                (bday == null || !this._birthday.equal (bday))) ||
1821               (this._calendar_event_id != calendar_event_id))
1822             {
1823               this._birthday = bday;
1824               this._calendar_event_id = calendar_event_id;
1825
1826               this.freeze_notify ();
1827               this.notify_property ("birthday");
1828               this.notify_property ("calendar-event-id");
1829               this.thaw_notify ();
1830             }
1831         });
1832     }
1833
1834   private void _update_notes ()
1835     {
1836       this._notes.clear ();
1837
1838       foreach (var persona in this._persona_set)
1839         {
1840           var note_details = persona as NoteDetails;
1841           if (note_details != null)
1842             {
1843               foreach (var n in note_details.notes)
1844                 {
1845                   this._notes.add (n);
1846                 }
1847             }
1848         }
1849
1850       this.notify_property ("notes");
1851     }
1852
1853   private void _set_personas (Set<Persona>? personas,
1854       Individual? replacement_individual)
1855     {
1856       assert (replacement_individual == null || replacement_individual != this);
1857
1858       var added = new HashSet<Persona> ();
1859       var removed = new HashSet<Persona> ();
1860
1861       /* Determine which Personas have been added. If personas == null, we
1862        * assume it's an empty set. */
1863       if (personas != null)
1864         {
1865           foreach (var p in personas)
1866             {
1867               if (!this._persona_set.contains (p))
1868                 {
1869                   /* Keep track of how many Personas are users */
1870                   if (p.is_user)
1871                     this._persona_user_count++;
1872
1873                   added.add (p);
1874
1875                   this._persona_set.add (p);
1876                   this._connect_to_persona (p);
1877
1878                   /* Increment the Persona count for this PersonaStore */
1879                   var store = p.store;
1880                   var num_from_store = this._stores.get (store);
1881                   if (num_from_store == 0)
1882                     {
1883                       this._stores.set (store, num_from_store + 1);
1884                     }
1885                   else
1886                     {
1887                       this._stores.set (store, 1);
1888
1889                       store.removed.connect (this._store_removed_cb);
1890                       store.personas_changed.connect (
1891                           this._store_personas_changed_cb);
1892                     }
1893                 }
1894             }
1895         }
1896
1897       /* Determine which Personas have been removed */
1898       var iter = this._persona_set.iterator ();
1899       while (iter.next ())
1900         {
1901           var p = iter.get ();
1902
1903           if (personas == null || !personas.contains (p))
1904             {
1905               /* Keep track of how many Personas are users */
1906               if (p.is_user)
1907                 this._persona_user_count--;
1908
1909               removed.add (p);
1910
1911               /* Decrement the Persona count for this PersonaStore */
1912               var store = p.store;
1913               var num_from_store = this._stores.get (store);
1914               if (num_from_store > 1)
1915                 {
1916                   this._stores.set (store, num_from_store - 1);
1917                 }
1918               else
1919                 {
1920                   store.removed.disconnect (this._store_removed_cb);
1921                   store.personas_changed.disconnect (
1922                       this._store_personas_changed_cb);
1923
1924                   this._stores.unset (store);
1925                 }
1926
1927               this._disconnect_from_persona (p, replacement_individual);
1928               iter.remove ();
1929             }
1930         }
1931
1932       this._emit_personas_changed (added, removed);
1933
1934       /* Update this.is_user */
1935       var new_is_user = (this._persona_user_count > 0) ? true : false;
1936       if (new_is_user != this.is_user)
1937         this.is_user = new_is_user;
1938
1939       /* If all the Personas have been removed, remove the Individual */
1940       if (this._persona_set.size < 1)
1941         {
1942           this.removed (replacement_individual);
1943           return;
1944         }
1945
1946       /* Update the ID. We choose the most interesting Persona in the
1947        * Individual and hash their UID. This is guaranteed to be globally
1948        * unique, and may not change (for one of the two Individuals) if we link
1949        * two Individuals together, which is nice though we can't rely on this
1950        * behaviour.
1951        *
1952        * This method of constructing an ID ensures that it'll be unique and
1953        * stable for a given Individual once the IndividualAggregator reaches
1954        * a quiescent state after startup. It guarantees that the ID will be
1955        * the same every time folks is used, until the Individual is linked
1956        * or unlinked to another Individual.
1957        *
1958        * We choose the most interesting Persona by ranking all the Personas
1959        * in the Individual by:
1960        *  1. store.is-primary-store
1961        *  2. store.trust-level
1962        *  3. store.id (alphabetically)
1963        *
1964        * Note that this heuristic shouldn't be changed without careful thought,
1965        * since stored references to IDs may be broken by the change.
1966        */
1967       if (this._persona_set.size > 0)
1968         {
1969           Persona? chosen_persona = null;
1970
1971           foreach (var persona in this._persona_set)
1972             {
1973               if (chosen_persona == null ||
1974                   (chosen_persona.store.is_primary_store == false &&
1975                       persona.store.is_primary_store == true) ||
1976                   (chosen_persona.store.is_primary_store ==
1977                           persona.store.is_primary_store &&
1978                       chosen_persona.store.trust_level >
1979                           persona.store.trust_level) ||
1980                   (chosen_persona.store.is_primary_store ==
1981                           persona.store.is_primary_store &&
1982                       chosen_persona.store.trust_level ==
1983                           persona.store.trust_level &&
1984                       chosen_persona.store.id > persona.store.id)
1985                  )
1986                {
1987                  chosen_persona = persona;
1988                }
1989             }
1990
1991           // Hash the chosen persona's UID
1992           this.id = Checksum.compute_for_string (ChecksumType.SHA1,
1993               chosen_persona.uid);
1994         }
1995
1996       /* Update our aggregated fields and notify the changes */
1997       this._update_fields ();
1998     }
1999
2000   internal void replace (Individual replacement_individual)
2001     {
2002       this._set_personas (null, replacement_individual);
2003     }
2004 }