#!/usr/bin/env python
# -*- coding: utf-8 -*-
# WebBoard allows you to publish text on a public pastebin on the net
# This applications is based on the command line tool paste of 
# Dennis Kaarsemaker
#
#   (c) 2005 - Dennis Kaarsemaker <dennis@kaarsemaker.net>
#   (c) 2006 - Sebastian Heinlein <sebastian.heinlein@web.de>
#   (c) 2009 - Olivier Le Thanh Duong <olivier@lethanh.be>
#
# 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.

import sys
import os.path
import re
import urllib

import pygtk
pygtk.require('2.0')
import gtk
import gtk.glade
import gnome
import gnomeapplet
import gnome.ui
import gobject

#import debug

import webboardlib.wbconfig as wbconfig
from webboardlib.webboard import WebBoard
from webboardlib.wbconfig import WebBoardConfig
from webboardlib.wbhistory import WebBoardHistory
import webboardlib.constants as constants
import webboardlib.util as util

import gettext
from gettext import gettext as _
gettext.bindtextdomain('webboard')
gettext.textdomain('webboard')
gtk.glade.bindtextdomain('webboard')
gtk.glade.textdomain('webboard')

class WebBoardApplet(gnomeapplet.Applet):

    def __init__(self, applet, iid):
        #Necessity of this?
        self.__gobject_init__()

        icons = gtk.icon_theme_get_default()
        self.logo_pixbuf = icons.load_icon("gtk-paste", 32, 0)
        gtk.window_set_default_icon_list(self.logo_pixbuf)

        self.applet = applet

        self.big_evbox = gtk.EventBox()
        self.big_evbox.connect("button-press-event",self.button_press)
        self.orientation = self.applet.get_orient()
        self.applet.add(self.big_evbox)  

        self.image = gtk.Image()
        self.big_evbox.add(self.image)
        self.image.set_from_stock(gtk.STOCK_PASTE, gtk.ICON_SIZE_SMALL_TOOLBAR)

        # setup drag'n'drop
        self.big_evbox.drag_dest_set(gtk.DEST_DEFAULT_ALL, \
                                    [('text/uri-list',0 , 0)], \
                                    gtk.gdk.ACTION_COPY)
        self.big_evbox.connect("drag_data_received", \
                             self.on_applet_drag_data_received)

        self.config = WebBoardConfig()
        self.history = WebBoardHistory(self.config)

        self.clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)

        self.tooltips = gtk.Tooltips()
        tooltip_text = _("WebBoard\n Publish source codeon a pastebin server") 
        self.tooltips.set_tip(self.big_evbox, tooltip_text)

        self.applet.show_all()

    def on_applet_drag_data_received(self, widget, context, x, y, \
                                     selection, target_type, timestamp):
        """ call when we got a drop event """
        for path in util.uri_from_dnd(selection.data):
            wb = WebBoard(self.config, self.history, file=path)
            self.config.remove_notifier(wb.on_config_changed)
            del wb

    def button_press(self, widget, event):
        if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3:
            self.create_menu()
        elif event.type == gtk.gdk.BUTTON_PRESS and event.button == 1:
            wb = WebBoard(self.config, self.history, clip=True)
            self.config.remove_notifier(wb.on_config_changed)
            del wb
            #debug.dumpObjects()

    def create_menu(self):
        menuxml="<popup name=\"button3\">\n"\
            "<menuitem name=\"Item 1\" verb=\"Board\" label=\"%s\" "\
            "pixtype=\"stock\" pixname=\"gtk-new\"/>\n" % _("_New WebBoard")
        verbs = [("Board", self.open_new_webboard)]

        # include history menu
        if len(self.history.sites) > 0:
            menuxml += "<separator/>\n"
            for id, stamp, title, url in self.history.sites:
                age = self.history.age(id)
                title = title.replace("\"", "&quot;")
                menuxml += "<menuitem name=\"%s\" verb=\"%s\" label="\
                           "\"%s (%s)\"/>\n" % (id, id, title, age)
                verbs.append(("%s" % id, self.open_link))
            menuxml += "<separator/>\n"

        menuxml += "<menuitem name=\"Item 2\" verb=\"Prefs\" label=\"%s\" "\
                   "pixtype=\"stock\" pixname=\"gnome-stock-preferences\"/>\n" \
                   "<menuitem name=\"Item 3\" verb=\"About\" label=\"%s\" "\
                   "pixtype=\"stock\" pixname=\"gnome-stock-about\"/>\n" \
                   "</popup>" % (_("_Preferences"), _("_About"))

        verbs.extend((("Prefs", self.config.preferences),\
                     ("About", self.show_about_dialog)))
        
        print menuxml
        self.applet.setup_menu(menuxml, verbs, None)

    def open_new_webboard(self, event, data=None):
        wb = WebBoard(self.config, self.history)
        self.config.remove_notifier(wb.on_config_changed)
        del wb

    def show_about_dialog(self, event, data):
        util.show_about_dialog()

    def open_link(self, event, id):
        url = self.history.sites[int(id)][3]
        # Copy the url to the clipboard
        self.clipboard.set_text(url, len=-1)
        # Open the url in a browser
        util.open_url(url)

gobject.type_register(WebBoardApplet)

def webboard_applet_factory(applet, iid):
    WebBoardApplet(applet, iid)
    return gtk.TRUE

if __name__ == '__main__':
    # initialize gnome application and set up all the gnome internals
    gnome.init(constants.name, constants.version)

    # run it in a gtk window
    if len(sys.argv) > 1 and sys.argv[1] == "run-in-window":
        main_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        main_window.set_title("WebBoard")
        main_window.connect("destroy", gtk.main_quit) 
        app = gnomeapplet.Applet()
        webboard_applet_factory(app, None)
        app.reparent(main_window)
        main_window.show_all()
        gtk.main()
        sys.exit()
    else:
        gnomeapplet.bonobo_factory("OAFIID:GNOME_WebBoardApplet_Factory",
                                WebBoardApplet.__gtype__, 
                                "hello", "0", webboard_applet_factory)
