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