Import _ into each module rather than using a builtin
[zeroinstall.git] / zeroinstall / gtkui / xdgutils.py
blob403eebbcb9c6a7693deb0650fc344d445da53cc0
1 """Adding icons and menu items using the freedesktop.org system.
2 (xdg = X Desktop Group)
3 """
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
17 Type=Application
18 Version=1.0
19 Name=%s
20 Comment=%s
21 Exec=0launch -- %s %%f
22 Categories=Application;%s
23 """
25 _icon_template = """Icon=%s
26 """
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-')
34 try:
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))
38 if icon_path:
39 desktop.write(_icon_template % icon_path)
40 desktop.close()
41 status = os.spawnlp(os.P_WAIT, 'xdg-desktop-menu', 'xdg-desktop-menu', 'install', desktop_name)
42 finally:
43 shutil.rmtree(tmpdir)
45 if status:
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)
56 try:
57 for line in file(full):
58 line = line.strip()
59 if line.startswith('Exec=0launch '):
60 bits = line.split(' -- ', 1)
61 if ' ' in bits[0]:
62 uri = bits[0].split(' ', 1)[1] # 0launch URI -- %u
63 else:
64 uri = bits[1].split(' ', 1)[0].strip() # 0launch -- URI %u
65 already_installed[uri] = full
66 break
67 else:
68 info(_("Failed to find Exec line in %s"), full)
69 except Exception, ex:
70 warn(_("Failed to load .desktop file %(filename)s: %(exceptions"), {'filename': full, 'exception': ex})
71 return already_installed