Ejemplo n.º 1
0
    def run(self):
        config = ConfigManager()
        preferences = config.get_config_dict(
            'preferences.conf')['TrayIconPlugin']
        preferences.setdefault('classic', False)

        set_global_trayicon(preferences['classic'])
Ejemplo n.º 2
0
def get_notebook_list():
	'''Returns a list of known notebooks as a L{NotebookInfoList}

	This will load the list from the default X{notebooks.list} file
	'''
	config = ConfigManager() # XXX should be passed in
	file = config.get_config_file('notebooks.list')
	return NotebookInfoList(file)
Ejemplo n.º 3
0
    def _run_new_window(self, notebook, page):
        from gi.repository import GObject

        from zim.gui.mainwindow import MainWindow
        from zim.config import ConfigManager
        from zim.plugins import PluginManager

        config = ConfigManager()
        preferences = config.preferences['General']
        preferences.setdefault('plugins', [
            'pageindex',
            'pathbar',
            'journal',
            'insertsymbol',
            'printtobrowser',
            'versioncontrol',
        ])

        # Upgrade plugin list
        preferences.setdefault('plugins_list_version', 'none')
        if preferences['plugins_list_version'] != '0.68':
            preferences['plugins'].extend(['pageindex', 'pathbar'])
            if 'calendar' in preferences['plugins']:
                preferences['plugins'].remove('calendar')
                preferences['plugins'].append('journal')
                config.preferences['JournalPlugin'] = config.preferences[
                    'CalendarPlugin']
            preferences['plugins_list_version'] = '0.68'

        pluginmanager = PluginManager(config)
        pluginmanager.extend(notebook)

        window = MainWindow(notebook,
                            config,
                            page=page,
                            **self.get_options('geometry', 'fullscreen'))
        pluginmanager.extend(window)
        pluginmanager.extend(window.pageview)
        window.__pluginmanager__ = pluginmanager  # HACK to allow dialogs to find it
        window.present()

        if not window.notebook.index.is_uptodate:
            window._uiactions.reload_index(update_only=True)  # XXX
        else:
            # Start a lightweight background check of the index
            # put a small delay to ensure window is shown before we start
            def start_background_check():
                notebook.index.start_background_check(notebook)
                return False  # only run once

            GObject.timeout_add(500, start_background_check)

        return window
Ejemplo n.º 4
0
    def run(self):
        from zim.config import ConfigManager
        import zim.notebook

        notebook_info = self.get_default_or_only_notebook()
        if not notebook_info:
            logger.error("No notebooks?")
            return
        notebook, _junk = zim.notebook.build_notebook(notebook_info)
        config_manager = ConfigManager()
        config_dict = config_manager.get_config_dict('preferences.conf')
        preferences = config_dict['GnomeShellSearch']
        preferences.setdefault('search_all', True)
        Provider(notebook, preferences['search_all']).main()
Ejemplo n.º 5
0
    def run(self):
        from zim.config import ConfigManager
        import zim.notebook

        notebook_info = self.get_default_or_only_notebook()
        if not notebook_info:
            logger.error("No notebooks?")
            return
        notebook, _junk = zim.notebook.build_notebook(notebook_info)
        config_manager = ConfigManager()
        config_dict = config_manager.get_config_dict('preferences.conf')
        preferences = config_dict['GnomeShellSearch']
        preferences.setdefault('search_all', True)
        Provider(notebook, preferences['search_all']).main()
Ejemplo n.º 6
0
Archivo: trayicon.py Proyecto: gdw2/zim
	def run(self):
		start_server_if_not_running()

		config = ConfigManager()
		preferences = config.get_config_dict('preferences.conf')['TrayIconPlugin']
		preferences.setdefault('classic', False)

		if appindicator and not preferences['classic']:
			obj = RemoteObject('zim.plugins.trayicon.AppIndicatorTrayIcon')
		else:
			obj = RemoteObject('zim.plugins.trayicon.DaemonTrayIcon')

		server = ServerProxy()
		if not server.has_object(obj):
			server.init_object(obj)
Ejemplo n.º 7
0
def mount_notebook(filepath):
	from zim.config import ConfigManager, String

	config = ConfigManager() # XXX should be passed in
	configdict = config.get_config_dict('automount.conf')

	groups = sorted([k for k in configdict.keys() if k.startswith('Path')])
	for group in groups:
		path = group[4:].strip() # len('Path') = 4
		dir = Dir(path)
		if filepath.path == dir.path or filepath.ischild(dir):
			configdict[group].define(mount=String(None))
			handler = ApplicationMountPointHandler(dir, **configdict[group])
			if handler(filepath):
				break
