/usr/share/pyshared/kiwi/ui/entry.py is in python-kiwi 1.9.22-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 | #
# Kiwi: a Framework and Enhanced Widgets for Python
#
# Copyright (C) 2006 Async Open Source
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#
# Author(s): Johan Dahlin <jdahlin@async.com.br>
# Ronaldo Maia <romaia@async.com.br>
#
#
# Design notes:
#
# When inserting new text, supose, the entry, at some time is like this,
# ahd the user presses '0', for instance:
# --------------------------------
# | ( 1 2 ) 3 4 5 - 6 7 8 9 |
# --------------------------------
# ^ ^ ^
# S P E
#
# S - start of the field (start)
# E - end of the field (end)
# P - pos - where the new text is being inserted. (pos)
#
# So, the new text will be:
#
# the old text, from 0 until P
# + the new text
# + the old text, from P until the end of the field, shifted to the
# right
# + the old text, from the end of the field, to the end of the text.
#
# After inserting, the text will be this:
# --------------------------------
# | ( 1 2 ) 3 0 4 5 - 6 7 8 9 |
# --------------------------------
# ^ ^ ^
# S P E
#
#
# When deleting some text, supose, the entry, at some time is like this:
# --------------------------------
# | ( 1 2 ) 3 4 5 6 - 7 8 9 0 |
# --------------------------------
# ^ ^ ^ ^
# S s e E
#
# S - start of the field (_start)
# E - end of the field (_end)
# s - start of the text being deleted (start)
# e - end of the text being deleted (end)
#
# end - start -> the number of characters being deleted.
#
# So, the new text will be:
#
# the old text, from 0 until the start of the text being deleted.
# + the old text, from the start of where the text is being deleted, until
# the end of the field, shifted to the left, end-start positions
# + the old text, from the end of the field, to the end of the text.
#
# So, after the text is deleted, the entry will look like this:
#
# --------------------------------
# | ( 1 2 ) 3 5 6 - 7 8 9 0 |
# --------------------------------
# ^
# P
#
# P = the position of the cursor after the deletion, witch is equal to
# start (s at the previous illustration)
"""
An enchanced version of GtkEntry that supports icons and masks
"""
import gettext
import string
try:
set
except NameError:
from sets import Set as set
import gobject
import pango
import gtk
from kiwi.enums import Direction
from kiwi.environ import environ
from kiwi.ui.icon import IconEntry
from kiwi.ui.entrycompletion import KiwiEntryCompletion
from kiwi.utils import PropertyObject, gsignal, gproperty, type_register
if not environ.epydoc:
HAVE_2_6 = gtk.pygtk_version[:2] <= (2, 6)
else:
HAVE_2_6 = True
class MaskError(Exception):
pass
(INPUT_ASCII_LETTER,
INPUT_ALPHA,
INPUT_ALPHANUMERIC,
INPUT_DIGIT) = range(4)
INPUT_FORMATS = {
'0': INPUT_DIGIT,
'L': INPUT_ASCII_LETTER,
'A': INPUT_ALPHANUMERIC,
'a': INPUT_ALPHANUMERIC,
'&': INPUT_ALPHA,
}
# Todo list: Other usefull Masks
# 9 - Digit, optional
# ? - Ascii letter, optional
# C - Alpha, optional
INPUT_CHAR_MAP = {
INPUT_ASCII_LETTER: lambda text: text in string.ascii_letters,
INPUT_ALPHA: unicode.isalpha,
INPUT_ALPHANUMERIC: unicode.isalnum,
INPUT_DIGIT: unicode.isdigit,
}
(COL_TEXT,
COL_OBJECT) = range(2)
(ENTRY_MODE_UNKNOWN,
ENTRY_MODE_TEXT,
ENTRY_MODE_DATA) = range(3)
_ = lambda msg: gettext.dgettext('kiwi', msg)
class KiwiEntry(PropertyObject, gtk.Entry):
"""
The KiwiEntry is a Entry subclass with the following additions:
- IconEntry, allows you to have an icon inside the entry
- Mask, force the input to meet certain requirements
- IComboMixin: Allows you work with objects instead of strings
Adds a number of convenience methods such as L{prefill}().
"""
__gtype_name__ = 'KiwiEntry'
gproperty("completion", bool, False)
gproperty('exact-completion', bool, default=False)
gproperty("mask", str, default='')
def __init__(self):
self._completion = None
gtk.Entry.__init__(self)
PropertyObject.__init__(self)
self.connect('insert-text', self._on_insert_text)
self.connect('delete-text', self._on_delete_text)
self.connect_after('grab-focus', self._after_grab_focus)
self.connect('changed', self._on_changed)
self.connect('focus', self._on_focus)
self.connect('focus-out-event', self._on_focus_out_event)
self.connect('move-cursor', self._on_move_cursor)
# Ideally, this should be connected to notify::cursor-position, but
# there seems to be a bug in gtk that the notification is not emited
# when it should.
# TODO: investigate that and report a bug.
self.connect('notify::selection-bound',
self._on_notify_selection_bound)
self._block_changed = False
self._current_object = None
self._mode = ENTRY_MODE_TEXT
self._icon = IconEntry(self)
# List of validators
# str -> static characters
# int -> dynamic, according to constants above
self._mask_validators = []
self._mask = None
# Fields defined by mask
# each item is a tuble, containing the begining and the end of the
# field in the text
self._mask_fields = []
self._current_field = -1
self._pos = 0
self._selecting = False
self._block_insert = False
self._block_delete = False
# Virtual methods
# PyGTK 2.6 does not support the virtual method do_size_allocate so
# we have to use the signal instead
# PyGTK 2.9.0 and later (bug #327715) does not work using the old code,
# so we have to make this conditionally
if HAVE_2_6:
gsignal('size-allocate', 'override')
def do_size_allocate(self, allocation):
self.chain(allocation)
if self.flags() & gtk.REALIZED:
self._icon.resize_windows()
else:
def do_size_allocate(self, allocation):
gtk.Entry.do_size_allocate(self, allocation)
if self.flags() & gtk.REALIZED:
self._icon.resize_windows()
def do_expose_event(self, event):
gtk.Entry.do_expose_event(self, event)
if event.window == self.window:
self._icon.draw_pixbuf()
def do_realize(self):
gtk.Entry.do_realize(self)
self._icon.construct()
def do_unrealize(self):
self._icon.deconstruct()
gtk.Entry.do_unrealize(self)
# Properties
def prop_set_exact_completion(self, value):
self.set_exact_completion(value)
return value
def prop_set_completion(self, value):
if not self.get_completion():
self.set_completion(gtk.EntryCompletion())
return value
def prop_set_mask(self, value):
try:
self.set_mask(value)
return self.get_mask()
except MaskError, e:
pass
return ''
# Public API
def set_text(self, text):
completion = self.get_completion()
if isinstance(completion, KiwiEntryCompletion):
self.handler_block(completion.changed_id)
gtk.Entry.set_text(self, text)
if isinstance(completion, KiwiEntryCompletion):
self.handler_unblock(completion.changed_id)
# Mask & Fields
def set_mask(self, mask):
"""
Sets the mask of the Entry.
Supported format characters are:
- '0' digit
- 'L' ascii letter (a-z and A-Z)
- '&' alphabet, honors the locale
- 'a' alphanumeric, honors the locale
- 'A' alphanumeric, honors the locale
This is similar to MaskedTextBox:
U{http://msdn2.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask(VS.80).aspx}
Example mask for a ISO-8601 date
>>> entry.set_mask('0000-00-00')
@param mask: the mask to set
"""
if not mask:
self.modify_font(pango.FontDescription("sans"))
self._mask = mask
return
# First, reset
self._mask_validators = []
self._mask_fields = []
self._current_field = -1
mask = unicode(mask)
input_length = len(mask)
lenght = 0
pos = 0
field_begin = 0
field_end = 0
while True:
if pos >= input_length:
break
if mask[pos] in INPUT_FORMATS:
self._mask_validators += [INPUT_FORMATS[mask[pos]]]
field_end += 1
else:
self._mask_validators.append(mask[pos])
if field_begin != field_end:
self._mask_fields.append((field_begin, field_end))
field_end += 1
field_begin = field_end
pos += 1
self._mask_fields.append((field_begin, field_end))
self.modify_font(pango.FontDescription("monospace"))
self._really_delete_text(0, -1)
self._insert_mask(0, input_length)
self._mask = mask
def get_mask(self):
"""
Get the mask.
@returns: the mask
"""
return self._mask
def get_field_text(self, field):
if not self._mask:
raise MaskError("a mask must be set before calling get_field_text")
text = self.get_text()
start, end = self._mask_fields[field]
return text[start: end].strip()
def get_fields(self):
"""
Get the fields assosiated with the entry.
A field is dynamic content separated by static.
For example, the format string 000-000 has two fields
separated by a dash.
if a field is empty it'll return an empty string
otherwise it'll include the content
@returns: fields
@rtype: list of strings
"""
if not self._mask:
raise MaskError("a mask must be set before calling get_fields")
fields = []
text = unicode(self.get_text())
for start, end in self._mask_fields:
fields.append(text[start:end].strip())
return fields
def get_empty_mask(self, start=None, end=None):
"""
Gets the empty mask between start and end
@param start:
@param end:
@returns: mask
@rtype: string
"""
if start is None:
start = 0
if end is None:
end = len(self._mask_validators)
s = ''
for validator in self._mask_validators[start:end]:
if isinstance(validator, int):
s += ' '
elif isinstance(validator, unicode):
s += validator
else:
raise AssertionError
return s
def get_field_pos(self, field):
"""
Get the position at the specified field.
"""
if field >= len(self._mask_fields):
return None
start, end = self._mask_fields[field]
return start
def _get_field_ideal_pos(self, field):
start, end = self._mask_fields[field]
text = self.get_field_text(field)
pos = start+len(text)
return pos
def get_field(self):
if self._current_field >= 0:
return self._current_field
else:
return None
def set_field(self, field, select=False):
if field >= len(self._mask_fields):
return
pos = self._get_field_ideal_pos(field)
self.set_position(pos)
if select:
field_text = self.get_field_text(field)
start, end = self._mask_fields[field]
self.select_region(start, pos)
self._current_field = field
def get_field_length(self, field):
if 0 <= field < len(self._mask_fields):
start, end = self._mask_fields[field]
return end - start
def _shift_text(self, start, end, direction=Direction.LEFT,
positions=1):
"""
Shift the text, to the right or left, n positions. Note that this
does not change the entry text. It returns the shifted text.
@param start:
@param end:
@param direction: see L{kiwi.enums.Direction}
@param positions: the number of positions to shift.
@return: returns the text between start and end, shifted to
the direction provided.
"""
text = self.get_text()
new_text = ''
validators = self._mask_validators
if direction == Direction.LEFT:
i = start
else:
i = end - 1
# When shifting a text, we wanna keep the static chars where they
# are, and move the non-static chars to the right position.
while start <= i < end:
if isinstance(validators[i], int):
# Non-static char shoud be here. Get the next one (depending
# on the direction, and the number of positions to skip.)
#
# When shifting left, the next char will be on the right,
# so, it will be appended, to the new text.
# Otherwise, when shifting right, the char will be
# prepended.
next_pos = self._get_next_non_static_char_pos(i, direction,
positions-1)
# If its outside the bounds of the region, ignore it.
if not start <= next_pos <= end:
next_pos = None
if next_pos is not None:
if direction == Direction.LEFT:
new_text = new_text + text[next_pos]
else:
new_text = text[next_pos] + new_text
else:
if direction == Direction.LEFT:
new_text = new_text + ' '
else:
new_text = ' ' + new_text
else:
# Keep the static char where it is.
if direction == Direction.LEFT:
new_text = new_text + text[i]
else:
new_text = text[i] + new_text
i += direction
return new_text
def _get_next_non_static_char_pos(self, pos, direction=Direction.LEFT,
skip=0):
"""
Get next non-static char position, skiping some chars, if necessary.
@param skip: skip first n chars
@param direction: direction of the search.
"""
text = self.get_text()
validators = self._mask_validators
i = pos+direction+skip
while 0 <= i < len(text):
if isinstance(validators[i], int):
return i
i += direction
return None
def _get_field_at_pos(self, pos, dir=None):
"""
Return the field index at position pos.
"""
for p in self._mask_fields:
if p[0] <= pos <= p[1]:
return self._mask_fields.index(p)
return None
def set_exact_completion(self, value):
"""
Enable exact entry completion.
Exact means it needs to start with the value typed
and the case needs to be correct.
@param value: enable exact completion
@type value: boolean
"""
if value:
match_func = self._completion_exact_match_func
else:
match_func = self._completion_normal_match_func
completion = self._get_completion()
completion.set_match_func(match_func)
def is_empty(self):
text = self.get_text()
if self._mask:
empty = self.get_empty_mask()
else:
empty = ''
return text == empty
# Private
def _really_delete_text(self, start, end):
# A variant of delete_text() that never is blocked by us
self._block_delete = True
self.delete_text(start, end)
self._block_delete = False
def _really_insert_text(self, text, position):
# A variant of insert_text() that never is blocked by us
self._block_insert = True
self.insert_text(text, position)
self._block_insert = False
def _insert_mask(self, start, end):
text = self.get_empty_mask(start, end)
self._really_insert_text(text, position=start)
def _confirms_to_mask(self, position, text):
validators = self._mask_validators
if position < 0 or position >= len(validators):
return False
validator = validators[position]
if isinstance(validator, int):
if not INPUT_CHAR_MAP[validator](text):
return False
if isinstance(validator, unicode):
if validator == text:
return True
return False
return True
def _update_current_object(self, text):
if self._mode != ENTRY_MODE_DATA:
return
for row in self.get_completion().get_model():
if row[COL_TEXT] == text:
self._current_object = row[COL_OBJECT]
break
else:
# Customized validation
if text:
self.set_invalid(_("'%s' is not a valid object" % text))
elif self.mandatory:
self.set_blank()
else:
self.set_valid()
self._current_object = None
def _get_text_from_object(self, obj):
if self._mode != ENTRY_MODE_DATA:
return
for row in self.get_completion().get_model():
if row[COL_OBJECT] == obj:
return row[COL_TEXT]
def _get_completion(self):
# Check so we have completion enabled, not this does not
# depend on the property, the user can manually override it,
# as long as there is a completion object set
completion = self.get_completion()
if completion:
return completion
completion = gtk.EntryCompletion()
self.set_completion(completion)
return completion
def get_completion(self):
return self._completion
def set_completion(self, completion):
if not isinstance(completion, KiwiEntryCompletion):
gtk.Entry.set_completion(self, completion)
completion.set_model(gtk.ListStore(str, object))
completion.set_text_column(0)
self._completion = gtk.Entry.get_completion(self)
return
old = self.get_completion()
if old == completion:
return completion
if old and isinstance(old, KiwiEntryCompletion):
old.disconnect_completion_signals()
self._completion = completion
# First, tell the completion what entry it will complete
completion.set_entry(self)
completion.set_model(gtk.ListStore(str, object))
completion.set_text_column(0)
self.set_exact_completion(False)
completion.connect("match-selected",
self._on_completion__match_selected)
self._current_object = None
return completion
def _completion_exact_match_func(self, completion, key, iter):
model = completion.get_model()
if not len(model):
return
content = model[iter][COL_TEXT]
return key.startswith(content)
def _completion_normal_match_func(self, completion, key, iter):
model = completion.get_model()
if not len(model):
return
raw_content = model[iter][COL_TEXT]
if raw_content is not None:
return key.lower() in raw_content.lower()
else:
return False
def _on_completion__match_selected(self, completion, model, iter):
if not len(model):
return
# this updates current_object and triggers content-changed
self.set_text(model[iter][COL_TEXT])
self.set_position(-1)
# FIXME: Enable this at some point
#self.activate()
def _appers_later(self, char, start):
"""
Check if a char appers later on the mask. If it does, return
the field it appers at. returns False otherwise.
"""
validators = self._mask_validators
i = start
while i < len(validators):
if self._mask_validators[i] == char:
field = self._get_field_at_pos(i)
if field is None:
return False
return field
i += 1
return False
def _can_insert_at_pos(self, new, pos):
"""
Check if a chararcter can be inserted at some position
@param new: The char that wants to be inserted.
@param pos: The position where it wants to be inserted.
@return: Returns None if it can be inserted. If it cannot be,
return the next position where it can be successfuly
inserted.
"""
validators = self._mask_validators
# Do not let insert if the field is full
field = self._get_field_at_pos(pos)
if field is not None:
text = self.get_field_text(field)
length = self.get_field_length(field)
if len(text) == length:
gtk.gdk.beep()
return pos
# If the char confirms to the mask, but is a static char, return the
# position after that static char.
if (self._confirms_to_mask(pos, new) and
not isinstance(validators[pos], int)):
return pos+1
# If does not confirms to mask:
# - Check if the char the user just tried to enter appers later.
# - If it does, Jump to the start of the field after that
if not self._confirms_to_mask(pos, new):
field = self._appers_later(new, pos)
if field is not False:
pos = self.get_field_pos(field+1)
if pos is not None:
gobject.idle_add(self.set_position, pos)
return pos
return None
def _insert_at_pos(self, text, new, pos):
"""
Inserts the character at the give position in text. Note that the
insertion won't be applied to the entry, but to the text provided.
@param text: Text that it will be inserted into.
@param new: New text to insert.
@param pos: Positon to insert at
@return: Returns a tuple, with the position after the insetion
and the new text.
"""
field = self._get_field_at_pos(pos)
length = len(new)
new_pos = pos
start, end = self._mask_fields[field]
# Shift Right
new_text = (text[:pos] + new +
self._shift_text(pos, end, Direction.RIGHT)[1:] +
text[end:])
# Overwrite Right
# new_text = (text[:pos] + new +
# text[pos+length:end]+
# text[end:])
new_pos = pos+1
gobject.idle_add(self.set_position, new_pos)
# If the field is full, jump to the next field
if len(self.get_field_text(field)) == self.get_field_length(field)-1:
gobject.idle_add(self.set_field, field+1, True)
self.set_field(field+1)
return new_pos, new_text
# Callbacks
def _on_insert_text(self, editable, new, length, position):
if not self._mask or self._block_insert:
return
new = unicode(new)
pos = self.get_position()
self.stop_emission('insert-text')
text = self.get_text()
# Insert one char at a time
for c in new:
_pos = self._can_insert_at_pos(c, pos)
if _pos is None:
pos, text = self._insert_at_pos(text, c, pos)
else:
pos = _pos
# Change the text with the new text.
self._block_changed = True
self._really_delete_text(0, -1)
self._block_changed = False
self._really_insert_text(text, 0)
def _on_delete_text(self, editable, start, end):
if not self._mask or self._block_delete:
return
self.stop_emission('delete-text')
pos = self.get_position()
# Trying to delete an static char. Delete the char before that
if (0 < start < len(self._mask_validators)
and not isinstance(self._mask_validators[start], int)
and pos != start):
self._on_delete_text(editable, start-1, start)
return
# we just tried to delete, stop the selection.
self._selecting = False
field = self._get_field_at_pos(end-1)
# Outside a field. Cannot delete.
if field is None:
self.set_position(end-1)
return
_start, _end = self._mask_fields[field]
# Deleting from outside the bounds of the field.
if start < _start or end > _end:
_start, _end = start, end
# Change the text
text = self.get_text()
# Shift Left
new_text = (text[:start] +
self._shift_text(start, _end, Direction.LEFT,
end-start) +
text[_end:])
# Overwrite Left
# empty_mask = self.get_empty_mask()
# new_text = (text[:_start] +
# text[_start:start] +
# empty_mask[start:start+(end-start)] +
# text[start+(end-start):_end] +
# text[_end:])
new_pos = start
self._block_changed = True
self._really_delete_text(0, -1)
self._block_changed = False
self._really_insert_text(new_text, 0)
# Position the cursor on the right place.
self.set_position(new_pos)
if pos == new_pos:
self._handle_position_change()
def _after_grab_focus(self, widget):
# The text is selectet in grab-focus, so this needs to be done after
# that:
if self.is_empty():
if self._mask:
self.set_field(0)
else:
self.set_position(0)
def _on_focus(self, widget, direction):
if not self._mask:
return
field = self._current_field
if (direction == gtk.DIR_TAB_FORWARD or
direction == gtk.DIR_DOWN):
field += 1
elif (direction == gtk.DIR_TAB_BACKWARD or
direction == gtk.DIR_UP):
field = -1
# Leaving the entry
if field == len(self._mask_fields) or field == -1:
self.select_region(0, 0)
self._current_field = -1
return False
if field < 0:
field = len(self._mask_fields)-1
# grab_focus changes the selection, so we need to grab_focus before
# making the selection.
self.grab_focus()
self.set_field(field, select=True)
return True
def _on_notify_selection_bound(self, widget, pspec):
if not self._mask:
return
if not self.is_focus():
return
if self._selecting:
return
self._handle_position_change()
def _handle_position_change(self):
pos = self.get_position()
field = self._get_field_at_pos(pos)
# Humm, the pos is not inside any field. Get the next pos inside
# some field, depending on the direction that the cursor is
# moving
diff = pos - self._pos
# but move only one position at a time.
if diff:
diff /= abs(diff)
_field = field
if diff:
while _field is None and pos >= 0:
pos += diff
_field = self._get_field_at_pos(pos)
self._pos = pos
if pos < 0:
self._pos = self.get_field_pos(0)
if field is None:
self.set_position(self._pos)
else:
if self._current_field != -1:
self._current_field = field
self._pos = pos
def _on_changed(self, widget):
if self._block_changed:
self.stop_emission('changed')
def _on_focus_out_event(self, widget, event):
if not self._mask:
return
self._current_field = -1
def _on_move_cursor(self, entry, step, count, extend_selection):
self._selecting = extend_selection
# IconEntry
def set_tooltip(self, text):
self._icon.set_tooltip(text)
def set_pixbuf(self, pixbuf):
self._icon.set_pixbuf(pixbuf)
def update_background(self, color):
self._icon.update_background(color)
def get_background(self):
return self._icon.get_background()
def get_icon_window(self):
return self._icon.get_icon_window()
# IComboMixin
def prefill(self, itemdata, sort=False):
"""
See L{kiwi.interfaces.IEasyCombo.prefill}
"""
if not isinstance(itemdata, (list, tuple)):
raise TypeError("'data' parameter must be a list or tuple of item "
"descriptions, found %s") % type(itemdata)
completion = self._get_completion()
model = completion.get_model()
if len(itemdata) == 0:
model.clear()
return
if (len(itemdata) > 0 and
type(itemdata[0]) in (tuple, list) and
len(itemdata[0]) == 2):
mode = self._mode = ENTRY_MODE_DATA
else:
mode = self._mode
values = set()
if mode == ENTRY_MODE_TEXT:
if sort:
itemdata.sort()
for item in itemdata:
if item in values:
raise KeyError("Tried to insert duplicate value "
"%r into the entry" % item)
else:
values.add(item)
model.append((item, None))
elif mode == ENTRY_MODE_DATA:
if sort:
itemdata.sort(lambda x, y: cmp(x[0], y[0]))
for item in itemdata:
text, data = item
# Add (n) to the end in case of duplicates
count = 1
orig = text
while text in values:
text = orig + ' (%d)' % count
count += 1
values.add(text)
model.append((text, data))
else:
raise TypeError("Incorrect format for itemdata; see "
"docstring for more information")
def get_iter_by_data(self, data):
if self._mode != ENTRY_MODE_DATA:
raise TypeError(
"select_item_by_data can only be used in data mode")
completion = self._get_completion()
model = completion.get_model()
for row in model:
if row[COL_OBJECT] == data:
return row.iter
break
else:
raise KeyError("No item correspond to data %r in the combo %s"
% (data, self.name))
def get_iter_by_label(self, label):
completion = self._get_completion()
model = completion.get_model()
for row in model:
if row[COL_TEXT] == label:
return row.iter
else:
raise KeyError("No item correspond to label %r in the combo %s"
% (label, self.name))
def get_selected_by_iter(self, treeiter):
completion = self._get_completion()
model = completion.get_model()
mode = self._mode
text = model[treeiter][COL_TEXT]
if text != self.get_text():
return
if mode == ENTRY_MODE_TEXT:
return text
elif mode == ENTRY_MODE_DATA:
return model[treeiter][COL_OBJECT]
else:
raise AssertionError
def get_selected_label(self, treeiter):
completion = self._get_completion()
model = completion.get_model()
return model[treeiter][COL_TEXT]
def get_selected_data(self, treeiter):
completion = self._get_completion()
model = completion.get_model()
return model[treeiter][COL_OBJECT]
def get_iter_from_obj(self, obj):
mode = self._mode
if mode == ENTRY_MODE_TEXT:
return self.get_iter_by_label(obj)
elif mode == ENTRY_MODE_DATA:
return self.get_iter_by_data(obj)
else:
# XXX: When setting the datatype to non string, automatically go to
# data mode
raise TypeError("unknown Entry mode. Did you call prefill?")
def get_mode(self):
return self._mode
type_register(KiwiEntry)
def main(args):
win = gtk.Window()
win.set_title('gtk.Entry subclass')
def cb(window, event):
print 'fields', widget.get_field_text()
gtk.main_quit()
win.connect('delete-event', cb)
widget = KiwiEntry()
widget.set_mask('000.000.000.000')
win.add(widget)
win.show_all()
widget.select_region(0, 0)
gtk.main()
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
|