Beispiel #1
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'})
Beispiel #2
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')
    def testCopyLocation(self):
        from zim.gui.clipboard import Clipboard

        Clipboard.set_text('XXX')
        self.assertEqual(Clipboard.get_text(), 'XXX')

        self.uiactions.copy_location()
        self.assertEqual(Clipboard.get_text(), 'Test')
Beispiel #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'})
Beispiel #5
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'})
Beispiel #6
0
    def testTaskListTreeView(self):
        klass = zim.plugins.get_plugin("tasklist")
        ui = MockUI()
        plugin = klass(ui)
        ui.notebook.index.flush()
        ui.notebook.index.update()

        from zim.plugins.tasklist import TaskListTreeView

        treeview = TaskListTreeView(ui, plugin, filter_actionable=False)

        menu = treeview.get_popup()

        # Check these do not cause errors - how to verify state ?
        tests.gtk_activate_menu_item(menu, _("Expand _All"))
        tests.gtk_activate_menu_item(menu, _("_Collapse All"))

        # Copy tasklist -> csv
        from zim.gui.clipboard import Clipboard

        tests.gtk_activate_menu_item(menu, "gtk-copy")
        text = Clipboard.get_text()
        lines = text.splitlines()
        self.assertTrue(len(lines) > 10)
        self.assertTrue(len(lines[0].split(",")) > 3)
        self.assertFalse(any("<span" in l for l in lines))  # make sure encoding is removed
Beispiel #7
0
    def testTaskListTreeView(self):
        klass = zim.plugins.get_plugin_class('tasklist')
        plugin = klass()

        notebook = tests.new_notebook()
        plugin.extend(notebook.index)
        index_ext = plugin.get_extension(IndexExtension)
        self.assertIsNotNone(index_ext)

        notebook.index.flush()
        notebook.index.update()

        from zim.plugins.tasklist import TaskListTreeView
        opener = tests.MockObject()
        treeview = TaskListTreeView(index_ext, opener)

        menu = treeview.get_popup()

        # Check these do not cause errors - how to verify state ?
        tests.gtk_activate_menu_item(menu, _("Expand _All"))
        tests.gtk_activate_menu_item(menu, _("_Collapse All"))

        # Copy tasklist -> csv
        from zim.gui.clipboard import Clipboard
        tests.gtk_activate_menu_item(menu, 'gtk-copy')
        text = Clipboard.get_text()
        lines = text.splitlines()
        self.assertTrue(len(lines) > 10)
        self.assertTrue(len(lines[0].split(',')) > 3)
        self.assertFalse(any('<span' in l
                             for l in lines))  # make sure encoding is removed
Beispiel #8
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
Beispiel #9
0
    def testTaskListTreeView(self):
        plugin = PluginManager.load_plugin('tasklist')

        notebook = self.setUpNotebook(content=tests.FULL_NOTEBOOK)
        notebook.index.check_and_update()

        from zim.plugins.tasklist.gui import TaskListTreeView
        view = TasksView.new_from_index(notebook.index)
        opener = tests.MockObject()
        treeview = TaskListTreeView(view,
                                    opener,
                                    task_labels=['TODO', 'FIXME'])

        menu = treeview.get_popup()

        # Check these do not cause errors - how to verify state ?
        tests.gtk_activate_menu_item(menu, _("Expand _All"))
        tests.gtk_activate_menu_item(menu, _("_Collapse All"))

        # Copy tasklist -> csv
        from zim.gui.clipboard import Clipboard
        tests.gtk_activate_menu_item(menu, _('_Copy'))
        text = Clipboard.get_text()
        lines = text.splitlines()
        self.assertTrue(len(lines) > 10)
        self.assertTrue(len(lines[0].split(',')) > 3)
        self.assertFalse(any('<span' in l
                             for l in lines))  # make sure encoding is removed

        # Test tags
        tags = treeview.get_tags()
        for tag in ('home', 'FIXME', '__no_tags__', 'tags'):
            self.assertIn(tag, tags)
            self.assertGreater(tags[tag], 0)
	def rename_bookmark(self, button):
		'''
		Change label of the button.
		New name is taken from the clipboard.
		If button's name has been changed before,
		change it back to its initial state.
		'''
		_full, _short = button.zim_path, self._get_short_page_name(button.zim_path)

		if button.get_label() in (_short, _full):
			# Change the button to new name.
			new_name = None
			try:
				# Take from clipboard.
				new_name = self._convert_path_name(Clipboard.get_text())
			except:
				logger.error('BookmarksBar: Error while converting from buffer.')
			if new_name:
				self.paths_names[_full] = new_name
				button.set_label(new_name)
		else:
			# Change the button back to its initial state.
			new_name = _full if self.uistate['show_full_page_name'] else _short
			button.set_label(new_name)
			self.paths_names.pop(_full, None)

		if self.save_flag:
			self.uistate['bookmarks_names'] = self.paths_names
