summary refs log blame commit diff stats
path: root/src/fe-gtk/textgui.c
blob: fbee6590e21da169dcad6f1fed497745e612c753 (plain) (tree)















































































































































































































































































































                                                                                                                                          
                                                                                       




















                                                        
                                                                                          
































































































































                                                                                                                                                        
/* X-Chat
 * Copyright (C) 1998 Peter Zelezny.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "fe-gtk.h"

#include <gtk/gtkbutton.h>
#include <gtk/gtkentry.h>
#include <gtk/gtkhbox.h>
#include <gtk/gtkhbbox.h>
#include <gtk/gtkliststore.h>
#include <gtk/gtkstock.h>
#include <gtk/gtkvbox.h>
#include <gtk/gtkvpaned.h>
#include <gtk/gtkvscrollbar.h>

#include "../common/xchat.h"
#include "../common/xchatc.h"
#include "../common/cfgfiles.h"
#include "../common/outbound.h"
#include "../common/fe.h"
#include "../common/text.h"
#include "gtkutil.h"
#include "xtext.h"
#include "maingui.h"
#include "palette.h"
#include "textgui.h"

extern struct text_event te[];
extern char *pntevts_text[];
extern char *pntevts[];

static GtkWidget *pevent_dialog = NULL, *pevent_dialog_twid,
	*pevent_dialog_entry,
	*pevent_dialog_list, *pevent_dialog_hlist;

enum
{
	COL_EVENT_NAME,
	COL_EVENT_TEXT,
	COL_ROW,
	N_COLUMNS
};


/* this is only used in xtext.c for indented timestamping */
int
xtext_get_stamp_str (time_t tim, char **ret)
{
	return get_stamp_str (prefs.stamp_format, tim, ret);
}

static void
PrintTextLine (xtext_buffer *xtbuf, unsigned char *text, int len, int indent, time_t timet)
{
	unsigned char *tab, *new_text;
	int leftlen;

	if (len == 0)
		len = 1;

	if (!indent)
	{
		if (prefs.timestamp)
		{
			int stamp_size;
			char *stamp;

			if (timet == 0)
				timet = time (0);

			stamp_size = get_stamp_str (prefs.stamp_format, timet, &stamp);
			new_text = malloc (len + stamp_size + 1);
			memcpy (new_text, stamp, stamp_size);
			g_free (stamp);
			memcpy (new_text + stamp_size, text, len);
			gtk_xtext_append (xtbuf, new_text, len + stamp_size);
			free (new_text);
		} else
			gtk_xtext_append (xtbuf, text, len);
		return;
	}

	tab = strchr (text, '\t');
	if (tab && tab < (text + len))
	{
		leftlen = tab - text;
		gtk_xtext_append_indent (xtbuf,
										 text, leftlen, tab + 1, len - (leftlen + 1), timet);
	} else
		gtk_xtext_append_indent (xtbuf, 0, 0, text, len, timet);
}

void
PrintTextRaw (void *xtbuf, unsigned char *text, int indent, time_t stamp)
{
	char *last_text = text;
	int len = 0;
	int beep_done = FALSE;

	/* split the text into separate lines */
	while (1)
	{
		switch (*text)
		{
		case 0:
			PrintTextLine (xtbuf, last_text, len, indent, stamp);
			return;
		case '\n':
			PrintTextLine (xtbuf, last_text, len, indent, stamp);
			text++;
			if (*text == 0)
				return;
			last_text = text;
			len = 0;
			break;
		case ATTR_BEEP:
			*text = ' ';
			if (!beep_done) /* beeps may be slow, so only do 1 per line */
			{
				beep_done = TRUE;
				if (!prefs.filterbeep)
					gdk_beep ();
			}
		default:
			text++;
			len++;
		}
	}
}

static void
pevent_dialog_close (GtkWidget *wid, gpointer arg)
{
	pevent_dialog = NULL;
	pevent_save (NULL);
}

static void
pevent_dialog_update (GtkWidget * wid, GtkWidget * twid)
{
	int len, m;
	const char *text;
	char *out;
	int sig;
	GtkTreeIter iter;
	GtkListStore *store;

	if (!gtkutil_treeview_get_selected (GTK_TREE_VIEW (pevent_dialog_list),
													&iter, COL_ROW, &sig, -1))
		return;

	text = gtk_entry_get_text (GTK_ENTRY (wid));
	len = strlen (text);

	if (pevt_build_string (text, &out, &m) != 0)
	{
		fe_message (_("There was an error parsing the string"), FE_MSG_ERROR);
		return;
	}
	if (m > (te[sig].num_args & 0x7f))
	{
		free (out);
		out = malloc (4096);
		snprintf (out, 4096,
					 _("This signal is only passed %d args, $%d is invalid"),
					 te[sig].num_args & 0x7f, m);
		fe_message (out, FE_MSG_WARN);
		free (out);
		return;
	}

	store = (GtkListStore *)gtk_tree_view_get_model (GTK_TREE_VIEW (pevent_dialog_list));
	gtk_list_store_set (store, &iter, COL_EVENT_TEXT, text, -1);

	if (pntevts_text[sig])
		free (pntevts_text[sig]);
	if (pntevts[sig])
		free (pntevts[sig]);

	pntevts_text[sig] = malloc (len + 1);
	memcpy (pntevts_text[sig], text, len + 1);
	pntevts[sig] = out;

	out = malloc (len + 2);
	memcpy (out, text, len + 1);
	out[len] = '\n';
	out[len + 1] = 0;
	check_special_chars (out, TRUE);

	PrintTextRaw (GTK_XTEXT (twid)->buffer, out, 0, 0);
	free (out);

	/* save this when we exit */
	prefs.save_pevents = 1;
}

