-
-
Notifications
You must be signed in to change notification settings - Fork 965
/
forms.py
2859 lines (2486 loc) · 95.3 KB
/
forms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright © Michal Čihař <michal@weblate.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
import copy
import json
import re
from datetime import date, datetime, timedelta
from secrets import token_hex
from crispy_forms.bootstrap import InlineCheckboxes, InlineRadios, Tab, TabHolder
from crispy_forms.helper import FormHelper
from crispy_forms.layout import HTML, Div, Field, Fieldset, Layout
from django import forms
from django.conf import settings
from django.core.exceptions import NON_FIELD_ERRORS, PermissionDenied, ValidationError
from django.core.validators import FileExtensionValidator, validate_slug
from django.db.models import Q
from django.forms import model_to_dict
from django.forms.utils import from_current_timezone
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils import timezone
from django.utils.html import format_html, format_html_join
from django.utils.http import urlencode
from django.utils.safestring import mark_safe
from django.utils.text import slugify
from django.utils.translation import gettext, gettext_lazy
from translation_finder import DiscoveryResult, discover
from weblate.auth.models import Group, User
from weblate.checks.flags import Flags
from weblate.checks.models import CHECKS
from weblate.checks.utils import highlight_string
from weblate.formats.models import EXPORTERS, FILE_FORMATS
from weblate.glossary.forms import GlossaryAddMixin
from weblate.lang.data import BASIC_LANGUAGES
from weblate.lang.models import Language
from weblate.machinery.models import MACHINERY
from weblate.trans.backups import ProjectBackup
from weblate.trans.defines import (
BRANCH_LENGTH,
COMPONENT_NAME_LENGTH,
FILENAME_LENGTH,
REPO_LENGTH,
)
from weblate.trans.filter import FILTERS, get_filter_choice
from weblate.trans.models import (
Announcement,
Category,
Change,
Component,
Label,
Project,
Unit,
WorkflowSetting,
)
from weblate.trans.specialchars import RTL_CHARS_DATA, get_special_chars
from weblate.trans.util import check_upload_method_permissions, is_repo_link
from weblate.trans.validators import validate_check_flags
from weblate.utils.antispam import is_spam
from weblate.utils.forms import (
CachedModelMultipleChoiceField,
ColorWidget,
ContextDiv,
EmailField,
QueryField,
SearchField,
SortedSelect,
SortedSelectMultiple,
UserField,
UsernameField,
)
from weblate.utils.hash import checksum_to_hash, hash_to_checksum
from weblate.utils.state import (
STATE_APPROVED,
STATE_EMPTY,
STATE_FUZZY,
STATE_READONLY,
STATE_TRANSLATED,
StringState,
get_state_label,
)
from weblate.utils.validators import validate_file_extension
from weblate.vcs.models import VCS_REGISTRY
BUTTON_TEMPLATE = """
<button class="btn btn-default {0}" title="{1}" {2}>{3}</button>
"""
RADIO_TEMPLATE = """
<label class="btn btn-default {0}" title="{1}">
<input type="radio" name="{2}" value="{3}" {4}/>
{5}
</label>
"""
GROUP_TEMPLATE = """
<div class="btn-group btn-group-xs" {0}>{1}</div>
"""
TOOLBAR_TEMPLATE = """
<div class="btn-toolbar pull-right flip editor-toolbar">{0}</div>
"""
class MarkdownTextarea(forms.Textarea):
def __init__(self, **kwargs):
kwargs["attrs"] = {
"dir": "auto",
"class": "markdown-editor highlight-editor",
"data-mode": "markdown",
}
super().__init__(**kwargs)
class WeblateDateInput(forms.DateInput):
input_type = "date"
class WeblateDateField(forms.DateField):
def __init__(self, **kwargs):
if "widget" not in kwargs:
kwargs["widget"] = WeblateDateInput
super().__init__(**kwargs)
def to_python(self, value):
"""Produce timezone-aware datetime with 00:00:00 as time."""
value = super().to_python(value)
if isinstance(value, date):
return from_current_timezone(
datetime(value.year, value.month, value.day, 0, 0, 0) # noqa: DTZ001
)
return value
class ChecksumField(forms.CharField):
"""Field for handling checksum IDs for translation."""
def __init__(self, *args, **kwargs):
kwargs["widget"] = forms.HiddenInput
super().__init__(*args, **kwargs)
def clean(self, value):
super().clean(value)
if not value:
return None
try:
return checksum_to_hash(value)
except ValueError:
raise ValidationError(gettext("Invalid checksum specified!"))
class FlagField(forms.CharField):
default_validators = [validate_check_flags]
class PluralTextarea(forms.Textarea):
"""Text-area extension which possibly handles plurals."""
def __init__(self, *args, **kwargs):
self.profile = None
super().__init__(*args, **kwargs)
def get_rtl_toolbar(self, fieldname):
# Special chars
chars = format_html_join(
"\n",
BUTTON_TEMPLATE,
(
(
"specialchar",
name,
format_html(
'data-value="{}"',
mark_safe( # noqa: S308
value.encode("ascii", "xmlcharrefreplace").decode("ascii")
),
),
char,
)
for name, char, value in RTL_CHARS_DATA
),
)
groups = format_html_join(
"\n",
GROUP_TEMPLATE,
[("", chars)], # Only one group.
)
return format_html(TOOLBAR_TEMPLATE, groups)
def get_rtl_toggle(self, language, fieldname):
if language.direction != "rtl":
return ""
# RTL/LTR switch
rtl_name = f"rtl-{fieldname}"
rtl_switch = format_html_join(
"\n",
RADIO_TEMPLATE,
[
(
"direction-toggle active",
gettext("Toggle text direction"),
rtl_name,
"rtl",
format_html('checked="checked"'),
"RTL",
),
(
"direction-toggle",
gettext("Toggle text direction"),
rtl_name,
"ltr",
format_html(""),
"LTR",
),
],
)
groups = format_html_join(
"\n",
GROUP_TEMPLATE,
[(format_html('data-toggle="buttons"'), rtl_switch)], # Only one group.
)
return format_html(TOOLBAR_TEMPLATE, groups)
def get_toolbar(self, language, fieldname, unit, idx, source):
"""Return toolbar HTML code."""
profile = self.profile
# Special chars
chars = format_html_join(
"\n",
BUTTON_TEMPLATE,
(
(
"specialchar",
name,
format_html(
'data-value="{}"',
mark_safe( # noqa: S308
value.encode("ascii", "xmlcharrefreplace").decode("ascii")
),
),
char,
)
for name, char, value in get_special_chars(
language, profile.special_chars, unit.source
)
),
)
groups = format_html_join(
"\n",
GROUP_TEMPLATE,
[("", chars)], # Only one group.
)
result = format_html(TOOLBAR_TEMPLATE, groups)
if language.direction == "rtl":
result = format_html("{}{}", self.get_rtl_toolbar(fieldname), result)
return result
def render(self, name, value, attrs=None, renderer=None, **kwargs):
"""Render all textareas with correct plural labels."""
unit = value
values = unit.get_target_plurals()
translation = unit.translation
lang_label = lang = translation.language
if "zen-mode" in self.attrs:
lang_label = format_html(
'<a class="language" href="{}">{}</a>',
unit.get_absolute_url(),
lang_label,
)
plural = translation.plural
tabindex = self.attrs["tabindex"]
plurals = unit.get_source_plurals()
placeables = set()
for text in plurals:
placeables.update(hl[2] for hl in highlight_string(text, unit))
placeables = list(placeables)
show_plural_labels = len(values) > 1 and not translation.component.is_multivalue
# Need to add extra class
attrs["class"] = "translation-editor form-control highlight-editor"
attrs["tabindex"] = tabindex
attrs["lang"] = lang.code
attrs["dir"] = lang.direction
attrs["rows"] = 3
attrs["data-max"] = unit.get_max_length()
attrs["data-mode"] = unit.edit_mode
attrs["data-placeables"] = "|".join(re.escape(pl) for pl in placeables if pl)
if unit.readonly:
attrs["readonly"] = 1
# Okay we have more strings
ret = []
base_id = f"id_{unit.checksum}"
for idx, val in enumerate(values):
# Generate ID
fieldname = f"{name}_{idx}"
fieldid = f"{base_id}_{idx}"
attrs["id"] = fieldid
attrs["tabindex"] = tabindex + idx
source = plurals[1] if idx and len(plurals) > 1 else plurals[0]
# Render textare
textarea = super().render(fieldname, val, attrs, renderer, **kwargs)
# Label for plural
label = lang_label
if show_plural_labels:
label = format_html("{}, {}", label, plural.get_plural_label(idx))
elif translation.component.is_multivalue and idx > 0:
label = format_html("{}, {}", label, gettext("Alternative translation"))
ret.append(
render_to_string(
"snippets/editor.html",
{
"toolbar": self.get_toolbar(lang, fieldid, unit, idx, source),
"fieldid": fieldid,
"label": label,
"textarea": textarea,
"max_length": attrs["data-max"],
"length": len(val),
"source_length": len(source),
"rtl_toggle": self.get_rtl_toggle(lang, fieldid),
},
)
)
# Show plural formula for more strings
if show_plural_labels:
ret.append(
render_to_string(
"snippets/plural-formula.html",
{"plural": plural, "user": self.profile.user},
)
)
return format_html_join("", "{}", ((v,) for v in ret))
def value_from_datadict(self, data, files, name):
"""Return processed plurals as a list."""
ret = []
for idx in range(10):
fieldname = f"{name}_{idx:d}"
if fieldname not in data:
break
ret.append(data.get(fieldname, ""))
return [r.replace("\r", "") for r in ret]
class PluralField(forms.CharField):
"""
Renderer for the plural field.
The only difference from CharField is that it does not
enforce the value to be a string.
"""
def __init__(self, **kwargs):
kwargs["label"] = ""
super().__init__(widget=PluralTextarea, **kwargs)
def to_python(self, value):
"""Return list of strings as returned by PluralTextarea."""
return value
def clean(self, value):
value = super().clean(value)
if not value or (self.required and not any(value)):
raise ValidationError(self.error_messages["required"], code="required")
return value
class FilterField(forms.ChoiceField):
def __init__(self, *args, **kwargs):
kwargs["label"] = gettext_lazy("Search filter")
if "required" not in kwargs:
kwargs["required"] = False
kwargs["choices"] = get_filter_choice()
kwargs["error_messages"] = {
"invalid_choice": gettext_lazy("Please choose a valid filter type.")
}
super().__init__(*args, **kwargs)
def to_python(self, value):
if value == "untranslated":
return "todo"
return super().to_python(value)
class ChecksumForm(forms.Form):
"""Form for handling checksum IDs for translation."""
checksum = ChecksumField(required=True)
def __init__(self, unit_set, *args, **kwargs):
self.unit_set = unit_set
super().__init__(*args, **kwargs)
def clean_checksum(self):
"""Validate whether checksum is valid and fetches unit for it."""
if "checksum" not in self.cleaned_data:
return
unit_set = self.unit_set
try:
self.cleaned_data["unit"] = unit_set.filter(
id_hash=self.cleaned_data["checksum"]
)[0]
except (Unit.DoesNotExist, IndexError):
raise ValidationError(
gettext("The string you wanted to translate is no longer available.")
)
class UnitForm(forms.Form):
def __init__(self, unit: Unit, *args, **kwargs):
self.unit = unit
super().__init__(*args, **kwargs)
class FuzzyField(forms.BooleanField):
help_as_icon = True
def __init__(self, *args, **kwargs):
kwargs["label"] = gettext_lazy("Needs editing")
kwargs["help_text"] = gettext_lazy(
'Strings are usually marked as "Needs editing" after the source '
"string is updated, or when marked as such manually."
)
super().__init__(*args, **kwargs)
self.widget.attrs["class"] = "fuzzy_checkbox"
class TranslationForm(UnitForm):
"""Form used for translation of single string."""
contentsum = ChecksumField(required=True)
translationsum = ChecksumField(required=True)
target = PluralField(required=False)
fuzzy = FuzzyField(required=False)
review = forms.ChoiceField(
label=gettext_lazy("Review state"),
choices=[
(state, get_state_label(state, label, True))
for state, label in StringState.choices
if state not in (STATE_READONLY, STATE_EMPTY)
],
required=False,
widget=forms.RadioSelect,
)
explanation = forms.CharField(
widget=MarkdownTextarea,
label=gettext_lazy("Explanation"),
help_text=gettext_lazy(
"Additional explanation to clarify meaning or usage of the string."
),
max_length=1000,
required=False,
)
def __init__(self, user, unit: Unit, *args, **kwargs):
if unit is not None:
kwargs["initial"] = {
"checksum": unit.checksum,
"contentsum": hash_to_checksum(unit.content_hash),
"translationsum": hash_to_checksum(unit.get_target_hash()),
"target": unit,
"fuzzy": unit.fuzzy,
"review": unit.state,
"explanation": unit.explanation,
}
kwargs["auto_id"] = f"id_{unit.checksum}_%s"
tabindex = kwargs.pop("tabindex", 100)
super().__init__(unit, *args, **kwargs)
if unit.readonly:
for field in ["target", "fuzzy", "review"]:
self.fields[field].widget.attrs["readonly"] = 1
self.fields["review"].choices = [
(state, label)
for state, label in StringState.choices
if state == STATE_READONLY
]
self.user = user
self.fields["target"].widget.attrs["tabindex"] = tabindex
self.fields["target"].widget.profile = user.profile
self.fields["review"].widget.attrs["class"] = "review_radio"
# Avoid failing validation on untranslated string
if args:
self.fields["review"].choices.append((STATE_EMPTY, ""))
self.helper = FormHelper()
self.helper.form_method = "post"
self.helper.form_tag = False
self.helper.disable_csrf = True
self.helper.layout = Layout(
Field("target"),
Field("fuzzy"),
Field("contentsum"),
Field("translationsum"),
InlineRadios("review"),
Field("explanation"),
)
if unit and user.has_perm("unit.review", unit.translation):
self.fields["fuzzy"].widget = forms.HiddenInput()
else:
self.fields["review"].widget = forms.HiddenInput()
if unit.translation.component.is_glossary:
if unit.is_source:
self.fields["explanation"].label = gettext("Source string explanation")
else:
self.fields["explanation"].label = gettext("Translation explanation")
else:
self.fields["explanation"].widget = forms.HiddenInput()
def clean(self):
super().clean()
# Check required fields
required = {"target", "contentsum", "translationsum"}
if not required.issubset(self.cleaned_data):
return
unit = self.unit
if self.cleaned_data["contentsum"] != unit.content_hash:
raise ValidationError(
gettext(
"The source string has changed meanwhile. "
"Please check your changes."
)
)
if self.cleaned_data["translationsum"] != unit.get_target_hash():
# Allow repeated edits by the same author
last_author = unit.get_last_content_change()[0]
if last_author != self.user:
raise ValidationError(
gettext(
"The translation of the string has changed meanwhile. "
"Please check your changes."
)
)
# Add extra margin to limit to allow XML tags which might
# be ignored for the length calculation. On the other side,
# we do not want to process arbitrarily long strings here.
max_length = 10 * (unit.get_max_length() + 100)
for text in self.cleaned_data["target"]:
if len(text) > max_length:
raise ValidationError(gettext("Translation text too long!"))
if self.user.has_perm(
"unit.review", unit.translation
) and self.cleaned_data.get("review"):
self.cleaned_data["state"] = int(self.cleaned_data["review"])
elif self.cleaned_data["fuzzy"]:
self.cleaned_data["state"] = STATE_FUZZY
else:
self.cleaned_data["state"] = STATE_TRANSLATED
class ZenTranslationForm(TranslationForm):
checksum = ChecksumField(required=True)
def __init__(self, user, unit, *args, **kwargs):
super().__init__(user, unit, *args, **kwargs)
self.helper.form_action = reverse(
"save_zen", kwargs={"path": unit.translation.get_url_path()}
)
self.helper.form_tag = True
self.helper.disable_csrf = False
self.helper.layout.append(Field("checksum"))
self.fields["target"].widget.attrs["zen-mode"] = True
if not user.has_perm("unit.edit", unit):
for field in ["target", "fuzzy", "review"]:
self.fields[field].widget.attrs["disabled"] = 1
class DownloadForm(forms.Form):
q = QueryField()
format = forms.ChoiceField(
label=gettext_lazy("File format"),
choices=[],
initial="po",
required=True,
widget=forms.RadioSelect,
)
def __init__(self, translation, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["format"].choices = [
(x.name, x.verbose) for x in EXPORTERS.values() if x.supports(translation)
]
self.helper = FormHelper(self)
self.helper.form_tag = False
self.helper.layout = Layout(
SearchField("q"),
InlineRadios("format"),
)
class SimpleUploadForm(forms.Form):
"""Base form for uploading a file."""
file = forms.FileField(
label=gettext_lazy("File"), validators=[validate_file_extension]
)
method = forms.ChoiceField(
label=gettext_lazy("File upload mode"),
choices=(
("translate", gettext_lazy("Add as translation")),
("approve", gettext_lazy("Add as approved translation")),
("suggest", gettext_lazy("Add as suggestion")),
("fuzzy", gettext_lazy("Add as translation needing edit")),
("replace", gettext_lazy("Replace existing translation file")),
("source", gettext_lazy("Update source strings")),
("add", gettext_lazy("Add new strings")),
),
widget=forms.RadioSelect,
required=True,
)
fuzzy = forms.ChoiceField(
label=gettext_lazy('Processing of "Needs editing" strings'),
choices=(
("", gettext_lazy("Do not import")),
("process", gettext_lazy('Import as "Needs editing"')),
("approve", gettext_lazy("Import as translated")),
),
required=False,
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_tag = False
@staticmethod
def get_field_doc(field):
return ("user/files", f"upload-{field.name}")
def remove_translation_choice(self, value):
"""Remove "Add as translation" choice."""
choices = self.fields["method"].choices
self.fields["method"].choices = [
choice for choice in choices if choice[0] != value
]
class UploadForm(SimpleUploadForm):
"""Uploading form with the option to overwrite current messages."""
conflicts = forms.ChoiceField(
label=gettext_lazy("Conflict handling"),
help_text=gettext_lazy(
"Whether to overwrite existing translations if the string is "
"already translated."
),
choices=(
("", gettext_lazy("Change only untranslated strings")),
("replace-translated", gettext_lazy("Change translated strings")),
(
"replace-approved",
gettext_lazy("Change translated and approved strings"),
),
),
required=False,
initial="replace-translated",
)
class ExtraUploadForm(UploadForm):
"""Advanced upload form for users who can override authorship."""
author_name = forms.CharField(label=gettext_lazy("Author name"))
author_email = EmailField(label=gettext_lazy("Author e-mail"))
def get_upload_form(user, translation, *args, **kwargs):
"""Return correct upload form based on user permissions."""
if user.has_perm("upload.authorship", translation):
form = ExtraUploadForm
kwargs["initial"] = {"author_name": user.full_name, "author_email": user.email}
elif user.has_perm("upload.overwrite", translation):
form = UploadForm
else:
form = SimpleUploadForm
result = form(*args, **kwargs)
for method in [x[0] for x in result.fields["method"].choices]:
if not check_upload_method_permissions(user, translation, method):
result.remove_translation_choice(method)
# Remove approved choice for non review projects
if not user.has_perm("unit.review", translation) and form != SimpleUploadForm:
result.fields["conflicts"].choices = [
choice
for choice in result.fields["conflicts"].choices
if choice[0] != "approved"
]
return result
class SearchForm(forms.Form):
"""Text-searching form."""
q = QueryField()
sort_by = forms.CharField(required=False, widget=forms.HiddenInput)
checksum = ChecksumField(required=False)
offset = forms.IntegerField(min_value=-1, required=False, widget=forms.HiddenInput)
offset_kwargs = {}
@staticmethod
def get_initial(request):
if "q" in request.GET:
return {"q": request.GET["q"]}
return None
def __init__(self, user, language=None, show_builder=True, **kwargs):
"""Generate choices for other components in the same project."""
self.user = user
self.language = language
super().__init__(**kwargs)
self.helper = FormHelper(self)
self.helper.disable_csrf = True
self.helper.form_tag = False
self.helper.layout = Layout(
Div(
Field("offset", **self.offset_kwargs),
SearchField("q"),
Field("sort_by", template="snippets/sort-field.html"),
css_class="btn-toolbar",
role="toolbar",
),
ContextDiv(
template="snippets/query-builder.html",
context={
"user": self.user,
"month_ago": timezone.now() - timedelta(days=31),
"show_builder": show_builder,
"language": self.language,
},
),
Field("checksum"),
# Add hidden submit button so that submission via enter works
# See https://stackoverflow.com/a/477699/225718
HTML('<input type="submit" hidden />'),
)
def get_name(self):
"""Return verbose name for a search."""
return FILTERS.get_search_name(self.cleaned_data.get("q", ""))
def get_search_query(self):
return self.cleaned_data["q"]
def clean_offset(self):
if self.cleaned_data.get("offset") is None:
self.cleaned_data["offset"] = 1
return self.cleaned_data["offset"]
def items(self):
items = []
# Skip checksum and offset as these change
ignored = {"offset", "checksum"}
for param in sorted(self.cleaned_data):
value = self.cleaned_data[param]
# We don't care about empty values or ignored ones
if value is None or param in ignored:
continue
if isinstance(value, bool):
# Only store true values
if value:
items.append((param, "1"))
elif isinstance(value, int):
# Avoid storing 0 values
if value > 0:
items.append((param, str(value)))
elif isinstance(value, datetime):
# Convert date to string
items.append((param, value.date().isoformat()))
elif isinstance(value, list):
items.extend((param, val) for val in value)
elif isinstance(value, User):
items.append((param, value.username))
elif value:
# It should be a string here
items.append((param, value))
return items
def urlencode(self):
return urlencode(self.items())
def reset_offset(self):
"""
Resets form offset.
This is needed to avoid issues when using the form as the default for
any new search.
"""
data = copy.copy(self.data) # pylint: disable=access-member-before-definition
data["offset"] = "1"
data["checksum"] = ""
self.data = data
return self
class PositionSearchForm(SearchForm):
offset = forms.IntegerField(min_value=-1, required=False)
offset_kwargs = {"template": "snippets/position-field.html"}
class MergeForm(UnitForm):
"""Simple form for merging the translation of two units."""
merge = forms.IntegerField()
def clean(self):
super().clean()
if "merge" not in self.cleaned_data:
return None
unit = self.unit
translation = unit.translation
project = translation.component.project
try:
self.cleaned_data["merge_unit"] = merge_unit = Unit.objects.get(
pk=self.cleaned_data["merge"],
translation__component__project=project,
translation__language=translation.language,
)
except Unit.DoesNotExist:
raise ValidationError(gettext("Could not find the merged string."))
else:
# Compare in Python to ensure case sensitiveness on MySQL
if not translation.is_source and unit.source != merge_unit.source:
raise ValidationError(gettext("Could not find merged string."))
return self.cleaned_data
class RevertForm(UnitForm):
"""Form for reverting edits."""
revert = forms.IntegerField()
def clean(self):
super().clean()
if "revert" not in self.cleaned_data:
return None
try:
self.cleaned_data["revert_change"] = Change.objects.get(
pk=self.cleaned_data["revert"], unit=self.unit
)
except Change.DoesNotExist:
raise ValidationError(gettext("Could not find the reverted change."))
return self.cleaned_data
class AutoForm(forms.Form):
"""Automatic translation form."""
mode = forms.ChoiceField(
label=gettext_lazy("Automatic translation mode"),
initial="suggest",
)
filter_type = FilterField(
required=True,
initial="todo",
help_text=gettext_lazy(
"Please note that translating all strings will "
"discard all existing translations."
),
)
auto_source = forms.ChoiceField(
label=gettext_lazy("Source of automated translations"),
choices=[
("others", gettext_lazy("Other translation components")),
("mt", gettext_lazy("Machine translation")),
],
initial="others",
)
component = forms.ChoiceField(
label=gettext_lazy("Component"),
required=False,
help_text=gettext_lazy(
"Turn on contribution to shared translation memory for the project to "
"get access to additional components."
),
initial="",
)
engines = forms.MultipleChoiceField(
label=gettext_lazy("Machine translation engines"), choices=[], required=False
)
threshold = forms.IntegerField(
label=gettext_lazy("Score threshold"), initial=80, min_value=1, max_value=100
)
def __init__(self, obj, user=None, *args, **kwargs):
"""Generate choices for other components in the same project."""
super().__init__(*args, **kwargs)
self.obj = obj
# Add components from other projects with enabled shared TM
self.components = obj.project.component_set.filter(
source_language=obj.source_language
) | Component.objects.filter(
source_language_id=obj.source_language_id,
project__contribute_shared_tm=True,
).exclude(project=obj.project)
# Fetching first few entries is faster than doing a count query on possibly
# thousands of components
if len(self.components.values_list("id")[:30]) == 30:
# Do not show choices when too many
self.fields["component"] = forms.CharField(
required=False,
label=gettext("Component"),
help_text=gettext(
"Enter slug of a component to use as source, "
"keep blank to use all components in the current project."
),
)
else:
choices = [
(s.id, str(s))
for s in self.components.order_project().prefetch_related("project")
]
self.fields["component"].choices = [
("", gettext("All components in current project")),
*choices,
]
machinery_settings = obj.project.get_machinery_settings()
engines = sorted(
(
MACHINERY[engine](setting)
for engine, setting in machinery_settings.items()
if engine in MACHINERY
),
key=lambda engine: engine.name,
)
engine_ids = {engine.get_identifier() for engine in engines}
self.fields["engines"].choices = [
(engine.get_identifier(), engine.name) for engine in engines
]
if "weblate" in engine_ids:
self.fields["engines"].initial = "weblate"
use_types = {
"all",
"nottranslated",
"todo",
"fuzzy",
"check:inconsistent",
"check:translated",
}
self.fields["filter_type"].choices = [
x for x in self.fields["filter_type"].choices if x[0] in use_types
]
choices = [
("suggest", gettext("Add as suggestion")),
("translate", gettext("Add as translation")),
("fuzzy", gettext('Add as "Needing edit"')),
]
if user is not None and user.has_perm("unit.review", obj):
choices.append(("approved", gettext("Add as approved translation")))
self.fields["mode"].choices = choices
self.helper = FormHelper(self)
self.helper.layout = Layout(
Field("mode"),
Field("filter_type"),
InlineRadios("auto_source", id="select_auto_source"),
Div("component", css_id="auto_source_others"),
Div("engines", "threshold", css_id="auto_source_mt"),
)
def clean_component(self):
component = self.cleaned_data["component"]
if not component:
return None
if component.isdigit():
try:
result = self.components.get(pk=component)
except Component.DoesNotExist:
raise ValidationError(gettext("Component not found!"))
else:
slashes = component.count("/")
if slashes == 0:
try:
result = self.components.get(
slug=component, project=self.obj.project
)