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