static void
pevent_dialog_hfill (GtkWidget * list, int e)
{
	int i = 0;
	char *text;
	GtkTreeIter iter;
	GtkListStore *store;

	store = (GtkListStore *)gtk_tree_view_get_model (GTK_TREE_VIEW (pevent_dialog_hlist));
	gtk_list_store_clear (store);
	while (i < (te[e].num_args & 0x7f))
	{
		text = _(te[e].help[i]);
		i++;
		if (text[0] == '\001')
			text++;
		gtk_list_store_insert_with_values (store, &iter, -1,
													  0, i,
													  1, text, -1);
	}
}

static void
pevent_dialog_unselect (void)
{
	gtk_entry_set_text (GTK_ENTRY (pevent_dialog_entry), "");
	gtk_list_store_clear ((GtkListStore *)gtk_tree_view_get_model (GTK_TREE_VIEW (pevent_dialog_hlist)));
}

static void
pevent_dialog_select (GtkTreeSelection *sel, gpointer store)
{
	char *text;
	int sig;
	GtkTreeIter iter;

	if (!gtkutil_treeview_get_selected (GTK_TREE_VIEW (pevent_dialog_list),
													&iter, COL_ROW, &sig, -1))
	{
		pevent_dialog_unselect ();
	}
	else
	{
		gtk_tree_model_get (store, &iter, COL_EVENT_TEXT, &text, -1);
		gtk_entry_set_text (GTK_ENTRY (pevent_dialog_entry), text);
		g_free (text);
		pevent_dialog_hfill (pevent_dialog_hlist, sig);
	}
}

static void
pevent_dialog_fill (GtkWidget * list)
{
	int i;
	GtkListStore *store;
	GtkTreeIter iter;

	store = (GtkListStore *)gtk_tree_view_get_model (GTK_TREE_VIEW (list));
	gtk_list_store_clear (store);

	i = NUM_XP;
	do
	{
		i--;
		gtk_list_store_insert_with_values (store, &iter, 0,
													  COL_EVENT_NAME, te[i].name,
													  COL_EVENT_TEXT, pntevts_text[i],
													  COL_ROW, i, -1);
	}
	while (i != 0);
}

static void
pevent_save_req_cb (void *arg1, char *file)
{
	if (file)
		pevent_save (file);
}

static void
pevent_save_cb (GtkWidget * wid, void *data)
{
	if (data)
	{
		gtkutil_file_req (_("Print Texts File"), pevent_save_req_cb, NULL,
								NULL, NULL, FRF_WRITE);
		return;
	}
	pevent_save (NULL);
}

static void
pevent_load_req_cb (void *arg1, char *file)
{
	if (file)
	{
		pevent_load (file);
		pevent_make_pntevts ();
		pevent_dialog_fill (pevent_dialog_list);
		pevent_dialog_unselect ();
		prefs.save_pevents = 1;
	}
}

static void
pevent_load_cb (GtkWidget * wid, void *data)
{
	gtkutil_file_req (_("Print Texts File"), pevent_load_req_cb, NULL, NULL, NULL, 0);
}

static void
pevent_ok_cb (GtkWidget * wid, void *data)
{
	gtk_widget_destroy (pevent_dialog);
}

static void
pevent_test_cb (GtkWidget * wid, GtkWidget * twid)
{
	int len, n;
	char *out, *text;

	for (n = 0; n < NUM_XP; n++)
	{
		text = _(pntevts_text[n]);
		len = strlen (text);

		out = malloc (len + 2);
		memcpy (out, text, len + 1);
		out[len] = '\n';
		out[len + 1] = 0;
		check_special_chars (out, TRUE);

		PrintTextRaw (GTK_XTEXT (twid)->buffer, out, 0, 0);
		free (out);
	}
}

