Exemplo n.º 1
0
	def testMain(self):
		def has_text(text):
			# create the actual check function
			def my_has_text(dialog):
				self.assertIsInstance(dialog, QuickNoteDialog)
				buffer = dialog.textview.get_buffer()
				result = buffer.get_text(*buffer.get_bounds())
				#~ print result
				self.assertTrue(text in result)

			return my_has_text

		# Text on commandline
		text = 'foo bar baz\ndus 123'
		with tests.DialogContext(has_text(text)):
			main('text=' + text)

		# Clipboard input
		text = 'foo bar baz\ndus 123'
		SelectionClipboard.clipboard.clear() # just to be sure
		Clipboard.set_text(text)
		with tests.DialogContext(has_text(text)):
			main('input=clipboard')

		text = 'foo bar baz\ndus 456'
		SelectionClipboard.set_text(text)
		with tests.DialogContext(has_text(text)):
			main('input=clipboard')
Exemplo n.º 2
0
	def testMain(self):
		# Text on commandline
		text = 'foo bar baz\ndus 123'
		self.assertRun(('text=' + text,), text)
		self.assertRun(('--text', text), text)

		encoded = 'Zm9vIGJhciBiYXoKZHVzIDEyMwo='
		self.assertRun(('--text', encoded, '--encoding', 'base64'), text)

		encoded = 'foo%20bar%20baz%0Adus%20123'
		self.assertRun(('--text', encoded, '--encoding', 'url'), text)

		# Clipboard input
		text = 'foo bar baz\ndus 123'
		SelectionClipboard.clipboard.clear() # just to be sure
		Clipboard.set_text(text)
		self.assertRun(('input=clipboard',), text)
		self.assertRun(('--input', 'clipboard',), text)

		text = 'foo bar baz\ndus 456'
		SelectionClipboard.set_text(text)
		self.assertRun(('input=clipboard',), text)
		self.assertRun(('--input', 'clipboard',), text)

		# Template options
		cmd = QuickNotePluginCommand('quicknote')
		cmd.parse_options('option:url=foo')
		self.assertEqual(cmd.template_options, {'url': 'foo'})

		cmd = QuickNotePluginCommand('quicknote')
		cmd.parse_options('--option', 'url=foo')
		self.assertEqual(cmd.template_options, {'url': 'foo'})
Exemplo n.º 3
0
	def testMain(self):
		def main(*args):
			cmd = QuickNotePluginCommand('quicknote')
			cmd.parse_options(*args)
			cmd.run()

		def has_text(text):
			# create the actual check function
			def my_has_text(dialog):
				self.assertIsInstance(dialog, QuickNoteDialog)
				buffer = dialog.textview.get_buffer()
				result = buffer.get_text(*buffer.get_bounds())
				self.assertTrue(text in result)

			return my_has_text

		# Text on commandline
		text = 'foo bar baz\ndus 123'
		with tests.DialogContext(has_text(text)):
			main('text=' + text)

		with tests.DialogContext(has_text(text)):
			main('--text', text)

		encoded = 'Zm9vIGJhciBiYXoKZHVzIDEyMwo='
		with tests.DialogContext(has_text(text)):
			main('--text', encoded, '--encoding', 'base64')

		encoded = 'foo%20bar%20baz%0Adus%20123'
		with tests.DialogContext(has_text(text)):
			main('--text', encoded, '--encoding', 'url')

		# Clipboard input
		text = 'foo bar baz\ndus 123'
		SelectionClipboard.clipboard.clear() # just to be sure
		Clipboard.set_text(text)
		with tests.DialogContext(has_text(text)):
			main('input=clipboard')

		with tests.DialogContext(has_text(text)):
			main('--input', 'clipboard')

		text = 'foo bar baz\ndus 456'
		SelectionClipboard.set_text(text)
		with tests.DialogContext(has_text(text)):
			main('input=clipboard')

		with tests.DialogContext(has_text(text)):
			main('--input', 'clipboard')

		# Template options
		cmd = QuickNotePluginCommand('quicknote')
		cmd.parse_options('option:url=foo')
		self.assertEqual(cmd.template_options, {'url': 'foo'})

		cmd = QuickNotePluginCommand('quicknote')
		cmd.parse_options('--option', 'url=foo')
		self.assertEqual(cmd.template_options, {'url': 'foo'})