Ejemplo n.º 8
0
    def testAddCustomTool(self):
        config = ConfigManager()
        manager = CustomToolManager(config)
        mytool = {
            'Name': 'Add',
            'Comment': 'Test Add',
            'X-Zim-ExecTool': 'add %f',
            'X-Zim-ReadOnly': False,
            'X-Zim-ShowInToolBar': False,
            'X-Zim-ReplaceSelection': False,
        }

        self.assertIsNone(manager.get_tool('Add'))

        def add_tool(dialog):
            dialog.set_input(**mytool)
            dialog.assert_response_ok()

        dialog = CustomToolManagerDialog(None, config)
        with tests.DialogContext(add_tool):
            dialog.on_add()
            dialog.assert_response_ok()

        # XXX listview intialization fails in test ???
        #model = dialog.listview.get_model()
        #self.assertIn('Add', [r[CustomToolList.NAME_COL] for r in model])

        tool = manager.get_tool('Add')
        self.assertIsNotNone(tool)
        for key, value in list(mytool.items()):
            self.assertEqual(tool['Desktop Entry'][key], value)
Ejemplo n.º 9
0
    def create(self, Name, **properties):
        '''Create a new custom tool

		@param Name: the name to show in the Tools menu
		@param properties: properties for the custom tool, e.g.:
		  - Comment
		  - Icon
		  - X-Zim-ExecTool
		  - X-Zim-ReadOnly
		  - X-Zim-ShowInToolBar

		@returns: a new L{CustomTool} object.
		'''
        properties['Type'] = 'X-Zim-CustomTool'
        dir = XDG_CONFIG_HOME.subdir('zim/customtools')
        tool = _create_application(dir,
                                   Name,
                                   '',
                                   klass=CustomTool,
                                   NoDisplay=False,
                                   **properties)

        # XXX - hack to ensure we link to configmanager
        file = ConfigManager.get_config_file('customtools/' +
                                             tool.file.basename)
        tool.file = file
        file.connect('changed', partial(self._on_tool_changed, tool))

        self._tools[tool.key] = tool
        self._names.append(tool.key)
        self._write_list()

        return tool
	def _add_font_selection(self, table):
		# need to hardcode this, cannot register it as a preference
		table.add_inputs((
			('use_custom_font', 'bool', _('Use a custom font')),
			# T: option in preferences dialog
		))
		table.preferences_sections['use_custom_font'] = 'GtkInterface'

		self.fontbutton = Gtk.FontButton()
		self.fontbutton.set_use_font(True) # preview in button
		self.fontbutton.set_sensitive(False)
		text_style = ConfigManager.get_config_dict('style.conf')
		try:
			font = text_style['TextView']['font']
			if font:
				self.fontbutton.set_font_name(font)
				self.fontbutton.set_sensitive(True)
				table['use_custom_font'] = True
		except KeyError:
			pass

		table.widgets['use_custom_font'].connect('toggled',
			lambda o: self.fontbutton.set_sensitive(o.get_active()))

		self.fontbutton.set_size_request(100, -1)
		input_table_factory(((None, self.fontbutton),), table)
	def do_response_ok(self):
		# Get dynamic tabs
		newpreferences = {}
		for form in list(self.forms.values()):
			for key, value in list(form.items()):
				section = form.preferences_sections[key]
				if not section in newpreferences:
					newpreferences[section] = {}
				newpreferences[section][key] = value

		# Set font - special case, consider it a HACK
		customfont = newpreferences['GtkInterface'].pop('use_custom_font')
		if customfont:
			font = self.fontbutton.get_font_name()
		else:
			font = None

		text_style = ConfigManager.get_config_dict('style.conf')
		text_style['TextView'].define(font=String(None))
		text_style['TextView']['font'] = font
		#

		with self.preferences.block_signals('changed'):
			# note we do not block signal on section dicts
			for section in newpreferences:
				self.preferences[section].update(newpreferences[section])

		self.preferences.emit('changed') # delayed emission

		return True
Ejemplo n.º 12
0
    def run(self):
        start_server_if_not_running()

        config = ConfigManager()
        preferences = config.get_config_dict(
            'preferences.conf')['TrayIconPlugin']
        preferences.setdefault('classic', False)

        if appindicator and not preferences['classic']:
            obj = RemoteObject('zim.plugins.trayicon.AppIndicatorTrayIcon')
        else:
            obj = RemoteObject('zim.plugins.trayicon.DaemonTrayIcon')

        server = ServerProxy()
        if not server.has_object(obj):
            server.init_object(obj)
