1 """Adding icons and menu items using the freedesktop.org system.
2 (xdg = X Desktop Group)
4 # Copyright (C) 2009, Thomas Leonard
5 # See the README file for details, or visit http://0install.net.
7 from zeroinstall
import _
8 import shutil
, os
, tempfile
9 from logging
import info
, warn
11 from zeroinstall
import SafeException
12 from zeroinstall
.support
import basedir
14 _template
= """[Desktop Entry]
15 # This file was generated by zero2desktop.
16 # See the Zero Install project for details: http://0install.net
21 Exec=0launch -- %s %%f
22 Categories=Application;%s
25 _icon_template
= """Icon=%s
28 def add_to_menu(iface
, icon_path
, category
):
29 """Write a .desktop file for this application.
30 @param iface: the program being added
31 @param icon_path: the path of the icon, or None
32 @param category: the freedesktop.org menu category"""
33 tmpdir
= tempfile
.mkdtemp(prefix
= 'zero2desktop-')
35 desktop_name
= os
.path
.join(tmpdir
, 'zeroinstall-%s.desktop' % iface
.get_name().lower().replace(' ', ''))
36 desktop
= file(desktop_name
, 'w')
37 desktop
.write(_template
% (iface
.get_name(), iface
.summary
, iface
.uri
, category
))
39 desktop
.write(_icon_template
% icon_path
)
41 status
= os
.spawnlp(os
.P_WAIT
, 'xdg-desktop-menu', 'xdg-desktop-menu', 'install', desktop_name
)
46 raise SafeException(_('Failed to run xdg-desktop-menu (error code %d)') % status
)
48 def discover_existing_apps():
49 """Search through the configured XDG datadirs looking for .desktop files created by L{add_to_menu}.
50 @return: a map from application URIs to .desktop filenames"""
51 already_installed
= {}
52 for d
in basedir
.load_data_paths('applications'):
53 for desktop_file
in os
.listdir(d
):
54 if desktop_file
.startswith('zeroinstall-') and desktop_file
.endswith('.desktop'):
55 full
= os
.path
.join(d
, desktop_file
)
57 for line
in file(full
):
59 if line
.startswith('Exec=0launch '):
60 bits
= line
.split(' -- ', 1)
62 uri
= bits
[0].split(' ', 1)[1] # 0launch URI -- %u
64 uri
= bits
[1].split(' ', 1)[0].strip() # 0launch -- URI %u
65 already_installed
[uri
] = full
68 info(_("Failed to find Exec line in %s"), full
)
70 warn(_("Failed to load .desktop file %(filename)s: %(exceptions"), {'filename': full
, 'exception': ex
})
71 return already_installed