Esempio n. 1
0
    def runTest(self):
        from zim.gui.notebookdialog import NotebookComboBox, NotebookTreeModel

        class MyList(list):
            pass

        notebooklist = MyList([
            NotebookInfo('file:///test/foo', name='Foo'),
            NotebookInfo('file:///test/bar', name='Bar')
        ])
        notebooklist.default = notebooklist[1]
        notebooklist.write = lambda: None

        model = NotebookTreeModel(notebooklist)

        combobox = NotebookComboBox(model)
        self.assertEqual(combobox.get_notebook(),
                         notebooklist[1].uri)  # default

        combobox.set_active(-1)
        self.assertEqual(combobox.get_notebook(), None)

        combobox.set_notebook(notebooklist[0].uri)
        self.assertEqual(combobox.get_notebook(), notebooklist[0].uri)

        combobox.set_notebook('file:///yet/another/notebook')
        self.assertEqual(combobox.get_notebook(), None)

        combobox.set_notebook('file:///yet/another/notebook', append=True)
        self.assertEqual(combobox.get_notebook(),
                         'file:///yet/another/notebook')
Esempio n. 2
0
	def append_notebook(self, uri, name=None):
		'''Append a notebook to the list. If the name is not specified
		it will be looked up by reading the config file of the notebook.
		Returns an iter for this notebook in the list.
		'''
		assert uri.startswith('file://')
		info = NotebookInfo(uri, name=name)
		info.update()
		self._append(info)
		self.write()
		return len(self) - 1 # iter
Esempio n. 3
0
	def append_notebook(self, uri, name=None):
		'''Append a notebook to the list. If the name is not specified
		it will be looked up by reading the config file of the notebook.
		Returns an iter for this notebook in the list.
		'''
		assert uri.startswith('file://')
		info = NotebookInfo(uri, name=name)
		info.update()
		self._append(info)
		self.write()
		return len(self) - 1 # iter
Esempio n. 4
0
    def start(self):
        # Start server
        try:
            uri = self.notebookcombobox.get_notebook()
            if uri:
                notebook, x = build_notebook(NotebookInfo(uri))
                if not notebook:
                    return
            else:
                return

            port = int(self.portentry.get_value())
            public = self.public_checkbox.get_active()
            self.httpd = make_server(notebook, port, public,
                                     **self.interface_opts)
            if sys.platform == 'win32':
                # glib io watch conflicts with socket use on windows..
                # idle handler uses a bit to much CPU for my taste,
                # timeout every 0.5 sec is better
                self.httpd.timeout = 0.1  # 100 ms
                self._source_id = glib.timeout_add(500, self.do_serve_on_poll)
            else:
                self.httpd.timeout = 3  # if no response after 3 sec, drop it
                self._source_id = glib.io_add_watch(
                    self.httpd.fileno(),
                    glib.IO_IN | glib.IO_OUT | glib.IO_ERR | glib.IO_HUP
                    | glib.IO_PRI,  # any event..
                    self.do_serve_on_io)
            logger.info("Serving HTTP on %s port %i...",
                        self.httpd.server_name, self.httpd.server_port)
        except Exception, error:
            ErrorDialog(self, error).run()
            return
Esempio n. 5
0
    def runTest(self):
        '''Test proper linking of files in export'''
        notebook = tests.new_notebook(fakedir='/source/dir/')

        linker = StaticLinker('html', notebook)
        linker.set_usebase(True)  # normally set by html format module
        linker.set_path(Path('foo:bar'))  # normally set by exporter
        linker.set_base(Dir('/source/dir/foo'))  # normally set by exporter

        self.assertEqual(linker.link_page('+dus'), './bar/dus.html')
        self.assertEqual(linker.link_page('dus'), './dus.html')
        self.assertEqual(linker.link_file('./dus.pdf'), './bar/dus.pdf')
        self.assertEqual(linker.link_file('../dus.pdf'), './dus.pdf')
        self.assertEqual(linker.link_file('../../dus.pdf'), '../dus.pdf')

        ## setup environment for interwiki link
        if os.name == 'nt':
            uri = 'file:///C:/foo'
        else:
            uri = 'file:///foo'

        list = get_notebook_list()
        list.append(NotebookInfo(uri, interwiki='foo'))
        list.write()
        ##

        href = interwiki_link('foo?Ideas:Task List')
        self.assertIsNotNone(href)
        self.assertEqual(linker.link('foo?Ideas:Task List'),
                         uri + '/Ideas/Task_List.txt')
Esempio n. 6
0
    def start(self):
        # Start server
        try:
            uri = self.notebookcombobox.get_notebook()
            if uri:
                notebook, x = build_notebook(NotebookInfo(uri))
                if not notebook:
                    return
            else:
                return

            if not notebook.index.is_uptodate:
                for info in notebook.index.update_iter():
                    #logger.info('Indexing %s', info)
                    pass  # TODO meaningful info for above message

            port = int(self.portentry.get_value())
            public = self.public_checkbox.get_active()
            self.httpd = make_server(notebook, port, public,
                                     **self.interface_opts)
            if sys.platform == 'win32':
                # GObject io watch conflicts with socket use on windows..
                # idle handler uses a bit to much CPU for my taste,
                # timeout every 0.5 sec is better
                self.httpd.timeout = 0.1  # 100 ms
                self._source_id = GObject.timeout_add(500,
                                                      self.do_serve_on_poll)
            else:
                self.httpd.timeout = 3  # if no response after 3 sec, drop it
                self._source_id = GObject.io_add_watch(
                    self.httpd.fileno(),
                    GObject.IO_IN | GObject.IO_OUT | GObject.IO_ERR
                    | GObject.IO_HUP | GObject.IO_PRI,  # any event..
                    self.do_serve_on_io)
            logger.info("Serving HTTP on %s port %i...",
                        self.httpd.server_name, self.httpd.server_port)
        except Exception as error:
            ErrorDialog(self, error).run()
            return

        # Update UI
        self.notebookcombobox.set_sensitive(False)
        self.portentry.set_sensitive(False)
        self.public_checkbox.set_sensitive(False)
        self.open_button.set_sensitive(False)
        self.start_button.set_sensitive(False)
        self.stop_button.set_sensitive(True)

        self.status_label.set_markup('<i>' + _('Server started') + '</i>')
        # T: Status in web server gui
        #if self.public_checkbox.get_active():
        #	url = 'http://%s:%i' % (self.httpd.server_name, self.httpd.server_port)
        #else:
        #	url = 'http://localhost:%i' % self.httpd.server_port
        url = 'http://localhost:%i' % self.httpd.server_port
        if self.link_button:
            self.link_button.set_uri(url)
            self.link_button.set_label(url)
            self.link_button.set_sensitive(True)
Esempio n. 7
0
    def runTest(self):
        dir = Dir(self.get_tmp_name())
        notebook = tests.new_notebook(fakedir=dir.subdir('notebook'))
        for name in (
                'foo',
                'bar',
                'foo:bar',
        ):
            p = notebook.get_page(Path(name))
            p.parse('wiki', "test 123")
            notebook.store_page(p)

        layout = MultiFileLayout(dir.subdir('layout'), 'html')
        source = Path('foo:bar')
        output = layout.page_file(source)

        linker = ExportLinker(notebook,
                              layout,
                              source=source,
                              output=output,
                              usebase=True)

        self.assertEqual(linker.link('+dus'), './bar/dus.html')
        self.assertEqual(linker.link('dus'), './dus.html')
        self.assertEqual(linker.link('./dus.pdf'), './bar/dus.pdf')
        self.assertEqual(linker.link('../dus.pdf'), './dus.pdf')
        self.assertEqual(linker.link('../../dus.pdf'), '../dus.pdf')
        self.assertEqual(linker.link('/dus.pdf'), File('/dus.pdf').uri)

        # TODO:
        # 	img
        # 	icon
        # 	resource
        # 	resolve_source_file
        # 	page_object
        # 	file_object
        #
        #	document_root_url

        ## setup environment for interwiki link
        if os.name == 'nt':
            uri = 'file:///C:/foo'
        else:
            uri = 'file:///foo'

        list = get_notebook_list()
        list.append(NotebookInfo(uri, interwiki='foo'))
        list.write()
        ##

        href = interwiki_link('foo?Ideas:Task List')
        self.assertIsNotNone(href)
        self.assertEqual(linker.link('foo?Ideas:Task List'),
                         uri + '/Ideas/Task_List.txt')
Esempio n. 8
0
def prompt_notebook():
	'''Prompts the NotebookDialog and returns the result or None.
	As a special case for first time usage it immediately prompts for
	the notebook location without showing the notebook list.
	@returns: a L{NotebookInfo} object or C{None}
	'''
	list = get_notebook_list()
	if len(list) == 0:
		logger.debug('First time usage - prompt for notebook folder')
		fields = AddNotebookDialog(ui=None).run()
		if fields:
			dir = Dir(fields['folder'])
			init_notebook(dir, name=fields['name'])
			list.append(NotebookInfo(dir.uri, name=fields['name']))
			list.write()
			return NotebookInfo(dir.uri, name=fields['name'])
		else:
			return None # User canceled the dialog ?
	else:
		# Multiple notebooks defined and no default
		return NotebookDialog(ui=None).run()