Ejemplo n.º 13
0
    def __init__(self, notebook, config=None, template='Default'):
        '''Constructor
		@param notebook: a L{Notebook} object
		@param config: optional C{ConfigManager} object
		@param template: html template for zim pages
		'''
        assert isinstance(notebook, Notebook)
        self.notebook = notebook
        self.config = config or ConfigManager(profile=notebook.profile)

        self.output = None
        if isinstance(template, basestring):
            from zim.templates import get_template
            self.template = get_template('html', template)
            if not self.template:
                raise AssertionError, 'Could not find html template: %s' % template
        else:
            self.template = template

        self.linker = WWWLinker(self.notebook)
        self.template.set_linker(self.linker)

        self.plugins = PluginManager(self.config)
        self.plugins.extend(notebook.index)
        self.plugins.extend(notebook)
        self.plugins.extend(self)
Ejemplo n.º 14
0
    def __init__(self, notebook, config=None, template='Default'):
        '''Constructor
		@param notebook: a L{Notebook} object
		@param config: optional C{ConfigManager} object
		@param template: html template for zim pages
		'''
        assert isinstance(notebook, Notebook)
        self.notebook = notebook
        self.config = config or ConfigManager(profile=notebook.profile)

        self.output = None

        if template is None:
            template = 'Default'

        if isinstance(template, basestring):
            from zim.templates import get_template
            self.template = get_template('html', template)
            if not self.template:
                raise AssertionError('Could not find html template: %s' %
                                     template)
        else:
            self.template = template

        self.linker_factory = partial(WWWLinker, self.notebook,
                                      self.template.resources_dir)
        self.dumper_factory = get_format('html').Dumper  # XXX

        self.plugins = PluginManager(self.config)
        self.plugins.extend(notebook)
        self.plugins.extend(self)
Ejemplo n.º 15
0
    def testEditCustomTool(self):
        config = ConfigManager()
        manager = CustomToolManager(config)
        mytool = {
            'Name': 'Edit',
            'Comment': 'Test Edit',
            'X-Zim-ExecTool': 'edit %f',
        }
        manager.create(**mytool)
        self.assertIsNotNone(manager.get_tool('Edit'))

        def edit_tool(dialog):
            dialog.set_input(Comment='Editted Comment')
            dialog.assert_response_ok()

        dialog = CustomToolManagerDialog(None, config)
        #model = dialog.listview.get_model()
        #self.assertIn('Edit', [r[CustomToolList.NAME_COL] for r in model])
        with tests.DialogContext(edit_tool):
            dialog.listview.select_by_name('Edit')
            dialog.on_edit()
            dialog.assert_response_ok()

        tool = manager.get_tool('Edit')
        self.assertEqual(tool.comment, 'Editted Comment')
Ejemplo n.º 16
0
def get_notebook_list():
	'''Returns a list of known notebooks as a L{NotebookInfoList}

	This will load the list from the default X{notebooks.list} file
	'''
	file = ConfigManager.get_config_file('notebooks.list')
	return NotebookInfoList(file)
Ejemplo n.º 17
0
 def __init__(self):
     self._names = []
     self._tools = {}
     self._listfile = ConfigManager.get_config_file(
         'customtools/customtools.list')
     self._read_list()
     self._listfile.connect('changed', self._on_list_changed)
Ejemplo n.º 18
0
	def runTest(self):
		plugin = InsertSymbolPlugin(ConfigManager())

		mainwindow = setUpMainWindow(self.setUpNotebook(content={'Test': ''}), path='Test')
		pageview = mainwindow.pageview
		textview = pageview.textview
		buffer = textview.get_buffer()

		plugin.extend(pageview)

		# Widget needs to be realized
		pageview.realize()
		textview.realize()

		# insert on end-of-word with space
		press(textview, '\\alpha ')
		start, end = buffer.get_bounds()
		text = start.get_text(end)
		self.assertEqual(text, ALPHA + ' \n')

		# Check undo - first undo replace, then the insert space
		pageview.undo()
		start, end = buffer.get_bounds()
		text = start.get_text(end)
		self.assertEqual(text, '\\alpha \n')
		pageview.undo()
		start, end = buffer.get_bounds()
		text = start.get_text(end)
		self.assertEqual(text, '\\alpha\n') # no trailing space

		# insert on end-of-word with ;
		buffer.clear()
		press(textview, r'\alpha;')
		start, end = buffer.get_bounds()
		text = start.get_text(end)
		self.assertEqual(text, ALPHA) # no trailing space

		# no insert in code or pre section
		buffer.clear()
		pageview.toggle_format(VERBATIM)
		press(textview, r'\alpha ')
		start, end = buffer.get_bounds()
		text = start.get_text(end)
		self.assertEqual(text, r'\alpha ') # no replace

		# test dialog
		def check_dialog(dialog):
			self.assertIsInstance(dialog, InsertSymbolDialog)
			dialog.iconview.item_activated(Gtk.TreePath((9,))) # path for 10th item in symbol list
			dialog.iconview.item_activated(Gtk.TreePath((10,))) # path for 11th item in symbol list
			dialog.iconview.item_activated(Gtk.TreePath((11,))) # path for 12th item in symbol list
			dialog.assert_response_ok()

		buffer.clear()
		pageview_ext = find_extension(pageview, InsertSymbolPageViewExtension)
		with tests.DialogContext(check_dialog):
			pageview_ext.insert_symbol()
		start, end = buffer.get_bounds()
		text = start.get_text(end)
		self.assertEqual(text, EACUTE + ECIRC + EGRAVE)
