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