summaryrefslogtreecommitdiffstats
path: root/unotools/source/i18n/textsearch.cxx
blob: f61aeaf1a2a71cc419b5cf4560f369fb43d211bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <sal/config.h>

#include <cstdlib>
#include <string_view>

#include <i18nlangtag/languagetag.hxx>
#include <i18nutil/searchopt.hxx>
#include <i18nutil/transliteration.hxx>
#include <com/sun/star/util/TextSearch2.hpp>
#include <com/sun/star/util/SearchAlgorithms2.hpp>
#include <com/sun/star/util/SearchFlags.hpp>
#include <unotools/charclass.hxx>
#include <comphelper/processfactory.hxx>
#include <unotools/textsearch.hxx>
#include <rtl/ustrbuf.hxx>
#include <comphelper/diagnose_ex.hxx>
#include <mutex>

using namespace ::com::sun::star::util;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

namespace utl
{

SearchParam::SearchParam( const OUString &rText,
                                SearchType eType,
                                bool bCaseSensitive,
                                sal_uInt32 cWildEscChar,
                                bool bWildMatchSel )
{
    sSrchStr        = rText;
    m_eSrchType     = eType;

    m_cWildEscChar  = cWildEscChar;

    m_bCaseSense    = bCaseSensitive;
    m_bWildMatchSel = bWildMatchSel;
}

SearchParam::SearchParam( const SearchParam& rParam )
{
    sSrchStr        = rParam.sSrchStr;
    m_eSrchType     = rParam.m_eSrchType;

    m_cWildEscChar  = rParam.m_cWildEscChar;

    m_bCaseSense    = rParam.m_bCaseSense;
    m_bWildMatchSel = rParam.m_bWildMatchSel;
}

SearchParam::~SearchParam() {}

static bool lcl_Equals( const i18nutil::SearchOptions2& rSO1, const i18nutil::SearchOptions2& rSO2 )
{
    return
        rSO1.AlgorithmType2 == rSO2.AlgorithmType2 &&
        rSO1.WildcardEscapeCharacter == rSO2.WildcardEscapeCharacter &&
        rSO1.searchFlag == rSO2.searchFlag &&
        rSO1.searchString == rSO2.searchString &&
        rSO1.replaceString == rSO2.replaceString &&
        rSO1.changedChars == rSO2.changedChars &&
        rSO1.deletedChars == rSO2.deletedChars &&
        rSO1.insertedChars == rSO2.insertedChars &&
        rSO1.Locale.Language == rSO2.Locale.Language &&
        rSO1.Locale.Country == rSO2.Locale.Country &&
        rSO1.Locale.Variant == rSO2.Locale.Variant &&
        rSO1.transliterateFlags == rSO2.transliterateFlags;
}

namespace
{
    struct CachedTextSearch
    {
        std::mutex mutex;
        i18nutil::SearchOptions2 Options;
        css::uno::Reference< css::util::XTextSearch2 > xTextSearch;
    };
}

Reference<XTextSearch2> TextSearch::getXTextSearch( const i18nutil::SearchOptions2& rPara )
{
    static CachedTextSearch theCachedTextSearch;

    std::scoped_lock aGuard(theCachedTextSearch.mutex);

    if ( lcl_Equals(theCachedTextSearch.Options, rPara) )
        return theCachedTextSearch.xTextSearch;

    Reference< XComponentContext > xContext = ::comphelper::getProcessComponentContext();
    theCachedTextSearch.xTextSearch.set( ::TextSearch2::create(xContext) );
    theCachedTextSearch.xTextSearch->setOptions2( rPara.toUnoSearchOptions2() );
    theCachedTextSearch.Options = rPara;

    return theCachedTextSearch.xTextSearch;
}

TextSearch::TextSearch(const SearchParam & rParam, LanguageType eLang )
{
    if( LANGUAGE_NONE == eLang )
        eLang = LANGUAGE_SYSTEM;
    css::lang::Locale aLocale( LanguageTag::convertToLocale( eLang ) );

    Init( rParam, aLocale);
}

TextSearch::TextSearch(const SearchParam & rParam, const CharClass& rCClass )
{
    Init( rParam, rCClass.getLanguageTag().getLocale() );
}

TextSearch::TextSearch( const i18nutil::SearchOptions2& rPara )
{
    xTextSearch = getXTextSearch( rPara );
}

void TextSearch::Init( const SearchParam & rParam,
                        const css::lang::Locale& rLocale )
{
    // convert SearchParam to the UNO SearchOptions2
    i18nutil::SearchOptions2 aSOpt;

    switch( rParam.GetSrchType() )
    {
    case SearchParam::SearchType::Wildcard:
        aSOpt.AlgorithmType2 = SearchAlgorithms2::WILDCARD;
        aSOpt.WildcardEscapeCharacter = rParam.GetWildEscChar();
        if (rParam.IsWildMatchSel())
            aSOpt.searchFlag |= SearchFlags::WILD_MATCH_SELECTION;
        break;

    case SearchParam::SearchType::Regexp:
        aSOpt.AlgorithmType2 = SearchAlgorithms2::REGEXP;
        break;

    case SearchParam::SearchType::Normal:
        aSOpt.AlgorithmType2 = SearchAlgorithms2::ABSOLUTE;
        break;

    default:
        for (;;) std::abort();
    }
    aSOpt.searchString = rParam.GetSrchStr();
    aSOpt.replaceString = "";
    aSOpt.Locale = rLocale;
    aSOpt.transliterateFlags = TransliterationFlags::NONE;
    if( !rParam.IsCaseSensitive() )
    {
        aSOpt.searchFlag |= SearchFlags::ALL_IGNORE_CASE;
        aSOpt.transliterateFlags |= TransliterationFlags::IGNORE_CASE;
    }

    xTextSearch = getXTextSearch( aSOpt );
}

void TextSearch::SetLocale( const i18nutil::SearchOptions2& rOptions,
                            const css::lang::Locale& rLocale )
{
    i18nutil::SearchOptions2 aSOpt( rOptions );
    aSOpt.Locale = rLocale;

    xTextSearch = getXTextSearch( aSOpt );
}

TextSearch::~TextSearch()
{
}

/*
 * General search methods. These methods will call the respective
 * methods, such as ordinary string searching or regular expression
 * matching, using the method pointer.
 */
bool TextSearch::SearchForward( const OUString &rStr,
                    sal_Int32* pStart, sal_Int32* pEnd,
                    css::util::SearchResult* pRes)
{
    bool bRet = false;
    try
    {
        if( xTextSearch.is() )
        {
            SearchResult aRet( xTextSearch->searchForward( rStr, *pStart, *pEnd ));
            if( aRet.subRegExpressions > 0 )
            {
                bRet = true;
                // the XTextsearch returns in startOffset the higher position
                // and the endposition is always exclusive.
                // The caller of this function will have in startPos the
                // lower pos. and end
                *pStart = aRet.startOffset[ 0 ];
                *pEnd = aRet.endOffset[ 0 ];
                if( pRes )
                    *pRes = aRet;
            }
        }
    }
    catch ( Exception& )
    {
        TOOLS_WARN_EXCEPTION("unotools.i18n", "" );
    }
    return bRet;
}

bool TextSearch::searchForward( const OUString &rStr )
{
    sal_Int32 pStart = 0;
    sal_Int32 pEnd = rStr.getLength();

    bool bResult = SearchForward(rStr, &pStart, &pEnd);

    return bResult;
}

bool TextSearch::SearchBackward( const OUString & rStr, sal_Int32* pStart,
                                sal_Int32* pEnd, SearchResult* pRes )
{
    bool bRet = false;
    try
    {
        if( xTextSearch.is() )
        {
            SearchResult aRet( xTextSearch->searchBackward( rStr, *pStart, *pEnd ));
            if( aRet.subRegExpressions )
            {
                bRet = true;
                // the XTextsearch returns in startOffset the higher position
                // and the endposition is always exclusive.
                // The caller of this function will have in startPos the
                // lower pos. and end
                *pEnd = aRet.startOffset[ 0 ];
                *pStart = aRet.endOffset[ 0 ];
                if( pRes )
                    *pRes = aRet;
            }
        }
    }
    catch ( Exception& )
    {
        TOOLS_WARN_EXCEPTION("unotools.i18n", "" );
    }
    return bRet;
}

void TextSearch::ReplaceBackReferences( OUString& rReplaceStr, std::u16string_view rStr, const SearchResult& rResult ) const
{
    if( rResult.subRegExpressions <= 0 )
        return;

    sal_Unicode sFndChar;
    sal_Int32 i;
    OUStringBuffer sBuff(rReplaceStr.getLength()*4);
    for(i = 0; i < rReplaceStr.getLength(); i++)
    {
        if( rReplaceStr[i] == '&')
        {
            sal_Int32 nStart = rResult.startOffset[0];
            sal_Int32 nLength = rResult.endOffset[0] - rResult.startOffset[0];
            sBuff.append(rStr.substr(nStart, nLength));
        }
        else if((i < rReplaceStr.getLength() - 1) && rReplaceStr[i] == '$')
        {
            sFndChar = rReplaceStr[ i + 1 ];
            switch(sFndChar)
            {   // placeholder for a backward reference?
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                {
                    int j = sFndChar - '0'; // index
                    if(j < rResult.subRegExpressions)
                    {
                        sal_Int32 nSttReg = rResult.startOffset[j];
                        sal_Int32 nRegLen = rResult.endOffset[j];
                        if (nSttReg < 0 || nRegLen < 0) // A "not found" optional capture
                        {
                            nSttReg = nRegLen = 0; // Copy empty string
                        }
                        else if (nRegLen >= nSttReg)
                        {
                            nRegLen = nRegLen - nSttReg;
                        }
                        else
                        {
                            nRegLen = nSttReg - nRegLen;
                            nSttReg = rResult.endOffset[j];
                        }
                        // Copy reference from found string
                        sBuff.append(rStr.substr(nSttReg, nRegLen));
                    }
                    i += 1;
                }
                break;
            default:
                sBuff.append(OUStringChar(rReplaceStr[i]) + OUStringChar(rReplaceStr[i+1]));
                i += 1;
                break;
            }
        }
        else if((i < rReplaceStr.getLength() - 1) && rReplaceStr[i] == '\\')
        {
            sFndChar = rReplaceStr[ i+1 ];
            switch(sFndChar)
            {
            case '\\':
            case '&':
            case '$':
                sBuff.append(sFndChar);
                i+=1;
                break;
            case 't':
                sBuff.append('\t');
                i += 1;
                break;
            default:
                sBuff.append(OUStringChar(rReplaceStr[i]) + OUStringChar(rReplaceStr[i+1]));
                i += 1;
                break;
            }
        }
        else
        {
            sBuff.append(rReplaceStr[i]);
        }
    }
    rReplaceStr = sBuff.makeStringAndClear();
}

}   // namespace utl

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */