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