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