Пример #1
0
def main(argv):
    """Run the main program

    Depending on the commandline given and whether or not there is
    an instance of zim running already, this method may return
    immediatly, or go into the mainloop untill the program is exitted.

    @param argv: commandline arguments, e.g. from C{sys.argv}

    @raises UsageError: when number of arguments is not correct
    @raises GetOptError: when invalid options are found
    """
    global ZIM_EXECUTABLE

    # FIXME - this returns python.exe on my windows test
    ZIM_EXECUTABLE = argv[0]
    zim_exec_file = File(ZIM_EXECUTABLE)
    if zim_exec_file.exists():
        # We were given an absolute path, e.g. "python ./zim.py"
        ZIM_EXECUTABLE = zim_exec_file.path

    # Check for special commandline args for ipc, does not return
    # if handled
    import zim.ipc

    zim.ipc.handle_argv()

    # Let getopt parse the option list
    short = "".join(shortopts.keys())
    for s, l in shortopts.items():
        if l.endswith("="):
            short = short.replace(s, s + ":")
    long = list(longopts) + list(commands)
    for opts in commandopts.values():
        long.extend(opts)

    opts, args = gnu_getopt(argv[1:], short, long)

    # First figure out which command to execute
    cmd = "gui"  # default
    if opts:
        o = opts[0][0].lstrip("-")
        if o in shortopts:
            o = shortopts[o].rstrip("=")
        if o in commands:
            opts.pop(0)
            cmd = o

    # If it is a simple command execute it and return
    if cmd == "version":
        print "zim %s\n" % __version__
        print __copyright__, "\n"
        print __license__
        return
    elif cmd == "help":
        print usagehelp.replace("zim", argv[0])
        print optionhelp
        return

    # Otherwise check the number of arguments
    if cmd in maxargs and len(args) > maxargs[cmd]:
        raise UsageError

    # --manual is an alias for --gui /usr/share/zim/manual
    if cmd == "manual":
        cmd = "gui"
        args.insert(0, data_dir("manual").path)

    # Now figure out which options are allowed for this command
    allowedopts = list(longopts)
    allowedopts.extend(commandopts[cmd])

    # Convert options into a proper dict
    optsdict = {}
    for o, a in opts:
        o = str(o.lstrip("-"))  # str() -> no unicode for keys
        if o in shortopts:
            o = shortopts[o].rstrip("=")

        if o + "=" in allowedopts:
            o = o.replace("-", "_")
            optsdict[o] = a
        elif o in allowedopts:
            o = o.replace("-", "_")
            optsdict[o] = True
        else:
            raise GetoptError, ("--%s is not allowed in combination with --%s" % (o, cmd), o)

    # --port is the only option that is not of type string
    if "port" in optsdict and not optsdict["port"] is None:
        try:
            optsdict["port"] = int(optsdict["port"])
        except ValueError:
            raise GetoptError, ("--port takes an integer argument", "port")

    # set logging output level for logging root (format has been set in zim.py)
    if not ZIM_EXECUTABLE[-4:].lower() == ".exe":
        # for most platforms
        level = logging.WARN
    else:
        # if running from Windows compiled .exe
        level = logging.ERROR
    if optsdict.pop("verbose", False):
        level = logging.INFO
    if optsdict.pop("debug", False):
        level = logging.DEBUG  # no "elif" !
    logging.getLogger().setLevel(level)

    logger.info("This is zim %s", __version__)
    if level == logging.DEBUG:
        logger.debug("Python version is %s", str(sys.version_info))
        logger.debug("Platform is %s", os.name)
        logger.debug(get_zim_revision())
        log_basedirs()

    # Now we determine the class to handle this command
    # and start the application ...
    logger.debug("Running command: %s", cmd)
    if cmd in ("export", "index", "search"):
        if not len(args) >= 1:
            default = _get_default_or_only_notebook()
            if not default:
                raise UsageError
            handler = NotebookInterface(notebook=default)
        else:
            handler = NotebookInterface(notebook=args[0])

        handler.load_plugins()  # should this go somewhere else ?

        if cmd == "search":
            if not len(args) == 2:
                raise UsageError
            optsdict["query"] = args[1]
        elif len(args) == 2:
            optsdict["page"] = args[1]

        method = getattr(handler, "cmd_" + cmd)
        method(**optsdict)
    elif cmd == "gui":
        notebook = None
        page = None
        if args:
            from zim.notebook import resolve_notebook

            notebook, page = resolve_notebook(args[0])
            if not notebook:
                notebook = File(args[0]).uri
                # make sure daemon approves of this uri and proper
                # error dialog is shown as a result by GtkInterface
            if len(args) == 2:
                page = args[1]

        if "list" in optsdict:
            del optsdict["list"]  # do not use default
        elif not notebook:
            import zim.notebook

            default = _get_default_or_only_notebook()
            if default:
                notebook = default
                logger.info("Opening default notebook")

        # DGT: HACK for debuger
        if "standalone" in optsdict or DEBUG:
            import zim.gui

            try:
                del optsdict["standalone"]
            except:
                pass

            if not notebook:
                import zim.gui.notebookdialog

                notebook = zim.gui.notebookdialog.prompt_notebook()
                if not notebook:
                    return  # User canceled notebook dialog
            handler = zim.gui.GtkInterface(notebook, page, **optsdict)
            handler.main()
        else:
            from zim.ipc import start_server_if_not_running, ServerProxy

            if not notebook:
                import zim.gui.notebookdialog

                notebook = zim.gui.notebookdialog.prompt_notebook()
                if not notebook:
                    return  # User canceled notebook dialog

            start_server_if_not_running()
            server = ServerProxy()
            gui = server.get_notebook(notebook)
            gui.present(page, **optsdict)

            logger.debug(
                """
NOTE FOR BUG REPORTS:
    At this point zim has send the command to open a notebook to a
    background process and the current process will now quit.
    If this is the end of your debug output it is probably not useful
    for bug reports. Please close all zim windows, quit the
    zim trayicon (if any), and try again.
"""
            )
    elif cmd == "server":
        standalone = optsdict.pop("standalone", False)
        # No daemon support for server, so no option doesn't
        # do anything for now
        gui = optsdict.pop("gui", False)
        if gui:
            import zim.gui.server

            zim.gui.server.main(*args, **optsdict)
        else:
            import zim.www

            zim.www.main(*args, **optsdict)
    elif cmd == "plugin":
        import zim.plugins

        try:
            pluginname = args.pop(0)
        except IndexError:
            raise UsageError
        module = zim.plugins.get_plugin_module(pluginname)
        module.main(*args)
