-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathInputField.lua
2440 lines (1871 loc) · 74.1 KB
/
InputField.lua
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
--[[============================================================
--=
--= InputField v3.3.1 - text input handling library for LÖVE (0.10.2+)
--= - Written by Marcus 'ReFreezed' Thunström
--= - MIT License (See the bottom of this file)
--= - https://github.com/ReFreezed/InputField
--=
--==============================================================
1. Functions
2. Enums
3. Basic usage
1. Functions
----------------------------------------------------------------
-- Search through the file for more info about each individual function.
-- Settings:
getAlignment, setAlignment
getDimensions, getWidth, getHeight, setDimensions, setWidth, setHeight
getDoubleClickMaxDelay, setDoubleClickMaxDelay
getFilter, setFilter
getFont, setFont
getMaxHistory, setMaxHistory
getMouseScrollSpeed, getMouseScrollSpeedX, getMouseScrollSpeedY, setMouseScrollSpeed, setMouseScrollSpeedX, setMouseScrollSpeedY
getType, setType, isPassword, isMultiline
getWheelScrollSpeed, getWheelScrollSpeedX, getWheelScrollSpeedY, setWheelScrollSpeed, setWheelScrollSpeedX, setWheelScrollSpeedY
isEditable, setEditable
isFontFilteringActive, setFontFilteringActive
-- Events:
update
mousepressed, mousemoved, mousereleased, wheelmoved
keypressed, textinput
-- Other:
canScroll, canScrollHorizontally, canScrollVertically
clearHistory
eachVisibleLine, eachSelection, eachSelectionOptimized
getBlinkPhase, resetBlinking
getCursor, setCursor, moveCursor, getCursorSelectionSide, getAnchorSelectionSide
getCursorLayout
getInfoAtCoords, getInfoAtCursor, getInfoAtCharacter
getScroll, getScrollX, getScrollY, setScroll, setScrollX, setScrollY, scroll, scrollToCursor
getScrollHandles, getScrollHandleHorizontal, getScrollHandleVertical
getScrollLimits
getSelection, setSelection, selectAll, getSelectedText, getSelectedVisibleText
getText, setText, getVisibleText, insert
getTextDimensions, getTextWidth, getTextHeight
getTextLength
getTextOffset
getVisibleLine, getVisibleLineCount
isBusy
releaseMouse
reset
2. Enums
----------------------------------------------------------------
InputFieldType
"normal" -- Simple single-line input.
"password" -- Single-line input where all characters are obscured.
"multiwrap" -- Multi-line input where text wraps by the width of the field.
"multinowrap" -- Multi-line input with no wrapping.
SelectionSide
"start" -- The start (left side) of the text selection.
"end" -- The end (right side) of the text selection.
TextCursorAlignment
"left" -- Align cursor to the left.
"right" -- Align cursor to the right.
TextAlignment
"left" -- Align text to the left.
"right" -- Align text to the right.
"center" -- Align text to the center.
3. Basic usage
----------------------------------------------------------------
local InputField = require("InputField")
local field = InputField("Initial text.")
local fieldX = 80
local fieldY = 50
love.keyboard.setKeyRepeat(true)
function love.keypressed(key, scancode, isRepeat)
field:keypressed(key, isRepeat)
end
function love.textinput(text)
field:textinput(text)
end
function love.mousepressed(mx, my, mbutton, pressCount)
field:mousepressed(mx-fieldX, my-fieldY, mbutton, pressCount)
end
function love.mousemoved(mx, my)
field:mousemoved(mx-fieldX, my-fieldY)
end
function love.mousereleased(mx, my, mbutton)
field:mousereleased(mx-fieldX, my-fieldY, mbutton)
end
function love.wheelmoved(dx, dy)
field:wheelmoved(dx, dy)
end
function love.draw()
love.graphics.setColor(0, 0, 1)
for _, x, y, w, h in field:eachSelection() do
love.graphics.rectangle("fill", fieldX+x, fieldY+y, w, h)
end
love.graphics.setColor(1, 1, 1)
for _, text, x, y in field:eachVisibleLine() do
love.graphics.print(text, fieldX+x, fieldY+y)
end
local x, y, h = field:getCursorLayout()
love.graphics.rectangle("fill", fieldX+x, fieldY+y, 1, h)
end
--============================================================]]
local InputField = {
_VERSION = "InputField 3.3.1",
}
local LK = require"love.keyboard"
local LS = require"love.system"
local LT = require"love.timer"
local utf8 = require"utf8"
local isMac = (LS.getOS() == "OS X")
local InputField = {}
InputField.__index = InputField
--[[ @Debug macOS on Windows.
isMac = true
local _isDown = LK.isDown
function LK.isDown(...)
for i = 1, select("#", ...) do
local key = select(i, ...)
if key == "lgui" then key = "lctrl"
elseif key == "rgui" then key = "rctrl"
elseif key == "lctrl" then key = "application"
elseif key == "rctrl" then key = "application"
end
if _isDown(key) then return true end
end
return false
end
--]]
--==============================================================
--= Internal functions =========================================
--==============================================================
local function noop() end
local function clamp(n, min, max)
return math.max(math.min(n, max), min)
end
local function nextCodepoint(s, i)
if i > 0 then
local b = s:byte(i)
if not b then
return
elseif b >= 240 then
i = i + 4
elseif b >= 224 then
i = i + 3
elseif b >= 192 then
i = i + 2
else
i = i + 1
end
elseif i == 0 then
i = 1
elseif i < 0 then
return
end
if i > #s then return end
return i, utf8.codepoint(s, i)
end
local function utf8Codes(s) -- We don't use utf8.codes() as it creates garbage!
return nextCodepoint, s, 0
end
local function utf8GetEndOffset(line, pos)
return (utf8.offset(line, pos+1) or #line+1) - 1
end
local function cleanString(field, s)
local isMultiline = field:isMultiline()
s = s:gsub((isMultiline and "[%z\1-\9\11-\31]+" or "[%z\1-\31]+"), "") -- Should we allow horizontal tab?
if field.fontFilteringIsActive then
local font = field.font
local hasGlyphs = font.hasGlyphs
s = s:gsub(utf8.charpattern, function(c)
if not (hasGlyphs(font, c) or (c == "\n" and isMultiline)) then
return ""
end
end)
end
return s
end
--
-- boundPosition = getNextWordBound ( string, startPosition, direction )
-- boundPosition = getNextHardLineBound( string, startPosition, direction )
-- direction = -1 | 1
--
-- Cursor behavior examples when navigating by word:
-- a|a bb -> aa| bb
-- aa| bb -> aa bb|
-- aa |bb -> aa bb|
-- cc| = dd+ee -> cc =| dd+ee
-- cc =| dd+ee -> cc = dd|+ee
-- cc = dd|+ee -> cc = dd+|ee
-- f|f(-88 -> ff|(-88
-- ff|(-88 -> ff(-|88
-- ff(|-88 -> ff(-|88
--
local getNextWordBound, getNextHardLineBound
do
local function newSet(values)
local set = {}
for _, v in ipairs(values) do
set[v] = true
end
return set
end
local ASCII_PUNCTUATION = "!\"#$%&'()*+,-./:;<=>?@[\\]^`{|}~"; ASCII_PUNCTUATION = newSet{ ASCII_PUNCTUATION:byte(1, #ASCII_PUNCTUATION) }
local ASCII_WHITESPACE = newSet{ 9--[[,10]],11,12,13,32 } -- Horizontal tab, line feed, vertical tab, form feed, carriage return, space.
-- Generated by tools/generateUnicodeInfo.lua:
-- PUNCTUATION (8330, 97+230)
local UNICODE_PUNCTUATION = newSet{180,187,191,215,247,749,885,894,903,1014,1154,1470,1472,1475,1478,1563,1748,1758,1769,2142,2416,2557,2678,2928,3191,3199,3204,3407,3449,
3572,3647,3663,3892,3894,3896,3973,4347,5120,6464,7379,8125,8468,8485,8487,8489,8494,8527,11632,12336,12448,12539,12880,42611,42622,43260,43359,43867,44011,64297,
65952,66463,66512,66927,67671,67871,67903,68223,68296,69293,70093,70107,70313,70749,70854,71739,72162,73727,92917,94178,113820,113823,119365,120513,120539,120571,120597,120629,120655,120687,
120713,120745,120771,123215,123647,126124,126128,126254}
local ranges = {161,169,171,172,174,177,182,184,706,709,722,735,741,747,751,767,900,901,1370,1375,1417,1418,
1421,1423,1523,1524,1542,1551,1566,1567,1642,1645,1789,1790,1792,1805,2038,2041,2046,2047,2096,2110,2404,2405,2546,2547,
2554,2555,2800,2801,3059,3066,3674,3675,3841,3863,3866,3871,3898,3901,4030,4037,4039,4044,4046,4058,4170,4175,4254,4255,
4960,4968,5008,5017,5741,5742,5787,5788,5867,5869,5941,5942,6100,6102,6104,6107,6144,6154,6468,6469,6622,6655,6686,6687,
6816,6822,6824,6829,7002,7018,7028,7036,7164,7167,7227,7231,7294,7295,7360,7367,8127,8129,8141,8143,8157,8159,8173,8175,
8189,8190,8208,8231,8240,8286,8314,8318,8330,8334,8352,8383,8448,8449,8451,8454,8456,8457,8470,8472,8478,8483,8506,8507,
8512,8516,8522,8525,8586,8587,8592,9254,9280,9290,9372,9449,9472,10101,10132,11123,11126,11157,11159,11263,11493,11498,11513,11516,
11518,11519,11776,11822,11824,11858,11904,11929,11931,12019,12032,12245,12272,12283,12289,12292,12296,12320,12342,12343,12349,12351,12443,12444,
12688,12689,12694,12703,12736,12771,12800,12830,12842,12871,12896,12927,12938,12976,12992,13311,19904,19967,42128,42182,42238,42239,42509,42511,
42738,42743,42752,42774,42784,42785,42889,42890,43048,43051,43062,43065,43124,43127,43214,43215,43256,43258,43310,43311,43457,43469,43486,43487,
43612,43615,43639,43641,43742,43743,43760,43761,43882,43883,64434,64449,64830,64831,65020,65021,65040,65049,65072,65106,65108,65126,65128,65131,
65281,65295,65306,65312,65339,65344,65371,65381,65504,65510,65512,65518,65532,65533,65792,65794,65847,65855,65913,65929,65932,65934,65936,65948,
66000,66044,67703,67704,68176,68184,68336,68342,68409,68415,68505,68508,69461,69465,69703,69709,69819,69820,69822,69825,69952,69955,70004,70005,
70085,70088,70109,70111,70200,70205,70731,70735,70746,70747,71105,71127,71233,71235,71264,71276,71484,71487,72004,72006,72255,72262,72346,72348,
72350,72354,72769,72773,72816,72817,73463,73464,73685,73713,74864,74868,92782,92783,92983,92991,92996,92997,93847,93850,118784,119029,119040,119078,
119081,119140,119146,119148,119171,119172,119180,119209,119214,119272,119296,119361,119552,119638,120832,121343,121399,121402,121453,121460,121462,121475,121477,121483,
125278,125279,126704,126705,126976,127019,127024,127123,127136,127150,127153,127167,127169,127183,127185,127221,127245,127405,127462,127490,127504,127547,127552,127560,
127568,127569,127584,127589,127744,128727,128736,128748,128752,128764,128768,128883,128896,128984,128992,129003,129024,129035,129040,129095,129104,129113,129120,129159,
129168,129197,129200,129201,129280,129400,129402,129483,129485,129619,129632,129645,129648,129652,129656,129658,129664,129670,129680,129704,129712,129718,129728,129730,
129744,129750,129792,129938,129940,129994}
for i = 1, #ranges, 2 do for cp = ranges[i], ranges[i+1] do UNICODE_PUNCTUATION[cp] = true end end
-- WHITESPACE (18, 5+2)
local UNICODE_WHITESPACE = newSet{160,5760,8239,8287,12288}
local ranges = {8192,8202,8232,8233}
for i = 1, #ranges, 2 do for cp = ranges[i], ranges[i+1] do UNICODE_WHITESPACE[cp] = true end end
local function getCodepointCharType(cp)
return ASCII_PUNCTUATION[cp] and "punctuation"
or cp == 10 and "newline"
or ASCII_WHITESPACE[cp] and "whitespace"
or cp <= 127 and "word"
or UNICODE_PUNCTUATION[cp] and "punctuation"
or UNICODE_WHITESPACE[cp] and "whitespace"
or "word"
end
local codepoints = {}
function getNextWordBound(s, pos, direction)
local len = 0
for _, cp in utf8Codes(s) do
len = len + 1
codepoints[len] = cp
end
for i = len+1, #codepoints do
codepoints[i] = nil
end
pos = clamp(pos, 0, len)
if direction < 0 then pos = pos+1 end
while true do
pos = pos + direction
-- Check for end of string.
local prevCp = codepoints[pos]
local nextCp = codepoints[pos+direction]
if not (prevCp and nextCp) then
pos = pos + direction
break
end
-- Check for word bound.
local prevType = getCodepointCharType(prevCp)
local nextType = getCodepointCharType(nextCp)
if (nextType ~= prevType and not (nextType ~= "whitespace" and prevType == "whitespace")) or nextType == "newline" then
if direction < 0 then pos = pos-1 end
break
end
end
return clamp(pos, 0, len)
end
function getNextHardLineBound(s, pos, direction)
local len = 0
for _, cp in utf8Codes(s) do
len = len + 1
codepoints[len] = cp
end
for i = len+1, #codepoints do
codepoints[i] = nil
end
while codepoints[pos] or codepoints[pos+direction] do
pos = pos + direction
if (codepoints[pos] or 10) == 10 then
if direction > 0 then pos = pos-1 end
break
end
end
return clamp(pos, 0, len)
end
end
local function updateWrap(field)
local text = field:getVisibleText()
if field.lastWrappedText == text then return end
field.lastWrappedText = text
if field:isMultiline() then
field.wrappedWidth = 0
local wrapWidth = (field.type == "multiwrap") and field.width or 1/0
local lineCount = 0
local processed = 0
for line, i in text:gmatch"([^\n]*)()" do
if i > processed then
processed = i
if line == "" then
lineCount = lineCount + 1
field.wrappedText[lineCount] = ""
field.softBreak[lineCount] = false
else
local w, subLines = field.font:getWrap(line, wrapWidth)
local subLineCount = #subLines
for subLineI, subLine in ipairs(subLines) do
lineCount = lineCount + 1
field.wrappedText[lineCount] = subLine
field.softBreak[lineCount] = subLineI < subLineCount
end
field.wrappedWidth = math.max(field.wrappedWidth, w)
end
end
end
for lineI = lineCount+1, #field.wrappedText do
field.wrappedText[lineI] = nil
field.softBreak[lineI] = nil
end
else
field.wrappedText[1] = text
field.softBreak[1] = false
field.wrappedWidth = field.font:getWidth(text)
for lineI = 2, #field.wrappedText do
field.wrappedText[lineI] = nil
field.softBreak[lineI] = nil
end
end
--[[ @Debug
print("--------------------------------")
for i = 1, #field.wrappedText do
print(i, field.softBreak[i], field.wrappedText[i])
end
--]]
end
local function getLineAlignmentOffset(field, line)
if field.alignment == "left" then return 0
elseif field.width == 1/0 then return 0
elseif field.type == "multinowrap" then return 0
elseif field.alignment == "right" then return math.max(field.width-field.font:getWidth(line), 0)
elseif field.alignment == "center" then return math.floor(.5 * math.max(field.width-field.font:getWidth(line), 0))
else
error(field.alignment)
end
end
local function alignOnLine(field, line, x)
return x + getLineAlignmentOffset(field, line)
end
local function unalignOnLine(field, line, x)
return x - getLineAlignmentOffset(field, line)
end
-- cursorPosition, side = getCursorPositionAtX(field, line, x)
-- side = -1 | 1
local function getCursorPositionAtX(field, line, x)
x = unalignOnLine(field, line, x)
if line == "" or x <= 0 then
return 0
elseif x <= field.font:getWidth(line:sub(1, utf8GetEndOffset(line, 1)))/2 then
return 0
end
local lineW = field.font:getWidth(line)
if x >= lineW then
return utf8.len(line)
end
-- Binary search.
local posL = 1
local posR = utf8.len(line)
local closestDist = math.abs(x - lineW)
local closestPos = posR
while posL < posR do
local pos = math.floor((posL+posR)/2)
local linePart = line:sub(1, utf8GetEndOffset(line, pos)) -- @Memory (We could maybe use font:getKerning() in LÖVE 11.4+ to traverse one character at a time. Might be slower though.)
local dx = x - field.font:getWidth(linePart)
if dx == 0 then return pos end -- x is exactly at the cursor's position.
local dist = math.abs(dx)
if dist < closestDist then
closestDist = dist
closestPos = pos
end
if dx < 0 then
posR = pos
else
posL = pos
if posL == posR-1 then break end -- Because pos is rounded down we'd get stuck without this (as pos would be posL again and again).
end
end
return closestPos
end
local function getLineStartPosition(field, targetLineI)
local linePos1 = 1
for lineI = 1, targetLineI-1 do
linePos1 = linePos1 + utf8.len(field.wrappedText[lineI])
if not field.softBreak[lineI] then
linePos1 = linePos1 + 1
end
end
return linePos1
end
-- cursorPosition, visualLineIndex, visualLineIndexUnclamped = getCursorPositionAtCoordinates( field, x, y )
local function getCursorPositionAtCoordinates(field, x, y)
updateWrap(field)
if not field:isMultiline() then
return getCursorPositionAtX(field, field.wrappedText[1], x), 1, 1
end
local fontH = field.font:getHeight()
local lineDist = math.ceil(fontH*field.font:getLineHeight())
local lineSpace = lineDist - fontH
local lineIUnclamped = math.floor(1 + (y+lineSpace/2) / lineDist)
local lineI = clamp(lineIUnclamped, 1, #field.wrappedText)
local line = field.wrappedText[lineI]
if not line then return 0, 0, lineIUnclamped end
local linePos1 = getLineStartPosition(field, lineI)
local posOnLine = getCursorPositionAtX(field, line, x)
return linePos1+posOnLine-1, lineI, lineIUnclamped
end
-- line, positionOnLine, lineIndex, linePosition1, linePosition2 = getLineInfoAtPosition( field, position )
local function getLineInfoAtPosition(field, pos)
updateWrap(field)
pos = math.min(pos, utf8.len(field.text))
local linePos1 = 1
for lineI, line in ipairs(field.wrappedText) do
local linePos2 = linePos1 + utf8.len(line) - 1
local softBreak = field.softBreak[lineI]
if pos <= (softBreak and linePos2-1 or linePos2) then -- Any trailing newline counts as being on the next line.
return line, pos-linePos1+1, lineI, linePos1, linePos2
end
linePos1 = linePos2 + (softBreak and 1 or 2) -- Jump over any newline.
end
-- We should never get here!
return getLineInfoAtPosition(field, 0)
end
local LCTRL = isMac and "lgui" or "lctrl"
local RCTRL = isMac and "rgui" or "rctrl"
-- modKeys = getModKeys( )
-- modKeys = "cas" | "ca" | "cs" | "as" | "c" | "a" | "s" | "" | "^cas" | "^ca" | "^cs" | "^as" | "^c" | "^a" | "^s" | "^"
local function getModKeys()
local c = LK.isDown(LCTRL, RCTRL )
local a = LK.isDown("lalt", "ralt" )
local s = LK.isDown("lshift", "rshift")
if isMac and LK.isDown("lctrl", "rctrl") then
if c and a and s then return "^cas"
elseif c and a then return "^ca"
elseif c and s then return "^cs"
elseif a and s then return "^as"
elseif c then return "^c"
elseif a then return "^a"
elseif s then return "^s"
else return "^" end
end
if c and a and s then return "cas"
elseif c and a then return "ca"
elseif c and s then return "cs"
elseif a and s then return "as"
elseif c then return "c"
elseif a then return "a"
elseif s then return "s"
else return "" end
end
local function limitScroll(field)
local limitX, limitY = field:getScrollLimits()
field.scrollX = clamp(field.scrollX, 0, limitX)
field.scrollY = clamp(field.scrollY, 0, limitY)
end
local function applyFilter(field, s)
local filterFunc = field.filterFunction
if not filterFunc then return s end
s = s:gsub(utf8.charpattern, function(c)
if filterFunc(c) then return "" end
end)
return s
end
-- pushHistory( field, group|nil )
local function pushHistory(field, group)
local history = field.editHistory
local i, state
-- Never save history for password fields.
if field.type == "password" then
i = 1
state = history[1]
-- Update last entry if group matches.
elseif group and group == field.editHistoryGroup then
i = field.editHistoryIndex
state = history[i]
-- History limit reached.
elseif field.editHistoryIndex >= field.editHistoryMax then
i = field.editHistoryIndex
state = table.remove(history, 1)
history[i] = state
-- Expand history.
else
i = field.editHistoryIndex + 1
state = {}
history[i] = state
end
for i = i+1, #history do
history[i] = nil
end
state.text = field.text
state.cursorPosition = field.cursorPosition
state.selectionStart = field.selectionStart
state.selectionEnd = field.selectionEnd
field.editHistoryIndex = i
field.editHistoryGroup = group
field.navigationTargetX = nil
end
local function finilizeHistoryGroup(field)
field.editHistoryGroup = nil
end
local function applyHistoryState(field, offset)
field.editHistoryIndex = field.editHistoryIndex + offset
local state = field.editHistory[field.editHistoryIndex] or assert(false)
field.text = state.text
field.cursorPosition = state.cursorPosition
field.selectionStart = state.selectionStart
field.selectionEnd = state.selectionEnd
field.navigationTargetX = nil
end
-- @UX: Improve how the cursor and selection are restored on undo.
local function undoEdit(field)
if field.editHistoryIndex == 1 then return false end
finilizeHistoryGroup(field)
applyHistoryState(field, -1)
field:resetBlinking()
field:scrollToCursor()
return true
end
local function redoEdit(field)
if field.editHistoryIndex == #field.editHistory then return false end
finilizeHistoryGroup(field)
applyHistoryState(field, 1)
field:resetBlinking()
field:scrollToCursor()
return true
end
--==============================================================
--= Exported functions =========================================
--==============================================================
-- InputField( [ initialText="", type:InputFieldType="normal" ] )
local function newInputField(text, fieldType)
if not (fieldType == nil or fieldType == "normal" or fieldType == "password" or fieldType == "multiwrap" or fieldType == "multinowrap") then
error("[InputField] Invalid field type '"..tostring(fieldType).."'.", 2)
end
fieldType = fieldType or "normal"
local field = setmetatable({
type = fieldType,
blinkTimer = LT.getTime(),
cursorPosition = 0,
selectionStart = 0,
selectionEnd = 0,
clickCount = 1, -- This and multiClickMaxDelay are only used if the 'pressCount' argument isn't supplied to mousepressed().
multiClickMaxDelay = 0.40,
multiClickExpirationTime = 0.00,
multiClickLastX = 0.0,
multiClickLastY = 0.0,
editHistoryMax = 100,
editHistory = {},
editHistoryIndex = 1,
editHistoryGroup = nil, -- nil | "insert" | "remove"
font = require"love.graphics".getFont(),
fontFilteringIsActive = false,
filterFunction = nil,
mouseScrollSpeedX = 6.0, -- Per pixel per second.
mouseScrollSpeedY = 8.0,
wheelScrollSpeedX = 1.0, -- Per second. Relative to the font size.
wheelScrollSpeedY = 1.0,
dragMode = "", -- "" | "character" | "word" | "line"
dragStartPosition1 = 0,
dragStartPosition2 = 0,
dragLastX = 0,
dragLastY = 0,
editingEnabled = true,
scrollX = 0.0,
scrollY = 0.0,
text = "",
width = 1/0,
height = 1/0,
alignment = "left",
navigationTargetX = nil, -- Used when navigating vertically. Nil means need recalculation.
-- These are updated by updateWrap():
lastWrappedText = "",
wrappedText = {""}, -- []line
softBreak = {false}, -- []bool
wrappedWidth = 0,
}, InputField)
text = cleanString(field, tostring(text == nil and "" or text))
field.text = text
local len = utf8.len(text)
field.editHistory[1] = {
text = text,
cursorPosition = len,
selectionStart = 0,
selectionEnd = len,
}
return field
end
-- phase = field:getBlinkPhase( )
-- Get current phase for an animated cursor.
-- The value is the time since the last blink reset.
function InputField.getBlinkPhase(field)
return LT.getTime() - field.blinkTimer
end
-- field:resetBlinking( )
function InputField.resetBlinking(field)
field.blinkTimer = LT.getTime()
end
-- position = field:getCursor( )
-- Position 0 is before first character, position 1 is between first and second etc.
function InputField.getCursor(field)
return field.cursorPosition
end
-- field:setCursor( position [, selectionSideToAnchor:SelectionSide=none ] )
-- Position 0 is before first character, position 1 is between first and second etc.
function InputField.setCursor(field, pos, selSideAnchor)
finilizeHistoryGroup(field)
pos = clamp(pos, 0, field:getTextLength())
field.cursorPosition = pos
local selStart = (selSideAnchor == "start" and field.selectionStart or pos)
local selEnd = (selSideAnchor == "end" and field.selectionEnd or pos)
field.selectionStart = math.min(selStart, selEnd)
field.selectionEnd = math.max(selStart, selEnd)
field:resetBlinking()
field:scrollToCursor()
end
local function setCursorPosition(field, pos, selSideAnchor, eraseNavTargetX)
field:setCursor(pos, selSideAnchor)
if eraseNavTargetX then
field.navigationTargetX = nil
end
end
-- field:moveCursor( steps [, selectionSideToAnchor:SelectionSide=none ] )
-- 'steps' may be positive or negative.
function InputField.moveCursor(field, steps, selSideAnchor)
setCursorPosition(field, field.cursorPosition+steps, selSideAnchor, true)
end
-- side:SelectionSide = field:getCursorSelectionSide( )
function InputField.getCursorSelectionSide(field)
return (field.cursorPosition < field.selectionEnd and "start" or "end")
end
-- side:SelectionSide = field:getAnchorSelectionSide( )
function InputField.getAnchorSelectionSide(field)
return (field.cursorPosition < field.selectionEnd and "end" or "start")
end
-- font = field:getFont( )
function InputField.getFont(field)
return field.font
end
-- field:setFont( font )
-- The font is used for text measurements.
function InputField.setFont(field, font)
if field.font == font then return end
if not font then error("Missing font argument.", 2) end
field.font = font
field.lastWrappedText = "\0" -- Make sure wrappedText updates.
limitScroll(field)
end
-- scrollX, scrollY = field:getScroll( )
-- scrollX = field:getScrollX( )
-- scrollY = field:getScrollY( )
function InputField.getScroll(field)
return field.scrollX, field.scrollY
end
function InputField.getScrollX(field)
return field.scrollX
end
function InputField.getScrollY(field)
return field.scrollY
end
-- field:setScroll( scrollX, scrollY )
-- field:setScrollX( scrollX )
-- field:setScrollY( scrollY )
function InputField.setScroll(field, scrollX, scrollY)
field.scrollX = scrollX
field.scrollY = scrollY
limitScroll(field)
end
function InputField.setScrollX(field, scrollX)
field.scrollX = scrollX
limitScroll(field)
end
function InputField.setScrollY(field, scrollY)
field.scrollY = scrollY
limitScroll(field)
end
-- scrolledX, scrolledY = field:scroll( deltaX, deltaY )
-- Returned values are how much was actually scrolled.
function InputField.scroll(field, dx, dy)
local oldScrollX = field.scrollX
local oldScrollY = field.scrollY
field.scrollX = oldScrollX + dx
field.scrollY = oldScrollY + dy
limitScroll(field)
return field.scrollX - oldScrollX,
field.scrollY - oldScrollY
end
-- field:scrollToCursor( )
function InputField.scrollToCursor(field)
local line, posOnLine, lineI = getLineInfoAtPosition(field, field.cursorPosition)
do
local fontH = field.font:getHeight()
local lineDist = math.ceil(fontH*field.font:getLineHeight())
local y = (lineI - 1) * lineDist
field.scrollY = clamp(field.scrollY, y-field.height+fontH, y)
end
if not field:isMultiline() then
local visibleText = field:getVisibleText()
local preText = visibleText:sub(1, utf8GetEndOffset(visibleText, field.cursorPosition))
local x = field.font:getWidth(preText)
field.scrollX = clamp(field.scrollX, x-field.width, x)
elseif field.type == "multinowrap" then
local preText = line:sub(1, utf8GetEndOffset(line, posOnLine))
local x = field.font:getWidth(preText)
field.scrollX = clamp(field.scrollX, x-field.width, x)
end
limitScroll(field)
end
-- limitX, limitY = field:getScrollLimits( )
function InputField.getScrollLimits(field)
updateWrap(field)
local fontH = field.font:getHeight()
local lineDist = math.ceil(fontH*field.font:getLineHeight())
return (field.type == "multiwrap") and 0 or math.max((field.wrappedWidth ) - field.width, 0),
(not field:isMultiline() ) and 0 or math.max(((#field.wrappedText-1)*lineDist+fontH) - field.height, 0)
end
-- speedX, speedY = field:getMouseScrollSpeed( )
-- speedX = field:getMouseScrollSpeedX( )
-- speedY = field:getMouseScrollSpeedY( )
function InputField.getMouseScrollSpeed(field)
return field.mouseScrollSpeedX, field.mouseScrollSpeedY
end
function InputField.getMouseScrollSpeedX(field)
return field.mouseScrollSpeedX
end
function InputField.getMouseScrollSpeedY(field)
return field.mouseScrollSpeedY
end
--
-- field:setMouseScrollSpeed( speedX [, speedY=speedX ] )
-- field:setMouseScrollSpeedX( speedX )
-- field:setMouseScrollSpeedY( speedY )
--
-- Also see setWheelScrollSpeed().
--
function InputField.setMouseScrollSpeed(field, speedX, speedY)
speedY = speedY or speedX