Coverage Report

Created: 2026-07-10 11:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libreoffice/lingucomponent/source/hyphenator/hyphen/hyphenimp.cxx
Line
Count
Source
1
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
/*
3
 * This file is part of the LibreOffice project.
4
 *
5
 * This Source Code Form is subject to the terms of the Mozilla Public
6
 * License, v. 2.0. If a copy of the MPL was not distributed with this
7
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8
 *
9
 * This file incorporates work covered by the following license notice:
10
 *
11
 *   Licensed to the Apache Software Foundation (ASF) under one or more
12
 *   contributor license agreements. See the NOTICE file distributed
13
 *   with this work for additional information regarding copyright
14
 *   ownership. The ASF licenses this file to you under the Apache
15
 *   License, Version 2.0 (the "License"); you may not use this file
16
 *   except in compliance with the License. You may obtain a copy of
17
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
18
 */
19
20
#include <com/sun/star/uno/Reference.h>
21
22
#include <comphelper/lok.hxx>
23
#include <comphelper/sequence.hxx>
24
#include <comphelper/processfactory.hxx>
25
#include <cppuhelper/factory.hxx>
26
#include <cppuhelper/supportsservice.hxx>
27
#include <cppuhelper/weak.hxx>
28
#include <com/sun/star/linguistic2/XLinguProperties.hpp>
29
#include <com/sun/star/linguistic2/LinguServiceManager.hpp>
30
#include <com/sun/star/linguistic2/XSpellChecker1.hpp>
31
#include <i18nlangtag/languagetag.hxx>
32
#include <tools/debug.hxx>
33
#include <osl/mutex.hxx>
34
#include <osl/thread.h>
35
36
#include <hyphen.h>
37
#include "hyphenimp.hxx"
38
39
#include <linguistic/hyphdta.hxx>
40
#include <rtl/ustring.hxx>
41
#include <rtl/ustrbuf.hxx>
42
#include <rtl/textenc.h>
43
#include <sal/log.hxx>
44
45
#include <linguistic/misc.hxx>
46
#include <svtools/strings.hrc>
47
#include <unotools/charclass.hxx>
48
#include <unotools/lingucfg.hxx>
49
#include <unotools/resmgr.hxx>
50
#include <osl/file.hxx>
51
52
#include <stdio.h>
53
#include <string.h>
54
55
#include <cassert>
56
#include <numeric>
57
#include <vector>
58
#include <set>
59
#include <memory>
60
#include <o3tl/string_view.hxx>
61
62
// XML-header to query SPELLML support
63
constexpr OUStringLiteral SPELLML_SUPPORT = u"<?xml?>";
64
65
using namespace osl;
66
using namespace com::sun::star;
67
using namespace com::sun::star::beans;
68
using namespace com::sun::star::lang;
69
using namespace com::sun::star::uno;
70
using namespace com::sun::star::linguistic2;
71
using namespace linguistic;
72
73
static uno::Reference< XLinguServiceManager2 > GetLngSvcMgr_Impl()
74
0
{
75
0
    const uno::Reference< XComponentContext >& xContext( comphelper::getProcessComponentContext() );
76
0
    uno::Reference< XLinguServiceManager2 > xRes = LinguServiceManager::create( xContext ) ;
77
0
    return xRes;
78
0
}
79
80
Hyphenator::Hyphenator() :
81
0
    aEvtListeners   ( GetLinguMutex() )
82
0
{
83
0
    bDisposing = false;
84
0
}
85
86
Hyphenator::~Hyphenator()
87
0
{
88
0
    for (auto & rInfo : mvDicts)
89
0
    {
90
0
        if (rInfo.aPtr)
91
0
            hnj_hyphen_free(rInfo.aPtr);
92
0
    }
93
94
0
    if (pPropHelper)
95
0
    {
96
0
        pPropHelper->RemoveAsPropListener();
97
0
    }
98
0
}
99
100
PropertyHelper_Hyphenation& Hyphenator::GetPropHelper_Impl()
101
0
{
102
0
    if (!pPropHelper)
103
0
    {
104
0
        Reference< XLinguProperties >   xPropSet = GetLinguProperties();
105
106
0
        pPropHelper.reset( new PropertyHelper_Hyphenation (static_cast<XHyphenator *>(this), xPropSet ) );
107
0
        pPropHelper->AddAsPropListener();   //! after a reference is established
108
0
    }
109
0
    return *pPropHelper;
110
0
}
111
112
// Requires GetLinguMutex locked
113
void Hyphenator::ensureLocales()
114
0
{
115
    // this routine should return the locales supported by the installed
116
    // dictionaries.
117
0
    if (mvDicts.empty())
118
0
    {
119
0
        SvtLinguConfig aLinguCfg;
120
121
        // get list of dictionaries-to-use
122
        // (or better speaking: the list of dictionaries using the
123
        // new configuration entries).
124
0
        std::vector< SvtLinguConfigDictionaryEntry > aDics;
125
0
        uno::Sequence< OUString > aFormatList;
126
0
        aLinguCfg.GetSupportedDictionaryFormatsFor( u"Hyphenators"_ustr,
127
0
                u"org.openoffice.lingu.LibHnjHyphenator"_ustr, aFormatList );
128
0
        for (const auto& rFormat : aFormatList)
129
0
        {
130
0
            std::vector< SvtLinguConfigDictionaryEntry > aTmpDic(
131
0
                    aLinguCfg.GetActiveDictionariesByFormat( rFormat ) );
132
0
            aDics.insert( aDics.end(), aTmpDic.begin(), aTmpDic.end() );
133
0
        }
134
135
        //!! for compatibility with old dictionaries (the ones not using extensions
136
        //!! or new configuration entries, but still using the dictionary.lst file)
137
        //!! Get the list of old style spell checking dictionaries to use...
138
0
        std::vector< SvtLinguConfigDictionaryEntry > aOldStyleDics(
139
0
                GetOldStyleDics( "HYPH" ) );
140
141
        // to prefer dictionaries with configuration entries we will only
142
        // use those old style dictionaries that add a language that
143
        // is not yet supported by the list of new style dictionaries
144
0
        MergeNewStyleDicsAndOldStyleDics( aDics, aOldStyleDics );
145
146
0
        if (!aDics.empty())
147
0
        {
148
            // get supported locales from the dictionaries-to-use...
149
0
            std::set<OUString> aLocaleNamesSet;
150
0
            for (auto const& dict : aDics)
151
0
            {
152
0
                for (const auto& rLocaleName : dict.aLocaleNames)
153
0
                {
154
0
                    if (!comphelper::LibreOfficeKit::isAllowlistedLanguage(rLocaleName))
155
0
                        continue;
156
0
                    aLocaleNamesSet.insert( rLocaleName );
157
0
                }
158
0
            }
159
            // ... and add them to the resulting sequence
160
0
            std::vector<Locale> aLocalesVec;
161
0
            aLocalesVec.reserve(aLocaleNamesSet.size());
162
163
0
            std::transform(aLocaleNamesSet.begin(), aLocaleNamesSet.end(), std::back_inserter(aLocalesVec),
164
0
                [](const OUString& localeName) { return LanguageTag::convertToLocale(localeName); });
165
166
0
            aSuppLocales = comphelper::containerToSequence(aLocalesVec);
167
168
            //! For each dictionary and each locale we need a separate entry.
169
            //! If this results in more than one dictionary per locale than (for now)
170
            //! it is undefined which dictionary gets used.
171
            //! In the future the implementation should support using several dictionaries
172
            //! for one locale.
173
0
            sal_Int32 numdict = std::accumulate(aDics.begin(), aDics.end(), 0,
174
0
                [](const sal_Int32 nSum, const SvtLinguConfigDictionaryEntry& dict) {
175
0
                    return nSum + dict.aLocaleNames.getLength(); });
176
177
            // add dictionary information
178
0
            mvDicts.resize(numdict);
179
180
0
            sal_Int32 k = 0;
181
0
            for (auto const& dict :  aDics)
182
0
            {
183
0
                if (dict.aLocaleNames.hasElements() &&
184
0
                    dict.aLocations.hasElements())
185
0
                {
186
                    // currently only one language per dictionary is supported in the actual implementation...
187
                    // Thus here we work-around this by adding the same dictionary several times.
188
                    // Once for each of its supported locales.
189
0
                    for (const auto& rLocaleName : dict.aLocaleNames)
190
0
                    {
191
0
                        LanguageTag aLanguageTag(rLocaleName);
192
0
                        mvDicts[k].aPtr = nullptr;
193
0
                        mvDicts[k].eEnc = RTL_TEXTENCODING_DONTKNOW;
194
0
                        mvDicts[k].aLoc = aLanguageTag.getLocale();
195
0
                        mvDicts[k].apCC.reset( new CharClass( std::move(aLanguageTag) ) );
196
                        // also both files have to be in the same directory and the
197
                        // file names must only differ in the extension (.aff/.dic).
198
                        // Thus we use the first location only and strip the extension part.
199
0
                        OUString aLocation = dict.aLocations[0];
200
0
                        sal_Int32 nPos = aLocation.lastIndexOf( '.' );
201
0
                        aLocation = aLocation.copy( 0, nPos );
202
0
                        mvDicts[k].aName = aLocation;
203
204
0
                        ++k;
205
0
                    }
206
0
                }
207
0
            }
208
0
            DBG_ASSERT( k == numdict, "index mismatch?" );
209
0
        }
210
0
        else
211
0
        {
212
            // no dictionary found so register no dictionaries
213
0
            mvDicts.clear();
214
0
            aSuppLocales.realloc(0);
215
0
        }
216
0
    }
217
0
}
218
219
Sequence< Locale > SAL_CALL Hyphenator::getLocales()
220
0
{
221
0
    MutexGuard aGuard(GetLinguMutex());
222
0
    ensureLocales();
223
0
    return aSuppLocales;
224
0
}
225
226
sal_Bool SAL_CALL Hyphenator::hasLocale(const Locale& rLocale)
227
0
{
228
0
    MutexGuard  aGuard( GetLinguMutex() );
229
0
    ensureLocales();
230
0
    return comphelper::findValue(aSuppLocales, rLocale) != -1;
231
0
}
232
233
namespace {
234
bool LoadDictionary(HDInfo& rDict)
235
0
{
236
0
    OUString DictFN = rDict.aName + ".dic";
237
0
    OUString dictpath;
238
239
0
    osl::FileBase::getSystemPathFromFileURL(DictFN, dictpath);
240
241
#if defined(_WIN32)
242
    // hnj_hyphen_load expects UTF-8 encoded paths with \\?\ long path prefix.
243
    OString sTmp = Win_AddLongPathPrefix(OUStringToOString(dictpath, RTL_TEXTENCODING_UTF8));
244
#else
245
0
    OString sTmp(OU2ENC(dictpath, osl_getThreadTextEncoding()));
246
0
#endif
247
0
    HyphenDict* dict = hnj_hyphen_load(sTmp.getStr());
248
0
    if (!dict)
249
0
    {
250
0
        SAL_WARN(
251
0
            "lingucomponent",
252
0
            "Couldn't find file " << dictpath);
253
0
        return false;
254
0
    }
255
0
    rDict.aPtr = dict;
256
0
    rDict.eEnc = getTextEncodingFromCharset(dict->cset);
257
0
    return true;
258
0
}
259
260
OUString makeLowerCase(const OUString& aTerm, CharClass const* pCC)
261
0
{
262
0
    if (pCC)
263
0
        return pCC->lowercase(aTerm);
264
0
    return aTerm;
265
0
}
266
267
OUString makeUpperCase(const OUString& aTerm, CharClass const* pCC)
268
0
{
269
0
    if (pCC)
270
0
        return pCC->uppercase(aTerm);
271
0
    return aTerm;
272
0
}
273
274
OUString makeInitCap(const OUString& aTerm, CharClass const* pCC)
275
0
{
276
0
    sal_Int32 tlen = aTerm.getLength();
277
0
    if (pCC && tlen)
278
0
    {
279
0
        OUString bTemp = aTerm.copy(0, 1);
280
0
        if (tlen > 1)
281
0
            return (pCC->uppercase(bTemp, 0, 1) + pCC->lowercase(aTerm, 1, (tlen - 1)));
282
283
0
        return pCC->uppercase(bTemp, 0, 1);
284
0
    }
285
0
    return aTerm;
286
0
}
287
288
struct hyphenation_result
289
{
290
    int n = 0;
291
    bool failed = true;
292
    char** rep = nullptr; // replacements of discretionary hyphenation
293
    int* pos = nullptr; // array of [hyphenation point] minus [deletion position]
294
    int* cut = nullptr; // length of deletions in original word
295
    std::unique_ptr<char[]> hyphens;
296
297
    ~hyphenation_result()
298
0
    {
299
0
        if (rep)
300
0
        {
301
0
            for (int i = 0; i < n; i++)
302
0
            {
303
0
                if (rep[i])
304
0
                    free(rep[i]);
305
0
            }
306
0
            free(rep);
307
0
        }
308
0
        if (pos)
309
0
            free(pos);
310
0
        if (cut)
311
0
            free(cut);
312
0
    }
313
};
314
315
hyphenation_result getHyphens(std::u16string_view word, const HDInfo& hdInfo, sal_Int16 minLead,
316
                              sal_Int16 minTrail)
317
0
{
318
    // first convert any smart quotes or apostrophes to normal ones
319
0
    OUStringBuffer aBuf(word);
320
0
    for (sal_Int32 ix = 0; ix < aBuf.getLength(); ix++)
321
0
    {
322
0
        sal_Unicode ch = aBuf[ix];
323
0
        if ((ch == 0x201C) || (ch == 0x201D))
324
0
            aBuf[ix] = u'"';
325
0
        if ((ch == 0x2018) || (ch == 0x2019))
326
0
            aBuf[ix] = u'\'';
327
0
    }
328
329
    // now convert word to all lowercase for pattern recognition
330
0
    OUString nTerm(makeLowerCase(OUString::unacquired(aBuf), hdInfo.apCC.get()));
331
332
    // now convert word to needed encoding
333
0
    OString encWord(OU2ENC(nTerm, hdInfo.eEnc));
334
335
    // now strip off any ending periods
336
0
    auto lastValidPos = std::string_view(encWord).find_last_not_of('.');
337
0
    if (lastValidPos == std::string_view::npos)
338
0
        return {};
339
340
0
    int n = lastValidPos + 1;
341
0
    std::unique_ptr<char[]> hyphens(new char[n + 5]);
342
0
    char** rep = nullptr; // replacements of discretionary hyphenation
343
0
    int* pos = nullptr; // array of [hyphenation point] minus [deletion position]
344
0
    int* cut = nullptr; // length of deletions in original word
345
346
0
    HyphenDict* dict = hdInfo.aPtr;
347
0
    const bool failed = 0 != hnj_hyphen_hyphenate3( dict, encWord.getStr(), n, hyphens.get(), nullptr,
348
0
                &rep, &pos, &cut, minLead, minTrail,
349
                // TODO add "no-limit"/0 clh/crh support to libhyphen, also add minCompoundLead/Trail support
350
0
                std::max<sal_Int16>(dict->clhmin, 2) + std::max(0, minLead  - std::max<sal_Int16>(dict->lhmin, 2)),
351
0
                std::max<sal_Int16>(dict->crhmin, 2) + std::max(0, minTrail - std::max<sal_Int16>(dict->rhmin, 2)) );
352
0
    return { n, failed, rep, pos, cut, std::move(hyphens) }; // buffers will free in dtor
353
0
}
354
}
355
356
const HDInfo* Hyphenator::getMatchingDict(const css::lang::Locale& aLocale)
357
0
{
358
0
    MutexGuard aGuard(GetLinguMutex());
359
0
    ensureLocales();
360
0
    auto it = std::find_if(mvDicts.rbegin(), mvDicts.rend(),
361
0
                           [&aLocale](auto& el) { return el.aLoc == aLocale; });
362
0
    if (it == mvDicts.rend())
363
0
        return nullptr;
364
365
    // if this dictionary has not been loaded yet do that
366
0
    if (!it->aPtr)
367
0
    {
368
0
        if (!LoadDictionary(*it))
369
0
            return nullptr;
370
0
    }
371
372
    // we don't want to work with a default text encoding since following incorrect
373
    // results may occur only for specific text and thus may be hard to notice.
374
    // Thus better always make a clean exit here if the text encoding is in question.
375
    // Hopefully something not working at all will raise proper attention quickly. ;-)
376
0
    DBG_ASSERT(it->eEnc != RTL_TEXTENCODING_DONTKNOW,
377
0
               "failed to get text encoding! (maybe incorrect encoding string in file)");
378
0
    if (it->eEnc == RTL_TEXTENCODING_DONTKNOW)
379
0
        return nullptr;
380
381
0
    return &*it;
382
0
}
383
384
Reference< XHyphenatedWord > SAL_CALL Hyphenator::hyphenate( const OUString& aWord,
385
       const css::lang::Locale& aLocale,
386
       sal_Int16 nMaxLeading,
387
       const css::uno::Sequence< css::beans::PropertyValue >& aProperties )