Beispiel #11
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
Beispiel #12
0
	def testTaskListTreeView(self):
		klass = PluginManager.get_plugin_class('tasklist')
		plugin = klass()

		notebook = tests.new_notebook()
		plugin.extend(notebook.index)
		index_ext = plugin.get_extension(IndexExtension)
		self.assertIsNotNone(index_ext)

		notebook.index.flush()
		notebook.index.update()

		from zim.plugins.tasklist import TaskListTreeView
		opener = tests.MockObject()
		treeview = TaskListTreeView(index_ext, opener)

		menu = treeview.get_popup()

		# Check these do not cause errors - how to verify state ?
		tests.gtk_activate_menu_item(menu, _("Expand _All"))
		tests.gtk_activate_menu_item(menu, _("_Collapse All"))

		# Copy tasklist -> csv
		from zim.gui.clipboard import Clipboard
		tests.gtk_activate_menu_item(menu, 'gtk-copy')
		text = Clipboard.get_text()
		lines = text.splitlines()
		self.assertTrue(len(lines) > 10)
		self.assertTrue(len(lines[0].split(',')) > 3)
		self.assertFalse(any('<span' in l for l in lines)) # make sure encoding is removed
Beispiel #13
0
    def rename_bookmark(self, button):
        '''
		Change label of the button.
		New name is taken from the clipboard.
		If button's name has been changed before,
		change it back to its initial state.
		'''
        _full, _short = button.zim_path, self._get_short_page_name(
            button.zim_path)

        if button.get_label() in (_short, _full):
            # Change the button to new name.
            new_name = None
            try:
                # Take from clipboard.
                new_name = self._convert_path_name(Clipboard.get_text())
            except:
                logger.error(
                    'BookmarksBar: Error while converting from buffer.')
            if new_name:
                self.paths_names[_full] = new_name
                button.set_label(new_name)
        else:
            # Change the button back to its initial state.
            new_name = _full if self.uistate['show_full_page_name'] else _short
            button.set_label(new_name)
            self.paths_names.pop(_full, None)

        if self.save_flag:
            self.uistate['bookmarks_names'] = self.paths_names
Beispiel #14
0
    def testContextMenu(self):
        menu = self.treeview.get_popup()

        # Check these do not cause errors - how to verify state ?
        tests.gtk_activate_menu_item(menu, _("Expand _All"))
        tests.gtk_activate_menu_item(menu, _("_Collapse All"))

        # Copy item
        tests.gtk_activate_menu_item(menu, 'gtk-copy')
        self.assertEqual(Clipboard.get_text(), 'Test')
Beispiel #15
0
	def testContextMenu(self):
		menu = self.treeview.get_popup()

		# Check these do not cause errors - how to verify state ?
		tests.gtk_activate_menu_item(menu, _("Expand _All"))
		tests.gtk_activate_menu_item(menu, _("_Collapse All"))

		# Copy item
		tests.gtk_activate_menu_item(menu, 'gtk-copy')
		self.assertEqual(Clipboard.get_text(), 'Test')
