<commit_before># coding: utf-8

# maposmatic, the web front-end of the MapOSMatic city map generation system
# Copyright (C) 2009  <NAME>
# Copyright (C) 2009  <NAME>
# Copyright (C) 2009  <NAME>
# Copyright (C) 2009  <NAME>
# Copyright (C) 2009  <NAME>
# Copyright (C) 2009  <NAME>
# Copyright (C) 2009  <NAME>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Forms for MapOSMatic

from django import forms
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.forms.utils import ErrorList
import time

import ocitysmap
from www.maposmatic import models, widgets
import www.settings

class MapSearchForm(forms.Form):
    """
    The map search form, allowing search through the rendered maps.
    """

    query = forms.CharField(min_length=1, required=True,
                widget=forms.TextInput(attrs=
                    {'placeholder': _('Search for a map'),
                     'class': 'span2'}))

class MapRenderingJobForm(forms.ModelForm):
    """
    The main map rendering form, displayed on the 'Create Map' page. It's a
    ModelForm based on the MapRenderingJob model.
    """
    class Meta:
        model = models.MapRenderingJob
        fields = ('layout', 'stylesheet', 'overlay',
                  'maptitle', 'administrative_city',
                  'lat_upper_left', 'lon_upper_left',
                  'lat_bottom_right', 'lon_bottom_right',
                  'track', 'umap', 'submittermail')

    MODES = (('admin', _('Administrative boundary')),
             ('bbox', _('Bounding box')))

    ORIENTATION = (('portrait', _('Portrait')),
                   ('landscape', _('Landscape')))

    mode = forms.ChoiceField(choices=MODES, initial='admin',
                             widget=forms.RadioSelect)
    layout = forms.ChoiceField(choices=(), widget=forms.RadioSelect(attrs= { 'onclick' : '$("#layout-preview").attr("src","/media/img/layout/"+this.value+".png");'}))
    stylesheet = forms.ChoiceField(choices=(), widget=forms.RadioSelect(attrs= { 'onclick' : '$("#style-preview").attr("src","/media/img/style/"+this.value+".jpg");'}))
    overlay = forms.MultipleChoiceField(choices=(), widget=forms.CheckboxSelectMultiple(attrs= { 'onclick' : '$("#overlay-preview").attr("src","/media/img/overlay/"+this.value+".jpg");'}), required=False)
    papersize = forms.ChoiceField(choices=(), widget=forms.RadioSelect)
    paperorientation = forms.ChoiceField(choices=ORIENTATION,
                                         widget=forms.RadioSelect)
    paper_width_mm = forms.IntegerField(widget=forms.HiddenInput)
    paper_height_mm = forms.IntegerField(widget=forms.HiddenInput)
    maptitle = forms.CharField(max_length=256, required=False)
    bbox = widgets.AreaField(label=_("Area"),
                             fields=(forms.FloatField(), forms.FloatField(),
                                     forms.FloatField(), forms.FloatField()))
    map_language = forms.ChoiceField(choices=www.settings.MAP_LANGUAGES_LIST,
                                     widget=forms.Select(
                                        attrs={'style': 'min-width: 200px'}))
    administrative_osmid = forms.IntegerField(widget=forms.HiddenInput,
                                              required=False)

    def __init__(self, *args, **kwargs):
        super(MapRenderingJobForm, self).__init__(*args, **kwargs)

        self._ocitysmap = ocitysmap.OCitySMap(www.settings.OCITYSMAP_CFG_PATH)

        layout_renderers = self._ocitysmap.get_all_renderers()
        stylesheets = self._ocitysmap.get_all_style_configurations()
        overlays = self._ocitysmap.get_all_overlay_configurations()

        self.fields['layout'].choices = []
        # TODO move descriptions to ocitysmap side
        for r in layout_renderers:
            if r.name == 'plain':
                description = _(u"Full-page layout without street index")
            elif r.name == 'single_page_index_side':
                description = _(u"Full-page layout with the street index on the side")
            elif r.name == 'single_page_index_bottom':
                description = _(u"Full-page layout with the street index at the bottom")
            elif r.name == 'multi_page':
                description = _(u"Multi-page layout")
            else:
                description = mark_safe(_(u"The %(layout_name)s layout") % {'layout_name':r.name})
            self.fields['layout'].choices.append((r.name, description))

        if not self.fields['layout'].initial:
            self.fields['layout'].initial = layout_renderers[0].name

        self.fields['stylesheet'].choices = []
        # TODO fetch descriptions from style config file
        for s in stylesheets:
            if s.description is not None:
                description = mark_safe(s.description)
            elif s.name == "Default":
                description = _("The default OpenStreetMap.org style")
            elif s.name == "MapQuestEu":
                description = _("The european MapQuest style")
            elif s.name == "MapQuestUs":
                description = _("The US MapQuest style")
            elif s.name == "MapQuestUk":
                description = _("The UK MapQuest style")
            elif s.name == "Printable":
                description = _("A MapOSMatic-specific stylesheet suitable for printing")
            else:
                description = mark_safe(_("The <i>%(stylesheet_name)s</i> stylesheet") % {'stylesheet_name':s.name})
            self.fields['stylesheet'].choices.append((s.name, description))

        if not self.fields['stylesheet'].initial:
            self.fields['stylesheet'].initial = stylesheets[0].name

        self.fields['overlay'].choices = []
        for s in overlays:
            if s.description is not None:
                description = mark_safe(s.description)
            else:
                description = mark_safe(_("The <i>%(stylesheet_name)s</i> overlay") % {'stylesheet_name':s.name})
            self.fields['overlay'].choices.append((s.name, description))

        if not self.fields['overlay'].initial:
            self.fields['overlay'].initial = ''

        def _build_papersize_description(p):
            if p[0] == "Best fit":
                return mark_safe(_("Best fit <em class=\"papersize\"></em>"))
            else:
                return mark_safe("%s <em class=\"papersize\">"
                                 "(%.1f &times; %.1f cm²)</em>"
                                 % (p[0], p[1] / 10., p[2] / 10.))

        self.fields['papersize'].choices = [
                (p[0], _build_papersize_description(p))
                for p in self._ocitysmap.get_all_paper_sizes()]

    def clean(self):
        """Cleanup function for the map query form. Different checks are
        required depending on the selected mode (by admininstrative city, or by
        bounding box).

        Returns the cleaned_data array.
        """

        cleaned_data = self.cleaned_data

        mode = cleaned_data.get("mode")
        city = cleaned_data.get("administrative_city")
        title = cleaned_data.get("maptitle")
        layout = cleaned_data.get("layout")
        stylesheet = cleaned_data.get("stylesheet")
        overlay_array = []
        for overlay in cleaned_data.get("overlay"):
            overlay_array.append(overlay)
        overlay = ",".join(overlay_array)

        if cleaned_data.get("paperorientation") == 'landscape':
            cleaned_data["paper_width_mm"], cleaned_data["paper_height_mm"] = \
                cleaned_data.get("paper_height_mm"), cleaned_data.get("paper_width_mm")

        if title == '':
            msg = _(u"Map title required")
            self._errors["maptitle"] = ErrorList([msg])
            del cleaned_data["maptitle"]

        if layout == '':
            msg = _(u"Layout required")
            self._errors["layout"] = ErrorList([msg])
            del cleaned_data["layout"]

        if stylesheet == '':
            msg = _(u"Stylesheet required")
            self._errors["stylesheet"] = ErrorList([msg])<commit_msg>allow empty map titles<commit_after># coding: utf-8

