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