Beispiel #16
0
	def runTest(self):
		'''There is one long test.'''

		ui = MockUI()
		ui.notebook = self.notebook
		ui.page = Path('Test:foo')
		uistate = ConfigDict()
		self.assertTrue(self.notebook.get_page(ui.page).exists())

		PATHS = ('Parent:Daughter:Granddaughter',
				 'Test:tags', 'Test:foo', 'Books')
		LEN_PATHS = len(PATHS)
		PATHS_NAMES = {PATHS[0]:'name 1', PATHS[1]:'name 2', PATHS[2]:'name 3'}

		# Check correctness of reading uistate.
		uistate.setdefault('bookmarks', [])
		uistate.setdefault('bookmarks_names', {})

		uistate['bookmarks'] = list(PATHS)
		uistate['bookmarks_names'] = dict(PATHS_NAMES)
		Bar = BookmarkBar(ui, uistate, get_page_func = lambda: '')
		self.assertTrue(Bar.paths == list(PATHS))
		self.assertTrue(Bar.paths_names == PATHS_NAMES)

		uistate['bookmarks'] = []
		uistate['bookmarks_names'] = {}
		Bar = BookmarkBar(ui, uistate, get_page_func = lambda: '')
		self.assertTrue(Bar.paths == [])
		self.assertTrue(Bar.paths_names == {})

		# Add paths to the beginning of the bar.
		for i, path in enumerate(PATHS):
			Bar._add_new(path, add_bookmarks_to_beginning = True)
			self.assertTrue(len(Bar.paths) == i + 1)
		self.assertTrue(Bar.paths == list(reversed(PATHS)))

		# Add paths to the end of the bar.
		Bar.paths = []
		for i, path in enumerate(PATHS):
			Bar._add_new(path, add_bookmarks_to_beginning = False)
			self.assertTrue(len(Bar.paths) == i + 1)
		self.assertTrue(Bar.paths == list(PATHS))

		# Check that the same path can't be added to the bar.
		Bar._add_new(PATHS[0])
		Bar._add_new(PATHS[1])
		self.assertTrue(Bar.paths == list(PATHS))

		# Delete paths from the bar.
		for i, button in enumerate(Bar.container.get_children()[2:]):
			path = button.zim_path
			self.assertTrue(path in Bar.paths)
			Bar.delete(button.zim_path)
			self.assertTrue(len(Bar.paths) == LEN_PATHS - i - 1)
			self.assertTrue(path not in Bar.paths)
		self.assertTrue(Bar.paths == [])

		# Check short page names.
		uistate['show_full_page_name'] = False
		for path in PATHS:
			Bar._add_new(path)
		self.assertTrue(Bar.paths == list(PATHS))
		for i, button in enumerate(Bar.container.get_children()[2:]):
			self.assertTrue(PATHS[i] == button.zim_path)
			self.assertTrue(Path(PATHS[i]).basename == button.get_label())
		uistate['show_full_page_name'] = True

		# Delete all bookmarks from the bar.
		Bar.delete_all()
		self.assertTrue(Bar.paths == [])

		# Check restriction of max bookmarks in the bar.
		pagelist = set(self.index.list_pages(None))
		_enhanced_pagelist = set()
		for page in pagelist:
			_enhanced_pagelist.update( set(self.index.list_pages(page)) )
			if len(_enhanced_pagelist) > MAX_BOOKMARKS:
				break
		pagelist.update(_enhanced_pagelist)
		self.assertTrue(len(pagelist) > MAX_BOOKMARKS)
		pagelist = list(pagelist)
		for page in pagelist:
			Bar._add_new(page.name)
		self.assertTrue(len(Bar.paths) == MAX_BOOKMARKS)
		self.assertTrue(Bar.paths == [a.name for a in pagelist[:MAX_BOOKMARKS]])
		Bar.delete_all()

		# Check 'save' option in preferences.
		for i, path in enumerate(PATHS):
			Bar.on_preferences_changed({'save':False, 'add_bookmarks_to_beginning':False})
			Bar._add_new(path)
			self.assertTrue(uistate['bookmarks'] == [])
			Bar.on_preferences_changed({'save':True, 'add_bookmarks_to_beginning':False})
			self.assertTrue(uistate['bookmarks'] == list(PATHS[:i+1]))
		self.assertTrue(uistate['bookmarks'] == list(PATHS))

		# Check changing a bookmark.
		self.assertTrue('Test' not in Bar.paths)
		self.assertTrue('Books' in Bar.paths)
		Bar.change_bookmark('Books', 'Books')
		self.assertTrue(Bar.paths == list(PATHS))
		_b_paths = [a for a in Bar.paths if a != 'Books']
		Bar.change_bookmark('Books', 'Test')
		self.assertTrue('Test' in Bar.paths)
		self.assertTrue('Books' not in Bar.paths)
		_e_paths = [a for a in Bar.paths if a != 'Test']
		self.assertTrue(_b_paths == _e_paths)

		Bar.change_bookmark('Test', 'Books')
		self.assertTrue(Bar.paths == list(PATHS))

		# Check deleting a bookmark after deleting a page in the notebook.
		self.assertTrue(len(Bar.paths) == LEN_PATHS)
		for i, path in enumerate(PATHS):
			self.assertTrue(path in Bar.paths)
			self.notebook.delete_page(Path(path))
			self.assertTrue(path not in Bar.paths)
			self.assertTrue(len(Bar.paths) == LEN_PATHS - i - 1)
		self.assertTrue(Bar.paths == [])

		# Check reordering bookmarks.
		PATHS_2 = ('1','2','3','4','5')
		PATHS_NAMES_2 = {PATHS_2[0]:'11', PATHS_2[1]:'22', PATHS_2[2]:'33'}

		Bar.paths = list(PATHS_2)
		Bar.move_bookmark(PATHS_2[2], PATHS_2[2], 'left')
		self.assertTrue(Bar.paths == list(PATHS_2))
		Bar.move_bookmark(PATHS_2[3], PATHS_2[3], 'right')
		self.assertTrue(Bar.paths == list(PATHS_2))
		Bar.move_bookmark('3', '1', 'left')
		self.assertTrue(Bar.paths == ['3','1','2','4','5'])
		Bar.move_bookmark('5', '1', 'left')
		self.assertTrue(Bar.paths == ['3','5','1','2','4'])
		Bar.move_bookmark('5', '1', 'right')
		self.assertTrue(Bar.paths == ['3','1','5','2','4'])
		Bar.move_bookmark('3', '4', 'right')
		self.assertTrue(Bar.paths == ['1','5','2','4','3'])
		Bar.move_bookmark('5', '4', '-')
		self.assertTrue(Bar.paths == ['1','5','2','4','3'])

		# CHECK RENAMING
		# Check rename_bookmark and save options.
		Bar.paths = list(PATHS_2)
		button = gtk.Button(label = PATHS_2[0], use_underline = False)
		button.zim_path = PATHS_2[0]
		Bar.on_preferences_changed({'save':True, 'add_bookmarks_to_beginning':False})
		Bar._reload_bar()

		def rename_check(label, path, paths_names, path_names_uistate):
			self.assertTrue(button.get_label() == label)
			self.assertTrue(button.zim_path == path)
			self.assertTrue(Bar.paths_names == paths_names)
			self.assertTrue(uistate['bookmarks_names'] == path_names_uistate)

		rename_check(PATHS_2[0], PATHS_2[0], {}, {})
		Clipboard.set_text('new name')
		Bar.rename_bookmark(button)
		rename_check('new name', PATHS_2[0], {PATHS_2[0]:'new name'}, {PATHS_2[0]:'new name'})
		Bar.on_preferences_changed({'save':False, 'add_bookmarks_to_beginning':False})
		rename_check('new name', PATHS_2[0], {PATHS_2[0]:'new name'}, {})
		Bar.on_preferences_changed({'save':True, 'add_bookmarks_to_beginning':False})
		rename_check('new name', PATHS_2[0], {PATHS_2[0]:'new name'}, {PATHS_2[0]:'new name'})
		Bar.rename_bookmark(button)
		rename_check(PATHS_2[0], PATHS_2[0], {}, {})

		# Check delete with renaming.
		Bar.on_preferences_changed({'save':True, 'add_bookmarks_to_beginning':False})
		paths_names_copy = dict(PATHS_NAMES_2)
		Bar.paths_names = dict(PATHS_NAMES_2)
		for key in PATHS_NAMES_2:
			Bar.delete(key)
			del paths_names_copy[key]
			self.assertTrue(Bar.paths_names == paths_names_copy)
			self.assertTrue(uistate['bookmarks_names'] == Bar.paths_names)

		# Check delete all with renaming.
		Bar.paths_names = dict(PATHS_NAMES_2)
		Bar.delete_all()
		self.assertTrue(Bar.paths_names == {})
		self.assertTrue(uistate['bookmarks_names'] == {})

		# Check change bookmark with renaming.
		Bar.paths = list(PATHS_2)
		Bar.paths_names = dict(PATHS_NAMES_2)
		paths_names_copy = dict(PATHS_NAMES_2)
		paths_names_copy.pop(PATHS_2[0], None)
		Bar.change_bookmark(PATHS_2[0], 'new path')
		self.assertTrue(Bar.paths_names == paths_names_copy)
		self.assertTrue(Bar.paths == ['new path'] + list(PATHS_2[1:]))

		# Check that paths and paths_names didn't change in the process.
		self.assertTrue(PATHS_2 == ('1','2','3','4','5'))
		self.assertTrue(PATHS_NAMES_2 == {PATHS_2[0]:'11', PATHS_2[1]:'22', PATHS_2[2]:'33'})
