-
Notifications
You must be signed in to change notification settings - Fork 0
/
widgets.py
4530 lines (3314 loc) · 151 KB
/
widgets.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
"""GUI interface and widgets. Documentation is found throughout the file,
though in some areas it may be obsolete or incomplete.
More than meets the eye in this example. To see all features, look at the source
code of each widget. This includes several different types of interactive
widgets and displays an example at the end. It also includes API for creating
your own widgets, which are quite easy to do. Everything is object-oriented,
which aids in accessing properties and setting them. Nearly all properties can
be accessed and set from creation. These built-in widgets have plenty of
documentation and functions.
Several widgets are provided to use. These include Image, Label, Button,
Slider, Toggle, Entry, Combobox, and various shapes. Like most projects based
off pyglet, in this GUI toolkit, all widgets subclass a base widget class,
which dispatches events to them.
This uses the awesome pyglet and arcade libraries, which are still active and
working today. Arcade's website is https://arcade.academy/, while pyglet's is
https://pyglet.org/.
Arcade does have a seperate GUI toolkit implemented, but it has fewer features
compared to this. It does have some special enhancements and functionality that
is not provided here, such as the ability to place widgets with layouts and
groups. This is being developed here.
Contributions are welcome. Visit my Github respository at
https://github.com/eschan145/futura. From there, you can submit pull requests
or chat in discussions.
Code and graphics by Ethan Chan
GitHub: eschan145
Discord: EthanC145#8543
Contact me at esamuelchan@gmail.com
"""
from html import entities
from html.parser import HTMLParser
from re import compile
from tkinter import TclError, Tk
from typing import Tuple
from webbrowser import open_new
from arcade import (ShapeElementList, Sprite, SpriteList,
create_rectangle_outline, draw_rectangle_outline,
get_window, load_texture)
from pyglet import options
from pyglet.app import run
from pyglet.clock import get_frequency
from pyglet.event import EventDispatcher
from pyglet.graphics import Batch
from pyglet.image import load
from pyglet.text import DocumentLabel, HTMLLabel, decode_attributed
from pyglet.text.caret import Caret
from pyglet.text.formats.html import (_block_containers, _block_elements,
_metadata_elements, _parse_color,
_whitespace_re)
from pyglet.text.formats.structured import (ImageElement, OrderedListBuilder,
StructuredTextDecoder,
UnorderedListBuilder)
from pyglet.text.layout import IncrementalTextLayout, TextLayout
from .color import (BLACK, COOL_BLACK, DARK_GRAY, DARK_SLATE_GRAY, RED,
four_byte)
from .file import (blank1, entry_focus, entry_hover, entry_normal, knob,
slider_horizontal, toggle_false, toggle_false_hover,
toggle_true, toggle_true_hover, widgets)
from .geometry import Point, are_rects_intersecting, get_distance
from .key import (ALT, CONTROL, ENTER, KEY_LEFT, KEY_RIGHT, MOTION_BACKSPACE,
MOTION_BEGINNING_OF_FILE, MOTION_BEGINNING_OF_LINE,
MOTION_COPY, MOTION_DELETE, MOTION_DOWN, MOTION_END_OF_FILE,
MOTION_END_OF_LINE, MOTION_LEFT, MOTION_NEXT_WORD,
MOTION_PREVIOUS_WORD, MOTION_RIGHT, MOTION_UP,
MOUSE_BUTTON_LEFT, SHIFT, SPACE, TAB, A, B, C, I, Keys, V, X)
options["debug_gl"] = False
MAX = 2 ** 32
clipboard = Tk()
clipboard.withdraw()
# Sides
LEFT = "left"
CENTER = "center"
RIGHT = "right"
TOP = "top"
BOTTOM = "bottom"
# Callbacks
SINGLE = 1
DOUBLE = 2
MULTIPLE = 3
SIMPLE = "simple"
KEYBOARD = "keyboard"
MOUSE = "mouse"
PROGRAM = "program"
DISABLE_ALPHA = 160 # Alpha of disabled widget
FOCUS_SIZE = 1.05 # [DEPRECATED]
ENTRY_BLINK_INTERVAL = 0.5
TOGGLE_VELOCITY = 2
TOGGLE_FADE = 17
SLIDER_VELOCITY = 10
KNOB_HOVER_SCALE = 1
SCROLLER_PADDING = 20
HORIZONTAL = "horizontal"
VERTICAL = "vertical"
DEFAULT_FONT_FAMILY = "Montserrat"
DEFAULT_FONT_SIZE = 12
DEFAULT_FONT = ["Montserrat", 12]
DEFAULT_LABEL_COLORS = [BLACK, (COOL_BLACK, DARK_SLATE_GRAY, DARK_GRAY)]
def _exclude(exclusions):
import types
# Add everything as long as it's not a module and not prefixed with _
functions = [name for name, function in globals().items()
if not (name.startswith('_') or isinstance(function, types.ModuleType))]
# Remove the exclusions from the functions
for exclusion in exclusions:
if exclusion in functions:
functions.remove(exclusion)
del types # Deleting types from scope, introduced from the import
return functions
# The _ prefix is important, to not add these to the __all__
# _exclusions = ["function1", "function2"]
# __all__ = _exclude(_exclusions)
def set_container(_container):
"""Set the current container. This can be used for multiple views or
windows. It just sets container to the given parameter.
_container - main container to be used
parameters: Container
"""
import gui.management as management
management.container = _container
def get_container():
"""Get the current container.
returns: Container
"""
import gui.management as management
return management.container
def clipboard_get():
"""Get some text from the clipboard. This cathces exceptions if an image
is copied in the clipboard instead of a string.
_tkinter.TclError:
CLIPBOARD selection doesn't exist or form "STRING" not defined
returns: str
"""
try:
return clipboard.clipboard_get()
except TclError:
return
def clipboard_append(text):
"""Append some text to the clipboard.
text - text to append to the clipboard
parameters: str
"""
clipboard.clipboard_append(text)
def insert(index, text, add):
"""Insert some text to a string given an index. This was originally used for
the entry widget but was deceprated when we found a faster and more
efficient way to insert text.
index - index of the text addition
text - string to be edited
add - new text to be inserted
parameters: int, str, str
returns: str
"""
return text[:index] + add + text[index:]
def delete(start, end, text):
"""Delete some text to a string given an index. This was originally used for
the entry widget but was deceprated when we found a faster and more
efficient way to delete text.
start - start index of the text removal
end - end index of the text removal
text - string to be edited
parameters: int, int, str
returns: str
"""
if len(text) > end:
text = text[:start] + text[end + 1::]
return text
def convert_to_roman(number):
"""Convert an integer to a roman number, as in I, II, III, etc. The number
must between 0 and 3999. The number is automatically converted to an
integer to make it simple.
From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81611
Raises a ValueError if the number is not valid (see below rules)
number - number to be converted to roman. Must be between 0 and 3999.
parameters: int
returns: str
"""
if not 0 < number < 4000:
raise ValueError("Number must be between 1 and 3999")
# Typically don't format like this, but it makes it neater and readable
integers = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
numerals = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
result = ""
for i in range(len(integers)):
count = int(int(number) // integers[i])
result += numerals[i] * count
number -= integers[i] * count
return result
class HTMLDecoder(HTMLParser, StructuredTextDecoder):
"""A custom HTML decoder based off pyglet's built-in one. This has limited
functionality but still feature-rich. It is possible to modify styling and
tag names by overriding this.
"""
default_style = {
"font_name" : "Montserrat",
"font_size" : 12,
"margin_bottom" : "1pt",
"bold" : False,
"italic" : False,
}
font_sizes = {
1 : 8,
2 : 10,
3 : 12,
4 : 14,
5 : 18,
6 : 24,
7 : 48
}
def decode_structured(self, text, location):
"""Decode some structured text and convert it to the pyglet attributed
text (vnd.pyglet-attributed).
text - given HTML text to be decoded into pyglet attributed text
location - location of images and filepaths for the document
parameters: str, str
"""
self.location = location
self._font_size_stack = [3]
self.list_stack.append(UnorderedListBuilder({}))
self.strip_leading_space = True
self.block_begin = True
self.need_block_begin = False
self.element_stack = ["_top_block"]
self.in_metadata = False
self.in_pre = False
# Set default style
self.push_style("_default", self.default_style)
self.feed(text)
self.close()
def get_image(self, filename):
"""Get an image from a filename. This uses the location.
filename - filename of image
parameters: str
"""
return load(filename, file=self.location.open(filename))
def prepare_for_data(self):
"""Prepare the document for insertion of HTML text.
"""
if self.need_block_begin:
self.add_text("\n")
self.block_begin = True
self.need_block_begin = False
def handle_data(self, data):
"""Handle HTML data. See handle_starttag for details.
data - HTML data
"""
if self.in_metadata:
return
if self.in_pre:
self.add_text(data)
else:
data = _whitespace_re.sub(" ", data)
if data.strip():
self.prepare_for_data()
if self.block_begin or self.strip_leading_space:
data = data.lstrip()
self.block_begin = False
self.add_text(data)
self.strip_leading_space = data.endswith(" ")
def handle_starttag(self, tag, case_attributes):
"""Handle the start of tags for all HTML elements. This creates a map
of all the elements and pushes its style to a pyglet structured text
decoder. They may be upper or lower case. Note that you can use
parse_distance to calculate the pixel distance from standard units like
inches, millimeters, etc.
Pyglet uses a subset of HTML 4.01 transitional.
TODO: make code blocks have a gray background, keyboard blocks with a
glowing gray background
The following elements are currently supported.
ALIGN B BLOCKQUOTE BR CODE DD DIR DL EM FONT H1 H2 H3 H4 H5 H6 I IMG
KBD LI MENU OL P PRE Q STRONG SUB SUP U UL VAR
The mark (bullet or number) of a list item is separated from the body
of the list item with a tab, as the pyglet document model does not
allow out-of-stream text. This means lists display as expected, but
behave a little oddly if edited. Multi-level lists are supported.
No style or script elements are currently supported.
A description of each tag is found below.
ALIGN - alignment of the text. This can be LEFT, CENTER, or RIGHT.
B - bold or heavy text. This has no parameters, and is defined in
Markdown as two asterisks (**). Alias of <strong>.
BLOCKQOUTE - a quote of some text. Later, a line drawn on the left side
may be implemented. The left margin is indented by 60
pixels, but can be changed by specifying a padding
parameter. In Markdown, this is a greater than equal sign,
with the level on the number of signs.
BR - a line break. This draws a horizontal line below the text.
CODE - a code block. This is displayed as ` for single-line code and
``` for multiline code blocks in Markdown. This is an alias for
<pre>
DD - description, definition, or value for a item
DIR - unordered list. This takes a type parameter, either CIRCLE or
SQUARE. It defaults to a bullet point. Alias for <ul> and <menu>.
DL - description list. This just sets the bottom margin to nothing.
EM - italic or slanted text. This has no parameters. Alias for <i> and
<var>.
FONT - font and style of the text. It takes several parameters.
family font family of the text. This must be a pyglet
loaded font.
size size changes of the text. If negative the text will
shrink, and if positive the text will be enlarged.
If not specified the text size will be 3.
real_size actual font size of the text. This only accepts
positive values.
color font color of the text in RGBA format
H1 - largest HTML heading. This sets the font size to 24 points. All
headings except <h6> are bold.
H2 - second largest HTML heading. This sets the font size to 18 points.
H3 - third largest HTML heading. This sets the font size to 16 points.
H4 - fourth largest HTML heading. This sets the font size to 14 points.
H5 - fifth largest HTML heading. This sets the font size to 12 points.
H6 - a copy of <h5>, but with italic instead of bold text
I - italic or slanted text. This has no parameters. Alias for <em> and
<var>.
IMG - display an image. This takes several parameters.
filepath filepath of the image. This is not a loaded image.
width width of the image. This must be set to a value
greater than 0, or the image will not be rendered.
height height of the image. This must be set to a value
greater than 0, or the image will not be rendered.
KBD - display keyboard shortcut
LI - display a list item. This should be inserted in a ordered or
unordered list, like this.
<ul> My special list
<li> My first list item </li>
<li> My second list item </li>
</ul>
MENU - unordered list. This takes a type parmeter, either CIRCLE or
SQUARE. It defaults to a bullet point. Alias for <dir> and <ul>.
OL - ordered list. Instead of having symbols, this uses sequential
titles. Parameters and options are listed below.
start start title of ordered list. (int)
format list format. Pyglet's ordered list supports
1 Decimal arabic (1, 2, 3)
a Lowercase alphanumeric (a, b, c)
A Uppercase alphanumeric (A, B, C)
i Lowercase roman (i, ii, i)
I Uppercase roman (I, II, III)
These values can contain prefixes and suffixes,
like "1.", "(1)", and so on. If the format is
invalid a question mark will be used instead.
P - paragraph. This is different that just plain HTML text, as it will
be formatted to the guidelines of a paragraph. This takes a align
parameter, either LEFT, CENTER, or RIGHT. Defaults to LEFT.
PRE - a code block. This is displayed as ` for single-line code and
``` for multiline code blocks in Markdown. This is an alias to
<code>
Q - inline quotation element. This adds formal quotation marks around
enclosed text. NOTE: not a regular ".
STRONG - bold or heavy text. This has no parameters, and is defined in
Markdown as two asterisks (**). Alias of <b>
SUB - subscript text. Enclosed text is offset by points given in the
baseline parameter. This has two parameters.
size size decrement of the enclosed text. This is the
amount the text is leveled down.
baseline offset of the enclosed text. This should be
negative. Defaults to -3 points.
SUP - superscript text. Enclosed text is offset by points given in the
baseline parameter. This has two parameters.
size size increment of the enclosed text. This is the
amount the text is leveled up.
baseline offset of the enclosed text. This should be
positive. Defaults to 3 points.
U - underlined text. This can take an optional color argument for the
color of the underline. If not specified this defaults to BLACK.
UL - unordered list. This takes a type parameter, either CIRCLE or
SQUARE. It defaults to a bullet point. Alias for <dir> and <menu>.
VAR - italic or slanted text. This has no parameters. Alias for <i>
and <em>.
"""
if self.in_metadata:
return
element = tag.lower()
attributes = {}
for key, value in case_attributes:
attributes[key.lower()] = value
if element in _metadata_elements:
self.in_metadata = True
elif element in _block_elements:
# Pop off elements until we get to a block container
while self.element_stack[-1] not in _block_containers:
self.handle_endtag(self.element_stack[-1])
if not self.block_begin:
self.add_text("\n")
self.block_begin = True
self.need_block_begin = False
self.element_stack.append(element)
style = {}
if element in ("b", "strong"):
style["bold"] = True
elif element in ("i", "em", "var"):
style["italic"] = True
elif element in ("tt", "code", "kbd"):
color = self.current_style.get("color")
if color is None:
color = attributes.get("background_color") or \
(246, 246, 246, 255)
style["font_name"] = "Courier New"
style["background_color"] = color
elif element == "u":
color = self.current_style.get("color")
if color is None:
color = attributes.get("color") or [0, 0, 0, 255]
style["underline"] = color
elif element == "font":
if "family" in attributes:
style["font_name"] = attributes["family"].split(",")
if "size" in attributes:
size = attributes["size"]
try:
if size.startswith("+"):
size = self._font_size_stack[-1] + int(size[1:])
elif size.startswith("-"):
size = self._font_size_stack[-1] - int(size[1:])
else:
size = int(size)
except ValueError:
size = 3
self._font_size_stack.append(size)
if size in self.font_sizes:
style["font_size"] = self.font_sizes.get(size, 3)
elif "real_size" in attributes:
size = int(attributes["real_size"])
self._font_size_stack.append(size)
style["font_size"] = size
else:
self._font_size_stack.append(self._font_size_stack[-1])
if "color" in attributes:
try:
style["color"] = _parse_color(attributes["color"])
except ValueError:
pass
elif element == "sup":
size = self._font_size_stack[-1] - (attributes.get("size") or 1)
style["font_size"] = self.font_sizes.get(size, 1)
style["baseline"] = attributes.get("baseline") or "3pt"
elif element == "sub":
size = self._font_size_stack[-1] - (attributes.get("size") or 1)
style["font_size"] = self.font_sizes.get(size, 1)
style["baseline"] = attributes.get("baseline") or "-3pt"
elif element == "h1":
style["font_size"] = 24
style["bold"] = True
elif element == "h2":
style["font_size"] = 18
style["bold"] = True
elif element == "h3":
style["font_size"] = 16
style["bold"] = True
elif element == "h4":
style["font_size"] = 14
style["bold"] = True
elif element == "h5":
style["font_size"] = 12
style["bold"] = True
elif element == "h6":
style["font_size"] = 12
style["italic"] = True
elif element == "br":
self.add_text(u"\u2028")
self.strip_leading_space = True
elif element == "p":
if attributes.get("align") in ("left", "center", "right"):
style["align"] = attributes["align"]
elif element == "align":
style["align"] = attributes.get("type")
elif element == "pre":
style["font_name"] = "Courier New"
style["margin_bottom"] = 0
self.in_pre = True
elif element == "blockquote":
padding = attributes.get("padding") or 60
left_margin = self.current_style.get("margin_left") or 0
right_margin = self.current_style.get("margin_right") or 0
style["margin_left"] = left_margin + padding
style["margin_right"] = right_margin + padding
elif element == "q":
self.handle_data(u"\u201c")
elif element == "ol":
try:
start = int(attributes.get("start", 1))
except ValueError:
start = 1
format = attributes.get("format", "1.")
builder = OrderedListBuilder(start, format)
builder.begin(self, style)
self.list_stack.append(builder)
elif element in ("ul", "dir", "menu"):
type = attributes.get("type", "circle").lower()
detail = attributes.get("detail")
if detail and not type:
raise UnicodeDecodeError("If a detail is specified, then a " \
"type must also be specified. " \
"Built in styles include circles, " \
"squares, arrows, and checkboxes."
)
elif type == "square":
mark = u"\u25a1" # □
else:
if type:
mark = type
else:
mark = u"\u25cf"
if detail:
if type == "circle":
if detail == "empty":
mark = u"\u25CB" # ○
elif detail == "filled":
mark = u"\u25CF" # • # ●‿●
if type == "arrow":
if detail == "black-white":
mark = u"\u27A3" # ➢
elif detail == "white-black":
mark = u"\u27A2" # ➣
elif type == "checkbox":
if detail == "check":
# Might not work on some platforms and fonts
mark = u"\u2611" # ☑
elif detail == "cross":
mark = u"\u2612" # ☒
else:
if type == "arrow":
mark = u"\u27A4" # ➤
elif type == "checkbox":
mark = u"\u2610" # ☐
elif type == "circle":
mark = u"\u25CF"
elif type == "dash":
mark = u"\u2014"
builder = UnorderedListBuilder(mark)
builder.begin(self, style)
self.list_stack.append(builder)
elif element == "li":
self.list_stack[-1].item(self, style)
self.strip_leading_space = True
elif element == "dl":
style["margin_bottom"] = 0
elif element == "dd":
left_margin = self.current_style.get("margin_left") or 0
style["margin_left"] = left_margin + 30
elif element == "img":
image = self.get_image(attributes.get("filepath"))
if image:
width = attributes.get("width")
if width:
width = int(width)
height = attributes.get("height")
if height:
height = int(height)
self.prepare_for_data()
self.add_element(ImageElement(image, width, height))
self.strip_leading_space = False
self.push_style(element, style)
def handle_endtag(self, tag):
"""Handle the end tags for the HTML document. They may be upper or lower case.
"""
element = tag.lower()
if element not in self.element_stack:
return
self.pop_style(element)
while self.element_stack.pop() != element:
pass
if element in _metadata_elements:
self.in_metadata = False
elif element in _block_elements:
self.block_begin = False
self.need_block_begin = True
if element == "font" and len(self._font_size_stack) > 1:
self._font_size_stack.pop()
elif element == "pre":
self.in_pre = False
elif element == "q":
self.handle_data(u"\u201d")
elif element in ("ul", "ol"):
if len(self.list_stack) > 1:
self.list_stack.pop()
def handle_entityref(self, name):
"""Handle entity references from the HTML document.
"""
if name in entities.name2codepoint:
self.handle_data(chr(entities.name2codepoint[name]))
def handle_charref(self, name):
"""Handle character references from the HTML document. This is used
internally for the pyglet document formatter.
"""
name = name.lower()
try:
if name.startswith("x"):
self.handle_data(chr(int(name[1:], 16)))
else:
self.handle_data(chr(int(name)))
except ValueError:
pass
class HTMLLabel(DocumentLabel):
def __init__(self, text="", location=None,
x=0, y=0, width=None, height=None,
anchor_x='left', anchor_y='baseline',
multiline=False):
self._text = text
self._location = location
document = HTMLDecoder().decode(text, location)
document.label = self
DocumentLabel.__init__(self, document, x, y, width, height,
anchor_x, anchor_y, multiline, None,
get_container().batch, None)
def _get_text(self):
return self._text
def _set_text(self, text):
if text == self._text:
return
self._text = text
self.document = HTMLDecoder().decode(text)
self.document.label = self
text = property(_get_text, _set_text)
class WidgetsError(Exception):
"""Widgets error. When creating custom widgets, this can be invoked. Only
use this if you need to, like if it is going to cause something to hang or
crash, or it raises an unhelpful error. Making this unnecessary will be
annoying in some scenarios. If the user absolutely wants to do something
and this error keeps on being raised, this is aggravating and he will have
to edit the source code.
"""
class Font:
"""An object-oriented Font."""
def __init__(self,
family=DEFAULT_FONT_FAMILY,
size=DEFAULT_FONT_SIZE
):
"""Initialize an object-oriented Font. This is an experimental
feature and has no effect.
family - family of the font (style)
size - size of the font (not in pixels)
parameters: int, int
"""
self.family = family
self.size = size
self.list = [self.family, self.size]
def __getitem__(self, item):
"""Get an item from the list.
item - item whose value to be returned
parameters: int
returns: str or int
"""
return self.list[item]
def __setitem__(self, index, item):
"""Get an item from the list.
item - item whose value to be set
parameters: int, str or int
"""
self.list[index] = item
default_font = Font()
class Container:
"""Container class to draw and update widgets. One current problem is that
each widget in its widget spritelist is being drawn every frame
individually.
You should create a Container in the __init__ function of your application,
and before creating any widgets. It will automatically push events so you
don't need to call pyglet.window.Window.push_handlers yourself or manually
dispatch events.
Containers have several useful properties, like getting the current
application focus and the list of created widgets. You can exit the
application (if you are going to create a new arcade.View or hide the
application) by calling the exit function. You can also call draw_bbox or
its aliases to draw each bounding box for each widget.
All properties are listed here:
focus - current widget with application focus. See Widget.on_focus for
details.
enable - whether the container is enabled or not
widgets - list of widgets that have been
"""
def __init__(self, window=None):
"""Initialize a container. You shouldn't usually need to create an
instance of this class directly, unless managing multiple windows.
"""
self.window = window or get_window()
self.focus = None
self.enable = True
self.widgets = []
self.fps_list = []
self.added_widgets = []
self.groups = []
self.track_fps = True
self._window = self.window
self.batch = Batch()
self.widget_sprites = SpriteList()
def _get_window(self):
"""Current arcade window of the container. Sometimes using
arcade.get_window doesn't work properly, do to GL context errors.
type: property, arcade.Window
"""
return self._window
def _set_window(self, window):
self._window = window or get_window()
self._window.push_handlers(self)
def _get_title(self):
"""Title or caption of the window. This is the text that is displayed
on the top of the screen. Currently, changing text color, font, and
other styles is not supported. In the future, a custom toolbar could be
implemented, for customization of colors and styles.
Raises AssertionError if there is no set window.
type: property, str
"""
assert self.window, (
"No window is active. It has not been created "
"yet, or it was closed. Be sure to set the "
"window property of the container before adding "
"any widgets."
)
return self.window.get_caption()
def _set_title(self, title):
assert self.window, (
"No window is active. It has not been created "
"yet, or it was closed. Be sure to set the "
"window property of the container before adding "
"any widgets."
)
if not title:
title = ""
title = str(title)
self.window.set_caption(str(title))
def _get_fps(self):
"""Current update rate in frames per second (fps). This should not vary
between multiple containers. Drawing a fps display can aid in profiling
and measuring of the time between code.
This property is read-only.
NOTE: this is not the refresh rate. The refresh rate is how fast the
monitor redraws itself. Most monitors have a refresh rate of 60
hertz or 120 hertz. Fps is the number of update frames per
second. Higher fps will speed up events and collision checks.
returns: float
"""
# Don't use arcade.get_fps(). This measures incorrectly.
return get_frequency()
def _get_average_fps(self):
"""Average update rate in frames per second (fps). The items of the fps
list are averaged and returned.
This property is read-only.
returns: float
"""
# Don't use arcade.get_fps(). This measures incorrectly.