Esempio n. 9
0
 def _set_autocomplete(self, notebook):
     if notebook:
         if isinstance(notebook, basestring):
             notebook = NotebookInfo(notebook)
         obj, x = build_notebook(notebook)
         self.form.widgets['namespace'].notebook = obj
         self.form.widgets['page'].notebook = obj
         logger.debug('Notebook for autocomplete: %s (%s)', obj, notebook)
     else:
         self.form.widgets['namespace'].notebook = None
         self.form.widgets['page'].notebook = None
         logger.debug('Notebook for autocomplete unset')
Esempio n. 10
0
    def runTest(self):
        notebook = self.setUpNotebook(content=(
            'foo',
            'bar',
            'foo:bar',
        ))
        dir = Dir(notebook.folder.parent().folder('layout').path)

        layout = MultiFileLayout(dir.subdir('layout'), 'html')
        source = Path('foo:bar')
        output = layout.page_file(source)

        linker = ExportLinker(notebook,
                              layout,
                              source=source,
                              output=output,
                              usebase=True)

        self.assertEqual(linker.link('+dus'), './bar/dus.html')
        self.assertEqual(linker.link('dus'), './dus.html')
        self.assertEqual(linker.link('./dus.pdf'), './bar/dus.pdf')
        self.assertEqual(linker.link('../dus.pdf'), './dus.pdf')
        self.assertEqual(linker.link('../../dus.pdf'), '../dus.pdf')

        extpath = 'C:\\dus.pdf' if os.name == 'nt' else '/duf.pdf'
        self.assertEqual(linker.link(extpath), FilePath(extpath).uri)

        # TODO:
        # 	img
        # 	icon
        # 	resource
        # 	resolve_source_file
        # 	page_object
        # 	file_object
        #
        #	document_root_url

        ## setup environment for interwiki link
        if os.name == 'nt':
            uri = 'file:///C:/foo'
        else:
            uri = 'file:///foo'

        list = get_notebook_list()
        list.append(NotebookInfo(uri, interwiki='foo'))
        list.write()
        ##

        href = interwiki_link('foo?Ideas:Task List')
        self.assertIsNotNone(href)
        self.assertEqual(linker.link('foo?Ideas:Task List'),
                         uri + '/Ideas/Task_List.txt')
Esempio n. 11
0
 def _set_autocomplete(self, notebook):
     if notebook:
         try:
             if isinstance(notebook, str):
                 notebook = NotebookInfo(notebook)
             obj, x = build_notebook(notebook)
             self.form.widgets['namespace'].notebook = obj
             self.form.widgets['page'].notebook = obj
             logger.debug('Notebook for autocomplete: %s (%s)', obj,
                          notebook)
         except:
             logger.exception('Could not set notebook: %s', notebook)
     else:
         self.form.widgets['namespace'].notebook = None
         self.form.widgets['page'].notebook = None
         logger.debug('Notebook for autocomplete unset')
Esempio n. 12
0
    def runTest(self):
        from zim.gui.notebookdialog import prompt_notebook, \
         AddNotebookDialog, NotebookDialog

        tmpdir = self.create_tmp_dir()
        dir1 = Dir(tmpdir + '/mynotebook1')
        dir2 = Dir(tmpdir + '/mynotebook2')

        # First time we get directly the AddNotebookDialog
        def doAddNotebook(dialog):
            self.assertTrue(isinstance(dialog, AddNotebookDialog))
            dialog.form['name'] = 'Foo'
            dialog.form['folder'] = dir1.path
            dialog.assert_response_ok()

        with tests.DialogContext(doAddNotebook):
            info = prompt_notebook()
            self.assertIsNotNone(info)
            self.assertEqual(info.uri, dir1.uri)

        # Second time we get the list
        def testNotebookDialog(dialog):
            self.assertTrue(isinstance(dialog, NotebookDialog))
            selection = dialog.treeview.get_selection()
            selection.select_path((0, ))  # select first and only notebook
            dialog.assert_response_ok()

        with tests.DialogContext(testNotebookDialog):
            info = prompt_notebook()
            self.assertIsNotNone(info)
            self.assertEqual(info.uri, dir1.uri)

        # Third time we add a notebook and set the default
        def doAddNotebook(dialog):
            self.assertTrue(isinstance(dialog, AddNotebookDialog))
            dialog.form['name'] = 'Bar'
            dialog.form['folder'] = dir2.path
            dialog.assert_response_ok()

        def testAddNotebook(dialog):
            self.assertTrue(isinstance(dialog, NotebookDialog))

            with tests.DialogContext(doAddNotebook):
                dialog.do_add_notebook()

            dialog.combobox.set_active(0)

            selection = dialog.treeview.get_selection()
            selection.select_path((1, ))  # select newly added notebook
            dialog.assert_response_ok()

        with tests.DialogContext(testAddNotebook):
            info = prompt_notebook()
            self.assertIsNotNone(info)
            self.assertEqual(info.uri, dir2.uri)

        # Check the notebook exists and the notebook list looks like it should
        for dir in (dir1, dir2):
            self.assertTrue(dir.exists())
            self.assertTrue(dir.file('notebook.zim').exists())

        list = get_notebook_list()
        self.assertTrue(len(list) == 2)
        self.assertEqual(list[0], NotebookInfo(dir1.uri, name='Foo'))
        self.assertEqual(list[1], NotebookInfo(dir2.uri, name='Bar'))
        self.assertEqual(list.default, NotebookInfo(dir1.uri, name='Foo'))

        # Now unset the default and again check the notebook list
        def unsetDefault(dialog):
            self.assertTrue(isinstance(dialog, NotebookDialog))
            dialog.combobox.set_active(-1)
            selection = dialog.treeview.get_selection()
            selection.select_path((1, ))  # select newly added notebook
            dialog.assert_response_ok()

        with tests.DialogContext(unsetDefault):
            info = prompt_notebook()
            self.assertIsNotNone(info)
            self.assertEqual(info.uri, dir2.uri)

        list = get_notebook_list()
        self.assertTrue(len(list) == 2)
        self.assertTrue(list.default is None)
