File indexing completed on 2024-04-28 15:34:19
0001 /* This file is part of the KDE libraries 0002 SPDX-FileCopyrightText: 2006 Jacob R Rideout <kde@jacobrideout.net> 0003 SPDX-FileCopyrightText: 2006 Martin Sandsmark <martin.sandsmark@kde.org> 0004 0005 SPDX-License-Identifier: LGPL-2.0-or-later 0006 */ 0007 0008 #include <QHash> 0009 #include <QString> 0010 #include <QTextBoundaryFinder> 0011 0012 #include "textbreaks_p.h" 0013 0014 namespace Sonnet 0015 { 0016 class TextBreaksPrivate 0017 { 0018 public: 0019 TextBreaksPrivate() 0020 { 0021 } 0022 0023 QString text; 0024 }; 0025 0026 TextBreaks::TextBreaks(const QString &text) 0027 : d(new TextBreaksPrivate()) 0028 { 0029 setText(text); 0030 } 0031 0032 TextBreaks::~TextBreaks() 0033 { 0034 delete d; 0035 } 0036 0037 QString TextBreaks::text() const 0038 { 0039 return d->text; 0040 } 0041 0042 void TextBreaks::setText(const QString &text) 0043 { 0044 d->text = text; 0045 } 0046 0047 TextBreaks::Positions TextBreaks::wordBreaks(const QString &text) 0048 { 0049 Positions breaks; 0050 0051 if (text.isEmpty()) { 0052 return breaks; 0053 } 0054 0055 QTextBoundaryFinder boundaryFinder(QTextBoundaryFinder::Word, text); 0056 0057 while (boundaryFinder.position() < text.length()) { 0058 if (!(boundaryFinder.boundaryReasons().testFlag(QTextBoundaryFinder::StartOfItem))) { 0059 if (boundaryFinder.toNextBoundary() == -1) { 0060 break; 0061 } 0062 continue; 0063 } 0064 0065 Position pos; 0066 pos.start = boundaryFinder.position(); 0067 int end = boundaryFinder.toNextBoundary(); 0068 if (end == -1) { 0069 break; 0070 } 0071 pos.length = end - pos.start; 0072 if (pos.length < 1) { 0073 continue; 0074 } 0075 breaks.append(pos); 0076 0077 if (boundaryFinder.toNextBoundary() == -1) { 0078 break; 0079 } 0080 } 0081 return breaks; 0082 } 0083 0084 TextBreaks::Positions TextBreaks::sentenceBreaks(const QString &text) 0085 { 0086 Positions breaks; 0087 0088 if (text.isEmpty()) { 0089 return breaks; 0090 } 0091 0092 QTextBoundaryFinder boundaryFinder(QTextBoundaryFinder::Sentence, text); 0093 0094 while (boundaryFinder.position() < text.length()) { 0095 Position pos; 0096 pos.start = boundaryFinder.position(); 0097 int end = boundaryFinder.toNextBoundary(); 0098 if (end == -1) { 0099 break; 0100 } 0101 pos.length = end - pos.start; 0102 if (pos.length < 1) { 0103 continue; 0104 } 0105 breaks.append(pos); 0106 } 0107 return breaks; 0108 } 0109 0110 TextBreaks::Positions TextBreaks::wordBreaks() const 0111 { 0112 return wordBreaks(d->text); 0113 } 0114 0115 TextBreaks::Positions TextBreaks::sentenceBreaks() const 0116 { 0117 return sentenceBreaks(d->text); 0118 } 0119 }