예제 #1
0
    def cleanup(self, request):
        """ remove all unused colors """
        from pylucid_project.apps.pylucid.models import Design, Color

        existing_colors = set()
        designs = Design.objects.all().filter(colorscheme=self)
        for design in designs:
            headfiles = design.headfiles.all().filter(render=True)
            for headfile in headfiles:
                css_names = get_new_css_names(existing_colors=(), content=headfile.content)
                existing_colors.update(set(css_names))

        messages.info(request,
            _("existing colors: %s") % ", ".join(['"%s"' % c for c in existing_colors])
        )

        queryset = Color.objects.all().filter(colorscheme=self).exclude(name__in=existing_colors)
        color_names = queryset.values_list('name', flat=True)
        if not color_names:
            messages.info(request, _("No unused colors found, ok."))
        else:
            messages.info(request, _("remove %(count)i colors: %(names)s") % {
                "count": len(color_names),
                "names": ", ".join(['"%s"' % n for n in color_names]),
            })
        queryset.delete()
예제 #2
0
    def cleanup(self, request):
        """ remove all unused colors """
        from pylucid_project.apps.pylucid.models import Design, Color

        existing_colors = set()
        designs = Design.objects.all().filter(colorscheme=self)
        for design in designs:
            headfiles = design.headfiles.all().filter(render=True)
            for headfile in headfiles:
                css_names = get_new_css_names(existing_colors=(),
                                              content=headfile.content)
                existing_colors.update(set(css_names))

        messages.info(
            request,
            _("existing colors: %s") %
            ", ".join(['"%s"' % c for c in existing_colors]))

        queryset = Color.objects.all().filter(colorscheme=self).exclude(
            name__in=existing_colors)
        color_names = queryset.values_list('name', flat=True)
        if not color_names:
            messages.info(request, _("No unused colors found, ok."))
        else:
            messages.info(
                request,
                _("remove %(count)i colors: %(names)s") % {
                    "count": len(color_names),
                    "names": ", ".join(['"%s"' % n for n in color_names]),
                })
        queryset.delete()
