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