388
0
{
389
0
    PropertyHelper_Hyphenation& rHelper = GetPropHelper();
390
0
    rHelper.SetTmpPropVals(aProperties);
391
0
    sal_Int16 minTrail = rHelper.GetMinTrailing();
392
0
    sal_Int16 minLead = rHelper.GetMinLeading();
393
0
    sal_Int16 minCompoundLead = rHelper.GetCompoundMinLeading();
394
0
    sal_Int16 minCompoundTrail = rHelper.GetCompoundMinTrailing();
395
0
    sal_Int16 minLen = rHelper.GetMinWordLength();
396
0
    bool bNoHyphenateCaps = rHelper.IsNoHyphenateCaps();
397
398
    // if we have a hyphenation dictionary matching this locale
399
0
    if (auto pHDInfo = getMatchingDict(aLocale))
400
0
    {
401
0
        int nHyphenationPos = -1;
402
0
        int nHyphenationPosAlt = -1;
403
0
        int nHyphenationPosAltHyph = -1;
404
0
        int nPrevHyphenationPos = -1;
405
0
        int nPrevHyphenationPosAlt = -1;
406
0
        int nPrevHyphenationPosAltHyph = -1;
407
0
        int nCompoundHyphenationPos = -1;
408
409
        // hyphenate the word with that dictionary
410
0
        rtl_TextEncoding eEnc = pHDInfo->eEnc;
411
0
        CharClass* pCC = pHDInfo->apCC.get();
412
413
        // Don't hyphenate uppercase words if requested
414
0
        if (bNoHyphenateCaps && aWord == makeUpperCase(aWord, pCC))
415
0
        {
416
0
            return nullptr;
417
0
        }
418
419
0
        CapType ct = capitalType(aWord, pCC);
420
421
0
        auto result = getHyphens(aWord, *pHDInfo, minLead, minTrail);
422
0
        if (result.failed)
423
0
            return nullptr;
424
425
0
        sal_Int32 Leading =  GetPosInWordToCheck( aWord, nMaxLeading );
426
427
        // use morphological analysis of Hunspell to get better hyphenation of compound words
428
        // optionally when hyphenation zone is enabled
429
        // pa: fields contain stems resulted by compound word analysis of non-dictionary words
430
        // hy: fields contain hyphenation data of dictionary (compound) words
431
0
        Reference< XSpellAlternatives > xTmpRes;
432
0
        bool bAnalyzed = false; // enough the analyse once the word
433
0
        bool bCompoundHyphenation = true; // try to hyphenate compound words better
434
0
        OUString sStems; // processed result of the compound word analysis, e.g. com|pound|word
435
0
        sal_Int32 nSuffixLen = 0; // do not remove break points in suffixes
436
437
0
        for (sal_Int32 i = 0; i < result.n; i++)
438
0
        {
439
0
            int leftrep = 0;
440
0
            bool hit = (result.n >= minLen);
441
0
            bool compoundhit = (result.n >= 1) && (result.hyphens[i] & 1);;
442
0
            bool bPrevCompound = false;
443
0
            if (!result.rep || !result.rep[i])
444
0
            {
445
0
                hit = hit && (result.hyphens[i] & 1) && (i < Leading);
446
0
                hit = hit && (i >= (minLead-1) );
447
0
                hit = hit && ((result.n - i - 1) >= minTrail);
448
0
            }
449
0
            else
450
0
            {
451
                // calculate change character length before hyphenation point signed with '='
452
0
                for (char * c = result.rep[i]; *c && (*c != '='); c++)
453
0
                {
454
0
                    if (eEnc == RTL_TEXTENCODING_UTF8)
455
0
                    {
456
0
                        if (static_cast<unsigned char>(*c) >> 6 != 2)
457
0
                            leftrep++;
458
0
                    }
459
0
                    else
460
0
                        leftrep++;
461
0
                }
462
0
                hit = hit && (result.hyphens[i] & 1) && ((i + leftrep - result.pos[i]) < Leading);
463
0
                hit = hit && ((i + leftrep - result.pos[i]) >= (minLead-1) );
464
0
                hit = hit && ((result.n - i - 1 + sal::static_int_cast< sal_sSize >(strlen(result.rep[i])) - leftrep - 1) >= minTrail);
465
0
            }
466
0
            if (hit || compoundhit)
467
0
            {
468
                // skip hyphenation inside compound constituents right after constituent boundaries in compound words
469
                // if minCompoundLead > 2 (default value: less than n=minCompoundLead character distance)
470
                // or always skip hyphenation inside compound constituents, if minCompoundLead == 0,
471
                // also skip hyphenation inside compound constituents right before constituent boundaries in compound words
472
                // or always skip hyphenation inside compound constituents, if minCompoundTrail == 0
473
                // if both minCompoundLead and minCompoundTrail == 0, don't hyphenate inside suffixes, too
474
0
                if ( bCompoundHyphenation && (nCompoundHyphenationPos > -1 || minCompoundLead == 0 || minCompoundTrail > 2 || minCompoundTrail == 0 ) &&
475
                        // check minimal distance from the left constituent boundary
476
0
                        ( ( minCompoundLead > 2 && i - nCompoundHyphenationPos < minCompoundLead ) ||
477
                        // check minimal distance from the right constituent boundary
478
0
                        ( minCompoundTrail > 2 && i - nCompoundHyphenationPos < minCompoundTrail ) ||
479
                        // special value: zero compound limit means forbidden hyphenation
480
                        // inside (stems of) compound constituents
481
0
                        minCompoundLead == 0 || minCompoundTrail == 0 ) )
482
0
                {
483
0
                    uno::Reference< XLinguServiceManager2 > xLngSvcMgr( GetLngSvcMgr_Impl() );
484
0
                    uno::Reference< XSpellChecker1 > xSpell;
485
486
0
                    LanguageType nLanguage = LinguLocaleToLanguage( aLocale );
487
488
0
                    xSpell.set( xLngSvcMgr->getSpellChecker(), UNO_QUERY );
489
490
                    // get morphological analysis of the word
491
0
                    if ( ( bAnalyzed && xTmpRes.is() ) || ( xSpell.is() && xSpell->isValid(
492
0
                            SPELLML_SUPPORT, static_cast<sal_uInt16>(nLanguage),
493
0
                            uno::Sequence< beans::PropertyValue >() ) ) )
494
0
                    {
495
0
                        if ( !bAnalyzed )
496
0
                        {
497
0
                            xTmpRes = xSpell->spell( "<?xml?><query type='analyze'><word>" +
498
0
                                                       aWord + "</word></query>",
499
0
                                               static_cast<sal_uInt16>(nLanguage),
500
0
                                               uno::Sequence< beans::PropertyValue >() );
501
0
                            bAnalyzed = true;
502
503
0
                            if (xTmpRes.is())
504
0
                            {
505
0
                                Sequence<OUString>seq = xTmpRes->getAlternatives();
506
0
                                if (seq.hasElements())
507
0
                                {
508
0
                                    sal_Int32 nEndOfFirstAnalysis = seq[0].indexOf("</a>");
509
                                    // FIXME use only the first analysis
510
0
                                    OUString morph(
511
0
                                            seq[0].copy(0, nEndOfFirstAnalysis));
512
513
                                    // concatenate pa: fields, i.e. stems in the analysis:
514
                                    // pa:stem1 pa:stem2 pa:stem3 -> stem1||stem2||stem3
515
0
                                    sal_Int32 nPa = -1;
516
0
                                    while ( (nPa = morph.indexOf(u" pa:", nPa + 1)) > -1 )
517
0
                                    {
518
                                        // use hy: field of the actual stem, if it exists
519
                                        // pa:stem1 hy:st|em1 pa:stem2 -> st|em1||stem2
520
0
                                        sal_Int32 nHy = morph.indexOf(u" hy:", nPa + 3);
521
0
                                        sal_Int32 nPa2 = morph.indexOf(u" pa:", nPa + 3);
522
523
0
                                        if ( nHy > -1 && ( nPa2 == -1 || nHy < nPa2 ) )
524
0
                                        {
525
0
                                            OUString sStems2(morph.getToken(1, ' ', nHy).copy(3));
526
0
                                            if ( sStems2.indexOf('|') > -1 )
527
0
                                                sStems += sStems2+ u"||";
528
0
                                            else if ( sal_Int32 nBreak = o3tl::toInt32(sStems2) )
529
0
                                            {
530
0
                                                OUString sPa(morph.getToken(1, ' ', nPa).copy(3));
531
0
                                                if ( nBreak < sPa.getLength() )
532
0
                                                    sStems += OUString::Concat(sPa.subView(0, nBreak)) + u"|" +
533
0
                                                           sPa.subView(nBreak);
534
0
                                            }
535
0
                                        }
536
0
                                        else
537
0
                                        {
538
0
                                            OUString sPa(morph.getToken(1, ' ', nPa).copy(3));
539
540
                                            // handle special case: missing pa: in morphological analysis
541
                                            // before in-word suffixes (German, Sweden etc. dictionaries)
542
                                            // (recognized by the single last pa:)
543
0
                                            if (sStems.isEmpty() && nPa2 == -1 && aWord.endsWith(sPa))
544
0
                                            {
545
0
                                                sStems = OUString::Concat(aWord.subView(0, aWord.getLength() -
546
0
                                                             sPa.getLength())) + u"||" +
547
0
                                                         aWord.subView(aWord.getLength() -
548
0
                                                             sPa.getLength());
549
0
                                                break;
550
0
                                            }
551
552
0
                                            sStems += sPa + "||";
553
554
                                            // count suffix length
555
0
                                            sal_Int32 nSt = morph.lastIndexOf(" st:");
556
0
                                            if ( nSt > -1 )
557
0
                                            {
558
0
                                                sal_Int32 nStemLen =
559
0
                                                    o3tl::getToken(morph, 1, ' ', nSt).length() - 3;
560
0
                                                if ( nStemLen < sPa.getLength() )
561
0
                                                    nSuffixLen = sPa.getLength() - nStemLen;
562
0
                                            }
563
0
                                        }
564
565
0
                                        if ( nPa == -1 ) // getToken() can modify nPa
566
0
                                            break;
567
0
                                    }
568
569
                                    // only hy:, but not pa:
570
0
                                    if ( sStems.isEmpty() )
571
0
                                    {
572
                                        // check hy: (pre-defined hyphenation)
573
0
                                        sal_Int32 nHy = morph.indexOf(" hy:");
574
0
                                        if (nHy > -1)
575
0
                                        {
576
0
                                            sStems = morph.getToken(1, ' ', nHy).copy(3);
577
0
                                            if ( sStems.indexOf('|') == -1 && sStems.indexOf('-') == -1 )
578
0
                                            {
579
0
                                                if ( sal_Int32 nBreak = o3tl::toInt32(sStems) )
580
0
                                                {
581
0
                                                    if ( nBreak < aWord.getLength() )
582
0
                                                        sStems += OUString::Concat(aWord.subView(0, nBreak)) + u"|" +
583
0
                                                               aWord.subView(nBreak);
584
0
                                                }
585
0
                                            }
586
0
                                        }
587
0
                                    }
588
0
                                }
589
0
                            }
590
0
                        }
591
592
                        // handle string separated by |, e.g "program hy:pro|gram"
593
0
                        if ( sStems.indexOf('|') > -1 )
594
0
                        {
595
0
                            sal_Int32 nLetters = 0; // count not separator characters
596
0
                            sal_Int32 nSepPos = -1; // position of last character | used for stem boundaries
597
0
                            sal_Int32 nSepLetterPos = -1; // letter position of the character associated to nSepPos
598
0
                            bool bWeightedSep = false; // double separator || = weighted stem boundary
599
0
                            sal_Int32 j = 0;
600
0
                            for (; j < sStems.getLength() && nLetters <= i; j++)
601
0
                            {
602
0
                                if ( sStems[j] == '|' )
603
0
                                {
604
0
                                    bWeightedSep = nSepPos > -1 && (j - 1 == nSepPos);
605
0
                                    nSepPos = j;
606
0
                                    nSepLetterPos = nLetters;
607
0
                                }
608
0
                                else if ( sStems[j] != '-' && sStems[j] != '=' && sStems[j] != '*' )
609
0
                                    ++nLetters;
610
0
                            }
611
                            // skip break points near after the stem boundaries
612
0
                            if ( hit &&
613
                                // too close to the left break point or special case?
614
0
                                ( i - nCompoundHyphenationPos < minCompoundLead || minCompoundLead == 0 ) &&
615
                                // there is a stem boundary before the actual break point
616
0
                                nSepPos > -1 &&
617
                                // and the break point is within a stem, i.e. not in the
618
                                // suffix of the last stem or both minCompoundLead and
619
                                // minCompoundTrail == 0, i.e. hyphenation is allowed only
620
                                // at compound constituent boundaries
621
0
                                ( i < aWord.getLength() - nSuffixLen - 1 ||
622
0
                                    ( minCompoundLead == 0 && minCompoundTrail == 0) ) &&
623
                                // and it is not another stem boundary
624
0
                                j + 1 < sStems.getLength() &&
625
0
                                ( sStems[j] != u'|' ||
626
                                // except if it's only the previous was a weighted one
627
0
                                    ( bWeightedSep && ( j + 1 == sStems.getLength() ||
628
0
                                                        sStems[j + 1] != u'|' ) ) ) )
629
0
                            {
630
0
                                continue;
631
0
                            }
632
                            // skip break points near before the stem boundaries
633
                            // (hit is not mandatory, only compondhit, because the
634
                            // compound boundary can be after the lead limit)
635
0
                            if (!hit &&
636
                                // too close to the right break point?
637
0
                                ( i - nCompoundHyphenationPos < minCompoundTrail || minCompoundTrail == 0 ) &&
638
                                // and the break point is within a stem, i.e. not in the
639
                                // suffix of the last stem suffix or both minCompoundLead and
640
                                // minCompoundTrail == 0, i.e. hyphenation is allowed only
641
                                // at compound constituent boundaries
642
0
                                ( i < aWord.getLength() - nSuffixLen - 1 ||
643
0
                                    ( minCompoundLead == 0 && minCompoundTrail == 0) ) &&
644
                                // and it is a stem boundary
645
0
                                j + 1 < sStems.getLength() && sStems[j+1] == u'|' &&
646
                                // the previous break point is not a boundary
647
0
                                (nSepPos == -1 || nCompoundHyphenationPos != nSepLetterPos - 1 ) )
648
0
                            {
649
0
                                nHyphenationPos = nPrevHyphenationPos;
650
0
                                nHyphenationPosAlt = nPrevHyphenationPosAlt;
651
0
                                nHyphenationPosAltHyph = nPrevHyphenationPosAltHyph;
652
0
                                continue;
653
0
                            }
654
0
                            bPrevCompound = nSepPos == j || nSepPos == j - 1;
655
0
                        }
656
0
                        else
657
                            // not a compound word
658
0
                            bCompoundHyphenation = false;
659
0
                    }
660
0
                    else
661
                        // no SPELLML support, no morphological analysis
662
0
                        bCompoundHyphenation = false;
663
0
                }
664
665
0
                nCompoundHyphenationPos = i;
666
0
                if (hit)
667
0
                {
668
0
                    if ( bPrevCompound )
669
0
                        nPrevHyphenationPos = nHyphenationPos;
670
0
                    nHyphenationPos = i;
671
0
                }
672
0
                if (result.rep && result.rep[i])
673
0
                {
674
0
                    if ( bPrevCompound )
675
0
                    {
676
0
                        nPrevHyphenationPosAlt = nHyphenationPosAlt;
677
0
                        nPrevHyphenationPosAltHyph = nHyphenationPosAltHyph;
678
0
                    }
679
0
                    nHyphenationPosAlt = i - result.pos[i];
680
0
                    nHyphenationPosAltHyph = i + leftrep - result.pos[i];
681
0
                }
682
0
            }
683
0
        }
684
685
0
        Reference<XHyphenatedWord> xRes;
686
0
        if (nHyphenationPos != -1)
687
0
        {
688
0
            if (result.rep && result.rep[nHyphenationPos])
689
0
            {
690
                // remove equal sign
691
0
                char * s = result.rep[nHyphenationPos];
692
0
                int eq = 0;
693
0
                for (; *s; s++)
694
0
                {
695
0
                    if (*s == '=') eq = 1;
696
0
                    if (eq) *s = *(s + 1);
697
0
                }
698
0
                OUString repHyphlow(result.rep[nHyphenationPos], strlen(result.rep[nHyphenationPos]), eEnc);
699
0
                OUString repHyph;
700
0
                switch (ct)
701
0
                {
702
0
                    case CapType::ALLCAP:
703
0
                    {
704
0
                        repHyph = makeUpperCase(repHyphlow, pCC);
705
0
                        break;
706
0
                    }
707
0
                    case CapType::INITCAP:
708
0
                    {
709
0
                        if (nHyphenationPosAlt == -1)
710
0
                            repHyph = makeInitCap(repHyphlow, pCC);
711
0
                        else
712
0
                             repHyph = repHyphlow;
713
0
                        break;
714
0
                    }
715
0
                    default:
716
0
                    {
717
0
                        repHyph = repHyphlow;
718
0
                        break;
719
0
                    }
720
0
                }
721
722
                // handle shortening
723
0
                sal_Int16 nPos = static_cast<sal_Int16>((nHyphenationPosAltHyph < nHyphenationPos) ?
724
0
                nHyphenationPosAltHyph : nHyphenationPos);
725
                // discretionary hyphenation
726
0
                xRes = HyphenatedWord::CreateHyphenatedWord( aWord, LinguLocaleToLanguage( aLocale ), nPos,
727
0
                    aWord.replaceAt(nHyphenationPosAlt + 1, result.cut[nHyphenationPos], repHyph),
728
0
                    static_cast<sal_Int16>(nHyphenationPosAltHyph));
729
0
            }
730
0
            else
731
0
            {
732
0
                xRes = HyphenatedWord::CreateHyphenatedWord( aWord, LinguLocaleToLanguage( aLocale ),
733
0
                    static_cast<sal_Int16>(nHyphenationPos), aWord, static_cast<sal_Int16>(nHyphenationPos));
734
0
            }
735
0
        }
736
0
        return xRes;
737
0
    }
738
0
    return nullptr;
739
0
}
740
741
Reference < XHyphenatedWord > SAL_CALL Hyphenator::queryAlternativeSpelling(
742
        const OUString& aWord,
743
        const css::lang::Locale& aLocale,
744
        sal_Int16 nIndex,
745
        const css::uno::Sequence< css::beans::PropertyValue >& aProperties )
