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
13 from zeroinstall
.injector
import namespaces
15 _template
= """[Desktop Entry]
16 # This file was generated by zero2desktop.
17 # See the Zero Install project for details: http://0install.net
22 Exec=%(0launch)s -- %(iface)s %%f
23 Categories=Application;%(category)s
26 _icon_template
= """Icon=%s
29 def add_to_menu(iface
, icon_path
, category
, zlaunch
=None):
30 """Write a .desktop file for this application.
31 @param iface: the program being added
32 @param icon_path: the path of the icon, or None
33 @param category: the freedesktop.org menu category"""
34 tmpdir
= tempfile
.mkdtemp(prefix
= 'zero2desktop-')
36 desktop_name
= os
.path
.join(tmpdir
, 'zeroinstall-%s.desktop' % iface
.get_name().lower().replace(os
.sep
, '-').replace(' ', ''))
37 desktop
= file(desktop_name
, 'w')
38 desktop
.write(_template
% {'name': iface
.get_name(),
39 'comment': iface
.summary
,
40 '0launch': zlaunch
or '0launch',
42 'category': category
})
44 desktop
.write(_icon_template
% icon_path
)
45 if len(iface
.get_metadata(namespaces
.XMLNS_IFACE
, 'needs-terminal')):
46 desktop
.write('Terminal=true\n')
48 status
= os
.spawnlp(os
.P_WAIT
, 'xdg-desktop-menu', 'xdg-desktop-menu', 'install', desktop_name
)
53 raise SafeException(_('Failed to run xdg-desktop-menu (error code %d)') % status
)
55 def discover_existing_apps():
56 """Search through the configured XDG datadirs looking for .desktop files created by L{add_to_menu}.
57 @return: a map from application URIs to .desktop filenames"""
58 already_installed
= {}
59 for d
in basedir
.load_data_paths('applications'):
60 for desktop_file
in os
.listdir(d
):
61 if desktop_file
.startswith('zeroinstall-') and desktop_file
.endswith('.desktop'):
62 full
= os
.path
.join(d
, desktop_file
)
64 for line
in file(full
):
66 if line
.startswith('Exec=0launch '):
67 bits
= line
.split(' -- ', 1)
69 uri
= bits
[0].split(' ', 1)[1] # 0launch URI -- %u
71 uri
= bits
[1].split(' ', 1)[0].strip() # 0launch -- URI %u
72 already_installed
[uri
] = full
75 info(_("Failed to find Exec line in %s"), full
)
77 warn(_("Failed to load .desktop file %(filename)s: %(exceptions"), {'filename': full
, 'exception': ex
})
78 return already_installed