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