Debian Codegraph @

wxgeometrie/geolib/widgets.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 ##--------------------------------------#######
4 # Feuille #
5 ##--------------------------------------#######
6 # WxGeometrie
7 # Dynamic geometry, graph plotter, and more for french mathematic teachers.
8 # Copyright (C) 2005-2013 Nicolas Pourcelot
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program; if not, write to the Free Software
22 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
23
24 ##from sympy import S
25 from random import normalvariate
26
27 from .objet import Objet_avec_coordonnees_modifiables, Argument, Ref
28 from .textes import Texte_editable_generique, Texte
29 from ..pylib import print_error
30 from .. import param
31
32
33 class Bouton(Texte_editable_generique, Objet_avec_coordonnees_modifiables):
34 """Un bouton cliquable.
35
36 Un bouton avec texte. Typiquement, on lui associe une action
37 lorsque l'on clique dessus, via la méthode `onLeftClick`.
38 """
39
40 _style_defaut = param.boutons
41
42 texte = __texte = Argument("str")
43 abscisse = x = __x = Argument("Variable_generique", defaut=0)
44 ordonnee = y = __y = Argument("Variable_generique", defaut=0)
45
46 def __init__(self, texte=' ', x=None, y=None, **styles):
47 x, y, styles = self._recuperer_x_y(x, y, styles)
48 texte = str(texte)
49
50 ##if texte != "":
51 ##styles["label"] = texte
52
53 self.__texte = texte = Ref(texte)
54 self.__x = x = Ref(x)
55 self.__y = y = Ref(y)
56
57 Objet_avec_coordonnees_modifiables.__init__(self, x, y, **styles)
58 Texte_editable_generique(self, texte, **styles)
59
60 ##def _creer_figure(self):
61 ##x, y = self.coordonnees
62 ##if not self._representation:
63 ##self._representation = [self.rendu.texte(), self.rendu.polygone(), self.rendu.ligne()]
64 ##Texte_editable_generique._creer_figure(self)
65 ##text, fill, plot = self._representation
66 ##fill.set_visible(True)
67 ##can = self.canvas
68 ##box = can.txt_box(text)
69 ##w, h = can.dpix2coo(.5*box.width, -.5*box.height)
70 ##niveau = self.style("niveau")
71 ##mx, my = can.dpix2coo(10, -10) # marge verticale et horizontale (en pixels)
72 ##w += mx
73 ##h += my
74 ##xy = [(x - w, y - h), (x - w, y + h), (x + w, y + h), (x + w, y - h)]
75 ##fill.xy = xy
76 ##fond = self.style('couleur_fond')
77 ##fill.set(facecolor=fond, edgecolor=self._foncer(fond))
78 ##fill.zorder = niveau
79 ##xy.append(xy[0])
80 ##plot.set_data(*zip(*xy))
81 ##plot.set(color='k')
82 ### TODO : utiliser FancyBboxPatch
83 ### http://matplotlib.sourceforge.net/examples/pylab_examples/fancybox_demo.html
84
85 def _creer_figure(self):
86 x, y = self.coordonnees
87 if not self._representation:
88 self._representation = [self.rendu.texte(), self.rendu.rectangle()]
89 Texte_editable_generique._creer_figure(self)
90 text, rect = self._representation
91 rect.set_visible(True)
92 box = self.canvas.txt_box(text)
93 w, h = self.feuille.dpix2coo(box.width, -box.height)
94 niveau = self.style("niveau")
95 marge = self.style("marge")
96 ##if av == "left":
97 ##x += w
98 ##elif av == "right":
99 ##x -= w
100 ##if ah == "top":
101 ##y -= h
102 ##elif ah == "bottom":
103 ##y += h
104 mx, my = self.feuille.dpix2coo(marge, -marge) # marge verticale et horizontale (en pixels)
105 rect.set_width(w + 2*mx)
106 rect.set_height(h + 2*my)
107 rect.set_x(self.x - .5*w - mx)
108 rect.set_y(self.y - .5*h - my)
109 fond = self.style('couleur_fond')
110 rect.set(facecolor=fond, edgecolor=self._foncer(fond))
111 rect.zorder = niveau
112 # TODO : utiliser FancyBboxPatch
113 # http://matplotlib.sourceforge.net/examples/pylab_examples/fancybox_demo.html
114
115
116 ##def _distance_inf(self, x, y, d):
117 ##d += self.style("marge")
118 ##xmin, xmax, ymin, ymax = self._boite()
119 ##return xmin - d - 3 < x < xmax + d + 3 and ymin - d < y < ymax + d
120
121 def _boite(self):
122 # Note : ymin et ymax "permutent" souvent car les transformations appliquées inversent l'orientation.
123 can = self.canvas
124 l, h = can.dimensions
125 box = can.txt_box(self.figure[1])
126 xmin = box.xmin
127 ymax = h - box.ymin
128 xmax = box.xmax
129 ymin = h - box.ymax
130 return xmin, xmax, ymin, ymax
131
132 def _distance_inf(self, x, y, d):
133 # Pour cliquer sur un bouton, il faut que la distance soit nulle.
134 return Texte_editable_generique._distance_inf(self, x, y, 0)
135
136 ##d += self.style("marge")
137 ##xmin, xmax, ymin, ymax = self._boite()
138 ##return xmin - d - 3 < x < xmax + d + 3 and ymin - d < y < ymax + d
139
140
141 def _en_gras(self, booleen):
142 fond = self.style('couleur_fond')
143 if booleen:
144 self._representation[1].set_facecolor(self._claircir(fond))
145 else:
146 self._representation[1].set_facecolor(fond)
147
148 @staticmethod
149 def _claircir(couleur):
150 r, g, b = couleur
151 r = 1 - .5*(1 - r)
152 g = 1 - .5*(1 - g)
153 b = 1 - .5*(1 - b)
154 return r, g, b
155
156 @staticmethod
157 def _foncer(couleur):
158 r, g, b = couleur
159 r = .75*r
160 g = .75*g
161 b = .75*b
162 return r, g, b
163
164
165
166 class Champ(Texte):
167 """Un champ de texte.
168
169 Un champ de texte éditable en double-cliquant dessus.
170
171 Le champ peut être encadré par du texte, via les mots-clefs `prefixe`
172 (texte à gauche) et `suffixe` (texte à droite).
173 On peut également lui associer un résultat attendu,
174 via le mot-clef `attendu`::
175
176 >>> from wxgeometrie import Champ
177 >>> c = Champ('modifiez moi', 10, 5, prefixe="1+1=", attendu="2",
178 ... formatage='rien', suffixe=" (entrer le resultat)")
179 >>> c.style("attendu")
180 '2'
181 >>> c.texte = '?'
182 >>> print(c.label())
183 1+1=? (entrer le resultat)
184
185 Si un résultat est attendu, alors le texte rentré par l'utilisateur passera
186 un test de validation. Si le résultat passe le test, un check vert est
187 affiché à côté, sinon, un smiley :-( rouge est affiché.
188
189 Par défaut, pour être validé, il faut que le résultat soit exactement
190 conforme au texte attendu::
191
192 >>> c.texte = "2.0"
193 >>> c.correct
194 False
195 >>> c.texte = "2"
196 >>> c.correct
197 True
198
199 Cependant, il est possible de définir un test de validation personnalisé::
200
201 >>> def test(reponse, attendu):
202 ... return float(reponse) == float(attendu)
203 >>> c.valider = test
204 >>> c.texte = "2.0"
205 >>> c.correct
206 True
207
208 On peut aussi associer une action à la validation::
209
210 >>> def action(**kw):
211 ... if kw['correct']:
212 ... if not kw['correct_old']:
213 ... # Ce n'était pas correct avant
214 ... print('Bravo !')
215 ... else:
216 ... # C'était déjà correct
217 ... print("Oui, c'est bon aussi !")
218 ... else:
219 ... print('Essaie encore...')
220 >>> c.evt_valider = action
221 >>> c.texte = "3"
222 Essaie encore...
223 >>> c.texte = "2"
224 Bravo !
225 >>> c.texte = "2.0"
226 Oui, c'est bon aussi !
227
228 Cet action sera effectuée lorsque le texte du champ est modifié, si
229 celui-ci passe le test de validation.
230
231 Enfin, une liste des propositions peut être passée via le mot-clef `choix`::
232
233 >>> c = Champ('', 10, 5, choix=['oui', 'non', 'sans opinion'])
234 >>> c.style('choix')
235 ['oui', 'non', 'sans opinion']
236 """
237
238 _style_defaut = param.champs
239
240 def _test_correct(self, txt):
241 attendu = self.style('attendu')
242 if attendu is None:
243 return
244 if self.valider is None:
245 # Validation basique par défaut
246 return (txt == attendu)
247 else:
248 # Méthode de validation personnalisée
249 return self.valider(txt, attendu)
250
251 def _set_texte(self, value):
252 value = Texte._set_texte(self, value)
253 if self._initialise:
254 # Impossible de vérifier si le résultat est correct tant
255 # que l'objet n'a pas fini d'être initialisé (le style
256 # 'attendu' n'est pas encore enregistré.)
257 txt = self.texte
258 if value != txt:
259 # Le contenu du champ de texte a changé.
260 # On vérifie si le résultat est correct, et on met
261 # en cache le résultat de cette vérification.
262 self._correct_old = self.correct
263 self.correct = self._test_correct(value)
264 if getattr(self, 'evt_valider', None) is not None:
265 self.evt_valider(champ=self, correct=self.correct,
266 correct_old=self._correct_old)
267 return value
268
269
270 texte = __texte = Argument("str", Texte._get_texte, _set_texte)
271 abscisse = x = __x = Argument("Variable_generique", defaut = lambda: normalvariate(0,10))
272 ordonnee = y = __y = Argument("Variable_generique", defaut = lambda: normalvariate(0,10))
273
274 # Il est possible d'attacher un test de validation personnalisé à l'objet.
275 valider = None
276 # Par ailleurs, on peut attacher à l'objet une action qui sera appelée après
277 # chaque test de validation.
278 evt_valider = None
279 # Indique si le contenu du champ est conforme aux attentes
280 correct = None
281
282 def __init__(self, texte="", x=None, y=None, **styles):
283 self.__texte = texte = Ref(texte)
284 self.__x = x = Ref(x)
285 self.__y = y = Ref(y)
286
287 Texte.__init__(self, texte, x, y, **styles)
288
289 # Permet de conserver la valeur precedente de `self.correct`.
290 # Lorsque l'utilisateur entre un nouveau résultat, on peut ainsi
291 # savoir si celui-ci était déjà correct, ou si le résultat est
292 # devenu correct (il peut y avoir plusieurs résultats corrects).
293 self._correct_old = self.correct = self._test_correct(self.texte)
294 ##self.__label_old = self.style('label')
295
296
297 def label(self, *args, **kw):
298 txt = Texte.label(self, *args, **kw)
299 if txt is None:
300 return
301 if not txt.strip('$\n'):
302 txt = '...' # u'\u20DB'
303 prefixe = self.style('prefixe')
304 suffixe = self.style('suffixe')
305 return (prefixe or '') + txt + (suffixe or '')
306
307
308 def style(self, *args, **kw):
309 label_change = ('label' in kw and kw['label'] != self._style['label'])
310 val = Texte.style(self, *args, **kw)
311 if label_change:
312 self._correct_old = self.correct
313 self.correct = self._test_correct()
314 if getattr(self, 'evt_valider', None) is not None:
315 self.evt_valider(champ=self, correct=self.correct,
316 correct_old=self._correct_old)
317 return val
318
319
320
321 def _creer_figure(self):
322 ##print 'champ-label::', self.label()
323 if not self._representation:
324 self._representation = [self.rendu.texte(), self.rendu.decoration_texte(), self.rendu.texte()]
325 Texte._creer_figure(self)
326 can = self.canvas
327 box = can.txt_box(self._representation[0])
328 px, py = box.max
329 x, y = self.feuille.pix2coo(px + 5, can.hauteur - py)
330 txt = self._representation[2]
331 attendu = self.style('attendu')
332 if attendu is None or not self.texte.strip():
333 txt.set(visible=False)
334 else:
335 txt.set(visible=True, x=x, y=y, va='top', ha='left')
336 if self.correct:
337 txt.set(text='\u2713', color='g') # 263A 00D8
338 else:
339 txt.set(text='\u2639', color='r') #u'\u26A0'
340 ##if getattr(self, 'evt_valider', None) is not None and lbl != self.__label_old:
341 ##self.evt_valider(champ=self, correct=correct,
342 ##correct_old=self.__correct_old)
343 ##self.__correct_old = correct
344 ##self.__label_old = lbl