示例#1
0
文件: main.py 项目: gdw2/zim
	def get_notebook_argument(self):
		'''Get the notebook and page arguments for this command
		@returns: a 2-tuple of an L{NotebookInfo} object and an
		optional L{Path} or C{(None, None)} if the notebook
		argument is optional and not given
		@raises NotebookLookupError: if the notebook is mandatory and
		not given, or if it is given but could not be resolved
		'''
		assert self.arguments[0] in ('NOTEBOOK', '[NOTEBOOK]')
		args = self.get_arguments()
		notebook = args[0]

		if notebook is None:
			notebook = self.get_default_or_only_notebook()
			if notebook:
				logger.info('Using default notebook: %s', notebook)
			elif self.arguments[0] == 'NOTEBOOK': # not optional
				raise NotebookLookupError, _('Please specify a notebook')
					# T: Error when looking up a notebook
			else:
				return None, None

		notebookinfo = resolve_notebook(notebook)
		if not notebookinfo:
			raise NotebookLookupError, _('Could not find notebook: %s') % notebook

		if len(self.arguments) > 1 \
		and self.arguments[1] in ('PAGE', '[PAGE]') \
		and args[1] is not None:
			pagename = Notebook.cleanup_pathname(args[1], purge=True)
			return notebookinfo, Path(pagename)
		else:
			return notebookinfo, None
示例#2
0
	def open_notebook(self, notebook):
		'''Open a notebook if no notebook was set already.
		'notebook' can be either a string, a File or Dir object or a
		Notebook object.

		If the notebook is a string which also specifies a page the page
		path is returned so it can be handled in a sub-class.
		'''
		from zim.notebook import resolve_notebook, get_notebook, Notebook
		assert self.notebook is None, 'BUG: other notebook opened already'
		assert not notebook is None, 'BUG: no notebook specified'

		logger.debug('Opening notebook: %s', notebook)
		if isinstance(notebook, (basestring, File, Dir)):
			if isinstance(notebook, basestring):
				nb, path = resolve_notebook(notebook)
			else:
				nb, path = notebook, None

			if not nb is None:
				nb = get_notebook(nb)

			if nb is None:
				raise NotebookLookupError, _('Could not find notebook: %s') % notebook
					# T: Error when looking up a notebook

			self.emit('open-notebook', nb)
			return path
		else:
			assert isinstance(notebook, Notebook)
			self.emit('open-notebook', notebook)
			return None
示例#3
0
    def get_notebook_argument(self):
        '''Get the notebook and page arguments for this command
		@returns: a 2-tuple of an L{NotebookInfo} object and an
		optional L{Path} or C{(None, None)} if the notebook
		argument is optional and not given
		@raises NotebookLookupError: if the notebook is mandatory and
		not given, or if it is given but could not be resolved
		'''
        assert self.arguments[0] in ('NOTEBOOK', '[NOTEBOOK]')
        args = self.get_arguments()
        notebook = args[0]

        if notebook is None:
            notebook = self.get_default_or_only_notebook()
            if notebook:
                logger.info('Using default notebook: %s', notebook)
            elif self.arguments[0] == 'NOTEBOOK':  # not optional
                raise NotebookLookupError, _('Please specify a notebook')
                # T: Error when looking up a notebook
            else:
                return None, None

        notebookinfo = resolve_notebook(notebook)
        if not notebookinfo:
            raise NotebookLookupError, _(
                'Could not find notebook: %s') % notebook
            # T: error message

        if len(self.arguments) > 1 \
        and self.arguments[1] in ('PAGE', '[PAGE]') \
        and args[1] is not None:
            pagename = Notebook.cleanup_pathname(args[1], purge=True)
            return notebookinfo, Path(pagename)
        else:
            return notebookinfo, None