void
pevent_dialog_show ()
{
	GtkWidget *vbox, *hbox, *tbox, *wid, *bh, *th;
	GtkListStore *store, *hstore;
	GtkTreeSelection *sel;

	if (pevent_dialog)
	{
		mg_bring_tofront (pevent_dialog);
		return;
	}

	pevent_dialog =
			  mg_create_generic_tab ("edit events", _("Edit Events"),
											 TRUE, FALSE, pevent_dialog_close, NULL,
											 600, 455, &vbox, 0);

	wid = gtk_vpaned_new ();
	th = gtk_vbox_new (0, 2);
	bh = gtk_vbox_new (0, 2);
	gtk_widget_show (th);
	gtk_widget_show (bh);
	gtk_paned_pack1 (GTK_PANED (wid), th, 1, 1);
	gtk_paned_pack2 (GTK_PANED (wid), bh, 0, 1);
	gtk_box_pack_start (GTK_BOX (vbox), wid, 1, 1, 0);
	gtk_widget_show (wid);

	store = gtk_list_store_new (N_COLUMNS, G_TYPE_STRING,
	                            G_TYPE_STRING, G_TYPE_INT);
	pevent_dialog_list = gtkutil_treeview_new (th, GTK_TREE_MODEL (store), NULL,
															 COL_EVENT_NAME, _("Event"),
															 COL_EVENT_TEXT, _("Text"), -1);
	sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (pevent_dialog_list));
	g_signal_connect (G_OBJECT (sel), "changed",
							G_CALLBACK (pevent_dialog_select), store);

	pevent_dialog_twid = gtk_xtext_new (colors, 0);
	gtk_xtext_set_tint (GTK_XTEXT (pevent_dialog_twid), prefs.tint_red, prefs.tint_green, prefs.tint_blue);
	gtk_xtext_set_background (GTK_XTEXT (pevent_dialog_twid),
									  channelwin_pix, prefs.transparent);

	pevent_dialog_entry = gtk_entry_new_with_max_length (255);
	g_signal_connect (G_OBJECT (pevent_dialog_entry), "activate",
							G_CALLBACK (pevent_dialog_update), pevent_dialog_twid);
	gtk_box_pack_start (GTK_BOX (bh), pevent_dialog_entry, 0, 0, 0);
	gtk_widget_show (pevent_dialog_entry);

	tbox = gtk_hbox_new (0, 0);
	gtk_container_add (GTK_CONTAINER (bh), tbox);
	gtk_widget_show (tbox);

	gtk_widget_set_usize (pevent_dialog_twid, 150, 20);
	gtk_container_add (GTK_CONTAINER (tbox), pevent_dialog_twid);
	gtk_xtext_set_font (GTK_XTEXT (pevent_dialog_twid), prefs.font_normal);

	wid = gtk_vscrollbar_new (GTK_XTEXT (pevent_dialog_twid)->adj);
	gtk_box_pack_start (GTK_BOX (tbox), wid, FALSE, FALSE, 0);
	show_and_unfocus (wid);

	gtk_widget_show (pevent_dialog_twid);

	hstore = gtk_list_store_new (2, G_TYPE_INT, G_TYPE_STRING);
	pevent_dialog_hlist = gtkutil_treeview_new (bh, GTK_TREE_MODEL (hstore),
															  NULL,
															  0, _("$ Number"),
															  1, _("Description"), -1);
	gtk_widget_show (pevent_dialog_hlist);

	pevent_dialog_fill (pevent_dialog_list);
	gtk_widget_show (pevent_dialog_list);

	hbox = gtk_hbutton_box_new ();
	gtk_box_pack_end (GTK_BOX (vbox), hbox, 0, 0, 2);
	/*wid = gtk_button_new_with_label (_("Save"));
	gtk_box_pack_end (GTK_BOX (hbox), wid, 0, 0, 0);
	gtk_signal_connect (GTK_OBJECT (wid), "clicked",
							  GTK_SIGNAL_FUNC (pevent_save_cb), NULL);
	gtk_widget_show (wid);*/
	gtkutil_button (hbox, GTK_STOCK_SAVE_AS, NULL, pevent_save_cb,
						 (void *) 1, _("Save As..."));
	gtkutil_button (hbox, GTK_STOCK_OPEN, NULL, pevent_load_cb,
						 (void *) 0, _("Load From..."));
	wid = gtk_button_new_with_label (_("Test All"));
	gtk_box_pack_end (GTK_BOX (hbox), wid, 0, 0, 0);
	g_signal_connect (G_OBJECT (wid), "clicked",
							G_CALLBACK (pevent_test_cb), pevent_dialog_twid);
	gtk_widget_show (wid);

	wid = gtk_button_new_from_stock (GTK_STOCK_OK);
	gtk_box_pack_start (GTK_BOX (hbox), wid, 0, 0, 0);
	g_signal_connect (G_OBJECT (wid), "clicked",
							G_CALLBACK (pevent_ok_cb), NULL);
	gtk_widget_show (wid);

	gtk_widget_show (hbox);

	gtk_widget_show (pevent_dialog);
}
n390'>390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787


                                            


                                     



                              
                               





                    



                   










                                                               




















                                                               
                               


                                       




                              
                          

















                                  
                                                 


















































                                                                  



                                                         
     


                            
      







                                                                        
                                                        





                                                          


                                         
 





                                                                        
                                                                                                              



                                      
                                                                                          



                                                      















































                                                                      
                                                                                                   

                                                                             
                                                                                











































































































                                                                                       
                             


                                          


































                                                                       
                                                                        
 
                                                               


























































































































                                                                                         
             


                           
      

                                                
                                                                        




                                                                                  
                                                                                        
            
                                                                                     

                                                             
                                                   
                                                    


                                                                                      











                                                                                 
      
 
























                                                                                              





                                                                                           







                                                                                                 
                                          
 
                                                                                                           





                                                                
                                                                                            
                                                                                                           
                    
                                                                                                        
                                                                                                                               

         
                                                                                                              
                                                                                                 
                                                                                                            
 
                                





                                                                         
                                        
 
                                                                                                         




                                          
                                                                                           
                                                                                                           
                    
                                                                                                   

         
                                                                                                            
                                                                                                
                                                                                                            
 
                                






                                  
                                                              

                       
                                  
 
                                                   
                     
                                                          


                                 
                                                                                

                                                                       
                                                                                            

                                                                                        
                                                                                                           
                                                                                          






                                                                                
                                          
 
                                                                                                        

                                             
                                





                                              
                                          
 
                                                                                                        

                                               
                                







                                          
                                          
 
                                                   
                     
                                                          
 
                                                                                                        




                                           
                                                                                   

                                                                                  
                                                                                               


                                                                                                   
                                                                                                           
                                                                                   

                                                                                  
                                






                                            
                                


















                                                   
                                        



                                        
                                                           




                                     
                                                                    

                                                                                     
                                                                       





                             

                                                                                     
 


                                                                              
 



                                                                                     
 
                                                                    
 
                                                                         
 
                                                   





                                                  
                                                  


                        

                            


                 
/* Copyright (C) 2006-2007 Peter Zelezny. */

