1 | /* This file is part of the KDE libraries |
---|---|
2 | SPDX-FileCopyrightText: 2006 Jacob R Rideout <kde@jacobrideout.net> |
3 | SPDX-FileCopyrightText: 2006 Martin Sandsmark <martin.sandsmark@kde.org> |
4 | |
5 | SPDX-License-Identifier: LGPL-2.0-or-later |
6 | */ |
7 | |
8 | #include <QHash> |
9 | #include <QString> |
10 | #include <QTextBoundaryFinder> |
11 | |
12 | #include "textbreaks_p.h" |
13 | |
14 | namespace Sonnet |
15 | { |
16 | class TextBreaksPrivate |
17 | { |
18 | public: |
19 | TextBreaksPrivate() |
20 | { |
21 | } |
22 | |
23 | QString text; |
24 | }; |
25 | |
26 | TextBreaks::TextBreaks(const QString &text) |
27 | : d(new TextBreaksPrivate()) |
28 | { |
29 | setText(text); |
30 | } |
31 | |
32 | TextBreaks::~TextBreaks() = default; |
33 | |
34 | QString TextBreaks::text() const |
35 | { |
36 | return d->text; |
37 | } |
38 | |
39 | void TextBreaks::setText(const QString &text) |
40 | { |
41 | d->text = text; |
42 | } |
43 | |
44 | TextBreaks::Positions TextBreaks::wordBreaks(const QString &text) |
45 | { |
46 | Positions breaks; |
47 | |
48 | if (text.isEmpty()) { |
49 | return breaks; |
50 | } |
51 | |
52 | QTextBoundaryFinder boundaryFinder(QTextBoundaryFinder::Word, text); |
53 | |
54 | while (boundaryFinder.position() < text.length()) { |
55 | if (!(boundaryFinder.boundaryReasons().testFlag(flag: QTextBoundaryFinder::StartOfItem))) { |
56 | if (boundaryFinder.toNextBoundary() == -1) { |
57 | break; |
58 | } |
59 | continue; |
60 | } |
61 | |
62 | Position pos; |
63 | pos.start = boundaryFinder.position(); |
64 | int end = boundaryFinder.toNextBoundary(); |
65 | if (end == -1) { |
66 | break; |
67 | } |
68 | pos.length = end - pos.start; |
69 | if (pos.length < 1) { |
70 | continue; |
71 | } |
72 | breaks.append(t: pos); |
73 | |
74 | if (boundaryFinder.toNextBoundary() == -1) { |
75 | break; |
76 | } |
77 | } |
78 | return breaks; |
79 | } |
80 | |
81 | TextBreaks::Positions TextBreaks::sentenceBreaks(const QString &text) |
82 | { |
83 | Positions breaks; |
84 | |
85 | if (text.isEmpty()) { |
86 | return breaks; |
87 | } |
88 | |
89 | QTextBoundaryFinder boundaryFinder(QTextBoundaryFinder::Sentence, text); |
90 | |
91 | while (boundaryFinder.position() < text.length()) { |
92 | Position pos; |
93 | pos.start = boundaryFinder.position(); |
94 | int end = boundaryFinder.toNextBoundary(); |
95 | if (end == -1) { |
96 | break; |
97 | } |
98 | pos.length = end - pos.start; |
99 | if (pos.length < 1) { |
100 | continue; |
101 | } |
102 | breaks.append(t: pos); |
103 | } |
104 | return breaks; |
105 | } |
106 | |
107 | TextBreaks::Positions TextBreaks::wordBreaks() const |
108 | { |
109 | return wordBreaks(text: d->text); |
110 | } |
111 | |
112 | TextBreaks::Positions TextBreaks::sentenceBreaks() const |
113 | { |
114 | return sentenceBreaks(text: d->text); |
115 | } |
116 | } |
117 |