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