-
Notifications
You must be signed in to change notification settings - Fork 3
/
textrender.lua
2714 lines (2160 loc) · 89.8 KB
/
textrender.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
-- textwrap.lua
--
-- Version 3.0
--
-- Copyright (C) 2014 David I. Gross. All Rights Reserved.
--
-- This software is is protected by the author's copyright, and may not be used, copied,
-- modified, merged, published, distributed, sublicensed, and/or sold, without
-- written permission of the author.
--
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
--
--[[
This version renders lines of text, then aligns them left/right/center. The previous version
could not do this with sub-elements in a block, e.g.
<p>my text <span>is cool</span> but not hot.</p>
would have failed.
--]]
--[[
Create a block text, wrapped to fit a rectangular boundary.
Formats text using basic HTML.
@return textblock A display group containing the wrapped text.
Pass params in a table, e.g. options = { ... }
Inside of the options table:
@param hyperlinkFillColor An RGBa string, e.g. "150,200,120,50", of the color for a box around the hyperlinks.
@param hyperlinkTextColor An RGBa string, e.g. "150,200,120,50", of the color for hyperlink text.
]]
-- TESTING
local testing = false
-- Don't use the line-wrap cache
local noCache = false
if (noCache) then
print ("TEXTWRAP: CACHING TURNED OFF!")
end
-- Main var for this module
local T = {}
local funx = require ("funx")
local html = require ("html")
local entities = require ("entities")
local sqlite3 = require "sqlite3"
local json = require("json")
local crypto = require "crypto"
-- functions
local max = math.max
local min = math.min
local lower = string.lower
local upper = string.upper
local gmatch = string.gmatch
local gsub = string.gsub
local strlen = string.len
local substring = string.sub
local find = string.find
local floor = math.floor
local gfind = string.gfind
-- shortcuts to my functions
local anchor = funx.anchor
local anchorZero = funx.anchorZero
local trim = funx.trim
local rtrim = funx.rtrim
local ltrim = funx.ltrim
local stringToColorTable = funx.stringToColorTable
local setFillColorFromString = funx.setFillColorFromString
local split = funx.split
local setCase = funx.setCase
local fixCapsForReferencePoint = funx.fixCapsForReferencePoint
-- Useful constants
local OPAQUE = 255
local TRANSPARENT = 0
-- Be sure a caches dir is set up inside the system caches
local textWrapCacheDir = "textwrap"
--funx.mkdir (textWrapCacheDir, "",false, system.CachesDirectory)
-- testing function
local function showTestLine(group, y, isFirstTextInBlock, i)
local q = display.newLine(group, 0,y,200,y)
i = i or 1
if (isFirstTextInBlock) then
q:setStrokeColor(250,0,0)
else
q:setStrokeColor(80 * i,80 * i, 80)
end
q.strokeWidth = 2
end
-- Use "." at the beginning of a line to add spaces before it.
local usePeriodsForLineBeginnings = false
-------------------------------------------------
-- font metrics module, for knowing text heights and baselines
-- variations, for knowing the names of font variations, e.g. italic
-- Corona doesn't do this so we must.
-------------------------------------------------
local fontMetricsLib = require("fontmetrics")
local fontMetrics = fontMetricsLib.new()
local fontFaces = fontMetrics.metrics.variations or {}
-------------------------------------------------
-- HTML/XML tags that are inline tags, e.g. <b>
-- This table can be used to check if a tag is an inline tag:
-- if (inline[tag]) then...
-------------------------------------------------
--[[
local inline = {
a = true,
abbr = true,
acronym = true,
applet = true,
b = true,
basefont = true,
bdo = true,
big = true,
br = true,
button = true,
cite = true,
code = true,
dfn = true,
em = true,
font = true,
i = true,
iframe = true,
img = true,
input = true,
kbd = true,
label = true,
map = true,
object = true,
q = true,
s = true,
samp = true,
select = true,
small = true,
span = true,
strike = true,
strong = true,
sub = true,
sup = true,
textarea = true,
tt = true,
u = true,
var = true,
}
--]]
--------------------------------------------------------
-- Common functions redefined for speed
--------------------------------------------------------
--------------------------------------------------------
-- Convert pt values to pixels, for font sizing.
-- Basically, I think we should just use the pt sizing as
-- px sizing. Or, we could use the screen pixel sizing?
-- We could use funx.getDeviceMetrics()
-- Using 72 pixels per point:
-- 12pt => 72/72 * 12pt => 12px
-- 12pt => 132/72 * 12pt => 24px
--------------------------------------------------------
local function convertValuesToPixels (t, deviceMetrics)
t = trim(t)
local _, _, n = find(t, "^(%d+)")
local _, _, u = find(t, "(%a%a)$")
if (u == "pt" and deviceMetrics) then
n = n * (deviceMetrics.ppi/72)
end
return tonumber(n)
end
--------------------------------------------------------
-- Trim based on alignment
--------------------------------------------------------
local function trimToAlignment(t,a)
if (a == "Right") then
t = rtrim(t)
elseif (a == "Center") then
t = trim(t)
else
t = ltrim(t)
end
return t
end
--------------------------------------------------------
-- Get tag formatting values
--------------------------------------------------------
local function getTagFormatting(fontFaces, tag, currentfont, variation, attr)
local font, basename
------------
-- If the fontfaces list has our font transformation, use it,
-- otherwise try to figure it out.
------------
local function getFontFace (basefont, variation)
local newFont = ""
if (fontFaces[basefont .. variation]) then
newFont = fontFaces[basefont .. variation]
else
-- Some name transformations...
-- -Roman becomes -Italic or -Bold or -BoldItalic
newFont = basefont:gsub("-Roman","") .. variation
end
return newFont
end
------------
if (type(currentfont) ~= "string") then
return {}
end
local basefont = gsub(currentfont, "%-.*$","")
--local _,_,variation = find(currentfont, "%-(.-)$")
variation = variation or ""
local format = {}
if (tag == "em" or tag == "i") then
if (variation == "Bold" or variation == "BoldItalic") then
format.font = getFontFace (basefont, "-BoldItalic")
format.fontvariation = "BoldItalic"
else
format.font = getFontFace (basefont, "-Italic")
format.fontvariation = "Italic"
--print (basefont, format.font)
end
elseif (tag == "strong" or tag == "b") then
if (variation == "Italic" or variation == "BoldItalic") then
format.font = getFontFace (basefont, "-BoldItalic")
format.fontvariation = "BoldItalic"
else
format.font = getFontFace (basefont, "-Bold")
format.fontvariation = "Bold"
end
elseif (tag == "font" and attr) then
format = attr
format.font = attr.name
--format.basename = attr.name
elseif (attr) then
-- get style info
local style = {}
local p = split(attr.style, ";", true) or {}
for i,j in pairs( p ) do
local c = split(j,":",true)
if (c[1] and c[2]) then
style[c[1]] = c[2]
end
end
format = funx.tableMerge(attr, style)
--format.basename = attr.font
end
return format
end
--------------------------------------------------------
-- Break text into paragraphs using <p>
-- Any carriage returns inside any element is remove!
local function breakTextIntoParagraphs(text)
-- remove CR inside of <p>
local count = 1
while (count > 0) do
text, count = text:gsub("(%<.-)%s*[\r\n]%s*(.-<%/.->)","%1 %2")
end
text = text:gsub("%<p(.-)%>","<p%1>\r")
text = text:gsub("%<%/p%>","</p>\r")
return text
end
--------------------------------------------------------
-- Convert <h> tags into paragraph tags but set the style to the header, e.g. h1
-- Hopefully, the style will exist!
-- @param tag, attr
-- @return tag, attr
local function convertHeaders(tag, attr)
if ( tag and find(tag, "[hH]%d") ) then
attr.class = lower(tag)
tag = "p"
end
return tag, attr
end
--------------------------------------------------------
-- CACHE of textwrap!!!
-- The closing of the database is done when the app quits.
--------------------------------------------------------
--- Fix single quotes for SQLite
-- Single quotes become double single-quotes, ' -> ''
local function fixQuotes(s)
--s = string.gsub(s, "'", "''")
s = s or ""
s = string.gsub(s, [[']], [['']])
return s
end
--- Implent the db:first_row command
-- @param db The database handle
-- @param cmd A text SQL command, e.g. "SELECT * FROM books"
local function first_row(db, cmd)
local row = false
local a
for a in db:nrows(cmd) do
return a
end
return row
end
local function openCacheDB()
-- Create the new DB
--print ("not T.db or not T.db:isopen()", not T.db or not T.db:isopen())
if ( not T.db or not T.db:isopen() ) then
local path = system.pathForFile( "textcache.db", system.CachesDirectory )
local db = sqlite3.open( path )
-- Be sure the table exists
local cmd = "CREATE TABLE IF NOT EXISTS caches (id TEXT PRIMARY KEY, cache TEXT, baseline TEXT );"
db:exec( cmd )
-- save in the module table
T.db = db
--print ("openCacheDB: Opened")
end
--T.cacheToDB = true
end
-- Install a closing function for the caching database into the applicationExit
local function closeDB( event )
if event.type == "applicationExit" then
if T.db and T.db:isopen() then
T.db:close()
print ("closeDB: Close")
end
end
end
local function saveTextWrapToCache(id, cache, baselineCache, cacheDir)
--print ("saveTextWrapToCache: ID", id)
if (T.cacheToDB) then
if ( not T.db or not T.db:isopen() ) then
openCacheDB()
end
local cmd = "INSERT INTO 'caches' (id,cache,baseline) VALUES ('" ..id .. "','" .. fixQuotes(json.encode(cache)) .. "','" .. fixQuotes(json.encode(baselineCache)) .. "');"
T.db:exec( cmd )
else
if (cacheDir and cacheDir ~= "") then
funx.mkdirTree (cacheDir .. "/" .. textWrapCacheDir, system.CachesDirectory)
--funx.mkdir (cacheDir .. "/" .. textWrapCacheDir, "",false, system.CachesDirectory)
-- Developing: delete the cache
-- Add in the baseline cache
local c = { wrapCache = cache, baselineCache = baselineCache, }
if (true) then
local fn = cacheDir .. "/" .. textWrapCacheDir .. "/" .. id .. ".json"
funx.saveTable(c, fn , system.CachesDirectory)
end
end
end
end
--------------------------------------------------------
local function loadTextWrapFromCache(id, cacheDir)
if (T.cacheToDB) then
if ( not T.db or not T.db:isopen() ) then
openCacheDB()
end
--print ("loadTextWrapFromCache: ID",id)
local cmd = "SELECT * FROM caches WHERE id='" .. id .. "';"
local row = first_row(T.db, cmd)
if (row ) then
local c = { wrapCache = json.decode(row.cache), baselineCache = json.decode(row.baseline), }
return c
else
--print ("NOT CACHED: ID",id)
return false
end
else
if (cacheDir) then
local fn = cacheDir .. "/" .. textWrapCacheDir .. "/" .. id .. ".json"
if (funx.fileExists(fn, system.CachesDirectory)) then
local c = funx.loadTable(fn, system.CachesDirectory)
--print ("cacheTemplatizedPage: found page "..fn )
return c
end
end
return false
end
end
--------------------------------------------------------
local function iteratorOverCacheText (t)
local i = 0
local n = table.getn(t)
return function ()
i = i + 1
if i <= n then
return t[i], ""
end
end
end
-- Create a cache chunk table from either an existing cache entry or for a chunk of XML for the cache table.
-- A chunk may have multiple lines.
-- Weird to use separate tables for each attribute? But this allows us to iterate over the words
-- instead of over the cache entry, allowing us to use the existing for-do structure.
local function newCacheChunk ( cachedChunk )
cachedChunk = {
text = {},
item = {},
}
return cachedChunk
end
-- Get a chunk entry from the cache table
local function getCachedChunkItem(t, i)
return t.item[i]
end
local function updateCachedChunk (t, args)
local i = args.index or 1
-- Write all in one entry
t.item[i] = args
-- Write text table for iteration
t.text[i] = args.text
return t
end
--------------------------------------------------------
-- CACHE: Clear all caches
local function clearAllCaches(cacheDir)
if (cacheDir and cacheDir ~= "") then
funx.rmDir (cacheDir .. "/" .. textWrapCacheDir, system.CachesDirectory, true) -- keep structure, delete contents
end
-- Remove DB file
local path = system.pathForFile( "textcache.db", system.CachesDirectory )
local results, reason = os.remove( path )
end
--------------------------------------------------------
-- Make a box that is the right size for touching.
-- Problem is, the font sizes are so big, they overlap lines.
-- This box will be a nicer size.
-- NOte, there is no stroke, so we don't x+1/y+1
local function touchableBox(g, referencePoint, x,y, width, height, fillColor)
local touchme = display.newRect(0,0,width, height)
setFillColorFromString(touchme, fillColor)
g:insert(touchme)
anchor(touchme, referencePoint)
touchme.x = x
touchme.y = y
touchme:toBack()
return touchme
end
--------------------------------------------------------
-- Add a tap handler to the object and pass it the tag attributes, e.g. href
-- @param obj A display object, probably text
-- @param id String: ID of the object?
-- @param attr table: the attributes of the tag, e.g. href or target, HTML stuff, !!! also the text tapped should be in "text" in attr
-- @param handler table A function to handle link values, like "goToPage". These should work with the button handler in slideView
local function attachLinkToObj(obj, attr, handler)
local function comboListener( event )
local object = event.target
if not ( event.phase ) then
local attr = event.target._attr
--print( "Tap event on word!", attr.text)
if (handler) then
handler(event)
--print( "Tap event on word!", attr.text)
--print ("Tapped on ", attr.text)
else
print ("WARNING: textwrap:attachLinkToObj says no handler set for this event.")
end
end
return true
end
obj.id = attr.id or (attr.id or "")
obj._attr = attr
obj:addEventListener( "tap", comboListener )
obj:addEventListener( "touch", comboListener )
end
------------------------------------------------
-- Get the ascent of a font, which is how we position text.
-- Set InDesign to position from the box top using leading
------------------------------------------------
local function getFontAscent(baselineCache, font, size)
local baseline, descent, ascent
if (baselineCache[font] and baselineCache[font][size]) then
baseline, descent, ascent = unpack(baselineCache[font][size])
else
local fontInfo = fontMetrics.getMetrics(font)
-- Get the iOS bounding box size for this particular font!!!
-- This must be done for each size and font, since it changes unpredictably
local samplefont = display.newText("X", 0, 0, font, size)
local boxHeight = samplefont.height
samplefont:removeSelf()
samplefont = nil
-- Set the new baseline from the font metrics
baseline = boxHeight + (size * fontInfo.descent)
ascent = fontInfo.ascent * size
-- This should adjust the font above/below the baseline to reflect differences in fonts,
-- putting them all on the same line.
-- This amount is above the bottom of the rendered font box
descent = (size * fontInfo.descent)
if (not baselineCache[font]) then
baselineCache[font] = {}
end
baselineCache[font][size] = { baseline, descent, ascent }
end
return baseline, descent, ascent
end
-- ------------------------------------------------------
-- Finished lines, aligns them left/right/center
-- ------------------------------------------------------
local function alignRenderedLines(lines, stats)
for i,_ in pairs(lines) do
if (stats[i].textAlignment == "Right") then
lines[i].anchorX = 1
lines[i].x = stats[i].currentWidth + stats[i].leftIndent + stats[i].firstLineIndent
elseif (stats[i].textAlignment == "Center") then
lines[i].anchorX = 0.5
-- currentWidth compensates for margins
local c = stats[i].leftIndent + stats[i].firstLineIndent + (stats[i].currentWidth)/2
lines[i].x = c
else
lines[i].x = stats[i].leftIndent + stats[i].firstLineIndent
end
end
return lines
end
--------------------------------------------------------
-- Wrap text to a width
-- Blank lines are ignored.
-- *** To show a blank line, put a space on it.
-- The minCharCount is the number of chars to assume are in the line, which means
-- fewer calculations to figure out first line's.
-- It starts at 25, about 5 words or so, which is probabaly fine in 99% of the cases.
-- You can raise lower this for very narrow columns.
-- opacity : 0.0-1.0
-- "minWordLen" is the shortest word a line can end with, usually 2, i.e, don't end with single letter words.
-- NOTE: the "floor" is crucial in the y-position of the lines. If they are not integer values, the text blurs!
--
-- Look for CR codes. Since clumsy XML, such as that from inDesign, cannot include line breaks,
-- we have to allow for a special code for line breaks: [[[cr]]]
--------------------------------------------------------
local function autoWrappedText(text, font, size, lineHeight, color, width, alignment, opacity, minCharCount, targetDeviceScreenSize, letterspacing, maxHeight, minWordLen, textstyles, defaultStyle, cacheDir)
-- Set the width/height of screen. Might have changed from when module loaded due to orientation change
local screenW, screenH = display.contentWidth, display.contentHeight
local viewableScreenW, viewableScreenH = display.viewableContentWidth, display.viewableContentHeight
local screenOffsetW, screenOffsetH = display.contentWidth - display.viewableContentWidth, display.contentHeight - display.viewableContentHeight
local midscreenX = screenW*(0.5)
local midscreenY = screenH*(0.5)
local baseline = 0
local descent = 0
local ascent = 0
if (testing) then
print ("autoWrappedText: testing flag is true.")
print ("----------")
--print (text.text)
--print ("----------")
end
-- table for useful settings. We need fewer upvalues, and this is a way to do that
local settings = {}
settings.deviceMetrics = funx.getDeviceMetrics( )
settings.minWordLen = 2
settings.isHTML = false
settings.useHTMLSpacing = false
-- handler for links
settings.handler = {}
--if text == '' then return false end
local result = display.newGroup()
-- Get from the funx textStyles variable.
local textstyles = textstyles or {}
local hyperlinkFillColor = "0,0,255,"..TRANSPARENT
local hyperlinkTextColor -- "0,0,255,"..OPAQUE
T.cacheToDB = true
-- If table passed, then extract values
if (type(text) == "table") then
font = text.font
size = text.size
lineHeight = text.lineHeight
color = text.color
width = text.width
alignment = text.textAlignment
opacity = text.opacity
minCharCount = text.minCharCount
targetDeviceScreenSize = text.targetDeviceScreenSize
letterspacing = text.letterspacing
maxHeight = text.maxHeight
settings.minWordLen = text.minWordLen
textstyles = text.textstyles or textstyles
settings.isHTML = text.isHTML or false
settings.useHTMLSpacing = text.useHTMLSpacing or false
defaultStyle = text.defaultStyle or ""
cacheDir = text.cacheDir
settings.handler = text.handler
hyperlinkFillColor = text.hyperlinkFillColor or hyperlinkFillColor
hyperlinkTextColor = text.hyperlinkTextColor
testing = testing or text.testing
-- Default is true, allow set to false here
if (text.cacheToDB ~= nil) then
T.cacheToDB = text.cacheToDB
end
-- restore text
text = text.text
end
-- If no text, do nothing.
if (not text) then
return result
end
-- Be sure text isn't nil
text = text or ""
-- Caching values
-- Name the cache with the width, too, so the same text isn't wrapped to the wrong
-- width based on the cache.
local textUID = 0
local textwrapIsCached = false
local cache = { { text = "", width = "", } }
local cacheIndex = 1
-- Cache of font baselines for different sizes, as drawing on screen
local baselineCache = {}
-- Interpret the width so we can get it right caching:
width = funx.percentOfScreenWidth(width) or display.contentWidth
-- TESTING
if (noCache) then
cacheDir = nil
T.cacheToDB = false
end
-- Default is to cache using the sqlite3 database.
-- If cacheToDB is FALSE, then we fall back on the text file cacheing
-- if cacheDir is set.
if ( T.cacheToDB or (cacheDir and cacheDir ~= "") ) then
--textUID = "cache"..funx.checksum(text).."_"..tostring(width)
textUID = crypto.digest( crypto.md4, tostring(width) .. text )
--print ( tostring(width) .. text )
local c = loadTextWrapFromCache(textUID, cacheDir)
if (c) then
textwrapIsCached = true
cache = c.wrapCache
baselineCache = c.baselineCache
--print ("***** CACHE LOADED")
--funx.dump(cache)
end
end
-- default
settings.minWordLen = settings.minWordLen or 2
text = text or ""
if (text == "") then
return result
end
-- alignment is the initial setting for the text block, but sub-elements may differ
local textAlignment = fixCapsForReferencePoint(alignment) or "Left"
-- Just in case
text = tostring(text)
--[[
------------------------
-- HANDLING LINE BREAKS:
-- This is also a standard XML paragraph separator used by Unicode
See: http://www.fileformat.info/info/unicode/char/2028/index.htm
Unicode introduced separator <textblock>
<text>
Fish are ncie to me.
I sure like them!
They're great!
</text>
</textblock>
In an attempt to simplify the several newline characters used in legacy text, UCS introduces its own newline characters to separate either lines or paragraphs: U+2028 line separator (HTML: 
 LSEP) and U+2029 paragraph separator (HTML: 
 PSEP). These characters are text formatting only, and not <control> characters.
Unicode Decimal Code 

Symbol Name: Paragraph Separator
Html Entity:
Hex Code: 

Decimal Code: 

Unicode Group: General Punctuation
InDesign also uses ” instead of double-quote marks when exporting quotes in XML. WTF?
]]
-- This is ”
--local doubleRtQuote
-- Strip InDesign end-of-line values, since we now use a kind of HTML from
-- InDesign.
local lineSeparatorCode = "%E2%80%A8"
local paragraphSeparatorCode = "%E2%80%A9" -- This is ;

text = text:gsub(funx.unescape(lineSeparatorCode),"")
text = text:gsub(funx.unescape(paragraphSeparatorCode),"")
-- Convert entities in the text, .e.g. "–"
if (not settings.isHTML) then
text = entities.unescape(text)
end
--- THEN, TOO, THERE'S MY OWN FLAVOR OF LINE BREAK!
-- Replace our special line break code one could use in the source text with an HTML return!
text = text:gsub("%[%[%[br%]%]%]","<br>")
------------------------
maxHeight = tonumber(maxHeight) or 0
-- Minimum number of characters per line. Start low.
--local minLineCharCount = minCharCount or 5
-- This will cause problems with Android
-- font = font or "Helvetica" --native.systemFont
-- size = tonumber(size) or 12
-- color = color or {0,0,0,0}
-- width = funx.percentOfScreenWidth(width) or display.contentWidth
-- opacity = funx.applyPercent(opacity, OPAQUE) or OPAQUE
-- targetDeviceScreenSize = targetDeviceScreenSize or screenW..","..screenH
-- case can be ALL_CAPS or UPPERCASE or LOWERCASE or NORMAL
--local case = "NORMAL";
-- Space before/after paragraph
--local spaceBefore = 0
--local spaceAfter = 0
--local firstLineIndent = 0
--local currentFirstLineIndent = 0
--local leftIndent = 0
--local rightIndent = 0
--local bullet = "●"
-- Combine a bunch of local variables into a settings array because we have too many "upvalues"!!!
settings.font = font or "Helvetica" --native.systemFont
-- used to restore from bold, bold-italic, etc. since some names aren't clear, e.g. FoozleSemiBold might be the only bold for a font
settings.fontvariation = ""
settings.size = tonumber(size) or 12
settings.color = color or {0,0,0,255}
settings.width = width
settings.opacity = funx.applyPercent(opacity, OPAQUE) or OPAQUE
settings.targetDeviceScreenSize = targetDeviceScreenSize or screenW..","..screenH
settings.case = "none"
settings.decoration = "none"
settings.spaceBefore = 0
settings.spaceAfter = 0
settings.firstLineIndent = 0
settings.currentFirstLineIndent = 0
settings.leftIndent =0
settings.rightIndent = 0
settings.bullet = "●"
settings.minLineCharCount = minCharCount or 5
settings.maxHeight = tonumber(maxHeight) or 0
lineHeight = funx.applyPercent(lineHeight, settings.size) or floor(settings.size * 1.3)
-- Scaling for device
-- Scale the text proportionally
-- We don't need this if we set use the Corona Dynamic Content Scaling!
-- Set in the config.lua
-- Actually, we do, for the width, because that doesn't seem to be shrinking!
-- WHAT TO DO? WIDTH DOES NOT ADJUST, AND WE DON'T KNOW THE
-- ACTUAL SCREEN WIDTH. WHAT NOW?
local scalingRatio = funx.scaleFactorForRetina()
local currentLine = ''
local lineCount = 0
-- x is start of line
local lineY = 0
local x = 0
local defaultSettings = {}
---------------------------------------------------------------------------
-- Style setting functions
---------------------------------------------------------------------------
-- get all style settings so we can save them in a table
local function getAllStyleSettings ()
local params = {}
params.font = settings.font
params.fontvariation = settings.fontvariation
-- font size
params.size = settings.size
params.minLineCharCount = settings.minLineCharCount
params.lineHeight = lineHeight
params.color = settings.color
params.width = settings.width
params.opacity = settings.opacity
-- case (uppercase/lowercase)
params.case = settings.case
if (params.case == "all_caps") then
params.case = "uppercase"
end
-- space before paragraph
params.spaceBefore = settings.spaceBefore or 0
-- space after paragraph
params.spaceAfter = settings.spaceAfter or 0
-- First Line Indent
params.firstLineIndent = settings.firstLineIndent
-- Left Indent
params.leftIndent = settings.leftIndent
-- Right Indent
params.rightIndent = settings.rightIndent
params.textAlignment = textAlignment
return params
end
-- Set style settings which were saved using the function above.
-- These are set using the values from internal variables, e.g. font or size,
-- NOT from the style sheet parameters.
local function setStyleSettings (params)
if (params.font ) then settings.font = params.font end
if (params.fontvariation) then settings.fontvariation = params.fontvariation end
-- font size
if (params.size ) then settings.size = params.size end
if (params.minLineCharCount ) then settings.minLineCharCount = params.minLineCharCount end
if (params.lineHeight ) then lineHeight = params.lineHeight end
if (params.color ) then
settings.color = params.color
end
if (params.width ) then settings.width = params.width end
if (params.opacity ) then settings.opacity = params.opacity end
-- case (upper/normal)
if (params.case ) then settings.case = params.case end
-- space before paragraph
if (params.spaceBefore ) then settings.spaceBefore = tonumber(params.spaceBefore) end
-- space after paragraph
if (params.spaceAfter ) then settings.spaceAfter = tonumber(params.spaceAfter) end
-- First Line Indent
if (params.firstLineIndent ) then params.firstLineIndent = tonumber(settings.firstLineIndent) end
-- Left Indent
if (params.leftIndent ) then settings.leftIndent = tonumber(params.leftIndent) end
-- Right Indent
if (params.rightIndent ) then settings.rightIndent = tonumber(params.rightIndent) end
if (params.textAlignment ) then textAlignment = params.textAlignment end
--[[
if (lower(textAlignment) == "right") then
x = settings.width - settings.rightIndent
settings.currentFirstLineIndent = 0
settings.firstLineIndent = 0
elseif (lower(textAlignment) == "left") then
x = 0
else
local currentWidth = settings.width - settings.leftIndent - settings.rightIndent -- settings.firstLineIndent
x = floor(currentWidth/2) --+ settings.firstLineIndent
end
]]
end
-- set style from params in a ### set, ... command line in the text
-- This depends on the closure for variables, such as font, size, etc.
local function setStyleFromCommandLine (params)
-- font
if (params[2] and params[2] ~= "") then settings.font = trim(params[2]) end
-- font size
if (params[3] and params[3] ~= "") then
settings.size = tonumber(params[3])
--size = scaleToScreenSize(tonumber(params[3]), scalingRatio)
-- reset min char count in case we loaded a BIG font
settings.minLineCharCount = minCharCount or 5
end
-- line height
if (params[4] and params[4] ~= "") then
lineHeight = tonumber(params[4])
--lineHeight = scaleToScreenSize(tonumber(params[4]), scalingRatio)
end
-- color
if ((params[5] and params[5] ~= "") and (params[6] and params[6] ~= "") and (params[7] and params[7] ~= "")) then
-- Handle opacity as RGBa or HDRa, not by itself
if (params[9] and params[9] ~= "") then
settings.color = {tonumber(params[5]), tonumber(params[6]), tonumber(params[7]), funx.applyPercent(params[9], OPAQUE) }
else
settings.color = {tonumber(params[5]), tonumber(params[6]), tonumber(params[7], OPAQUE) }
end
end
-- width of the text block
if (params[8] and params[8] ~= "") then
if (params[8] == "reset" or params[8] == "r") then
settings.width = defaultSettings.width
else
settings.width = tonumber(funx.percentOfScreenWidth(params[8]) or defaultSettings.width)