]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
Move modules that make no sense to be used in other applicaton from libempathy-gtk...
[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.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-geometry.h"
46 #include "empathy-conf.h"
47 #include "empathy-spell.h"
48 #include "empathy-spell-dialog.h"
49 #include "empathy-ui-utils.h"
50 #include "empathy-gtk-marshal.h"
51
52 #define GET_PRIV(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), EMPATHY_TYPE_CHAT, EmpathyChatPriv))
53
54 #define DEBUG_DOMAIN "Chat"
55
56 #define CHAT_DIR_CREATE_MODE  (S_IRUSR | S_IWUSR | S_IXUSR)
57 #define CHAT_FILE_CREATE_MODE (S_IRUSR | S_IWUSR)
58
59 #define IS_ENTER(v) (v == GDK_Return || v == GDK_ISO_Enter || v == GDK_KP_Enter)
60
61 #define MAX_INPUT_HEIGHT 150
62
63 #define COMPOSING_STOP_TIMEOUT 5
64
65 struct _EmpathyChatPriv {
66         EmpathyLogManager     *log_manager;
67         EmpathyTpChat         *tp_chat;
68         McAccount             *account;
69         MissionControl        *mc;
70         GtkWidget             *widget;
71         guint                  composing_stop_timeout_id;
72         gboolean               sensitive;
73         gchar                 *id;
74         GSList                *sent_messages;
75         gint                   sent_messages_index;
76         GList                 *compositors;
77         guint                  scroll_idle_id;
78         gboolean               first_tp_chat;
79         time_t                 last_log_timestamp;
80         gboolean               is_first_char;
81         guint                  block_events_timeout_id;
82         /* Used to automatically shrink a window that has temporarily
83          * grown due to long input. 
84          */
85         gint                   padding_height;
86         gint                   default_window_height;
87         gint                   last_input_height;
88         gboolean               vscroll_visible;
89 };
90
91 typedef struct {
92         EmpathyChat  *chat;
93         gchar       *word;
94
95         GtkTextIter  start;
96         GtkTextIter  end;
97 } EmpathyChatSpell;
98
99 static void             empathy_chat_class_init           (EmpathyChatClass       *klass);
100 static void             empathy_chat_init                 (EmpathyChat            *chat);
101 static void             chat_finalize                     (GObject                *object);
102 static void             chat_destroy_cb                   (EmpathyTpChat          *tp_chat,
103                                                            EmpathyChat            *chat);
104 static void             chat_send                         (EmpathyChat            *chat,
105                                                            const gchar            *msg);
106 static void             chat_input_text_view_send         (EmpathyChat            *chat);
107 static void             chat_message_received_cb          (EmpathyTpChat          *tp_chat,
108                                                            EmpathyMessage         *message,
109                                                            EmpathyChat            *chat);
110 static void             chat_send_error_cb                (EmpathyTpChat          *tp_chat,
111                                                            EmpathyMessage         *message,
112                                                            TpChannelTextSendError  error_code,
113                                                            EmpathyChat            *chat);
114 static void             chat_sent_message_add             (EmpathyChat            *chat,
115                                                            const gchar            *str);
116 static const gchar *    chat_sent_message_get_next        (EmpathyChat            *chat);
117 static const gchar *    chat_sent_message_get_last        (EmpathyChat            *chat);
118 static gboolean         chat_input_key_press_event_cb     (GtkWidget              *widget,
119                                                            GdkEventKey            *event,
120                                                            EmpathyChat            *chat);
121 static void             chat_input_text_buffer_changed_cb (GtkTextBuffer          *buffer,
122                                                            EmpathyChat            *chat);
123 static gboolean         chat_text_view_focus_in_event_cb  (GtkWidget              *widget,
124                                                            GdkEvent               *event,
125                                                            EmpathyChat            *chat);
126 static void             chat_text_view_scroll_hide_cb     (GtkWidget              *widget,
127                                                            EmpathyChat            *chat);
128 static void             chat_text_view_size_allocate_cb   (GtkWidget              *widget,
129                                                            GtkAllocation          *allocation,
130                                                            EmpathyChat            *chat);
131 static void             chat_text_view_realize_cb         (GtkWidget              *widget,
132                                                            EmpathyChat            *chat);
133 static void             chat_text_populate_popup_cb       (GtkTextView            *view,
134                                                            GtkMenu                *menu,
135                                                            EmpathyChat            *chat);
136 static void             chat_text_check_word_spelling_cb  (GtkMenuItem            *menuitem,
137                                                            EmpathyChatSpell       *chat_spell);
138 static EmpathyChatSpell *chat_spell_new                   (EmpathyChat            *chat,
139                                                            const gchar            *word,
140                                                            GtkTextIter             start,
141                                                            GtkTextIter             end);
142 static void             chat_spell_free                   (EmpathyChatSpell       *chat_spell);
143 static void             chat_composing_start              (EmpathyChat            *chat);
144 static void             chat_composing_stop               (EmpathyChat            *chat);
145 static void             chat_composing_remove_timeout     (EmpathyChat            *chat);
146 static gboolean         chat_composing_stop_timeout_cb    (EmpathyChat            *chat);
147 static void             chat_state_changed_cb             (EmpathyTpChat          *tp_chat,
148                                                            EmpathyContact         *contact,
149                                                            TpChannelChatState      state,
150                                                            EmpathyChat            *chat);
151 static void             chat_add_logs                     (EmpathyChat            *chat);
152 static gboolean         chat_scroll_down_idle_func        (EmpathyChat            *chat);
153
154 enum {
155         COMPOSING,
156         NEW_MESSAGE,
157         NAME_CHANGED,
158         STATUS_CHANGED,
159         LAST_SIGNAL
160 };
161
162 enum {
163         PROP_0,
164         PROP_TP_CHAT
165 };
166
167 static guint signals[LAST_SIGNAL] = { 0 };
168
169 G_DEFINE_TYPE (EmpathyChat, empathy_chat, G_TYPE_OBJECT);
170
171 static void
172 chat_get_property (GObject    *object,
173                    guint       param_id,
174                    GValue     *value,
175                    GParamSpec *pspec)
176 {
177         EmpathyChatPriv *priv = GET_PRIV (object);
178
179         switch (param_id) {
180         case PROP_TP_CHAT:
181                 g_value_set_object (value, priv->tp_chat);
182                 break;
183         default:
184                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
185                 break;
186         };
187 }
188
189 static void
190 chat_set_property (GObject      *object,
191                    guint         param_id,
192                    const GValue *value,
193                    GParamSpec   *pspec)
194 {
195         EmpathyChat *chat = EMPATHY_CHAT (object);
196
197         switch (param_id) {
198         case PROP_TP_CHAT:
199                 empathy_chat_set_tp_chat (chat,
200                                           EMPATHY_TP_CHAT (g_value_get_object (value)));
201                 break;
202         default:
203                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
204                 break;
205         };
206 }
207
208 static void
209 chat_status_changed_cb (MissionControl           *mc,
210                         TpConnectionStatus        status,
211                         McPresence                presence,
212                         TpConnectionStatusReason  reason,
213                         const gchar              *unique_name,
214                         EmpathyChat              *chat)
215 {
216         EmpathyChatPriv *priv = GET_PRIV (chat);
217         McAccount       *account;
218
219         account = mc_account_lookup (unique_name);
220
221         if (status == TP_CONNECTION_STATUS_CONNECTED && !priv->tp_chat &&
222             empathy_account_equal (account, priv->account)) {
223                 TpHandleType handle_type;
224
225                 empathy_debug (DEBUG_DOMAIN,
226                                "Account reconnected, request a new Text channel");
227
228                 if (empathy_chat_is_group_chat (chat)) {
229                         handle_type = TP_HANDLE_TYPE_ROOM;
230                 } else {
231                         handle_type = TP_HANDLE_TYPE_CONTACT;
232                 }
233
234                 mission_control_request_channel_with_string_handle (mc,
235                                                                     priv->account,
236                                                                     TP_IFACE_CHANNEL_TYPE_TEXT,
237                                                                     priv->id,
238                                                                     handle_type,
239                                                                     NULL, NULL);
240         }
241
242         g_object_unref (account);
243 }
244
245 static void
246 empathy_chat_class_init (EmpathyChatClass *klass)
247 {
248         GObjectClass *object_class;
249
250         object_class = G_OBJECT_CLASS (klass);
251
252         object_class->finalize = chat_finalize;
253         object_class->get_property = chat_get_property;
254         object_class->set_property = chat_set_property;
255
256         g_object_class_install_property (object_class,
257                                          PROP_TP_CHAT,
258                                          g_param_spec_object ("tp-chat",
259                                                               "Empathy tp chat",
260                                                               "The tp chat object",
261                                                               EMPATHY_TYPE_TP_CHAT,
262                                                               G_PARAM_CONSTRUCT |
263                                                               G_PARAM_READWRITE));
264
265         signals[COMPOSING] =
266                 g_signal_new ("composing",
267                               G_OBJECT_CLASS_TYPE (object_class),
268                               G_SIGNAL_RUN_LAST,
269                               0,
270                               NULL, NULL,
271                               g_cclosure_marshal_VOID__BOOLEAN,
272                               G_TYPE_NONE,
273                               1, G_TYPE_BOOLEAN);
274
275         signals[NEW_MESSAGE] =
276                 g_signal_new ("new-message",
277                               G_OBJECT_CLASS_TYPE (object_class),
278                               G_SIGNAL_RUN_LAST,
279                               0,
280                               NULL, NULL,
281                               _empathy_gtk_marshal_VOID__OBJECT_BOOLEAN,
282                               G_TYPE_NONE,
283                               2, EMPATHY_TYPE_MESSAGE, G_TYPE_BOOLEAN);
284
285         signals[NAME_CHANGED] =
286                 g_signal_new ("name-changed",
287                               G_OBJECT_CLASS_TYPE (object_class),
288                               G_SIGNAL_RUN_LAST,
289                               0,
290                               NULL, NULL,
291                               g_cclosure_marshal_VOID__POINTER,
292                               G_TYPE_NONE,
293                               1, G_TYPE_POINTER);
294
295         signals[STATUS_CHANGED] =
296                 g_signal_new ("status-changed",
297                               G_OBJECT_CLASS_TYPE (object_class),
298                               G_SIGNAL_RUN_LAST,
299                               0,
300                               NULL, NULL,
301                               g_cclosure_marshal_VOID__VOID,
302                               G_TYPE_NONE,
303                               0);
304
305         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
306 }
307
308 static void
309 empathy_chat_init (EmpathyChat *chat)
310 {
311         EmpathyChatPriv *priv = GET_PRIV (chat);
312         GtkTextBuffer  *buffer;
313
314         chat->view = empathy_chat_view_new ();
315         chat->input_text_view = gtk_text_view_new ();
316
317         priv->is_first_char = TRUE;
318
319         g_object_set (chat->input_text_view,
320                       "pixels-above-lines", 2,
321                       "pixels-below-lines", 2,
322                       "pixels-inside-wrap", 1,
323                       "right-margin", 2,
324                       "left-margin", 2,
325                       "wrap-mode", GTK_WRAP_WORD_CHAR,
326                       NULL);
327
328         priv->log_manager = empathy_log_manager_new ();
329         priv->default_window_height = -1;
330         priv->vscroll_visible = FALSE;
331         priv->sensitive = TRUE;
332         priv->sent_messages = NULL;
333         priv->sent_messages_index = -1;
334         priv->first_tp_chat = TRUE;
335         priv->mc = empathy_mission_control_new ();
336
337         dbus_g_proxy_connect_signal (DBUS_G_PROXY (priv->mc), "AccountStatusChanged",
338                                      G_CALLBACK (chat_status_changed_cb),
339                                      chat, NULL);
340
341         g_signal_connect (chat->input_text_view,
342                           "key_press_event",
343                           G_CALLBACK (chat_input_key_press_event_cb),
344                           chat);
345
346         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
347         g_signal_connect (buffer,
348                           "changed",
349                           G_CALLBACK (chat_input_text_buffer_changed_cb),
350                           chat);
351         g_signal_connect (chat->view,
352                           "focus_in_event",
353                           G_CALLBACK (chat_text_view_focus_in_event_cb),
354                           chat);
355
356         g_signal_connect (chat->input_text_view,
357                           "size_allocate",
358                           G_CALLBACK (chat_text_view_size_allocate_cb),
359                           chat);
360
361         g_signal_connect (chat->input_text_view,
362                           "realize",
363                           G_CALLBACK (chat_text_view_realize_cb),
364                           chat);
365
366         g_signal_connect (GTK_TEXT_VIEW (chat->input_text_view),
367                           "populate_popup",
368                           G_CALLBACK (chat_text_populate_popup_cb),
369                           chat);
370
371         /* create misspelt words identification tag */
372         gtk_text_buffer_create_tag (buffer,
373                                     "misspelled",
374                                     "underline", PANGO_UNDERLINE_ERROR,
375                                     NULL);
376 }
377
378 static void
379 chat_finalize (GObject *object)
380 {
381         EmpathyChat     *chat;
382         EmpathyChatPriv *priv;
383
384         chat = EMPATHY_CHAT (object);
385         priv = GET_PRIV (chat);
386
387         empathy_debug (DEBUG_DOMAIN, "Finalized: %p", object);
388
389         g_slist_foreach (priv->sent_messages, (GFunc) g_free, NULL);
390         g_slist_free (priv->sent_messages);
391
392         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
393         g_list_free (priv->compositors);
394
395         chat_composing_remove_timeout (chat);
396         g_object_unref (priv->log_manager);
397
398         dbus_g_proxy_disconnect_signal (DBUS_G_PROXY (priv->mc), "AccountStatusChanged",
399                                         G_CALLBACK (chat_status_changed_cb),
400                                         chat);
401         g_object_unref (priv->mc);
402
403
404         if (priv->tp_chat) {
405                 g_object_unref (priv->tp_chat);
406         }
407
408         if (priv->account) {
409                 g_object_unref (priv->account);
410         }
411
412         if (priv->scroll_idle_id) {
413                 g_source_remove (priv->scroll_idle_id);
414         }
415
416         if (priv->block_events_timeout_id) {
417                 g_source_remove (priv->block_events_timeout_id);
418         }
419
420         g_free (priv->id);
421
422         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
423 }
424
425 static void
426 chat_destroy_cb (EmpathyTpChat *tp_chat,
427                  EmpathyChat    *chat)
428 {
429         EmpathyChatPriv *priv;
430
431         priv = GET_PRIV (chat);
432
433         if (priv->tp_chat) {
434                 g_object_unref (priv->tp_chat);
435                 priv->tp_chat = NULL;
436         }
437         priv->sensitive = FALSE;
438
439         empathy_chat_view_append_event (chat->view, _("Disconnected"));
440         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
441
442         if (priv->block_events_timeout_id != 0) {
443                 g_source_remove (priv->block_events_timeout_id);
444         }
445
446         if (EMPATHY_CHAT_GET_CLASS (chat)->set_tp_chat) {
447                 EMPATHY_CHAT_GET_CLASS (chat)->set_tp_chat (chat, NULL);
448         }
449 }
450
451 static void
452 chat_send (EmpathyChat  *chat,
453            const gchar *msg)
454 {
455         EmpathyChatPriv *priv;
456         EmpathyMessage  *message;
457
458         priv = GET_PRIV (chat);
459
460         if (G_STR_EMPTY (msg)) {
461                 return;
462         }
463
464         chat_sent_message_add (chat, msg);
465
466         if (g_str_has_prefix (msg, "/clear")) {
467                 empathy_chat_view_clear (chat->view);
468                 return;
469         }
470
471         /* FIXME: add here something to let group/privrate chat handle
472          *        some special messages */
473
474         message = empathy_message_new (msg);
475
476         empathy_tp_chat_send (priv->tp_chat, message);
477
478         g_object_unref (message);
479 }
480
481 static void
482 chat_input_text_view_send (EmpathyChat *chat)
483 {
484         EmpathyChatPriv *priv;
485         GtkTextBuffer  *buffer;
486         GtkTextIter     start, end;
487         gchar          *msg;
488
489         priv = GET_PRIV (chat);
490
491         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
492
493         gtk_text_buffer_get_bounds (buffer, &start, &end);
494         msg = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
495
496         /* clear the input field */
497         gtk_text_buffer_set_text (buffer, "", -1);
498
499         chat_send (chat, msg);
500
501         g_free (msg);
502
503         priv->is_first_char = TRUE;
504 }
505
506 static void
507 chat_message_received_cb (EmpathyTpChat  *tp_chat,
508                           EmpathyMessage *message,
509                           EmpathyChat    *chat)
510 {
511         EmpathyChatPriv *priv;
512         EmpathyContact  *sender;
513         time_t           timestamp;
514
515         priv = GET_PRIV (chat);
516
517         timestamp = empathy_message_get_timestamp (message);
518         if (timestamp <= priv->last_log_timestamp) {
519                 /* Do not take care of messages anterior of the last
520                  * logged message. Some Jabber chatroom sends messages
521                  * received before we joined the room, this avoid
522                  * displaying those messages if we already logged them
523                  * last time we joined that room. */
524                 empathy_debug (DEBUG_DOMAIN, "Skipping message because it is "
525                                "anterior of last logged message.");
526                 return;
527         }
528
529         sender = empathy_message_get_sender (message);
530         empathy_debug (DEBUG_DOMAIN, "Appending message ('%s')",
531                       empathy_contact_get_name (sender));
532
533         empathy_log_manager_add_message (priv->log_manager,
534                                          empathy_chat_get_id (chat),
535                                          empathy_chat_is_group_chat (chat),
536                                          message);
537
538         empathy_chat_view_append_message (chat->view, message);
539
540         if (empathy_chat_should_play_sound (chat)) {
541                 // FIXME: empathy_sound_play (EMPATHY_SOUND_CHAT);
542         }
543
544         /* We received a message so the contact is no more composing */
545         chat_state_changed_cb (tp_chat, sender,
546                                TP_CHANNEL_CHAT_STATE_ACTIVE,
547                                chat);
548
549         g_signal_emit (chat, signals[NEW_MESSAGE], 0, message, FALSE);
550 }
551
552 static void
553 chat_send_error_cb (EmpathyTpChat          *tp_chat,
554                     EmpathyMessage         *message,
555                     TpChannelTextSendError  error_code,
556                     EmpathyChat            *chat)
557 {
558         const gchar *error;
559         gchar       *str;
560
561         switch (error_code) {
562         case TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE:
563                 error = _("offline");
564                 break;
565         case TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT:
566                 error = _("invalid contact");
567                 break;
568         case TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED:
569                 error = _("permission denied");
570                 break;
571         case TP_CHANNEL_TEXT_SEND_ERROR_TOO_LONG:
572                 error = _("too long message");
573                 break;
574         case TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED:
575                 error = _("not implemented");
576                 break;
577         default:
578                 error = _("unknown");
579                 break;
580         }
581
582         str = g_strdup_printf (_("Error sending message '%s': %s"),
583                                empathy_message_get_body (message),
584                                error);
585         empathy_chat_view_append_event (chat->view, str);
586         g_free (str);
587 }
588
589 static void 
590 chat_sent_message_add (EmpathyChat  *chat,
591                        const gchar *str)
592 {
593         EmpathyChatPriv *priv;
594         GSList         *list;
595         GSList         *item;
596
597         priv = GET_PRIV (chat);
598
599         /* Save the sent message in our repeat buffer */
600         list = priv->sent_messages;
601         
602         /* Remove any other occurances of this msg */
603         while ((item = g_slist_find_custom (list, str, (GCompareFunc) strcmp)) != NULL) {
604                 list = g_slist_remove_link (list, item);
605                 g_free (item->data);
606                 g_slist_free1 (item);
607         }
608
609         /* Trim the list to the last 10 items */
610         while (g_slist_length (list) > 10) {
611                 item = g_slist_last (list);
612                 if (item) {
613                         list = g_slist_remove_link (list, item);
614                         g_free (item->data);
615                         g_slist_free1 (item);
616                 }
617         }
618
619         /* Add new message */
620         list = g_slist_prepend (list, g_strdup (str));
621
622         /* Set list and reset the index */
623         priv->sent_messages = list;
624         priv->sent_messages_index = -1;
625 }
626
627 static const gchar *
628 chat_sent_message_get_next (EmpathyChat *chat)
629 {
630         EmpathyChatPriv *priv;
631         gint            max;
632         
633         priv = GET_PRIV (chat);
634
635         if (!priv->sent_messages) {
636                 empathy_debug (DEBUG_DOMAIN, 
637                               "No sent messages, next message is NULL");
638                 return NULL;
639         }
640
641         max = g_slist_length (priv->sent_messages) - 1;
642
643         if (priv->sent_messages_index < max) {
644                 priv->sent_messages_index++;
645         }
646         
647         empathy_debug (DEBUG_DOMAIN, 
648                       "Returning next message index:%d",
649                       priv->sent_messages_index);
650
651         return g_slist_nth_data (priv->sent_messages, priv->sent_messages_index);
652 }
653
654 static const gchar *
655 chat_sent_message_get_last (EmpathyChat *chat)
656 {
657         EmpathyChatPriv *priv;
658
659         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
660
661         priv = GET_PRIV (chat);
662         
663         if (!priv->sent_messages) {
664                 empathy_debug (DEBUG_DOMAIN, 
665                               "No sent messages, last message is NULL");
666                 return NULL;
667         }
668
669         if (priv->sent_messages_index >= 0) {
670                 priv->sent_messages_index--;
671         }
672
673         empathy_debug (DEBUG_DOMAIN, 
674                       "Returning last message index:%d",
675                       priv->sent_messages_index);
676
677         return g_slist_nth_data (priv->sent_messages, priv->sent_messages_index);
678 }
679
680 static gboolean
681 chat_input_key_press_event_cb (GtkWidget   *widget,
682                                GdkEventKey *event,
683                                EmpathyChat *chat)
684 {
685         EmpathyChatPriv *priv;
686         GtkAdjustment  *adj;
687         gdouble         val;
688         GtkWidget      *text_view_sw;
689
690         priv = GET_PRIV (chat);
691
692         /* Catch ctrl+up/down so we can traverse messages we sent */
693         if ((event->state & GDK_CONTROL_MASK) && 
694             (event->keyval == GDK_Up || 
695              event->keyval == GDK_Down)) {
696                 GtkTextBuffer *buffer;
697                 const gchar   *str;
698
699                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
700
701                 if (event->keyval == GDK_Up) {
702                         str = chat_sent_message_get_next (chat);
703                 } else {
704                         str = chat_sent_message_get_last (chat);
705                 }
706
707                 g_signal_handlers_block_by_func (buffer, 
708                                                  chat_input_text_buffer_changed_cb,
709                                                  chat);
710                 gtk_text_buffer_set_text (buffer, str ? str : "", -1);
711                 g_signal_handlers_unblock_by_func (buffer, 
712                                                    chat_input_text_buffer_changed_cb,
713                                                    chat);
714
715                 return TRUE;    
716         }
717
718         /* Catch enter but not ctrl/shift-enter */
719         if (IS_ENTER (event->keyval) &&
720             !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
721                 GtkTextView *view;
722
723                 /* This is to make sure that kinput2 gets the enter. And if
724                  * it's handled there we shouldn't send on it. This is because
725                  * kinput2 uses Enter to commit letters. See:
726                  * http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=104299
727                  */
728
729                 view = GTK_TEXT_VIEW (chat->input_text_view);
730                 if (gtk_im_context_filter_keypress (view->im_context, event)) {
731                         GTK_TEXT_VIEW (chat->input_text_view)->need_im_reset = TRUE;
732                         return TRUE;
733                 }
734
735                 chat_input_text_view_send (chat);
736                 return TRUE;
737         }
738
739         text_view_sw = gtk_widget_get_parent (GTK_WIDGET (chat->view));
740
741         if (IS_ENTER (event->keyval) &&
742             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
743                 /* Newline for shift/control-enter. */
744                 return FALSE;
745         }
746         else if (!(event->state & GDK_CONTROL_MASK) &&
747                  event->keyval == GDK_Page_Up) {
748                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
749                 gtk_adjustment_set_value (adj, adj->value - adj->page_size);
750
751                 return TRUE;
752         }
753         else if ((event->state & GDK_CONTROL_MASK) != GDK_CONTROL_MASK &&
754                  event->keyval == GDK_Page_Down) {
755                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
756                 val = MIN (adj->value + adj->page_size, adj->upper - adj->page_size);
757                 gtk_adjustment_set_value (adj, val);
758
759                 return TRUE;
760         }
761
762         if (EMPATHY_CHAT_GET_CLASS (chat)->key_press_event) {
763                 return EMPATHY_CHAT_GET_CLASS (chat)->key_press_event (chat, event);
764         }
765
766         return FALSE;
767 }
768
769 static gboolean
770 chat_text_view_focus_in_event_cb (GtkWidget  *widget,
771                                   GdkEvent   *event,
772                                   EmpathyChat *chat)
773 {
774         gtk_widget_grab_focus (chat->input_text_view);
775
776         return TRUE;
777 }
778
779 static void
780 chat_input_text_buffer_changed_cb (GtkTextBuffer *buffer,
781                                    EmpathyChat    *chat)
782 {
783         EmpathyChatPriv *priv;
784         GtkTextIter     start, end;
785         gchar          *str;
786         gboolean        spell_checker = FALSE;
787
788         priv = GET_PRIV (chat);
789
790         if (gtk_text_buffer_get_char_count (buffer) == 0) {
791                 chat_composing_stop (chat);
792         } else {
793                 chat_composing_start (chat);
794         }
795
796         empathy_conf_get_bool (empathy_conf_get (),
797                               EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
798                               &spell_checker);
799
800         if (priv->is_first_char) {
801                 GtkRequisition  req;
802                 gint            window_height;
803                 GtkWindow      *dialog;
804                 GtkAllocation  *allocation;
805
806                 /* Save the window's size */
807                 dialog = empathy_get_toplevel_window (priv->widget);
808                 if (dialog) {
809                         gtk_window_get_size (GTK_WINDOW (dialog), NULL, &window_height);
810                         gtk_widget_size_request (chat->input_text_view, &req);
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
818                 priv->is_first_char = FALSE;
819         }
820
821         gtk_text_buffer_get_start_iter (buffer, &start);
822
823         if (!spell_checker) {
824                 gtk_text_buffer_get_end_iter (buffer, &end);
825                 gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
826                 return;
827         }
828
829         if (!empathy_spell_supported ()) {
830                 return;
831         }
832
833         /* NOTE: this is really inefficient, we shouldn't have to
834            reiterate the whole buffer each time and check each work
835            every time. */
836         while (TRUE) {
837                 gboolean correct = FALSE;
838
839                 /* if at start */
840                 if (gtk_text_iter_is_start (&start)) {
841                         end = start;
842
843                         if (!gtk_text_iter_forward_word_end (&end)) {
844                                 /* no whole word yet */
845                                 break;
846                         }
847                 } else {
848                         if (!gtk_text_iter_forward_word_end (&end)) {
849                                 /* must be the end of the buffer */
850                                 break;
851                         }
852
853                         start = end;
854                         gtk_text_iter_backward_word_start (&start);
855                 }
856
857                 str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
858
859                 /* spell check string */
860                 if (!empathy_chat_get_is_command (str)) {
861                         correct = empathy_spell_check (str);
862                 } else {
863                         correct = TRUE;
864                 }
865
866                 if (!correct) {
867                         gtk_text_buffer_apply_tag_by_name (buffer, "misspelled", &start, &end);
868                 } else {
869                         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
870                 }
871
872                 g_free (str);
873
874                 /* set start iter to the end iters position */
875                 start = end;
876         }
877 }
878
879 typedef struct {
880         GtkWindow *window;
881         gint       width;
882         gint       height;
883 } ChangeSizeData;
884
885 static gboolean
886 chat_change_size_in_idle_cb (ChangeSizeData *data)
887 {
888         gtk_window_resize (data->window, 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         GtkWindow      *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_get_toplevel_window (priv->widget);
960         gtk_window_get_size (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 (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 (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         EmpathyChatPriv *priv = GET_PRIV (chat);
1395
1396         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
1397
1398         if (!priv->widget && EMPATHY_CHAT_GET_CLASS (chat)->get_widget) {
1399                 priv->widget = EMPATHY_CHAT_GET_CLASS (chat)->get_widget (chat);
1400         }
1401
1402         return priv->widget;
1403 }
1404
1405 gboolean
1406 empathy_chat_is_group_chat (EmpathyChat *chat)
1407 {
1408         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
1409
1410         if (EMPATHY_CHAT_GET_CLASS (chat)->is_group_chat) {
1411                 return EMPATHY_CHAT_GET_CLASS (chat)->is_group_chat (chat);
1412         }
1413
1414         return FALSE;
1415 }
1416
1417 gboolean 
1418 empathy_chat_is_connected (EmpathyChat *chat)
1419 {
1420         EmpathyChatPriv *priv;
1421
1422         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
1423
1424         priv = GET_PRIV (chat);
1425
1426         return (priv->tp_chat != NULL);
1427 }
1428
1429 static const gchar *
1430 chat_get_window_id_for_geometry (EmpathyChat *chat)
1431 {
1432         gboolean separate_windows;
1433
1434         empathy_conf_get_bool (empathy_conf_get (),
1435                                EMPATHY_PREFS_UI_SEPARATE_CHAT_WINDOWS,
1436                                &separate_windows);
1437
1438         if (separate_windows) {
1439                 return empathy_chat_get_id (chat);
1440         } else {
1441                 return "chat-window";
1442         }
1443 }
1444
1445 void
1446 empathy_chat_save_geometry (EmpathyChat *chat,
1447                            gint        x,
1448                            gint        y,
1449                            gint        w,
1450                            gint        h)
1451 {
1452         empathy_geometry_save (chat_get_window_id_for_geometry (chat), x, y, w, h);
1453 }
1454
1455 void
1456 empathy_chat_load_geometry (EmpathyChat *chat,
1457                            gint       *x,
1458                            gint       *y,
1459                            gint       *w,
1460                            gint       *h)
1461 {
1462         empathy_geometry_load (chat_get_window_id_for_geometry (chat), x, y, w, h);
1463 }
1464
1465 static gboolean
1466 chat_block_events_timeout_cb (gpointer data)
1467 {
1468         EmpathyChat     *chat = EMPATHY_CHAT (data);
1469         EmpathyChatPriv *priv = GET_PRIV (chat);
1470
1471         chat->block_events = FALSE;
1472         priv->block_events_timeout_id = 0;
1473
1474         return FALSE;
1475 }
1476
1477 void
1478 empathy_chat_set_tp_chat (EmpathyChat   *chat,
1479                           EmpathyTpChat *tp_chat)
1480 {
1481         EmpathyChatPriv *priv;
1482
1483         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1484         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
1485
1486         priv = GET_PRIV (chat);
1487
1488         if (tp_chat == priv->tp_chat) {
1489                 return;
1490         }
1491
1492         /* Block events for some time to avoid having "has come online" or
1493          * "joined" messages. */
1494         chat->block_events = TRUE;
1495         if (priv->block_events_timeout_id != 0) {
1496                 g_source_remove (priv->block_events_timeout_id);
1497         }
1498         priv->block_events_timeout_id =
1499                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
1500
1501         if (priv->tp_chat) {
1502                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
1503                                                       chat_message_received_cb,
1504                                                       chat);
1505                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
1506                                                       chat_send_error_cb,
1507                                                       chat);
1508                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
1509                                                       chat_destroy_cb,
1510                                                       chat);
1511                 g_object_unref (priv->tp_chat);
1512         }
1513         if (priv->account) {
1514                 g_object_unref (priv->account);
1515         }
1516
1517         g_free (priv->id);
1518         priv->tp_chat = g_object_ref (tp_chat);
1519         priv->id = g_strdup (empathy_tp_chat_get_id (tp_chat));
1520         priv->account = g_object_ref (empathy_tp_chat_get_account (tp_chat));
1521         empathy_tp_chat_set_acknowledge (tp_chat, TRUE);
1522
1523         if (priv->first_tp_chat) {
1524                 chat_add_logs (chat);
1525                 priv->first_tp_chat = FALSE;
1526         }
1527
1528         g_signal_connect (tp_chat, "message-received",
1529                           G_CALLBACK (chat_message_received_cb),
1530                           chat);
1531         g_signal_connect (tp_chat, "send-error",
1532                           G_CALLBACK (chat_send_error_cb),
1533                           chat);
1534         g_signal_connect (tp_chat, "chat-state-changed",
1535                           G_CALLBACK (chat_state_changed_cb),
1536                           chat);
1537         g_signal_connect (tp_chat, "destroy",
1538                           G_CALLBACK (chat_destroy_cb),
1539                           chat);
1540
1541         if (!priv->sensitive) {
1542                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
1543                 empathy_chat_view_append_event (chat->view, _("Connected"));
1544                 priv->sensitive = TRUE;
1545         }
1546
1547         if (EMPATHY_CHAT_GET_CLASS (chat)->set_tp_chat) {
1548                 EMPATHY_CHAT_GET_CLASS (chat)->set_tp_chat (chat, tp_chat);
1549         }
1550
1551         g_object_notify (G_OBJECT (chat), "tp-chat");
1552 }
1553
1554 const gchar *
1555 empathy_chat_get_id (EmpathyChat *chat)
1556 {
1557         EmpathyChatPriv *priv;
1558
1559         priv = GET_PRIV (chat);
1560
1561         return priv->id;
1562 }
1563
1564 McAccount *
1565 empathy_chat_get_account (EmpathyChat *chat)
1566 {
1567         EmpathyChatPriv *priv = GET_PRIV (chat);
1568
1569         return priv->account;
1570 }
1571
1572 void
1573 empathy_chat_clear (EmpathyChat *chat)
1574 {
1575         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1576
1577         empathy_chat_view_clear (chat->view);
1578 }
1579
1580 void
1581 empathy_chat_scroll_down (EmpathyChat *chat)
1582 {
1583         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1584
1585         empathy_chat_view_scroll_down (chat->view);
1586 }
1587
1588 void
1589 empathy_chat_cut (EmpathyChat *chat)
1590 {
1591         GtkTextBuffer *buffer;
1592
1593         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1594
1595         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1596         if (gtk_text_buffer_get_selection_bounds (buffer, NULL, NULL)) {
1597                 GtkClipboard *clipboard;
1598
1599                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
1600
1601                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
1602         }
1603 }
1604
1605 void
1606 empathy_chat_copy (EmpathyChat *chat)
1607 {
1608         GtkTextBuffer *buffer;
1609
1610         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1611
1612         if (empathy_chat_view_get_selection_bounds (chat->view, NULL, NULL)) {
1613                 empathy_chat_view_copy_clipboard (chat->view);
1614                 return;
1615         }
1616
1617         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1618         if (gtk_text_buffer_get_selection_bounds (buffer, NULL, NULL)) {
1619                 GtkClipboard *clipboard;
1620
1621                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
1622
1623                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
1624         }
1625 }
1626
1627 void
1628 empathy_chat_paste (EmpathyChat *chat)
1629 {
1630         GtkTextBuffer *buffer;
1631         GtkClipboard  *clipboard;
1632
1633         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1634
1635         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1636         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
1637
1638         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
1639 }
1640
1641 gboolean
1642 empathy_chat_should_play_sound (EmpathyChat *chat)
1643 {
1644         EmpathyChatPriv *priv = GET_PRIV (chat);
1645         GtkWindow       *window;
1646         gboolean         has_focus = FALSE;
1647
1648         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
1649
1650         window = empathy_get_toplevel_window (priv->widget);
1651         if (window) {
1652                 g_object_get (window, "has-toplevel-focus", &has_focus, NULL);
1653         }
1654
1655         return !has_focus;
1656 }
1657
1658 gboolean
1659 empathy_chat_should_highlight_nick (EmpathyMessage *message)
1660 {
1661         EmpathyContact *contact;
1662         const gchar   *msg, *to;
1663         gchar         *cf_msg, *cf_to;
1664         gchar         *ch;
1665         gboolean       ret_val;
1666
1667         g_return_val_if_fail (EMPATHY_IS_MESSAGE (message), FALSE);
1668
1669         empathy_debug (DEBUG_DOMAIN, "Highlighting nickname");
1670
1671         ret_val = FALSE;
1672
1673         msg = empathy_message_get_body (message);
1674         if (!msg) {
1675                 return FALSE;
1676         }
1677
1678         contact = empathy_message_get_receiver (message);
1679         if (!contact || !empathy_contact_is_user (contact)) {
1680                 return FALSE;
1681         }
1682
1683         to = empathy_contact_get_name (contact);
1684         if (!to) {
1685                 return FALSE;
1686         }
1687
1688         cf_msg = g_utf8_casefold (msg, -1);
1689         cf_to = g_utf8_casefold (to, -1);
1690
1691         ch = strstr (cf_msg, cf_to);
1692         if (ch == NULL) {
1693                 goto finished;
1694         }
1695
1696         if (ch != cf_msg) {
1697                 /* Not first in the message */
1698                 if ((*(ch - 1) != ' ') &&
1699                     (*(ch - 1) != ',') &&
1700                     (*(ch - 1) != '.')) {
1701                         goto finished;
1702                 }
1703         }
1704
1705         ch = ch + strlen (cf_to);
1706         if (ch >= cf_msg + strlen (cf_msg)) {
1707                 ret_val = TRUE;
1708                 goto finished;
1709         }
1710
1711         if ((*ch == ' ') ||
1712             (*ch == ',') ||
1713             (*ch == '.') ||
1714             (*ch == ':')) {
1715                 ret_val = TRUE;
1716                 goto finished;
1717         }
1718
1719 finished:
1720         g_free (cf_msg);
1721         g_free (cf_to);
1722
1723         return ret_val;
1724 }
1725