746
0
{
747
    // Firstly we allow only one plus character before the hyphen to avoid to miss the right break point:
748
0
    for (int extrachar = 1; extrachar <= 2; extrachar++)
749
0
    {
750
0
        Reference< XHyphenatedWord > xRes = hyphenate(aWord, aLocale, nIndex + 1 + extrachar, aProperties);
751
0
        if (xRes.is() && xRes->isAlternativeSpelling() && xRes->getHyphenationPos() == nIndex)
752
0
            return xRes;
753
0
    }
754
0
    return nullptr;
755
0
}
756
757
Reference< XPossibleHyphens > SAL_CALL Hyphenator::createPossibleHyphens( const OUString& aWord,
758
        const css::lang::Locale& aLocale,
759
        const css::uno::Sequence< css::beans::PropertyValue >& aProperties )
760
0
{
761
0
    PropertyHelper_Hyphenation& rHelper = GetPropHelper();
762
0
    rHelper.SetTmpPropVals(aProperties);
763
0
    sal_Int16 minTrail = rHelper.GetMinTrailing();
764
0
    sal_Int16 minLead = rHelper.GetMinLeading();
765
0
    sal_Int16 minLen = rHelper.GetMinWordLength();
766
767
    // Resolves: fdo#41083 honour MinWordLength in "createPossibleHyphens" as
768
    // well as "hyphenate"
769
0
    if (aWord.getLength() < minLen)
770
0
        return nullptr;
771
772
    // if we have a hyphenation dictionary matching this locale
773
0
    if (auto pHDInfo = getMatchingDict(aLocale))
774
0
    {
775
        // hyphenate the word with that dictionary
776
0
        auto result = getHyphens(aWord, *pHDInfo, minLead, minTrail);
777
0
        if (result.failed)
778
0
            return nullptr;
779
780
0
        sal_Int32 nHyphCount = 0;
781
782
        // FIXME: shouldn't we iterate code points instead?
783
0
        for (sal_Int32 i = 0; i < aWord.getLength(); i++)
784
0
        {
785
0
            if (result.hyphens[i] & 1)
786
0
                nHyphCount++;
787
0
        }
788
789
0
        Sequence< sal_Int16 > aHyphPos(nHyphCount);
790
0
        sal_Int16 *pPos = aHyphPos.getArray();
791
0
        OUStringBuffer hyphenatedWordBuffer;
792
0
        nHyphCount = 0;
793
794
0
        for (sal_Int32 i = 0; i < aWord.getLength(); i++)
795
0
        {
796
0
            hyphenatedWordBuffer.append(aWord[i]);
797
            // hyphenation position
798
0
            if (result.hyphens[i] & 1)
799
0
            {
800
                // linguistic::PossibleHyphens is stuck with
801
                // css::uno::Sequence<sal_Int16> because of
802
                // css.linguistic2.XPossibleHyphens.getHyphenationPositions, so
803
                // any further positions need to be ignored:
804
0
                assert(i >= SAL_MIN_INT16);
805
0
                if (i > SAL_MAX_INT16)
806
0
                {
807
0
                    SAL_WARN(
808
0
                        "lingucomponent",
809
0
                        "hyphen pos " << i << " > SAL_MAX_INT16 in \"" << aWord
810
0
                            << "\"");
811
0
                    continue;
812
0
                }
813
0
                pPos[nHyphCount] = i;
814
0
                hyphenatedWordBuffer.append('=');
815
0
                nHyphCount++;
816
0
            }
817
0
        }
818
819
0
        OUString hyphenatedWord = hyphenatedWordBuffer.makeStringAndClear();
820
821
0
        return PossibleHyphens::CreatePossibleHyphens(
822
0
            aWord, LinguLocaleToLanguage( aLocale ), hyphenatedWord, aHyphPos);
823
0
    }
824
825
0
    return nullptr;
826
0
}
827
828
sal_Bool SAL_CALL Hyphenator::addLinguServiceEventListener(
829
        const Reference< XLinguServiceEventListener >& rxLstnr )
