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