-
Notifications
You must be signed in to change notification settings - Fork 5
/
hummusrenderer.js
1390 lines (1208 loc) · 41.1 KB
/
hummusrenderer.js
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
var hummus = require('hummus'),
tmp = require('temporary'),
http = require('http'),
https = require('https'),
bidi = require('icu-bidi'),
fs = require('fs');
module.exports.render = function(inDocument,inTargetStream,inOptions,inCallback)
{
var state = new RenderingState();
downloadExternals(inDocument.externals,function(inDownloadMap)
{
state.externalsLocalFiles = inDownloadMap;
try
{
var writer;
if(inDocument.source)
{
state.modifiedFileStream = new hummus.PDFRStreamForFile(inDocument.source.path ?
inDocument.source.path :
state.getLocalFile(inDocument.source.external));
state.isModification = true;
writer = hummus.createWriterToModify(state.modifiedFileStream,inTargetStream,inOptions);
}
else
writer = hummus.createWriter(inTargetStream,inOptions);
renderDocument(inDocument,writer,state);
writer.end();
if(inOptions.cleanExternals)
cleanExternals(state.externalsLocalFiles)
if(inCallback)
inCallback();
}
catch(err)
{
inCallback(err);
}
});
}
// internal state class
function RenderingState()
{
this.externalsLocalFiles = {};
this.boxIDToBox = {};
}
RenderingState.prototype.getLocalFile = function(inExternalName)
{
return this.externalsLocalFiles[inExternalName];
};
RenderingState.prototype.getImageItemFilePath = function(inItem)
{
if(inItem.path)
return inItem.path;
else if(inItem.external)
return this.externalsLocalFiles[inItem.external];
else
return null;
};
RenderingState.prototype.getFontItemFilePath = function(inItem)
{
if(inItem.options.fontPath)
return inItem.options.fontPath;
else if(inItem.options.fontExternal)
return this.externalsLocalFiles[inItem.options.fontExternal];
else
return null;
};
RenderingState.prototype.getFontSecondItemFilePath = function(inItem)
{
if(inItem.options.fontSecondPath)
return inItem.options.fontSecondPath;
else if(inItem.options.fontSecondExternal)
return this.externalsLocalFiles[inItem.options.fontSecondExternal];
else
return null;
};
// download all externals
function downloadExternals(inExternals,inCallback)
{
if(!inExternals || Object.keys(inExternals).length == 0)
{
inCallback({});
return;
}
var downloadMap = {};
var keys = Object.keys(inExternals);
var index = 0;
downloadFile(inExternals[keys[index]],new tmp.File().path,function(inTargetFilePath,inThis)
{
downloadMap[keys[index]] = inTargetFilePath;
++index;
if(index < keys.length)
downloadFile(inExternals[keys[index]],new tmp.File().path,inThis);
else
inCallback(downloadMap);
});
}
function downloadFile(inFileURL,inTargetFilePath,inCallback)
{
var file = fs.createWriteStream(inTargetFilePath);
var theDownloadService = inFileURL.substring(0,5) == 'https' ? https:http;
var request = theDownloadService.get(inFileURL, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(inCallback.bind(null,inTargetFilePath,inCallback));
});
});
}
function NewPageDriver(inPDFWriter,inWidth,inHeight)
{
this.pdfWriter = inPDFWriter;
this.pdfPage = inPDFWriter.createPage(0,0,inWidth,inHeight);
}
NewPageDriver.prototype.startContentContext = function()
{
return this.pdfWriter.startPageContentContext(this.pdfPage);
}
NewPageDriver.prototype.writePage = function(inLinks)
{
if(inLinks.length > 0)
{
this.pdfWriter.pausePageContentContext(this.pdfWriter.startPageContentContext(this.pdfPage));
var self = this;
inLinks.forEach(function(link)
{
self.pdfWriter.attachURLLinktoCurrentPage(link.link,link.rect[0],link.rect[1],link.rect[2],link.rect[3]);
});
}
this.pdfWriter.writePage(this.pdfPage);
}
function ModifiedPageDriver(inPDFWriter,inPageIndex)
{
this.pdfWriter = inPDFWriter;
this.pageModifier = new hummus.PDFPageModifier(inPDFWriter,inPageIndex);
}
ModifiedPageDriver.prototype.startContentContext = function()
{
return this.pageModifier.startContext().getContext();
}
ModifiedPageDriver.prototype.writePage = function(inLinks)
{
if(this.pageModifier.getContext())
this.pageModifier.endContext();
if(inLinks.length > 0)
{
var self = this;
inLinks.forEach(function(link)
{
self.pageModifier.attachURLLinktoCurrentPage(link.link,link.rect[0],link.rect[1],link.rect[2],link.rect[3]);
});
}
this.pageModifier.writePage();
}
// main rendering method (when all externals are downloaded)
function renderDocument(inDocument,inPDFWriter,inRenderingState)
{
var width;
var height;
inRenderingState.theDocument = inDocument;
// render pages
inDocument.pages.forEach(function(inPage)
{
inRenderingState.links = [];
var thePageDriver;
if(inPage.modifiedFrom !== undefined)
{
thePageDriver = new ModifiedPageDriver(inPDFWriter,inPage.modifiedFrom);
}
else
{
// accumulate required properties [syntax test]
width = inPage.width || width;
height = inPage.height || height;
thePageDriver = new NewPageDriver(inPDFWriter,width,height);
}
// render boxes
if(inPage.boxes)
{
inPage.boxes.forEach(function(inBox)
{
renderBox(inBox,thePageDriver,inPDFWriter,inRenderingState);
});
}
thePageDriver.writePage(inRenderingState.links);
});
}
function renderBox(inBox,inPDFPage,inPDFWriter,inRenderingState)
{
// render the box
if(inBox.items)
{
inBox.items.forEach(function(inItem)
{
renderItem(inBox,inItem,inPDFPage,inPDFWriter,inRenderingState);
});
}
else if(inBox.image)
renderImageItem(inBox,inBox.image,inPDFPage,inPDFWriter,inRenderingState);
else if(inBox.shape)
renderShapeItem(inBox,inBox.shape,inPDFPage,inPDFWriter,inRenderingState);
else if(inBox.text)
renderTextItem(inBox,inBox.text,inPDFPage,inPDFWriter,inRenderingState);
else if(inBox.stream)
renderStreamItem(inBox,inBox.stream,inPDFPage,inPDFWriter,inRenderingState);
// collect box ID. collecting it after to allow reference in repeaters
// [meaning, allow a later ID to override this ID]
if(inBox.id)
inRenderingState.boxIDToBox[inBox.id] = inBox;
}
function renderItem(inBox,inItem,inPDFPage,inPDFWriter,inRenderingState)
{
switch(inItem.type)
{
case 'image':
renderImageItem(inBox,inItem,inPDFPage,inPDFWriter,inRenderingState);
break;
case 'shape':
renderShapeItem(inBox,inItem,inPDFPage,inPDFWriter,inRenderingState);
break;
case 'text':
renderTextItem(inBox,inItem,inPDFPage,inPDFWriter,inRenderingState);
break;
case 'stream':
renderStreamItem(inBox,inItem,inPDFPage,inPDFWriter,inRenderingState);
break;
}
}
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
function renderImageItem(inBox,inItem,inPDFPage,inPDFWriter,inRenderingState)
{
var opts = {};
opts.index = inItem.index;
opts.transformation = inItem.transformation;
if(opts.transformation && !isArray(opts.transformation) &&
!opts.transformation.width &&
!opts.transformation.height)
{
opts.transformation.width = inBox.width;
opts.transformation.height = inBox.height;
}
var imageItemMeasures = getImageItemMeasures(inItem,inPDFWriter,inRenderingState);
if(inBox.top !== undefined && inBox.bottom == undefined)
{
if(typeof(inBox.top) == 'object')
computeBoxTopFromAnchor(inBox,inPDFWriter,inRenderingState);
inBox.bottom = inBox.top - (inBox.height !== undefined ? inBox.height:imageItemMeasures.height);
}
var left = getLeftForAlignment(inBox,inItem,inPDFWriter,inRenderingState);
var imagePath = inRenderingState.getImageItemFilePath(inItem);
if(imagePath)
inPDFPage.startContentContext().drawImage(left,inBox.bottom,imagePath,opts);
if(inItem.link)
inRenderingState.links.push({link:inItem.link,rect:[left,inBox.bottom,left+imageItemMeasures.width,inBox.bottom+imageItemMeasures.height]});
}
function getLeftForAlignment(inBox,inItem,inPDFWriter,inRenderingState)
{
if(!inBox.alignment || inBox.alginment == "left")
return inBox.left;
else if(inBox.alignment == "right")
{
return inBox.left + inBox.width - getItemMeasures(inItem,inBox,inPDFWriter,inRenderingState).width;
}
else
{
// center
return inBox.left + (inBox.width - getItemMeasures(inItem,inBox,inPDFWriter,inRenderingState).width)/2;
}
}
function renderShapeItem(inBox,inItem,inPDFPage,inPDFWriter,inRenderingState)
{
if(inBox.top !== undefined && inBox.bottom == undefined)
{
if(typeof(inBox.top) == 'object')
computeBoxTopFromAnchor(inBox,inPDFWriter,inRenderingState);
inBox.bottom = inBox.top - (inBox.height !== undefined ? inBox.height:getShapeItemMeasures(inItem).height);
}
var left = getLeftForAlignment(inBox,inItem,inPDFWriter,inRenderingState);
switch(inItem.method)
{
case 'rectangle':
inPDFPage.startContentContext().drawRectangle(left,inBox.bottom,inItem.width,inItem.height,inItem.options);
break;
case 'square':
inPDFPage.startContentContext().drawSquare(left,inBox.bottom,inItem.width,inItem.options);
break;
case 'circle':
// translate bottom/left to center
inPDFPage.startContentContext().drawCircle(left+inItem.radius,inBox.bottom+inItem.radius,inItem.radius,inItem.options);
break;
case 'path':
// translate bottom left to paths points
var args = inItem.points.slice();
for(var i=0;i<args.length;i+=2)
{
args[i]+=left;
args[i+1]+=inBox.bottom;
}
if(inItem.options)
args.push(inItem.options);
var cxt = inPDFPage.startContentContext();
cxt.drawPath.apply(cxt,args);
break;
}
}
function renderTextItem(inBox,inItem,inPDFPage,inPDFWriter,inRenderingState)
{
var theFont = getFont(inPDFWriter,inRenderingState,inItem);
if(!theFont)
return;
inItem.options.font = theFont;
var theText = computeTextForItem(inItem);
if(inBox.top !== undefined && inBox.bottom == undefined)
{
if(typeof(inBox.top) == 'object')
computeBoxTopFromAnchor(inBox,inPDFWriter,inRenderingState);
inBox.bottom = inBox.top - (inBox.height !== undefined ? inBox.height:getTextItemMeasures(inItem,inPDFWriter,inRenderingState).height);
}
var left = getLeftForAlignment(inBox,inItem,inPDFWriter,inRenderingState);
inPDFPage.startContentContext().writeText(theText,left,inBox.bottom,inItem.options);
if(inItem.link)
{
var measures = calculateTextDimensions(theFont,theText,inItem.options.size);
inRenderingState.links.push({link:inItem.link,rect:[left+measures.xMin,inBox.bottom+measures.yMin,left+measures.xMax,inBox.bottom+measures.yMax]});
}
}
function hasNonSpace(inText)
{
return inText.match(/[^\s]/);
}
function calculateTextDimensions(inFont,inText,inFontSize)
{
// calculate the text measures. handles a bug where space only strings don't get their correct measures
if(hasNonSpace(inText))
{
// may be ending with space, in which case i'll get the same problem as having spaces...so do a similar trick..with no height this time
if(inText.search(/[\s]*$/) != inText.length)
{
var measures = inFont.calculateTextDimensions(inText+'a',inFontSize);
var measuresA = inFont.calculateTextDimensions('a',inFontSize);
measures.width-=measuresA.xMax;
measures.xMax-=measuresA.xMax;
return measures;
}
else
return inFont.calculateTextDimensions(inText,inFontSize);
}
else
{
var measures = inFont.calculateTextDimensions('a'+inText+'a',inFontSize);
var measuresA = inFont.calculateTextDimensions('aa',inFontSize);
var dMeasure = inFont.calculateTextDimensions('d',inFontSize);
dMeasure.width = measures.width-measuresA.width;
dMeasure.xMin = 0;
dMeasure.xMax = dMeasure.width;
return dMeasure;
}
}
function computeTextForItem(inItem)
{
var theText = isArray(inItem.text) ? joinTextArray(inItem.text):inItem.text;
var p = bidi.Paragraph(theText,{paraLevel: inItem.direction == 'rtl' ? bidi.RTL:bidi.LTR});
return p.writeReordered(bidi.Reordered.KEEP_BASE_COMBINING);
}
function getTextItemMeasures(inItem,inPDFWriter,inRenderingState)
{
var theFont = getFont(inPDFWriter,inRenderingState,inItem);
var theText = computeTextForItem(inItem);
if(theFont && theText.length > 0)
{
var measures = calculateTextDimensions(theFont,theText,inItem.options.size);
return {width:measures.xMax,height:measures.yMax}; // note, taking yMax, and not height, because we want the ascent and not the descent, which is below the baseline!
// also taking xMAx...cause i want the advance and not just the start to end glyphs area
}
else
{
return {width:0,height:0};
}
}
function joinTextArray(inStringArray)
{
var result = '';
inStringArray.forEach(function(inElement){result+=inElement});
return result;
}
function calculateBoxTopAndBottomForStream(inBox,inPDFWriter,inRenderingState)
{
if(inBox.top !== undefined && inBox.bottom == undefined)
{
if(typeof(inBox.top) == 'object')
computeBoxTopFromAnchor(inBox,inPDFWriter,inRenderingState);
inBox.bottom = inBox.top - (inBox.height !== undefined ? inBox.height:0);
}
}
function renderStreamItem(inBox,inItem,inPDFPage,inPDFWriter,inRenderingState)
{
inRenderingState.pdfPage = inPDFPage;
composeStreamItem(inBox,inItem,inPDFWriter,inRenderingState,renderRun);
}
function composeStreamItem(inBox,inItem,inPDFWriter,inRenderingState,inRenderRunMethod)
{
calculateBoxTopAndBottomForStream(inBox,inPDFWriter,inRenderingState);
var alignment = inBox.alignment === undefined ? (inItem.direction == 'rtl' ? 'right':'left'):inBox.alignment;
// transform the stream items to a structure that is defined by a plain text stream
// representing the stream text [non textual elements are represented by placeholder characters]
// and an accompanying array providing run data (which is essentially inItem.items with index pointers into the text
// stream array)
var logicalLines = createLogicalTextDataLines(inItem);
var top = (inBox.top !== undefined ? inBox.top : (inBox.bottom + (inBox.height !== undefined ? inBox.height:0)));
var left = inBox.left;
var lineCompositionState = {
height:0,
xOffset:left,
yOffset:top,
firstLine:true,
leading:inItem.leading ? inItem.leading:1.2,
box:inBox,
item:inItem,
pdfWriter:inPDFWriter,
renderingState:inRenderingState,
renderRun:inRenderRunMethod,
lineSpacingModifier:function()
{
return this.firstLine?1:this.leading;
},
lineSpacing:function()
{
return this.height*this.lineSpacingModifier();
},
startLine:function(inDirection,inWidth,inHeight)
{
// before a lign is rendered. when there's already knowledge
// of the line width. setup alignment. the direction determines
// the default if no alignment is defined
if(alignment == 'center')
this.xOffset += (inBox.width - inWidth)/2;
else if(alignment == 'right')
this.xOffset += (inBox.width - inWidth);
// setup baseline for text placement
this.height = inHeight;
this.yOffset -= this.lineSpacing();
inItem.lowestContentOffset = this.yOffset;
inItem.contentHeight = top - inItem.lowestContentOffset;
},
reset:function()
{
// ran after line is rendered and finished. prpare for next line
this.xOffset = left;
this.height = 0;
this.firstLine = false;
}
};
for(var i=0;i<logicalLines.length;++i)
{
// loop logical lines and place. lines may be broken further to allow for text wrap where required
if(!composeLine(logicalLines[i],lineCompositionState))
break; // will break on overflow
}
}
var kDefaultInlineObjectChar = '?';
function createLogicalTextDataLines(inItem)
{
var logicalLines = [];
var currentText = '';
var currentStyles = [];
var currentTextLength = 0;
// loop stream item creating an array of "logical lines"
// the lines are spearated by text items with newlines (\r or \n or \r\n)
// each line is made of a single string of text, where each character
// represents either a real text character or an inline object (e.g. an image)
// an additional array of "styles" has multiple objects, where each object
// represents either a text style run or an inline object. the "style" propery
// will have the originla stream item. an additional "limit" property is an index that
// represents the first characters index after this run.
inItem.items.forEach(function(inItem)
{
if(inItem.type == 'text')
{
// texts may have line ends, analyse the text and finish line if necessary
var theText = isArray(inItem.text) ? joinTextArray(inItem.text):inItem.text;
var textComponents = theText.match(/[^\r\n]+|\r\n|\n|\r/g);
if(textComponents)
{
textComponents.forEach(function(inText)
{
if(inText.search(/\r|\n/) == -1)
{
// non line. append to current text line
currentText+=inText;
currentTextLength+=inText.length;
currentStyles.push({style:inItem,limit:currentTextLength});
}
else
{
// line, finalize current line and restart
if(currentStyles.length == 0)
currentStyles.push({style:inItem}); // for empty line make sure the maintain the style for the newline height to be calculated
logicalLines.push({text:currentText,styles:currentStyles});
currentText = '';
currentStyles = [];
currentTextLength = 0;
}
});
}
}
else
{
// non texts are simple "one character" objects
currentText+=kDefaultInlineObjectChar;
currentTextLength+=1;
currentStyles.push({style:inItem,limit:currentTextLength});
}
});
// close a final line if one exists
if(currentTextLength > 0)
logicalLines.push({text:currentText,styles:currentStyles});
return logicalLines;
}
function composeLine(inLine,inState)
{
if(inLine.text.length > 0)
{
// compose line considering various items placement and direction
return renderParagraph(inLine,inState);
}
else
{
// empty line, just increase yOffset per the newline height.
var lineHeight = getFont(inPDFWriter,inRenderingState,inLine.styles[0]).calculateTextDimensions('d',inLine.styles[0].options.size).yMax;
if(inState.box.height !== undefined && inState.yOffset-lineHeight*inState.lineSpacingModifier() < inState.box.bottom)
{
return false;
}
else
{
inState.startLine(inState.item.direction,0,lineHeight);
inState.reset();
return true;
}
}
}
function renderParagraph(inLine,inState)
{
var p = bidi.Paragraph(inLine.text,{paraLevel: inState.item.direction == 'rtl' ? bidi.RTL:bidi.LTR});
var textLength = inLine.text.length;
var paraLevel=1&p.getParaLevel();
var direction = ((paraLevel == bidi.RTL) ? 'rtl':'ltr');
var nonSpaceEndIndex = inLine.text.search(/[\s]*$/);
// i'm looking to trim ending spaces, for propper alignment (centering and the opposite)
var measures=getTextMeasures(p,inLine.text.substring(0,nonSpaceEndIndex),inLine.styles,inState);
if(measures.width<=inState.box.width
&& (inState.box.height == undefined || (inState.yOffset-measures.height*inState.lineSpacingModifier() >= inState.box.bottom)))
{
// everything fits onto one line
// prepare rendering a new line from either left or right
inState.startLine(direction,measures.width,measures.height);
renderLine(p,inLine.text,0,nonSpaceEndIndex, inLine.styles, 0,inLine.styles.length,inState);
inState.reset();
return true;
}
else
{
var start=0,
styleRunStart = 0,
rw = {limit:null, styleRunLimit:null,width:null,height:null,verticalOverflow:false},
skipSpaces = false; // skip spaces is for line start. any spaces should be skipped after a line that got broken
for(;;)
{
rw.limit = textLength;
rw.styleRunLimit = inLine.styles.length;
if(skipSpaces) // only false in the first line. skip spaces in line breaks so that text start at line start.
{
var nonSpaceIndex = inLine.text.substr(start).search(/[^\s]/);
if(nonSpaceIndex != -1)
{
start+= nonSpaceIndex;
if(start == textLength) // if the skipped spaces are the end of the text
{
break;
}
}
}
rw = getLineBreak(inLine.text,start,rw.limit,p,inLine.styles,styleRunStart,rw.styleRunLimit,inState);
if(rw.verticalOverflow)
{
break;
}
var line = p.setLine(start,rw.limit);
// prepare rendering a new line
// from either left or right
inState.startLine(direction,rw.width,rw.height);
renderLine(line,inLine.text,start,rw.limit,inLine.styles,styleRunStart,rw.styleRunLimit-styleRunStart,inState);
inState.reset();
if(rw.limit == textLength)
{
break;
}
start = rw.limit;
styleRunStart=rw.styleRunLimit-1;
if(start>=inLine.styles[styleRunStart].limit)
++styleRunStart;
if(!skipSpaces)
skipSpaces = true;
}
return rw.verticalOverflow;
}
}
function renderLine(inBidiLine,inText,inStart,inLimit,inStyleRuns,inStyleRunsStart,inStyleRunsCount,inState)
{
var direction = inBidiLine.getDirection();
if(direction != 'mixed')
{
// unidirectional
if(inStyleRunsCount<=1)
inState.renderRun(inText,inStart,inLimit,direction,inStyleRuns[inStyleRunsStart].style,inState);
else
renderDirectionalRun(inText,inStart,inLimit,direction,inStyleRuns,inStyleRunsStart,inStyleRunsCount,inState);
}
else
{
// mixed-directional
var count,i;
count = inBidiLine.countRuns();
if(inStyleRunsCount<=1)
{
style = inStyleRuns[inStyleRunsStart].style;
// iterate over direcitonal runs
for(i=0;i<count;++i)
{
var visRun = inBidiLine.getVisualRun(i);
inState.renderRun(inText, inStart+visRun.logicalStart, inStart+visRun.logicalStart+visRun.length, visRun.dir, style,inState);
}
}
else
{
for(i=0;i<count;++i)
{
var visRun = inBidiLine.getVisualRun(i);
renderDirectionalRun(inText, inStart+visRun.logicalStart, inStart+visRun.logicalStart+visRun.length, visRun.dir, inStyleRuns,inStyleRunsStart,inStyleRunsCount,inState);
}
}
}
}
function renderDirectionalRun(inText,inStart,inLimit,inDirection,inStyleRuns,inStyleRunsStart,inStyleRunsCount,inState)
{
var i;
if(inDirection == 'ltr')
{
var styleLimit;
for(i=0;i<inStyleRunsCount;++i)
{
styleLimit = inStyleRuns[inStyleRunsStart + i].limit;
if(inStart < styleLimit)
{
if(styleLimit>inLimit) { styleLimit=inLimit; }
inState.renderRun(inText,inStart,styleLimit,inDirection,inStyleRuns[inStyleRunsStart + i].style,inState);
if(styleLimit==inLimit) { break; }
inStart=styleLimit;
}
}
}
else
{
var styleStart;
for(i=inStyleRunsCount-1;i>=0;--i)
{
if(i>0)
styleStart = inStyleRuns[inStyleRunsStart+i-1].limit;
else
styleStart = 0;
if(inLimit>=styleStart)
{
if(styleStart<inStart) {styleStart=start;}
inState.renderRun(inText,styleStart,inLimit,inDirection,inStyleRuns[inStyleRunsStart + i].style,inState);
if(styleStart == start){break;}
inLimit = styleStart;
}
}
}
}
function renderRun(inText,inStart,inLimit,inDirection,inStyle,inState)
{
var itemMeasures;
if(inStyle.type !== undefined)
{
// regular item, place using regular method, with a new box stating it's position
var theItem;
if(inStyle.type == 'text')
{
theItem = shallowCopy(inStyle);
theItem.text = inText.substring(inStart,inLimit);
}
else
{
theItem = inStyle;
}
theItem.direction = inDirection;
var theBox = {left:inState.xOffset,bottom:inState.yOffset,items:[theItem]};
renderItem(theBox,theItem,inState.renderingState.pdfPage,inState.pdfWriter,inState.renderingState);
itemMeasures = getItemMeasures(theItem,theBox,inState.pdfWriter,inState.renderingState);
}
else
{
// a box. create a copy of the box, and replace the xOffset and yOffset
// ponder:replacing. should i add? right now will not support non-0 coordinates
// of box...oh well...we still have to figure out what its good for anyways
var newBox = shallowCopy(inStyle);
newBox.left = inState.xOffset;
newBox.bottom = inState.yOffset;
renderBox(newBox,inState.renderingState.pdfPage,inState.pdfWriter,inState.renderingState);
itemMeasures = calculateBoxMeasures(newBox,inState.pdfWriter,inState.renderingState);
}
inState.xOffset += itemMeasures.width;
inState.height = Math.max(inState.height,itemMeasures.height);
}
function computeRun(inText,inStart,inLimit,inDirection,inStyle,inState)
{
var itemMeasures;
if(inStyle.type !== undefined)
{
// regular item, place using regular method, with a new box stating it's position
var theItem;
if(inStyle.type == 'text')
{
theItem = shallowCopy(inStyle);
theItem.text = inText;
}
else
{
theItem = inStyle;
}
theItem.direction = inDirection;
var theBox = {left:inState.xOffset,bottom:inState.yOffset,items:[theItem]};
itemMeasures = getItemMeasures(theItem,theBox,inState.pdfWriter,inState.renderingState);
}
else
{
// a box. create a copy of the box, and replace the xOffset and yOffset
// ponder:replacing. should i add? right now will not support non-0 coordinates
// of box...oh well...we still have to figure out what its good for anyways
var newBox = shallowCopy(inStyle);
newBox.left = inState.xOffset;
newBox.bottom = inState.yOffset;
itemMeasures = calculateBoxMeasures(newBox,inState.pdfWriter,inState.renderingState);
}
inState.xOffset += itemMeasures.width;
inState.height = Math.max(inState.height,itemMeasures.width);
}
function getLineBreak(inText,inStart,inLimit,inBidi,inStyles,inStylesStart,inStylesLimit,inState)
{
// getlinebreak will find a line break for content so that it can be placed in a line so that it
// fits the box width/height.
// get line break assumes that it is placed in a constant width box.
// therefore if it can't place anything in the line, this will mark a necessary vertical overflow.
var maxWidth = inState.box.width;
var result = {width:0,limit:inStart,height:0,styleRunLimit:inStylesStart};
// empty case
if(inLimit == inStart)
return result;
// advance styles start to an affective range
while(inStyles[result.styleRunLimit].limit < inStart)
++reslt.stylesLimit;
for(;;)
{
// advance by logicalRun and style run, adding to width
var logicalRun = inBidi.getLogicalRun(result.limit);
if(logicalRun.limit > inLimit)
logicalRun.limit = inLimit;
// for each style in logical run. measure as style in full
// if good - go on [advance limit and style limit]. if not, need to break.
while(result.styleRunLimit < inStylesLimit && (result.styleRunLimit<1 || inStyles[result.styleRunLimit-1].limit<= logicalRun.logicalLimit))
{
// get the width of the range result.limit...Math.min(result.styleRunLimit,logicalRun.limit)
var runLimit = Math.min(inStyles[result.styleRunLimit].limit,logicalRun.logicalLimit);
var runMeasures = getRunMeasures(inText,result.limit,runLimit,logicalRun.dir,inStyles[result.styleRunLimit].style,inState);
if((result.width + runMeasures.width <=maxWidth) &&
(inState.box.height == undefined || (inState.yOffset-runMeasures.height*inState.lineSpacingModifier() >= inState.box.bottom)))
{
// add run/logical run in full
result.width+=runMeasures.width;
result.height = Math.max(runMeasures.height,result.height);
result.limit = runLimit;
if(runLimit == inStyles[result.styleRunLimit].limit)
++result.styleRunLimit;
else
break; // logical run finish...so finish
}
else
{
// got a break, break according to spaces, and finish
var textComponentsStart = result.limit;
var accumulatedWidth = 0;
var accumulatedLimitAdd = 0;
var accumulatedLimitAddToNonSpace = 0;
var textComponents = inText.substring(result.limit,runLimit).match(/[^\s]+|[^\S]+/g);
for(var i=0;i<textComponents.length;++i)
{
runMeasures = getRunMeasures(inText,textComponentsStart,result.limit+accumulatedLimitAdd+textComponents[i].length,logicalRun.dir,inStyles[result.styleRunLimit].style,inState);
if((result.width + runMeasures.width <=maxWidth) &&
(inState.box.height == undefined || (inState.yOffset-runMeasures.height*inState.lineSpacingModifier() >= inState.box.bottom)))
{
// add word/spaces in
accumulatedLimitAdd+=textComponents[i].length;
if(hasNonSpace(textComponents[i]))
{
accumulatedWidth=runMeasures.width; // add space to width ONLY when a later non space would show up. this should fix up the alignment problem nicely
accumulatedLimitAddToNonSpace = accumulatedLimitAdd;
}
result.height = Math.max(runMeasures.height,result.height);
}
else
{
// add to width what accumulated so far
break;
}
}
// add accumulated width/range of what of the text that got in. take the measures so that will trim any ending spaces
result.width+=accumulatedWidth;
result.limit+=accumulatedLimitAddToNonSpace;
// advance style in 1 to get to the limit
++result.styleRunLimit;
// force finish
logicalRun.logicalLimit = inLimit;
break;
}
}
if(logicalRun.logicalLimit == inLimit) // ended text, break
break;
}
result.verticalOverflow = (inStart == result.limit);
return result;
}
function getRunMeasures(inText,inStart,inLimit,inDirection,inStyle,inState)
{
var itemMeasures;
if(inStyle.type !== undefined)
{
// regular item, place using regular method, with a new box stating it's position
var theItem;
if(inStyle.type == 'text')
{
theItem = shallowCopy(inStyle);
theItem.text = inText.substring(inStart,inLimit);
}
else
{
theItem = inStyle;
}
theItem.direction = inDirection;
var theBox = {left:0,bottom:0,items:[theItem]};
itemMeasures = getItemMeasures(theItem,theBox,inState.pdfWriter,inState.renderingState);
if(!inState.firstLine && inStyle.type == 'text') // when not the first relevant line height is actually the font size, not the text height
itemMeasures.height = inStyle.options.size;
}
else
{
// a box. create a copy of the box, and replace the xOffset and yOffset
// ponder:replacing. should i add? right now will not support non-0 coordinates
// of box...oh well...we still have to figure out what its good for anyways
var newBox = shallowCopy(inStyle);
newBox.left = inState.xOffset;
newBox.bottom = inState.yOffset;
itemMeasures = calculateBoxMeasures(newBox,inState.pdfWriter,inState.renderingState);
}
return itemMeasures;
}
function getTextMeasures(p,inText, inStyles,inState)
{
// total text width. loop through logical runs