# maposmatic, the web front-end of the MapOSMatic city map generation system
# Copyright (C) 2009  <NAME>
# Copyright (C) 2009  <NAME>
# Copyright (C) 2009  <NAME>
# Copyright (C) 2009  <NAME>
# Copyright (C) 2009  <NAME>
# Copyright (C) 2009  <NAME>
# Copyright (C) 2009  <NAME>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Forms for MapOSMatic

from django import forms
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.forms.utils import ErrorList
import time

import ocitysmap
from www.maposmatic import models, widgets
import www.settings

class MapSearchForm(forms.Form):
    """
    The map search form, allowing search through the rendered maps.
    """

    query = forms.CharField(min_length=1, required=True,
                widget=forms.TextInput(attrs=
                    {'placeholder': _('Search for a map'),
                     'class': 'span2'}))

class MapRenderingJobForm(forms.ModelForm):
    """
    The main map rendering form, displayed on the 'Create Map' page. It's a
    ModelForm based on the MapRenderingJob model.
    """
    class Meta:
        model = models.MapRenderingJob
        fields = ('layout', 'stylesheet', 'overlay',
                  'maptitle', 'administrative_city',
                  'lat_upper_left', 'lon_upper_left',
                  'lat_bottom_right', 'lon_bottom_right',
                  'track', 'umap', 'submittermail')

    MODES = (('admin', _('Administrative boundary')),
             ('bbox', _('Bounding box')))

    ORIENTATION = (('portrait', _('Portrait')),
                   ('landscape', _('Landscape')))

    mode = forms.ChoiceField(choices=MODES, initial='admin',
                             widget=forms.RadioSelect)
    layout = forms.ChoiceField(choices=(), widget=forms.RadioSelect(attrs= { 'onclick' : '$("#layout-preview").attr("src","/media/img/layout/"+this.value+".png");'}))
    stylesheet = forms.ChoiceField(choices=(), widget=forms.RadioSelect(attrs= { 'onclick' : '$("#style-preview").attr("src","/media/img/style/"+this.value+".jpg");'}))
    overlay = forms.MultipleChoiceField(choices=(), widget=forms.CheckboxSelectMultiple(attrs= { 'onclick' : '$("#overlay-preview").attr("src","/media/img/overlay/"+this.value+".jpg");'}), required=False)
    papersize = forms.ChoiceField(choices=(), widget=forms.RadioSelect)
    paperorientation = forms.ChoiceField(choices=ORIENTATION,
                                         widget=forms.RadioSelect)
    paper_width_mm = forms.IntegerField(widget=forms.HiddenInput)
    paper_height_mm = forms.IntegerField(widget=forms.HiddenInput)
    maptitle = forms.CharField(max_length=256, required=False)
    bbox = widgets.AreaField(label=_("Area"),
                             fields=(forms.FloatField(), forms.FloatField(),
                                     forms.FloatField(), forms.FloatField()))
    map_language = forms.ChoiceField(choices=www.settings.MAP_LANGUAGES_LIST,
                                     widget=forms.Select(
                                        attrs={'style': 'min-width: 200px'}))
    administrative_osmid = forms.IntegerField(widget=forms.HiddenInput,
                                              required=False)

    def __init__(self, *args, **kwargs):
        super(MapRenderingJobForm, self).__init__(*args, **kwargs)

        self._ocitysmap = ocitysmap.OCitySMap(www.settings.OCITYSMAP_CFG_PATH)

        layout_renderers = self._ocitysmap.get_all_renderers()
        stylesheets = self._ocitysmap.get_all_style_configurations()
        overlays = self._ocitysmap.get_all_overlay_configurations()

        self.fields['layout'].choices = []
        # TODO move descriptions to ocitysmap side
        for r in layout_renderers:
            if r.name == 'plain':
                description = _(u"Full-page layout without street index")
            elif r.name == 'single_page_index_side':
                description = _(u"Full-page layout with the street index on the side")
            elif r.name == 'single_page_index_bottom':
                description = _(u"Full-page layout with the street index at the bottom")
            elif r.name == 'multi_page':
                description = _(u"Multi-page layout")
            else:
                description = mark_safe(_(u"The %(layout_name)s layout") % {'layout_name':r.name})
            self.fields['layout'].choices.append((r.name, description))

        if not self.fields['layout'].initial:
            self.fields['layout'].initial = layout_renderers[0].name

        self.fields['stylesheet'].choices = []
        # TODO fetch descriptions from style config file
        for s in stylesheets:
            if s.description is not None:
                description = mark_safe(s.description)
            elif s.name == "Default":
                description = _("The default OpenStreetMap.org style")
            elif s.name == "MapQuestEu":
                description = _("The european MapQuest style")
            elif s.name == "MapQuestUs":
                description = _("The US MapQuest style")
            elif s.name == "MapQuestUk":
                description = _("The UK MapQuest style")
            elif s.name == "Printable":
                description = _("A MapOSMatic-specific stylesheet suitable for printing")
            else:
                description = mark_safe(_("The <i>%(stylesheet_name)s</i> stylesheet") % {'stylesheet_name':s.name})
            self.fields['stylesheet'].choices.append((s.name, description))

        if not self.fields['stylesheet'].initial:
            self.fields['stylesheet'].initial = stylesheets[0].name

        self.fields['overlay'].choices = []
        for s in overlays:
            if s.description is not None:
                description = mark_safe(s.description)
            else:
                description = mark_safe(_("The <i>%(stylesheet_name)s</i> overlay") % {'stylesheet_name':s.name})
            self.fields['overlay'].choices.append((s.name, description))

        if not self.fields['overlay'].initial:
            self.fields['overlay'].initial = ''

        def _build_papersize_description(p):
            if p[0] == "Best fit":
                return mark_safe(_("Best fit <em class=\"papersize\"></em>"))
            else:
                return mark_safe("%s <em class=\"papersize\">"
                                 "(%.1f &times; %.1f cm²)</em>"
                                 % (p[0], p[1] / 10., p[2] / 10.))

        self.fields['papersize'].choices = [
                (p[0], _build_papersize_description(p))
                for p in self._ocitysmap.get_all_paper_sizes()]

    def clean(self):
        """Cleanup function for the map query form. Different checks are
        required depending on the selected mode (by admininstrative city, or by
        bounding box).

        Returns the cleaned_data array.
        """

        cleaned_data = self.cleaned_data

        mode = cleaned_data.get("mode")
        city = cleaned_data.get("administrative_city")
        title = cleaned_data.get("maptitle")
        layout = cleaned_data.get("layout")
        stylesheet = cleaned_data.get("stylesheet")
        overlay_array = []
        for overlay in cleaned_data.get("overlay"):
            overlay_array.append(overlay)
        overlay = ",".join(overlay_array)

        if cleaned_data.get("paperorientation") == 'landscape':
            cleaned_data["paper_width_mm"], cleaned_data["paper_height_mm"] = \
                cleaned_data.get("paper_height_mm"), cleaned_data.get("paper_width_mm")

        if layout == '':
            msg = _(u"Layout required")
            self._errors["layout"] = ErrorList([msg])
            del cleaned_data["layout"]

        if stylesheet == '':
            msg = _(u"Stylesheet required")
            self._errors["stylesheet"] = ErrorList([msg])
{'fraction_non_alphanumeric': 0.12273361227336123, 'fraction_numerical': 0.005927475592747559, 'mean_word_length': 2.4695564516129034, 'pattern_counts': {'":': 12, '<': 35, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 10, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1272949', 'n_tokens_mistral': 4826, 'n_tokens_neox': 4618, 'n_words': 1162}