Ejemplo n.º 19
0
    def __init__(self,
                 window,
                 notebook=None,
                 page=None,
                 namespace=None,
                 basename=None,
                 append=None,
                 text=None,
                 template_options=None,
                 attachments=None):
        assert page is None, 'TODO'

        manager = ConfigManager()  # FIXME should be passed in
        self.config = manager.get_config_dict('quicknote.conf')
        self.uistate = self.config['QuickNoteDialog']

        Dialog.__init__(self, window, _('Quick Note'))
        self._updating_title = False
        self._title_set_manually = not basename is None
        self.attachments = attachments

        if notebook and not isinstance(notebook, str):
            notebook = notebook.uri

        self.uistate.setdefault('lastnotebook', None, str)
        if self.uistate['lastnotebook']:
            notebook = notebook or self.uistate['lastnotebook']
            self.config['Namespaces'].setdefault(notebook, None, str)
            namespace = namespace or self.config['Namespaces'][notebook]

        self.form = InputForm()
        self.vbox.pack_start(self.form, False, True, 0)

        # TODO dropdown could use an option "Other..."
        label = Gtk.Label(label=_('Notebook') + ': ')
        label.set_alignment(0.0, 0.5)
        self.form.attach(label, 0, 1, 0, 1, xoptions=Gtk.AttachOptions.FILL)
        # T: Field to select Notebook from drop down list
        self.notebookcombobox = NotebookComboBox(current=notebook)
        self.notebookcombobox.connect('changed', self.on_notebook_changed)
        self.form.attach(self.notebookcombobox, 1, 2, 0, 1)

        self._init_inputs(namespace, basename, append, text, template_options)

        self.uistate['lastnotebook'] = notebook
        self._set_autocomplete(notebook)
Ejemplo n.º 20
0
class GoogletasksCommand(NotebookCommand, GtkCommand):
    """Class to handle "zim --plugin googletasks" """
    arguments = ('[NOTEBOOK]',)

    preferences = ConfigManager().get_config_dict('preferences.conf')['GoogletasksPlugin'].dump()

    def run(self):
        ntb_name = self.get_notebook_argument()[0] or self.get_default_or_only_notebook()
        ntb, _ = build_notebook(ntb_name)
        GoogletasksController(notebook=ntb, preferences=GoogletasksCommand.preferences).fetch()  # add new lines
Ejemplo n.º 21
0
	def testChangeFont(self):
		preferences = ConfigManager.get_config_dict('preferences.conf')
		window = MyWindow()

		text_style = ConfigManager.get_config_dict('style.conf')
		text_style['TextView'].setdefault('font', None, str)
		text_style['TextView']['font'] = 'Sans 12'

		dialog = PreferencesDialog(window)
		self.assertEqual(dialog.forms['Interface']['use_custom_font'], True)
		dialog.assert_response_ok()
		self.assertEqual(text_style['TextView']['font'], 'Sans 12')
		self.assertFalse(any(['use_custom_font' in d for d in list(preferences.values())]))

		text_style['TextView']['font'] = 'Sans 12'
		dialog = PreferencesDialog(window)
		self.assertEqual(dialog.forms['Interface']['use_custom_font'], True)
		dialog.forms['Interface']['use_custom_font'] = False
		dialog.assert_response_ok()
		self.assertEqual(text_style['TextView']['font'], None)
		self.assertFalse(any(['use_custom_font' in d for d in list(preferences.values())]))
