#!/usr/bin/python
# -*- encoding: utf-8 -*- 
#
# Author: Victor Ananjevsky, 2007
# based on xdg-menu.py, writen by Piotr Zielinski (http://www.cl.cam.ac.uk/~pz215/)
# Licence: GPL
#
# This script takes names of menu files conforming to the XDG Desktop
# Menu Specification, and outputs their FVWM equivalents to the
# standard output.
#
#   http://standards.freedesktop.org/menu-spec/latest/
#
# Requirements:
#   pyxdg, pygtk, gnome-menus
#
# Syntax:
#   fvwm-xdg-menu.py menufile1 menufile2 menufile3 ...
#
# Each menufile is an XDG menu description file.
# Icons of menu entries cached in $XDG_CACHE_HOME/fvwm/icons/menu
#
# Example:
#   fvwm-xdg-menu.py /etc/xdg/menus/applications.menu
#   fvwm-xdg-menu.py applications
#


import sys
import os
import xdg.Menu
from xdg.DesktopEntry import *
from xdg.BaseDirectory import xdg_config_dirs, xdg_cache_home
import gtk


# Default size for cached icons
icon_size = 16


# fix for correct output of unicode chars without terminal
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)


def cache_icon (icon):
    ''' cache an icon  '''
    icon_file = "%s/fvwm/menu/%s.png" % (xdg_cache_home, icon)
    if os.path.exists(icon_file):
        return
    icon_theme = gtk.icon_theme_get_default()
    try:
        icon_theme.load_icon(icon, icon_size, gtk.ICON_LOOKUP_NO_SVG).save(icon_file, "png")
    except:
        pass


def parse_menu (menu):
    ''' parse menu file '''
    print ''
    print 'DestroyMenu "%s"' % menu
    print 'AddToMenu "%s"' % menu

    for entry in menu.getEntries():
	if isinstance(entry, xdg.Menu.Menu):
            icon = entry.getIcon()
            print u'+ "%s%%menu/folder.png%%" Popup %s' % (entry.getName(), entry)
	elif isinstance(entry, xdg.Menu.MenuEntry):
            desktop = DesktopEntry(entry.DesktopEntry.getFileName())
            icon = desktop.getIcon()
            ind = icon.rfind('.')
            if ind != -1:
                icon = icon[0:ind]
            cmd = desktop.getExec().rstrip('%FU')
            cache_icon(icon)
            print u'+ "%s%%menu/%s.png%%" Exec exec %s' % (desktop.getName(), icon, cmd)
	else:
	    pass

    for entry in menu.getEntries():
	if isinstance(entry, xdg.Menu.Menu):
	    parse_menu(entry)


# Start

cache_path = "%s/fvwm/menu" % xdg_cache_home
if not os.path.exists(cache_path):
    os.makedirs(cache_path)

for arg in sys.argv[1:]:
    filename = ""
    if os.path.exists(arg):
        filename = arg
    else:
        tmpfile = "%s/menus/%s.menu" % (xdg_config_home, arg)
        if os.path.exists(tmpfile):
            filename = tmpfile
        else:
            for dir in xdg_config_dirs:
                tmpfile = "%s/menus/%s.menu" % (dir, arg)
                if os.path.exists(tmpfile):
                    filename = tmpfile
                    break
    if filename == "":
        continue
    parse_menu(xdg.Menu.parse(filename))
        