#include <string.h>
#include "../common/hexchat-plugin.h"
#include "../common/hexchat.h"
#include "../common/hexchatc.h"
#include "../common/inbound.h"
#include "../common/server.h"
#include "../common/fe.h"
#include "../common/util.h"
#include "../common/outbound.h"
#include "fe-gtk.h"
#include "pixmaps.h"
#include "maingui.h"
#include "menu.h"
#include <gtk/gtk.h>

#ifndef WIN32
#include <unistd.h>
#endif

#ifdef USE_LIBNOTIFY
#include <libnotify/notify.h>
#ifndef NOTIFY_CHECK_VERSION
#define NOTIFY_CHECK_VERSION(x,y,z) 0
#endif
#if NOTIFY_CHECK_VERSION(0,7,0)
#define XC_NOTIFY_NEW(a,b,c,d) notify_notification_new(a,b,c)
#else
#define XC_NOTIFY_NEW(a,b,c,d) notify_notification_new(a,b,c,d)
#endif
#endif

typedef enum	/* current icon status */
{
	TS_NONE,
	TS_MESSAGE,
	TS_HIGHLIGHT,
	TS_FILEOFFER,
	TS_CUSTOM /* plugin */
} TrayStatus;

typedef enum
{
	WS_FOCUSED,
	WS_NORMAL,
	WS_HIDDEN
} WinStatus;

typedef GdkPixbuf* TrayIcon;
#define tray_icon_from_file(f) gdk_pixbuf_new_from_file(f,NULL)
#define tray_icon_free(i) g_object_unref(i)

#define ICON_NORMAL pix_hexchat
#define ICON_MSG pix_tray_message
#define ICON_HILIGHT pix_tray_highlight
#define ICON_FILE pix_tray_fileoffer
#define TIMEOUT 500

static GtkStatusIcon *sticon;
static gint flash_tag;
static TrayStatus tray_status;
static hexchat_plugin *ph;

static TrayIcon custom_icon1;
static TrayIcon custom_icon2;

static int tray_priv_count = 0;
static int tray_pub_count = 0;
static int tray_hilight_count = 0;
static int tray_file_count = 0;


void tray_apply_setup (void);


static WinStatus
tray_get_window_status (void)
{
	const char *st;

	st = hexchat_get_info (ph, "win_status");

	if (!st)
		return WS_HIDDEN;

	if (!strcmp (st, "active"))
		return WS_FOCUSED;

	if (!strcmp (st, "hidden"))
		return WS_HIDDEN;

	return WS_NORMAL;
}

static int
tray_count_channels (void)
{
	int cons = 0;
	GSList *list;
	session *sess;

	for (list = sess_list; list; list = list->next)
	{
		sess = list->data;
		if (sess->server->connected && sess->channel[0] &&
			 sess->type == SESS_CHANNEL)
			cons++;
	}
	return cons;
}

static int
tray_count_networks (void)
{
	int cons = 0;
	GSList *list;

	for (list = serv_list; list; list = list->next)
	{
		if (((server *)list->data)->connected)
			cons++;
	}
	return cons;
}

