]> git.0d.be Git - empathy.git/blob - libempathy-gtk/empathy-chat.c
add timestamp arg to empathy_dispatcher_join_muc
[empathy.git] / libempathy-gtk / empathy-chat.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2002-2007 Imendio AB
4  * Copyright (C) 2007-2008 Collabora Ltd.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 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 #include <gdk/gdkkeysyms.h>
34 #include <glib/gi18n-lib.h>
35 #include <gtk/gtk.h>
36
37 #include <telepathy-glib/account-manager.h>
38 #include <telepathy-glib/util.h>
39 #ifdef ENABLE_TPL
40 #include <telepathy-logger/log-manager.h>
41 #else
42
43 #include <libempathy/empathy-log-manager.h>
44 #endif /* ENABLE_TPL */
45 #include <libempathy/empathy-contact-list.h>
46 #include <libempathy/empathy-utils.h>
47 #include <libempathy/empathy-dispatcher.h>
48
49 #include "empathy-chat.h"
50 #include "empathy-conf.h"
51 #include "empathy-spell.h"
52 #include "empathy-contact-list-store.h"
53 #include "empathy-contact-list-view.h"
54 #include "empathy-contact-menu.h"
55 #include "empathy-search-bar.h"
56 #include "empathy-theme-manager.h"
57 #include "empathy-smiley-manager.h"
58 #include "empathy-ui-utils.h"
59 #include "empathy-string-parser.h"
60
61 #define DEBUG_FLAG EMPATHY_DEBUG_CHAT
62 #include <libempathy/empathy-debug.h>
63
64 #define CHAT_DIR_CREATE_MODE  (S_IRUSR | S_IWUSR | S_IXUSR)
65 #define CHAT_FILE_CREATE_MODE (S_IRUSR | S_IWUSR)
66 #define IS_ENTER(v) (v == GDK_Return || v == GDK_ISO_Enter || v == GDK_KP_Enter)
67 #define MAX_INPUT_HEIGHT 150
68 #define COMPOSING_STOP_TIMEOUT 5
69
70 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyChat)
71 typedef struct {
72         EmpathyTpChat     *tp_chat;
73         TpAccount         *account;
74         gchar             *id;
75         gchar             *name;
76         gchar             *subject;
77         EmpathyContact    *remote_contact;
78         gboolean           show_contacts;
79
80 #ifdef ENABLE_TPL
81         TplLogManager     *log_manager;
82 #else
83         EmpathyLogManager *log_manager;
84 #endif /* ENABLE_TPL */
85         TpAccountManager  *account_manager;
86         GList             *input_history;
87         GList             *input_history_current;
88         GList             *compositors;
89         GCompletion       *completion;
90         guint              composing_stop_timeout_id;
91         guint              block_events_timeout_id;
92         TpHandleType       handle_type;
93         gint               contacts_width;
94         gboolean           has_input_vscroll;
95         gint               topic_width;
96
97         GtkWidget         *widget;
98         GtkWidget         *hpaned;
99         GtkWidget         *vbox_left;
100         GtkWidget         *scrolled_window_chat;
101         GtkWidget         *scrolled_window_input;
102         GtkWidget         *scrolled_window_contacts;
103         GtkWidget         *hbox_topic;
104         GtkWidget         *expander_topic;
105         GtkWidget         *label_topic;
106         GtkWidget         *contact_list_view;
107         GtkWidget         *info_bar_vbox;
108         GtkWidget         *search_bar;
109
110         guint              unread_messages;
111         /* TRUE if the pending messages can be displayed. This is to avoid to show
112          * pending messages *before* messages from logs. (#603980) */
113         gboolean           can_show_pending;
114
115         /* FIXME: retrieving_backlogs flag is a workaround for Bug#610994 and should
116          * be differently handled since it introduces another race condition, which
117          * is really hard to occur, but still possible.
118          *
119          * With the current workaround (which has the race above), we need to be
120          * sure to ACK any pending messages only when the retrieval of backlogs is
121          * finished, that's why using retrieving_backlogs flag.
122          * empathy_chat_messages_read () will check this variable and not ACK
123          * anything when TRUE. It will be set TRUE at chat_constructed () and set
124          * back to FALSE when the backlog has been retrieved and the pending
125          * messages actually showed to the user.
126          *
127          * Race condition introduced with this workaround:
128          * Scenario: a message is pending, the user is notified and selects the tab.
129          * the tab with a pending message is focused before the messages are properly
130          * shown (since the preparation of the window is slower AND async WRT the
131          * tab showing), which means the user won't see any new messages (rare but
132          * possible), if he/she will change tab focus before the messages are
133          * properly shown, the tab will be set as 'seen' and the user won't be
134          * notified again about the already notified pending messages when the
135          * messages in tab will be properly shown */
136         gboolean           retrieving_backlogs;
137 } EmpathyChatPriv;
138
139 typedef struct {
140         gchar *text; /* Original message that was specified
141                       * upon entry creation. */
142         gchar *modified_text; /* Message that was modified by user.
143                                * When no modifications were made, it is NULL */
144 } InputHistoryEntry;
145
146 enum {
147         COMPOSING,
148         NEW_MESSAGE,
149         LAST_SIGNAL
150 };
151
152 enum {
153         PROP_0,
154         PROP_TP_CHAT,
155         PROP_ACCOUNT,
156         PROP_ID,
157         PROP_NAME,
158         PROP_SUBJECT,
159         PROP_REMOTE_CONTACT,
160         PROP_SHOW_CONTACTS,
161 };
162
163 static guint signals[LAST_SIGNAL] = { 0 };
164
165 G_DEFINE_TYPE (EmpathyChat, empathy_chat, GTK_TYPE_BIN);
166
167 static void
168 chat_get_property (GObject    *object,
169                    guint       param_id,
170                    GValue     *value,
171                    GParamSpec *pspec)
172 {
173         EmpathyChat *chat = EMPATHY_CHAT (object);
174         EmpathyChatPriv *priv = GET_PRIV (object);
175
176         switch (param_id) {
177         case PROP_TP_CHAT:
178                 g_value_set_object (value, priv->tp_chat);
179                 break;
180         case PROP_ACCOUNT:
181                 g_value_set_object (value, priv->account);
182                 break;
183         case PROP_NAME:
184                 g_value_set_string (value, empathy_chat_get_name (chat));
185                 break;
186         case PROP_ID:
187                 g_value_set_string (value, priv->id);
188                 break;
189         case PROP_SUBJECT:
190                 g_value_set_string (value, priv->subject);
191                 break;
192         case PROP_REMOTE_CONTACT:
193                 g_value_set_object (value, priv->remote_contact);
194                 break;
195         case PROP_SHOW_CONTACTS:
196                 g_value_set_boolean (value, priv->show_contacts);
197                 break;
198         default:
199                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
200                 break;
201         };
202 }
203
204 static void
205 chat_set_property (GObject      *object,
206                    guint         param_id,
207                    const GValue *value,
208                    GParamSpec   *pspec)
209 {
210         EmpathyChat *chat = EMPATHY_CHAT (object);
211
212         switch (param_id) {
213         case PROP_TP_CHAT:
214                 empathy_chat_set_tp_chat (chat, EMPATHY_TP_CHAT (g_value_get_object (value)));
215                 break;
216         case PROP_SHOW_CONTACTS:
217                 empathy_chat_set_show_contacts (chat, g_value_get_boolean (value));
218                 break;
219         default:
220                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
221                 break;
222         };
223 }
224
225 static void
226 chat_connect_channel_reconnected (EmpathyDispatchOperation *dispatch,
227                                   const GError             *error,
228                                   gpointer                  user_data)
229 {
230         EmpathyChat *chat = EMPATHY_CHAT (user_data);
231         EmpathyTpChat *tpchat;
232
233         if (error != NULL) {
234                 empathy_chat_view_append_event (chat->view,
235                         _("Failed to reconnect this chat"));
236                 return;
237         }
238
239         tpchat = EMPATHY_TP_CHAT (
240                 empathy_dispatch_operation_get_channel_wrapper (dispatch));
241
242         if (empathy_dispatch_operation_claim (dispatch)) {
243                 empathy_chat_set_tp_chat (chat, tpchat);
244         }
245 }
246
247 static void
248 reconnected_connection_ready_cb (TpConnection *connection,
249                         const GError *error,
250                         gpointer user_data)
251 {
252         EmpathyChat *chat = user_data;
253         EmpathyChatPriv *priv = GET_PRIV (chat);
254
255         if (error != NULL) {
256                 DEBUG ("connection is not ready: %s", error->message);
257                 goto out;
258         }
259
260         DEBUG ("Account reconnected, request a new Text channel");
261
262         switch (priv->handle_type) {
263                 case TP_HANDLE_TYPE_CONTACT:
264                         empathy_dispatcher_chat_with_contact_id (
265                                 connection, priv->id, EMPATHY_DISPATCHER_NON_USER_ACTION,
266                                 chat_connect_channel_reconnected,
267                                 chat);
268                         break;
269                 case TP_HANDLE_TYPE_ROOM:
270                         empathy_dispatcher_join_muc (connection,
271                                 priv->id, EMPATHY_DISPATCHER_NON_USER_ACTION,
272                                 chat_connect_channel_reconnected,
273                                 chat);
274                         break;
275                 default:
276                         g_assert_not_reached ();
277                         break;
278         }
279
280 out:
281         g_object_unref (chat);
282 }
283
284 static void
285 chat_new_connection_cb (TpAccount   *account,
286                         guint        old_status,
287                         guint        new_status,
288                         guint        reason,
289                         gchar       *dbus_error_name,
290                         GHashTable  *details,
291                         EmpathyChat *chat)
292 {
293         EmpathyChatPriv *priv = GET_PRIV (chat);
294         TpConnection *connection;
295
296         if (new_status != TP_CONNECTION_STATUS_CONNECTED)
297                 return;
298
299         connection = tp_account_get_connection (account);
300
301         if (priv->tp_chat != NULL || account != priv->account ||
302             priv->handle_type == TP_HANDLE_TYPE_NONE ||
303             EMP_STR_EMPTY (priv->id))
304                 return;
305
306         g_object_ref (chat);
307         tp_connection_call_when_ready (connection, reconnected_connection_ready_cb,
308                                    chat);
309 }
310
311 static void
312 chat_composing_remove_timeout (EmpathyChat *chat)
313 {
314         EmpathyChatPriv *priv;
315
316         priv = GET_PRIV (chat);
317
318         if (priv->composing_stop_timeout_id) {
319                 g_source_remove (priv->composing_stop_timeout_id);
320                 priv->composing_stop_timeout_id = 0;
321         }
322 }
323
324 static gboolean
325 chat_composing_stop_timeout_cb (EmpathyChat *chat)
326 {
327         EmpathyChatPriv *priv;
328
329         priv = GET_PRIV (chat);
330
331         priv->composing_stop_timeout_id = 0;
332         empathy_tp_chat_set_state (priv->tp_chat,
333                                    TP_CHANNEL_CHAT_STATE_PAUSED);
334
335         return FALSE;
336 }
337
338 static void
339 chat_composing_start (EmpathyChat *chat)
340 {
341         EmpathyChatPriv *priv;
342
343         priv = GET_PRIV (chat);
344
345         if (priv->composing_stop_timeout_id) {
346                 /* Just restart the timeout */
347                 chat_composing_remove_timeout (chat);
348         } else {
349                 empathy_tp_chat_set_state (priv->tp_chat,
350                                            TP_CHANNEL_CHAT_STATE_COMPOSING);
351         }
352
353         priv->composing_stop_timeout_id = g_timeout_add_seconds (
354                 COMPOSING_STOP_TIMEOUT,
355                 (GSourceFunc) chat_composing_stop_timeout_cb,
356                 chat);
357 }
358
359 static void
360 chat_composing_stop (EmpathyChat *chat)
361 {
362         EmpathyChatPriv *priv;
363
364         priv = GET_PRIV (chat);
365
366         chat_composing_remove_timeout (chat);
367         empathy_tp_chat_set_state (priv->tp_chat,
368                                    TP_CHANNEL_CHAT_STATE_ACTIVE);
369 }
370
371 static gint
372 chat_input_history_entry_cmp (InputHistoryEntry *entry,
373                               const gchar *text)
374 {
375         if (!tp_strdiff (entry->text, text)) {
376                 if (entry->modified_text != NULL) {
377                         /* Modified entry and single string cannot be equal. */
378                         return 1;
379                 }
380                 return 0;
381         }
382         return 1;
383 }
384
385 static InputHistoryEntry *
386 chat_input_history_entry_new_with_text (const gchar *text)
387 {
388         InputHistoryEntry *entry;
389         entry = g_slice_new0 (InputHistoryEntry);
390         entry->text = g_strdup (text);
391
392         return entry;
393 }
394
395 static void
396 chat_input_history_entry_free (InputHistoryEntry *entry)
397 {
398         g_free (entry->text);
399         g_free (entry->modified_text);
400         g_slice_free (InputHistoryEntry, entry);
401 }
402
403 static void
404 chat_input_history_entry_revert (InputHistoryEntry *entry)
405 {
406         g_free (entry->modified_text);
407         entry->modified_text = NULL;
408 }
409
410 static void
411 chat_input_history_entry_update_text (InputHistoryEntry *entry,
412                                       const gchar *text)
413 {
414         gchar *old;
415
416         if (!tp_strdiff (text, entry->text)) {
417                 g_free (entry->modified_text);
418                 entry->modified_text = NULL;
419                 return;
420         }
421
422         old = entry->modified_text;
423         entry->modified_text = g_strdup (text);
424         g_free (old);
425 }
426
427 static const gchar *
428 chat_input_history_entry_get_text (InputHistoryEntry *entry)
429 {
430         if (entry == NULL) {
431                 return NULL;
432         }
433
434         if (entry->modified_text != NULL) {
435                 return entry->modified_text;
436         }
437         return entry->text;
438 }
439
440 static GList *
441 chat_input_history_remove_item (GList *list,
442                                 GList *item)
443 {
444         list = g_list_remove_link (list, item);
445         chat_input_history_entry_free (item->data);
446         g_list_free_1 (item);
447         return list;
448 }
449
450 static void
451 chat_input_history_revert (EmpathyChat *chat)
452 {
453         EmpathyChatPriv   *priv;
454         GList             *list;
455         GList             *item1;
456         GList             *item2;
457         InputHistoryEntry *entry;
458
459         priv = GET_PRIV (chat);
460         list = priv->input_history;
461
462         if (list == NULL) {
463                 DEBUG ("No input history");
464                 return;
465         }
466
467         /* Delete temporary entry */
468         if (priv->input_history_current != NULL) {
469                 item1 = list;
470                 list = chat_input_history_remove_item (list, item1);
471                 if (priv->input_history_current == item1) {
472                         /* Removed temporary entry was current entry */
473                         priv->input_history = list;
474                         priv->input_history_current = NULL;
475                         return;
476                 }
477         }
478         else {
479                 /* There is no entry to revert */
480                 return;
481         }
482
483         /* Restore the current history entry to original value */
484         item1 = priv->input_history_current;
485         entry = item1->data;
486         chat_input_history_entry_revert (entry);
487
488         /* Remove restored entry if there is other occurance before this entry */
489         item2 = g_list_find_custom (list, chat_input_history_entry_get_text (entry),
490                                     (GCompareFunc) chat_input_history_entry_cmp);
491         if (item2 != item1) {
492                 list = chat_input_history_remove_item (list, item1);
493         }
494         else {
495                 /* Remove other occurance of the restored entry */
496                 item2 = g_list_find_custom (item1->next,
497                                             chat_input_history_entry_get_text (entry),
498                                             (GCompareFunc) chat_input_history_entry_cmp);
499                 if (item2 != NULL) {
500                         list = chat_input_history_remove_item (list, item2);
501                 }
502         }
503
504         priv->input_history_current = NULL;
505         priv->input_history = list;
506 }
507
508 static void
509 chat_input_history_add (EmpathyChat  *chat,
510                         const gchar *str,
511                         gboolean temporary)
512 {
513         EmpathyChatPriv   *priv;
514         GList             *list;
515         GList             *item;
516         InputHistoryEntry *entry;
517
518         priv = GET_PRIV (chat);
519
520         list = priv->input_history;
521
522         /* Remove any other occurances of this entry, if not temporary */
523         if (!temporary) {
524                 while ((item = g_list_find_custom (list, str,
525                     (GCompareFunc) chat_input_history_entry_cmp)) != NULL) {
526                         list = chat_input_history_remove_item (list, item);
527                 }
528
529                 /* Trim the list to the last 10 items */
530                 while (g_list_length (list) > 10) {
531                         item = g_list_last (list);
532                         if (item != NULL) {
533                                 list = chat_input_history_remove_item (list, item);
534                         }
535                 }
536         }
537
538
539
540         /* Add new entry */
541         entry = chat_input_history_entry_new_with_text (str);
542         list = g_list_prepend (list, entry);
543
544         /* Set the list and the current item pointer */
545         priv->input_history = list;
546         if (temporary) {
547                 priv->input_history_current = list;
548         }
549         else {
550                 priv->input_history_current = NULL;
551         }
552 }
553
554 static const gchar *
555 chat_input_history_get_next (EmpathyChat *chat)
556 {
557         EmpathyChatPriv *priv;
558         GList           *item;
559         const gchar     *msg;
560
561         priv = GET_PRIV (chat);
562
563         if (priv->input_history == NULL) {
564                 DEBUG ("No input history, next entry is NULL");
565                 return NULL;
566         }
567         g_assert (priv->input_history_current != NULL);
568
569         if ((item = g_list_next (priv->input_history_current)) == NULL)
570         {
571                 item = priv->input_history_current;
572         }
573
574         msg = chat_input_history_entry_get_text (item->data);
575
576         DEBUG ("Returning next entry: '%s'", msg);
577
578         priv->input_history_current = item;
579
580         return msg;
581 }
582
583 static const gchar *
584 chat_input_history_get_prev (EmpathyChat *chat)
585 {
586         EmpathyChatPriv *priv;
587         GList           *item;
588         const gchar     *msg;
589
590         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
591
592         priv = GET_PRIV (chat);
593
594         if (priv->input_history == NULL) {
595                 DEBUG ("No input history, previous entry is NULL");
596                 return NULL;
597         }
598
599         if (priv->input_history_current == NULL)
600         {
601                 return NULL;
602         }
603         else if ((item = g_list_previous (priv->input_history_current)) == NULL)
604         {
605                 item = priv->input_history_current;
606         }
607
608         msg = chat_input_history_entry_get_text (item->data);
609
610         DEBUG ("Returning previous entry: '%s'", msg);
611
612         priv->input_history_current = item;
613
614         return msg;
615 }
616
617 static void
618 chat_input_history_update (EmpathyChat *chat,
619                            GtkTextBuffer *buffer)
620 {
621         EmpathyChatPriv      *priv;
622         GtkTextIter           start, end;
623         gchar                *text;
624         InputHistoryEntry    *entry;
625
626         priv = GET_PRIV (chat);
627
628         gtk_text_buffer_get_bounds (buffer, &start, &end);
629         text = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
630
631         if (priv->input_history_current == NULL) {
632                 /* Add the current text temporarily to the history */
633                 chat_input_history_add (chat, text, TRUE);
634                 g_free (text);
635                 return;
636         }
637
638         /* Save the changes in the history */
639         entry = priv->input_history_current->data;
640         if (tp_strdiff (chat_input_history_entry_get_text (entry), text)) {
641                 chat_input_history_entry_update_text (entry, text);
642         }
643
644         g_free (text);
645 }
646
647 static void
648 chat_command_join_cb (EmpathyDispatchOperation *dispatch,
649                       const GError             *error,
650                       gpointer                  user_data)
651 {
652         EmpathyChat *chat = user_data;
653
654         if (error != NULL) {
655                 DEBUG ("Error: %s", error->message);
656                 empathy_chat_view_append_event (chat->view,
657                         _("Failed to join chat room"));
658         }
659 }
660
661 typedef struct {
662         EmpathyChat *chat;
663         gchar *message;
664 } ChatCommandMsgData;
665
666 static void
667 chat_command_msg_cb (EmpathyDispatchOperation *dispatch,
668                               const GError             *error,
669                               gpointer                  user_data)
670 {
671         ChatCommandMsgData *data = user_data;
672
673         if (error != NULL) {
674                 empathy_chat_view_append_event (data->chat->view,
675                         _("Failed to open private chat"));
676                 goto OUT;
677         }
678
679         if (!EMP_STR_EMPTY (data->message)) {
680                 EmpathyTpChat *tpchat;
681                 EmpathyMessage *message;
682
683                 tpchat = EMPATHY_TP_CHAT (
684                         empathy_dispatch_operation_get_channel_wrapper (dispatch));
685
686                 message = empathy_message_new (data->message);
687                 empathy_tp_chat_send (tpchat, message);
688                 g_object_unref (message);
689         }
690
691 OUT:
692         g_free (data->message);
693         g_slice_free (ChatCommandMsgData, data);
694 }
695
696 static void
697 chat_command_clear (EmpathyChat *chat,
698                     GStrv        strv)
699 {
700         empathy_chat_view_clear (chat->view);
701 }
702
703 static void
704 chat_command_topic (EmpathyChat *chat,
705                     GStrv        strv)
706 {
707         EmpathyChatPriv *priv = GET_PRIV (chat);
708         EmpathyTpChatProperty *property;
709         GValue value = {0, };
710
711         property = empathy_tp_chat_get_property (priv->tp_chat, "subject");
712         if (property == NULL) {
713                 empathy_chat_view_append_event (chat->view,
714                         _("Topic not supported on this conversation"));
715                 return;
716         }
717
718         if (!(property->flags & TP_PROPERTY_FLAG_WRITE)) {
719                 empathy_chat_view_append_event (chat->view,
720                         _("You are not allowed to change the topic"));
721                 return;
722         }
723
724         g_value_init (&value, G_TYPE_STRING);
725         g_value_set_string (&value, strv[1]);
726         empathy_tp_chat_set_property (priv->tp_chat, "subject", &value);
727         g_value_unset (&value);
728 }
729
730 static void
731 chat_command_join (EmpathyChat *chat,
732                    GStrv        strv)
733 {
734         guint i = 0;
735         EmpathyChatPriv *priv = GET_PRIV (chat);
736
737         GStrv rooms = g_strsplit_set (strv[1], ", ", -1);
738
739         while (rooms[i] != NULL) {
740                 /* ignore empty strings */
741                 if (!EMP_STR_EMPTY (rooms[i])) {
742                         TpConnection *connection;
743
744                         connection = empathy_tp_chat_get_connection (priv->tp_chat);
745                         empathy_dispatcher_join_muc (connection, rooms[i],
746                                                      gtk_get_current_event_time (),
747                                                      chat_command_join_cb,
748                                                      chat);
749                 }
750                 i++;
751         }
752         g_strfreev (rooms);
753 }
754
755 static void
756 chat_command_msg_internal (EmpathyChat *chat,
757                            const gchar *contact_id,
758                            const gchar *message)
759 {
760         EmpathyChatPriv *priv = GET_PRIV (chat);
761         TpConnection *connection;
762         ChatCommandMsgData *data;
763
764         /* FIXME: We should probably search in members alias. But this
765          * is enough for IRC */
766         data = g_slice_new (ChatCommandMsgData);
767         data->chat = chat;
768         data->message = g_strdup (message);
769         connection = empathy_tp_chat_get_connection (priv->tp_chat);
770         empathy_dispatcher_chat_with_contact_id (connection, contact_id,
771                                                  gtk_get_current_event_time (),
772                                                  chat_command_msg_cb,
773                                                  data);
774 }
775
776 static void
777 chat_command_query (EmpathyChat *chat,
778                     GStrv        strv)
779 {
780         /* If <message> part is not defined,
781          * strv[2] will be the terminal NULL */
782         chat_command_msg_internal (chat, strv[1], strv[2]);
783 }
784
785 static void
786 chat_command_msg (EmpathyChat *chat,
787                   GStrv        strv)
788 {
789         chat_command_msg_internal (chat, strv[1], strv[2]);
790 }
791
792 static void
793 chat_command_nick (EmpathyChat *chat,
794                    GStrv        strv)
795 {
796         EmpathyChatPriv *priv = GET_PRIV (chat);
797         TpConnection *connection;
798         GHashTable *new_alias;
799         TpHandle handle;
800
801         connection = tp_account_get_connection (priv->account);
802         handle = tp_connection_get_self_handle (connection);
803         new_alias = g_hash_table_new (g_direct_hash, g_direct_equal);
804         g_hash_table_insert (new_alias, GUINT_TO_POINTER (handle), strv[1]);
805
806         tp_cli_connection_interface_aliasing_call_set_aliases (connection, -1,
807                 new_alias, NULL, NULL, NULL, NULL);
808
809         g_hash_table_destroy (new_alias);
810 }
811
812 static void
813 chat_command_me (EmpathyChat *chat,
814                   GStrv        strv)
815 {
816         EmpathyChatPriv *priv = GET_PRIV (chat);
817         EmpathyMessage *message;
818
819         message = empathy_message_new (strv[1]);
820         empathy_message_set_tptype (message, TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION);
821         empathy_tp_chat_send (priv->tp_chat, message);
822         g_object_unref (message);
823 }
824
825 static void
826 chat_command_say (EmpathyChat *chat,
827                   GStrv        strv)
828 {
829         EmpathyChatPriv *priv = GET_PRIV (chat);
830         EmpathyMessage *message;
831
832         message = empathy_message_new (strv[1]);
833         empathy_tp_chat_send (priv->tp_chat, message);
834         g_object_unref (message);
835 }
836
837 static void chat_command_help (EmpathyChat *chat, GStrv strv);
838
839 typedef void (*ChatCommandFunc) (EmpathyChat *chat, GStrv strv);
840
841 typedef struct {
842         const gchar *prefix;
843         guint min_parts;
844         guint max_parts;
845         ChatCommandFunc func;
846         const gchar *help;
847 } ChatCommandItem;
848
849 static ChatCommandItem commands[] = {
850         {"clear", 1, 1, chat_command_clear,
851          N_("/clear: clear all messages from the current conversation")},
852
853         {"topic", 2, 2, chat_command_topic,
854          N_("/topic <topic>: set the topic of the current conversation")},
855
856         {"join", 2, 2, chat_command_join,
857          N_("/join <chat room ID>: join a new chat room")},
858
859         {"j", 2, 2, chat_command_join,
860          N_("/j <chat room ID>: join a new chat room")},
861
862         {"query", 2, 3, chat_command_query,
863          N_("/query <contact ID> [<message>]: open a private chat")},
864
865         {"msg", 3, 3, chat_command_msg,
866          N_("/msg <contact ID> <message>: open a private chat")},
867
868         {"nick", 2, 2, chat_command_nick,
869          N_("/nick <nickname>: change your nickname on the current server")},
870
871         {"me", 2, 2, chat_command_me,
872          N_("/me <message>: send an ACTION message to the current conversation")},
873
874         {"say", 2, 2, chat_command_say,
875          N_("/say <message>: send <message> to the current conversation. "
876             "This is used to send a message starting with a '/'. For example: "
877             "\"/say /join is used to join a new chat room\"")},
878
879         {"help", 1, 2, chat_command_help,
880          N_("/help [<command>]: show all supported commands. "
881             "If <command> is defined, show its usage.")},
882 };
883
884 static void
885 chat_command_show_help (EmpathyChat     *chat,
886                         ChatCommandItem *item)
887 {
888         gchar *str;
889
890         str = g_strdup_printf (_("Usage: %s"), _(item->help));
891         empathy_chat_view_append_event (chat->view, str);
892         g_free (str);
893 }
894
895 static void
896 chat_command_help (EmpathyChat *chat,
897                    GStrv        strv)
898 {
899         guint i;
900
901         /* If <command> part is not defined,
902          * strv[1] will be the terminal NULL */
903         if (strv[1] == NULL) {
904                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
905                         empathy_chat_view_append_event (chat->view,
906                                 _(commands[i].help));
907                 }
908                 return;
909         }
910
911         for (i = 0; i < G_N_ELEMENTS (commands); i++) {
912                 if (g_ascii_strcasecmp (strv[1], commands[i].prefix) == 0) {
913                         chat_command_show_help (chat, &commands[i]);
914                         return;
915                 }
916         }
917
918         empathy_chat_view_append_event (chat->view,
919                 _("Unknown command"));
920 }
921
922 static GStrv
923 chat_command_parse (const gchar *text, guint max_parts)
924 {
925         GPtrArray *array;
926         gchar *item;
927
928         DEBUG ("Parse command, parts=%d text=\"%s\":", max_parts, text);
929
930         array = g_ptr_array_sized_new (max_parts + 1);
931         while (max_parts > 1) {
932                 const gchar *end;
933
934                 /* Skip white spaces */
935                 while (g_ascii_isspace (*text)) {
936                         text++;
937                 }
938
939                 /* Search the end of this part, until first space. */
940                 for (end = text; *end != '\0' && !g_ascii_isspace (*end); end++)
941                         /* Do nothing */;
942                 if (*end == '\0') {
943                         break;
944                 }
945
946                 item = g_strndup (text, end - text);
947                 g_ptr_array_add (array, item);
948                 DEBUG ("\tITEM: \"%s\"", item);
949
950                 text = end;
951                 max_parts--;
952         }
953
954         /* Append last part if not empty */
955         item = g_strstrip (g_strdup (text));
956         if (!EMP_STR_EMPTY (item)) {
957                 g_ptr_array_add (array, item);
958                 DEBUG ("\tITEM: \"%s\"", item);
959         } else {
960                 g_free (item);
961         }
962
963         /* Make the array NULL-terminated */
964         g_ptr_array_add (array, NULL);
965
966         return (GStrv) g_ptr_array_free (array, FALSE);
967 }
968
969 static gboolean
970 has_prefix_case (const gchar *s,
971                   const gchar *prefix)
972 {
973         return g_ascii_strncasecmp (s, prefix, strlen (prefix)) == 0;
974 }
975
976 static void
977 chat_send (EmpathyChat  *chat,
978            const gchar *msg)
979 {
980         EmpathyChatPriv *priv;
981         EmpathyMessage  *message;
982         guint            i;
983
984         if (EMP_STR_EMPTY (msg)) {
985                 return;
986         }
987
988         priv = GET_PRIV (chat);
989
990         chat_input_history_add (chat, msg, FALSE);
991
992         if (msg[0] == '/') {
993                 gboolean second_slash = FALSE;
994                 const gchar *iter = msg + 1;
995
996                 for (i = 0; i < G_N_ELEMENTS (commands); i++) {
997                         GStrv strv;
998                         guint strv_len;
999                         gchar c;
1000
1001                         if (!has_prefix_case (msg + 1, commands[i].prefix)) {
1002                                 continue;
1003                         }
1004                         c = *(msg + 1 + strlen (commands[i].prefix));
1005                         if (c != '\0' && !g_ascii_isspace (c)) {
1006                                 continue;
1007                         }
1008
1009                         /* We can't use g_strsplit here because it does
1010                          * not deal correctly if we have more than one space
1011                          * between args */
1012                         strv = chat_command_parse (msg + 1, commands[i].max_parts);
1013
1014                         strv_len = g_strv_length (strv);
1015                         if (strv_len < commands[i].min_parts ||
1016                             strv_len > commands[i].max_parts) {
1017                                 chat_command_show_help (chat, &commands[i]);
1018                                 g_strfreev (strv);
1019                                 return;
1020                         }
1021
1022                         commands[i].func (chat, strv);
1023                         g_strfreev (strv);
1024                         return;
1025                 }
1026
1027                 /* Also allow messages with two slashes before the
1028                  * first space, so it is possible to send a /unix/path.
1029                  * This heuristic is kind of crap. */
1030                 while (*iter != '\0' && !g_ascii_isspace (*iter)) {
1031                         if (*iter == '/') {
1032                                 second_slash = TRUE;
1033                                 break;
1034                         }
1035                         iter++;
1036                 }
1037
1038                 if (!second_slash) {
1039                         empathy_chat_view_append_event (chat->view,
1040                                 _("Unknown command; see /help for the available"
1041                                   " commands"));
1042                         return;
1043                 }
1044         }
1045
1046         message = empathy_message_new (msg);
1047         empathy_tp_chat_send (priv->tp_chat, message);
1048         g_object_unref (message);
1049 }
1050
1051 static void
1052 chat_input_text_view_send (EmpathyChat *chat)
1053 {
1054         EmpathyChatPriv *priv;
1055         GtkTextBuffer  *buffer;
1056         GtkTextIter     start, end;
1057         gchar          *msg;
1058
1059         priv = GET_PRIV (chat);
1060
1061         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1062
1063         gtk_text_buffer_get_bounds (buffer, &start, &end);
1064         msg = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1065
1066         /* clear the input field */
1067         gtk_text_buffer_set_text (buffer, "", -1);
1068         /* delete input history modifications */
1069         chat_input_history_revert (chat);
1070
1071         chat_send (chat, msg);
1072         g_free (msg);
1073 }
1074
1075 static void
1076 chat_state_changed_cb (EmpathyTpChat      *tp_chat,
1077                        EmpathyContact     *contact,
1078                        TpChannelChatState  state,
1079                        EmpathyChat        *chat)
1080 {
1081         EmpathyChatPriv *priv;
1082         GList          *l;
1083         gboolean        was_composing;
1084
1085         priv = GET_PRIV (chat);
1086
1087         if (empathy_contact_is_user (contact)) {
1088                 /* We don't care about our own chat state */
1089                 return;
1090         }
1091
1092         was_composing = (priv->compositors != NULL);
1093
1094         /* Find the contact in the list. After that l is the list elem or NULL */
1095         for (l = priv->compositors; l; l = l->next) {
1096                 if (contact == l->data) {
1097                         break;
1098                 }
1099         }
1100
1101         switch (state) {
1102         case TP_CHANNEL_CHAT_STATE_GONE:
1103         case TP_CHANNEL_CHAT_STATE_INACTIVE:
1104         case TP_CHANNEL_CHAT_STATE_PAUSED:
1105         case TP_CHANNEL_CHAT_STATE_ACTIVE:
1106                 /* Contact is not composing */
1107                 if (l) {
1108                         priv->compositors = g_list_remove_link (priv->compositors, l);
1109                         g_object_unref (l->data);
1110                         g_list_free1 (l);
1111                 }
1112                 break;
1113         case TP_CHANNEL_CHAT_STATE_COMPOSING:
1114                 /* Contact is composing */
1115                 if (!l) {
1116                         priv->compositors = g_list_prepend (priv->compositors,
1117                                                             g_object_ref (contact));
1118                 }
1119                 break;
1120         default:
1121                 g_assert_not_reached ();
1122         }
1123
1124         DEBUG ("Was composing: %s now composing: %s",
1125                 was_composing ? "yes" : "no",
1126                 priv->compositors ? "yes" : "no");
1127
1128         if ((was_composing && !priv->compositors) ||
1129             (!was_composing && priv->compositors)) {
1130                 /* Composing state changed */
1131                 g_signal_emit (chat, signals[COMPOSING], 0,
1132                                priv->compositors != NULL);
1133         }
1134 }
1135
1136 static void
1137 chat_message_received (EmpathyChat *chat, EmpathyMessage *message)
1138 {
1139         EmpathyChatPriv *priv = GET_PRIV (chat);
1140         EmpathyContact  *sender;
1141
1142         sender = empathy_message_get_sender (message);
1143
1144         DEBUG ("Appending new message from %s (%d)",
1145                 empathy_contact_get_name (sender),
1146                 empathy_contact_get_handle (sender));
1147
1148         empathy_chat_view_append_message (chat->view, message);
1149
1150         /* We received a message so the contact is no longer composing */
1151         chat_state_changed_cb (priv->tp_chat, sender,
1152                                TP_CHANNEL_CHAT_STATE_ACTIVE,
1153                                chat);
1154
1155         priv->unread_messages++;
1156         g_signal_emit (chat, signals[NEW_MESSAGE], 0, message);
1157 }
1158
1159 static void
1160 chat_message_received_cb (EmpathyTpChat  *tp_chat,
1161                           EmpathyMessage *message,
1162                           EmpathyChat    *chat)
1163 {
1164         chat_message_received (chat, message);
1165 }
1166
1167 static void
1168 chat_send_error_cb (EmpathyTpChat          *tp_chat,
1169                     const gchar            *message_body,
1170                     TpChannelTextSendError  error_code,
1171                     EmpathyChat            *chat)
1172 {
1173         const gchar *error;
1174         gchar       *str;
1175
1176         switch (error_code) {
1177         case TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE:
1178                 error = _("offline");
1179                 break;
1180         case TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT:
1181                 error = _("invalid contact");
1182                 break;
1183         case TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED:
1184                 error = _("permission denied");
1185                 break;
1186         case TP_CHANNEL_TEXT_SEND_ERROR_TOO_LONG:
1187                 error = _("too long message");
1188                 break;
1189         case TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED:
1190                 error = _("not implemented");
1191                 break;
1192         default:
1193                 error = _("unknown");
1194                 break;
1195         }
1196
1197         str = g_strdup_printf (_("Error sending message '%s': %s"),
1198                                message_body,
1199                                error);
1200         empathy_chat_view_append_event (chat->view, str);
1201         g_free (str);
1202 }
1203
1204 /* WARNING: EXPLICIT CONTENT, keep away childrens!
1205  *
1206  * When a GtkLabel is set to wrap, it assume and hardcoded width. To change
1207  * that width we have to set a size request on the label... but that's not
1208  * possible because we want the window to be able to shrink, so we MUST request
1209  * width of 1. Note that the height of a wrapping label depends on its width.
1210  *
1211  * To work around that, here is what happens:
1212  * 1) size-request is first called, an hardcoded small width is requested by
1213  *    GtkLabel, which means also a too big height. We do nothing.
1214  * 2) size-allocate is called with the full width available, that's the width
1215  *    we really want to make wrap the label. We save that width and restart a
1216  *    size-request/size-allocate round.
1217  * 3) size-request is called a 2nd time, now we can tell the pango layout its
1218  *    width (we can't do that in step 2 because GtkLabel::size-request recreate
1219  *    the layout each time). When the layout has its width, we can know the
1220  *    height of the label and set its requisition. The width request is set to
1221  *    1px to make sure the window can shrink, the layout will fill all the
1222  *    available width anyway.
1223  */
1224 static void
1225 chat_topic_label_size_request_cb (GtkLabel *label,
1226                                    GtkRequisition *requisition,
1227                                    EmpathyChat *chat)
1228 {
1229         EmpathyChatPriv *priv = GET_PRIV (chat);
1230
1231         if (gtk_label_get_line_wrap (label) && priv->topic_width > 0) {
1232                 PangoLayout *layout;
1233                 PangoRectangle rect;
1234                 gint ypad;
1235
1236                 layout = gtk_label_get_layout (label);
1237                 pango_layout_set_width (layout, priv->topic_width * PANGO_SCALE);
1238                 pango_layout_get_extents (layout, NULL, &rect);
1239                 gtk_misc_get_padding (GTK_MISC (label), NULL, &ypad);
1240
1241                 requisition->width = 1;
1242                 requisition->height = PANGO_PIXELS (rect.height) + ypad * 2;
1243         }
1244 }
1245
1246 static void
1247 chat_topic_label_size_allocate_cb (GtkLabel *label,
1248                                    GtkAllocation *allocation,
1249                                    EmpathyChat *chat)
1250 {
1251         EmpathyChatPriv *priv = GET_PRIV (chat);
1252
1253         if (!gtk_label_get_line_wrap (label)) {
1254                 priv->topic_width = -1;
1255
1256                 if (pango_layout_is_ellipsized (gtk_label_get_layout (label)))
1257                         gtk_widget_show (priv->expander_topic);
1258                 else
1259                         gtk_widget_hide (priv->expander_topic);
1260
1261                 return;
1262         }
1263
1264         if (priv->topic_width != allocation->width) {
1265                 priv->topic_width = allocation->width;
1266                 gtk_widget_queue_resize (GTK_WIDGET (label));
1267         }
1268 }
1269
1270 static void
1271 chat_topic_expander_activate_cb (GtkExpander *expander,
1272                                  GParamSpec *param_spec,
1273                                  EmpathyChat *chat)
1274 {
1275         EmpathyChatPriv *priv = GET_PRIV (chat);
1276
1277         if (gtk_expander_get_expanded (expander)) {
1278                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_NONE);
1279                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), TRUE);
1280         } else {
1281                 gtk_label_set_ellipsize (GTK_LABEL (priv->label_topic), PANGO_ELLIPSIZE_END);
1282                 gtk_label_set_line_wrap (GTK_LABEL (priv->label_topic), FALSE);
1283         }
1284 }
1285
1286 static void
1287 chat_property_changed_cb (EmpathyTpChat *tp_chat,
1288                           const gchar   *name,
1289                           GValue        *value,
1290                           EmpathyChat   *chat)
1291 {
1292         EmpathyChatPriv *priv = GET_PRIV (chat);
1293
1294         if (!tp_strdiff (name, "subject")) {
1295                 g_free (priv->subject);
1296                 priv->subject = g_value_dup_string (value);
1297                 g_object_notify (G_OBJECT (chat), "subject");
1298
1299                 if (EMP_STR_EMPTY (priv->subject)) {
1300                         gtk_widget_hide (priv->hbox_topic);
1301                 } else {
1302                         gchar *markup_topic;
1303                         gchar *markup_text;
1304
1305                         markup_topic = empathy_add_link_markup (priv->subject);
1306                         markup_text = g_strdup_printf ("<span weight=\"bold\">%s</span> %s",
1307                                 _("Topic:"), markup_topic);
1308
1309                         gtk_label_set_markup (GTK_LABEL (priv->label_topic), markup_text);
1310                         g_free (markup_text);
1311                         g_free (markup_topic);
1312
1313                         gtk_widget_show (priv->hbox_topic);
1314                 }
1315                 if (priv->block_events_timeout_id == 0) {
1316                         gchar *str;
1317
1318                         if (!EMP_STR_EMPTY (priv->subject)) {
1319                                 str = g_strdup_printf (_("Topic set to: %s"), priv->subject);
1320                         } else {
1321                                 str = g_strdup (_("No topic defined"));
1322                         }
1323                         empathy_chat_view_append_event (EMPATHY_CHAT (chat)->view, str);
1324                         g_free (str);
1325                 }
1326         }
1327         else if (!tp_strdiff (name, "name")) {
1328                 g_free (priv->name);
1329                 priv->name = g_value_dup_string (value);
1330                 g_object_notify (G_OBJECT (chat), "name");
1331         }
1332 }
1333
1334 static void
1335 chat_input_text_buffer_changed_cb (GtkTextBuffer *buffer,
1336                                    EmpathyChat    *chat)
1337 {
1338         GtkTextIter     start, end;
1339         gchar          *str;
1340         gboolean        spell_checker = FALSE;
1341
1342         if (gtk_text_buffer_get_char_count (buffer) == 0) {
1343                 chat_composing_stop (chat);
1344         } else {
1345                 chat_composing_start (chat);
1346         }
1347
1348         empathy_conf_get_bool (empathy_conf_get (),
1349                            EMPATHY_PREFS_CHAT_SPELL_CHECKER_ENABLED,
1350                            &spell_checker);
1351
1352         gtk_text_buffer_get_start_iter (buffer, &start);
1353
1354         if (!spell_checker) {
1355                 gtk_text_buffer_get_end_iter (buffer, &end);
1356                 gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
1357                 return;
1358         }
1359
1360         if (!empathy_spell_supported ()) {
1361                 return;
1362         }
1363
1364         /* NOTE: this is really inefficient, we shouldn't have to
1365            reiterate the whole buffer each time and check each work
1366            every time. */
1367         while (TRUE) {
1368                 gboolean correct = FALSE;
1369
1370                 /* if at start */
1371                 if (gtk_text_iter_is_start (&start)) {
1372                         end = start;
1373
1374                         if (!gtk_text_iter_forward_word_end (&end)) {
1375                                 /* no whole word yet */
1376                                 break;
1377                         }
1378                 } else {
1379                         if (!gtk_text_iter_forward_word_end (&end)) {
1380                                 /* must be the end of the buffer */
1381                                 break;
1382                         }
1383
1384                         start = end;
1385                         gtk_text_iter_backward_word_start (&start);
1386                 }
1387
1388                 str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1389
1390                 /* spell check string if not a command */
1391                 if (str[0] != '/') {
1392                         correct = empathy_spell_check (str);
1393                 } else {
1394                         correct = TRUE;
1395                 }
1396
1397                 if (!correct) {
1398                         gtk_text_buffer_apply_tag_by_name (buffer, "misspelled", &start, &end);
1399                 } else {
1400                         gtk_text_buffer_remove_tag_by_name (buffer, "misspelled", &start, &end);
1401                 }
1402
1403                 g_free (str);
1404
1405                 /* set start iter to the end iters position */
1406                 start = end;
1407         }
1408 }
1409
1410 static gboolean
1411 empathy_isspace_cb (gunichar c,
1412                  gpointer data)
1413 {
1414         return g_unichar_isspace (c);
1415 }
1416
1417 static gboolean
1418 chat_input_key_press_event_cb (GtkWidget   *widget,
1419                                GdkEventKey *event,
1420                                EmpathyChat *chat)
1421 {
1422         EmpathyChatPriv *priv;
1423         GtkAdjustment  *adj;
1424         gdouble         val;
1425         GtkWidget      *text_view_sw;
1426
1427         priv = GET_PRIV (chat);
1428
1429         /* Catch ctrl+up/down so we can traverse messages we sent */
1430         if ((event->state & GDK_CONTROL_MASK) &&
1431             (event->keyval == GDK_Up ||
1432              event->keyval == GDK_Down)) {
1433                 GtkTextBuffer *buffer;
1434                 const gchar   *str;
1435
1436                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1437                 chat_input_history_update (chat, buffer);
1438
1439                 if (event->keyval == GDK_Up) {
1440                         str = chat_input_history_get_next (chat);
1441                 } else {
1442                         str = chat_input_history_get_prev (chat);
1443                 }
1444
1445                 g_signal_handlers_block_by_func (buffer,
1446                                                  chat_input_text_buffer_changed_cb,
1447                                                  chat);
1448                 gtk_text_buffer_set_text (buffer, str ? str : "", -1);
1449                 g_signal_handlers_unblock_by_func (buffer,
1450                                                    chat_input_text_buffer_changed_cb,
1451                                                    chat);
1452
1453                 return TRUE;
1454         }
1455
1456         /* Catch enter but not ctrl/shift-enter */
1457         if (IS_ENTER (event->keyval) &&
1458             !(event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1459                 GtkTextView *view;
1460
1461                 /* This is to make sure that kinput2 gets the enter. And if
1462                  * it's handled there we shouldn't send on it. This is because
1463                  * kinput2 uses Enter to commit letters. See:
1464                  * http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=104299
1465                  */
1466
1467                 view = GTK_TEXT_VIEW (chat->input_text_view);
1468                 if (gtk_im_context_filter_keypress (view->im_context, event)) {
1469                         GTK_TEXT_VIEW (chat->input_text_view)->need_im_reset = TRUE;
1470                         return TRUE;
1471                 }
1472
1473                 chat_input_text_view_send (chat);
1474                 return TRUE;
1475         }
1476
1477         text_view_sw = gtk_widget_get_parent (GTK_WIDGET (chat->view));
1478
1479         if (IS_ENTER (event->keyval) &&
1480             (event->state & (GDK_SHIFT_MASK | GDK_CONTROL_MASK))) {
1481                 /* Newline for shift/control-enter. */
1482                 return FALSE;
1483         }
1484         if (!(event->state & GDK_CONTROL_MASK) &&
1485             event->keyval == GDK_Page_Up) {
1486                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1487                 gtk_adjustment_set_value (adj, gtk_adjustment_get_value (adj) - gtk_adjustment_get_page_size (adj));
1488                 return TRUE;
1489         }
1490         if ((event->state & GDK_CONTROL_MASK) != GDK_CONTROL_MASK &&
1491             event->keyval == GDK_Page_Down) {
1492                 adj = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (text_view_sw));
1493                 val = MIN (gtk_adjustment_get_value (adj) + gtk_adjustment_get_page_size (adj),
1494                            gtk_adjustment_get_upper (adj) - gtk_adjustment_get_page_size (adj));
1495                 gtk_adjustment_set_value (adj, val);
1496                 return TRUE;
1497         }
1498         if (event->keyval == GDK_Escape) {
1499                 empathy_search_bar_hide (EMPATHY_SEARCH_BAR (priv->search_bar));
1500         }
1501         if (!(event->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK)) &&
1502             event->keyval == GDK_Tab) {
1503                 GtkTextBuffer *buffer;
1504                 GtkTextIter    start, current;
1505                 gchar         *nick, *completed;
1506                 GList         *list, *completed_list;
1507                 gboolean       is_start_of_buffer;
1508
1509                 buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (EMPATHY_CHAT (chat)->input_text_view));
1510                 gtk_text_buffer_get_iter_at_mark (buffer, &current, gtk_text_buffer_get_insert (buffer));
1511
1512                 /* Get the start of the nick to complete. */
1513                 gtk_text_buffer_get_iter_at_mark (buffer, &start, gtk_text_buffer_get_insert (buffer));
1514                 if (gtk_text_iter_backward_find_char (&start, &empathy_isspace_cb, NULL, NULL)) {
1515                         gtk_text_iter_set_offset (&start, gtk_text_iter_get_offset (&start) + 1);
1516                 }
1517                 is_start_of_buffer = gtk_text_iter_is_start (&start);
1518
1519                 list = empathy_contact_list_get_members (EMPATHY_CONTACT_LIST (priv->tp_chat));
1520                 g_completion_add_items (priv->completion, list);
1521
1522                 nick = gtk_text_buffer_get_text (buffer, &start, &current, FALSE);
1523                 completed_list = g_completion_complete (priv->completion,
1524                                                         nick,
1525                                                         &completed);
1526
1527                 g_free (nick);
1528
1529                 if (completed) {
1530                         guint        len;
1531                         const gchar *text;
1532                         gchar       *complete_char = NULL;
1533                         GString     *message = NULL;
1534                         GList       *l;
1535
1536                         gtk_text_buffer_delete (buffer, &start, &current);
1537
1538                         len = g_list_length (completed_list);
1539
1540                         if (len == 1) {
1541                                 /* If we only have one hit, use that text
1542                                  * instead of the text in completed since the
1543                                  * completed text will use the typed string
1544                                  * which might be cased all wrong.
1545                                  * Fixes #120876
1546                                  * */
1547                                 text = empathy_contact_get_name (completed_list->data);
1548                         } else {
1549                                 text = completed;
1550
1551                                 /* Print all hits to the scrollback view, so the
1552                                  * user knows what possibilities he has.
1553                                  * Fixes #599779
1554                                  * */
1555                                  message = g_string_new ("");
1556                                  for (l = completed_list; l != NULL; l = l->next) {
1557                                         g_string_append (message, empathy_contact_get_name (l->data));
1558                                         g_string_append (message, " - ");
1559                                  }
1560                                  empathy_chat_view_append_event (chat->view, message->str);
1561                                  g_string_free (message, TRUE);
1562                         }
1563
1564                         gtk_text_buffer_insert_at_cursor (buffer, text, strlen (text));
1565
1566                         if (len == 1 && is_start_of_buffer &&
1567                             empathy_conf_get_string (empathy_conf_get (),
1568                                                      EMPATHY_PREFS_CHAT_NICK_COMPLETION_CHAR,
1569                                                      &complete_char) &&
1570                             complete_char != NULL) {
1571                                 gtk_text_buffer_insert_at_cursor (buffer,
1572                                                                   complete_char,
1573                                                                   strlen (complete_char));
1574                                 gtk_text_buffer_insert_at_cursor (buffer, " ", 1);
1575                                 g_free (complete_char);
1576                         }
1577
1578                         g_free (completed);
1579                 }
1580
1581                 g_completion_clear_items (priv->completion);
1582
1583                 g_list_foreach (list, (GFunc) g_object_unref, NULL);
1584                 g_list_free (list);
1585
1586                 return TRUE;
1587         }
1588
1589         return FALSE;
1590 }
1591
1592 static gboolean
1593 chat_text_view_focus_in_event_cb (GtkWidget  *widget,
1594                                   GdkEvent   *event,
1595                                   EmpathyChat *chat)
1596 {
1597         gtk_widget_grab_focus (chat->input_text_view);
1598
1599         return TRUE;
1600 }
1601
1602 static gboolean
1603 chat_input_set_size_request_idle (gpointer sw)
1604 {
1605         gtk_widget_set_size_request (sw, -1, MAX_INPUT_HEIGHT);
1606
1607         return FALSE;
1608 }
1609
1610 static void
1611 chat_input_size_request_cb (GtkWidget      *widget,
1612                             GtkRequisition *requisition,
1613                             EmpathyChat    *chat)
1614 {
1615         EmpathyChatPriv *priv = GET_PRIV (chat);
1616         GtkWidget       *sw;
1617
1618         sw = gtk_widget_get_parent (widget);
1619         if (requisition->height >= MAX_INPUT_HEIGHT && !priv->has_input_vscroll) {
1620                 g_idle_add (chat_input_set_size_request_idle, sw);
1621                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
1622                                                 GTK_POLICY_NEVER,
1623                                                 GTK_POLICY_ALWAYS);
1624                 priv->has_input_vscroll = TRUE;
1625         }
1626
1627         if (requisition->height < MAX_INPUT_HEIGHT && priv->has_input_vscroll) {
1628                 gtk_widget_set_size_request (sw, -1, -1);
1629                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw),
1630                                                 GTK_POLICY_NEVER,
1631                                                 GTK_POLICY_NEVER);
1632                 priv->has_input_vscroll = FALSE;
1633         }
1634 }
1635
1636 static void
1637 chat_input_realize_cb (GtkWidget   *widget,
1638                        EmpathyChat *chat)
1639 {
1640         DEBUG ("Setting focus to the input text view");
1641         if (gtk_widget_is_sensitive (widget)) {
1642                 gtk_widget_grab_focus (widget);
1643         }
1644 }
1645
1646 static void
1647 chat_insert_smiley_activate_cb (EmpathySmileyManager *manager,
1648                                 EmpathySmiley        *smiley,
1649                                 gpointer              user_data)
1650 {
1651         EmpathyChat   *chat = EMPATHY_CHAT (user_data);
1652         GtkTextBuffer *buffer;
1653         GtkTextIter    iter;
1654
1655         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
1656
1657         gtk_text_buffer_get_end_iter (buffer, &iter);
1658         gtk_text_buffer_insert (buffer, &iter, smiley->str, -1);
1659
1660         gtk_text_buffer_get_end_iter (buffer, &iter);
1661         gtk_text_buffer_insert (buffer, &iter, " ", -1);
1662 }
1663
1664 typedef struct {
1665         EmpathyChat  *chat;
1666         gchar       *word;
1667
1668         GtkTextIter  start;
1669         GtkTextIter  end;
1670 } EmpathyChatSpell;
1671
1672 static EmpathyChatSpell *
1673 chat_spell_new (EmpathyChat  *chat,
1674                 const gchar *word,
1675                 GtkTextIter  start,
1676                 GtkTextIter  end)
1677 {
1678         EmpathyChatSpell *chat_spell;
1679
1680         chat_spell = g_slice_new0 (EmpathyChatSpell);
1681
1682         chat_spell->chat = g_object_ref (chat);
1683         chat_spell->word = g_strdup (word);
1684         chat_spell->start = start;
1685         chat_spell->end = end;
1686
1687         return chat_spell;
1688 }
1689
1690 static void
1691 chat_spell_free (EmpathyChatSpell *chat_spell)
1692 {
1693         g_object_unref (chat_spell->chat);
1694         g_free (chat_spell->word);
1695         g_slice_free (EmpathyChatSpell, chat_spell);
1696 }
1697
1698 static void
1699 chat_spelling_menu_activate_cb (GtkMenuItem     *menu_item,
1700                                                 EmpathyChatSpell *chat_spell)
1701 {
1702     empathy_chat_correct_word (chat_spell->chat,
1703                                &(chat_spell->start),
1704                                &(chat_spell->end),
1705                                gtk_menu_item_get_label (menu_item));
1706 }
1707
1708 static GtkWidget *
1709 chat_spelling_build_menu (EmpathyChatSpell *chat_spell)
1710 {
1711     GtkWidget *menu, *menu_item;
1712     GList     *suggestions, *l;
1713
1714     menu = gtk_menu_new ();
1715     suggestions = empathy_spell_get_suggestions (chat_spell->word);
1716     if (suggestions == NULL) {
1717         menu_item = gtk_menu_item_new_with_label (_("(No Suggestions)"));
1718         gtk_widget_set_sensitive (menu_item, FALSE);
1719         gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
1720     } else {
1721         for (l = suggestions; l; l = l->next) {
1722             menu_item = gtk_menu_item_new_with_label (l->data);
1723             g_signal_connect (G_OBJECT (menu_item),
1724                           "activate",
1725                           G_CALLBACK (chat_spelling_menu_activate_cb),
1726                           chat_spell);
1727             gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
1728         }
1729     }
1730     empathy_spell_free_suggestions (suggestions);
1731
1732     gtk_widget_show_all (menu);
1733
1734     return menu;
1735 }
1736
1737 static void
1738 chat_text_send_cb (GtkMenuItem *menuitem,
1739                    EmpathyChat *chat)
1740 {
1741         chat_input_text_view_send (chat);
1742 }
1743
1744 static void
1745 chat_input_populate_popup_cb (GtkTextView *view,
1746                               GtkMenu     *menu,
1747                               EmpathyChat *chat)
1748 {
1749         EmpathyChatPriv      *priv;
1750         GtkTextBuffer        *buffer;
1751         GtkTextTagTable      *table;
1752         GtkTextTag           *tag;
1753         gint                  x, y;
1754         GtkTextIter           iter, start, end;
1755         GtkWidget            *item;
1756         gchar                *str = NULL;
1757         EmpathyChatSpell     *chat_spell;
1758         GtkWidget            *spell_menu;
1759         EmpathySmileyManager *smiley_manager;
1760         GtkWidget            *smiley_menu;
1761         GtkWidget            *image;
1762
1763         priv = GET_PRIV (chat);
1764         buffer = gtk_text_view_get_buffer (view);
1765
1766         /* Add the emoticon menu. */
1767         item = gtk_separator_menu_item_new ();
1768         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1769         gtk_widget_show (item);
1770
1771         item = gtk_image_menu_item_new_with_mnemonic (_("Insert Smiley"));
1772         image = gtk_image_new_from_icon_name ("face-smile",
1773                                               GTK_ICON_SIZE_MENU);
1774         gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
1775         gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1776         gtk_widget_show (item);
1777
1778         smiley_manager = empathy_smiley_manager_dup_singleton ();
1779         smiley_menu = empathy_smiley_menu_new (smiley_manager,
1780                                                chat_insert_smiley_activate_cb,
1781                                                chat);
1782         gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), smiley_menu);
1783         g_object_unref (smiley_manager);
1784
1785         /* Add the Send menu item. */
1786         gtk_text_buffer_get_bounds (buffer, &start, &end);
1787         str = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
1788         if (!EMP_STR_EMPTY (str)) {
1789                 item = gtk_menu_item_new_with_mnemonic (_("_Send"));
1790                 g_signal_connect (G_OBJECT (item), "activate",
1791                                   G_CALLBACK (chat_text_send_cb), chat);
1792                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1793                 gtk_widget_show (item);
1794         }
1795         str = NULL;
1796
1797         /* Add the spell check menu item. */
1798         table = gtk_text_buffer_get_tag_table (buffer);
1799         tag = gtk_text_tag_table_lookup (table, "misspelled");
1800         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
1801         gtk_text_view_window_to_buffer_coords (GTK_TEXT_VIEW (view),
1802                                                GTK_TEXT_WINDOW_WIDGET,
1803                                                x, y,
1804                                                &x, &y);
1805         gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW (view), &iter, x, y);
1806         start = end = iter;
1807         if (gtk_text_iter_backward_to_tag_toggle (&start, tag) &&
1808             gtk_text_iter_forward_to_tag_toggle (&end, tag)) {
1809
1810                 str = gtk_text_buffer_get_text (buffer,
1811                                                 &start, &end, FALSE);
1812         }
1813         if (!EMP_STR_EMPTY (str)) {
1814                 chat_spell = chat_spell_new (chat, str, start, end);
1815                 g_object_set_data_full (G_OBJECT (menu),
1816                                         "chat_spell", chat_spell,
1817                                         (GDestroyNotify) chat_spell_free);
1818
1819                 item = gtk_separator_menu_item_new ();
1820                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1821                 gtk_widget_show (item);
1822
1823                 item = gtk_image_menu_item_new_with_mnemonic (_("_Spelling Suggestions"));
1824                 image = gtk_image_new_from_icon_name (GTK_STOCK_SPELL_CHECK,
1825                                                       GTK_ICON_SIZE_MENU);
1826                 gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image);
1827
1828                 spell_menu = chat_spelling_build_menu (chat_spell);
1829                 gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), spell_menu);
1830
1831                 gtk_menu_shell_prepend (GTK_MENU_SHELL (menu), item);
1832                 gtk_widget_show (item);
1833         }
1834 }
1835
1836
1837 #ifdef ENABLE_TPL
1838 static gboolean
1839 chat_log_filter (TplLogEntry *log,
1840                  gpointer user_data)
1841 #else
1842 static gboolean
1843 chat_log_filter (EmpathyMessage *message,
1844                  gpointer user_data)
1845 #endif /* ENABLE_TPL */
1846 {
1847         EmpathyChat *chat = user_data;
1848 #ifdef ENABLE_TPL
1849         EmpathyMessage *message;
1850 #endif /* ENABLE_TPL */
1851         EmpathyChatPriv *priv = GET_PRIV (chat);
1852         const GList *pending;
1853
1854 #ifdef ENABLE_TPL
1855         g_return_val_if_fail (TPL_IS_LOG_ENTRY (log), FALSE);
1856 #else
1857         g_return_val_if_fail (EMPATHY_IS_MESSAGE (message), FALSE);
1858 #endif /* ENABLE_TPL */
1859         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
1860
1861         pending = empathy_tp_chat_get_pending_messages (priv->tp_chat);
1862 #ifdef ENABLE_TPL
1863         message = empathy_message_from_tpl_log_entry (log);
1864 #endif /* ENABLE_TPL */
1865
1866         for (; pending; pending = g_list_next (pending)) {
1867                 if (empathy_message_equal (message, pending->data)) {
1868                         return FALSE;
1869                 }
1870         }
1871 #ifdef ENABLE_TPL
1872         g_object_unref (message);
1873 #endif
1874         return TRUE;
1875 }
1876
1877
1878 static void
1879 show_pending_messages (EmpathyChat *chat) {
1880         EmpathyChatPriv *priv = GET_PRIV (chat);
1881         const GList *messages, *l;
1882
1883         g_return_if_fail (EMPATHY_IS_CHAT (chat));
1884
1885         if (chat->view == NULL || priv->tp_chat == NULL)
1886                 return;
1887
1888         if (!priv->can_show_pending)
1889                 return;
1890
1891         messages = empathy_tp_chat_get_pending_messages (priv->tp_chat);
1892
1893         for (l = messages; l != NULL ; l = g_list_next (l)) {
1894                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
1895                 chat_message_received (chat, message);
1896         }
1897 }
1898
1899
1900 #ifdef ENABLE_TPL
1901 static void
1902 got_filtered_messages_cb (GObject *manager,
1903                 GAsyncResult *result,
1904                 gpointer user_data)
1905 {
1906         GList *l;
1907         GList *messages;
1908         EmpathyChat *chat = EMPATHY_CHAT (user_data);
1909         EmpathyChatPriv *priv = GET_PRIV (chat);
1910         GError *error = NULL;
1911
1912         messages = tpl_log_manager_get_filtered_messages_async_finish (result, &error);
1913
1914         if (error != NULL) {
1915                 DEBUG ("%s. Aborting.", error->message);
1916                 empathy_chat_view_append_event (chat->view,
1917                         _("Failed to retrieve recent logs"));
1918                 g_error_free (error);
1919                 goto out;
1920         }
1921
1922         for (l = messages; l; l = g_list_next (l)) {
1923                 EmpathyMessage *message;
1924                 g_assert (TPL_IS_LOG_ENTRY (l->data));
1925
1926                 message = empathy_message_from_tpl_log_entry (l->data);
1927                 g_object_unref (l->data);
1928
1929                 empathy_chat_view_append_message (chat->view, message);
1930                 g_object_unref (message);
1931         }
1932         g_list_free (messages);
1933
1934 out:
1935         /* in case of TPL error, skip backlog and show pending messages */
1936         priv->can_show_pending = TRUE;
1937         show_pending_messages (chat);
1938
1939         /* FIXME: See Bug#610994, we are forcing the ACK of the queue. See comments
1940          * about it in EmpathyChatPriv definition */
1941         priv->retrieving_backlogs = FALSE;
1942         empathy_chat_messages_read (chat);
1943
1944         /* Turn back on scrolling */
1945         empathy_chat_view_scroll (chat->view, TRUE);
1946 }
1947 #endif /* ENABLE_TPL */
1948
1949
1950 static void
1951 chat_add_logs (EmpathyChat *chat)
1952 {
1953         EmpathyChatPriv *priv = GET_PRIV (chat);
1954         gboolean         is_chatroom;
1955 #ifndef ENABLE_TPL
1956         GList           *messages, *l;
1957 #endif /* ENABLE_TPL */
1958
1959         if (!priv->id) {
1960                 return;
1961         }
1962
1963         /* Turn off scrolling temporarily */
1964         empathy_chat_view_scroll (chat->view, FALSE);
1965
1966         /* Add messages from last conversation */
1967         is_chatroom = priv->handle_type == TP_HANDLE_TYPE_ROOM;
1968
1969 #ifndef ENABLE_TPL
1970         messages = empathy_log_manager_get_filtered_messages (priv->log_manager,
1971                                                               priv->account,
1972                                                               priv->id,
1973                                                               is_chatroom,
1974                                                               5,
1975                                                               chat_log_filter,
1976                                                               chat);
1977
1978         for (l = messages; l; l = g_list_next (l)) {
1979                 empathy_chat_view_append_message (chat->view, l->data);
1980                 g_object_unref (l->data);
1981         }
1982
1983         g_list_free (messages);
1984
1985         /* Turn back on scrolling */
1986         empathy_chat_view_scroll (chat->view, TRUE);
1987 #else
1988         priv->retrieving_backlogs = TRUE;
1989         tpl_log_manager_get_filtered_messages_async (priv->log_manager,
1990                                                               priv->account,
1991                                                               priv->id,
1992                                                               is_chatroom,
1993                                                               5,
1994                                                               chat_log_filter,
1995                                                               chat,
1996                                                               got_filtered_messages_cb,
1997                                                               (gpointer) chat);
1998 #endif /* ENABLE_TPL */
1999 }
2000
2001 static gint
2002 chat_contacts_completion_func (const gchar *s1,
2003                                const gchar *s2,
2004                                gsize        n)
2005 {
2006         gchar *tmp, *nick1, *nick2;
2007         gint   ret;
2008
2009         if (s1 == s2) {
2010                 return 0;
2011         }
2012         if (!s1 || !s2) {
2013                 return s1 ? -1 : +1;
2014         }
2015
2016         tmp = g_utf8_normalize (s1, -1, G_NORMALIZE_DEFAULT);
2017         nick1 = g_utf8_casefold (tmp, -1);
2018         g_free (tmp);
2019
2020         tmp = g_utf8_normalize (s2, -1, G_NORMALIZE_DEFAULT);
2021         nick2 = g_utf8_casefold (tmp, -1);
2022         g_free (tmp);
2023
2024         ret = strncmp (nick1, nick2, n);
2025
2026         g_free (nick1);
2027         g_free (nick2);
2028
2029         return ret;
2030 }
2031
2032 static gchar *
2033 build_part_message (guint           reason,
2034                     const gchar    *name,
2035                     EmpathyContact *actor,
2036                     const gchar    *message)
2037 {
2038         GString *s = g_string_new ("");
2039         const gchar *actor_name = NULL;
2040
2041         if (actor != NULL) {
2042                 actor_name = empathy_contact_get_name (actor);
2043         }
2044
2045         /* Having an actor only really makes sense for a few actions... */
2046         switch (reason) {
2047         case TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE:
2048                 g_string_append_printf (s, _("%s has disconnected"), name);
2049                 break;
2050         case TP_CHANNEL_GROUP_CHANGE_REASON_KICKED:
2051                 if (actor_name != NULL) {
2052                         /* translators: reverse the order of these arguments
2053                          * if the kicked should come before the kicker in your locale.
2054                          */
2055                         g_string_append_printf (s, _("%1$s was kicked by %2$s"),
2056                                 name, actor_name);
2057                 } else {
2058                         g_string_append_printf (s, _("%s was kicked"), name);
2059                 }
2060                 break;
2061         case TP_CHANNEL_GROUP_CHANGE_REASON_BANNED:
2062                 if (actor_name != NULL) {
2063                         /* translators: reverse the order of these arguments
2064                          * if the banned should come before the banner in your locale.
2065                          */
2066                         g_string_append_printf (s, _("%1$s was banned by %2$s"),
2067                                 name, actor_name);
2068                 } else {
2069                         g_string_append_printf (s, _("%s was banned"), name);
2070                 }
2071                 break;
2072         default:
2073                 g_string_append_printf (s, _("%s has left the room"), name);
2074         }
2075
2076         if (!EMP_STR_EMPTY (message)) {
2077                 /* Note to translators: this string is appended to
2078                  * notifications like "foo has left the room", with the message
2079                  * given by the user living the room. If this poses a problem,
2080                  * please let us know. :-)
2081                  */
2082                 g_string_append_printf (s, _(" (%s)"), message);
2083         }
2084
2085         return g_string_free (s, FALSE);
2086 }
2087
2088 static void
2089 chat_members_changed_cb (EmpathyTpChat  *tp_chat,
2090                          EmpathyContact *contact,
2091                          EmpathyContact *actor,
2092                          guint           reason,
2093                          gchar          *message,
2094                          gboolean        is_member,
2095                          EmpathyChat    *chat)
2096 {
2097         EmpathyChatPriv *priv = GET_PRIV (chat);
2098         const gchar *name = empathy_contact_get_name (contact);
2099         gchar *str;
2100
2101         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED != reason);
2102
2103         if (priv->block_events_timeout_id != 0)
2104                 return;
2105
2106         if (is_member) {
2107                 str = g_strdup_printf (_("%s has joined the room"),
2108                                        name);
2109         } else {
2110                 str = build_part_message (reason, name, actor, message);
2111         }
2112
2113         empathy_chat_view_append_event (chat->view, str);
2114         g_free (str);
2115 }
2116
2117 static void
2118 chat_member_renamed_cb (EmpathyTpChat  *tp_chat,
2119                          EmpathyContact *old_contact,
2120                          EmpathyContact *new_contact,
2121                          guint           reason,
2122                          gchar          *message,
2123                          EmpathyChat    *chat)
2124 {
2125         EmpathyChatPriv *priv = GET_PRIV (chat);
2126
2127         g_return_if_fail (TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED == reason);
2128
2129         if (priv->block_events_timeout_id == 0) {
2130                 gchar *str;
2131
2132                 str = g_strdup_printf (_("%s is now known as %s"),
2133                                        empathy_contact_get_name (old_contact),
2134                                        empathy_contact_get_name (new_contact));
2135                 empathy_chat_view_append_event (chat->view, str);
2136                 g_free (str);
2137         }
2138
2139 }
2140
2141 static gboolean
2142 chat_reset_size_request (gpointer widget)
2143 {
2144         gtk_widget_set_size_request (widget, -1, -1);
2145
2146         return FALSE;
2147 }
2148
2149 static void
2150 chat_update_contacts_visibility (EmpathyChat *chat,
2151                          gboolean show)
2152 {
2153         EmpathyChatPriv *priv = GET_PRIV (chat);
2154         GtkAllocation allocation;
2155
2156         if (!priv->scrolled_window_contacts) {
2157                 return;
2158         }
2159
2160         if (priv->remote_contact != NULL) {
2161                 show = FALSE;
2162         }
2163
2164         if (show && priv->contact_list_view == NULL) {
2165                 EmpathyContactListStore *store;
2166                 gint                     min_width;
2167
2168                 /* We are adding the contact list to the chat, we don't want the
2169                  * chat view to become too small. If the chat view is already
2170                  * smaller than 250 make sure that size won't change. If the
2171                  * chat view is bigger the contact list will take some space on
2172                  * it but we make sure the chat view don't become smaller than
2173                  * 250. Relax the size request once the resize is done */
2174                 gtk_widget_get_allocation (priv->vbox_left, &allocation);
2175                 min_width = MIN (allocation.width, 250);
2176                 gtk_widget_set_size_request (priv->vbox_left, min_width, -1);
2177                 g_idle_add (chat_reset_size_request, priv->vbox_left);
2178
2179                 if (priv->contacts_width > 0) {
2180                         gtk_paned_set_position (GTK_PANED (priv->hpaned),
2181                                                 priv->contacts_width);
2182                 }
2183
2184                 store = empathy_contact_list_store_new (
2185                                 EMPATHY_CONTACT_LIST (priv->tp_chat));
2186                 empathy_contact_list_store_set_show_groups (
2187                                 EMPATHY_CONTACT_LIST_STORE (store), FALSE);
2188
2189                 priv->contact_list_view = GTK_WIDGET (empathy_contact_list_view_new (store,
2190                         EMPATHY_CONTACT_LIST_FEATURE_CONTACT_TOOLTIP,
2191                         EMPATHY_CONTACT_FEATURE_CHAT |
2192                         EMPATHY_CONTACT_FEATURE_CALL |
2193                         EMPATHY_CONTACT_FEATURE_LOG |
2194                         EMPATHY_CONTACT_FEATURE_INFO));
2195                 gtk_container_add (GTK_CONTAINER (priv->scrolled_window_contacts),
2196                                    priv->contact_list_view);
2197                 gtk_widget_show (priv->contact_list_view);
2198                 gtk_widget_show (priv->scrolled_window_contacts);
2199                 g_object_unref (store);
2200         } else if (!show) {
2201                 priv->contacts_width = gtk_paned_get_position (GTK_PANED (priv->hpaned));
2202                 gtk_widget_hide (priv->scrolled_window_contacts);
2203                 if (priv->contact_list_view != NULL) {
2204                         gtk_widget_destroy (priv->contact_list_view);
2205                         priv->contact_list_view = NULL;
2206                 }
2207         }
2208 }
2209
2210 void
2211 empathy_chat_set_show_contacts (EmpathyChat *chat,
2212                                 gboolean     show)
2213 {
2214         EmpathyChatPriv *priv = GET_PRIV (chat);
2215
2216         priv->show_contacts = show;
2217
2218         chat_update_contacts_visibility (chat, show);
2219
2220         g_object_notify (G_OBJECT (chat), "show-contacts");
2221 }
2222
2223 static void
2224 chat_remote_contact_changed_cb (EmpathyChat *chat)
2225 {
2226         EmpathyChatPriv *priv = GET_PRIV (chat);
2227
2228         if (priv->remote_contact != NULL) {
2229                 g_object_unref (priv->remote_contact);
2230                 priv->remote_contact = NULL;
2231         }
2232
2233         g_free (priv->id);
2234
2235         priv->id = g_strdup (empathy_tp_chat_get_id (priv->tp_chat));
2236         priv->remote_contact = empathy_tp_chat_get_remote_contact (priv->tp_chat);
2237         if (priv->remote_contact != NULL) {
2238                 g_object_ref (priv->remote_contact);
2239                 priv->handle_type = TP_HANDLE_TYPE_CONTACT;
2240         }
2241         else if (priv->tp_chat != NULL) {
2242                 TpChannel *channel;
2243
2244                 channel = empathy_tp_chat_get_channel (priv->tp_chat);
2245                 g_object_get (channel, "handle-type", &priv->handle_type, NULL);
2246         }
2247
2248         chat_update_contacts_visibility (chat, priv->show_contacts);
2249
2250         g_object_notify (G_OBJECT (chat), "remote-contact");
2251         g_object_notify (G_OBJECT (chat), "id");
2252 }
2253
2254 static void
2255 chat_destroy_cb (EmpathyTpChat *tp_chat,
2256                  EmpathyChat   *chat)
2257 {
2258         EmpathyChatPriv *priv;
2259
2260         priv = GET_PRIV (chat);
2261
2262         if (!priv->tp_chat) {
2263                 return;
2264         }
2265
2266         chat_composing_remove_timeout (chat);
2267         g_object_unref (priv->tp_chat);
2268         priv->tp_chat = NULL;
2269         g_object_notify (G_OBJECT (chat), "tp-chat");
2270
2271         empathy_chat_view_append_event (chat->view, _("Disconnected"));
2272         gtk_widget_set_sensitive (chat->input_text_view, FALSE);
2273
2274         chat_update_contacts_visibility (chat, FALSE);
2275 }
2276
2277 static gboolean
2278 chat_hpaned_pos_changed_cb (GtkWidget* hpaned, gpointer user_data)
2279 {
2280         gint hpaned_pos;
2281         hpaned_pos = gtk_paned_get_position (GTK_PANED(hpaned));
2282         empathy_conf_set_int (empathy_conf_get (),
2283                               EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
2284                               hpaned_pos);
2285         return TRUE;
2286 }
2287
2288 static void
2289 chat_create_ui (EmpathyChat *chat)
2290 {
2291         EmpathyChatPriv *priv = GET_PRIV (chat);
2292         GtkBuilder      *gui;
2293         GList           *list = NULL;
2294         gchar           *filename;
2295         GtkTextBuffer   *buffer;
2296         gint              paned_pos;
2297
2298         filename = empathy_file_lookup ("empathy-chat.ui",
2299                                         "libempathy-gtk");
2300         gui = empathy_builder_get_file (filename,
2301                                         "chat_widget", &priv->widget,
2302                                         "hpaned", &priv->hpaned,
2303                                         "vbox_left", &priv->vbox_left,
2304                                         "scrolled_window_chat", &priv->scrolled_window_chat,
2305                                         "scrolled_window_input", &priv->scrolled_window_input,
2306                                         "hbox_topic", &priv->hbox_topic,
2307                                         "expander_topic", &priv->expander_topic,
2308                                         "label_topic", &priv->label_topic,
2309                                         "scrolled_window_contacts", &priv->scrolled_window_contacts,
2310                                         "info_bar_vbox", &priv->info_bar_vbox,
2311                                         NULL);
2312
2313         empathy_builder_connect (gui, chat,
2314                 "expander_topic", "notify::expanded", chat_topic_expander_activate_cb,
2315                 "label_topic", "size-allocate", chat_topic_label_size_allocate_cb,
2316                 "label_topic", "size-request", chat_topic_label_size_request_cb,
2317                 NULL);
2318
2319         g_free (filename);
2320
2321         /* Add message view. */
2322         chat->view = empathy_theme_manager_create_view (empathy_theme_manager_get ());
2323         /* If this is a GtkTextView, it's set as a drag destination for text/plain
2324            and other types, even though it's non-editable and doesn't accept any
2325            drags.  This steals drag motion for anything inside the scrollbars,
2326            making drag destinations on chat windows far less useful.
2327          */
2328         gtk_drag_dest_unset (GTK_WIDGET (chat->view));
2329         g_signal_connect (chat->view, "focus_in_event",
2330                           G_CALLBACK (chat_text_view_focus_in_event_cb),
2331                           chat);
2332         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_chat),
2333                            GTK_WIDGET (chat->view));
2334         gtk_widget_show (GTK_WIDGET (chat->view));
2335
2336         /* Add input GtkTextView */
2337         chat->input_text_view = g_object_new (GTK_TYPE_TEXT_VIEW,
2338                                               "pixels-above-lines", 2,
2339                                               "pixels-below-lines", 2,
2340                                               "pixels-inside-wrap", 1,
2341                                               "right-margin", 2,
2342                                               "left-margin", 2,
2343                                               "wrap-mode", GTK_WRAP_WORD_CHAR,
2344                                               NULL);
2345         g_signal_connect (chat->input_text_view, "key-press-event",
2346                           G_CALLBACK (chat_input_key_press_event_cb),
2347                           chat);
2348         g_signal_connect (chat->input_text_view, "size-request",
2349                           G_CALLBACK (chat_input_size_request_cb),
2350                           chat);
2351         g_signal_connect (chat->input_text_view, "realize",
2352                           G_CALLBACK (chat_input_realize_cb),
2353                           chat);
2354         g_signal_connect (chat->input_text_view, "populate-popup",
2355                           G_CALLBACK (chat_input_populate_popup_cb),
2356                           chat);
2357         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
2358         tp_g_signal_connect_object  (buffer, "changed",
2359                           G_CALLBACK (chat_input_text_buffer_changed_cb),
2360                           chat, 0);
2361         gtk_text_buffer_create_tag (buffer, "misspelled",
2362                                     "underline", PANGO_UNDERLINE_ERROR,
2363                                     NULL);
2364         gtk_container_add (GTK_CONTAINER (priv->scrolled_window_input),
2365                            chat->input_text_view);
2366         gtk_widget_show (chat->input_text_view);
2367
2368         /* Add the (invisible) search bar */
2369         priv->search_bar = empathy_search_bar_new (chat->view);
2370         gtk_box_pack_start (GTK_BOX(priv->vbox_left),
2371                             priv->search_bar,
2372                             FALSE, FALSE, 0);
2373         gtk_box_reorder_child (GTK_BOX(priv->vbox_left), priv->search_bar, 1);
2374
2375         /* Initialy hide the topic, will be shown if not empty */
2376         gtk_widget_hide (priv->hbox_topic);
2377
2378         g_signal_connect (priv->hpaned, "notify::position",
2379                           G_CALLBACK (chat_hpaned_pos_changed_cb),
2380                           NULL);
2381
2382         /* Load the paned position */
2383         if (empathy_conf_get_int (empathy_conf_get (),
2384                                  EMPATHY_PREFS_UI_CHAT_WINDOW_PANED_POS,
2385                                  &paned_pos)
2386                 && paned_pos)
2387                 gtk_paned_set_position (GTK_PANED(priv->hpaned), paned_pos);
2388
2389         /* Set widget focus order */
2390         list = g_list_append (NULL, priv->search_bar);
2391         list = g_list_append (list, priv->scrolled_window_input);
2392         gtk_container_set_focus_chain (GTK_CONTAINER (priv->vbox_left), list);
2393         g_list_free (list);
2394
2395         list = g_list_append (NULL, priv->vbox_left);
2396         list = g_list_append (list, priv->scrolled_window_contacts);
2397         gtk_container_set_focus_chain (GTK_CONTAINER (priv->hpaned), list);
2398         g_list_free (list);
2399
2400         list = g_list_append (NULL, priv->hpaned);
2401         list = g_list_append (list, priv->hbox_topic);
2402         gtk_container_set_focus_chain (GTK_CONTAINER (priv->widget), list);
2403         g_list_free (list);
2404
2405         /* Add the main widget in the chat widget */
2406         gtk_container_add (GTK_CONTAINER (chat), priv->widget);
2407         g_object_unref (gui);
2408 }
2409
2410 static void
2411 chat_size_request (GtkWidget      *widget,
2412                    GtkRequisition *requisition)
2413 {
2414   GtkBin *bin = GTK_BIN (widget);
2415   GtkWidget *child;
2416
2417   requisition->width = gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2;
2418   requisition->height = gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2;
2419
2420   child = gtk_bin_get_child (bin);
2421
2422   if (child && gtk_widget_get_visible (child))
2423     {
2424       GtkRequisition child_requisition;
2425
2426       gtk_widget_size_request (child, &child_requisition);
2427
2428       requisition->width += child_requisition.width;
2429       requisition->height += child_requisition.height;
2430     }
2431 }
2432
2433 static void
2434 chat_size_allocate (GtkWidget     *widget,
2435                     GtkAllocation *allocation)
2436 {
2437   GtkBin *bin = GTK_BIN (widget);
2438   GtkAllocation child_allocation;
2439   GtkWidget *child;
2440
2441   gtk_widget_set_allocation (widget, allocation);
2442
2443   child = gtk_bin_get_child (bin);
2444
2445   if (child && gtk_widget_get_visible (child))
2446     {
2447       child_allocation.x = allocation->x + gtk_container_get_border_width (GTK_CONTAINER (widget));
2448       child_allocation.y = allocation->y + gtk_container_get_border_width (GTK_CONTAINER (widget));
2449       child_allocation.width = MAX (allocation->width - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2450       child_allocation.height = MAX (allocation->height - gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2, 0);
2451
2452       gtk_widget_size_allocate (child, &child_allocation);
2453     }
2454 }
2455
2456 static void
2457 chat_finalize (GObject *object)
2458 {
2459         EmpathyChat     *chat;
2460         EmpathyChatPriv *priv;
2461
2462         chat = EMPATHY_CHAT (object);
2463         priv = GET_PRIV (chat);
2464
2465         DEBUG ("Finalized: %p", object);
2466
2467         g_list_foreach (priv->input_history, (GFunc) chat_input_history_entry_free, NULL);
2468         g_list_free (priv->input_history);
2469
2470         g_list_foreach (priv->compositors, (GFunc) g_object_unref, NULL);
2471         g_list_free (priv->compositors);
2472
2473         chat_composing_remove_timeout (chat);
2474
2475         g_object_unref (priv->account_manager);
2476         g_object_unref (priv->log_manager);
2477
2478         if (priv->tp_chat) {
2479                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2480                         chat_destroy_cb, chat);
2481                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2482                         chat_message_received_cb, chat);
2483                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2484                         chat_send_error_cb, chat);
2485                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2486                         chat_state_changed_cb, chat);
2487                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2488                         chat_property_changed_cb, chat);
2489                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2490                         chat_members_changed_cb, chat);
2491                 g_signal_handlers_disconnect_by_func (priv->tp_chat,
2492                         chat_remote_contact_changed_cb, chat);
2493                 empathy_tp_chat_leave (priv->tp_chat);
2494                 g_object_unref (priv->tp_chat);
2495         }
2496         if (priv->account) {
2497                 g_object_unref (priv->account);
2498         }
2499         if (priv->remote_contact) {
2500                 g_object_unref (priv->remote_contact);
2501         }
2502
2503         if (priv->block_events_timeout_id) {
2504                 g_source_remove (priv->block_events_timeout_id);
2505         }
2506
2507         g_free (priv->id);
2508         g_free (priv->name);
2509         g_free (priv->subject);
2510         g_completion_free (priv->completion);
2511
2512         G_OBJECT_CLASS (empathy_chat_parent_class)->finalize (object);
2513 }
2514
2515 static void
2516 chat_constructed (GObject *object)
2517 {
2518         EmpathyChat *chat = EMPATHY_CHAT (object);
2519         EmpathyChatPriv *priv = GET_PRIV (chat);
2520
2521         if (priv->handle_type != TP_HANDLE_TYPE_ROOM)
2522                 chat_add_logs (chat);
2523 #ifndef ENABLE_TPL
2524         /* When async API are involved, pending message are shown at the end of the
2525          * callbacks' chain fired by chat_add_logs */
2526         priv->can_show_pending = TRUE;
2527         show_pending_messages (chat);
2528 #endif /* ENABLE_TPL */
2529 }
2530
2531 static void
2532 empathy_chat_class_init (EmpathyChatClass *klass)
2533 {
2534         GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
2535         GObjectClass   *object_class = G_OBJECT_CLASS (klass);
2536
2537         object_class->finalize = chat_finalize;
2538         object_class->get_property = chat_get_property;
2539         object_class->set_property = chat_set_property;
2540         object_class->constructed = chat_constructed;
2541
2542         widget_class->size_request = chat_size_request;
2543         widget_class->size_allocate = chat_size_allocate;
2544
2545         g_object_class_install_property (object_class,
2546                                          PROP_TP_CHAT,
2547                                          g_param_spec_object ("tp-chat",
2548                                                               "Empathy tp chat",
2549                                                               "The tp chat object",
2550                                                               EMPATHY_TYPE_TP_CHAT,
2551                                                               G_PARAM_CONSTRUCT |
2552                                                               G_PARAM_READWRITE |
2553                                                               G_PARAM_STATIC_STRINGS));
2554         g_object_class_install_property (object_class,
2555                                          PROP_ACCOUNT,
2556                                          g_param_spec_object ("account",
2557                                                               "Account of the chat",
2558                                                               "The account of the chat",
2559                                                               TP_TYPE_ACCOUNT,
2560                                                               G_PARAM_READABLE |
2561                                                               G_PARAM_STATIC_STRINGS));
2562         g_object_class_install_property (object_class,
2563                                          PROP_ID,
2564                                          g_param_spec_string ("id",
2565                                                               "Chat's id",
2566                                                               "The id of the chat",
2567                                                               NULL,
2568                                                               G_PARAM_READABLE |
2569                                                               G_PARAM_STATIC_STRINGS));
2570         g_object_class_install_property (object_class,
2571                                          PROP_NAME,
2572                                          g_param_spec_string ("name",
2573                                                               "Chat's name",
2574                                                               "The name of the chat",
2575                                                               NULL,
2576                                                               G_PARAM_READABLE |
2577                                                               G_PARAM_STATIC_STRINGS));
2578         g_object_class_install_property (object_class,
2579                                          PROP_SUBJECT,
2580                                          g_param_spec_string ("subject",
2581                                                               "Chat's subject",
2582                                                               "The subject or topic of the chat",
2583                                                               NULL,
2584                                                               G_PARAM_READABLE |
2585                                                               G_PARAM_STATIC_STRINGS));
2586         g_object_class_install_property (object_class,
2587                                          PROP_REMOTE_CONTACT,
2588                                          g_param_spec_object ("remote-contact",
2589                                                               "The remote contact",
2590                                                               "The remote contact is any",
2591                                                               EMPATHY_TYPE_CONTACT,
2592                                                               G_PARAM_READABLE |
2593                                                               G_PARAM_STATIC_STRINGS));
2594         g_object_class_install_property (object_class,
2595                                          PROP_SHOW_CONTACTS,
2596                                          g_param_spec_boolean ("show-contacts",
2597                                                                "Contacts' visibility",
2598                                                                "The visibility of the contacts' list",
2599                                                                TRUE,
2600                                                                G_PARAM_READWRITE |
2601                                                                G_PARAM_STATIC_STRINGS));
2602
2603         signals[COMPOSING] =
2604                 g_signal_new ("composing",
2605                               G_OBJECT_CLASS_TYPE (object_class),
2606                               G_SIGNAL_RUN_LAST,
2607                               0,
2608                               NULL, NULL,
2609                               g_cclosure_marshal_VOID__BOOLEAN,
2610                               G_TYPE_NONE,
2611                               1, G_TYPE_BOOLEAN);
2612
2613         signals[NEW_MESSAGE] =
2614                 g_signal_new ("new-message",
2615                               G_OBJECT_CLASS_TYPE (object_class),
2616                               G_SIGNAL_RUN_LAST,
2617                               0,
2618                               NULL, NULL,
2619                               g_cclosure_marshal_VOID__OBJECT,
2620                               G_TYPE_NONE,
2621                               1, EMPATHY_TYPE_MESSAGE);
2622
2623         g_type_class_add_private (object_class, sizeof (EmpathyChatPriv));
2624 }
2625
2626 static gboolean
2627 chat_block_events_timeout_cb (gpointer data)
2628 {
2629         EmpathyChatPriv *priv = GET_PRIV (data);
2630
2631         priv->block_events_timeout_id = 0;
2632
2633         return FALSE;
2634 }
2635
2636 static void
2637 account_manager_prepared_cb (GObject *source_object,
2638                              GAsyncResult *result,
2639                              gpointer user_data)
2640 {
2641         GList *accounts, *l;
2642         TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
2643         EmpathyChat *chat = user_data;
2644         GError *error = NULL;
2645
2646         if (!tp_account_manager_prepare_finish (account_manager, result, &error)) {
2647                 DEBUG ("Failed to prepare the account manager: %s", error->message);
2648                 g_error_free (error);
2649                 return;
2650         }
2651
2652         accounts = tp_account_manager_get_valid_accounts (account_manager);
2653
2654         for (l = accounts; l != NULL; l = l->next) {
2655                 TpAccount *account = l->data;
2656                 tp_g_signal_connect_object (account, "status-changed",
2657                                              G_CALLBACK (chat_new_connection_cb),
2658                                              chat, 0);
2659         }
2660
2661         g_list_free (accounts);
2662 }
2663
2664 static void
2665 empathy_chat_init (EmpathyChat *chat)
2666 {
2667         EmpathyChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
2668                 EMPATHY_TYPE_CHAT, EmpathyChatPriv);
2669
2670         chat->priv = priv;
2671 #ifndef ENABLE_TPL
2672         priv->log_manager = empathy_log_manager_dup_singleton ();
2673 #else
2674         priv->log_manager = tpl_log_manager_dup_singleton ();
2675 #endif /* ENABLE_TPL */
2676         priv->contacts_width = -1;
2677         priv->input_history = NULL;
2678         priv->input_history_current = NULL;
2679         priv->account_manager = tp_account_manager_dup ();
2680
2681         tp_account_manager_prepare_async (priv->account_manager, NULL,
2682                                           account_manager_prepared_cb, chat);
2683
2684         empathy_conf_get_bool (empathy_conf_get (),
2685                                EMPATHY_PREFS_CHAT_SHOW_CONTACTS_IN_ROOMS,
2686                                &priv->show_contacts);
2687
2688         /* Block events for some time to avoid having "has come online" or
2689          * "joined" messages. */
2690         priv->block_events_timeout_id =
2691                 g_timeout_add_seconds (1, chat_block_events_timeout_cb, chat);
2692
2693         /* Add nick name completion */
2694         priv->completion = g_completion_new ((GCompletionFunc) empathy_contact_get_name);
2695         g_completion_set_compare (priv->completion, chat_contacts_completion_func);
2696
2697         chat_create_ui (chat);
2698 }
2699
2700 EmpathyChat *
2701 empathy_chat_new (EmpathyTpChat *tp_chat)
2702 {
2703         return g_object_new (EMPATHY_TYPE_CHAT, "tp-chat", tp_chat, NULL);
2704 }
2705
2706 EmpathyTpChat *
2707 empathy_chat_get_tp_chat (EmpathyChat *chat)
2708 {
2709         EmpathyChatPriv *priv = GET_PRIV (chat);
2710
2711         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2712
2713         return priv->tp_chat;
2714 }
2715
2716 static void display_password_info_bar (EmpathyChat *self,
2717                                        gboolean retry);
2718
2719 static void
2720 provide_password_cb (GObject *tp_chat,
2721                      GAsyncResult *res,
2722                      gpointer user_data)
2723 {
2724         EmpathyChat *self = EMPATHY_CHAT (user_data);
2725         EmpathyChatPriv *priv = GET_PRIV (self);
2726         GError *error = NULL;
2727
2728         if (!empathy_tp_chat_provide_password_finish (EMPATHY_TP_CHAT (tp_chat), res,
2729                                                       &error)) {
2730                 DEBUG ("error: %s", error->message);
2731                 /* FIXME: what should we do if that's another error? Close the channel?
2732                  * Display the raw D-Bus error to the user isn't very useful */
2733                 if (g_error_matches (error, TP_ERRORS, TP_ERROR_AUTHENTICATION_FAILED))
2734                         display_password_info_bar (self, TRUE);
2735                 g_error_free (error);
2736                 return;
2737         }
2738
2739         /* Room joined */
2740         gtk_widget_set_sensitive (priv->hpaned, TRUE);
2741         gtk_widget_grab_focus (self->input_text_view);
2742 }
2743
2744 static void
2745 password_infobar_response_cb (GtkWidget *info_bar,
2746                               gint response_id,
2747                               EmpathyChat *self)
2748 {
2749         EmpathyChatPriv *priv = GET_PRIV (self);
2750         GtkWidget *entry;
2751         const gchar *password;
2752
2753         if (response_id != GTK_RESPONSE_OK)
2754                 goto out;
2755
2756         entry = g_object_get_data (G_OBJECT (info_bar), "password-entry");
2757         g_assert (entry != NULL);
2758
2759         password = gtk_entry_get_text (GTK_ENTRY (entry));
2760
2761         empathy_tp_chat_provide_password_async (priv->tp_chat, password,
2762                                                 provide_password_cb, self);
2763
2764  out:
2765         gtk_widget_destroy (info_bar);
2766 }
2767
2768 static void
2769 password_entry_activate_cb (GtkWidget *entry,
2770                           GtkWidget *info_bar)
2771 {
2772         gtk_info_bar_response (GTK_INFO_BAR (info_bar), GTK_RESPONSE_OK);
2773 }
2774
2775 static void
2776 passwd_join_button_cb (GtkButton *button,
2777                           GtkWidget *info_bar)
2778 {
2779         gtk_info_bar_response (GTK_INFO_BAR (info_bar), GTK_RESPONSE_OK);
2780 }
2781
2782 static void
2783 display_password_info_bar (EmpathyChat *self,
2784                            gboolean retry)
2785 {
2786         EmpathyChatPriv *priv = GET_PRIV (self);
2787         GtkWidget *info_bar;
2788         GtkWidget *content_area;
2789         GtkWidget *hbox;
2790         GtkWidget *image;
2791         GtkWidget *label;
2792         GtkWidget *entry;
2793         GtkWidget *alig;
2794         GtkWidget *button;
2795         GtkMessageType type;
2796         const gchar *msg, *button_label;
2797
2798         if (retry) {
2799                 /* Previous password was wrong */
2800                 type = GTK_MESSAGE_ERROR;
2801                 msg = _("Wrong password; please try again:");
2802                 button_label = _("Retry");
2803         }
2804         else {
2805                 /* First time we're trying to join */
2806                 type = GTK_MESSAGE_QUESTION;
2807                 msg = _("This room is protected by a password:");
2808                 button_label = _("Join");
2809         }
2810
2811         info_bar = gtk_info_bar_new ();
2812         gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar), type);
2813
2814         content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar));
2815
2816         hbox = gtk_hbox_new (FALSE, 3);
2817         gtk_container_add (GTK_CONTAINER (content_area), hbox);
2818
2819         /* Add image */
2820         image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_AUTHENTICATION,
2821                                           GTK_ICON_SIZE_DIALOG);
2822         gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
2823
2824         /* Add message */
2825         label = gtk_label_new (msg);
2826         gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
2827
2828         /* Add password entry */
2829         entry = gtk_entry_new ();
2830         gtk_entry_set_visibility (GTK_ENTRY (entry), FALSE);
2831         gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 0);
2832
2833         g_signal_connect (entry, "activate",
2834                           G_CALLBACK (password_entry_activate_cb), info_bar);
2835
2836         /* Focus the password entry once it's realized */
2837         g_signal_connect (entry, "realize", G_CALLBACK (gtk_widget_grab_focus), NULL);
2838
2839         /* Add 'Join' button */
2840         alig = gtk_alignment_new (0, 0.5, 0, 0);
2841
2842         button = gtk_button_new_with_label (button_label);
2843         gtk_container_add (GTK_CONTAINER (alig), button);
2844         gtk_box_pack_start (GTK_BOX (hbox), alig, FALSE, FALSE, 0);
2845
2846         g_signal_connect (button, "clicked", G_CALLBACK (passwd_join_button_cb),
2847                           info_bar);
2848
2849         g_object_set_data (G_OBJECT (info_bar), "password-entry", entry);
2850
2851         gtk_box_pack_start (GTK_BOX (priv->info_bar_vbox), info_bar,
2852                             FALSE, FALSE, 3);
2853         gtk_widget_show_all (hbox);
2854
2855         g_signal_connect (info_bar, "response",
2856                           G_CALLBACK (password_infobar_response_cb), self);
2857
2858         gtk_widget_show_all (info_bar);
2859 }
2860
2861 static void
2862 chat_password_needed_changed_cb (EmpathyChat *self)
2863 {
2864         EmpathyChatPriv *priv = GET_PRIV (self);
2865
2866         if (empathy_tp_chat_password_needed (priv->tp_chat)) {
2867                 display_password_info_bar (self, FALSE);
2868                 gtk_widget_set_sensitive (priv->hpaned, FALSE);
2869         }
2870 }
2871
2872 void
2873 empathy_chat_set_tp_chat (EmpathyChat   *chat,
2874                           EmpathyTpChat *tp_chat)
2875 {
2876         EmpathyChatPriv *priv = GET_PRIV (chat);
2877         TpConnection    *connection;
2878         GPtrArray       *properties;
2879
2880         g_return_if_fail (EMPATHY_IS_CHAT (chat));
2881         g_return_if_fail (EMPATHY_IS_TP_CHAT (tp_chat));
2882         g_return_if_fail (empathy_tp_chat_is_ready (tp_chat));
2883
2884         if (priv->tp_chat) {
2885                 return;
2886         }
2887
2888         if (priv->account) {
2889                 g_object_unref (priv->account);
2890         }
2891
2892         priv->tp_chat = g_object_ref (tp_chat);
2893         connection = empathy_tp_chat_get_connection (priv->tp_chat);
2894         priv->account = g_object_ref (empathy_get_account_for_connection (connection));
2895
2896         g_signal_connect (tp_chat, "destroy",
2897                           G_CALLBACK (chat_destroy_cb),
2898                           chat);
2899         g_signal_connect (tp_chat, "message-received",
2900                           G_CALLBACK (chat_message_received_cb),
2901                           chat);
2902         g_signal_connect (tp_chat, "send-error",
2903                           G_CALLBACK (chat_send_error_cb),
2904                           chat);
2905         g_signal_connect (tp_chat, "chat-state-changed",
2906                           G_CALLBACK (chat_state_changed_cb),
2907                           chat);
2908         g_signal_connect (tp_chat, "property-changed",
2909                           G_CALLBACK (chat_property_changed_cb),
2910                           chat);
2911         g_signal_connect (tp_chat, "members-changed",
2912                           G_CALLBACK (chat_members_changed_cb),
2913                           chat);
2914         g_signal_connect (tp_chat, "member-renamed",
2915                           G_CALLBACK (chat_member_renamed_cb),
2916                           chat);
2917         g_signal_connect_swapped (tp_chat, "notify::remote-contact",
2918                                   G_CALLBACK (chat_remote_contact_changed_cb),
2919                                   chat);
2920         g_signal_connect_swapped (tp_chat, "notify::password-needed",
2921                                   G_CALLBACK (chat_password_needed_changed_cb),
2922                                   chat);
2923
2924         /* Get initial value of properties */
2925         properties = empathy_tp_chat_get_properties (priv->tp_chat);
2926         if (properties != NULL) {
2927                 guint i;
2928
2929                 for (i = 0; i < properties->len; i++) {
2930                         EmpathyTpChatProperty *property;
2931
2932                         property = g_ptr_array_index (properties, i);
2933                         if (property->value == NULL)
2934                                 continue;
2935
2936                         chat_property_changed_cb (priv->tp_chat,
2937                                                   property->name,
2938                                                   property->value,
2939                                                   chat);
2940                 }
2941         }
2942
2943         chat_remote_contact_changed_cb (chat);
2944
2945         if (chat->input_text_view) {
2946                 gtk_widget_set_sensitive (chat->input_text_view, TRUE);
2947                 if (priv->block_events_timeout_id == 0) {
2948                         empathy_chat_view_append_event (chat->view, _("Connected"));
2949                 }
2950         }
2951
2952         g_object_notify (G_OBJECT (chat), "tp-chat");
2953         g_object_notify (G_OBJECT (chat), "id");
2954         g_object_notify (G_OBJECT (chat), "account");
2955
2956         /* This is a noop when tp-chat is set at object construction time and causes
2957          * the pending messages to be show when it's set on the object after it has
2958          * been created */
2959         show_pending_messages (chat);
2960
2961         /* check if a password is needed */
2962         chat_password_needed_changed_cb (chat);
2963 }
2964
2965 TpAccount *
2966 empathy_chat_get_account (EmpathyChat *chat)
2967 {
2968         EmpathyChatPriv *priv = GET_PRIV (chat);
2969
2970         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2971
2972         return priv->account;
2973 }
2974
2975 const gchar *
2976 empathy_chat_get_id (EmpathyChat *chat)
2977 {
2978         EmpathyChatPriv *priv = GET_PRIV (chat);
2979
2980         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2981
2982         return priv->id;
2983 }
2984
2985 const gchar *
2986 empathy_chat_get_name (EmpathyChat *chat)
2987 {
2988         EmpathyChatPriv *priv = GET_PRIV (chat);
2989         const gchar *ret;
2990
2991         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
2992
2993         ret = priv->name;
2994         if (!ret && priv->remote_contact) {
2995                 ret = empathy_contact_get_name (priv->remote_contact);
2996         }
2997
2998         if (!ret)
2999                 ret = priv->id;
3000
3001         return ret ? ret : _("Conversation");
3002 }
3003
3004 const gchar *
3005 empathy_chat_get_subject (EmpathyChat *chat)
3006 {
3007         EmpathyChatPriv *priv = GET_PRIV (chat);
3008
3009         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3010
3011         return priv->subject;
3012 }
3013
3014 EmpathyContact *
3015 empathy_chat_get_remote_contact (EmpathyChat *chat)
3016 {
3017         EmpathyChatPriv *priv = GET_PRIV (chat);
3018
3019         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3020
3021         return priv->remote_contact;
3022 }
3023
3024 GtkWidget *
3025 empathy_chat_get_contact_menu (EmpathyChat *chat)
3026 {
3027         EmpathyChatPriv *priv = GET_PRIV (chat);
3028         GtkWidget       *menu = NULL;
3029
3030         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), NULL);
3031
3032         if (priv->remote_contact) {
3033                 menu = empathy_contact_menu_new (priv->remote_contact,
3034                                                  EMPATHY_CONTACT_FEATURE_CALL |
3035                                                  EMPATHY_CONTACT_FEATURE_LOG |
3036                                                  EMPATHY_CONTACT_FEATURE_INFO);
3037         }
3038         else if (priv->contact_list_view) {
3039                 EmpathyContactListView *view;
3040
3041                 view = EMPATHY_CONTACT_LIST_VIEW (priv->contact_list_view);
3042                 menu = empathy_contact_list_view_get_contact_menu (view);
3043         }
3044
3045         return menu;
3046 }
3047
3048 void
3049 empathy_chat_clear (EmpathyChat *chat)
3050 {
3051         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3052
3053         empathy_chat_view_clear (chat->view);
3054 }
3055
3056 void
3057 empathy_chat_scroll_down (EmpathyChat *chat)
3058 {
3059         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3060
3061         empathy_chat_view_scroll_down (chat->view);
3062 }
3063
3064 void
3065 empathy_chat_cut (EmpathyChat *chat)
3066 {
3067         GtkTextBuffer *buffer;
3068
3069         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3070
3071         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3072         if (gtk_text_buffer_get_has_selection (buffer)) {
3073                 GtkClipboard *clipboard;
3074
3075                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3076
3077                 gtk_text_buffer_cut_clipboard (buffer, clipboard, TRUE);
3078         }
3079 }
3080
3081 void
3082 empathy_chat_copy (EmpathyChat *chat)
3083 {
3084         GtkTextBuffer *buffer;
3085
3086         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3087
3088         if (empathy_chat_view_get_has_selection (chat->view)) {
3089                 empathy_chat_view_copy_clipboard (chat->view);
3090                 return;
3091         }
3092
3093         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3094         if (gtk_text_buffer_get_has_selection (buffer)) {
3095                 GtkClipboard *clipboard;
3096
3097                 clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3098
3099                 gtk_text_buffer_copy_clipboard (buffer, clipboard);
3100         }
3101 }
3102
3103 void
3104 empathy_chat_paste (EmpathyChat *chat)
3105 {
3106         GtkTextBuffer *buffer;
3107         GtkClipboard  *clipboard;
3108         EmpathyChatPriv *priv;
3109
3110         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3111
3112         priv = GET_PRIV (chat);
3113
3114         if (priv->tp_chat == NULL ||
3115             !gtk_widget_is_sensitive (chat->input_text_view))
3116                 return;
3117
3118         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3119         clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
3120
3121         gtk_text_buffer_paste_clipboard (buffer, clipboard, NULL, TRUE);
3122 }
3123
3124 void
3125 empathy_chat_find (EmpathyChat *chat)
3126 {
3127         EmpathyChatPriv *priv;
3128
3129         g_return_if_fail (EMPATHY_IS_CHAT (chat));
3130
3131         priv = GET_PRIV (chat);
3132
3133         empathy_search_bar_show (EMPATHY_SEARCH_BAR (priv->search_bar));
3134 }
3135
3136 void
3137 empathy_chat_correct_word (EmpathyChat  *chat,
3138                           GtkTextIter *start,
3139                           GtkTextIter *end,
3140                           const gchar *new_word)
3141 {
3142         GtkTextBuffer *buffer;
3143
3144         g_return_if_fail (chat != NULL);
3145         g_return_if_fail (new_word != NULL);
3146
3147         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (chat->input_text_view));
3148
3149         gtk_text_buffer_delete (buffer, start, end);
3150         gtk_text_buffer_insert (buffer, start,
3151                                 new_word,
3152                                 -1);
3153 }
3154
3155 gboolean
3156 empathy_chat_is_room (EmpathyChat *chat)
3157 {
3158         EmpathyChatPriv *priv = GET_PRIV (chat);
3159
3160         g_return_val_if_fail (EMPATHY_IS_CHAT (chat), FALSE);
3161
3162         return (priv->handle_type == TP_HANDLE_TYPE_ROOM);
3163 }
3164
3165 guint
3166 empathy_chat_get_nb_unread_messages (EmpathyChat *self)
3167 {
3168         EmpathyChatPriv *priv = GET_PRIV (self);
3169
3170         g_return_val_if_fail (EMPATHY_IS_CHAT (self), 0);
3171
3172         return priv->unread_messages;
3173 }
3174
3175 /* called when the messages have been read by user */
3176 void
3177 empathy_chat_messages_read (EmpathyChat *self)
3178 {
3179         EmpathyChatPriv *priv = GET_PRIV (self);
3180
3181         g_return_if_fail (EMPATHY_IS_CHAT (self));
3182
3183         /* FIXME: See Bug#610994, See comments about it in EmpathyChatPriv
3184          * definition. If we are still retrieving the backlogs, do not ACK */
3185         if (priv->retrieving_backlogs)
3186                 return;
3187
3188         if (priv->tp_chat != NULL ) {
3189                         empathy_tp_chat_acknowledge_all_messages (priv->tp_chat);
3190         }
3191         priv->unread_messages = 0;
3192 }