Ejemplo n.º 22
0
	def testSetSimpleValue(self):
		preferences = ConfigManager.get_config_dict('preferences.conf')
		window = MyWindow()

		dialog = PreferencesDialog(window)
		self.assertEqual(dialog.forms['Interface']['toggle_on_ctrlspace'], False)
		dialog.assert_response_ok()
		self.assertEqual(preferences['GtkInterface']['toggle_on_ctrlspace'], False)

		dialog = PreferencesDialog(window)
		dialog.forms['Interface']['toggle_on_ctrlspace'] = True
		dialog.assert_response_ok()
		self.assertEqual(preferences['GtkInterface']['toggle_on_ctrlspace'], True)
Ejemplo n.º 23
0
	def __init__(self, window, notebook=None,
		page=None, namespace=None, basename=None,
		append=None, text=None, template_options=None, attachments=None
	):
		assert page is None, 'TODO'
		manager = ConfigManager() # FIXME should be passed in
		self.config = manager.get_config_dict('quicknote.conf')
		self.uistate = self.config['QuickNoteDialog']

		Dialog.__init__(self, window, _('Quick Note'))
		self._updating_title = False
		self._title_set_manually = not basename is None
		self.attachments = attachments

		if notebook and not isinstance(notebook, basestring):
			notebook = notebook.uri

		self.uistate.setdefault('lastnotebook', None, basestring)
		if self.uistate['lastnotebook']:
			notebook = notebook or self.uistate['lastnotebook']
			self.config['Namespaces'].setdefault(notebook, None, basestring)
			namespace = namespace or self.config['Namespaces'][notebook]

		self.form = InputForm()
		self.vbox.pack_start(self.form, False)

		# TODO dropdown could use an option "Other..."
		label = gtk.Label(_('Notebook')+': ')
		label.set_alignment(0.0, 0.5)
		self.form.attach(label, 0,1, 0,1, xoptions=gtk.FILL)
			# T: Field to select Notebook from drop down list
		self.notebookcombobox = NotebookComboBox(current=notebook)
		self.notebookcombobox.connect('changed', self.on_notebook_changed)
		self.form.attach(self.notebookcombobox, 1,2, 0,1)

		self._init_inputs(namespace, basename, append, text, template_options)

		self.uistate['lastnotebook'] = notebook
		self._set_autocomplete(notebook)
Ejemplo n.º 24
0
def mount_notebook(filepath):
	from zim.config import ConfigManager, String

	configdict = ConfigManager.get_config_dict('automount.conf')

	groups = sorted([k for k in list(configdict.keys()) if k.startswith('Path')])
	for group in groups:
		path = group[4:].strip() # len('Path') = 4
		dir = Dir(path)
		if is_relevant_mount_point(dir, filepath):
			configdict[group].define(mount=String(None))
			handler = ApplicationMountPointHandler(dir, **configdict[group])
			if handler(filepath):
				break
Ejemplo n.º 25
0
    def setUp(self):
        clear_customtools()

        notebook = self.setUpNotebook(content=('test', ))
        page = notebook.get_page(Path('test'))

        self.uimanager = Gtk.UIManager()
        group = Gtk.ActionGroup('test')
        group.add_actions([('tools_menu', None, '_Tools')])
        self.uimanager.insert_action_group(group)

        self.pageview = StubPageView(notebook, page)
        self.config = ConfigManager()
        self.customtoolsui = CustomToolManagerUI(self.uimanager, self.config,
                                                 self.pageview)
Ejemplo n.º 26
0
    def init_uistate(self):
        # Initialize all the uistate parameters
        # delayed till show or show_all because all this needs real
        # uistate to be in place and plugins to be loaded
        # Run between loading plugins and actually presenting the window to the user

        if not self._geometry_set:
            # Ignore this if an explicit geometry was specified to the constructor
            if self.uistate['windowpos'] is not None:
                x, y = self.uistate['windowpos']
                self.move(x, y)

            w, h = self.uistate['windowsize']
            self.set_default_size(w, h)

            if self.uistate['windowmaximized']:
                self.maximize()

        Window.init_uistate(self)  # takes care of sidepane positions etc

        self.toggle_fullscreen(self._set_fullscreen)

        # And hook to notebook properties
        self.on_notebook_properties_changed(self.notebook.properties)
        self.notebook.properties.connect('changed',
                                         self.on_notebook_properties_changed)

        # Notify plugins
        self.emit('init-uistate')

        # Update menus etc.
        self.uimanager.ensure_update()
        # Prevent flashing when the toolbar is loaded after showing the window
        # and do this before connecting signal below for accelmap.

        # Load accelmap config and setup saving it
        # TODO - this probably belongs in the application class, not here
        accelmap = ConfigManager.get_config_file('accelmap').file
        logger.debug('Accelmap: %s', accelmap.path)
        if accelmap.exists():
            Gtk.AccelMap.load(accelmap.path)

        def on_accel_map_changed(o, path, key, mod):
            logger.info('Accelerator changed for %s', path)
            Gtk.AccelMap.save(accelmap.path)

        Gtk.AccelMap.get().connect('changed', on_accel_map_changed)
