1""" 2Convenience routines for performing common operations. 3@since: 0.28 4""" 5 6# Copyright (C) 2009, Thomas Leonard 7# See the README file for details, or visit http://0install.net. 8 9from__future__importprint_function 10 11importos,sys 12fromzeroinstallimportsupport,SafeException,logger 13fromzeroinstall.supportimporttasks 14 15DontUseGUI=object() 16
18"""Run the GUI to choose and download a set of implementations. 19 The user may ask the GUI to submit a bug report about the program. In that case, 20 the GUI may ask us to test it. test_callback is called in that case with the implementations 21 to be tested; the callback will typically call L{zeroinstall.injector.run.test_selections} and return the result of that. 22 @param iface_uri: the required program, or None to show just the preferences dialog 23 @type iface_uri: str 24 @param gui_args: any additional arguments for the GUI itself 25 @type gui_args: [str] 26 @param test_callback: function to use to try running the program 27 @type test_callback: L{zeroinstall.injector.selections.Selections} -> str 28 @param use_gui: if True, raise a SafeException if the GUI is not available. If None, returns DontUseGUI if the GUI cannot be started. If False, returns DontUseGUI always. (since 1.11) 29 @type use_gui: bool | None 30 @return: the selected implementations 31 @rtype: L{zeroinstall.injector.selections.Selections} 32 @since: 0.28""" 33ifuse_guiisFalse: 34returnDontUseGUI 35 36ifnotos.environ.get('DISPLAY',None): 37ifuse_guiisNone: 38returnDontUseGUI 39else: 40raiseSafeException("Can't use GUI because $DISPLAY is not set") 41 42fromzeroinstall.injectorimportselections,qdom 43fromioimportBytesIO 44 45fromos.pathimportjoin,dirname 46gui_exe=join(dirname(__file__),'0launch-gui','0launch-gui') 47 48importsocket 49cli,gui=socket.socketpair() 50 51try: 52child=os.fork() 53ifchild==0: 54# We are the child (GUI) 55try: 56try: 57cli.close() 58# We used to use pipes to support Python2.3... 59os.dup2(gui.fileno(),1) 60os.dup2(gui.fileno(),0) 61ifuse_guiisTrue: 62gui_args=['-g']+gui_args 63ififace_uriisnotNone: 64gui_args=gui_args+['--',iface_uri] 65os.execvp(sys.executable,[sys.executable,gui_exe]+gui_args) 66except: 67importtraceback 68traceback.print_exc(file=sys.stderr) 69finally: 70sys.stderr.flush() 71os._exit(1) 72# We are the parent (CLI) 73gui.close() 74gui=None 75 76whileTrue: 77logger.info("Waiting for selections from GUI...") 78 79reply=support.read_bytes(cli.fileno(),len('Length:')+9,null_ok=True) 80ifreply: 81ifnotreply.startswith(b'Length:'): 82raiseException("Expected Length:, but got %s"%repr(reply)) 83reply=reply.decode('ascii') 84xml=support.read_bytes(cli.fileno(),int(reply.split(':',1)[1],16)) 85 86dom=qdom.parse(BytesIO(xml)) 87sels=selections.Selections(dom) 88 89ifdom.getAttribute('run-test'): 90logger.info("Testing program, as requested by GUI...") 91iftest_callbackisNone: 92output=b"Can't test: no test_callback was passed to get_selections_gui()\n" 93else: 94output=test_callback(sels) 95logger.info("Sending results to GUI...") 96output=('Length:%8x\n'%len(output)).encode('utf-8')+output 97logger.debug("Sending: %s",repr(output)) 98whileoutput: 99sent=cli.send(output)100output=output[sent:]101continue102else:103sels=None104105pid,status=os.waitpid(child,0)106assertpid==child107ifstatus==1<<8:108logger.info("User cancelled the GUI; aborting")109returnNone# Aborted110elifstatus==100<<8:111ifuse_guiisNone:112returnDontUseGUI113else:114raiseSafeException("No GUI available")115ifstatus!=0:116raiseException("Error from GUI: code = %d"%status)117break118finally:119forsockin[cli,gui]:120ifsockisnotNone:sock.close()121122returnsels
155"""Exec the man command to show the man-page for this interface.156 Never returns.157 @type stores: L{zeroinstall.zerostore.Stores}158 @type sels: L{zeroinstall.injector.selections.Selections}159 @type main: str | None160 @type fallback_name: str | None161 @since: 1.12"""162interface_uri=sels.interface163selected_impl=sels.selections[interface_uri]164165ifselected_impl.id.startswith('package'):166impl_path=None167else:168impl_path=selected_impl.get_path(stores)169170ifmainisNone:171ifsels.commands:172selected_command=sels.commands[0]173else:174print("No <command> in selections!",file=sys.stderr)175sys.exit(1)176main=selected_command.path177ifmainisNone:178print("No main program for interface '%s'"%interface_uri,file=sys.stderr)179sys.exit(1)180181prog_name=os.path.basename(main)182183ifimpl_pathisNone:184# Package implementation185logger.debug("Searching for man-page native command %s (from %s)"%(prog_name,fallback_name))186os.execlp('man','man',prog_name)187188assertimpl_path189190logger.debug("Searching for man-page for %s or %s in %s"%(prog_name,fallback_name,impl_path))191192# TODO: the feed should say where the man-pages are, but for now we'll accept193# a directory called man in some common locations...194formandirin['man','share/man','usr/man','usr/share/man']:195manpath=os.path.join(impl_path,mandir)196ifos.path.isdir(manpath):197# Note: unlike "man -M", this also copes with LANG settings...198os.environ['MANPATH']=manpath199os.execlp('man','man',prog_name)200sys.exit(1)201202# No man directory given or found, so try searching for man files203204manpages=[]205forroot,dirs,filesinos.walk(impl_path):206forfinfiles:207iff.endswith('.gz'):208manpage_file=f[:-3]209else:210manpage_file=f211ifmanpage_file.endswith('.1')or \ 212manpage_file.endswith('.6')or \ 213manpage_file.endswith('.8'):214manpage_prog=manpage_file[:-2]215ifmanpage_prog==prog_nameormanpage_prog==fallback_name:216os.execlp('man','man',os.path.join(root,f))217sys.exit(1)218else:219manpages.append((root,f))220fordinlist(dirs):221ifd.startswith('.'):222dirs.remove(d)223224print("No matching manpage was found for '%s' (%s)"%(fallback_name,interface_uri))225ifmanpages:226print("These non-matching man-pages were found, however:")227forroot,fileinmanpages:228print(os.path.join(root,file))229sys.exit(1)