示例#4
0
    def get_notebook_argument(self):
        '''Get the notebook and page arguments for this command
		@returns: a 2-tuple of an L{NotebookInfo} object and an
		optional L{Path} or C{(None, None)} if the notebook
		argument is optional and not given
		@raises NotebookLookupError: if the notebook is mandatory and
		not given, or if it is given but could not be resolved
		'''
        assert self.arguments[0] in ('NOTEBOOK', '[NOTEBOOK]')
        args = self.get_arguments()
        notebook = args[0]

        if notebook is None:
            if self.arguments[0] == 'NOTEBOOK':  # not optional
                raise NotebookLookupError(_('Please specify a notebook'))
                # T: Error when looking up a notebook
            else:
                return None, None

        notebookinfo = resolve_notebook(notebook, pwd=self.pwd)
        if not notebookinfo:
            raise NotebookLookupError(
                _('Could not find notebook: %s') % notebook)
            # T: error message

        if len(self.arguments) > 1 \
        and self.arguments[1] in ('PAGE', '[PAGE]') \
        and args[1] is not None:
            pagename = Path.makeValidPageName(args[1])
            return notebookinfo, Path(pagename)
        else:
            return notebookinfo, None
示例#5
0
    def get_default_or_only_notebook(self):
        '''Helper to get a default notebook'''
        notebooks = get_notebook_list()
        if notebooks.default:
            uri = notebooks.default.uri
        elif len(notebooks) == 1:
            uri = notebooks[0].uri
        else:
            return None

        return resolve_notebook(uri, pwd=self.pwd)  # None if not found
示例#6
0
文件: __init__.py 项目: Jam71/Zim-QDA
    def open_notebook(self, notebook):
        """Open the notebook object

        Open the notebook object for this interface if no notebook was
        set already.

        @param notebook: either a string, a L{File} or L{Dir} object,
        or a L{Notebook} object.

        When the notebook is not given as a Notebook object,
        L{zim.notebook.resolve_notebook()} is used to resolve it.
        If this method returns a page as well it is returned here
        so it can be handled in a sub-class.

        The reason that we call C{resolve_notebook()} from here (instead
        of resolving it first and than calling this method only with a
        notebook object) is that we want to allow active plugins to
        handle the notebook uri before loading the Notebook object
        (e.g. to auto-mount the notebook folder).

        @emits: open-notebook

        @returns: a L{Path} if any was specified in the notebook spec
        """
        from zim.notebook import resolve_notebook, get_notebook, Notebook

        assert self.notebook is None, "BUG: other notebook opened already"
        assert not notebook is None, "BUG: no notebook specified"

        logger.debug("Opening notebook: %s", notebook)
        if isinstance(notebook, (basestring, File, Dir)):
            if isinstance(notebook, basestring):
                nb, path = resolve_notebook(notebook)
            else:
                nb, path = notebook, None

            if not nb is None:
                self.emit("initialize-notebook", nb.uri)
                nb = get_notebook(nb)

            if nb is None:
                raise NotebookLookupError, _("Could not find notebook: %s") % notebook
                # T: Error when looking up a notebook

            self.emit("open-notebook", nb)
            return path
        else:
            assert isinstance(notebook, Notebook)
            self.emit("open-notebook", notebook)
            return None
    def run(self):
        if self.opts.get('help'):
            print usagehelp

            return

        if len(self.args) == 0:
            # TODO: find and open the default notebook
            notebook, ns = build_notebook(nb)
            print(notebook)
        else:
            nbi = resolve_notebook(self.args[0])
            notebook, ns = build_notebook(nbi)

        self.process_subpages(notebook, None)
示例#8
0
    def build_dialog(self):
        if 'notebook' in self.opts:
            notebook = resolve_notebook(self.opts['notebook'])
        else:
            notebook = None

        dialog = QuickNoteDialog(None,
                                 notebook=notebook,
                                 namespace=self.opts.get('namespace'),
                                 basename=self.opts.get('basename'),
                                 append=self.opts.get('append'),
                                 text=self.get_text(),
                                 template_options=self.template_options,
                                 attachments=self.opts.get('attachments'))
        dialog.show_all()
        return dialog
示例#9
0
    def run(self):
        if self.opts.get('help'):
            print usagehelp  # TODO handle this in the base class
        else:
            if 'notebook' in self.opts:
                notebook = resolve_notebook(self.opts['notebook'])
            else:
                notebook = None

            dialog = QuickNoteDialog(None,
                                     notebook=notebook,
                                     namespace=self.opts.get('namespace'),
                                     basename=self.opts.get('basename'),
                                     append=self.opts.get('append'),
                                     text=self.get_text(),
                                     template_options=self.template_options,
                                     attachments=self.opts.get('attachments'))
            dialog.show_all()
            return dialog
示例#10
0
    def run(self):
        if self.opts.get('help'):
            print usagehelp  # TODO handle this in Command base class
        else:
            gtk_window_set_default_icon()

            if 'notebook' in self.opts:
                notebook = resolve_notebook(self.opts['notebook'])
            else:
                notebook = None

            dialog = QuickNoteDialog(None,
                                     notebook=notebook,
                                     namespace=self.opts.get('namespace'),
                                     basename=self.opts.get('basename'),
                                     append=self.opts.get('append'),
                                     text=self.get_text(),
                                     template_options=self.template_options,
                                     attachments=self.opts.get('attachments'))
            dialog.run()
示例#11
0
	def run(self):
		if self.opts.get('help'):
			print usagehelp # TODO handle this in Command base class
		else:
			gtk_window_set_default_icon()

			if 'notebook' in self.opts:
				notebook = resolve_notebook(self.opts['notebook'])
			else:
				notebook = None

			dialog = QuickNoteDialog(None,
				notebook=notebook,
				namespace=self.opts.get('namespace'),
				basename=self.opts.get('basename'),
				append=self.opts.get('append'),
				text=self.get_text(),
				template_options=self.template_options,
				attachments=self.opts.get('attachments')
			)
			dialog.run()
示例#12
0
    def run(self):
        if self.opts.get('help'):
            print usagehelp

            return

        nbi = None

        if len(self.args) > 0:
            nbi = resolve_notebook(self.args[0])

        if nbi is None:
            print("Notebook must be specified!")

            return

        self.nb, ns = build_notebook(nbi)

        listing = None

        if self.opts.get('missing-only'):
            listing = 'M'

        if self.opts.get('existing-only'):
            if listing == 'M':
                print """\
--missing-only and --existing-only are mutually exclusive!"""

                return

            listing = 'E'

        for page in self._all_links():
            exists = page.exists()

            if listing is None or \
               (listing == 'M' and exists == 0) or \
               (listing == 'E' and exists == 1):
                print "%c %s" % ('E' if exists == 1 else 'M', page.name)
示例#13
0
def main(*args):
	options = {}
	template_options = {}
	for arg in args:
		if arg.startswith('option:'):
			arg = arg[7:]
			dict = template_options
		else:
			dict = options

		if '=' in arg:
			key, value = arg.split('=', 1)
			dict[key] = value
		else:
			dict[arg] = True
	#~ print 'OPTIONS:', options, template_options

	if 'help' in options:
		print usagehelp
		return

	if 'notebook' in options:
		notebook, page = resolve_notebook(options['notebook'])
	else:
		notebook = None

	if 'append' in options:
		if options['append'].lower() == 'true':
			options['append'] = True
		else:
			options['append'] = False

	if 'input' in options:
		if options['input'] == 'stdin':
			import sys
			text = sys.stdin.read()
		elif options['input'] == 'clipboard':
			text = \
				SelectionClipboard.get_text() \
				or Clipboard.get_text()
	else:
		text = options.get('text')

	if text and options.get('encoding'):
		if options['encoding'] == 'base64':
			import base64
			text = base64.b64decode(text)
		elif options['encoding'] == 'url':
			from zim.parsing import url_decode, URL_ENCODE_DATA
			text = url_decode(text, mode=URL_ENCODE_DATA)
		else:
			raise AssertionError, 'Unknown encoding: %s' % options['encoding']

	if text and not isinstance(text, unicode):
		text = text.decode('utf-8')

	icon = data_file('zim.png').path
	gtk_window_set_default_icon()

	dialog = QuickNoteDialog(None,
		notebook,
		options.get('namespace'), options.get('basename'),
		options.get('append'),
		text,
		template_options,
		options.get('attachments')
	)
	dialog.run()
示例#14
0
def main(*args):
    options = {}
    template_options = {}
    for arg in args:
        if arg.startswith("option:"):
            arg = arg[7:]
            dict = template_options
        else:
            dict = options

        if "=" in arg:
            key, value = arg.split("=", 1)
            dict[key] = value
        else:
            dict[arg] = True
    # ~ print 'OPTIONS:', options, template_options

    if "help" in options:
        print usagehelp
        return

    if "notebook" in options:
        notebook, page = resolve_notebook(options["notebook"])
    else:
        notebook = None

    if "append" in options:
        if options["append"].lower() == "true":
            options["append"] = True
        else:
            options["append"] = False

    if "input" in options:
        if options["input"] == "stdin":
            import sys

            text = sys.stdin.read()
        elif options["input"] == "clipboard":
            text = SelectionClipboard.get_text() or Clipboard.get_text()
    else:
        text = options.get("text")

    if text and options.get("encoding"):
        if options["encoding"] == "base64":
            import base64

            text = base64.b64decode(text)
        elif options["encoding"] == "url":
            from zim.parsing import url_decode, URL_ENCODE_DATA

            text = url_decode(text, mode=URL_ENCODE_DATA)
        else:
            raise AssertionError, "Unknown encoding: %s" % options["encoding"]

    if text and not isinstance(text, unicode):
        text = text.decode("utf-8")

    icon = data_file("zim.png").path
    gtk_window_set_default_icon()

    dialog = QuickNoteDialog(
        None,
        notebook,
        options.get("namespace"),
        options.get("basename"),
        options.get("append"),
        text,
        template_options,
        options.get("attachments"),
    )
    dialog.run()
示例#15
0
文件: __init__.py 项目: Jam71/Zim-QDA
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)
示例#16
0
    def run(self):
        if not self.opts or self.opts.get('help'):
            print usagehelp
        else:
            _raise = 'raise' in self.opts
            _show = 'show' in self.opts

            if 'notebook' in self.opts:
                notebookInfo = resolve_notebook(self.opts['notebook'])
            else:
                notebookInfo = resolve_notebook(defaultNotebook)

            print 'NotebookInfo=', notebookInfo

            # The notion of 'today' might extend into the wee hours of the morning.
            offset_time = datetime.today() - timedelta(
                hours=hours_past_midnight)
            todaysJournal = offset_time.strftime(':Journal:%Y:%m:%d')

            if 'page' in self.opts:
                pagename = self.opts['page']
            elif 'journal' in self.opts:
                pagename = todaysJournal
            elif 'date' in self.opts:
                pagename = parse(
                    self.opts['date']).strftime(':Journal:%Y:%m:%d')
            else:
                print self.opts
                raise Exception, 'you must somehow identify a page to modify'

            print 'Pagename=', pagename

            ui = None
            notebook = None

            if (zim66):
                server = ZIM_APPLICATION
                #print ZIM_APPLICATION._running
                for window in ZIM_APPLICATION._windows:
                    if window.ui.notebook.uri == notebookInfo.uri:
                        notebook = window.ui.notebook
                        ui = window.ui
                        break
                    else:
                        logger.debug("not it: '%s' != '%s'",
                                     window.ui.notebook.uri, notebookInfo.uri)
            else:
                start_server_if_not_running()
                server = ServerProxy()
                pprint.pprint(server.list_objects())
                ui = server.get_notebook(notebookInfo, _raise or _show)
                notebook = ui.notebook

            print 'Server=', server
            print 'UI=', ui
            print 'Notebook?=', notebook

            quoting = ('quote' in self.opts)

            text = ''
            emptyString = False

            if 'literal' in self.opts:
                if type(self.opts['literal']) == bool:
                    emptyString = True
                else:
                    text += self.opts['literal']

            if 'time' in self.opts:
                print "time(): ", time.time()
                print "timezone: ", time.tzname
                print "localtime: ", time.localtime()
                if pagename == todaysJournal:
                    # It's log-like... all the same day... so don't include the full date...
                    text = strftime('%I:%M%P - ') + text
                else:
                    text = strftime('%Y-%m-%d @ %I:%M%P - ') + text

            if 'file' in self.opts:
                #if not quoting:
                #	text += '\n{0}:\n'.format(self.opts['file'])
                text += open(self.opts['file']).read()

            if 'clipboard' in self.opts:
                text += SelectionClipboard.get_text() or Clipboard.get_text()

            # BUG: This does not work, because this code executes in the main zim process...
            # we need a pre-handoff hook to convert it to a '--literal', or similar.
            if 'stdin' in self.opts:
                import sys
                text += sys.stdin.read()

            # --------------------------------------------------------------------------------

            if text and quoting:
                text = "'''\n{0}\n'''".format(text)

            didSomething = False

            if text or emptyString:
                # BUG: the journal template is not used for new pages...
                # BUG: If the page does not exist, then we assume that it cannot be 'open'... while generally true, this is probably technically incorrect for stub pages just-navigated-to (but not yet saved).
                if self.pageExists(notebookInfo, pagename):
                    print 'Page exists...'

                    if 'create' in self.opts:
                        raise Exception, 'Page already exists: ' + pagename

                    if ui is None:
                        self._direct_append(notebookInfo, pagename, text)
                    else:
                        ui.append_text_to_page(pagename, text)
                elif ui is None:
                    self._direct_create(notebookInfo, pagename, text)
                elif self.likelyHasChildPages(ui, notebookInfo, pagename):
                    print 'Page dne, but has children... yuck...'
                    # The new_page_from_text function would create enumerated side-pages...
                    # so we can't use the template when creating a new page... :-(
                    #text = (
                    #	"====== " + pagename + " ======\n"
                    #	"https://github.com/Osndok/zim-plugin-append/issues/1\n\n"
                    #	+text
                    #)
                    #ui.append_text_to_page(pagename, text);
                    path = ui.notebook.pages.lookup_from_user_input(pagename)
                    page = ui.notebook.get_page(
                        path)  # as opposed to 'get_new_page' (!!!!)
                    parsetree = ui.notebook.get_template(page)
                    page.set_parsetree(parsetree)
                    page.parse('wiki', text,
                               append=True)  # FIXME format hard coded
                    ui.notebook.store_page(page)
                else:
                    print 'Page does not exist'

                    if 'exists' in self.opts:
                        raise Exception, 'Page does not exist: ' + pagename

                    ui.new_page_from_text(text,
                                          name=pagename,
                                          use_template=True)

                didSomething = True

            #BUG: these features don't work without 'ui'...

            if 'directory' in self.opts:
                ui.import_attachments(path, self.opts['directory'])
                didSomething = True

            if 'attach' in self.opts:
                if zim66:
                    attachments = notebook.get_attachments_dir(path)
                    file = dir.file(name)
                    if file.isdir():
                        print 'BUG: dont know how to handle folders in 0.66'
                    else:
                        file.copyto(attachments)
                else:
                    ui.do_attach_file(path, self.opts['attach'])

            if _raise or _show:
                if ui:
                    ui.present(pagename)
                    didSomething = True
                else:
                    print 'ERROR: unable to raise/show window, no UI running'
示例#17
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()