Ejemplo n.º 27
0
	def get_tool(self, name):
		'''Get a L{CustomTool} by name.
		@param name: the tool name
		@returns: a L{CustomTool} object or C{None}
		'''
		if not '-usercreated' in name:
			name = cleanup_filename(name.lower()) + '-usercreated'

		if not name in self._tools:
			file = ConfigManager.get_config_file('customtools/%s.desktop' % name)
			if file.exists():
				tool = CustomTool(file)
				self._tools[name] = tool
				file.connect('changed', partial(self._on_tool_changed, tool))
			else:
				return None

		return self._tools[name]
Ejemplo n.º 28
0
	def load_file(self):
		self.symbols = {}
		self.symbol_order = []
		file = ConfigManager.get_config_file('symbols.list')
		for line in file.readlines():
			line = line.strip()
			if not line or line.startswith('#'):
				continue
			try:
				if '#' in line:
					line, _ = line.split('#', 1)
					line = line.strip()
				shortcut, code = line.split()
				symbol = chr(int(code))
				if not shortcut in self.symbols:
					self.symbols[shortcut] = symbol
					self.symbol_order.append(shortcut)
				else:
					logger.exception('Shortcut defined twice: %s', shortcut)
			except:
				logger.exception('Could not parse symbol: %s', line)
Ejemplo n.º 29
0
    def run(self):
        from zim.export.selections import AllPages, SinglePage, SubPages
        from zim.plugins import PluginManager
        from zim.config import ConfigManager

        notebook, page = self.build_notebook()

        # load plugins, needed so the the proper export functions would work from CLI
        config = ConfigManager(profile=notebook.profile)
        plugins = PluginManager(config)
        plugins.extend(notebook.index)
        plugins.extend(notebook)

        if page and self.opts.get('recursive'):
            selection = SubPages(notebook, page)
        elif page:
            selection = SinglePage(notebook, page)
        else:
            selection = AllPages(notebook)

        exporter = self.get_exporter(page)
        exporter.export(selection)
Ejemplo n.º 30
0
	def __init__(self):
		self.config = ConfigManager() # XXX should be passed in
		self.names = []
		self.tools = {}
		self._read_list()
Ejemplo n.º 31
0
class CustomToolManager(object):
	'''Manager for dealing with the desktop files which are used to
	store custom tools.

	Custom tools are external commands that are intended to show in the
	"Tools" menu in zim (and optionally in the tool bar). They are
	defined as desktop entry files in a special folder (typically
	"~/.local/share/zim/customtools") and use several non standard keys.
	See L{CustomTool} for details.

	This object is iterable and maintains a specific order for tools
	to be shown in in the user interface.
	'''

	def __init__(self):
		self.config = ConfigManager() # XXX should be passed in
		self.names = []
		self.tools = {}
		self._read_list()

	def _read_list(self):
		file = self.config.get_config_file('customtools/customtools.list')
		seen = set()
		for line in file.readlines():
			name = line.strip()
			if not name in seen:
				seen.add(name)
				self.names.append(name)

	def _write_list(self):
		file = self.config.get_config_file('customtools/customtools.list')
		file.writelines([name + '\n' for name in self.names])

	def __iter__(self):
		for name in self.names:
			tool = self.get_tool(name)
			if tool and tool.isvalid():
				yield tool

	def get_tool(self, name):
		'''Get a L{CustomTool} by name.
		@param name: the tool name
		@returns: a L{CustomTool} object
		'''
		if not name in self.tools:
			file = self.config.get_config_file('customtools/%s.desktop' % name)
			tool = CustomTool(file)
			self.tools[name] = tool

		return self.tools[name]

	def create(self, Name, **properties):
		'''Create a new custom tool

		@param Name: the name to show in the Tools menu
		@param properties: properties for the custom tool, e.g.:
		  - Comment
		  - Icon
		  - X-Zim-ExecTool
		  - X-Zim-ReadOnly
		  - X-Zim-ShowInToolBar

		@returns: a new L{CustomTool} object.
		'''
		properties['Type'] = 'X-Zim-CustomTool'
		dir = XDG_CONFIG_HOME.subdir('zim/customtools')
		tool = _create_application(dir, Name, '', klass=CustomTool, NoDisplay=False, **properties)
		self.tools[tool.key] = tool
		self.names.append(tool.key)
		self._write_list()

		return tool

	def delete(self, tool):
		'''Remove a custom tool from the list and delete the definition
		file.
		@param tool: a custom tool name or L{CustomTool} object
		'''
		if not isinstance(tool, CustomTool):
			tool = self.get_tool(tool)
		tool.file.remove()
		self.tools.pop(tool.key)
		self.names.remove(tool.key)
		self._write_list()

	def index(self, tool):
		'''Get the position of a specific tool in the list.
		@param tool: a custom tool name or L{CustomTool} object
		@returns: an integer for the position
		'''
		if isinstance(tool, CustomTool):
			tool = tool.key
		return self.names.index(tool)

	def reorder(self, tool, i):
		'''Change the position of a tool in the list.
		@param tool: a custom tool name or L{CustomTool} object
		@param i: the new position as integer
		'''
		if not 0 <= i < len(self.names):
			return

		if isinstance(tool, CustomTool):
			tool = tool.key

		j = self.names.index(tool)
		self.names.pop(j)
		self.names.insert(i, tool)
		# Insert before i. If i was before old position indeed before
		# old item at that position. However if i was after old position
		# if shifted due to the pop(), now it inserts after the old item.
		# This is intended behavior to make all moves possible.
		self._write_list()
Ejemplo n.º 32
0
	def setUp(self):
		config = ConfigManager()
		list = config.get_config_file('notebooks.list')
		file = list.file
		if file.exists():
			file.remove()
Ejemplo n.º 33
0
    def init_uistate(self):
        # Initialize all the uistate parameters
        # delayed till show or show_all because all this needs real
        # uistate to be in place and plugins to be loaded
        # Run between loading plugins and actually presenting the window to the user

        if not self._geometry_set:
            # Ignore this if an explicit geometry was specified to the constructor
            if self.uistate['windowpos'] is not None:
                x, y = self.uistate['windowpos']
                self.move(x, y)

            w, h = self.uistate['windowsize']
            self.set_default_size(w, h)

            if self.uistate['windowmaximized']:
                self.maximize()

        # For these two "None" means system default, but we don't know what that default is :(
        self.preferences.setdefault(
            'toolbar_style', None,
            (TOOLBAR_ICONS_ONLY, TOOLBAR_ICONS_AND_TEXT, TOOLBAR_TEXT_ONLY))
        self.preferences.setdefault(
            'toolbar_size', None,
            (TOOLBAR_ICONS_TINY, TOOLBAR_ICONS_SMALL, TOOLBAR_ICONS_LARGE))

        self.toggle_toolbar(self.uistate['show_toolbar'])
        self.toggle_statusbar(self.uistate['show_statusbar'])

        Window.init_uistate(self)  # takes care of sidepane positions etc

        if self.preferences['toolbar_style'] is not None:
            self.set_toolbar_style(self.preferences['toolbar_style'])

        if self.preferences['toolbar_size'] is not None:
            self.set_toolbar_icon_size(self.preferences['toolbar_size'])

        self.toggle_fullscreen(self._set_fullscreen)

        if self.notebook.readonly:
            self.toggle_editable(False)
            action = self.actiongroup.get_action('toggle_editable')
            action.set_sensitive(False)
        else:
            self.toggle_editable(not self.uistate['readonly'])

        # And hook to notebook properties
        self.on_notebook_properties_changed(self.notebook.properties)
        self.notebook.properties.connect('changed',
                                         self.on_notebook_properties_changed)

        # Hook up the statusbar
        self.connect('page-changed', self.do_update_statusbar)
        self.connect('readonly-changed', self.do_update_statusbar)
        self.pageview.connect('modified-changed', self.do_update_statusbar)
        self.notebook.connect_after('stored-page', self.do_update_statusbar)

        # Notify plugins
        self.emit('init-uistate')

        # Update menus etc.
        self.uimanager.ensure_update()
        # Prevent flashing when the toolbar is loaded after showing the window
        # and do this before connecting signal below for accelmap.

        # Add search bar onec toolbar is loaded
        space = Gtk.SeparatorToolItem()
        space.set_draw(False)
        space.set_expand(True)
        self.toolbar.insert(space, -1)

        from zim.gui.widgets import InputEntry
        entry = InputEntry(placeholder_text=_('Search'))
        entry.set_icon_from_stock(Gtk.EntryIconPosition.SECONDARY,
                                  Gtk.STOCK_FIND)
        entry.set_icon_activatable(Gtk.EntryIconPosition.SECONDARY, True)
        entry.set_icon_tooltip_text(Gtk.EntryIconPosition.SECONDARY,
                                    _('Search Pages...'))
        # T: label in search entry
        inline_search = lambda e, *a: self._uiactions.show_search(
            query=e.get_text() or None)
        entry.connect('activate', inline_search)
        entry.connect('icon-release', inline_search)
        entry.show()
        item = Gtk.ToolItem()
        item.add(entry)
        self.toolbar.insert(item, -1)

        # Load accelmap config and setup saving it
        # TODO - this probably belongs in the application class, not here
        accelmap = ConfigManager.get_config_file('accelmap').file
        logger.debug('Accelmap: %s', accelmap.path)
        if accelmap.exists():
            Gtk.AccelMap.load(accelmap.path)

        def on_accel_map_changed(o, path, key, mod):
            logger.info('Accelerator changed for %s', path)
            Gtk.AccelMap.save(accelmap.path)

        Gtk.AccelMap.get().connect('changed', on_accel_map_changed)

        self.do_update_statusbar()
Ejemplo n.º 34
0
class CustomToolManager(object):
	'''Manager for dealing with the desktop files which are used to
	store custom tools.

	Custom tools are external commands that are intended to show in the
	"Tools" menu in zim (and optionally in the tool bar). They are
	defined as desktop entry files in a special folder (typically
	"~/.local/share/zim/customtools") and use several non standard keys.
	See L{CustomTool} for details.

	This object is iterable and maintains a specific order for tools
	to be shown in in the user interface.
	'''

	def __init__(self):
		self.config = ConfigManager() # XXX should be passed in
		self.names = []
		self.tools = {}
		self._read_list()

	def _read_list(self):
		file = self.config.get_config_file('customtools/customtools.list')
		seen = set()
		for line in file.readlines():
			name = line.strip()
			if not name in seen:
				seen.add(name)
				self.names.append(name)

	def _write_list(self):
		file = self.config.get_config_file('customtools/customtools.list')
		file.writelines([name + '\n' for name in self.names])

	def __iter__(self):
		for name in self.names:
			tool = self.get_tool(name)
			if tool and tool.isvalid():
				yield tool

	def get_tool(self, name):
		'''Get a L{CustomTool} by name.
		@param name: the tool name
		@returns: a L{CustomTool} object
		'''
		if not name in self.tools:
			file = self.config.get_config_file('customtools/%s.desktop' % name)
			tool = CustomTool(file)
			self.tools[name] = tool

		return self.tools[name]

	def create(self, Name, **properties):
		'''Create a new custom tool

		@param Name: the name to show in the Tools menu
		@param properties: properties for the custom tool, e.g.:
		  - Comment
		  - Icon
		  - X-Zim-ExecTool
		  - X-Zim-ReadOnly
		  - X-Zim-ShowInToolBar

		@returns: a new L{CustomTool} object.
		'''
		properties['Type'] = 'X-Zim-CustomTool'
		dir = XDG_CONFIG_HOME.subdir('zim/customtools')
		tool = _create_application(dir, Name, '', klass=CustomTool, NoDisplay=False, **properties)
		self.tools[tool.key] = tool
		self.names.append(tool.key)
		self._write_list()

		return tool

	def delete(self, tool):
		'''Remove a custom tool from the list and delete the definition
		file.
		@param tool: a custom tool name or L{CustomTool} object
		'''
		if not isinstance(tool, CustomTool):
			tool = self.get_tool(tool)
		tool.file.remove()
		self.tools.pop(tool.key)
		self.names.remove(tool.key)
		self._write_list()

	def index(self, tool):
		'''Get the position of a specific tool in the list.
		@param tool: a custom tool name or L{CustomTool} object
		@returns: an integer for the position
		'''
		if isinstance(tool, CustomTool):
			tool = tool.key
		return self.names.index(tool)

	def reorder(self, tool, i):
		'''Change the position of a tool in the list.
		@param tool: a custom tool name or L{CustomTool} object
		@param i: the new position as integer
		'''
		if not 0 <= i < len(self.names):
			return

		if isinstance(tool, CustomTool):
			tool = tool.key

		j = self.names.index(tool)
		self.names.pop(j)
		self.names.insert(i, tool)
		# Insert before i. If i was before old position indeed before
		# old item at that position. However if i was after old position
		# if shifted due to the pop(), now it inserts after the old item.
		# This is intended behavior to make all moves possible.
		self._write_list()
Ejemplo n.º 35
0
 def setUp(self):
     config = ConfigManager()
     list = config.get_config_file('notebooks.list')
     file = list.file
     if file.exists():
         file.remove()
Ejemplo n.º 36
0
	def __init__(self):
		self.config = ConfigManager() # XXX should be passed in
		self.names = []
		self.tools = {}
		self._read_list()