<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 ocitysmap.coords import BoundingBox as OCMBoundingBox
from www.maposmatic import helpers, models, widgets
import www.settings

def get_layout_list():
    return [("plain", "Sans index"), ("index", "With index"), ("booklet", "Booklet")]

def get_stylesheet_list():
    return [("default", "Mapnik par défaut"), ("nobuildings", "Mapnik no buildings")]

def get_papersize_list():
    return [("A4", 210, 297), ("A3", 297, 420), ("A2", 420, 594), ("US Letter", 216, 279)]

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

    query = forms.CharField(min_length=1, required=True)

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 Media:
        css = { "all": ["/smedia/map_rendering_form.css"] }
        js = ["/smedia/jquery.js", "/smedia/map_rendering_form.js"]

    class Meta:
        model = models.MapRenderingJob
        fields = ('maptitle', 'administrative_city',
                  'lat_upper_left', 'lon_upper_left',
                  'lat_bottom_right', 'lon_bottom_right')

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

    mode = forms.ChoiceField(choices=MODES, initial='admin',
                             widget=forms.RadioSelect)
    layout = forms.ChoiceField(choices=(), widget=forms.RadioSelect)
    stylesheet = forms.ChoiceField(choices=(), widget=forms.RadioSelect)
    papersize = forms.ChoiceField(choices=(), widget=forms.RadioSelect)
    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,
                                     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.fields['layout'].choices = get_layout_list()
        self.fields['layout'].initial = 'index'
        self.fields['stylesheet'].choices = get_stylesheet_list()
        self.fields['stylesheet'].initial = 'default'
        self.fields['papersize'].choices = \
            [(p[0], mark_safe("%s <em class=\"papersize\">(%.1f &times; %.1f cm²)</em>" % \
                                  (p[0], p[1] / 10., p[2] / 10.))) for p in get_papersize_list()]

    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")

        if mode == 'admin':
            if city == "":
                msg = _(u"Administrative city required")
                self._errors["administrative_city"] = forms.util.ErrorList([msg])
                del cleaned_data["administrative_city"]

            # No choice, the map title is always the name of the city
            cleaned_data["maptitle"] = city

            # Make sure that bbox and admin modes are exclusive
            cleaned_data["lat_upper_left"] = None
            cleaned_data["lon_upper_left"] = None
            cleaned_data["lat_bottom_right"] = None
            cleaned_data["lon_bottom_right"] = None

            try:
                helpers.check_osm_id(cleaned_data.get("administrative_osmid"))
            except Exception,ex:
                msg = _(u"Error with osm city: %s" % ex)
                self._errors['administrative_osmid'] = forms.util.ErrorList([msg])

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

            for f in [ "lat_upper_left", "lon_upper_left",
                       "lat_bottom_right", "lon_bottom_right" ]:<commit_msg>Fix maptitle handling in MapRenderingJobForm<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 ocitysmap.coords import BoundingBox as OCMBoundingBox
from www.maposmatic import helpers, models, widgets
import www.settings

def get_layout_list():
    return [("plain", "Sans index"), ("index", "With index"), ("booklet", "Booklet")]

def get_stylesheet_list():
    return [("default", "Mapnik par défaut"), ("nobuildings", "Mapnik no buildings")]

def get_papersize_list():
    return [("A4", 210, 297), ("A3", 297, 420), ("A2", 420, 594), ("US Letter", 216, 279)]

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

    query = forms.CharField(min_length=1, required=True)

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 Media:
        css = { "all": ["/smedia/map_rendering_form.css"] }
        js = ["/smedia/jquery.js", "/smedia/map_rendering_form.js"]

    class Meta:
        model = models.MapRenderingJob
        fields = ('maptitle', 'administrative_city',
                  'lat_upper_left', 'lon_upper_left',
                  'lat_bottom_right', 'lon_bottom_right')

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

    mode = forms.ChoiceField(choices=MODES, initial='admin',
                             widget=forms.RadioSelect)
    layout = forms.ChoiceField(choices=(), widget=forms.RadioSelect)
    stylesheet = forms.ChoiceField(choices=(), widget=forms.RadioSelect)
    papersize = forms.ChoiceField(choices=(), widget=forms.RadioSelect)
    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,
                                     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.fields['layout'].choices = get_layout_list()
        self.fields['layout'].initial = 'index'
        self.fields['stylesheet'].choices = get_stylesheet_list()
        self.fields['stylesheet'].initial = 'default'
        self.fields['papersize'].choices = \
            [(p[0], mark_safe("%s <em class=\"papersize\">(%.1f &times; %.1f cm²)</em>" % \
                                  (p[0], p[1] / 10., p[2] / 10.))) for p in get_papersize_list()]

    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")

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

        if mode == 'admin':
            if city == "":
                msg = _(u"Administrative city required")
                self._errors["administrative_city"] = forms.util.ErrorList([msg])
                del cleaned_data["administrative_city"]

            # Make sure that bbox and admin modes are exclusive
            cleaned_data["lat_upper_left"] = None
            cleaned_data["lon_upper_left"] = None
            cleaned_data["lat_bottom_right"] = None
            cleaned_data["lon_bottom_right"] = None

            try:
                helpers.check_osm_id(cleaned_data.get("administrative_osmid"))
            except Exception,ex:
                msg = _(u"Error with osm city: %s" % ex)
                self._errors['administrative_osmid'] = forms.util.ErrorList([msg])

        elif mode == 'bbox':
            for f in [ "lat_upper_left", "lon_upper_left",
                       "lat_bottom_right", "lon_bottom_right" ]:
{'fraction_non_alphanumeric': 0.11818181818181818, 'fraction_numerical': 0.01332133213321332, 'mean_word_length': 2.654934210526316, 'pattern_counts': {'":': 4, '<': 23, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 8, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '737141', 'n_tokens_mistral': 3292, 'n_tokens_neox': 3111, 'n_words': 886}