1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
3 * This file is part of the LibreOffice project.
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/.
9 * This file incorporates work covered by the following license notice:
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 .
20 #include <com/sun/star/uno/Reference.h>
22 #include <com/sun/star/linguistic2/SpellFailure.hpp>
23 #include <com/sun/star/linguistic2/XLinguProperties.hpp>
24 #include <cppuhelper/factory.hxx>
25 #include <cppuhelper/supportsservice.hxx>
26 #include <cppuhelper/weak.hxx>
27 #include <com/sun/star/registry/XRegistryKey.hpp>
28 #include <com/sun/star/lang/XSingleServiceFactory.hpp>
29 #include <tools/debug.hxx>
30 #include <osl/mutex.hxx>
32 #include "macspellimp.hxx"
34 #include <linguistic/spelldta.hxx>
35 #include <unotools/pathoptions.hxx>
36 #include <unotools/useroptions.hxx>
37 #include <osl/file.hxx>
38 #include <rtl/ref.hxx>
39 #include <rtl/ustrbuf.hxx>
43 using namespace com::sun::star;
44 using namespace com::sun::star::beans;
45 using namespace com::sun::star::lang;
46 using namespace com::sun::star::uno;
47 using namespace com::sun::star::linguistic2;
48 using namespace linguistic;
50 MacSpellChecker::MacSpellChecker() :
51 aEvtListeners( GetLinguMutex() )
60 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
61 macTag = [NSSpellChecker uniqueSpellDocumentTag];
64 pChecker = [[UITextChecker alloc] init];
69 MacSpellChecker::~MacSpellChecker()
72 if (aDEncs) delete[] aDEncs;
74 if (aDLocs) delete[] aDLocs;
76 if (aDNames) delete[] aDNames;
79 xPropHelper->RemoveAsPropListener();
83 PropertyHelper_Spell & MacSpellChecker::GetPropHelper_Impl()
85 if (!xPropHelper.is())
87 Reference< XLinguProperties > xPropSet( GetLinguProperties() );
89 xPropHelper = new PropertyHelper_Spell( static_cast<XSpellChecker *>(this), xPropSet );
90 xPropHelper->AddAsPropListener();
96 Sequence< Locale > SAL_CALL MacSpellChecker::getLocales()
98 MutexGuard aGuard( GetLinguMutex() );
100 // this routine should return the locales supported by the installed
101 // dictionaries. So here we need to parse both the user edited
102 // dictionary list and the shared dictionary list
103 // to see what dictionaries the admin/user has installed
105 int numshr; // number of shared dictionary entries
106 rtl_TextEncoding aEnc = RTL_TEXTENCODING_UTF8;
108 std::vector<NSString *> postspdict;
112 // invoke a dictionary manager to get the user dictionary list
113 // TODO How on macOS?
115 // invoke a second dictionary manager to get the shared dictionary list
117 NSArray *aSpellCheckLanguages = [[NSSpellChecker sharedSpellChecker] availableLanguages];
119 NSArray *aSpellCheckLanguages = [UITextChecker availableLanguages];
122 for (NSUInteger i = 0; i < [aSpellCheckLanguages count]; i++)
124 NSString* pLangStr = static_cast<NSString*>([aSpellCheckLanguages objectAtIndex:i]);
126 // Fix up generic languages (without territory code) and odd combinations that LO
128 if ([pLangStr isEqualToString:@"da"])
130 postspdict.push_back( @"da_DK" );
132 else if ([pLangStr isEqualToString:@"de"])
134 // Not de_CH and de_LI, though. They need separate dictionaries.
135 const std::vector<NSString*> aDE
136 { @"AT", @"BE", @"DE", @"LU" };
139 pLangStr = [@"de_" stringByAppendingString: c];
140 postspdict.push_back( pLangStr );
144 // iOS says it has specifically de_DE. Let's assume it is good enough for German as
145 // written in Austria, Belgium, and Luxembourg, too. (Not for German in Switzerland and
146 // Liechtenstein. For those you need to bundle the myspell dictionary.)
147 else if ([pLangStr isEqualToString:@"de_DE"])
149 const std::vector<NSString*> aDE
150 { @"AT", @"BE", @"DE", @"LU" };
153 pLangStr = [@"de_" stringByAppendingString: c];
154 postspdict.push_back( pLangStr );
158 else if ([pLangStr isEqualToString:@"en"])
160 // System has en_AU, en_CA, en_GB, and en_IN. Add the rest.
161 const std::vector<NSString*> aEN
162 { @"BW", @"BZ", @"GH", @"GM", @"IE", @"JM", @"MU", @"MW", @"MY", @"NA",
163 @"NZ", @"PH", @"TT", @"US", @"ZA", @"ZW" };
166 pLangStr = [@"en_" stringByAppendingString: c];
167 postspdict.push_back( pLangStr );
170 else if ([pLangStr isEqualToString:@"en_JP"]
171 || [pLangStr isEqualToString:@"en_SG"])
173 // Just skip, LO doesn't have those yet in this context.
175 else if ([pLangStr isEqualToString:@"es"])
177 const std::vector<NSString*> aES
178 { @"AR", @"BO", @"CL", @"CO", @"CR", @"CU", @"DO", @"EC", @"ES", @"GT",
179 @"HN", @"MX", @"NI", @"PA", @"PE", @"PR", @"PY", @"SV", @"UY", @"VE" };
182 pLangStr = [@"es_" stringByAppendingString: c];
183 postspdict.push_back( pLangStr );
186 else if ([pLangStr isEqualToString:@"fi"])
188 postspdict.push_back( @"fi_FI" );
190 else if ([pLangStr isEqualToString:@"fr"])
192 const std::vector<NSString*> aFR
193 { @"BE", @"BF", @"BJ", @"CA", @"CH", @"CI", @"FR", @"LU", @"MC", @"ML",
194 @"MU", @"NE", @"SN", @"TG" };
197 pLangStr = [@"fr_" stringByAppendingString: c];
198 postspdict.push_back( pLangStr );
202 else if ([pLangStr isEqualToString:@"fr_FR"])
204 const std::vector<NSString*> aFR
205 { @"BE", @"BF", @"BJ", @"CA", @"CH", @"CI", @"FR", @"LU", @"MC", @"ML",
206 @"MU", @"NE", @"SN", @"TG" };
209 pLangStr = [@"fr_" stringByAppendingString: c];
210 postspdict.push_back( pLangStr );
214 else if ([pLangStr isEqualToString:@"it"])
216 postspdict.push_back( @"it_CH" );
217 postspdict.push_back( @"it_IT" );
220 else if ([pLangStr isEqualToString:@"it_IT"])
222 const std::vector<NSString*> aIT
226 pLangStr = [@"it_" stringByAppendingString: c];
227 postspdict.push_back( pLangStr );
231 else if ([pLangStr isEqualToString:@"ko"])
233 postspdict.push_back( @"ko_KR" );
235 else if ([pLangStr isEqualToString:@"nl"])
237 postspdict.push_back( @"nl_BE" );
238 postspdict.push_back( @"nl_NL" );
240 else if ([pLangStr isEqualToString:@"nb"])
242 postspdict.push_back( @"nb_NO" );
244 else if ([pLangStr isEqualToString:@"pl"])
246 postspdict.push_back( @"pl_PL" );
248 else if ([pLangStr isEqualToString:@"ru"])
250 postspdict.push_back( @"ru_RU" );
252 else if ([pLangStr isEqualToString:@"sv"])
254 postspdict.push_back( @"sv_FI" );
255 postspdict.push_back( @"sv_SE" );
258 else if ([pLangStr isEqualToString:@"sv_SE"])
260 postspdict.push_back( @"sv_FI" );
261 postspdict.push_back( @"sv_SE" );
264 else if ([pLangStr isEqualToString:@"tr"])
266 postspdict.push_back( @"tr_TR" );
269 postspdict.push_back( pLangStr );
271 // System has pt_BR and pt_PT, add pt_AO.
272 postspdict.push_back( @"pt_AO" );
274 numshr = postspdict.size();
276 // we really should merge these and remove duplicates but since
277 // users can name their dictionaries anything they want it would
278 // be impossible to know if a real duplication exists unless we
279 // add some unique key to each myspell dictionary
283 aDLocs = new Locale [numdict];
284 aDEncs = new rtl_TextEncoding [numdict];
285 aDNames = new OUString [numdict];
286 aSuppLocales.realloc(numdict);
287 Locale * pLocale = aSuppLocales.getArray();
293 //first add the user dictionaries
296 // now add the shared dictionaries
297 for (i = 0; i < numshr; i++) {
298 NSDictionary *aLocDict = [ NSLocale componentsFromLocaleIdentifier:postspdict[i] ];
299 NSString* aLang = [ aLocDict objectForKey:NSLocaleLanguageCode ];
300 NSString* aCountry = [ aLocDict objectForKey:NSLocaleCountryCode ];
301 OUString lang([aLang cStringUsingEncoding: NSUTF8StringEncoding], [aLang length], aEnc);
302 OUString country([ aCountry cStringUsingEncoding: NSUTF8StringEncoding], [aCountry length], aEnc);
303 Locale nLoc( lang, country, OUString() );
305 //eliminate duplicates (is this needed for MacOS?)
306 for (j = 0; j < numlocs; j++) {
307 if (nLoc == pLocale[j]) newloc = 0;
310 pLocale[numlocs] = nLoc;
318 aSuppLocales.realloc(numlocs);
321 /* no dictionary.lst found so register no dictionaries */
326 aSuppLocales.realloc(0);
335 sal_Bool SAL_CALL MacSpellChecker::hasLocale(const Locale& rLocale)
337 MutexGuard aGuard( GetLinguMutex() );
340 if (!aSuppLocales.getLength())
343 sal_Int32 nLen = aSuppLocales.getLength();
344 for (sal_Int32 i = 0; i < nLen; ++i)
346 const Locale *pLocale = aSuppLocales.getConstArray();
347 if (rLocale == pLocale[i])
357 sal_Int16 MacSpellChecker::GetSpellFailure( const OUString &rWord, const Locale &rLocale )
359 // initialize a myspell object for each dictionary once
360 // (note: mutex is held higher up in isValid)
365 // first handle smart quotes both single and double
366 OUStringBuffer rBuf(rWord);
367 sal_Int32 n = rBuf.getLength();
369 for (sal_Int32 ix=0; ix < n; ix++) {
371 if ((c == 0x201C) || (c == 0x201D)) rBuf[ix] = u'"';
372 if ((c == 0x2018) || (c == 0x2019)) rBuf[ix] = u'\'';
374 OUString nWord(rBuf.makeStringAndClear());
378 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
379 NSString* aNSStr = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(nWord.getStr()) length: nWord.getLength()]autorelease];
380 NSString* aLang = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Language.getStr()) length: rLocale.Language.getLength()]autorelease];
381 if(rLocale.Country.getLength()>0)
383 NSString* aCountry = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Country.getStr()) length: rLocale.Country.getLength()]autorelease];
384 NSString* aTaggedCountry = [@"_" stringByAppendingString:aCountry];
385 aLang = [aLang stringByAppendingString:aTaggedCountry];
390 NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:aNSStr startingAt:0 language:aLang wrap:false inSpellDocumentWithTag:macTag wordCount:&aCount];
392 NSRange range = [pChecker rangeOfMisspelledWordInString:aNSStr range:NSMakeRange(0, [aNSStr length]) startingAt:0 wrap:NO language:aLang];
406 nRes = SpellFailure::SPELLING_ERROR;
417 MacSpellChecker::isValid( const OUString& rWord, const Locale& rLocale,
418 const css::uno::Sequence<PropertyValue>& rProperties )
420 MutexGuard aGuard( GetLinguMutex() );
422 if (rLocale == Locale() || !rWord.getLength())
425 if (!hasLocale( rLocale ))
428 // Get property values to be used.
429 // These are be the default values set in the SN_LINGU_PROPERTIES
430 // PropertySet which are overridden by the supplied ones from the
432 // You'll probably like to use a simpler solution than the provided
433 // one using the PropertyHelper_Spell.
435 PropertyHelper_Spell &rHelper = GetPropHelper();
436 rHelper.SetTmpPropVals( rProperties );
438 sal_Int16 nFailure = GetSpellFailure( rWord, rLocale );
441 LanguageType nLang = LinguLocaleToLanguage( rLocale );
442 // postprocess result for errors that should be ignored
443 if ( (!rHelper.IsSpellUpperCase() && IsUpper( rWord, nLang ))
444 || (!rHelper.IsSpellWithDigits() && HasDigits( rWord ))
445 || (!rHelper.IsSpellCapitalization()
446 && nFailure == SpellFailure::CAPTION_ERROR)
451 return (nFailure == -1);
454 Reference< XSpellAlternatives >
455 MacSpellChecker::GetProposals( const OUString &rWord, const Locale &rLocale )
457 // Retrieves the return values for the 'spell' function call in case
458 // of a misspelled word.
459 // Especially it may give a list of suggested (correct) words:
461 Reference< XSpellAlternatives > xRes;
462 // note: mutex is held by higher up by spell which covers both
464 LanguageType nLang = LinguLocaleToLanguage( rLocale );
466 Sequence< OUString > aStr( 0 );
468 // first handle smart quotes (single and double)
469 OUStringBuffer rBuf(rWord);
470 sal_Int32 n = rBuf.getLength();
472 for (sal_Int32 ix=0; ix < n; ix++) {
474 if ((c == 0x201C) || (c == 0x201D)) rBuf[ix] = u'"';
475 if ((c == 0x2018) || (c == 0x2019)) rBuf[ix] = u'\'';
477 OUString nWord(rBuf.makeStringAndClear());
481 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
482 NSString* aNSStr = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(nWord.getStr()) length: nWord.getLength()]autorelease];
483 NSString* aLang = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Language.getStr()) length: rLocale.Language.getLength()]autorelease];
484 if(rLocale.Country.getLength()>0)
486 NSString* aCountry = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Country.getStr()) length: rLocale.Country.getLength()]autorelease];
487 NSString* aTaggedCountry = [@"_" stringByAppendingString:aCountry];
488 aLang = [aLang stringByAppendingString:aTaggedCountry];
491 [[NSSpellChecker sharedSpellChecker] setLanguage:aLang];
492 NSArray *guesses = [[NSSpellChecker sharedSpellChecker] guessesForWordRange:NSMakeRange(0, [aNSStr length]) inString:aNSStr language:aLang inSpellDocumentWithTag:0];
493 (void) this; // avoid loplugin:staticmethods, the !MACOSX case uses 'this'
495 NSArray *guesses = [pChecker guessesForWordRange:NSMakeRange(0, [aNSStr length]) inString:aNSStr language:aLang];
497 count = [guesses count];
500 aStr.realloc( count );
501 OUString *pStr = aStr.getArray();
502 for (int ii=0; ii < count; ii++)
504 // if needed add: if (suglst[ii] == NULL) continue;
505 NSString* guess = [guesses objectAtIndex:ii];
506 OUString cvtwrd(reinterpret_cast<const sal_Unicode*>([guess cStringUsingEncoding:NSUnicodeStringEncoding]), static_cast<sal_Int32>([guess length]));
513 // now return an empty alternative for no suggestions or the list of alternatives if some found
514 rtl::Reference<SpellAlternatives> pAlt = new SpellAlternatives;
515 pAlt->SetWordLanguage( rWord, nLang );
516 pAlt->SetFailureType( SpellFailure::SPELLING_ERROR );
517 pAlt->SetAlternatives( aStr );
523 Reference< XSpellAlternatives > SAL_CALL
524 MacSpellChecker::spell( const OUString& rWord, const Locale& rLocale,
525 const css::uno::Sequence<PropertyValue>& rProperties )
527 MutexGuard aGuard( GetLinguMutex() );
529 if (rLocale == Locale() || !rWord.getLength())
532 if (!hasLocale( rLocale ))
535 Reference< XSpellAlternatives > xAlt;
536 if (!isValid( rWord, rLocale, rProperties ))
538 xAlt = GetProposals( rWord, rLocale );
544 MacSpellChecker::addLinguServiceEventListener(
545 const Reference< XLinguServiceEventListener >& rxLstnr )
547 MutexGuard aGuard( GetLinguMutex() );
550 if (!bDisposing && rxLstnr.is())
552 bRes = GetPropHelper().addLinguServiceEventListener( rxLstnr );
559 MacSpellChecker::removeLinguServiceEventListener(
560 const Reference< XLinguServiceEventListener >& rxLstnr )
562 MutexGuard aGuard( GetLinguMutex() );
565 if (!bDisposing && rxLstnr.is())
567 DBG_ASSERT( xPropHelper.is(), "xPropHelper non existent" );
568 bRes = GetPropHelper().removeLinguServiceEventListener( rxLstnr );
575 MacSpellChecker::getServiceDisplayName( const Locale& /*rLocale*/ )
577 MutexGuard aGuard( GetLinguMutex() );
578 return "macOS Spell Checker";
583 MacSpellChecker::initialize( const Sequence< Any >& rArguments )
585 MutexGuard aGuard( GetLinguMutex() );
587 if (!xPropHelper.is())
589 sal_Int32 nLen = rArguments.getLength();
592 Reference< XLinguProperties > xPropSet;
593 rArguments.getConstArray()[0] >>= xPropSet;
594 //rArguments.getConstArray()[1] >>= xDicList;
596 //! Pointer allows for access of the non-UNO functions.
597 //! And the reference to the UNO-functions while increasing
598 //! the ref-count and will implicitly free the memory
599 //! when the object is no longer used.
600 xPropHelper = new PropertyHelper_Spell( static_cast<XSpellChecker *>(this), xPropSet );
601 xPropHelper->AddAsPropListener();
604 OSL_FAIL( "wrong number of arguments in sequence" );
611 MacSpellChecker::dispose()
613 MutexGuard aGuard( GetLinguMutex() );
618 EventObject aEvtObj( static_cast<XSpellChecker *>(this) );
619 aEvtListeners.disposeAndClear( aEvtObj );
625 MacSpellChecker::addEventListener( const Reference< XEventListener >& rxListener )
627 MutexGuard aGuard( GetLinguMutex() );
629 if (!bDisposing && rxListener.is())
630 aEvtListeners.addInterface( rxListener );
635 MacSpellChecker::removeEventListener( const Reference< XEventListener >& rxListener )
637 MutexGuard aGuard( GetLinguMutex() );
639 if (!bDisposing && rxListener.is())
640 aEvtListeners.removeInterface( rxListener );
643 // Service specific part
644 OUString SAL_CALL MacSpellChecker::getImplementationName()
646 return "org.openoffice.lingu.MacOSXSpellChecker";
649 sal_Bool SAL_CALL MacSpellChecker::supportsService( const OUString& ServiceName )
651 return cppu::supportsService(this, ServiceName);
654 Sequence< OUString > SAL_CALL MacSpellChecker::getSupportedServiceNames()
656 return { SN_SPELLCHECKER };
659 extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
660 lingucomponent_MacSpellChecker_get_implementation(
661 css::uno::XComponentContext* , css::uno::Sequence<css::uno::Any> const&)
663 return cppu::acquire(new MacSpellChecker());
666 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */