Path fix ups

bzr-revno: 2881
This commit is contained in:
Phill 2019-06-25 12:13:01 +01:00
commit c5cac9fa34
6 changed files with 26 additions and 30 deletions

View File

@ -111,6 +111,8 @@ class OpenLPJSONDecoder(JSONDecoder):
:param dict obj: A decoded JSON object :param dict obj: A decoded JSON object
:return: The custom object from the serialized data if the custom object is registered, else obj :return: The custom object from the serialized data if the custom object is registered, else obj
""" """
if '__Path__' in obj:
return PathSerializer.encode_json(obj, **self.kwargs)
try: try:
key = obj['json_meta']['class'] key = obj['json_meta']['class']
except KeyError: except KeyError:
@ -150,8 +152,8 @@ class OpenLPJSONEncoder(JSONEncoder):
if isinstance(obj, JSONMixin): if isinstance(obj, JSONMixin):
return obj.json_object() return obj.json_object()
elif obj.__class__.__name__ in _registered_classes: elif obj.__class__.__name__ in _registered_classes:
return _registered_classes[obj.__class__.__name__].json_object(obj) return _registered_classes[obj.__class__.__name__].json_object(obj, **self.kwargs)
return super().default(obj) return super().default(obj, **self.kwargs)
def is_serializable(obj): def is_serializable(obj):
@ -174,17 +176,22 @@ class PathSerializer(JSONMixin, register_names=('Path', 'PosixPath', 'WindowsPat
:param kwargs: Contains any extra parameters. Not used! :param kwargs: Contains any extra parameters. Not used!
:return Path: The deserialized Path object :return Path: The deserialized Path object
""" """
path = Path(*obj['parts']) if '__Path__' in obj:
parts = obj['__Path__']
else:
parts = obj['parts']
path = Path(*parts)
if base_path and not path.is_absolute(): if base_path and not path.is_absolute():
return base_path / path return base_path / path
return path return path
@classmethod @classmethod
def json_object(cls, obj, base_path=None, **kwargs): def json_object(cls, obj, base_path=None, is_js=False, **kwargs):
""" """
Create a dictionary that can be JSON decoded. Create a dictionary that can be JSON decoded.
:param Path base_path: If specified, an absolute path to make a relative path from. :param Path base_path: If specified, an absolute path to make a relative path from.
:param bool is_js: Encode the path as a uri. For example for use in the js rendering code.
:param kwargs: Contains any extra parameters. Not used! :param kwargs: Contains any extra parameters. Not used!
:return: The dictionary representation of this Path object. :return: The dictionary representation of this Path object.
:rtype: dict[tuple] :rtype: dict[tuple]
@ -193,6 +200,8 @@ class PathSerializer(JSONMixin, register_names=('Path', 'PosixPath', 'WindowsPat
if base_path: if base_path:
with suppress(ValueError): with suppress(ValueError):
path = path.relative_to(base_path) path = path.relative_to(base_path)
if is_js is True:
return path.as_uri()
json_dict = {'parts': path.parts} json_dict = {'parts': path.parts}
cls.attach_meta(json_dict) cls.attach_meta(json_dict)
return json_dict return json_dict

View File

@ -612,7 +612,7 @@ class Settings(QtCore.QSettings):
elif isinstance(default_value, dict): elif isinstance(default_value, dict):
return {} return {}
elif isinstance(setting, str): elif isinstance(setting, str):
if 'json_meta' in setting or setting.startswith('{'): if 'json_meta' in setting or '__Path__' in setting or setting.startswith('{'):
return json.loads(setting, cls=OpenLPJSONDecoder) return json.loads(setting, cls=OpenLPJSONDecoder)
# Convert the setting to the correct type. # Convert the setting to the correct type.
if isinstance(default_value, bool): if isinstance(default_value, bool):

View File

@ -117,20 +117,6 @@ function _prepareText(text) {
return "<p>" + _nl2br(text) + "</p>"; return "<p>" + _nl2br(text) + "</p>";
} }
/**
* The paths we get are JSON versions of Python Path objects, so let's just fix that.
* @private
* @param {object} path - The Path object
* @returns {string} The actual file path
*/
function _pathToString(path) {
var filename = path.__Path__.join("/").replace("//", "/");
if (!filename.startsWith("/")) {
filename = "/" + filename;
}
return filename;
}
/** /**
* An audio player with a play list * An audio player with a play list
*/ */
@ -676,13 +662,13 @@ var Display = {
} }
break; break;
case BackgroundType.Image: case BackgroundType.Image:
background_filename = _pathToString(theme.background_filename); backgroundStyle["background-image"] = "url('" + theme.background_filename + "')";
backgroundStyle["background-image"] = "url('file://" + background_filename + "')"; console.warn(backgroundStyle["background-image"]);
break; break;
case BackgroundType.Video: case BackgroundType.Video:
background_filename = _pathToString(theme.background_filename);
backgroundStyle["background-color"] = theme.background_border_color; backgroundStyle["background-color"] = theme.background_border_color;
backgroundHtml = "<video loop autoplay muted><source src='file://" + background_filename + "'></video>"; backgroundHtml = "<video loop autoplay muted><source src='" + theme.background_filename + "'></video>";
console.warn(backgroundHtml);
break; break;
default: default:
backgroundStyle["background"] = "#000"; backgroundStyle["background"] = "#000";

View File

@ -332,9 +332,9 @@ class DisplayWindow(QtWidgets.QWidget):
theme_copy = copy.deepcopy(theme) theme_copy = copy.deepcopy(theme)
theme_copy.background_type = 'image' theme_copy.background_type = 'image'
theme_copy.background_filename = self.checkerboard_path theme_copy.background_filename = self.checkerboard_path
exported_theme = theme_copy.export_theme() exported_theme = theme_copy.export_theme(is_js=True)
else: else:
exported_theme = theme.export_theme() exported_theme = theme.export_theme(is_js=True)
self.run_javascript('Display.setTheme({theme});'.format(theme=exported_theme)) self.run_javascript('Display.setTheme({theme});'.format(theme=exported_theme))
def get_video_types(self): def get_video_types(self):

View File

@ -225,17 +225,18 @@ class Theme(object):
jsn = json.loads(theme, cls=OpenLPJSONDecoder) jsn = json.loads(theme, cls=OpenLPJSONDecoder)
self.expand_json(jsn) self.expand_json(jsn)
def export_theme(self, theme_path=None): def export_theme(self, theme_path=None, is_js=False):
""" """
Loop through the fields and build a dictionary of them Loop through the fields and build a dictionary of them
:param pathlib.Path | None theme_path:
:param bool is_js: For internal use, for example with the theme js code.
:return str: The json encoded theme object
""" """
theme_data = {} theme_data = {}
for attr, value in self.__dict__.items(): for attr, value in self.__dict__.items():
theme_data["{attr}".format(attr=attr)] = value theme_data["{attr}".format(attr=attr)] = value
if theme_path: return json.dumps(theme_data, cls=OpenLPJSONEncoder, base_path=theme_path, is_js=is_js)
return json.dumps(theme_data, cls=OpenLPJSONEncoder, base_path=theme_path)
return json.dumps(theme_data, cls=OpenLPJSONEncoder)
def parse(self, xml): def parse(self, xml):
""" """

View File

@ -129,7 +129,7 @@ class PresentationDocument(object):
thumbnail_folder_path = self.get_thumbnail_folder() thumbnail_folder_path = self.get_thumbnail_folder()
temp_folder_path = self.get_temp_folder() temp_folder_path = self.get_temp_folder()
if thumbnail_folder_path.exists(): if thumbnail_folder_path.exists():
thumbnail_folder_path.rmtree() shutil.rmtree(thumbnail_folder_path)
if temp_folder_path.exists(): if temp_folder_path.exists():
shutil.rmtree(temp_folder_path) shutil.rmtree(temp_folder_path)
except OSError: except OSError: