QSkinny 0.8.0
C++/Qt UI toolkit
Loading...
Searching...
No Matches
QskPinyinTextPredictor.cpp
1/******************************************************************************
2 * QSkinny - Copyright (C) The authors
3 * SPDX-License-Identifier: BSD-3-Clause
4 *****************************************************************************/
5
6#include "QskPinyinTextPredictor.h"
7#include "QskInputContext.h"
8
9#include "pinyinime.h"
10
11#include <QDebug>
12#include <QStringList>
13
14class QskPinyinTextPredictor::PrivateData
15{
16 public:
17 QStringList candidates;
18};
19
20QskPinyinTextPredictor::QskPinyinTextPredictor( QObject* parent )
21 : Inherited( Attributes(), parent )
22 , m_data( new PrivateData )
23{
24#if 1
25 const char dictionary[] = "XXX/3rdparty/pinyin/data/dict_pinyin.dat";
26#endif
27
28 // ### prevent having 2 calls to im_open_decoder by using a singleton or so
29 bool opened = ime_pinyin::im_open_decoder( dictionary, "" );
30
31 if ( !opened )
32 {
33 qWarning() << "could not open pinyin decoder dictionary at" << dictionary;
34 }
35}
36
37QskPinyinTextPredictor::~QskPinyinTextPredictor()
38{
39 ime_pinyin::im_close_decoder();
40}
41
42int QskPinyinTextPredictor::candidateCount() const
43{
44 return m_data->candidates.count();
45}
46
47QString QskPinyinTextPredictor::candidate( int index ) const
48{
49 if ( ( index >= 0 ) && ( index < m_data->candidates.count() ) )
50 return m_data->candidates[ index ];
51
52 return QString();
53}
54
55void QskPinyinTextPredictor::reset()
56{
57 ime_pinyin::im_reset_search();
58
59 if ( !m_data->candidates.isEmpty() )
60 {
61 m_data->candidates.clear();
62 Q_EMIT predictionChanged();
63 }
64}
65
66void QskPinyinTextPredictor::request( const QString& text )
67{
68 const QByteArray bytes = text.toLatin1();
69
70 size_t count = ime_pinyin::im_search(
71 bytes.constData(), size_t( bytes.length() ) );
72
73 if ( count <= 0 )
74 return;
75
76 const size_t maxCount = 20;
77 if ( count > maxCount )
78 count = maxCount;
79
80 QVector< QChar > candidateBuffer;
81 candidateBuffer.resize( ime_pinyin::kMaxSearchSteps + 1 );
82
83 QStringList candidates;
84 candidates.reserve( count );
85
86 for ( unsigned int i = 0; i < count; i++ )
87 {
88 size_t length = static_cast< size_t >( candidateBuffer.length() - 1 );
89 const auto buf = reinterpret_cast< ime_pinyin::char16* >( candidateBuffer.data() );
90
91 const bool found = ime_pinyin::im_get_candidate( i, buf, length );
92 Q_ASSERT( found );
93
94 candidateBuffer.last() = 0;
95
96 auto candidate = QString( candidateBuffer.data() );
97 candidate = QChar( Qt::Key( candidate[ 0 ].unicode() ) );
98
99 candidates += candidate;
100 }
101
102 m_data->candidates = candidates;
103 Q_EMIT predictionChanged();
104}
105
106#include "moc_QskPinyinTextPredictor.cpp"