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