Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions course/check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# -*- coding: utf-8 -*-

from __future__ import division

__copyright__ = "Copyright (C) 2016 Dong Zhuang, Andreas Kloeckner"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from django.core.checks import register, Tags as DjangoTags
from django.conf import settings

from course.latex.utils import get_all_indirect_subclasses
from course.latex.converter import CommandBase


class Tags(DjangoTags):
relate_course_tag = 'relate_course_tag'


@register(Tags.relate_course_tag, deploy=True)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this need to be duplicated?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not saying it's wrong, in fact I don't know--the duplication just looks fishy.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right. I'll correct it.

def latex2image_bin_check(app_configs, **kwargs):
"""
Check if all tex compiler and image converter
are correctly configured, if latex utility is
enabled.
"""
if not getattr(settings, "RELATE_LATEX_TO_IMAGE_ENABLED", False):
return []
klass = get_all_indirect_subclasses(CommandBase)
instance_list = [cls() for cls in klass]
errors = []
for instance in instance_list:
error = instance.check()
if error:
errors.append(error)
return errors
43 changes: 41 additions & 2 deletions course/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -855,6 +855,7 @@ def expand_markup(
repo, # type: Repo_ish
commit_sha, # type: bytes
text, # type: Text
validate_only=False, # type: bool
use_jinja=True, # type: bool
jinja_env={}, # type: Dict
):
Expand All @@ -870,8 +871,45 @@ def expand_markup(
env = Environment(
loader=GitTemplateLoader(repo, commit_sha),
undefined=StrictUndefined)

template = env.from_string(text)
text = template.render(**jinja_env)
kwargs = {}
if jinja_env:
kwargs.update(jinja_env)

# {{{ tex2img

def latex_not_enabled_warning(caller, *args, **kwargs):
return (
"<div class='alert alert-danger'>%s</div>" %
("RELATE_LATEX_TO_IMAGE_ENABLED is set to False, "
"no image will be generated."))

def jinja_tex_to_img_tag(caller, *args, **kwargs):
try:
from course.latex import tex_to_img_tag
return tex_to_img_tag(caller(), *args, **kwargs)
except Exception as e:
raise ValueError(
u"<pre><div class='alert alert-danger'>"
u"Error: %s: %s</div></pre>"
% (type(e).__name__, str(e)))

latex2image_enabled = getattr(
settings, "RELATE_LATEX_TO_IMAGE_ENABLED", False)

if latex2image_enabled:
env.globals["latex"] = jinja_tex_to_img_tag
else:
if not validate_only:
env.globals["latex"] = latex_not_enabled_warning
else:
raise ImproperlyConfigured(
_("RELATE_LATEX_TO_IMAGE_ENABLED is set to False, "
"no image will be generated."))
# }}}

text = template.render(**kwargs)

# }}}

Expand Down Expand Up @@ -912,7 +950,8 @@ def markup_to_html(
cache_key = None

text = expand_markup(
course, repo, commit_sha, text, use_jinja=use_jinja, jinja_env=jinja_env)
course, repo, commit_sha, text, validate_only=validate_only,
use_jinja=use_jinja, jinja_env=jinja_env)

if reverse_func is None:
from django.urls import reverse
Expand Down
126 changes: 126 additions & 0 deletions course/latex/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# -*- coding: utf-8 -*-

from __future__ import division

__copyright__ = "Copyright (C) 2016 Dong Zhuang, Andreas Kloeckner"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import six
import re

from django.utils.translation import ugettext as _

from course.latex.converter import get_tex2img_class
from course.latex.latex import TexDoc
from course.latex.utils import (
replace_latex_space_seperator, strip_spaces)

TIKZ_PGF_RE = re.compile(r"\\begin\{(?:tikzpicture|pgfpicture)\}")
DEFAULT_IMG_HTML_CLASS = "img-responsive"

# {{{ mypy

if False:
from typing import Text, Any, Optional # noqa

# }}}


def tex_to_img_tag(tex_source, *args, **kwargs):
# type: (Text, *Any, **Any) -> Optional[Text]
'''Convert LaTex to IMG tag'''

compiler = kwargs.get("compiler", None)
if not compiler:
raise ValueError(_("'compiler' must be specified."))

image_format = kwargs.get("image_format", "")
if not image_format:
raise ValueError(_("'image_format' must be specified."))

tex_filename = kwargs.get("tex_filename", None)
tex_preamble = kwargs.get("tex_preamble", "")
tex_preamble_extra = kwargs.get("tex_preamble_extra", "")

force_regenerate = kwargs.get("force_regenerate", False)
html_class_extra = kwargs.get("html_class_extra", "")
empty_pagestyle = kwargs.get("empty_pagestyle", True)
alt = kwargs.get("alt", None)

# remove spaces added to latex code in jinja template.
tex_source = replace_latex_space_seperator(
strip_spaces(tex_source, allow_single_empty_line=True))
tex_preamble = replace_latex_space_seperator(
strip_spaces(tex_preamble, allow_single_empty_line=True))
tex_preamble_extra = replace_latex_space_seperator(
strip_spaces(tex_preamble_extra,
allow_single_empty_line=True))

if html_class_extra:
if isinstance(html_class_extra, list):
html_class_extra = " ".join(html_class_extra)
elif not isinstance(html_class_extra, six.string_types):
raise ValueError(
_('"html_class_extra" must be a string or a list'))
html_class = "%s %s" % (DEFAULT_IMG_HTML_CLASS, html_class_extra)
else:
html_class = DEFAULT_IMG_HTML_CLASS

texdoc = TexDoc(
tex_source, preamble=tex_preamble,
preamble_extra=tex_preamble_extra, empty_pagestyle=empty_pagestyle)

# empty document
if not texdoc.document.strip():
return ""

if (compiler == "latex"
and image_format == "png"
and
re.search(TIKZ_PGF_RE, tex_source)):
image_format = "svg"

assert isinstance(compiler, six.text_type)

tex2img_class = get_tex2img_class(compiler, image_format) # type: ignore

if not alt:
alt = texdoc.document

if alt:
alt = "alt='%s'" % alt.strip().replace("\n", "")

latex2img = tex2img_class(
tex_source=texdoc.as_latex(),
tex_filename=tex_filename,
)

return (
"<img src='%(src)s' "
"class='%(html_class)s' %(alt)s>"
% {
"src": latex2img.get_data_uri_cached(force_regenerate),
"html_class": html_class,
"alt": alt,
})

# vim: foldmethod=marker
Loading