Permalink
Browse files

Add NotesTreeRegistry. Tree items state is stored in the registry now.

  • Loading branch information...
Jenyay committed Jun 10, 2018
1 parent 48a4808 commit 27470d8b1bdb701a765b05edc5a6ae3d012998f4
View
@@ -53,3 +53,4 @@ serverinfo.py
.vscode
Pipfile.lock
.pytest_cache
__cache.tmp
@@ -338,6 +338,7 @@ def wikiroot(self, value):
self.onWikiClose(self.__wikiroot)
if self.__wikiroot is not None:
self.__wikiroot.save()
self.__unbindWikiEvents(self.__wikiroot)
self.__wikiroot = value
@@ -14,6 +14,9 @@
# Page options (properties)
PAGE_OPT_FILE = u'__page.opt'
# Registry file (cache)
REGISTRY_FILE = '__cache.tmp'
# Base name for icons
PAGE_ICON_NAME = u'__icon'
@@ -57,6 +60,8 @@
CONFIG_TOOLBARS_SECTION = 'Toolbars'
CONFIG_TOOLBARS_VISIBLE_SUFFIX = '_visible'
REGISTRY_SECTION_PAGES = '__pages'
# To translate this words with xgettext
if __name__ == u'__main__':
@@ -211,3 +211,13 @@ def _set(self, path, option_name, value):
raise KeyError
parent[option_name] = value
def get_subregistry(self, *args):
if not args:
raise KeyError
item = self._get_item(args, self._items)
if not self._is_section(item):
raise KeyError
return Registry(item)
@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
import json
import logging
from collections import MutableMapping
from .registry import Registry
from .defines import REGISTRY_SECTION_PAGES
from outwiker.utilites.textfile import readTextFile, writeTextFile
logger = logging.getLogger('outwiker.core.notestreeregistry')
class BaseSaver(object, metaclass=ABCMeta):
@abstractmethod
def load(self):
pass
@abstractmethod
def save(self, items_dict):
pass
class JSONSaver(BaseSaver):
def __init__(self, fname):
self._fname = fname
def load(self):
try:
text = readTextFile(self._fname)
items = json.loads(text)
except (IOError, json.JSONDecodeError):
logger.error('Error reading a notes tree registry')
items = {}
return items
def save(self, items):
text = json.dumps(items)
try:
writeTextFile(self._fname, text)
except IOError:
logger.error('Error saving a notes tree registry')
class NotesTreeRegistry(Registry):
def __init__(self, saver):
'''
saver - interface with two methods - save() and load().
'''
self._saver = saver
self._version = 1
self._VERSION_OPTION = '__version'
items = saver.load()
if items.get(self._VERSION_OPTION, None) != self._version:
logger.warning('Invalid notes tree registry version')
items = {}
if not isinstance(items, MutableMapping):
logger.error('Invalid notes tree registry format')
items = {}
items[self._VERSION_OPTION] = self._version
super().__init__(items)
def save(self):
self._saver.save(self._items)
def _get_pages_section(self):
try:
subregistry = self.get_subregistry(REGISTRY_SECTION_PAGES)
except KeyError:
self._items[REGISTRY_SECTION_PAGES] = {}
subregistry = self.get_subregistry(REGISTRY_SECTION_PAGES)
return subregistry
def get_section_or_create(self, *path_elements):
path_elements_list = list(path_elements[:])
parent = self._items
while path_elements_list:
next = path_elements_list.pop(0)
if next not in parent or not self._is_section(parent[next]):
parent[next] = {}
parent = parent[next]
return Registry(parent)
def get_page_registry(self, page):
return self.get_section_or_create(REGISTRY_SECTION_PAGES, page.subpath)
View
@@ -1,4 +1,4 @@
# -*- coding: UTF-8 -*-
# -*- coding: utf-8 -*-
import logging
import os
@@ -9,21 +9,17 @@
from functools import cmp_to_key
from functools import reduce
from outwiker.core.config import PageConfig
from outwiker.core.bookmarks import Bookmarks
from outwiker.core.event import Event
from outwiker.core.exceptions import (ClearConfigError,
RootFormatError,
DuplicateTitle,
ReadonlyException,
TreeException)
from outwiker.core.tagscommands import parseTagsList
from outwiker.core.sortfunctions import (sortOrderFunction,
sortAlphabeticalFunction)
from outwiker.core.defines import (PAGE_CONTENT_FILE,
PAGE_OPT_FILE)
from outwiker.core.iconcontroller import IconController
from outwiker.core.system import getIconsDirList
from .config import PageConfig
from .bookmarks import Bookmarks
from .event import Event
from .exceptions import (ClearConfigError, RootFormatError, DuplicateTitle,
ReadonlyException, TreeException)
from .tagscommands import parseTagsList
from .sortfunctions import sortOrderFunction, sortAlphabeticalFunction
from .defines import PAGE_CONTENT_FILE, PAGE_OPT_FILE, REGISTRY_FILE
from .iconcontroller import IconController
from .system import getIconsDirList
from .registrynotestree import NotesTreeRegistry, JSONSaver
from . import events
@@ -275,6 +271,11 @@ def __init__(self, path, readonly=False):
self._selectedPage = None
self._createEvents()
self.bookmarks = Bookmarks(self, self._params)
self._registry = NotesTreeRegistry(self._getRegistrySaver(self._path))
def _getRegistrySaver(self, path):
registry_path = os.path.join(path, REGISTRY_FILE)
return JSONSaver(registry_path)
def _createEvents(self):
# Выбор новой страницы
@@ -360,6 +361,10 @@ def load(path, readonly=False):
root.onTreeUpdate(root)
return root
def save(self):
super().save()
self._registry.save()
@staticmethod
def create(path):
"""
@@ -402,6 +407,10 @@ def title(self):
def getTypeString():
return u"document"
@property
def registry(self):
return self._registry
class WikiPage(RootWikiPage):
"""
@@ -2,7 +2,6 @@
import os
import os.path
import configparser
import wx
@@ -16,7 +15,6 @@
from outwiker.actions.removepage import RemovePageAction
from outwiker.actions.editpageprop import EditPagePropertiesAction
from outwiker.actions.moving import GoToParentAction
from outwiker.core.config import BooleanOption
from outwiker.core.events import PAGE_UPDATE_ICON
from outwiker.core.defines import ICON_WIDTH, ICON_HEIGHT
from outwiker.gui.pagepopupmenu import PagePopupMenu
@@ -238,18 +236,13 @@ def __saveItemState(self, itemid):
assert itemid.IsOk()
page = self.treeCtrl.GetItemData(itemid)
if page.readonly:
return
expanded = self.treeCtrl.IsExpanded(itemid)
expandedOption = BooleanOption(page.params,
self.pageOptionsSection,
self.pageOptionExpand,
False)
try:
expandedOption.value = expanded
except IOError as e:
outwiker.core.commands.MessageBox(
_(u"Can't save page options\n{}").format(str(e)),
_(u"Error"), wx.ICON_ERROR | wx.OK)
page_registry = page.root.registry.get_page_registry(page)
page_registry.set(self.pageOptionExpand, expanded)
def __getItemExpandState(self, page):
"""
@@ -266,21 +259,15 @@ def __getItemExpandState(self, page):
def __getPageExpandState(self, page):
"""
Проверить состояние "раскрытости" страницы
(что по этому поводу написано в настройках страницы)
"""
if page is None:
return True
if page.parent is None:
return True
try:
expanded = page.params.getbool(self.pageOptionsSection,
self.pageOptionExpand)
except configparser.NoSectionError:
return False
except configparser.NoOptionError:
return False
page_registry = page.root.registry.get_page_registry(page)
expanded = page_registry.getbool(self.pageOptionExpand, default=False)
return expanded
@@ -620,3 +620,88 @@ def test_set_05(self):
self.assertTrue(reg.has_option('раздел-1', 'раздел-2', 'параметр'))
self.assertEqual(reg.getint('раздел-1', 'раздел-2', 'параметр'), 100)
def test_get_subregistry_error_01(self):
items = {}
reg = Registry(items)
self.assertRaises(KeyError, reg.get_subregistry)
def test_get_subregistry_error_02(self):
items = {}
reg = Registry(items)
self.assertRaises(KeyError, reg.get_subregistry, 'раздел')
def test_get_subregistry_error_03(self):
items = {
'параметр': 10,
}
reg = Registry(items)
self.assertRaises(KeyError, reg.get_subregistry, 'параметр')
def test_get_subregistry_error_04(self):
items = {
'раздел': {
'параметр': 10,
},
}
reg = Registry(items)
self.assertRaises(KeyError, reg.get_subregistry, 'раздел', 'параметр')
def test_get_subregistry_01(self):
items = {
'раздел': {
'параметр': 10,
},
}
reg = Registry(items)
subreg = reg.get_subregistry('раздел')
self.assertTrue(subreg.has_option('параметр'))
def test_get_subregistry_02(self):
items = {
'раздел-1': {
'раздел-2': {
'параметр': 10,
},
},
}
reg = Registry(items)
subreg = reg.get_subregistry('раздел-1')
self.assertTrue(subreg.has_option('раздел-2', 'параметр'))
def test_get_subregistry_03_change(self):
items = {
'раздел-1': {
'раздел-2': {
'параметр': 10,
},
},
}
reg = Registry(items)
subreg = reg.get_subregistry('раздел-1')
subreg.set('раздел-2', 'параметр', 1000)
self.assertEqual(subreg.getint('раздел-2', 'параметр'), 1000)
self.assertEqual(reg.getint('раздел-1', 'раздел-2', 'параметр'), 1000)
def test_get_subregistry_04_change(self):
items = {
'раздел-1': {
'раздел-2': {
'параметр': 10,
},
},
}
reg = Registry(items)
subreg = reg.get_subregistry('раздел-1')
subreg.create_section('раздел-2', 'раздел-3')
self.assertTrue(reg.has_section('раздел-1', 'раздел-2', 'раздел-3'))
Oops, something went wrong.

0 comments on commit 27470d8

Please sign in to comment.