source: trunk/src/gui/text/qtextengine.cpp@ 605

Last change on this file since 605 was 561, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.1 sources.

File size: 95.9 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtGui module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "qdebug.h"
43#include "qtextformat.h"
44#include "qtextformat_p.h"
45#include "qtextengine_p.h"
46#include "qabstracttextdocumentlayout.h"
47#include "qtextlayout.h"
48#include "qtextboundaryfinder.h"
49#include "qvarlengtharray.h"
50#include "qfont.h"
51#include "qfont_p.h"
52#include "qfontengine_p.h"
53#include "qstring.h"
54#include <private/qunicodetables_p.h>
55#include "qtextdocument_p.h"
56#include <qapplication.h>
57#include <stdlib.h>
58
59
60QT_BEGIN_NAMESPACE
61
62namespace {
63// Helper class used in QTextEngine::itemize
64// keep it out here to allow us to keep supporting various compilers.
65class Itemizer {
66public:
67 Itemizer(const QString &string, const QScriptAnalysis *analysis, QScriptItemArray &items)
68 : m_string(string),
69 m_analysis(analysis),
70 m_items(items),
71 m_splitter(0)
72 {
73 }
74 ~Itemizer()
75 {
76 delete m_splitter;
77 }
78
79 /// generate the script items
80 /// The caps parameter is used to choose the algoritm of splitting text and assiging roles to the textitems
81 void generate(int start, int length, QFont::Capitalization caps)
82 {
83 if ((int)caps == (int)QFont::SmallCaps)
84 generateScriptItemsSmallCaps(m_string.utf16(), start, length);
85 else if(caps == QFont::Capitalize)
86 generateScriptItemsCapitalize(start, length);
87 else if(caps != QFont::MixedCase) {
88 generateScriptItemsAndChangeCase(start, length,
89 caps == QFont::AllLowercase ? QScriptAnalysis::Lowercase : QScriptAnalysis::Uppercase);
90 }
91 else
92 generateScriptItems(start, length);
93 }
94
95private:
96 enum { MaxItemLength = 4096 };
97
98 void generateScriptItemsAndChangeCase(int start, int length, QScriptAnalysis::Flags flags)
99 {
100 generateScriptItems(start, length);
101 if (m_items.isEmpty()) // the next loop won't work in that case
102 return;
103 QScriptItemArray::Iterator iter = m_items.end();
104 do {
105 iter--;
106 if (iter->analysis.flags < QScriptAnalysis::TabOrObject)
107 iter->analysis.flags = flags;
108 } while (iter->position > start);
109 }
110
111 void generateScriptItems(int start, int length)
112 {
113 if (!length)
114 return;
115 const int end = start + length;
116 for (int i = start + 1; i < end; ++i) {
117 if ((m_analysis[i] == m_analysis[start])
118 && m_analysis[i].flags < QScriptAnalysis::SpaceTabOrObject
119 && i - start < MaxItemLength)
120 continue;
121 m_items.append(QScriptItem(start, m_analysis[start]));
122 start = i;
123 }
124 m_items.append(QScriptItem(start, m_analysis[start]));
125 }
126
127 void generateScriptItemsCapitalize(int start, int length)
128 {
129 if (!length)
130 return;
131
132 if (!m_splitter)
133 m_splitter = new QTextBoundaryFinder(QTextBoundaryFinder::Word,
134 m_string.constData(), m_string.length(),
135 /*buffer*/0, /*buffer size*/0);
136
137 m_splitter->setPosition(start);
138 QScriptAnalysis itemAnalysis = m_analysis[start];
139
140 if (m_splitter->boundaryReasons() & QTextBoundaryFinder::StartWord) {
141 itemAnalysis.flags = QScriptAnalysis::Uppercase;
142 m_splitter->toNextBoundary();
143 }
144
145 const int end = start + length;
146 for (int i = start + 1; i < end; ++i) {
147
148 bool atWordBoundary = false;
149
150 if (i == m_splitter->position()) {
151 if (m_splitter->boundaryReasons() & QTextBoundaryFinder::StartWord
152 && m_analysis[i].flags < QScriptAnalysis::TabOrObject)
153 atWordBoundary = true;
154
155 m_splitter->toNextBoundary();
156 }
157
158 if (m_analysis[i] == itemAnalysis
159 && m_analysis[i].flags < QScriptAnalysis::TabOrObject
160 && !atWordBoundary
161 && i - start < MaxItemLength)
162 continue;
163
164 m_items.append(QScriptItem(start, itemAnalysis));
165 start = i;
166 itemAnalysis = m_analysis[start];
167
168 if (atWordBoundary)
169 itemAnalysis.flags = QScriptAnalysis::Uppercase;
170 }
171 m_items.append(QScriptItem(start, itemAnalysis));
172 }
173
174 void generateScriptItemsSmallCaps(const ushort *uc, int start, int length)
175 {
176 if (!length)
177 return;
178 bool lower = (QChar::category(uc[start]) == QChar::Letter_Lowercase);
179 const int end = start + length;
180 // split text into parts that are already uppercase and parts that are lowercase, and mark the latter to be uppercased later.
181 for (int i = start + 1; i < end; ++i) {
182 bool l = (QChar::category(uc[i]) == QChar::Letter_Lowercase);
183 if ((m_analysis[i] == m_analysis[start])
184 && m_analysis[i].flags < QScriptAnalysis::TabOrObject
185 && l == lower
186 && i - start < MaxItemLength)
187 continue;
188 m_items.append(QScriptItem(start, m_analysis[start]));
189 if (lower)
190 m_items.last().analysis.flags = QScriptAnalysis::SmallCaps;
191
192 start = i;
193 lower = l;
194 }
195 m_items.append(QScriptItem(start, m_analysis[start]));
196 if (lower)
197 m_items.last().analysis.flags = QScriptAnalysis::SmallCaps;
198 }
199
200 const QString &m_string;
201 const QScriptAnalysis * const m_analysis;
202 QScriptItemArray &m_items;
203 QTextBoundaryFinder *m_splitter;
204};
205}
206
207
208// ----------------------------------------------------------------------------
209//
210// The BiDi algorithm
211//
212// ----------------------------------------------------------------------------
213
214#define BIDI_DEBUG 0
215#if (BIDI_DEBUG >= 1)
216QT_BEGIN_INCLUDE_NAMESPACE
217#include <iostream>
218QT_END_INCLUDE_NAMESPACE
219using namespace std;
220
221static const char *directions[] = {
222 "DirL", "DirR", "DirEN", "DirES", "DirET", "DirAN", "DirCS", "DirB", "DirS", "DirWS", "DirON",
223 "DirLRE", "DirLRO", "DirAL", "DirRLE", "DirRLO", "DirPDF", "DirNSM", "DirBN"
224};
225
226#endif
227
228struct QBidiStatus {
229 QBidiStatus() {
230 eor = QChar::DirON;
231 lastStrong = QChar::DirON;
232 last = QChar:: DirON;
233 dir = QChar::DirON;
234 }
235 QChar::Direction eor;
236 QChar::Direction lastStrong;
237 QChar::Direction last;
238 QChar::Direction dir;
239};
240
241enum { MaxBidiLevel = 61 };
242
243struct QBidiControl {
244 inline QBidiControl(bool rtl)
245 : cCtx(0), base(rtl ? 1 : 0), level(rtl ? 1 : 0), override(false) {}
246
247 inline void embed(bool rtl, bool o = false) {
248 unsigned int toAdd = 1;
249 if((level%2 != 0) == rtl ) {
250 ++toAdd;
251 }
252 if (level + toAdd <= MaxBidiLevel) {
253 ctx[cCtx].level = level;
254 ctx[cCtx].override = override;
255 cCtx++;
256 override = o;
257 level += toAdd;
258 }
259 }
260 inline bool canPop() const { return cCtx != 0; }
261 inline void pdf() {
262 Q_ASSERT(cCtx);
263 --cCtx;
264 level = ctx[cCtx].level;
265 override = ctx[cCtx].override;
266 }
267
268 inline QChar::Direction basicDirection() const {
269 return (base ? QChar::DirR : QChar:: DirL);
270 }
271 inline unsigned int baseLevel() const {
272 return base;
273 }
274 inline QChar::Direction direction() const {
275 return ((level%2) ? QChar::DirR : QChar:: DirL);
276 }
277
278 struct {
279 unsigned int level;
280 bool override;
281 } ctx[MaxBidiLevel];
282 unsigned int cCtx;
283 const unsigned int base;
284 unsigned int level;
285 bool override;
286};
287
288
289static void appendItems(QScriptAnalysis *analysis, int &start, int &stop, const QBidiControl &control, QChar::Direction dir)
290{
291 if (start > stop)
292 return;
293
294 int level = control.level;
295
296 if(dir != QChar::DirON && !control.override) {
297 // add level of run (cases I1 & I2)
298 if(level % 2) {
299 if(dir == QChar::DirL || dir == QChar::DirAN || dir == QChar::DirEN)
300 level++;
301 } else {
302 if(dir == QChar::DirR)
303 level++;
304 else if(dir == QChar::DirAN || dir == QChar::DirEN)
305 level += 2;
306 }
307 }
308
309#if (BIDI_DEBUG >= 1)
310 qDebug("new run: dir=%s from %d, to %d level = %d override=%d", directions[dir], start, stop, level, control.override);
311#endif
312 QScriptAnalysis *s = analysis + start;
313 const QScriptAnalysis *e = analysis + stop;
314 while (s <= e) {
315 s->bidiLevel = level;
316 ++s;
317 }
318 ++stop;
319 start = stop;
320}
321
322
323// creates the next QScript items.
324static bool bidiItemize(QTextEngine *engine, QScriptAnalysis *analysis, QBidiControl &control)
325{
326 bool rightToLeft = (control.basicDirection() == 1);
327 bool hasBidi = rightToLeft;
328#if BIDI_DEBUG >= 2
329 qDebug() << "bidiItemize: rightToLeft=" << rightToLeft << engine->layoutData->string;
330#endif
331
332 int sor = 0;
333 int eor = -1;
334
335
336 int length = engine->layoutData->string.length();
337
338 const ushort *unicode = (const ushort *)engine->layoutData->string.unicode();
339 int current = 0;
340
341 QChar::Direction dir = rightToLeft ? QChar::DirR : QChar::DirL;
342 QBidiStatus status;
343
344 QChar::Direction sdir = QChar::direction(*unicode);
345 if (sdir != QChar::DirL && sdir != QChar::DirR && sdir != QChar::DirEN && sdir != QChar::DirAN)
346 sdir = QChar::DirON;
347 else
348 dir = QChar::DirON;
349 status.eor = sdir;
350 status.lastStrong = rightToLeft ? QChar::DirR : QChar::DirL;
351 status.last = status.lastStrong;
352 status.dir = sdir;
353
354
355 while (current <= length) {
356
357 QChar::Direction dirCurrent;
358 if (current == (int)length)
359 dirCurrent = control.basicDirection();
360 else
361 dirCurrent = QChar::direction(unicode[current]);
362
363#if (BIDI_DEBUG >= 2)
364// qDebug() << "pos=" << current << " dir=" << directions[dir]
365// << " current=" << directions[dirCurrent] << " last=" << directions[status.last]
366// << " eor=" << eor << '/' << directions[status.eor]
367// << " sor=" << sor << " lastStrong="
368// << directions[status.lastStrong]
369// << " level=" << (int)control.level << " override=" << (bool)control.override;
370#endif
371
372 switch(dirCurrent) {
373
374 // embedding and overrides (X1-X9 in the BiDi specs)
375 case QChar::DirRLE:
376 case QChar::DirRLO:
377 case QChar::DirLRE:
378 case QChar::DirLRO:
379 {
380 bool rtl = (dirCurrent == QChar::DirRLE || dirCurrent == QChar::DirRLO);
381 hasBidi |= rtl;
382 bool override = (dirCurrent == QChar::DirLRO || dirCurrent == QChar::DirRLO);
383
384 unsigned int level = control.level+1;
385 if ((level%2 != 0) == rtl) ++level;
386 if(level < MaxBidiLevel) {
387 eor = current-1;
388 appendItems(analysis, sor, eor, control, dir);
389 eor = current;
390 control.embed(rtl, override);
391 QChar::Direction edir = (rtl ? QChar::DirR : QChar::DirL);
392 dir = status.eor = edir;
393 status.lastStrong = edir;
394 }
395 break;
396 }
397 case QChar::DirPDF:
398 {
399 if (control.canPop()) {
400 if (dir != control.direction()) {
401 eor = current-1;
402 appendItems(analysis, sor, eor, control, dir);
403 dir = control.direction();
404 }
405 eor = current;
406 appendItems(analysis, sor, eor, control, dir);
407 control.pdf();
408 dir = QChar::DirON; status.eor = QChar::DirON;
409 status.last = control.direction();
410 if (control.override)
411 dir = control.direction();
412 else
413 dir = QChar::DirON;
414 status.lastStrong = control.direction();
415 }
416 break;
417 }
418
419 // strong types
420 case QChar::DirL:
421 if(dir == QChar::DirON)
422 dir = QChar::DirL;
423 switch(status.last)
424 {
425 case QChar::DirL:
426 eor = current; status.eor = QChar::DirL; break;
427 case QChar::DirR:
428 case QChar::DirAL:
429 case QChar::DirEN:
430 case QChar::DirAN:
431 if (eor >= 0) {
432 appendItems(analysis, sor, eor, control, dir);
433 dir = eor < length ? QChar::direction(unicode[eor]) : control.basicDirection();
434 status.eor = dir;
435 } else {
436 eor = current; status.eor = dir;
437 }
438 break;
439 case QChar::DirES:
440 case QChar::DirET:
441 case QChar::DirCS:
442 case QChar::DirBN:
443 case QChar::DirB:
444 case QChar::DirS:
445 case QChar::DirWS:
446 case QChar::DirON:
447 if(dir != QChar::DirL) {
448 //last stuff takes embedding dir
449 if(control.direction() == QChar::DirR) {
450 if(status.eor != QChar::DirR) {
451 // AN or EN
452 appendItems(analysis, sor, eor, control, dir);
453 status.eor = QChar::DirON;
454 dir = QChar::DirR;
455 }
456 eor = current - 1;
457 appendItems(analysis, sor, eor, control, dir);
458 dir = eor < length ? QChar::direction(unicode[eor]) : control.basicDirection();
459 status.eor = dir;
460 } else {
461 if(status.eor != QChar::DirL) {
462 appendItems(analysis, sor, eor, control, dir);
463 status.eor = QChar::DirON;
464 dir = QChar::DirL;
465 } else {
466 eor = current; status.eor = QChar::DirL; break;
467 }
468 }
469 } else {
470 eor = current; status.eor = QChar::DirL;
471 }
472 default:
473 break;
474 }
475 status.lastStrong = QChar::DirL;
476 break;
477 case QChar::DirAL:
478 case QChar::DirR:
479 hasBidi = true;
480 if(dir == QChar::DirON) dir = QChar::DirR;
481 switch(status.last)
482 {
483 case QChar::DirL:
484 case QChar::DirEN:
485 case QChar::DirAN:
486 if (eor >= 0)
487 appendItems(analysis, sor, eor, control, dir);
488 // fall through
489 case QChar::DirR:
490 case QChar::DirAL:
491 dir = QChar::DirR; eor = current; status.eor = QChar::DirR; break;
492 case QChar::DirES:
493 case QChar::DirET:
494 case QChar::DirCS:
495 case QChar::DirBN:
496 case QChar::DirB:
497 case QChar::DirS:
498 case QChar::DirWS:
499 case QChar::DirON:
500 if(status.eor != QChar::DirR && status.eor != QChar::DirAL) {
501 //last stuff takes embedding dir
502 if(control.direction() == QChar::DirR
503 || status.lastStrong == QChar::DirR || status.lastStrong == QChar::DirAL) {
504 appendItems(analysis, sor, eor, control, dir);
505 dir = QChar::DirR; status.eor = QChar::DirON;
506 eor = current;
507 } else {
508 eor = current - 1;
509 appendItems(analysis, sor, eor, control, dir);
510 dir = QChar::DirR; status.eor = QChar::DirON;
511 }
512 } else {
513 eor = current; status.eor = QChar::DirR;
514 }
515 default:
516 break;
517 }
518 status.lastStrong = dirCurrent;
519 break;
520
521 // weak types:
522
523 case QChar::DirNSM:
524 if (eor == current-1)
525 eor = current;
526 break;
527 case QChar::DirEN:
528 // if last strong was AL change EN to AN
529 if(status.lastStrong != QChar::DirAL) {
530 if(dir == QChar::DirON) {
531 if(status.lastStrong == QChar::DirL)
532 dir = QChar::DirL;
533 else
534 dir = QChar::DirEN;
535 }
536 switch(status.last)
537 {
538 case QChar::DirET:
539 if (status.lastStrong == QChar::DirR || status.lastStrong == QChar::DirAL) {
540 appendItems(analysis, sor, eor, control, dir);
541 status.eor = QChar::DirON;
542 dir = QChar::DirAN;
543 }
544 // fall through
545 case QChar::DirEN:
546 case QChar::DirL:
547 eor = current;
548 status.eor = dirCurrent;
549 break;
550 case QChar::DirR:
551 case QChar::DirAL:
552 case QChar::DirAN:
553 if (eor >= 0)
554 appendItems(analysis, sor, eor, control, dir);
555 else
556 eor = current;
557 status.eor = QChar::DirEN;
558 dir = QChar::DirAN; break;
559 case QChar::DirES:
560 case QChar::DirCS:
561 if(status.eor == QChar::DirEN || dir == QChar::DirAN) {
562 eor = current; break;
563 }
564 case QChar::DirBN:
565 case QChar::DirB:
566 case QChar::DirS:
567 case QChar::DirWS:
568 case QChar::DirON:
569 if(status.eor == QChar::DirR) {
570 // neutrals go to R
571 eor = current - 1;
572 appendItems(analysis, sor, eor, control, dir);
573 dir = QChar::DirON; status.eor = QChar::DirEN;
574 dir = QChar::DirAN;
575 }
576 else if(status.eor == QChar::DirL ||
577 (status.eor == QChar::DirEN && status.lastStrong == QChar::DirL)) {
578 eor = current; status.eor = dirCurrent;
579 } else {
580 // numbers on both sides, neutrals get right to left direction
581 if(dir != QChar::DirL) {
582 appendItems(analysis, sor, eor, control, dir);
583 dir = QChar::DirON; status.eor = QChar::DirON;
584 eor = current - 1;
585 dir = QChar::DirR;
586 appendItems(analysis, sor, eor, control, dir);
587 dir = QChar::DirON; status.eor = QChar::DirON;
588 dir = QChar::DirAN;
589 } else {
590 eor = current; status.eor = dirCurrent;
591 }
592 }
593 default:
594 break;
595 }
596 break;
597 }
598 case QChar::DirAN:
599 hasBidi = true;
600 dirCurrent = QChar::DirAN;
601 if(dir == QChar::DirON) dir = QChar::DirAN;
602 switch(status.last)
603 {
604 case QChar::DirL:
605 case QChar::DirAN:
606 eor = current; status.eor = QChar::DirAN; break;
607 case QChar::DirR:
608 case QChar::DirAL:
609 case QChar::DirEN:
610 if (eor >= 0){
611 appendItems(analysis, sor, eor, control, dir);
612 } else {
613 eor = current;
614 }
615 dir = QChar::DirON; status.eor = QChar::DirAN;
616 break;
617 case QChar::DirCS:
618 if(status.eor == QChar::DirAN) {
619 eor = current; break;
620 }
621 case QChar::DirES:
622 case QChar::DirET:
623 case QChar::DirBN:
624 case QChar::DirB:
625 case QChar::DirS:
626 case QChar::DirWS:
627 case QChar::DirON:
628 if(status.eor == QChar::DirR) {
629 // neutrals go to R
630 eor = current - 1;
631 appendItems(analysis, sor, eor, control, dir);
632 status.eor = QChar::DirAN;
633 dir = QChar::DirAN;
634 } else if(status.eor == QChar::DirL ||
635 (status.eor == QChar::DirEN && status.lastStrong == QChar::DirL)) {
636 eor = current; status.eor = dirCurrent;
637 } else {
638 // numbers on both sides, neutrals get right to left direction
639 if(dir != QChar::DirL) {
640 appendItems(analysis, sor, eor, control, dir);
641 status.eor = QChar::DirON;
642 eor = current - 1;
643 dir = QChar::DirR;
644 appendItems(analysis, sor, eor, control, dir);
645 status.eor = QChar::DirAN;
646 dir = QChar::DirAN;
647 } else {
648 eor = current; status.eor = dirCurrent;
649 }
650 }
651 default:
652 break;
653 }
654 break;
655 case QChar::DirES:
656 case QChar::DirCS:
657 break;
658 case QChar::DirET:
659 if(status.last == QChar::DirEN) {
660 dirCurrent = QChar::DirEN;
661 eor = current; status.eor = dirCurrent;
662 }
663 break;
664
665 // boundary neutrals should be ignored
666 case QChar::DirBN:
667 break;
668 // neutrals
669 case QChar::DirB:
670 // ### what do we do with newline and paragraph separators that come to here?
671 break;
672 case QChar::DirS:
673 // ### implement rule L1
674 break;
675 case QChar::DirWS:
676 case QChar::DirON:
677 break;
678 default:
679 break;
680 }
681
682 //qDebug() << " after: dir=" << // dir << " current=" << dirCurrent << " last=" << status.last << " eor=" << status.eor << " lastStrong=" << status.lastStrong << " embedding=" << control.direction();
683
684 if(current >= (int)length) break;
685
686 // set status.last as needed.
687 switch(dirCurrent) {
688 case QChar::DirET:
689 case QChar::DirES:
690 case QChar::DirCS:
691 case QChar::DirS:
692 case QChar::DirWS:
693 case QChar::DirON:
694 switch(status.last)
695 {
696 case QChar::DirL:
697 case QChar::DirR:
698 case QChar::DirAL:
699 case QChar::DirEN:
700 case QChar::DirAN:
701 status.last = dirCurrent;
702 break;
703 default:
704 status.last = QChar::DirON;
705 }
706 break;
707 case QChar::DirNSM:
708 case QChar::DirBN:
709 // ignore these
710 break;
711 case QChar::DirLRO:
712 case QChar::DirLRE:
713 status.last = QChar::DirL;
714 break;
715 case QChar::DirRLO:
716 case QChar::DirRLE:
717 status.last = QChar::DirR;
718 break;
719 case QChar::DirEN:
720 if (status.last == QChar::DirL) {
721 status.last = QChar::DirL;
722 break;
723 }
724 // fall through
725 default:
726 status.last = dirCurrent;
727 }
728
729 ++current;
730 }
731
732#if (BIDI_DEBUG >= 1)
733 qDebug() << "reached end of line current=" << current << ", eor=" << eor;
734#endif
735 eor = current - 1; // remove dummy char
736
737 if (sor <= eor)
738 appendItems(analysis, sor, eor, control, dir);
739
740 return hasBidi;
741}
742
743void QTextEngine::bidiReorder(int numItems, const quint8 *levels, int *visualOrder)
744{
745
746 // first find highest and lowest levels
747 quint8 levelLow = 128;
748 quint8 levelHigh = 0;
749 int i = 0;
750 while (i < numItems) {
751 //printf("level = %d\n", r->level);
752 if (levels[i] > levelHigh)
753 levelHigh = levels[i];
754 if (levels[i] < levelLow)
755 levelLow = levels[i];
756 i++;
757 }
758
759 // implements reordering of the line (L2 according to BiDi spec):
760 // L2. From the highest level found in the text to the lowest odd level on each line,
761 // reverse any contiguous sequence of characters that are at that level or higher.
762
763 // reversing is only done up to the lowest odd level
764 if(!(levelLow%2)) levelLow++;
765
766#if (BIDI_DEBUG >= 1)
767// qDebug() << "reorderLine: lineLow = " << (uint)levelLow << ", lineHigh = " << (uint)levelHigh;
768#endif
769
770 int count = numItems - 1;
771 for (i = 0; i < numItems; i++)
772 visualOrder[i] = i;
773
774 while(levelHigh >= levelLow) {
775 int i = 0;
776 while (i < count) {
777 while(i < count && levels[i] < levelHigh) i++;
778 int start = i;
779 while(i <= count && levels[i] >= levelHigh) i++;
780 int end = i-1;
781
782 if(start != end) {
783 //qDebug() << "reversing from " << start << " to " << end;
784 for(int j = 0; j < (end-start+1)/2; j++) {
785 int tmp = visualOrder[start+j];
786 visualOrder[start+j] = visualOrder[end-j];
787 visualOrder[end-j] = tmp;
788 }
789 }
790 i++;
791 }
792 levelHigh--;
793 }
794
795#if (BIDI_DEBUG >= 1)
796// qDebug() << "visual order is:";
797// for (i = 0; i < numItems; i++)
798// qDebug() << visualOrder[i];
799#endif
800}
801
802QT_BEGIN_INCLUDE_NAMESPACE
803
804#if defined(Q_WS_X11) || defined (Q_WS_QWS)
805# include "qfontengine_ft_p.h"
806#elif defined(Q_WS_MAC)
807# include "qtextengine_mac.cpp"
808#endif
809
810#include <private/qharfbuzz_p.h>
811
812QT_END_INCLUDE_NAMESPACE
813
814// ask the font engine to find out which glyphs (as an index in the specific font) to use for the text in one item.
815static bool stringToGlyphs(HB_ShaperItem *item, QGlyphLayout *glyphs, QFontEngine *fontEngine)
816{
817 int nGlyphs = item->num_glyphs;
818
819 QTextEngine::ShaperFlags shaperFlags(QTextEngine::GlyphIndicesOnly);
820 if (item->item.bidiLevel % 2)
821 shaperFlags |= QTextEngine::RightToLeft;
822
823 bool result = fontEngine->stringToCMap(reinterpret_cast<const QChar *>(item->string + item->item.pos), item->item.length, glyphs, &nGlyphs, shaperFlags);
824 item->num_glyphs = nGlyphs;
825 glyphs->numGlyphs = nGlyphs;
826 return result;
827}
828
829// shape all the items that intersect with the line, taking tab widths into account to find out what text actually fits in the line.
830void QTextEngine::shapeLine(const QScriptLine &line)
831{
832 QFixed x;
833 bool first = true;
834 const int end = findItem(line.from + line.length - 1);
835 int item = findItem(line.from);
836 if (item == -1)
837 return;
838 for (item = findItem(line.from); item <= end; ++item) {
839 QScriptItem &si = layoutData->items[item];
840 if (si.analysis.flags == QScriptAnalysis::Tab) {
841 ensureSpace(1);
842 si.width = calculateTabWidth(item, x);
843 } else {
844 shape(item);
845 }
846 if (first && si.position != line.from) { // that means our x position has to be offset
847 QGlyphLayout glyphs = shapedGlyphs(&si);
848 Q_ASSERT(line.from > si.position);
849 for (int i = line.from - si.position - 1; i >= 0; i--) {
850 x -= glyphs.effectiveAdvance(i);
851 }
852 }
853 first = false;
854
855 x += si.width;
856 }
857}
858
859extern int qt_defaultDpiY(); // in qfont.cpp
860
861void QTextEngine::shapeText(int item) const
862{
863 Q_ASSERT(item < layoutData->items.size());
864 QScriptItem &si = layoutData->items[item];
865
866 if (si.num_glyphs)
867 return;
868
869#if defined(Q_WS_MAC)
870 shapeTextMac(item);
871#elif defined(Q_WS_WINCE)
872 shapeTextWithCE(item);
873#else
874 shapeTextWithHarfbuzz(item);
875#endif
876
877 si.width = 0;
878
879 if (!si.num_glyphs)
880 return;
881 QGlyphLayout glyphs = shapedGlyphs(&si);
882
883 QFont font = this->font(si);
884 bool letterSpacingIsAbsolute = font.d->letterSpacingIsAbsolute;
885 QFixed letterSpacing = font.d->letterSpacing;
886 QFixed wordSpacing = font.d->wordSpacing;
887
888 if (letterSpacingIsAbsolute)
889 letterSpacing *= font.d->dpi / qt_defaultDpiY();
890
891 if (letterSpacing != 0) {
892 for (int i = 1; i < si.num_glyphs; ++i) {
893 if (glyphs.attributes[i].clusterStart) {
894 if (letterSpacingIsAbsolute)
895 glyphs.advances_x[i-1] += letterSpacing;
896 else {
897 const QFixed advance = glyphs.advances_x[i-1];
898 glyphs.advances_x[i-1] += (letterSpacing - 100) * advance / 100;
899 }
900 }
901 }
902 if (letterSpacingIsAbsolute)
903 glyphs.advances_x[si.num_glyphs-1] += letterSpacing;
904 else {
905 const QFixed advance = glyphs.advances_x[si.num_glyphs-1];
906 glyphs.advances_x[si.num_glyphs-1] += (letterSpacing - 100) * advance / 100;
907 }
908 }
909 if (wordSpacing != 0) {
910 for (int i = 0; i < si.num_glyphs; ++i) {
911 if (glyphs.attributes[i].justification == HB_Space
912 || glyphs.attributes[i].justification == HB_Arabic_Space) {
913 // word spacing only gets added once to a consecutive run of spaces (see CSS spec)
914 if (i + 1 == si.num_glyphs
915 ||(glyphs.attributes[i+1].justification != HB_Space
916 && glyphs.attributes[i+1].justification != HB_Arabic_Space))
917 glyphs.advances_x[i] += wordSpacing;
918 }
919 }
920 }
921
922 for (int i = 0; i < si.num_glyphs; ++i)
923 si.width += glyphs.advances_x[i];
924}
925
926#if defined(Q_WS_WINCE) //TODO
927// set the glyph attributes heuristically. Assumes a 1 to 1 relationship between chars and glyphs
928// and no reordering.
929// also computes logClusters heuristically
930static void heuristicSetGlyphAttributes(const QChar *uc, int length, QGlyphLayout *glyphs, unsigned short *logClusters, int num_glyphs)
931{
932 // ### zeroWidth and justification are missing here!!!!!
933
934 Q_UNUSED(num_glyphs);
935 Q_ASSERT(num_glyphs <= length);
936
937// qDebug("QScriptEngine::heuristicSetGlyphAttributes, num_glyphs=%d", item->num_glyphs);
938
939 int glyph_pos = 0;
940 for (int i = 0; i < length; i++) {
941 if (uc[i].unicode() >= 0xd800 && uc[i].unicode() < 0xdc00 && i < length-1
942 && uc[i+1].unicode() >= 0xdc00 && uc[i+1].unicode() < 0xe000) {
943 logClusters[i] = glyph_pos;
944 logClusters[++i] = glyph_pos;
945 } else {
946 logClusters[i] = glyph_pos;
947 }
948 ++glyph_pos;
949 }
950
951 // first char in a run is never (treated as) a mark
952 int cStart = 0;
953
954 const bool symbolFont = false; // ####
955 glyphs->attributes[0].mark = false;
956 glyphs->attributes[0].clusterStart = true;
957 glyphs->attributes[0].dontPrint = (!symbolFont && uc[0].unicode() == 0x00ad) || qIsControlChar(uc[0].unicode());
958
959 int pos = 0;
960 int lastCat = QChar::category(uc[0].unicode());
961 for (int i = 1; i < length; ++i) {
962 if (logClusters[i] == pos)
963 // same glyph
964 continue;
965 ++pos;
966 while (pos < logClusters[i]) {
967 glyphs[pos].attributes = glyphs[pos-1].attributes;
968 ++pos;
969 }
970 // hide soft-hyphens by default
971 if ((!symbolFont && uc[i].unicode() == 0x00ad) || qIsControlChar(uc[i].unicode()))
972 glyphs->attributes[pos].dontPrint = true;
973 const QUnicodeTables::Properties *prop = QUnicodeTables::properties(uc[i].unicode());
974 int cat = prop->category;
975 if (cat != QChar::Mark_NonSpacing) {
976 glyphs->attributes[pos].mark = false;
977 glyphs->attributes[pos].clusterStart = true;
978 glyphs->attributes[pos].combiningClass = 0;
979 cStart = logClusters[i];
980 } else {
981 int cmb = prop->combiningClass;
982
983 if (cmb == 0) {
984 // Fix 0 combining classes
985 if ((uc[pos].unicode() & 0xff00) == 0x0e00) {
986 // thai or lao
987 unsigned char col = uc[pos].cell();
988 if (col == 0x31 ||
989 col == 0x34 ||
990 col == 0x35 ||
991 col == 0x36 ||
992 col == 0x37 ||
993 col == 0x47 ||
994 col == 0x4c ||
995 col == 0x4d ||
996 col == 0x4e) {
997 cmb = QChar::Combining_AboveRight;
998 } else if (col == 0xb1 ||
999 col == 0xb4 ||
1000 col == 0xb5 ||
1001 col == 0xb6 ||
1002 col == 0xb7 ||
1003 col == 0xbb ||
1004 col == 0xcc ||
1005 col == 0xcd) {
1006 cmb = QChar::Combining_Above;
1007 } else if (col == 0xbc) {
1008 cmb = QChar::Combining_Below;
1009 }
1010 }
1011 }
1012
1013 glyphs->attributes[pos].mark = true;
1014 glyphs->attributes[pos].clusterStart = false;
1015 glyphs->attributes[pos].combiningClass = cmb;
1016 logClusters[i] = cStart;
1017 glyphs->advances_x[pos] = 0;
1018 glyphs->advances_y[pos] = 0;
1019 }
1020
1021 // one gets an inter character justification point if the current char is not a non spacing mark.
1022 // as then the current char belongs to the last one and one gets a space justification point
1023 // after the space char.
1024 if (lastCat == QChar::Separator_Space)
1025 glyphs->attributes[pos-1].justification = HB_Space;
1026 else if (cat != QChar::Mark_NonSpacing)
1027 glyphs->attributes[pos-1].justification = HB_Character;
1028 else
1029 glyphs->attributes[pos-1].justification = HB_NoJustification;
1030
1031 lastCat = cat;
1032 }
1033 pos = logClusters[length-1];
1034 if (lastCat == QChar::Separator_Space)
1035 glyphs->attributes[pos].justification = HB_Space;
1036 else
1037 glyphs->attributes[pos].justification = HB_Character;
1038}
1039
1040void QTextEngine::shapeTextWithCE(int item) const
1041{
1042 QScriptItem &si = layoutData->items[item];
1043 si.glyph_data_offset = layoutData->used;
1044
1045 QFontEngine *fe = fontEngine(si, &si.ascent, &si.descent, &si.leading);
1046
1047 QTextEngine::ShaperFlags flags;
1048 if (si.analysis.bidiLevel % 2)
1049 flags |= RightToLeft;
1050 if (option.useDesignMetrics())
1051 flags |= DesignMetrics;
1052
1053 attributes(); // pre-initialize char attributes
1054
1055 const int len = length(item);
1056 int num_glyphs = length(item);
1057 const QChar *str = layoutData->string.unicode() + si.position;
1058 ushort upperCased[256];
1059 if (si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase
1060 || si.analysis.flags == QScriptAnalysis::Lowercase) {
1061 ushort *uc = upperCased;
1062 if (len > 256)
1063 uc = new ushort[len];
1064 for (int i = 0; i < len; ++i) {
1065 if(si.analysis.flags == QScriptAnalysis::Lowercase)
1066 uc[i] = str[i].toLower().unicode();
1067 else
1068 uc[i] = str[i].toUpper().unicode();
1069 }
1070 str = reinterpret_cast<const QChar *>(uc);
1071 }
1072
1073 while (true) {
1074 ensureSpace(num_glyphs);
1075 num_glyphs = layoutData->glyphLayout.numGlyphs - layoutData->used;
1076
1077 QGlyphLayout g = availableGlyphs(&si);
1078 unsigned short *log_clusters = logClusters(&si);
1079
1080 if (fe->stringToCMap(str,
1081 len,
1082 &g,
1083 &num_glyphs,
1084 flags)) {
1085 heuristicSetGlyphAttributes(str, len, &g, log_clusters, num_glyphs);
1086 break;
1087 }
1088 }
1089
1090 si.num_glyphs = num_glyphs;
1091
1092 layoutData->used += si.num_glyphs;
1093
1094 const ushort *uc = reinterpret_cast<const ushort *>(str);
1095 if ((si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase
1096 || si.analysis.flags == QScriptAnalysis::Lowercase)
1097 && uc != upperCased)
1098 delete [] uc;
1099}
1100#endif
1101
1102static inline void moveGlyphData(const QGlyphLayout &destination, const QGlyphLayout &source, int num)
1103{
1104 if (num > 0 && destination.glyphs != source.glyphs) {
1105 memmove(destination.glyphs, source.glyphs, num * sizeof(HB_Glyph));
1106 memmove(destination.attributes, source.attributes, num * sizeof(HB_GlyphAttributes));
1107 memmove(destination.advances_x, source.advances_x, num * sizeof(HB_Fixed));
1108 memmove(destination.offsets, source.offsets, num * sizeof(HB_FixedPoint));
1109 }
1110}
1111
1112/// take the item from layoutData->items and
1113void QTextEngine::shapeTextWithHarfbuzz(int item) const
1114{
1115 Q_ASSERT(sizeof(HB_Fixed) == sizeof(QFixed));
1116 Q_ASSERT(sizeof(HB_FixedPoint) == sizeof(QFixedPoint));
1117
1118 QScriptItem &si = layoutData->items[item];
1119
1120 si.glyph_data_offset = layoutData->used;
1121
1122 QFontEngine *font = fontEngine(si, &si.ascent, &si.descent, &si.leading);
1123
1124 bool kerningEnabled = this->font(si).d->kerning;
1125
1126 HB_ShaperItem entire_shaper_item;
1127 entire_shaper_item.kerning_applied = false;
1128 entire_shaper_item.string = reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData());
1129 entire_shaper_item.stringLength = layoutData->string.length();
1130 entire_shaper_item.item.script = (HB_Script)si.analysis.script;
1131 entire_shaper_item.item.pos = si.position;
1132 entire_shaper_item.item.length = length(item);
1133 entire_shaper_item.item.bidiLevel = si.analysis.bidiLevel;
1134 entire_shaper_item.glyphIndicesPresent = false;
1135
1136 HB_UChar16 upperCased[256]; // XXX what about making this 4096, so we don't have to extend it ever.
1137 if (si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase
1138 || si.analysis.flags == QScriptAnalysis::Lowercase) {
1139 HB_UChar16 *uc = upperCased;
1140 if (entire_shaper_item.item.length > 256)
1141 uc = new HB_UChar16[entire_shaper_item.item.length];
1142 for (uint i = 0; i < entire_shaper_item.item.length; ++i) {
1143 if(si.analysis.flags == QScriptAnalysis::Lowercase)
1144 uc[i] = QChar::toLower(entire_shaper_item.string[si.position + i]);
1145 else
1146 uc[i] = QChar::toUpper(entire_shaper_item.string[si.position + i]);
1147 }
1148 entire_shaper_item.item.pos = 0;
1149 entire_shaper_item.string = uc;
1150 entire_shaper_item.stringLength = entire_shaper_item.item.length;
1151 }
1152
1153 entire_shaper_item.shaperFlags = 0;
1154 if (!kerningEnabled)
1155 entire_shaper_item.shaperFlags |= HB_ShaperFlag_NoKerning;
1156 if (option.useDesignMetrics())
1157 entire_shaper_item.shaperFlags |= HB_ShaperFlag_UseDesignMetrics;
1158
1159 entire_shaper_item.num_glyphs = qMax(layoutData->glyphLayout.numGlyphs - layoutData->used, int(entire_shaper_item.item.length));
1160 ensureSpace(entire_shaper_item.num_glyphs);
1161 QGlyphLayout initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1162
1163 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1164 ensureSpace(entire_shaper_item.num_glyphs);
1165 initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1166
1167 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1168 // ############ if this happens there's a bug in the fontengine
1169 if ((si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase
1170 || si.analysis.flags == QScriptAnalysis::Lowercase) && entire_shaper_item.string != upperCased)
1171 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1172 return;
1173 }
1174 }
1175
1176 // split up the item into parts that come from different font engines.
1177 QVarLengthArray<int> itemBoundaries(2);
1178 // k * 2 entries, array[k] == index in string, array[k + 1] == index in glyphs
1179 itemBoundaries[0] = entire_shaper_item.item.pos;
1180 itemBoundaries[1] = 0;
1181
1182 if (font->type() == QFontEngine::Multi) {
1183 uint lastEngine = 0;
1184 int charIdx = entire_shaper_item.item.pos;
1185 const int stringEnd = charIdx + entire_shaper_item.item.length;
1186 for (quint32 i = 0; i < entire_shaper_item.num_glyphs; ++i, ++charIdx) {
1187 uint engineIdx = initialGlyphs.glyphs[i] >> 24;
1188 if (engineIdx != lastEngine && i > 0) {
1189 itemBoundaries.append(charIdx);
1190 itemBoundaries.append(i);
1191 }
1192 lastEngine = engineIdx;
1193 if (HB_IsHighSurrogate(entire_shaper_item.string[charIdx])
1194 && charIdx < stringEnd - 1
1195 && HB_IsLowSurrogate(entire_shaper_item.string[charIdx + 1]))
1196 ++charIdx;
1197 }
1198 }
1199
1200
1201
1202 int remaining_glyphs = entire_shaper_item.num_glyphs;
1203 int glyph_pos = 0;
1204 // for each item shape using harfbuzz and store the results in our layoutData's glyphs array.
1205 for (int k = 0; k < itemBoundaries.size(); k += 2) { // for the +2, see the comment at the definition of itemBoundaries
1206
1207 HB_ShaperItem shaper_item = entire_shaper_item;
1208
1209 shaper_item.item.pos = itemBoundaries[k];
1210 if (k < itemBoundaries.size() - 3) {
1211 shaper_item.item.length = itemBoundaries[k + 2] - shaper_item.item.pos;
1212 shaper_item.num_glyphs = itemBoundaries[k + 3] - itemBoundaries[k + 1];
1213 } else { // last combo in the list, avoid out of bounds access.
1214 shaper_item.item.length -= shaper_item.item.pos - entire_shaper_item.item.pos;
1215 shaper_item.num_glyphs -= itemBoundaries[k + 1];
1216 }
1217 shaper_item.initialGlyphCount = shaper_item.num_glyphs;
1218
1219 QFontEngine *actualFontEngine = font;
1220 uint engineIdx = 0;
1221 if (font->type() == QFontEngine::Multi) {
1222 engineIdx = uint(availableGlyphs(&si).glyphs[glyph_pos] >> 24);
1223
1224 actualFontEngine = static_cast<QFontEngineMulti *>(font)->engine(engineIdx);
1225 }
1226
1227 shaper_item.font = actualFontEngine->harfbuzzFont();
1228 shaper_item.face = actualFontEngine->harfbuzzFace();
1229
1230 shaper_item.glyphIndicesPresent = true;
1231
1232 remaining_glyphs -= shaper_item.initialGlyphCount;
1233
1234 do {
1235 ensureSpace(glyph_pos + shaper_item.num_glyphs + remaining_glyphs);
1236
1237 const QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos);
1238 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1239
1240 shaper_item.glyphs = g.glyphs;
1241 shaper_item.attributes = g.attributes;
1242 shaper_item.advances = reinterpret_cast<HB_Fixed *>(g.advances_x);
1243 shaper_item.offsets = reinterpret_cast<HB_FixedPoint *>(g.offsets);
1244
1245 if (shaper_item.glyphIndicesPresent) {
1246 for (hb_uint32 i = 0; i < shaper_item.initialGlyphCount; ++i)
1247 shaper_item.glyphs[i] &= 0x00ffffff;
1248 }
1249
1250 shaper_item.log_clusters = logClusters(&si) + shaper_item.item.pos - entire_shaper_item.item.pos;
1251
1252// qDebug(" .. num_glyphs=%d, used=%d, item.num_glyphs=%d", num_glyphs, used, shaper_item.num_glyphs);
1253 } while (!qShapeItem(&shaper_item)); // this does the actual shaping via harfbuzz.
1254
1255 QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos, shaper_item.num_glyphs);
1256 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1257
1258 for (hb_uint32 i = 0; i < shaper_item.num_glyphs; ++i)
1259 g.glyphs[i] = g.glyphs[i] | (engineIdx << 24);
1260
1261 for (hb_uint32 i = 0; i < shaper_item.item.length; ++i)
1262 shaper_item.log_clusters[i] += glyph_pos;
1263
1264 if (kerningEnabled && !shaper_item.kerning_applied)
1265 font->doKerning(&g, option.useDesignMetrics() ? QFlag(QTextEngine::DesignMetrics) : QFlag(0));
1266
1267 glyph_pos += shaper_item.num_glyphs;
1268 }
1269
1270// qDebug(" -> item: script=%d num_glyphs=%d", shaper_item.script, shaper_item.num_glyphs);
1271 si.num_glyphs = glyph_pos;
1272
1273 layoutData->used += si.num_glyphs;
1274
1275 if ((si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase)
1276 && entire_shaper_item.string != upperCased)
1277 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1278}
1279
1280static void init(QTextEngine *e)
1281{
1282 e->ignoreBidi = false;
1283 e->cacheGlyphs = false;
1284 e->forceJustification = false;
1285
1286 e->layoutData = 0;
1287
1288 e->minWidth = 0;
1289 e->maxWidth = 0;
1290
1291 e->underlinePositions = 0;
1292 e->specialData = 0;
1293 e->stackEngine = false;
1294}
1295
1296QTextEngine::QTextEngine()
1297{
1298 init(this);
1299}
1300
1301QTextEngine::QTextEngine(const QString &str, const QFont &f)
1302 : fnt(f)
1303{
1304 init(this);
1305 text = str;
1306}
1307
1308QTextEngine::~QTextEngine()
1309{
1310 if (!stackEngine)
1311 delete layoutData;
1312 delete specialData;
1313}
1314
1315const HB_CharAttributes *QTextEngine::attributes() const
1316{
1317 if (layoutData && layoutData->haveCharAttributes)
1318 return (HB_CharAttributes *) layoutData->memory;
1319
1320 itemize();
1321 ensureSpace(layoutData->string.length());
1322
1323 QVarLengthArray<HB_ScriptItem> hbScriptItems(layoutData->items.size());
1324
1325 for (int i = 0; i < layoutData->items.size(); ++i) {
1326 const QScriptItem &si = layoutData->items[i];
1327 hbScriptItems[i].pos = si.position;
1328 hbScriptItems[i].length = length(i);
1329 hbScriptItems[i].bidiLevel = si.analysis.bidiLevel;
1330 hbScriptItems[i].script = (HB_Script)si.analysis.script;
1331 }
1332
1333 qGetCharAttributes(reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData()),
1334 layoutData->string.length(),
1335 hbScriptItems.data(), hbScriptItems.size(),
1336 (HB_CharAttributes *)layoutData->memory);
1337
1338
1339 layoutData->haveCharAttributes = true;
1340 return (HB_CharAttributes *) layoutData->memory;
1341}
1342
1343void QTextEngine::shape(int item) const
1344{
1345 if (layoutData->items[item].analysis.flags == QScriptAnalysis::Object) {
1346 ensureSpace(1);
1347 if (block.docHandle()) {
1348 QTextFormat format = formats()->format(formatIndex(&layoutData->items[item]));
1349 docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
1350 layoutData->items[item].position + block.position(), format);
1351 }
1352 } else if (layoutData->items[item].analysis.flags == QScriptAnalysis::Tab) {
1353 // set up at least the ascent/descent/leading of the script item for the tab
1354 fontEngine(layoutData->items[item],
1355 &layoutData->items[item].ascent,
1356 &layoutData->items[item].descent,
1357 &layoutData->items[item].leading);
1358 } else {
1359 shapeText(item);
1360 }
1361}
1362
1363void QTextEngine::invalidate()
1364{
1365 freeMemory();
1366 minWidth = 0;
1367 maxWidth = 0;
1368 if (specialData)
1369 specialData->resolvedFormatIndices.clear();
1370}
1371
1372void QTextEngine::clearLineData()
1373{
1374 lines.clear();
1375}
1376
1377void QTextEngine::validate() const
1378{
1379 if (layoutData)
1380 return;
1381 layoutData = new LayoutData();
1382 if (block.docHandle()) {
1383 layoutData->string = block.text();
1384 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1385 layoutData->string += QLatin1Char(block.next().isValid() ? 0xb6 : 0x20);
1386 } else {
1387 layoutData->string = text;
1388 }
1389 if (specialData && specialData->preeditPosition != -1)
1390 layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
1391}
1392
1393void QTextEngine::itemize() const
1394{
1395 validate();
1396 if (layoutData->items.size())
1397 return;
1398
1399 int length = layoutData->string.length();
1400 if (!length)
1401 return;
1402#if defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA)
1403 // ATSUI requires RTL flags to correctly identify the character stops.
1404 bool ignore = false;
1405#else
1406 bool ignore = ignoreBidi;
1407#endif
1408 if (!ignore && option.textDirection() == Qt::LeftToRight) {
1409 ignore = true;
1410 const QChar *start = layoutData->string.unicode();
1411 const QChar * const end = start + length;
1412 while (start < end) {
1413 if (start->unicode() >= 0x590) {
1414 ignore = false;
1415 break;
1416 }
1417 ++start;
1418 }
1419 }
1420
1421 QVarLengthArray<QScriptAnalysis, 4096> scriptAnalysis(length);
1422 QScriptAnalysis *analysis = scriptAnalysis.data();
1423
1424 QBidiControl control(option.textDirection() == Qt::RightToLeft);
1425
1426 if (ignore) {
1427 memset(analysis, 0, length*sizeof(QScriptAnalysis));
1428 if (option.textDirection() == Qt::RightToLeft) {
1429 for (int i = 0; i < length; ++i)
1430 analysis[i].bidiLevel = 1;
1431 layoutData->hasBidi = true;
1432 }
1433 } else {
1434 layoutData->hasBidi = bidiItemize(const_cast<QTextEngine *>(this), analysis, control);
1435 }
1436
1437 const ushort *unicode = layoutData->string.utf16();
1438 // correctly assign script, isTab and isObject to the script analysis
1439 const ushort *uc = unicode;
1440 const ushort *e = uc + length;
1441 int lastScript = QUnicodeTables::Common;
1442 while (uc < e) {
1443 int script = QUnicodeTables::script(*uc);
1444 if (script == QUnicodeTables::Inherited)
1445 script = lastScript;
1446 analysis->flags = QScriptAnalysis::None;
1447 if (*uc == QChar::ObjectReplacementCharacter) {
1448 if (analysis->bidiLevel % 2)
1449 --analysis->bidiLevel;
1450 analysis->script = QUnicodeTables::Common;
1451 analysis->flags = QScriptAnalysis::Object;
1452 } else if (*uc == QChar::LineSeparator) {
1453 if (analysis->bidiLevel % 2)
1454 --analysis->bidiLevel;
1455 analysis->script = QUnicodeTables::Common;
1456 analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
1457 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1458 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
1459 } else if (*uc == 9) {
1460 analysis->script = QUnicodeTables::Common;
1461 analysis->flags = QScriptAnalysis::Tab;
1462 analysis->bidiLevel = control.baseLevel();
1463 } else if ((*uc == 32 || *uc == QChar::Nbsp)
1464 && (option.flags() & QTextOption::ShowTabsAndSpaces)) {
1465 analysis->script = QUnicodeTables::Common;
1466 analysis->flags = QScriptAnalysis::Space;
1467 analysis->bidiLevel = control.baseLevel();
1468 } else {
1469 analysis->script = script;
1470 }
1471 lastScript = analysis->script;
1472 ++uc;
1473 ++analysis;
1474 }
1475 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
1476 (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
1477 }
1478
1479 Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
1480
1481 const QTextDocumentPrivate *p = block.docHandle();
1482 if (p) {
1483 SpecialData *s = specialData;
1484
1485 QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
1486 QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
1487 int format = it.value()->format;
1488
1489 int prevPosition = 0;
1490 int position = prevPosition;
1491 while (1) {
1492 const QTextFragmentData * const frag = it.value();
1493 if (it == end || format != frag->format) {
1494 if (s && position >= s->preeditPosition) {
1495 position += s->preeditText.length();
1496 s = 0;
1497 }
1498 Q_ASSERT(position <= length);
1499 itemizer.generate(prevPosition, position - prevPosition,
1500 formats()->charFormat(format).fontCapitalization());
1501 if (it == end) {
1502 if (position < length)
1503 itemizer.generate(position, length - position,
1504 formats()->charFormat(format).fontCapitalization());
1505 break;
1506 }
1507 format = frag->format;
1508 prevPosition = position;
1509 }
1510 position += frag->size_array[0];
1511 ++it;
1512 }
1513 } else {
1514 itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
1515 }
1516
1517 addRequiredBoundaries();
1518 resolveAdditionalFormats();
1519}
1520
1521int QTextEngine::findItem(int strPos) const
1522{
1523 itemize();
1524
1525 // ##### use binary search
1526 int item;
1527 for (item = layoutData->items.size()-1; item > 0; --item) {
1528 if (layoutData->items[item].position <= strPos)
1529 break;
1530 }
1531 return item;
1532}
1533
1534QFixed QTextEngine::width(int from, int len) const
1535{
1536 itemize();
1537
1538 QFixed w = 0;
1539
1540// qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from, len, items.size(), string.length());
1541 for (int i = 0; i < layoutData->items.size(); i++) {
1542 const QScriptItem *si = layoutData->items.constData() + i;
1543 int pos = si->position;
1544 int ilen = length(i);
1545// qDebug("item %d: from %d len %d", i, pos, ilen);
1546 if (pos >= from + len)
1547 break;
1548 if (pos + ilen > from) {
1549 if (!si->num_glyphs)
1550 shape(i);
1551
1552 if (si->analysis.flags == QScriptAnalysis::Object) {
1553 w += si->width;
1554 continue;
1555 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1556 w += calculateTabWidth(i, w);
1557 continue;
1558 }
1559
1560
1561 QGlyphLayout glyphs = shapedGlyphs(si);
1562 unsigned short *logClusters = this->logClusters(si);
1563
1564// fprintf(stderr, " logclusters:");
1565// for (int k = 0; k < ilen; k++)
1566// fprintf(stderr, " %d", logClusters[k]);
1567// fprintf(stderr, "\n");
1568 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1569 int charFrom = from - pos;
1570 if (charFrom < 0)
1571 charFrom = 0;
1572 int glyphStart = logClusters[charFrom];
1573 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1574 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1575 charFrom++;
1576 if (charFrom < ilen) {
1577 glyphStart = logClusters[charFrom];
1578 int charEnd = from + len - 1 - pos;
1579 if (charEnd >= ilen)
1580 charEnd = ilen-1;
1581 int glyphEnd = logClusters[charEnd];
1582 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1583 charEnd++;
1584 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1585
1586// qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
1587 for (int i = glyphStart; i < glyphEnd; i++)
1588 w += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
1589 }
1590 }
1591 }
1592// qDebug(" --> w= %d ", w);
1593 return w;
1594}
1595
1596glyph_metrics_t QTextEngine::boundingBox(int from, int len) const
1597{
1598 itemize();
1599
1600 glyph_metrics_t gm;
1601
1602 for (int i = 0; i < layoutData->items.size(); i++) {
1603 const QScriptItem *si = layoutData->items.constData() + i;
1604 QFontEngine *fe = fontEngine(*si);
1605
1606 int pos = si->position;
1607 int ilen = length(i);
1608 if (pos > from + len)
1609 break;
1610 if (pos + ilen > from) {
1611 if (!si->num_glyphs)
1612 shape(i);
1613
1614 if (si->analysis.flags == QScriptAnalysis::Object) {
1615 gm.width += si->width;
1616 continue;
1617 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1618 gm.width += calculateTabWidth(i, gm.width);
1619 continue;
1620 }
1621
1622 unsigned short *logClusters = this->logClusters(si);
1623 QGlyphLayout glyphs = shapedGlyphs(si);
1624
1625 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1626 int charFrom = from - pos;
1627 if (charFrom < 0)
1628 charFrom = 0;
1629 int glyphStart = logClusters[charFrom];
1630 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1631 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1632 charFrom++;
1633 if (charFrom < ilen) {
1634 glyphStart = logClusters[charFrom];
1635 int charEnd = from + len - 1 - pos;
1636 if (charEnd >= ilen)
1637 charEnd = ilen-1;
1638 int glyphEnd = logClusters[charEnd];
1639 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1640 charEnd++;
1641 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1642 if (glyphStart <= glyphEnd ) {
1643 glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1644 gm.x = qMin(gm.x, m.x + gm.xoff);
1645 gm.y = qMin(gm.y, m.y + gm.yoff);
1646 gm.width = qMax(gm.width, m.width+gm.xoff);
1647 gm.height = qMax(gm.height, m.height+gm.yoff);
1648 gm.xoff += m.xoff;
1649 gm.yoff += m.yoff;
1650 }
1651 }
1652
1653 glyph_t glyph = glyphs.glyphs[logClusters[pos + ilen - 1]];
1654 glyph_metrics_t gi = fe->boundingBox(glyph);
1655 if (gi.isValid())
1656 gm.width -= qRound(gi.xoff - gi.x - gi.width);
1657 }
1658 }
1659 return gm;
1660}
1661
1662glyph_metrics_t QTextEngine::tightBoundingBox(int from, int len) const
1663{
1664 itemize();
1665
1666 glyph_metrics_t gm;
1667
1668 for (int i = 0; i < layoutData->items.size(); i++) {
1669 const QScriptItem *si = layoutData->items.constData() + i;
1670 int pos = si->position;
1671 int ilen = length(i);
1672 if (pos > from + len)
1673 break;
1674 if (pos + len > from) {
1675 if (!si->num_glyphs)
1676 shape(i);
1677 unsigned short *logClusters = this->logClusters(si);
1678 QGlyphLayout glyphs = shapedGlyphs(si);
1679
1680 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1681 int charFrom = from - pos;
1682 if (charFrom < 0)
1683 charFrom = 0;
1684 int glyphStart = logClusters[charFrom];
1685 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1686 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1687 charFrom++;
1688 if (charFrom < ilen) {
1689 glyphStart = logClusters[charFrom];
1690 int charEnd = from + len - 1 - pos;
1691 if (charEnd >= ilen)
1692 charEnd = ilen-1;
1693 int glyphEnd = logClusters[charEnd];
1694 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1695 charEnd++;
1696 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1697 if (glyphStart <= glyphEnd ) {
1698 QFontEngine *fe = fontEngine(*si);
1699 glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1700 gm.x = qMin(gm.x, m.x + gm.xoff);
1701 gm.y = qMin(gm.y, m.y + gm.yoff);
1702 gm.width = qMax(gm.width, m.width+gm.xoff);
1703 gm.height = qMax(gm.height, m.height+gm.yoff);
1704 gm.xoff += m.xoff;
1705 gm.yoff += m.yoff;
1706 }
1707 }
1708 }
1709 }
1710 return gm;
1711}
1712
1713QFont QTextEngine::font(const QScriptItem &si) const
1714{
1715 QFont font = fnt;
1716 if (hasFormats()) {
1717 QTextCharFormat f = format(&si);
1718 font = f.font();
1719
1720 if (block.docHandle() && block.docHandle()->layout()) {
1721 // Make sure we get the right dpi on printers
1722 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1723 if (pdev)
1724 font = QFont(font, pdev);
1725 } else {
1726 font = font.resolve(fnt);
1727 }
1728 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1729 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1730 if (font.pointSize() != -1)
1731 font.setPointSize((font.pointSize() * 2) / 3);
1732 else
1733 font.setPixelSize((font.pixelSize() * 2) / 3);
1734 }
1735 }
1736
1737 if (si.analysis.flags == QScriptAnalysis::SmallCaps)
1738 font = font.d->smallCapsFont();
1739
1740 return font;
1741}
1742
1743QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
1744{
1745 QFontEngine *engine = 0;
1746 QFontEngine *scaledEngine = 0;
1747 int script = si.analysis.script;
1748
1749 QFont font = fnt;
1750 if (hasFormats()) {
1751 QTextCharFormat f = format(&si);
1752 font = f.font();
1753
1754 if (block.docHandle() && block.docHandle()->layout()) {
1755 // Make sure we get the right dpi on printers
1756 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1757 if (pdev)
1758 font = QFont(font, pdev);
1759 } else {
1760 font = font.resolve(fnt);
1761 }
1762 engine = font.d->engineForScript(script);
1763 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1764 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1765 if (font.pointSize() != -1)
1766 font.setPointSize((font.pointSize() * 2) / 3);
1767 else
1768 font.setPixelSize((font.pixelSize() * 2) / 3);
1769 scaledEngine = font.d->engineForScript(script);
1770 }
1771 } else {
1772 engine = font.d->engineForScript(script);
1773 }
1774
1775 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
1776 QFontPrivate *p = font.d->smallCapsFontPrivate();
1777 scaledEngine = p->engineForScript(script);
1778 }
1779
1780 if (ascent) {
1781 *ascent = engine->ascent();
1782 *descent = engine->descent();
1783 *leading = engine->leading();
1784 }
1785
1786 if (scaledEngine)
1787 return scaledEngine;
1788 return engine;
1789}
1790
1791struct QJustificationPoint {
1792 int type;
1793 QFixed kashidaWidth;
1794 QGlyphLayout glyph;
1795 QFontEngine *fontEngine;
1796};
1797
1798Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE);
1799
1800static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
1801{
1802 point->type = type;
1803 point->glyph = glyph;
1804 point->fontEngine = fe;
1805
1806 if (type >= HB_Arabic_Normal) {
1807 QChar ch(0x640); // Kashida character
1808 QGlyphLayoutArray<8> glyphs;
1809 int nglyphs = 7;
1810 fe->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1811 if (glyphs.glyphs[0] && glyphs.advances_x[0] != 0) {
1812 point->kashidaWidth = glyphs.advances_x[0];
1813 } else {
1814 point->type = HB_NoJustification;
1815 point->kashidaWidth = 0;
1816 }
1817 }
1818}
1819
1820
1821void QTextEngine::justify(const QScriptLine &line)
1822{
1823// qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
1824 if (line.gridfitted && line.justified)
1825 return;
1826
1827 if (!line.gridfitted) {
1828 // redo layout in device metrics, then adjust
1829 const_cast<QScriptLine &>(line).gridfitted = true;
1830 }
1831
1832 if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
1833 return;
1834
1835 itemize();
1836
1837 if (!forceJustification) {
1838 int end = line.from + (int)line.length;
1839 if (end == layoutData->string.length())
1840 return; // no justification at end of paragraph
1841 if (end && layoutData->items[findItem(end-1)].analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
1842 return; // no justification at the end of an explicitely separated line
1843 }
1844
1845 // justify line
1846 int maxJustify = 0;
1847
1848 // don't include trailing white spaces when doing justification
1849 int line_length = line.length;
1850 const HB_CharAttributes *a = attributes()+line.from;
1851 while (line_length && a[line_length-1].whiteSpace)
1852 --line_length;
1853 // subtract one char more, as we can't justfy after the last character
1854 --line_length;
1855
1856 if (!line_length)
1857 return;
1858
1859 int firstItem = findItem(line.from);
1860 int nItems = findItem(line.from + line_length - 1) - firstItem + 1;
1861
1862 QVarLengthArray<QJustificationPoint> justificationPoints;
1863 int nPoints = 0;
1864// qDebug("justifying from %d len %d, firstItem=%d, nItems=%d (%s)", line.from, line_length, firstItem, nItems, layoutData->string.mid(line.from, line_length).toUtf8().constData());
1865 QFixed minKashida = 0x100000;
1866
1867 // we need to do all shaping before we go into the next loop, as we there
1868 // store pointers to the glyph data that could get reallocated by the shaping
1869 // process.
1870 for (int i = 0; i < nItems; ++i) {
1871 QScriptItem &si = layoutData->items[firstItem + i];
1872 if (!si.num_glyphs)
1873 shape(firstItem + i);
1874 }
1875
1876 for (int i = 0; i < nItems; ++i) {
1877 QScriptItem &si = layoutData->items[firstItem + i];
1878
1879 int kashida_type = HB_Arabic_Normal;
1880 int kashida_pos = -1;
1881
1882 int start = qMax(line.from - si.position, 0);
1883 int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
1884
1885 unsigned short *log_clusters = logClusters(&si);
1886
1887 int gs = log_clusters[start];
1888 int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
1889
1890 const QGlyphLayout g = shapedGlyphs(&si);
1891
1892 for (int i = gs; i < ge; ++i) {
1893 g.justifications[i].type = QGlyphJustification::JustifyNone;
1894 g.justifications[i].nKashidas = 0;
1895 g.justifications[i].space_18d6 = 0;
1896
1897 justificationPoints.resize(nPoints+3);
1898 int justification = g.attributes[i].justification;
1899
1900 switch(justification) {
1901 case HB_NoJustification:
1902 break;
1903 case HB_Space :
1904 // fall through
1905 case HB_Arabic_Space :
1906 if (kashida_pos >= 0) {
1907// qDebug("kashida position at %d in word", kashida_pos);
1908 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
1909 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
1910 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
1911 ++nPoints;
1912 }
1913 kashida_pos = -1;
1914 kashida_type = HB_Arabic_Normal;
1915 // fall through
1916 case HB_Character :
1917 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
1918 maxJustify = qMax(maxJustify, justification);
1919 break;
1920 case HB_Arabic_Normal :
1921 case HB_Arabic_Waw :
1922 case HB_Arabic_BaRa :
1923 case HB_Arabic_Alef :
1924 case HB_Arabic_HaaDal :
1925 case HB_Arabic_Seen :
1926 case HB_Arabic_Kashida :
1927 if (justification >= kashida_type) {
1928 kashida_pos = i;
1929 kashida_type = justification;
1930 }
1931 }
1932 }
1933 if (kashida_pos >= 0) {
1934 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
1935 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
1936 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
1937 ++nPoints;
1938 }
1939 }
1940
1941 QFixed need = line.width - line.textWidth;
1942 if (need < 0) {
1943 // line overflows already!
1944 const_cast<QScriptLine &>(line).justified = true;
1945 return;
1946 }
1947
1948// qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
1949// qDebug(" minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
1950
1951 // distribute in priority order
1952 if (maxJustify >= HB_Arabic_Normal) {
1953 while (need >= minKashida) {
1954 for (int type = maxJustify; need >= minKashida && type >= HB_Arabic_Normal; --type) {
1955 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
1956 if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
1957 justificationPoints[i].glyph.justifications->nKashidas++;
1958 // ############
1959 justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
1960 need -= justificationPoints[i].kashidaWidth;
1961// qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
1962 }
1963 }
1964 }
1965 }
1966 }
1967 Q_ASSERT(need >= 0);
1968 if (!need)
1969 goto end;
1970
1971 maxJustify = qMin(maxJustify, (int)HB_Space);
1972 for (int type = maxJustify; need != 0 && type > 0; --type) {
1973 int n = 0;
1974 for (int i = 0; i < nPoints; ++i) {
1975 if (justificationPoints[i].type == type)
1976 ++n;
1977 }
1978// qDebug("number of points for justification type %d: %d", type, n);
1979
1980
1981 if (!n)
1982 continue;
1983
1984 for (int i = 0; i < nPoints; ++i) {
1985 if (justificationPoints[i].type == type) {
1986 QFixed add = need/n;
1987// qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
1988 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
1989 need -= add;
1990 --n;
1991 }
1992 }
1993
1994 Q_ASSERT(!need);
1995 }
1996 end:
1997 const_cast<QScriptLine &>(line).justified = true;
1998}
1999
2000void QScriptLine::setDefaultHeight(QTextEngine *eng)
2001{
2002 QFont f;
2003 QFontEngine *e;
2004
2005 if (eng->block.docHandle() && eng->block.docHandle()->layout()) {
2006 f = eng->block.charFormat().font();
2007 // Make sure we get the right dpi on printers
2008 QPaintDevice *pdev = eng->block.docHandle()->layout()->paintDevice();
2009 if (pdev)
2010 f = QFont(f, pdev);
2011 e = f.d->engineForScript(QUnicodeTables::Common);
2012 } else {
2013 e = eng->fnt.d->engineForScript(QUnicodeTables::Common);
2014 }
2015
2016 QFixed other_ascent = e->ascent();
2017 QFixed other_descent = e->descent();
2018 QFixed other_leading = e->leading();
2019 leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2020 ascent = qMax(ascent, other_ascent);
2021 descent = qMax(descent, other_descent);
2022}
2023
2024QTextEngine::LayoutData::LayoutData()
2025{
2026 memory = 0;
2027 allocated = 0;
2028 memory_on_stack = false;
2029 used = 0;
2030 hasBidi = false;
2031 inLayout = false;
2032 haveCharAttributes = false;
2033 logClustersPtr = 0;
2034 available_glyphs = 0;
2035}
2036
2037QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, int _allocated)
2038 : string(str)
2039{
2040 allocated = _allocated;
2041
2042 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2043 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2044 available_glyphs = ((int)allocated - space_charAttributes - space_logClusters)*(int)sizeof(void*)/(int)QGlyphLayout::spaceNeededForGlyphLayout(1);
2045
2046 if (available_glyphs < str.length()) {
2047 // need to allocate on the heap
2048 allocated = 0;
2049
2050 memory_on_stack = false;
2051 memory = 0;
2052 logClustersPtr = 0;
2053 } else {
2054 memory_on_stack = true;
2055 memory = stack_memory;
2056 logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2057
2058 void *m = memory + space_charAttributes + space_logClusters;
2059 glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.length());
2060 glyphLayout.clear();
2061 memset(memory, 0, space_charAttributes*sizeof(void *));
2062 }
2063 used = 0;
2064 hasBidi = false;
2065 inLayout = false;
2066 haveCharAttributes = false;
2067}
2068
2069QTextEngine::LayoutData::~LayoutData()
2070{
2071 if (!memory_on_stack)
2072 free(memory);
2073 memory = 0;
2074}
2075
2076void QTextEngine::LayoutData::reallocate(int totalGlyphs)
2077{
2078 Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2079 if (memory_on_stack && available_glyphs >= totalGlyphs) {
2080 glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2081 return;
2082 }
2083
2084 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2085 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2086 int space_glyphs = QGlyphLayout::spaceNeededForGlyphLayout(totalGlyphs)/sizeof(void*) + 2;
2087
2088 int newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2089 Q_ASSERT(newAllocated >= allocated);
2090 void **newMem = memory;
2091 newMem = (void **)::realloc(memory_on_stack ? 0 : memory, newAllocated*sizeof(void *));
2092 Q_CHECK_PTR(newMem);
2093 if (memory_on_stack && newMem)
2094 memcpy(newMem, memory, allocated*sizeof(void *));
2095 memory = newMem;
2096 memory_on_stack = false;
2097
2098 void **m = memory;
2099 m += space_charAttributes;
2100 logClustersPtr = (unsigned short *) m;
2101 m += space_logClusters;
2102
2103 const int space_preGlyphLayout = space_charAttributes + space_logClusters;
2104 if (allocated < space_preGlyphLayout)
2105 memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2106
2107 glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2108
2109 allocated = newAllocated;
2110}
2111
2112// grow to the new size, copying the existing data to the new layout
2113void QGlyphLayout::grow(char *address, int totalGlyphs)
2114{
2115 QGlyphLayout oldLayout(address, numGlyphs);
2116 QGlyphLayout newLayout(address, totalGlyphs);
2117
2118 if (numGlyphs) {
2119 // move the existing data
2120 memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(HB_GlyphAttributes));
2121 memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2122 memmove(newLayout.advances_y, oldLayout.advances_y, numGlyphs * sizeof(QFixed));
2123 memmove(newLayout.advances_x, oldLayout.advances_x, numGlyphs * sizeof(QFixed));
2124 memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(HB_Glyph));
2125 }
2126
2127 // clear the new data
2128 newLayout.clear(numGlyphs);
2129
2130 *this = newLayout;
2131}
2132
2133void QTextEngine::freeMemory()
2134{
2135 if (!stackEngine) {
2136 delete layoutData;
2137 layoutData = 0;
2138 } else {
2139 layoutData->used = 0;
2140 layoutData->hasBidi = false;
2141 layoutData->inLayout = false;
2142 layoutData->haveCharAttributes = false;
2143 }
2144 for (int i = 0; i < lines.size(); ++i) {
2145 lines[i].justified = 0;
2146 lines[i].gridfitted = 0;
2147 }
2148}
2149
2150int QTextEngine::formatIndex(const QScriptItem *si) const
2151{
2152 if (specialData && !specialData->resolvedFormatIndices.isEmpty())
2153 return specialData->resolvedFormatIndices.at(si - &layoutData->items[0]);
2154 QTextDocumentPrivate *p = block.docHandle();
2155 if (!p)
2156 return -1;
2157 int pos = si->position;
2158 if (specialData && si->position >= specialData->preeditPosition) {
2159 if (si->position < specialData->preeditPosition + specialData->preeditText.length())
2160 pos = qMax(specialData->preeditPosition - 1, 0);
2161 else
2162 pos -= specialData->preeditText.length();
2163 }
2164 QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2165 return it.value()->format;
2166}
2167
2168
2169QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2170{
2171 QTextCharFormat format;
2172 const QTextFormatCollection *formats = 0;
2173 if (block.docHandle()) {
2174 formats = this->formats();
2175 format = formats->charFormat(formatIndex(si));
2176 }
2177 if (specialData && specialData->resolvedFormatIndices.isEmpty()) {
2178 int end = si->position + length(si);
2179 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2180 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2181 if (r.start <= si->position && r.start + r.length >= end) {
2182 if (!specialData->addFormatIndices.isEmpty())
2183 format.merge(formats->format(specialData->addFormatIndices.at(i)));
2184 else
2185 format.merge(r.format);
2186 }
2187 }
2188 }
2189 return format;
2190}
2191
2192void QTextEngine::addRequiredBoundaries() const
2193{
2194 if (specialData) {
2195 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2196 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2197 setBoundary(r.start);
2198 setBoundary(r.start + r.length);
2199 //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
2200 }
2201 }
2202}
2203
2204bool QTextEngine::atWordSeparator(int position) const
2205{
2206 const QChar c = layoutData->string.at(position);
2207 switch (c.toLatin1()) {
2208 case '.':
2209 case ',':
2210 case '?':
2211 case '!':
2212 case ':':
2213 case ';':
2214 case '-':
2215 case '<':
2216 case '>':
2217 case '[':
2218 case ']':
2219 case '(':
2220 case ')':
2221 case '{':
2222 case '}':
2223 case '=':
2224 case '/':
2225 case '+':
2226 case '%':
2227 case '&':
2228 case '^':
2229 case '*':
2230 case '\'':
2231 case '"':
2232 case '~':
2233 case '|':
2234 return true;
2235 default:
2236 return false;
2237 }
2238}
2239
2240bool QTextEngine::atSpace(int position) const
2241{
2242 const QChar c = layoutData->string.at(position);
2243
2244 return c == QLatin1Char(' ')
2245 || c == QChar::Nbsp
2246 || c == QChar::LineSeparator
2247 || c == QLatin1Char('\t')
2248 ;
2249}
2250
2251
2252void QTextEngine::indexAdditionalFormats()
2253{
2254 if (!block.docHandle())
2255 return;
2256
2257 specialData->addFormatIndices.resize(specialData->addFormats.count());
2258 QTextFormatCollection * const formats = this->formats();
2259
2260 for (int i = 0; i < specialData->addFormats.count(); ++i) {
2261 specialData->addFormatIndices[i] = formats->indexForFormat(specialData->addFormats.at(i).format);
2262 specialData->addFormats[i].format = QTextCharFormat();
2263 }
2264}
2265
2266/* These two helper functions are used to determine whether we need to insert a ZWJ character
2267 between the text that gets truncated and the ellipsis. This is important to get
2268 correctly shaped results for arabic text.
2269*/
2270static bool nextCharJoins(const QString &string, int pos)
2271{
2272 while (pos < string.length() && string.at(pos).category() == QChar::Mark_NonSpacing)
2273 ++pos;
2274 if (pos == string.length())
2275 return false;
2276 return string.at(pos).joining() != QChar::OtherJoining;
2277}
2278
2279static bool prevCharJoins(const QString &string, int pos)
2280{
2281 while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
2282 --pos;
2283 if (pos == 0)
2284 return false;
2285 return (string.at(pos - 1).joining() == QChar::Dual || string.at(pos - 1).joining() == QChar::Center);
2286}
2287
2288QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int flags) const
2289{
2290// qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
2291
2292 if (flags & Qt::TextShowMnemonic) {
2293 itemize();
2294 for (int i = 0; i < layoutData->items.size(); ++i) {
2295 QScriptItem &si = layoutData->items[i];
2296 if (!si.num_glyphs)
2297 shape(i);
2298
2299 HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
2300 unsigned short *logClusters = this->logClusters(&si);
2301 QGlyphLayout glyphs = shapedGlyphs(&si);
2302
2303 const int end = si.position + length(&si);
2304 for (int i = si.position; i < end - 1; ++i)
2305 if (layoutData->string.at(i) == QLatin1Char('&')) {
2306 const int gp = logClusters[i - si.position];
2307 glyphs.attributes[gp].dontPrint = true;
2308 attributes[i + 1].charStop = false;
2309 attributes[i + 1].whiteSpace = false;
2310 attributes[i + 1].lineBreakType = HB_NoBreak;
2311 if (i < end - 1
2312 && layoutData->string.at(i + 1) == QLatin1Char('&'))
2313 ++i;
2314 }
2315 }
2316 }
2317
2318 validate();
2319
2320 if (mode == Qt::ElideNone
2321 || this->width(0, layoutData->string.length()) <= width
2322 || layoutData->string.length() <= 1)
2323 return layoutData->string;
2324
2325 QFixed ellipsisWidth;
2326 QString ellipsisText;
2327 {
2328 QChar ellipsisChar(0x2026);
2329
2330 QFontEngine *fe = fnt.d->engineForScript(QUnicodeTables::Common);
2331
2332 QGlyphLayoutArray<1> ellipsisGlyph;
2333 {
2334 QFontEngine *feForEllipsis = (fe->type() == QFontEngine::Multi)
2335 ? static_cast<QFontEngineMulti *>(fe)->engine(0)
2336 : fe;
2337
2338 if (feForEllipsis->type() == QFontEngine::Mac)
2339 feForEllipsis = fe;
2340
2341 // the lookup can be really slow when we use XLFD fonts
2342 if (feForEllipsis->type() != QFontEngine::XLFD
2343 && feForEllipsis->canRender(&ellipsisChar, 1)) {
2344 int nGlyphs = 1;
2345 feForEllipsis->stringToCMap(&ellipsisChar, 1, &ellipsisGlyph, &nGlyphs, 0);
2346 }
2347 }
2348
2349 if (ellipsisGlyph.glyphs[0]) {
2350 ellipsisWidth = ellipsisGlyph.advances_x[0];
2351 ellipsisText = ellipsisChar;
2352 } else {
2353 QString dotDotDot(QLatin1String("..."));
2354
2355 QGlyphLayoutArray<3> glyphs;
2356 int nGlyphs = 3;
2357 if (!fe->stringToCMap(dotDotDot.constData(), 3, &glyphs, &nGlyphs, 0))
2358 // should never happen...
2359 return layoutData->string;
2360 for (int i = 0; i < nGlyphs; ++i)
2361 ellipsisWidth += glyphs.advances_x[i];
2362 ellipsisText = dotDotDot;
2363 }
2364 }
2365
2366 const QFixed availableWidth = width - ellipsisWidth;
2367 if (availableWidth < 0)
2368 return QString();
2369
2370 const HB_CharAttributes *attributes = this->attributes();
2371
2372 if (mode == Qt::ElideRight) {
2373 QFixed currentWidth;
2374 int pos = 0;
2375 int nextBreak = 0;
2376
2377 do {
2378 pos = nextBreak;
2379
2380 ++nextBreak;
2381 while (nextBreak < layoutData->string.length() && !attributes[nextBreak].charStop)
2382 ++nextBreak;
2383
2384 currentWidth += this->width(pos, nextBreak - pos);
2385 } while (nextBreak < layoutData->string.length()
2386 && currentWidth < availableWidth);
2387
2388 if (nextCharJoins(layoutData->string, pos))
2389 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2390
2391 return layoutData->string.left(pos) + ellipsisText;
2392 } else if (mode == Qt::ElideLeft) {
2393 QFixed currentWidth;
2394 int pos = layoutData->string.length();
2395 int nextBreak = layoutData->string.length();
2396
2397 do {
2398 pos = nextBreak;
2399
2400 --nextBreak;
2401 while (nextBreak > 0 && !attributes[nextBreak].charStop)
2402 --nextBreak;
2403
2404 currentWidth += this->width(nextBreak, pos - nextBreak);
2405 } while (nextBreak > 0
2406 && currentWidth < availableWidth);
2407
2408 if (prevCharJoins(layoutData->string, pos))
2409 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2410
2411 return ellipsisText + layoutData->string.mid(pos);
2412 } else if (mode == Qt::ElideMiddle) {
2413 QFixed leftWidth;
2414 QFixed rightWidth;
2415
2416 int leftPos = 0;
2417 int nextLeftBreak = 0;
2418
2419 int rightPos = layoutData->string.length();
2420 int nextRightBreak = layoutData->string.length();
2421
2422 do {
2423 leftPos = nextLeftBreak;
2424 rightPos = nextRightBreak;
2425
2426 ++nextLeftBreak;
2427 while (nextLeftBreak < layoutData->string.length() && !attributes[nextLeftBreak].charStop)
2428 ++nextLeftBreak;
2429
2430 --nextRightBreak;
2431 while (nextRightBreak > 0 && !attributes[nextRightBreak].charStop)
2432 --nextRightBreak;
2433
2434 leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
2435 rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
2436 } while (nextLeftBreak < layoutData->string.length()
2437 && nextRightBreak > 0
2438 && leftWidth + rightWidth < availableWidth);
2439
2440 if (nextCharJoins(layoutData->string, leftPos))
2441 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2442 if (prevCharJoins(layoutData->string, rightPos))
2443 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2444
2445 return layoutData->string.left(leftPos) + ellipsisText + layoutData->string.mid(rightPos);
2446 }
2447
2448 return layoutData->string;
2449}
2450
2451void QTextEngine::setBoundary(int strPos) const
2452{
2453 if (strPos <= 0 || strPos >= layoutData->string.length())
2454 return;
2455
2456 int itemToSplit = 0;
2457 while (itemToSplit < layoutData->items.size() && layoutData->items[itemToSplit].position <= strPos)
2458 itemToSplit++;
2459 itemToSplit--;
2460 if (layoutData->items[itemToSplit].position == strPos) {
2461 // already a split at the requested position
2462 return;
2463 }
2464 splitItem(itemToSplit, strPos - layoutData->items[itemToSplit].position);
2465}
2466
2467void QTextEngine::splitItem(int item, int pos) const
2468{
2469 if (pos <= 0)
2470 return;
2471
2472 layoutData->items.insert(item + 1, QScriptItem(layoutData->items[item]));
2473 QScriptItem &oldItem = layoutData->items[item];
2474 QScriptItem &newItem = layoutData->items[item+1];
2475 newItem.position += pos;
2476
2477 if (oldItem.num_glyphs) {
2478 // already shaped, break glyphs aswell
2479 int breakGlyph = logClusters(&oldItem)[pos];
2480
2481 newItem.num_glyphs = oldItem.num_glyphs - breakGlyph;
2482 oldItem.num_glyphs = breakGlyph;
2483 newItem.glyph_data_offset = oldItem.glyph_data_offset + breakGlyph;
2484
2485 for (int i = 0; i < newItem.num_glyphs; i++)
2486 logClusters(&newItem)[i] -= breakGlyph;
2487
2488 QFixed w = 0;
2489 const QGlyphLayout g = shapedGlyphs(&oldItem);
2490 for(int j = 0; j < breakGlyph; ++j)
2491 w += g.advances_x[j];
2492
2493 newItem.width = oldItem.width - w;
2494 oldItem.width = w;
2495 }
2496
2497// qDebug("split at position %d itempos=%d", pos, item);
2498}
2499
2500extern int qt_defaultDpiY();
2501
2502QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
2503{
2504 const QScriptItem &si = layoutData->items[item];
2505
2506 QFixed dpiScale = 1;
2507 if (block.docHandle() && block.docHandle()->layout()) {
2508 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2509 if (pdev)
2510 dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
2511 } else {
2512 dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
2513 }
2514
2515 QList<QTextOption::Tab> tabArray = option.tabs();
2516 if (!tabArray.isEmpty()) {
2517 if (option.textDirection() == Qt::RightToLeft) { // rebase the tabArray positions.
2518 QList<QTextOption::Tab> newTabs;
2519 QList<QTextOption::Tab>::Iterator iter = tabArray.begin();
2520 while(iter != tabArray.end()) {
2521 QTextOption::Tab tab = *iter;
2522 if (tab.type == QTextOption::LeftTab)
2523 tab.type = QTextOption::RightTab;
2524 else if (tab.type == QTextOption::RightTab)
2525 tab.type = QTextOption::LeftTab;
2526 newTabs << tab;
2527 ++iter;
2528 }
2529 tabArray = newTabs;
2530 }
2531 for (int i = 0; i < tabArray.size(); ++i) {
2532 QFixed tab = QFixed::fromReal(tabArray[i].position) * dpiScale;
2533 if (tab > x) { // this is the tab we need.
2534 QTextOption::Tab tabSpec = tabArray[i];
2535 int tabSectionEnd = layoutData->string.count();
2536 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
2537 // find next tab to calculate the width required.
2538 tab = QFixed::fromReal(tabSpec.position);
2539 for (int i=item + 1; i < layoutData->items.count(); i++) {
2540 const QScriptItem &item = layoutData->items[i];
2541 if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
2542 tabSectionEnd = item.position;
2543 break;
2544 }
2545 }
2546 }
2547 else if (tabSpec.type == QTextOption::DelimiterTab)
2548 // find delimitor character to calculate the width required
2549 tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
2550
2551 if (tabSectionEnd > si.position) {
2552 QFixed length;
2553 // Calculate the length of text between this tab and the tabSectionEnd
2554 for (int i=item; i < layoutData->items.count(); i++) {
2555 QScriptItem &item = layoutData->items[i];
2556 if (item.position > tabSectionEnd || item.position <= si.position)
2557 continue;
2558 shape(i); // first, lets make sure relevant text is already shaped
2559 QGlyphLayout glyphs = this->shapedGlyphs(&item);
2560 const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
2561 for (int i=0; i < end; i++)
2562 length += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
2563 if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
2564 length -= glyphs.advances_x[end] / 2 * !glyphs.attributes[end].dontPrint;
2565 }
2566
2567 switch (tabSpec.type) {
2568 case QTextOption::CenterTab:
2569 length /= 2;
2570 // fall through
2571 case QTextOption::DelimiterTab:
2572 // fall through
2573 case QTextOption::RightTab:
2574 tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
2575 if (tab < 0) // default to tab taking no space
2576 return QFixed();
2577 break;
2578 case QTextOption::LeftTab:
2579 break;
2580 }
2581 }
2582 return tab - x;
2583 }
2584 }
2585 }
2586 QFixed tab = QFixed::fromReal(option.tabStop());
2587 if (tab <= 0)
2588 tab = 80; // default
2589 tab *= dpiScale;
2590 QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
2591 QFixed tabWidth = nextTabPos - x;
2592
2593 return tabWidth;
2594}
2595
2596void QTextEngine::resolveAdditionalFormats() const
2597{
2598 if (!specialData || specialData->addFormats.isEmpty()
2599 || !block.docHandle()
2600 || !specialData->resolvedFormatIndices.isEmpty())
2601 return;
2602
2603 QTextFormatCollection *collection = this->formats();
2604
2605 specialData->resolvedFormatIndices.clear();
2606 QVector<int> indices(layoutData->items.count());
2607 for (int i = 0; i < layoutData->items.count(); ++i) {
2608 QTextCharFormat f = format(&layoutData->items.at(i));
2609 indices[i] = collection->indexForFormat(f);
2610 }
2611 specialData->resolvedFormatIndices = indices;
2612}
2613
2614QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
2615 : _layoutData(string, _memory, MemSize)
2616{
2617 fnt = f;
2618 text = string;
2619 stackEngine = true;
2620 layoutData = &_layoutData;
2621}
2622
2623QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
2624 : justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
2625 num_chars(0), chars(0), logClusters(0), f(0), fontEngine(0)
2626{
2627 // explicitly initialize flags so that initFontAttributes can be called
2628 // multiple times on the same TextItem
2629 flags = 0;
2630 if (si.analysis.bidiLevel %2)
2631 flags |= QTextItem::RightToLeft;
2632 ascent = si.ascent;
2633 descent = si.descent;
2634 f = font;
2635 fontEngine = f->d->engineForScript(si.analysis.script);
2636 Q_ASSERT(fontEngine);
2637
2638 if (format.hasProperty(QTextFormat::TextUnderlineStyle)) {
2639 underlineStyle = format.underlineStyle();
2640 } else if (format.boolProperty(QTextFormat::FontUnderline)
2641 || f->d->underline) {
2642 underlineStyle = QTextCharFormat::SingleUnderline;
2643 }
2644
2645 // compat
2646 if (underlineStyle == QTextCharFormat::SingleUnderline)
2647 flags |= QTextItem::Underline;
2648
2649 if (f->d->overline || format.fontOverline())
2650 flags |= QTextItem::Overline;
2651 if (f->d->strikeOut || format.fontStrikeOut())
2652 flags |= QTextItem::StrikeOut;
2653}
2654
2655QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
2656{
2657 QTextItemInt ti = *this;
2658 const int end = firstGlyphIndex + numGlyphs;
2659 ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
2660 ti.fontEngine = fontEngine;
2661
2662 if (logClusters && chars) {
2663 const int logClusterOffset = logClusters[0];
2664 while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
2665 ++ti.chars;
2666
2667 ti.logClusters += (ti.chars - chars);
2668
2669 ti.num_chars = 0;
2670 int char_start = ti.chars - chars;
2671 while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
2672 ++ti.num_chars;
2673 }
2674 return ti;
2675}
2676
2677
2678QTransform qt_true_matrix(qreal w, qreal h, QTransform x)
2679{
2680 QRectF rect = x.mapRect(QRectF(0, 0, w, h));
2681 return x * QTransform::fromTranslate(-rect.x(), -rect.y());
2682}
2683
2684
2685glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
2686{
2687 if (matrix.type() < QTransform::TxTranslate)
2688 return *this;
2689
2690 glyph_metrics_t m = *this;
2691
2692 qreal w = width.toReal();
2693 qreal h = height.toReal();
2694 QTransform xform = qt_true_matrix(w, h, matrix);
2695
2696 QRectF rect(0, 0, w, h);
2697 rect = xform.mapRect(rect);
2698 m.width = QFixed::fromReal(rect.width());
2699 m.height = QFixed::fromReal(rect.height());
2700
2701 QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
2702
2703 m.x = QFixed::fromReal(l.x1());
2704 m.y = QFixed::fromReal(l.y1());
2705
2706 // The offset is relative to the baseline which is why we use dx/dy of the line
2707 m.xoff = QFixed::fromReal(l.dx());
2708 m.yoff = QFixed::fromReal(l.dy());
2709
2710 return m;
2711}
2712
2713
2714QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.