Exemplo n.º 4
0
    def testMain(self):
        def main(*args):
            cmd = QuickNotePluginCommand('quicknote')
            cmd.parse_options(*args)
            cmd.run()

        def has_text(text):
            # create the actual check function
            def my_has_text(dialog):
                self.assertIsInstance(dialog, QuickNoteDialog)
                buffer = dialog.textview.get_buffer()
                result = buffer.get_text(*buffer.get_bounds())
                self.assertTrue(text in result)

            return my_has_text

        # Text on commandline
        text = 'foo bar baz\ndus 123'
        with tests.DialogContext(has_text(text)):
            main('text=' + text)

        with tests.DialogContext(has_text(text)):
            main('--text', text)

        encoded = 'Zm9vIGJhciBiYXoKZHVzIDEyMwo='
        with tests.DialogContext(has_text(text)):
            main('--text', encoded, '--encoding', 'base64')

        encoded = 'foo%20bar%20baz%0Adus%20123'
        with tests.DialogContext(has_text(text)):
            main('--text', encoded, '--encoding', 'url')

        # Clipboard input
        text = 'foo bar baz\ndus 123'
        SelectionClipboard.clipboard.clear()  # just to be sure
        Clipboard.set_text(text)
        with tests.DialogContext(has_text(text)):
            main('input=clipboard')

        with tests.DialogContext(has_text(text)):
            main('--input', 'clipboard')

        text = 'foo bar baz\ndus 456'
        SelectionClipboard.set_text(text)
        with tests.DialogContext(has_text(text)):
            main('input=clipboard')

        with tests.DialogContext(has_text(text)):
            main('--input', 'clipboard')

        # Template options
        cmd = QuickNotePluginCommand('quicknote')
        cmd.parse_options('option:url=foo')
        self.assertEqual(cmd.template_options, {'url': 'foo'})

        cmd = QuickNotePluginCommand('quicknote')
        cmd.parse_options('--option', 'url=foo')
        self.assertEqual(cmd.template_options, {'url': 'foo'})
Exemplo n.º 5
0
    def get_text(self):
        if 'input' in self.opts:
            if self.opts['input'] == 'stdin':
                import sys
                text = sys.stdin.read()
            elif self.opts['input'] == 'clipboard':
                text = \
                 SelectionClipboard.get_text() \
                 or Clipboard.get_text()
            else:
                raise AssertionError('Unknown input type: %s' %
                                     self.opts['input'])
        else:
            text = self.opts.get('text')

        if text and 'encoding' in self.opts:
            if self.opts['encoding'] == 'base64':
                import base64
                text = base64.b64decode(text).decode('UTF-8')
            elif self.opts['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' %
                                     self.opts['encoding'])

        assert isinstance(text, str), '%r is not decoded' % text
        return text
Exemplo n.º 6
0
	def get_text(self):
		if 'input' in self.opts:
			if self.opts['input'] == 'stdin':
				import sys
				text = sys.stdin.read()
			elif self.opts['input'] == 'clipboard':
				text = \
					SelectionClipboard.get_text() \
					or Clipboard.get_text()
			else:
				raise AssertionError, 'Unknown input type: %s' % self.opts['input']
		else:
			text = self.opts.get('text')

		if text and 'encoding' in self.opts:
			if self.opts['encoding'] == 'base64':
				import base64
				text = base64.b64decode(text)
			elif self.opts['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' % self.opts['encoding']

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

		return text
Exemplo n.º 7
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()
Exemplo n.º 8
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'
Exemplo n.º 9
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()