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

Last change on this file since 1147 was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

File size: 97.7 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
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 qt-info@nokia.com.
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(reinterpret_cast<const ushort *>(m_string.unicode()), 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
859Q_GUI_EXPORT extern 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 && letterSpacing.value())
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 QFixed &advance = glyphs.advances_x[i-1];
898 advance += (letterSpacing - 100) * advance / 100;
899 }
900 }
901 }
902 if (letterSpacingIsAbsolute)
903 glyphs.advances_x[si.num_glyphs-1] += letterSpacing;
904 else {
905 QFixed &advance = glyphs.advances_x[si.num_glyphs-1];
906 advance += (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
926static inline bool hasCaseChange(const QScriptItem &si)
927{
928 return si.analysis.flags == QScriptAnalysis::SmallCaps ||
929 si.analysis.flags == QScriptAnalysis::Uppercase ||
930 si.analysis.flags == QScriptAnalysis::Lowercase;
931}
932
933#if defined(Q_WS_WINCE) //TODO
934// set the glyph attributes heuristically. Assumes a 1 to 1 relationship between chars and glyphs
935// and no reordering.
936// also computes logClusters heuristically
937static void heuristicSetGlyphAttributes(const QChar *uc, int length, QGlyphLayout *glyphs, unsigned short *logClusters, int num_glyphs)
938{
939 // ### zeroWidth and justification are missing here!!!!!
940
941 Q_UNUSED(num_glyphs);
942 Q_ASSERT(num_glyphs <= length);
943
944// qDebug("QScriptEngine::heuristicSetGlyphAttributes, num_glyphs=%d", item->num_glyphs);
945
946 int glyph_pos = 0;
947 for (int i = 0; i < length; i++) {
948 if (uc[i].unicode() >= 0xd800 && uc[i].unicode() < 0xdc00 && i < length-1
949 && uc[i+1].unicode() >= 0xdc00 && uc[i+1].unicode() < 0xe000) {
950 logClusters[i] = glyph_pos;
951 logClusters[++i] = glyph_pos;
952 } else {
953 logClusters[i] = glyph_pos;
954 }
955 ++glyph_pos;
956 }
957
958 // first char in a run is never (treated as) a mark
959 int cStart = 0;
960
961 const bool symbolFont = false; // ####
962 glyphs->attributes[0].mark = false;
963 glyphs->attributes[0].clusterStart = true;
964 glyphs->attributes[0].dontPrint = (!symbolFont && uc[0].unicode() == 0x00ad) || qIsControlChar(uc[0].unicode());
965
966 int pos = 0;
967 int lastCat = QChar::category(uc[0].unicode());
968 for (int i = 1; i < length; ++i) {
969 if (logClusters[i] == pos)
970 // same glyph
971 continue;
972 ++pos;
973 while (pos < logClusters[i]) {
974 glyphs[pos].attributes = glyphs[pos-1].attributes;
975 ++pos;
976 }
977 // hide soft-hyphens by default
978 if ((!symbolFont && uc[i].unicode() == 0x00ad) || qIsControlChar(uc[i].unicode()))
979 glyphs->attributes[pos].dontPrint = true;
980 const QUnicodeTables::Properties *prop = QUnicodeTables::properties(uc[i].unicode());
981 int cat = prop->category;
982 if (cat != QChar::Mark_NonSpacing) {
983 glyphs->attributes[pos].mark = false;
984 glyphs->attributes[pos].clusterStart = true;
985 glyphs->attributes[pos].combiningClass = 0;
986 cStart = logClusters[i];
987 } else {
988 int cmb = prop->combiningClass;
989
990 if (cmb == 0) {
991 // Fix 0 combining classes
992 if ((uc[pos].unicode() & 0xff00) == 0x0e00) {
993 // thai or lao
994 unsigned char col = uc[pos].cell();
995 if (col == 0x31 ||
996 col == 0x34 ||
997 col == 0x35 ||
998 col == 0x36 ||
999 col == 0x37 ||
1000 col == 0x47 ||
1001 col == 0x4c ||
1002 col == 0x4d ||
1003 col == 0x4e) {
1004 cmb = QChar::Combining_AboveRight;
1005 } else if (col == 0xb1 ||
1006 col == 0xb4 ||
1007 col == 0xb5 ||
1008 col == 0xb6 ||
1009 col == 0xb7 ||
1010 col == 0xbb ||
1011 col == 0xcc ||
1012 col == 0xcd) {
1013 cmb = QChar::Combining_Above;
1014 } else if (col == 0xbc) {
1015 cmb = QChar::Combining_Below;
1016 }
1017 }
1018 }
1019
1020 glyphs->attributes[pos].mark = true;
1021 glyphs->attributes[pos].clusterStart = false;
1022 glyphs->attributes[pos].combiningClass = cmb;
1023 logClusters[i] = cStart;
1024 glyphs->advances_x[pos] = 0;
1025 glyphs->advances_y[pos] = 0;
1026 }
1027
1028 // one gets an inter character justification point if the current char is not a non spacing mark.
1029 // as then the current char belongs to the last one and one gets a space justification point
1030 // after the space char.
1031 if (lastCat == QChar::Separator_Space)
1032 glyphs->attributes[pos-1].justification = HB_Space;
1033 else if (cat != QChar::Mark_NonSpacing)
1034 glyphs->attributes[pos-1].justification = HB_Character;
1035 else
1036 glyphs->attributes[pos-1].justification = HB_NoJustification;
1037
1038 lastCat = cat;
1039 }
1040 pos = logClusters[length-1];
1041 if (lastCat == QChar::Separator_Space)
1042 glyphs->attributes[pos].justification = HB_Space;
1043 else
1044 glyphs->attributes[pos].justification = HB_Character;
1045}
1046
1047void QTextEngine::shapeTextWithCE(int item) const
1048{
1049 QScriptItem &si = layoutData->items[item];
1050 si.glyph_data_offset = layoutData->used;
1051
1052 QFontEngine *fe = fontEngine(si, &si.ascent, &si.descent, &si.leading);
1053
1054 QTextEngine::ShaperFlags flags;
1055 if (si.analysis.bidiLevel % 2)
1056 flags |= RightToLeft;
1057 if (option.useDesignMetrics())
1058 flags |= DesignMetrics;
1059
1060 // pre-initialize char attributes
1061 if (! attributes())
1062 return;
1063
1064 const int len = length(item);
1065 int num_glyphs = length(item);
1066 const QChar *str = layoutData->string.unicode() + si.position;
1067 ushort upperCased[256];
1068 if (hasCaseChange(si)) {
1069 ushort *uc = upperCased;
1070 if (len > 256)
1071 uc = new ushort[len];
1072 for (int i = 0; i < len; ++i) {
1073 if(si.analysis.flags == QScriptAnalysis::Lowercase)
1074 uc[i] = str[i].toLower().unicode();
1075 else
1076 uc[i] = str[i].toUpper().unicode();
1077 }
1078 str = reinterpret_cast<const QChar *>(uc);
1079 }
1080
1081 while (true) {
1082 if (! ensureSpace(num_glyphs)) {
1083 // If str is converted to uppercase/lowercase form with a new buffer,
1084 // we need to delete that buffer before return for error
1085 const ushort *uc = reinterpret_cast<const ushort *>(str);
1086 if (hasCaseChange(si) && uc != upperCased)
1087 delete [] uc;
1088 return;
1089 }
1090 num_glyphs = layoutData->glyphLayout.numGlyphs - layoutData->used;
1091
1092 QGlyphLayout g = availableGlyphs(&si);
1093 unsigned short *log_clusters = logClusters(&si);
1094
1095 if (fe->stringToCMap(str,
1096 len,
1097 &g,
1098 &num_glyphs,
1099 flags)) {
1100 heuristicSetGlyphAttributes(str, len, &g, log_clusters, num_glyphs);
1101 break;
1102 }
1103 }
1104
1105 si.num_glyphs = num_glyphs;
1106
1107 layoutData->used += si.num_glyphs;
1108
1109 const ushort *uc = reinterpret_cast<const ushort *>(str);
1110 if (hasCaseChange(si) && uc != upperCased)
1111 delete [] uc;
1112}
1113#endif
1114
1115static inline void moveGlyphData(const QGlyphLayout &destination, const QGlyphLayout &source, int num)
1116{
1117 if (num > 0 && destination.glyphs != source.glyphs) {
1118 memmove(destination.glyphs, source.glyphs, num * sizeof(HB_Glyph));
1119 memmove(destination.attributes, source.attributes, num * sizeof(HB_GlyphAttributes));
1120 memmove(destination.advances_x, source.advances_x, num * sizeof(HB_Fixed));
1121 memmove(destination.offsets, source.offsets, num * sizeof(HB_FixedPoint));
1122 }
1123}
1124
1125/// take the item from layoutData->items and
1126void QTextEngine::shapeTextWithHarfbuzz(int item) const
1127{
1128 Q_ASSERT(sizeof(HB_Fixed) == sizeof(QFixed));
1129 Q_ASSERT(sizeof(HB_FixedPoint) == sizeof(QFixedPoint));
1130
1131 QScriptItem &si = layoutData->items[item];
1132
1133 si.glyph_data_offset = layoutData->used;
1134
1135 QFontEngine *font = fontEngine(si, &si.ascent, &si.descent, &si.leading);
1136
1137 bool kerningEnabled = this->font(si).d->kerning;
1138
1139 HB_ShaperItem entire_shaper_item;
1140 qMemSet(&entire_shaper_item, 0, sizeof(entire_shaper_item));
1141 entire_shaper_item.string = reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData());
1142 entire_shaper_item.stringLength = layoutData->string.length();
1143 entire_shaper_item.item.script = (HB_Script)si.analysis.script;
1144 entire_shaper_item.item.pos = si.position;
1145 entire_shaper_item.item.length = length(item);
1146 entire_shaper_item.item.bidiLevel = si.analysis.bidiLevel;
1147
1148 HB_UChar16 upperCased[256]; // XXX what about making this 4096, so we don't have to extend it ever.
1149 if (hasCaseChange(si)) {
1150 HB_UChar16 *uc = upperCased;
1151 if (entire_shaper_item.item.length > 256)
1152 uc = new HB_UChar16[entire_shaper_item.item.length];
1153 for (uint i = 0; i < entire_shaper_item.item.length; ++i) {
1154 if(si.analysis.flags == QScriptAnalysis::Lowercase)
1155 uc[i] = QChar::toLower(entire_shaper_item.string[si.position + i]);
1156 else
1157 uc[i] = QChar::toUpper(entire_shaper_item.string[si.position + i]);
1158 }
1159 entire_shaper_item.item.pos = 0;
1160 entire_shaper_item.string = uc;
1161 entire_shaper_item.stringLength = entire_shaper_item.item.length;
1162 }
1163
1164 entire_shaper_item.shaperFlags = 0;
1165 if (!kerningEnabled)
1166 entire_shaper_item.shaperFlags |= HB_ShaperFlag_NoKerning;
1167 if (option.useDesignMetrics())
1168 entire_shaper_item.shaperFlags |= HB_ShaperFlag_UseDesignMetrics;
1169
1170 entire_shaper_item.num_glyphs = qMax(layoutData->glyphLayout.numGlyphs - layoutData->used, int(entire_shaper_item.item.length));
1171 if (! ensureSpace(entire_shaper_item.num_glyphs)) {
1172 if (hasCaseChange(si))
1173 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1174 return;
1175 }
1176 QGlyphLayout initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1177
1178 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1179 if (! ensureSpace(entire_shaper_item.num_glyphs)) {
1180 if (hasCaseChange(si))
1181 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1182 return;
1183 }
1184 initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs);
1185
1186 if (!stringToGlyphs(&entire_shaper_item, &initialGlyphs, font)) {
1187 // ############ if this happens there's a bug in the fontengine
1188 if (hasCaseChange(si) && entire_shaper_item.string != upperCased)
1189 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1190 return;
1191 }
1192 }
1193
1194 // split up the item into parts that come from different font engines.
1195 QVarLengthArray<int> itemBoundaries(2);
1196 // k * 2 entries, array[k] == index in string, array[k + 1] == index in glyphs
1197 itemBoundaries[0] = entire_shaper_item.item.pos;
1198 itemBoundaries[1] = 0;
1199
1200 if (font->type() == QFontEngine::Multi) {
1201 uint lastEngine = 0;
1202 int charIdx = entire_shaper_item.item.pos;
1203 const int stringEnd = charIdx + entire_shaper_item.item.length;
1204 for (quint32 i = 0; i < entire_shaper_item.num_glyphs; ++i, ++charIdx) {
1205 uint engineIdx = initialGlyphs.glyphs[i] >> 24;
1206 if (engineIdx != lastEngine && i > 0) {
1207 itemBoundaries.append(charIdx);
1208 itemBoundaries.append(i);
1209 }
1210 lastEngine = engineIdx;
1211 if (HB_IsHighSurrogate(entire_shaper_item.string[charIdx])
1212 && charIdx < stringEnd - 1
1213 && HB_IsLowSurrogate(entire_shaper_item.string[charIdx + 1]))
1214 ++charIdx;
1215 }
1216 }
1217
1218
1219
1220 int remaining_glyphs = entire_shaper_item.num_glyphs;
1221 int glyph_pos = 0;
1222 // for each item shape using harfbuzz and store the results in our layoutData's glyphs array.
1223 for (int k = 0; k < itemBoundaries.size(); k += 2) { // for the +2, see the comment at the definition of itemBoundaries
1224
1225 HB_ShaperItem shaper_item = entire_shaper_item;
1226
1227 shaper_item.item.pos = itemBoundaries[k];
1228 if (k < itemBoundaries.size() - 3) {
1229 shaper_item.item.length = itemBoundaries[k + 2] - shaper_item.item.pos;
1230 shaper_item.num_glyphs = itemBoundaries[k + 3] - itemBoundaries[k + 1];
1231 } else { // last combo in the list, avoid out of bounds access.
1232 shaper_item.item.length -= shaper_item.item.pos - entire_shaper_item.item.pos;
1233 shaper_item.num_glyphs -= itemBoundaries[k + 1];
1234 }
1235 shaper_item.initialGlyphCount = shaper_item.num_glyphs;
1236
1237 QFontEngine *actualFontEngine = font;
1238 uint engineIdx = 0;
1239 if (font->type() == QFontEngine::Multi) {
1240 engineIdx = uint(availableGlyphs(&si).glyphs[glyph_pos] >> 24);
1241
1242 actualFontEngine = static_cast<QFontEngineMulti *>(font)->engine(engineIdx);
1243 }
1244
1245 shaper_item.font = actualFontEngine->harfbuzzFont();
1246 shaper_item.face = actualFontEngine->harfbuzzFace();
1247
1248 shaper_item.glyphIndicesPresent = true;
1249
1250 remaining_glyphs -= shaper_item.initialGlyphCount;
1251
1252 do {
1253 if (! ensureSpace(glyph_pos + shaper_item.num_glyphs + remaining_glyphs)) {
1254 if (hasCaseChange(si))
1255 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1256 return;
1257 }
1258
1259 const QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos);
1260 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1261
1262 shaper_item.glyphs = g.glyphs;
1263 shaper_item.attributes = g.attributes;
1264 shaper_item.advances = reinterpret_cast<HB_Fixed *>(g.advances_x);
1265 shaper_item.offsets = reinterpret_cast<HB_FixedPoint *>(g.offsets);
1266
1267 if (shaper_item.glyphIndicesPresent) {
1268 for (hb_uint32 i = 0; i < shaper_item.initialGlyphCount; ++i)
1269 shaper_item.glyphs[i] &= 0x00ffffff;
1270 }
1271
1272 shaper_item.log_clusters = logClusters(&si) + shaper_item.item.pos - entire_shaper_item.item.pos;
1273
1274// qDebug(" .. num_glyphs=%d, used=%d, item.num_glyphs=%d", num_glyphs, used, shaper_item.num_glyphs);
1275 } while (!qShapeItem(&shaper_item)); // this does the actual shaping via harfbuzz.
1276
1277 QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos, shaper_item.num_glyphs);
1278 moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
1279
1280 for (hb_uint32 i = 0; i < shaper_item.num_glyphs; ++i)
1281 g.glyphs[i] = g.glyphs[i] | (engineIdx << 24);
1282
1283 for (hb_uint32 i = 0; i < shaper_item.item.length; ++i)
1284 shaper_item.log_clusters[i] += glyph_pos;
1285
1286 if (kerningEnabled && !shaper_item.kerning_applied)
1287 font->doKerning(&g, option.useDesignMetrics() ? QFlag(QTextEngine::DesignMetrics) : QFlag(0));
1288
1289 glyph_pos += shaper_item.num_glyphs;
1290 }
1291
1292// qDebug(" -> item: script=%d num_glyphs=%d", shaper_item.script, shaper_item.num_glyphs);
1293 si.num_glyphs = glyph_pos;
1294
1295 layoutData->used += si.num_glyphs;
1296
1297 if (hasCaseChange(si) && entire_shaper_item.string != upperCased)
1298 delete [] const_cast<HB_UChar16 *>(entire_shaper_item.string);
1299}
1300
1301static void init(QTextEngine *e)
1302{
1303 e->ignoreBidi = false;
1304 e->cacheGlyphs = false;
1305 e->forceJustification = false;
1306
1307 e->layoutData = 0;
1308
1309 e->minWidth = 0;
1310 e->maxWidth = 0;
1311
1312 e->underlinePositions = 0;
1313 e->specialData = 0;
1314 e->stackEngine = false;
1315}
1316
1317QTextEngine::QTextEngine()
1318{
1319 init(this);
1320}
1321
1322QTextEngine::QTextEngine(const QString &str, const QFont &f)
1323 : text(str),
1324 fnt(f)
1325{
1326 init(this);
1327}
1328
1329QTextEngine::~QTextEngine()
1330{
1331 if (!stackEngine)
1332 delete layoutData;
1333 delete specialData;
1334}
1335
1336const HB_CharAttributes *QTextEngine::attributes() const
1337{
1338 if (layoutData && layoutData->haveCharAttributes)
1339 return (HB_CharAttributes *) layoutData->memory;
1340
1341 itemize();
1342 if (! ensureSpace(layoutData->string.length()))
1343 return NULL;
1344
1345 QVarLengthArray<HB_ScriptItem> hbScriptItems(layoutData->items.size());
1346
1347 for (int i = 0; i < layoutData->items.size(); ++i) {
1348 const QScriptItem &si = layoutData->items[i];
1349 hbScriptItems[i].pos = si.position;
1350 hbScriptItems[i].length = length(i);
1351 hbScriptItems[i].bidiLevel = si.analysis.bidiLevel;
1352 hbScriptItems[i].script = (HB_Script)si.analysis.script;
1353 }
1354
1355 qGetCharAttributes(reinterpret_cast<const HB_UChar16 *>(layoutData->string.constData()),
1356 layoutData->string.length(),
1357 hbScriptItems.data(), hbScriptItems.size(),
1358 (HB_CharAttributes *)layoutData->memory);
1359
1360
1361 layoutData->haveCharAttributes = true;
1362 return (HB_CharAttributes *) layoutData->memory;
1363}
1364
1365void QTextEngine::shape(int item) const
1366{
1367 if (layoutData->items[item].analysis.flags == QScriptAnalysis::Object) {
1368 ensureSpace(1);
1369 if (block.docHandle()) {
1370 QTextFormat format = formats()->format(formatIndex(&layoutData->items[item]));
1371 docLayout()->resizeInlineObject(QTextInlineObject(item, const_cast<QTextEngine *>(this)),
1372 layoutData->items[item].position + block.position(), format);
1373 }
1374 } else if (layoutData->items[item].analysis.flags == QScriptAnalysis::Tab) {
1375 // set up at least the ascent/descent/leading of the script item for the tab
1376 fontEngine(layoutData->items[item],
1377 &layoutData->items[item].ascent,
1378 &layoutData->items[item].descent,
1379 &layoutData->items[item].leading);
1380 } else {
1381 shapeText(item);
1382 }
1383}
1384
1385void QTextEngine::invalidate()
1386{
1387 freeMemory();
1388 minWidth = 0;
1389 maxWidth = 0;
1390 if (specialData)
1391 specialData->resolvedFormatIndices.clear();
1392}
1393
1394void QTextEngine::clearLineData()
1395{
1396 lines.clear();
1397}
1398
1399void QTextEngine::validate() const
1400{
1401 if (layoutData)
1402 return;
1403 layoutData = new LayoutData();
1404 if (block.docHandle()) {
1405 layoutData->string = block.text();
1406 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1407 layoutData->string += QLatin1Char(block.next().isValid() ? 0xb6 : 0x20);
1408 } else {
1409 layoutData->string = text;
1410 }
1411 if (specialData && specialData->preeditPosition != -1)
1412 layoutData->string.insert(specialData->preeditPosition, specialData->preeditText);
1413}
1414
1415void QTextEngine::itemize() const
1416{
1417 validate();
1418 if (layoutData->items.size())
1419 return;
1420
1421 int length = layoutData->string.length();
1422 if (!length)
1423 return;
1424#if defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA)
1425 // ATSUI requires RTL flags to correctly identify the character stops.
1426 bool ignore = false;
1427#else
1428 bool ignore = ignoreBidi;
1429#endif
1430
1431 bool rtl = isRightToLeft();
1432
1433 if (!ignore && !rtl) {
1434 ignore = true;
1435 const QChar *start = layoutData->string.unicode();
1436 const QChar * const end = start + length;
1437 while (start < end) {
1438 if (start->unicode() >= 0x590) {
1439 ignore = false;
1440 break;
1441 }
1442 ++start;
1443 }
1444 }
1445
1446 QVarLengthArray<QScriptAnalysis, 4096> scriptAnalysis(length);
1447 QScriptAnalysis *analysis = scriptAnalysis.data();
1448
1449 QBidiControl control(rtl);
1450
1451 if (ignore) {
1452 memset(analysis, 0, length*sizeof(QScriptAnalysis));
1453 if (option.textDirection() == Qt::RightToLeft) {
1454 for (int i = 0; i < length; ++i)
1455 analysis[i].bidiLevel = 1;
1456 layoutData->hasBidi = true;
1457 }
1458 } else {
1459 layoutData->hasBidi = bidiItemize(const_cast<QTextEngine *>(this), analysis, control);
1460 }
1461
1462 const ushort *uc = reinterpret_cast<const ushort *>(layoutData->string.unicode());
1463 const ushort *e = uc + length;
1464 int lastScript = QUnicodeTables::Common;
1465 while (uc < e) {
1466 int script = QUnicodeTables::script(*uc);
1467 if (script == QUnicodeTables::Inherited)
1468 script = lastScript;
1469 analysis->flags = QScriptAnalysis::None;
1470 if (*uc == QChar::ObjectReplacementCharacter) {
1471 if (analysis->bidiLevel % 2)
1472 --analysis->bidiLevel;
1473 analysis->script = QUnicodeTables::Common;
1474 analysis->flags = QScriptAnalysis::Object;
1475 } else if (*uc == QChar::LineSeparator) {
1476 if (analysis->bidiLevel % 2)
1477 --analysis->bidiLevel;
1478 analysis->script = QUnicodeTables::Common;
1479 analysis->flags = QScriptAnalysis::LineOrParagraphSeparator;
1480 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators)
1481 *const_cast<ushort*>(uc) = 0x21B5; // visual line separator
1482 } else if (*uc == 9) {
1483 analysis->script = QUnicodeTables::Common;
1484 analysis->flags = QScriptAnalysis::Tab;
1485 analysis->bidiLevel = control.baseLevel();
1486 } else if ((*uc == 32 || *uc == QChar::Nbsp)
1487 && (option.flags() & QTextOption::ShowTabsAndSpaces)) {
1488 analysis->script = QUnicodeTables::Common;
1489 analysis->flags = QScriptAnalysis::Space;
1490 analysis->bidiLevel = control.baseLevel();
1491 } else {
1492 analysis->script = script;
1493 }
1494 lastScript = analysis->script;
1495 ++uc;
1496 ++analysis;
1497 }
1498 if (option.flags() & QTextOption::ShowLineAndParagraphSeparators) {
1499 (analysis-1)->flags = QScriptAnalysis::LineOrParagraphSeparator; // to exclude it from width
1500 }
1501
1502 Itemizer itemizer(layoutData->string, scriptAnalysis.data(), layoutData->items);
1503
1504 const QTextDocumentPrivate *p = block.docHandle();
1505 if (p) {
1506 SpecialData *s = specialData;
1507
1508 QTextDocumentPrivate::FragmentIterator it = p->find(block.position());
1509 QTextDocumentPrivate::FragmentIterator end = p->find(block.position() + block.length() - 1); // -1 to omit the block separator char
1510 int format = it.value()->format;
1511
1512 int prevPosition = 0;
1513 int position = prevPosition;
1514 while (1) {
1515 const QTextFragmentData * const frag = it.value();
1516 if (it == end || format != frag->format) {
1517 if (s && position >= s->preeditPosition) {
1518 position += s->preeditText.length();
1519 s = 0;
1520 }
1521 Q_ASSERT(position <= length);
1522 itemizer.generate(prevPosition, position - prevPosition,
1523 formats()->charFormat(format).fontCapitalization());
1524 if (it == end) {
1525 if (position < length)
1526 itemizer.generate(position, length - position,
1527 formats()->charFormat(format).fontCapitalization());
1528 break;
1529 }
1530 format = frag->format;
1531 prevPosition = position;
1532 }
1533 position += frag->size_array[0];
1534 ++it;
1535 }
1536 } else {
1537 itemizer.generate(0, length, static_cast<QFont::Capitalization> (fnt.d->capital));
1538 }
1539
1540 addRequiredBoundaries();
1541 resolveAdditionalFormats();
1542}
1543
1544bool QTextEngine::isRightToLeft() const
1545{
1546 switch (option.textDirection()) {
1547 case Qt::LeftToRight:
1548 return false;
1549 case Qt::RightToLeft:
1550 return true;
1551 default:
1552 break;
1553 }
1554 // this places the cursor in the right position depending on the keyboard layout
1555 if (layoutData->string.isEmpty())
1556 return QApplication::keyboardInputDirection() == Qt::RightToLeft;
1557 return layoutData->string.isRightToLeft();
1558}
1559
1560
1561int QTextEngine::findItem(int strPos) const
1562{
1563 itemize();
1564 int left = 0;
1565 int right = layoutData->items.size()-1;
1566 while(left <= right) {
1567 int middle = ((right-left)/2)+left;
1568 if (strPos > layoutData->items[middle].position)
1569 left = middle+1;
1570 else if(strPos < layoutData->items[middle].position)
1571 right = middle-1;
1572 else {
1573 return middle;
1574 }
1575 }
1576 return right;
1577}
1578
1579QFixed QTextEngine::width(int from, int len) const
1580{
1581 itemize();
1582
1583 QFixed w = 0;
1584
1585// qDebug("QTextEngine::width(from = %d, len = %d), numItems=%d, strleng=%d", from, len, items.size(), string.length());
1586 for (int i = 0; i < layoutData->items.size(); i++) {
1587 const QScriptItem *si = layoutData->items.constData() + i;
1588 int pos = si->position;
1589 int ilen = length(i);
1590// qDebug("item %d: from %d len %d", i, pos, ilen);
1591 if (pos >= from + len)
1592 break;
1593 if (pos + ilen > from) {
1594 if (!si->num_glyphs)
1595 shape(i);
1596
1597 if (si->analysis.flags == QScriptAnalysis::Object) {
1598 w += si->width;
1599 continue;
1600 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1601 w += calculateTabWidth(i, w);
1602 continue;
1603 }
1604
1605
1606 QGlyphLayout glyphs = shapedGlyphs(si);
1607 unsigned short *logClusters = this->logClusters(si);
1608
1609// fprintf(stderr, " logclusters:");
1610// for (int k = 0; k < ilen; k++)
1611// fprintf(stderr, " %d", logClusters[k]);
1612// fprintf(stderr, "\n");
1613 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1614 int charFrom = from - pos;
1615 if (charFrom < 0)
1616 charFrom = 0;
1617 int glyphStart = logClusters[charFrom];
1618 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1619 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1620 charFrom++;
1621 if (charFrom < ilen) {
1622 glyphStart = logClusters[charFrom];
1623 int charEnd = from + len - 1 - pos;
1624 if (charEnd >= ilen)
1625 charEnd = ilen-1;
1626 int glyphEnd = logClusters[charEnd];
1627 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1628 charEnd++;
1629 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1630
1631// qDebug("char: start=%d end=%d / glyph: start = %d, end = %d", charFrom, charEnd, glyphStart, glyphEnd);
1632 for (int i = glyphStart; i < glyphEnd; i++)
1633 w += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
1634 }
1635 }
1636 }
1637// qDebug(" --> w= %d ", w);
1638 return w;
1639}
1640
1641glyph_metrics_t QTextEngine::boundingBox(int from, int len) const
1642{
1643 itemize();
1644
1645 glyph_metrics_t gm;
1646
1647 for (int i = 0; i < layoutData->items.size(); i++) {
1648 const QScriptItem *si = layoutData->items.constData() + i;
1649
1650 int pos = si->position;
1651 int ilen = length(i);
1652 if (pos > from + len)
1653 break;
1654 if (pos + ilen > from) {
1655 if (!si->num_glyphs)
1656 shape(i);
1657
1658 if (si->analysis.flags == QScriptAnalysis::Object) {
1659 gm.width += si->width;
1660 continue;
1661 } else if (si->analysis.flags == QScriptAnalysis::Tab) {
1662 gm.width += calculateTabWidth(i, gm.width);
1663 continue;
1664 }
1665
1666 unsigned short *logClusters = this->logClusters(si);
1667 QGlyphLayout glyphs = shapedGlyphs(si);
1668
1669 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1670 int charFrom = from - pos;
1671 if (charFrom < 0)
1672 charFrom = 0;
1673 int glyphStart = logClusters[charFrom];
1674 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1675 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1676 charFrom++;
1677 if (charFrom < ilen) {
1678 QFontEngine *fe = fontEngine(*si);
1679 glyphStart = logClusters[charFrom];
1680 int charEnd = from + len - 1 - pos;
1681 if (charEnd >= ilen)
1682 charEnd = ilen-1;
1683 int glyphEnd = logClusters[charEnd];
1684 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1685 charEnd++;
1686 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1687 if (glyphStart <= glyphEnd ) {
1688 glyph_metrics_t m = fe->boundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1689 gm.x = qMin(gm.x, m.x + gm.xoff);
1690 gm.y = qMin(gm.y, m.y + gm.yoff);
1691 gm.width = qMax(gm.width, m.width+gm.xoff);
1692 gm.height = qMax(gm.height, m.height+gm.yoff);
1693 gm.xoff += m.xoff;
1694 gm.yoff += m.yoff;
1695 }
1696 }
1697 }
1698 }
1699 return gm;
1700}
1701
1702glyph_metrics_t QTextEngine::tightBoundingBox(int from, int len) const
1703{
1704 itemize();
1705
1706 glyph_metrics_t gm;
1707
1708 for (int i = 0; i < layoutData->items.size(); i++) {
1709 const QScriptItem *si = layoutData->items.constData() + i;
1710 int pos = si->position;
1711 int ilen = length(i);
1712 if (pos > from + len)
1713 break;
1714 if (pos + len > from) {
1715 if (!si->num_glyphs)
1716 shape(i);
1717 unsigned short *logClusters = this->logClusters(si);
1718 QGlyphLayout glyphs = shapedGlyphs(si);
1719
1720 // do the simple thing for now and give the first glyph in a cluster the full width, all other ones 0.
1721 int charFrom = from - pos;
1722 if (charFrom < 0)
1723 charFrom = 0;
1724 int glyphStart = logClusters[charFrom];
1725 if (charFrom > 0 && logClusters[charFrom-1] == glyphStart)
1726 while (charFrom < ilen && logClusters[charFrom] == glyphStart)
1727 charFrom++;
1728 if (charFrom < ilen) {
1729 glyphStart = logClusters[charFrom];
1730 int charEnd = from + len - 1 - pos;
1731 if (charEnd >= ilen)
1732 charEnd = ilen-1;
1733 int glyphEnd = logClusters[charEnd];
1734 while (charEnd < ilen && logClusters[charEnd] == glyphEnd)
1735 charEnd++;
1736 glyphEnd = (charEnd == ilen) ? si->num_glyphs : logClusters[charEnd];
1737 if (glyphStart <= glyphEnd ) {
1738 QFontEngine *fe = fontEngine(*si);
1739 glyph_metrics_t m = fe->tightBoundingBox(glyphs.mid(glyphStart, glyphEnd - glyphStart));
1740 gm.x = qMin(gm.x, m.x + gm.xoff);
1741 gm.y = qMin(gm.y, m.y + gm.yoff);
1742 gm.width = qMax(gm.width, m.width+gm.xoff);
1743 gm.height = qMax(gm.height, m.height+gm.yoff);
1744 gm.xoff += m.xoff;
1745 gm.yoff += m.yoff;
1746 }
1747 }
1748 }
1749 }
1750 return gm;
1751}
1752
1753QFont QTextEngine::font(const QScriptItem &si) const
1754{
1755 QFont font = fnt;
1756 if (hasFormats()) {
1757 QTextCharFormat f = format(&si);
1758 font = f.font();
1759
1760 if (block.docHandle() && block.docHandle()->layout()) {
1761 // Make sure we get the right dpi on printers
1762 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1763 if (pdev)
1764 font = QFont(font, pdev);
1765 } else {
1766 font = font.resolve(fnt);
1767 }
1768 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1769 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1770 if (font.pointSize() != -1)
1771 font.setPointSize((font.pointSize() * 2) / 3);
1772 else
1773 font.setPixelSize((font.pixelSize() * 2) / 3);
1774 }
1775 }
1776
1777 if (si.analysis.flags == QScriptAnalysis::SmallCaps)
1778 font = font.d->smallCapsFont();
1779
1780 return font;
1781}
1782
1783QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
1784{
1785 QFontEngine *engine = 0;
1786 QFontEngine *scaledEngine = 0;
1787 int script = si.analysis.script;
1788
1789 QFont font = fnt;
1790 if (hasFormats()) {
1791 QTextCharFormat f = format(&si);
1792 font = f.font();
1793
1794 if (block.docHandle() && block.docHandle()->layout()) {
1795 // Make sure we get the right dpi on printers
1796 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
1797 if (pdev)
1798 font = QFont(font, pdev);
1799 } else {
1800 font = font.resolve(fnt);
1801 }
1802 engine = font.d->engineForScript(script);
1803 QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
1804 if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
1805 if (font.pointSize() != -1)
1806 font.setPointSize((font.pointSize() * 2) / 3);
1807 else
1808 font.setPixelSize((font.pixelSize() * 2) / 3);
1809 scaledEngine = font.d->engineForScript(script);
1810 }
1811 } else {
1812 engine = font.d->engineForScript(script);
1813 }
1814
1815 if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
1816 QFontPrivate *p = font.d->smallCapsFontPrivate();
1817 scaledEngine = p->engineForScript(script);
1818 }
1819
1820 if (ascent) {
1821 *ascent = engine->ascent();
1822 *descent = engine->descent();
1823 *leading = engine->leading();
1824 }
1825
1826 if (scaledEngine)
1827 return scaledEngine;
1828 return engine;
1829}
1830
1831struct QJustificationPoint {
1832 int type;
1833 QFixed kashidaWidth;
1834 QGlyphLayout glyph;
1835 QFontEngine *fontEngine;
1836};
1837
1838Q_DECLARE_TYPEINFO(QJustificationPoint, Q_PRIMITIVE_TYPE);
1839
1840static void set(QJustificationPoint *point, int type, const QGlyphLayout &glyph, QFontEngine *fe)
1841{
1842 point->type = type;
1843 point->glyph = glyph;
1844 point->fontEngine = fe;
1845
1846 if (type >= HB_Arabic_Normal) {
1847 QChar ch(0x640); // Kashida character
1848 QGlyphLayoutArray<8> glyphs;
1849 int nglyphs = 7;
1850 fe->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1851 if (glyphs.glyphs[0] && glyphs.advances_x[0] != 0) {
1852 point->kashidaWidth = glyphs.advances_x[0];
1853 } else {
1854 point->type = HB_NoJustification;
1855 point->kashidaWidth = 0;
1856 }
1857 }
1858}
1859
1860
1861void QTextEngine::justify(const QScriptLine &line)
1862{
1863// qDebug("justify: line.gridfitted = %d, line.justified=%d", line.gridfitted, line.justified);
1864 if (line.gridfitted && line.justified)
1865 return;
1866
1867 if (!line.gridfitted) {
1868 // redo layout in device metrics, then adjust
1869 const_cast<QScriptLine &>(line).gridfitted = true;
1870 }
1871
1872 if ((option.alignment() & Qt::AlignHorizontal_Mask) != Qt::AlignJustify)
1873 return;
1874
1875 itemize();
1876
1877 if (!forceJustification) {
1878 int end = line.from + (int)line.length;
1879 if (end == layoutData->string.length())
1880 return; // no justification at end of paragraph
1881 if (end && layoutData->items[findItem(end-1)].analysis.flags == QScriptAnalysis::LineOrParagraphSeparator)
1882 return; // no justification at the end of an explicitly separated line
1883 }
1884
1885 // justify line
1886 int maxJustify = 0;
1887
1888 // don't include trailing white spaces when doing justification
1889 int line_length = line.length;
1890 const HB_CharAttributes *a = attributes();
1891 if (! a)
1892 return;
1893 a += line.from;
1894 while (line_length && a[line_length-1].whiteSpace)
1895 --line_length;
1896 // subtract one char more, as we can't justfy after the last character
1897 --line_length;
1898
1899 if (!line_length)
1900 return;
1901
1902 int firstItem = findItem(line.from);
1903 int nItems = findItem(line.from + line_length - 1) - firstItem + 1;
1904
1905 QVarLengthArray<QJustificationPoint> justificationPoints;
1906 int nPoints = 0;
1907// 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());
1908 QFixed minKashida = 0x100000;
1909
1910 // we need to do all shaping before we go into the next loop, as we there
1911 // store pointers to the glyph data that could get reallocated by the shaping
1912 // process.
1913 for (int i = 0; i < nItems; ++i) {
1914 QScriptItem &si = layoutData->items[firstItem + i];
1915 if (!si.num_glyphs)
1916 shape(firstItem + i);
1917 }
1918
1919 for (int i = 0; i < nItems; ++i) {
1920 QScriptItem &si = layoutData->items[firstItem + i];
1921
1922 int kashida_type = HB_Arabic_Normal;
1923 int kashida_pos = -1;
1924
1925 int start = qMax(line.from - si.position, 0);
1926 int end = qMin(line.from + line_length - (int)si.position, length(firstItem+i));
1927
1928 unsigned short *log_clusters = logClusters(&si);
1929
1930 int gs = log_clusters[start];
1931 int ge = (end == length(firstItem+i) ? si.num_glyphs : log_clusters[end]);
1932
1933 const QGlyphLayout g = shapedGlyphs(&si);
1934
1935 for (int i = gs; i < ge; ++i) {
1936 g.justifications[i].type = QGlyphJustification::JustifyNone;
1937 g.justifications[i].nKashidas = 0;
1938 g.justifications[i].space_18d6 = 0;
1939
1940 justificationPoints.resize(nPoints+3);
1941 int justification = g.attributes[i].justification;
1942
1943 switch(justification) {
1944 case HB_NoJustification:
1945 break;
1946 case HB_Space :
1947 // fall through
1948 case HB_Arabic_Space :
1949 if (kashida_pos >= 0) {
1950// qDebug("kashida position at %d in word", kashida_pos);
1951 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
1952 if (justificationPoints[nPoints].kashidaWidth > 0) {
1953 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
1954 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
1955 ++nPoints;
1956 }
1957 }
1958 kashida_pos = -1;
1959 kashida_type = HB_Arabic_Normal;
1960 // fall through
1961 case HB_Character :
1962 set(&justificationPoints[nPoints++], justification, g.mid(i), fontEngine(si));
1963 maxJustify = qMax(maxJustify, justification);
1964 break;
1965 case HB_Arabic_Normal :
1966 case HB_Arabic_Waw :
1967 case HB_Arabic_BaRa :
1968 case HB_Arabic_Alef :
1969 case HB_Arabic_HaaDal :
1970 case HB_Arabic_Seen :
1971 case HB_Arabic_Kashida :
1972 if (justification >= kashida_type) {
1973 kashida_pos = i;
1974 kashida_type = justification;
1975 }
1976 }
1977 }
1978 if (kashida_pos >= 0) {
1979 set(&justificationPoints[nPoints], kashida_type, g.mid(kashida_pos), fontEngine(si));
1980 if (justificationPoints[nPoints].kashidaWidth > 0) {
1981 minKashida = qMin(minKashida, justificationPoints[nPoints].kashidaWidth);
1982 maxJustify = qMax(maxJustify, justificationPoints[nPoints].type);
1983 ++nPoints;
1984 }
1985 }
1986 }
1987
1988 QFixed need = line.width - line.textWidth;
1989 if (need < 0) {
1990 // line overflows already!
1991 const_cast<QScriptLine &>(line).justified = true;
1992 return;
1993 }
1994
1995// qDebug("doing justification: textWidth=%x, requested=%x, maxJustify=%d", line.textWidth.value(), line.width.value(), maxJustify);
1996// qDebug(" minKashida=%f, need=%f", minKashida.toReal(), need.toReal());
1997
1998 // distribute in priority order
1999 if (maxJustify >= HB_Arabic_Normal) {
2000 while (need >= minKashida) {
2001 for (int type = maxJustify; need >= minKashida && type >= HB_Arabic_Normal; --type) {
2002 for (int i = 0; need >= minKashida && i < nPoints; ++i) {
2003 if (justificationPoints[i].type == type && justificationPoints[i].kashidaWidth <= need) {
2004 justificationPoints[i].glyph.justifications->nKashidas++;
2005 // ############
2006 justificationPoints[i].glyph.justifications->space_18d6 += justificationPoints[i].kashidaWidth.value();
2007 need -= justificationPoints[i].kashidaWidth;
2008// qDebug("adding kashida type %d with width %x, neednow %x", type, justificationPoints[i].kashidaWidth, need.value());
2009 }
2010 }
2011 }
2012 }
2013 }
2014 Q_ASSERT(need >= 0);
2015 if (!need)
2016 goto end;
2017
2018 maxJustify = qMin(maxJustify, (int)HB_Space);
2019 for (int type = maxJustify; need != 0 && type > 0; --type) {
2020 int n = 0;
2021 for (int i = 0; i < nPoints; ++i) {
2022 if (justificationPoints[i].type == type)
2023 ++n;
2024 }
2025// qDebug("number of points for justification type %d: %d", type, n);
2026
2027
2028 if (!n)
2029 continue;
2030
2031 for (int i = 0; i < nPoints; ++i) {
2032 if (justificationPoints[i].type == type) {
2033 QFixed add = need/n;
2034// qDebug("adding %x to glyph %x", add.value(), justificationPoints[i].glyph->glyph);
2035 justificationPoints[i].glyph.justifications[0].space_18d6 = add.value();
2036 need -= add;
2037 --n;
2038 }
2039 }
2040
2041 Q_ASSERT(!need);
2042 }
2043 end:
2044 const_cast<QScriptLine &>(line).justified = true;
2045}
2046
2047void QScriptLine::setDefaultHeight(QTextEngine *eng)
2048{
2049 QFont f;
2050 QFontEngine *e;
2051
2052 if (eng->block.docHandle() && eng->block.docHandle()->layout()) {
2053 f = eng->block.charFormat().font();
2054 // Make sure we get the right dpi on printers
2055 QPaintDevice *pdev = eng->block.docHandle()->layout()->paintDevice();
2056 if (pdev)
2057 f = QFont(f, pdev);
2058 e = f.d->engineForScript(QUnicodeTables::Common);
2059 } else {
2060 e = eng->fnt.d->engineForScript(QUnicodeTables::Common);
2061 }
2062
2063 QFixed other_ascent = e->ascent();
2064 QFixed other_descent = e->descent();
2065 QFixed other_leading = e->leading();
2066 leading = qMax(leading + ascent, other_leading + other_ascent) - qMax(ascent, other_ascent);
2067 ascent = qMax(ascent, other_ascent);
2068 descent = qMax(descent, other_descent);
2069}
2070
2071QTextEngine::LayoutData::LayoutData()
2072{
2073 memory = 0;
2074 allocated = 0;
2075 memory_on_stack = false;
2076 used = 0;
2077 hasBidi = false;
2078 layoutState = LayoutEmpty;
2079 haveCharAttributes = false;
2080 logClustersPtr = 0;
2081 available_glyphs = 0;
2082}
2083
2084QTextEngine::LayoutData::LayoutData(const QString &str, void **stack_memory, int _allocated)
2085 : string(str)
2086{
2087 allocated = _allocated;
2088
2089 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2090 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2091 available_glyphs = ((int)allocated - space_charAttributes - space_logClusters)*(int)sizeof(void*)/(int)QGlyphLayout::spaceNeededForGlyphLayout(1);
2092
2093 if (available_glyphs < str.length()) {
2094 // need to allocate on the heap
2095 allocated = 0;
2096
2097 memory_on_stack = false;
2098 memory = 0;
2099 logClustersPtr = 0;
2100 } else {
2101 memory_on_stack = true;
2102 memory = stack_memory;
2103 logClustersPtr = (unsigned short *)(memory + space_charAttributes);
2104
2105 void *m = memory + space_charAttributes + space_logClusters;
2106 glyphLayout = QGlyphLayout(reinterpret_cast<char *>(m), str.length());
2107 glyphLayout.clear();
2108 memset(memory, 0, space_charAttributes*sizeof(void *));
2109 }
2110 used = 0;
2111 hasBidi = false;
2112 layoutState = LayoutEmpty;
2113 haveCharAttributes = false;
2114}
2115
2116QTextEngine::LayoutData::~LayoutData()
2117{
2118 if (!memory_on_stack)
2119 free(memory);
2120 memory = 0;
2121}
2122
2123bool QTextEngine::LayoutData::reallocate(int totalGlyphs)
2124{
2125 Q_ASSERT(totalGlyphs >= glyphLayout.numGlyphs);
2126 if (memory_on_stack && available_glyphs >= totalGlyphs) {
2127 glyphLayout.grow(glyphLayout.data(), totalGlyphs);
2128 return true;
2129 }
2130
2131 int space_charAttributes = sizeof(HB_CharAttributes)*string.length()/sizeof(void*) + 1;
2132 int space_logClusters = sizeof(unsigned short)*string.length()/sizeof(void*) + 1;
2133 int space_glyphs = QGlyphLayout::spaceNeededForGlyphLayout(totalGlyphs)/sizeof(void*) + 2;
2134
2135 int newAllocated = space_charAttributes + space_glyphs + space_logClusters;
2136 // These values can be negative if the length of string/glyphs causes overflow,
2137 // we can't layout such a long string all at once, so return false here to
2138 // indicate there is a failure
2139 if (space_charAttributes < 0 || space_logClusters < 0 || space_glyphs < 0 || newAllocated < allocated) {
2140 layoutState = LayoutFailed;
2141 return false;
2142 }
2143
2144 void **newMem = memory;
2145 newMem = (void **)::realloc(memory_on_stack ? 0 : memory, newAllocated*sizeof(void *));
2146 if (!newMem) {
2147 layoutState = LayoutFailed;
2148 return false;
2149 }
2150 if (memory_on_stack)
2151 memcpy(newMem, memory, allocated*sizeof(void *));
2152 memory = newMem;
2153 memory_on_stack = false;
2154
2155 void **m = memory;
2156 m += space_charAttributes;
2157 logClustersPtr = (unsigned short *) m;
2158 m += space_logClusters;
2159
2160 const int space_preGlyphLayout = space_charAttributes + space_logClusters;
2161 if (allocated < space_preGlyphLayout)
2162 memset(memory + allocated, 0, (space_preGlyphLayout - allocated)*sizeof(void *));
2163
2164 glyphLayout.grow(reinterpret_cast<char *>(m), totalGlyphs);
2165
2166 allocated = newAllocated;
2167 return true;
2168}
2169
2170// grow to the new size, copying the existing data to the new layout
2171void QGlyphLayout::grow(char *address, int totalGlyphs)
2172{
2173 QGlyphLayout oldLayout(address, numGlyphs);
2174 QGlyphLayout newLayout(address, totalGlyphs);
2175
2176 if (numGlyphs) {
2177 // move the existing data
2178 memmove(newLayout.attributes, oldLayout.attributes, numGlyphs * sizeof(HB_GlyphAttributes));
2179 memmove(newLayout.justifications, oldLayout.justifications, numGlyphs * sizeof(QGlyphJustification));
2180 memmove(newLayout.advances_y, oldLayout.advances_y, numGlyphs * sizeof(QFixed));
2181 memmove(newLayout.advances_x, oldLayout.advances_x, numGlyphs * sizeof(QFixed));
2182 memmove(newLayout.glyphs, oldLayout.glyphs, numGlyphs * sizeof(HB_Glyph));
2183 }
2184
2185 // clear the new data
2186 newLayout.clear(numGlyphs);
2187
2188 *this = newLayout;
2189}
2190
2191void QTextEngine::freeMemory()
2192{
2193 if (!stackEngine) {
2194 delete layoutData;
2195 layoutData = 0;
2196 } else {
2197 layoutData->used = 0;
2198 layoutData->hasBidi = false;
2199 layoutData->layoutState = LayoutEmpty;
2200 layoutData->haveCharAttributes = false;
2201 }
2202 for (int i = 0; i < lines.size(); ++i) {
2203 lines[i].justified = 0;
2204 lines[i].gridfitted = 0;
2205 }
2206}
2207
2208int QTextEngine::formatIndex(const QScriptItem *si) const
2209{
2210 if (specialData && !specialData->resolvedFormatIndices.isEmpty())
2211 return specialData->resolvedFormatIndices.at(si - &layoutData->items[0]);
2212 QTextDocumentPrivate *p = block.docHandle();
2213 if (!p)
2214 return -1;
2215 int pos = si->position;
2216 if (specialData && si->position >= specialData->preeditPosition) {
2217 if (si->position < specialData->preeditPosition + specialData->preeditText.length())
2218 pos = qMax(specialData->preeditPosition - 1, 0);
2219 else
2220 pos -= specialData->preeditText.length();
2221 }
2222 QTextDocumentPrivate::FragmentIterator it = p->find(block.position() + pos);
2223 return it.value()->format;
2224}
2225
2226
2227QTextCharFormat QTextEngine::format(const QScriptItem *si) const
2228{
2229 QTextCharFormat format;
2230 const QTextFormatCollection *formats = 0;
2231 if (block.docHandle()) {
2232 formats = this->formats();
2233 format = formats->charFormat(formatIndex(si));
2234 }
2235 if (specialData && specialData->resolvedFormatIndices.isEmpty()) {
2236 int end = si->position + length(si);
2237 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2238 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2239 if (r.start <= si->position && r.start + r.length >= end) {
2240 if (!specialData->addFormatIndices.isEmpty())
2241 format.merge(formats->format(specialData->addFormatIndices.at(i)));
2242 else
2243 format.merge(r.format);
2244 }
2245 }
2246 }
2247 return format;
2248}
2249
2250void QTextEngine::addRequiredBoundaries() const
2251{
2252 if (specialData) {
2253 for (int i = 0; i < specialData->addFormats.size(); ++i) {
2254 const QTextLayout::FormatRange &r = specialData->addFormats.at(i);
2255 setBoundary(r.start);
2256 setBoundary(r.start + r.length);
2257 //qDebug("adding boundaries %d %d", r.start, r.start+r.length);
2258 }
2259 }
2260}
2261
2262bool QTextEngine::atWordSeparator(int position) const
2263{
2264 const QChar c = layoutData->string.at(position);
2265 switch (c.toLatin1()) {
2266 case '.':
2267 case ',':
2268 case '?':
2269 case '!':
2270 case '@':
2271 case '#':
2272 case '$':
2273 case ':':
2274 case ';':
2275 case '-':
2276 case '<':
2277 case '>':
2278 case '[':
2279 case ']':
2280 case '(':
2281 case ')':
2282 case '{':
2283 case '}':
2284 case '=':
2285 case '/':
2286 case '+':
2287 case '%':
2288 case '&':
2289 case '^':
2290 case '*':
2291 case '\'':
2292 case '"':
2293 case '`':
2294 case '~':
2295 case '|':
2296 return true;
2297 default:
2298 return false;
2299 }
2300}
2301
2302bool QTextEngine::atSpace(int position) const
2303{
2304 const QChar c = layoutData->string.at(position);
2305
2306 return c == QLatin1Char(' ')
2307 || c == QChar::Nbsp
2308 || c == QChar::LineSeparator
2309 || c == QLatin1Char('\t')
2310 ;
2311}
2312
2313
2314void QTextEngine::indexAdditionalFormats()
2315{
2316 if (!block.docHandle())
2317 return;
2318
2319 specialData->addFormatIndices.resize(specialData->addFormats.count());
2320 QTextFormatCollection * const formats = this->formats();
2321
2322 for (int i = 0; i < specialData->addFormats.count(); ++i) {
2323 specialData->addFormatIndices[i] = formats->indexForFormat(specialData->addFormats.at(i).format);
2324 specialData->addFormats[i].format = QTextCharFormat();
2325 }
2326}
2327
2328/* These two helper functions are used to determine whether we need to insert a ZWJ character
2329 between the text that gets truncated and the ellipsis. This is important to get
2330 correctly shaped results for arabic text.
2331*/
2332static bool nextCharJoins(const QString &string, int pos)
2333{
2334 while (pos < string.length() && string.at(pos).category() == QChar::Mark_NonSpacing)
2335 ++pos;
2336 if (pos == string.length())
2337 return false;
2338 return string.at(pos).joining() != QChar::OtherJoining;
2339}
2340
2341static bool prevCharJoins(const QString &string, int pos)
2342{
2343 while (pos > 0 && string.at(pos - 1).category() == QChar::Mark_NonSpacing)
2344 --pos;
2345 if (pos == 0)
2346 return false;
2347 return (string.at(pos - 1).joining() == QChar::Dual || string.at(pos - 1).joining() == QChar::Center);
2348}
2349
2350QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int flags) const
2351{
2352// qDebug() << "elidedText; available width" << width.toReal() << "text width:" << this->width(0, layoutData->string.length()).toReal();
2353
2354 if (flags & Qt::TextShowMnemonic) {
2355 itemize();
2356 for (int i = 0; i < layoutData->items.size(); ++i) {
2357 QScriptItem &si = layoutData->items[i];
2358 if (!si.num_glyphs)
2359 shape(i);
2360
2361 HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
2362 if (!attributes)
2363 return QString();
2364
2365 unsigned short *logClusters = this->logClusters(&si);
2366 QGlyphLayout glyphs = shapedGlyphs(&si);
2367
2368 const int end = si.position + length(&si);
2369 for (int i = si.position; i < end - 1; ++i)
2370 if (layoutData->string.at(i) == QLatin1Char('&')) {
2371 const int gp = logClusters[i - si.position];
2372 glyphs.attributes[gp].dontPrint = true;
2373 attributes[i + 1].charStop = false;
2374 attributes[i + 1].whiteSpace = false;
2375 attributes[i + 1].lineBreakType = HB_NoBreak;
2376 if (i < end - 1
2377 && layoutData->string.at(i + 1) == QLatin1Char('&'))
2378 ++i;
2379 }
2380 }
2381 }
2382
2383 validate();
2384
2385 if (mode == Qt::ElideNone
2386 || this->width(0, layoutData->string.length()) <= width
2387 || layoutData->string.length() <= 1)
2388 return layoutData->string;
2389
2390 QFixed ellipsisWidth;
2391 QString ellipsisText;
2392 {
2393 QChar ellipsisChar(0x2026);
2394
2395 QFontEngine *fe = fnt.d->engineForScript(QUnicodeTables::Common);
2396
2397 QGlyphLayoutArray<1> ellipsisGlyph;
2398 {
2399 QFontEngine *feForEllipsis = (fe->type() == QFontEngine::Multi)
2400 ? static_cast<QFontEngineMulti *>(fe)->engine(0)
2401 : fe;
2402
2403 if (feForEllipsis->type() == QFontEngine::Mac)
2404 feForEllipsis = fe;
2405
2406 // the lookup can be really slow when we use XLFD fonts
2407 if (feForEllipsis->type() != QFontEngine::XLFD
2408 && feForEllipsis->canRender(&ellipsisChar, 1)) {
2409 int nGlyphs = 1;
2410 feForEllipsis->stringToCMap(&ellipsisChar, 1, &ellipsisGlyph, &nGlyphs, 0);
2411 }
2412 }
2413
2414 if (ellipsisGlyph.glyphs[0]) {
2415 ellipsisWidth = ellipsisGlyph.advances_x[0];
2416 ellipsisText = ellipsisChar;
2417 } else {
2418 QString dotDotDot(QLatin1String("..."));
2419
2420 QGlyphLayoutArray<3> glyphs;
2421 int nGlyphs = 3;
2422 if (!fe->stringToCMap(dotDotDot.constData(), 3, &glyphs, &nGlyphs, 0))
2423 // should never happen...
2424 return layoutData->string;
2425 for (int i = 0; i < nGlyphs; ++i)
2426 ellipsisWidth += glyphs.advances_x[i];
2427 ellipsisText = dotDotDot;
2428 }
2429 }
2430
2431 const QFixed availableWidth = width - ellipsisWidth;
2432 if (availableWidth < 0)
2433 return QString();
2434
2435 const HB_CharAttributes *attributes = this->attributes();
2436 if (!attributes)
2437 return QString();
2438
2439 if (mode == Qt::ElideRight) {
2440 QFixed currentWidth;
2441 int pos = 0;
2442 int nextBreak = 0;
2443
2444 do {
2445 pos = nextBreak;
2446
2447 ++nextBreak;
2448 while (nextBreak < layoutData->string.length() && !attributes[nextBreak].charStop)
2449 ++nextBreak;
2450
2451 currentWidth += this->width(pos, nextBreak - pos);
2452 } while (nextBreak < layoutData->string.length()
2453 && currentWidth < availableWidth);
2454
2455 if (nextCharJoins(layoutData->string, pos))
2456 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2457
2458 return layoutData->string.left(pos) + ellipsisText;
2459 } else if (mode == Qt::ElideLeft) {
2460 QFixed currentWidth;
2461 int pos = layoutData->string.length();
2462 int nextBreak = layoutData->string.length();
2463
2464 do {
2465 pos = nextBreak;
2466
2467 --nextBreak;
2468 while (nextBreak > 0 && !attributes[nextBreak].charStop)
2469 --nextBreak;
2470
2471 currentWidth += this->width(nextBreak, pos - nextBreak);
2472 } while (nextBreak > 0
2473 && currentWidth < availableWidth);
2474
2475 if (prevCharJoins(layoutData->string, pos))
2476 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2477
2478 return ellipsisText + layoutData->string.mid(pos);
2479 } else if (mode == Qt::ElideMiddle) {
2480 QFixed leftWidth;
2481 QFixed rightWidth;
2482
2483 int leftPos = 0;
2484 int nextLeftBreak = 0;
2485
2486 int rightPos = layoutData->string.length();
2487 int nextRightBreak = layoutData->string.length();
2488
2489 do {
2490 leftPos = nextLeftBreak;
2491 rightPos = nextRightBreak;
2492
2493 ++nextLeftBreak;
2494 while (nextLeftBreak < layoutData->string.length() && !attributes[nextLeftBreak].charStop)
2495 ++nextLeftBreak;
2496
2497 --nextRightBreak;
2498 while (nextRightBreak > 0 && !attributes[nextRightBreak].charStop)
2499 --nextRightBreak;
2500
2501 leftWidth += this->width(leftPos, nextLeftBreak - leftPos);
2502 rightWidth += this->width(nextRightBreak, rightPos - nextRightBreak);
2503 } while (nextLeftBreak < layoutData->string.length()
2504 && nextRightBreak > 0
2505 && leftWidth + rightWidth < availableWidth);
2506
2507 if (nextCharJoins(layoutData->string, leftPos))
2508 ellipsisText.prepend(QChar(0x200d) /* ZWJ */);
2509 if (prevCharJoins(layoutData->string, rightPos))
2510 ellipsisText.append(QChar(0x200d) /* ZWJ */);
2511
2512 return layoutData->string.left(leftPos) + ellipsisText + layoutData->string.mid(rightPos);
2513 }
2514
2515 return layoutData->string;
2516}
2517
2518void QTextEngine::setBoundary(int strPos) const
2519{
2520 if (strPos <= 0 || strPos >= layoutData->string.length())
2521 return;
2522
2523 int itemToSplit = 0;
2524 while (itemToSplit < layoutData->items.size() && layoutData->items.at(itemToSplit).position <= strPos)
2525 itemToSplit++;
2526 itemToSplit--;
2527 if (layoutData->items.at(itemToSplit).position == strPos) {
2528 // already a split at the requested position
2529 return;
2530 }
2531 splitItem(itemToSplit, strPos - layoutData->items.at(itemToSplit).position);
2532}
2533
2534void QTextEngine::splitItem(int item, int pos) const
2535{
2536 if (pos <= 0)
2537 return;
2538
2539 layoutData->items.insert(item + 1, layoutData->items[item]);
2540 QScriptItem &oldItem = layoutData->items[item];
2541 QScriptItem &newItem = layoutData->items[item+1];
2542 newItem.position += pos;
2543
2544 if (oldItem.num_glyphs) {
2545 // already shaped, break glyphs aswell
2546 int breakGlyph = logClusters(&oldItem)[pos];
2547
2548 newItem.num_glyphs = oldItem.num_glyphs - breakGlyph;
2549 oldItem.num_glyphs = breakGlyph;
2550 newItem.glyph_data_offset = oldItem.glyph_data_offset + breakGlyph;
2551
2552 for (int i = 0; i < newItem.num_glyphs; i++)
2553 logClusters(&newItem)[i] -= breakGlyph;
2554
2555 QFixed w = 0;
2556 const QGlyphLayout g = shapedGlyphs(&oldItem);
2557 for(int j = 0; j < breakGlyph; ++j)
2558 w += g.advances_x[j];
2559
2560 newItem.width = oldItem.width - w;
2561 oldItem.width = w;
2562 }
2563
2564// qDebug("split at position %d itempos=%d", pos, item);
2565}
2566
2567Q_GUI_EXPORT extern int qt_defaultDpiY();
2568
2569QFixed QTextEngine::calculateTabWidth(int item, QFixed x) const
2570{
2571 const QScriptItem &si = layoutData->items[item];
2572
2573 QFixed dpiScale = 1;
2574 if (block.docHandle() && block.docHandle()->layout()) {
2575 QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
2576 if (pdev)
2577 dpiScale = QFixed::fromReal(pdev->logicalDpiY() / qreal(qt_defaultDpiY()));
2578 } else {
2579 dpiScale = QFixed::fromReal(fnt.d->dpi / qreal(qt_defaultDpiY()));
2580 }
2581
2582 QList<QTextOption::Tab> tabArray = option.tabs();
2583 if (!tabArray.isEmpty()) {
2584 if (isRightToLeft()) { // rebase the tabArray positions.
2585 QList<QTextOption::Tab> newTabs;
2586 QList<QTextOption::Tab>::Iterator iter = tabArray.begin();
2587 while(iter != tabArray.end()) {
2588 QTextOption::Tab tab = *iter;
2589 if (tab.type == QTextOption::LeftTab)
2590 tab.type = QTextOption::RightTab;
2591 else if (tab.type == QTextOption::RightTab)
2592 tab.type = QTextOption::LeftTab;
2593 newTabs << tab;
2594 ++iter;
2595 }
2596 tabArray = newTabs;
2597 }
2598 for (int i = 0; i < tabArray.size(); ++i) {
2599 QFixed tab = QFixed::fromReal(tabArray[i].position) * dpiScale;
2600 if (tab > x) { // this is the tab we need.
2601 QTextOption::Tab tabSpec = tabArray[i];
2602 int tabSectionEnd = layoutData->string.count();
2603 if (tabSpec.type == QTextOption::RightTab || tabSpec.type == QTextOption::CenterTab) {
2604 // find next tab to calculate the width required.
2605 tab = QFixed::fromReal(tabSpec.position);
2606 for (int i=item + 1; i < layoutData->items.count(); i++) {
2607 const QScriptItem &item = layoutData->items[i];
2608 if (item.analysis.flags == QScriptAnalysis::TabOrObject) { // found it.
2609 tabSectionEnd = item.position;
2610 break;
2611 }
2612 }
2613 }
2614 else if (tabSpec.type == QTextOption::DelimiterTab)
2615 // find delimitor character to calculate the width required
2616 tabSectionEnd = qMax(si.position, layoutData->string.indexOf(tabSpec.delimiter, si.position) + 1);
2617
2618 if (tabSectionEnd > si.position) {
2619 QFixed length;
2620 // Calculate the length of text between this tab and the tabSectionEnd
2621 for (int i=item; i < layoutData->items.count(); i++) {
2622 QScriptItem &item = layoutData->items[i];
2623 if (item.position > tabSectionEnd || item.position <= si.position)
2624 continue;
2625 shape(i); // first, lets make sure relevant text is already shaped
2626 QGlyphLayout glyphs = this->shapedGlyphs(&item);
2627 const int end = qMin(item.position + item.num_glyphs, tabSectionEnd) - item.position;
2628 for (int i=0; i < end; i++)
2629 length += glyphs.advances_x[i] * !glyphs.attributes[i].dontPrint;
2630 if (end + item.position == tabSectionEnd && tabSpec.type == QTextOption::DelimiterTab) // remove half of matching char
2631 length -= glyphs.advances_x[end] / 2 * !glyphs.attributes[end].dontPrint;
2632 }
2633
2634 switch (tabSpec.type) {
2635 case QTextOption::CenterTab:
2636 length /= 2;
2637 // fall through
2638 case QTextOption::DelimiterTab:
2639 // fall through
2640 case QTextOption::RightTab:
2641 tab = QFixed::fromReal(tabSpec.position) * dpiScale - length;
2642 if (tab < 0) // default to tab taking no space
2643 return QFixed();
2644 break;
2645 case QTextOption::LeftTab:
2646 break;
2647 }
2648 }
2649 return tab - x;
2650 }
2651 }
2652 }
2653 QFixed tab = QFixed::fromReal(option.tabStop());
2654 if (tab <= 0)
2655 tab = 80; // default
2656 tab *= dpiScale;
2657 QFixed nextTabPos = ((x / tab).truncate() + 1) * tab;
2658 QFixed tabWidth = nextTabPos - x;
2659
2660 return tabWidth;
2661}
2662
2663void QTextEngine::resolveAdditionalFormats() const
2664{
2665 if (!specialData || specialData->addFormats.isEmpty()
2666 || !block.docHandle()
2667 || !specialData->resolvedFormatIndices.isEmpty())
2668 return;
2669
2670 QTextFormatCollection *collection = this->formats();
2671
2672 specialData->resolvedFormatIndices.clear();
2673 QVector<int> indices(layoutData->items.count());
2674 for (int i = 0; i < layoutData->items.count(); ++i) {
2675 QTextCharFormat f = format(&layoutData->items.at(i));
2676 indices[i] = collection->indexForFormat(f);
2677 }
2678 specialData->resolvedFormatIndices = indices;
2679}
2680
2681QStackTextEngine::QStackTextEngine(const QString &string, const QFont &f)
2682 : QTextEngine(string, f),
2683 _layoutData(string, _memory, MemSize)
2684{
2685 stackEngine = true;
2686 layoutData = &_layoutData;
2687}
2688
2689QTextItemInt::QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format)
2690 : justified(false), underlineStyle(QTextCharFormat::NoUnderline), charFormat(format),
2691 num_chars(0), chars(0), logClusters(0), f(0), fontEngine(0)
2692{
2693 // explicitly initialize flags so that initFontAttributes can be called
2694 // multiple times on the same TextItem
2695 flags = 0;
2696 if (si.analysis.bidiLevel %2)
2697 flags |= QTextItem::RightToLeft;
2698 ascent = si.ascent;
2699 descent = si.descent;
2700 f = font;
2701 fontEngine = f->d->engineForScript(si.analysis.script);
2702 Q_ASSERT(fontEngine);
2703
2704 if (format.hasProperty(QTextFormat::TextUnderlineStyle)) {
2705 underlineStyle = format.underlineStyle();
2706 } else if (format.boolProperty(QTextFormat::FontUnderline)
2707 || f->d->underline) {
2708 underlineStyle = QTextCharFormat::SingleUnderline;
2709 }
2710
2711 // compat
2712 if (underlineStyle == QTextCharFormat::SingleUnderline)
2713 flags |= QTextItem::Underline;
2714
2715 if (f->d->overline || format.fontOverline())
2716 flags |= QTextItem::Overline;
2717 if (f->d->strikeOut || format.fontStrikeOut())
2718 flags |= QTextItem::StrikeOut;
2719}
2720
2721QTextItemInt::QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars_, int numChars, QFontEngine *fe)
2722 : flags(0), justified(false), underlineStyle(QTextCharFormat::NoUnderline),
2723 num_chars(numChars), chars(chars_), logClusters(0), f(font), glyphs(g), fontEngine(fe)
2724{
2725}
2726
2727QTextItemInt QTextItemInt::midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const
2728{
2729 QTextItemInt ti = *this;
2730 const int end = firstGlyphIndex + numGlyphs;
2731 ti.glyphs = glyphs.mid(firstGlyphIndex, numGlyphs);
2732 ti.fontEngine = fontEngine;
2733
2734 if (logClusters && chars) {
2735 const int logClusterOffset = logClusters[0];
2736 while (logClusters[ti.chars - chars] - logClusterOffset < firstGlyphIndex)
2737 ++ti.chars;
2738
2739 ti.logClusters += (ti.chars - chars);
2740
2741 ti.num_chars = 0;
2742 int char_start = ti.chars - chars;
2743 while (char_start + ti.num_chars < num_chars && ti.logClusters[ti.num_chars] - logClusterOffset < end)
2744 ++ti.num_chars;
2745 }
2746 return ti;
2747}
2748
2749
2750QTransform qt_true_matrix(qreal w, qreal h, QTransform x)
2751{
2752 QRectF rect = x.mapRect(QRectF(0, 0, w, h));
2753 return x * QTransform::fromTranslate(-rect.x(), -rect.y());
2754}
2755
2756
2757glyph_metrics_t glyph_metrics_t::transformed(const QTransform &matrix) const
2758{
2759 if (matrix.type() < QTransform::TxTranslate)
2760 return *this;
2761
2762 glyph_metrics_t m = *this;
2763
2764 qreal w = width.toReal();
2765 qreal h = height.toReal();
2766 QTransform xform = qt_true_matrix(w, h, matrix);
2767
2768 QRectF rect(0, 0, w, h);
2769 rect = xform.mapRect(rect);
2770 m.width = QFixed::fromReal(rect.width());
2771 m.height = QFixed::fromReal(rect.height());
2772
2773 QLineF l = xform.map(QLineF(x.toReal(), y.toReal(), xoff.toReal(), yoff.toReal()));
2774
2775 m.x = QFixed::fromReal(l.x1());
2776 m.y = QFixed::fromReal(l.y1());
2777
2778 // The offset is relative to the baseline which is why we use dx/dy of the line
2779 m.xoff = QFixed::fromReal(l.dx());
2780 m.yoff = QFixed::fromReal(l.dy());
2781
2782 return m;
2783}
2784
2785
2786QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.