Beispiel #17
0
	def do_copy(self):
		#~ print '!! copy location'
		page = self.get_selected_path()
		if page:
			Clipboard.set_pagelink(self.ui.notebook, page)
Beispiel #18
0
 def do_copy(self):
     #~ print '!! copy location'
     page = self.get_selected_path()
     if page:
         Clipboard.set_pagelink(self.ui.notebook, page)
Beispiel #19
0
	def testFunctions(self):
		'''Test bookmark functions: changing, reordering, ranaming.'''
		navigation = tests.MockObject()
		bar = BookmarkBar(self.notebook, navigation, self.uistate, get_page_func = lambda: '')
		bar.max_bookmarks = 15 # set maximum number of bookmarks

		# Check changing a bookmark.
		for i, path in enumerate(self.PATHS):
			bar._add_new(path, add_bookmarks_to_beginning = False)

		self.assertTrue('Test' not in bar.paths)
		self.assertTrue('Books' in bar.paths)
		bar.change_bookmark('Books', 'Books')
		self.assertEqual(bar.paths, list(self.PATHS))
		bar.change_bookmark('Books', 'Test')
		self.assertTrue('Test' in bar.paths)
		self.assertTrue('Books' not in bar.paths)
		_result = [a if a != 'Books' else 'Test' for a in self.PATHS]
		self.assertEqual(bar.paths, _result)

		bar.change_bookmark('Test', 'Books')
		self.assertEqual(bar.paths, list(self.PATHS))

		# Check reordering bookmarks.
		new_paths = ('1', '2', '3', '4', '5')

		bar.paths = list(new_paths)
		bar.move_bookmark(new_paths[2], new_paths[2], 'left')
		self.assertEqual(bar.paths, list(new_paths))
		bar.move_bookmark(new_paths[3], new_paths[3], 'right')
		self.assertEqual(bar.paths, list(new_paths))
		bar.move_bookmark('3', '1', 'left')
		self.assertEqual(bar.paths, ['3', '1', '2', '4', '5'])
		bar.move_bookmark('5', '1', 'left')
		self.assertEqual(bar.paths, ['3', '5', '1', '2', '4'])
		bar.move_bookmark('5', '1', 'right')
		self.assertEqual(bar.paths, ['3', '1', '5', '2', '4'])
		bar.move_bookmark('3', '4', 'right')
		self.assertEqual(bar.paths, ['1', '5', '2', '4', '3'])
		bar.move_bookmark('5', '4', '-')
		self.assertEqual(bar.paths, ['1', '5', '2', '4', '3'])

		# Check rename_bookmark and save options.
		preferences_changed = lambda save: bar.on_preferences_changed({'save': save,
				'add_bookmarks_to_beginning': False,
				'max_bookmarks': 15})

		new_path_names = {new_paths[0]: '11', new_paths[1]: '22', new_paths[2]: '33'}
		bar.paths = list(new_paths)
		preferences_changed(True)
		bar._reload_bar()

		def rename_check(label, path, paths_names, path_names_uistate):
			self.assertEqual(button.get_label(), label)
			self.assertEqual(button.zim_path, path)
			self.assertEqual(bar.paths_names, paths_names)
			self.assertEqual(self.uistate['bookmarks_names'], path_names_uistate)

		button = Gtk.Button(label = new_paths[0], use_underline = False)
		button.zim_path = new_paths[0]
		rename_check(new_paths[0], new_paths[0], {}, {})

		Clipboard.set_text('new name')
		bar.rename_bookmark(button)
		rename_check('new name', new_paths[0], {new_paths[0]: 'new name'}, {new_paths[0]: 'new name'})
		preferences_changed(False)
		rename_check('new name', new_paths[0], {new_paths[0]: 'new name'}, {})
		preferences_changed(True)
		rename_check('new name', new_paths[0], {new_paths[0]: 'new name'}, {new_paths[0]: 'new name'})
		bar.rename_bookmark(button)
		rename_check(new_paths[0], new_paths[0], {}, {})

		# Check delete with renaming.
		preferences_changed(True)
		paths_names_copy = dict(new_path_names)
		bar.paths_names = dict(new_path_names)
		for key in new_path_names:
			bar.delete(key)
			del paths_names_copy[key]
			self.assertEqual(bar.paths_names, paths_names_copy)
			self.assertEqual(self.uistate['bookmarks_names'], bar.paths_names)

		# Check delete all with renaming.
		bar.paths_names = dict(new_path_names)
		bar.delete_all()
		self.assertEqual(bar.paths_names, {})
		self.assertEqual(self.uistate['bookmarks_names'], {})

		# Check change bookmark with renaming.
		new_path_names = {new_paths[0]: '11', new_paths[1]: '22', new_paths[2]: '33'}

		bar.paths = list(new_paths)
		bar.paths_names = dict(new_path_names)
		paths_names_copy = dict(new_path_names)
		_name = paths_names_copy.pop(new_paths[0])
		paths_names_copy['new path'] = _name
		bar.change_bookmark(new_paths[0], 'new path')
		self.assertEqual(bar.paths_names, paths_names_copy)
		self.assertEqual(bar.paths, ['new path'] + list(new_paths[1:]))
