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