void
fe_tray_set_tooltip (const char *text)
{
	if (sticon)
		gtk_status_icon_set_tooltip (sticon, text);
}

void
fe_tray_set_balloon (const char *title, const char *text)
{
#ifndef WIN32
#if 0
	const char *argv[8];
	const char *path;
	char time[16];
#endif
	WinStatus ws;

	/* no balloons if the window is focused */
	ws = tray_get_window_status ();
	if (ws == WS_FOCUSED)
		return;

	/* bit 1 of flags means "no balloons unless hidden/iconified" */
	if (ws != WS_HIDDEN && prefs.hex_gui_tray_quiet)
		return;

	/* FIXME: this should close the current balloon */
	if (!text)
		return;

#ifdef USE_LIBNOTIFY
	NotifyNotification *notification;
	char *notify_text, *notify_title;

	if (!notify_is_initted())
		notify_init(PACKAGE_NAME);

	notify_text = strip_color (text, -1, STRIP_ALL|STRIP_ESCMARKUP);
	notify_title = strip_color (title, -1, STRIP_ALL);

	notification = XC_NOTIFY_NEW (notify_title, notify_text, HEXCHATSHAREDIR"/pixmaps/hexchat.png", NULL);

	g_free ((char *)notify_title);
	g_free ((char *)notify_text);

	notify_notification_set_timeout (notification, prefs.hex_input_balloon_time*1000);
	notify_notification_show (notification, NULL);

	g_object_unref (notification);
#endif
#endif
}

static void
tray_set_balloonf (const char *text, const char *format, ...)
{
	va_list args;
	char *buf;

	va_start (args, format);
	buf = g_strdup_vprintf (format, args);
	va_end (args);

	fe_tray_set_balloon (buf, text);
	g_free (buf);
}

static void
tray_set_tipf (const char *format, ...)
{
	va_list args;
	char *buf;

	va_start (args, format);
	buf = g_strdup_vprintf (format, args);
	va_end (args);

	fe_tray_set_tooltip (buf);
	g_free (buf);
}

static void
tray_stop_flash (void)
{
	int nets, chans;

	if (flash_tag)
	{
		g_source_remove (flash_tag);
		flash_tag = 0;
	}

	if (sticon)
	{
		gtk_status_icon_set_from_pixbuf (sticon, ICON_NORMAL);
		nets = tray_count_networks ();
		chans = tray_count_channels ();
		if (nets)
			tray_set_tipf (_(DISPLAY_NAME": Connected to %u networks and %u channels"),
								nets, chans);
		else
			tray_set_tipf (DISPLAY_NAME": %s", _("Not connected."));
	}

	if (custom_icon1)
	{
		tray_icon_free (custom_icon1);
		custom_icon1 = NULL;
	}

	if (custom_icon2)
	{
		tray_icon_free (custom_icon2);
		custom_icon2 = NULL;
	}

	tray_status = TS_NONE;
}

static void
tray_reset_counts (void)
{
	tray_priv_count = 0;
	tray_pub_count = 0;
	tray_hilight_count = 0;
	tray_file_count = 0;
}

static int
tray_timeout_cb (TrayIcon icon)
{
	if (custom_icon1)
	{
		if (gtk_status_icon_get_pixbuf (sticon) == custom_icon1)
		{
			if (custom_icon2)
				gtk_status_icon_set_from_pixbuf (sticon, custom_icon2);
			else
				gtk_status_icon_set_from_pixbuf (sticon, ICON_NORMAL);
		}
		else
		{
			gtk_status_icon_set_from_pixbuf (sticon, custom_icon1);
		}
	}
	else
	{
		if (gtk_status_icon_get_pixbuf (sticon) == ICON_NORMAL)
			gtk_status_icon_set_from_pixbuf (sticon, icon);
		else
			gtk_status_icon_set_from_pixbuf (sticon, ICON_NORMAL);
	}
	return 1;
}

static void
tray_set_flash (TrayIcon icon)
{
	if (!sticon)
		return;

	/* already flashing the same icon */
	if (flash_tag && gtk_status_icon_get_pixbuf (sticon) == icon)
		return;

	/* no flashing if window is focused */
	if (tray_get_window_status () == WS_FOCUSED)
		return;

	tray_stop_flash ();

	gtk_status_icon_set_from_pixbuf (sticon, icon);
	flash_tag = g_timeout_add (TIMEOUT, (GSourceFunc) tray_timeout_cb, icon);
}

void
fe_tray_set_flash (const char *filename1, const char *filename2, int tout)
{
	tray_apply_setup ();
	if (!sticon)
		return;

	tray_stop_flash ();

	if (tout == -1)
		tout = TIMEOUT;

	custom_icon1 = tray_icon_from_file (filename1);
	if (filename2)
		custom_icon2 = tray_icon_from_file (filename2);

	gtk_status_icon_set_from_pixbuf (sticon, custom_icon1);
	flash_tag = g_timeout_add (tout, (GSourceFunc) tray_timeout_cb, NULL);
	tray_status = TS_CUSTOM;
}

