10ea8af5ec8aeadf64d4fc623c3ecabfc10d552e
[empathy.git] / libempathy-gtk / empathy-log-window.c
1 /*
2  * Copyright (C) 2006-2007 Imendio AB
3  * Copyright (C) 2007-2011 Collabora Ltd.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program 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 GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA  02110-1301  USA
19  *
20  * Authors: Martyn Russell <martyn@imendio.com>
21  *          Xavier Claessens <xclaesse@gmail.com>
22  *          Emilio Pozuelo Monfort <emilio.pozuelo@collabora.co.uk>
23  */
24
25 #include "config.h"
26
27 #include <string.h>
28 #include <stdlib.h>
29
30 #include <glib/gi18n-lib.h>
31 #include <gtk/gtk.h>
32 #include <webkit/webkit.h>
33
34 #include <telepathy-glib/telepathy-glib.h>
35 #include <telepathy-glib/proxy-subclass.h>
36
37 #include <telepathy-yell/telepathy-yell.h>
38
39 #include <telepathy-logger/telepathy-logger.h>
40 #ifdef HAVE_CALL_LOGS
41 # include <telepathy-logger/call-event.h>
42 #endif
43
44 #include <extensions/extensions.h>
45
46 #include <libempathy/action-chain-internal.h>
47 #include <libempathy/empathy-camera-monitor.h>
48 #include <libempathy/empathy-chatroom-manager.h>
49 #include <libempathy/empathy-chatroom.h>
50 #include <libempathy/empathy-gsettings.h>
51 #include <libempathy/empathy-message.h>
52 #include <libempathy/empathy-request-util.h>
53 #include <libempathy/empathy-utils.h>
54 #include <libempathy/empathy-time.h>
55
56 #include "empathy-log-window.h"
57 #include "empathy-account-chooser.h"
58 #include "empathy-call-utils.h"
59 #include "empathy-chat-view.h"
60 #include "empathy-contact-dialogs.h"
61 #include "empathy-images.h"
62 #include "empathy-theme-manager.h"
63 #include "empathy-ui-utils.h"
64 #include "empathy-webkit-utils.h"
65
66 #define DEBUG_FLAG EMPATHY_DEBUG_OTHER
67 #include <libempathy/empathy-debug.h>
68
69 #define EMPATHY_NS "http://live.gnome.org/Empathy"
70
71 G_DEFINE_TYPE (EmpathyLogWindow, empathy_log_window, GTK_TYPE_WINDOW);
72
73 struct _EmpathyLogWindowPriv
74 {
75   GtkWidget *vbox;
76
77   GtkWidget *button_profile;
78   GtkWidget *button_chat;
79   GtkWidget *button_call;
80   GtkWidget *button_video;
81
82   GtkWidget *search_entry;
83
84   GtkWidget *notebook;
85   GtkWidget *spinner;
86
87   GtkWidget *treeview_who;
88   GtkWidget *treeview_what;
89   GtkWidget *treeview_when;
90   GtkWidget *webview;
91
92   GtkTreeStore *store_events;
93
94   GtkWidget *account_chooser;
95
96   gchar *last_find;
97
98   /* List of selected GDates, free with g_list_free_full (l, g_date_free) */
99   GList *current_dates;
100
101   TplActionChain *chain;
102   TplLogManager *log_manager;
103
104   /* Hash of TpChannel<->TpAccount for use by the observer until we can
105    * get a TpAccount from a TpConnection or wherever */
106   GHashTable *channels;
107   TpBaseClient *observer;
108
109   EmpathyContact *selected_contact;
110   EmpathyContact *events_contact;
111
112   EmpathyCameraMonitor *camera_monitor;
113   GBinding *button_video_binding;
114
115   /* Used to cancel logger calls when no longer needed */
116   guint count;
117
118   /* List of owned TplLogSearchHits, free with tpl_log_search_hit_free */
119   GList *hits;
120   guint source;
121
122   /* Only used while waiting for the account chooser to be ready */
123   TpAccount *selected_account;
124   gchar *selected_chat_id;
125   gboolean selected_is_chatroom;
126
127   GSettings *gsettings_chat;
128   GSettings *gsettings_desktop;
129 };
130
131 static void log_window_search_entry_changed_cb   (GtkWidget        *entry,
132                                                   EmpathyLogWindow *self);
133 static void log_window_search_entry_activate_cb  (GtkWidget        *widget,
134                                                   EmpathyLogWindow *self);
135 static void log_window_search_entry_icon_pressed_cb (GtkEntry      *entry,
136                                                   GtkEntryIconPosition icon_pos,
137                                                   GdkEvent *event,
138                                                   gpointer user_data);
139 static void log_window_who_populate              (EmpathyLogWindow *self);
140 static void log_window_who_setup                 (EmpathyLogWindow *self);
141 static void log_window_when_setup                (EmpathyLogWindow *self);
142 static void log_window_what_setup                (EmpathyLogWindow *self);
143 static void log_window_events_setup              (EmpathyLogWindow *self);
144 static void log_window_chats_accounts_changed_cb (GtkWidget        *combobox,
145                                                   EmpathyLogWindow *self);
146 static void log_window_chats_set_selected        (EmpathyLogWindow *self);
147 static void log_window_chats_get_messages        (EmpathyLogWindow *self,
148                                                   gboolean force_get_dates);
149 static void log_window_when_changed_cb           (GtkTreeSelection *selection,
150                                                   EmpathyLogWindow *self);
151 static void log_window_delete_menu_clicked_cb    (GtkMenuItem      *menuitem,
152                                                   EmpathyLogWindow *self);
153 static void start_spinner                        (void);
154
155 static void log_window_create_observer           (EmpathyLogWindow *window);
156 static gboolean log_window_events_button_press_event (GtkWidget *webview,
157     GdkEventButton *event, EmpathyLogWindow *self);
158 static void log_window_update_buttons_sensitivity (EmpathyLogWindow *self);
159
160 static void
161 empathy_account_chooser_filter_has_logs (TpAccount *account,
162     EmpathyAccountChooserFilterResultCallback callback,
163     gpointer callback_data,
164     gpointer user_data);
165
166 enum
167 {
168   PAGE_EVENTS,
169   PAGE_SPINNER,
170   PAGE_EMPTY
171 };
172
173 enum
174 {
175   COL_TYPE_ANY,
176   COL_TYPE_SEPARATOR,
177   COL_TYPE_NORMAL
178 };
179
180 enum
181 {
182   COL_WHO_TYPE,
183   COL_WHO_ICON,
184   COL_WHO_NAME,
185   COL_WHO_NAME_SORT_KEY,
186   COL_WHO_ID,
187   COL_WHO_ACCOUNT,
188   COL_WHO_TARGET,
189   COL_WHO_COUNT
190 };
191
192 enum
193 {
194   COL_WHAT_TYPE,
195   COL_WHAT_SUBTYPE,
196   COL_WHAT_SENSITIVE,
197   COL_WHAT_TEXT,
198   COL_WHAT_ICON,
199   COL_WHAT_COUNT
200 };
201
202 enum
203 {
204   COL_WHEN_DATE,
205   COL_WHEN_TEXT,
206   COL_WHEN_ICON,
207   COL_WHEN_COUNT
208 };
209
210 enum
211 {
212   COL_EVENTS_TYPE,
213   COL_EVENTS_TS,
214   COL_EVENTS_PRETTY_DATE,
215   COL_EVENTS_ICON,
216   COL_EVENTS_TEXT,
217   COL_EVENTS_ACCOUNT,
218   COL_EVENTS_TARGET,
219   COL_EVENTS_EVENT,
220   COL_EVENTS_COUNT
221 };
222
223 #define CALENDAR_ICON "stock_calendar"
224
225 /* Seconds between two messages to be considered one conversation */
226 #define MAX_GAP 30*60
227
228 #define WHAT_TYPE_SEPARATOR -1
229
230 typedef enum
231 {
232   EVENT_CALL_INCOMING = 1 << 0,
233   EVENT_CALL_OUTGOING = 1 << 1,
234   EVENT_CALL_MISSED   = 1 << 2,
235   EVENT_CALL_ALL      = 1 << 3,
236 } EventSubtype;
237
238 static gboolean
239 log_window_get_selected (EmpathyLogWindow *window,
240     GList **accounts,
241     GList **entities,
242     gboolean *anyone,
243     GList **dates,
244     TplEventTypeMask *event_mask,
245     EventSubtype *subtype);
246
247 static EmpathyLogWindow *log_window = NULL;
248
249 static gboolean has_element;
250
251 #ifndef _date_copy
252 #define _date_copy(d) g_date_new_julian (g_date_get_julian (d))
253 #endif
254
255 typedef struct
256 {
257   EmpathyLogWindow *self;
258   TpAccount *account;
259   TplEntity *entity;
260   GDate *date;
261   TplEventTypeMask event_mask;
262   EventSubtype subtype;
263   guint count;
264 } Ctx;
265
266 static Ctx *
267 ctx_new (EmpathyLogWindow *self,
268     TpAccount *account,
269     TplEntity *entity,
270     GDate *date,
271     TplEventTypeMask event_mask,
272     EventSubtype subtype,
273     guint count)
274 {
275   Ctx *ctx = g_slice_new0 (Ctx);
276
277   ctx->self = self;
278   if (account != NULL)
279     ctx->account = g_object_ref (account);
280   if (entity != NULL)
281     ctx->entity = g_object_ref (entity);
282   if (date != NULL)
283     ctx->date = _date_copy (date);
284   ctx->event_mask = event_mask;
285   ctx->subtype = subtype;
286   ctx->count = count;
287
288   return ctx;
289 }
290
291 static void
292 ctx_free (Ctx *ctx)
293 {
294   tp_clear_object (&ctx->account);
295   tp_clear_object (&ctx->entity);
296   tp_clear_pointer (&ctx->date, g_date_free);
297
298   g_slice_free (Ctx, ctx);
299 }
300
301 static void
302 select_account_once_ready (EmpathyLogWindow *self,
303     TpAccount *account,
304     const gchar *chat_id,
305     gboolean is_chatroom)
306 {
307   EmpathyAccountChooser *account_chooser;
308
309   account_chooser = EMPATHY_ACCOUNT_CHOOSER (self->priv->account_chooser);
310
311   tp_clear_object (&self->priv->selected_account);
312   self->priv->selected_account = g_object_ref (account);
313
314   g_free (self->priv->selected_chat_id);
315   self->priv->selected_chat_id = g_strdup (chat_id);
316
317   self->priv->selected_is_chatroom = is_chatroom;
318
319   empathy_account_chooser_set_account (account_chooser,
320       self->priv->selected_account);
321 }
322
323 static void
324 toolbutton_profile_clicked (GtkToolButton *toolbutton,
325     EmpathyLogWindow *self)
326 {
327   g_return_if_fail (self != NULL);
328   g_return_if_fail (EMPATHY_IS_CONTACT (self->priv->selected_contact));
329
330   empathy_contact_information_dialog_show (self->priv->selected_contact,
331       GTK_WINDOW (self));
332 }
333
334 static void
335 toolbutton_chat_clicked (GtkToolButton *toolbutton,
336     EmpathyLogWindow *self)
337 {
338   g_return_if_fail (self != NULL);
339   g_return_if_fail (EMPATHY_IS_CONTACT (self->priv->selected_contact));
340
341   empathy_chat_with_contact (self->priv->selected_contact,
342       gtk_get_current_event_time ());
343 }
344
345 static void
346 toolbutton_av_clicked (GtkToolButton *toolbutton,
347     EmpathyLogWindow *self)
348 {
349   gboolean video;
350
351   g_return_if_fail (self != NULL);
352   g_return_if_fail (EMPATHY_IS_CONTACT (self->priv->selected_contact));
353
354   video = (GTK_WIDGET (toolbutton) == self->priv->button_video);
355
356   empathy_call_new_with_streams (
357       empathy_contact_get_id (self->priv->selected_contact),
358       empathy_contact_get_account (self->priv->selected_contact),
359       TRUE, video, gtk_get_current_event_time ());
360 }
361
362 static void
363 insert_or_change_row (EmpathyLogWindow *self,
364     const char *method,
365     GtkTreeModel *model,
366     GtkTreePath *path,
367     GtkTreeIter *iter)
368 {
369   char *str = gtk_tree_path_to_string (path);
370   char *script, *text, *date, *stock_icon;
371   char *icon = NULL;
372
373   gtk_tree_model_get (model, iter,
374       COL_EVENTS_TEXT, &text,
375       COL_EVENTS_PRETTY_DATE, &date,
376       COL_EVENTS_ICON, &stock_icon,
377       -1);
378
379   if (!tp_str_empty (stock_icon))
380     {
381       GtkIconInfo *icon_info = gtk_icon_theme_lookup_icon (
382           gtk_icon_theme_get_default (),
383           stock_icon,
384           GTK_ICON_SIZE_MENU, 0);
385
386       if (icon_info != NULL)
387         icon = g_strdup (gtk_icon_info_get_filename (icon_info));
388
389       gtk_icon_info_free (icon_info);
390     }
391
392   script = g_strdup_printf ("javascript:%s([%s], '%s', '%s', '%s');",
393       method,
394       g_strdelimit (str, ":", ','),
395       text,
396       icon != NULL ? icon : "",
397       date);
398
399   webkit_web_view_execute_script (WEBKIT_WEB_VIEW (self->priv->webview),
400       script);
401
402   g_free (str);
403   g_free (text);
404   g_free (date);
405   g_free (stock_icon);
406   g_free (icon);
407   g_free (script);
408 }
409
410 static void
411 store_events_row_inserted (GtkTreeModel *model,
412     GtkTreePath *path,
413     GtkTreeIter *iter,
414     EmpathyLogWindow *self)
415 {
416   insert_or_change_row (self, "insertRow", model, path, iter);
417 }
418
419 static void
420 store_events_row_changed (GtkTreeModel *model,
421     GtkTreePath *path,
422     GtkTreeIter *iter,
423     EmpathyLogWindow *self)
424 {
425   insert_or_change_row (self, "changeRow", model, path, iter);
426 }
427
428 static void
429 store_events_row_deleted (GtkTreeModel *model,
430     GtkTreePath *path,
431     EmpathyLogWindow *self)
432 {
433   char *str = gtk_tree_path_to_string (path);
434   char *script;
435
436   script = g_strdup_printf ("javascript:deleteRow([%s]);",
437       g_strdelimit (str, ":", ','));
438
439   webkit_web_view_execute_script (WEBKIT_WEB_VIEW (self->priv->webview),
440       script);
441
442   g_free (str);
443   g_free (script);
444 }
445
446 static void
447 store_events_has_child_rows (GtkTreeModel *model,
448     GtkTreePath *path,
449     GtkTreeIter *iter,
450     EmpathyLogWindow *self)
451 {
452   char *str = gtk_tree_path_to_string (path);
453   char *script;
454
455   script = g_strdup_printf ("javascript:hasChildRows([%s], %u);",
456       g_strdelimit (str, ":", ','),
457       gtk_tree_model_iter_has_child (model, iter));
458
459   webkit_web_view_execute_script (WEBKIT_WEB_VIEW (self->priv->webview),
460       script);
461
462   g_free (str);
463   g_free (script);
464 }
465
466 static void
467 store_events_rows_reordered (GtkTreeModel *model,
468     GtkTreePath *path,
469     GtkTreeIter *iter,
470     int *new_order,
471     EmpathyLogWindow *self)
472 {
473   char *str = gtk_tree_path_to_string (path);
474   int i, children = gtk_tree_model_iter_n_children (model, iter);
475   char **new_order_strv, *new_order_s;
476   char *script;
477
478   new_order_strv = g_new0 (char *, children + 1);
479
480   for (i = 0; i < children; i++)
481     new_order_strv[i] = g_strdup_printf ("%i", new_order[i]);
482
483   new_order_s = g_strjoinv (",", new_order_strv);
484
485   script = g_strdup_printf ("javascript:reorderRows([%s], [%s]);",
486       str == NULL ? "" : g_strdelimit (str, ":", ','),
487       new_order_s);
488
489   webkit_web_view_execute_script (WEBKIT_WEB_VIEW (self->priv->webview),
490       script);
491
492   g_free (str);
493   g_free (script);
494   g_free (new_order_s);
495   g_strfreev (new_order_strv);
496 }
497
498 static gboolean
499 events_webview_handle_navigation (WebKitWebView *webview,
500     WebKitWebFrame *frame,
501     WebKitNetworkRequest *request,
502     WebKitWebNavigationAction *navigation_action,
503     WebKitWebPolicyDecision *policy_decision,
504     EmpathyLogWindow *window)
505 {
506   empathy_url_show (GTK_WIDGET (webview),
507       webkit_network_request_get_uri (request));
508
509   webkit_web_policy_decision_ignore (policy_decision);
510   return TRUE;
511 }
512
513 static GObject *
514 empathy_log_window_constructor (GType type,
515     guint n_props,
516     GObjectConstructParam *props)
517 {
518   GObject *retval;
519
520   if (log_window != NULL)
521     {
522       retval = (GObject *) log_window;
523     }
524   else
525     {
526       retval = G_OBJECT_CLASS (empathy_log_window_parent_class)
527           ->constructor (type, n_props, props);
528
529       log_window = EMPATHY_LOG_WINDOW (retval);
530       g_object_add_weak_pointer (retval, (gpointer) &log_window);
531     }
532
533   return retval;
534 }
535
536 static void
537 empathy_log_window_dispose (GObject *object)
538 {
539   EmpathyLogWindow *self = EMPATHY_LOG_WINDOW (object);
540
541   if (self->priv->source != 0)
542     {
543       g_source_remove (self->priv->source);
544       self->priv->source = 0;
545     }
546
547   if (self->priv->current_dates != NULL)
548     {
549       g_list_free_full (self->priv->current_dates,
550           (GDestroyNotify) g_date_free);
551       self->priv->current_dates = NULL;
552     }
553
554   tp_clear_pointer (&self->priv->chain, _tpl_action_chain_free);
555   tp_clear_pointer (&self->priv->channels, g_hash_table_unref);
556
557   tp_clear_object (&self->priv->observer);
558   tp_clear_object (&self->priv->log_manager);
559   tp_clear_object (&self->priv->selected_account);
560   tp_clear_object (&self->priv->selected_contact);
561   tp_clear_object (&self->priv->events_contact);
562   tp_clear_object (&self->priv->camera_monitor);
563
564   tp_clear_object (&self->priv->gsettings_chat);
565   tp_clear_object (&self->priv->gsettings_desktop);
566
567   tp_clear_object (&self->priv->store_events);
568
569   G_OBJECT_CLASS (empathy_log_window_parent_class)->dispose (object);
570 }
571
572 static void
573 empathy_log_window_finalize (GObject *object)
574 {
575   EmpathyLogWindow *self = EMPATHY_LOG_WINDOW (object);
576
577   g_free (self->priv->last_find);
578   g_free (self->priv->selected_chat_id);
579
580   G_OBJECT_CLASS (empathy_log_window_parent_class)->finalize (object);
581 }
582
583 static void
584 empathy_log_window_class_init (
585   EmpathyLogWindowClass *empathy_log_window_class)
586 {
587   GObjectClass *object_class = G_OBJECT_CLASS (empathy_log_window_class);
588
589   g_type_class_add_private (empathy_log_window_class,
590       sizeof (EmpathyLogWindowPriv));
591
592   object_class->constructor = empathy_log_window_constructor;
593   object_class->dispose = empathy_log_window_dispose;
594   object_class->finalize = empathy_log_window_finalize;
595 }
596
597 static void
598 empathy_log_window_init (EmpathyLogWindow *self)
599 {
600   EmpathyAccountChooser *account_chooser;
601   GtkBuilder *gui;
602   gchar *filename;
603   GFile *gfile;
604   GtkWidget *vbox, *accounts, *search, *label, *closeitem;
605   GtkWidget *scrolledwindow_events;
606
607   self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self,
608       EMPATHY_TYPE_LOG_WINDOW, EmpathyLogWindowPriv);
609
610   self->priv->chain = _tpl_action_chain_new_async (NULL, NULL, NULL);
611
612   self->priv->camera_monitor = empathy_camera_monitor_dup_singleton ();
613
614   self->priv->log_manager = tpl_log_manager_dup_singleton ();
615
616   self->priv->gsettings_chat = g_settings_new (EMPATHY_PREFS_CHAT_SCHEMA);
617   self->priv->gsettings_desktop = g_settings_new (
618       EMPATHY_PREFS_DESKTOP_INTERFACE_SCHEMA);
619
620   gtk_window_set_title (GTK_WINDOW (self), _("History"));
621   gtk_widget_set_can_focus (GTK_WIDGET (self), FALSE);
622   gtk_window_set_default_size (GTK_WINDOW (self), 800, 600);
623
624   filename = empathy_file_lookup ("empathy-log-window.ui", "libempathy-gtk");
625   gui = empathy_builder_get_file (filename,
626       "vbox1", &self->priv->vbox,
627       "toolbutton_profile", &self->priv->button_profile,
628       "toolbutton_chat", &self->priv->button_chat,
629       "toolbutton_call", &self->priv->button_call,
630       "toolbutton_video", &self->priv->button_video,
631       "toolbutton_accounts", &accounts,
632       "toolbutton_search", &search,
633       "imagemenuitem_close", &closeitem,
634       "treeview_who", &self->priv->treeview_who,
635       "treeview_what", &self->priv->treeview_what,
636       "treeview_when", &self->priv->treeview_when,
637       "scrolledwindow_events", &scrolledwindow_events,
638       "notebook", &self->priv->notebook,
639       "spinner", &self->priv->spinner,
640       NULL);
641   g_free (filename);
642
643   empathy_builder_connect (gui, self,
644       "toolbutton_profile", "clicked", toolbutton_profile_clicked,
645       "toolbutton_chat", "clicked", toolbutton_chat_clicked,
646       "toolbutton_call", "clicked", toolbutton_av_clicked,
647       "toolbutton_video", "clicked", toolbutton_av_clicked,
648       "imagemenuitem_delete", "activate", log_window_delete_menu_clicked_cb,
649       NULL);
650
651   gtk_container_add (GTK_CONTAINER (self), self->priv->vbox);
652
653   g_object_unref (gui);
654
655   g_signal_connect_swapped (closeitem, "activate",
656       G_CALLBACK (gtk_widget_destroy), self);
657
658   /* Account chooser for chats */
659   vbox = gtk_vbox_new (FALSE, 3);
660
661   self->priv->account_chooser = empathy_account_chooser_new ();
662   account_chooser = EMPATHY_ACCOUNT_CHOOSER (self->priv->account_chooser);
663   empathy_account_chooser_set_has_all_option (account_chooser, TRUE);
664   empathy_account_chooser_set_filter (account_chooser,
665       empathy_account_chooser_filter_has_logs, NULL);
666   empathy_account_chooser_set_all (account_chooser);
667
668   gtk_style_context_add_class (gtk_widget_get_style_context (self->priv->account_chooser),
669                                GTK_STYLE_CLASS_RAISED);
670
671   g_signal_connect (self->priv->account_chooser, "changed",
672       G_CALLBACK (log_window_chats_accounts_changed_cb),
673       self);
674
675   label = gtk_label_new (_("Show"));
676
677   gtk_box_pack_start (GTK_BOX (vbox),
678       self->priv->account_chooser,
679       FALSE, FALSE, 0);
680
681   gtk_box_pack_start (GTK_BOX (vbox),
682       label,
683       FALSE, FALSE, 0);
684
685   gtk_widget_show_all (vbox);
686   gtk_container_add (GTK_CONTAINER (accounts), vbox);
687
688   /* Search entry */
689   vbox = gtk_vbox_new (FALSE, 3);
690
691   self->priv->search_entry = gtk_entry_new ();
692   gtk_entry_set_icon_from_icon_name (GTK_ENTRY (self->priv->search_entry),
693       GTK_ENTRY_ICON_SECONDARY, "edit-find-symbolic");
694   gtk_entry_set_icon_sensitive (GTK_ENTRY (self->priv->search_entry),
695                                 GTK_ENTRY_ICON_SECONDARY, FALSE);
696
697   label = gtk_label_new (_("Search"));
698
699   gtk_box_pack_start (GTK_BOX (vbox),
700       self->priv->search_entry,
701       FALSE, FALSE, 0);
702
703   gtk_box_pack_start (GTK_BOX (vbox),
704       label,
705       FALSE, FALSE, 0);
706
707   gtk_widget_show_all (vbox);
708   gtk_container_add (GTK_CONTAINER (search), vbox);
709
710   g_signal_connect (self->priv->search_entry, "changed",
711       G_CALLBACK (log_window_search_entry_changed_cb),
712       self);
713
714   g_signal_connect (self->priv->search_entry, "activate",
715       G_CALLBACK (log_window_search_entry_activate_cb),
716       self);
717
718   g_signal_connect (self->priv->search_entry, "icon-press",
719       G_CALLBACK (log_window_search_entry_icon_pressed_cb),
720       self);
721
722   /* Contacts */
723   log_window_events_setup (self);
724   log_window_who_setup (self);
725   log_window_what_setup (self);
726   log_window_when_setup (self);
727
728   log_window_create_observer (self);
729
730   log_window_who_populate (self);
731
732   /* events */
733   self->priv->webview = webkit_web_view_new ();
734   gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolledwindow_events),
735       GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
736   gtk_container_add (GTK_CONTAINER (scrolledwindow_events),
737       self->priv->webview);
738   gtk_widget_show (self->priv->webview);
739
740   empathy_webkit_bind_font_setting (WEBKIT_WEB_VIEW (self->priv->webview),
741       self->priv->gsettings_desktop,
742       EMPATHY_PREFS_DESKTOP_INTERFACE_FONT_NAME);
743
744   filename = empathy_file_lookup ("empathy-log-window.html", "data");
745   gfile = g_file_new_for_path (filename);
746   g_free (filename);
747
748   webkit_web_view_load_uri (WEBKIT_WEB_VIEW (self->priv->webview),
749       g_file_get_uri (gfile));
750   g_object_unref (gfile);
751
752   /* handle all navigation externally */
753   g_signal_connect (self->priv->webview, "navigation-policy-decision-requested",
754       G_CALLBACK (events_webview_handle_navigation), self);
755
756   /* listen to changes to the treemodel */
757   g_signal_connect (self->priv->store_events, "row-inserted",
758       G_CALLBACK (store_events_row_inserted), self);
759   g_signal_connect (self->priv->store_events, "row-changed",
760       G_CALLBACK (store_events_row_changed), self);
761   g_signal_connect (self->priv->store_events, "row-deleted",
762       G_CALLBACK (store_events_row_deleted), self);
763   g_signal_connect (self->priv->store_events, "rows-reordered",
764       G_CALLBACK (store_events_rows_reordered), self);
765   g_signal_connect (self->priv->store_events, "row-has-child-toggled",
766       G_CALLBACK (store_events_has_child_rows), self);
767
768   /* track clicked row */
769   g_signal_connect (self->priv->webview, "button-press-event",
770       G_CALLBACK (log_window_events_button_press_event), self);
771
772   log_window_update_buttons_sensitivity (self);
773   gtk_widget_show (GTK_WIDGET (self));
774 }
775
776 GtkWidget *
777 empathy_log_window_show (TpAccount *account,
778      const gchar *chat_id,
779      gboolean is_chatroom,
780      GtkWindow *parent)
781 {
782   log_window = g_object_new (EMPATHY_TYPE_LOG_WINDOW, NULL);
783
784   gtk_window_present (GTK_WINDOW (log_window));
785
786   if (account != NULL && chat_id != NULL)
787     select_account_once_ready (log_window, account, chat_id, is_chatroom);
788
789   if (parent != NULL)
790     gtk_window_set_transient_for (GTK_WINDOW (log_window),
791         GTK_WINDOW (parent));
792
793   return GTK_WIDGET (log_window);
794 }
795
796 static gboolean
797 account_equal (TpAccount *a,
798     TpAccount *b)
799 {
800   return g_str_equal (tp_proxy_get_object_path (a),
801       tp_proxy_get_object_path (b));
802 }
803
804 static gboolean
805 entity_equal (TplEntity *a,
806     TplEntity *b)
807 {
808   return g_str_equal (tpl_entity_get_identifier (a),
809       tpl_entity_get_identifier (b));
810 }
811
812 static gboolean
813 is_same_confroom (TplEvent *e1,
814     TplEvent *e2)
815 {
816   TplEntity *sender1 = tpl_event_get_sender (e1);
817   TplEntity *receiver1 = tpl_event_get_receiver (e1);
818   TplEntity *sender2 = tpl_event_get_sender (e2);
819   TplEntity *receiver2 = tpl_event_get_receiver (e2);
820   TplEntity *room1, *room2;
821
822   if (receiver1 == NULL || receiver2 == NULL)
823     return FALSE;
824
825   if (tpl_entity_get_entity_type (sender1) == TPL_ENTITY_ROOM)
826     room1 = sender1;
827   else if (tpl_entity_get_entity_type (receiver1) == TPL_ENTITY_ROOM)
828     room1 = receiver1;
829   else
830     return FALSE;
831
832   if (tpl_entity_get_entity_type (sender2) == TPL_ENTITY_ROOM)
833     room2 = sender2;
834   else if (tpl_entity_get_entity_type (receiver2) == TPL_ENTITY_ROOM)
835     room2 = receiver2;
836   else
837     return FALSE;
838
839   return g_str_equal (tpl_entity_get_identifier (room1),
840       tpl_entity_get_identifier (room2));
841 }
842
843 static void
844 maybe_refresh_logs (TpChannel *channel,
845     TpAccount *account)
846 {
847   GList *accounts = NULL, *entities = NULL, *dates = NULL;
848   GList *acc, *ent;
849   TplEventTypeMask event_mask;
850   GDate *anytime = NULL, *today = NULL;
851   GDateTime *now = NULL;
852   gboolean refresh = FALSE;
853   gboolean anyone;
854   const gchar *type;
855
856   if (!log_window_get_selected (log_window,
857       &accounts, &entities, &anyone, &dates, &event_mask, NULL))
858     {
859       DEBUG ("Could not get selected rows");
860       return;
861     }
862
863   type = tp_channel_get_channel_type (channel);
864
865   /* If the channel type is not in the What pane, whatever has happened
866    * won't be displayed in the events pane. */
867   if (!tp_strdiff (type, TP_IFACE_CHANNEL_TYPE_TEXT) &&
868       !(event_mask & TPL_EVENT_MASK_TEXT))
869     goto out;
870   if ((!tp_strdiff (type, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA) ||
871        !tp_strdiff (type, TPY_IFACE_CHANNEL_TYPE_CALL)) &&
872       !(event_mask & TPL_EVENT_MASK_CALL))
873     goto out;
874
875   anytime = g_date_new_dmy (2, 1, -1);
876   now = g_date_time_new_now_local ();
877   today = g_date_new_dmy (g_date_time_get_day_of_month (now),
878       g_date_time_get_month (now),
879       g_date_time_get_year (now));
880
881   /* If Today (or anytime) isn't selected, anything that has happened now
882    * won't be displayed. */
883   if (!g_list_find_custom (dates, anytime, (GCompareFunc) g_date_compare) &&
884       !g_list_find_custom (dates, today, (GCompareFunc) g_date_compare))
885     goto out;
886
887   if (anyone)
888     {
889       refresh = TRUE;
890       goto out;
891     }
892
893   for (acc = accounts, ent = entities;
894        acc != NULL && ent != NULL;
895        acc = g_list_next (acc), ent = g_list_next (ent))
896     {
897       if (!account_equal (account, acc->data))
898         continue;
899
900       if (!tp_strdiff (tp_channel_get_identifier (channel),
901                        tpl_entity_get_identifier (ent->data)))
902         {
903           refresh = TRUE;
904           break;
905         }
906     }
907
908  out:
909   tp_clear_pointer (&anytime, g_date_free);
910   tp_clear_pointer (&today, g_date_free);
911   tp_clear_pointer (&now, g_date_time_unref);
912   g_list_free_full (accounts, g_object_unref);
913   g_list_free_full (entities, g_object_unref);
914   g_list_free_full (dates, (GFreeFunc) g_date_free);
915
916   if (refresh)
917     {
918       DEBUG ("Refreshing logs after received event");
919
920       /* FIXME:  We need to populate the entities in case we
921        * didn't have any previous logs with this contact. */
922       log_window_chats_get_messages (log_window, FALSE);
923     }
924 }
925
926 static void
927 on_msg_sent (TpTextChannel *channel,
928     TpSignalledMessage *message,
929     guint flags,
930     gchar *token,
931     EmpathyLogWindow *self)
932 {
933   TpAccount *account = g_hash_table_lookup (self->priv->channels, channel);
934
935   maybe_refresh_logs (TP_CHANNEL (channel), account);
936 }
937
938 static void
939 on_msg_received (TpTextChannel *channel,
940     TpSignalledMessage *message,
941     EmpathyLogWindow *self)
942 {
943   TpMessage *msg = TP_MESSAGE (message);
944   TpChannelTextMessageType type = tp_message_get_message_type (msg);
945   TpAccount *account = g_hash_table_lookup (self->priv->channels, channel);
946
947   if (type != TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL &&
948       type != TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION)
949     return;
950
951   maybe_refresh_logs (TP_CHANNEL (channel), account);
952 }
953
954 static void
955 on_channel_ended (TpChannel *channel,
956     guint domain,
957     gint code,
958     gchar *message,
959     EmpathyLogWindow *self)
960 {
961   if (self->priv->channels != NULL)
962     g_hash_table_remove (self->priv->channels, channel);
963 }
964
965 static void
966 on_call_ended (TpChannel *channel,
967     guint domain,
968     gint code,
969     gchar *message,
970     EmpathyLogWindow *self)
971 {
972   TpAccount *account = g_hash_table_lookup (self->priv->channels, channel);
973
974   maybe_refresh_logs (channel, account);
975
976   if (self->priv->channels != NULL)
977     g_hash_table_remove (self->priv->channels, channel);
978 }
979
980 static void
981 observe_channels (TpSimpleObserver *observer,
982     TpAccount *account,
983     TpConnection *connection,
984     GList *channels,
985     TpChannelDispatchOperation *dispatch_operation,
986     GList *requests,
987     TpObserveChannelsContext *context,
988     gpointer user_data)
989 {
990   EmpathyLogWindow *self = user_data;
991
992   GList *l;
993
994   for (l = channels; l != NULL; l = g_list_next (l))
995     {
996       TpChannel *channel = l->data;
997       const gchar *type = tp_channel_get_channel_type (channel);
998
999       if (!tp_strdiff (type, TP_IFACE_CHANNEL_TYPE_TEXT))
1000         {
1001           TpTextChannel *text_channel = TP_TEXT_CHANNEL (channel);
1002
1003           g_hash_table_insert (self->priv->channels,
1004               g_object_ref (channel), g_object_ref (account));
1005
1006           tp_g_signal_connect_object (text_channel, "message-sent",
1007               G_CALLBACK (on_msg_sent), self, 0);
1008           tp_g_signal_connect_object (text_channel, "message-received",
1009               G_CALLBACK (on_msg_received), self, 0);
1010           tp_g_signal_connect_object (channel, "invalidated",
1011               G_CALLBACK (on_channel_ended), self, 0);
1012         }
1013       else if (!tp_strdiff (type, TPY_IFACE_CHANNEL_TYPE_CALL) ||
1014           !tp_strdiff (type, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA))
1015         {
1016           g_hash_table_insert (self->priv->channels,
1017               g_object_ref (channel), g_object_ref (account));
1018
1019           tp_g_signal_connect_object (channel, "invalidated",
1020               G_CALLBACK (on_call_ended), self, 0);
1021         }
1022       else
1023         {
1024           g_warning ("Unknown channel type: %s", type);
1025         }
1026     }
1027
1028   tp_observe_channels_context_accept (context);
1029 }
1030
1031 static void
1032 log_window_create_observer (EmpathyLogWindow *self)
1033 {
1034   TpAccountManager *am;
1035
1036   am = tp_account_manager_dup ();
1037
1038   self->priv->observer = tp_simple_observer_new_with_am (am, TRUE, "LogWindow",
1039       TRUE, observe_channels,
1040       g_object_ref (self), g_object_unref);
1041
1042   self->priv->channels = g_hash_table_new_full (g_direct_hash, g_direct_equal,
1043       g_object_unref, g_object_unref);
1044
1045   tp_base_client_take_observer_filter (self->priv->observer,
1046       tp_asv_new (
1047           TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING,
1048             TP_IFACE_CHANNEL_TYPE_TEXT,
1049           NULL));
1050   tp_base_client_take_observer_filter (self->priv->observer,
1051       tp_asv_new (
1052           TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING,
1053             TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
1054           NULL));
1055   tp_base_client_take_observer_filter (self->priv->observer,
1056       tp_asv_new (
1057           TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING,
1058             TPY_IFACE_CHANNEL_TYPE_CALL,
1059           NULL));
1060
1061   tp_base_client_register (self->priv->observer, NULL);
1062
1063   g_object_unref (am);
1064 }
1065
1066 static TplEntity *
1067 event_get_target (TplEvent *event)
1068 {
1069   TplEntity *sender = tpl_event_get_sender (event);
1070   TplEntity *receiver = tpl_event_get_receiver (event);
1071
1072   if (tpl_entity_get_entity_type (sender) == TPL_ENTITY_SELF)
1073     return receiver;
1074
1075   return sender;
1076 }
1077
1078 static gboolean
1079 model_is_parent (GtkTreeModel *model,
1080     GtkTreeIter *iter,
1081     TplEvent *event)
1082 {
1083   TplEvent *stored_event;
1084   TplEntity *target;
1085   TpAccount *account;
1086   gboolean found = FALSE;
1087   GtkTreeIter parent;
1088
1089   if (gtk_tree_model_iter_parent (model, &parent, iter))
1090     return FALSE;
1091
1092   gtk_tree_model_get (model, iter,
1093       COL_EVENTS_ACCOUNT, &account,
1094       COL_EVENTS_TARGET, &target,
1095       COL_EVENTS_EVENT, &stored_event,
1096       -1);
1097
1098   if (G_OBJECT_TYPE (event) == G_OBJECT_TYPE (stored_event) &&
1099       account_equal (account, tpl_event_get_account (event)) &&
1100       (entity_equal (target, event_get_target (event)) ||
1101       is_same_confroom (event, stored_event)))
1102     {
1103       GtkTreeIter child;
1104       gint64 timestamp;
1105
1106       gtk_tree_model_iter_nth_child (model, &child, iter,
1107           gtk_tree_model_iter_n_children (model, iter) - 1);
1108
1109       gtk_tree_model_get (model, &child,
1110           COL_EVENTS_TS, &timestamp,
1111           -1);
1112
1113       if (ABS (tpl_event_get_timestamp (event) - timestamp) < MAX_GAP)
1114         {
1115           /* The gap is smaller than 30 min */
1116           found = TRUE;
1117         }
1118     }
1119
1120   g_object_unref (stored_event);
1121   g_object_unref (account);
1122   g_object_unref (target);
1123
1124   return found;
1125 }
1126
1127 static gchar *
1128 get_display_string_for_chat_message (EmpathyMessage *message,
1129     TplEvent *event)
1130 {
1131   EmpathyContact *sender, *receiver, *target;
1132   TplEntity *ent_sender, *ent_receiver;
1133   const gchar *format;
1134
1135   sender = empathy_message_get_sender (message);
1136   receiver = empathy_message_get_receiver (message);
1137
1138   ent_sender = tpl_event_get_sender (event);
1139   ent_receiver = tpl_event_get_receiver (event);
1140
1141   /* If this is a MUC, we want to show "Chat in <room>". */
1142   if (tpl_entity_get_entity_type (ent_sender) == TPL_ENTITY_ROOM ||
1143       (ent_receiver != NULL &&
1144       tpl_entity_get_entity_type (ent_receiver) == TPL_ENTITY_ROOM))
1145     format = _("Chat in %s");
1146   else
1147     format = _("Chat with %s");
1148
1149   if (tpl_entity_get_entity_type (ent_sender) == TPL_ENTITY_ROOM)
1150     target = sender;
1151   else if (ent_receiver != NULL &&
1152       tpl_entity_get_entity_type (ent_receiver) == TPL_ENTITY_ROOM)
1153     target = receiver;
1154   else if (empathy_contact_is_user (sender))
1155     target = receiver;
1156   else
1157     target = sender;
1158
1159   return g_markup_printf_escaped (format, empathy_contact_get_alias (target));
1160 }
1161
1162 static void
1163 get_parent_iter_for_message (TplEvent *event,
1164     EmpathyMessage *message,
1165     GtkTreeIter *parent)
1166 {
1167   GtkTreeStore *store;
1168   GtkTreeModel *model;
1169   GtkTreeIter iter;
1170   gboolean parent_found = FALSE;
1171   gboolean next;
1172
1173   store = log_window->priv->store_events;
1174   model = GTK_TREE_MODEL (store);
1175
1176   for (next = gtk_tree_model_get_iter_first (model, &iter);
1177        next;
1178        next = gtk_tree_model_iter_next (model, &iter))
1179     {
1180       if ((parent_found = model_is_parent (model, &iter, event)))
1181         break;
1182     }
1183
1184   if (parent_found)
1185     {
1186       *parent = iter;
1187     }
1188   else
1189     {
1190       GDateTime *date;
1191       gchar *body, *pretty_date;
1192
1193       date = g_date_time_new_from_unix_local (
1194           tpl_event_get_timestamp (event));
1195
1196       pretty_date = g_date_time_format (date,
1197           C_("A date with the time", "%A, %e %B %Y %X"));
1198
1199       body = get_display_string_for_chat_message (message, event);
1200
1201       gtk_tree_store_append (store, &iter, NULL);
1202       gtk_tree_store_set (store, &iter,
1203           COL_EVENTS_TS, tpl_event_get_timestamp (event),
1204           COL_EVENTS_PRETTY_DATE, pretty_date,
1205           COL_EVENTS_TEXT, body,
1206           COL_EVENTS_ICON, "format-justify-fill",
1207           COL_EVENTS_ACCOUNT, tpl_event_get_account (event),
1208           COL_EVENTS_TARGET, event_get_target (event),
1209           COL_EVENTS_EVENT, event,
1210           -1);
1211
1212       *parent = iter;
1213
1214       g_free (body);
1215       g_free (pretty_date);
1216       g_date_time_unref (date);
1217     }
1218 }
1219
1220 static const gchar *
1221 get_icon_for_event (TplEvent *event)
1222 {
1223   const gchar *icon = NULL;
1224
1225   if (TPL_IS_TEXT_EVENT (event))
1226     {
1227       TplTextEvent *text = TPL_TEXT_EVENT (event);
1228
1229       if (!tp_str_empty (tpl_text_event_get_supersedes_token (text)))
1230         icon = EMPATHY_IMAGE_EDIT_MESSAGE;
1231     }
1232 #ifdef HAVE_CALL_LOGS
1233   else if (TPL_IS_CALL_EVENT (event))
1234     {
1235       TplCallEvent *call = TPL_CALL_EVENT (event);
1236       TplCallEndReason reason = tpl_call_event_get_end_reason (call);
1237       TplEntity *sender = tpl_event_get_sender (event);
1238       TplEntity *receiver = tpl_event_get_receiver (event);
1239
1240       if (reason == TPL_CALL_END_REASON_NO_ANSWER)
1241         icon = EMPATHY_IMAGE_CALL_MISSED;
1242       else if (tpl_entity_get_entity_type (sender) == TPL_ENTITY_SELF)
1243         icon = EMPATHY_IMAGE_CALL_OUTGOING;
1244       else if (tpl_entity_get_entity_type (receiver) == TPL_ENTITY_SELF)
1245         icon = EMPATHY_IMAGE_CALL_INCOMING;
1246     }
1247 #endif
1248
1249   return icon;
1250 }
1251
1252 static void
1253 log_window_append_chat_message (TplEvent *event,
1254     EmpathyMessage *message)
1255 {
1256   GtkTreeStore *store = log_window->priv->store_events;
1257   GtkTreeIter iter, parent;
1258   gchar *pretty_date, *alias, *body;
1259   GDateTime *date;
1260   EmpathyStringParser *parsers;
1261   GString *msg;
1262
1263   date = g_date_time_new_from_unix_local (
1264       tpl_event_get_timestamp (event));
1265
1266   pretty_date = g_date_time_format (date, "%X");
1267
1268   get_parent_iter_for_message (event, message, &parent);
1269
1270   alias = g_markup_escape_text (
1271       tpl_entity_get_alias (tpl_event_get_sender (event)), -1);
1272
1273   /* escape the text */
1274   parsers = empathy_webkit_get_string_parser (
1275       g_settings_get_boolean (log_window->priv->gsettings_chat,
1276         EMPATHY_PREFS_CHAT_SHOW_SMILEYS));
1277   msg = g_string_new ("");
1278
1279   empathy_string_parser_substr (empathy_message_get_body (message), -1,
1280       parsers, msg);
1281
1282   if (tpl_text_event_get_message_type (TPL_TEXT_EVENT (event))
1283       == TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION)
1284     {
1285       /* Translators: this is an emote: '* Danielle waves' */
1286       body = g_strdup_printf (_("<i>* %s %s</i>"), alias, msg->str);
1287     }
1288   else
1289     {
1290       /* Translators: this is a message: 'Danielle: hello'
1291        * The string in bold is the sender's name */
1292       body = g_strdup_printf (_("<b>%s:</b> %s"), alias, msg->str);
1293     }
1294
1295   gtk_tree_store_append (store, &iter, &parent);
1296   gtk_tree_store_set (store, &iter,
1297       COL_EVENTS_TS, tpl_event_get_timestamp (event),
1298       COL_EVENTS_PRETTY_DATE, pretty_date,
1299       COL_EVENTS_TEXT, body,
1300       COL_EVENTS_ICON, get_icon_for_event (event),
1301       COL_EVENTS_ACCOUNT, tpl_event_get_account (event),
1302       COL_EVENTS_TARGET, event_get_target (event),
1303       COL_EVENTS_EVENT, event,
1304       -1);
1305
1306   g_string_free (msg, TRUE);
1307   g_free (body);
1308   g_free (alias);
1309   g_free (pretty_date);
1310   g_date_time_unref (date);
1311 }
1312
1313 #ifdef HAVE_CALL_LOGS
1314 static void
1315 log_window_append_call (TplEvent *event,
1316     EmpathyMessage *message)
1317 {
1318   TplCallEvent *call = TPL_CALL_EVENT (event);
1319   GtkTreeStore *store = log_window->priv->store_events;
1320   GtkTreeIter iter, child;
1321   gchar *pretty_date, *duration, *finished;
1322   GDateTime *started_date, *finished_date;
1323   GTimeSpan span;
1324
1325   /* If searching, only add the call if the search string appears anywhere */
1326   if (!EMP_STR_EMPTY (log_window->priv->last_find))
1327     {
1328       if (strstr (tpl_entity_get_identifier (tpl_event_get_sender (event)),
1329               log_window->priv->last_find) == NULL &&
1330           strstr (tpl_entity_get_identifier (tpl_event_get_receiver (event)),
1331               log_window->priv->last_find) == NULL &&
1332           strstr (tpl_call_event_get_detailed_end_reason (call),
1333               log_window->priv->last_find) == NULL)
1334         {
1335           DEBUG ("TplCallEvent doesn't match search string, ignoring");
1336           return;
1337         }
1338     }
1339
1340   started_date = g_date_time_new_from_unix_local (
1341       tpl_event_get_timestamp (event));
1342
1343   pretty_date = g_date_time_format (started_date,
1344       C_("A date with the time", "%A, %e %B %Y %X"));
1345
1346   gtk_tree_store_append (store, &iter, NULL);
1347   gtk_tree_store_set (store, &iter,
1348       COL_EVENTS_TS, tpl_event_get_timestamp (event),
1349       COL_EVENTS_PRETTY_DATE, pretty_date,
1350       COL_EVENTS_TEXT, empathy_message_get_body (message),
1351       COL_EVENTS_ICON, get_icon_for_event (event),
1352       COL_EVENTS_ACCOUNT, tpl_event_get_account (event),
1353       COL_EVENTS_TARGET, event_get_target (event),
1354       COL_EVENTS_EVENT, event,
1355       -1);
1356
1357   if (tpl_call_event_get_end_reason (call) != TPL_CALL_END_REASON_NO_ANSWER)
1358     {
1359       gchar *body;
1360       gchar *tmp;
1361
1362       span = tpl_call_event_get_duration (TPL_CALL_EVENT (event));
1363
1364       if (span < 60)
1365         {
1366           tmp = g_strdup_printf ("%" G_GINT64_FORMAT, span);
1367           duration = g_strdup_printf (
1368               ngettext ("%s second", "%s seconds", span), tmp);
1369           g_free (tmp);
1370         }
1371       else
1372         {
1373           tmp = g_strdup_printf ("%" G_GINT64_FORMAT, span / 60);
1374           duration = g_strdup_printf (
1375               ngettext ("%s minute", "%s minutes", span / 60), tmp);
1376           g_free (tmp);
1377         }
1378
1379       finished_date = g_date_time_add (started_date, -span);
1380       finished = g_date_time_format (finished_date, "%X");
1381       g_date_time_unref (finished_date);
1382
1383       body = g_strdup_printf (_("Call took %s, ended at %s"),
1384           duration, finished);
1385
1386       g_free (duration);
1387       g_free (finished);
1388
1389       gtk_tree_store_append (store, &child, &iter);
1390       gtk_tree_store_set (store, &child,
1391           COL_EVENTS_TS, tpl_event_get_timestamp (event),
1392           COL_EVENTS_TEXT, body,
1393           COL_EVENTS_ACCOUNT, tpl_event_get_account (event),
1394           COL_EVENTS_TARGET, event_get_target (event),
1395           COL_EVENTS_EVENT, event,
1396           -1);
1397
1398       g_free (body);
1399     }
1400
1401   g_free (pretty_date);
1402   g_date_time_unref (started_date);
1403 }
1404 #endif
1405
1406 static void
1407 log_window_append_message (TplEvent *event,
1408     EmpathyMessage *message)
1409 {
1410   if (TPL_IS_TEXT_EVENT (event))
1411     log_window_append_chat_message (event, message);
1412 #ifdef HAVE_CALL_LOGS
1413   else if (TPL_IS_CALL_EVENT (event))
1414     log_window_append_call (event, message);
1415 #endif
1416   else
1417     DEBUG ("Message type not handled");
1418 }
1419
1420 static void
1421 add_all_accounts_and_entities (GList **accounts,
1422     GList **entities)
1423 {
1424   GtkTreeView      *view;
1425   GtkTreeModel     *model;
1426   GtkTreeIter       iter;
1427
1428   view = GTK_TREE_VIEW (log_window->priv->treeview_who);
1429   model = gtk_tree_view_get_model (view);
1430
1431   if (!gtk_tree_model_get_iter_first (model, &iter))
1432     return;
1433
1434   do
1435     {
1436       TpAccount *account;
1437       TplEntity *entity;
1438       gint type;
1439
1440       gtk_tree_model_get (model, &iter,
1441           COL_WHO_ACCOUNT, &account,
1442           COL_WHO_TARGET, &entity,
1443           COL_WHO_TYPE, &type,
1444           -1);
1445
1446       if (type != COL_TYPE_NORMAL)
1447         continue;
1448
1449       if (accounts != NULL)
1450         *accounts = g_list_append (*accounts, account);
1451
1452       if (entities != NULL)
1453         *entities = g_list_append (*entities, entity);
1454     }
1455   while (gtk_tree_model_iter_next (model, &iter));
1456 }
1457
1458 static gboolean
1459 log_window_get_selected (EmpathyLogWindow *self,
1460     GList **accounts,
1461     GList **entities,
1462     gboolean *anyone,
1463     GList **dates,
1464     TplEventTypeMask *event_mask,
1465     EventSubtype *subtype)
1466 {
1467   GtkTreeView      *view;
1468   GtkTreeModel     *model;
1469   GtkTreeSelection *selection;
1470   GtkTreeIter       iter;
1471   TplEventTypeMask  ev = 0;
1472   EventSubtype      st = 0;
1473   GList            *paths, *l;
1474   gint              type;
1475
1476   view = GTK_TREE_VIEW (self->priv->treeview_who);
1477   model = gtk_tree_view_get_model (view);
1478   selection = gtk_tree_view_get_selection (view);
1479
1480   paths = gtk_tree_selection_get_selected_rows (selection, NULL);
1481   if (paths == NULL)
1482     return FALSE;
1483
1484   if (accounts != NULL)
1485     *accounts = NULL;
1486   if (entities != NULL)
1487     *entities = NULL;
1488   if (anyone != NULL)
1489     *anyone = FALSE;
1490
1491   for (l = paths; l != NULL; l = l->next)
1492     {
1493       GtkTreePath *path = l->data;
1494       TpAccount *account;
1495       TplEntity *entity;
1496
1497       gtk_tree_model_get_iter (model, &iter, path);
1498       gtk_tree_model_get (model, &iter,
1499           COL_WHO_ACCOUNT, &account,
1500           COL_WHO_TARGET, &entity,
1501           COL_WHO_TYPE, &type,
1502           -1);
1503
1504       if (type == COL_TYPE_ANY)
1505         {
1506           if (accounts != NULL || entities != NULL)
1507             add_all_accounts_and_entities (accounts, entities);
1508           if (anyone != NULL)
1509             *anyone = TRUE;
1510           break;
1511         }
1512
1513       if (accounts != NULL)
1514         *accounts = g_list_append (*accounts, g_object_ref (account));
1515
1516       if (entities != NULL)
1517         *entities = g_list_append (*entities, g_object_ref (entity));
1518
1519       g_object_unref (account);
1520       g_object_unref (entity);
1521     }
1522   g_list_free_full (paths, (GDestroyNotify) gtk_tree_path_free);
1523
1524   view = GTK_TREE_VIEW (self->priv->treeview_what);
1525   model = gtk_tree_view_get_model (view);
1526   selection = gtk_tree_view_get_selection (view);
1527
1528   paths = gtk_tree_selection_get_selected_rows (selection, NULL);
1529   for (l = paths; l != NULL; l = l->next)
1530     {
1531       GtkTreePath *path = l->data;
1532       TplEventTypeMask mask;
1533       EventSubtype submask;
1534
1535       gtk_tree_model_get_iter (model, &iter, path);
1536       gtk_tree_model_get (model, &iter,
1537           COL_WHAT_TYPE, &mask,
1538           COL_WHAT_SUBTYPE, &submask,
1539           -1);
1540
1541       ev |= mask;
1542       st |= submask;
1543     }
1544   g_list_free_full (paths, (GDestroyNotify) gtk_tree_path_free);
1545
1546   view = GTK_TREE_VIEW (self->priv->treeview_when);
1547   model = gtk_tree_view_get_model (view);
1548   selection = gtk_tree_view_get_selection (view);
1549
1550   if (dates != NULL)
1551     {
1552       *dates = NULL;
1553
1554       paths = gtk_tree_selection_get_selected_rows (selection, NULL);
1555       for (l = paths; l != NULL; l = l->next)
1556         {
1557           GtkTreePath *path = l->data;
1558           GDate *date;
1559
1560           gtk_tree_model_get_iter (model, &iter, path);
1561           gtk_tree_model_get (model, &iter,
1562               COL_WHEN_DATE, &date,
1563               -1);
1564
1565           *dates = g_list_append (*dates, date);
1566         }
1567       g_list_free_full (paths, (GDestroyNotify) gtk_tree_path_free);
1568     }
1569
1570   if (event_mask != NULL)
1571     *event_mask = ev;
1572
1573   if (subtype != NULL)
1574     *subtype = st;
1575
1576   return TRUE;
1577 }
1578
1579 static gboolean
1580 model_has_entity (GtkTreeModel *model,
1581     GtkTreePath *path,
1582     GtkTreeIter *iter,
1583     gpointer data)
1584 {
1585   TplLogSearchHit *hit = data;
1586   TplEntity *e;
1587   TpAccount *a;
1588   gboolean ret = FALSE;
1589
1590   gtk_tree_model_get (model, iter,
1591       COL_WHO_TARGET, &e,
1592       COL_WHO_ACCOUNT, &a,
1593       -1);
1594
1595   if (e != NULL && entity_equal (hit->target, e) &&
1596       a != NULL && account_equal (hit->account, a))
1597     {
1598       ret = has_element = TRUE;
1599     }
1600
1601   tp_clear_object (&e);
1602   tp_clear_object (&a);
1603
1604   return ret;
1605 }
1606
1607 static gboolean
1608 model_has_date (GtkTreeModel *model,
1609     GtkTreePath *path,
1610     GtkTreeIter *iter,
1611     gpointer data)
1612 {
1613   GDate *date = data;
1614   GDate *d;
1615
1616   gtk_tree_model_get (model, iter,
1617       COL_WHEN_DATE, &d,
1618       -1);
1619
1620   if (!g_date_compare (date, d))
1621     {
1622       has_element = TRUE;
1623       return TRUE;
1624     }
1625
1626   return FALSE;
1627 }
1628
1629 static void
1630 get_events_for_date (TplActionChain *chain, gpointer user_data);
1631
1632 static void
1633 populate_events_from_search_hits (GList *accounts,
1634     GList *targets,
1635     GList *dates)
1636 {
1637   TplEventTypeMask event_mask;
1638   EventSubtype subtype;
1639   GDate *anytime;
1640   GList *l;
1641   gboolean is_anytime = FALSE;
1642
1643   if (!log_window_get_selected (log_window,
1644       NULL, NULL, NULL, NULL, &event_mask, &subtype))
1645     return;
1646
1647   anytime = g_date_new_dmy (2, 1, -1);
1648   if (g_list_find_custom (dates, anytime, (GCompareFunc) g_date_compare))
1649     is_anytime = TRUE;
1650
1651   for (l = log_window->priv->hits; l != NULL; l = l->next)
1652     {
1653       TplLogSearchHit *hit = l->data;
1654       GList *acc, *targ;
1655       gboolean found = FALSE;
1656
1657       /* Protect against invalid data (corrupt or old log files). */
1658       if (hit->account == NULL || hit->target == NULL)
1659         continue;
1660
1661       for (acc = accounts, targ = targets;
1662            acc != NULL && targ != NULL && !found;
1663            acc = acc->next, targ = targ->next)
1664         {
1665           TpAccount *account = acc->data;
1666           TplEntity *target = targ->data;
1667
1668           if (account_equal (hit->account, account) &&
1669               entity_equal (hit->target, target))
1670             found = TRUE;
1671         }
1672
1673         if (!found)
1674           continue;
1675
1676       if (is_anytime ||
1677           g_list_find_custom (dates, hit->date, (GCompareFunc) g_date_compare)
1678               != NULL)
1679         {
1680           Ctx *ctx;
1681
1682           ctx = ctx_new (log_window, hit->account, hit->target, hit->date,
1683               event_mask, subtype, log_window->priv->count);
1684           _tpl_action_chain_append (log_window->priv->chain,
1685               get_events_for_date, ctx);
1686         }
1687     }
1688
1689   start_spinner ();
1690   _tpl_action_chain_start (log_window->priv->chain);
1691
1692   g_date_free (anytime);
1693 }
1694
1695 static gchar *
1696 format_date_for_display (GDate *date)
1697 {
1698   gchar *text;
1699   GDate *now = NULL;
1700   gint days_elapsed;
1701
1702   /* g_date_strftime sucks */
1703
1704   now = g_date_new ();
1705   g_date_set_time_t (now, time (NULL));
1706
1707   days_elapsed = g_date_days_between (date, now);
1708
1709   if (days_elapsed < 0)
1710     {
1711       text = NULL;
1712     }
1713   else if (days_elapsed == 0)
1714     {
1715       text = g_strdup (_("Today"));
1716     }
1717   else if (days_elapsed == 1)
1718     {
1719       text = g_strdup (_("Yesterday"));
1720     }
1721   else
1722     {
1723       GDateTime *dt;
1724
1725       dt = g_date_time_new_utc (g_date_get_year (date),
1726           g_date_get_month (date), g_date_get_day (date),
1727           0, 0, 0);
1728
1729       if (days_elapsed <= 7)
1730         text = g_date_time_format (dt, "%A");
1731       else
1732         text = g_date_time_format (dt,
1733             /* Translators: A date such as '23 May 2010' (strftime format) */
1734             _("%e %B %Y"));
1735
1736       g_date_time_unref (dt);
1737     }
1738
1739   g_date_free (now);
1740
1741   return text;
1742 }
1743
1744 static void
1745 populate_dates_from_search_hits (GList *accounts,
1746     GList *targets)
1747 {
1748   GList *l;
1749   GtkTreeView *view;
1750   GtkTreeModel *model;
1751   GtkListStore *store;
1752   GtkTreeSelection *selection;
1753   GtkTreeIter iter;
1754
1755   if (log_window == NULL)
1756     return;
1757
1758   view = GTK_TREE_VIEW (log_window->priv->treeview_when);
1759   model = gtk_tree_view_get_model (view);
1760   store = GTK_LIST_STORE (model);
1761   selection = gtk_tree_view_get_selection (view);
1762
1763   for (l = log_window->priv->hits; l != NULL; l = l->next)
1764     {
1765       TplLogSearchHit *hit = l->data;
1766       GList *acc, *targ;
1767       gboolean found = FALSE;
1768
1769       /* Protect against invalid data (corrupt or old log files). */
1770       if (hit->account == NULL || hit->target == NULL)
1771         continue;
1772
1773       for (acc = accounts, targ = targets;
1774            acc != NULL && targ != NULL && !found;
1775            acc = acc->next, targ = targ->next)
1776         {
1777           TpAccount *account = acc->data;
1778           TplEntity *target = targ->data;
1779
1780           if (account_equal (hit->account, account) &&
1781               entity_equal (hit->target, target))
1782             found = TRUE;
1783         }
1784
1785         if (!found)
1786           continue;
1787
1788       /* Add the date if it's not already there */
1789       has_element = FALSE;
1790       gtk_tree_model_foreach (model, model_has_date, hit->date);
1791       if (!has_element)
1792         {
1793           gchar *text = format_date_for_display (hit->date);
1794
1795           gtk_list_store_append (store, &iter);
1796           gtk_list_store_set (store, &iter,
1797               COL_WHEN_DATE, hit->date,
1798               COL_WHEN_TEXT, text,
1799               COL_WHEN_ICON, CALENDAR_ICON,
1800               -1);
1801         }
1802     }
1803
1804   if (gtk_tree_model_get_iter_first (model, &iter))
1805     {
1806       gtk_list_store_prepend (store, &iter);
1807       gtk_list_store_set (store, &iter,
1808           COL_WHEN_DATE, g_date_new_dmy (1, 1, -1),
1809           COL_WHEN_TEXT, "separator",
1810           -1);
1811
1812       gtk_list_store_prepend (store, &iter);
1813       gtk_list_store_set (store, &iter,
1814           COL_WHEN_DATE, g_date_new_dmy (2, 1, -1),
1815           COL_WHEN_TEXT, _("Anytime"),
1816           -1);
1817
1818       if (gtk_tree_model_iter_nth_child (model, &iter, NULL, 2))
1819         gtk_tree_selection_select_iter (selection, &iter);
1820     }
1821 }
1822
1823 static void
1824 populate_entities_from_search_hits (void)
1825 {
1826   EmpathyAccountChooser *account_chooser;
1827   TpAccount *account;
1828   GtkTreeView *view;
1829   GtkTreeModel *model;
1830   GtkTreeSelection *selection;
1831   GtkTreeIter iter;
1832   GtkListStore *store;
1833   GList *l;
1834
1835   view = GTK_TREE_VIEW (log_window->priv->treeview_who);
1836   model = gtk_tree_view_get_model (view);
1837   store = GTK_LIST_STORE (model);
1838   selection = gtk_tree_view_get_selection (view);
1839
1840   gtk_list_store_clear (store);
1841
1842   account_chooser = EMPATHY_ACCOUNT_CHOOSER (log_window->priv->account_chooser);
1843   account = empathy_account_chooser_get_account (account_chooser);
1844
1845   for (l = log_window->priv->hits; l; l = l->next)
1846     {
1847       TplLogSearchHit *hit = l->data;
1848
1849       /* Protect against invalid data (corrupt or old log files). */
1850       if (hit->account == NULL || hit->target == NULL)
1851         continue;
1852
1853       /* Filter based on the selected account */
1854       if (account != NULL && !account_equal (account, hit->account))
1855         continue;
1856
1857       /* Add the entity if it's not already there */
1858       has_element = FALSE;
1859       gtk_tree_model_foreach (model, model_has_entity, hit);
1860       if (!has_element)
1861         {
1862           TplEntityType type = tpl_entity_get_entity_type (hit->target);
1863           EmpathyContact *contact;
1864           const gchar *name;
1865           gchar *sort_key;
1866           gboolean room = type == TPL_ENTITY_ROOM;
1867
1868           contact = empathy_contact_from_tpl_contact (hit->account,
1869               hit->target);
1870
1871           name = empathy_contact_get_alias (contact);
1872           sort_key = g_utf8_collate_key (name, -1);
1873
1874           gtk_list_store_append (store, &iter);
1875           gtk_list_store_set (store, &iter,
1876               COL_WHO_TYPE, COL_TYPE_NORMAL,
1877               COL_WHO_ICON, room ? EMPATHY_IMAGE_GROUP_MESSAGE
1878                                  : EMPATHY_IMAGE_AVATAR_DEFAULT,
1879               COL_WHO_NAME, name,
1880               COL_WHO_NAME_SORT_KEY, sort_key,
1881               COL_WHO_ID, tpl_entity_get_identifier (hit->target),
1882               COL_WHO_ACCOUNT, hit->account,
1883               COL_WHO_TARGET, hit->target,
1884               -1);
1885
1886           g_free (sort_key);
1887           g_object_unref (contact);
1888         }
1889     }
1890
1891   if (gtk_tree_model_get_iter_first (model, &iter))
1892     {
1893       gtk_list_store_prepend (store, &iter);
1894       gtk_list_store_set (store, &iter,
1895           COL_WHO_TYPE, COL_TYPE_SEPARATOR,
1896           COL_WHO_NAME, "separator",
1897           -1);
1898
1899       gtk_list_store_prepend (store, &iter);
1900       gtk_list_store_set (store, &iter,
1901           COL_WHO_TYPE, COL_TYPE_ANY,
1902           COL_WHO_NAME, _("Anyone"),
1903           -1);
1904     }
1905
1906   /* Select 'Anyone' */
1907   if (gtk_tree_model_get_iter_first (model, &iter))
1908     gtk_tree_selection_select_iter (selection, &iter);
1909 }
1910
1911 static void
1912 log_manager_searched_new_cb (GObject *manager,
1913     GAsyncResult *result,
1914     gpointer user_data)
1915 {
1916   GList *hits;
1917   GtkTreeView *view;
1918   GtkTreeSelection *selection;
1919   GError *error = NULL;
1920
1921   if (log_window == NULL)
1922     return;
1923
1924   if (!tpl_log_manager_search_finish (TPL_LOG_MANAGER (manager),
1925       result, &hits, &error))
1926     {
1927       DEBUG ("%s. Aborting", error->message);
1928       g_error_free (error);
1929       return;
1930     }
1931
1932   tp_clear_pointer (&log_window->priv->hits, tpl_log_manager_search_free);
1933   log_window->priv->hits = hits;
1934
1935   view = GTK_TREE_VIEW (log_window->priv->treeview_when);
1936   selection = gtk_tree_view_get_selection (view);
1937
1938   g_signal_handlers_unblock_by_func (selection,
1939       log_window_when_changed_cb,
1940       log_window);
1941
1942   populate_entities_from_search_hits ();
1943 }
1944
1945 static void
1946 log_window_find_populate (EmpathyLogWindow *self,
1947     const gchar *search_criteria)
1948 {
1949   GtkTreeView *view;
1950   GtkTreeModel *model;
1951   GtkTreeSelection *selection;
1952   GtkListStore *store;
1953
1954   gtk_tree_store_clear (self->priv->store_events);
1955
1956   view = GTK_TREE_VIEW (self->priv->treeview_who);
1957   model = gtk_tree_view_get_model (view);
1958   store = GTK_LIST_STORE (model);
1959
1960   gtk_list_store_clear (store);
1961
1962   view = GTK_TREE_VIEW (self->priv->treeview_when);
1963   model = gtk_tree_view_get_model (view);
1964   store = GTK_LIST_STORE (model);
1965   selection = gtk_tree_view_get_selection (view);
1966
1967   gtk_list_store_clear (store);
1968
1969   if (EMP_STR_EMPTY (search_criteria))
1970     {
1971       tp_clear_pointer (&self->priv->hits, tpl_log_manager_search_free);
1972       webkit_web_view_set_highlight_text_matches (
1973           WEBKIT_WEB_VIEW (self->priv->webview), FALSE);
1974       log_window_who_populate (self);
1975       return;
1976     }
1977
1978   g_signal_handlers_block_by_func (selection,
1979       log_window_when_changed_cb,
1980       self);
1981
1982   /* highlight the search text */
1983   webkit_web_view_mark_text_matches (WEBKIT_WEB_VIEW (self->priv->webview),
1984       search_criteria, FALSE, 0);
1985
1986   tpl_log_manager_search_async (self->priv->log_manager,
1987       search_criteria, TPL_EVENT_MASK_ANY,
1988       log_manager_searched_new_cb, NULL);
1989 }
1990
1991 static gboolean
1992 start_find_search (EmpathyLogWindow *self)
1993 {
1994   const gchar *str;
1995
1996   str = gtk_entry_get_text (GTK_ENTRY (self->priv->search_entry));
1997
1998   /* Don't find the same crap again */
1999   if (self->priv->last_find && !tp_strdiff (self->priv->last_find, str))
2000     return FALSE;
2001
2002   g_free (self->priv->last_find);
2003   self->priv->last_find = g_strdup (str);
2004
2005   log_window_find_populate (self, str);
2006
2007   return FALSE;
2008 }
2009
2010 static void
2011 log_window_search_entry_changed_cb (GtkWidget *entry,
2012     EmpathyLogWindow *self)
2013 {
2014   const gchar *str;
2015
2016   str = gtk_entry_get_text (GTK_ENTRY (self->priv->search_entry));
2017
2018   if (!tp_str_empty (str))
2019     {
2020       gtk_entry_set_icon_from_icon_name (GTK_ENTRY (self->priv->search_entry),
2021           GTK_ENTRY_ICON_SECONDARY, "edit-clear-symbolic");
2022       gtk_entry_set_icon_sensitive (GTK_ENTRY (self->priv->search_entry),
2023           GTK_ENTRY_ICON_SECONDARY, TRUE);
2024     }
2025   else
2026     {
2027       gtk_entry_set_icon_from_icon_name (GTK_ENTRY (self->priv->search_entry),
2028           GTK_ENTRY_ICON_SECONDARY, "edit-find-symbolic");
2029       gtk_entry_set_icon_sensitive (GTK_ENTRY (self->priv->search_entry),
2030           GTK_ENTRY_ICON_SECONDARY, FALSE);
2031     }
2032
2033   if (self->priv->source != 0)
2034     g_source_remove (self->priv->source);
2035   self->priv->source = g_timeout_add (500, (GSourceFunc) start_find_search,
2036       self);
2037 }
2038
2039 static void
2040 log_window_search_entry_activate_cb (GtkWidget *entry,
2041     EmpathyLogWindow *self)
2042 {
2043   start_find_search (self);
2044 }
2045
2046 static void
2047 log_window_search_entry_icon_pressed_cb (GtkEntry *entry,
2048     GtkEntryIconPosition icon_pos,
2049     GdkEvent *event,
2050     gpointer user_data)
2051 {
2052   if (icon_pos != GTK_ENTRY_ICON_SECONDARY)
2053     return;
2054
2055   gtk_entry_buffer_set_text (gtk_entry_get_buffer (entry),
2056     "", -1);
2057 }
2058
2059 static void
2060 log_window_update_buttons_sensitivity (EmpathyLogWindow *self)
2061 {
2062   GtkTreeView *view;
2063   GtkTreeModel *model;
2064   GtkTreeSelection *selection;
2065   EmpathyCapabilities capabilities;
2066   TpAccount *account;
2067   TplEntity *target;
2068   GtkTreeIter iter;
2069   GList *paths;
2070   GtkTreePath *path;
2071   gboolean profile, chat, call, video;
2072
2073   profile = chat = call = video = FALSE;
2074
2075   tp_clear_object (&self->priv->button_video_binding);
2076   tp_clear_object (&self->priv->selected_contact);
2077
2078   view = GTK_TREE_VIEW (self->priv->treeview_who);
2079   model = gtk_tree_view_get_model (view);
2080   selection = gtk_tree_view_get_selection (view);
2081
2082   profile = chat = call = video = FALSE;
2083
2084   if (!gtk_tree_model_get_iter_first (model, &iter))
2085     goto events;
2086
2087   if (gtk_tree_selection_count_selected_rows (selection) != 1)
2088     goto events;
2089
2090   if (gtk_tree_selection_iter_is_selected (selection, &iter))
2091     goto events;
2092
2093   paths = gtk_tree_selection_get_selected_rows (selection, &model);
2094   g_return_if_fail (paths != NULL);
2095
2096   path = paths->data;
2097   gtk_tree_model_get_iter (model, &iter, path);
2098   gtk_tree_model_get (model, &iter,
2099       COL_WHO_ACCOUNT, &account,
2100       COL_WHO_TARGET, &target,
2101       -1);
2102
2103   g_list_free_full (paths, (GDestroyNotify) gtk_tree_path_free);
2104
2105   self->priv->selected_contact = empathy_contact_from_tpl_contact (account,
2106       target);
2107
2108   g_object_unref (account);
2109   g_object_unref (target);
2110
2111   capabilities = empathy_contact_get_capabilities (self->priv->selected_contact);
2112
2113   profile = chat = TRUE;
2114   call = capabilities & EMPATHY_CAPABILITIES_AUDIO;
2115   video = capabilities & EMPATHY_CAPABILITIES_VIDEO;
2116
2117   goto out;
2118
2119  events:
2120   /* If the Who pane doesn't contain a contact (e.g. it has many
2121    * selected, or has 'Anyone', let's try to get the contact from
2122    * the selected event. */
2123
2124   if (self->priv->events_contact != NULL)
2125     self->priv->selected_contact = g_object_ref (self->priv->events_contact);
2126   else
2127     goto out;
2128
2129   capabilities = empathy_contact_get_capabilities (self->priv->selected_contact);
2130
2131   profile = chat = TRUE;
2132   call = capabilities & EMPATHY_CAPABILITIES_AUDIO;
2133   video = capabilities & EMPATHY_CAPABILITIES_VIDEO;
2134
2135   if (video)
2136     self->priv->button_video_binding = g_object_bind_property (
2137         self->priv->camera_monitor, "available",
2138         self->priv->button_video, "sensitive",
2139         G_BINDING_SYNC_CREATE);
2140
2141  out:
2142   gtk_widget_set_sensitive (self->priv->button_profile, profile);
2143   gtk_widget_set_sensitive (self->priv->button_chat, chat);
2144   gtk_widget_set_sensitive (self->priv->button_call, call);
2145
2146   /* Don't override the binding */
2147   if (!video)
2148     gtk_widget_set_sensitive (self->priv->button_video, video);
2149 }
2150
2151 static void
2152 log_window_update_what_iter_sensitivity (GtkTreeModel *model,
2153     GtkTreeIter *iter,
2154     gboolean sensitive)
2155 {
2156   GtkTreeStore *store = GTK_TREE_STORE (model);
2157   GtkTreeIter child;
2158   gboolean next;
2159
2160   gtk_tree_store_set (store, iter,
2161       COL_WHAT_SENSITIVE, sensitive,
2162       -1);
2163
2164   for (next = gtk_tree_model_iter_children (model, &child, iter);
2165        next;
2166        next = gtk_tree_model_iter_next (model, &child))
2167     {
2168       gtk_tree_store_set (store, &child,
2169           COL_WHAT_SENSITIVE, sensitive,
2170           -1);
2171     }
2172 }
2173
2174 static void
2175 log_window_update_what_sensitivity (EmpathyLogWindow *self)
2176 {
2177   GtkTreeView *view;
2178   GtkTreeModel *model;
2179   GtkTreeIter iter;
2180   GList *accounts, *targets, *acc, *targ;
2181   gboolean next;
2182
2183   if (!log_window_get_selected (self, &accounts, &targets, NULL, NULL,
2184       NULL, NULL))
2185     return;
2186
2187   view = GTK_TREE_VIEW (self->priv->treeview_what);
2188   model = gtk_tree_view_get_model (view);
2189
2190   /* For each event type... */
2191   for (next = gtk_tree_model_get_iter_first (model, &iter);
2192        next;
2193        next = gtk_tree_model_iter_next (model, &iter))
2194     {
2195       TplEventTypeMask type;
2196
2197       gtk_tree_model_get (model, &iter,
2198           COL_WHAT_TYPE, &type,
2199           -1);
2200
2201       /* ...we set the type and its subtypes (if any) unsensitive... */
2202       log_window_update_what_iter_sensitivity (model, &iter, FALSE);
2203
2204       for (acc = accounts, targ = targets;
2205            acc != NULL && targ != NULL;
2206            acc = acc->next, targ = targ->next)
2207         {
2208           TpAccount *account = acc->data;
2209           TplEntity *target = targ->data;
2210
2211           if (tpl_log_manager_exists (self->priv->log_manager,
2212                   account, target, type))
2213             {
2214               /* And then we set it (and its subtypes, again, if any)
2215                * as sensitive if there are logs of that type. */
2216               log_window_update_what_iter_sensitivity (model, &iter, TRUE);
2217               break;
2218             }
2219         }
2220     }
2221
2222   g_list_free_full (accounts, g_object_unref);
2223   g_list_free_full (targets, g_object_unref);
2224 }
2225
2226 static void
2227 log_window_who_changed_cb (GtkTreeSelection *selection,
2228     EmpathyLogWindow *self)
2229 {
2230   GtkTreeView *view;
2231   GtkTreeModel *model;
2232   GtkTreeIter iter;
2233
2234   DEBUG ("log_window_who_changed_cb");
2235
2236   view = gtk_tree_selection_get_tree_view (selection);
2237   model = gtk_tree_view_get_model (view);
2238
2239   if (gtk_tree_model_get_iter_first (model, &iter))
2240     {
2241       /* If 'Anyone' is selected, everything else should be deselected */
2242       if (gtk_tree_selection_iter_is_selected (selection, &iter))
2243         {
2244           g_signal_handlers_block_by_func (selection,
2245               log_window_who_changed_cb,
2246               self);
2247
2248           gtk_tree_selection_unselect_all (selection);
2249           gtk_tree_selection_select_iter (selection, &iter);
2250
2251           g_signal_handlers_unblock_by_func (selection,
2252               log_window_who_changed_cb,
2253               self);
2254         }
2255     }
2256
2257   log_window_update_what_sensitivity (self);
2258   log_window_update_buttons_sensitivity (self);
2259
2260   /* The contact changed, so the dates need to be updated */
2261   log_window_chats_get_messages (self, TRUE);
2262 }
2263
2264 static void
2265 log_manager_got_entities_cb (GObject *manager,
2266     GAsyncResult *result,
2267     gpointer user_data)
2268 {
2269   Ctx                   *ctx = user_data;
2270   GList                 *entities;
2271   GList                 *l;
2272   GtkTreeView           *view;
2273   GtkTreeModel          *model;
2274   GtkTreeSelection      *selection;
2275   GtkListStore          *store;
2276   GtkTreeIter            iter;
2277   GError                *error = NULL;
2278   gboolean               select_account = FALSE;
2279
2280   if (log_window == NULL)
2281     goto out;
2282
2283   if (log_window->priv->count != ctx->count)
2284     goto out;
2285
2286   if (!tpl_log_manager_get_entities_finish (TPL_LOG_MANAGER (manager),
2287       result, &entities, &error))
2288     {
2289       DEBUG ("%s. Aborting", error->message);
2290       g_error_free (error);
2291       goto out;
2292     }
2293
2294   view = GTK_TREE_VIEW (ctx->self->priv->treeview_who);
2295   model = gtk_tree_view_get_model (view);
2296   selection = gtk_tree_view_get_selection (view);
2297   store = GTK_LIST_STORE (model);
2298
2299   /* Block signals to stop the logs being retrieved prematurely  */
2300   g_signal_handlers_block_by_func (selection,
2301       log_window_who_changed_cb, ctx->self);
2302
2303   for (l = entities; l; l = l->next)
2304     {
2305       TplEntity *entity = TPL_ENTITY (l->data);
2306       TplEntityType type = tpl_entity_get_entity_type (entity);
2307       EmpathyContact *contact;
2308       const gchar *name;
2309       gchar *sort_key;
2310       gboolean room = type == TPL_ENTITY_ROOM;
2311
2312       contact = empathy_contact_from_tpl_contact (ctx->account, entity);
2313
2314       name = empathy_contact_get_alias (contact);
2315       sort_key = g_utf8_collate_key (name, -1);
2316
2317       gtk_list_store_append (store, &iter);
2318       gtk_list_store_set (store, &iter,
2319           COL_WHO_TYPE, COL_TYPE_NORMAL,
2320           COL_WHO_ICON, room ? EMPATHY_IMAGE_GROUP_MESSAGE
2321                              : EMPATHY_IMAGE_AVATAR_DEFAULT,
2322           COL_WHO_NAME, name,
2323           COL_WHO_NAME_SORT_KEY, sort_key,
2324           COL_WHO_ID, tpl_entity_get_identifier (entity),
2325           COL_WHO_ACCOUNT, ctx->account,
2326           COL_WHO_TARGET, entity,
2327           -1);
2328
2329       g_free (sort_key);
2330       g_object_unref (contact);
2331
2332       if (ctx->self->priv->selected_account != NULL &&
2333           !tp_strdiff (tp_proxy_get_object_path (ctx->account),
2334           tp_proxy_get_object_path (ctx->self->priv->selected_account)))
2335         select_account = TRUE;
2336     }
2337   g_list_free_full (entities, g_object_unref);
2338
2339   if (gtk_tree_model_get_iter_first (model, &iter))
2340     {
2341       gint type;
2342
2343       gtk_tree_model_get (model, &iter,
2344           COL_WHO_TYPE, &type,
2345           -1);
2346
2347       if (type != COL_TYPE_ANY)
2348         {
2349           gtk_list_store_prepend (store, &iter);
2350           gtk_list_store_set (store, &iter,
2351               COL_WHO_TYPE, COL_TYPE_SEPARATOR,
2352               COL_WHO_NAME, "separator",
2353               -1);
2354
2355           gtk_list_store_prepend (store, &iter);
2356           gtk_list_store_set (store, &iter,
2357               COL_WHO_TYPE, COL_TYPE_ANY,
2358               COL_WHO_NAME, _("Anyone"),
2359               -1);
2360         }
2361     }
2362
2363   /* Unblock signals */
2364   g_signal_handlers_unblock_by_func (selection,
2365       log_window_who_changed_cb,
2366       ctx->self);
2367
2368   /* We display the selected account if we populate the model with chats from
2369    * this account. */
2370   if (select_account)
2371     log_window_chats_set_selected (ctx->self);
2372
2373 out:
2374   _tpl_action_chain_continue (log_window->priv->chain);
2375   ctx_free (ctx);
2376 }
2377
2378 static void
2379 get_entities_for_account (TplActionChain *chain, gpointer user_data)
2380 {
2381   Ctx *ctx = user_data;
2382
2383   tpl_log_manager_get_entities_async (ctx->self->priv->log_manager, ctx->account,
2384       log_manager_got_entities_cb, ctx);
2385 }
2386
2387 static void
2388 select_first_entity (TplActionChain *chain, gpointer user_data)
2389 {
2390   EmpathyLogWindow *self = user_data;
2391   GtkTreeView *view;
2392   GtkTreeModel *model;
2393   GtkTreeSelection *selection;
2394   GtkTreeIter iter;
2395
2396   view = GTK_TREE_VIEW (self->priv->treeview_who);
2397   model = gtk_tree_view_get_model (view);
2398   selection = gtk_tree_view_get_selection (view);
2399
2400   if (gtk_tree_model_get_iter_first (model, &iter))
2401     gtk_tree_selection_select_iter (selection, &iter);
2402
2403   _tpl_action_chain_continue (self->priv->chain);
2404 }
2405
2406 static void
2407 log_window_who_populate (EmpathyLogWindow *self)
2408 {
2409   EmpathyAccountChooser *account_chooser;
2410   TpAccount *account;
2411   gboolean all_accounts;
2412   GtkTreeView *view;
2413   GtkTreeModel *model;
2414   GtkTreeSelection *selection;
2415   GtkListStore *store;
2416   Ctx *ctx;
2417
2418   if (self->priv->hits != NULL)
2419     {
2420       populate_entities_from_search_hits ();
2421       return;
2422     }
2423
2424   account_chooser = EMPATHY_ACCOUNT_CHOOSER (self->priv->account_chooser);
2425   account = empathy_account_chooser_dup_account (account_chooser);
2426   all_accounts = empathy_account_chooser_has_all_selected (account_chooser);
2427
2428   view = GTK_TREE_VIEW (self->priv->treeview_who);
2429   model = gtk_tree_view_get_model (view);
2430   selection = gtk_tree_view_get_selection (view);
2431   store = GTK_LIST_STORE (model);
2432
2433   /* Block signals to stop the logs being retrieved prematurely  */
2434   g_signal_handlers_block_by_func (selection,
2435       log_window_who_changed_cb,
2436       self);
2437
2438   gtk_list_store_clear (store);
2439
2440   /* Unblock signals */
2441   g_signal_handlers_unblock_by_func (selection,
2442       log_window_who_changed_cb,
2443       self);
2444
2445   _tpl_action_chain_clear (self->priv->chain);
2446   self->priv->count++;
2447
2448   if (!all_accounts && account == NULL)
2449     {
2450       return;
2451     }
2452   else if (!all_accounts)
2453     {
2454       ctx = ctx_new (self, account, NULL, NULL, 0, 0, self->priv->count);
2455       _tpl_action_chain_append (self->priv->chain, get_entities_for_account, ctx);
2456     }
2457   else
2458     {
2459       TpAccountManager *manager;
2460       GList *accounts, *l;
2461
2462       manager = empathy_account_chooser_get_account_manager (account_chooser);
2463       accounts = tp_account_manager_get_valid_accounts (manager);
2464
2465       for (l = accounts; l != NULL; l = l->next)
2466         {
2467           account = l->data;
2468
2469           ctx = ctx_new (self, account, NULL, NULL, 0, 0, self->priv->count);
2470           _tpl_action_chain_append (self->priv->chain,
2471               get_entities_for_account, ctx);
2472         }
2473
2474       g_list_free (accounts);
2475     }
2476   _tpl_action_chain_append (self->priv->chain, select_first_entity, self);
2477   _tpl_action_chain_start (self->priv->chain);
2478 }
2479
2480 static gint
2481 sort_by_name_key (GtkTreeModel *model,
2482     GtkTreeIter *a,
2483     GtkTreeIter *b,
2484     gpointer user_data)
2485 {
2486   gchar *key1, *key2;
2487   gint type1, type2;
2488   gint ret;
2489
2490   gtk_tree_model_get (model, a,
2491       COL_WHO_TYPE, &type1,
2492       COL_WHO_NAME_SORT_KEY, &key1,
2493       -1);
2494
2495   gtk_tree_model_get (model, b,
2496       COL_WHO_TYPE, &type2,
2497       COL_WHO_NAME_SORT_KEY, &key2,
2498       -1);
2499
2500   if (type1 == COL_TYPE_ANY)
2501     ret = -1;
2502   else if (type2 == COL_TYPE_ANY)
2503     ret = 1;
2504   else if (type1 == COL_TYPE_SEPARATOR)
2505     ret = -1;
2506   else if (type2 == COL_TYPE_SEPARATOR)
2507     ret = 1;
2508   else
2509     ret = g_strcmp0 (key1, key2);
2510
2511   g_free (key1);
2512   g_free (key2);
2513
2514   return ret;
2515 }
2516
2517 static gboolean
2518 who_row_is_separator (GtkTreeModel *model,
2519     GtkTreeIter *iter,
2520     gpointer data)
2521 {
2522   gint type;
2523
2524   gtk_tree_model_get (model, iter,
2525       COL_WHO_TYPE, &type,
2526       -1);
2527
2528   return (type == COL_TYPE_SEPARATOR);
2529 }
2530
2531 static void
2532 log_window_find_row (EmpathyLogWindow *self,
2533     GdkEventButton *event)
2534 {
2535   WebKitHitTestResult *hit = webkit_web_view_get_hit_test_result (
2536       WEBKIT_WEB_VIEW (self->priv->webview), event);
2537   WebKitDOMNode *inner_node;
2538
2539   tp_clear_object (&self->priv->events_contact);
2540
2541   g_object_get (hit,
2542       "inner-node", &inner_node,
2543       NULL);
2544
2545   if (inner_node != NULL)
2546     {
2547       GtkTreeModel *model = GTK_TREE_MODEL (self->priv->store_events);
2548       WebKitDOMNode *node;
2549       const char *path = NULL;
2550       GtkTreeIter iter;
2551
2552       /* walk back up the DOM tree looking for a node with empathy:path set */
2553       for (node = inner_node; node != NULL;
2554            node = webkit_dom_node_get_parent_node (node))
2555         {
2556           if (!WEBKIT_DOM_IS_ELEMENT (node))
2557             continue;
2558
2559           path = webkit_dom_element_get_attribute_ns (
2560               WEBKIT_DOM_ELEMENT (node), EMPATHY_NS, "path");
2561
2562           if (!tp_str_empty (path))
2563             break;
2564         }
2565
2566       /* look up the contact for this path */
2567       if (!tp_str_empty (path) &&
2568           gtk_tree_model_get_iter_from_string (model, &iter, path))
2569         {
2570           TpAccount *account;
2571           TplEntity *target;
2572
2573           gtk_tree_model_get (model, &iter,
2574               COL_EVENTS_ACCOUNT, &account,
2575               COL_EVENTS_TARGET, &target,
2576               -1);
2577
2578           self->priv->events_contact = empathy_contact_from_tpl_contact (
2579               account, target);
2580
2581           g_object_unref (account);
2582           g_object_unref (target);
2583         }
2584
2585       g_object_unref (inner_node);
2586     }
2587
2588   g_object_unref (hit);
2589
2590   log_window_update_buttons_sensitivity (self);
2591 }
2592
2593 static gboolean
2594 log_window_events_button_press_event (GtkWidget *webview,
2595     GdkEventButton *event,
2596     EmpathyLogWindow *self)
2597 {
2598   switch (event->button)
2599     {
2600       case 1:
2601         log_window_find_row (self, event);
2602         break;
2603
2604       case 3:
2605         empathy_webkit_context_menu_for_event (
2606             WEBKIT_WEB_VIEW (webview), event, 0);
2607         return TRUE;
2608
2609       default:
2610         break;
2611     }
2612
2613   return FALSE;
2614 }
2615
2616 static void
2617 log_window_events_setup (EmpathyLogWindow *self)
2618 {
2619   GtkTreeSortable   *sortable;
2620   GtkTreeStore      *store;
2621
2622   /* new store */
2623   self->priv->store_events = store = gtk_tree_store_new (COL_EVENTS_COUNT,
2624       G_TYPE_INT,           /* type */
2625       G_TYPE_INT64,         /* timestamp */
2626       G_TYPE_STRING,        /* stringified date */
2627       G_TYPE_STRING,        /* icon */
2628       G_TYPE_STRING,        /* name */
2629       TP_TYPE_ACCOUNT,      /* account */
2630       TPL_TYPE_ENTITY,      /* target */
2631       TPL_TYPE_EVENT);      /* event */
2632
2633   sortable = GTK_TREE_SORTABLE (store);
2634
2635   gtk_tree_sortable_set_sort_column_id (sortable,
2636       COL_EVENTS_TS,
2637       GTK_SORT_ASCENDING);
2638 }
2639
2640 static void
2641 log_window_who_setup (EmpathyLogWindow *self)
2642 {
2643   GtkTreeView       *view;
2644   GtkTreeModel      *model;
2645   GtkTreeSelection  *selection;
2646   GtkTreeSortable   *sortable;
2647   GtkTreeViewColumn *column;
2648   GtkListStore      *store;
2649   GtkCellRenderer   *cell;
2650
2651   view = GTK_TREE_VIEW (self->priv->treeview_who);
2652   selection = gtk_tree_view_get_selection (view);
2653
2654   /* new store */
2655   store = gtk_list_store_new (COL_WHO_COUNT,
2656       G_TYPE_INT,           /* type */
2657       G_TYPE_STRING,        /* icon */
2658       G_TYPE_STRING,        /* name */
2659       G_TYPE_STRING,        /* name sort key */
2660       G_TYPE_STRING,        /* id */
2661       TP_TYPE_ACCOUNT,      /* account */
2662       TPL_TYPE_ENTITY);     /* target */
2663
2664   model = GTK_TREE_MODEL (store);
2665   sortable = GTK_TREE_SORTABLE (store);
2666
2667   gtk_tree_view_set_model (view, model);
2668
2669   /* new column */
2670   column = gtk_tree_view_column_new ();
2671   gtk_tree_view_column_set_title (column, _("Who"));
2672
2673   cell = gtk_cell_renderer_pixbuf_new ();
2674   gtk_tree_view_column_pack_start (column, cell, FALSE);
2675   gtk_tree_view_column_add_attribute (column, cell,
2676       "icon-name",
2677       COL_WHO_ICON);
2678
2679   cell = gtk_cell_renderer_text_new ();
2680   g_object_set (cell, "ellipsize", PANGO_ELLIPSIZE_END, NULL);
2681   gtk_tree_view_column_pack_start (column, cell, TRUE);
2682   gtk_tree_view_column_add_attribute (column, cell,
2683       "text",
2684       COL_WHO_NAME);
2685
2686   gtk_tree_view_append_column (view, column);
2687
2688   /* set up treeview properties */
2689   gtk_tree_selection_set_mode (selection, GTK_SELECTION_MULTIPLE);
2690   gtk_tree_view_set_row_separator_func (view, who_row_is_separator,
2691       NULL, NULL);
2692
2693   gtk_tree_sortable_set_sort_column_id (sortable,
2694       COL_WHO_NAME_SORT_KEY,
2695       GTK_SORT_ASCENDING);
2696   gtk_tree_sortable_set_sort_func (sortable,
2697       COL_WHO_NAME_SORT_KEY, sort_by_name_key,
2698       NULL, NULL);
2699
2700   gtk_tree_view_set_search_column (view, COL_WHO_NAME);
2701   gtk_tree_view_set_tooltip_column (view, COL_WHO_ID);
2702
2703   /* set up signals */
2704   g_signal_connect (selection, "changed",
2705       G_CALLBACK (log_window_who_changed_cb), self);
2706
2707   g_object_unref (store);
2708 }
2709
2710 static void
2711 log_window_chats_accounts_changed_cb (GtkWidget *combobox,
2712     EmpathyLogWindow *self)
2713 {
2714   /* Clear all current messages shown in the textview */
2715   gtk_tree_store_clear (self->priv->store_events);
2716
2717   log_window_who_populate (self);
2718 }
2719
2720 static void
2721 log_window_chats_set_selected (EmpathyLogWindow *self)
2722 {
2723   GtkTreeView          *view;
2724   GtkTreeModel         *model;
2725   GtkTreeSelection     *selection;
2726   GtkTreeIter           iter;
2727   GtkTreePath          *path;
2728   gboolean              next;
2729
2730   view = GTK_TREE_VIEW (self->priv->treeview_who);
2731   model = gtk_tree_view_get_model (view);
2732   selection = gtk_tree_view_get_selection (view);
2733
2734   for (next = gtk_tree_model_get_iter_first (model, &iter);
2735        next;
2736        next = gtk_tree_model_iter_next (model, &iter))
2737     {
2738       TpAccount   *this_account;
2739       TplEntity   *this_target;
2740       const gchar *this_chat_id;
2741       gboolean     this_is_chatroom;
2742       gint         this_type;
2743
2744       gtk_tree_model_get (model, &iter,
2745           COL_WHO_TYPE, &this_type,
2746           COL_WHO_ACCOUNT, &this_account,
2747           COL_WHO_TARGET, &this_target,
2748           -1);
2749
2750       if (this_type != COL_TYPE_NORMAL)
2751         continue;
2752
2753       this_chat_id = tpl_entity_get_identifier (this_target);
2754       this_is_chatroom = tpl_entity_get_entity_type (this_target)
2755           == TPL_ENTITY_ROOM;
2756
2757       if (this_account == self->priv->selected_account &&
2758           !tp_strdiff (this_chat_id, self->priv->selected_chat_id) &&
2759           this_is_chatroom == self->priv->selected_is_chatroom)
2760         {
2761           gtk_tree_selection_select_iter (selection, &iter);
2762           path = gtk_tree_model_get_path (model, &iter);
2763           gtk_tree_view_scroll_to_cell (view, path, NULL, TRUE, 0.5, 0.0);
2764           gtk_tree_path_free (path);
2765           g_object_unref (this_account);
2766           g_object_unref (this_target);
2767           break;
2768         }
2769
2770       g_object_unref (this_account);
2771       g_object_unref (this_target);
2772     }
2773
2774   tp_clear_object (&self->priv->selected_account);
2775   tp_clear_pointer (&self->priv->selected_chat_id, g_free);
2776 }
2777
2778 static gint
2779 sort_by_date (GtkTreeModel *model,
2780     GtkTreeIter *a,
2781     GtkTreeIter *b,
2782     gpointer user_data)
2783 {
2784   GDate *date1, *date2;
2785
2786   gtk_tree_model_get (model, a,
2787       COL_WHEN_DATE, &date1,
2788       -1);
2789
2790   gtk_tree_model_get (model, b,
2791       COL_WHEN_DATE, &date2,
2792       -1);
2793
2794   return g_date_compare (date1, date2);
2795 }
2796
2797 static gboolean
2798 when_row_is_separator (GtkTreeModel *model,
2799     GtkTreeIter *iter,
2800     gpointer data)
2801 {
2802   gchar *when;
2803   gboolean ret;
2804
2805   gtk_tree_model_get (model, iter,
2806       COL_WHEN_TEXT, &when,
2807       -1);
2808
2809   ret = !tp_strdiff (when, "separator");
2810   g_free (when);
2811   return ret;
2812 }
2813
2814 static void
2815 log_window_when_changed_cb (GtkTreeSelection *selection,
2816     EmpathyLogWindow *self)
2817 {
2818   GtkTreeView *view;
2819   GtkTreeModel *model;
2820   GtkTreeIter iter;
2821
2822   DEBUG ("log_window_when_changed_cb");
2823
2824   view = gtk_tree_selection_get_tree_view (selection);
2825   model = gtk_tree_view_get_model (view);
2826
2827   /* If 'Anytime' is selected, everything else should be deselected */
2828   if (gtk_tree_model_get_iter_first (model, &iter))
2829     {
2830       if (gtk_tree_selection_iter_is_selected (selection, &iter))
2831         {
2832           g_signal_handlers_block_by_func (selection,
2833               log_window_when_changed_cb,
2834               self);
2835
2836           gtk_tree_selection_unselect_all (selection);
2837           gtk_tree_selection_select_iter (selection, &iter);
2838
2839           g_signal_handlers_unblock_by_func (selection,
2840               log_window_when_changed_cb,
2841               self);
2842         }
2843     }
2844
2845   log_window_chats_get_messages (self, FALSE);
2846 }
2847
2848 static void
2849 log_window_when_setup (EmpathyLogWindow *self)
2850 {
2851   GtkTreeView       *view;
2852   GtkTreeModel      *model;
2853   GtkTreeSelection  *selection;
2854   GtkTreeSortable   *sortable;
2855   GtkTreeViewColumn *column;
2856   GtkListStore      *store;
2857   GtkCellRenderer   *cell;
2858
2859   view = GTK_TREE_VIEW (self->priv->treeview_when);
2860   selection = gtk_tree_view_get_selection (view);
2861
2862   /* new store */
2863   store = gtk_list_store_new (COL_WHEN_COUNT,
2864       G_TYPE_DATE,        /* date */
2865       G_TYPE_STRING,      /* stringified date */
2866       G_TYPE_STRING);     /* icon */
2867
2868   model = GTK_TREE_MODEL (store);
2869   sortable = GTK_TREE_SORTABLE (store);
2870
2871   gtk_tree_view_set_model (view, model);
2872
2873   /* new column */
2874   column = gtk_tree_view_column_new ();
2875   gtk_tree_view_column_set_title (column, _("When"));
2876
2877   cell = gtk_cell_renderer_pixbuf_new ();
2878   gtk_tree_view_column_pack_start (column, cell, FALSE);
2879   gtk_tree_view_column_add_attribute (column, cell,
2880       "icon-name", COL_WHEN_ICON);
2881
2882   cell = gtk_cell_renderer_text_new ();
2883   g_object_set (cell, "ellipsize", PANGO_ELLIPSIZE_END, NULL);
2884   gtk_tree_view_column_pack_start (column, cell, TRUE);
2885   gtk_tree_view_column_add_attribute (column, cell,
2886       "text",
2887       COL_WHEN_TEXT);
2888
2889   gtk_tree_view_append_column (view, column);
2890
2891   /* set up treeview properties */
2892   gtk_tree_selection_set_mode (selection, GTK_SELECTION_MULTIPLE);
2893   gtk_tree_view_set_row_separator_func (view, when_row_is_separator,
2894       NULL, NULL);
2895   gtk_tree_sortable_set_sort_column_id (sortable,
2896       COL_WHEN_DATE,
2897       GTK_SORT_DESCENDING);
2898   gtk_tree_sortable_set_sort_func (sortable,
2899       COL_WHEN_DATE, sort_by_date,
2900       NULL, NULL);
2901
2902   gtk_tree_view_set_search_column (view, COL_WHEN_TEXT);
2903
2904   /* set up signals */
2905   g_signal_connect (selection, "changed",
2906       G_CALLBACK (log_window_when_changed_cb),
2907       self);
2908
2909   g_object_unref (store);
2910 }
2911
2912 static gboolean
2913 what_row_is_separator (GtkTreeModel *model,
2914     GtkTreeIter *iter,
2915     gpointer data)
2916 {
2917   gint type;
2918
2919   gtk_tree_model_get (model, iter,
2920       COL_WHAT_TYPE, &type,
2921       -1);
2922
2923   return (type == WHAT_TYPE_SEPARATOR);
2924 }
2925
2926 static void
2927 log_window_what_changed_cb (GtkTreeSelection *selection,
2928     EmpathyLogWindow *self)
2929 {
2930   GtkTreeView *view;
2931   GtkTreeModel *model;
2932   GtkTreeIter iter;
2933
2934   DEBUG ("log_window_what_changed_cb");
2935
2936   view = gtk_tree_selection_get_tree_view (selection);
2937   model = gtk_tree_view_get_model (view);
2938
2939   /* If 'Anything' is selected, everything else should be deselected */
2940   if (gtk_tree_model_get_iter_first (model, &iter))
2941     {
2942       if (gtk_tree_selection_iter_is_selected (selection, &iter))
2943         {
2944           g_signal_handlers_block_by_func (selection,
2945               log_window_what_changed_cb,
2946               self);
2947
2948           gtk_tree_selection_unselect_all (selection);
2949           gtk_tree_selection_select_iter (selection, &iter);
2950
2951           g_signal_handlers_unblock_by_func (selection,
2952               log_window_what_changed_cb,
2953               self);
2954         }
2955     }
2956
2957   /* The dates need to be updated if we're not searching */
2958   log_window_chats_get_messages (self, self->priv->hits == NULL);
2959 }
2960
2961 static gboolean
2962 log_window_what_collapse_row_cb (GtkTreeView *tree_view,
2963     GtkTreeIter *iter,
2964     GtkTreePath *path,
2965     gpointer user_data)
2966 {
2967   /* Reject collapsing */
2968   return TRUE;
2969 }
2970
2971 struct event
2972 {
2973   gint type;
2974   EventSubtype subtype;
2975   const gchar *icon;
2976   const gchar *text;
2977 };
2978
2979 static void
2980 log_window_what_setup (EmpathyLogWindow *self)
2981 {
2982   GtkTreeView       *view;
2983   GtkTreeModel      *model;
2984   GtkTreeSelection  *selection;
2985   GtkTreeViewColumn *column;
2986   GtkTreeIter        iter;
2987   GtkTreeStore      *store;
2988   GtkCellRenderer   *cell;
2989   guint i;
2990   struct event events [] = {
2991     { TPL_EVENT_MASK_ANY, 0, NULL, _("Anything") },
2992     { WHAT_TYPE_SEPARATOR, 0, NULL, "separator" },
2993     { TPL_EVENT_MASK_TEXT, 0, "format-justify-fill", _("Text chats") },
2994 #ifdef HAVE_CALL_LOGS
2995     { TPL_EVENT_MASK_CALL, EVENT_CALL_ALL, EMPATHY_IMAGE_CALL, _("Calls") },
2996 #endif
2997   };
2998 #ifdef HAVE_CALL_LOGS
2999   struct event call_events [] = {
3000     { TPL_EVENT_MASK_CALL, EVENT_CALL_INCOMING, EMPATHY_IMAGE_CALL_INCOMING, _("Incoming calls") },
3001     { TPL_EVENT_MASK_CALL, EVENT_CALL_OUTGOING, EMPATHY_IMAGE_CALL_OUTGOING, _("Outgoing calls") },
3002     { TPL_EVENT_MASK_CALL, EVENT_CALL_MISSED, EMPATHY_IMAGE_CALL_MISSED, _("Missed calls") }
3003   };
3004   GtkTreeIter parent;
3005 #endif
3006
3007   view = GTK_TREE_VIEW (self->priv->treeview_what);
3008   selection = gtk_tree_view_get_selection (view);
3009
3010   /* new store */
3011   store = gtk_tree_store_new (COL_WHAT_COUNT,
3012       G_TYPE_INT,         /* history type */
3013       G_TYPE_INT,         /* history subtype */
3014       G_TYPE_BOOLEAN,     /* sensitive */
3015       G_TYPE_STRING,      /* stringified history type */
3016       G_TYPE_STRING);     /* icon */
3017
3018   model = GTK_TREE_MODEL (store);
3019
3020   gtk_tree_view_set_model (view, model);
3021
3022   /* new column */
3023   column = gtk_tree_view_column_new ();
3024   gtk_tree_view_column_set_title (column, _("What"));
3025
3026   cell = gtk_cell_renderer_pixbuf_new ();
3027   gtk_tree_view_column_pack_start (column, cell, FALSE);
3028   gtk_tree_view_column_add_attribute (column, cell,
3029       "icon-name", COL_WHAT_ICON);
3030
3031   cell = gtk_cell_renderer_text_new ();
3032   g_object_set (cell, "ellipsize", PANGO_ELLIPSIZE_END, NULL);
3033   gtk_tree_view_column_pack_start (column, cell, TRUE);
3034   gtk_tree_view_column_add_attribute (column, cell,
3035       "text", COL_WHAT_TEXT);
3036   gtk_tree_view_column_add_attribute (column, cell,
3037       "sensitive", COL_WHAT_SENSITIVE);
3038
3039   gtk_tree_view_append_column (view, column);
3040   gtk_tree_view_set_search_column (view, COL_WHAT_TEXT);
3041
3042   /* set up treeview properties */
3043   gtk_tree_selection_set_mode (selection, GTK_SELECTION_MULTIPLE);
3044   gtk_tree_view_set_show_expanders (view, FALSE);
3045   gtk_tree_view_set_level_indentation (view, 12);
3046   gtk_tree_view_expand_all (view);
3047   gtk_tree_view_set_row_separator_func (view, what_row_is_separator,
3048       NULL, NULL);
3049
3050   /* populate */
3051   for (i = 0; i < G_N_ELEMENTS (events); i++)
3052     {
3053       gtk_tree_store_append (store, &iter, NULL);
3054       gtk_tree_store_set (store, &iter,
3055           COL_WHAT_TYPE, events[i].type,
3056           COL_WHAT_SUBTYPE, events[i].subtype,
3057           COL_WHAT_SENSITIVE, TRUE,
3058           COL_WHAT_TEXT, events[i].text,
3059           COL_WHAT_ICON, events[i].icon,
3060           -1);
3061     }
3062
3063 #ifdef HAVE_CALL_LOGS
3064   gtk_tree_model_iter_nth_child (model, &parent, NULL, 3);
3065   for (i = 0; i < G_N_ELEMENTS (call_events); i++)
3066     {
3067       gtk_tree_store_append (store, &iter, &parent);
3068       gtk_tree_store_set (store, &iter,
3069           COL_WHAT_TYPE, call_events[i].type,
3070           COL_WHAT_SUBTYPE, call_events[i].subtype,
3071           COL_WHAT_SENSITIVE, TRUE,
3072           COL_WHAT_TEXT, call_events[i].text,
3073           COL_WHAT_ICON, call_events[i].icon,
3074           -1);
3075     }
3076 #endif
3077
3078   gtk_tree_view_expand_all (view);
3079
3080   /* select 'Anything' */
3081   if (gtk_tree_model_get_iter_first (model, &iter))
3082     gtk_tree_selection_select_iter (selection, &iter);
3083
3084   /* set up signals */
3085   g_signal_connect (view, "test-collapse-row",
3086       G_CALLBACK (log_window_what_collapse_row_cb),
3087       NULL);
3088   g_signal_connect (selection, "changed",
3089       G_CALLBACK (log_window_what_changed_cb),
3090       self);
3091
3092   g_object_unref (store);
3093 }
3094
3095 static void
3096 log_window_maybe_expand_events (void)
3097 {
3098   GtkTreeModel      *model = GTK_TREE_MODEL (log_window->priv->store_events);
3099
3100   /* If there's only one result, expand it */
3101   if (gtk_tree_model_iter_n_children (model, NULL) == 1)
3102     webkit_web_view_execute_script (
3103         WEBKIT_WEB_VIEW (log_window->priv->webview),
3104         "javascript:expandAll()");
3105 }
3106
3107 static gboolean
3108 show_spinner (gpointer data)
3109 {
3110   gboolean active;
3111
3112   if (log_window == NULL)
3113     return FALSE;
3114
3115   g_object_get (log_window->priv->spinner, "active", &active, NULL);
3116
3117   if (active)
3118     gtk_notebook_set_current_page (GTK_NOTEBOOK (log_window->priv->notebook),
3119         PAGE_SPINNER);
3120
3121   return FALSE;
3122 }
3123
3124 static void
3125 show_events (TplActionChain *chain,
3126     gpointer user_data)
3127 {
3128   log_window_maybe_expand_events ();
3129   gtk_spinner_stop (GTK_SPINNER (log_window->priv->spinner));
3130   gtk_notebook_set_current_page (GTK_NOTEBOOK (log_window->priv->notebook),
3131       PAGE_EVENTS);
3132
3133   _tpl_action_chain_continue (chain);
3134 }
3135
3136 static void
3137 start_spinner (void)
3138 {
3139   gtk_spinner_start (GTK_SPINNER (log_window->priv->spinner));
3140   gtk_notebook_set_current_page (GTK_NOTEBOOK (log_window->priv->notebook),
3141       PAGE_EMPTY);
3142
3143   g_timeout_add (1000, show_spinner, NULL);
3144   _tpl_action_chain_append (log_window->priv->chain, show_events, NULL);
3145 }
3146
3147 static void
3148 log_window_got_messages_for_date_cb (GObject *manager,
3149     GAsyncResult *result,
3150     gpointer user_data)
3151 {
3152   Ctx *ctx = user_data;
3153   GtkTreeModel *model;
3154   GtkTreeIter iter;
3155   GList *events;
3156   GList *l;
3157   GError *error = NULL;
3158   gint n;
3159
3160   if (log_window == NULL)
3161     {
3162       ctx_free (ctx);
3163       return;
3164     }
3165
3166   if (log_window->priv->count != ctx->count)
3167     goto out;
3168
3169   if (!tpl_log_manager_get_events_for_date_finish (TPL_LOG_MANAGER (manager),
3170       result, &events, &error))
3171     {
3172       DEBUG ("Unable to retrieve messages for the selected date: %s. Aborting",
3173           error->message);
3174       g_error_free (error);
3175       goto out;
3176     }
3177
3178   for (l = events; l; l = l->next)
3179     {
3180       TplEvent *event = l->data;
3181       gboolean append = TRUE;
3182
3183 #ifdef HAVE_CALL_LOGS
3184       if (TPL_IS_CALL_EVENT (l->data)
3185           && ctx->event_mask & TPL_EVENT_MASK_CALL
3186           && ctx->event_mask != TPL_EVENT_MASK_ANY)
3187         {
3188           TplCallEvent *call = l->data;
3189
3190           append = FALSE;
3191
3192           if (ctx->subtype & EVENT_CALL_ALL)
3193             {
3194               append = TRUE;
3195             }
3196           else
3197             {
3198               TplCallEndReason reason = tpl_call_event_get_end_reason (call);
3199               TplEntity *sender = tpl_event_get_sender (event);
3200               TplEntity *receiver = tpl_event_get_receiver (event);
3201
3202               if (reason == TPL_CALL_END_REASON_NO_ANSWER)
3203                 {
3204                   if (ctx->subtype & EVENT_CALL_MISSED)
3205                     append = TRUE;
3206                 }
3207               else if (ctx->subtype & EVENT_CALL_OUTGOING
3208                   && tpl_entity_get_entity_type (sender) == TPL_ENTITY_SELF)
3209                 {
3210                   append = TRUE;
3211                 }
3212               else if (ctx->subtype & EVENT_CALL_INCOMING
3213                   && tpl_entity_get_entity_type (receiver) == TPL_ENTITY_SELF)
3214                 {
3215                   append = TRUE;
3216                 }
3217             }
3218         }
3219 #endif
3220
3221       if (append)
3222         {
3223           EmpathyMessage *msg = empathy_message_from_tpl_log_event (event);
3224           log_window_append_message (event, msg);
3225           tp_clear_object (&msg);
3226         }
3227
3228       g_object_unref (event);
3229     }
3230   g_list_free (events);
3231
3232   model = GTK_TREE_MODEL (log_window->priv->store_events);
3233   n = gtk_tree_model_iter_n_children (model, NULL) - 1;
3234
3235   if (n >= 0 && gtk_tree_model_iter_nth_child (model, &iter, NULL, n))
3236     {
3237       GtkTreePath *path;
3238       char *str, *script;
3239
3240       path = gtk_tree_model_get_path (model, &iter);
3241       str = gtk_tree_path_to_string (path);
3242
3243       script = g_strdup_printf ("javascript:scrollToRow([%s]);",
3244           g_strdelimit (str, ":", ','));
3245
3246       webkit_web_view_execute_script (
3247           WEBKIT_WEB_VIEW (log_window->priv->webview),
3248           script);
3249
3250       gtk_tree_path_free (path);
3251       g_free (str);
3252       g_free (script);
3253     }
3254
3255  out:
3256   ctx_free (ctx);
3257
3258   _tpl_action_chain_continue (log_window->priv->chain);
3259 }
3260
3261 static void
3262 get_events_for_date (TplActionChain *chain, gpointer user_data)
3263 {
3264   Ctx *ctx = user_data;
3265
3266   tpl_log_manager_get_events_for_date_async (ctx->self->priv->log_manager,
3267       ctx->account, ctx->entity, ctx->event_mask,
3268       ctx->date,
3269       log_window_got_messages_for_date_cb,
3270       ctx);
3271 }
3272
3273 static void
3274 log_window_get_messages_for_dates (EmpathyLogWindow *self,
3275     GList *dates)
3276 {
3277   GList *accounts, *targets, *acc, *targ, *l;
3278   TplEventTypeMask event_mask;
3279   EventSubtype subtype;
3280   GDate *date, *anytime, *separator;
3281
3282   if (!log_window_get_selected (self,
3283       &accounts, &targets, NULL, NULL, &event_mask, &subtype))
3284     return;
3285
3286   anytime = g_date_new_dmy (2, 1, -1);
3287   separator = g_date_new_dmy (1, 1, -1);
3288
3289   _tpl_action_chain_clear (self->priv->chain);
3290   self->priv->count++;
3291
3292   for (acc = accounts, targ = targets;
3293        acc != NULL && targ != NULL;
3294        acc = acc->next, targ = targ->next)
3295     {
3296       TpAccount *account = acc->data;
3297       TplEntity *target = targ->data;
3298
3299       for (l = dates; l != NULL; l = l->next)
3300         {
3301           date = l->data;
3302
3303           /* Get events */
3304           if (g_date_compare (date, anytime) != 0)
3305             {
3306               Ctx *ctx;
3307
3308               ctx = ctx_new (self, account, target, date, event_mask, subtype,
3309                   self->priv->count);
3310               _tpl_action_chain_append (self->priv->chain, get_events_for_date, ctx);
3311             }
3312           else
3313             {
3314               GtkTreeView *view = GTK_TREE_VIEW (self->priv->treeview_when);
3315               GtkTreeModel *model = gtk_tree_view_get_model (view);
3316               GtkTreeIter iter;
3317               gboolean next;
3318               GDate *d;
3319
3320               for (next = gtk_tree_model_get_iter_first (model, &iter);
3321                    next;
3322                    next = gtk_tree_model_iter_next (model, &iter))
3323                 {
3324                   Ctx *ctx;
3325
3326                   gtk_tree_model_get (model, &iter,
3327                       COL_WHEN_DATE, &d,
3328                       -1);
3329
3330                   if (g_date_compare (d, anytime) != 0 &&
3331                       g_date_compare (d, separator) != 0)
3332                     {
3333                       ctx = ctx_new (self, account, target, d,
3334                           event_mask, subtype, self->priv->count);
3335                       _tpl_action_chain_append (self->priv->chain, get_events_for_date, ctx);
3336                     }
3337                 }
3338             }
3339         }
3340     }
3341
3342   start_spinner ();
3343   _tpl_action_chain_start (self->priv->chain);
3344
3345   g_list_free_full (accounts, g_object_unref);
3346   g_list_free_full (targets, g_object_unref);
3347   g_date_free (separator);
3348   g_date_free (anytime);
3349 }
3350
3351 static void
3352 log_manager_got_dates_cb (GObject *manager,
3353     GAsyncResult *result,
3354     gpointer user_data)
3355 {
3356   Ctx *ctx = user_data;
3357   GtkTreeView *view;
3358   GtkTreeModel *model;
3359   GtkListStore *store;
3360   GtkTreeIter iter;
3361   GList *dates;
3362   GList *l;
3363   GError *error = NULL;
3364
3365   if (log_window == NULL)
3366     {
3367       ctx_free (ctx);
3368       return;
3369     }
3370
3371   if (log_window->priv->count != ctx->count)
3372     goto out;
3373
3374   if (!tpl_log_manager_get_dates_finish (TPL_LOG_MANAGER (manager),
3375        result, &dates, &error))
3376     {
3377       DEBUG ("Unable to retrieve messages' dates: %s. Aborting",
3378           error->message);
3379       goto out;
3380     }
3381
3382   view = GTK_TREE_VIEW (log_window->priv->treeview_when);
3383   model = gtk_tree_view_get_model (view);
3384   store = GTK_LIST_STORE (model);
3385
3386   for (l = dates; l != NULL; l = l->next)
3387     {
3388       GDate *date = l->data;
3389
3390       /* Add the date if it's not already there */
3391       has_element = FALSE;
3392       gtk_tree_model_foreach (model, model_has_date, date);
3393       if (!has_element)
3394         {
3395           gchar *text = format_date_for_display (date);
3396
3397           gtk_list_store_append (store, &iter);
3398           gtk_list_store_set (store, &iter,
3399               COL_WHEN_DATE, date,
3400               COL_WHEN_TEXT, text,
3401               COL_WHEN_ICON, CALENDAR_ICON,
3402               -1);
3403
3404           g_free (text);
3405         }
3406     }
3407
3408   if (gtk_tree_model_get_iter_first (model, &iter))
3409     {
3410       gchar *separator = NULL;
3411
3412       if (gtk_tree_model_iter_next (model, &iter))
3413         {
3414           gtk_tree_model_get (model, &iter,
3415               COL_WHEN_TEXT, &separator,
3416               -1);
3417         }
3418
3419       if (g_strcmp0 (separator, "separator") != 0)
3420         {
3421           gtk_list_store_prepend (store, &iter);
3422           gtk_list_store_set (store, &iter,
3423               COL_WHEN_DATE, g_date_new_dmy (1, 1, -1),
3424               COL_WHEN_TEXT, "separator",
3425               -1);
3426
3427           gtk_list_store_prepend (store, &iter);
3428           gtk_list_store_set (store, &iter,
3429               COL_WHEN_DATE, g_date_new_dmy (2, 1, -1),
3430               COL_WHEN_TEXT, _("Anytime"),
3431               -1);
3432         }
3433     }
3434
3435   g_list_free_full (dates, g_free);
3436  out:
3437   ctx_free (ctx);
3438   _tpl_action_chain_continue (log_window->priv->chain);
3439 }
3440
3441 static void
3442 select_date (TplActionChain *chain, gpointer user_data)
3443 {
3444   GtkTreeView *view;
3445   GtkTreeModel *model;
3446   GtkTreeSelection *selection;
3447   GtkTreeIter iter;
3448   gboolean next;
3449   gboolean selected = FALSE;
3450
3451   view = GTK_TREE_VIEW (log_window->priv->treeview_when);
3452   model = gtk_tree_view_get_model (view);
3453   selection = gtk_tree_view_get_selection (view);
3454
3455   if (log_window->priv->current_dates != NULL)
3456     {
3457       for (next = gtk_tree_model_get_iter_first (model, &iter);
3458            next;
3459            next = gtk_tree_model_iter_next (model, &iter))
3460         {
3461           GDate *date;
3462
3463           gtk_tree_model_get (model, &iter,
3464               COL_WHEN_DATE, &date,
3465               -1);
3466
3467           if (g_list_find_custom (log_window->priv->current_dates, date,
3468                   (GCompareFunc) g_date_compare) != NULL)
3469             {
3470               GtkTreePath *path;
3471
3472               gtk_tree_selection_select_iter (selection, &iter);
3473               path = gtk_tree_model_get_path (model, &iter);
3474               gtk_tree_view_scroll_to_cell (view, path, NULL, FALSE, 0, 0);
3475               selected = TRUE;
3476
3477               gtk_tree_path_free (path);
3478             }
3479
3480           g_date_free (date);
3481         }
3482     }
3483
3484   if (!selected)
3485     {
3486       /* Show messages of the most recent date */
3487       if (gtk_tree_model_iter_nth_child (model, &iter, NULL, 2))
3488         gtk_tree_selection_select_iter (selection, &iter);
3489     }
3490
3491   _tpl_action_chain_continue (log_window->priv->chain);
3492 }
3493
3494 static void
3495 get_dates_for_entity (TplActionChain *chain, gpointer user_data)
3496 {
3497   Ctx *ctx = user_data;
3498
3499   tpl_log_manager_get_dates_async (ctx->self->priv->log_manager,
3500       ctx->account, ctx->entity, ctx->event_mask,
3501       log_manager_got_dates_cb, ctx);
3502 }
3503
3504 static void
3505 log_window_chats_get_messages (EmpathyLogWindow *self,
3506     gboolean force_get_dates)
3507 {
3508   GList *accounts, *targets, *dates;
3509   TplEventTypeMask event_mask;
3510   GtkTreeView *view;
3511   GtkTreeModel *model;
3512   GtkListStore *store;
3513   GtkTreeSelection *selection;
3514
3515   if (!log_window_get_selected (self, &accounts, &targets, NULL,
3516       &dates, &event_mask, NULL))
3517     return;
3518
3519   view = GTK_TREE_VIEW (self->priv->treeview_when);
3520   selection = gtk_tree_view_get_selection (view);
3521   model = gtk_tree_view_get_model (view);
3522   store = GTK_LIST_STORE (model);
3523
3524   /* Clear all current messages shown in the textview */
3525   gtk_tree_store_clear (self->priv->store_events);
3526
3527   _tpl_action_chain_clear (self->priv->chain);
3528   self->priv->count++;
3529
3530   /* If there's a search use the returned hits */
3531   if (self->priv->hits != NULL)
3532     {
3533       if (force_get_dates)
3534         {
3535           g_signal_handlers_block_by_func (selection,
3536               log_window_when_changed_cb,
3537               self);
3538
3539           gtk_list_store_clear (store);
3540
3541           g_signal_handlers_unblock_by_func (selection,
3542               log_window_when_changed_cb,
3543               self);
3544
3545           populate_dates_from_search_hits (accounts, targets);
3546         }
3547       else
3548         {
3549           populate_events_from_search_hits (accounts, targets, dates);
3550         }
3551     }
3552   /* Either use the supplied date or get the last */
3553   else if (force_get_dates || dates == NULL)
3554     {
3555       GList *acc, *targ;
3556
3557       if (self->priv->current_dates != NULL)
3558         {
3559           g_list_free_full (self->priv->current_dates,
3560               (GDestroyNotify) g_date_free);
3561           self->priv->current_dates = NULL;
3562         }
3563
3564       if (gtk_tree_selection_count_selected_rows (selection) > 0)
3565         {
3566           GList *paths, *l;
3567           GtkTreeIter iter;
3568
3569           paths = gtk_tree_selection_get_selected_rows (selection, NULL);
3570
3571           for (l = paths; l != NULL; l = l->next)
3572             {
3573               GtkTreePath *path = l->data;
3574               GDate *date;
3575
3576               gtk_tree_model_get_iter (model, &iter, path);
3577               gtk_tree_model_get (model, &iter,
3578                   COL_WHEN_DATE, &date,
3579                   -1);
3580
3581               /* The list takes ownership of the date. */
3582               self->priv->current_dates =
3583                   g_list_prepend (self->priv->current_dates, date);
3584             }
3585
3586           g_list_free_full (paths, (GDestroyNotify) gtk_tree_path_free);
3587         }
3588
3589       g_signal_handlers_block_by_func (selection,
3590           log_window_when_changed_cb,
3591           self);
3592
3593       gtk_list_store_clear (store);
3594
3595       g_signal_handlers_unblock_by_func (selection,
3596           log_window_when_changed_cb,
3597           self);
3598
3599       /* Get a list of dates and show them on the treeview */
3600       for (targ = targets, acc = accounts;
3601            targ != NULL && acc != NULL;
3602            targ = targ->next, acc = acc->next)
3603         {
3604           TpAccount *account = acc->data;
3605           TplEntity *target = targ->data;
3606           Ctx *ctx = ctx_new (self, account, target, NULL, event_mask, 0,
3607               self->priv->count);
3608
3609           _tpl_action_chain_append (self->priv->chain, get_dates_for_entity, ctx);
3610         }
3611       _tpl_action_chain_append (self->priv->chain, select_date, NULL);
3612       _tpl_action_chain_start (self->priv->chain);
3613     }
3614   else
3615     {
3616       /* Show messages of the selected date */
3617       log_window_get_messages_for_dates (self, dates);
3618     }
3619
3620   g_list_free_full (accounts, g_object_unref);
3621   g_list_free_full (targets, g_object_unref);
3622   g_list_free_full (dates, (GFreeFunc) g_date_free);
3623 }
3624
3625 typedef struct {
3626   EmpathyAccountChooserFilterResultCallback callback;
3627   gpointer user_data;
3628 } FilterCallbackData;
3629
3630 static void
3631 got_entities (GObject *manager,
3632     GAsyncResult *result,
3633     gpointer user_data)
3634 {
3635   FilterCallbackData *data = user_data;
3636   GList *entities;
3637   GError *error = NULL;
3638
3639   if (!tpl_log_manager_get_entities_finish (TPL_LOG_MANAGER (manager),
3640       result, &entities, &error))
3641     {
3642       DEBUG ("Could not get entities: %s", error->message);
3643       g_error_free (error);
3644       data->callback (FALSE, data->user_data);
3645     }
3646   else
3647     {
3648       data->callback (entities != NULL, data->user_data);
3649
3650       g_list_free_full (entities, g_object_unref);
3651     }
3652
3653   g_slice_free (FilterCallbackData, data);
3654 }
3655
3656 static void
3657 empathy_account_chooser_filter_has_logs (TpAccount *account,
3658     EmpathyAccountChooserFilterResultCallback callback,
3659     gpointer callback_data,
3660     gpointer user_data)
3661 {
3662   TplLogManager *manager = tpl_log_manager_dup_singleton ();
3663   FilterCallbackData *cb_data = g_slice_new0 (FilterCallbackData);
3664
3665   cb_data->callback = callback;
3666   cb_data->user_data = callback_data;
3667
3668   tpl_log_manager_get_entities_async (manager, account, got_entities, cb_data);
3669
3670   g_object_unref (manager);
3671 }
3672
3673 static void
3674 log_window_logger_clear_account_cb (TpProxy *proxy,
3675     const GError *error,
3676     gpointer user_data,
3677     GObject *weak_object)
3678 {
3679   EmpathyLogWindow *self = EMPATHY_LOG_WINDOW (user_data);
3680
3681   if (error != NULL)
3682     g_warning ("Error when clearing logs: %s", error->message);
3683
3684   /* Refresh the log viewer so the logs are cleared if the account
3685    * has been deleted */
3686   gtk_tree_store_clear (self->priv->store_events);
3687   log_window_who_populate (self);
3688
3689   /* Re-filter the account chooser so the accounts without logs get
3690    * greyed out */
3691   empathy_account_chooser_refilter (
3692       EMPATHY_ACCOUNT_CHOOSER (self->priv->account_chooser));
3693 }
3694
3695 static void
3696 log_window_delete_menu_clicked_cb (GtkMenuItem *menuitem,
3697     EmpathyLogWindow *self)
3698 {
3699   GtkWidget *dialog, *content_area, *hbox, *label;
3700   EmpathyAccountChooser *account_chooser;
3701   gint response_id;
3702   TpDBusDaemon *bus;
3703   TpProxy *logger;
3704   GError *error = NULL;
3705
3706   account_chooser = (EmpathyAccountChooser *) empathy_account_chooser_new ();
3707   empathy_account_chooser_set_has_all_option (account_chooser, TRUE);
3708
3709   empathy_account_chooser_refilter (account_chooser);
3710
3711   /* Select the same account as in the history window */
3712   empathy_account_chooser_set_account (account_chooser,
3713       empathy_account_chooser_get_account (
3714         EMPATHY_ACCOUNT_CHOOSER (self->priv->account_chooser)));
3715
3716   dialog = gtk_message_dialog_new_with_markup (GTK_WINDOW (self),
3717       GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING,
3718       GTK_BUTTONS_NONE,
3719       _("Are you sure you want to delete all logs of previous conversations?"));
3720
3721   gtk_dialog_add_buttons (GTK_DIALOG (dialog),
3722       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3723       _("Clear All"), GTK_RESPONSE_APPLY,
3724       NULL);
3725
3726   content_area = gtk_message_dialog_get_message_area (
3727       GTK_MESSAGE_DIALOG (dialog));
3728
3729   hbox = gtk_hbox_new (FALSE, 6);
3730   label = gtk_label_new (_("Delete from:"));
3731   gtk_box_pack_start (GTK_BOX (hbox), label,
3732       FALSE, FALSE, 0);
3733   gtk_box_pack_start (GTK_BOX (hbox), GTK_WIDGET (account_chooser),
3734       FALSE, FALSE, 0);
3735   gtk_box_pack_start (GTK_BOX (content_area), hbox,
3736       FALSE, FALSE, 0);
3737
3738   gtk_widget_show_all (hbox);
3739
3740   response_id = gtk_dialog_run (GTK_DIALOG (dialog));
3741
3742   if (response_id != GTK_RESPONSE_APPLY)
3743     goto out;
3744
3745   bus = tp_dbus_daemon_dup (&error);
3746   if (error != NULL)
3747     {
3748       g_warning ("Could not delete logs: %s", error->message);
3749       g_error_free (error);
3750       goto out;
3751     }
3752
3753   logger = g_object_new (TP_TYPE_PROXY,
3754       "bus-name", "org.freedesktop.Telepathy.Logger",
3755       "object-path", "/org/freedesktop/Telepathy/Logger",
3756       "dbus-daemon", bus,
3757       NULL);
3758   g_object_unref (bus);
3759
3760   tp_proxy_add_interface_by_id (logger, EMP_IFACE_QUARK_LOGGER);
3761
3762   if (empathy_account_chooser_has_all_selected (account_chooser))
3763     {
3764       DEBUG ("Deleting logs for all the accounts");
3765
3766       emp_cli_logger_call_clear (logger, -1,
3767           log_window_logger_clear_account_cb,
3768           self, NULL, G_OBJECT (self));
3769     }
3770   else
3771     {
3772       TpAccount *account;
3773
3774       account = empathy_account_chooser_get_account (account_chooser);
3775
3776       DEBUG ("Deleting logs for %s", tp_proxy_get_object_path (account));
3777
3778       emp_cli_logger_call_clear_account (logger, -1,
3779           tp_proxy_get_object_path (account),
3780           log_window_logger_clear_account_cb,
3781           self, NULL, G_OBJECT (self));
3782     }
3783
3784   g_object_unref (logger);
3785  out:
3786   gtk_widget_destroy (dialog);
3787 }