예제 #3
0
class EditableHtmlHeadFile(UpdateInfoBaseModel):
    """
    Storage for editable static text files, e.g.: stylesheet / javascript.

    inherited attributes from UpdateInfoBaseModel:
        createtime     -> datetime of creation
        lastupdatetime -> datetime of the last change
        createby       -> ForeignKey to user who creaded this entry
        lastupdateby   -> ForeignKey to user who has edited this entry
    """
    objects = EditableHtmlHeadFileManager()

    filepath = models.CharField(max_length=255, unique=True)
    mimetype = models.CharField(max_length=64,
        help_text=_("MIME type for this file. (Leave empty for guess by filename)")
    )
    html_attributes = models.CharField(max_length=256, null=False, blank=True,
        help_text=_('Additional html tag attributes (CSS example: media="screen")')
    )
    render = models.BooleanField(default=False,
        help_text=_("Are there CSS ColorScheme entries in the content?")
    )
    description = models.TextField(null=True, blank=True)
    content = models.TextField()

    def get_filename(self):
        """ returns only the filename """
        return os.path.split(self.filepath)[1]

    def get_file_extension(self):
        """ return the file extension, e.g.: '.css' or '.js' """
        return os.path.splitext(self.filepath)[1].lower()

    def get_type(self):
        return self.get_file_extension().lstrip(".")

    def get_rendered(self, colorscheme):
        color_dict = colorscheme.get_color_dict()

        for name, value in color_dict.iteritems():
            color_dict[name] = "#%s" % value

        rendered_content = render.render_string_template(self.content, color_dict)
        return rendered_content

    def get_inline_html(self, colorscheme=None):
        if colorscheme:
            rendered_content = self.get_rendered(colorscheme)
        else:
            if self.render == True:
                raise AssertionError("This file should be rendered, but no colorscheme given!")
            rendered_content = self.content

        file_type = self.get_type()
        template = "pylucid/headfile_inline_%s.html" % file_type

        context = {
            "instance": self,
            "colorscheme": colorscheme,
            "rendered_content": rendered_content,
        }
        inline_html = render_to_string(template, context)
        return inline_html

    def iter_colorschemes(self, skip_colorschemes=None):
        """ TODO: Optimizes this """
        if skip_colorschemes is None:
            skip_colorschemes = []

        designs = Design.objects.all().filter()
        for design in designs:
            colorscheme = design.colorscheme
            if colorscheme in skip_colorschemes:
                continue
            headfiles = design.headfiles.filter(pk=self.pk)
            for headfile in headfiles:
                if headfile == self:
                    skip_colorschemes.append(colorscheme)
                    yield colorscheme

    def clean_fields(self, exclude):
        message_dict = {}

        if not self.mimetype and self.filepath:
            # Set mimetype by guess type from filepath
            self.mimetype = self.auto_mimetype()

        if "mimetype" not in exclude:
            all_mimetypes = set(mimetypes.types_map.values())
            if self.mimetype not in all_mimetypes:
                failsafe_message(
                    "Warning: Mimetype %(mimetype)r for headfile %(headfile)r unknown!" % {
                        "mimetype": self.mimetype, "headfile": self.filepath
                    }
                )

        if "filepath" not in exclude:
            try:
                # "validate" the filepath with the url re. 
                reverse('PyLucid-send_head_file', kwargs={"filepath": self.filepath})
            except NoReverseMatch, err:
                message_dict["filepath"] = [_(
                    "filepath %(filepath)r contains invalid characters!"
                    " (Original error: %(err)s)" % {
                        "filepath": self.filepath,
                        "err": err,
                    }
                )]

        if "render" not in exclude and self.render:
            has_colorscheme = False
            designs = Design.objects.all().exclude(colorscheme=None)
            for design in designs:
                its_me = design.headfiles.filter(pk=self.pk).count()
                if its_me:
                    has_colorscheme = True
                    break
            if not has_colorscheme:
                message_dict["render"] = [_("This headfile can't be rendered, because it's not used in a design witch has a colorscheme!")]

        if "content" not in exclude and self.render:
            for colorscheme in self.iter_colorschemes():
                existing_colors = colorscheme.get_color_names()
                css_names = get_new_css_names(existing_colors, self.content)
                if css_names:
                    if "content" not in message_dict:
                        message_dict["content"] = []
                    message_dict["content"].append(
                        _("Theses CSS color names %(css_names)s are unknown in %(colorscheme)s") % {
                            "colorscheme": colorscheme,
                            "css_names": ", ".join(["'%s'" % css_name for css_name in css_names])
                        }
                    )

        if message_dict:
            raise ValidationError(message_dict)
예제 #4
0
        if "render" not in exclude and self.render:
            has_colorscheme = False
            designs = Design.objects.all().exclude(colorscheme=None)
            for design in designs:
                its_me = design.headfiles.filter(pk=self.pk).count()
                if its_me:
                    has_colorscheme = True
                    break
            if not has_colorscheme:
                message_dict["render"] = [_("This headfile can't be rendered, because it's not used in a design witch has a colorscheme!")]

        if "content" not in exclude and self.render:
            for colorscheme in self.iter_colorschemes():
                existing_colors = colorscheme.get_color_names()
                css_names = get_new_css_names(existing_colors, self.content)
                if css_names:
                    if "content" not in message_dict:
                        message_dict["content"] = []
                    message_dict["content"].append(
                        _("Theses CSS color names %(css_names)s are unknown in %(colorscheme)s") % {
                            "colorscheme": colorscheme,
                            "css_names": ", ".join(["'%s'" % css_name for css_name in css_names])
                        }
                    )

        if message_dict:
            raise ValidationError(message_dict)

    def auto_mimetype(self):
        """ returns the mimetype for the current filename """