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