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. 6 7fromzeroinstallimport_,logger 8importshutil,os,tempfile 910fromzeroinstallimportSafeException11fromzeroinstall.supportimportbasedir12fromzeroinstall.injectorimportnamespaces1314_template="""[Desktop Entry]15# This file was generated by 0install.16# See the Zero Install project for details: http://0install.net17Type=Application18Version=1.019Name=%(name)s20Comment=%(comment)s21Exec=%(0launch)s -- %(iface)s %%f22Categories=Application;%(category)s23"""2425_icon_template="""Icon=%s26"""27
29"""Write a .desktop file for this application.30 @param iface: the program being added31 @param icon_path: the path of the icon, or None32 @param category: the freedesktop.org menu category"""33tmpdir=tempfile.mkdtemp(prefix='zero2desktop-')34try:35desktop_name=os.path.join(tmpdir,'zeroinstall-%s.desktop'%iface.get_name().lower().replace(os.sep,'-').replace(' ',''))36desktop=open(desktop_name,'w')37desktop.write(_template%{'name':iface.get_name(),38'comment':iface.summary,39'0launch':zlaunchor'0launch',40'iface':iface.uri,41'category':category})42ificon_path:43desktop.write(_icon_template%icon_path)44iflen(iface.get_metadata(namespaces.XMLNS_IFACE,'needs-terminal')):45desktop.write('Terminal=true\n')46desktop.close()47status=os.spawnlp(os.P_WAIT,'xdg-desktop-menu','xdg-desktop-menu','install',desktop_name)48finally:49shutil.rmtree(tmpdir)5051ifstatus:52raiseSafeException(_('Failed to run xdg-desktop-menu (error code %d)')%status)
55"""Search through the configured XDG datadirs looking for .desktop files created by L{add_to_menu}.56 @return: a map from application URIs to .desktop filenames"""57already_installed={}58fordinbasedir.load_data_paths('applications'):59fordesktop_fileinos.listdir(d):60ifdesktop_file.startswith('zeroinstall-')anddesktop_file.endswith('.desktop'):61full=os.path.join(d,desktop_file)62try:63withopen(full,'rt')asstream:64forlineinstream:65line=line.strip()66ifline.startswith('Exec=0launch '):67bits=line.split(' -- ',1)68if' 'inbits[0]:69uri=bits[0].split(' ',1)[1]# 0launch URI -- %u70else:71uri=bits[1].split(' ',1)[0].strip()# 0launch -- URI %u72already_installed[uri]=full73break74else:75logger.info(_("Failed to find Exec line in %s"),full)76exceptExceptionasex:77logger.warning(_("Failed to load .desktop file %(filename)s: %(exceptions"),{'filename':full,'exception':ex})78returnalready_installed