-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtextrender.lua
More file actions
3387 lines (2701 loc) · 114 KB
/
Copy pathtextrender.lua
File metadata and controls
3387 lines (2701 loc) · 114 KB
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
-- textrender.lua
--
-- Version 3.1.2
--
-- Copyright (C) 2015 David I. Gross. All Rights Reserved.
--
--[[
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
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.
]]
--display.setDrawMode( "wireframe", false )
-- TESTING
-- Check the GLOBAL testing variable
local testing = _TESTING
local noCache = _NOCACHE
if (testing) then
print ("**** WARNING: textrender: TESTING ON ****")
end
if (noCache) then
print ("**** WARNING: textrender: CACHING TURNED OFF FOR TESTING!!!! ****")
end
-- Main var for this module
local T = {}
local pathToModule = "scripts/textrender/"
T.path = pathToModule
-- funx must be installed in scripts folder
local funx = require ("scripts.funx")
local html = require ("scripts.textrender.html")
local entities = require ("scripts.textrender.entities")
local fontMetricsLib = require("scripts.textrender.fontmetrics")
local sqlite3 = require ( "sqlite3" )
local json = require( "json" )
local crypto = require ( "crypto" )
local widget = require( "widget" )
-- functions
local abs = math.abs
local ceil = math.ceil
local find = string.find
local floor = math.floor
local gfind = string.gfind
local gmatch = string.gmatch
local gsub = string.gsub
local lower = string.lower
local max = math.max
local min = math.min
local strlen = string.len
local substring = string.sub
local upper = string.upper
-- 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
local isPercent = funx.isPercent
local loadImageFile = funx.loadImageFile
local applyPercent = funx.applyPercent
-- Set the width/height of screen. Might have changed from when module loaded due to orientation change
local screenW, screenH = display.contentWidth, display.contentHeight
-- 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(100,250,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 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,
}
--]]
local isBlockTag = {
address = true,
blockquote = true,
center = true,
dir = true, div = true, dl = true,
fieldset = true, form = true,
h1 = true, h2 = true, h3 = true, h4 = true, h5 = true, h6 = true,
hr = true,
isindex = true,
-- Note, we treat <li> as a block, which is not standard HTML
li = true,
menu = true,
noframes = true,
ol = true,
p = true,
pre = true,
table = true,
ul = true,
}
local isListTag = {
ol = true,
ul = true,
}
--------------------------------------------------------
-- Common functions redefined for speed
--------------------------------------------------------
-- Get the yOffset for the first line of the text for proper positioning of the
-- line of text. This is set for the Ascent (not cap-height).
-- My formula matches InDesign, where for a text block, the Baseline Options, Offset = ascent
local function GetYAdjustment(text, font)
-- Old method
--local yAdjustment = ( (size / sampledFontSize ) * textHeight) - height
local metrics = graphics.getFontMetrics( font, text.size )
yAdjustment = metrics.height - text.height
-- Alternative method: To align to the Cap Height:
--yAdjustment = text.baselineOffset
return yAdjustment
end
--------------------------------------------------------
-- Convert CSS relational font sizings to percent
-- e.g. x-large = 150%
-- Return the new font size based on the one give
-- If no keyword found, then return current fontsize
-- Source: http://www.trishasdesignstudio.com/font-size-conversion-chart.asp
local function keywordFontsizeRatio (keyword)
local sizes = {
xxsmall = 0.55,
xsmall = 0.625,
small = 0.8,
medium = 1,
large = 1.2,
xlarge = 1.5,
xxlarge = 2.55,
}
return (sizes[lower(keyword:gsub("%-",""))] or 1)
end
local function convertCSSFontsizeKeyword(keyword, fontsize)
fontsize = fontsize or 14 -- default to 14px if something goes wrong
return fontsize * keywordFontsizeRatio(keyword)
end
--------------------------------------------------------
-- Convert pt values to pixels, for font sizing.
-- We use the font height for 1em.
-- 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
-- @param t = [string] The new font size, including units or as text, e.g. 'small'
-- @param fontsize = [number] Fallback font-size, usually whatever it current is before we try to change it
--------------------------------------------------------
local function convertValuesToPixels (t, fontsizeFallback, deviceMetrics)
if (t ~= nil) then
t = trim(t)
-- Get the numeric part of the size, e.g. 15pt -> 15
local _, _, n = find(t, "^(%--%d+)")
-- Get the units, e.g. pt or px, e.g. 15pt -> pt
local _, _, u = find(t, "(%a%a)$")
-- Handle textual fontsizing, e.g. "x-large"
--print ("A -----> ", t, fontsizeFallback)
n = convertCSSFontsizeKeyword(t, n)
--print ("B -----> ", t, n)
if (tonumber(n) == 0) then
n = fontsizeFallback
end
if ((u == "pt" ) and deviceMetrics) then
n = n * (deviceMetrics.ppi/72)
elseif (u == "em" and deviceMetrics) then
n = n * fontsize * (deviceMetrics.ppi/72)
end
--print ("C Result:",n)
--print (" ")
return tonumber(n)
end
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 ( tag == "sup") then
format.scale = "70%"
format.yOffset = "50%"
elseif ( tag == "sub") then
format.scale = "70%"
format.yOffset = "-10%"
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(tostring(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
-- if ( pcall(db:nrows(cmd) )) then
-- print ("OK")
-- else
-- print ("SQLITE DATABASE ERROR:" , pcall(db:nrows(cmd)) )
-- end
--
for a in db:nrows(cmd) do
return a
end
return row
end
----------------------------------------------------------
-- Made a text block a scrolling text block.
-- local scrollingblock = textblock:fitBlockToHeight ( options )
----------------------------------------------------------
local function fitBlockToHeight(textblock, options )
local maxheight = options.maxVisibleHeight or screenH
local scrollingFieldIndicatorActive = options.scrollingFieldIndicatorActive
local parentTouchObject = options.parentTouchObject
local h = funx.percentOfScreenHeight(maxheight)
if (not h) then
h = screenH
end
-- width and height must be a multiple of four
h = ceil( h/4 ) * 4
local w = funx.percentOfScreenWidth(textblock.width)
if (not w) then
w = screenW
end
-- width and height must be a multiple of four
w = ceil( w/4 ) * 4
-- Set a flag
local textBlockIsScrolling = false
-- This will be either the scrolling block, or just the textblock as it was
local finalTextBlock
if ( textblock.height > h ) then
-- Listener function to listen to scrollView events
-- However, this does NOT pass the touch event on even if we return false.
-- Dammit.
local prevPosX, prevPosY
local startTime
local minTapTime = 10
local maxTapTime = 200
local swipeDistance = 40
local dragDistance, dragDistanceX, dragDistanceY
--local swipeHorizontal, swipeVertical
local dX, dY
local function scrollViewListener( event )
--print ("event.phase",event.phase)
local phase = event.phase
if ( phase == "moved" ) then
local dx = math.abs( ( event.x - event.xStart ) )
-- If the touch on the object has moved more than 10 pixels,
-- pass focus back to the parent object so it can continue doing its thing,
-- usually scrolling
if ( parentTouchObject and dx > 10 ) then
parentTouchObject:takeFocus( event )
end
end
return true
end
-- Create a new ScrollView widget:
-- The scrolling handle isn't visible unless we provide some extra space for it.
-- We use a background but make it see-through, so that we can scroll from
-- by swiping inside the rect of the scrollview
--local correctForScrollHandle = 12
-- customScrollBar.options = true/false
local scrollBarOptions = nil
--[[
-- The custom scrollbar does not work in the current widgets!
if options.customScrollBar then
local scrollBarOpt = {
width = 20,
height = 20,
numFrames = 3,
sheetContentWidth = 20,
sheetContentHeight = 60,
}
local scrollBarSheet = graphics.newImageSheet( pathToModule.."assets/widget-scrollbar.png", scrollBarOpt )
scrollBarOptions = {
sheet = scrollBarSheet, --reference to the image sheet
frameWidth = 20,
frameHeight = 20,
topFrame = 1, --number of the "top" frame
middleFrame = 2, --number of the "middle" frame
bottomFrame = 3 --number of the "bottom" frame
}
end
--]]
local maskFileName = funx.makeMask(w,h, "masks")
local args = {
width = w,--+correctForScrollHandle,
height = h,
scrollWidth = w,--+correctForScrollHandle,
scrollHeight = h,
hideScrollBar = false,
maskFile = maskFileName,
baseDir = system.CachesDirectory,
listener = scrollViewListener,
hideBackground = options.hideBackground,
backgroundColor = options.backgroundColor or {1,1,1},
topPadding = 0,
bottomPadding = 0,
horizontalScrollDisabled = true,
scrollBarOptions = scrollBarOptions,
}
local scrollView = widget.newScrollView(args)
-- Create an object and place it inside of ScrollView:
scrollView:insert( textblock )
finalTextBlock = scrollView
-- Create an invisible rect so we can swipe anywhere in the text,
-- instead of only on text itself.
local objForSwipe = display.newRect(textblock, 0,0,textblock.contentWidth,textblock.contentHeight)
funx.anchor(objForSwipe, "TopLeft")
objForSwipe.x = 0
objForSwipe.y = 0
objForSwipe:setFillColor(250,0,0,0)
objForSwipe:toBack()
if (scrollingFieldIndicatorActive) then
-- Add an icon to indicate this is a scrolling text field,
-- Or add icons top/bottom, depending on settings
-- The icon should disappear after usage(?)
local scrollingFieldIndicator, scrollingFieldIndicatorUp, scrollingFieldIndicatorDown
if (options.scrollingFieldIndicatorLocation == "over") then
scrollingFieldIndicator = loadImageFile(options.scrollingFieldIndicatorIconOver)
local s = min(w, h) - 10
local r = s / min(scrollingFieldIndicator.width, scrollingFieldIndicator.height)
funx.anchor(scrollingFieldIndicator, "TopCenter")
scrollingFieldIndicator:scale(r,r)
scrollView:insert( scrollingFieldIndicator )
scrollView.Indicator = scrollingFieldIndicator
scrollingFieldIndicator.x = w/2
scrollingFieldIndicator.y = 0
elseif (options.scrollingFieldIndicatorLocation == "bottom") then
scrollingFieldIndicatorDown = loadImageFile(options.scrollingFieldIndicatorIconDown)
scrollView:insert( scrollingFieldIndicatorDown )
scrollView.downIndicator = scrollingFieldIndicatorDown
funx.anchor(scrollingFieldIndicatorDown, "BottomCenter")
scrollView.downIndicator.x = (scrollView.width /2)
scrollView.downIndicator.y = (h - 10)
else
scrollingFieldIndicatorUp = loadImageFile(options.scrollingFieldIndicatorIconUp)
scrollingFieldIndicatorDown = loadImageFile(options.scrollingFieldIndicatorIconDown)
scrollView:insert( scrollingFieldIndicatorUp )
scrollView:insert( scrollingFieldIndicatorDown )
scrollView.upIndicator = scrollingFieldIndicatorUp
scrollView.downIndicator = scrollingFieldIndicatorDown
funx.anchor(scrollingFieldIndicatorUp, "TopCenter")
funx.anchor(scrollingFieldIndicatorDown, "BottomCenter")
scrollView.upIndicator.x = (scrollView.width /2)
scrollView.downIndicator.x = (scrollView.width /2)
scrollView.upIndicator.y = 10
scrollView.downIndicator.y = (h - 10)
end
-- FADE AWAY scrollingFieldIndicator
local function fadeOpeningItems( )
-- Fade out
local function fout(obj)
funx.fadeOut(obj, nil, nil)
end
-- Wait...
local function waitabit(obj)
timer.performWithDelay( options.pageItemsPrefadeOnOpeningTime, function() fout(obj) end )
end
if (options.scrollingFieldIndicatorLocation == "over") then
funx.fadeIn(scrollingFieldIndicator, function() waitabit(scrollingFieldIndicator) end, options.pageItemsFadeInOpeningTime)
elseif (options.scrollingFieldIndicatorLocation == "bottom") then
funx.fadeIn(scrollingFieldIndicatorDown, function() waitabit(scrollingFieldIndicatorDown) end, options.pageItemsFadeInOpeningTime)
else
funx.fadeIn(scrollingFieldIndicatorUp, function() waitabit(scrollingFieldIndicatorUp) end, options.pageItemsFadeInOpeningTime)
funx.fadeIn(scrollingFieldIndicatorDown, function() waitabit(scrollingFieldIndicatorDown) end, options.pageItemsFadeInOpeningTime)
end
end
-- Begin the fade away immediately
fadeOpeningItems()
end -- scroll view indicator icon
textBlockIsScrolling = true
-- must copy this over!
finalTextBlock.anchorChildren = false
finalTextBlock.yAdjustment = textblock.yAdjustment
finalTextBlock.anchorChildren = true
finalTextBlock.anchorX, finalTextBlock.anchorY = 0,0
else
finalTextBlock = textblock
end
return finalTextBlock
end
local function openCacheDB()
-- Create the new DB
--print ("textrender : openCachDB() : 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 );"
local err = db:exec( cmd )
if (err ~= 0) then
-- error!
print ("ERROR: textrender : openCacheDB() : sqllite error = " .. err)
end
-- 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
-- ONLY "ascent" is actually used!!!
-- Caching is much, much faster than recalculating, so we use the cache if possible
------------------------------------------------
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 metrics = graphics.getFontMetrics( font, size )
ascent = metrics.ascent
descent = metrics.descent
end
return ascent, descent
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
--local c = stats[i].firstLineIndent + (stats[i].currentWidth)/2
local c = stats[i].firstLineIndent + (stats[i].width)/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)
----------
--if text == '' then return false end
local renderedTextblock = display.newGroup()
-- Add the scrollblock function to the result
renderedTextblock.fitBlockToHeight = fitBlockToHeight
local baseline = 0
local descent = 0
local ascent = 0
-- table for useful settings. We need fewer upvalues, and this is a way to do that
local settings = {}
-- ====================
-- FIXED VALUES
-- These should probably be changeable somewhere!
-- Fudge factor -- pixels to add after a change in font scale (not size!)
-- which is how we handle superscript and subscript.
settings.fontscaleChangeFudge = 1
-- Indent value in OL and UL lists
settings.listIndent = 10
settings.listExtraSpaceAfterBullet = 2
settings.listBulletToTextDistance = 30
-- ====================
-- Used to track x location while creating a line of text
settings.currentXOffset = 0
settings.deviceMetrics = funx.getDeviceMetrics( )
settings.minWordLen = 2