]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
port to latest tp-logger API
[empathy.git] / libempathy-gtk / empathy-chat.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2002-2007 Imendio AB
4  * Copyright (C) 2007-2008 Collabora Ltd.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19  * Boston, MA  02110-1301  USA
20  *
21  * Authors: Mikael Hallendal <micke@imendio.com>
22  *          Richard Hult <richard@imendio.com>
23  *          Martyn Russell <martyn@imendio.com>
24  *          Geert-Jan Van den Bogaerde <geertjan@gnome.org>
25  *          Xavier Claessens <xclaesse@gmail.com>
26  */
27
28 #include <config.h>
29
30 #include <string.h>
31 #include <stdlib.h>
32
33 #include <gdk/gdkkeysyms.h>
34 #include <glib/gi18n-lib.h>
35 #include <gtk/gtk.h>
36
37 #include <telepathy-glib/account-manager.h>
38 #include <telepathy-glib/util.h>
39 #ifdef ENABLE_TPL
40 #include <telepathy-logger/log-manager.h>
41 #else
42
43 #include <libempathy/empathy-log-manager.h>
44 #endif /* ENABLE_TPL */
45 #include <libempathy/empathy-contact-list.h>
46 #include <libempathy/empathy-gsettings.h>
47 #include <libempathy/empathy-utils.h>
48 #include <libempathy/empathy-dispatcher.h>
49
50 #include "empathy-chat.h"
51 #include "empathy-spell.h"
52 #include "empathy-contact-list-store.h"
53 #include "empathy-contact-list-view.h"
54 #include "empathy-contact-menu.h"
55 #include "empathy-search-bar.h"
56 #include "empathy-theme-manager.h"
57 #include "empathy-smiley-manager.h"
58 #include "empathy-ui-utils.h"
59 #include "empathy-string-parser.h"
60
61 #define DEBUG_FLAG EMPATHY_DEBUG_CHAT
62 #include <libempathy/empathy-debug.h>
63
64 #define CHAT_DIR_CREATE_MODE  (S_IRUSR | S_IWUSR | S_IXUSR)
65 #define CHAT_FILE_CREATE_MODE (S_IRUSR | S_IWUSR)
66 #define IS_ENTER(v) (v == GDK_Return || v == GDK_ISO_Enter || v == GDK_KP_Enter)
67 #define MAX_INPUT_HEIGHT 150
68 #define COMPOSING_STOP_TIMEOUT 5
69
70 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyChat)
71 typedef struct {
72         EmpathyTpChat     *tp_chat;
73         TpAccount         *account;
74         gchar             *id;
75         gchar             *name;
76         gchar             *subject;
77         EmpathyContact    *remote_contact;
78         gboolean           show_contacts;
79
80         GSettings         *gsettings_chat;
81         GSettings         *gsettings_ui;
82
83 #ifdef ENABLE_TPL
84         TplLogManager     *log_manager;
85 #else
86         EmpathyLogManager *log_manager;
87 #endif /* ENABLE_TPL */
88         TpAccountManager  *account_manager;
89         GList             *input_history;
90         GList             *input_history_current;
91         GList             *compositors;
92         GCompletion       *completion;
93         guint              composing_stop_timeout_id;
94         guint              block_events_timeout_id;
95         TpHandleType       handle_type;
96         gint               contacts_width;
97         gboolean           has_input_vscroll;
98         gint               topic_width;
99
100         /* TRUE if spell checking is enabled, FALSE otherwise.
101          * This is to keep track of the last state of spell checking
102          * when it changes. */
103         gboolean           spell_checking_enabled;
104
105         /* These store the signal handler ids for the enclosed text entry. */
106         gulong             insert_text_id;
107         gulong             delete_range_id;
108         gulong             notify_cursor_position_id;
109
110         GtkWidget         *widget;
111         GtkWidget         *hpaned;
112         GtkWidget         *vbox_left;
113         GtkWidget         *scrolled_window_chat;
114         GtkWidget         *scrolled_window_input;
115         GtkWidget         *scrolled_window_contacts;
116         GtkWidget         *hbox_topic;
117         GtkWidget         *expander_topic;
118         GtkWidget         *label_topic;
119         GtkWidget         *contact_list_view;
120         GtkWidget         *info_bar_vbox;
121         GtkWidget         *search_bar;
122
123         guint              unread_messages;
124         /* TRUE if the pending messages can be displayed. This is to avoid to show
125          * pending messages *before* messages from logs. (#603980) */
126         gboolean           can_show_pending;
127
128         /* FIXME: retrieving_backlogs flag is a workaround for Bug#610994 and should
129          * be differently handled since it introduces another race condition, which
130          * is really hard to occur, but still possible.
131          *
132          * With the current workaround (which has the race above), we need to be
133          * sure to ACK any pending messages only when the retrieval of backlogs is
134          * finished, that's why using retrieving_backlogs flag.
135          * empathy_chat_messages_read () will check this variable and not ACK
136          * anything when TRUE. It will be set TRUE at chat_constructed () and set
137          * back to FALSE when the backlog has been retrieved and the pending
138          * messages actually showed to the user.
139          *
140          * Race condition introduced with this workaround:
141          * Scenario: a message is pending, the user is notified and selects the tab.
142          * the tab with a pending message is focused before the messages are properly
143          * shown (since the preparation of the window is slower AND async WRT the
144          * tab showing), which means the user won't see any new messages (rare but
145          * possible), if he/she will change tab focus before the messages are
146          * properly shown, the tab will be set as 'seen' and the user won't be
147          * notified again about the already notified pending messages when the
148          * messages in tab will be properly shown */
149         gboolean           retrieving_backlogs;
150 } EmpathyChatPriv;
151
152 typedef struct {
153         gchar *text; /* Original message that was specified
154                       * upon entry creation. */
155         gchar *modified_text; /* Message that was modified by user.
156                                * When no modifications were made, it is NULL */
157 } InputHistoryEntry;
158
159 enum {
160         COMPOSING,
161         NEW_MESSAGE,
162         LAST_SIGNAL
163 };
164
165 enum {
166         PROP_0,
167         PROP_TP_CHAT,
168         PROP_ACCOUNT,
169         PROP_ID,
170         PROP_NAME,
171         PROP_SUBJECT,
172         PROP_REMOTE_CONTACT,
173         PROP_SHOW_CONTACTS,
174 };
175
176 static guint signals[LAST_SIGNAL] = { 0 };
177
178 G_DEFINE_TYPE (EmpathyChat, empathy_chat, GTK_TYPE_BIN);
179
180 static void
181 chat_get_property (GObject    *object,
182                    guint       param_id,
183                    GValue     *value,
184                    GParamSpec *pspec)
185 {
186         EmpathyChat *chat = EMPATHY_CHAT (object);
187         EmpathyChatPriv *priv = GET_PRIV (object);
188
189         switch (param_id) {
190         case PROP_TP_CHAT:
191                 g_value_set_object (value, priv->tp_chat);
192                 break;
193         case PROP_ACCOUNT:
194                 g_value_set_object (value, priv->account);
195                 break;
196         case PROP_NAME:
197                 g_value_set_string (value, empathy_chat_get_name (chat));
198                 break;
199         case PROP_ID:
200                 g_value_set_string (value, priv->id);
201                 break;
202         case PROP_SUBJECT:
203                 g_value_set_string (value, priv->subject);
204                 break;
205         case PROP_REMOTE_CONTACT:
206                 g_value_set_object (value, priv->remote_contact);
207                 break;
208         case PROP_SHOW_CONTACTS:
209                 g_value_set_boolean (value, priv->show_contacts);
210                 break;
211         default:
212                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
213                 break;
214         };
215 }
216
217 static void
218 chat_set_property (GObject      *object,
219                    guint         param_id,
220                    const GValue *value,
221                    GParamSpec   *pspec)
222 {
223         EmpathyChat *chat = EMPATHY_CHAT (object);
224
225         switch (param_id) {
226         case PROP_TP_CHAT:
227                 empathy_chat_set_tp_chat (chat, EMPATHY_TP_CHAT (g_value_get_object (value)));
228                 break;
229         case PROP_SHOW_CONTACTS:
230                 empathy_chat_set_show_contacts (chat, g_value_get_boolean (value));
231                 break;
232         default:
233                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
234                 break;
235         };
236 }
237
238 static void
239 chat_connect_channel_reconnected (EmpathyDispatchOperation *dispatch,
240                                   const GError             *error,
241                                   gpointer                  user_data)
242 {
243         EmpathyChat *chat = EMPATHY_CHAT (user_data);
244         EmpathyTpChat *tpchat;
245
246         if (error != NULL) {
247                 empathy_chat_view_append_event (chat->view,
248                         _("Failed to reconnect this chat"));
249                 return;
250         }
251
252         tpchat = EMPATHY_TP_CHAT (
253                 empathy_dispatch_operation_get_channel_wrapper (dispatch));
254
255         if (empathy_dispatch_operation_claim (dispatch)) {
256                 empathy_chat_set_tp_chat (chat, tpchat);
257         }
258 }
259
260 static void
261 reconnected_connection_ready_cb (TpConnection *connection,
262                         const GError *error,
263                         gpointer user_data)
264 {
265         EmpathyChat *chat = user_data;
266         EmpathyChatPriv *priv = GET_PRIV (chat);
267
268         if (error != NULL) {
269                 DEBUG ("connection is not ready: %s", error->message);
270                 goto out;
271         }
272
273         DEBUG ("Account reconnected, request a new Text channel");
274
275         switch (priv->handle_type) {
276                 case TP_HANDLE_TYPE_CONTACT:
277                         empathy_dispatcher_chat_with_contact_id (
278                                 connection, priv->id, EMPATHY_DISPATCHER_NON_USER_ACTION,
279                                 chat_connect_channel_reconnected,
280                                 chat);
281                         break;
282                 case TP_HANDLE_TYPE_ROOM:
283                         empathy_dispatcher_join_muc (connection,
284                                 priv->id, EMPATHY_DISPATCHER_NON_USER_ACTION,
285                                 chat_connect_channel_reconnected,
286                                 chat);
287                         break;
288                 default:
289                         g_assert_not_reached ();
290                         break;
291         }
292
293 out:
294         g_object_unref (chat);
295 }
296
297 static void
298 chat_new_connection_cb (TpAccount   *account,
299                         guint        old_status,
300                         guint        new_status,
301                         guint        reason,
302                         gchar       *dbus_error_name,
303                         GHashTable  *details,
304                         EmpathyChat *chat)
305 {
306         EmpathyChatPriv *priv = GET_PRIV (chat);
307         TpConnection *connection;
308
309         if (new_status != TP_CONNECTION_STATUS_CONNECTED)
310                 return;
311
312         connection = tp_account_get_connection (account);
313
314         if (priv->tp_chat != NULL || account != priv->account ||
315             priv->handle_type == TP_HANDLE_TYPE_NONE ||
316             EMP_STR_EMPTY (priv->id))
317                 return;
318
319         g_object_ref (chat);
320         tp_connection_call_when_ready (connection, reconnected_connection_ready_cb,
321                                    chat);
322 }
323
324 static void
325 chat_composing_remove_timeout (EmpathyChat *chat)
326 {
327         EmpathyChatPriv *priv;
328
329         priv = GET_PRIV (chat);
330
331         if (priv->composing_stop_timeout_id) {
332                 g_source_remove (priv->composing_stop_timeout_id);
333                 priv->composing_stop_timeout_id = 0;
334         }
335 }
336
337 static gboolean
338 chat_composing_stop_timeout_cb (EmpathyChat *chat)
339 {
340         EmpathyChatPriv *priv;
341
342         priv = GET_PRIV (chat);
343
344         priv->composing_stop_timeout_id = 0;
345         empathy_tp_chat_set_state (priv->tp_chat,
346                                    TP_CHANNEL_CHAT_STATE_PAUSED);
347
348         return FALSE;
349 }
350
351 static void
352 chat_composing_start (EmpathyChat *chat)
353 {
354         EmpathyChatPriv *priv;
355
356         priv = GET_PRIV (chat);
357
358         if (priv->composing_stop_timeout_id) {
359                 /* Just restart the timeout */
360                 chat_composing_remove_timeout (chat);
361         } else {
362                 empathy_tp_chat_set_state (priv->tp_chat,
363                                            TP_CHANNEL_CHAT_STATE_COMPOSING);
364         }
365
366         priv->composing_stop_timeout_id = g_timeout_add_seconds (
367                 COMPOSING_STOP_TIMEOUT,
368                 (GSourceFunc) chat_composing_stop_timeout_cb,
369                 chat);
370 }
371
372 static void
373 chat_composing_stop (EmpathyChat *chat)
374 {
375         EmpathyChatPriv *priv;
376
377         priv = GET_PRIV (chat);
378
379         chat_composing_remove_timeout (chat);
380         empathy_tp_chat_set_state (priv->tp_chat,
381                                    TP_CHANNEL_CHAT_STATE_ACTIVE);
382 }
383
384 static gint
385 chat_input_history_entry_cmp (InputHistoryEntry *entry,
386                               const gchar *text)
387 {
388         if (!tp_strdiff (entry->text, text)) {
389                 if (entry->modified_text != NULL) {
390                         /* Modified entry and single string cannot be equal. */
391                         return 1;
392                 }
393                 return 0;
394         }
395         return 1;
396 }
397
398 static InputHistoryEntry *
399 chat_input_history_entry_new_with_text (const gchar *text)
400 {
401         InputHistoryEntry *entry;
402         entry = g_slice_new0 (InputHistoryEntry);
403         entry->text = g_strdup (text);
404
405         return entry;
406 }
407
408 static void
409 chat_input_history_entry_free (InputHistoryEntry *entry)
410 {
411         g_free (entry->text);
412         g_free (entry->modified_text);
413         g_slice_free (InputHistoryEntry, entry);
414 }
415
416 static void
417 chat_input_history_entry_revert (InputHistoryEntry *entry)
418 {
419         g_free (entry->modified_text);
420         entry->modified_text = NULL;
421 }
422
423 static void
424 chat_input_history_entry_update_text (InputHistoryEntry *entry,
425                                       const gchar *text)
426 {
427         gchar *old;
428
429         if (!tp_strdiff (text, entry->text)) {
430                 g_free (entry->modified_text);
431                 entry->modified_text = NULL;
432                 return;
433         }
434
435         old = entry->modified_text;
436         entry->modified_text = g_strdup (text);
437         g_free (old);
438 }
439
440 static const gchar *
441 chat_input_history_entry_get_text (InputHistoryEntry *entry)
442 {
443         if (entry == NULL) {
444                 return NULL;
445         }
446
447         if (entry->modified_text != NULL) {
448                 return entry->modified_text;
449         }
450         return entry->text;
451 }
452
453 static GList *
454 chat_input_history_remove_item (GList *list,
455                                 GList *item)
456 {
457         list = g_list_remove_link (list, item);
458         chat_input_history_entry_free (item->data);
459         g_list_free_1 (item);
460         return list;
461 }
462
463 static void
464 chat_input_history_revert (EmpathyChat *chat)
465 {
466         EmpathyChatPriv   *priv;
467         GList             *list;
468         GList             *item1;
469         GList             *item2;
470         InputHistoryEntry *entry;
471
472         priv = GET_PRIV (chat);
473         list = priv->input_history;
474
475         if (list == NULL) {
476                 DEBUG ("No input history");
477                 return;
478         }
479
480         /* Delete temporary entry */
481         if (priv->input_history_current != NULL) {
482                 item1 = list;
483                 list = chat_input_history_remove_item (list, item1);
484                 if (priv->input_history_current == item1) {
485                         /* Removed temporary entry was current entry */
486                         priv->input_history = list;
487                         priv->input_history_current = NULL;
488                         return;
489                 }
490         }
491         else {
492                 /* There is no entry to revert */
493                 return;
494         }
495
496         /* Restore the current history entry to original value */
497         item1 = priv->input_history_current;
498         entry = item1->data;
499         chat_input_history_entry_revert (entry);
500
501         /* Remove restored entry if there is other occurance before this entry */
502         item2 = g_list_find_custom (list, chat_input_history_entry_get_text (entry),
503                                     (GCompareFunc) chat_input_history_entry_cmp);
504         if (item2 != item1) {
505                 list = chat_input_history_remove_item (list, item1);
506         }
507         else {
508                 /* Remove other occurance of the restored entry */
509                 item2 = g_list_find_custom (item1->next,
510                                             chat_input_history_entry_get_text (entry),
511                                             (GCompareFunc) chat_input_history_entry_cmp);
512                 if (item2 != NULL) {
513                         list = chat_input_history_remove_item (list, item2);
514                 }
515         }
516
517         priv->input_history_current = NULL;
518         priv->input_history = list;
519 }
520
521 static void
522 chat_input_history_add (EmpathyChat  *chat,
523                         const gchar *str,
524                         gboolean temporary)
525 {
526         EmpathyChatPriv   *priv;
527         GList             *list;
528         GList             *item;
529         InputHistoryEntry *entry;
530
531         priv = GET_PRIV (chat);
532
533         list = priv->input_history;
534
535         /* Remove any other occurances of this entry, if not temporary */
536         if (!temporary) {
537                 while ((item = g_list_find_custom (list, str,
538                     (GCompareFunc) chat_input_history_entry_cmp)) != NULL) {
539                         list = chat_input_history_remove_item (list, item);
540                 }
541
542                 /* Trim the list to the last 10 items */
543                 while (g_list_length (list) > 10) {
544                         item = g_list_last (list);
545                         if (item != NULL) {
546                                 list = chat_input_history_remove_item (list, item);
547                         }
548                 }
549         }
550
551
552
553         /* Add new entry */
554         entry = chat_input_history_entry_new_with_text (str);
555         list = g_list_prepend (list, entry);
556
557         /* Set the list and the current item pointer */
558         priv->input_history = list;
559         if (temporary) {
560                 priv->input_history_current = list;
561         }
562         else {
563                 priv->input_history_current = NULL;
564         }
565 }
566
567 static const gchar *
568 chat_input_history_get_next (EmpathyChat *chat)
569 {
570         EmpathyChatPriv *priv;
571         GList           *item;
572         const gchar     *msg;
573
574         priv = GET_PRIV (chat);
575
576         if (priv->input_history == NULL) {
577                 DEBUG ("No input history, next entry is NULL");
578                 return NULL;
579         }
580         g_assert (priv->input_history_current != NULL);
581
582         if ((item = g_list_next (priv->input_history_current)) == NULL)
583         {
584                 item = priv->input_history_current;
585         }
586
587         msg = chat_input_history_entry_get_text (item->data);
588
589         DEBUG ("Returning next entry: '%s'", msg);
590
591         priv->input_history_current = item;
592
593         return msg;
594 }
595
596 static const gchar *
597 chat_input_history_get_prev (EmpathyChat *chat)
598 {
599         EmpathyChatPriv *priv;
600         GList           *item;
601         const gchar     *msg;
602
603         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
604
605         priv = GET_PRIV (chat);
606
607         if (priv->input_history == NULL) {
608                 DEBUG ("No input history, previous entry is NULL");
609                 return NULL;
610         }
611
612         if (priv->input_history_current == NULL)
613         {
614                 return NULL;
615         }
616         else if ((item = g_list_previous (priv->input_history_current)) == NULL)
617         {
618                 item = priv->input_history_current;
619         }
620
621         msg = chat_input_history_entry_get_text (item->data);
622
623         DEBUG ("Returning previous entry: '%s'", msg);
624
625         priv->input_history_current = item;
626
627         return msg;
628 }
629
630 static void
631 chat_input_history_update (EmpathyChat *chat,
632                            GtkTextBuffer *buffer)
633 {
634         EmpathyChatPriv      *priv;
635         GtkTextIter           start, end;
636         gchar                *text;
637         InputHistoryEntry    *entry;
638
639         priv = GET_PRIV (chat);
640
641         gtk_text_buffer_get_bounds (buffer, &start, &end);
642         text = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
643
644         if (priv->input_history_current == NULL) {
645                 /* Add the current text temporarily to the history */
646                 chat_input_history_add (chat, text, TRUE);
647                 g_free (text);
648                 return;
649         }
650
651         /* Save the changes in the history */
652         entry = priv->input_history_current->data;
653         if (tp_strdiff (chat_input_history_entry_get_text (entry), text)) {
654                 chat_input_history_entry_update_text (entry, text);
655         }
656
657         g_free (text);
658 }
659
660 static void
661 chat_command_join_cb (EmpathyDispatchOperation *dispatch,
662                       const GError             *error,
663                       gpointer                  user_data)
664 {
665         EmpathyChat *chat = user_data;
666
667         if (error != NULL) {
668                 DEBUG ("Error: %s", error->message);
669                 empathy_chat_view_append_event (chat->view,
670                         _("Failed to join chat room"));
671         }
672 }
673
674 typedef struct {
675         EmpathyChat *chat;
676         gchar *message;
677 } ChatCommandMsgData;
678
679 static void
680 chat_command_msg_cb (EmpathyDispatchOperation *dispatch,
681                               const GError             *error,
682                               gpointer                  user_data)
683 {
684         ChatCommandMsgData *data = user_data;
685
686         if (error != NULL) {
687                 empathy_chat_view_append_event (data->chat->view,
688                         _("Failed to open private chat"));
689                 goto OUT;
690         }
691
692         if (!EMP_STR_EMPTY (data->message)) {
693                 EmpathyTpChat *tpchat;
694                 EmpathyMessage *message;
695
696                 tpchat = EMPATHY_TP_CHAT (
697                         empathy_dispatch_operation_get_channel_wrapper (dispatch));
698
699                 message = empathy_message_new (data->message);
700                 empathy_tp_chat_send (tpchat, message);
701                 g_object_unref (message);
702         }
703
704 OUT:
705         g_free (data->message);
706         g_slice_free (ChatCommandMsgData, data);
707 }
708
709 static void
710 chat_command_clear (EmpathyChat *chat,
711                     GStrv        strv)
712 {
713         empathy_chat_view_clear (chat->view);
714 }
715
716 static void
717 chat_command_topic (EmpathyChat *chat,
718                     GStrv        strv)
719 {
720         EmpathyChatPriv *priv = GET_PRIV (chat);
721         EmpathyTpChatProperty *property;
722         GValue value = {0, };
723
724         property = empathy_tp_chat_get_property (priv->tp_chat, "subject");
725         if (property == NULL) {
726                 empathy_chat_view_append_event (chat->view,
727                         _("Topic not supported on this conversation"));
728                 return;
729         }
730
731         if (!(property->flags & TP_PROPERTY_FLAG_WRITE)) {
732                 empathy_chat_view_append_event (chat->view,
733                         _("You are not allowed to change the topic"));
734                 return;
735         }
736
737         g_value_init (&value, G_TYPE_STRING);
738         g_value_set_string (&value, strv[1]);
739         empathy_tp_chat_set_property (priv->tp_chat, "subject", &value);
740         g_value_unset (&value);
741 }
742
743 static void
744 chat_command_join (EmpathyChat *chat,
745                    GStrv        strv)
746 {
747         guint i = 0;
748         EmpathyChatPriv *priv = GET_PRIV (chat);
749
750         GStrv rooms = g_strsplit_set (strv[1], ", ", -1);
751
752         while (rooms[i] != NULL) {
753                 /* ignore empty strings */
754                 if (!EMP_STR_EMPTY (rooms[i])) {
755                         TpConnection *connection;
756
757                         connection = empathy_tp_chat_get_connection (priv->tp_chat);
758                         empathy_dispatcher_join_muc (connection, rooms[i],
759                                                      gtk_get_current_event_time (),
760                                                      chat_command_join_cb,
761                                                      chat);
762                 }
763                 i++;
764         }
765         g_strfreev (rooms);
766 }
767
768 static void
769 chat_command_msg_internal (EmpathyChat *chat,
770                            const gchar *contact_id,
771                            const gchar *message)
772 {
773         EmpathyChatPriv *priv = GET_PRIV (chat);
774         TpConnection *connection;
775         ChatCommandMsgData *data;
776
777         /* FIXME: We should probably search in members alias. But this
778          * is enough for IRC */
779         data = g_slice_new (ChatCommandMsgData);
780         data->chat = chat;
781         data->message = g_strdup (message);
782         connection = empathy_tp_chat_get_connection (priv->tp_chat);
783         empathy_dispatcher_chat_with_contact_id (connection, contact_id,
784                                                  gtk_get_current_event_time (),
785                                                  chat_command_msg_cb,
786                                                  data);
787 }
788
789 static void
790 chat_command_query (EmpathyChat *chat,
791                     GStrv        strv)
792 {
793         /* If <message> part is not defined,
794          * strv[2] will be the terminal NULL */
795         chat_command_msg_internal (chat, strv[1], strv[2]);
796 }
797
798 static void
799 chat_command_msg (EmpathyChat *chat,
800                   GStrv        strv)
801 {
802         chat_command_msg_internal (chat, strv[1], strv[2]);
803 }
804
805 static void
806 chat_command_nick (EmpathyChat *chat,
807                    GStrv        strv)
808 {
809         EmpathyChatPriv *priv = GET_PRIV (chat);
810         TpConnection *connection;
811         GHashTable *new_alias;
812         TpHandle handle;
813
814         connection = tp_account_get_connection (priv->account);
815         handle = tp_connection_get_self_handle (connection);
816         new_alias = g_hash_table_new (g_direct_hash, g_direct_equal);
817         g_hash_table_insert (new_alias, GUINT_TO_POINTER (handle), strv[1]);
818
819         tp_cli_connection_interface_aliasing_call_set_aliases (connection, -1,
820                 new_alias, NULL, NULL, NULL, NULL);
821
822         g_hash_table_destroy (new_alias);
823 }
824
825 static void
826 chat_command_me (EmpathyChat *chat,
827                   GStrv        strv)
828 {
829         EmpathyChatPriv *priv = GET_PRIV (chat);
830         EmpathyMessage *message;
831
832         message = empathy_message_new (strv[1]);
833         empathy_message_set_tptype (message, TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION);
834         empathy_tp_chat_send (priv->tp_chat, message);
835         g_object_unref (message);
836 }
837
838 static void
839 chat_command_say (EmpathyChat *chat,
840                   GStrv        strv)
841 {
842         EmpathyChatPriv *priv = GET_PRIV (chat);
843         EmpathyMessage *message;
844
845         message = empathy_message_new (strv[1]);
846         empathy_tp_chat_send (priv->tp_chat, message);
847         g_object_unref (message);
848 }
849
850 static void chat_command_help (EmpathyChat *chat, GStrv strv);
851
852 typedef void (*ChatCommandFunc) (EmpathyChat *chat, GStrv strv);
853
854 typedef struct {
855         const gchar *prefix;
856         guint min_parts;
857         guint max_parts;
858         ChatCommandFunc func;
859         const gchar *help;
860 } ChatCommandItem;
861
862 static ChatCommandItem commands[] = {
863         {"clear", 1, 1, chat_command_clear,
864          N_("/clear: clear all messages from the current conversation")},
865
866         {"topic", 2, 2, chat_command_topic,
867          N_("/topic <topic>: set the topic of the current conversation")},
868
869         {"join", 2, 2, chat_command_join,
870          N_("/join <chat room ID>: join a new chat room")},
871
872         {"j", 2, 2, chat_command_join,
873          N_("/j <chat room ID>: join a new chat room")},
874
875         {"query", 2, 3, chat_command_query,
876          N_("/query <contact ID> [<message>]: open a private chat")},
877
878         {"msg", 3, 3, chat_command_msg,
879          N_("/msg <contact ID> <message>: open a private chat")},
880
881         {"nick", 2, 2, chat_command_nick,
882          N_("/nick <nickname>: change your nickname on the current server")},
883
884         {"me", 2, 2, chat_command_me,
885          N_("/me <message>: send an ACTION message to the current conversation")},
886
887         {"say", 2, 2, chat_command_say,
888          N_("/say <message>: send <message> to the current conversation. "
889             "This is used to send a message starting with a '/'. For example: "
890             "\"/say /join is used to join a new chat room\"")},
891
892         {"help", 1, 2, chat_command_help,
893          N_("/help [<command>]: show all supported commands. "
894             "If <command> is defined, show its usage.")},
895 };
896
897 static void
898 chat_command_show_help (EmpathyChat     *chat,
899                         ChatCommandItem *item)
900 {
901         gchar *str;
902
903         str = g_strdup_printf (_("Usage: %s"), _(item->help));
904         empathy_chat_view_append_event (chat->view, str);
905         g_free (str);
906 }
907
908 static void
909 chat_command_help (EmpathyChat *chat,
910                    GStrv        strv)
911 {
912         guint i;
913
914         /* If <command> part is not defined,
915          * strv[1] will be the terminal NULL */
916         if (strv[1] == NULL) {
917                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
918                         empathy_chat_view_append_event (chat->view,
919                                 _(commands[i].help));
920                 }
921                 return;
922         }
923
924         for (i = 0; i < G_N_ELEMENTS (commands); i++) {
925                 if (g_ascii_strcasecmp (strv[1], commands[i].prefix) == 0) {
926                         chat_command_show_help (chat, &commands[i]);
927                         return;
928                 }
929         }
930
931         empathy_chat_view_append_event (chat->view,
932                 _("Unknown command"));
933 }
934
935 static GStrv
936 chat_command_parse (const gchar *text, guint max_parts)
937 {
938         GPtrArray *array;
939         gchar *item;
940
941         DEBUG ("Parse command, parts=%d text=\"%s\":", max_parts, text);
942
943         array = g_ptr_array_sized_new (max_parts + 1);
944         while (max_parts > 1) {
945                 const gchar *end;
946
947                 /* Skip white spaces */
948                 while (g_ascii_isspace (*text)) {
949                         text++;
950                 }
951
952                 /* Search the end of this part, until first space. */
953                 for (end = text; *end != '\0' && !g_ascii_isspace (*end); end++)
954                         /* Do nothing */;
955                 if (*end == '\0') {
956                         break;
957                 }
958
959                 item = g_strndup (text, end - text);
960                 g_ptr_array_add (array, item);
961                 DEBUG ("\tITEM: \"%s\"", item);
962
963                 text = end;
964                 max_parts--;
965         }
966
967         /* Append last part if not empty */
968         item = g_strstrip (g_strdup (text));
969         if (!EMP_STR_EMPTY (item)) {
970                 g_ptr_array_add (array, item);
971                 DEBUG ("\tITEM: \"%s\"", item);
972         } else {
973                 g_free (item);
974         }
975
976         /* Make the array NULL-terminated */
977         g_ptr_array_add (array, NULL);
978
979         return (GStrv) g_ptr_array_free (array, FALSE);
980 }
981
982 static gboolean
983 has_prefix_case (const gchar *s,
984                   const gchar *prefix)
985 {
986         return g_ascii_strncasecmp (s, prefix, strlen (prefix)) == 0;
987 }
988
989 static void
990 chat_send (EmpathyChat  *chat,
991            const gchar *msg)
992 {
993         EmpathyChatPriv *priv;
994         EmpathyMessage  *message;
995         guint            i;
996
997         if (EMP_STR_EMPTY (msg)) {
998                 return;
999         }
1000
1001         priv = GET_PRIV (chat);
1002
1003         chat_input_history_add (chat, msg, FALSE);
1004
1005         if (msg[0] == '/') {
1006                 gboolean second_slash = FALSE;
1007                 const gchar *iter = msg + 1;
1008
1009                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
1010                         GStrv strv;
1011                         guint strv_len;
1012                         gchar c;
1013
1014                         if (!has_prefix_case (msg + 1, commands[i].prefix)) {
1015                                 continue;
1016                         }
1017                         c = *(msg + 1 + strlen (commands[i].prefix));
1018                         if (c != '\0' && !g_ascii_isspace (c)) {
1019                                 continue;
1020                         }
1021
1022                         /* We can't use g_strsplit here because it does
1023                          * not deal correctly if we have more than one space
1024                          * between args */
1025                         strv = chat_command_parse (msg + 1, commands[i].max_parts);
1026
1027                         strv_len = g_strv_length (strv);
1028                         if (strv_len < commands[i].min_parts ||
1029                             strv_len > commands[i].max_parts) {
1030                                 chat_command_show_help (chat, &commands[i]);
1031                                 g_strfreev (strv);
1032                                 return;
1033                         }
1034
1035                         commands[i].func (chat, strv);
1036                         g_strfreev (strv);
1037                         return;
1038                 }
1039
1040                 /* Also allow messages with two slashes before the
1041                  * first space, so it is possible to send a /unix/path.
1042                  * This heuristic is kind of crap. */
1043                 while (*iter != '\0' && !g_ascii_isspace (*iter)) {
1044                         if (*iter == '/') {
1045                                 second_slash = TRUE;
1046                                 break;
1047                         }
1048                         iter++;
1049                 }
1050
1051                 if (!second_slash) {
1052                         empathy_chat_view_append_event (chat->view,
1053                                 _("Unknown command; see /help for the available"
1054                                   " commands"));
1055                         return;
1056                 }
1057         }
1058
1059         message = empathy_message_new (msg);
1060         empathy_tp_chat_send (priv->tp_chat, message);
1061         g_object_unref (message);
1062 }
1063
1064 static void
1065 chat_input_text_view_send (EmpathyChat *chat)
1066 {
1067         EmpathyChatPriv *priv;
1068         GtkTextBuffer  *buffer;
1069         GtkTextIter     start, end;
1070         gchar          *msg;
1071
1072         priv = GET_PRIV (chat);
1073
1074         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1075
1076         gtk_text_buffer_get_bounds (buffer, &start, &end);
1077         msg = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1078
1079         /* clear the input field */
1080         gtk_text_buffer_set_text (buffer, "", -1);
1081         /* delete input history modifications */
1082         chat_input_history_revert (chat);
1083
1084         chat_send (chat, msg);
1085         g_free (msg);
1086 }
1087
1088 static void
1089 chat_state_changed_cb (EmpathyTpChat      *tp_chat,
1090                        EmpathyContact     *contact,
1091                        TpChannelChatState  state,
1092                        EmpathyChat        *chat)
1093 {
1094         EmpathyChatPriv *priv;
1095         GList          *l;
1096         gboolean        was_composing;
1097
1098         priv = GET_PRIV (chat);
1099
1100         if (empathy_contact_is_user (contact)) {
1101                 /* We don't care about our own chat state */
1102                 return;
1103         }
1104
1105         was_composing = (priv->compositors != NULL);
1106
1107         /* Find the contact in the list. After that l is the list elem or NULL */
1108         for (l = priv->compositors; l; l = l->next) {
1109                 if (contact == l->data) {
1110                         break;
1111                 }
1112         }
1113
1114         switch (state) {
1115         case TP_CHANNEL_CHAT_STATE_GONE:
1116         case TP_CHANNEL_CHAT_STATE_INACTIVE:
1117         case TP_CHANNEL_CHAT_STATE_PAUSED:
1118         case TP_CHANNEL_CHAT_STATE_ACTIVE:
1119                 /* Contact is not composing */
1120                 if (l) {
1121                         priv->compositors = g_list_remove_link (priv->compositors, l);
1122                         g_object_unref (l->data);
1123                         g_list_free1 (l);
1124                 }
1125                 break;
1126         case TP_CHANNEL_CHAT_STATE_COMPOSING:
1127                 /* Contact is composing */
1128                 if (!l) {
1129                         priv->compositors = g_list_prepend (priv->compositors,
1130                                                             g_object_ref (contact));
1131                 }
1132                 break;
1133         default:
1134                 g_assert_not_reached ();
1135         }
1136
1137         DEBUG ("Was composing: %s now composing: %s",
1138                 was_composing ? "yes" : "no",
1139                 priv->compositors ? "yes" : "no");
1140
1141         if ((was_composing && !priv->compositors) ||
1142             (!was_composing && priv->compositors)) {
1143                 /* Composing state changed */
1144                 g_signal_emit (chat, signals[COMPOSING], 0,
1145                                priv->compositors != NULL);
1146         }
1147 }
1148
1149 static void
1150 chat_message_received (EmpathyChat *chat, EmpathyMessage *message)
1151 {
1152         EmpathyChatPriv *priv = GET_PRIV (chat);
1153         EmpathyContact  *sender;
1154
1155         sender = empathy_message_get_sender (message);
1156
1157         DEBUG ("Appending new message from %s (%d)",
1158                 empathy_contact_get_name (sender),
1159                 empathy_contact_get_handle (sender));
1160
1161         empathy_chat_view_append_message (chat->view, message);
1162
1163         /* We received a message so the contact is no longer composing */
1164         chat_state_changed_cb (priv->tp_chat, sender,
1165                                TP_CHANNEL_CHAT_STATE_ACTIVE,
1166                                chat);
1167
1168         priv->unread_messages++;
1169         g_signal_emit (chat, signals[NEW_MESSAGE], 0, message);
1170 }
1171
1172 static void
1173 chat_message_received_cb (EmpathyTpChat  *tp_chat,
1174                           EmpathyMessage *message,
1175                           EmpathyChat    *chat)
1176 {
1177         chat_message_received (chat, message);
1178 }
1179
1180 static void
1181 chat_send_error_cb (EmpathyTpChat          *tp_chat,
1182                     const gchar            *message_body,
1183                     TpChannelTextSendError  error_code,
1184                     EmpathyChat            *chat)
1185 {
1186         const gchar *error;
1187         gchar       *str;
1188
1189         switch (error_code) {
1190         case TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE:
1191                 error = _("offline");
1192                 break;
1193         case TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT:
1194                 error = _("invalid contact");
1195                 break;
1196         case TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED:
1197                 error = _("permission denied");
1198                 break;
1199         case TP_CHANNEL_TEXT_SEND_ERROR_TOO_LONG:
1200                 error = _("too long message");
1201                 break;
1202         case TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED:
1203                 error = _("not implemented");
1204                 break;
1205         default:
1206                 error = _("unknown");
1207                 break;
1208         }
1209
1210         str = g_strdup_printf (_("Error sending message '%s': %s"),
1211                                message_body,
1212                                error);
1213         empathy_chat_view_append_event (chat->view, str);
1214         g_free (str);
1215 }
1216
1217 /* WARNING: EXPLICIT CONTENT, keep away childrens!
1218  *
1219  * When a GtkLabel is set to wrap, it assume and hardcoded width. To change
1220  * that width we have to set a size request on the label... but that's not
1221  * possible because we want the window to be able to shrink, so we MUST request
1222  * width of 1. Note that the height of a wrapping label depends on its width.
1223  *
1224  * To work around that, here is what happens:
1225  * 1) size-request is first called, an hardcoded small width is requested by
1226  *    GtkLabel, which means also a too big height. We do nothing.
1227  * 2) size-allocate is called with the full width available, that's the width
1228  *    we really want to make wrap the label. We save that width and restart a
1229  *    size-request/size-allocate round.
1230  * 3) size-request is called a 2nd time, now we can tell the pango layout its
1231  *    width (we can't do that in step 2 because GtkLabel::size-request recreate
1232  *    the layout each time). When the layout has its width, we can know the
1233  *    height of the label and set its requisition. The width request is set to
1234  *    1px to make sure the window can shrink, the layout will fill all the
1235  *    available width anyway.
1236  */
1237 static void
1238 chat_topic_label_size_request_cb (GtkLabel *label,
1239                                    GtkRequisition *requisition,
1240                                    EmpathyChat *chat)
1241 {
1242         EmpathyChatPriv *priv = GET_PRIV (chat);
1243
1244         if (gtk_label_get_line_wrap (label) && priv->topic_width > 0) {
1245                 PangoLayout *layout;
1246                 PangoRectangle rect;
1247                 gint ypad;
1248
1249                 layout = gtk_label_get_layout (label);
1250                 pango_layout_set_width (layout, priv->topic_width * PANGO_SCALE);
1251                 pango_layout_get_extents (layout, NULL, &rect);
1252                 gtk_misc_get_padding (GTK_MISC (label), NULL, &ypad);
1253
1254                 requisition->width = 1;
1255                 requisition->height = PANGO_PIXELS (rect.height) + ypad * 2;
1256         }
1257 }
1258
1259 static void
1260 chat_topic_label_size_allocate_cb (GtkLabel *label,
1261                                    GtkAllocation *allocation,
1262                                    EmpathyChat *chat)
1263 {
1264         EmpathyChatPriv *priv = GET_PRIV (chat);
1265
1266         if (!gtk_label_get_line_wrap (label)) {
1267                 priv->topic_width = -1;
1268
1269                 if (pango_layout_is_ellipsized (gtk_label_get_layout (label)))
1270                         gtk_widget_show (priv->expander_topic);
1271                 else
1272                         gtk_widget_hide (priv->expander_topic);
1273
1274                 return;
1275         }
1276
1277         if (priv->topic_width != allocation->width) {
1278                 priv->topic_width = allocation->width;
1279                 gtk_widget_queue_resize (GTK_WIDGET (label));
1280         }
1281 }
1282
1283 static void
1284 chat_topic_expander_activate_cb (GtkExpander *expander,
1285                                  GParamSpec *param_spec,
1286                                  EmpathyChat *chat)
1287 {
1288         EmpathyChatPriv *priv = GET_PRIV (chat);
1289
1290         if (gtk_expander_get_expanded (expander)) {
1291                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_NONE);
1292                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), TRUE);
1293         } else {
1294                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_END);
1295                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), FALSE);
1296         }
1297 }
1298
1299 static void
1300 chat_property_changed_cb (EmpathyTpChat *tp_chat,
1301                           const gchar   *name,
1302                           GValue        *value,
1303                           EmpathyChat   *chat)
1304 {
1305         EmpathyChatPriv *priv = GET_PRIV (chat);
1306
1307         if (!tp_strdiff (name, "subject")) {
1308                 g_free (priv->subject);
1309                 priv->subject = g_value_dup_string (value);
1310                 g_object_notify (G_OBJECT (chat), "subject");
1311
1312                 if (EMP_STR_EMPTY (priv->subject)) {
1313                         gtk_widget_hide (priv->hbox_topic);
1314                 } else {
1315                         gchar *markup_topic;
1316                         gchar *markup_text;
1317
1318                         markup_topic = empathy_add_link_markup (priv->subject);
1319                         markup_text = g_strdup_printf ("<span weight=\"bold\">%s</span> %s",
1320                                 _("Topic:"), markup_topic);
1321
1322                         gtk_label_set_markup (GTK_LABEL (priv->label_topic), markup_text);
1323                         g_free (markup_text);
1324                         g_free (markup_topic);
1325
1326                         gtk_widget_show (priv->hbox_topic);
1327                 }
1328                 if (priv->block_events_timeout_id == 0) {
1329                         gchar *str;
1330
1331                         if (!EMP_STR_EMPTY (priv->subject)) {
1332                                 str = g_strdup_printf (_("Topic set to: %s"), priv->subject);
1333                         } else {
1334                                 str = g_strdup (_("No topic defined"));
1335                         }
1336                         empathy_chat_view_append_event (EMPATHY_CHAT (chat)->view, str);
1337                         g_free (str);
1338                 }
1339         }
1340         else if (!tp_strdiff (name, "name")) {
1341                 g_free (priv->name);
1342                 priv->name = g_value_dup_string (value);
1343                 g_object_notify (G_OBJECT (chat), "name");
1344         }
1345 }
1346
1347 static gboolean
1348 chat_input_text_get_word_from_iter (GtkTextIter   *iter,
1349                                     GtkTextIter   *start,
1350                                     GtkTextIter   *end)
1351 {
1352         GtkTextIter word_start = *iter;
1353         GtkTextIter word_end = *iter;
1354         GtkTextIter tmp;
1355
1356         if (gtk_text_iter_inside_word (&word_end) &&
1357                         !gtk_text_iter_ends_word (&word_end)) {
1358                 gtk_text_iter_forward_word_end (&word_end);
1359         }
1360
1361         tmp = word_end;
1362
1363         if (gtk_text_iter_get_char (&tmp) == '\'') {
1364                 gtk_text_iter_forward_char (&tmp);
1365
1366                 if (g_unichar_isalpha (gtk_text_iter_get_char (&tmp))) {
1367                         gtk_text_iter_forward_word_end (&word_end);
1368                 }
1369         }
1370
1371
1372         if (gtk_text_iter_inside_word (&word_start) ||
1373                         gtk_text_iter_ends_word (&word_start)) {
1374                 if (!gtk_text_iter_starts_word (&word_start) ||
1375                                 gtk_text_iter_equal (&word_start, &word_end)) {
1376                         gtk_text_iter_backward_word_start (&word_start);
1377                 }
1378
1379                 tmp = word_start;
1380                 gtk_text_iter_backward_char (&tmp);
1381
1382                 if (gtk_text_iter_get_char (&tmp) == '\'') {
1383                         gtk_text_iter_backward_char (&tmp);
1384
1385                         if (g_unichar_isalpha (gtk_text_iter_get_char (&tmp))) {
1386                                 gtk_text_iter_backward_word_start (&word_start);
1387                         }
1388                 }
1389         }
1390
1391         *start = word_start;
1392         *end = word_end;
1393         return TRUE;
1394 }
1395
1396 static void
1397 chat_input_text_buffer_insert_text_cb (GtkTextBuffer *buffer,
1398                                        GtkTextIter   *location,
1399                                        gchar         *text,
1400                                        gint           len,
1401                                        EmpathyChat   *chat)
1402 {
1403         GtkTextIter iter, pos;
1404
1405         /* Remove all misspelled tags in the inserted text.
1406          * This happens when text is inserted within a misspelled word. */
1407         gtk_text_buffer_get_iter_at_offset (buffer, &iter,
1408                                             gtk_text_iter_get_offset (location) - len);
1409         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled",
1410                                             &iter, location);
1411
1412         gtk_text_buffer_get_iter_at_mark (buffer, &pos, gtk_text_buffer_get_insert (buffer));
1413
1414         do {
1415                 GtkTextIter start, end;
1416                 gchar *str;
1417
1418                 if (!chat_input_text_get_word_from_iter (&iter, &start, &end))
1419                         continue;
1420
1421                 str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1422
1423                 if (gtk_text_iter_in_range (&pos, &start, &end) ||
1424                                 gtk_text_iter_equal (&pos, &end) ||
1425                                 empathy_spell_check (str)) {
1426                         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
1427                 } else {
1428                         gtk_text_buffer_apply_tag_by_name (buffer, "misspelled", &start, &end);
1429                 }
1430
1431                 g_free (str);
1432
1433         } while (gtk_text_iter_forward_word_end (&iter) &&
1434                  gtk_text_iter_compare (&iter, location) <= 0);
1435 }
1436
1437 static void
1438 chat_input_text_buffer_delete_range_cb (GtkTextBuffer *buffer,
1439                                         GtkTextIter   *start,
1440                                         GtkTextIter   *end,
1441                                         EmpathyChat   *chat)
1442 {
1443         GtkTextIter word_start, word_end;
1444
1445         if (chat_input_text_get_word_from_iter (start, &word_start, &word_end)) {
1446                 gtk_text_buffer_remove_tag_by_name (buffer, "misspelled",
1447                                                     &word_start, &word_end);
1448         }
1449 }
1450
1451 static void
1452 chat_input_text_buffer_changed_cb (GtkTextBuffer *buffer,
1453                                    EmpathyChat    *chat)
1454 {
1455         if (gtk_text_buffer_get_char_count (buffer) == 0) {
1456                 chat_composing_stop (chat);
1457         } else {
1458                 chat_composing_start (chat);
1459         }
1460 }
1461
1462 static void
1463 chat_input_text_buffer_notify_cursor_position_cb (GtkTextBuffer *buffer,
1464                                                   GParamSpec    *pspec,
1465                                                   EmpathyChat    *chat)
1466 {
1467         GtkTextIter pos;
1468         GtkTextIter prev_pos;
1469         GtkTextIter word_start;
1470         GtkTextIter word_end;
1471         GtkTextMark *mark;
1472         gchar *str;
1473
1474         mark = gtk_text_buffer_get_mark (buffer, "previous-cursor-position");
1475
1476         gtk_text_buffer_get_iter_at_mark (buffer, &pos,
1477                                           gtk_text_buffer_get_insert (buffer));
1478         gtk_text_buffer_get_iter_at_mark (buffer, &prev_pos, mark);
1479
1480         if (!chat_input_text_get_word_from_iter (&prev_pos, &word_start, &word_end))
1481                 goto out;
1482
1483         if (!gtk_text_iter_in_range (&pos, &word_start, &word_end) &&
1484                         !gtk_text_iter_equal (&pos, &word_end)) {
1485                 str = gtk_text_buffer_get_text (buffer,
1486                                         &word_start, &word_end, FALSE);
1487
1488                 if (!empathy_spell_check (str)) {
1489                         gtk_text_buffer_apply_tag_by_name (buffer,
1490                                         "misspelled", &word_start, &word_end);
1491                 } else {
1492                         gtk_text_buffer_remove_tag_by_name (buffer,
1493                                         "misspelled", &word_start, &word_end);
1494                 }
1495
1496                 g_free (str);
1497         }
1498
1499 out:
1500         gtk_text_buffer_move_mark (buffer, mark, &pos);
1501 }
1502
1503 static gboolean
1504 empathy_isspace_cb (gunichar c,
1505                  gpointer data)
1506 {
1507         return g_unichar_isspace (c);
1508 }
1509
1510 static gboolean
1511 chat_input_key_press_event_cb (GtkWidget   *widget,
1512                                GdkEventKey *event,
1513                                EmpathyChat *chat)
1514 {
1515         EmpathyChatPriv *priv;
1516         GtkAdjustment  *adj;
1517         gdouble         val;
1518         GtkWidget      *text_view_sw;
1519
1520         priv = GET_PRIV (chat);
1521
1522         /* Catch ctrl+up/down so we can traverse messages we sent */
1523         if ((event->state & GDK_CONTROL_MASK) &&
1524             (event->keyval == GDK_Up ||
1525              event->keyval == GDK_Down)) {
1526                 GtkTextBuffer *buffer;
1527                 const gchar   *str;
1528
1529                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1530                 chat_input_history_update (chat, buffer);
1531
1532                 if (event->keyval == GDK_Up) {
1533                         str = chat_input_history_get_next (chat);
1534                 } else {
1535                         str = chat_input_history_get_prev (chat);
1536                 }
1537
1538                 g_signal_handlers_block_by_func (buffer,
1539                                                  chat_input_text_buffer_changed_cb,
1540                                                  chat);
1541                 gtk_text_buffer_set_text (buffer, str ? str : "", -1);
1542                 g_signal_handlers_unblock_by_func (buffer,
1543                                                    chat_input_text_buffer_changed_cb,
1544                                                    chat);
1545
1546                 return TRUE;
1547         }
1548
1549         /* Catch enter but not ctrl/shift-enter */
1550         if (IS_ENTER (event->keyval) &&
1551             !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1552                 GtkTextView *view;
1553
1554                 /* This is to make sure that kinput2 gets the enter. And if
1555                  * it's handled there we shouldn't send on it. This is because
1556                  * kinput2 uses Enter to commit letters. See:
1557                  * http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=104299
1558                  */
1559
1560                 view = GTK_TEXT_VIEW (chat->input_text_view);
1561                 if (gtk_text_view_im_context_filter_keypress (view, event)) {
1562                         gtk_text_view_reset_im_context (view);
1563                         return TRUE;
1564                 }
1565
1566                 chat_input_text_view_send (chat);
1567                 return TRUE;
1568         }
1569
1570         text_view_sw = gtk_widget_get_parent (GTK_WIDGET (chat->view));
1571
1572         if (IS_ENTER (event->keyval) &&
1573             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1574                 /* Newline for shift/control-enter. */
1575                 return FALSE;
1576         }
1577         if (!(event->state & GDK_CONTROL_MASK) &&
1578             event->keyval == GDK_Page_Up) {
1579                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1580                 gtk_adjustment_set_value (adj, gtk_adjustment_get_value (adj) - gtk_adjustment_get_page_size (adj));
1581                 return TRUE;
1582         }
1583         if ((event->state & GDK_CONTROL_MASK) != GDK_CONTROL_MASK &&
1584             event->keyval == GDK_Page_Down) {
1585                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1586                 val = MIN (gtk_adjustment_get_value (adj) + gtk_adjustment_get_page_size (adj),
1587                            gtk_adjustment_get_upper (adj) - gtk_adjustment_get_page_size (adj));
1588                 gtk_adjustment_set_value (adj, val);
1589                 return TRUE;
1590         }
1591         if (event->keyval == GDK_Escape) {
1592                 empathy_search_bar_hide (EMPATHY_SEARCH_BAR (priv->search_bar));
1593         }
1594         if (!(event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) &&
1595             event->keyval == GDK_Tab) {
1596                 GtkTextBuffer *buffer;
1597                 GtkTextIter    start, current;
1598                 gchar         *nick, *completed;
1599                 GList         *list, *completed_list;
1600                 gboolean       is_start_of_buffer;
1601
1602                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (EMPATHY_CHAT (chat)->input_text_view));
1603                 gtk_text_buffer_get_iter_at_mark (buffer, &current, gtk_text_buffer_get_insert (buffer));
1604
1605                 /* Get the start of the nick to complete. */
1606                 gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer));
1607                 if (gtk_text_iter_backward_find_char (&start, &empathy_isspace_cb, NULL, NULL)) {
1608                         gtk_text_iter_set_offset (&start, gtk_text_iter_get_offset (&start) + 1);
1609                 }
1610                 is_start_of_buffer = gtk_text_iter_is_start (&start);
1611
1612                 list = empathy_contact_list_get_members (EMPATHY_CONTACT_LIST (priv->tp_chat));
1613                 g_completion_add_items (priv->completion, list);
1614
1615                 nick = gtk_text_buffer_get_text (buffer, &start, &current, FALSE);
1616                 completed_list = g_completion_complete (priv->completion,
1617                                                         nick,
1618                                                         &completed);
1619
1620                 g_free (nick);
1621
1622                 if (completed) {
1623                         guint        len;
1624                         const gchar *text;
1625                         GString     *message = NULL;
1626                         GList       *l;
1627
1628                         gtk_text_buffer_delete (buffer, &start, &current);
1629
1630                         len = g_list_length (completed_list);
1631
1632                         if (len == 1) {
1633                                 /* If we only have one hit, use that text
1634                                  * instead of the text in completed since the
1635                                  * completed text will use the typed string
1636                                  * which might be cased all wrong.
1637                                  * Fixes #120876
1638                                  * */
1639                                 text = empathy_contact_get_name (completed_list->data);
1640                         } else {
1641                                 text = completed;
1642
1643                                 /* Print all hits to the scrollback view, so the
1644                                  * user knows what possibilities he has.
1645                                  * Fixes #599779
1646                                  * */
1647                                  message = g_string_new ("");
1648                                  for (l = completed_list; l != NULL; l = l->next) {
1649                                         g_string_append (message, empathy_contact_get_name (l->data));
1650                                         g_string_append (message, " - ");
1651                                  }
1652                                  empathy_chat_view_append_event (chat->view, message->str);
1653                                  g_string_free (message, TRUE);
1654                         }
1655
1656                         gtk_text_buffer_insert_at_cursor (buffer, text, strlen (text));
1657
1658                         if (len == 1 && is_start_of_buffer) {
1659                             gchar *complete_char;
1660
1661                             complete_char = g_settings_get_string (
1662                                     priv->gsettings_chat,
1663                                     EMPATHY_PREFS_CHAT_NICK_COMPLETION_CHAR);
1664
1665                             if (complete_char != NULL) {
1666                                 gtk_text_buffer_insert_at_cursor (buffer,
1667                                                                   complete_char,
1668                                                                   strlen (complete_char));
1669                                 gtk_text_buffer_insert_at_cursor (buffer, " ", 1);
1670                                 g_free (complete_char);
1671                             }
1672                         }
1673
1674                         g_free (completed);
1675                 }
1676
1677                 g_completion_clear_items (priv->completion);
1678
1679                 g_list_foreach (list, (GFunc) g_object_unref, NULL);
1680                 g_list_free (list);
1681
1682                 return TRUE;
1683         }
1684
1685         return FALSE;
1686 }
1687
1688 static gboolean
1689 chat_text_view_focus_in_event_cb (GtkWidget  *widget,
1690                                   GdkEvent   *event,
1691                                   EmpathyChat *chat)
1692 {
1693         gtk_widget_grab_focus (chat->input_text_view);
1694
1695         return TRUE;
1696 }
1697
1698 static gboolean
1699 chat_input_set_size_request_idle (gpointer sw)
1700 {
1701         gtk_widget_set_size_request (sw, -1, MAX_INPUT_HEIGHT);
1702
1703         return FALSE;
1704 }
1705
1706 static void
1707 chat_input_size_request_cb (GtkWidget      *widget,
1708                             GtkRequisition *requisition,
1709                             EmpathyChat    *chat)
1710 {
1711         EmpathyChatPriv *priv = GET_PRIV (chat);
1712         GtkWidget       *sw;
1713
1714         sw = gtk_widget_get_parent (widget);
1715         if (requisition->height >= MAX_INPUT_HEIGHT && !priv->has_input_vscroll) {
1716                 g_idle_add (chat_input_set_size_request_idle, sw);
1717                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
1718                                                 GTK_POLICY_NEVER,
1719                                                 GTK_POLICY_ALWAYS);
1720                 priv->has_input_vscroll = TRUE;
1721         }
1722
1723         if (requisition->height < MAX_INPUT_HEIGHT && priv->has_input_vscroll) {
1724                 gtk_widget_set_size_request (sw, -1, -1);
1725                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
1726                                                 GTK_POLICY_NEVER,
1727                                                 GTK_POLICY_NEVER);
1728                 priv->has_input_vscroll = FALSE;
1729         }
1730 }
1731
1732 static void
1733 chat_input_realize_cb (GtkWidget   *widget,
1734                        EmpathyChat *chat)
1735 {
1736         DEBUG ("Setting focus to the input text view");
1737         if (gtk_widget_is_sensitive (widget)) {
1738                 gtk_widget_grab_focus (widget);
1739         }
1740 }
1741
1742 static void
1743 chat_insert_smiley_activate_cb (EmpathySmileyManager *manager,
1744                                 EmpathySmiley        *smiley,
1745                                 gpointer              user_data)
1746 {
1747         EmpathyChat   *chat = EMPATHY_CHAT (user_data);
1748         GtkTextBuffer *buffer;
1749         GtkTextIter    iter;
1750
1751         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1752
1753         gtk_text_buffer_get_end_iter (buffer, &iter);
1754         gtk_text_buffer_insert (buffer, &iter, smiley->str, -1);
1755
1756         gtk_text_buffer_get_end_iter (buffer, &iter);
1757         gtk_text_buffer_insert (buffer, &iter, " ", -1);
1758 }
1759
1760 typedef struct {
1761         EmpathyChat  *chat;
1762         gchar       *word;
1763
1764         GtkTextIter  start;
1765         GtkTextIter  end;
1766 } EmpathyChatSpell;
1767
1768 static EmpathyChatSpell *
1769 chat_spell_new (EmpathyChat  *chat,
1770                 const gchar *word,
1771                 GtkTextIter  start,
1772                 GtkTextIter  end)
1773 {
1774         EmpathyChatSpell *chat_spell;
1775
1776         chat_spell = g_slice_new0 (EmpathyChatSpell);
1777
1778         chat_spell->chat = g_object_ref (chat);
1779         chat_spell->word = g_strdup (word);
1780         chat_spell->start = start;
1781         chat_spell->end = end;
1782
1783         return chat_spell;
1784 }
1785
1786 static void
1787 chat_spell_free (EmpathyChatSpell *chat_spell)
1788 {
1789         g_object_unref (chat_spell->chat);
1790         g_free (chat_spell->word);
1791         g_slice_free (EmpathyChatSpell, chat_spell);
1792 }
1793
1794 static void
1795 chat_spelling_menu_activate_cb (GtkMenuItem     *menu_item,
1796                                                 EmpathyChatSpell *chat_spell)
1797 {
1798     empathy_chat_correct_word (chat_spell->chat,
1799                                &(chat_spell->start),
1800                                &(chat_spell->end),
1801                                gtk_menu_item_get_label (menu_item));
1802 }
1803
1804 static GtkWidget *
1805 chat_spelling_build_menu (EmpathyChatSpell *chat_spell)
1806 {
1807     GtkWidget *menu, *menu_item;
1808     GList     *suggestions, *l;
1809
1810     menu = gtk_menu_new ();
1811     suggestions = empathy_spell_get_suggestions (chat_spell->word);
1812     if (suggestions == NULL) {
1813         menu_item = gtk_menu_item_new_with_label (_("(No Suggestions)"));
1814         gtk_widget_set_sensitive (menu_item, FALSE);
1815         gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
1816     } else {
1817         for (l = suggestions; l; l = l->next) {
1818             menu_item = gtk_menu_item_new_with_label (l->data);
1819             g_signal_connect (G_OBJECT (menu_item),
1820                           "activate",
1821                           G_CALLBACK (chat_spelling_menu_activate_cb),
1822                           chat_spell);
1823             gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
1824         }
1825     }
1826     empathy_spell_free_suggestions (suggestions);
1827
1828     gtk_widget_show_all (menu);
1829
1830     return menu;
1831 }
1832
1833 static void
1834 chat_text_send_cb (GtkMenuItem *menuitem,
1835                    EmpathyChat *chat)
1836 {
1837         chat_input_text_view_send (chat);
1838 }
1839
1840 static void
1841 chat_input_populate_popup_cb (GtkTextView *view,
1842                               GtkMenu     *menu,
1843                               EmpathyChat *chat)
1844 {
1845         EmpathyChatPriv      *priv;
1846         GtkTextBuffer        *buffer;
1847         GtkTextTagTable      *table;
1848         GtkTextTag           *tag;
1849         gint                  x, y;
1850         GtkTextIter           iter, start, end;
1851         GtkWidget            *item;
1852         gchar                *str = NULL;
1853         EmpathyChatSpell     *chat_spell;
1854         GtkWidget            *spell_menu;
1855         EmpathySmileyManager *smiley_manager;
1856         GtkWidget            *smiley_menu;
1857         GtkWidget            *image;
1858
1859         priv = GET_PRIV (chat);
1860         buffer = gtk_text_view_get_buffer (view);
1861
1862         /* Add the emoticon menu. */
1863         item = gtk_separator_menu_item_new ();
1864         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1865         gtk_widget_show (item);
1866
1867         item = gtk_image_menu_item_new_with_mnemonic (_("Insert Smiley"));
1868         image = gtk_image_new_from_icon_name ("face-smile",
1869                                               GTK_ICON_SIZE_MENU);
1870         gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
1871         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1872         gtk_widget_show (item);
1873
1874         smiley_manager = empathy_smiley_manager_dup_singleton ();
1875         smiley_menu = empathy_smiley_menu_new (smiley_manager,
1876                                                chat_insert_smiley_activate_cb,
1877                                                chat);
1878         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), smiley_menu);
1879         g_object_unref (smiley_manager);
1880
1881         /* Add the Send menu item. */
1882         gtk_text_buffer_get_bounds (buffer, &start, &end);
1883         str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1884         if (!EMP_STR_EMPTY (str)) {
1885                 item = gtk_menu_item_new_with_mnemonic (_("_Send"));
1886                 g_signal_connect (G_OBJECT (item), "activate",
1887                                   G_CALLBACK (chat_text_send_cb), chat);
1888                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1889                 gtk_widget_show (item);
1890         }
1891         str = NULL;
1892
1893         /* Add the spell check menu item. */
1894         table = gtk_text_buffer_get_tag_table (buffer);
1895         tag = gtk_text_tag_table_lookup (table, "misspelled");
1896         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
1897         gtk_text_view_window_to_buffer_coords (GTK_TEXT_VIEW (view),
1898                                                GTK_TEXT_WINDOW_WIDGET,
1899                                                x, y,
1900                                                &x, &y);
1901         gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW (view), &iter, x, y);
1902         start = end = iter;
1903         if (gtk_text_iter_backward_to_tag_toggle (&start, tag) &&
1904             gtk_text_iter_forward_to_tag_toggle (&end, tag)) {
1905
1906                 str = gtk_text_buffer_get_text (buffer,
1907                                                 &start, &end, FALSE);
1908         }
1909         if (!EMP_STR_EMPTY (str)) {
1910                 chat_spell = chat_spell_new (chat, str, start, end);
1911                 g_object_set_data_full (G_OBJECT (menu),
1912                                         "chat_spell", chat_spell,
1913                                         (GDestroyNotify) chat_spell_free);
1914
1915                 item = gtk_separator_menu_item_new ();
1916                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1917                 gtk_widget_show (item);
1918
1919                 item = gtk_image_menu_item_new_with_mnemonic (_("_Spelling Suggestions"));
1920                 image = gtk_image_new_from_icon_name (GTK_STOCK_SPELL_CHECK,
1921                                                       GTK_ICON_SIZE_MENU);
1922                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
1923
1924                 spell_menu = chat_spelling_build_menu (chat_spell);
1925                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), spell_menu);
1926
1927                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1928                 gtk_widget_show (item);
1929         }
1930 }
1931
1932
1933 #ifdef ENABLE_TPL
1934 static gboolean
1935 chat_log_filter (TplLogEntry *log,
1936                  gpointer user_data)
1937 #else
1938 static gboolean
1939 chat_log_filter (EmpathyMessage *message,
1940                  gpointer user_data)
1941 #endif /* ENABLE_TPL */
1942 {
1943         EmpathyChat *chat = user_data;
1944 #ifdef ENABLE_TPL
1945         EmpathyMessage *message;
1946 #endif /* ENABLE_TPL */
1947         EmpathyChatPriv *priv = GET_PRIV (chat);
1948         const GList *pending;
1949
1950 #ifdef ENABLE_TPL
1951         g_return_val_if_fail (TPL_IS_LOG_ENTRY (log), FALSE);
1952 #else
1953         g_return_val_if_fail (EMPATHY_IS_MESSAGE (message), FALSE);
1954 #endif /* ENABLE_TPL */
1955         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
1956
1957         pending = empathy_tp_chat_get_pending_messages (priv->tp_chat);
1958 #ifdef ENABLE_TPL
1959         message = empathy_message_from_tpl_log_entry (log);
1960 #endif /* ENABLE_TPL */
1961
1962         for (; pending; pending = g_list_next (pending)) {
1963                 if (empathy_message_equal (message, pending->data)) {
1964                         return FALSE;
1965                 }
1966         }
1967 #ifdef ENABLE_TPL
1968         g_object_unref (message);
1969 #endif
1970         return TRUE;
1971 }
1972
1973
1974 static void
1975 show_pending_messages (EmpathyChat *chat) {
1976         EmpathyChatPriv *priv = GET_PRIV (chat);
1977         const GList *messages, *l;
1978
1979         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1980
1981         if (chat->view == NULL || priv->tp_chat == NULL)
1982                 return;
1983
1984         if (!priv->can_show_pending)
1985                 return;
1986
1987         messages = empathy_tp_chat_get_pending_messages (priv->tp_chat);
1988
1989         for (l = messages; l != NULL ; l = g_list_next (l)) {
1990                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
1991                 chat_message_received (chat, message);
1992         }
1993 }
1994
1995
1996 #ifdef ENABLE_TPL
1997 static void
1998 got_filtered_messages_cb (GObject *manager,
1999                 GAsyncResult *result,
2000                 gpointer user_data)
2001 {
2002         GList *l;
2003         GList *messages;
2004         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2005         EmpathyChatPriv *priv = GET_PRIV (chat);
2006         GError *error = NULL;
2007
2008         if (!tpl_log_manager_get_filtered_messages_finish (TPL_LOG_MANAGER (manager),
2009                 result, &messages, &error)) {
2010                 DEBUG ("%s. Aborting.", error->message);
2011                 empathy_chat_view_append_event (chat->view,
2012                         _("Failed to retrieve recent logs"));
2013                 g_error_free (error);
2014                 goto out;
2015         }
2016
2017         for (l = messages; l; l = g_list_next (l)) {
2018                 EmpathyMessage *message;
2019                 g_assert (TPL_IS_LOG_ENTRY (l->data));
2020
2021                 message = empathy_message_from_tpl_log_entry (l->data);
2022                 g_object_unref (l->data);
2023
2024                 empathy_chat_view_append_message (chat->view, message);
2025                 g_object_unref (message);
2026         }
2027         g_list_free (messages);
2028
2029 out:
2030         /* in case of TPL error, skip backlog and show pending messages */
2031         priv->can_show_pending = TRUE;
2032         show_pending_messages (chat);
2033
2034         /* FIXME: See Bug#610994, we are forcing the ACK of the queue. See comments
2035          * about it in EmpathyChatPriv definition */
2036         priv->retrieving_backlogs = FALSE;
2037         empathy_chat_messages_read (chat);
2038
2039         /* Turn back on scrolling */
2040         empathy_chat_view_scroll (chat->view, TRUE);
2041 }
2042 #endif /* ENABLE_TPL */
2043
2044
2045 static void
2046 chat_add_logs (EmpathyChat *chat)
2047 {
2048         EmpathyChatPriv *priv = GET_PRIV (chat);
2049         gboolean         is_chatroom;
2050 #ifndef ENABLE_TPL
2051         GList           *messages, *l;
2052 #endif /* ENABLE_TPL */
2053
2054         if (!priv->id) {
2055                 return;
2056         }
2057
2058         /* Turn off scrolling temporarily */
2059         empathy_chat_view_scroll (chat->view, FALSE);
2060
2061         /* Add messages from last conversation */
2062         is_chatroom = priv->handle_type == TP_HANDLE_TYPE_ROOM;
2063
2064 #ifndef ENABLE_TPL
2065         messages = empathy_log_manager_get_filtered_messages (priv->log_manager,
2066                                                               priv->account,
2067                                                               priv->id,
2068                                                               is_chatroom,
2069                                                               5,
2070                                                               chat_log_filter,
2071                                                               chat);
2072
2073         for (l = messages; l; l = g_list_next (l)) {
2074                 empathy_chat_view_append_message (chat->view, l->data);
2075                 g_object_unref (l->data);
2076         }
2077
2078         g_list_free (messages);
2079
2080         /* Turn back on scrolling */
2081         empathy_chat_view_scroll (chat->view, TRUE);
2082 #else
2083         priv->retrieving_backlogs = TRUE;
2084         tpl_log_manager_get_filtered_messages_async (priv->log_manager,
2085                                                               priv->account,
2086                                                               priv->id,
2087                                                               is_chatroom,
2088                                                               5,
2089                                                               chat_log_filter,
2090                                                               chat,
2091                                                               got_filtered_messages_cb,
2092                                                               (gpointer) chat);
2093 #endif /* ENABLE_TPL */
2094 }
2095
2096 static gint
2097 chat_contacts_completion_func (const gchar *s1,
2098                                const gchar *s2,
2099                                gsize        n)
2100 {
2101         gchar *tmp, *nick1, *nick2;
2102         gint   ret;
2103
2104         if (s1 == s2) {
2105                 return 0;
2106         }
2107         if (!s1 || !s2) {
2108                 return s1 ? -1 : +1;
2109         }
2110
2111         tmp = g_utf8_normalize (s1, -1, G_NORMALIZE_DEFAULT);
2112         nick1 = g_utf8_casefold (tmp, -1);
2113         g_free (tmp);
2114
2115         tmp = g_utf8_normalize (s2, -1, G_NORMALIZE_DEFAULT);
2116         nick2 = g_utf8_casefold (tmp, -1);
2117         g_free (tmp);
2118
2119         ret = strncmp (nick1, nick2, n);
2120
2121         g_free (nick1);
2122         g_free (nick2);
2123
2124         return ret;
2125 }
2126
2127 static gchar *
2128 build_part_message (guint           reason,
2129                     const gchar    *name,
2130                     EmpathyContact *actor,
2131                     const gchar    *message)
2132 {
2133         GString *s = g_string_new ("");
2134         const gchar *actor_name = NULL;
2135
2136         if (actor != NULL) {
2137                 actor_name = empathy_contact_get_name (actor);
2138         }
2139
2140         /* Having an actor only really makes sense for a few actions... */
2141         switch (reason) {
2142         case TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE:
2143                 g_string_append_printf (s, _("%s has disconnected"), name);
2144                 break;
2145         case TP_CHANNEL_GROUP_CHANGE_REASON_KICKED:
2146                 if (actor_name != NULL) {
2147                         /* translators: reverse the order of these arguments
2148                          * if the kicked should come before the kicker in your locale.
2149                          */
2150                         g_string_append_printf (s, _("%1$s was kicked by %2$s"),
2151                                 name, actor_name);
2152                 } else {
2153                         g_string_append_printf (s, _("%s was kicked"), name);
2154                 }
2155                 break;
2156         case TP_CHANNEL_GROUP_CHANGE_REASON_BANNED:
2157                 if (actor_name != NULL) {
2158                         /* translators: reverse the order of these arguments
2159                          * if the banned should come before the banner in your locale.
2160                          */
2161                         g_string_append_printf (s, _("%1$s was banned by %2$s"),
2162                                 name, actor_name);
2163                 } else {
2164                         g_string_append_printf (s, _("%s was banned"), name);
2165                 }
2166                 break;
2167         default:
2168                 g_string_append_printf (s, _("%s has left the room"), name);
2169         }
2170
2171         if (!EMP_STR_EMPTY (message)) {
2172                 /* Note to translators: this string is appended to
2173                  * notifications like "foo has left the room", with the message
2174                  * given by the user living the room. If this poses a problem,
2175                  * please let us know. :-)
2176                  */
2177                 g_string_append_printf (s, _(" (%s)"), message);
2178         }
2179
2180         return g_string_free (s, FALSE);
2181 }
2182
2183 static void
2184 chat_members_changed_cb (EmpathyTpChat  *tp_chat,
2185                          EmpathyContact *contact,
2186                          EmpathyContact *actor,
2187                          guint           reason,
2188                          gchar          *message,
2189                          gboolean        is_member,
2190                          EmpathyChat    *chat)
2191 {
2192         EmpathyChatPriv *priv = GET_PRIV (chat);
2193         const gchar *name = empathy_contact_get_name (contact);
2194         gchar *str;
2195
2196         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED != reason);
2197
2198         if (priv->block_events_timeout_id != 0)
2199                 return;
2200
2201         if (is_member) {
2202                 str = g_strdup_printf (_("%s has joined the room"),
2203                                        name);
2204         } else {
2205                 str = build_part_message (reason, name, actor, message);
2206         }
2207
2208         empathy_chat_view_append_event (chat->view, str);
2209         g_free (str);
2210 }
2211
2212 static void
2213 chat_member_renamed_cb (EmpathyTpChat  *tp_chat,
2214                          EmpathyContact *old_contact,
2215                          EmpathyContact *new_contact,
2216                          guint           reason,
2217                          gchar          *message,
2218                          EmpathyChat    *chat)
2219 {
2220         EmpathyChatPriv *priv = GET_PRIV (chat);
2221
2222         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED == reason);
2223
2224         if (priv->block_events_timeout_id == 0) {
2225                 gchar *str;
2226
2227                 str = g_strdup_printf (_("%s is now known as %s"),
2228                                        empathy_contact_get_name (old_contact),
2229                                        empathy_contact_get_name (new_contact));
2230                 empathy_chat_view_append_event (chat->view, str);
2231                 g_free (str);
2232         }
2233
2234 }
2235
2236 static gboolean
2237 chat_reset_size_request (gpointer widget)
2238 {
2239         gtk_widget_set_size_request (widget, -1, -1);
2240
2241         return FALSE;
2242 }
2243
2244 static void
2245 chat_update_contacts_visibility (EmpathyChat *chat,
2246                          gboolean show)
2247 {
2248         EmpathyChatPriv *priv = GET_PRIV (chat);
2249         GtkAllocation allocation;
2250
2251         if (!priv->scrolled_window_contacts) {
2252                 return;
2253         }
2254
2255         if (priv->remote_contact != NULL) {
2256                 show = FALSE;
2257         }
2258
2259         if (show && priv->contact_list_view == NULL) {
2260                 EmpathyContactListStore *store;
2261                 gint                     min_width;
2262
2263                 /* We are adding the contact list to the chat, we don't want the
2264                  * chat view to become too small. If the chat view is already
2265                  * smaller than 250 make sure that size won't change. If the
2266                  * chat view is bigger the contact list will take some space on
2267                  * it but we make sure the chat view don't become smaller than
2268                  * 250. Relax the size request once the resize is done */
2269                 gtk_widget_get_allocation (priv->vbox_left, &allocation);
2270                 min_width = MIN (allocation.width, 250);
2271                 gtk_widget_set_size_request (priv->vbox_left, min_width, -1);
2272                 g_idle_add (chat_reset_size_request, priv->vbox_left);
2273
2274                 if (priv->contacts_width > 0) {
2275                         gtk_paned_set_position (GTK_PANED (priv->hpaned),
2276                                                 priv->contacts_width);
2277                 }
2278
2279                 store = empathy_contact_list_store_new (
2280                                 EMPATHY_CONTACT_LIST (priv->tp_chat));
2281                 empathy_contact_list_store_set_show_groups (
2282                                 EMPATHY_CONTACT_LIST_STORE (store), FALSE);
2283
2284                 priv->contact_list_view = GTK_WIDGET (empathy_contact_list_view_new (store,
2285                         EMPATHY_CONTACT_LIST_FEATURE_CONTACT_TOOLTIP,
2286                         EMPATHY_CONTACT_FEATURE_CHAT |
2287                         EMPATHY_CONTACT_FEATURE_CALL |
2288                         EMPATHY_CONTACT_FEATURE_LOG |
2289                         EMPATHY_CONTACT_FEATURE_INFO));
2290                 gtk_container_add (GTK_CONTAINER (priv->scrolled_window_contacts),
2291                                    priv->contact_list_view);
2292                 gtk_widget_show (priv->contact_list_view);
2293                 gtk_widget_show (priv->scrolled_window_contacts);
2294                 g_object_unref (store);
2295         } else if (!show) {
2296                 priv->contacts_width = gtk_paned_get_position (GTK_PANED (priv->hpaned));
2297                 gtk_widget_hide (priv->scrolled_window_contacts);
2298                 if (priv->contact_list_view != NULL) {
2299                         gtk_widget_destroy (priv->contact_list_view);
2300                         priv->contact_list_view = NULL;
2301                 }
2302         }
2303 }
2304
2305 void
2306 empathy_chat_set_show_contacts (EmpathyChat *chat,
2307                                 gboolean     show)
2308 {
2309         EmpathyChatPriv *priv = GET_PRIV (chat);
2310
2311         priv->show_contacts = show;
2312
2313         chat_update_contacts_visibility (chat, show);
2314
2315         g_object_notify (G_OBJECT (chat), "show-contacts");
2316 }
2317
2318 static void
2319 chat_remote_contact_changed_cb (EmpathyChat *chat)
2320 {
2321         EmpathyChatPriv *priv = GET_PRIV (chat);
2322
2323         if (priv->remote_contact != NULL) {
2324                 g_object_unref (priv->remote_contact);
2325                 priv->remote_contact = NULL;
2326         }
2327
2328         g_free (priv->id);
2329
2330         priv->id = g_strdup (empathy_tp_chat_get_id (priv->tp_chat));
2331         priv->remote_contact = empathy_tp_chat_get_remote_contact (priv->tp_chat);
2332         if (priv->remote_contact != NULL) {
2333                 g_object_ref (priv->remote_contact);
2334                 priv->handle_type = TP_HANDLE_TYPE_CONTACT;
2335         }
2336         else if (priv->tp_chat != NULL) {
2337                 TpChannel *channel;
2338
2339                 channel = empathy_tp_chat_get_channel (priv->tp_chat);
2340                 g_object_get (channel, "handle-type", &priv->handle_type, NULL);
2341         }
2342
2343         chat_update_contacts_visibility (chat, priv->show_contacts);
2344
2345         g_object_notify (G_OBJECT (chat), "remote-contact");
2346         g_object_notify (G_OBJECT (chat), "id");
2347 }
2348
2349 static void
2350 chat_destroy_cb (EmpathyTpChat *tp_chat,
2351                  EmpathyChat   *chat)
2352 {
2353         EmpathyChatPriv *priv;
2354
2355         priv = GET_PRIV (chat);
2356
2357         if (!priv->tp_chat) {
2358                 return;
2359         }
2360
2361         chat_composing_remove_timeout (chat);
2362         g_object_unref (priv->tp_chat);
2363         priv->tp_chat = NULL;
2364         g_object_notify (G_OBJECT (chat), "tp-chat");
2365
2366         empathy_chat_view_append_event (chat->view, _("Disconnected"));
2367         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
2368
2369         chat_update_contacts_visibility (chat, FALSE);
2370 }
2371
2372 static gboolean
2373 update_misspelled_words (gpointer data)
2374 {
2375         EmpathyChat *chat = EMPATHY_CHAT (data);
2376         GtkTextBuffer *buffer;
2377         GtkTextIter iter;
2378         gint length;
2379
2380         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2381
2382         gtk_text_buffer_get_end_iter (buffer, &iter);
2383         length = gtk_text_iter_get_offset (&iter);
2384         chat_input_text_buffer_insert_text_cb (buffer, &iter,
2385                                                NULL, length, chat);
2386         return FALSE;
2387 }
2388
2389 static void
2390 conf_spell_checking_cb (GSettings *gsettings_chat,
2391                         const gchar *key,
2392                         gpointer user_data)
2393 {
2394         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2395         EmpathyChatPriv *priv = GET_PRIV (chat);
2396         gboolean spell_checker;
2397         GtkTextBuffer *buffer;
2398
2399         if (strcmp (key, EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED) != 0)
2400                 return;
2401
2402         spell_checker = g_settings_get_boolean (gsettings_chat,
2403                         EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED);
2404
2405         if (!empathy_spell_supported ()) {
2406                 spell_checker = FALSE;
2407         }
2408
2409         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2410
2411         if (spell_checker == priv->spell_checking_enabled) {
2412                 if (spell_checker) {
2413                         /* Possibly changed dictionaries,
2414                          * update misspelled words. Need to do so in idle
2415                          * so the spell checker is updated. */
2416                         g_idle_add (update_misspelled_words, chat);
2417                 }
2418
2419                 return;
2420         }
2421
2422         if (spell_checker) {
2423                 GtkTextIter iter;
2424
2425                 priv->notify_cursor_position_id = tp_g_signal_connect_object  (
2426                                 buffer, "notify::cursor-position",
2427                                 G_CALLBACK (chat_input_text_buffer_notify_cursor_position_cb),
2428                                 chat, 0);
2429                 priv->insert_text_id = tp_g_signal_connect_object  (
2430                                 buffer, "insert-text",
2431                                 G_CALLBACK (chat_input_text_buffer_insert_text_cb),
2432                                 chat, G_CONNECT_AFTER);
2433                 priv->delete_range_id = tp_g_signal_connect_object  (
2434                                 buffer, "delete-range",
2435                                 G_CALLBACK (chat_input_text_buffer_delete_range_cb),
2436                                 chat, G_CONNECT_AFTER);
2437
2438                 gtk_text_buffer_create_tag (buffer, "misspelled",
2439                                             "underline", PANGO_UNDERLINE_ERROR,
2440                                             NULL);
2441
2442                 gtk_text_buffer_get_iter_at_mark (buffer, &iter,
2443                                                   gtk_text_buffer_get_insert (buffer));
2444                 gtk_text_buffer_create_mark (buffer, "previous-cursor-position",
2445                                              &iter, TRUE);
2446
2447                 /* Mark misspelled words in the existing buffer.
2448                  * Need to do so in idle so the spell checker is updated. */
2449                 g_idle_add (update_misspelled_words, chat);
2450         } else {
2451                 GtkTextTagTable *table;
2452                 GtkTextTag *tag;
2453
2454                 g_signal_handler_disconnect (buffer, priv->notify_cursor_position_id);
2455                 priv->notify_cursor_position_id = 0;
2456                 g_signal_handler_disconnect (buffer, priv->insert_text_id);
2457                 priv->insert_text_id = 0;
2458                 g_signal_handler_disconnect (buffer, priv->delete_range_id);
2459                 priv->delete_range_id = 0;
2460
2461                 table = gtk_text_buffer_get_tag_table (buffer);
2462                 tag = gtk_text_tag_table_lookup (table, "misspelled");
2463                 gtk_text_tag_table_remove (table, tag);
2464
2465                 gtk_text_buffer_delete_mark_by_name (buffer,
2466                                                      "previous-cursor-position");
2467         }
2468
2469         priv->spell_checking_enabled = spell_checker;
2470 }
2471
2472 static gboolean
2473 chat_hpaned_pos_changed_cb (GtkWidget* hpaned, gpointer user_data)
2474 {
2475         GSettings *gsettings_chat = g_settings_new (EMPATHY_PREFS_CHAT_SCHEMA);
2476         gint hpaned_pos;
2477
2478         hpaned_pos = gtk_paned_get_position (GTK_PANED(hpaned));
2479         g_settings_set_int (gsettings_chat,
2480                             EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
2481                             hpaned_pos);
2482
2483         g_object_unref (gsettings_chat);
2484
2485         return TRUE;
2486 }
2487
2488 static void
2489 chat_create_ui (EmpathyChat *chat)
2490 {
2491         EmpathyChatPriv *priv = GET_PRIV (chat);
2492         GtkBuilder      *gui;
2493         GList           *list = NULL;
2494         gchar           *filename;
2495         GtkTextBuffer   *buffer;
2496         gint              paned_pos;
2497
2498         filename = empathy_file_lookup ("empathy-chat.ui",
2499                                         "libempathy-gtk");
2500         gui = empathy_builder_get_file (filename,
2501                                         "chat_widget", &priv->widget,
2502                                         "hpaned", &priv->hpaned,
2503                                         "vbox_left", &priv->vbox_left,
2504                                         "scrolled_window_chat", &priv->scrolled_window_chat,
2505                                         "scrolled_window_input", &priv->scrolled_window_input,
2506                                         "hbox_topic", &priv->hbox_topic,
2507                                         "expander_topic", &priv->expander_topic,
2508                                         "label_topic", &priv->label_topic,
2509                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
2510                                         "info_bar_vbox", &priv->info_bar_vbox,
2511                                         NULL);
2512
2513         empathy_builder_connect (gui, chat,
2514                 "expander_topic", "notify::expanded", chat_topic_expander_activate_cb,
2515                 "label_topic", "size-allocate", chat_topic_label_size_allocate_cb,
2516                 "label_topic", "size-request", chat_topic_label_size_request_cb,
2517                 NULL);
2518
2519         g_free (filename);
2520
2521         /* Add message view. */
2522         chat->view = empathy_theme_manager_create_view (empathy_theme_manager_get ());
2523         /* If this is a GtkTextView, it's set as a drag destination for text/plain
2524            and other types, even though it's non-editable and doesn't accept any
2525            drags.  This steals drag motion for anything inside the scrollbars,
2526            making drag destinations on chat windows far less useful.
2527          */
2528         gtk_drag_dest_unset (GTK_WIDGET (chat->view));
2529         g_signal_connect (chat->view, "focus_in_event",
2530                           G_CALLBACK (chat_text_view_focus_in_event_cb),
2531                           chat);
2532         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
2533                            GTK_WIDGET (chat->view));
2534         gtk_widget_show (GTK_WIDGET (chat->view));
2535
2536         /* Add input GtkTextView */
2537         chat->input_text_view = g_object_new (GTK_TYPE_TEXT_VIEW,
2538                                               "pixels-above-lines", 2,
2539                                               "pixels-below-lines", 2,
2540                                               "pixels-inside-wrap", 1,
2541                                               "right-margin", 2,
2542                                               "left-margin", 2,
2543                                               "wrap-mode", GTK_WRAP_WORD_CHAR,
2544                                               NULL);
2545         g_signal_connect (chat->input_text_view, "key-press-event",
2546                           G_CALLBACK (chat_input_key_press_event_cb),
2547                           chat);
2548         g_signal_connect (chat->input_text_view, "size-request",
2549                           G_CALLBACK (chat_input_size_request_cb),
2550                           chat);
2551         g_signal_connect (chat->input_text_view, "realize",
2552                           G_CALLBACK (chat_input_realize_cb),
2553                           chat);
2554         g_signal_connect (chat->input_text_view, "populate-popup",
2555                           G_CALLBACK (chat_input_populate_popup_cb),
2556                           chat);
2557         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2558         tp_g_signal_connect_object  (buffer, "changed",
2559                           G_CALLBACK (chat_input_text_buffer_changed_cb),
2560                           chat, 0);
2561         tp_g_signal_connect_object (priv->gsettings_chat,
2562                         "changed::" EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
2563                         G_CALLBACK (conf_spell_checking_cb), chat, 0);
2564         conf_spell_checking_cb (priv->gsettings_chat,
2565                                 EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED, chat);
2566         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
2567                            chat->input_text_view);
2568         gtk_widget_show (chat->input_text_view);
2569
2570         /* Add the (invisible) search bar */
2571         priv->search_bar = empathy_search_bar_new (chat->view);
2572         gtk_box_pack_start (GTK_BOX(priv->vbox_left),
2573                             priv->search_bar,
2574                             FALSE, FALSE, 0);
2575         gtk_box_reorder_child (GTK_BOX(priv->vbox_left), priv->search_bar, 1);
2576
2577         /* Initialy hide the topic, will be shown if not empty */
2578         gtk_widget_hide (priv->hbox_topic);
2579
2580         g_signal_connect (priv->hpaned, "notify::position",
2581                           G_CALLBACK (chat_hpaned_pos_changed_cb),
2582                           NULL);
2583
2584         /* Load the paned position */
2585         paned_pos = g_settings_get_int (priv->gsettings_ui,
2586                         EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS);
2587         if (paned_pos != 0)
2588                 gtk_paned_set_position (GTK_PANED(priv->hpaned), paned_pos);
2589
2590         /* Set widget focus order */
2591         list = g_list_append (NULL, priv->search_bar);
2592         list = g_list_append (list, priv->scrolled_window_input);
2593         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
2594         g_list_free (list);
2595
2596         list = g_list_append (NULL, priv->vbox_left);
2597         list = g_list_append (list, priv->scrolled_window_contacts);
2598         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
2599         g_list_free (list);
2600
2601         list = g_list_append (NULL, priv->hpaned);
2602         list = g_list_append (list, priv->hbox_topic);
2603         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
2604         g_list_free (list);
2605
2606         /* Add the main widget in the chat widget */
2607         gtk_container_add (GTK_CONTAINER (chat), priv->widget);
2608         g_object_unref (gui);
2609 }
2610
2611 static void
2612 chat_size_request (GtkWidget      *widget,
2613                    GtkRequisition *requisition)
2614 {
2615   GtkBin *bin = GTK_BIN (widget);
2616   GtkWidget *child;
2617
2618   requisition->width = gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2;
2619   requisition->height = gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2;
2620
2621   child = gtk_bin_get_child (bin);
2622
2623   if (child && gtk_widget_get_visible (child))
2624     {
2625       GtkRequisition child_requisition;
2626
2627       gtk_widget_size_request (child, &child_requisition);
2628
2629       requisition->width += child_requisition.width;
2630       requisition->height += child_requisition.height;
2631     }
2632 }
2633
2634 static void
2635 chat_size_allocate (GtkWidget     *widget,
2636                     GtkAllocation *allocation)
2637 {
2638   GtkBin *bin = GTK_BIN (widget);
2639   GtkAllocation child_allocation;
2640   GtkWidget *child;
2641
2642   gtk_widget_set_allocation (widget, allocation);
2643
2644   child = gtk_bin_get_child (bin);
2645
2646   if (child && gtk_widget_get_visible (child))
2647     {
2648       child_allocation.x = allocation->x + gtk_container_get_border_width (GTK_CONTAINER (widget));
2649       child_allocation.y = allocation->y + gtk_container_get_border_width (GTK_CONTAINER (widget));
2650       child_allocation.width = MAX (allocation->width - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2651       child_allocation.height = MAX (allocation->height - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2652
2653       gtk_widget_size_allocate (child, &child_allocation);
2654     }
2655 }
2656
2657 static void
2658 chat_finalize (GObject *object)
2659 {
2660         EmpathyChat     *chat;
2661         EmpathyChatPriv *priv;
2662
2663         chat = EMPATHY_CHAT (object);
2664         priv = GET_PRIV (chat);
2665
2666         DEBUG ("Finalized: %p", object);
2667
2668         g_object_unref (priv->gsettings_chat);
2669         g_object_unref (priv->gsettings_ui);
2670
2671         g_list_foreach (priv->input_history, (GFunc) chat_input_history_entry_free, NULL);
2672         g_list_free (priv->input_history);
2673
2674         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
2675         g_list_free (priv->compositors);
2676
2677         chat_composing_remove_timeout (chat);
2678
2679         g_object_unref (priv->account_manager);
2680         g_object_unref (priv->log_manager);
2681
2682         if (priv->tp_chat) {
2683                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2684                         chat_destroy_cb, chat);
2685                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2686                         chat_message_received_cb, chat);
2687                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2688                         chat_send_error_cb, chat);
2689                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2690                         chat_state_changed_cb, chat);
2691                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2692                         chat_property_changed_cb, chat);
2693                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2694                         chat_members_changed_cb, chat);
2695                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2696                         chat_remote_contact_changed_cb, chat);
2697                 empathy_tp_chat_leave (priv->tp_chat);
2698                 g_object_unref (priv->tp_chat);
2699         }
2700         if (priv->account) {
2701                 g_object_unref (priv->account);
2702         }
2703         if (priv->remote_contact) {
2704                 g_object_unref (priv->remote_contact);
2705         }
2706
2707         if (priv->block_events_timeout_id) {
2708                 g_source_remove (priv->block_events_timeout_id);
2709         }
2710
2711         g_free (priv->id);
2712         g_free (priv->name);
2713         g_free (priv->subject);
2714         g_completion_free (priv->completion);
2715
2716         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
2717 }
2718
2719 static void
2720 chat_constructed (GObject *object)
2721 {
2722         EmpathyChat *chat = EMPATHY_CHAT (object);
2723         EmpathyChatPriv *priv = GET_PRIV (chat);
2724
2725         if (priv->handle_type != TP_HANDLE_TYPE_ROOM)
2726                 chat_add_logs (chat);
2727 #ifndef ENABLE_TPL
2728         /* When async API are involved, pending message are shown at the end of the
2729          * callbacks' chain fired by chat_add_logs */
2730         priv->can_show_pending = TRUE;
2731         show_pending_messages (chat);
2732 #endif /* ENABLE_TPL */
2733 }
2734
2735 static void
2736 empathy_chat_class_init (EmpathyChatClass *klass)
2737 {
2738         GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
2739         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
2740
2741         object_class->finalize = chat_finalize;
2742         object_class->get_property = chat_get_property;
2743         object_class->set_property = chat_set_property;
2744         object_class->constructed = chat_constructed;
2745
2746         widget_class->size_request = chat_size_request;
2747         widget_class->size_allocate = chat_size_allocate;
2748
2749         g_object_class_install_property (object_class,
2750                                          PROP_TP_CHAT,
2751                                          g_param_spec_object ("tp-chat",
2752                                                               "Empathy tp chat",
2753                                                               "The tp chat object",
2754                                                               EMPATHY_TYPE_TP_CHAT,
2755                                                               G_PARAM_CONSTRUCT |
2756                                                               G_PARAM_READWRITE |
2757                                                               G_PARAM_STATIC_STRINGS));
2758         g_object_class_install_property (object_class,
2759                                          PROP_ACCOUNT,
2760                                          g_param_spec_object ("account",
2761                                                               "Account of the chat",
2762                                                               "The account of the chat",
2763                                                               TP_TYPE_ACCOUNT,
2764                                                               G_PARAM_READABLE |
2765                                                               G_PARAM_STATIC_STRINGS));
2766         g_object_class_install_property (object_class,
2767                                          PROP_ID,
2768                                          g_param_spec_string ("id",
2769                                                               "Chat's id",
2770                                                               "The id of the chat",
2771                                                               NULL,
2772                                                               G_PARAM_READABLE |
2773                                                               G_PARAM_STATIC_STRINGS));
2774         g_object_class_install_property (object_class,
2775                                          PROP_NAME,
2776                                          g_param_spec_string ("name",
2777                                                               "Chat's name",
2778                                                               "The name of the chat",
2779                                                               NULL,
2780                                                               G_PARAM_READABLE |
2781                                                               G_PARAM_STATIC_STRINGS));
2782         g_object_class_install_property (object_class,
2783                                          PROP_SUBJECT,
2784                                          g_param_spec_string ("subject",
2785                                                               "Chat's subject",
2786                                                               "The subject or topic of the chat",
2787                                                               NULL,
2788                                                               G_PARAM_READABLE |
2789                                                               G_PARAM_STATIC_STRINGS));
2790         g_object_class_install_property (object_class,
2791                                          PROP_REMOTE_CONTACT,
2792                                          g_param_spec_object ("remote-contact",
2793                                                               "The remote contact",
2794                                                               "The remote contact is any",
2795                                                               EMPATHY_TYPE_CONTACT,
2796                                                               G_PARAM_READABLE |
2797                                                               G_PARAM_STATIC_STRINGS));
2798         g_object_class_install_property (object_class,
2799                                          PROP_SHOW_CONTACTS,
2800                                          g_param_spec_boolean ("show-contacts",
2801                                                                "Contacts' visibility",
2802                                                                "The visibility of the contacts' list",
2803                                                                TRUE,
2804                                                                G_PARAM_READWRITE |
2805                                                                G_PARAM_STATIC_STRINGS));
2806
2807         signals[COMPOSING] =
2808                 g_signal_new ("composing",
2809                               G_OBJECT_CLASS_TYPE (object_class),
2810                               G_SIGNAL_RUN_LAST,
2811                               0,
2812                               NULL, NULL,
2813                               g_cclosure_marshal_VOID__BOOLEAN,
2814                               G_TYPE_NONE,
2815                               1, G_TYPE_BOOLEAN);
2816
2817         signals[NEW_MESSAGE] =
2818                 g_signal_new ("new-message",
2819                               G_OBJECT_CLASS_TYPE (object_class),
2820                               G_SIGNAL_RUN_LAST,
2821                               0,
2822                               NULL, NULL,
2823                               g_cclosure_marshal_VOID__OBJECT,
2824                               G_TYPE_NONE,
2825                               1, EMPATHY_TYPE_MESSAGE);
2826
2827         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
2828 }
2829
2830 static gboolean
2831 chat_block_events_timeout_cb (gpointer data)
2832 {
2833         EmpathyChatPriv *priv = GET_PRIV (data);
2834
2835         priv->block_events_timeout_id = 0;
2836
2837         return FALSE;
2838 }
2839
2840 static void
2841 account_manager_prepared_cb (GObject *source_object,
2842                              GAsyncResult *result,
2843                              gpointer user_data)
2844 {
2845         GList *accounts, *l;
2846         TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
2847         EmpathyChat *chat = user_data;
2848         GError *error = NULL;
2849
2850         if (!tp_account_manager_prepare_finish (account_manager, result, &error)) {
2851                 DEBUG ("Failed to prepare the account manager: %s", error->message);
2852                 g_error_free (error);
2853                 return;
2854         }
2855
2856         accounts = tp_account_manager_get_valid_accounts (account_manager);
2857
2858         for (l = accounts; l != NULL; l = l->next) {
2859                 TpAccount *account = l->data;
2860                 tp_g_signal_connect_object (account, "status-changed",
2861                                              G_CALLBACK (chat_new_connection_cb),
2862                                              chat, 0);
2863         }
2864
2865         g_list_free (accounts);
2866 }
2867
2868 static void
2869 empathy_chat_init (EmpathyChat *chat)
2870 {
2871         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
2872                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
2873
2874         chat->priv = priv;
2875 #ifndef ENABLE_TPL
2876         priv->log_manager = empathy_log_manager_dup_singleton ();
2877 #else
2878         priv->log_manager = tpl_log_manager_dup_singleton ();
2879 #endif /* ENABLE_TPL */
2880         priv->gsettings_chat = g_settings_new (EMPATHY_PREFS_CHAT_SCHEMA);
2881         priv->gsettings_ui = g_settings_new (EMPATHY_PREFS_UI_SCHEMA);
2882
2883         priv->contacts_width = -1;
2884         priv->input_history = NULL;
2885         priv->input_history_current = NULL;
2886         priv->account_manager = tp_account_manager_dup ();
2887
2888         tp_account_manager_prepare_async (priv->account_manager, NULL,
2889                                           account_manager_prepared_cb, chat);
2890
2891         priv->show_contacts = g_settings_get_boolean (priv->gsettings_chat,
2892                         EMPATHY_PREFS_CHAT_SHOW_CONTACTS_IN_ROOMS);
2893
2894         /* Block events for some time to avoid having "has come online" or
2895          * "joined" messages. */
2896         priv->block_events_timeout_id =
2897                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
2898
2899         /* Add nick name completion */
2900         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_name);
2901         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
2902
2903         chat_create_ui (chat);
2904 }
2905
2906 EmpathyChat *
2907 empathy_chat_new (EmpathyTpChat *tp_chat)
2908 {
2909         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
2910 }
2911
2912 EmpathyTpChat *
2913 empathy_chat_get_tp_chat (EmpathyChat *chat)
2914 {
2915         EmpathyChatPriv *priv = GET_PRIV (chat);
2916
2917         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2918
2919         return priv->tp_chat;
2920 }
2921
2922 static void display_password_info_bar (EmpathyChat *self,
2923                                        gboolean retry);
2924
2925 static void
2926 provide_password_cb (GObject *tp_chat,
2927                      GAsyncResult *res,
2928                      gpointer user_data)
2929 {
2930         EmpathyChat *self = EMPATHY_CHAT (user_data);
2931         EmpathyChatPriv *priv = GET_PRIV (self);
2932         GError *error = NULL;
2933
2934         if (!empathy_tp_chat_provide_password_finish (EMPATHY_TP_CHAT (tp_chat), res,
2935                                                       &error)) {
2936                 DEBUG ("error: %s", error->message);
2937                 /* FIXME: what should we do if that's another error? Close the channel?
2938                  * Display the raw D-Bus error to the user isn't very useful */
2939                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED))
2940                         display_password_info_bar (self, TRUE);
2941                 g_error_free (error);
2942                 return;
2943         }
2944
2945         /* Room joined */
2946         gtk_widget_set_sensitive (priv->hpaned, TRUE);
2947         gtk_widget_grab_focus (self->input_text_view);
2948 }
2949
2950 static void
2951 password_infobar_response_cb (GtkWidget *info_bar,
2952                               gint response_id,
2953                               EmpathyChat *self)
2954 {
2955         EmpathyChatPriv *priv = GET_PRIV (self);
2956         GtkWidget *entry;
2957         const gchar *password;
2958
2959         if (response_id != GTK_RESPONSE_OK)
2960                 goto out;
2961
2962         entry = g_object_get_data (G_OBJECT (info_bar), "password-entry");
2963         g_assert (entry != NULL);
2964
2965         password = gtk_entry_get_text (GTK_ENTRY (entry));
2966
2967         empathy_tp_chat_provide_password_async (priv->tp_chat, password,
2968                                                 provide_password_cb, self);
2969
2970  out:
2971         gtk_widget_destroy (info_bar);
2972 }
2973
2974 static void
2975 password_entry_activate_cb (GtkWidget *entry,
2976                           GtkWidget *info_bar)
2977 {
2978         gtk_info_bar_response (GTK_INFO_BAR (info_bar), GTK_RESPONSE_OK);
2979 }
2980
2981 static void
2982 passwd_join_button_cb (GtkButton *button,
2983                           GtkWidget *info_bar)
2984 {
2985         gtk_info_bar_response (GTK_INFO_BAR (info_bar), GTK_RESPONSE_OK);
2986 }
2987
2988 static void
2989 display_password_info_bar (EmpathyChat *self,
2990                            gboolean retry)
2991 {
2992         EmpathyChatPriv *priv = GET_PRIV (self);
2993         GtkWidget *info_bar;
2994         GtkWidget *content_area;
2995         GtkWidget *hbox;
2996         GtkWidget *image;
2997         GtkWidget *label;
2998         GtkWidget *entry;
2999         GtkWidget *alig;
3000         GtkWidget *button;
3001         GtkMessageType type;
3002         const gchar *msg, *button_label;
3003
3004         if (retry) {
3005                 /* Previous password was wrong */
3006                 type = GTK_MESSAGE_ERROR;
3007                 msg = _("Wrong password; please try again:");
3008                 button_label = _("Retry");
3009         }
3010         else {
3011                 /* First time we're trying to join */
3012                 type = GTK_MESSAGE_QUESTION;
3013                 msg = _("This room is protected by a password:");
3014                 button_label = _("Join");
3015         }
3016
3017         info_bar = gtk_info_bar_new ();
3018         gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar), type);
3019
3020         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar));
3021
3022         hbox = gtk_hbox_new (FALSE, 3);
3023         gtk_container_add (GTK_CONTAINER (content_area), hbox);
3024
3025         /* Add image */
3026         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3027                                           GTK_ICON_SIZE_DIALOG);
3028         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3029
3030         /* Add message */
3031         label = gtk_label_new (msg);
3032         gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
3033
3034         /* Add password entry */
3035         entry = gtk_entry_new ();
3036         gtk_entry_set_visibility (GTK_ENTRY (entry), FALSE);
3037         gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
3038
3039         g_signal_connect (entry, "activate",
3040                           G_CALLBACK (password_entry_activate_cb), info_bar);
3041
3042         /* Focus the password entry once it's realized */
3043         g_signal_connect (entry, "realize", G_CALLBACK (gtk_widget_grab_focus), NULL);
3044
3045         /* Add 'Join' button */
3046         alig = gtk_alignment_new (0, 0.5, 0, 0);
3047
3048         button = gtk_button_new_with_label (button_label);
3049         gtk_container_add (GTK_CONTAINER (alig), button);
3050         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3051
3052         g_signal_connect (button, "clicked", G_CALLBACK (passwd_join_button_cb),
3053                           info_bar);
3054
3055         g_object_set_data (G_OBJECT (info_bar), "password-entry", entry);
3056
3057         gtk_box_pack_start (GTK_BOX (priv->info_bar_vbox), info_bar,
3058                             FALSE, FALSE, 3);
3059         gtk_widget_show_all (hbox);
3060
3061         g_signal_connect (info_bar, "response",
3062                           G_CALLBACK (password_infobar_response_cb), self);
3063
3064         gtk_widget_show_all (info_bar);
3065 }
3066
3067 static void
3068 chat_password_needed_changed_cb (EmpathyChat *self)
3069 {
3070         EmpathyChatPriv *priv = GET_PRIV (self);
3071
3072         if (empathy_tp_chat_password_needed (priv->tp_chat)) {
3073                 display_password_info_bar (self, FALSE);
3074                 gtk_widget_set_sensitive (priv->hpaned, FALSE);
3075         }
3076 }
3077
3078 void
3079 empathy_chat_set_tp_chat (EmpathyChat   *chat,
3080                           EmpathyTpChat *tp_chat)
3081 {
3082         EmpathyChatPriv *priv = GET_PRIV (chat);
3083         TpConnection    *connection;
3084         GPtrArray       *properties;
3085
3086         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3087         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
3088         g_return_if_fail (empathy_tp_chat_is_ready (tp_chat));
3089
3090         if (priv->tp_chat) {
3091                 return;
3092         }
3093
3094         if (priv->account) {
3095                 g_object_unref (priv->account);
3096         }
3097
3098         priv->tp_chat = g_object_ref (tp_chat);
3099         connection = empathy_tp_chat_get_connection (priv->tp_chat);
3100         priv->account = g_object_ref (empathy_get_account_for_connection (connection));
3101
3102         g_signal_connect (tp_chat, "destroy",
3103                           G_CALLBACK (chat_destroy_cb),
3104                           chat);
3105         g_signal_connect (tp_chat, "message-received",
3106                           G_CALLBACK (chat_message_received_cb),
3107                           chat);
3108         g_signal_connect (tp_chat, "send-error",
3109                           G_CALLBACK (chat_send_error_cb),
3110                           chat);
3111         g_signal_connect (tp_chat, "chat-state-changed",
3112                           G_CALLBACK (chat_state_changed_cb),
3113                           chat);
3114         g_signal_connect (tp_chat, "property-changed",
3115                           G_CALLBACK (chat_property_changed_cb),
3116                           chat);
3117         g_signal_connect (tp_chat, "members-changed",
3118                           G_CALLBACK (chat_members_changed_cb),
3119                           chat);
3120         g_signal_connect (tp_chat, "member-renamed",
3121                           G_CALLBACK (chat_member_renamed_cb),
3122                           chat);
3123         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
3124                                   G_CALLBACK (chat_remote_contact_changed_cb),
3125                                   chat);
3126         g_signal_connect_swapped (tp_chat, "notify::password-needed",
3127                                   G_CALLBACK (chat_password_needed_changed_cb),
3128                                   chat);
3129
3130         /* Get initial value of properties */
3131         properties = empathy_tp_chat_get_properties (priv->tp_chat);
3132         if (properties != NULL) {
3133                 guint i;
3134
3135                 for (i = 0; i < properties->len; i++) {
3136                         EmpathyTpChatProperty *property;
3137
3138                         property = g_ptr_array_index (properties, i);
3139                         if (property->value == NULL)
3140                                 continue;
3141
3142                         chat_property_changed_cb (priv->tp_chat,
3143                                                   property->name,
3144                                                   property->value,
3145                                                   chat);
3146                 }
3147         }
3148
3149         chat_remote_contact_changed_cb (chat);
3150
3151         if (chat->input_text_view) {
3152                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
3153                 if (priv->block_events_timeout_id == 0) {
3154                         empathy_chat_view_append_event (chat->view, _("Connected"));
3155                 }
3156         }
3157
3158         g_object_notify (G_OBJECT (chat), "tp-chat");
3159         g_object_notify (G_OBJECT (chat), "id");
3160         g_object_notify (G_OBJECT (chat), "account");
3161
3162         /* This is a noop when tp-chat is set at object construction time and causes
3163          * the pending messages to be show when it's set on the object after it has
3164          * been created */
3165         show_pending_messages (chat);
3166
3167         /* check if a password is needed */
3168         chat_password_needed_changed_cb (chat);
3169 }
3170
3171 TpAccount *
3172 empathy_chat_get_account (EmpathyChat *chat)
3173 {
3174         EmpathyChatPriv *priv = GET_PRIV (chat);
3175
3176         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3177
3178         return priv->account;
3179 }
3180
3181 const gchar *
3182 empathy_chat_get_id (EmpathyChat *chat)
3183 {
3184         EmpathyChatPriv *priv = GET_PRIV (chat);
3185
3186         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3187
3188         return priv->id;
3189 }
3190
3191 const gchar *
3192 empathy_chat_get_name (EmpathyChat *chat)
3193 {
3194         EmpathyChatPriv *priv = GET_PRIV (chat);
3195         const gchar *ret;
3196
3197         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3198
3199         ret = priv->name;
3200         if (!ret && priv->remote_contact) {
3201                 ret = empathy_contact_get_name (priv->remote_contact);
3202         }
3203
3204         if (!ret)
3205                 ret = priv->id;
3206
3207         return ret ? ret : _("Conversation");
3208 }
3209
3210 const gchar *
3211 empathy_chat_get_subject (EmpathyChat *chat)
3212 {
3213         EmpathyChatPriv *priv = GET_PRIV (chat);
3214
3215         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3216
3217         return priv->subject;
3218 }
3219
3220 EmpathyContact *
3221 empathy_chat_get_remote_contact (EmpathyChat *chat)
3222 {
3223         EmpathyChatPriv *priv = GET_PRIV (chat);
3224
3225         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3226
3227         return priv->remote_contact;
3228 }
3229
3230 GtkWidget *
3231 empathy_chat_get_contact_menu (EmpathyChat *chat)
3232 {
3233         EmpathyChatPriv *priv = GET_PRIV (chat);
3234         GtkWidget       *menu = NULL;
3235
3236         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3237
3238         if (priv->remote_contact) {
3239                 menu = empathy_contact_menu_new (priv->remote_contact,
3240                                                  EMPATHY_CONTACT_FEATURE_CALL |
3241                                                  EMPATHY_CONTACT_FEATURE_LOG |
3242                                                  EMPATHY_CONTACT_FEATURE_INFO);
3243         }
3244         else if (priv->contact_list_view) {
3245                 EmpathyContactListView *view;
3246
3247                 view = EMPATHY_CONTACT_LIST_VIEW (priv->contact_list_view);
3248                 menu = empathy_contact_list_view_get_contact_menu (view);
3249         }
3250
3251         return menu;
3252 }
3253
3254 void
3255 empathy_chat_clear (EmpathyChat *chat)
3256 {
3257         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3258
3259         empathy_chat_view_clear (chat->view);
3260 }
3261
3262 void
3263 empathy_chat_scroll_down (EmpathyChat *chat)
3264 {
3265         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3266
3267         empathy_chat_view_scroll_down (chat->view);
3268 }
3269
3270 void
3271 empathy_chat_cut (EmpathyChat *chat)
3272 {
3273         GtkTextBuffer *buffer;
3274
3275         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3276
3277         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3278         if (gtk_text_buffer_get_has_selection (buffer)) {
3279                 GtkClipboard *clipboard;
3280
3281                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3282
3283                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
3284         }
3285 }
3286
3287 void
3288 empathy_chat_copy (EmpathyChat *chat)
3289 {
3290         GtkTextBuffer *buffer;
3291
3292         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3293
3294         if (empathy_chat_view_get_has_selection (chat->view)) {
3295                 empathy_chat_view_copy_clipboard (chat->view);
3296                 return;
3297         }
3298
3299         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3300         if (gtk_text_buffer_get_has_selection (buffer)) {
3301                 GtkClipboard *clipboard;
3302
3303                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3304
3305                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
3306         }
3307 }
3308
3309 void
3310 empathy_chat_paste (EmpathyChat *chat)
3311 {
3312         GtkTextBuffer *buffer;
3313         GtkClipboard  *clipboard;
3314         EmpathyChatPriv *priv;
3315
3316         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3317
3318         priv = GET_PRIV (chat);
3319
3320         if (priv->tp_chat == NULL ||
3321             !gtk_widget_is_sensitive (chat->input_text_view))
3322                 return;
3323
3324         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3325         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3326
3327         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
3328 }
3329
3330 void
3331 empathy_chat_find (EmpathyChat *chat)
3332 {
3333         EmpathyChatPriv *priv;
3334
3335         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3336
3337         priv = GET_PRIV (chat);
3338
3339         empathy_search_bar_show (EMPATHY_SEARCH_BAR (priv->search_bar));
3340 }
3341
3342 void
3343 empathy_chat_correct_word (EmpathyChat  *chat,
3344                           GtkTextIter *start,
3345                           GtkTextIter *end,
3346                           const gchar *new_word)
3347 {
3348         GtkTextBuffer *buffer;
3349
3350         g_return_if_fail (chat != NULL);
3351         g_return_if_fail (new_word != NULL);
3352
3353         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3354
3355         gtk_text_buffer_delete (buffer, start, end);
3356         gtk_text_buffer_insert (buffer, start,
3357                                 new_word,
3358                                 -1);
3359 }
3360
3361 gboolean
3362 empathy_chat_is_room (EmpathyChat *chat)
3363 {
3364         EmpathyChatPriv *priv = GET_PRIV (chat);
3365
3366         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
3367
3368         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
3369 }
3370
3371 guint
3372 empathy_chat_get_nb_unread_messages (EmpathyChat *self)
3373 {
3374         EmpathyChatPriv *priv = GET_PRIV (self);
3375
3376         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
3377
3378         return priv->unread_messages;
3379 }
3380
3381 /* called when the messages have been read by user */
3382 void
3383 empathy_chat_messages_read (EmpathyChat *self)
3384 {
3385         EmpathyChatPriv *priv = GET_PRIV (self);
3386
3387         g_return_if_fail (EMPATHY_IS_CHAT (self));
3388
3389         /* FIXME: See Bug#610994, See comments about it in EmpathyChatPriv
3390          * definition. If we are still retrieving the backlogs, do not ACK */
3391         if (priv->retrieving_backlogs)
3392                 return;
3393
3394         if (priv->tp_chat != NULL ) {
3395                         empathy_tp_chat_acknowledge_all_messages (priv->tp_chat);
3396         }
3397         priv->unread_messages = 0;
3398 }