Beispiel #20
0
 def copy_to_clipboard(self, *a):
     '''Exports currently visible elements from the tasks list'''
     logger.debug('Exporting to clipboard current view of task list.')
     text = self.get_visible_data_as_csv()
     Clipboard.set_text(text)
	def testFunctions(self):
		'''Test bookmark functions: changing, reordering, ranaming.'''

		Bar = BookmarkBar(self.ui, self.uistate, get_page_func = lambda: '')
		Bar.max_bookmarks = 15 # set maximum number of bookmarks

		# Check changing a bookmark.
		for i, path in enumerate(self.PATHS):
			Bar._add_new(path, add_bookmarks_to_beginning = False)

		self.assertTrue('Test' not in Bar.paths)
		self.assertTrue('Books' in Bar.paths)
		Bar.change_bookmark('Books', 'Books')
		self.assertEqual(Bar.paths, list(self.PATHS))
		Bar.change_bookmark('Books', 'Test')
		self.assertTrue('Test' in Bar.paths)
		self.assertTrue('Books' not in Bar.paths)
		_result = [a if a != 'Books' else 'Test' for a in self.PATHS]
		self.assertEqual(Bar.paths, _result)

		Bar.change_bookmark('Test', 'Books')
		self.assertEqual(Bar.paths, list(self.PATHS))

		# Check reordering bookmarks.
		new_paths = ('1','2','3','4','5')

		Bar.paths = list(new_paths)
		Bar.move_bookmark(new_paths[2], new_paths[2], 'left')
		self.assertEqual(Bar.paths, list(new_paths))
		Bar.move_bookmark(new_paths[3], new_paths[3], 'right')
		self.assertEqual(Bar.paths, list(new_paths))
		Bar.move_bookmark('3', '1', 'left')
		self.assertEqual(Bar.paths, ['3','1','2','4','5'])
		Bar.move_bookmark('5', '1', 'left')
		self.assertEqual(Bar.paths, ['3','5','1','2','4'])
		Bar.move_bookmark('5', '1', 'right')
		self.assertEqual(Bar.paths, ['3','1','5','2','4'])
		Bar.move_bookmark('3', '4', 'right')
		self.assertEqual(Bar.paths, ['1','5','2','4','3'])
		Bar.move_bookmark('5', '4', '-')
		self.assertEqual(Bar.paths, ['1','5','2','4','3'])

		# Check rename_bookmark and save options.
		preferences_changed = lambda save: Bar.on_preferences_changed({'save': save,
				'add_bookmarks_to_beginning': False,
				'max_bookmarks': 15})

		new_path_names = {new_paths[0]:'11', new_paths[1]:'22', new_paths[2]:'33'}
		Bar.paths = list(new_paths)
		preferences_changed(True)
		Bar._reload_bar()

		def rename_check(label, path, paths_names, path_names_uistate):
			self.assertEqual(button.get_label(), label)
			self.assertEqual(button.zim_path, path)
			self.assertEqual(Bar.paths_names, paths_names)
			self.assertEqual(self.uistate['bookmarks_names'], path_names_uistate)

		button = gtk.Button(label = new_paths[0], use_underline = False)
		button.zim_path = new_paths[0]
		rename_check(new_paths[0], new_paths[0], {}, {})

		Clipboard.set_text('new name')
		Bar.rename_bookmark(button)
		rename_check('new name', new_paths[0], {new_paths[0]:'new name'}, {new_paths[0]:'new name'})
		preferences_changed(False)
		rename_check('new name', new_paths[0], {new_paths[0]:'new name'}, {})
		preferences_changed(True)
		rename_check('new name', new_paths[0], {new_paths[0]:'new name'}, {new_paths[0]:'new name'})
		Bar.rename_bookmark(button)
		rename_check(new_paths[0], new_paths[0], {}, {})

		# Check delete with renaming.
		preferences_changed(True)
		paths_names_copy = dict(new_path_names)
		Bar.paths_names = dict(new_path_names)
		for key in new_path_names:
			Bar.delete(key)
			del paths_names_copy[key]
			self.assertEqual(Bar.paths_names, paths_names_copy)
			self.assertEqual(self.uistate['bookmarks_names'], Bar.paths_names)

		# Check delete all with renaming.
		Bar.paths_names = dict(new_path_names)
		Bar.delete_all()
		self.assertEqual(Bar.paths_names, {})
		self.assertEqual(self.uistate['bookmarks_names'], {})

		# Check change bookmark with renaming.
		new_path_names = {new_paths[0]:'11', new_paths[1]:'22', new_paths[2]:'33'}

		Bar.paths = list(new_paths)
		Bar.paths_names = dict(new_path_names)
		paths_names_copy = dict(new_path_names)
		_name = paths_names_copy.pop(new_paths[0])
		paths_names_copy['new path'] = _name
		Bar.change_bookmark(new_paths[0], 'new path')
		self.assertEqual(Bar.paths_names, paths_names_copy)
		self.assertEqual(Bar.paths, ['new path'] + list(new_paths[1:]))
Beispiel #22
0
 def copy_to_clipboard(self, *a):
     '''Exports currently visible elements from the codes list'''
     logger.debug('Exporting to clipboard current view of qda codes.')
     text = self.get_visible_data_as_csv()
     Clipboard.set_text(text)
Beispiel #23
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()
Beispiel #24
0
 def testClipboard(self):
     self.ui.copy_location()
     self.assertEqual(Clipboard.get_text(), 'Test:foo:bar')
Beispiel #25
0
 def yank_current_path(self):
     """copy the absolute path of the current page to the clipboard"""
     curpage = ":" + self.pageview.page.name
     Clipboard.set_text(curpage)
Beispiel #26
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()
Beispiel #27
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'
Beispiel #28
0
	def testClipboard(self):
		self.ui.copy_location()
		self.assertEqual(Clipboard.get_text(), 'Test:foo:bar')
Beispiel #29
0
 def copy_location(self):
     '''Menu action to copy the current page name to the clipboard'''
     from zim.gui.clipboard import Clipboard
     Clipboard.set_pagelink(self.notebook, self.page)