]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
Don't highlight messages the user sent themself
[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-2010 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., 51 Franklin St, Fifth Floor,
19  * Boston, MA  02110-1301  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 #undef G_DISABLE_DEPRECATED /* for GCompletion */
34 #include <gdk/gdkkeysyms.h>
35 #include <glib/gi18n-lib.h>
36 #include <gtk/gtk.h>
37
38 #include <telepathy-glib/account-manager.h>
39 #include <telepathy-glib/util.h>
40 #include <telepathy-logger/log-manager.h>
41 #include <telepathy-logger/text-event.h>
42 #include <libempathy/empathy-contact-list.h>
43 #include <libempathy/empathy-gsettings.h>
44 #include <libempathy/empathy-keyring.h>
45 #include <libempathy/empathy-utils.h>
46 #include <libempathy/empathy-request-util.h>
47 #include <libempathy/empathy-chatroom-manager.h>
48
49 #include "empathy-chat.h"
50 #include "empathy-spell.h"
51 #include "empathy-contact-dialogs.h"
52 #include "empathy-individual-store-channel.h"
53 #include "empathy-individual-view.h"
54 #include "empathy-input-text-view.h"
55 #include "empathy-search-bar.h"
56 #include "empathy-theme-manager.h"
57 #include "empathy-theme-adium.h"
58 #include "empathy-smiley-manager.h"
59 #include "empathy-ui-utils.h"
60 #include "empathy-string-parser.h"
61 #include "extensions/extensions.h"
62
63 #define DEBUG_FLAG EMPATHY_DEBUG_CHAT
64 #include <libempathy/empathy-debug.h>
65
66 #define IS_ENTER(v) (v == GDK_KEY_Return || v == GDK_KEY_ISO_Enter || v == GDK_KEY_KP_Enter)
67 #define COMPOSING_STOP_TIMEOUT 5
68
69 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyChat)
70 struct _EmpathyChatPriv {
71         EmpathyTpChat     *tp_chat;
72         TpAccount         *account;
73         gchar             *id;
74         gchar             *name;
75         gchar             *subject;
76         EmpathyContact    *remote_contact;
77         gboolean           show_contacts;
78
79         GSettings         *gsettings_chat;
80         GSettings         *gsettings_ui;
81
82         TplLogManager     *log_manager;
83         TpAccountManager  *account_manager;
84         GList             *input_history;
85         GList             *input_history_current;
86         GList             *compositors;
87         GCompletion       *completion;
88         guint              composing_stop_timeout_id;
89         guint              block_events_timeout_id;
90         TpHandleType       handle_type;
91         gint               contacts_width;
92         gboolean           has_input_vscroll;
93
94         /* TRUE if spell checking is enabled, FALSE otherwise.
95          * This is to keep track of the last state of spell checking
96          * when it changes. */
97         gboolean           spell_checking_enabled;
98
99         /* These store the signal handler ids for the enclosed text entry. */
100         gulong             insert_text_id;
101         gulong             delete_range_id;
102         gulong             notify_cursor_position_id;
103
104         /* Source func ID for update_misspelled_words () */
105         guint              update_misspelled_words_id;
106         /* Source func ID for save_paned_pos_timeout () */
107         guint              save_paned_pos_id;
108         /* Source func ID for chat_contacts_visible_timeout_cb () */
109         guint              contacts_visible_id;
110
111         GtkWidget         *widget;
112         GtkWidget         *hpaned;
113         GtkWidget         *vbox_left;
114         GtkWidget         *scrolled_window_chat;
115         GtkWidget         *scrolled_window_input;
116         GtkWidget         *scrolled_window_contacts;
117         GtkWidget         *hbox_topic;
118         GtkWidget         *expander_topic;
119         GtkWidget         *label_topic;
120         GtkWidget         *contact_list_view;
121         GtkWidget         *info_bar_vbox;
122         GtkWidget         *search_bar;
123
124         guint              unread_messages;
125         guint              unread_messages_when_offline;
126         /* TRUE if the pending messages can be displayed. This is to avoid to show
127          * pending messages *before* messages from logs. (#603980) */
128         gboolean           can_show_pending;
129
130         /* FIXME: retrieving_backlogs flag is a workaround for Bug#610994 and should
131          * be differently handled since it introduces another race condition, which
132          * is really hard to occur, but still possible.
133          *
134          * With the current workaround (which has the race above), we need to be
135          * sure to ACK any pending messages only when the retrieval of backlogs is
136          * finished, that's why using retrieving_backlogs flag.
137          * empathy_chat_messages_read () will check this variable and not ACK
138          * anything when TRUE. It will be set TRUE at chat_constructed () and set
139          * back to FALSE when the backlog has been retrieved and the pending
140          * messages actually showed to the user.
141          *
142          * Race condition introduced with this workaround:
143          * Scenario: a message is pending, the user is notified and selects the tab.
144          * the tab with a pending message is focused before the messages are properly
145          * shown (since the preparation of the window is slower AND async WRT the
146          * tab showing), which means the user won't see any new messages (rare but
147          * possible), if he/she will change tab focus before the messages are
148          * properly shown, the tab will be set as 'seen' and the user won't be
149          * notified again about the already notified pending messages when the
150          * messages in tab will be properly shown */
151         gboolean           retrieving_backlogs;
152         gboolean           sms_channel;
153
154         /* we need to know whether populate-popup happened in response to
155          * the keyboard or the mouse. We can't ask GTK for the most recent
156          * event, because it will be a notify event. Instead we track it here */
157         GdkEventType       most_recent_event_type;
158 };
159
160 typedef struct {
161         gchar *text; /* Original message that was specified
162                       * upon entry creation. */
163         gchar *modified_text; /* Message that was modified by user.
164                                * When no modifications were made, it is NULL */
165 } InputHistoryEntry;
166
167 enum {
168         COMPOSING,
169         NEW_MESSAGE,
170         PART_COMMAND_ENTERED,
171         LAST_SIGNAL
172 };
173
174 enum {
175         PROP_0,
176         PROP_TP_CHAT,
177         PROP_ACCOUNT,
178         PROP_ID,
179         PROP_NAME,
180         PROP_SUBJECT,
181         PROP_REMOTE_CONTACT,
182         PROP_SHOW_CONTACTS,
183         PROP_SMS_CHANNEL,
184         PROP_N_MESSAGES_SENDING,
185         PROP_NB_UNREAD_MESSAGES,
186 };
187
188 static guint signals[LAST_SIGNAL] = { 0 };
189
190 G_DEFINE_TYPE (EmpathyChat, empathy_chat, GTK_TYPE_BOX);
191
192 static gboolean update_misspelled_words (gpointer data);
193
194 static void
195 chat_get_property (GObject    *object,
196                    guint       param_id,
197                    GValue     *value,
198                    GParamSpec *pspec)
199 {
200         EmpathyChat *chat = EMPATHY_CHAT (object);
201         EmpathyChatPriv *priv = GET_PRIV (object);
202
203         switch (param_id) {
204         case PROP_TP_CHAT:
205                 g_value_set_object (value, priv->tp_chat);
206                 break;
207         case PROP_ACCOUNT:
208                 g_value_set_object (value, priv->account);
209                 break;
210         case PROP_NAME:
211                 g_value_take_string (value, empathy_chat_dup_name (chat));
212                 break;
213         case PROP_ID:
214                 g_value_set_string (value, priv->id);
215                 break;
216         case PROP_SUBJECT:
217                 g_value_set_string (value, priv->subject);
218                 break;
219         case PROP_REMOTE_CONTACT:
220                 g_value_set_object (value, priv->remote_contact);
221                 break;
222         case PROP_SHOW_CONTACTS:
223                 g_value_set_boolean (value, priv->show_contacts);
224                 break;
225         case PROP_SMS_CHANNEL:
226                 g_value_set_boolean (value, priv->sms_channel);
227                 break;
228         case PROP_N_MESSAGES_SENDING:
229                 g_value_set_uint (value,
230                         empathy_chat_get_n_messages_sending (chat));
231                 break;
232         case PROP_NB_UNREAD_MESSAGES:
233                 g_value_set_uint (value,
234                         empathy_chat_get_nb_unread_messages (chat));
235                 break;
236         default:
237                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
238                 break;
239         };
240 }
241
242 static void
243 chat_set_property (GObject      *object,
244                    guint         param_id,
245                    const GValue *value,
246                    GParamSpec   *pspec)
247 {
248         EmpathyChat *chat = EMPATHY_CHAT (object);
249
250         switch (param_id) {
251         case PROP_TP_CHAT:
252                 empathy_chat_set_tp_chat (chat, EMPATHY_TP_CHAT (g_value_get_object (value)));
253                 break;
254         case PROP_SHOW_CONTACTS:
255                 empathy_chat_set_show_contacts (chat, g_value_get_boolean (value));
256                 break;
257         default:
258                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
259                 break;
260         };
261 }
262
263 static void
264 account_reconnected (EmpathyChat *chat,
265                         TpAccount *account)
266 {
267         EmpathyChatPriv *priv = GET_PRIV (chat);
268
269         DEBUG ("Account reconnected, request a new Text channel");
270
271         /* FIXME: Ideally we should ask to handle ourself the channel so we can
272         * report the error if any but this is blocked by
273         * https://bugs.freedesktop.org/show_bug.cgi?id=13422 */
274         switch (priv->handle_type) {
275                 case TP_HANDLE_TYPE_CONTACT:
276                         if (priv->sms_channel)
277                                 empathy_sms_contact_id (
278                                         account, priv->id,
279                                         TP_USER_ACTION_TIME_NOT_USER_ACTION,
280                                         NULL, NULL);
281                         else
282                                 empathy_chat_with_contact_id (
283                                         account, priv->id,
284                                         TP_USER_ACTION_TIME_NOT_USER_ACTION,
285                                         NULL, NULL);
286                         break;
287                 case TP_HANDLE_TYPE_ROOM:
288                         empathy_join_muc (account, priv->id,
289                                 TP_USER_ACTION_TIME_NOT_USER_ACTION);
290                         break;
291                 case TP_HANDLE_TYPE_NONE:
292                 case TP_HANDLE_TYPE_LIST:
293                 case TP_HANDLE_TYPE_GROUP:
294                 default:
295                         g_assert_not_reached ();
296                         break;
297         }
298
299         g_object_unref (chat);
300 }
301
302 static void
303 chat_new_connection_cb (TpAccount   *account,
304                         guint        old_status,
305                         guint        new_status,
306                         guint        reason,
307                         gchar       *dbus_error_name,
308                         GHashTable  *details,
309                         EmpathyChat *chat)
310 {
311         EmpathyChatPriv *priv = GET_PRIV (chat);
312
313         if (new_status != TP_CONNECTION_STATUS_CONNECTED)
314                 return;
315
316         if (priv->tp_chat != NULL || account != priv->account ||
317             priv->handle_type == TP_HANDLE_TYPE_NONE ||
318             EMP_STR_EMPTY (priv->id))
319                 return;
320
321         g_object_ref (chat);
322
323         account_reconnected (chat, account);
324 }
325
326 static void
327 chat_composing_remove_timeout (EmpathyChat *chat)
328 {
329         EmpathyChatPriv *priv;
330
331         priv = GET_PRIV (chat);
332
333         if (priv->composing_stop_timeout_id) {
334                 g_source_remove (priv->composing_stop_timeout_id);
335                 priv->composing_stop_timeout_id = 0;
336         }
337 }
338
339 static void
340 set_chate_state_cb (GObject *source,
341                     GAsyncResult *result,
342                     gpointer user_data)
343 {
344         GError *error = NULL;
345
346         if (!tp_text_channel_set_chat_state_finish (TP_TEXT_CHANNEL (source), result,
347                 &error)) {
348                 DEBUG ("Failed to set chat state: %s", error->message);
349                 g_error_free (error);
350         }
351 }
352
353 static void
354 set_chat_state (EmpathyChat *self,
355                 TpChannelChatState state)
356 {
357         EmpathyChatPriv *priv = GET_PRIV (self);
358
359         if (!tp_proxy_has_interface_by_id (priv->tp_chat,
360                 TP_IFACE_QUARK_CHANNEL_INTERFACE_CHAT_STATE))
361                 return;
362
363         tp_text_channel_set_chat_state_async (TP_TEXT_CHANNEL (priv->tp_chat), state,
364                 set_chate_state_cb, self);
365 }
366
367 static gboolean
368 chat_composing_stop_timeout_cb (EmpathyChat *chat)
369 {
370         EmpathyChatPriv *priv;
371
372         priv = GET_PRIV (chat);
373
374         priv->composing_stop_timeout_id = 0;
375         set_chat_state (chat, TP_CHANNEL_CHAT_STATE_PAUSED);
376
377         return FALSE;
378 }
379
380 static void
381 chat_composing_start (EmpathyChat *chat)
382 {
383         EmpathyChatPriv *priv;
384
385         priv = GET_PRIV (chat);
386
387         if (priv->composing_stop_timeout_id) {
388                 /* Just restart the timeout */
389                 chat_composing_remove_timeout (chat);
390         } else {
391                 set_chat_state (chat, TP_CHANNEL_CHAT_STATE_COMPOSING);
392         }
393
394         priv->composing_stop_timeout_id = g_timeout_add_seconds (
395                 COMPOSING_STOP_TIMEOUT,
396                 (GSourceFunc) chat_composing_stop_timeout_cb,
397                 chat);
398 }
399
400 static void
401 chat_composing_stop (EmpathyChat *chat)
402 {
403         chat_composing_remove_timeout (chat);
404         set_chat_state (chat, TP_CHANNEL_CHAT_STATE_ACTIVE);
405 }
406
407 static gint
408 chat_input_history_entry_cmp (InputHistoryEntry *entry,
409                               const gchar *text)
410 {
411         if (!tp_strdiff (entry->text, text)) {
412                 if (entry->modified_text != NULL) {
413                         /* Modified entry and single string cannot be equal. */
414                         return 1;
415                 }
416                 return 0;
417         }
418         return 1;
419 }
420
421 static InputHistoryEntry *
422 chat_input_history_entry_new_with_text (const gchar *text)
423 {
424         InputHistoryEntry *entry;
425         entry = g_slice_new0 (InputHistoryEntry);
426         entry->text = g_strdup (text);
427
428         return entry;
429 }
430
431 static void
432 chat_input_history_entry_free (InputHistoryEntry *entry)
433 {
434         g_free (entry->text);
435         g_free (entry->modified_text);
436         g_slice_free (InputHistoryEntry, entry);
437 }
438
439 static void
440 chat_input_history_entry_revert (InputHistoryEntry *entry)
441 {
442         g_free (entry->modified_text);
443         entry->modified_text = NULL;
444 }
445
446 static void
447 chat_input_history_entry_update_text (InputHistoryEntry *entry,
448                                       const gchar *text)
449 {
450         gchar *old;
451
452         if (!tp_strdiff (text, entry->text)) {
453                 g_free (entry->modified_text);
454                 entry->modified_text = NULL;
455                 return;
456         }
457
458         old = entry->modified_text;
459         entry->modified_text = g_strdup (text);
460         g_free (old);
461 }
462
463 static const gchar *
464 chat_input_history_entry_get_text (InputHistoryEntry *entry)
465 {
466         if (entry == NULL) {
467                 return NULL;
468         }
469
470         if (entry->modified_text != NULL) {
471                 return entry->modified_text;
472         }
473         return entry->text;
474 }
475
476 static GList *
477 chat_input_history_remove_item (GList *list,
478                                 GList *item)
479 {
480         list = g_list_remove_link (list, item);
481         chat_input_history_entry_free (item->data);
482         g_list_free_1 (item);
483         return list;
484 }
485
486 static void
487 chat_input_history_revert (EmpathyChat *chat)
488 {
489         EmpathyChatPriv   *priv;
490         GList             *list;
491         GList             *item1;
492         GList             *item2;
493         InputHistoryEntry *entry;
494
495         priv = GET_PRIV (chat);
496         list = priv->input_history;
497
498         if (list == NULL) {
499                 DEBUG ("No input history");
500                 return;
501         }
502
503         /* Delete temporary entry */
504         if (priv->input_history_current != NULL) {
505                 item1 = list;
506                 list = chat_input_history_remove_item (list, item1);
507                 if (priv->input_history_current == item1) {
508                         /* Removed temporary entry was current entry */
509                         priv->input_history = list;
510                         priv->input_history_current = NULL;
511                         return;
512                 }
513         }
514         else {
515                 /* There is no entry to revert */
516                 return;
517         }
518
519         /* Restore the current history entry to original value */
520         item1 = priv->input_history_current;
521         entry = item1->data;
522         chat_input_history_entry_revert (entry);
523
524         /* Remove restored entry if there is other occurance before this entry */
525         item2 = g_list_find_custom (list, chat_input_history_entry_get_text (entry),
526                                     (GCompareFunc) chat_input_history_entry_cmp);
527         if (item2 != item1) {
528                 list = chat_input_history_remove_item (list, item1);
529         }
530         else {
531                 /* Remove other occurance of the restored entry */
532                 item2 = g_list_find_custom (item1->next,
533                                             chat_input_history_entry_get_text (entry),
534                                             (GCompareFunc) chat_input_history_entry_cmp);
535                 if (item2 != NULL) {
536                         list = chat_input_history_remove_item (list, item2);
537                 }
538         }
539
540         priv->input_history_current = NULL;
541         priv->input_history = list;
542 }
543
544 static void
545 chat_input_history_add (EmpathyChat  *chat,
546                         const gchar *str,
547                         gboolean temporary)
548 {
549         EmpathyChatPriv   *priv;
550         GList             *list;
551         GList             *item;
552         InputHistoryEntry *entry;
553
554         priv = GET_PRIV (chat);
555
556         list = priv->input_history;
557
558         /* Remove any other occurances of this entry, if not temporary */
559         if (!temporary) {
560                 while ((item = g_list_find_custom (list, str,
561                     (GCompareFunc) chat_input_history_entry_cmp)) != NULL) {
562                         list = chat_input_history_remove_item (list, item);
563                 }
564
565                 /* Trim the list to the last 10 items */
566                 while (g_list_length (list) > 10) {
567                         item = g_list_last (list);
568                         if (item != NULL) {
569                                 list = chat_input_history_remove_item (list, item);
570                         }
571                 }
572         }
573
574
575
576         /* Add new entry */
577         entry = chat_input_history_entry_new_with_text (str);
578         list = g_list_prepend (list, entry);
579
580         /* Set the list and the current item pointer */
581         priv->input_history = list;
582         if (temporary) {
583                 priv->input_history_current = list;
584         }
585         else {
586                 priv->input_history_current = NULL;
587         }
588 }
589
590 static const gchar *
591 chat_input_history_get_next (EmpathyChat *chat)
592 {
593         EmpathyChatPriv *priv;
594         GList           *item;
595         const gchar     *msg;
596
597         priv = GET_PRIV (chat);
598
599         if (priv->input_history == NULL) {
600                 DEBUG ("No input history, next entry is NULL");
601                 return NULL;
602         }
603         g_assert (priv->input_history_current != NULL);
604
605         if ((item = g_list_next (priv->input_history_current)) == NULL)
606         {
607                 item = priv->input_history_current;
608         }
609
610         msg = chat_input_history_entry_get_text (item->data);
611
612         DEBUG ("Returning next entry: '%s'", msg);
613
614         priv->input_history_current = item;
615
616         return msg;
617 }
618
619 static const gchar *
620 chat_input_history_get_prev (EmpathyChat *chat)
621 {
622         EmpathyChatPriv *priv;
623         GList           *item;
624         const gchar     *msg;
625
626         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
627
628         priv = GET_PRIV (chat);
629
630         if (priv->input_history == NULL) {
631                 DEBUG ("No input history, previous entry is NULL");
632                 return NULL;
633         }
634
635         if (priv->input_history_current == NULL)
636         {
637                 return NULL;
638         }
639         else if ((item = g_list_previous (priv->input_history_current)) == NULL)
640         {
641                 item = priv->input_history_current;
642         }
643
644         msg = chat_input_history_entry_get_text (item->data);
645
646         DEBUG ("Returning previous entry: '%s'", msg);
647
648         priv->input_history_current = item;
649
650         return msg;
651 }
652
653 static void
654 chat_input_history_update (EmpathyChat *chat,
655                            GtkTextBuffer *buffer)
656 {
657         EmpathyChatPriv      *priv;
658         GtkTextIter           start, end;
659         gchar                *text;
660         InputHistoryEntry    *entry;
661
662         priv = GET_PRIV (chat);
663
664         gtk_text_buffer_get_bounds (buffer, &start, &end);
665         text = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
666
667         if (priv->input_history_current == NULL) {
668                 /* Add the current text temporarily to the history */
669                 chat_input_history_add (chat, text, TRUE);
670                 g_free (text);
671                 return;
672         }
673
674         /* Save the changes in the history */
675         entry = priv->input_history_current->data;
676         if (tp_strdiff (chat_input_history_entry_get_text (entry), text)) {
677                 chat_input_history_entry_update_text (entry, text);
678         }
679
680         g_free (text);
681 }
682
683 typedef struct {
684         EmpathyChat *chat;
685         gchar *message;
686 } ChatCommandMsgData;
687
688 static void
689 chat_command_msg_cb (GObject *source,
690                               GAsyncResult *result,
691                               gpointer                  user_data)
692 {
693         ChatCommandMsgData *data = user_data;
694         GError *error = NULL;
695         TpChannel *channel;
696
697         channel = tp_account_channel_request_ensure_and_observe_channel_finish (
698                                         TP_ACCOUNT_CHANNEL_REQUEST (source), result, &error);
699
700         if (channel == NULL) {
701                 DEBUG ("Failed to get channel: %s", error->message);
702                 g_error_free (error);
703
704                 empathy_chat_view_append_event (data->chat->view,
705                         _("Failed to open private chat"));
706                 goto OUT;
707         }
708
709         if (!EMP_STR_EMPTY (data->message) && TP_IS_TEXT_CHANNEL (channel)) {
710                 TpTextChannel *text = (TpTextChannel *) channel;
711                 TpMessage *msg;
712
713                 msg = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
714                         data->message);
715
716                 tp_text_channel_send_message_async (text, msg, 0, NULL, NULL);
717
718                 g_object_unref (msg);
719         }
720
721         g_object_unref (channel);
722
723 OUT:
724         g_free (data->message);
725         g_slice_free (ChatCommandMsgData, data);
726 }
727
728 static gboolean
729 nick_command_supported (EmpathyChat *chat)
730 {
731         EmpathyChatPriv * priv = GET_PRIV (chat);
732         TpConnection    *connection;
733
734         connection = tp_channel_borrow_connection (TP_CHANNEL (priv->tp_chat));
735         return tp_proxy_has_interface_by_id (connection,
736                 EMP_IFACE_QUARK_CONNECTION_INTERFACE_RENAMING);
737 }
738
739 static gboolean
740 part_command_supported (EmpathyChat *chat)
741 {
742         EmpathyChatPriv * priv = GET_PRIV (chat);
743
744         return tp_proxy_has_interface_by_id (priv->tp_chat,
745                         TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP);
746 }
747
748 static void
749 chat_command_clear (EmpathyChat *chat,
750                     GStrv        strv)
751 {
752         empathy_chat_view_clear (chat->view);
753 }
754
755 static void
756 chat_command_topic (EmpathyChat *chat,
757                     GStrv        strv)
758 {
759         EmpathyChatPriv *priv = GET_PRIV (chat);
760
761         if (!empathy_tp_chat_supports_subject (priv->tp_chat)) {
762                 empathy_chat_view_append_event (chat->view,
763                         _("Topic not supported on this conversation"));
764                 return;
765         }
766
767         if (!empathy_tp_chat_can_set_subject (priv->tp_chat)) {
768                 empathy_chat_view_append_event (chat->view,
769                         _("You are not allowed to change the topic"));
770                 return;
771         }
772
773         empathy_tp_chat_set_subject (priv->tp_chat, strv[1]);
774 }
775
776 void
777 empathy_chat_join_muc (EmpathyChat *chat,
778                    const gchar   *room)
779 {
780         EmpathyChatPriv *priv = GET_PRIV (chat);
781
782         empathy_join_muc (priv->account, room,
783                 empathy_get_current_action_time ());
784 }
785
786 static void
787 chat_command_join (EmpathyChat *chat,
788                    GStrv        strv)
789 {
790         guint i = 0;
791
792         GStrv rooms = g_strsplit_set (strv[1], ", ", -1);
793
794         /* FIXME: Ideally we should ask to handle ourself the channel so we can
795         * report the error if any but this is blocked by
796         * https://bugs.freedesktop.org/show_bug.cgi?id=13422 */
797         while (rooms[i] != NULL) {
798                 /* ignore empty strings */
799                 if (!EMP_STR_EMPTY (rooms[i])) {
800                         empathy_chat_join_muc (chat, rooms[i]);
801                 }
802                 i++;
803         }
804         g_strfreev (rooms);
805 }
806
807 static void
808 chat_command_part (EmpathyChat *chat,
809                            GStrv        strv)
810 {
811         g_signal_emit (chat, signals[PART_COMMAND_ENTERED], 0, strv);
812 }
813
814 static void
815 chat_command_msg_internal (EmpathyChat *chat,
816                            const gchar *contact_id,
817                            const gchar *message)
818 {
819         EmpathyChatPriv *priv = GET_PRIV (chat);
820         ChatCommandMsgData *data;
821         TpAccountChannelRequest *req;
822         GHashTable *request;
823
824         request = tp_asv_new (
825                 TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING, TP_IFACE_CHANNEL_TYPE_TEXT,
826                 TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT,
827                 TP_PROP_CHANNEL_TARGET_ID, G_TYPE_STRING, contact_id,
828                 NULL);
829
830         req = tp_account_channel_request_new (priv->account, request,
831                 empathy_get_current_action_time ());
832
833         /* FIXME: We should probably search in members alias. But this
834          * is enough for IRC */
835         data = g_slice_new (ChatCommandMsgData);
836         data->chat = chat;
837         data->message = g_strdup (message);
838
839         tp_account_channel_request_ensure_and_observe_channel_async (req,
840                 EMPATHY_CHAT_BUS_NAME, NULL, chat_command_msg_cb, data);
841
842         g_object_unref (req);
843         g_hash_table_unref (request);
844 }
845
846 static void
847 chat_command_query (EmpathyChat *chat,
848                     GStrv        strv)
849 {
850         /* If <message> part is not defined,
851          * strv[2] will be the terminal NULL */
852         chat_command_msg_internal (chat, strv[1], strv[2]);
853 }
854
855 static void
856 chat_command_msg (EmpathyChat *chat,
857                   GStrv        strv)
858 {
859         chat_command_msg_internal (chat, strv[1], strv[2]);
860 }
861
862 static void
863 callback_for_request_rename (TpProxy *proxy,
864                   const GError *error,
865                   gpointer user_data,
866                   GObject *weak_object)
867 {
868         if (error != NULL) {
869                 DEBUG ("Call to RequestRename method failed: %s",error->message);
870         }
871 }
872
873 static void
874 chat_command_nick (EmpathyChat *chat,
875                    GStrv        strv)
876 {
877         EmpathyChatPriv *priv = GET_PRIV (chat);
878         TpProxy *proxy;
879
880         proxy = TP_PROXY (tp_account_get_connection (priv->account));
881
882         emp_cli_connection_interface_renaming_call_request_rename (proxy, -1,
883                 strv[1], callback_for_request_rename, NULL, NULL, NULL);
884 }
885
886 static void
887 chat_command_me (EmpathyChat *chat,
888                   GStrv        strv)
889 {
890         EmpathyChatPriv *priv = GET_PRIV (chat);
891         TpMessage *message;
892         TpTextChannel *channel;
893
894         channel = (TpTextChannel *) (priv->tp_chat);
895
896         if (!tp_text_channel_supports_message_type (channel,
897                         TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION)) {
898                 /* Action message are not supported, 'simulate' the action */
899                 EmpathyContact *self_contact;
900                 gchar *tmp;
901
902                 self_contact = empathy_tp_chat_get_self_contact (priv->tp_chat);
903                 /* The TpChat can't be ready if it doesn't have the self contact */
904                 g_assert (self_contact != NULL);
905
906                 tmp = g_strdup_printf ("%s %s", empathy_contact_get_alias (self_contact),
907                         strv[1]);
908                 message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
909                         tmp);
910                 g_free (tmp);
911         }
912         else {
913                 message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION,
914                         strv[1]);
915         }
916
917         empathy_tp_chat_send (priv->tp_chat, message);
918         g_object_unref (message);
919 }
920
921 static void
922 chat_command_say (EmpathyChat *chat,
923                   GStrv        strv)
924 {
925         EmpathyChatPriv *priv = GET_PRIV (chat);
926         TpMessage *message;
927
928         message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
929                 strv[1]);
930         empathy_tp_chat_send (priv->tp_chat, message);
931         g_object_unref (message);
932 }
933
934 static void
935 whois_got_contact_cb (TpConnection *connection,
936                       guint n_contacts,
937                       TpContact * const *contacts,
938                       const gchar * const *requested_ids,
939                       GHashTable *failed_id_errors,
940                       const GError *error,
941                       gpointer user_data,
942                       GObject *weak_object)
943 {
944         EmpathyChat *chat = EMPATHY_CHAT (weak_object);
945
946         g_return_if_fail (n_contacts <= 1);
947
948         if (n_contacts == 0) {
949                 GHashTableIter iter;
950                 gpointer key = NULL, value = NULL;
951                 gchar *id;
952                 GError *id_error;
953
954                 /* tp-glib guarantees that the contacts you requested will be
955                  * in failed_id_errors regardless of whether the individual
956                  * contact was invalid or the whole operation failed.
957                  */
958                 g_hash_table_iter_init (&iter, failed_id_errors);
959                 g_hash_table_iter_next (&iter, &key, &value);
960                 id = key;
961                 id_error = value;
962
963                 DEBUG ("Error getting TpContact for '%s': %s %u %s",
964                         id, g_quark_to_string (id_error->domain),
965                         id_error->code, id_error->message);
966
967                 if (error == NULL) {
968                         /* The specific ID failed. */
969                         gchar *event = g_strdup_printf (
970                                 _("“%s” is not a valid contact ID"), id);
971                         empathy_chat_view_append_event (chat->view, event);
972                         g_free (event);
973                 }
974                 /* Otherwise we're disconnected or something; so the window
975                  * will already say ‘Disconnected’, so let's not show anything.
976                  */
977         } else {
978                 EmpathyContact *empathy_contact;
979                 GtkWidget *window;
980
981                 g_return_if_fail (contacts[0] != NULL);
982                 empathy_contact = empathy_contact_dup_from_tp_contact (
983                         contacts[0]);
984
985                 window = gtk_widget_get_toplevel (GTK_WIDGET (chat));
986                 /* If we're alive and this command is running, we'd better be
987                  * in a window. */
988                 g_return_if_fail (window != NULL);
989                 g_return_if_fail (gtk_widget_is_toplevel (window));
990                 empathy_contact_information_dialog_show (empathy_contact,
991                         GTK_WINDOW (window));
992                 g_object_unref (empathy_contact);
993         }
994 }
995
996 static void
997 chat_command_whois (EmpathyChat *chat,
998                     GStrv strv)
999 {
1000         EmpathyChatPriv *priv = GET_PRIV (chat);
1001         TpConnection *conn;
1002
1003         conn = tp_channel_borrow_connection ((TpChannel *) priv->tp_chat);
1004         tp_connection_get_contacts_by_id (conn,
1005                 /* Element 0 of 'strv' is "whois"; element 1 is the contact ID
1006                  * entered by the user (including spaces, if any). */
1007                 1, (const gchar * const *) strv + 1,
1008                 0, NULL,
1009                 whois_got_contact_cb, NULL, NULL, G_OBJECT (chat));
1010 }
1011
1012 static void
1013 chat_command_whale (EmpathyChat *chat,
1014                     GStrv        strv)
1015 {
1016         EmpathyChatPriv *priv = GET_PRIV (chat);
1017         TpMessage *message;
1018
1019         message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
1020                 "\n\n\n"
1021                 "•_______________•");
1022         empathy_tp_chat_send (priv->tp_chat, message);
1023         g_object_unref (message);
1024 }
1025
1026 static void
1027 chat_command_babywhale (EmpathyChat *chat,
1028                         GStrv        strv)
1029 {
1030         EmpathyChatPriv *priv = GET_PRIV (chat);
1031         TpMessage *message;
1032
1033         message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
1034                 "\n"
1035                 "•_____•");
1036         empathy_tp_chat_send (priv->tp_chat, message);
1037         g_object_unref (message);
1038 }
1039
1040 static void
1041 chat_command_inspector (EmpathyChat *chat,
1042                     GStrv        strv)
1043 {
1044         if (EMPATHY_IS_THEME_ADIUM (chat->view)) {
1045                 empathy_theme_adium_show_inspector (
1046                         EMPATHY_THEME_ADIUM (chat->view));
1047         }
1048 }
1049
1050 static void chat_command_help (EmpathyChat *chat, GStrv strv);
1051
1052 typedef void (*ChatCommandFunc) (EmpathyChat *chat, GStrv strv);
1053
1054 typedef struct {
1055         const gchar *prefix;
1056         guint min_parts;
1057         guint max_parts;
1058         ChatCommandFunc func;
1059         gboolean (*is_supported)(EmpathyChat *chat);
1060         const gchar *help;
1061 } ChatCommandItem;
1062
1063 static ChatCommandItem commands[] = {
1064         {"clear", 1, 1, chat_command_clear, NULL,
1065          N_("/clear: clear all messages from the current conversation")},
1066
1067         {"topic", 2, 2, chat_command_topic, NULL,
1068          N_("/topic <topic>: set the topic of the current conversation")},
1069
1070         {"join", 2, 2, chat_command_join, NULL,
1071          N_("/join <chat room ID>: join a new chat room")},
1072
1073         {"j", 2, 2, chat_command_join, NULL,
1074          N_("/j <chat room ID>: join a new chat room")},
1075
1076         /* FIXME: https://bugzilla.gnome.org/show_bug.cgi?id=643295 */
1077         {"part", 1, 3, chat_command_part, part_command_supported,
1078          N_("/part [<chat room ID>] [<reason>]: leave the chat room, "
1079             "by default the current one")},
1080
1081         {"query", 2, 3, chat_command_query, NULL,
1082          N_("/query <contact ID> [<message>]: open a private chat")},
1083
1084         {"msg", 3, 3, chat_command_msg, NULL,
1085          N_("/msg <contact ID> <message>: open a private chat")},
1086
1087         {"nick", 2, 2, chat_command_nick, nick_command_supported,
1088          N_("/nick <nickname>: change your nickname on the current server")},
1089
1090         {"me", 2, 2, chat_command_me, NULL,
1091          N_("/me <message>: send an ACTION message to the current conversation")},
1092
1093         {"say", 2, 2, chat_command_say, NULL,
1094          N_("/say <message>: send <message> to the current conversation. "
1095             "This is used to send a message starting with a '/'. For example: "
1096             "\"/say /join is used to join a new chat room\"")},
1097
1098         {"whois", 2, 2, chat_command_whois, NULL,
1099          N_("/whois <contact ID>: display information about a contact")},
1100
1101         {"help", 1, 2, chat_command_help, NULL,
1102          N_("/help [<command>]: show all supported commands. "
1103             "If <command> is defined, show its usage.")},
1104
1105         {"inspector", 1, 1, chat_command_inspector, NULL, NULL},
1106
1107         {"whale", 1, 1, chat_command_whale, NULL, NULL},
1108         {"babywhale", 1, 1, chat_command_babywhale, NULL, NULL},
1109 };
1110
1111 static void
1112 chat_command_show_help (EmpathyChat     *chat,
1113                         ChatCommandItem *item)
1114 {
1115         gchar *str;
1116
1117         if (item->help == NULL) {
1118                 return;
1119         }
1120
1121         str = g_strdup_printf (_("Usage: %s"), _(item->help));
1122         empathy_chat_view_append_event (chat->view, str);
1123         g_free (str);
1124 }
1125
1126 static void
1127 chat_command_help (EmpathyChat *chat,
1128                    GStrv        strv)
1129 {
1130         guint i;
1131
1132         /* If <command> part is not defined,
1133          * strv[1] will be the terminal NULL */
1134         if (strv[1] == NULL) {
1135                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
1136                         if (commands[i].is_supported != NULL) {
1137                                 if (!commands[i].is_supported (chat)) {
1138                                         continue;
1139                                 }
1140                         }
1141                         if (commands[i].help == NULL) {
1142                                 continue;
1143                         }
1144                         empathy_chat_view_append_event (chat->view,
1145                                 _(commands[i].help));
1146                 }
1147                 return;
1148         }
1149
1150         for (i = 0; i < G_N_ELEMENTS (commands); i++) {
1151                 if (g_ascii_strcasecmp (strv[1], commands[i].prefix) == 0) {
1152                         if (commands[i].is_supported != NULL) {
1153                                 if (!commands[i].is_supported (chat)) {
1154                                         break;
1155                                 }
1156                         }
1157                         if (commands[i].help == NULL) {
1158                                 break;
1159                         }
1160                         chat_command_show_help (chat, &commands[i]);
1161                         return;
1162                 }
1163         }
1164
1165         empathy_chat_view_append_event (chat->view,
1166                 _("Unknown command"));
1167 }
1168
1169 static GStrv
1170 chat_command_parse (const gchar *text, guint max_parts)
1171 {
1172         GPtrArray *array;
1173         gchar *item;
1174
1175         DEBUG ("Parse command, parts=%d text=\"%s\":", max_parts, text);
1176
1177         array = g_ptr_array_sized_new (max_parts + 1);
1178         while (max_parts > 1) {
1179                 const gchar *end;
1180
1181                 /* Skip white spaces */
1182                 while (g_ascii_isspace (*text)) {
1183                         text++;
1184                 }
1185
1186                 /* Search the end of this part, until first space. */
1187                 for (end = text; *end != '\0' && !g_ascii_isspace (*end); end++)
1188                         /* Do nothing */;
1189                 if (*end == '\0') {
1190                         break;
1191                 }
1192
1193                 item = g_strndup (text, end - text);
1194                 g_ptr_array_add (array, item);
1195                 DEBUG ("\tITEM: \"%s\"", item);
1196
1197                 text = end;
1198                 max_parts--;
1199         }
1200
1201         /* Append last part if not empty */
1202         item = g_strstrip (g_strdup (text));
1203         if (!EMP_STR_EMPTY (item)) {
1204                 g_ptr_array_add (array, item);
1205                 DEBUG ("\tITEM: \"%s\"", item);
1206         } else {
1207                 g_free (item);
1208         }
1209
1210         /* Make the array NULL-terminated */
1211         g_ptr_array_add (array, NULL);
1212
1213         return (GStrv) g_ptr_array_free (array, FALSE);
1214 }
1215
1216 static gboolean
1217 has_prefix_case (const gchar *s,
1218                   const gchar *prefix)
1219 {
1220         return g_ascii_strncasecmp (s, prefix, strlen (prefix)) == 0;
1221 }
1222
1223 static void
1224 chat_send (EmpathyChat  *chat,
1225            const gchar *msg)
1226 {
1227         EmpathyChatPriv *priv;
1228         TpMessage  *message;
1229         guint            i;
1230
1231         if (EMP_STR_EMPTY (msg)) {
1232                 return;
1233         }
1234
1235         priv = GET_PRIV (chat);
1236
1237         chat_input_history_add (chat, msg, FALSE);
1238
1239         if (msg[0] == '/') {
1240                 gboolean second_slash = FALSE;
1241                 const gchar *iter = msg + 1;
1242
1243                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
1244                         GStrv strv;
1245                         guint strv_len;
1246                         gchar c;
1247
1248                         if (!has_prefix_case (msg + 1, commands[i].prefix)) {
1249                                 continue;
1250                         }
1251                         c = *(msg + 1 + strlen (commands[i].prefix));
1252                         if (c != '\0' && !g_ascii_isspace (c)) {
1253                                 continue;
1254                         }
1255                         if (commands[i].is_supported != NULL) {
1256                                 if (!commands[i].is_supported (chat)) {
1257                                         continue;
1258                                 }
1259                         }
1260
1261                         /* We can't use g_strsplit here because it does
1262                          * not deal correctly if we have more than one space
1263                          * between args */
1264                         strv = chat_command_parse (msg + 1, commands[i].max_parts);
1265
1266                         strv_len = g_strv_length (strv);
1267                         if (strv_len < commands[i].min_parts ||
1268                             strv_len > commands[i].max_parts) {
1269                                 chat_command_show_help (chat, &commands[i]);
1270                                 g_strfreev (strv);
1271                                 return;
1272                         }
1273
1274                         commands[i].func (chat, strv);
1275                         g_strfreev (strv);
1276                         return;
1277                 }
1278
1279                 /* Also allow messages with two slashes before the
1280                  * first space, so it is possible to send a /unix/path.
1281                  * This heuristic is kind of crap. */
1282                 while (*iter != '\0' && !g_ascii_isspace (*iter)) {
1283                         if (*iter == '/') {
1284                                 second_slash = TRUE;
1285                                 break;
1286                         }
1287                         iter++;
1288                 }
1289
1290                 if (!second_slash) {
1291                         empathy_chat_view_append_event (chat->view,
1292                                 _("Unknown command; see /help for the available"
1293                                   " commands"));
1294                         return;
1295                 }
1296         }
1297
1298         message = tp_client_message_new_text (TP_CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
1299                 msg);
1300         empathy_tp_chat_send (priv->tp_chat, message);
1301         g_object_unref (message);
1302 }
1303
1304 static void
1305 chat_input_text_view_send (EmpathyChat *chat)
1306 {
1307         GtkTextBuffer  *buffer;
1308         GtkTextIter     start, end;
1309         gchar          *msg;
1310
1311         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1312
1313         gtk_text_buffer_get_bounds (buffer, &start, &end);
1314         msg = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1315
1316         /* clear the input field */
1317         gtk_text_buffer_set_text (buffer, "", -1);
1318         /* delete input history modifications */
1319         chat_input_history_revert (chat);
1320
1321         chat_send (chat, msg);
1322         g_free (msg);
1323 }
1324
1325 static void
1326 chat_state_changed_cb (EmpathyTpChat      *tp_chat,
1327                        EmpathyContact     *contact,
1328                        TpChannelChatState  state,
1329                        EmpathyChat        *chat)
1330 {
1331         EmpathyChatPriv *priv;
1332         GList          *l;
1333         gboolean        was_composing;
1334
1335         priv = GET_PRIV (chat);
1336
1337         if (empathy_contact_is_user (contact)) {
1338                 /* We don't care about our own chat state */
1339                 return;
1340         }
1341
1342         was_composing = (priv->compositors != NULL);
1343
1344         /* Find the contact in the list. After that l is the list elem or NULL */
1345         for (l = priv->compositors; l; l = l->next) {
1346                 if (contact == l->data) {
1347                         break;
1348                 }
1349         }
1350
1351         switch (state) {
1352         case TP_CHANNEL_CHAT_STATE_GONE:
1353         case TP_CHANNEL_CHAT_STATE_INACTIVE:
1354         case TP_CHANNEL_CHAT_STATE_PAUSED:
1355         case TP_CHANNEL_CHAT_STATE_ACTIVE:
1356                 /* Contact is not composing */
1357                 if (l) {
1358                         priv->compositors = g_list_remove_link (priv->compositors, l);
1359                         g_object_unref (l->data);
1360                         g_list_free1 (l);
1361                 }
1362                 break;
1363         case TP_CHANNEL_CHAT_STATE_COMPOSING:
1364                 /* Contact is composing */
1365                 if (!l) {
1366                         priv->compositors = g_list_prepend (priv->compositors,
1367                                                             g_object_ref (contact));
1368                 }
1369                 break;
1370         default:
1371                 g_assert_not_reached ();
1372         }
1373
1374         DEBUG ("Was composing: %s now composing: %s",
1375                 was_composing ? "yes" : "no",
1376                 priv->compositors ? "yes" : "no");
1377
1378         if ((was_composing && !priv->compositors) ||
1379             (!was_composing && priv->compositors)) {
1380                 /* Composing state changed */
1381                 g_signal_emit (chat, signals[COMPOSING], 0,
1382                                priv->compositors != NULL);
1383         }
1384 }
1385
1386 static GRegex *
1387 get_highlight_regex_for (const gchar *name)
1388 {
1389         GRegex *regex;
1390         gchar *name_esc, *pattern;
1391         GError *error = NULL;
1392
1393         name_esc = g_regex_escape_string (name, -1);
1394         pattern = g_strdup_printf ("\\b%s\\b", name_esc);
1395         regex = g_regex_new (pattern, G_REGEX_CASELESS | G_REGEX_OPTIMIZE, 0,
1396                 &error);
1397
1398         if (regex == NULL) {
1399                 DEBUG ("couldn't compile regex /%s/: %s", pattern,
1400                         error->message);
1401
1402                 g_error_free (error);
1403         }
1404
1405         g_free (pattern);
1406         g_free (name_esc);
1407
1408         return regex;
1409 }
1410
1411 static gboolean
1412 chat_should_highlight (EmpathyChat *chat,
1413         EmpathyMessage *message)
1414 {
1415         EmpathyContact *contact;
1416         const gchar   *msg, *to;
1417         gboolean       ret_val = FALSE;
1418         TpChannelTextMessageFlags flags;
1419         GRegex *regex;
1420
1421         g_return_val_if_fail (EMPATHY_IS_MESSAGE (message), FALSE);
1422
1423         if (!empathy_message_is_incoming (message)) {
1424                 return FALSE;
1425         }
1426
1427         msg = empathy_message_get_body (message);
1428         if (!msg) {
1429                 return FALSE;
1430         }
1431
1432         contact = empathy_tp_chat_get_self_contact (chat->priv->tp_chat);
1433         if (!contact) {
1434                 return FALSE;
1435         }
1436
1437         to = empathy_contact_get_alias (contact);
1438         if (!to) {
1439                 return FALSE;
1440         }
1441
1442         flags = empathy_message_get_flags (message);
1443         if (flags & TP_CHANNEL_TEXT_MESSAGE_FLAG_SCROLLBACK) {
1444                 /* FIXME: Ideally we shouldn't highlight scrollback messages only if they
1445                  * have already been received by the user before (and so are in the logs) */
1446                 return FALSE;
1447         }
1448
1449         regex = get_highlight_regex_for (to);
1450         if (regex != NULL) {
1451                 ret_val = g_regex_match (regex, msg, 0, NULL);
1452                 g_regex_unref (regex);
1453         }
1454
1455         return ret_val;
1456 }
1457
1458 static void
1459 chat_message_received (EmpathyChat *chat,
1460         EmpathyMessage *message,
1461         gboolean pending)
1462 {
1463         EmpathyChatPriv *priv = GET_PRIV (chat);
1464         EmpathyContact  *sender;
1465
1466         sender = empathy_message_get_sender (message);
1467
1468         if (empathy_message_is_edit (message)) {
1469                 DEBUG ("Editing message '%s' to '%s'",
1470                         empathy_message_get_supersedes (message),
1471                         empathy_message_get_body (message));
1472
1473                 empathy_chat_view_edit_message (chat->view, message);
1474         } else {
1475                 gboolean should_highlight = chat_should_highlight (chat, message);
1476                 DEBUG ("Appending new message '%s' from %s (%d)",
1477                         empathy_message_get_token (message),
1478                         empathy_contact_get_alias (sender),
1479                         empathy_contact_get_handle (sender));
1480
1481                 empathy_chat_view_append_message (chat->view, message, should_highlight);
1482
1483                 if (empathy_message_is_incoming (message)) {
1484                         priv->unread_messages++;
1485                         g_object_notify (G_OBJECT (chat), "nb-unread-messages");
1486                 }
1487
1488                 g_signal_emit (chat, signals[NEW_MESSAGE], 0, message, pending,
1489                                should_highlight);
1490         }
1491
1492         /* We received a message so the contact is no longer
1493          * composing */
1494         chat_state_changed_cb (priv->tp_chat, sender,
1495                                TP_CHANNEL_CHAT_STATE_ACTIVE,
1496                                chat);
1497 }
1498
1499 static void
1500 chat_message_received_cb (EmpathyTpChat  *tp_chat,
1501                           EmpathyMessage *message,
1502                           EmpathyChat    *chat)
1503 {
1504         chat_message_received (chat, message, FALSE);
1505 }
1506
1507 static void
1508 chat_message_acknowledged_cb (EmpathyTpChat  *tp_chat,
1509                               EmpathyMessage *message,
1510                               EmpathyChat    *chat)
1511 {
1512         EmpathyChatPriv *priv = GET_PRIV (chat);
1513
1514         empathy_chat_view_message_acknowledged (chat->view,
1515             message);
1516
1517         if (!empathy_message_is_edit (message)) {
1518                 priv->unread_messages--;
1519                 g_object_notify (G_OBJECT (chat), "nb-unread-messages");
1520         }
1521 }
1522
1523 static void
1524 append_balance_error (EmpathyChat *chat,
1525                       const gchar *message_body)
1526 {
1527         EmpathyChatPriv *priv = GET_PRIV (chat);
1528         TpConnection *conn = tp_channel_borrow_connection (TP_CHANNEL (priv->tp_chat));
1529         const gchar *uri = tp_connection_get_balance_uri (conn);
1530         const gchar *error = _("insufficient balance to send message");
1531         gchar *str, *str_markup = NULL;
1532
1533         if (message_body != NULL) {
1534                 str = g_strdup_printf (_("Error sending message '%s': %s"), message_body, error);
1535         } else {
1536                 str = g_strdup_printf (_("Error sending message: %s"), error);
1537         }
1538
1539         if (!tp_str_empty (uri)) {
1540                 /* translators: error used when user doesn't have enough credit on his
1541                  * account to send the message. */
1542                 gchar *markup_error = g_strdup_printf (_("insufficient balance to send message."
1543                                                          " <a href='%s'>Top up</a>."), uri);
1544
1545                 if (message_body != NULL) {
1546                         gchar *escaped_body = g_markup_escape_text (message_body, -1);
1547
1548                         str_markup = g_strdup_printf (_("Error sending message '%s': %s"),
1549                                 escaped_body, markup_error);
1550
1551                         g_free (escaped_body);
1552                 } else {
1553                         str_markup = g_strdup_printf (_("Error sending message: %s"), markup_error);
1554                 }
1555
1556                 g_free (markup_error);
1557         }
1558
1559         if (str_markup != NULL)
1560                 empathy_chat_view_append_event_markup (chat->view, str_markup, str);
1561         else
1562                 empathy_chat_view_append_event (chat->view, str);
1563
1564         g_free (str);
1565         g_free (str_markup);
1566 }
1567
1568 static void
1569 chat_send_error_cb (EmpathyTpChat          *tp_chat,
1570                     const gchar            *message_body,
1571                     TpChannelTextSendError  error_code,
1572                     const gchar            *dbus_error,
1573                     EmpathyChat            *chat)
1574 {
1575         const gchar *error = NULL;
1576         gchar       *str;
1577
1578         if (!tp_strdiff (dbus_error, TP_ERROR_STR_INSUFFICIENT_BALANCE)) {
1579                 append_balance_error (chat, message_body);
1580                 return;
1581         } else if (!tp_strdiff (dbus_error, TP_ERROR_STR_NOT_CAPABLE)) {
1582                 error = _("not capable");
1583         }
1584
1585         if (error == NULL) {
1586                 /* if we didn't find a dbus-error, try the old error */
1587                 switch (error_code) {
1588                 case TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE:
1589                         error = _("offline");
1590                         break;
1591                 case TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT:
1592                         error = _("invalid contact");
1593                         break;
1594                 case TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED:
1595                         error = _("permission denied");
1596                         break;
1597                 case TP_CHANNEL_TEXT_SEND_ERROR_TOO_LONG:
1598                         error = _("too long message");
1599                         break;
1600                 case TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED:
1601                         error = _("not implemented");
1602                         break;
1603                 case TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN:
1604                 default:
1605                         error = _("unknown");
1606                         break;
1607                 }
1608         }
1609
1610         if (message_body != NULL) {
1611                         str = g_strdup_printf (_("Error sending message '%s': %s"),
1612                                 message_body, error);
1613         }
1614         else {
1615                         str = g_strdup_printf (_("Error sending message: %s"), error);
1616         }
1617
1618         empathy_chat_view_append_event (chat->view, str);
1619         g_free (str);
1620 }
1621
1622 static void
1623 chat_topic_label_size_allocate_cb (GtkLabel *label,
1624                                    GtkAllocation *allocation,
1625                                    EmpathyChat *chat)
1626 {
1627         EmpathyChatPriv *priv = GET_PRIV (chat);
1628
1629         if (!gtk_label_get_line_wrap (label)) {
1630                 if (pango_layout_is_ellipsized (gtk_label_get_layout (label)))
1631                         gtk_widget_show (priv->expander_topic);
1632                 else
1633                         gtk_widget_hide (priv->expander_topic);
1634
1635                 return;
1636         }
1637 }
1638
1639 static void
1640 chat_topic_expander_activate_cb (GtkExpander *expander,
1641                                  GParamSpec *param_spec,
1642                                  EmpathyChat *chat)
1643 {
1644         EmpathyChatPriv *priv = GET_PRIV (chat);
1645
1646         if (gtk_expander_get_expanded (expander)) {
1647                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_NONE);
1648                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), TRUE);
1649         } else {
1650                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_END);
1651                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), FALSE);
1652         }
1653 }
1654
1655 static void
1656 chat_subject_changed_cb (EmpathyChat *chat)
1657 {
1658         EmpathyChatPriv *priv = GET_PRIV (chat);
1659
1660                 g_free (priv->subject);
1661                 priv->subject = g_strdup (empathy_tp_chat_get_subject (priv->tp_chat));
1662                 g_object_notify (G_OBJECT (chat), "subject");
1663
1664                 if (EMP_STR_EMPTY (priv->subject)) {
1665                         gtk_widget_hide (priv->hbox_topic);
1666                 } else {
1667                         gchar *markup_topic;
1668                         gchar *markup_text;
1669
1670                         markup_topic = empathy_add_link_markup (priv->subject);
1671                         markup_text = g_strdup_printf ("<span weight=\"bold\">%s</span> %s",
1672                                 _("Topic:"), markup_topic);
1673
1674                         gtk_label_set_markup (GTK_LABEL (priv->label_topic), markup_text);
1675                         g_free (markup_text);
1676                         g_free (markup_topic);
1677
1678                         gtk_widget_show (priv->hbox_topic);
1679                 }
1680                 if (priv->block_events_timeout_id == 0) {
1681                         gchar *str;
1682
1683                         if (!EMP_STR_EMPTY (priv->subject)) {
1684                                 str = g_strdup_printf (_("Topic set to: %s"), priv->subject);
1685                         } else {
1686                                 str = g_strdup (_("No topic defined"));
1687                         }
1688                         empathy_chat_view_append_event (EMPATHY_CHAT (chat)->view, str);
1689                         g_free (str);
1690                 }
1691 }
1692
1693 static void
1694 chat_title_changed_cb (EmpathyChat *chat)
1695 {
1696         EmpathyChatPriv *priv = GET_PRIV (chat);
1697
1698                 g_free (priv->name);
1699                 priv->name = g_strdup (empathy_tp_chat_get_title (priv->tp_chat));
1700                 g_object_notify (G_OBJECT (chat), "name");
1701 }
1702
1703 static gboolean
1704 chat_input_text_get_word_from_iter (GtkTextIter   *iter,
1705                                     GtkTextIter   *start,
1706                                     GtkTextIter   *end)
1707 {
1708         GtkTextIter word_start = *iter;
1709         GtkTextIter word_end = *iter;
1710         GtkTextIter tmp;
1711
1712         if (gtk_text_iter_inside_word (&word_end) &&
1713                         !gtk_text_iter_ends_word (&word_end)) {
1714                 gtk_text_iter_forward_word_end (&word_end);
1715         }
1716
1717         tmp = word_end;
1718
1719         if (gtk_text_iter_get_char (&tmp) == '\'') {
1720                 gtk_text_iter_forward_char (&tmp);
1721
1722                 if (g_unichar_isalpha (gtk_text_iter_get_char (&tmp))) {
1723                         gtk_text_iter_forward_word_end (&word_end);
1724                 }
1725         }
1726
1727
1728         if (gtk_text_iter_inside_word (&word_start) ||
1729                         gtk_text_iter_ends_word (&word_start)) {
1730                 if (!gtk_text_iter_starts_word (&word_start) ||
1731                                 gtk_text_iter_equal (&word_start, &word_end)) {
1732                         gtk_text_iter_backward_word_start (&word_start);
1733                 }
1734
1735                 tmp = word_start;
1736                 gtk_text_iter_backward_char (&tmp);
1737
1738                 if (gtk_text_iter_get_char (&tmp) == '\'') {
1739                         gtk_text_iter_backward_char (&tmp);
1740
1741                         if (g_unichar_isalpha (gtk_text_iter_get_char (&tmp))) {
1742                                 gtk_text_iter_backward_word_start (&word_start);
1743                         }
1744                 }
1745         }
1746
1747         *start = word_start;
1748         *end = word_end;
1749         return TRUE;
1750 }
1751
1752 static void
1753 chat_input_text_buffer_insert_text_cb (GtkTextBuffer *buffer,
1754                                        GtkTextIter   *location,
1755                                        gchar         *text,
1756                                        gint           len,
1757                                        EmpathyChat   *chat)
1758 {
1759         GtkTextIter iter, pos;
1760
1761         /* Remove all misspelled tags in the inserted text.
1762          * This happens when text is inserted within a misspelled word. */
1763         gtk_text_buffer_get_iter_at_offset (buffer, &iter,
1764                                             gtk_text_iter_get_offset (location) - len);
1765         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled",
1766                                             &iter, location);
1767
1768         gtk_text_buffer_get_iter_at_mark (buffer, &pos, gtk_text_buffer_get_insert (buffer));
1769
1770         do {
1771                 GtkTextIter start, end;
1772                 gchar *str;
1773
1774                 if (!chat_input_text_get_word_from_iter (&iter, &start, &end))
1775                         continue;
1776
1777                 str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1778
1779                 if (gtk_text_iter_in_range (&pos, &start, &end) ||
1780                                 gtk_text_iter_equal (&pos, &end) ||
1781                                 empathy_spell_check (str)) {
1782                         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
1783                 } else {
1784                         gtk_text_buffer_apply_tag_by_name (buffer, "misspelled", &start, &end);
1785                 }
1786
1787                 g_free (str);
1788
1789         } while (gtk_text_iter_forward_word_end (&iter) &&
1790                  gtk_text_iter_compare (&iter, location) <= 0);
1791 }
1792
1793 static void
1794 chat_input_text_buffer_delete_range_cb (GtkTextBuffer *buffer,
1795                                         GtkTextIter   *start,
1796                                         GtkTextIter   *end,
1797                                         EmpathyChat   *chat)
1798 {
1799         GtkTextIter word_start, word_end;
1800
1801         if (chat_input_text_get_word_from_iter (start, &word_start, &word_end)) {
1802                 gtk_text_buffer_remove_tag_by_name (buffer, "misspelled",
1803                                                     &word_start, &word_end);
1804         }
1805 }
1806
1807 static void
1808 chat_input_text_buffer_changed_cb (GtkTextBuffer *buffer,
1809                                    EmpathyChat    *chat)
1810 {
1811         if (gtk_text_buffer_get_char_count (buffer) == 0) {
1812                 chat_composing_stop (chat);
1813         } else {
1814                 chat_composing_start (chat);
1815         }
1816 }
1817
1818 static void
1819 chat_input_text_buffer_notify_cursor_position_cb (GtkTextBuffer *buffer,
1820                                                   GParamSpec    *pspec,
1821                                                   EmpathyChat    *chat)
1822 {
1823         GtkTextIter pos;
1824         GtkTextIter prev_pos;
1825         GtkTextIter word_start;
1826         GtkTextIter word_end;
1827         GtkTextMark *mark;
1828         gchar *str;
1829
1830         mark = gtk_text_buffer_get_mark (buffer, "previous-cursor-position");
1831
1832         gtk_text_buffer_get_iter_at_mark (buffer, &pos,
1833                                           gtk_text_buffer_get_insert (buffer));
1834         gtk_text_buffer_get_iter_at_mark (buffer, &prev_pos, mark);
1835
1836         if (!chat_input_text_get_word_from_iter (&prev_pos, &word_start, &word_end))
1837                 goto out;
1838
1839         if (!gtk_text_iter_in_range (&pos, &word_start, &word_end) &&
1840                         !gtk_text_iter_equal (&pos, &word_end)) {
1841                 str = gtk_text_buffer_get_text (buffer,
1842                                         &word_start, &word_end, FALSE);
1843
1844                 if (!empathy_spell_check (str)) {
1845                         gtk_text_buffer_apply_tag_by_name (buffer,
1846                                         "misspelled", &word_start, &word_end);
1847                 } else {
1848                         gtk_text_buffer_remove_tag_by_name (buffer,
1849                                         "misspelled", &word_start, &word_end);
1850                 }
1851
1852                 g_free (str);
1853         }
1854
1855 out:
1856         gtk_text_buffer_move_mark (buffer, mark, &pos);
1857 }
1858
1859 static gboolean
1860 empathy_isspace_cb (gunichar c,
1861                  gpointer data)
1862 {
1863         return g_unichar_isspace (c);
1864 }
1865
1866 static gboolean
1867 chat_input_key_press_event_cb (GtkWidget   *widget,
1868                                GdkEventKey *event,
1869                                EmpathyChat *chat)
1870 {
1871         EmpathyChatPriv *priv;
1872         GtkAdjustment  *adj;
1873         gdouble         val;
1874         GtkWidget      *text_view_sw;
1875
1876         priv = GET_PRIV (chat);
1877
1878         priv->most_recent_event_type = event->type;
1879
1880         /* Catch ctrl+up/down so we can traverse messages we sent */
1881         if ((event->state & GDK_CONTROL_MASK) &&
1882             (event->keyval == GDK_KEY_Up ||
1883              event->keyval == GDK_KEY_Down)) {
1884                 GtkTextBuffer *buffer;
1885                 const gchar   *str;
1886
1887                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1888                 chat_input_history_update (chat, buffer);
1889
1890                 if (event->keyval == GDK_KEY_Up) {
1891                         str = chat_input_history_get_next (chat);
1892                 } else {
1893                         str = chat_input_history_get_prev (chat);
1894                 }
1895
1896                 g_signal_handlers_block_by_func (buffer,
1897                                                  chat_input_text_buffer_changed_cb,
1898                                                  chat);
1899                 gtk_text_buffer_set_text (buffer, str ? str : "", -1);
1900                 g_signal_handlers_unblock_by_func (buffer,
1901                                                    chat_input_text_buffer_changed_cb,
1902                                                    chat);
1903
1904                 return TRUE;
1905         }
1906
1907         /* Catch enter but not ctrl/shift-enter */
1908         if (IS_ENTER (event->keyval) &&
1909             !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1910                 GtkTextView *view;
1911
1912                 /* This is to make sure that kinput2 gets the enter. And if
1913                  * it's handled there we shouldn't send on it. This is because
1914                  * kinput2 uses Enter to commit letters. See:
1915                  * http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=104299
1916                  */
1917
1918                 view = GTK_TEXT_VIEW (chat->input_text_view);
1919                 if (gtk_text_view_im_context_filter_keypress (view, event)) {
1920                         gtk_text_view_reset_im_context (view);
1921                         return TRUE;
1922                 }
1923
1924                 chat_input_text_view_send (chat);
1925                 return TRUE;
1926         }
1927
1928         text_view_sw = gtk_widget_get_parent (GTK_WIDGET (chat->view));
1929
1930         if (IS_ENTER (event->keyval) &&
1931             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1932                 /* Newline for shift/control-enter. */
1933                 return FALSE;
1934         }
1935         if (!(event->state & GDK_CONTROL_MASK) &&
1936             event->keyval == GDK_KEY_Page_Up) {
1937                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1938                 gtk_adjustment_set_value (adj, gtk_adjustment_get_value (adj) - gtk_adjustment_get_page_size (adj));
1939                 return TRUE;
1940         }
1941         if ((event->state & GDK_CONTROL_MASK) != GDK_CONTROL_MASK &&
1942             event->keyval == GDK_KEY_Page_Down) {
1943                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1944                 val = MIN (gtk_adjustment_get_value (adj) + gtk_adjustment_get_page_size (adj),
1945                            gtk_adjustment_get_upper (adj) - gtk_adjustment_get_page_size (adj));
1946                 gtk_adjustment_set_value (adj, val);
1947                 return TRUE;
1948         }
1949         if (event->keyval == GDK_KEY_Escape) {
1950                 empathy_search_bar_hide (EMPATHY_SEARCH_BAR (priv->search_bar));
1951         }
1952         if (!(event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) &&
1953             event->keyval == GDK_KEY_Tab) {
1954                 GtkTextBuffer *buffer;
1955                 GtkTextIter    start, current;
1956                 gchar         *nick, *completed;
1957                 GList         *list, *completed_list;
1958                 gboolean       is_start_of_buffer;
1959
1960                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (EMPATHY_CHAT (chat)->input_text_view));
1961                 gtk_text_buffer_get_iter_at_mark (buffer, &current, gtk_text_buffer_get_insert (buffer));
1962
1963                 /* Get the start of the nick to complete. */
1964                 gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer));
1965                 if (gtk_text_iter_backward_find_char (&start, &empathy_isspace_cb, NULL, NULL)) {
1966                         gtk_text_iter_set_offset (&start, gtk_text_iter_get_offset (&start) + 1);
1967                 }
1968                 is_start_of_buffer = gtk_text_iter_is_start (&start);
1969
1970                 list = empathy_contact_list_get_members (EMPATHY_CONTACT_LIST (priv->tp_chat));
1971                 g_completion_add_items (priv->completion, list);
1972
1973                 nick = gtk_text_buffer_get_text (buffer, &start, &current, FALSE);
1974                 completed_list = g_completion_complete (priv->completion,
1975                                                         nick,
1976                                                         &completed);
1977
1978                 g_free (nick);
1979
1980                 if (completed) {
1981                         guint        len;
1982                         const gchar *text;
1983                         GString     *message = NULL;
1984                         GList       *l;
1985
1986                         gtk_text_buffer_delete (buffer, &start, &current);
1987
1988                         len = g_list_length (completed_list);
1989
1990                         if (len == 1) {
1991                                 /* If we only have one hit, use that text
1992                                  * instead of the text in completed since the
1993                                  * completed text will use the typed string
1994                                  * which might be cased all wrong.
1995                                  * Fixes #120876
1996                                  * */
1997                                 text = empathy_contact_get_alias (completed_list->data);
1998                         } else {
1999                                 text = completed;
2000
2001                                 /* Print all hits to the scrollback view, so the
2002                                  * user knows what possibilities he has.
2003                                  * Fixes #599779
2004                                  * */
2005                                  message = g_string_new ("");
2006                                  for (l = completed_list; l != NULL; l = l->next) {
2007                                         g_string_append (message, empathy_contact_get_alias (l->data));
2008                                         g_string_append (message, " - ");
2009                                  }
2010                                  empathy_chat_view_append_event (chat->view, message->str);
2011                                  g_string_free (message, TRUE);
2012                         }
2013
2014                         gtk_text_buffer_insert_at_cursor (buffer, text, strlen (text));
2015
2016                         if (len == 1 && is_start_of_buffer) {
2017                             gchar *complete_char;
2018
2019                             complete_char = g_settings_get_string (
2020                                     priv->gsettings_chat,
2021                                     EMPATHY_PREFS_CHAT_NICK_COMPLETION_CHAR);
2022
2023                             if (complete_char != NULL) {
2024                                 gtk_text_buffer_insert_at_cursor (buffer,
2025                                                                   complete_char,
2026                                                                   strlen (complete_char));
2027                                 gtk_text_buffer_insert_at_cursor (buffer, " ", 1);
2028                                 g_free (complete_char);
2029                             }
2030                         }
2031
2032                         g_free (completed);
2033                 }
2034
2035                 g_completion_clear_items (priv->completion);
2036
2037                 g_list_foreach (list, (GFunc) g_object_unref, NULL);
2038                 g_list_free (list);
2039
2040                 return TRUE;
2041         }
2042
2043         return FALSE;
2044 }
2045
2046 static gboolean
2047 chat_text_view_focus_in_event_cb (GtkWidget  *widget,
2048                                   GdkEvent   *event,
2049                                   EmpathyChat *chat)
2050 {
2051         gtk_widget_grab_focus (chat->input_text_view);
2052
2053         return TRUE;
2054 }
2055
2056 static void
2057 chat_input_realize_cb (GtkWidget   *widget,
2058                        EmpathyChat *chat)
2059 {
2060         DEBUG ("Setting focus to the input text view");
2061         if (gtk_widget_is_sensitive (widget)) {
2062                 gtk_widget_grab_focus (widget);
2063         }
2064 }
2065
2066 static void
2067 chat_input_has_focus_notify_cb (GtkWidget   *widget,
2068                                 GParamSpec  *pspec,
2069                                 EmpathyChat *chat)
2070 {
2071         empathy_chat_view_focus_toggled (chat->view, gtk_widget_has_focus (widget));
2072 }
2073
2074 static void
2075 chat_insert_smiley_activate_cb (EmpathySmileyManager *manager,
2076                                 EmpathySmiley        *smiley,
2077                                 gpointer              user_data)
2078 {
2079         EmpathyChat   *chat = EMPATHY_CHAT (user_data);
2080         GtkTextBuffer *buffer;
2081         GtkTextIter    iter;
2082
2083         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2084
2085         gtk_text_buffer_get_end_iter (buffer, &iter);
2086         gtk_text_buffer_insert (buffer, &iter, smiley->str, -1);
2087
2088         gtk_text_buffer_get_end_iter (buffer, &iter);
2089         gtk_text_buffer_insert (buffer, &iter, " ", -1);
2090 }
2091
2092 typedef struct {
2093         EmpathyChat  *chat;
2094         gchar       *word;
2095
2096         GtkTextIter  start;
2097         GtkTextIter  end;
2098 } EmpathyChatSpell;
2099
2100 static EmpathyChatSpell *
2101 chat_spell_new (EmpathyChat  *chat,
2102                 const gchar *word,
2103                 GtkTextIter  start,
2104                 GtkTextIter  end)
2105 {
2106         EmpathyChatSpell *chat_spell;
2107
2108         chat_spell = g_slice_new0 (EmpathyChatSpell);
2109
2110         chat_spell->chat = g_object_ref (chat);
2111         chat_spell->word = g_strdup (word);
2112         chat_spell->start = start;
2113         chat_spell->end = end;
2114
2115         return chat_spell;
2116 }
2117
2118 static void
2119 chat_spell_free (EmpathyChatSpell *chat_spell)
2120 {
2121         g_object_unref (chat_spell->chat);
2122         g_free (chat_spell->word);
2123         g_slice_free (EmpathyChatSpell, chat_spell);
2124 }
2125
2126 static void
2127 chat_spelling_menu_activate_cb (GtkMenuItem     *menu_item,
2128                                                 EmpathyChatSpell *chat_spell)
2129 {
2130     empathy_chat_correct_word (chat_spell->chat,
2131                                &(chat_spell->start),
2132                                &(chat_spell->end),
2133                                gtk_menu_item_get_label (menu_item));
2134 }
2135
2136
2137 static GtkWidget *
2138 chat_spelling_build_suggestions_menu (const gchar *code,
2139                                       EmpathyChatSpell *chat_spell)
2140 {
2141         GList     *suggestions, *l;
2142         GtkWidget *menu, *menu_item;
2143
2144         suggestions = empathy_spell_get_suggestions (code, chat_spell->word);
2145         if (suggestions == NULL)
2146                 return NULL;
2147
2148         menu = gtk_menu_new ();
2149         for (l = suggestions; l; l = l->next) {
2150                 menu_item = gtk_menu_item_new_with_label (l->data);
2151                 g_signal_connect (G_OBJECT (menu_item), "activate",
2152                                   G_CALLBACK (chat_spelling_menu_activate_cb),
2153                                   chat_spell);
2154                 gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
2155         }
2156         empathy_spell_free_suggestions (suggestions);
2157
2158         gtk_widget_show_all (menu);
2159
2160         return menu;
2161 }
2162
2163 static GtkWidget *
2164 chat_spelling_build_menu (EmpathyChatSpell *chat_spell)
2165 {
2166         GtkWidget *menu, *submenu, *item;
2167         GList     *codes, *l;
2168
2169         codes = empathy_spell_get_enabled_language_codes ();
2170         g_assert (codes != NULL);
2171
2172         if (g_list_length (codes) > 1) {
2173                 menu = gtk_menu_new ();
2174
2175                 for (l = codes; l; l = l->next) {
2176                         const gchar *code, *name;
2177
2178                         code = l->data;
2179                         name = empathy_spell_get_language_name (code);
2180                         if (!name)
2181                                 continue;
2182
2183                         item = gtk_image_menu_item_new_with_label (name);
2184
2185                         submenu = chat_spelling_build_suggestions_menu (
2186                                         code, chat_spell);
2187                         if (submenu == NULL)
2188                                 gtk_widget_set_sensitive (item, FALSE);
2189                         else
2190                                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item),
2191                                                            submenu);
2192                         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2193                 }
2194         } else {
2195                 menu = chat_spelling_build_suggestions_menu (codes->data,
2196                                                              chat_spell);
2197                 if (menu == NULL) {
2198                         menu = gtk_menu_new ();
2199                         item = gtk_menu_item_new_with_label (_("(No Suggestions)"));
2200                         gtk_widget_set_sensitive (item, FALSE);
2201                         gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
2202                 }
2203         }
2204         g_list_free (codes);
2205
2206         gtk_widget_show_all (menu);
2207
2208         return menu;
2209 }
2210
2211 typedef struct {
2212         EmpathyChat  *chat;
2213         gchar        *word;
2214         gchar        *code;
2215 } EmpathyChatWord;
2216
2217 static EmpathyChatWord *
2218 chat_word_new (EmpathyChat  *chat,
2219                 const gchar  *word,
2220                 const gchar  *code)
2221 {
2222         EmpathyChatWord *chat_word;
2223
2224         chat_word = g_slice_new0 (EmpathyChatWord);
2225
2226         chat_word->chat = g_object_ref (chat);
2227         chat_word->word = g_strdup (word);
2228         chat_word->code = g_strdup (code);
2229
2230         return chat_word;
2231 }
2232
2233 static void
2234 chat_word_free (EmpathyChatWord *chat_word)
2235 {
2236         g_object_unref (chat_word->chat);
2237         g_free (chat_word->word);
2238         g_free (chat_word->code);
2239         g_slice_free (EmpathyChatWord, chat_word);
2240 }
2241
2242 static void
2243 chat_add_to_dictionary_activate_cb (GtkMenuItem     *menu_item,
2244                                     EmpathyChatWord *chat_word)
2245 {
2246         EmpathyChatPriv *priv = GET_PRIV (chat_word->chat);
2247
2248         empathy_spell_add_to_dictionary (chat_word->code,
2249                                          chat_word->word);
2250         priv->update_misspelled_words_id =
2251                 g_idle_add (update_misspelled_words, chat_word->chat);
2252 }
2253
2254 static GtkWidget *
2255 chat_spelling_build_add_to_dictionary_item (EmpathyChatSpell *chat_spell)
2256 {
2257         GtkWidget       *menu, *item, *lang_item, *image;
2258         GList           *codes, *l;
2259         gchar           *label;
2260         const gchar     *code, *name;
2261         EmpathyChatWord *chat_word;
2262
2263         codes = empathy_spell_get_enabled_language_codes ();
2264         g_assert (codes != NULL);
2265         if (g_list_length (codes) > 1) {
2266                 /* translators: %s is the selected word */
2267                 label = g_strdup_printf (_("Add '%s' to Dictionary"),
2268                                         chat_spell->word);
2269                 item = gtk_image_menu_item_new_with_mnemonic (label);
2270                 g_free (label);
2271                 image = gtk_image_new_from_icon_name (GTK_STOCK_ADD,
2272                                                       GTK_ICON_SIZE_MENU);
2273                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item),
2274                                                image);
2275
2276                 menu = gtk_menu_new ();
2277
2278                 for (l = codes; l; l = l->next) {
2279                         code = l->data;
2280                         name = empathy_spell_get_language_name (code);
2281                         if (name == NULL)
2282                                 continue;
2283
2284                         lang_item = gtk_image_menu_item_new_with_label (name);
2285
2286                         chat_word= chat_word_new (chat_spell->chat,
2287                                                   chat_spell->word, code);
2288                         g_object_set_data_full (G_OBJECT (lang_item),
2289                                 "chat-word", chat_word,
2290                                 (GDestroyNotify) chat_word_free);
2291
2292                         g_signal_connect (G_OBJECT (lang_item), "activate",
2293                                 G_CALLBACK (chat_add_to_dictionary_activate_cb),
2294                                 chat_word);
2295                         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), lang_item);
2296                 }
2297                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), menu);
2298         } else {
2299                 code = codes->data;
2300                 name = empathy_spell_get_language_name (code);
2301                 g_assert (name != NULL);
2302                 /* translators: first %s is the selected word,
2303                  * second %s is the language name of the target dictionary */
2304                 label = g_strdup_printf (_("Add '%s' to %s Dictionary"),
2305                                         chat_spell->word, name);
2306                 item = gtk_image_menu_item_new_with_mnemonic (label);
2307                 g_free (label);
2308                 image = gtk_image_new_from_icon_name (GTK_STOCK_ADD,
2309                                                       GTK_ICON_SIZE_MENU);
2310                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2311
2312                 chat_word = chat_word_new (chat_spell->chat, chat_spell->word,
2313                                            code);
2314                 g_object_set_data_full (G_OBJECT (item), "chat-word", chat_word,
2315                                         (GDestroyNotify) chat_word_free);
2316
2317                 g_signal_connect (G_OBJECT (item), "activate",
2318                                   G_CALLBACK (chat_add_to_dictionary_activate_cb),
2319                                   chat_word);
2320         }
2321         g_list_free (codes);
2322
2323         gtk_widget_show_all (item);
2324
2325         return item;
2326 }
2327
2328 static void
2329 chat_text_send_cb (GtkMenuItem *menuitem,
2330                    EmpathyChat *chat)
2331 {
2332         chat_input_text_view_send (chat);
2333 }
2334
2335 static gboolean
2336 chat_input_button_press_event_cb (GtkTextView    *view,
2337                                   GdkEventButton *event,
2338                                   EmpathyChat    *chat)
2339 {
2340         EmpathyChatPriv *priv = GET_PRIV (chat);
2341
2342         priv->most_recent_event_type = event->type;
2343
2344         return FALSE;
2345 }
2346
2347 static void
2348 chat_input_populate_popup_cb (GtkTextView *view,
2349                               GtkMenu     *menu,
2350                               EmpathyChat *chat)
2351 {
2352         EmpathyChatPriv      *priv = GET_PRIV (chat);
2353         GtkTextBuffer        *buffer;
2354         GtkTextTagTable      *table;
2355         GtkTextTag           *tag;
2356         gint                  x, y;
2357         GtkTextIter           iter, start, end;
2358         GtkWidget            *item;
2359         gchar                *str = NULL;
2360         EmpathyChatSpell     *chat_spell;
2361         GtkWidget            *spell_menu;
2362         GtkWidget            *spell_item;
2363         EmpathySmileyManager *smiley_manager;
2364         GtkWidget            *smiley_menu;
2365         GtkWidget            *image;
2366
2367         buffer = gtk_text_view_get_buffer (view);
2368
2369         /* Add the emoticon menu. */
2370         item = gtk_separator_menu_item_new ();
2371         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2372         gtk_widget_show (item);
2373
2374         item = gtk_image_menu_item_new_with_mnemonic (_("Insert Smiley"));
2375         image = gtk_image_new_from_icon_name ("face-smile",
2376                                               GTK_ICON_SIZE_MENU);
2377         gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2378         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2379         gtk_widget_show (item);
2380
2381         smiley_manager = empathy_smiley_manager_dup_singleton ();
2382         smiley_menu = empathy_smiley_menu_new (smiley_manager,
2383                                                chat_insert_smiley_activate_cb,
2384                                                chat);
2385         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), smiley_menu);
2386         g_object_unref (smiley_manager);
2387
2388         /* Add the Send menu item. */
2389         gtk_text_buffer_get_bounds (buffer, &start, &end);
2390         str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
2391         if (!EMP_STR_EMPTY (str)) {
2392                 item = gtk_menu_item_new_with_mnemonic (_("_Send"));
2393                 g_signal_connect (G_OBJECT (item), "activate",
2394                                   G_CALLBACK (chat_text_send_cb), chat);
2395                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2396                 gtk_widget_show (item);
2397         }
2398         str = NULL;
2399
2400         /* Add the spell check menu item. */
2401         table = gtk_text_buffer_get_tag_table (buffer);
2402         tag = gtk_text_tag_table_lookup (table, "misspelled");
2403
2404         switch (priv->most_recent_event_type) {
2405             case GDK_BUTTON_PRESS:
2406                 /* get the location from the pointer */
2407                 gdk_window_get_device_position (gtk_widget_get_window (GTK_WIDGET (view)),
2408                         gdk_device_manager_get_client_pointer (gdk_display_get_device_manager (
2409                                 gtk_widget_get_display (GTK_WIDGET (view)))), &x, &y, NULL);
2410
2411                 gtk_text_view_window_to_buffer_coords (GTK_TEXT_VIEW (view),
2412                                                        GTK_TEXT_WINDOW_WIDGET,
2413                                                        x, y,
2414                                                        &x, &y);
2415                 gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW (view),
2416                                                     &iter, x, y);
2417                 break;
2418
2419             default:
2420                 g_warn_if_reached ();
2421                 /* assume the KEY_PRESS case */
2422
2423             case GDK_KEY_PRESS:
2424                 /* get the location from the cursor */
2425                 gtk_text_buffer_get_iter_at_mark (buffer, &iter,
2426                                 gtk_text_buffer_get_insert (buffer));
2427                 break;
2428
2429         }
2430
2431         start = end = iter;
2432         if (gtk_text_iter_backward_to_tag_toggle (&start, tag) &&
2433             gtk_text_iter_forward_to_tag_toggle (&end, tag)) {
2434
2435                 str = gtk_text_buffer_get_text (buffer,
2436                                                 &start, &end, FALSE);
2437         }
2438         if (!EMP_STR_EMPTY (str)) {
2439                 chat_spell = chat_spell_new (chat, str, start, end);
2440                 g_object_set_data_full (G_OBJECT (menu),
2441                                         "chat-spell", chat_spell,
2442                                         (GDestroyNotify) chat_spell_free);
2443
2444                 item = gtk_separator_menu_item_new ();
2445                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2446                 gtk_widget_show (item);
2447
2448                 /* Spelling suggestions */
2449                 item = gtk_image_menu_item_new_with_mnemonic (_("_Spelling Suggestions"));
2450                 image = gtk_image_new_from_icon_name (GTK_STOCK_SPELL_CHECK,
2451                                                       GTK_ICON_SIZE_MENU);
2452                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
2453
2454                 spell_menu = chat_spelling_build_menu (chat_spell);
2455                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), spell_menu);
2456
2457
2458                 spell_item = gtk_separator_menu_item_new ();
2459                 gtk_menu_shell_append (GTK_MENU_SHELL (spell_menu), spell_item);
2460                 gtk_widget_show (spell_item);
2461
2462                 /* Add to dictionary */
2463                 spell_item = chat_spelling_build_add_to_dictionary_item (chat_spell);
2464
2465                 gtk_menu_shell_append (GTK_MENU_SHELL (spell_menu), spell_item);
2466                 gtk_widget_show (spell_item);
2467
2468                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
2469                 gtk_widget_show (item);
2470         }
2471 }
2472
2473
2474 static gboolean
2475 chat_log_filter (TplEvent *event,
2476                  gpointer user_data)
2477 {
2478         EmpathyChat *chat = user_data;
2479         EmpathyMessage *message;
2480         EmpathyChatPriv *priv = GET_PRIV (chat);
2481         const GList *pending;
2482
2483         g_return_val_if_fail (TPL_IS_EVENT (event), FALSE);
2484         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
2485
2486         pending = empathy_tp_chat_get_pending_messages (priv->tp_chat);
2487         message = empathy_message_from_tpl_log_event (event);
2488
2489         for (; pending; pending = g_list_next (pending)) {
2490                 if (empathy_message_equal (message, pending->data)) {
2491                         g_object_unref (message);
2492                         return FALSE;
2493                 }
2494         }
2495
2496         g_object_unref (message);
2497         return TRUE;
2498 }
2499
2500
2501 static void
2502 show_pending_messages (EmpathyChat *chat) {
2503         EmpathyChatPriv *priv = GET_PRIV (chat);
2504         const GList *messages, *l;
2505
2506         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2507
2508         if (chat->view == NULL || priv->tp_chat == NULL)
2509                 return;
2510
2511         if (!priv->can_show_pending)
2512                 return;
2513
2514         messages = empathy_tp_chat_get_pending_messages (priv->tp_chat);
2515
2516         for (l = messages; l != NULL ; l = g_list_next (l)) {
2517                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
2518                 chat_message_received (chat, message, TRUE);
2519         }
2520 }
2521
2522
2523 static void
2524 got_filtered_messages_cb (GObject *manager,
2525                 GAsyncResult *result,
2526                 gpointer user_data)
2527 {
2528         GList *l;
2529         GList *messages;
2530         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2531         EmpathyChatPriv *priv = GET_PRIV (chat);
2532         GError *error = NULL;
2533
2534         if (!tpl_log_manager_get_filtered_events_finish (TPL_LOG_MANAGER (manager),
2535                 result, &messages, &error)) {
2536                 DEBUG ("%s. Aborting.", error->message);
2537                 empathy_chat_view_append_event (chat->view,
2538                         _("Failed to retrieve recent logs"));
2539                 g_error_free (error);
2540                 goto out;
2541         }
2542
2543         for (l = messages; l; l = g_list_next (l)) {
2544                 EmpathyMessage *message;
2545
2546                 g_assert (TPL_IS_EVENT (l->data));
2547
2548                 message = empathy_message_from_tpl_log_event (l->data);
2549                 g_object_unref (l->data);
2550
2551                 if (empathy_message_is_edit (message)) {
2552                         /* this is an edited message, create a synthetic event
2553                          * using the supersedes token and
2554                          * original-message-sent timestamp, that we can then
2555                          * replace */
2556                         EmpathyMessage *syn_msg = g_object_new (
2557                                 EMPATHY_TYPE_MESSAGE,
2558                                 "body", "",
2559                                 "token", empathy_message_get_supersedes (message),
2560                                 "type", empathy_message_get_tptype (message),
2561                                 "timestamp", empathy_message_get_original_timestamp (message),
2562                                 "incoming", empathy_message_is_incoming (message),
2563                                 "is-backlog", TRUE,
2564                                 "receiver", empathy_message_get_receiver (message),
2565                                 "sender", empathy_message_get_sender (message),
2566                                 NULL);
2567
2568                         empathy_chat_view_append_message (chat->view, syn_msg,
2569                                                           chat_should_highlight (chat, syn_msg));
2570                         empathy_chat_view_edit_message (chat->view, message);
2571
2572                         g_object_unref (syn_msg);
2573                 } else {
2574                         /* append the latest message */
2575                         empathy_chat_view_append_message (chat->view, message,
2576                                                           chat_should_highlight (chat, message));
2577                 }
2578
2579                 g_object_unref (message);
2580         }
2581         g_list_free (messages);
2582
2583 out:
2584         /* in case of TPL error, skip backlog and show pending messages */
2585         priv->can_show_pending = TRUE;
2586         show_pending_messages (chat);
2587
2588         /* FIXME: See Bug#610994, we are forcing the ACK of the queue. See comments
2589          * about it in EmpathyChatPriv definition */
2590         priv->retrieving_backlogs = FALSE;
2591         empathy_chat_messages_read (chat);
2592
2593         /* Turn back on scrolling */
2594         empathy_chat_view_scroll (chat->view, TRUE);
2595 }
2596
2597 static void
2598 chat_add_logs (EmpathyChat *chat)
2599 {
2600         EmpathyChatPriv *priv = GET_PRIV (chat);
2601         TplEntity       *target;
2602
2603         if (!priv->id) {
2604                 return;
2605         }
2606
2607         /* Turn off scrolling temporarily */
2608         empathy_chat_view_scroll (chat->view, FALSE);
2609
2610         /* Add messages from last conversation */
2611         if (priv->handle_type == TP_HANDLE_TYPE_ROOM)
2612           target = tpl_entity_new_from_room_id (priv->id);
2613         else
2614           target = tpl_entity_new (priv->id, TPL_ENTITY_CONTACT, NULL, NULL);
2615
2616         priv->retrieving_backlogs = TRUE;
2617         tpl_log_manager_get_filtered_events_async (priv->log_manager,
2618                                                    priv->account,
2619                                                    target,
2620                                                    TPL_EVENT_MASK_TEXT,
2621                                                    5,
2622                                                    chat_log_filter,
2623                                                    chat,
2624                                                    got_filtered_messages_cb,
2625                                                    (gpointer) chat);
2626
2627         g_object_unref (target);
2628 }
2629
2630 static gint
2631 chat_contacts_completion_func (const gchar *s1,
2632                                const gchar *s2,
2633                                gsize        n)
2634 {
2635         gchar *tmp, *nick1, *nick2;
2636         gint   ret;
2637
2638         if (s1 == s2) {
2639                 return 0;
2640         }
2641         if (!s1 || !s2) {
2642                 return s1 ? -1 : +1;
2643         }
2644
2645         tmp = g_utf8_normalize (s1, -1, G_NORMALIZE_DEFAULT);
2646         nick1 = g_utf8_casefold (tmp, -1);
2647         g_free (tmp);
2648
2649         tmp = g_utf8_normalize (s2, -1, G_NORMALIZE_DEFAULT);
2650         nick2 = g_utf8_casefold (tmp, -1);
2651         g_free (tmp);
2652
2653         ret = strncmp (nick1, nick2, n);
2654
2655         g_free (nick1);
2656         g_free (nick2);
2657
2658         return ret;
2659 }
2660
2661 static gchar *
2662 build_part_message (guint           reason,
2663                     const gchar    *name,
2664                     EmpathyContact *actor,
2665                     const gchar    *message)
2666 {
2667         GString *s = g_string_new ("");
2668         const gchar *actor_name = NULL;
2669
2670         if (actor != NULL) {
2671                 actor_name = empathy_contact_get_alias (actor);
2672         }
2673
2674         /* Having an actor only really makes sense for a few actions... */
2675         switch (reason) {
2676         case TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE:
2677                 g_string_append_printf (s, _("%s has disconnected"), name);
2678                 break;
2679         case TP_CHANNEL_GROUP_CHANGE_REASON_KICKED:
2680                 if (actor_name != NULL) {
2681                         /* translators: reverse the order of these arguments
2682                          * if the kicked should come before the kicker in your locale.
2683                          */
2684                         g_string_append_printf (s, _("%1$s was kicked by %2$s"),
2685                                 name, actor_name);
2686                 } else {
2687                         g_string_append_printf (s, _("%s was kicked"), name);
2688                 }
2689                 break;
2690         case TP_CHANNEL_GROUP_CHANGE_REASON_BANNED:
2691                 if (actor_name != NULL) {
2692                         /* translators: reverse the order of these arguments
2693                          * if the banned should come before the banner in your locale.
2694                          */
2695                         g_string_append_printf (s, _("%1$s was banned by %2$s"),
2696                                 name, actor_name);
2697                 } else {
2698                         g_string_append_printf (s, _("%s was banned"), name);
2699                 }
2700                 break;
2701         default:
2702                 g_string_append_printf (s, _("%s has left the room"), name);
2703         }
2704
2705         if (!EMP_STR_EMPTY (message)) {
2706                 /* Note to translators: this string is appended to
2707                  * notifications like "foo has left the room", with the message
2708                  * given by the user living the room. If this poses a problem,
2709                  * please let us know. :-)
2710                  */
2711                 g_string_append_printf (s, _(" (%s)"), message);
2712         }
2713
2714         return g_string_free (s, FALSE);
2715 }
2716
2717 static void
2718 chat_members_changed_cb (EmpathyTpChat  *tp_chat,
2719                          EmpathyContact *contact,
2720                          EmpathyContact *actor,
2721                          guint           reason,
2722                          gchar          *message,
2723                          gboolean        is_member,
2724                          EmpathyChat    *chat)
2725 {
2726         EmpathyChatPriv *priv = GET_PRIV (chat);
2727         const gchar *name = empathy_contact_get_alias (contact);
2728         gchar *str;
2729
2730         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED != reason);
2731
2732         if (priv->block_events_timeout_id != 0)
2733                 return;
2734
2735         if (is_member) {
2736                 str = g_strdup_printf (_("%s has joined the room"),
2737                                        name);
2738         } else {
2739                 str = build_part_message (reason, name, actor, message);
2740         }
2741
2742         empathy_chat_view_append_event (chat->view, str);
2743         g_free (str);
2744 }
2745
2746 static void
2747 chat_member_renamed_cb (EmpathyTpChat  *tp_chat,
2748                          EmpathyContact *old_contact,
2749                          EmpathyContact *new_contact,
2750                          guint           reason,
2751                          gchar          *message,
2752                          EmpathyChat    *chat)
2753 {
2754         EmpathyChatPriv *priv = GET_PRIV (chat);
2755
2756         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED == reason);
2757
2758         if (priv->block_events_timeout_id == 0) {
2759                 gchar *str;
2760
2761                 str = g_strdup_printf (_("%s is now known as %s"),
2762                                        empathy_contact_get_alias (old_contact),
2763                                        empathy_contact_get_alias (new_contact));
2764                 empathy_chat_view_append_event (chat->view, str);
2765                 g_free (str);
2766         }
2767
2768 }
2769
2770 static gboolean
2771 chat_contacts_visible_timeout_cb (gpointer chat)
2772 {
2773         EmpathyChatPriv *priv = GET_PRIV (chat);
2774
2775         /* Relax the size request */
2776         gtk_widget_set_size_request (priv->vbox_left, -1, -1);
2777
2778         /* Set the position of the slider. This must be done here because
2779          * GtkPaned need to know its size allocation and it will be settled only
2780          * after the gtk_window_resize () tough effect. */
2781         if (priv->contacts_width > 0) {
2782                 gtk_paned_set_position (GTK_PANED (priv->hpaned),
2783                                         priv->contacts_width);
2784         }
2785
2786         priv->contacts_visible_id = 0;
2787
2788         return FALSE;
2789 }
2790
2791 static void
2792 chat_update_contacts_visibility (EmpathyChat *chat,
2793                          gboolean show)
2794 {
2795         EmpathyChatPriv *priv = GET_PRIV (chat);
2796
2797         if (!priv->scrolled_window_contacts) {
2798                 return;
2799         }
2800
2801         if (priv->remote_contact != NULL) {
2802                 show = FALSE;
2803         }
2804
2805         if (show && priv->contact_list_view == NULL) {
2806                 EmpathyIndividualStore *store;
2807                 gint                     min_width;
2808                 GtkAllocation            allocation;
2809
2810                 /* We are adding the contact list to the chat, we don't want the
2811                  * chat view to become too small. If the chat view is already
2812                  * smaller than 250 make sure that size won't change. If the
2813                  * chat view is bigger the contact list will take some space on
2814                  * it but we make sure the chat view don't become smaller than
2815                  * 250. Relax the size request once the resize is done */
2816                 gtk_widget_get_allocation (priv->vbox_left, &allocation);
2817                 min_width = MIN (allocation.width, 250);
2818                 gtk_widget_set_size_request (priv->vbox_left, min_width, -1);
2819
2820                 /* There is no way to know when the window resize will happen
2821                  * since it is WM's decision. Let's hope it won't be longer. */
2822                 if (priv->contacts_visible_id != 0)
2823                         g_source_remove (priv->contacts_visible_id);
2824                 priv->contacts_visible_id = g_timeout_add (500,
2825                         chat_contacts_visible_timeout_cb, chat);
2826
2827                 store = EMPATHY_INDIVIDUAL_STORE (
2828                                 empathy_individual_store_channel_new ((TpChannel *) priv->tp_chat));
2829
2830                 empathy_individual_store_set_show_groups (store, FALSE);
2831
2832                 priv->contact_list_view = GTK_WIDGET (empathy_individual_view_new (store,
2833                         EMPATHY_INDIVIDUAL_VIEW_FEATURE_INDIVIDUAL_TOOLTIP,
2834                         EMPATHY_INDIVIDUAL_FEATURE_ADD_CONTACT |
2835                         EMPATHY_INDIVIDUAL_FEATURE_CHAT |
2836                         EMPATHY_INDIVIDUAL_FEATURE_CALL |
2837                         EMPATHY_INDIVIDUAL_FEATURE_LOG |
2838                         EMPATHY_INDIVIDUAL_FEATURE_INFO));
2839
2840                 empathy_individual_view_set_show_offline (
2841                         EMPATHY_INDIVIDUAL_VIEW (priv->contact_list_view), TRUE);
2842                 empathy_individual_view_set_show_uninteresting (
2843                         EMPATHY_INDIVIDUAL_VIEW (priv->contact_list_view), TRUE);
2844
2845                 gtk_container_add (GTK_CONTAINER (priv->scrolled_window_contacts),
2846                                    priv->contact_list_view);
2847
2848                 gtk_widget_show (priv->contact_list_view);
2849                 gtk_widget_show (priv->scrolled_window_contacts);
2850                 g_object_unref (store);
2851         } else if (!show) {
2852                 priv->contacts_width = gtk_paned_get_position (GTK_PANED (priv->hpaned));
2853                 gtk_widget_hide (priv->scrolled_window_contacts);
2854                 if (priv->contact_list_view != NULL) {
2855                         gtk_widget_destroy (priv->contact_list_view);
2856                         priv->contact_list_view = NULL;
2857                 }
2858         }
2859 }
2860
2861 void
2862 empathy_chat_set_show_contacts (EmpathyChat *chat,
2863                                 gboolean     show)
2864 {
2865         EmpathyChatPriv *priv = GET_PRIV (chat);
2866
2867         priv->show_contacts = show;
2868
2869         chat_update_contacts_visibility (chat, show);
2870
2871         g_object_notify (G_OBJECT (chat), "show-contacts");
2872 }
2873
2874 static void
2875 chat_remote_contact_changed_cb (EmpathyChat *chat)
2876 {
2877         EmpathyChatPriv *priv = GET_PRIV (chat);
2878
2879         if (priv->remote_contact != NULL) {
2880                 g_object_unref (priv->remote_contact);
2881                 priv->remote_contact = NULL;
2882         }
2883
2884         g_free (priv->id);
2885
2886         priv->id = g_strdup (empathy_tp_chat_get_id (priv->tp_chat));
2887         priv->remote_contact = empathy_tp_chat_get_remote_contact (priv->tp_chat);
2888         if (priv->remote_contact != NULL) {
2889                 g_object_ref (priv->remote_contact);
2890                 priv->handle_type = TP_HANDLE_TYPE_CONTACT;
2891         }
2892         else if (priv->tp_chat != NULL) {
2893                 tp_channel_get_handle ((TpChannel *) priv->tp_chat, &priv->handle_type);
2894         }
2895
2896         chat_update_contacts_visibility (chat, priv->show_contacts);
2897
2898         g_object_notify (G_OBJECT (chat), "remote-contact");
2899         g_object_notify (G_OBJECT (chat), "id");
2900 }
2901
2902 static void
2903 chat_invalidated_cb (EmpathyTpChat *tp_chat,
2904                  guint domain,
2905                  gint code,
2906                  gchar *message,
2907                  EmpathyChat   *chat)
2908 {
2909         EmpathyChatPriv *priv;
2910
2911         priv = GET_PRIV (chat);
2912
2913         if (!priv->tp_chat) {
2914                 return;
2915         }
2916
2917         chat_composing_remove_timeout (chat);
2918         g_object_unref (priv->tp_chat);
2919         priv->tp_chat = NULL;
2920         g_object_notify (G_OBJECT (chat), "tp-chat");
2921
2922         empathy_chat_view_append_event (chat->view, _("Disconnected"));
2923         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
2924
2925         chat_update_contacts_visibility (chat, FALSE);
2926
2927         priv->unread_messages_when_offline = priv->unread_messages;
2928 }
2929
2930 static gboolean
2931 update_misspelled_words (gpointer data)
2932 {
2933         EmpathyChat *chat = EMPATHY_CHAT (data);
2934         EmpathyChatPriv *priv = GET_PRIV (chat);
2935         GtkTextBuffer *buffer;
2936         GtkTextIter iter;
2937         gint length;
2938
2939         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2940
2941         gtk_text_buffer_get_end_iter (buffer, &iter);
2942         length = gtk_text_iter_get_offset (&iter);
2943         chat_input_text_buffer_insert_text_cb (buffer, &iter,
2944                                                NULL, length, chat);
2945
2946         priv->update_misspelled_words_id = 0;
2947
2948         return FALSE;
2949 }
2950
2951 static void
2952 conf_spell_checking_cb (GSettings *gsettings_chat,
2953                         const gchar *key,
2954                         gpointer user_data)
2955 {
2956         EmpathyChat *chat = EMPATHY_CHAT (user_data);
2957         EmpathyChatPriv *priv = GET_PRIV (chat);
2958         gboolean spell_checker;
2959         GtkTextBuffer *buffer;
2960
2961         if (strcmp (key, EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED) != 0)
2962                 return;
2963
2964         spell_checker = g_settings_get_boolean (gsettings_chat,
2965                         EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED);
2966
2967         if (!empathy_spell_supported ()) {
2968                 spell_checker = FALSE;
2969         }
2970
2971         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2972
2973         if (spell_checker == priv->spell_checking_enabled) {
2974                 if (spell_checker) {
2975                         /* Possibly changed dictionaries,
2976                          * update misspelled words. Need to do so in idle
2977                          * so the spell checker is updated. */
2978                         priv->update_misspelled_words_id =
2979                                 g_idle_add (update_misspelled_words, chat);
2980                 }
2981
2982                 return;
2983         }
2984
2985         if (spell_checker) {
2986                 GtkTextIter iter;
2987
2988                 priv->notify_cursor_position_id = tp_g_signal_connect_object  (
2989                                 buffer, "notify::cursor-position",
2990                                 G_CALLBACK (chat_input_text_buffer_notify_cursor_position_cb),
2991                                 chat, 0);
2992                 priv->insert_text_id = tp_g_signal_connect_object  (
2993                                 buffer, "insert-text",
2994                                 G_CALLBACK (chat_input_text_buffer_insert_text_cb),
2995                                 chat, G_CONNECT_AFTER);
2996                 priv->delete_range_id = tp_g_signal_connect_object  (
2997                                 buffer, "delete-range",
2998                                 G_CALLBACK (chat_input_text_buffer_delete_range_cb),
2999                                 chat, G_CONNECT_AFTER);
3000
3001                 gtk_text_buffer_create_tag (buffer, "misspelled",
3002                                             "underline", PANGO_UNDERLINE_ERROR,
3003                                             NULL);
3004
3005                 gtk_text_buffer_get_iter_at_mark (buffer, &iter,
3006                                                   gtk_text_buffer_get_insert (buffer));
3007                 gtk_text_buffer_create_mark (buffer, "previous-cursor-position",
3008                                              &iter, TRUE);
3009
3010                 /* Mark misspelled words in the existing buffer.
3011                  * Need to do so in idle so the spell checker is updated. */
3012                 priv->update_misspelled_words_id =
3013                         g_idle_add (update_misspelled_words, chat);
3014         } else {
3015                 GtkTextTagTable *table;
3016                 GtkTextTag *tag;
3017
3018                 g_signal_handler_disconnect (buffer, priv->notify_cursor_position_id);
3019                 priv->notify_cursor_position_id = 0;
3020                 g_signal_handler_disconnect (buffer, priv->insert_text_id);
3021                 priv->insert_text_id = 0;
3022                 g_signal_handler_disconnect (buffer, priv->delete_range_id);
3023                 priv->delete_range_id = 0;
3024
3025                 table = gtk_text_buffer_get_tag_table (buffer);
3026                 tag = gtk_text_tag_table_lookup (table, "misspelled");
3027                 gtk_text_tag_table_remove (table, tag);
3028
3029                 gtk_text_buffer_delete_mark_by_name (buffer,
3030                                                      "previous-cursor-position");
3031         }
3032
3033         priv->spell_checking_enabled = spell_checker;
3034 }
3035
3036 static gboolean
3037 save_paned_pos_timeout (gpointer data)
3038 {
3039         EmpathyChat *self = data;
3040         gint hpaned_pos;
3041
3042         hpaned_pos = gtk_paned_get_position (GTK_PANED (self->priv->hpaned));
3043
3044         g_settings_set_int (self->priv->gsettings_ui,
3045                             EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
3046                             hpaned_pos);
3047
3048         return FALSE;
3049 }
3050
3051 static gboolean
3052 chat_hpaned_pos_changed_cb (GtkWidget* hpaned,
3053                 GParamSpec *spec,
3054                 gpointer user_data)
3055 {
3056         EmpathyChat *chat = EMPATHY_CHAT (user_data);
3057
3058         if (chat->priv->save_paned_pos_id != 0)
3059                 g_source_remove (chat->priv->save_paned_pos_id);
3060
3061         chat->priv->save_paned_pos_id = g_timeout_add_seconds (1,
3062                 save_paned_pos_timeout, chat);
3063
3064         return TRUE;
3065 }
3066
3067 static void
3068 chat_create_ui (EmpathyChat *chat)
3069 {
3070         EmpathyChatPriv *priv = GET_PRIV (chat);
3071         GtkBuilder      *gui;
3072         GList           *list = NULL;
3073         gchar           *filename;
3074         GtkTextBuffer   *buffer;
3075         EmpathyThemeManager *theme_mgr;
3076
3077         filename = empathy_file_lookup ("empathy-chat.ui",
3078                                         "libempathy-gtk");
3079         gui = empathy_builder_get_file (filename,
3080                                         "chat_widget", &priv->widget,
3081                                         "hpaned", &priv->hpaned,
3082                                         "vbox_left", &priv->vbox_left,
3083                                         "scrolled_window_chat", &priv->scrolled_window_chat,
3084                                         "scrolled_window_input", &priv->scrolled_window_input,
3085                                         "hbox_topic", &priv->hbox_topic,
3086                                         "expander_topic", &priv->expander_topic,
3087                                         "label_topic", &priv->label_topic,
3088                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
3089                                         "info_bar_vbox", &priv->info_bar_vbox,
3090                                         NULL);
3091
3092         empathy_builder_connect (gui, chat,
3093                 "expander_topic", "notify::expanded", chat_topic_expander_activate_cb,
3094                 "label_topic", "size-allocate", chat_topic_label_size_allocate_cb,
3095                 NULL);
3096
3097         g_free (filename);
3098
3099         /* Add message view. */
3100         theme_mgr = empathy_theme_manager_dup_singleton ();
3101         chat->view = empathy_theme_manager_create_view (theme_mgr);
3102         g_object_unref (theme_mgr);
3103         /* If this is a GtkTextView, it's set as a drag destination for text/plain
3104            and other types, even though it's non-editable and doesn't accept any
3105            drags.  This steals drag motion for anything inside the scrollbars,
3106            making drag destinations on chat windows far less useful.
3107          */
3108         gtk_drag_dest_unset (GTK_WIDGET (chat->view));
3109         g_signal_connect (chat->view, "focus_in_event",
3110                           G_CALLBACK (chat_text_view_focus_in_event_cb),
3111                           chat);
3112         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
3113                            GTK_WIDGET (chat->view));
3114         gtk_widget_show (GTK_WIDGET (chat->view));
3115
3116         /* Add input GtkTextView */
3117         chat->input_text_view = empathy_input_text_view_new ();
3118         g_signal_connect (chat->input_text_view, "notify::has-focus",
3119                           G_CALLBACK (chat_input_has_focus_notify_cb),
3120                           chat);
3121         g_signal_connect (chat->input_text_view, "key-press-event",
3122                           G_CALLBACK (chat_input_key_press_event_cb),
3123                           chat);
3124         g_signal_connect (chat->input_text_view, "realize",
3125                           G_CALLBACK (chat_input_realize_cb),
3126                           chat);
3127         g_signal_connect (chat->input_text_view, "button-press-event",
3128                           G_CALLBACK (chat_input_button_press_event_cb),
3129                           chat);
3130         g_signal_connect (chat->input_text_view, "populate-popup",
3131                           G_CALLBACK (chat_input_populate_popup_cb),
3132                           chat);
3133         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3134         tp_g_signal_connect_object  (buffer, "changed",
3135                           G_CALLBACK (chat_input_text_buffer_changed_cb),
3136                           chat, 0);
3137         tp_g_signal_connect_object (priv->gsettings_chat,
3138                         "changed::" EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
3139                         G_CALLBACK (conf_spell_checking_cb), chat, 0);
3140         conf_spell_checking_cb (priv->gsettings_chat,
3141                                 EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED, chat);
3142         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
3143                            chat->input_text_view);
3144         gtk_widget_show (chat->input_text_view);
3145
3146         /* Add the (invisible) search bar */
3147         priv->search_bar = empathy_search_bar_new (chat->view);
3148         gtk_box_pack_start (GTK_BOX(priv->vbox_left),
3149                             priv->search_bar,
3150                             FALSE, FALSE, 0);
3151         gtk_box_reorder_child (GTK_BOX(priv->vbox_left), priv->search_bar, 1);
3152
3153         /* Initialy hide the topic, will be shown if not empty */
3154         gtk_widget_hide (priv->hbox_topic);
3155
3156         g_signal_connect (priv->hpaned, "notify::position",
3157                           G_CALLBACK (chat_hpaned_pos_changed_cb),
3158                           chat);
3159
3160         /* Set widget focus order */
3161         list = g_list_append (NULL, priv->search_bar);
3162         list = g_list_append (list, priv->scrolled_window_input);
3163         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
3164         g_list_free (list);
3165
3166         list = g_list_append (NULL, priv->vbox_left);
3167         list = g_list_append (list, priv->scrolled_window_contacts);
3168         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
3169         g_list_free (list);
3170
3171         list = g_list_append (NULL, priv->hpaned);
3172         list = g_list_append (list, priv->hbox_topic);
3173         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
3174         g_list_free (list);
3175
3176         /* Add the main widget in the chat widget */
3177         gtk_box_pack_start (GTK_BOX (chat), priv->widget, TRUE, TRUE, 0);
3178         g_object_unref (gui);
3179 }
3180
3181 static void
3182 chat_finalize (GObject *object)
3183 {
3184         EmpathyChat     *chat;
3185         EmpathyChatPriv *priv;
3186
3187         chat = EMPATHY_CHAT (object);
3188         priv = GET_PRIV (chat);
3189
3190         DEBUG ("Finalized: %p", object);
3191
3192         if (priv->update_misspelled_words_id != 0)
3193                 g_source_remove (priv->update_misspelled_words_id);
3194
3195         if (priv->save_paned_pos_id != 0)
3196                 g_source_remove (priv->save_paned_pos_id);
3197
3198         if (priv->contacts_visible_id != 0)
3199                 g_source_remove (priv->contacts_visible_id);
3200
3201         g_object_unref (priv->gsettings_chat);
3202         g_object_unref (priv->gsettings_ui);
3203
3204         g_list_foreach (priv->input_history, (GFunc) chat_input_history_entry_free, NULL);
3205         g_list_free (priv->input_history);
3206
3207         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
3208         g_list_free (priv->compositors);
3209
3210         chat_composing_remove_timeout (chat);
3211
3212         g_object_unref (priv->account_manager);
3213         g_object_unref (priv->log_manager);
3214
3215         if (priv->tp_chat) {
3216                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3217                         chat_invalidated_cb, chat);
3218                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3219                         chat_message_received_cb, chat);
3220                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3221                         chat_message_acknowledged_cb, chat);
3222                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3223                         chat_send_error_cb, chat);
3224                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3225                         chat_state_changed_cb, chat);
3226                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3227                         chat_members_changed_cb, chat);
3228                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3229                         chat_remote_contact_changed_cb, chat);
3230                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3231                         chat_title_changed_cb, chat);
3232                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
3233                         chat_subject_changed_cb, chat);
3234                 empathy_tp_chat_leave (priv->tp_chat, "");
3235                 g_object_unref (priv->tp_chat);
3236         }
3237         if (priv->account) {
3238                 g_object_unref (priv->account);
3239         }
3240         if (priv->remote_contact) {
3241                 g_object_unref (priv->remote_contact);
3242         }
3243
3244         if (priv->block_events_timeout_id) {
3245                 g_source_remove (priv->block_events_timeout_id);
3246         }
3247
3248         g_free (priv->id);
3249         g_free (priv->name);
3250         g_free (priv->subject);
3251         g_completion_free (priv->completion);
3252
3253         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
3254 }
3255
3256 static void
3257 chat_constructed (GObject *object)
3258 {
3259         EmpathyChat *chat = EMPATHY_CHAT (object);
3260         EmpathyChatPriv *priv = GET_PRIV (chat);
3261
3262         if (priv->handle_type != TP_HANDLE_TYPE_ROOM) {
3263                 /* First display logs from the logger and then display pending messages */
3264                 chat_add_logs (chat);
3265         }
3266          else {
3267                 /* Just display pending messages for rooms */
3268                 priv->can_show_pending = TRUE;
3269                 show_pending_messages (chat);
3270         }
3271 }
3272
3273 static void
3274 empathy_chat_class_init (EmpathyChatClass *klass)
3275 {
3276         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
3277
3278         object_class->finalize = chat_finalize;
3279         object_class->get_property = chat_get_property;
3280         object_class->set_property = chat_set_property;
3281         object_class->constructed = chat_constructed;
3282
3283         g_object_class_install_property (object_class,
3284                                          PROP_TP_CHAT,
3285                                          g_param_spec_object ("tp-chat",
3286                                                               "Empathy tp chat",
3287                                                               "The tp chat object",
3288                                                               EMPATHY_TYPE_TP_CHAT,
3289                                                               G_PARAM_CONSTRUCT |
3290                                                               G_PARAM_READWRITE |
3291                                                               G_PARAM_STATIC_STRINGS));
3292         g_object_class_install_property (object_class,
3293                                          PROP_ACCOUNT,
3294                                          g_param_spec_object ("account",
3295                                                               "Account of the chat",
3296                                                               "The account of the chat",
3297                                                               TP_TYPE_ACCOUNT,
3298                                                               G_PARAM_READABLE |
3299                                                               G_PARAM_STATIC_STRINGS));
3300         g_object_class_install_property (object_class,
3301                                          PROP_ID,
3302                                          g_param_spec_string ("id",
3303                                                               "Chat's id",
3304                                                               "The id of the chat",
3305                                                               NULL,
3306                                                               G_PARAM_READABLE |
3307                                                               G_PARAM_STATIC_STRINGS));
3308         g_object_class_install_property (object_class,
3309                                          PROP_NAME,
3310                                          g_param_spec_string ("name",
3311                                                               "Chat's name",
3312                                                               "The name of the chat",
3313                                                               NULL,
3314                                                               G_PARAM_READABLE |
3315                                                               G_PARAM_STATIC_STRINGS));
3316         g_object_class_install_property (object_class,
3317                                          PROP_SUBJECT,
3318                                          g_param_spec_string ("subject",
3319                                                               "Chat's subject",
3320                                                               "The subject or topic of the chat",
3321                                                               NULL,
3322                                                               G_PARAM_READABLE |
3323                                                               G_PARAM_STATIC_STRINGS));
3324         g_object_class_install_property (object_class,
3325                                          PROP_REMOTE_CONTACT,
3326                                          g_param_spec_object ("remote-contact",
3327                                                               "The remote contact",
3328                                                               "The remote contact is any",
3329                                                               EMPATHY_TYPE_CONTACT,
3330                                                               G_PARAM_READABLE |
3331                                                               G_PARAM_STATIC_STRINGS));
3332         g_object_class_install_property (object_class,
3333                                          PROP_SHOW_CONTACTS,
3334                                          g_param_spec_boolean ("show-contacts",
3335                                                                "Contacts' visibility",
3336                                                                "The visibility of the contacts' list",
3337                                                                TRUE,
3338                                                                G_PARAM_READWRITE |
3339                                                                G_PARAM_STATIC_STRINGS));
3340
3341         g_object_class_install_property (object_class,
3342                                          PROP_SMS_CHANNEL,
3343                                          g_param_spec_boolean ("sms-channel",
3344                                                                "SMS Channel",
3345                                                                "TRUE if this channel is for sending SMSes",
3346                                                                FALSE,
3347                                                                G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3348
3349         g_object_class_install_property (object_class,
3350                                          PROP_N_MESSAGES_SENDING,
3351                                          g_param_spec_uint ("n-messages-sending",
3352                                                             "Num Messages Sending",
3353                                                             "The number of messages being sent",
3354                                                             0, G_MAXUINT, 0,
3355                                                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3356
3357         g_object_class_install_property (object_class,
3358                                          PROP_NB_UNREAD_MESSAGES,
3359                                          g_param_spec_uint ("nb-unread-messages",
3360                                                             "Num Unread Messages",
3361                                                             "The number of unread messages",
3362                                                             0, G_MAXUINT, 0,
3363                                                             G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
3364
3365         signals[COMPOSING] =
3366                 g_signal_new ("composing",
3367                               G_OBJECT_CLASS_TYPE (object_class),
3368                               G_SIGNAL_RUN_LAST,
3369                               0,
3370                               NULL, NULL,
3371                               g_cclosure_marshal_generic,
3372                               G_TYPE_NONE,
3373                               1, G_TYPE_BOOLEAN);
3374
3375         /**
3376          * EmpathyChat::new-message:
3377          * @self: the #EmpathyChat
3378          * @message: the new message
3379          * @pending: whether the message was in the pending queue when @self
3380          *  was created
3381          * @should_highlight: %TRUE if the message mentions the local user
3382          */
3383         signals[NEW_MESSAGE] =
3384                 g_signal_new ("new-message",
3385                               G_OBJECT_CLASS_TYPE (object_class),
3386                               G_SIGNAL_RUN_LAST,
3387                               0,
3388                               NULL, NULL,
3389                               g_cclosure_marshal_generic,
3390                               G_TYPE_NONE,
3391                               3, EMPATHY_TYPE_MESSAGE, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN);
3392
3393         signals[PART_COMMAND_ENTERED] =
3394                         g_signal_new ("part-command-entered",
3395                                   G_OBJECT_CLASS_TYPE (object_class),
3396                                   G_SIGNAL_RUN_LAST,
3397                                   0,
3398                                   NULL, NULL,
3399                                   g_cclosure_marshal_generic,
3400                                   G_TYPE_NONE,
3401                                   1, G_TYPE_STRV);
3402
3403         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
3404 }
3405
3406 static gboolean
3407 chat_block_events_timeout_cb (gpointer data)
3408 {
3409         EmpathyChatPriv *priv = GET_PRIV (data);
3410
3411         priv->block_events_timeout_id = 0;
3412
3413         return FALSE;
3414 }
3415
3416 static void
3417 account_manager_prepared_cb (GObject *source_object,
3418                              GAsyncResult *result,
3419                              gpointer user_data)
3420 {
3421         GList *accounts, *l;
3422         TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
3423         EmpathyChat *chat = user_data;
3424         GError *error = NULL;
3425
3426         if (!tp_proxy_prepare_finish (account_manager, result, &error)) {
3427                 DEBUG ("Failed to prepare the account manager: %s", error->message);
3428                 g_error_free (error);
3429                 return;
3430         }
3431
3432         accounts = tp_account_manager_get_valid_accounts (account_manager);
3433
3434         for (l = accounts; l != NULL; l = l->next) {
3435                 TpAccount *account = l->data;
3436                 tp_g_signal_connect_object (account, "status-changed",
3437                                              G_CALLBACK (chat_new_connection_cb),
3438                                              chat, 0);
3439         }
3440
3441         g_list_free (accounts);
3442 }
3443
3444 static void
3445 empathy_chat_init (EmpathyChat *chat)
3446 {
3447         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
3448                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
3449
3450         chat->priv = priv;
3451         priv->log_manager = tpl_log_manager_dup_singleton ();
3452         priv->gsettings_chat = g_settings_new (EMPATHY_PREFS_CHAT_SCHEMA);
3453         priv->gsettings_ui = g_settings_new (EMPATHY_PREFS_UI_SCHEMA);
3454
3455         priv->contacts_width = g_settings_get_int (priv->gsettings_ui,
3456                 EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS);
3457         priv->input_history = NULL;
3458         priv->input_history_current = NULL;
3459         priv->account_manager = tp_account_manager_dup ();
3460
3461         tp_proxy_prepare_async (priv->account_manager, NULL,
3462                                           account_manager_prepared_cb, chat);
3463
3464         priv->show_contacts = g_settings_get_boolean (priv->gsettings_chat,
3465                         EMPATHY_PREFS_CHAT_SHOW_CONTACTS_IN_ROOMS);
3466
3467         /* Block events for some time to avoid having "has come online" or
3468          * "joined" messages. */
3469         priv->block_events_timeout_id =
3470                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
3471
3472         /* Add nick name completion */
3473         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_alias);
3474         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
3475
3476         chat_create_ui (chat);
3477 }
3478
3479 EmpathyChat *
3480 empathy_chat_new (EmpathyTpChat *tp_chat)
3481 {
3482         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
3483 }
3484
3485 EmpathyTpChat *
3486 empathy_chat_get_tp_chat (EmpathyChat *chat)
3487 {
3488         EmpathyChatPriv *priv = GET_PRIV (chat);
3489
3490         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3491
3492         return priv->tp_chat;
3493 }
3494
3495 typedef struct
3496 {
3497         EmpathyChat *self;
3498         GtkWidget *info_bar;
3499         gulong response_id;
3500         GtkWidget *button;
3501         GtkWidget *label;
3502         GtkWidget *entry;
3503         GtkWidget *spinner;
3504         gchar *password;
3505 } PasswordData;
3506
3507 static void
3508 passwd_remember_button_cb (GtkButton *button,
3509                           PasswordData *data)
3510 {
3511         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3512 }
3513
3514 static void
3515 passwd_not_now_button_cb (GtkButton *button,
3516                           PasswordData *data)
3517 {
3518         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_NO);
3519 }
3520
3521 static void
3522 remember_password_infobar_response_cb (GtkWidget *info_bar,
3523                                        gint response_id,
3524                                        PasswordData *data)
3525 {
3526         EmpathyChatPriv *priv = GET_PRIV (data->self);
3527
3528         if (response_id == GTK_RESPONSE_OK) {
3529                 DEBUG ("Saving room password");
3530                 empathy_keyring_set_room_password_async (priv->account,
3531                                                          empathy_tp_chat_get_id (priv->tp_chat),
3532                                                          data->password,
3533                                                          NULL, NULL);
3534         }
3535
3536         gtk_widget_destroy (info_bar);
3537         g_free (data->password);
3538         g_slice_free (PasswordData, data);
3539 }
3540
3541 static void
3542 chat_prompt_to_save_password (EmpathyChat *self,
3543                               PasswordData *data)
3544 {
3545         GtkWidget *content_area;
3546         GtkWidget *hbox;
3547         GtkWidget *image;
3548         GtkWidget *label;
3549         GtkWidget *alig;
3550         GtkWidget *button;
3551
3552         /* save the password in case it needs to be saved */
3553         data->password = g_strdup (gtk_entry_get_text (GTK_ENTRY (data->entry)));
3554
3555         /* Remove all previous widgets */
3556         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (data->info_bar));
3557         gtk_container_forall (GTK_CONTAINER (content_area),
3558                               (GtkCallback) gtk_widget_destroy, NULL);
3559         data->button = NULL;
3560         data->label = NULL;
3561         data->entry = NULL;
3562         data->spinner = NULL;
3563
3564         gtk_info_bar_set_message_type (GTK_INFO_BAR (data->info_bar),
3565                                        GTK_MESSAGE_QUESTION);
3566
3567         hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 5);
3568         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3569
3570         /* Add image */
3571         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3572                                           GTK_ICON_SIZE_DIALOG);
3573         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3574
3575         /* Add message */
3576         label = gtk_label_new (_("Would you like to store this password?"));
3577         gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0);
3578
3579         /* Add 'Remember' button */
3580         alig = gtk_alignment_new (0, 0.5, 1, 0);
3581
3582         button = gtk_button_new_with_label (_("Remember"));
3583         gtk_container_add (GTK_CONTAINER (alig), button);
3584         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3585
3586         g_signal_connect (button, "clicked", G_CALLBACK (passwd_remember_button_cb),
3587                           data);
3588
3589         /* Add 'Not now' button */
3590         alig = gtk_alignment_new (0, 0.5, 1, 0);
3591
3592         button = gtk_button_new_with_label (_("Not now"));
3593         gtk_container_add (GTK_CONTAINER (alig), button);
3594         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3595
3596         g_signal_connect (button, "clicked", G_CALLBACK (passwd_not_now_button_cb),
3597                           data);
3598
3599         /* go! */
3600         g_signal_handler_disconnect (data->info_bar, data->response_id);
3601         g_signal_connect (data->info_bar, "response",
3602                           G_CALLBACK (remember_password_infobar_response_cb), data);
3603
3604         gtk_widget_show_all (data->info_bar);
3605 }
3606
3607 static void
3608 provide_password_cb (GObject *tp_chat,
3609                      GAsyncResult *res,
3610                      gpointer user_data)
3611 {
3612         PasswordData *data = user_data;
3613         EmpathyChat *self = data->self;
3614         EmpathyChatPriv *priv = GET_PRIV (self);
3615         GError *error = NULL;
3616
3617         if (!tp_channel_provide_password_finish (TP_CHANNEL (tp_chat), res,
3618                                                       &error)) {
3619                 DEBUG ("error: %s", error->message);
3620                 /* FIXME: what should we do if that's another error? Close the channel?
3621                  * Display the raw D-Bus error to the user isn't very useful */
3622                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED)) {
3623                         /* entry */
3624                         gtk_entry_set_text (GTK_ENTRY (data->entry), "");
3625                         gtk_widget_set_sensitive (data->entry, TRUE);
3626                         gtk_widget_grab_focus (data->entry);
3627
3628                         /* info bar */
3629                         gtk_info_bar_set_message_type (
3630                             GTK_INFO_BAR (data->info_bar),
3631                             GTK_MESSAGE_ERROR);
3632
3633                         /* button */
3634                         gtk_widget_set_sensitive (data->button, TRUE);
3635                         gtk_button_set_label (GTK_BUTTON (data->button),
3636                             _("Retry"));
3637
3638                         /* label */
3639                         gtk_label_set_text (GTK_LABEL (data->label),
3640                             _("Wrong password; please try again:"));
3641
3642                         /* spinner */
3643                         gtk_spinner_stop (GTK_SPINNER (data->spinner));
3644                         gtk_widget_hide (data->spinner);
3645                 }
3646                 g_error_free (error);
3647                 return;
3648         }
3649
3650         if (empathy_keyring_is_available ()) {
3651                 /* ask whether they want to save the password */
3652                 chat_prompt_to_save_password (self, data);
3653         } else {
3654                 /* Get rid of the password info bar finally */
3655                 gtk_widget_destroy (data->info_bar);
3656                 g_slice_free (PasswordData, data);
3657         }
3658
3659         /* Room joined */
3660         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3661         gtk_widget_set_sensitive (self->input_text_view, TRUE);
3662         gtk_widget_grab_focus (self->input_text_view);
3663 }
3664
3665 static void
3666 password_infobar_response_cb (GtkWidget *info_bar,
3667                               gint response_id,
3668                               PasswordData *data)
3669 {
3670         EmpathyChatPriv *priv = GET_PRIV (data->self);
3671         const gchar *password;
3672
3673         if (response_id != GTK_RESPONSE_OK) {
3674                 gtk_widget_destroy (info_bar);
3675                 g_slice_free (PasswordData, data);
3676                 return;
3677         }
3678
3679         password = gtk_entry_get_text (GTK_ENTRY (data->entry));
3680
3681         tp_channel_provide_password_async (TP_CHANNEL (priv->tp_chat), password,
3682                                                 provide_password_cb, data);
3683
3684         gtk_widget_set_sensitive (data->button, FALSE);
3685         gtk_widget_set_sensitive (data->entry, FALSE);
3686
3687         gtk_spinner_start (GTK_SPINNER (data->spinner));
3688         gtk_widget_show (data->spinner);
3689 }
3690
3691 static void
3692 password_entry_activate_cb (GtkWidget *entry,
3693                           PasswordData *data)
3694 {
3695         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3696 }
3697
3698 static void
3699 passwd_join_button_cb (GtkButton *button,
3700                           PasswordData *data)
3701 {
3702         gtk_info_bar_response (GTK_INFO_BAR (data->info_bar), GTK_RESPONSE_OK);
3703 }
3704
3705 static void
3706 clear_icon_released_cb (GtkEntry *entry,
3707                         GtkEntryIconPosition icon_pos,
3708                         GdkEvent *event,
3709                         PasswordData *data)
3710 {
3711         gtk_entry_set_text (entry, "");
3712 }
3713
3714 static void
3715 password_entry_changed_cb (GtkEditable *entry,
3716                            PasswordData *data)
3717 {
3718         const gchar *str;
3719
3720         str = gtk_entry_get_text (GTK_ENTRY (entry));
3721
3722         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3723             GTK_ENTRY_ICON_SECONDARY, !EMP_STR_EMPTY (str));
3724 }
3725
3726 static void
3727 infobar_chat_invalidated_cb (TpProxy       *proxy,
3728                            guint          domain,
3729                            gint           code,
3730                            gchar         *message,
3731                            gpointer       password_infobar)
3732 {
3733         /* Destroy the password infobar whenever a channel is invalidated
3734          * so we don't have multiple infobars when the MUC is rejoined */
3735         gtk_widget_destroy (GTK_WIDGET (password_infobar));
3736 }
3737
3738 static void
3739 display_password_info_bar (EmpathyChat *self)
3740 {
3741         EmpathyChatPriv *priv = GET_PRIV (self);
3742         GtkWidget *info_bar;
3743         GtkWidget *content_area;
3744         GtkWidget *hbox;
3745         GtkWidget *image;
3746         GtkWidget *label;
3747         GtkWidget *entry;
3748         GtkWidget *alig;
3749         GtkWidget *button;
3750         GtkWidget *spinner;
3751         PasswordData *data;
3752
3753         data = g_slice_new0 (PasswordData);
3754
3755         info_bar = gtk_info_bar_new ();
3756         gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar),
3757             GTK_MESSAGE_QUESTION);
3758
3759         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar));
3760
3761         hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 5);
3762         gtk_box_pack_start (GTK_BOX (content_area), hbox, TRUE, TRUE, 0);
3763
3764         /* Add image */
3765         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
3766                                           GTK_ICON_SIZE_DIALOG);
3767         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
3768
3769         /* Add message */
3770         label = gtk_label_new (_("This room is protected by a password:"));
3771         gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
3772
3773         /* Add password entry */
3774         entry = gtk_entry_new ();
3775         gtk_entry_set_visibility (GTK_ENTRY (entry), FALSE);
3776         gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
3777
3778         gtk_entry_set_icon_from_stock (GTK_ENTRY (entry),
3779                                        GTK_ENTRY_ICON_SECONDARY, GTK_STOCK_CLEAR);
3780         gtk_entry_set_icon_sensitive (GTK_ENTRY (entry),
3781                                       GTK_ENTRY_ICON_SECONDARY, FALSE);
3782
3783         g_signal_connect (entry, "icon-release",
3784                           G_CALLBACK (clear_icon_released_cb), data);
3785         g_signal_connect (entry, "changed",
3786                           G_CALLBACK (password_entry_changed_cb), data);
3787
3788         g_signal_connect (entry, "activate",
3789                           G_CALLBACK (password_entry_activate_cb), data);
3790
3791         /* Focus the password entry once it's realized */
3792         g_signal_connect (entry, "realize", G_CALLBACK (gtk_widget_grab_focus), NULL);
3793
3794         /* Add 'Join' button */
3795         alig = gtk_alignment_new (0, 0.5, 1, 0);
3796
3797         button = gtk_button_new_with_label (_("Join"));
3798         gtk_container_add (GTK_CONTAINER (alig), button);
3799         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
3800
3801         g_signal_connect (button, "clicked", G_CALLBACK (passwd_join_button_cb),
3802                           data);
3803
3804         /* Add spinner */
3805         spinner = gtk_spinner_new ();
3806         gtk_box_pack_end (GTK_BOX (hbox), spinner, FALSE, FALSE, 0);
3807
3808         /* Save some data for messing around with later */
3809         data->self = self;
3810         data->info_bar = info_bar;
3811         data->button = button;
3812         data->label = label;
3813         data->entry = entry;
3814         data->spinner = spinner;
3815
3816         gtk_box_pack_start (GTK_BOX (priv->info_bar_vbox), info_bar,
3817                             TRUE, TRUE, 3);
3818         gtk_widget_show_all (hbox);
3819
3820         tp_g_signal_connect_object (priv->tp_chat,
3821                                   "invalidated", G_CALLBACK (infobar_chat_invalidated_cb),
3822                                   info_bar, 0);
3823
3824         data->response_id = g_signal_connect (info_bar, "response",
3825                                               G_CALLBACK (password_infobar_response_cb), data);
3826
3827         gtk_widget_show_all (info_bar);
3828         /* ... but hide the spinner */
3829         gtk_widget_hide (spinner);
3830
3831         /* prevent the user from typing anything */
3832         gtk_widget_set_sensitive (self->input_text_view, FALSE);
3833 }
3834
3835 static void
3836 provide_saved_password_cb (GObject *tp_chat,
3837                            GAsyncResult *res,
3838                            gpointer user_data)
3839 {
3840         EmpathyChat *self = user_data;
3841         EmpathyChatPriv *priv = GET_PRIV (self);
3842         GError *error = NULL;
3843
3844         if (!tp_channel_provide_password_finish (TP_CHANNEL (tp_chat), res,
3845                                                       &error)) {
3846                 DEBUG ("error: %s", error->message);
3847                 /* FIXME: what should we do if that's another error? Close the channel?
3848                  * Display the raw D-Bus error to the user isn't very useful */
3849                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED)) {
3850                         display_password_info_bar (self);
3851                         gtk_widget_set_sensitive (priv->hpaned, FALSE);
3852                 }
3853                 g_error_free (error);
3854                 return;
3855         }
3856
3857         /* Room joined */
3858         gtk_widget_set_sensitive (priv->hpaned, TRUE);
3859         gtk_widget_grab_focus (self->input_text_view);
3860 }
3861
3862 static void
3863 chat_room_got_password_cb (GObject *source,
3864                            GAsyncResult *result,
3865                            gpointer user_data)
3866 {
3867         EmpathyChat *self = user_data;
3868         EmpathyChatPriv *priv = GET_PRIV (self);
3869         const gchar *password;
3870         GError *error = NULL;
3871
3872         password = empathy_keyring_get_room_password_finish (priv->account,
3873             result, &error);
3874
3875         if (error != NULL) {
3876                 DEBUG ("Couldn't get room password: %s\n", error->message);
3877                 g_clear_error (&error);
3878
3879                 display_password_info_bar (self);
3880                 gtk_widget_set_sensitive (priv->hpaned, FALSE);
3881                 return;
3882         }
3883
3884         tp_channel_provide_password_async (TP_CHANNEL (priv->tp_chat), password,
3885                                                 provide_saved_password_cb, self);
3886 }
3887
3888 static void
3889 chat_password_needed_changed_cb (EmpathyChat *self)
3890 {
3891         EmpathyChatPriv *priv = GET_PRIV (self);
3892
3893         if (tp_channel_password_needed (TP_CHANNEL (priv->tp_chat))) {
3894                 empathy_keyring_get_room_password_async (priv->account,
3895                                                          empathy_tp_chat_get_id (priv->tp_chat),
3896                                                          chat_room_got_password_cb, self);
3897         }
3898 }
3899
3900 static void
3901 chat_sms_channel_changed_cb (EmpathyChat *self)
3902 {
3903         EmpathyChatPriv *priv = GET_PRIV (self);
3904
3905         priv->sms_channel = tp_text_channel_is_sms_channel (
3906                 (TpTextChannel *) priv->tp_chat);
3907         g_object_notify (G_OBJECT (self), "sms-channel");
3908 }
3909
3910 static void
3911 chat_n_messages_sending_changed_cb (EmpathyChat *self)
3912 {
3913         g_object_notify (G_OBJECT (self), "n-messages-sending");
3914 }
3915
3916 void
3917 empathy_chat_set_tp_chat (EmpathyChat   *chat,
3918                           EmpathyTpChat *tp_chat)
3919 {
3920         EmpathyChatPriv *priv = GET_PRIV (chat);
3921
3922         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3923         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
3924
3925         if (priv->tp_chat) {
3926                 return;
3927         }
3928
3929         if (priv->account) {
3930                 g_object_unref (priv->account);
3931         }
3932
3933         priv->tp_chat = g_object_ref (tp_chat);
3934         priv->account = g_object_ref (empathy_tp_chat_get_account (priv->tp_chat));
3935
3936         g_signal_connect (tp_chat, "invalidated",
3937                           G_CALLBACK (chat_invalidated_cb),
3938                           chat);
3939         g_signal_connect (tp_chat, "message-received-empathy",
3940                           G_CALLBACK (chat_message_received_cb),
3941                           chat);
3942         g_signal_connect (tp_chat, "message_acknowledged",
3943                           G_CALLBACK (chat_message_acknowledged_cb),
3944                           chat);
3945         g_signal_connect (tp_chat, "send-error",
3946                           G_CALLBACK (chat_send_error_cb),
3947                           chat);
3948         g_signal_connect (tp_chat, "chat-state-changed-empathy",
3949                           G_CALLBACK (chat_state_changed_cb),
3950                           chat);
3951         g_signal_connect (tp_chat, "members-changed",
3952                           G_CALLBACK (chat_members_changed_cb),
3953                           chat);
3954         g_signal_connect (tp_chat, "member-renamed",
3955                           G_CALLBACK (chat_member_renamed_cb),
3956                           chat);
3957         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
3958                                   G_CALLBACK (chat_remote_contact_changed_cb),
3959                                   chat);
3960         g_signal_connect_swapped (tp_chat, "notify::password-needed",
3961                                   G_CALLBACK (chat_password_needed_changed_cb),
3962                                   chat);
3963         g_signal_connect_swapped (tp_chat, "notify::is-sms-channel",
3964                                   G_CALLBACK (chat_sms_channel_changed_cb),
3965                                   chat);
3966         g_signal_connect_swapped (tp_chat, "notify::n-messages-sending",
3967                                   G_CALLBACK (chat_n_messages_sending_changed_cb),
3968                                   chat);
3969         g_signal_connect_swapped (tp_chat, "notify::title",
3970                                   G_CALLBACK (chat_title_changed_cb),
3971                                   chat);
3972         g_signal_connect_swapped (tp_chat, "notify::subject",
3973                                   G_CALLBACK (chat_subject_changed_cb),
3974                                   chat);
3975
3976         /* Get initial value of properties */
3977         chat_sms_channel_changed_cb (chat);
3978         chat_remote_contact_changed_cb (chat);
3979         chat_title_changed_cb (chat);
3980         chat_subject_changed_cb (chat);
3981
3982         if (chat->input_text_view) {
3983                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
3984                 if (priv->block_events_timeout_id == 0) {
3985                         empathy_chat_view_append_event (chat->view, _("Connected"));
3986                 }
3987         }
3988
3989         g_object_notify (G_OBJECT (chat), "tp-chat");
3990         g_object_notify (G_OBJECT (chat), "id");
3991         g_object_notify (G_OBJECT (chat), "account");
3992
3993         /* This is a noop when tp-chat is set at object construction time and causes
3994          * the pending messages to be show when it's set on the object after it has
3995          * been created */
3996         show_pending_messages (chat);
3997
3998         /* check if a password is needed */
3999         chat_password_needed_changed_cb (chat);
4000 }
4001
4002 TpAccount *
4003 empathy_chat_get_account (EmpathyChat *chat)
4004 {
4005         EmpathyChatPriv *priv = GET_PRIV (chat);
4006
4007         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
4008
4009         return priv->account;
4010 }
4011
4012 const gchar *
4013 empathy_chat_get_id (EmpathyChat *chat)
4014 {
4015         EmpathyChatPriv *priv = GET_PRIV (chat);
4016
4017         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
4018
4019         return priv->id;
4020 }
4021
4022 gchar *
4023 empathy_chat_dup_name (EmpathyChat *chat)
4024 {
4025         EmpathyChatPriv *priv = GET_PRIV (chat);
4026         const gchar *ret;
4027
4028         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
4029
4030         ret = priv->name;
4031
4032         if (!ret && priv->remote_contact) {
4033                 ret = empathy_contact_get_alias (priv->remote_contact);
4034         }
4035
4036         if (!ret)
4037                 ret = priv->id;
4038
4039         if (!ret)
4040                 ret = _("Conversation");
4041
4042         if (priv->sms_channel)
4043                 /* Translators: this string is a something like
4044                  * "Escher Cat (SMS)" */
4045                 return g_strdup_printf (_("%s (SMS)"), ret);
4046         else
4047                 return g_strdup (ret);
4048 }
4049
4050 const gchar *
4051 empathy_chat_get_subject (EmpathyChat *chat)
4052 {
4053         EmpathyChatPriv *priv = GET_PRIV (chat);
4054
4055         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
4056
4057         return priv->subject;
4058 }
4059
4060 EmpathyContact *
4061 empathy_chat_get_remote_contact (EmpathyChat *chat)
4062 {
4063         EmpathyChatPriv *priv = GET_PRIV (chat);
4064
4065         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
4066
4067         return priv->remote_contact;
4068 }
4069
4070 GtkWidget *
4071 empathy_chat_get_contact_menu (EmpathyChat *chat)
4072 {
4073         EmpathyChatPriv *priv = GET_PRIV (chat);
4074         GtkWidget       *menu = NULL;
4075         FolksIndividual *individual;
4076         TpContact *contact;
4077
4078         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
4079
4080         if (priv->remote_contact == NULL)
4081                 return NULL;
4082
4083         contact = empathy_contact_get_tp_contact (priv->remote_contact);
4084         if (contact == NULL)
4085                 return NULL;
4086
4087         individual = empathy_create_individual_from_tp_contact (contact);
4088         if (individual == NULL)
4089                 return NULL;
4090
4091         menu = empathy_individual_menu_new (individual,
4092                                          EMPATHY_INDIVIDUAL_FEATURE_CALL |
4093                                          EMPATHY_INDIVIDUAL_FEATURE_LOG |
4094                                          EMPATHY_INDIVIDUAL_FEATURE_INFO |
4095                                          EMPATHY_INDIVIDUAL_FEATURE_BLOCK, NULL);
4096
4097         g_object_unref (individual);
4098
4099         return menu;
4100 }
4101
4102 void
4103 empathy_chat_clear (EmpathyChat *chat)
4104 {
4105         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4106
4107         empathy_chat_view_clear (chat->view);
4108 }
4109
4110 void
4111 empathy_chat_scroll_down (EmpathyChat *chat)
4112 {
4113         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4114
4115         empathy_chat_view_scroll_down (chat->view);
4116 }
4117
4118 void
4119 empathy_chat_cut (EmpathyChat *chat)
4120 {
4121         GtkTextBuffer *buffer;
4122
4123         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4124
4125         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
4126         if (gtk_text_buffer_get_has_selection (buffer)) {
4127                 GtkClipboard *clipboard;
4128
4129                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
4130
4131                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
4132         }
4133 }
4134
4135 void
4136 empathy_chat_copy (EmpathyChat *chat)
4137 {
4138         GtkTextBuffer *buffer;
4139
4140         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4141
4142         if (empathy_chat_view_get_has_selection (chat->view)) {
4143                 empathy_chat_view_copy_clipboard (chat->view);
4144                 return;
4145         }
4146
4147         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
4148         if (gtk_text_buffer_get_has_selection (buffer)) {
4149                 GtkClipboard *clipboard;
4150
4151                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
4152
4153                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
4154         }
4155         else {
4156                 gint start_offset;
4157                 gint end_offset;
4158                 EmpathyChatPriv *priv = GET_PRIV (chat);
4159
4160                 if (gtk_label_get_selection_bounds (GTK_LABEL (priv->label_topic),
4161                                                                &start_offset,
4162                                                                &end_offset)) {
4163                         gchar *start;
4164                         gchar *end;
4165                         gchar *selection;
4166                         const gchar *topic;
4167                         GtkClipboard *clipboard;
4168
4169                         topic = gtk_label_get_text (GTK_LABEL (priv->label_topic));
4170                         start = g_utf8_offset_to_pointer (topic, start_offset);
4171                         end = g_utf8_offset_to_pointer (topic, end_offset);
4172                         selection = g_strndup (start, end - start);
4173
4174                         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
4175                         gtk_clipboard_set_text (clipboard, selection, -1);
4176
4177                         g_free (selection);
4178                 }
4179         }
4180 }
4181
4182 void
4183 empathy_chat_paste (EmpathyChat *chat)
4184 {
4185         GtkTextBuffer *buffer;
4186         GtkClipboard  *clipboard;
4187         EmpathyChatPriv *priv;
4188
4189         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4190
4191         priv = GET_PRIV (chat);
4192
4193         if (gtk_widget_get_visible (priv->search_bar)) {
4194                 empathy_search_bar_paste_clipboard (EMPATHY_SEARCH_BAR (priv->search_bar));
4195                 return;
4196         }
4197
4198         if (priv->tp_chat == NULL ||
4199             !gtk_widget_is_sensitive (chat->input_text_view))
4200                 return;
4201
4202         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
4203         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
4204
4205         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
4206 }
4207
4208 void
4209 empathy_chat_find (EmpathyChat *chat)
4210 {
4211         EmpathyChatPriv *priv;
4212
4213         g_return_if_fail (EMPATHY_IS_CHAT (chat));
4214
4215         priv = GET_PRIV (chat);
4216
4217         empathy_search_bar_show (EMPATHY_SEARCH_BAR (priv->search_bar));
4218 }
4219
4220 void
4221 empathy_chat_correct_word (EmpathyChat  *chat,
4222                           GtkTextIter *start,
4223                           GtkTextIter *end,
4224                           const gchar *new_word)
4225 {
4226         GtkTextBuffer *buffer;
4227
4228         g_return_if_fail (chat != NULL);
4229         g_return_if_fail (new_word != NULL);
4230
4231         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
4232
4233         gtk_text_buffer_delete (buffer, start, end);
4234         gtk_text_buffer_insert (buffer, start,
4235                                 new_word,
4236                                 -1);
4237 }
4238
4239 gboolean
4240 empathy_chat_is_room (EmpathyChat *chat)
4241 {
4242         EmpathyChatPriv *priv = GET_PRIV (chat);
4243
4244         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
4245
4246         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
4247 }
4248
4249 guint
4250 empathy_chat_get_nb_unread_messages (EmpathyChat *self)
4251 {
4252         EmpathyChatPriv *priv = GET_PRIV (self);
4253
4254         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
4255
4256         return priv->unread_messages;
4257 }
4258
4259 /* called when the messages have been read by user */
4260 void
4261 empathy_chat_messages_read (EmpathyChat *self)
4262 {
4263         EmpathyChatPriv *priv = GET_PRIV (self);
4264
4265         g_return_if_fail (EMPATHY_IS_CHAT (self));
4266
4267         /* FIXME: See Bug#610994, See comments about it in EmpathyChatPriv
4268          * definition. If we are still retrieving the backlogs, do not ACK */
4269         if (priv->retrieving_backlogs)
4270                 return;
4271
4272         if (priv->tp_chat != NULL) {
4273                 tp_text_channel_ack_all_pending_messages_async (
4274                         TP_TEXT_CHANNEL (priv->tp_chat), NULL, NULL);
4275         }
4276
4277         if (priv->unread_messages_when_offline > 0) {
4278                 /* We can't ack those as the connection has gone away so just consider
4279                 * them as read. */
4280                 priv->unread_messages -= priv->unread_messages_when_offline;
4281                 g_object_notify (G_OBJECT (self), "nb-unread-messages");
4282                 priv->unread_messages_when_offline = 0;
4283         }
4284 }
4285
4286 /* Return TRUE if on of the contacts in this chat is composing */
4287 gboolean
4288 empathy_chat_is_composing (EmpathyChat *chat)
4289 {
4290   return chat->priv->compositors != NULL;
4291 }
4292
4293 gboolean
4294 empathy_chat_is_sms_channel (EmpathyChat *self)
4295 {
4296         EmpathyChatPriv *priv = GET_PRIV (self);
4297
4298         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
4299
4300         return priv->sms_channel;
4301 }
4302
4303 guint
4304 empathy_chat_get_n_messages_sending (EmpathyChat *self)
4305 {
4306         EmpathyChatPriv *priv;
4307
4308         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
4309
4310         priv = GET_PRIV (self);
4311
4312         if (priv->tp_chat == NULL) {
4313                 return 0;
4314         } else {
4315                 guint n_messages;
4316
4317                 g_object_get (priv->tp_chat,
4318                         "n-messages-sending", &n_messages,
4319                         NULL);
4320
4321                 return n_messages;
4322         }
4323 }
4324
4325 gchar *
4326 empathy_chat_dup_text (EmpathyChat *self)
4327 {
4328         GtkTextBuffer *buffer;
4329         GtkTextIter     start, end;
4330
4331         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (self->input_text_view));
4332
4333         gtk_text_buffer_get_bounds (buffer, &start, &end);
4334         return gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
4335 }
4336
4337 void
4338 empathy_chat_set_text (EmpathyChat *self,
4339                        const gchar *text)
4340 {
4341         GtkTextBuffer *buffer;
4342
4343         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (self->input_text_view));
4344
4345         gtk_text_buffer_set_text (buffer, text, -1);
4346 }