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 <com/sun/star/registry/XRegistryKey.hpp>
27 #include <com/sun/star/lang/XSingleServiceFactory.hpp>
28 #include <tools/debug.hxx>
29 #include <osl/mutex.hxx>
31 #include "macspellimp.hxx"
33 #include <linguistic/spelldta.hxx>
34 #include <unotools/pathoptions.hxx>
35 #include <unotools/useroptions.hxx>
36 #include <osl/file.hxx>
37 #include <rtl/ustrbuf.hxx>
41 using namespace com::sun::star;
42 using namespace com::sun::star::beans;
43 using namespace com::sun::star::lang;
44 using namespace com::sun::star::uno;
45 using namespace com::sun::star::linguistic2;
46 using namespace linguistic;
48 MacSpellChecker::MacSpellChecker() :
49 aEvtListeners( GetLinguMutex() )
55 pPropHelper = nullptr;
59 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
60 macTag = [NSSpellChecker uniqueSpellDocumentTag];
63 pChecker = [[UITextChecker alloc] init];
68 MacSpellChecker::~MacSpellChecker()
71 if (aDEncs) delete[] aDEncs;
73 if (aDLocs) delete[] aDLocs;
75 if (aDNames) delete[] aDNames;
78 pPropHelper->RemoveAsPropListener();
82 PropertyHelper_Spell & MacSpellChecker::GetPropHelper_Impl()
86 Reference< XLinguProperties > xPropSet( GetLinguProperties(), UNO_QUERY );
88 pPropHelper = new PropertyHelper_Spell( static_cast<XSpellChecker *>(this), xPropSet );
89 xPropHelper = pPropHelper;
90 pPropHelper->AddAsPropListener(); //! after a reference is established
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 const std::vector<NSString*> aDE
135 { @"AT", @"BE", @"CH", @"DE", @"LI", @"LU" };
138 pLangStr = [@"de_" stringByAppendingString: c];
139 postspdict.push_back( pLangStr );
143 // iOS says it has specifically de_DE, but let's assume it is good enough for the other
144 // variants, too, for now.
145 else if ([pLangStr isEqualToString:@"de_DE"])
147 const std::vector<NSString*> aDE
148 { @"AT", @"BE", @"CH", @"DE", @"LI", @"LU" };
151 pLangStr = [@"de_" stringByAppendingString: c];
152 postspdict.push_back( pLangStr );
156 else if ([pLangStr isEqualToString:@"en"])
158 // System has en_AU, en_CA, en_GB, and en_IN. Add the rest.
159 const std::vector<NSString*> aEN
160 { @"BW", @"BZ", @"GH", @"GM", @"IE", @"JM", @"MU", @"MW", @"MY", @"NA",
161 @"NZ", @"PH", @"TT", @"US", @"ZA", @"ZW" };
164 pLangStr = [@"en_" stringByAppendingString: c];
165 postspdict.push_back( pLangStr );
168 else if ([pLangStr isEqualToString:@"en_JP"]
169 || [pLangStr isEqualToString:@"en_SG"])
171 // Just skip, LO doesn't have those yet in this context.
173 else if ([pLangStr isEqualToString:@"es"])
175 const std::vector<NSString*> aES
176 { @"AR", @"BO", @"CL", @"CO", @"CR", @"CU", @"DO", @"EC", @"ES", @"GT",
177 @"HN", @"MX", @"NI", @"PA", @"PE", @"PR", @"PY", @"SV", @"UY", @"VE" };
180 pLangStr = [@"es_" stringByAppendingString: c];
181 postspdict.push_back( pLangStr );
184 else if ([pLangStr isEqualToString:@"fi"])
186 postspdict.push_back( @"fi_FI" );
188 else if ([pLangStr isEqualToString:@"fr"])
190 const std::vector<NSString*> aFR
191 { @"BE", @"BF", @"BJ", @"CA", @"CH", @"CI", @"FR", @"LU", @"MC", @"ML",
192 @"MU", @"NE", @"SN", @"TG" };
195 pLangStr = [@"fr_" stringByAppendingString: c];
196 postspdict.push_back( pLangStr );
199 else if ([pLangStr isEqualToString:@"it"])
201 postspdict.push_back( @"it_CH" );
202 postspdict.push_back( @"it_IT" );
204 else if ([pLangStr isEqualToString:@"ko"])
206 postspdict.push_back( @"ko_KR" );
208 else if ([pLangStr isEqualToString:@"nl"])
210 postspdict.push_back( @"nl_BE" );
211 postspdict.push_back( @"nl_NL" );
213 else if ([pLangStr isEqualToString:@"nb"])
215 postspdict.push_back( @"nb_NO" );
217 else if ([pLangStr isEqualToString:@"pl"])
219 postspdict.push_back( @"pl_PL" );
221 else if ([pLangStr isEqualToString:@"ru"])
223 postspdict.push_back( @"ru_RU" );
225 else if ([pLangStr isEqualToString:@"sv"])
227 postspdict.push_back( @"sv_FI" );
228 postspdict.push_back( @"sv_SE" );
231 else if ([pLangStr isEqualToString:@"sv_SE"])
233 postspdict.push_back( @"sv_FI" );
234 postspdict.push_back( @"sv_SE" );
237 else if ([pLangStr isEqualToString:@"tr"])
239 postspdict.push_back( @"tr_TR" );
242 postspdict.push_back( pLangStr );
244 // System has pt_BR and pt_PT, add pt_AO.
245 postspdict.push_back( @"pt_AO" );
247 numshr = postspdict.size();
249 // we really should merge these and remove duplicates but since
250 // users can name their dictionaries anything they want it would
251 // be impossible to know if a real duplication exists unless we
252 // add some unique key to each myspell dictionary
256 aDLocs = new Locale [numdict];
257 aDEncs = new rtl_TextEncoding [numdict];
258 aDNames = new OUString [numdict];
259 aSuppLocales.realloc(numdict);
260 Locale * pLocale = aSuppLocales.getArray();
266 //first add the user dictionaries
269 // now add the shared dictionaries
270 for (i = 0; i < numshr; i++) {
271 NSDictionary *aLocDict = [ NSLocale componentsFromLocaleIdentifier:postspdict[i] ];
272 NSString* aLang = [ aLocDict objectForKey:NSLocaleLanguageCode ];
273 NSString* aCountry = [ aLocDict objectForKey:NSLocaleCountryCode ];
274 OUString lang([aLang cStringUsingEncoding: NSUTF8StringEncoding], [aLang length], aEnc);
275 OUString country([ aCountry cStringUsingEncoding: NSUTF8StringEncoding], [aCountry length], aEnc);
276 Locale nLoc( lang, country, OUString() );
278 //eliminate duplicates (is this needed for MacOS?)
279 for (j = 0; j < numlocs; j++) {
280 if (nLoc == pLocale[j]) newloc = 0;
283 pLocale[numlocs] = nLoc;
291 aSuppLocales.realloc(numlocs);
294 /* no dictionary.lst found so register no dictionaries */
299 aSuppLocales.realloc(0);
308 sal_Bool SAL_CALL MacSpellChecker::hasLocale(const Locale& rLocale)
310 MutexGuard aGuard( GetLinguMutex() );
313 if (!aSuppLocales.getLength())
316 sal_Int32 nLen = aSuppLocales.getLength();
317 for (sal_Int32 i = 0; i < nLen; ++i)
319 const Locale *pLocale = aSuppLocales.getConstArray();
320 if (rLocale == pLocale[i])
330 sal_Int16 MacSpellChecker::GetSpellFailure( const OUString &rWord, const Locale &rLocale )
332 rtl_TextEncoding aEnc;
334 // initialize a myspell object for each dictionary once
335 // (note: mutex is held higher up in isValid)
340 // first handle smart quotes both single and double
341 OUStringBuffer rBuf(rWord);
342 sal_Int32 n = rBuf.getLength();
344 for (sal_Int32 ix=0; ix < n; ix++) {
346 if ((c == 0x201C) || (c == 0x201D)) rBuf[ix] = u'"';
347 if ((c == 0x2018) || (c == 0x2019)) rBuf[ix] = u'\'';
349 OUString nWord(rBuf.makeStringAndClear());
354 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
355 NSString* aNSStr = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(nWord.getStr()) length: nWord.getLength()]autorelease];
356 NSString* aLang = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Language.getStr()) length: rLocale.Language.getLength()]autorelease];
357 if(rLocale.Country.getLength()>0)
359 NSString* aCountry = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Country.getStr()) length: rLocale.Country.getLength()]autorelease];
360 NSString* aTaggedCountry = [@"_" stringByAppendingString:aCountry];
361 aLang = [aLang stringByAppendingString:aTaggedCountry];
366 NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:aNSStr startingAt:0 language:aLang wrap:false inSpellDocumentWithTag:macTag wordCount:&aCount];
368 NSRange range = [pChecker rangeOfMisspelledWordInString:aNSStr range:NSMakeRange(0, [aNSStr length]) startingAt:0 wrap:NO language:aLang];
382 nRes = SpellFailure::SPELLING_ERROR;
393 MacSpellChecker::isValid( const OUString& rWord, const Locale& rLocale,
394 const css::uno::Sequence<PropertyValue>& rProperties )
396 MutexGuard aGuard( GetLinguMutex() );
398 if (rLocale == Locale() || !rWord.getLength())
401 if (!hasLocale( rLocale ))
404 // Get property values to be used.
405 // These are be the default values set in the SN_LINGU_PROPERTIES
406 // PropertySet which are overridden by the supplied ones from the
408 // You'll probably like to use a simpler solution than the provided
409 // one using the PropertyHelper_Spell.
411 PropertyHelper_Spell &rHelper = GetPropHelper();
412 rHelper.SetTmpPropVals( rProperties );
414 sal_Int16 nFailure = GetSpellFailure( rWord, rLocale );
417 LanguageType nLang = LinguLocaleToLanguage( rLocale );
418 // postprocess result for errors that should be ignored
419 if ( (!rHelper.IsSpellUpperCase() && IsUpper( rWord, nLang ))
420 || (!rHelper.IsSpellWithDigits() && HasDigits( rWord ))
421 || (!rHelper.IsSpellCapitalization()
422 && nFailure == SpellFailure::CAPTION_ERROR)
427 return (nFailure == -1);
430 Reference< XSpellAlternatives >
431 MacSpellChecker::GetProposals( const OUString &rWord, const Locale &rLocale )
433 // Retrieves the return values for the 'spell' function call in case
434 // of a misspelled word.
435 // Especially it may give a list of suggested (correct) words:
437 Reference< XSpellAlternatives > xRes;
438 // note: mutex is held by higher up by spell which covers both
440 LanguageType nLang = LinguLocaleToLanguage( rLocale );
442 Sequence< OUString > aStr( 0 );
444 // first handle smart quotes (single and double)
445 OUStringBuffer rBuf(rWord);
446 sal_Int32 n = rBuf.getLength();
448 for (sal_Int32 ix=0; ix < n; ix++) {
450 if ((c == 0x201C) || (c == 0x201D)) rBuf[ix] = u'"';
451 if ((c == 0x2018) || (c == 0x2019)) rBuf[ix] = u'\'';
453 OUString nWord(rBuf.makeStringAndClear());
457 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
458 NSString* aNSStr = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(nWord.getStr()) length: nWord.getLength()]autorelease];
459 NSString* aLang = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Language.getStr()) length: rLocale.Language.getLength()]autorelease];
460 if(rLocale.Country.getLength()>0)
462 NSString* aCountry = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Country.getStr()) length: rLocale.Country.getLength()]autorelease];
463 NSString* aTaggedCountry = [@"_" stringByAppendingString:aCountry];
464 aLang = [aLang stringByAppendingString:aTaggedCountry];
467 [[NSSpellChecker sharedSpellChecker] setLanguage:aLang];
468 NSArray *guesses = [[NSSpellChecker sharedSpellChecker] guessesForWordRange:NSMakeRange(0, [aNSStr length]) inString:aNSStr language:aLang inSpellDocumentWithTag:0];
469 (void) this; // avoid loplugin:staticmethods, the !MACOSX case uses 'this'
471 NSArray *guesses = [pChecker guessesForWordRange:NSMakeRange(0, [aNSStr length]) inString:aNSStr language:aLang];
473 count = [guesses count];
476 aStr.realloc( count );
477 OUString *pStr = aStr.getArray();
478 for (int ii=0; ii < count; ii++)
480 // if needed add: if (suglst[ii] == NULL) continue;
481 NSString* guess = [guesses objectAtIndex:ii];
482 OUString cvtwrd(reinterpret_cast<const sal_Unicode*>([guess cStringUsingEncoding:NSUnicodeStringEncoding]), static_cast<sal_Int32>([guess length]));
489 // now return an empty alternative for no suggestions or the list of alternatives if some found
490 SpellAlternatives *pAlt = new SpellAlternatives;
491 pAlt->SetWordLanguage( rWord, nLang );
492 pAlt->SetFailureType( SpellFailure::SPELLING_ERROR );
493 pAlt->SetAlternatives( aStr );
499 Reference< XSpellAlternatives > SAL_CALL
500 MacSpellChecker::spell( const OUString& rWord, const Locale& rLocale,
501 const css::uno::Sequence<PropertyValue>& rProperties )
503 MutexGuard aGuard( GetLinguMutex() );
505 if (rLocale == Locale() || !rWord.getLength())
508 if (!hasLocale( rLocale ))
511 Reference< XSpellAlternatives > xAlt;
512 if (!isValid( rWord, rLocale, rProperties ))
514 xAlt = GetProposals( rWord, rLocale );
519 /// @throws Exception
520 static Reference< XInterface > MacSpellChecker_CreateInstance(
521 const Reference< XMultiServiceFactory > & /*rSMgr*/ )
524 Reference< XInterface > xService = static_cast<cppu::OWeakObject*>(new MacSpellChecker);
530 MacSpellChecker::addLinguServiceEventListener(
531 const Reference< XLinguServiceEventListener >& rxLstnr )
533 MutexGuard aGuard( GetLinguMutex() );
536 if (!bDisposing && rxLstnr.is())
538 bRes = GetPropHelper().addLinguServiceEventListener( rxLstnr );
545 MacSpellChecker::removeLinguServiceEventListener(
546 const Reference< XLinguServiceEventListener >& rxLstnr )
548 MutexGuard aGuard( GetLinguMutex() );
551 if (!bDisposing && rxLstnr.is())
553 DBG_ASSERT( xPropHelper.is(), "xPropHelper non existent" );
554 bRes = GetPropHelper().removeLinguServiceEventListener( rxLstnr );
561 MacSpellChecker::getServiceDisplayName( const Locale& /*rLocale*/ )
563 MutexGuard aGuard( GetLinguMutex() );
564 return OUString( "macOS Spell Checker" );
569 MacSpellChecker::initialize( const Sequence< Any >& rArguments )
571 MutexGuard aGuard( GetLinguMutex() );
575 sal_Int32 nLen = rArguments.getLength();
578 Reference< XLinguProperties > xPropSet;
579 rArguments.getConstArray()[0] >>= xPropSet;
580 //rArguments.getConstArray()[1] >>= xDicList;
582 //! Pointer allows for access of the non-UNO functions.
583 //! And the reference to the UNO-functions while increasing
584 //! the ref-count and will implicitly free the memory
585 //! when the object is no longer used.
586 pPropHelper = new PropertyHelper_Spell( static_cast<XSpellChecker *>(this), xPropSet );
587 xPropHelper = pPropHelper;
588 pPropHelper->AddAsPropListener(); //! after a reference is established
591 OSL_FAIL( "wrong number of arguments in sequence" );
598 MacSpellChecker::dispose()
600 MutexGuard aGuard( GetLinguMutex() );
605 EventObject aEvtObj( static_cast<XSpellChecker *>(this) );
606 aEvtListeners.disposeAndClear( aEvtObj );
612 MacSpellChecker::addEventListener( const Reference< XEventListener >& rxListener )
614 MutexGuard aGuard( GetLinguMutex() );
616 if (!bDisposing && rxListener.is())
617 aEvtListeners.addInterface( rxListener );
622 MacSpellChecker::removeEventListener( const Reference< XEventListener >& rxListener )
624 MutexGuard aGuard( GetLinguMutex() );
626 if (!bDisposing && rxListener.is())
627 aEvtListeners.removeInterface( rxListener );
630 // Service specific part
631 OUString SAL_CALL MacSpellChecker::getImplementationName()
633 return getImplementationName_Static();
636 sal_Bool SAL_CALL MacSpellChecker::supportsService( const OUString& ServiceName )
638 return cppu::supportsService(this, ServiceName);
641 Sequence< OUString > SAL_CALL MacSpellChecker::getSupportedServiceNames()
643 return getSupportedServiceNames_Static();
646 Sequence< OUString > MacSpellChecker::getSupportedServiceNames_Static()
649 Sequence< OUString > aSNS { SN_SPELLCHECKER };
656 SAL_DLLPUBLIC_EXPORT void * MacOSXSpell_component_getFactory(
657 const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
659 void * pRet = nullptr;
660 if ( MacSpellChecker::getImplementationName_Static().equalsAscii( pImplName ) )
662 Reference< XSingleServiceFactory > xFactory =
663 cppu::createOneInstanceFactory(
664 static_cast< XMultiServiceFactory * >( pServiceManager ),
665 MacSpellChecker::getImplementationName_Static(),
666 MacSpellChecker_CreateInstance,
667 MacSpellChecker::getSupportedServiceNames_Static());
668 // acquire, because we return an interface pointer instead of a reference
670 pRet = xFactory.get();
679 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */