## Contacts Browser Example

Contacts Browser Example — Explanation of how to create a scrolling window listing contacts in alphabetical order.

## Introduction

This is a fully functional reference application for implementing scrolling contact browsers using the EBookClientCursor. With the cursor, the following features are possible.

- Display contacts in a configurable sort order

  Sort by any EContactField which conforms to G_TYPE_STRING, this can be checked with `e_contact_field_type()`

- Minimal memory constraints

  Only load into memory the contacts which are currently visible in the list

- Filter search results on the fly

  Set new search expressions generated with EBookQuery on the fly. Refresh the contact list at the current position without losing the current cursor position.

- Display the the user's alphabet

  Using interesting features from ICU libraries allow us to display the user's alphabet, and implement features such as jumping to a given letter in the user's alphabet.

The actual example code is built into the 'example' subdirectory of the Evolution Data Server sources. In order to run the example, just launch the program and give it a path to a directory full of vcards, bearing the .vcf filename extention.

## Contact Browser

Below is an example of the contact browser code itself, the example program is broken down into a couple of object classes which are also listed below.

    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
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698

    /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
    /*
     * Copyright (C) 2013 Intel Corporation
     *
     * This library is free software you can redistribute it and/or modify it
     * under the terms of the GNU Lesser General Public License as published by
     * the Free Software Foundation.
     *
     * This library 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 Lesser General Public License
     * along with this library; if not, see <http://www.gnu.org/licenses/>.
     *
     * Author: Tristan Van Berkom <tristanvb@openismus.com>
     */

    #include <libebook/libebook.h>

    #include "cursor-example.h"
    #include "cursor-navigator.h"
    #include "cursor-search.h"
    #include "cursor-slot.h"
    #include "cursor-data.h"
    #include "cursor-slot.h"

    #define N_SLOTS         10

    #define INITIAL_TIMEOUT 600
    #define TICK_TIMEOUT    100

    #define d(x)

    typedef enum _TimeoutActivity TimeoutActivity;

    /* GObjectClass */
    static void            cursor_example_dispose                 (GObject            *object);

    /* UI Callbacks */
    static gboolean        cursor_example_up_button_press         (CursorExample      *example,
                                   GdkEvent           *event,
                                   GtkButton          *button);
    static gboolean        cursor_example_up_button_release       (CursorExample      *example,
                                   GdkEvent           *event,
                                   GtkButton          *button);
    static gboolean        cursor_example_down_button_press       (CursorExample      *example,
                                   GdkEvent           *event,
                                   GtkButton          *button);
    static gboolean        cursor_example_down_button_release     (CursorExample      *example,
                                   GdkEvent           *event,
                                   GtkButton          *button);
    static void            cursor_example_navigator_changed       (CursorExample      *example,
                                   CursorNavigator    *navigator);
    static void            cursor_example_sexp_changed            (CursorExample      *example,
                                   GParamSpec         *pspec,
                                   CursorSearch       *search);

    /* EDS Callbacks */
    static void            cursor_example_refresh                 (EBookClientCursor  *cursor,
                                   CursorExample      *example);
    static void            cursor_example_alphabet_changed        (EBookClientCursor  *cursor,
                                   GParamSpec         *pspec,
                                   CursorExample      *example);
    static void            cursor_example_status_changed          (EBookClientCursor  *cursor,
                                   GParamSpec         *spec,
                                   CursorExample      *example);

    /* Utilities */
    static void            cursor_example_load_alphabet           (CursorExample      *example);
    static gboolean        cursor_example_move_cursor             (CursorExample      *example,
                                   EBookCursorOrigin   origin,
                                   gint                count);
    static gboolean        cursor_example_load_page               (CursorExample      *example,
                                   gboolean           *full_results);
    static void            cursor_example_update_status           (CursorExample      *example);
    static void            cursor_example_update_current_index    (CursorExample      *example,
                                   EContact           *contact);
    static void            cursor_example_ensure_timeout          (CursorExample      *example,
                                   TimeoutActivity     activity);
    static void            cursor_example_cancel_timeout          (CursorExample      *example);

    enum _TimeoutActivity {
    TIMEOUT_NONE = 0,
    TIMEOUT_UP_INITIAL,
    TIMEOUT_UP_TICK,
    TIMEOUT_DOWN_INITIAL,
    TIMEOUT_DOWN_TICK,
    };

    struct _CursorExamplePrivate {
    /* Screen widgets */
    GtkWidget *browse_up_button;
    GtkWidget *browse_down_button;
    GtkWidget *progressbar;
    GtkWidget *alphabet_label;
    GtkWidget *slots[N_SLOTS];
    CursorNavigator *navigator;

    /* EDS Resources */
    EBookClient          *client;
    EBookClientCursor    *cursor;

    /* Manage the automatic scrolling with button pressed */
    guint                 timeout_id;
    TimeoutActivity       activity;
    };

    G_DEFINE_TYPE_WITH_PRIVATE (CursorExample, cursor_example, GTK_TYPE_WINDOW);

    /************************************************************************
     *                          GObjectClass                                *
     ************************************************************************/
    static void
    cursor_example_class_init (CursorExampleClass *klass)
    {
    GObjectClass *object_class;
    GtkWidgetClass *widget_class;
    gint i;

    object_class = G_OBJECT_CLASS (klass);
    object_class->dispose = cursor_example_dispose;

    /* Bind to template */
    widget_class = GTK_WIDGET_CLASS (klass);
    gtk_widget_class_set_template_from_resource (widget_class, "/org/gnome/evolution/cursor-example/cursor-example.ui");
    gtk_widget_class_bind_template_child_private (widget_class, CursorExample, navigator);
    gtk_widget_class_bind_template_child_private (widget_class, CursorExample, browse_up_button);
    gtk_widget_class_bind_template_child_private (widget_class, CursorExample, browse_down_button);
    gtk_widget_class_bind_template_child_private (widget_class, CursorExample, alphabet_label);
    gtk_widget_class_bind_template_child_private (widget_class, CursorExample, progressbar);

    for (i = 0; i < N_SLOTS; i++) {
        gchar *name = g_strdup_printf ("contact_slot_%d", i + 1);

        gtk_widget_class_bind_template_child_full (widget_class, name, FALSE, 0);
        g_free (name);
    }

    gtk_widget_class_bind_template_callback (widget_class, cursor_example_navigator_changed);
    gtk_widget_class_bind_template_callback (widget_class, cursor_example_up_button_press);
    gtk_widget_class_bind_template_callback (widget_class, cursor_example_up_button_release);
    gtk_widget_class_bind_template_callback (widget_class, cursor_example_down_button_press);
    gtk_widget_class_bind_template_callback (widget_class, cursor_example_down_button_release);
    gtk_widget_class_bind_template_callback (widget_class, cursor_example_sexp_changed);
    }

    static void
    cursor_example_init (CursorExample *example)
    {
    CursorExamplePrivate *priv;
    gint i;

    example->priv = priv =
        cursor_example_get_instance_private (example);

    g_type_ensure (CURSOR_TYPE_NAVIGATOR);
    g_type_ensure (CURSOR_TYPE_SEARCH);

    gtk_widget_init_template (GTK_WIDGET (example));

    for (i = 0; i < N_SLOTS; i++) {

        gchar *name = g_strdup_printf ("contact_slot_%d", i + 1);
        priv->slots[i] = (GtkWidget *) gtk_widget_get_template_child (GTK_WIDGET (example),
                                         CURSOR_TYPE_EXAMPLE,
                                         name);
        g_free (name);
    }
    }

    static void
    cursor_example_dispose (GObject *object)
    {
    CursorExample        *example = CURSOR_EXAMPLE (object);
    CursorExamplePrivate *priv = example->priv;

    cursor_example_cancel_timeout (example);

    if (priv->client) {
        g_object_unref (priv->client);
        priv->client = NULL;
    }

    if (priv->cursor) {
        g_object_unref (priv->cursor);
        priv->cursor = NULL;
    }

    G_OBJECT_CLASS (cursor_example_parent_class)->dispose (object);
    }

    /************************************************************************
     *                           UI Callbacks                               *
     ************************************************************************/
    static gboolean
    cursor_example_up_button_press (CursorExample *example,
                                    GdkEvent *event,
                                    GtkButton *button)
    {
    d (g_print ("Browse up press\n"));

    /* Move the cursor backwards by 1 and then refresh the page */
    if (cursor_example_move_cursor (example, E_BOOK_CURSOR_ORIGIN_CURRENT, 0 - 1))
        cursor_example_load_page (example, NULL);

    cursor_example_ensure_timeout (example, TIMEOUT_UP_INITIAL);

    return FALSE;
    }

    static gboolean
    cursor_example_up_button_release (CursorExample *example,
                                      GdkEvent *event,
                                      GtkButton *button)
    {
    d (g_print ("Browse up release\n"));

    cursor_example_cancel_timeout (example);

    return FALSE;
    }

    static gboolean
    cursor_example_down_button_press (CursorExample *example,
                                      GdkEvent *event,
                                      GtkButton *button)
    {
    d (g_print ("Browse down press\n"));

    /* Move the cursor forward by 1 and then refresh the page */
    if (cursor_example_move_cursor (example, E_BOOK_CURSOR_ORIGIN_CURRENT, 1))
        cursor_example_load_page (example, NULL);

    cursor_example_ensure_timeout (example, TIMEOUT_DOWN_INITIAL);

    return FALSE;
    }

    static gboolean
    cursor_example_down_button_release (CursorExample *example,
                                        GdkEvent *event,
                                        GtkButton *button)
    {
    d (g_print ("Browse down released\n"));

    cursor_example_cancel_timeout (example);

    return FALSE;
    }

    static void
    cursor_example_navigator_changed (CursorExample *example,
                                      CursorNavigator *navigator)
    {
    CursorExamplePrivate *priv = example->priv;
    GError               *error = NULL;
    gint                  index;
    gboolean              full_results = FALSE;

    index = cursor_navigator_get_index (priv->navigator);

    d (g_print ("Alphabet index changed to: %d\n", index));

    /* Move to this index */
    if (!e_book_client_cursor_set_alphabetic_index_sync (priv->cursor, index, NULL, &error)) {

        if (g_error_matches (error,
                     E_CLIENT_ERROR,
                     E_CLIENT_ERROR_OUT_OF_SYNC)) {

            /* Just ignore the error.
             *
             * The addressbook locale has recently changed, very
             * soon we will receive an alphabet change notification
             * where we will reset the cursor position and reload
             * the alphabet.
             */
            d (g_print ("Cursor was temporarily out of sync while setting the alphabetic target\n"));
        } else
            g_warning ("Failed to move the cursor: %s", error->message);

        g_clear_error (&error);
    }

    /* And load one page full of results starting with this index */
    if (!cursor_example_load_page (example, &full_results))
        return;

    /* If we hit the end of the results (less than a full page) then load the last page of results */
    if (!full_results) {
        if (cursor_example_move_cursor (example,
                        E_BOOK_CURSOR_ORIGIN_END,
                        0 - (N_SLOTS + 1))) {
            cursor_example_load_page (example, NULL);
        }
    }
    }

    static void
    cursor_example_sexp_changed (CursorExample *example,
                                 GParamSpec *pspec,
                                 CursorSearch *search)
    {
    CursorExamplePrivate *priv = example->priv;
    gboolean              full_results = FALSE;
    GError               *error = NULL;
    const gchar          *sexp;

    sexp = cursor_search_get_sexp (search);

    d (g_print ("Search expression changed to: '%s'\n", sexp));

    /* Set the search expression */
    if (!e_book_client_cursor_set_sexp_sync (priv->cursor, sexp, NULL, &error)) {
        g_warning ("Failed to move the cursor: %s", error->message);
        g_clear_error (&error);
    }

    /* And load one page full of results */
    if (!cursor_example_load_page (example, &full_results))
        return;

    /* If we hit the end of the results (less than a full page) then load the last page of results */
    if (!full_results)
        if (cursor_example_move_cursor (example,
                        E_BOOK_CURSOR_ORIGIN_END,
                        0 - (N_SLOTS + 1))) {
            cursor_example_load_page (example, NULL);
    }
    }

    /************************************************************************
     *                           EDS Callbacks                              *
     ************************************************************************/
    static void
    cursor_example_refresh (EBookClientCursor *cursor,
                            CursorExample *example)
    {
    d (g_print ("Cursor refreshed\n"));

    /* Refresh the page */
    if (cursor_example_load_page (example, NULL))
        cursor_example_update_status (example);
    }

    static void
    cursor_example_alphabet_changed (EBookClientCursor *cursor,
                                     GParamSpec *spec,
                                     CursorExample *example)
    {
    d (g_print ("Alphabet Changed\n"));

    cursor_example_load_alphabet (example);

    /* Get the first page of contacts in the addressbook */
    if (cursor_example_move_cursor (example, E_BOOK_CURSOR_ORIGIN_BEGIN, 0))
        cursor_example_load_page (example, NULL);
    }

    static void
    cursor_example_status_changed (EBookClientCursor *cursor,
                                   GParamSpec *spec,
                                   CursorExample *example)
    {
    d (g_print ("Status changed\n"));

    cursor_example_update_status (example);
    }

    /************************************************************************
     *                             Utilities                                *
     ************************************************************************/
    static void
    cursor_example_load_alphabet (CursorExample *example)
    {
    CursorExamplePrivate *priv = example->priv;
    const gchar *const   *alphabet;

    /* Update the alphabet on the navigator */
    alphabet = e_book_client_cursor_get_alphabet (priv->cursor, NULL, NULL, NULL, NULL);
    cursor_navigator_set_alphabet (priv->navigator, alphabet);

    /* Reset navigator to the beginning */
    g_signal_handlers_block_by_func (priv->navigator, cursor_example_navigator_changed, example);
    cursor_navigator_set_index (priv->navigator, 0);
    g_signal_handlers_unblock_by_func (priv->navigator, cursor_example_navigator_changed, example);
    }

    static gboolean
    cursor_example_move_cursor (CursorExample *example,
                                EBookCursorOrigin origin,
                                gint count)
    {
    CursorExamplePrivate *priv = example->priv;
    GError               *error = NULL;
    gint                  n_results;

    n_results = e_book_client_cursor_step_sync (
        priv->cursor,
        E_BOOK_CURSOR_STEP_MOVE,
        origin,
        count,
        NULL, /* Result list */
        NULL, /* GCancellable */
        &error);

    if (n_results < 0) {

        if (g_error_matches (error,
                     E_CLIENT_ERROR,
                     E_CLIENT_ERROR_OUT_OF_SYNC)) {

            /* The addressbook has very recently been modified,
             * very soon we will receive a "refresh" signal and
             * automatically reload the current page position.
             */
            d (g_print ("Cursor was temporarily out of sync while moving\n"));

        } else if (g_error_matches (error,
                        E_CLIENT_ERROR,
                        E_CLIENT_ERROR_QUERY_REFUSED)) {

            d (g_print ("End of list was reached\n"));

        } else
            g_warning ("Failed to move the cursor: %s", error->message);

        g_clear_error (&error);

    }

    return n_results >= 0;
    }

    /* Loads a page at the current cursor position, returns
     * FALSE if there was an error.
     */
    static gboolean
    cursor_example_load_page (CursorExample *example,
                              gboolean *full_results)
    {
    CursorExamplePrivate *priv = example->priv;
    GError               *error = NULL;
    GSList               *results = NULL;
    gint                  n_results;

    /* Fetch N_SLOTS contacts after the current cursor position,
     * without modifying the current cursor position
     */
    n_results = e_book_client_cursor_step_sync (
        priv->cursor,
        E_BOOK_CURSOR_STEP_FETCH,
        E_BOOK_CURSOR_ORIGIN_CURRENT,
        N_SLOTS,
        &results,
        NULL, /* GCancellable */
        &error);

    if (n_results < 0) {
        if (g_error_matches (error,
                     E_CLIENT_ERROR,
                     E_CLIENT_ERROR_OUT_OF_SYNC)) {

            /* The addressbook has very recently been modified,
             * very soon we will receive a "refresh" signal and
             * automatically reload the current page position.
             */
            d (g_print ("Cursor was temporarily out of sync while loading page\n"));

        } else if (g_error_matches (error,
                        E_CLIENT_ERROR,
                        E_CLIENT_ERROR_QUERY_REFUSED)) {

            d (g_print ("End of list was reached\n"));

        } else
            g_warning ("Failed to move the cursor: %s", error->message);

        g_clear_error (&error);

    } else {
        /* Display the results */
        EContact             *contact;
        gint                  i;

        /* Fill the page with results for the current cursor position
         */
        for (i = 0; i < N_SLOTS; i++) {
            contact = g_slist_nth_data (results, i);

            /* For the first contact, give some visual feedback about where we
             * are in the list, which alphabet character we're browsing right now.
             */
            if (i == 0 && contact)
                cursor_example_update_current_index (example, contact);

            cursor_slot_set_from_contact (CURSOR_SLOT (priv->slots[i]), contact);
        }
    }

    if (full_results)
        *full_results = (n_results == N_SLOTS);

    g_slist_free_full (results, (GDestroyNotify) g_object_unref);

    return n_results >= 0;
    }

    static void
    cursor_example_update_status (CursorExample *example)
    {
    CursorExamplePrivate *priv = example->priv;
    gint                  total, position;
    gchar                *txt;
    gboolean              up_sensitive;
    gboolean              down_sensitive;
    gdouble               fraction;

    total = e_book_client_cursor_get_total (priv->cursor);
    position = e_book_client_cursor_get_position (priv->cursor);

    /* Set the label showing the cursor position and total contacts */
    txt = g_strdup_printf ("Position %d / Total %d", position, total);
    gtk_progress_bar_set_text (GTK_PROGRESS_BAR (priv->progressbar), txt);
    g_free (txt);

    /* Give visual feedback on how far we are into the contact list */
    fraction = position * 1.0F / (total - N_SLOTS);
    gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (priv->progressbar), fraction);

    /* Update sensitivity of buttons */
    if (total <= N_SLOTS) {
        /* If the amount of contacts is less than the amount of visual slots,
         * then we cannot browse up and down
         */
        up_sensitive = FALSE;
        down_sensitive = FALSE;
    } else {
        /* The cursor is always pointing directly before
         * the first contact visible in the view, so if the
         * cursor is passed the first contact we can rewind.
         */
        up_sensitive = position > 0;

        /* If more than N_SLOTS contacts remain, then
         * we can still scroll down */
        down_sensitive = position < total - N_SLOTS;
    }

    gtk_widget_set_sensitive (priv->browse_up_button, up_sensitive);
    gtk_widget_set_sensitive (priv->browse_down_button, down_sensitive);
    }

    /* This is called when refreshing the window contents with
     * the first contact shown in the window.
     */
    static void
    cursor_example_update_current_index (CursorExample *example,
                                         EContact *contact)
    {
    CursorExamplePrivate *priv = example->priv;
    const gchar *const   *labels;
    gint                  index;

    /* Fetch the alphabetic index for this contact */
    index = e_book_client_cursor_get_contact_alphabetic_index (priv->cursor, contact);

    /* Refresh the current alphabet index indicator.
     *
     * The index returned by e_book_client_cursor_get_contact_alphabetic_index() is
     * a valid position into the array returned by e_book_client_cursor_get_alphabet().
     */
    labels = e_book_client_cursor_get_alphabet (priv->cursor, NULL, NULL, NULL, NULL);
    gtk_label_set_text (GTK_LABEL (priv->alphabet_label), labels[index]);

    /* Update the current scroll position (and avoid reacting to the value change)
     */
    if (contact) {
        g_signal_handlers_block_by_func (priv->navigator, cursor_example_navigator_changed, example);
        cursor_navigator_set_index (priv->navigator, index);
        g_signal_handlers_unblock_by_func (priv->navigator, cursor_example_navigator_changed, example);
    }
    }

    static gboolean
    cursor_example_timeout (CursorExample *example)
    {
    CursorExamplePrivate *priv = example->priv;
    gboolean can_move;

    switch (priv->activity) {
    case TIMEOUT_NONE:
        break;

    case TIMEOUT_UP_INITIAL:
    case TIMEOUT_UP_TICK:

        /* Move the cursor backwards by 1 and then refresh the page */
        if (cursor_example_move_cursor (example, E_BOOK_CURSOR_ORIGIN_CURRENT, 0 - 1)) {
            cursor_example_load_page (example, NULL);
            cursor_example_ensure_timeout (example, TIMEOUT_UP_TICK);
        } else
            cursor_example_cancel_timeout (example);

        break;

    case TIMEOUT_DOWN_INITIAL:
    case TIMEOUT_DOWN_TICK:

        /* Avoid scrolling past the end of the list - N_SLOTS */
        can_move = (e_book_client_cursor_get_position (priv->cursor) <
                e_book_client_cursor_get_total (priv->cursor) - N_SLOTS);

        /* Move the cursor forwards by 1 and then refresh the page */
        if (can_move &&
            cursor_example_move_cursor (example, E_BOOK_CURSOR_ORIGIN_CURRENT, 1)) {
            cursor_example_load_page (example, NULL);
            cursor_example_ensure_timeout (example, TIMEOUT_DOWN_TICK);
        } else
            cursor_example_cancel_timeout (example);

        break;
    }

    return FALSE;
    }

    static void
    cursor_example_ensure_timeout (CursorExample *example,
                                   TimeoutActivity activity)
    {
    CursorExamplePrivate *priv = example->priv;
    guint                 timeout = 0;

    cursor_example_cancel_timeout (example);

    if (activity == TIMEOUT_UP_INITIAL ||
        activity == TIMEOUT_DOWN_INITIAL)
        timeout = INITIAL_TIMEOUT;
    else
        timeout = TICK_TIMEOUT;

    priv->activity = activity;

    priv->timeout_id =
        g_timeout_add (
            timeout,
            (GSourceFunc) cursor_example_timeout,
            example);
    }

    static void
    cursor_example_cancel_timeout (CursorExample *example)
    {
    CursorExamplePrivate *priv = example->priv;

    if (priv->timeout_id) {
        g_source_remove (priv->timeout_id);
        priv->timeout_id = 0;
    }
    }

    /************************************************************************
     *                                API                                   *
     ************************************************************************/
    GtkWidget *
    cursor_example_new (const gchar *vcard_path)
    {
      CursorExample *example;
      CursorExamplePrivate *priv;

      example = g_object_new (CURSOR_TYPE_EXAMPLE, NULL);
      priv = example->priv;

      priv->client = cursor_load_data (vcard_path, &priv->cursor);

      cursor_example_load_alphabet (example);

      /* Load the first page of results */
      cursor_example_load_page (example, NULL);
      cursor_example_update_status (example);

      g_signal_connect (priv->cursor, "refresh",
            G_CALLBACK (cursor_example_refresh), example);
      g_signal_connect (priv->cursor, "notify::alphabet",
            G_CALLBACK (cursor_example_alphabet_changed), example);
      g_signal_connect (priv->cursor, "notify::total",
            G_CALLBACK (cursor_example_status_changed), example);
      g_signal_connect (priv->cursor, "notify::position",
            G_CALLBACK (cursor_example_status_changed), example);

      g_message ("Cursor example started in locale: %s",
         e_book_client_get_locale (priv->client));

      return (GtkWidget *) example;
    }

## The alphabetic navigator

This is a simple class which implements a vertical scroller and displays various letters according to the currently active alphabet. The actual interaction with EBookClientCursor is done in the main contact browser and this class is simply configured with the active alphabet.

    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
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257

    /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
    /*
     * Copyright (C) 2013 Intel Corporation
     *
     * This library is free software you can redistribute it and/or modify it
     * under the terms of the GNU Lesser General Public License as published by
     * the Free Software Foundation.
     *
     * This library 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 Lesser General Public License
     * along with this library; if not, see <http://www.gnu.org/licenses/>.
     *
     * Author: Tristan Van Berkom <tristanvb@openismus.com>
     */

    #include "cursor-navigator.h"

    /* GObjectClass */
    static void            cursor_navigator_constructed     (GObject              *object);
    static void            cursor_navigator_finalize        (GObject              *object);

    /* GtkScaleClass */
    static gchar          *cursor_navigator_format_value    (GtkScale             *scale,
                             gdouble               value);

    static void            cursor_navigator_changed         (GtkAdjustment        *adj,
                             GParamSpec           *pspec,
                             CursorNavigator      *navigator);

    struct _CursorNavigatorPrivate {
    gchar **alphabet;
    gint    letters;
    gint    index;
    };

    enum {
    INDEX_CHANGED,
    LAST_SIGNAL
    };

    static guint signals[LAST_SIGNAL];

    enum {
    PROP_0,
    PROP_INDEX,
    };

    G_DEFINE_TYPE (CursorNavigator, cursor_navigator, GTK_TYPE_SCALE);

    /************************************************************************
     *                          GObjectClass                                *
     ************************************************************************/
    static void
    cursor_navigator_class_init (CursorNavigatorClass *klass)
    {
    GObjectClass       *object_class;
    GtkScaleClass      *scale_class;

    object_class = G_OBJECT_CLASS (klass);
    object_class->constructed = cursor_navigator_constructed;
    object_class->finalize = cursor_navigator_finalize;

    scale_class = GTK_SCALE_CLASS (klass);
    scale_class->format_value = cursor_navigator_format_value;

    signals[INDEX_CHANGED] = g_signal_new (
        "index-changed",
        G_OBJECT_CLASS_TYPE (object_class),
        G_SIGNAL_RUN_LAST,
        0, NULL, NULL, NULL,
        G_TYPE_NONE, 0);

    g_type_class_add_private (object_class, sizeof (CursorNavigatorPrivate));
    }

    static void
    cursor_navigator_init (CursorNavigator *navigator)
    {
    CursorNavigatorPrivate *priv;

    navigator->priv = priv =
        G_TYPE_INSTANCE_GET_PRIVATE (
            navigator,
            CURSOR_TYPE_NAVIGATOR,
            CursorNavigatorPrivate);

    priv->letters = -1;
    }

    static void
    cursor_navigator_constructed (GObject *object)
    {
    CursorNavigator        *navigator = CURSOR_NAVIGATOR (object);
    GtkAdjustment          *adj = NULL;

    G_OBJECT_CLASS (cursor_navigator_parent_class)->constructed (object);

    adj = gtk_adjustment_new (0.0F, 0.0F, 1.0F, 1.0F, 1.0F, 0.0F);
    gtk_range_set_adjustment (GTK_RANGE (navigator), adj);

    g_signal_connect (
        adj, "notify::value",
        G_CALLBACK (cursor_navigator_changed), navigator);
    }

    static void
    cursor_navigator_finalize (GObject *object)
    {
    CursorNavigator        *navigator = CURSOR_NAVIGATOR (object);
    CursorNavigatorPrivate *priv = navigator->priv;

    g_strfreev (priv->alphabet);

    G_OBJECT_CLASS (cursor_navigator_parent_class)->finalize (object);
    }

    /************************************************************************
     *                          GtkScaleClass                               *
     ************************************************************************/
    static gchar *
    cursor_navigator_format_value (GtkScale *scale,
                                   gdouble value)
    {
    CursorNavigator        *navigator = CURSOR_NAVIGATOR (scale);
    CursorNavigatorPrivate *priv = navigator->priv;
    gint                    index;

    if (priv->letters < 0)
        return NULL;

    index = CLAMP ((gint) value, 0, priv->letters - 1);

    /* Return the letter for the gvoidiven value
     */
    return g_strdup (priv->alphabet[index]);
    }

    static void
    cursor_navigator_changed (GtkAdjustment *adj,
                              GParamSpec *pspec,
                              CursorNavigator *navigator)
    {
    gint index = gtk_adjustment_get_value (adj);

    cursor_navigator_set_index (navigator, index);
    }

    /************************************************************************
     *                                API                                   *
     ************************************************************************/
    CursorNavigator *
    cursor_navigator_new (void)
    {
    return g_object_new (CURSOR_TYPE_NAVIGATOR, NULL);
    }

    static void
    cursor_navigator_update_parameters (CursorNavigator *navigator)
    {
    CursorNavigatorPrivate *priv = navigator->priv;
    GtkScale               *scale = GTK_SCALE (navigator);
    GtkAdjustment          *adj;
    gint                    i;

    gtk_scale_clear_marks (scale);
    for (i = 0; i < priv->letters; i++) {
        gchar *letter;

        letter = g_strdup_printf ("<span size=\"x-small\">%s</span>", priv->alphabet[i]);

        gtk_scale_add_mark (scale, i, GTK_POS_LEFT, letter);
        g_free (letter);
    }

    adj = gtk_range_get_adjustment (GTK_RANGE (navigator));

    gtk_adjustment_set_upper (adj, priv->letters - 1);
    }

    void
    cursor_navigator_set_alphabet (CursorNavigator *navigator,
                                   const gchar * const *alphabet)
    {
    CursorNavigatorPrivate *priv;

    g_return_if_fail (CURSOR_IS_NAVIGATOR (navigator));
    g_return_if_fail (alphabet == NULL ||
              g_strv_length ((gchar **) alphabet) > 0);

    priv = navigator->priv;

    g_free (priv->alphabet);
    if (alphabet) {
        priv->alphabet = g_strdupv ((gchar **) alphabet);
        priv->letters = g_strv_length ((gchar **) alphabet);
    } else {
        priv->alphabet = NULL;
        priv->letters = -1;
    }

    cursor_navigator_update_parameters (navigator);
    cursor_navigator_set_index (navigator, 0);
    }

    const gchar * const *
    cursor_navigator_get_alphabet (CursorNavigator *navigator)
    {
    CursorNavigatorPrivate *priv;

    g_return_val_if_fail (CURSOR_IS_NAVIGATOR (navigator), NULL);

    priv = navigator->priv;

    return (const gchar * const *) priv->alphabet;
    }

    void
    cursor_navigator_set_index (CursorNavigator *navigator,
                                gint index)
    {
    CursorNavigatorPrivate *priv;
    GtkAdjustment          *adj;

    g_return_if_fail (CURSOR_IS_NAVIGATOR (navigator));

    priv = navigator->priv;
    adj = gtk_range_get_adjustment (GTK_RANGE (navigator));

    index = CLAMP (index, 0, priv->letters);

    if (priv->index != index) {

        priv->index = index;

        g_signal_emit (navigator, signals[INDEX_CHANGED], 0);

        g_signal_handlers_block_by_func (adj, cursor_navigator_changed, navigator);
        gtk_adjustment_set_value (adj, priv->index);
        g_signal_handlers_unblock_by_func (adj, cursor_navigator_changed, navigator);
    }
    }

    gint
    cursor_navigator_get_index (CursorNavigator *navigator)
    {
    CursorNavigatorPrivate *priv;

    g_return_val_if_fail (CURSOR_IS_NAVIGATOR (navigator), 0);

    priv = navigator->priv;

    return priv->index;
    }

## The search entry

The search entry is placed at the top of the contacts browser, this class simply implements a drop down box choosing the appropriate search expression which should be used to filter the contacts in the browser display window.

    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
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253

    /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
    /*
     * Copyright (C) 2013 Intel Corporation
     *
     * This library is free software you can redistribute it and/or modify it
     * under the terms of the GNU Lesser General Public License as published by
     * the Free Software Foundation.
     *
     * This library 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 Lesser General Public License
     * along with this library; if not, see <http://www.gnu.org/licenses/>.
     *
     * Author: Tristan Van Berkom <tristanvb@openismus.com>
     */

    #include <libebook/libebook.h>

    #include "cursor-search.h"

    /* GObjectClass */
    static void  cursor_search_finalize       (GObject           *object);
    static void  cursor_search_get_property   (GObject           *object,
                       guint              property_id,
                       GValue            *value,
                       GParamSpec        *pspec);

    /* UI Callbacks */
    static void  cursor_search_option_toggled (CursorSearch         *search,
                       GtkWidget            *item);
    static void  cursor_search_entry_changed  (CursorSearch         *search,
                       GtkEditable          *entry);
    static void  cursor_search_icon_press     (CursorSearch         *search,
                       GtkEntryIconPosition  icon_pos,
                       GdkEvent             *event,
                       GtkEntry             *entry);

    typedef enum {
    SEARCH_NAME,
    SEARCH_PHONE,
    SEARCH_EMAIL
    } SearchType;

    struct _CursorSearchPrivate {
    GtkWidget   *popup;
    GtkWidget   *name_radio;
    GtkWidget   *phone_radio;
    GtkWidget   *email_radio;

    SearchType   type;
    gchar       *sexp;
    };

    enum {
    PROP_0,
    PROP_SEXP,
    };

    G_DEFINE_TYPE_WITH_PRIVATE (CursorSearch, cursor_search, GTK_TYPE_SEARCH_ENTRY);

    /************************************************************************
     *                          GObjectClass                                *
     ************************************************************************/
    static void
    cursor_search_class_init (CursorSearchClass *klass)
    {
    GObjectClass *object_class;
    GtkWidgetClass *widget_class;

    object_class = G_OBJECT_CLASS (klass);
    object_class->finalize = cursor_search_finalize;
    object_class->get_property = cursor_search_get_property;

    g_object_class_install_property (
        object_class,
        PROP_SEXP,
        g_param_spec_string (
            "sexp",
            "Search Expression",
            "The active search expression",
            NULL,
            G_PARAM_READABLE |
            G_PARAM_STATIC_STRINGS));

    /* Bind to template */
    widget_class = GTK_WIDGET_CLASS (klass);
    gtk_widget_class_set_template_from_resource (widget_class, "/org/gnome/evolution/cursor-example/cursor-search.ui");
    gtk_widget_class_bind_template_child_private (widget_class, CursorSearch, popup);
    gtk_widget_class_bind_template_child_private (widget_class, CursorSearch, name_radio);
    gtk_widget_class_bind_template_child_private (widget_class, CursorSearch, phone_radio);
    gtk_widget_class_bind_template_child_private (widget_class, CursorSearch, email_radio);
    gtk_widget_class_bind_template_callback (widget_class, cursor_search_option_toggled);
    gtk_widget_class_bind_template_callback (widget_class, cursor_search_entry_changed);
    gtk_widget_class_bind_template_callback (widget_class, cursor_search_icon_press);
    }

    static void
    cursor_search_init (CursorSearch *search)
    {
    search->priv = cursor_search_get_instance_private (search);

    gtk_widget_init_template (GTK_WIDGET (search));

    g_object_set (
        search,
        "primary-icon-activatable", TRUE,
        "primary-icon-sensitive", TRUE,
        NULL);
    }

    static void
    cursor_search_finalize (GObject *object)
    {
    CursorSearch        *search = CURSOR_SEARCH (object);
    CursorSearchPrivate *priv = search->priv;

    g_free (priv->sexp);

    G_OBJECT_CLASS (cursor_search_parent_class)->finalize (object);
    }

    static void
    cursor_search_get_property (GObject *object,
                                guint property_id,
                                GValue *value,
                                GParamSpec *pspec)
    {
    CursorSearch        *search = CURSOR_SEARCH (object);
    CursorSearchPrivate *priv = search->priv;

    switch (property_id) {
    case PROP_SEXP:
        g_value_set_string (value, priv->sexp);
        break;

    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
        break;

    }
    }

    /************************************************************************
     *                              UI Callbacks                            *
     ************************************************************************/
    static void
    cursor_search_option_toggled (CursorSearch *search,
                                  GtkWidget *item)
    {
    CursorSearchPrivate *priv = search->priv;

    if (gtk_check_menu_item_get_active (GTK_CHECK_MENU_ITEM (item))) {

        if (item == priv->name_radio)
            priv->type = SEARCH_NAME;
        else if (item == priv->phone_radio)
            priv->type = SEARCH_PHONE;
        else if (item == priv->email_radio)
            priv->type = SEARCH_EMAIL;

        /* Refresh the search */
        cursor_search_entry_changed (search, NULL);
    }
    }

    static void
    cursor_search_entry_changed (CursorSearch *search,
                                 GtkEditable *entry)
    {
    CursorSearchPrivate *priv = search->priv;
    EBookQuery  *query = NULL;
    const gchar *text;

    text = gtk_entry_get_text (GTK_ENTRY (search));

    if (text && text[0]) {
        switch (priv->type) {
        case SEARCH_NAME:
            query = e_book_query_orv (
                e_book_query_field_test (E_CONTACT_FAMILY_NAME,
                E_BOOK_QUERY_CONTAINS,
                text),
                e_book_query_field_test (E_CONTACT_GIVEN_NAME,
                E_BOOK_QUERY_CONTAINS,
                text),
                NULL);
            break;
        case SEARCH_PHONE:
            query = e_book_query_field_test (
                E_CONTACT_TEL,
                E_BOOK_QUERY_CONTAINS,
                text);
            break;
        case SEARCH_EMAIL:
            query = e_book_query_field_test (
                E_CONTACT_EMAIL,
                E_BOOK_QUERY_CONTAINS,
                text);
            break;
        }
    }

    g_free (priv->sexp);

    if (query) {
        priv->sexp = e_book_query_to_string (query);
        e_book_query_unref (query);
    } else
        priv->sexp = g_strdup ("");

    g_object_notify (G_OBJECT (search), "sexp");
    }

    static void
    cursor_search_icon_press (CursorSearch *search,
                              GtkEntryIconPosition icon_pos,
                              GdkEvent *event,
                              GtkEntry *entry)
    {
    CursorSearchPrivate *priv = search->priv;
    GdkEventButton *button_event = (GdkEventButton *) event;

    if (icon_pos == GTK_ENTRY_ICON_PRIMARY)
        gtk_menu_popup (
            GTK_MENU (priv->popup),
                NULL, NULL, NULL, NULL,
                button_event->button,
                button_event->time);
    }

    /************************************************************************
     *                                API                                   *
     ************************************************************************/
    GtkWidget *
    cursor_search_new (void)
    {
      return (GtkWidget *) g_object_new (CURSOR_TYPE_SEARCH, NULL);
    }

    const gchar *
    cursor_search_get_sexp (CursorSearch *search)
    {
    CursorSearchPrivate *priv;

    g_return_val_if_fail (CURSOR_IS_SEARCH (search), NULL);

    priv = search->priv;

    return priv->sexp;
    }

## The contact slot

This is a very simple class who's only purpose is to display contact related data, each entry in the list is a 'slot'

    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
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136

    /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
    /*
     * Copyright (C) 2013 Intel Corporation
     *
     * This library is free software you can redistribute it and/or modify it
     * under the terms of the GNU Lesser General Public License as published by
     * the Free Software Foundation.
     *
     * This library 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 Lesser General Public License
     * along with this library; if not, see <http://www.gnu.org/licenses/>.
     *
     * Author: Tristan Van Berkom <tristanvb@openismus.com>
     */

    #include <libebook/libebook.h>

    #include "cursor-slot.h"

    struct _CursorSlotPrivate {
    /* Screen widgets */
    GtkWidget *area;
    GtkLabel  *name_label;
    GtkLabel  *emails_label;
    GtkLabel  *telephones_label;
    };

    G_DEFINE_TYPE_WITH_PRIVATE (CursorSlot, cursor_slot, GTK_TYPE_GRID);

    /************************************************************************
     *                          GObjectClass                                *
     ************************************************************************/
    static void
    cursor_slot_class_init (CursorSlotClass *klass)
    {
    GtkWidgetClass *widget_class;

    /* Bind to template */
    widget_class = GTK_WIDGET_CLASS (klass);
    gtk_widget_class_set_template_from_resource (widget_class, "/org/gnome/evolution/cursor-example/cursor-slot.ui");
    gtk_widget_class_bind_template_child_private (widget_class, CursorSlot, area);
    gtk_widget_class_bind_template_child_private (widget_class, CursorSlot, name_label);
    gtk_widget_class_bind_template_child_private (widget_class, CursorSlot, emails_label);
    gtk_widget_class_bind_template_child_private (widget_class, CursorSlot, telephones_label);
    }

    static void
    cursor_slot_init (CursorSlot *slot)
    {
    slot->priv = cursor_slot_get_instance_private (slot);

    gtk_widget_init_template (GTK_WIDGET (slot));
    }

    /************************************************************************
     *                                API                                   *
     ************************************************************************/
    GtkWidget *
    cursor_slot_new (EContact *contact)
    {
      CursorSlot *slot;

      slot = g_object_new (CURSOR_TYPE_SLOT, NULL);

      cursor_slot_set_from_contact (slot, contact);

      return (GtkWidget *) slot;
    }

    static gchar *
    make_string_from_list (EContact *contact,
                           EContactField field)
    {
    GList *values, *l;
    GString *string;

    string = g_string_new ("<span size=\"x-small\">");
    values = e_contact_get (contact, field);

    for (l = values; l; l = l->next) {
        gchar *value = (gchar *) l->data;

        if (l->prev != NULL)
            g_string_append (string, ", ");

        g_string_append (string, value);
    }

    if (!values)
        g_string_append (string, " - none - ");

    e_contact_attr_list_free (values);
    g_string_append (string, "</span>");

    return g_string_free (string, FALSE);
    }

    void
    cursor_slot_set_from_contact (CursorSlot *slot,
                                  EContact *contact)
    {
    CursorSlotPrivate *priv;
    const gchar *family_name, *given_name;
    gchar *str;

    g_return_if_fail (CURSOR_IS_SLOT (slot));
    g_return_if_fail (contact == NULL || E_IS_CONTACT (contact));

    priv = slot->priv;

    if (!contact) {
        gtk_widget_hide (priv->area);
        return;
    }

    family_name = (const gchar *) e_contact_get_const (contact, E_CONTACT_FAMILY_NAME);
    given_name = (const gchar *) e_contact_get_const (contact, E_CONTACT_GIVEN_NAME);

    str = g_strdup_printf ("%s, %s", family_name, given_name);
    gtk_label_set_text (priv->name_label, str);
    g_free (str);

    str = make_string_from_list (contact, E_CONTACT_EMAIL);
    gtk_label_set_markup (priv->emails_label, str);
    g_free (str);

    str = make_string_from_list (contact, E_CONTACT_TEL);
    gtk_label_set_markup (priv->telephones_label, str);
    g_free (str);

    gtk_widget_show (priv->area);
    }

## Creating addressbooks and loading vcards

This is the messy part of the example, here we take care of creating a custom addressbook and populating it with the contacts found in the directory given to the example.

    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
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250

    /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
    /*
     * Copyright (C) 2013 Intel Corporation
     *
     * This library is free software you can redistribute it and/or modify it
     * under the terms of the GNU Lesser General Public License as published by
     * the Free Software Foundation.
     *
     * This library 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 Lesser General Public License
     * along with this library; if not, see <http://www.gnu.org/licenses/>.
     *
     * Author: Tristan Van Berkom <tristanvb@openismus.com>
     */
    #include "cursor-data.h"

    #define CURSOR_DATA_SOURCE_ID "cursor-example-book"

    /* We need to spin the main loop a bit to wait for the ESource
     * to be created. This particular API is admittedly cumbersome,
     * hopefully this will be fixed in a later version so that
     * the ESource can be synchronously created.
     *
     * Just an example so lets just use some global variables here...
     */
    static EBookClient *address_book = NULL;
    static ESource     *address_book_source = NULL;

    static void
    cursor_data_source_added (ESourceRegistry *registry,
                              ESource *source,
                              gpointer data)
    {
    GError    *error = NULL;
    GMainLoop *loop = (GMainLoop *) data;

    if (g_strcmp0 (e_source_get_uid (source), CURSOR_DATA_SOURCE_ID) != 0)
        return;

    /* Open the address book */
    address_book = (EBookClient *) e_book_client_connect_sync (source, NULL, &error);
    if (!address_book)
        g_error ("Unable to create the test book: %s", error->message);

    address_book_source = g_object_ref (source);

    if (loop)
        g_main_loop_quit (loop);
    }

    static gboolean
    cursor_data_source_timeout (gpointer user_data)
    {
    g_error ("Timed out while waiting for ESource creation from the registry");

    return FALSE;
    }

    /*
     * Helper function to load a contact from a vcard file.
     */
    static EContact *
    contact_from_file (const gchar *vcard_file)
    {
    EContact *contact;
    GError *error;
    gchar *vcard = NULL;

    if (!g_file_get_contents (vcard_file, &vcard, NULL, &error))
        g_error ("Failed to load vcard: %s", error->message);

    contact = e_contact_new_from_vcard (vcard);
    g_free (vcard);

    return contact;
    }

    /*
     * Load all the contacts from 'vcard_directory', and add them to 'client'.
     */
    static void
    load_contacts (EBookClient *client,
                   const gchar *vcard_directory)
    {
    GDir *dir;
    GError *error = NULL;
    const gchar *filename;
    GSList *contacts = NULL;

    dir = g_dir_open (vcard_directory, 0, &error);
    if (!dir)
        g_error ("Failed to open vcard directory '%s': %s", vcard_directory, error->message);

    while ((filename = g_dir_read_name (dir)) != NULL) {

        if (g_str_has_suffix (filename, ".vcf")) {
            gchar *fullpath = g_build_filename (vcard_directory, filename, NULL);
            EContact *contact;

            contact = contact_from_file (fullpath);
            contacts = g_slist_prepend (contacts, contact);

            g_free (fullpath);
        }
    }

    g_dir_close (dir);

    if (contacts != NULL) {

        if (!e_book_client_add_contacts_sync (client, contacts, NULL, NULL, &error)) {

            /* If they were already added, ignore the error */
            if (g_error_matches (error, E_BOOK_CLIENT_ERROR,
                         E_BOOK_CLIENT_ERROR_CONTACT_ID_ALREADY_EXISTS))
                g_clear_error (&error);
            else
                g_error ("Failed to add test contacts: %s", error->message);
        }
    }
    }

    /*
     * Create an EBookClient cursor sorted by family name, and then by given name as
     * the secondary sort key.
     */
    static EBookClientCursor *
    get_cursor (EBookClient *book_client)
    {
      EContactField sort_fields[] = { E_CONTACT_FAMILY_NAME, E_CONTACT_GIVEN_NAME };
      EBookCursorSortType sort_types[] = { E_BOOK_CURSOR_SORT_ASCENDING, E_BOOK_CURSOR_SORT_ASCENDING };
      EBookClientCursor *cursor = NULL;
      GError *error = NULL;

      if (!e_book_client_get_cursor_sync (book_client,
                      NULL,
                      sort_fields,
                      sort_types,
                      2,
                      &cursor,
                      NULL,
                      &error)) {
      g_warning ("Unable to create cursor");
      g_clear_error (&error);
      }

      return cursor;
    }

    /* Entry point for this file, here we take care of
     * creating the addressbook if it doesnt exist,
     * getting an EBookClient, and creating our EBookClientCursor.
     */
    EBookClient *
    cursor_load_data (const gchar *vcard_path,
                      EBookClientCursor **ret_cursor)
    {
    ESourceRegistry *registry;
    ESource *scratch;
    ESourceBackend *backend = NULL;
    GMainLoop *loop;
    GError  *error = NULL;
    EBookClient *ret_book;

    g_return_val_if_fail (vcard_path != NULL, NULL);
    g_return_val_if_fail (ret_cursor != NULL, NULL);

    g_print ("Cursor loading data from %s\n", vcard_path);

    loop = g_main_loop_new (NULL, FALSE);

    registry = e_source_registry_new_sync (NULL, &error);
    if (!registry)
        g_error ("Unable to create the registry: %s", error->message);

    /* Listen to the registry for our added source */
    g_signal_connect (
        registry, "source-added",
        G_CALLBACK (cursor_data_source_added), loop);

    /* Now create a scratch source for our addressbook */
    scratch = e_source_new_with_uid (CURSOR_DATA_SOURCE_ID, NULL, &error);

    /* Ensure the new ESource will be a local addressbook source */
    backend = e_source_get_extension (scratch, E_SOURCE_EXTENSION_ADDRESS_BOOK);
    e_source_backend_set_backend_name (backend, "local");

    /* Now is the right time to use the ESourceBackendSummarySetup to configure
     * your newly created addressbook. This configuration should happen on the
     * scratch source before calling e_source_registry_commit_source_sync().
     */

    /* Commit the source to the registry */
    if (!e_source_registry_commit_source_sync (registry, scratch, NULL, &error)) {

        /* It's possible the source already exists if we already ran the example with this data server */
        if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_EXISTS)) {
            /* If so... then just call our callback early */
            ESource *source = e_source_registry_ref_source (registry, CURSOR_DATA_SOURCE_ID);

            g_clear_error (&error);
            g_assert (E_IS_SOURCE (source));

            /* Run the callback which creates the addressbook client connection */
            cursor_data_source_added (registry, source, NULL);
            g_object_unref (source);
        } else
            g_error ("Unable to add new addressbook source to the registry: %s", error->message);
    }

    g_object_unref (scratch);

    /* Give EDS a little time to actually create the ESource remotely and
     * also have a copy if it cached locally, wait for the "source-added"
     * signal.
     */
    if (address_book == NULL) {
        g_timeout_add_seconds (20, cursor_data_source_timeout, NULL);
        g_main_loop_run (loop);

        /* By now we aborted or we have an addressbook created */
        g_assert (address_book != NULL);
    }

    /**********************************************************
     * Ok, done with creating an addressbook, let's add data  *
     **********************************************************/
    load_contacts (address_book, vcard_path);

    /* Addressbook should have contacts now, let's create the cursor */
    *ret_cursor = get_cursor (address_book);

    /* Cleanup some resources we used to populate the addressbook */
    g_main_loop_unref (loop);
    g_object_unref (address_book_source);
    g_object_unref (registry);

    /* Give the ref through the return value*/
    ret_book = address_book;

    address_book_source = NULL;
    address_book = NULL;

    /* Return the addressbook */
    return ret_book;
    }