Esempio n. 13
0
    def runTest(self):
        # Test setting up the server
        start_server_if_not_running()
        server = ServerProxy()
        ack = server.ping()
        self.assertEqual(ack[0], 'ACK')
        start_server_if_not_running()  # Should do nothing..
        server = ServerProxy()
        self.assertEqual(
            server.ping(),
            ack)  # ack has pid, so we know still same server process

        # Test adding a child and interact with it
        child = server.get_proxy(
            RemoteObject('tests.ipc.ChildClass', 'file:///foo'))
        ack = child.ping()
        self.assertEqual(ack[0], 'CHILD')

        child = server.get_proxy(
            RemoteObject('tests.ipc.ChildClass', 'file:///foo'))
        # should not vivicate again, verify by pid in ack
        self.assertEqual(child.ping(), ack)

        # Error handling
        self.assertRaises(ValueError, child.error)

        # Add a second child
        child2 = server.get_proxy(
            RemoteObject('tests.ipc.ChildClass', 'file:///bar'))
        # should not vivicate again, verify by pid in ack
        self.assertNotEqual(child2.ping(), ack)

        children = server.list_objects()
        children.sort(key=lambda c: c.id)
        self.assertEqual(children, [
            RemoteObject('tests.ipc.ChildClass', 'file:///bar'),
            RemoteObject('tests.ipc.ChildClass', 'file:///foo')
        ])

        # Test API for notebooks
        server._notebookklass = 'tests.ipc.ChildClass'  # HACK to test convenience methods
        self.assertEqual(server.list_notebooks(),
                         ['file:///bar', 'file:///foo'])
        proxy = server.get_notebook('file:///foo')
        self.assertEqual(child.ping(), ack)

        # Test these are serializable
        for obj in (
                File('file:///test'),
                NotebookInfo('file:///test'),
                Path('foo'),
                Page(Path('foo')),
                FileStorePage(Path('foo'),
                              File('file:///test'),
                              File('file:///test'),
                              format='wiki'),
        ):
            #~ print ">>> %r" % obj
            re = proxy.echo(obj)
            self.assertEqual(re, obj)

        # send a signal
        n = child.get_n_signals()
        server.emit('notebook-list-changed')
        self.assertEqual(child.get_n_signals(), n + 1)

        # Wrap up
        server.quit()
Esempio n. 14
0
 def list_open_notebooks(self):
     for uri in self.server.list_notebooks():
         info = NotebookInfo(uri)
         info.active = True
         yield info
Esempio n. 15
0
 def list_open_notebooks(self):
     # No daemon, so we only know one open notebook
     info = NotebookInfo(self.notebook.uri, name=self.notebook.name)
     info.active = True
     return [info]
Esempio n. 16
0
 def list_open_notebooks(self):
     for uri in self.server.list_notebooks():
         info = NotebookInfo(uri)
         info.active = True
         yield info
Esempio n. 17
0
 def list_open_notebooks(self):
     # No daemon, so we only know one open notebook
     notebook = self.ui.notebook
     info = NotebookInfo(notebook.uri, name=notebook.name)
     info.active = True
     return [ info ]