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