Пример #2
0
def main(argv):
	'''Run the main program.'''
	global ZIM_EXECUTABLE

	# FIXME - this returns python.exe on my windows test
	ZIM_EXECUTABLE = argv[0]
	if '/' in ZIM_EXECUTABLE or '\\' in ZIM_EXECUTABLE:
		ZIM_EXECUTABLE = File(ZIM_EXECUTABLE).path # abs path

	# Let getopt parse the option list
	short = ''.join(shortopts.keys())
	for s, l in shortopts.items():
		if l.endswith('='): short = short.replace(s, s+':')
	long = list(longopts) + list(commands)
	for opts in commandopts.values():
		long.extend(opts)

	opts, args = gnu_getopt(argv[1:], short, long)

	# First figure out which command to execute
	cmd = 'gui' # default
	if opts:
		o = opts[0][0].lstrip('-')
		if o in shortopts:
			o = shortopts[o].rstrip('=')
		if o in commands:
			opts.pop(0)
			cmd = o

	# If it is a simple command execute it and return
	if cmd == 'version':
		print 'zim %s\n' % __version__
		print __copyright__, '\n'
		print __license__
		return
	elif cmd == 'help':
		print usagehelp.replace('zim', argv[0])
		print optionhelp
		return

	# Otherwise check the number of arguments
	if len(args) > maxargs[cmd]:
		raise UsageError

	# --manual is an alias for --gui /usr/share/zim/manual
	if cmd == 'manual':
		cmd = 'gui'
		args.insert(0, data_dir('manual').path)

	# Now figure out which options are allowed for this command
	allowedopts = list(longopts)
	allowedopts.extend(commandopts[cmd])

	# Convert options into a proper dict
	optsdict = {}
	for o, a in opts:
		o = str(o.lstrip('-')) # str() -> no unicode for keys
		if o in shortopts:
			o = shortopts[o].rstrip('=')

		if o+'=' in allowedopts:
			o = o.replace('-', '_')
			optsdict[o] = a
		elif o in allowedopts:
			o = o.replace('-', '_')
			optsdict[o] = True
		else:
			raise GetoptError, ("--%s no allowed in combination with --%s" % (o, cmd), o)

	# --port is the only option that is not of type string
	if 'port' in optsdict and not optsdict['port'] is None:
		try:
			optsdict['port'] = int(optsdict['port'])
		except ValueError:
			raise GetoptError, ("--port takes an integer argument", 'port')

	# set loggin output level for logging root
	level = logging.WARNING
	if optsdict.pop('verbose', False): level = logging.INFO
	if optsdict.pop('debug', False): level = logging.DEBUG # no "elif" !
	logging.basicConfig(level=level, format='%(levelname)s: %(message)s')

	logger.info('This is zim %s', __version__)
	if level == logging.DEBUG:
		logger.debug('Python version is %s' % str(sys.version_info))
		try:
			from zim._version import version_info
			logger.debug(
				'Zim revision is:\n'
				'\tbranch: %(branch_nick)s\n'
				'\trevision: %(revno)d %(revision_id)s\n'
				'\tdate: %(date)s\n',
				version_info )
		except ImportError:
			logger.debug('No bzr version-info found')

		log_basedirs()

	# Now we determine the class to handle this command
	# and start the application ...
	logger.debug('Running command: %s', cmd)
	if cmd in ('export', 'index'):
		if not len(args) >= 1:
			import zim.notebook
			default = zim.notebook.get_default_notebook()
			handler = NotebookInterface(notebook=default)
		else:
			handler = NotebookInterface(notebook=args[0])

		if len(args) == 2:
			optsdict['page'] = args[1]

		method = getattr(handler, 'cmd_' + cmd)
		method(**optsdict)
	elif cmd == 'gui':
		notebook = None
		page = None
		if args:
			from zim.notebook import resolve_notebook
			notebook, page = resolve_notebook(args[0])
			if not notebook:
				notebook = args[0]
			if len(args) == 2:
				page = args[1]

		if 'list' in optsdict:
			del optsdict['list'] # do not use default
		elif not notebook:
			import zim.notebook
			default = zim.notebook.get_default_notebook()
			if default:
				notebook = default
				logger.info('Opening default notebook')

		if 'no_daemon' in optsdict or os.name == 'nt':
			import zim.gui
			try:
				del optsdict['no_daemon']
			except KeyError:
				pass
			if not notebook:
				import zim.gui.notebookdialog
				notebook = zim.gui.notebookdialog.prompt_notebook()
				if not notebook:
					return # User cancelled notebook dialog
			handler = zim.gui.GtkInterface(notebook, page, **optsdict)
			handler.main()
		else:
			import zim.daemon
			proxy = zim.daemon.DaemonProxy()
			if not notebook:
				# Need to call this after spawning the daemon, else we
				# have gtk loaded in the daemon process, and that causes
				# problems with using gtk in child processes.
				import zim.gui.notebookdialog
				notebook = zim.gui.notebookdialog.prompt_notebook()
				if not notebook:
					proxy.quit_if_nochild()
					return # User cancelled notebook dialog
			gui = proxy.get_notebook(notebook)
			gui.present(page, **optsdict)
	elif cmd == 'server':
		try:
			del optsdict['no_daemon']
		except KeyError:
			pass

		import zim.www
		handler = zim.www.Server(*args, **optsdict)
		handler.main()