summaryrefslogtreecommitdiff
path: root/src/contacts-individual-sorter.vala
blob: ea503f267e92dd3aaa93fb88455004028f690ebd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
 * Copyright (C) 2021 Niels De Graef <nielsdegraef@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

using Folks;

/**
 * A subclass of {@link Gtk.Sorter} which sorts {@link Folks.Individual}s.
 */
public class Contacts.IndividualSorter : Gtk.Sorter {

  private bool sort_on_surname = false;

  public IndividualSorter (GLib.Settings settings) {
    this.sort_on_surname = settings.get_boolean ("sort-on-surname");
    settings.changed["sort-on-surname"].connect (() => {
      this.sort_on_surname = settings.get_boolean ("sort-on-surname");
      this.changed (Gtk.SorterChange.DIFFERENT);
    });
  }

  public override Gtk.Ordering compare (Object? item1, Object? item2) {
    unowned var a = item1 as Individual;
    if (a == null)
      return Gtk.Ordering.SMALLER;

    unowned var b = item2 as Individual;
    if (b == null)
      return Gtk.Ordering.LARGER;

    // Always prefer favourites over non-favourites.
    if (a.is_favourite != b.is_favourite)
      return a.is_favourite? Gtk.Ordering.SMALLER : Gtk.Ordering.LARGER;

    // Both are (non-)favourites: sort by either first name or surname (user preference)
    unowned var a_name = this.sort_on_surname? try_get_surname (a) : a.display_name;
    unowned var b_name = this.sort_on_surname? try_get_surname (b) : b.display_name;

    int names_cmp = a_name.collate (b_name);
    if (names_cmp != 0)
      return Gtk.Ordering.from_cmpfunc (names_cmp);

    // Since we want total ordering, compare uuids as a last resort
    return Gtk.Ordering.from_cmpfunc (strcmp (a.id, b.id));
  }

  private unowned string try_get_surname (Individual indiv) {
    if (indiv.structured_name != null && indiv.structured_name.family_name != "")
      return indiv.structured_name.family_name;

    // Fall back to the display_name
    return indiv.display_name;
  }

  public override Gtk.SorterOrder get_order () {
    return Gtk.SorterOrder.TOTAL;
  }
}