void
fe_tray_set_icon (feicon icon)
{
	tray_apply_setup ();
	if (!sticon)
		return;

	tray_stop_flash ();

	switch (icon)
	{
	case FE_ICON_NORMAL:
		break;
	case FE_ICON_MESSAGE:
	case FE_ICON_PRIVMSG:
		tray_set_flash (ICON_MSG);
		break;
	case FE_ICON_HIGHLIGHT:
		tray_set_flash (ICON_HILIGHT);
		break;
	case FE_ICON_FILEOFFER:
		tray_set_flash (ICON_FILE);
	}
}

void
fe_tray_set_file (const char *filename)
{
	tray_apply_setup ();
	if (!sticon)
		return;

	tray_stop_flash ();

	if (filename)
	{
		custom_icon1 = tray_icon_from_file (filename);
		gtk_status_icon_set_from_pixbuf (sticon, custom_icon1);
		tray_status = TS_CUSTOM;
	}
}

gboolean
tray_toggle_visibility (gboolean force_hide)
{
	static int x, y;
	static GdkScreen *screen;
	GtkWindow *win;

	if (!sticon)
		return FALSE;

	/* ph may have an invalid context now */
	hexchat_set_context (ph, hexchat_find_context (ph, NULL, NULL));

	win = GTK_WINDOW (hexchat_get_info (ph, "gtkwin_ptr"));

	tray_stop_flash ();
	tray_reset_counts ();

	if (!win)
		return FALSE;

#if GTK_CHECK_VERSION(2,20,0)
	if (force_hide || gtk_widget_get_visible (GTK_WIDGET (win)))
#else
	if (force_hide || GTK_WIDGET_VISIBLE (win))
#endif
	{
		gtk_window_get_position (win, &x, &y);
		screen = gtk_window_get_screen (win);
		gtk_widget_hide (GTK_WIDGET (win));
	}
	else
	{
		gtk_window_set_screen (win, screen);
		gtk_window_move (win, x, y);
		gtk_widget_show (GTK_WIDGET (win));
		gtk_window_present (win);
	}

	return TRUE;
}

static void
tray_menu_restore_cb (GtkWidget *item, gpointer userdata)
{
	tray_toggle_visibility (FALSE);
}

static void
tray_menu_quit_cb (GtkWidget *item, gpointer userdata)
{
	mg_open_quit_dialog (FALSE);
}

/* returns 0-mixed 1-away 2-back */

static int
tray_find_away_status (void)
{
	GSList *list;
	server *serv;
	int away = 0;
	int back = 0;

	for (list = serv_list; list; list = list->next)
	{
		serv = list->data;

		if (serv->is_away || serv->reconnect_away)
			away++;
		else
			back++;
	}

	if (away && back)
		return 0;

	if (away)
		return 1;

	return 2;
}

static void
tray_foreach_server (GtkWidget *item, char *cmd)
{
	GSList *list;
	server *serv;

	for (list = serv_list; list; list = list->next)
	{
		serv = list->data;
		if (serv->connected)
			handle_command (serv->server_session, cmd, FALSE);
	}
}

static GtkWidget *
tray_make_item (GtkWidget *menu, char *label, void *callback, void *userdata)
{
	GtkWidget *item;

	if (label)
		item = gtk_menu_item_new_with_mnemonic (label);
	else
		item = gtk_menu_item_new ();
	gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
	g_signal_connect (G_OBJECT (item), "activate",
							G_CALLBACK (callback), userdata);
	gtk_widget_show (item);

	return item;
}

static void
tray_toggle_cb (GtkCheckMenuItem *item, unsigned int *setting)
{
	*setting = item->active;
}

static void
blink_item (unsigned int *setting, GtkWidget *menu, char *label)
{
	menu_toggle_item (label, menu, tray_toggle_cb, setting, *setting);
}

static void
tray_menu_destroy (GtkWidget *menu, gpointer userdata)
{
	gtk_widget_destroy (menu);
	g_object_unref (menu);
}

