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