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

Last change on this file since 135 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 93.3 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the QtGui module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** 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 are unsure which license is appropriate for your use, please
37** contact the sales department 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_OS_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_OS_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);
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
1102/// take the item from layoutData->items and
1103void QTextEngine::shapeTextWithHarfbuzz(int item) const
1104{
1105 Q_ASSERT(sizeof(HB_Fixed) == sizeof(QFixed));
1106 Q_ASSERT(sizeof(HB_FixedPoint) == sizeof(QFixedPoint));
1107
1108 QScriptItem &si = layoutData->items[item];
1109
1110 si.glyph_data_offset = layoutData->used;
1111
1112 QFontEngine *font = fontEngine(si, &si.ascent, &si.descent);
1113
1114 bool kerningEnabled = this->font(si).d->kerning;
1115
1116 HB_ShaperItem entire_shaper_item;
1117 entire_shaper_item.kerning_applied = false;
1118 entire_shaper_item.string = reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData());
1119 entire_shaper_item.stringLength = layoutData->string.length();
1120 entire_shaper_item.item.script = (HB_Script)si.analysis.script;
1121 entire_shaper_item.item.pos = si.position;
1122 entire_shaper_item.item.length = length(item);
1123 entire_shaper_item.item.bidiLevel = si.analysis.bidiLevel;
1124 entire_shaper_item.glyphIndicesPresent = false;
1125
1126 HB_UChar16 upperCased[256]; // XXX what about making this 4096, so we don't have to extend it ever.
1127 if (si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase
1128 || si.analysis.flags == QScriptAnalysis::Lowercase) {
1129 HB_UChar16 *uc = upperCased;
1130 if (entire_shaper_item.item.length > 256)
1131 uc = new HB_UChar16[entire_shaper_item.item.length];
1132 for (uint i = 0; i < entire_shaper_item.item.length; ++i) {
1133 if(si.analysis.flags == QScriptAnalysis::Lowercase)
1134 uc[i] = QChar::toLower(entire_shaper_item.string[si.position + i]);
1135 else
1136 uc[i] = QChar::toUpper(entire_shaper_item.string[si.position + i]);
1137 }
1138 entire_shaper_item.item.pos = 0;
1139 entire_shaper_item.string = uc;
1140 entire_shaper_item.stringLength = entire_shaper_item.item.length;
1141 }
1142
1143 entire_shaper_item.shaperFlags = 0;
1144 if (!kerningEnabled)
1145 entire_shaper_item.shaperFlags |= HB_ShaperFlag_NoKerning;
1146 if (option.useDesignMetrics())
1147 entire_shaper_item.shaperFlags |= HB_ShaperFlag_UseDesignMetrics;
1148
1149 entire_shaper_item.num_glyphs = qMax(layoutData->glyphLayout.numGlyphs - layoutData->used, int(entire_shaper_item.item.length));
1150 ensureSpace(entire_shaper_item.num_glyphs);
1151 QGlyphLayout initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1152
1153 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1154 ensureSpace(entire_shaper_item.num_glyphs);
1155 initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1156
1157 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1158 // ############ if this happens there's a bug in the fontengine
1159 if ((si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase
1160 || si.analysis.flags == QScriptAnalysis::Lowercase) && entire_shaper_item.string != upperCased)
1161 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1162 return;
1163 }
1164 }
1165
1166 // split up the item into parts that come from different font engines.
1167 QVarLengthArray<int> itemBoundaries(2);
1168 // k * 2 entries, array[k] == index in string, array[k + 1] == index in glyphs
1169 itemBoundaries[0] = entire_shaper_item.item.pos;
1170 itemBoundaries[1] = 0;
1171
1172 if (font->type() == QFontEngine::Multi) {
1173 uint lastEngine = 0;
1174 int charIdx = entire_shaper_item.item.pos;
1175 const int stringEnd = charIdx + entire_shaper_item.item.length;
1176 for (quint32 i = 0; i < entire_shaper_item.num_glyphs; ++i, ++charIdx) {
1177 uint engineIdx = initialGlyphs.glyphs[i] >> 24;
1178 if (engineIdx != lastEngine && i > 0) {
1179 itemBoundaries.append(charIdx);
1180 itemBoundaries.append(i);
1181 }
1182 lastEngine = engineIdx;
1183 if (HB_IsHighSurrogate(entire_shaper_item.string[charIdx])
1184 && charIdx < stringEnd - 1
1185 && HB_IsLowSurrogate(entire_shaper_item.string[charIdx + 1]))
1186 ++charIdx;
1187 }
1188 }
1189
1190
1191
1192 int initial_glyph_pos = 0;
1193 int glyph_pos = 0;
1194 // for each item shape using harfbuzz and store the results in our layoutData's glyphs array.
1195 for (int k = 0; k < itemBoundaries.size(); k += 2) { // for the +2, see the comment at the definition of itemBoundaries
1196
1197 HB_ShaperItem shaper_item = entire_shaper_item;
1198
1199 shaper_item.item.pos = itemBoundaries[k];
1200 if (k < itemBoundaries.size() - 3) {
1201 shaper_item.item.length = itemBoundaries[k + 2] - shaper_item.item.pos;
1202 shaper_item.num_glyphs = itemBoundaries[k + 3] - itemBoundaries[k + 1];
1203 } else { // last combo in the list, avoid out of bounds access.
1204 shaper_item.item.length -= shaper_item.item.pos - entire_shaper_item.item.pos;
1205 shaper_item.num_glyphs -= itemBoundaries[k + 1];
1206 }
1207 shaper_item.initialGlyphCount = shaper_item.num_glyphs;
1208
1209 QFontEngine *actualFontEngine = font;
1210 uint engineIdx = 0;
1211 if (font->type() == QFontEngine::Multi) {
1212 engineIdx = uint(initialGlyphs.glyphs[itemBoundaries[k + 1]] >> 24);
1213
1214 actualFontEngine = static_cast<QFontEngineMulti *>(font)->engine(engineIdx);
1215 }
1216
1217 shaper_item.font = actualFontEngine->harfbuzzFont();
1218 shaper_item.face = actualFontEngine->harfbuzzFace();
1219
1220 shaper_item.glyphIndicesPresent = true;
1221
1222 do {
1223 ensureSpace(glyph_pos + shaper_item.num_glyphs);
1224 initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1225 shaper_item.num_glyphs = layoutData->glyphLayout.numGlyphs - layoutData->used - glyph_pos;
1226
1227 const QGlyphLayout g = availableGlyphs(&si);
1228 shaper_item.glyphs = g.glyphs + glyph_pos;
1229 shaper_item.attributes = g.attributes + glyph_pos;
1230 shaper_item.advances = reinterpret_cast<HB_Fixed *>(g.advances_x + glyph_pos);
1231 shaper_item.offsets = reinterpret_cast<HB_FixedPoint *>(g.offsets + glyph_pos);
1232
1233 if (shaper_item.glyphIndicesPresent) {
1234 for (hb_uint32 i = 0; i < shaper_item.initialGlyphCount; ++i)
1235 shaper_item.glyphs[i] &= 0x00ffffff;
1236 }
1237
1238 shaper_item.log_clusters = logClusters(&si) + shaper_item.item.pos - entire_shaper_item.item.pos;
1239
1240// qDebug(" .. num_glyphs=%d, used=%d, item.num_glyphs=%d", num_glyphs, used, shaper_item.num_glyphs);
1241 } while (!qShapeItem(&shaper_item)); // this does the actual shaping via harfbuzz.
1242
1243 QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos, shaper_item.num_glyphs);
1244
1245 for (hb_uint32 i = 0; i < shaper_item.item.length; ++i) {
1246 g.glyphs[i] = g.glyphs[i] | (engineIdx << 24);
1247 shaper_item.log_clusters[i] += glyph_pos;
1248 }
1249
1250 if (kerningEnabled && !shaper_item.kerning_applied)
1251 font->doKerning(&g, option.useDesignMetrics() ? QFlag(QTextEngine::DesignMetrics) : QFlag(0));
1252
1253 glyph_pos += shaper_item.num_glyphs;
1254
1255 initial_glyph_pos += shaper_item.initialGlyphCount;
1256 }
1257
1258// qDebug(" -> item: script=%d num_glyphs=%d", shaper_item.script, shaper_item.num_glyphs);
1259 si.num_glyphs = glyph_pos;
1260
1261 layoutData->used += si.num_glyphs;
1262
1263 if ((si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase)
1264 && entire_shaper_item.string != upperCased)
1265 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1266}
1267
1268static void init(QTextEngine *e)
1269{
1270 e->ignoreBidi = false;
1271 e->cacheGlyphs = false;
1272 e->forceJustification = false;
1273
1274 e->layoutData = 0;
1275
1276 e->minWidth = 0;
1277 e->maxWidth = 0;
1278
1279 e->underlinePositions = 0;
1280 e->specialData = 0;
1281 e->stackEngine = false;
1282}
1283
1284QTextEngine::QTextEngine()
1285{
1286 init(this);
1287}
1288
1289QTextEngine::QTextEngine(const QString &str, const QFont &f)
1290 : fnt(f)
1291{
1292 init(this);
1293 text = str;
1294}
1295
1296QTextEngine::~QTextEngine()
1297{
1298 if (!stackEngine)
1299 delete layoutData;
1300 delete specialData;
1301}
1302
1303const HB_CharAttributes *QTextEngine::attributes() const
1304{
1305 if (layoutData && layoutData->haveCharAttributes)
1306 return (HB_CharAttributes *) layoutData->memory;
1307
1308 itemize();
1309 ensureSpace(layoutData->string.length());
1310
1311 QVarLengthArray<HB_ScriptItem> hbScriptItems(layoutData->items.size());
1312
1313 for (int i = 0; i < layoutData->items.size(); ++i) {
1314 const QScriptItem &si = layoutData->items[i];
1315 hbScriptItems[i].pos = si.position;
1316 hbScriptItems[i].length = length(i);
1317 hbScriptItems[i].bidiLevel = si.analysis.bidiLevel;
1318 hbScriptItems[i].script = (HB_Script)si.analysis.script;
1319 }
1320
1321 qGetCharAttributes(reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData()),
1322 layoutData->string.length(),
1323 hbScriptItems.data(), hbScriptItems.size(),
1324 (HB_CharAttributes *)layoutData->memory);
1325
1326
1327 layoutData->haveCharAttributes = true;
1328 return (HB_CharAttributes *) layoutData->memory;
1329}
1330
1331void QTextEngine::shape(int item) const
1332{
1333 if (layoutData->items[item].analysis.flags == QScriptAnalysis::Object) {
1334 ensureSpace(1);
1335 if (block.docHandle()) {
1336 QTextFormat format = formats()->format(formatIndex(&layoutData->items[item]));
1337 docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
1338 layoutData->items[item].position + block.position(), format);
1339 }
1340 } else if (layoutData->items[item].analysis.flags == QScriptAnalysis::Tab) {
1341 // set up at least the ascent/descent of the script item for the tab
1342 fontEngine(layoutData->items[item], &layoutData->items[item].ascent, &layoutData->items[item].descent);
1343 } else {
1344 shapeText(item);
1345 }
1346}
1347
1348void QTextEngine::invalidate()
1349{
1350 freeMemory();
1351 minWidth = 0;
1352 maxWidth = 0;
1353 if (specialData)
1354 specialData->resolvedFormatIndices.clear();
1355}
1356
1357void QTextEngine::clearLineData()
1358{
1359 lines.clear();
1360}
1361
1362void QTextEngine::validate() const
1363{
1364 if (layoutData)
1365 return;
1366 layoutData = new LayoutData();
1367 if (block.docHandle()) {
1368 layoutData->string = block.text();
1369 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1370 layoutData->string += QLatin1Char(block.next().isValid() ? 0xb6 : 0x20);
1371 } else {
1372 layoutData->string = text;
1373 }
1374 if (specialData && specialData->preeditPosition != -1)
1375 layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
1376}
1377
1378void QTextEngine::itemize() const
1379{
1380 validate();
1381 if (layoutData->items.size())
1382 return;
1383
1384 int length = layoutData->string.length();
1385 if (!length)
1386 return;
1387
1388 bool ignore = ignoreBidi;
1389 if (!ignore && option.textDirection() == Qt::LeftToRight) {
1390 ignore = true;
1391 const QChar *start = layoutData->string.unicode();
1392 const QChar * const end = start + length;
1393 while (start < end) {
1394 if (start->unicode() >= 0x590) {
1395 ignore = false;
1396 break;
1397 }
1398 ++start;
1399 }
1400 }
1401
1402 QVarLengthArray<QScriptAnalysis, 4096> scriptAnalysis(length);
1403 QScriptAnalysis *analysis = scriptAnalysis.data();
1404
1405 QBidiControl control(option.textDirection() == Qt::RightToLeft);
1406
1407 if (ignore) {
1408 memset(analysis, 0, length*sizeof(QScriptAnalysis));
1409 if (option.textDirection() == Qt::RightToLeft) {
1410 for (int i = 0; i < length; ++i)
1411 analysis[i].bidiLevel = 1;
1412 layoutData->hasBidi = true;
1413 }
1414 } else {
1415 layoutData->hasBidi = bidiItemize(const_cast<QTextEngine *>(this), analysis, control);
1416 }
1417
1418 const ushort *unicode = layoutData->string.utf16();
1419 // correctly assign script, isTab and isObject to the script analysis
1420 const ushort *uc = unicode;
1421 const ushort *e = uc + length;
1422 int lastScript = QUnicodeTables::Common;
1423 while (uc < e) {
1424 int script = QUnicodeTables::script(*uc);
1425 if (script == QUnicodeTables::Inherited)
1426 script = lastScript;
1427 analysis->flags = QScriptAnalysis::None;
1428 if (*uc == QChar::ObjectReplacementCharacter) {
1429 if (analysis->bidiLevel % 2)
1430 --analysis->bidiLevel;
1431 analysis->script = QUnicodeTables::Common;
1432 analysis->flags = QScriptAnalysis::Object;
1433 } else if (*uc == QChar::LineSeparator) {
1434 if (analysis->bidiLevel % 2)
1435 --analysis->bidiLevel;
1436 analysis->script = QUnicodeTables::Common;
1437 analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
1438 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1439 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
1440 } else if (*uc == 9) {
1441 analysis->script = QUnicodeTables::Common;
1442 analysis->flags = QScriptAnalysis::Tab;
1443 analysis->bidiLevel = control.baseLevel();
1444 } else if ((*uc == 32 || *uc == QChar::Nbsp)
1445 && (option.flags() & QTextOption::ShowTabsAndSpaces)) {
1446 analysis->script = QUnicodeTables::Common;
1447 analysis->flags = QScriptAnalysis::Space;
1448 analysis->bidiLevel = control.baseLevel();
1449 } else {
1450 analysis->script = script;
1451 }
1452 lastScript = analysis->script;
1453 ++uc;
1454 ++analysis;
1455 }
1456 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
1457 (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
1458 }
1459
1460 Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
1461
1462 const QTextDocumentPrivate *p = block.docHandle();
1463 if (p) {
1464 SpecialData *s = specialData;
1465
1466 QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
1467 QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
1468 int format = it.value()->format;
1469
1470 int prevPosition = 0;
1471 int position = prevPosition;
1472 while (1) {
1473 const QTextFragmentData * const frag = it.value();
1474 if (it == end || format != frag->format) {
1475 if (s && position >= s->preeditPosition) {
1476 position += s->preeditText.length();
1477 s = 0;
1478 }
1479 Q_ASSERT(position <= length);
1480 itemizer.generate(prevPosition, position - prevPosition,
1481 formats()->charFormat(format).fontCapitalization());
1482 if (it == end) {
1483 if (position < length)
1484 itemizer.generate(position, length - position,
1485 formats()->charFormat(format).fontCapitalization());
1486 break;
1487 }
1488 format = frag->format;
1489 prevPosition = position;
1490 }
1491 position += frag->size_array[0];
1492 ++it;
1493 }
1494 } else {
1495 itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
1496 }
1497
1498 addRequiredBoundaries();
1499 resolveAdditionalFormats();
1500}
1501
1502int QTextEngine::findItem(int strPos) const
1503{
1504 itemize();
1505
1506 // ##### use binary search
1507 int item;
1508 for (item = layoutData->items.size()-1; item > 0; --item) {
1509 if (layoutData->items[item].position <= strPos)
1510 break;
1511 }
1512 return item;
1513}
1514
1515QFixed QTextEngine::width(int from, int len) const
1516{
1517 itemize();
1518
1519 QFixed w = 0;
1520
1521// qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from, len, items.size(), string.length());
1522 for (int i = 0; i < layoutData->items.size(); i++) {
1523 const QScriptItem *si = layoutData->items.constData() + i;
1524 int pos = si->position;
1525 int ilen = length(i);
1526// qDebug("item %d: from %d len %d", i, pos, ilen);
1527 if (pos >= from + len)
1528 break;
1529 if (pos + ilen > from) {
1530 if (!si->num_glyphs)
1531 shape(i);
1532
1533 if (si->analysis.flags == QScriptAnalysis::Object) {
1534 w += si->width;
1535 continue;
1536 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1537 w += calculateTabWidth(i, w);
1538 continue;
1539 }
1540
1541
1542 QGlyphLayout glyphs = shapedGlyphs(si);
1543 unsigned short *logClusters = this->logClusters(si);
1544
1545// fprintf(stderr, " logclusters:");
1546// for (int k = 0; k < ilen; k++)
1547// fprintf(stderr, " %d", logClusters[k]);
1548// fprintf(stderr, "\n");
1549 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1550 int charFrom = from - pos;
1551 if (charFrom < 0)
1552 charFrom = 0;
1553 int glyphStart = logClusters[charFrom];
1554 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1555 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1556 charFrom++;
1557 if (charFrom < ilen) {
1558 glyphStart = logClusters[charFrom];
1559 int charEnd = from + len - 1 - pos;
1560 if (charEnd >= ilen)
1561 charEnd = ilen-1;
1562 int glyphEnd = logClusters[charEnd];
1563 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1564 charEnd++;
1565 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1566
1567// qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
1568 for (int i = glyphStart; i < glyphEnd; i++)
1569 w += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
1570 }
1571 }
1572 }
1573// qDebug(" --> w= %d ", w);
1574 return w;
1575}
1576
1577glyph_metrics_t QTextEngine::boundingBox(int from, int len) const
1578{
1579 itemize();
1580
1581 glyph_metrics_t gm;
1582
1583 for (int i = 0; i < layoutData->items.size(); i++) {
1584 const QScriptItem *si = layoutData->items.constData() + i;
1585 int pos = si->position;
1586 int ilen = length(i);
1587 if (pos > from + len)
1588 break;
1589 if (pos + len > from) {
1590 if (!si->num_glyphs)
1591 shape(i);
1592
1593 if (si->analysis.flags == QScriptAnalysis::Object) {
1594 gm.width += si->width;
1595 continue;
1596 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1597 gm.width += calculateTabWidth(i, gm.width);
1598 continue;
1599 }
1600
1601 unsigned short *logClusters = this->logClusters(si);
1602 QGlyphLayout glyphs = shapedGlyphs(si);
1603
1604 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1605 int charFrom = from - pos;
1606 if (charFrom < 0)
1607 charFrom = 0;
1608 int glyphStart = logClusters[charFrom];
1609 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1610 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1611 charFrom++;
1612 if (charFrom < ilen) {
1613 glyphStart = logClusters[charFrom];
1614 int charEnd = from + len - 1 - pos;
1615 if (charEnd >= ilen)
1616 charEnd = ilen-1;
1617 int glyphEnd = logClusters[charEnd];
1618 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1619 charEnd++;
1620 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1621 if (glyphStart <= glyphEnd ) {
1622 QFontEngine *fe = fontEngine(*si);
1623 glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1624 gm.x = qMin(gm.x, m.x + gm.xoff);
1625 gm.y = qMin(gm.y, m.y + gm.yoff);
1626 gm.width = qMax(gm.width, m.width+gm.xoff);
1627 gm.height = qMax(gm.height, m.height+gm.yoff);
1628 gm.xoff += m.xoff;
1629 gm.yoff += m.yoff;
1630 }
1631 }
1632 }
1633 }
1634 return gm;
1635}
1636
1637glyph_metrics_t QTextEngine::tightBoundingBox(int from, int len) const
1638{
1639 itemize();
1640
1641 glyph_metrics_t gm;
1642
1643 for (int i = 0; i < layoutData->items.size(); i++) {
1644 const QScriptItem *si = layoutData->items.constData() + i;
1645 int pos = si->position;
1646 int ilen = length(i);
1647 if (pos > from + len)
1648 break;
1649 if (pos + len > from) {
1650 if (!si->num_glyphs)
1651 shape(i);
1652 unsigned short *logClusters = this->logClusters(si);
1653 QGlyphLayout glyphs = shapedGlyphs(si);
1654
1655 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1656 int charFrom = from - pos;
1657 if (charFrom < 0)
1658 charFrom = 0;
1659 int glyphStart = logClusters[charFrom];
1660 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1661 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1662 charFrom++;
1663 if (charFrom < ilen) {
1664 glyphStart = logClusters[charFrom];
1665 int charEnd = from + len - 1 - pos;
1666 if (charEnd >= ilen)
1667 charEnd = ilen-1;
1668 int glyphEnd = logClusters[charEnd];
1669 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1670 charEnd++;
1671 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1672 if (glyphStart <= glyphEnd ) {
1673 QFontEngine *fe = fontEngine(*si);
1674 glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1675 gm.x = qMin(gm.x, m.x + gm.xoff);
1676 gm.y = qMin(gm.y, m.y + gm.yoff);
1677 gm.width = qMax(gm.width, m.width+gm.xoff);
1678 gm.height = qMax(gm.height, m.height+gm.yoff);
1679 gm.xoff += m.xoff;
1680 gm.yoff += m.yoff;
1681 }
1682 }
1683 }
1684 }
1685 return gm;
1686}
1687
1688QFont QTextEngine::font(const QScriptItem &si) const
1689{
1690 QFont font = fnt;
1691 if (hasFormats()) {
1692 QTextCharFormat f = format(&si);
1693 font = f.font();
1694
1695 if (block.docHandle() && block.docHandle()->layout()) {
1696 // Make sure we get the right dpi on printers
1697 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1698 if (pdev)
1699 font = QFont(font, pdev);
1700 } else {
1701 font = font.resolve(fnt);
1702 }
1703 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1704 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1705 if (font.pointSize() != -1)
1706 font.setPointSize((font.pointSize() * 2) / 3);
1707 else
1708 font.setPixelSize((font.pixelSize() * 2) / 3);
1709 }
1710 }
1711
1712 if (si.analysis.flags == QScriptAnalysis::SmallCaps)
1713 font = font.d->smallCapsFont();
1714
1715 return font;
1716}
1717
1718QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent) const
1719{
1720 QFontEngine *engine = 0;
1721 QFontEngine *scaledEngine = 0;
1722 int script = si.analysis.script;
1723
1724 QFont font = fnt;
1725 if (hasFormats()) {
1726 QTextCharFormat f = format(&si);
1727 font = f.font();
1728
1729 if (block.docHandle() && block.docHandle()->layout()) {
1730 // Make sure we get the right dpi on printers
1731 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1732 if (pdev)
1733 font = QFont(font, pdev);
1734 } else {
1735 font = font.resolve(fnt);
1736 }
1737 engine = font.d->engineForScript(script);
1738 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1739 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1740 if (font.pointSize() != -1)
1741 font.setPointSize((font.pointSize() * 2) / 3);
1742 else
1743 font.setPixelSize((font.pixelSize() * 2) / 3);
1744 scaledEngine = font.d->engineForScript(script);
1745 }
1746 } else {
1747 engine = font.d->engineForScript(script);
1748 }
1749
1750 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
1751 QFontPrivate *p = font.d->smallCapsFontPrivate();
1752 scaledEngine = p->engineForScript(script);
1753 }
1754
1755 if (ascent) {
1756 *ascent = engine->ascent();
1757 *descent = engine->descent();
1758 }
1759
1760 if (scaledEngine)
1761 return scaledEngine;
1762 return engine;
1763}
1764
1765struct QJustificationPoint {
1766 int type;
1767 QFixed kashidaWidth;
1768 QGlyphLayout glyph;
1769 QFontEngine *fontEngine;
1770};
1771
1772Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE);
1773
1774static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
1775{
1776 point->type = type;
1777 point->glyph = glyph;
1778 point->fontEngine = fe;
1779
1780 if (type >= HB_Arabic_Normal) {
1781 QChar ch(0x640); // Kashida character
1782 QGlyphLayoutArray<8> glyphs;
1783 int nglyphs = 7;
1784 fe->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1785 if (glyphs.glyphs[0] && glyphs.advances_x[0] != 0) {
1786 point->kashidaWidth = glyphs.advances_x[0];
1787 } else {
1788 point->type = HB_NoJustification;
1789 point->kashidaWidth = 0;
1790 }
1791 }
1792}
1793
1794
1795void QTextEngine::justify(const QScriptLine &line)
1796{
1797// qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
1798 if (line.gridfitted && line.justified)
1799 return;
1800
1801 if (!line.gridfitted) {
1802 // redo layout in device metrics, then adjust
1803 const_cast<QScriptLine &>(line).gridfitted = true;
1804 }
1805
1806 if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
1807 return;
1808
1809 itemize();
1810
1811 if (!forceJustification) {
1812 int end = line.from + (int)line.length;
1813 if (end == layoutData->string.length())
1814 return; // no justification at end of paragraph
1815 if (end && layoutData->items[findItem(end-1)].analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
1816 return; // no justification at the end of an explicitely separated line
1817 }
1818
1819 // justify line
1820 int maxJustify = 0;
1821
1822 // don't include trailing white spaces when doing justification
1823 int line_length = line.length;
1824 const HB_CharAttributes *a = attributes()+line.from;
1825 while (line_length && a[line_length-1].whiteSpace)
1826 --line_length;
1827 // subtract one char more, as we can't justfy after the last character
1828 --line_length;
1829
1830 if (!line_length)
1831 return;
1832
1833 int firstItem = findItem(line.from);
1834 int nItems = findItem(line.from + line_length - 1) - firstItem + 1;
1835
1836 QVarLengthArray<QJustificationPoint> justificationPoints;
1837 int nPoints = 0;
1838// 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());
1839 QFixed minKashida = 0x100000;
1840
1841 // we need to do all shaping before we go into the next loop, as we there
1842 // store pointers to the glyph data that could get reallocated by the shaping
1843 // process.
1844 for (int i = 0; i < nItems; ++i) {
1845 QScriptItem &si = layoutData->items[firstItem + i];
1846 if (!si.num_glyphs)
1847 shape(firstItem + i);
1848 }
1849
1850 for (int i = 0; i < nItems; ++i) {
1851 QScriptItem &si = layoutData->items[firstItem + i];
1852
1853 int kashida_type = HB_Arabic_Normal;
1854 int kashida_pos = -1;
1855
1856 int start = qMax(line.from - si.position, 0);
1857 int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
1858
1859 unsigned short *log_clusters = logClusters(&si);
1860
1861 int gs = log_clusters[start];
1862 int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
1863
1864 const QGlyphLayout g = shapedGlyphs(&si);
1865
1866 for (int i = gs; i < ge; ++i) {
1867 g.justifications[i].type = QGlyphJustification::JustifyNone;
1868 g.justifications[i].nKashidas = 0;
1869 g.justifications[i].space_18d6 = 0;
1870
1871 justificationPoints.resize(nPoints+3);
1872 int justification = g.attributes[i].justification;
1873
1874 switch(justification) {
1875 case HB_NoJustification:
1876 break;
1877 case HB_Space :
1878 // fall through
1879 case HB_Arabic_Space :
1880 if (kashida_pos >= 0) {
1881// qDebug("kashida position at %d in word", kashida_pos);
1882 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
1883 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
1884 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
1885 ++nPoints;
1886 }
1887 kashida_pos = -1;
1888 kashida_type = HB_Arabic_Normal;
1889 // fall through
1890 case HB_Character :
1891 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
1892 maxJustify = qMax(maxJustify, justification);
1893 break;
1894 case HB_Arabic_Normal :
1895 case HB_Arabic_Waw :
1896 case HB_Arabic_BaRa :
1897 case HB_Arabic_Alef :
1898 case HB_Arabic_HaaDal :
1899 case HB_Arabic_Seen :
1900 case HB_Arabic_Kashida :
1901 if (justification >= kashida_type) {
1902 kashida_pos = i;
1903 kashida_type = justification;
1904 }
1905 }
1906 }
1907 if (kashida_pos >= 0) {
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 }
1914
1915 QFixed need = line.width - line.textWidth;
1916 if (need < 0) {
1917 // line overflows already!
1918 const_cast<QScriptLine &>(line).justified = true;
1919 return;
1920 }
1921
1922// qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
1923// qDebug(" minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
1924
1925 // distribute in priority order
1926 if (maxJustify >= HB_Arabic_Normal) {
1927 while (need >= minKashida) {
1928 for (int type = maxJustify; need >= minKashida && type >= HB_Arabic_Normal; --type) {
1929 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
1930 if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
1931 justificationPoints[i].glyph.justifications->nKashidas++;
1932 // ############
1933 justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
1934 need -= justificationPoints[i].kashidaWidth;
1935// qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
1936 }
1937 }
1938 }
1939 }
1940 }
1941 Q_ASSERT(need >= 0);
1942 if (!need)
1943 goto end;
1944
1945 maxJustify = qMin(maxJustify, (int)HB_Space);
1946 for (int type = maxJustify; need != 0 && type > 0; --type) {
1947 int n = 0;
1948 for (int i = 0; i < nPoints; ++i) {
1949 if (justificationPoints[i].type == type)
1950 ++n;
1951 }
1952// qDebug("number of points for justification type %d: %d", type, n);
1953
1954
1955 if (!n)
1956 continue;
1957
1958 for (int i = 0; i < nPoints; ++i) {
1959 if (justificationPoints[i].type == type) {
1960 QFixed add = need/n;
1961// qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
1962 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
1963 need -= add;
1964 --n;
1965 }
1966 }
1967
1968 Q_ASSERT(!need);
1969 }
1970 end:
1971 const_cast<QScriptLine &>(line).justified = true;
1972}
1973
1974void QScriptLine::setDefaultHeight(QTextEngine *eng)
1975{
1976 QFont f;
1977 QFontEngine *e;
1978
1979 if (eng->block.docHandle() && eng->block.docHandle()->layout()) {
1980 f = eng->block.charFormat().font();
1981 // Make sure we get the right dpi on printers
1982 QPaintDevice *pdev = eng->block.docHandle()->layout()->paintDevice();
1983 if (pdev)
1984 f = QFont(f, pdev);
1985 e = f.d->engineForScript(QUnicodeTables::Common);
1986 } else {
1987 e = eng->fnt.d->engineForScript(QUnicodeTables::Common);
1988 }
1989
1990 ascent = qMax(ascent, e->ascent());
1991 descent = qMax(descent, e->descent());
1992}
1993
1994QTextEngine::LayoutData::LayoutData()
1995{
1996 memory = 0;
1997 allocated = 0;
1998 memory_on_stack = false;
1999 used = 0;
2000 hasBidi = false;
2001 inLayout = false;
2002 haveCharAttributes = false;
2003 logClustersPtr = 0;
2004 available_glyphs = 0;
2005}
2006
2007QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, int _allocated)
2008 : string(str)
2009{
2010 allocated = _allocated;
2011
2012 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2013 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2014 available_glyphs = ((int)allocated - space_charAttributes - space_logClusters)*(int)sizeof(void*)/(int)QGlyphLayout::spaceNeededForGlyphLayout(1);
2015
2016 if (available_glyphs < str.length()) {
2017 // need to allocate on the heap
2018 allocated = 0;
2019
2020 memory_on_stack = false;
2021 memory = 0;
2022 logClustersPtr = 0;
2023 } else {
2024 memory_on_stack = true;
2025 memory = stack_memory;
2026 logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2027
2028 void *m = memory + space_charAttributes + space_logClusters;
2029 glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.length());
2030 glyphLayout.clear();
2031 memset(memory, 0, space_charAttributes*sizeof(void *));
2032 }
2033 used = 0;
2034 hasBidi = false;
2035 inLayout = false;
2036 haveCharAttributes = false;
2037}
2038
2039QTextEngine::LayoutData::~LayoutData()
2040{
2041 if (!memory_on_stack)
2042 free(memory);
2043 memory = 0;
2044}
2045
2046void QTextEngine::LayoutData::reallocate(int totalGlyphs)
2047{
2048 Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2049 if (memory_on_stack && available_glyphs >= totalGlyphs) {
2050 glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2051 return;
2052 }
2053
2054 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2055 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2056 int space_glyphs = QGlyphLayout::spaceNeededForGlyphLayout(totalGlyphs)/sizeof(void*) + 2;
2057
2058 int newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2059 Q_ASSERT(newAllocated >= allocated);
2060 void **old_mem = memory;
2061 memory = (void **)::realloc(memory_on_stack ? 0 : old_mem, newAllocated*sizeof(void *));
2062 if (memory_on_stack && memory)
2063 memcpy(memory, old_mem, allocated*sizeof(void *));
2064 memory_on_stack = false;
2065
2066 void **m = memory;
2067 m += space_charAttributes;
2068 logClustersPtr = (unsigned short *) m;
2069 m += space_logClusters;
2070
2071 const int space_preGlyphLayout = space_charAttributes + space_logClusters;
2072 if (allocated < space_preGlyphLayout)
2073 memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2074
2075 glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2076
2077 allocated = newAllocated;
2078}
2079
2080// grow to the new size, copying the existing data to the new layout
2081void QGlyphLayout::grow(char *address, int totalGlyphs)
2082{
2083 QGlyphLayout oldLayout(address, numGlyphs);
2084 QGlyphLayout newLayout(address, totalGlyphs);
2085
2086 if (numGlyphs) {
2087 // move the existing data
2088 memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(HB_GlyphAttributes));
2089 memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2090 memmove(newLayout.advances_y, oldLayout.advances_y, numGlyphs * sizeof(QFixed));
2091 memmove(newLayout.advances_x, oldLayout.advances_x, numGlyphs * sizeof(QFixed));
2092 memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(HB_Glyph));
2093 }
2094
2095 // clear the new data
2096 newLayout.clear(numGlyphs);
2097
2098 *this = newLayout;
2099}
2100
2101void QTextEngine::freeMemory()
2102{
2103 if (!stackEngine) {
2104 delete layoutData;
2105 layoutData = 0;
2106 } else {
2107 layoutData->used = 0;
2108 layoutData->hasBidi = false;
2109 layoutData->inLayout = false;
2110 layoutData->haveCharAttributes = false;
2111 }
2112 for (int i = 0; i < lines.size(); ++i) {
2113 lines[i].justified = 0;
2114 lines[i].gridfitted = 0;
2115 }
2116}
2117
2118int QTextEngine::formatIndex(const QScriptItem *si) const
2119{
2120 if (specialData && !specialData->resolvedFormatIndices.isEmpty())
2121 return specialData->resolvedFormatIndices.at(si - &layoutData->items[0]);
2122 QTextDocumentPrivate *p = block.docHandle();
2123 if (!p)
2124 return -1;
2125 int pos = si->position;
2126 if (specialData && si->position >= specialData->preeditPosition) {
2127 if (si->position < specialData->preeditPosition + specialData->preeditText.length())
2128 pos = qMax(specialData->preeditPosition - 1, 0);
2129 else
2130 pos -= specialData->preeditText.length();
2131 }
2132 QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2133 return it.value()->format;
2134}
2135
2136
2137QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2138{
2139 QTextCharFormat format;
2140 const QTextFormatCollection *formats = 0;
2141 if (block.docHandle()) {
2142 formats = this->formats();
2143 format = formats->charFormat(formatIndex(si));
2144 }
2145 if (specialData && specialData->resolvedFormatIndices.isEmpty()) {
2146 int end = si->position + length(si);
2147 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2148 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2149 if (r.start <= si->position && r.start + r.length >= end) {
2150 if (!specialData->addFormatIndices.isEmpty())
2151 format.merge(formats->format(specialData->addFormatIndices.at(i)));
2152 else
2153 format.merge(r.format);
2154 }
2155 }
2156 }
2157 return format;
2158}
2159
2160void QTextEngine::addRequiredBoundaries() const
2161{
2162 if (specialData) {
2163 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2164 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2165 setBoundary(r.start);
2166 setBoundary(r.start + r.length);
2167 //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
2168 }
2169 }
2170}
2171
2172bool QTextEngine::atWordSeparator(int position) const
2173{
2174 const QChar c = layoutData->string.at(position);
2175 switch (c.toLatin1()) {
2176 case '.':
2177 case ',':
2178 case '?':
2179 case '!':
2180 case ':':
2181 case ';':
2182 case '-':
2183 case '<':
2184 case '>':
2185 case '[':
2186 case ']':
2187 case '(':
2188 case ')':
2189 case '{':
2190 case '}':
2191 case '=':
2192 case '/':
2193 case '+':
2194 case '%':
2195 case '&':
2196 case '^':
2197 case '*':
2198 case '\'':
2199 case '"':
2200 case '~':
2201 return true;
2202 default:
2203 return false;
2204 }
2205}
2206
2207bool QTextEngine::atSpace(int position) const
2208{
2209 const QChar c = layoutData->string.at(position);
2210
2211 return c == QLatin1Char(' ')
2212 || c == QChar::Nbsp
2213 || c == QChar::LineSeparator
2214 || c == QLatin1Char('\t')
2215 ;
2216}
2217
2218
2219void QTextEngine::indexAdditionalFormats()
2220{
2221 if (!block.docHandle())
2222 return;
2223
2224 specialData->addFormatIndices.resize(specialData->addFormats.count());
2225 QTextFormatCollection * const formats = this->formats();
2226
2227 for (int i = 0; i < specialData->addFormats.count(); ++i) {
2228 specialData->addFormatIndices[i] = formats->indexForFormat(specialData->addFormats.at(i).format);
2229 specialData->addFormats[i].format = QTextCharFormat();
2230 }
2231}
2232
2233QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int flags) const
2234{
2235// qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
2236
2237 if (flags & Qt::TextShowMnemonic) {
2238 itemize();
2239 for (int i = 0; i < layoutData->items.size(); ++i) {
2240 QScriptItem &si = layoutData->items[i];
2241 if (!si.num_glyphs)
2242 shape(i);
2243
2244 HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
2245 unsigned short *logClusters = this->logClusters(&si);
2246 QGlyphLayout glyphs = shapedGlyphs(&si);
2247
2248 const int end = si.position + length(&si);
2249 for (int i = si.position; i < end - 1; ++i)
2250 if (layoutData->string.at(i) == QLatin1Char('&')) {
2251 const int gp = logClusters[i - si.position];
2252 glyphs.attributes[gp].dontPrint = true;
2253 attributes[i + 1].charStop = false;
2254 attributes[i + 1].whiteSpace = false;
2255 attributes[i + 1].lineBreakType = HB_NoBreak;
2256 if (i < end - 1
2257 && layoutData->string.at(i + 1) == QLatin1Char('&'))
2258 ++i;
2259 }
2260 }
2261 }
2262
2263 validate();
2264
2265 if (mode == Qt::ElideNone
2266 || this->width(0, layoutData->string.length()) <= width
2267 || layoutData->string.length() <= 1)
2268 return layoutData->string;
2269
2270 QFixed ellipsisWidth;
2271 QString ellipsisText;
2272 {
2273 QChar ellipsisChar(0x2026);
2274
2275 QFontEngine *fe = fnt.d->engineForScript(QUnicodeTables::Common);
2276
2277 QGlyphLayoutArray<1> ellipsisGlyph;
2278 {
2279 QFontEngine *feForEllipsis = (fe->type() == QFontEngine::Multi)
2280 ? static_cast<QFontEngineMulti *>(fe)->engine(0)
2281 : fe;
2282
2283 if (feForEllipsis->type() == QFontEngine::Mac)
2284 feForEllipsis = fe;
2285
2286 // the lookup can be really slow when we use XLFD fonts
2287 if (feForEllipsis->type() != QFontEngine::XLFD
2288 && feForEllipsis->canRender(&ellipsisChar, 1)) {
2289 int nGlyphs = 1;
2290 feForEllipsis->stringToCMap(&ellipsisChar, 1, &ellipsisGlyph, &nGlyphs, 0);
2291 }
2292 }
2293
2294 if (ellipsisGlyph.glyphs[0]) {
2295 ellipsisWidth = ellipsisGlyph.advances_x[0];
2296 ellipsisText = ellipsisChar;
2297 } else {
2298 QString dotDotDot(QLatin1String("..."));
2299
2300 QGlyphLayoutArray<3> glyphs;
2301 int nGlyphs = 3;
2302 if (!fe->stringToCMap(dotDotDot.constData(), 3, &glyphs, &nGlyphs, 0))
2303 // should never happen...
2304 return layoutData->string;
2305 for (int i = 0; i < nGlyphs; ++i)
2306 ellipsisWidth += glyphs.advances_x[i];
2307 ellipsisText = dotDotDot;
2308 }
2309 }
2310
2311 const QFixed availableWidth = width - ellipsisWidth;
2312 if (availableWidth < 0)
2313 return QString();
2314
2315 const HB_CharAttributes *attributes = this->attributes();
2316
2317 if (mode == Qt::ElideRight) {
2318 QFixed currentWidth;
2319 int pos = 0;
2320 int nextBreak = 0;
2321
2322 do {
2323 pos = nextBreak;
2324
2325 ++nextBreak;
2326 while (nextBreak < layoutData->string.length() && !attributes[nextBreak].charStop)
2327 ++nextBreak;
2328
2329 currentWidth += this->width(pos, nextBreak - pos);
2330 } while (nextBreak < layoutData->string.length()
2331 && currentWidth < availableWidth);
2332
2333 return layoutData->string.left(pos) + ellipsisText;
2334 } else if (mode == Qt::ElideLeft) {
2335 QFixed currentWidth;
2336 int pos = layoutData->string.length();
2337 int nextBreak = layoutData->string.length();
2338
2339 do {
2340 pos = nextBreak;
2341
2342 --nextBreak;
2343 while (nextBreak > 0 && !attributes[nextBreak].charStop)
2344 --nextBreak;
2345
2346 currentWidth += this->width(nextBreak, pos - nextBreak);
2347 } while (nextBreak > 0
2348 && currentWidth < availableWidth);
2349
2350 return ellipsisText + layoutData->string.mid(pos);
2351 } else if (mode == Qt::ElideMiddle) {
2352 QFixed leftWidth;
2353 QFixed rightWidth;
2354
2355 int leftPos = 0;
2356 int nextLeftBreak = 0;
2357
2358 int rightPos = layoutData->string.length();
2359 int nextRightBreak = layoutData->string.length();
2360
2361 do {
2362 leftPos = nextLeftBreak;
2363 rightPos = nextRightBreak;
2364
2365 ++nextLeftBreak;
2366 while (nextLeftBreak < layoutData->string.length() && !attributes[nextLeftBreak].charStop)
2367 ++nextLeftBreak;
2368
2369 --nextRightBreak;
2370 while (nextRightBreak > 0 && !attributes[nextRightBreak].charStop)
2371 --nextRightBreak;
2372
2373 leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
2374 rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
2375 } while (nextLeftBreak < layoutData->string.length()
2376 && nextRightBreak > 0
2377 && leftWidth + rightWidth < availableWidth);
2378
2379 return layoutData->string.left(leftPos) + ellipsisText + layoutData->string.mid(rightPos);
2380 }
2381
2382 return layoutData->string;
2383}
2384
2385void QTextEngine::setBoundary(int strPos) const
2386{
2387 if (strPos <= 0 || strPos >= layoutData->string.length())
2388 return;
2389
2390 int itemToSplit = 0;
2391 while (itemToSplit < layoutData->items.size() && layoutData->items[itemToSplit].position <= strPos)
2392 itemToSplit++;
2393 itemToSplit--;
2394 if (layoutData->items[itemToSplit].position == strPos) {
2395 // already a split at the requested position
2396 return;
2397 }
2398 splitItem(itemToSplit, strPos - layoutData->items[itemToSplit].position);
2399}
2400
2401void QTextEngine::splitItem(int item, int pos) const
2402{
2403 if (pos <= 0)
2404 return;
2405
2406 layoutData->items.insert(item + 1, QScriptItem(layoutData->items[item]));
2407 QScriptItem &oldItem = layoutData->items[item];
2408 QScriptItem &newItem = layoutData->items[item+1];
2409 newItem.position += pos;
2410
2411 if (oldItem.num_glyphs) {
2412 // already shaped, break glyphs aswell
2413 int breakGlyph = logClusters(&oldItem)[pos];
2414
2415 newItem.num_glyphs = oldItem.num_glyphs - breakGlyph;
2416 oldItem.num_glyphs = breakGlyph;
2417 newItem.glyph_data_offset = oldItem.glyph_data_offset + breakGlyph;
2418
2419 for (int i = 0; i < newItem.num_glyphs; i++)
2420 logClusters(&newItem)[i] -= breakGlyph;
2421
2422 QFixed w = 0;
2423 const QGlyphLayout g = shapedGlyphs(&oldItem);
2424 for(int j = 0; j < breakGlyph; ++j)
2425 w += g.advances_x[j];
2426
2427 newItem.width = oldItem.width - w;
2428 oldItem.width = w;
2429 }
2430
2431// qDebug("split at position %d itempos=%d", pos, item);
2432}
2433
2434extern int qt_defaultDpiY();
2435
2436QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
2437{
2438 const QScriptItem &si = layoutData->items[item];
2439
2440 QFixed dpiScale = 1;
2441 if (block.docHandle() && block.docHandle()->layout()) {
2442 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2443 if (pdev)
2444 dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
2445 } else {
2446 dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
2447 }
2448
2449 QList<QTextOption::Tab> tabArray = option.tabs();
2450 if (!tabArray.isEmpty()) {
2451 if (option.textDirection() == Qt::RightToLeft) { // rebase the tabArray positions.
2452 QList<QTextOption::Tab> newTabs;
2453 QList<QTextOption::Tab>::Iterator iter = tabArray.begin();
2454 while(iter != tabArray.end()) {
2455 QTextOption::Tab tab = *iter;
2456 if (tab.type == QTextOption::LeftTab)
2457 tab.type = QTextOption::RightTab;
2458 else if (tab.type == QTextOption::RightTab)
2459 tab.type = QTextOption::LeftTab;
2460 newTabs << tab;
2461 ++iter;
2462 }
2463 tabArray = newTabs;
2464 }
2465 for (int i = 0; i < tabArray.size(); ++i) {
2466 QFixed tab = QFixed::fromReal(tabArray[i].position) * dpiScale;
2467 if (tab > x) { // this is the tab we need.
2468 QTextOption::Tab tabSpec = tabArray[i];
2469 int tabSectionEnd = layoutData->string.count();
2470 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
2471 // find next tab to calculate the width required.
2472 tab = QFixed::fromReal(tabSpec.position);
2473 for (int i=item + 1; i < layoutData->items.count(); i++) {
2474 const QScriptItem &item = layoutData->items[i];
2475 if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
2476 tabSectionEnd = item.position;
2477 break;
2478 }
2479 }
2480 }
2481 else if (tabSpec.type == QTextOption::DelimiterTab)
2482 // find delimitor character to calculate the width required
2483 tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
2484
2485 if (tabSectionEnd > si.position) {
2486 QFixed length;
2487 // Calculate the length of text between this tab and the tabSectionEnd
2488 for (int i=item; i < layoutData->items.count(); i++) {
2489 QScriptItem &item = layoutData->items[i];
2490 if (item.position > tabSectionEnd || item.position <= si.position)
2491 continue;
2492 shape(i); // first, lets make sure relevant text is already shaped
2493 QGlyphLayout glyphs = this->shapedGlyphs(&item);
2494 const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
2495 for (int i=0; i < end; i++)
2496 length += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
2497 if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
2498 length -= glyphs.advances_x[end] / 2 * !glyphs.attributes[end].dontPrint;
2499 }
2500
2501 switch (tabSpec.type) {
2502 case QTextOption::CenterTab:
2503 length /= 2;
2504 // fall through
2505 case QTextOption::DelimiterTab:
2506 // fall through
2507 case QTextOption::RightTab:
2508 tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
2509 if (tab < 0) // default to tab taking no space
2510 return QFixed();
2511 break;
2512 case QTextOption::LeftTab:
2513 break;
2514 }
2515 }
2516 return tab - x;
2517 }
2518 }
2519 }
2520 QFixed tab = QFixed::fromReal(option.tabStop());
2521 if (tab <= 0)
2522 tab = 80; // default
2523 tab *= dpiScale;
2524 QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
2525 QFixed tabWidth = nextTabPos - x;
2526
2527 return tabWidth;
2528}
2529
2530void QTextEngine::resolveAdditionalFormats() const
2531{
2532 if (!specialData || specialData->addFormats.isEmpty()
2533 || !block.docHandle()
2534 || !specialData->resolvedFormatIndices.isEmpty())
2535 return;
2536
2537 QTextFormatCollection *collection = this->formats();
2538
2539 specialData->resolvedFormatIndices.clear();
2540 QVector<int> indices(layoutData->items.count());
2541 for (int i = 0; i < layoutData->items.count(); ++i) {
2542 QTextCharFormat f = format(&layoutData->items.at(i));
2543 indices[i] = collection->indexForFormat(f);
2544 }
2545 specialData->resolvedFormatIndices = indices;
2546}
2547
2548QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
2549 : _layoutData(string, _memory, MemSize)
2550{
2551 fnt = f;
2552 text = string;
2553 stackEngine = true;
2554 layoutData = &_layoutData;
2555}
2556
2557QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
2558 : justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
2559 num_chars(0), chars(0), logClusters(0), f(0), fontEngine(0)
2560{
2561 // explicitly initialize flags so that initFontAttributes can be called
2562 // multiple times on the same TextItem
2563 flags = 0;
2564 if (si.analysis.bidiLevel %2)
2565 flags |= QTextItem::RightToLeft;
2566 ascent = si.ascent;
2567 descent = si.descent;
2568 f = font;
2569 fontEngine = f->d->engineForScript(si.analysis.script);
2570 Q_ASSERT(fontEngine);
2571
2572 if (format.hasProperty(QTextFormat::TextUnderlineStyle)) {
2573 underlineStyle = format.underlineStyle();
2574 } else if (format.boolProperty(QTextFormat::FontUnderline)
2575 || f->d->underline) {
2576 underlineStyle = QTextCharFormat::SingleUnderline;
2577 }
2578
2579 // compat
2580 if (underlineStyle == QTextCharFormat::SingleUnderline)
2581 flags |= QTextItem::Underline;
2582
2583 if (f->d->overline || format.fontOverline())
2584 flags |= QTextItem::Overline;
2585 if (f->d->strikeOut || format.fontStrikeOut())
2586 flags |= QTextItem::StrikeOut;
2587}
2588
2589QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
2590{
2591 QTextItemInt ti = *this;
2592 const int end = firstGlyphIndex + numGlyphs;
2593 ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
2594 ti.fontEngine = fontEngine;
2595
2596 if (logClusters && chars) {
2597 const int logClusterOffset = logClusters[0];
2598 while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
2599 ++ti.chars;
2600
2601 ti.logClusters += (ti.chars - chars);
2602
2603 ti.num_chars = 0;
2604 int char_start = ti.chars - chars;
2605 while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
2606 ++ti.num_chars;
2607 }
2608 return ti;
2609}
2610
2611
2612QTransform qt_true_matrix(qreal w, qreal h, QTransform x)
2613{
2614 QRectF rect = x.mapRect(QRectF(0, 0, w, h));
2615 return x * QTransform::fromTranslate(-rect.x(), -rect.y());
2616}
2617
2618
2619glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
2620{
2621 if (matrix.type() < QTransform::TxTranslate)
2622 return *this;
2623
2624 glyph_metrics_t m = *this;
2625
2626 qreal w = width.toReal();
2627 qreal h = height.toReal();
2628 QTransform xform = qt_true_matrix(w, h, matrix);
2629
2630 QRectF rect(0, 0, w, h);
2631 rect = xform.mapRect(rect);
2632 m.width = QFixed::fromReal(rect.width());
2633 m.height = QFixed::fromReal(rect.height());
2634
2635 QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
2636
2637 m.x = QFixed::fromReal(l.x1());
2638 m.y = QFixed::fromReal(l.y1());
2639
2640 // The offset is relative to the baseline which is why we use dx/dy of the line
2641 m.xoff = QFixed::fromReal(l.dx());
2642 m.yoff = QFixed::fromReal(l.dy());
2643
2644 return m;
2645}
2646
2647
2648QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.