static void
tray_menu_cb (GtkWidget *widget, guint button, guint time, gpointer userdata)
{
	GtkWidget *menu;
#ifndef WIN32
	GtkWidget *submenu;
	GtkWidget *item;
	int away_status;
#endif

	/* ph may have an invalid context now */
	hexchat_set_context (ph, hexchat_find_context (ph, NULL, NULL));

	menu = gtk_menu_new ();
	/*gtk_menu_set_screen (GTK_MENU (menu), gtk_widget_get_screen (widget));*/

	if (tray_get_window_status () == WS_HIDDEN)
		tray_make_item (menu, _("_Restore Window"), tray_menu_restore_cb, NULL);
	else
		tray_make_item (menu, _("_Hide Window"), tray_menu_restore_cb, NULL);
	tray_make_item (menu, NULL, tray_menu_quit_cb, NULL);

#ifndef WIN32 /* somehow this is broken on win32 */
	submenu = mg_submenu (menu, _("_Blink on"));
	blink_item (&prefs.hex_input_tray_chans, submenu, _("Channel Message"));
	blink_item (&prefs.hex_input_tray_priv, submenu, _("Private Message"));
	blink_item (&prefs.hex_input_tray_hilight, submenu, _("Highlighted Message"));
	/*blink_item (BIT_FILEOFFER, submenu, _("File Offer"));*/

	submenu = mg_submenu (menu, _("_Change status"));
	away_status = tray_find_away_status ();
	item = tray_make_item (submenu, _("_Away"), tray_foreach_server, "away");
	if (away_status == 1)
		gtk_widget_set_sensitive (item, FALSE);
	item = tray_make_item (submenu, _("_Back"), tray_foreach_server, "back");
	if (away_status == 2)
		gtk_widget_set_sensitive (item, FALSE);

	tray_make_item (menu, NULL, tray_menu_quit_cb, NULL);
#endif

	mg_create_icon_item (_("_Quit"), GTK_STOCK_QUIT, menu, tray_menu_quit_cb, NULL);

	menu_add_plugin_items (menu, "\x5$TRAY", NULL);

	g_object_ref (menu);
	g_object_ref_sink (menu);
	g_object_unref (menu);
	g_signal_connect (G_OBJECT (menu), "selection-done",
							G_CALLBACK (tray_menu_destroy), NULL);

	gtk_menu_popup (GTK_MENU (menu), NULL, NULL, gtk_status_icon_position_menu,
						 userdata, button, time);
}

static void
tray_init (void)
{
	flash_tag = 0;
	tray_status = TS_NONE;
	custom_icon1 = NULL;
	custom_icon2 = NULL;

	sticon = gtk_status_icon_new_from_pixbuf (ICON_NORMAL);
	if (!sticon)
		return;

#ifndef WIN32
	g_signal_connect (G_OBJECT (sticon), "popup-menu",
							G_CALLBACK (tray_menu_cb), sticon);
#endif

	g_signal_connect (G_OBJECT (sticon), "activate",
							G_CALLBACK (tray_menu_restore_cb), NULL);
}

static int
tray_hilight_cb (char *word[], void *userdata)
{
	/*if (tray_status == TS_HIGHLIGHT)
		return HEXCHAT_EAT_NONE;*/

	if (prefs.hex_input_tray_hilight && (!prefs.hex_away_omit_alerts || tray_find_away_status () != 1))
	{
		tray_set_flash (ICON_HILIGHT);

		/* FIXME: hides any previous private messages */
		tray_hilight_count++;
		if (tray_hilight_count == 1)
			tray_set_tipf (_(DISPLAY_NAME": Highlighted message from: %s (%s)"),
								word[1], hexchat_get_info (ph, "channel"));
		else
			tray_set_tipf (_(DISPLAY_NAME": %u highlighted messages, latest from: %s (%s)"),
								tray_hilight_count, word[1], hexchat_get_info (ph, "channel"));
	}

	if (prefs.hex_input_balloon_hilight && (!prefs.hex_away_omit_alerts || tray_find_away_status () != 1))
		tray_set_balloonf (word[2], _(DISPLAY_NAME": Highlighted message from: %s (%s)"),
								 word[1], hexchat_get_info (ph, "channel"));

	return HEXCHAT_EAT_NONE;
}

static int
tray_message_cb (char *word[], void *userdata)
{
	if (/*tray_status == TS_MESSAGE ||*/ tray_status == TS_HIGHLIGHT)
		return HEXCHAT_EAT_NONE;

	if (prefs.hex_input_tray_chans && (!prefs.hex_away_omit_alerts || tray_find_away_status () != 1))
	{
		tray_set_flash (ICON_MSG);

		tray_pub_count++;
		if (tray_pub_count == 1)
			tray_set_tipf (_(DISPLAY_NAME": New public message from: %s (%s)"),
								word[1], hexchat_get_info (ph, "channel"));
		else
			tray_set_tipf (_(DISPLAY_NAME": %u new public messages."), tray_pub_count);
	}

	if (prefs.hex_input_balloon_chans && (!prefs.hex_away_omit_alerts || tray_find_away_status () != 1))
		tray_set_balloonf (word[2], _(DISPLAY_NAME": New public message from: %s (%s)"),
								 word[1], hexchat_get_info (ph, "channel"));

	return HEXCHAT_EAT_NONE;
}