830
0
{
831
0
    MutexGuard  aGuard( GetLinguMutex() );
832
833
0
    bool bRes = false;
834
0
    if (!bDisposing && rxLstnr.is())
835
0
    {
836
0
        bRes = GetPropHelper().addLinguServiceEventListener( rxLstnr );
837
0
    }
838
0
    return bRes;
839
0
}
840
841
sal_Bool SAL_CALL Hyphenator::removeLinguServiceEventListener(
842
        const Reference< XLinguServiceEventListener >& rxLstnr )
843
0
{
844
0
    MutexGuard  aGuard( GetLinguMutex() );
845
846
0
    bool bRes = false;
847
0
    if (!bDisposing && rxLstnr.is())
848
0
    {
849
0
        bRes = GetPropHelper().removeLinguServiceEventListener( rxLstnr );
850
0
    }
851
0
    return bRes;
852
0
}
853
854
OUString SAL_CALL Hyphenator::getServiceDisplayName(const Locale& rLocale)
855
0
{
856
0
    std::locale loc(Translate::Create("svt", LanguageTag(rLocale)));
857
0
    return Translate::get(STR_DESCRIPTION_LIBHYPHEN, loc);
858
0
}
859
860
void SAL_CALL Hyphenator::initialize( const Sequence< Any >& rArguments )
861
0
{
862
0
    MutexGuard  aGuard( GetLinguMutex() );
863
864
0
    if (pPropHelper)
865
0
        return;
866
867
0
    sal_Int32 nLen = rArguments.getLength();
868
0
    if (2 == nLen)
869
0
    {
870
0
        Reference< XLinguProperties >   xPropSet;
871
0
        rArguments[0] >>= xPropSet;
872
        // rArguments[1] >>= xDicList;
873
874
        //! Pointer allows for access of the non-UNO functions.
875
        //! And the reference to the UNO-functions while increasing
876
        //! the ref-count and will implicitly free the memory
877
        //! when the object is no longer used.
878
0
        pPropHelper.reset( new PropertyHelper_Hyphenation( static_cast<XHyphenator *>(this), xPropSet ) );
879
0
        pPropHelper->AddAsPropListener();   //! after a reference is established
880
0
    }
881
0
    else {
882
0
        OSL_FAIL( "wrong number of arguments in sequence" );
883
0
    }
884
0
}
885
886
void SAL_CALL Hyphenator::dispose()
887
0
{
888
0
    MutexGuard  aGuard( GetLinguMutex() );
889
890
0
    if (!bDisposing)
891
0
    {
892
0
        bDisposing = true;
893
0
        EventObject aEvtObj( static_cast<XHyphenator *>(this) );
894
0
        aEvtListeners.disposeAndClear( aEvtObj );
895
0
        if (pPropHelper)
896
0
        {
897
0
            pPropHelper->RemoveAsPropListener();
898
0
            pPropHelper.reset();
899
0
        }
900
0
    }
901
0
}
902
903
void SAL_CALL Hyphenator::addEventListener( const Reference< XEventListener >& rxListener )
904
0
{
905
0
    MutexGuard  aGuard( GetLinguMutex() );
906
907
0
    if (!bDisposing && rxListener.is())
908
0
        aEvtListeners.addInterface( rxListener );
909
0
}
910
911
void SAL_CALL Hyphenator::removeEventListener( const Reference< XEventListener >& rxListener )
912
0
{
913
0
    MutexGuard  aGuard( GetLinguMutex() );
914
915
0
    if (!bDisposing && rxListener.is())
916
0
        aEvtListeners.removeInterface( rxListener );
917
0
}
918
919
// Service specific part
920
OUString SAL_CALL Hyphenator::getImplementationName()
921
0
{
922
0
    return u"org.openoffice.lingu.LibHnjHyphenator"_ustr;
923
0
}
924
925
sal_Bool SAL_CALL Hyphenator::supportsService( const OUString& ServiceName )
926
0
{
927
0
    return cppu::supportsService(this, ServiceName);
928
0
}
929
930
Sequence< OUString > SAL_CALL Hyphenator::getSupportedServiceNames()
931
0
{
932
0
    return { SN_HYPHENATOR };
933
0
}
934
935
extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
936
lingucomponent_Hyphenator_get_implementation(
937
    css::uno::XComponentContext* , css::uno::Sequence<css::uno::Any> const&)
938
0
{
939
0
    return cppu::acquire(new Hyphenator());
940
0
}
941
942
943
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */