]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
Added Belarusian translation.
[empathy.git] / libempathy-gtk / empathy-chat.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2002-2007 Imendio AB
4  * Copyright (C) 2007-2008 Collabora Ltd.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  * 
21  * Authors: Mikael Hallendal <micke@imendio.com>
22  *          Richard Hult <richard@imendio.com>
23  *          Martyn Russell <martyn@imendio.com>
24  *          Geert-Jan Van den Bogaerde <geertjan@gnome.org>
25  *          Xavier Claessens <xclaesse@gmail.com>
26  */
27
28 #include <config.h>
29
30 #include <string.h>
31 #include <stdlib.h>
32
33 #include <gdk/gdkkeysyms.h>
34 #include <glib/gi18n-lib.h>
35 #include <gtk/gtk.h>
36
37 #include <telepathy-glib/util.h>
38
39 #include <libempathy/empathy-account-manager.h>
40 #include <libempathy/empathy-log-manager.h>
41 #include <libempathy/empathy-contact-list.h>
42 #include <libempathy/empathy-utils.h>
43 #include <libempathy/empathy-dispatcher.h>
44
45 #include "empathy-chat.h"
46 #include "empathy-conf.h"
47 #include "empathy-spell.h"
48 #include "empathy-spell-dialog.h"
49 #include "empathy-contact-list-store.h"
50 #include "empathy-contact-list-view.h"
51 #include "empathy-contact-menu.h"
52 #include "empathy-theme-manager.h"
53 #include "empathy-smiley-manager.h"
54 #include "empathy-ui-utils.h"
55
56 #define DEBUG_FLAG EMPATHY_DEBUG_CHAT
57 #include <libempathy/empathy-debug.h>
58
59 #define CHAT_DIR_CREATE_MODE  (S_IRUSR | S_IWUSR | S_IXUSR)
60 #define CHAT_FILE_CREATE_MODE (S_IRUSR | S_IWUSR)
61 #define IS_ENTER(v) (v == GDK_Return || v == GDK_ISO_Enter || v == GDK_KP_Enter)
62 #define MAX_INPUT_HEIGHT 150
63 #define COMPOSING_STOP_TIMEOUT 5
64
65 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyChat)
66 typedef struct {
67         EmpathyTpChat     *tp_chat;
68         gulong            tp_chat_destroy_handler;
69         McAccount         *account;
70         gchar             *id;
71         gchar             *name;
72         gchar             *subject;
73         EmpathyContact    *remote_contact;
74
75         EmpathyLogManager *log_manager;
76         EmpathyAccountManager *account_manager;
77         GSList            *sent_messages;
78         gint               sent_messages_index;
79         GList             *compositors;
80         GCompletion       *completion;
81         guint              composing_stop_timeout_id;
82         guint              block_events_timeout_id;
83         TpHandleType       handle_type;
84         gint               contacts_width;
85         gboolean           has_input_vscroll;
86
87         GtkWidget         *widget;
88         GtkWidget         *hpaned;
89         GtkWidget         *vbox_left;
90         GtkWidget         *scrolled_window_chat;
91         GtkWidget         *scrolled_window_input;
92         GtkWidget         *scrolled_window_contacts;
93         GtkWidget         *hbox_topic;
94         GtkWidget         *label_topic;
95         GtkWidget         *contact_list_view;
96 } EmpathyChatPriv;
97
98 enum {
99         COMPOSING,
100         NEW_MESSAGE,
101         LAST_SIGNAL
102 };
103
104 enum {
105         PROP_0,
106         PROP_TP_CHAT,
107         PROP_ACCOUNT,
108         PROP_ID,
109         PROP_NAME,
110         PROP_SUBJECT,
111         PROP_REMOTE_CONTACT,
112 };
113
114 static guint signals[LAST_SIGNAL] = { 0 };
115
116 G_DEFINE_TYPE (EmpathyChat, empathy_chat, GTK_TYPE_BIN);
117
118 static void
119 chat_get_property (GObject    *object,
120                    guint       param_id,
121                    GValue     *value,
122                    GParamSpec *pspec)
123 {
124         EmpathyChat *chat = EMPATHY_CHAT (object);
125         EmpathyChatPriv *priv = GET_PRIV (object);
126
127         switch (param_id) {
128         case PROP_TP_CHAT:
129                 g_value_set_object (value, priv->tp_chat);
130                 break;
131         case PROP_ACCOUNT:
132                 g_value_set_object (value, priv->account);
133                 break;
134         case PROP_NAME:
135                 g_value_set_string (value, empathy_chat_get_name (chat));
136                 break;
137         case PROP_ID:
138                 g_value_set_string (value, priv->id);
139                 break;
140         case PROP_SUBJECT:
141                 g_value_set_string (value, priv->subject);
142                 break;
143         case PROP_REMOTE_CONTACT:
144                 g_value_set_object (value, priv->remote_contact);
145                 break;
146         default:
147                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
148                 break;
149         };
150 }
151
152 static void
153 chat_set_property (GObject      *object,
154                    guint         param_id,
155                    const GValue *value,
156                    GParamSpec   *pspec)
157 {
158         EmpathyChat *chat = EMPATHY_CHAT (object);
159
160         switch (param_id) {
161         case PROP_TP_CHAT:
162                 empathy_chat_set_tp_chat (chat, EMPATHY_TP_CHAT (g_value_get_object (value)));
163                 break;
164         default:
165                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
166                 break;
167         };
168 }
169
170 static void
171 chat_connection_changed_cb (EmpathyAccountManager *manager,
172                             McAccount *account,
173                             TpConnectionStatusReason reason,
174                             TpConnectionStatus current,
175                             TpConnectionStatus previous,
176                             EmpathyChat *chat)
177 {
178         EmpathyChatPriv *priv = GET_PRIV (chat);
179
180         if (current == TP_CONNECTION_STATUS_CONNECTED && !priv->tp_chat &&
181             empathy_account_equal (account, priv->account) &&
182             priv->handle_type != TP_HANDLE_TYPE_NONE &&
183             !EMP_STR_EMPTY (priv->id)) {
184                 
185                 DEBUG ("Account reconnected, request a new Text channel");
186
187                 switch (priv->handle_type) {
188                         case TP_HANDLE_TYPE_CONTACT:
189                                 empathy_dispatcher_chat_with_contact_id (account, priv->id,
190                                         NULL, NULL);
191                                 break;
192                         case TP_HANDLE_TYPE_ROOM:
193                                 empathy_dispatcher_join_muc (account, priv->id, NULL, NULL);
194                                 break;
195                         default:
196                                 g_assert_not_reached ();
197                                 break;
198                 }
199         }
200 }
201
202 static void
203 chat_composing_remove_timeout (EmpathyChat *chat)
204 {
205         EmpathyChatPriv *priv;
206
207         priv = GET_PRIV (chat);
208
209         if (priv->composing_stop_timeout_id) {
210                 g_source_remove (priv->composing_stop_timeout_id);
211                 priv->composing_stop_timeout_id = 0;
212         }
213 }
214
215 static gboolean
216 chat_composing_stop_timeout_cb (EmpathyChat *chat)
217 {
218         EmpathyChatPriv *priv;
219
220         priv = GET_PRIV (chat);
221
222         priv->composing_stop_timeout_id = 0;
223         empathy_tp_chat_set_state (priv->tp_chat,
224                                    TP_CHANNEL_CHAT_STATE_PAUSED);
225
226         return FALSE;
227 }
228
229 static void
230 chat_composing_start (EmpathyChat *chat)
231 {
232         EmpathyChatPriv *priv;
233
234         priv = GET_PRIV (chat);
235
236         if (priv->composing_stop_timeout_id) {
237                 /* Just restart the timeout */
238                 chat_composing_remove_timeout (chat);
239         } else {
240                 empathy_tp_chat_set_state (priv->tp_chat,
241                                            TP_CHANNEL_CHAT_STATE_COMPOSING);
242         }
243
244         priv->composing_stop_timeout_id = g_timeout_add_seconds (
245                 COMPOSING_STOP_TIMEOUT,
246                 (GSourceFunc) chat_composing_stop_timeout_cb,
247                 chat);
248 }
249
250 static void
251 chat_composing_stop (EmpathyChat *chat)
252 {
253         EmpathyChatPriv *priv;
254
255         priv = GET_PRIV (chat);
256
257         chat_composing_remove_timeout (chat);
258         empathy_tp_chat_set_state (priv->tp_chat,
259                                    TP_CHANNEL_CHAT_STATE_ACTIVE);
260 }
261
262 static void 
263 chat_sent_message_add (EmpathyChat  *chat,
264                        const gchar *str)
265 {
266         EmpathyChatPriv *priv;
267         GSList         *list;
268         GSList         *item;
269
270         priv = GET_PRIV (chat);
271
272         /* Save the sent message in our repeat buffer */
273         list = priv->sent_messages;
274         
275         /* Remove any other occurances of this msg */
276         while ((item = g_slist_find_custom (list, str, (GCompareFunc) strcmp)) != NULL) {
277                 list = g_slist_remove_link (list, item);
278                 g_free (item->data);
279                 g_slist_free1 (item);
280         }
281
282         /* Trim the list to the last 10 items */
283         while (g_slist_length (list) > 10) {
284                 item = g_slist_last (list);
285                 if (item) {
286                         list = g_slist_remove_link (list, item);
287                         g_free (item->data);
288                         g_slist_free1 (item);
289                 }
290         }
291
292         /* Add new message */
293         list = g_slist_prepend (list, g_strdup (str));
294
295         /* Set list and reset the index */
296         priv->sent_messages = list;
297         priv->sent_messages_index = -1;
298 }
299
300 static const gchar *
301 chat_sent_message_get_next (EmpathyChat *chat)
302 {
303         EmpathyChatPriv *priv;
304         gint            max;
305         
306         priv = GET_PRIV (chat);
307
308         if (!priv->sent_messages) {
309                 DEBUG ("No sent messages, next message is NULL");
310                 return NULL;
311         }
312
313         max = g_slist_length (priv->sent_messages) - 1;
314
315         if (priv->sent_messages_index < max) {
316                 priv->sent_messages_index++;
317         }
318         
319         DEBUG ("Returning next message index:%d", priv->sent_messages_index);
320
321         return g_slist_nth_data (priv->sent_messages, priv->sent_messages_index);
322 }
323
324 static const gchar *
325 chat_sent_message_get_last (EmpathyChat *chat)
326 {
327         EmpathyChatPriv *priv;
328
329         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
330
331         priv = GET_PRIV (chat);
332         
333         if (!priv->sent_messages) {
334                 DEBUG ("No sent messages, last message is NULL");
335                 return NULL;
336         }
337
338         if (priv->sent_messages_index >= 0) {
339                 priv->sent_messages_index--;
340         }
341
342         DEBUG ("Returning last message index:%d", priv->sent_messages_index);
343
344         return g_slist_nth_data (priv->sent_messages, priv->sent_messages_index);
345 }
346
347 static void
348 chat_send (EmpathyChat  *chat,
349            const gchar *msg)
350 {
351         EmpathyChatPriv *priv;
352         EmpathyMessage  *message;
353
354         if (EMP_STR_EMPTY (msg)) {
355                 return;
356         }
357
358         priv = GET_PRIV (chat);
359
360         chat_sent_message_add (chat, msg);
361
362         if (g_str_has_prefix (msg, "/clear")) {
363                 empathy_chat_view_clear (chat->view);
364                 return;
365         }
366
367         /* Blacklist messages begining by '/', except for "/me" and "/say"
368          * because they are handled in EmpathyMessage */
369         if (msg[0] == '/' &&
370             !g_str_has_prefix (msg, "/me") &&
371             !g_str_has_prefix (msg, "/say")) {
372                 empathy_chat_view_append_event (chat->view,
373                         _("Unsupported command"));
374                 return;
375         }
376
377         /* We can send the message */
378         message = empathy_message_new (msg);
379         empathy_tp_chat_send (priv->tp_chat, message);
380         g_object_unref (message);
381 }
382
383 static void
384 chat_input_text_view_send (EmpathyChat *chat)
385 {
386         EmpathyChatPriv *priv;
387         GtkTextBuffer  *buffer;
388         GtkTextIter     start, end;
389         gchar          *msg;
390
391         priv = GET_PRIV (chat);
392
393         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
394
395         gtk_text_buffer_get_bounds (buffer, &start, &end);
396         msg = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
397
398         /* clear the input field */
399         gtk_text_buffer_set_text (buffer, "", -1);
400
401         chat_send (chat, msg);
402         g_free (msg);
403 }
404
405 static void
406 chat_state_changed_cb (EmpathyTpChat      *tp_chat,
407                        EmpathyContact     *contact,
408                        TpChannelChatState  state,
409                        EmpathyChat        *chat)
410 {
411         EmpathyChatPriv *priv;
412         GList          *l;
413         gboolean        was_composing;
414
415         priv = GET_PRIV (chat);
416
417         if (empathy_contact_is_user (contact)) {
418                 /* We don't care about our own chat state */
419                 return;
420         }
421
422         was_composing = (priv->compositors != NULL);
423
424         /* Find the contact in the list. After that l is the list elem or NULL */
425         for (l = priv->compositors; l; l = l->next) {
426                 if (contact == l->data) {
427                         break;
428                 }
429         }
430
431         switch (state) {
432         case TP_CHANNEL_CHAT_STATE_GONE:
433         case TP_CHANNEL_CHAT_STATE_INACTIVE:
434         case TP_CHANNEL_CHAT_STATE_PAUSED:
435         case TP_CHANNEL_CHAT_STATE_ACTIVE:
436                 /* Contact is not composing */
437                 if (l) {
438                         priv->compositors = g_list_remove_link (priv->compositors, l);
439                         g_object_unref (l->data);
440                         g_list_free1 (l);
441                 }
442                 break;
443         case TP_CHANNEL_CHAT_STATE_COMPOSING:
444                 /* Contact is composing */
445                 if (!l) {
446                         priv->compositors = g_list_prepend (priv->compositors,
447                                                             g_object_ref (contact));
448                 }
449                 break;
450         default:
451                 g_assert_not_reached ();
452         }
453
454         DEBUG ("Was composing: %s now composing: %s",
455                 was_composing ? "yes" : "no",
456                 priv->compositors ? "yes" : "no");
457
458         if ((was_composing && !priv->compositors) ||
459             (!was_composing && priv->compositors)) {
460                 /* Composing state changed */
461                 g_signal_emit (chat, signals[COMPOSING], 0,
462                                priv->compositors != NULL);
463         }
464 }
465
466 static void
467 chat_message_received (EmpathyChat *chat, EmpathyMessage *message)
468 {
469         EmpathyChatPriv *priv = GET_PRIV (chat);
470         EmpathyContact  *sender;
471
472         sender = empathy_message_get_sender (message);
473
474         DEBUG ("Appending new message from %s (%d)",
475                 empathy_contact_get_name (sender),
476                 empathy_contact_get_handle (sender));
477
478         empathy_chat_view_append_message (chat->view, message);
479
480         /* We received a message so the contact is no longer composing */
481         chat_state_changed_cb (priv->tp_chat, sender,
482                                TP_CHANNEL_CHAT_STATE_ACTIVE,
483                                chat);
484
485         g_signal_emit (chat, signals[NEW_MESSAGE], 0, message);
486 }
487
488 static void
489 chat_message_received_cb (EmpathyTpChat  *tp_chat,
490                           EmpathyMessage *message,
491                           EmpathyChat    *chat)
492 {
493         chat_message_received (chat, message);
494         empathy_tp_chat_acknowledge_message (tp_chat, message);
495 }
496
497 static void
498 chat_send_error_cb (EmpathyTpChat          *tp_chat,
499                     EmpathyMessage         *message,
500                     TpChannelTextSendError  error_code,
501                     EmpathyChat            *chat)
502 {
503         const gchar *error;
504         gchar       *str;
505
506         switch (error_code) {
507         case TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE:
508                 error = _("offline");
509                 break;
510         case TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT:
511                 error = _("invalid contact");
512                 break;
513         case TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED:
514                 error = _("permission denied");
515                 break;
516         case TP_CHANNEL_TEXT_SEND_ERROR_TOO_LONG:
517                 error = _("too long message");
518                 break;
519         case TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED:
520                 error = _("not implemented");
521                 break;
522         default:
523                 error = _("unknown");
524                 break;
525         }
526
527         str = g_strdup_printf (_("Error sending message '%s': %s"),
528                                empathy_message_get_body (message),
529                                error);
530         empathy_chat_view_append_event (chat->view, str);
531         g_free (str);
532 }
533
534 static void
535 chat_property_changed_cb (EmpathyTpChat *tp_chat,
536                           const gchar   *name,
537                           GValue        *value,
538                           EmpathyChat   *chat)
539 {
540         EmpathyChatPriv *priv = GET_PRIV (chat);
541
542         if (!tp_strdiff (name, "subject")) {
543                 g_free (priv->subject);
544                 priv->subject = g_value_dup_string (value);
545                 g_object_notify (G_OBJECT (chat), "subject");
546
547                 if (EMP_STR_EMPTY (priv->subject)) {
548                         gtk_widget_hide (priv->hbox_topic);
549                 } else {
550                         gtk_label_set_text (GTK_LABEL (priv->label_topic), priv->subject);
551                         gtk_widget_show (priv->hbox_topic);
552                 }
553                 if (priv->block_events_timeout_id == 0) {
554                         gchar *str;
555
556                         if (!EMP_STR_EMPTY (priv->subject)) {
557                                 str = g_strdup_printf (_("Topic set to: %s"), priv->subject);
558                         } else {
559                                 str = g_strdup (_("No topic defined"));
560                         }
561                         empathy_chat_view_append_event (EMPATHY_CHAT (chat)->view, str);
562                         g_free (str);
563                 }
564         }
565         else if (!tp_strdiff (name, "name")) {
566                 g_free (priv->name);
567                 priv->name = g_value_dup_string (value);
568                 g_object_notify (G_OBJECT (chat), "name");
569         }
570 }
571
572 static void
573 chat_input_text_buffer_changed_cb (GtkTextBuffer *buffer,
574                                    EmpathyChat    *chat)
575 {
576         EmpathyChatPriv *priv;
577         GtkTextIter     start, end;
578         gchar          *str;
579         gboolean        spell_checker = FALSE;
580
581         priv = GET_PRIV (chat);
582
583         if (gtk_text_buffer_get_char_count (buffer) == 0) {
584                 chat_composing_stop (chat);
585         } else {
586                 chat_composing_start (chat);
587         }
588
589         empathy_conf_get_bool (empathy_conf_get (),
590                               EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
591                               &spell_checker);
592
593         gtk_text_buffer_get_start_iter (buffer, &start);
594
595         if (!spell_checker) {
596                 gtk_text_buffer_get_end_iter (buffer, &end);
597                 gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
598                 return;
599         }
600
601         if (!empathy_spell_supported ()) {
602                 return;
603         }
604
605         /* NOTE: this is really inefficient, we shouldn't have to
606            reiterate the whole buffer each time and check each work
607            every time. */
608         while (TRUE) {
609                 gboolean correct = FALSE;
610
611                 /* if at start */
612                 if (gtk_text_iter_is_start (&start)) {
613                         end = start;
614
615                         if (!gtk_text_iter_forward_word_end (&end)) {
616                                 /* no whole word yet */
617                                 break;
618                         }
619                 } else {
620                         if (!gtk_text_iter_forward_word_end (&end)) {
621                                 /* must be the end of the buffer */
622                                 break;
623                         }
624
625                         start = end;
626                         gtk_text_iter_backward_word_start (&start);
627                 }
628
629                 str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
630
631                 /* spell check string if not a command */
632                 if (str[0] != '/') {
633                         correct = empathy_spell_check (str);
634                 } else {
635                         correct = TRUE;
636                 }
637
638                 if (!correct) {
639                         gtk_text_buffer_apply_tag_by_name (buffer, "misspelled", &start, &end);
640                 } else {
641                         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
642                 }
643
644                 g_free (str);
645
646                 /* set start iter to the end iters position */
647                 start = end;
648         }
649 }
650
651 static gboolean
652 chat_input_key_press_event_cb (GtkWidget   *widget,
653                                GdkEventKey *event,
654                                EmpathyChat *chat)
655 {
656         EmpathyChatPriv *priv;
657         GtkAdjustment  *adj;
658         gdouble         val;
659         GtkWidget      *text_view_sw;
660
661         priv = GET_PRIV (chat);
662
663         /* Catch ctrl+up/down so we can traverse messages we sent */
664         if ((event->state & GDK_CONTROL_MASK) && 
665             (event->keyval == GDK_Up || 
666              event->keyval == GDK_Down)) {
667                 GtkTextBuffer *buffer;
668                 const gchar   *str;
669
670                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
671
672                 if (event->keyval == GDK_Up) {
673                         str = chat_sent_message_get_next (chat);
674                 } else {
675                         str = chat_sent_message_get_last (chat);
676                 }
677
678                 g_signal_handlers_block_by_func (buffer, 
679                                                  chat_input_text_buffer_changed_cb,
680                                                  chat);
681                 gtk_text_buffer_set_text (buffer, str ? str : "", -1);
682                 g_signal_handlers_unblock_by_func (buffer, 
683                                                    chat_input_text_buffer_changed_cb,
684                                                    chat);
685
686                 return TRUE;    
687         }
688
689         /* Catch enter but not ctrl/shift-enter */
690         if (IS_ENTER (event->keyval) &&
691             !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
692                 GtkTextView *view;
693
694                 /* This is to make sure that kinput2 gets the enter. And if
695                  * it's handled there we shouldn't send on it. This is because
696                  * kinput2 uses Enter to commit letters. See:
697                  * http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=104299
698                  */
699
700                 view = GTK_TEXT_VIEW (chat->input_text_view);
701                 if (gtk_im_context_filter_keypress (view->im_context, event)) {
702                         GTK_TEXT_VIEW (chat->input_text_view)->need_im_reset = TRUE;
703                         return TRUE;
704                 }
705
706                 chat_input_text_view_send (chat);
707                 return TRUE;
708         }
709
710         text_view_sw = gtk_widget_get_parent (GTK_WIDGET (chat->view));
711
712         if (IS_ENTER (event->keyval) &&
713             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
714                 /* Newline for shift/control-enter. */
715                 return FALSE;
716         }
717         if (!(event->state & GDK_CONTROL_MASK) &&
718             event->keyval == GDK_Page_Up) {
719                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
720                 gtk_adjustment_set_value (adj, adj->value - adj->page_size);
721                 return TRUE;
722         }
723         if ((event->state & GDK_CONTROL_MASK) != GDK_CONTROL_MASK &&
724             event->keyval == GDK_Page_Down) {
725                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
726                 val = MIN (adj->value + adj->page_size, adj->upper - adj->page_size);
727                 gtk_adjustment_set_value (adj, val);
728                 return TRUE;
729         }
730         if (!(event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) &&
731             event->keyval == GDK_Tab) {
732                 GtkTextBuffer *buffer;
733                 GtkTextIter    start, current;
734                 gchar         *nick, *completed;
735                 GList         *list, *completed_list;
736                 gboolean       is_start_of_buffer;
737
738                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (EMPATHY_CHAT (chat)->input_text_view));
739                 gtk_text_buffer_get_iter_at_mark (buffer, &current, gtk_text_buffer_get_insert (buffer));
740
741                 /* Get the start of the nick to complete. */
742                 gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer));
743                 gtk_text_iter_backward_word_start (&start);
744                 is_start_of_buffer = gtk_text_iter_is_start (&start);
745
746                 list = empathy_contact_list_get_members (EMPATHY_CONTACT_LIST (priv->tp_chat));
747                 g_completion_add_items (priv->completion, list);
748
749                 nick = gtk_text_buffer_get_text (buffer, &start, &current, FALSE);
750                 completed_list = g_completion_complete (priv->completion,
751                                                         nick,
752                                                         &completed);
753
754                 g_free (nick);
755
756                 if (completed) {
757                         guint        len;
758                         const gchar *text;
759                         gchar       *complete_char = NULL;
760
761                         gtk_text_buffer_delete (buffer, &start, &current);
762
763                         len = g_list_length (completed_list);
764
765                         if (len == 1) {
766                                 /* If we only have one hit, use that text
767                                  * instead of the text in completed since the
768                                  * completed text will use the typed string
769                                  * which might be cased all wrong.
770                                  * Fixes #120876
771                                  * */
772                                 text = empathy_contact_get_name (completed_list->data);
773                         } else {
774                                 text = completed;
775                         }
776
777                         gtk_text_buffer_insert_at_cursor (buffer, text, strlen (text));
778
779                         if (len == 1 && is_start_of_buffer &&
780                             empathy_conf_get_string (empathy_conf_get (),
781                                                      EMPATHY_PREFS_CHAT_NICK_COMPLETION_CHAR,
782                                                      &complete_char) &&
783                             complete_char != NULL) {
784                                 gtk_text_buffer_insert_at_cursor (buffer,
785                                                                   complete_char,
786                                                                   strlen (complete_char));
787                                 gtk_text_buffer_insert_at_cursor (buffer, " ", 1);
788                                 g_free (complete_char);
789                         }
790
791                         g_free (completed);
792                 }
793
794                 g_completion_clear_items (priv->completion);
795
796                 g_list_foreach (list, (GFunc) g_object_unref, NULL);
797                 g_list_free (list);
798
799                 return TRUE;
800         }
801
802         return FALSE;
803 }
804
805 static gboolean
806 chat_text_view_focus_in_event_cb (GtkWidget  *widget,
807                                   GdkEvent   *event,
808                                   EmpathyChat *chat)
809 {
810         gtk_widget_grab_focus (chat->input_text_view);
811
812         return TRUE;
813 }
814
815 static gboolean
816 chat_input_set_size_request_idle (gpointer sw)
817 {
818         gtk_widget_set_size_request (sw, -1, MAX_INPUT_HEIGHT);
819
820         return FALSE;
821 }
822
823 static void
824 chat_input_size_request_cb (GtkWidget      *widget,
825                             GtkRequisition *requisition,
826                             EmpathyChat    *chat)
827 {
828         EmpathyChatPriv *priv = GET_PRIV (chat);
829         GtkWidget       *sw;
830
831         sw = gtk_widget_get_parent (widget);
832         if (requisition->height >= MAX_INPUT_HEIGHT && !priv->has_input_vscroll) {
833                 g_idle_add (chat_input_set_size_request_idle, sw);
834                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
835                                                 GTK_POLICY_NEVER,
836                                                 GTK_POLICY_ALWAYS);
837                 priv->has_input_vscroll = TRUE;
838         }
839
840         if (requisition->height < MAX_INPUT_HEIGHT && priv->has_input_vscroll) {
841                 gtk_widget_set_size_request (sw, -1, -1);
842                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
843                                                 GTK_POLICY_NEVER,
844                                                 GTK_POLICY_NEVER);
845                 priv->has_input_vscroll = FALSE;
846         }
847 }
848
849 static void
850 chat_input_realize_cb (GtkWidget   *widget,
851                        EmpathyChat *chat)
852 {
853         DEBUG ("Setting focus to the input text view");
854         gtk_widget_grab_focus (widget);
855 }
856
857 static void
858 chat_insert_smiley_activate_cb (EmpathySmileyManager *manager,
859                                 EmpathySmiley        *smiley,
860                                 gpointer              user_data)
861 {
862         EmpathyChat   *chat = EMPATHY_CHAT (user_data);
863         GtkTextBuffer *buffer;
864         GtkTextIter    iter;
865
866         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
867
868         gtk_text_buffer_get_end_iter (buffer, &iter);
869         gtk_text_buffer_insert (buffer, &iter, smiley->str, -1);
870
871         gtk_text_buffer_get_end_iter (buffer, &iter);
872         gtk_text_buffer_insert (buffer, &iter, " ", -1);
873 }
874
875 typedef struct {
876         EmpathyChat  *chat;
877         gchar       *word;
878
879         GtkTextIter  start;
880         GtkTextIter  end;
881 } EmpathyChatSpell;
882
883 static EmpathyChatSpell *
884 chat_spell_new (EmpathyChat  *chat,
885                 const gchar *word,
886                 GtkTextIter  start,
887                 GtkTextIter  end)
888 {
889         EmpathyChatSpell *chat_spell;
890
891         chat_spell = g_slice_new0 (EmpathyChatSpell);
892
893         chat_spell->chat = g_object_ref (chat);
894         chat_spell->word = g_strdup (word);
895         chat_spell->start = start;
896         chat_spell->end = end;
897
898         return chat_spell;
899 }
900
901 static void
902 chat_spell_free (EmpathyChatSpell *chat_spell)
903 {
904         g_object_unref (chat_spell->chat);
905         g_free (chat_spell->word);
906         g_slice_free (EmpathyChatSpell, chat_spell);
907 }
908
909 static void
910 chat_text_check_word_spelling_cb (GtkMenuItem     *menuitem,
911                                   EmpathyChatSpell *chat_spell)
912 {
913         empathy_spell_dialog_show (chat_spell->chat,
914                                   &chat_spell->start,
915                                   &chat_spell->end,
916                                   chat_spell->word);
917 }
918
919 static void
920 chat_text_send_cb (GtkMenuItem *menuitem,
921                    EmpathyChat *chat)
922 {
923         chat_input_text_view_send (chat);
924 }
925
926 static void
927 chat_input_populate_popup_cb (GtkTextView *view,
928                               GtkMenu     *menu,
929                               EmpathyChat *chat)
930 {
931         EmpathyChatPriv      *priv;
932         GtkTextBuffer        *buffer;
933         GtkTextTagTable      *table;
934         GtkTextTag           *tag;
935         gint                  x, y;
936         GtkTextIter           iter, start, end;
937         GtkWidget            *item;
938         gchar                *str = NULL;
939         EmpathyChatSpell      *chat_spell;
940         EmpathySmileyManager *smiley_manager;
941         GtkWidget            *smiley_menu;
942         GtkWidget            *image;
943
944         priv = GET_PRIV (chat);
945         buffer = gtk_text_view_get_buffer (view);
946
947         /* Add the emoticon menu. */
948         item = gtk_separator_menu_item_new ();
949         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
950         gtk_widget_show (item);
951
952         item = gtk_image_menu_item_new_with_mnemonic (_("Insert Smiley"));
953         image = gtk_image_new_from_icon_name ("face-smile",
954                                               GTK_ICON_SIZE_MENU);
955         gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
956         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
957         gtk_widget_show (item);
958
959         smiley_manager = empathy_smiley_manager_dup_singleton ();
960         smiley_menu = empathy_smiley_menu_new (smiley_manager,
961                                                chat_insert_smiley_activate_cb,
962                                                chat);
963         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), smiley_menu);
964         g_object_unref (smiley_manager);
965
966         /* Add the Send menu item. */
967         gtk_text_buffer_get_bounds (buffer, &start, &end);
968         str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
969         if (!EMP_STR_EMPTY (str)) {
970                 item = gtk_menu_item_new_with_mnemonic (_("_Send"));
971                 g_signal_connect (G_OBJECT (item), "activate",
972                                   G_CALLBACK (chat_text_send_cb), chat);
973                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
974                 gtk_widget_show (item);
975         }
976         str = NULL;
977
978         /* Add the spell check menu item. */
979         table = gtk_text_buffer_get_tag_table (buffer);
980         tag = gtk_text_tag_table_lookup (table, "misspelled");
981         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
982         gtk_text_view_window_to_buffer_coords (GTK_TEXT_VIEW (view),
983                                                GTK_TEXT_WINDOW_WIDGET,
984                                                x, y,
985                                                &x, &y);
986         gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW (view), &iter, x, y);
987         start = end = iter;
988         if (gtk_text_iter_backward_to_tag_toggle (&start, tag) &&
989             gtk_text_iter_forward_to_tag_toggle (&end, tag)) {
990
991                 str = gtk_text_buffer_get_text (buffer,
992                                                 &start, &end, FALSE);
993         }
994         if (!EMP_STR_EMPTY (str)) {
995                 chat_spell = chat_spell_new (chat, str, start, end);
996                 g_object_set_data_full (G_OBJECT (menu),
997                                         "chat_spell", chat_spell,
998                                         (GDestroyNotify) chat_spell_free);
999
1000                 item = gtk_separator_menu_item_new ();
1001                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1002                 gtk_widget_show (item);
1003
1004                 item = gtk_image_menu_item_new_with_mnemonic (_("_Check Word Spelling..."));
1005                 image = gtk_image_new_from_icon_name (GTK_STOCK_SPELL_CHECK,
1006                                                       GTK_ICON_SIZE_MENU);
1007                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
1008                 g_signal_connect (item,
1009                                   "activate",
1010                                   G_CALLBACK (chat_text_check_word_spelling_cb),
1011                                   chat_spell);
1012                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1013                 gtk_widget_show (item);
1014         }
1015 }
1016
1017 static gboolean
1018 chat_log_filter (EmpathyMessage *message,
1019                  gpointer user_data)
1020 {
1021         EmpathyChat *chat = (EmpathyChat *) user_data;
1022         EmpathyChatPriv *priv = GET_PRIV (chat);
1023         const GList *pending;
1024
1025         pending = empathy_tp_chat_get_pending_messages (priv->tp_chat);
1026
1027         for (; pending; pending = g_list_next (pending)) {
1028                 if (empathy_message_equal (message, pending->data)) {
1029                         return FALSE;
1030                 }
1031         }
1032
1033         return TRUE;
1034 }
1035
1036 static void
1037 chat_add_logs (EmpathyChat *chat)
1038 {
1039         EmpathyChatPriv *priv = GET_PRIV (chat);
1040         gboolean         is_chatroom;
1041         GList           *messages, *l;
1042
1043         if (!priv->id) {
1044                 return;
1045         }
1046
1047         /* Turn off scrolling temporarily */
1048         empathy_chat_view_scroll (chat->view, FALSE);
1049
1050         /* Add messages from last conversation */
1051         is_chatroom = priv->handle_type == TP_HANDLE_TYPE_ROOM;
1052
1053         messages = empathy_log_manager_get_filtered_messages (priv->log_manager,
1054                                                               priv->account,
1055                                                               priv->id,
1056                                                               is_chatroom,
1057                                                               5,
1058                                                               chat_log_filter,
1059                                                               chat);
1060
1061         for (l = messages; l; l = g_list_next (l)) {
1062                 empathy_chat_view_append_message (chat->view, l->data);
1063                 g_object_unref (l->data);
1064         }
1065
1066         g_list_free (messages);
1067
1068         /* Turn back on scrolling */
1069         empathy_chat_view_scroll (chat->view, TRUE);
1070 }
1071
1072 static gint
1073 chat_contacts_completion_func (const gchar *s1,
1074                                const gchar *s2,
1075                                gsize        n)
1076 {
1077         gchar *tmp, *nick1, *nick2;
1078         gint   ret;
1079
1080         if (s1 == s2) {
1081                 return 0;
1082         }
1083         if (!s1 || !s2) {
1084                 return s1 ? -1 : +1;
1085         }
1086
1087         tmp = g_utf8_normalize (s1, -1, G_NORMALIZE_DEFAULT);
1088         nick1 = g_utf8_casefold (tmp, -1);
1089         g_free (tmp);
1090
1091         tmp = g_utf8_normalize (s2, -1, G_NORMALIZE_DEFAULT);
1092         nick2 = g_utf8_casefold (tmp, -1);
1093         g_free (tmp);
1094
1095         ret = strncmp (nick1, nick2, n);
1096
1097         g_free (nick1);
1098         g_free (nick2);
1099
1100         return ret;
1101 }
1102
1103 static void
1104 chat_members_changed_cb (EmpathyTpChat  *tp_chat,
1105                          EmpathyContact *contact,
1106                          EmpathyContact *actor,
1107                          guint           reason,
1108                          gchar          *message,
1109                          gboolean        is_member,
1110                          EmpathyChat    *chat)
1111 {
1112         EmpathyChatPriv *priv = GET_PRIV (chat);
1113
1114         if (priv->block_events_timeout_id == 0) {
1115                 gchar *str;
1116
1117                 empathy_contact_run_until_ready (contact,
1118                                                  EMPATHY_CONTACT_READY_NAME,
1119                                                  NULL);
1120
1121                 if (is_member) {
1122                         str = g_strdup_printf (_("%s has joined the room"),
1123                                                empathy_contact_get_name (contact));
1124                 } else {
1125                         str = g_strdup_printf (_("%s has left the room"),
1126                                                empathy_contact_get_name (contact));
1127                 }
1128                 empathy_chat_view_append_event (chat->view, str);
1129                 g_free (str);
1130         }
1131 }
1132
1133 static gboolean
1134 chat_reset_size_request (gpointer widget)
1135 {
1136         gtk_widget_set_size_request (widget, -1, -1);
1137
1138         return FALSE;
1139 }
1140
1141 static void
1142 chat_set_show_contacts (EmpathyChat *chat, gboolean show)
1143 {
1144         EmpathyChatPriv *priv = GET_PRIV (chat);
1145
1146         if (!priv->scrolled_window_contacts) {
1147                 return;
1148         }
1149
1150         if (show) {
1151                 EmpathyContactListStore *store;
1152                 gint                     min_width;
1153
1154                 /* We are adding the contact list to the chat, we don't want the
1155                  * chat view to become too small. If the chat view is already
1156                  * smaller than 250 make sure that size won't change. If the
1157                  * chat view is bigger the contact list will take some space on
1158                  * it but we make sure the chat view don't become smaller than
1159                  * 250. Relax the size request once the resize is done */
1160                 min_width = MIN (priv->vbox_left->allocation.width, 250);
1161                 gtk_widget_set_size_request (priv->vbox_left, min_width, -1);
1162                 g_idle_add (chat_reset_size_request, priv->vbox_left);
1163
1164                 if (priv->contacts_width > 0) {
1165                         gtk_paned_set_position (GTK_PANED (priv->hpaned),
1166                                                 priv->contacts_width);
1167                 }
1168
1169                 store = empathy_contact_list_store_new (EMPATHY_CONTACT_LIST (priv->tp_chat));
1170                 priv->contact_list_view = GTK_WIDGET (empathy_contact_list_view_new (store,
1171                         EMPATHY_CONTACT_LIST_FEATURE_NONE,
1172                         EMPATHY_CONTACT_FEATURE_CHAT |
1173                         EMPATHY_CONTACT_FEATURE_CALL |
1174                         EMPATHY_CONTACT_FEATURE_LOG |
1175                         EMPATHY_CONTACT_FEATURE_INFO));
1176                 gtk_container_add (GTK_CONTAINER (priv->scrolled_window_contacts),
1177                                    priv->contact_list_view);
1178                 gtk_widget_show (priv->contact_list_view);
1179                 gtk_widget_show (priv->scrolled_window_contacts);
1180                 g_object_unref (store);
1181         } else {
1182                 priv->contacts_width = gtk_paned_get_position (GTK_PANED (priv->hpaned));
1183                 gtk_widget_hide (priv->scrolled_window_contacts);
1184                 if (priv->contact_list_view) {
1185                         gtk_widget_destroy (priv->contact_list_view);
1186                         priv->contact_list_view = NULL;
1187                 }
1188         }
1189 }
1190
1191 static void
1192 chat_remote_contact_changed_cb (EmpathyChat *chat)
1193 {
1194         EmpathyChatPriv *priv = GET_PRIV (chat);
1195
1196         if (priv->remote_contact) {
1197                 g_object_unref (priv->remote_contact);
1198                 priv->remote_contact = NULL;
1199         }
1200
1201         priv->remote_contact = empathy_tp_chat_get_remote_contact (priv->tp_chat);
1202         if (priv->remote_contact) {
1203                 g_object_ref (priv->remote_contact);
1204                 priv->handle_type = TP_HANDLE_TYPE_CONTACT;
1205                 g_free (priv->id);
1206                 priv->id = g_strdup (empathy_contact_get_id (priv->remote_contact));
1207         }
1208         else if (priv->tp_chat) {
1209                 TpChannel *channel;
1210
1211                 channel = empathy_tp_chat_get_channel (priv->tp_chat);
1212                 g_object_get (channel, "handle-type", &priv->handle_type, NULL);
1213                 g_free (priv->id);
1214                 priv->id = g_strdup (empathy_tp_chat_get_id (priv->tp_chat));
1215         }
1216
1217         chat_set_show_contacts (chat, priv->remote_contact == NULL);
1218
1219         g_object_notify (G_OBJECT (chat), "remote-contact");
1220         g_object_notify (G_OBJECT (chat), "id");
1221 }
1222
1223 static void
1224 chat_destroy_cb (EmpathyTpChat *tp_chat,
1225                  EmpathyChat   *chat)
1226 {
1227         EmpathyChatPriv *priv;
1228
1229         priv = GET_PRIV (chat);
1230
1231         if (!priv->tp_chat) {
1232                 return;
1233         }
1234
1235         chat_composing_remove_timeout (chat);
1236         g_object_unref (priv->tp_chat);
1237         priv->tp_chat = NULL;
1238         g_object_notify (G_OBJECT (chat), "tp-chat");
1239
1240         empathy_chat_view_append_event (chat->view, _("Disconnected"));
1241         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
1242         chat_set_show_contacts (chat, FALSE);
1243 }
1244
1245 static void
1246 show_pending_messages (EmpathyChat *chat) {
1247         EmpathyChatPriv *priv = GET_PRIV (chat);
1248         const GList *messages, *l;
1249
1250         if (chat->view == NULL || priv->tp_chat == NULL)
1251                 return;
1252
1253         messages = empathy_tp_chat_get_pending_messages (priv->tp_chat);
1254
1255         for (l = messages; l != NULL ; l = g_list_next (l)) {
1256                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
1257                 chat_message_received (chat, message);
1258         }
1259         empathy_tp_chat_acknowledge_messages (priv->tp_chat, messages);
1260 }
1261
1262 static void
1263 chat_create_ui (EmpathyChat *chat)
1264 {
1265         EmpathyChatPriv *priv = GET_PRIV (chat);
1266         GladeXML        *glade;
1267         GList           *list = NULL; 
1268         gchar           *filename;
1269         GtkTextBuffer   *buffer;
1270
1271         filename = empathy_file_lookup ("empathy-chat.glade",
1272                                         "libempathy-gtk");
1273         glade = empathy_glade_get_file (filename,
1274                                         "chat_widget",
1275                                         NULL,
1276                                         "chat_widget", &priv->widget,
1277                                         "hpaned", &priv->hpaned,
1278                                         "vbox_left", &priv->vbox_left,
1279                                         "scrolled_window_chat", &priv->scrolled_window_chat,
1280                                         "scrolled_window_input", &priv->scrolled_window_input,
1281                                         "hbox_topic", &priv->hbox_topic,
1282                                         "label_topic", &priv->label_topic,
1283                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
1284                                         NULL);
1285         g_free (filename);
1286         g_object_unref (glade);
1287
1288         /* Add message view. */
1289         chat->view = empathy_theme_manager_create_view (empathy_theme_manager_get ());
1290         g_signal_connect (chat->view, "focus_in_event",
1291                           G_CALLBACK (chat_text_view_focus_in_event_cb),
1292                           chat);
1293         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
1294                            GTK_WIDGET (chat->view));
1295         gtk_widget_show (GTK_WIDGET (chat->view));
1296
1297         /* Add input GtkTextView */
1298         chat->input_text_view = g_object_new (GTK_TYPE_TEXT_VIEW,
1299                                               "pixels-above-lines", 2,
1300                                               "pixels-below-lines", 2,
1301                                               "pixels-inside-wrap", 1,
1302                                               "right-margin", 2,
1303                                               "left-margin", 2,
1304                                               "wrap-mode", GTK_WRAP_WORD_CHAR,
1305                                               NULL);
1306         g_signal_connect (chat->input_text_view, "key-press-event",
1307                           G_CALLBACK (chat_input_key_press_event_cb),
1308                           chat);
1309         g_signal_connect (chat->input_text_view, "size-request",
1310                           G_CALLBACK (chat_input_size_request_cb),
1311                           chat);
1312         g_signal_connect (chat->input_text_view, "realize",
1313                           G_CALLBACK (chat_input_realize_cb),
1314                           chat);
1315         g_signal_connect (chat->input_text_view, "populate-popup",
1316                           G_CALLBACK (chat_input_populate_popup_cb),
1317                           chat);
1318         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1319         g_signal_connect (buffer, "changed",
1320                           G_CALLBACK (chat_input_text_buffer_changed_cb),
1321                           chat);
1322         gtk_text_buffer_create_tag (buffer, "misspelled",
1323                                     "underline", PANGO_UNDERLINE_ERROR,
1324                                     NULL);
1325         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
1326                            chat->input_text_view);
1327         gtk_widget_show (chat->input_text_view);
1328
1329         /* Create contact list */
1330         chat_set_show_contacts (chat, priv->remote_contact == NULL);
1331
1332         /* Initialy hide the topic, will be shown if not empty */
1333         gtk_widget_hide (priv->hbox_topic);
1334
1335         /* Set widget focus order */
1336         list = g_list_append (NULL, priv->scrolled_window_input);
1337         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
1338         g_list_free (list);
1339
1340         list = g_list_append (NULL, priv->vbox_left);
1341         list = g_list_append (list, priv->scrolled_window_contacts);
1342         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
1343         g_list_free (list);
1344
1345         list = g_list_append (NULL, priv->hpaned);
1346         list = g_list_append (list, priv->hbox_topic);
1347         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
1348         g_list_free (list);
1349
1350         /* Add the main widget in the chat widget */
1351         gtk_container_add (GTK_CONTAINER (chat), priv->widget);
1352 }
1353
1354 static void
1355 chat_size_request (GtkWidget      *widget,
1356                    GtkRequisition *requisition)
1357 {
1358   GtkBin *bin = GTK_BIN (widget);
1359
1360   requisition->width = GTK_CONTAINER (widget)->border_width * 2;
1361   requisition->height = GTK_CONTAINER (widget)->border_width * 2;
1362
1363   if (bin->child && GTK_WIDGET_VISIBLE (bin->child))
1364     {
1365       GtkRequisition child_requisition;
1366       
1367       gtk_widget_size_request (bin->child, &child_requisition);
1368
1369       requisition->width += child_requisition.width;
1370       requisition->height += child_requisition.height;
1371     }
1372 }
1373
1374 static void
1375 chat_size_allocate (GtkWidget     *widget,
1376                     GtkAllocation *allocation)
1377 {
1378   GtkBin *bin = GTK_BIN (widget);
1379   GtkAllocation child_allocation;
1380   
1381   widget->allocation = *allocation;
1382
1383   if (bin->child && GTK_WIDGET_VISIBLE (bin->child))
1384     {
1385       child_allocation.x = allocation->x + GTK_CONTAINER (widget)->border_width;
1386       child_allocation.y = allocation->y + GTK_CONTAINER (widget)->border_width;
1387       child_allocation.width = MAX (allocation->width - GTK_CONTAINER (widget)->border_width * 2, 0);
1388       child_allocation.height = MAX (allocation->height - GTK_CONTAINER (widget)->border_width * 2, 0);
1389
1390       gtk_widget_size_allocate (bin->child, &child_allocation);
1391     }
1392 }
1393
1394 static void
1395 chat_finalize (GObject *object)
1396 {
1397         EmpathyChat     *chat;
1398         EmpathyChatPriv *priv;
1399
1400         chat = EMPATHY_CHAT (object);
1401         priv = GET_PRIV (chat);
1402
1403         DEBUG ("Finalized: %p", object);
1404
1405         g_slist_foreach (priv->sent_messages, (GFunc) g_free, NULL);
1406         g_slist_free (priv->sent_messages);
1407
1408         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
1409         g_list_free (priv->compositors);
1410
1411         chat_composing_remove_timeout (chat);
1412
1413         g_signal_handlers_disconnect_by_func (priv->account_manager,
1414                                               chat_connection_changed_cb, object);
1415
1416         g_object_unref (priv->account_manager);
1417         g_object_unref (priv->log_manager);
1418
1419         if (priv->tp_chat) {
1420                 g_signal_handler_disconnect (priv->tp_chat, priv->tp_chat_destroy_handler);
1421                 empathy_tp_chat_close (priv->tp_chat);
1422                 g_object_unref (priv->tp_chat);
1423         }
1424         if (priv->account) {
1425                 g_object_unref (priv->account);
1426         }
1427         if (priv->remote_contact) {
1428                 g_object_unref (priv->remote_contact);
1429         }
1430
1431         if (priv->block_events_timeout_id) {
1432                 g_source_remove (priv->block_events_timeout_id);
1433         }
1434
1435         g_free (priv->id);
1436         g_free (priv->name);
1437         g_free (priv->subject);
1438         g_completion_free (priv->completion);
1439
1440         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
1441 }
1442
1443 static void
1444 chat_constructed (GObject *object)
1445 {
1446         EmpathyChat *chat = EMPATHY_CHAT (object);
1447
1448         chat_create_ui (chat);
1449         chat_add_logs (chat);
1450         show_pending_messages (chat);
1451 }
1452
1453 static void
1454 empathy_chat_class_init (EmpathyChatClass *klass)
1455 {
1456         GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
1457         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
1458
1459         object_class->finalize = chat_finalize;
1460         object_class->get_property = chat_get_property;
1461         object_class->set_property = chat_set_property;
1462         object_class->constructed = chat_constructed;
1463
1464         widget_class->size_request = chat_size_request;
1465         widget_class->size_allocate = chat_size_allocate;
1466
1467         g_object_class_install_property (object_class,
1468                                          PROP_TP_CHAT,
1469                                          g_param_spec_object ("tp-chat",
1470                                                               "Empathy tp chat",
1471                                                               "The tp chat object",
1472                                                               EMPATHY_TYPE_TP_CHAT,
1473                                                               G_PARAM_CONSTRUCT |
1474                                                               G_PARAM_READWRITE));
1475         g_object_class_install_property (object_class,
1476                                          PROP_ACCOUNT,
1477                                          g_param_spec_object ("account",
1478                                                               "Account of the chat",
1479                                                               "The account of the chat",
1480                                                               MC_TYPE_ACCOUNT,
1481                                                               G_PARAM_READABLE));
1482         g_object_class_install_property (object_class,
1483                                          PROP_ID,
1484                                          g_param_spec_string ("id",
1485                                                               "Chat's id",
1486                                                               "The id of the chat",
1487                                                               NULL,
1488                                                               G_PARAM_READABLE));
1489         g_object_class_install_property (object_class,
1490                                          PROP_NAME,
1491                                          g_param_spec_string ("name",
1492                                                               "Chat's name",
1493                                                               "The name of the chat",
1494                                                               NULL,
1495                                                               G_PARAM_READABLE));
1496         g_object_class_install_property (object_class,
1497                                          PROP_SUBJECT,
1498                                          g_param_spec_string ("subject",
1499                                                               "Chat's subject",
1500                                                               "The subject or topic of the chat",
1501                                                               NULL,
1502                                                               G_PARAM_READABLE));
1503         g_object_class_install_property (object_class,
1504                                          PROP_REMOTE_CONTACT,
1505                                          g_param_spec_object ("remote-contact",
1506                                                               "The remote contact",
1507                                                               "The remote contact is any",
1508                                                               EMPATHY_TYPE_CONTACT,
1509                                                               G_PARAM_READABLE));
1510
1511         signals[COMPOSING] =
1512                 g_signal_new ("composing",
1513                               G_OBJECT_CLASS_TYPE (object_class),
1514                               G_SIGNAL_RUN_LAST,
1515                               0,
1516                               NULL, NULL,
1517                               g_cclosure_marshal_VOID__BOOLEAN,
1518                               G_TYPE_NONE,
1519                               1, G_TYPE_BOOLEAN);
1520
1521         signals[NEW_MESSAGE] =
1522                 g_signal_new ("new-message",
1523                               G_OBJECT_CLASS_TYPE (object_class),
1524                               G_SIGNAL_RUN_LAST,
1525                               0,
1526                               NULL, NULL,
1527                               g_cclosure_marshal_VOID__OBJECT,
1528                               G_TYPE_NONE,
1529                               1, EMPATHY_TYPE_MESSAGE);
1530
1531         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
1532 }
1533
1534 static gboolean
1535 chat_block_events_timeout_cb (gpointer data)
1536 {
1537         EmpathyChatPriv *priv = GET_PRIV (data);
1538
1539         priv->block_events_timeout_id = 0;
1540
1541         return FALSE;
1542 }
1543
1544 static void
1545 empathy_chat_init (EmpathyChat *chat)
1546 {
1547         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
1548                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
1549
1550         chat->priv = priv;
1551         priv->log_manager = empathy_log_manager_dup_singleton ();
1552         priv->contacts_width = -1;
1553         priv->sent_messages = NULL;
1554         priv->sent_messages_index = -1;
1555         priv->account_manager = empathy_account_manager_dup_singleton ();
1556
1557         g_signal_connect (priv->account_manager,
1558                           "account-connection-changed",
1559                           G_CALLBACK (chat_connection_changed_cb),
1560                           chat);
1561
1562         /* Block events for some time to avoid having "has come online" or
1563          * "joined" messages. */
1564         priv->block_events_timeout_id =
1565                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
1566
1567         /* Add nick name completion */
1568         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_name);
1569         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
1570 }
1571
1572 EmpathyChat *
1573 empathy_chat_new (EmpathyTpChat *tp_chat)
1574 {
1575         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
1576 }
1577
1578 EmpathyTpChat *
1579 empathy_chat_get_tp_chat (EmpathyChat *chat)
1580 {
1581         EmpathyChatPriv *priv = GET_PRIV (chat);
1582
1583         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1584
1585         return priv->tp_chat;
1586 }
1587
1588 void
1589 empathy_chat_set_tp_chat (EmpathyChat   *chat,
1590                           EmpathyTpChat *tp_chat)
1591 {
1592         EmpathyChatPriv *priv = GET_PRIV (chat);
1593
1594         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1595         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
1596         g_return_if_fail (empathy_tp_chat_is_ready (tp_chat));
1597
1598         if (priv->tp_chat) {
1599                 return;
1600         }
1601
1602         if (priv->account) {
1603                 g_object_unref (priv->account);
1604         }
1605
1606         priv->tp_chat = g_object_ref (tp_chat);
1607         priv->account = g_object_ref (empathy_tp_chat_get_account (tp_chat));
1608
1609         g_signal_connect (tp_chat, "message-received",
1610                           G_CALLBACK (chat_message_received_cb),
1611                           chat);
1612         g_signal_connect (tp_chat, "send-error",
1613                           G_CALLBACK (chat_send_error_cb),
1614                           chat);
1615         g_signal_connect (tp_chat, "chat-state-changed",
1616                           G_CALLBACK (chat_state_changed_cb),
1617                           chat);
1618         g_signal_connect (tp_chat, "property-changed",
1619                           G_CALLBACK (chat_property_changed_cb),
1620                           chat);
1621         g_signal_connect (tp_chat, "members-changed",
1622                           G_CALLBACK (chat_members_changed_cb),
1623                           chat);
1624         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
1625                                   G_CALLBACK (chat_remote_contact_changed_cb),
1626                                   chat);
1627         priv->tp_chat_destroy_handler =
1628                 g_signal_connect (tp_chat, "destroy",
1629                           G_CALLBACK (chat_destroy_cb),
1630                           chat);
1631
1632         chat_remote_contact_changed_cb (chat);
1633
1634         if (chat->input_text_view) {
1635                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
1636                 if (priv->block_events_timeout_id == 0) {
1637                         empathy_chat_view_append_event (chat->view, _("Connected"));
1638                 }
1639         }
1640
1641         g_object_notify (G_OBJECT (chat), "tp-chat");
1642         g_object_notify (G_OBJECT (chat), "id");
1643         g_object_notify (G_OBJECT (chat), "account");
1644
1645         /* This is a noop when tp-chat is set at object construction time and causes
1646          * the pending messages to be show when it's set on the object after it has
1647          * been created */
1648         show_pending_messages (chat);
1649 }
1650
1651 McAccount *
1652 empathy_chat_get_account (EmpathyChat *chat)
1653 {
1654         EmpathyChatPriv *priv = GET_PRIV (chat);
1655
1656         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1657
1658         return priv->account;
1659 }
1660
1661 const gchar *
1662 empathy_chat_get_id (EmpathyChat *chat)
1663 {
1664         EmpathyChatPriv *priv = GET_PRIV (chat);
1665
1666         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1667
1668         return priv->id;
1669 }
1670
1671 const gchar *
1672 empathy_chat_get_name (EmpathyChat *chat)
1673 {
1674         EmpathyChatPriv *priv = GET_PRIV (chat);
1675         const gchar *ret;
1676
1677         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1678
1679         ret = priv->name;
1680         if (!ret && priv->remote_contact) {
1681                 ret = empathy_contact_get_name (priv->remote_contact);
1682         }
1683
1684         if (!ret)
1685                 ret = priv->id;
1686
1687         return ret ? ret : _("Conversation");
1688 }
1689
1690 const gchar *
1691 empathy_chat_get_subject (EmpathyChat *chat)
1692 {
1693         EmpathyChatPriv *priv = GET_PRIV (chat);
1694
1695         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1696
1697         return priv->subject;
1698 }
1699
1700 EmpathyContact *
1701 empathy_chat_get_remote_contact (EmpathyChat *chat)
1702 {
1703         EmpathyChatPriv *priv = GET_PRIV (chat);
1704
1705         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1706
1707         return priv->remote_contact;
1708 }
1709
1710 guint
1711 empathy_chat_get_members_count (EmpathyChat *chat)
1712 {
1713         EmpathyChatPriv *priv = GET_PRIV (chat);
1714
1715         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), 0);
1716
1717         if (priv->tp_chat) {
1718                 return empathy_tp_chat_get_members_count (priv->tp_chat);
1719         }
1720
1721         return 0;
1722 }
1723
1724 GtkWidget *
1725 empathy_chat_get_contact_menu (EmpathyChat *chat)
1726 {
1727         EmpathyChatPriv *priv = GET_PRIV (chat);
1728         GtkWidget       *menu = NULL;
1729
1730         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1731
1732         if (priv->remote_contact) {
1733                 menu = empathy_contact_menu_new (priv->remote_contact,
1734                                                  EMPATHY_CONTACT_FEATURE_CALL |
1735                                                  EMPATHY_CONTACT_FEATURE_LOG |
1736                                                  EMPATHY_CONTACT_FEATURE_INFO);
1737         }
1738         else if (priv->contact_list_view) {
1739                 EmpathyContactListView *view;
1740
1741                 view = EMPATHY_CONTACT_LIST_VIEW (priv->contact_list_view);
1742                 menu = empathy_contact_list_view_get_contact_menu (view);
1743         }
1744
1745         return menu;
1746 }
1747
1748 void
1749 empathy_chat_clear (EmpathyChat *chat)
1750 {
1751         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1752
1753         empathy_chat_view_clear (chat->view);
1754 }
1755
1756 void
1757 empathy_chat_scroll_down (EmpathyChat *chat)
1758 {
1759         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1760
1761         empathy_chat_view_scroll_down (chat->view);
1762 }
1763
1764 void
1765 empathy_chat_cut (EmpathyChat *chat)
1766 {
1767         GtkTextBuffer *buffer;
1768
1769         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1770
1771         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1772         if (gtk_text_buffer_get_has_selection (buffer)) {
1773                 GtkClipboard *clipboard;
1774
1775                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
1776
1777                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
1778         }
1779 }
1780
1781 void
1782 empathy_chat_copy (EmpathyChat *chat)
1783 {
1784         GtkTextBuffer *buffer;
1785
1786         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1787
1788         if (empathy_chat_view_get_has_selection (chat->view)) {
1789                 empathy_chat_view_copy_clipboard (chat->view);
1790                 return;
1791         }
1792
1793         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1794         if (gtk_text_buffer_get_has_selection (buffer)) {
1795                 GtkClipboard *clipboard;
1796
1797                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
1798
1799                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
1800         }
1801 }
1802
1803 void
1804 empathy_chat_paste (EmpathyChat *chat)
1805 {
1806         GtkTextBuffer *buffer;
1807         GtkClipboard  *clipboard;
1808
1809         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1810
1811         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1812         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
1813
1814         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
1815 }
1816
1817 void
1818 empathy_chat_correct_word (EmpathyChat  *chat,
1819                           GtkTextIter *start,
1820                           GtkTextIter *end,
1821                           const gchar *new_word)
1822 {
1823         GtkTextBuffer *buffer;
1824
1825         g_return_if_fail (chat != NULL);
1826         g_return_if_fail (new_word != NULL);
1827
1828         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1829
1830         gtk_text_buffer_delete (buffer, start, end);
1831         gtk_text_buffer_insert (buffer, start,
1832                                 new_word,
1833                                 -1);
1834 }
1835
1836 gboolean
1837 empathy_chat_is_room (EmpathyChat *chat)
1838 {
1839         EmpathyChatPriv *priv = GET_PRIV (chat);
1840
1841         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
1842
1843         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
1844 }
1845