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