static void
tray_priv (char *from, char *text)
{
	const char *network;

	if (alert_match_word (from, prefs.hex_irc_no_hilight))
		return;

	tray_set_flash (ICON_MSG);

	network = hexchat_get_info (ph, "network");
	if (!network)
		network = hexchat_get_info (ph, "server");

	tray_priv_count++;
	if (tray_priv_count == 1)
		tray_set_tipf (_(DISPLAY_NAME": Private message from: %s (%s)"),
							from, network);
	else
		tray_set_tipf (_(DISPLAY_NAME": %u private messages, latest from: %s (%s)"),
							tray_priv_count, from, network);

	if (prefs.hex_input_balloon_priv && (!prefs.hex_away_omit_alerts || tray_find_away_status () != 1))
		tray_set_balloonf (text, _(DISPLAY_NAME": Private message from: %s (%s)"),
								 from, network);
}

static int
tray_priv_cb (char *word[], void *userdata)
{
	/*if (tray_status == TS_HIGHLIGHT)
		return HEXCHAT_EAT_NONE;*/

	if (prefs.hex_input_tray_priv && (!prefs.hex_away_omit_alerts || tray_find_away_status () != 1))
		tray_priv (word[1], word[2]);

	return HEXCHAT_EAT_NONE;
}

static int
tray_invited_cb (char *word[], void *userdata)
{
	/*if (tray_status == TS_HIGHLIGHT)
		return HEXCHAT_EAT_NONE;*/

	if (prefs.hex_input_tray_priv && (!prefs.hex_away_omit_alerts || tray_find_away_status () != 1))
		tray_priv (word[2], "Invited");

	return HEXCHAT_EAT_NONE;
}

static int
tray_dcc_cb (char *word[], void *userdata)
{
	const char *network;

/*	if (tray_status == TS_FILEOFFER)
		return HEXCHAT_EAT_NONE;*/

	network = hexchat_get_info (ph, "network");
	if (!network)
		network = hexchat_get_info (ph, "server");

	if (prefs.hex_input_tray_priv && (!prefs.hex_away_omit_alerts || tray_find_away_status () != 1))
	{
		tray_set_flash (ICON_FILE);

		tray_file_count++;
		if (tray_file_count == 1)
			tray_set_tipf (_(DISPLAY_NAME": File offer from: %s (%s)"),
								word[1], network);
		else
			tray_set_tipf (_(DISPLAY_NAME": %u file offers, latest from: %s (%s)"),
								tray_file_count, word[1], network);
	}

	if (prefs.hex_input_balloon_priv && (!prefs.hex_away_omit_alerts || tray_find_away_status () != 1))
		tray_set_balloonf ("", _(DISPLAY_NAME": File offer from: %s (%s)"),
								word[1], network);

	return HEXCHAT_EAT_NONE;
}

static int
tray_focus_cb (char *word[], void *userdata)
{
	tray_stop_flash ();
	tray_reset_counts ();
	return HEXCHAT_EAT_NONE;
}

static void
tray_cleanup (void)
{
	tray_stop_flash ();

	if (sticon)
	{
		g_object_unref ((GObject *)sticon);
		sticon = NULL;
	}
}

void
tray_apply_setup (void)
{
	if (sticon)
	{
		if (!prefs.hex_gui_tray)
			tray_cleanup ();
	}
	else
	{
		if (prefs.hex_gui_tray && !hextray_mode ())
			tray_init ();
	}
}

int
tray_plugin_init (hexchat_plugin *plugin_handle, char **plugin_name,
				char **plugin_desc, char **plugin_version, char *arg)
{
	/* we need to save this for use with any hexchat_* functions */
	ph = plugin_handle;

	*plugin_name = "";
	*plugin_desc = "";
	*plugin_version = "";

	hexchat_hook_print (ph, "Channel Msg Hilight", -1, tray_hilight_cb, NULL);
	hexchat_hook_print (ph, "Channel Action Hilight", -1, tray_hilight_cb, NULL);

	hexchat_hook_print (ph, "Channel Message", -1, tray_message_cb, NULL);
	hexchat_hook_print (ph, "Channel Action", -1, tray_message_cb, NULL);
	hexchat_hook_print (ph, "Channel Notice", -1, tray_message_cb, NULL);

	hexchat_hook_print (ph, "Private Message", -1, tray_priv_cb, NULL);
	hexchat_hook_print (ph, "Private Message to Dialog", -1, tray_priv_cb, NULL);
	hexchat_hook_print (ph, "Notice", -1, tray_priv_cb, NULL);
	hexchat_hook_print (ph, "Invited", -1, tray_invited_cb, NULL);

	hexchat_hook_print (ph, "DCC Offer", -1, tray_dcc_cb, NULL);

	hexchat_hook_print (ph, "Focus Window", -1, tray_focus_cb, NULL);

	if (prefs.hex_gui_tray && !hextray_mode ())
		tray_init ();

	return 1;       /* return 1 for success */
}

int
tray_plugin_deinit (hexchat_plugin *plugin_handle)
{
#ifdef WIN32
	tray_cleanup ();
#elif defined(USE_LIBNOTIFY)
	notify_uninit ();
#endif
	return 1;
}