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:@"ar"])
130 const std::vector<NSString*> aAR
131 { @"AE", @"BH", @"DJ", @"DZ", @"EG", @"ER", @"IL", @"IQ", @"JO",
132 @"KM", @"KW", @"LB", @"LY", @"MA", @"MR", @"OM", @"PS", @"QA",
133 @"SA", @"SD", @"SO", @"SY", @"TD", @"TN", @"YE" };
136 pLangStr = [@"ar_" stringByAppendingString: c];
137 postspdict.push_back( pLangStr );
140 else if ([pLangStr isEqualToString:@"da"])
142 postspdict.push_back( @"da_DK" );
144 else if ([pLangStr isEqualToString:@"de"])
146 // Not de_CH and de_LI, though. They need separate dictionaries.
147 const std::vector<NSString*> aDE
148 { @"AT", @"BE", @"DE", @"LU" };
151 pLangStr = [@"de_" stringByAppendingString: c];
152 postspdict.push_back( pLangStr );
156 // iOS says it has specifically de_DE. Let's assume it is good enough for German as
157 // written in Austria, Belgium, and Luxembourg, too. (Not for German in Switzerland and
158 // Liechtenstein. For those you need to bundle the myspell dictionary.)
159 else if ([pLangStr isEqualToString:@"de_DE"])
161 const std::vector<NSString*> aDE
162 { @"AT", @"BE", @"DE", @"LU" };
165 pLangStr = [@"de_" stringByAppendingString: c];
166 postspdict.push_back( pLangStr );
170 else if ([pLangStr isEqualToString:@"en"])
172 // System has en_AU, en_CA, en_GB, and en_IN. Add the rest.
173 const std::vector<NSString*> aEN
174 { @"BW", @"BZ", @"GH", @"GM", @"IE", @"JM", @"MU", @"MW", @"MY", @"NA",
175 @"NZ", @"PH", @"TT", @"US", @"ZA", @"ZW" };
178 pLangStr = [@"en_" stringByAppendingString: c];
179 postspdict.push_back( pLangStr );
182 else if ([pLangStr isEqualToString:@"en_JP"]
183 || [pLangStr isEqualToString:@"en_SG"])
185 // Just skip, LO doesn't have those yet in this context.
187 else if ([pLangStr isEqualToString:@"es"])
189 const std::vector<NSString*> aES
190 { @"AR", @"BO", @"CL", @"CO", @"CR", @"CU", @"DO", @"EC", @"ES", @"GT",
191 @"HN", @"MX", @"NI", @"PA", @"PE", @"PR", @"PY", @"SV", @"UY", @"VE" };
194 pLangStr = [@"es_" stringByAppendingString: c];
195 postspdict.push_back( pLangStr );
198 else if ([pLangStr isEqualToString:@"fi"])
200 postspdict.push_back( @"fi_FI" );
202 else if ([pLangStr isEqualToString:@"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:@"fr_FR"])
216 const std::vector<NSString*> aFR
217 { @"BE", @"BF", @"BJ", @"CA", @"CH", @"CI", @"FR", @"LU", @"MC", @"ML",
218 @"MU", @"NE", @"SN", @"TG" };
221 pLangStr = [@"fr_" stringByAppendingString: c];
222 postspdict.push_back( pLangStr );
226 else if ([pLangStr isEqualToString:@"it"])
228 postspdict.push_back( @"it_CH" );
229 postspdict.push_back( @"it_IT" );
232 else if ([pLangStr isEqualToString:@"it_IT"])
234 const std::vector<NSString*> aIT
238 pLangStr = [@"it_" stringByAppendingString: c];
239 postspdict.push_back( pLangStr );
243 else if ([pLangStr isEqualToString:@"ko"])
245 postspdict.push_back( @"ko_KR" );
247 else if ([pLangStr isEqualToString:@"nl"])
249 postspdict.push_back( @"nl_BE" );
250 postspdict.push_back( @"nl_NL" );
252 else if ([pLangStr isEqualToString:@"nb"])
254 postspdict.push_back( @"nb_NO" );
256 else if ([pLangStr isEqualToString:@"pl"])
258 postspdict.push_back( @"pl_PL" );
260 else if ([pLangStr isEqualToString:@"ru"])
262 postspdict.push_back( @"ru_RU" );
264 else if ([pLangStr isEqualToString:@"sv"])
266 postspdict.push_back( @"sv_FI" );
267 postspdict.push_back( @"sv_SE" );
270 else if ([pLangStr isEqualToString:@"sv_SE"])
272 postspdict.push_back( @"sv_FI" );
273 postspdict.push_back( @"sv_SE" );
276 else if ([pLangStr isEqualToString:@"tr"])
278 postspdict.push_back( @"tr_TR" );
281 postspdict.push_back( pLangStr );
283 // System has pt_BR and pt_PT, add pt_AO.
284 postspdict.push_back( @"pt_AO" );
286 numshr = postspdict.size();
288 // we really should merge these and remove duplicates but since
289 // users can name their dictionaries anything they want it would
290 // be impossible to know if a real duplication exists unless we
291 // add some unique key to each myspell dictionary
295 aDLocs = new Locale [numdict];
296 aDEncs = new rtl_TextEncoding [numdict];
297 aDNames = new OUString [numdict];
298 aSuppLocales.realloc(numdict);
299 Locale * pLocale = aSuppLocales.getArray();
305 //first add the user dictionaries
308 // now add the shared dictionaries
309 for (i = 0; i < numshr; i++) {
310 NSDictionary *aLocDict = [ NSLocale componentsFromLocaleIdentifier:postspdict[i] ];
311 NSString* aLang = [ aLocDict objectForKey:NSLocaleLanguageCode ];
312 NSString* aCountry = [ aLocDict objectForKey:NSLocaleCountryCode ];
313 OUString lang([aLang cStringUsingEncoding: NSUTF8StringEncoding], [aLang length], aEnc);
314 OUString country([ aCountry cStringUsingEncoding: NSUTF8StringEncoding], [aCountry length], aEnc);
315 Locale nLoc( lang, country, OUString() );
317 //eliminate duplicates (is this needed for MacOS?)
318 for (j = 0; j < numlocs; j++) {
319 if (nLoc == pLocale[j]) newloc = 0;
322 pLocale[numlocs] = nLoc;
330 aSuppLocales.realloc(numlocs);
333 /* no dictionary.lst found so register no dictionaries */
338 aSuppLocales.realloc(0);
347 sal_Bool SAL_CALL MacSpellChecker::hasLocale(const Locale& rLocale)
349 MutexGuard aGuard( GetLinguMutex() );
352 if (!aSuppLocales.getLength())
355 sal_Int32 nLen = aSuppLocales.getLength();
356 for (sal_Int32 i = 0; i < nLen; ++i)
358 const Locale *pLocale = aSuppLocales.getConstArray();
359 if (rLocale == pLocale[i])
369 sal_Int16 MacSpellChecker::GetSpellFailure( const OUString &rWord, const Locale &rLocale )
371 // initialize a myspell object for each dictionary once
372 // (note: mutex is held higher up in isValid)
377 // first handle smart quotes both single and double
378 OUStringBuffer rBuf(rWord);
379 sal_Int32 n = rBuf.getLength();
381 for (sal_Int32 ix=0; ix < n; ix++) {
383 if ((c == 0x201C) || (c == 0x201D)) rBuf[ix] = u'"';
384 if ((c == 0x2018) || (c == 0x2019)) rBuf[ix] = u'\'';
386 OUString nWord(rBuf.makeStringAndClear());
390 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
391 NSString* aNSStr = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(nWord.getStr()) length: nWord.getLength()]autorelease];
392 NSString* aLang = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Language.getStr()) length: rLocale.Language.getLength()]autorelease];
393 if(rLocale.Country.getLength()>0)
395 NSString* aCountry = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Country.getStr()) length: rLocale.Country.getLength()]autorelease];
396 NSString* aTaggedCountry = [@"_" stringByAppendingString:aCountry];
397 aLang = [aLang stringByAppendingString:aTaggedCountry];
402 NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:aNSStr startingAt:0 language:aLang wrap:false inSpellDocumentWithTag:macTag wordCount:&aCount];
404 NSRange range = [pChecker rangeOfMisspelledWordInString:aNSStr range:NSMakeRange(0, [aNSStr length]) startingAt:0 wrap:NO language:aLang];
418 nRes = SpellFailure::SPELLING_ERROR;
429 MacSpellChecker::isValid( const OUString& rWord, const Locale& rLocale,
430 const css::uno::Sequence<PropertyValue>& rProperties )
432 MutexGuard aGuard( GetLinguMutex() );
434 if (rLocale == Locale() || !rWord.getLength())
437 if (!hasLocale( rLocale ))
440 // Get property values to be used.
441 // These are be the default values set in the SN_LINGU_PROPERTIES
442 // PropertySet which are overridden by the supplied ones from the
444 // You'll probably like to use a simpler solution than the provided
445 // one using the PropertyHelper_Spell.
447 PropertyHelper_Spell &rHelper = GetPropHelper();
448 rHelper.SetTmpPropVals( rProperties );
450 sal_Int16 nFailure = GetSpellFailure( rWord, rLocale );
453 LanguageType nLang = LinguLocaleToLanguage( rLocale );
454 // postprocess result for errors that should be ignored
455 if ( (!rHelper.IsSpellUpperCase() && IsUpper( rWord, nLang ))
456 || (!rHelper.IsSpellWithDigits() && HasDigits( rWord ))
457 || (!rHelper.IsSpellCapitalization()
458 && nFailure == SpellFailure::CAPTION_ERROR)
463 return (nFailure == -1);
466 Reference< XSpellAlternatives >
467 MacSpellChecker::GetProposals( const OUString &rWord, const Locale &rLocale )
469 // Retrieves the return values for the 'spell' function call in case
470 // of a misspelled word.
471 // Especially it may give a list of suggested (correct) words:
473 Reference< XSpellAlternatives > xRes;
474 // note: mutex is held by higher up by spell which covers both
476 LanguageType nLang = LinguLocaleToLanguage( rLocale );
478 Sequence< OUString > aStr( 0 );
480 // first handle smart quotes (single and double)
481 OUStringBuffer rBuf(rWord);
482 sal_Int32 n = rBuf.getLength();
484 for (sal_Int32 ix=0; ix < n; ix++) {
486 if ((c == 0x201C) || (c == 0x201D)) rBuf[ix] = u'"';
487 if ((c == 0x2018) || (c == 0x2019)) rBuf[ix] = u'\'';
489 OUString nWord(rBuf.makeStringAndClear());
493 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
494 NSString* aNSStr = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(nWord.getStr()) length: nWord.getLength()]autorelease];
495 NSString* aLang = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Language.getStr()) length: rLocale.Language.getLength()]autorelease];
496 if(rLocale.Country.getLength()>0)
498 NSString* aCountry = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Country.getStr()) length: rLocale.Country.getLength()]autorelease];
499 NSString* aTaggedCountry = [@"_" stringByAppendingString:aCountry];
500 aLang = [aLang stringByAppendingString:aTaggedCountry];
503 [[NSSpellChecker sharedSpellChecker] setLanguage:aLang];
504 NSArray *guesses = [[NSSpellChecker sharedSpellChecker] guessesForWordRange:NSMakeRange(0, [aNSStr length]) inString:aNSStr language:aLang inSpellDocumentWithTag:0];
505 (void) this; // avoid loplugin:staticmethods, the !MACOSX case uses 'this'
507 NSArray *guesses = [pChecker guessesForWordRange:NSMakeRange(0, [aNSStr length]) inString:aNSStr language:aLang];
509 count = [guesses count];
512 aStr.realloc( count );
513 OUString *pStr = aStr.getArray();
514 for (int ii=0; ii < count; ii++)
516 // if needed add: if (suglst[ii] == NULL) continue;
517 NSString* guess = [guesses objectAtIndex:ii];
518 OUString cvtwrd(reinterpret_cast<const sal_Unicode*>([guess cStringUsingEncoding:NSUnicodeStringEncoding]), static_cast<sal_Int32>([guess length]));
525 // now return an empty alternative for no suggestions or the list of alternatives if some found
526 rtl::Reference<SpellAlternatives> pAlt = new SpellAlternatives;
527 pAlt->SetWordLanguage( rWord, nLang );
528 pAlt->SetFailureType( SpellFailure::SPELLING_ERROR );
529 pAlt->SetAlternatives( aStr );
535 Reference< XSpellAlternatives > SAL_CALL
536 MacSpellChecker::spell( const OUString& rWord, const Locale& rLocale,
537 const css::uno::Sequence<PropertyValue>& rProperties )
539 MutexGuard aGuard( GetLinguMutex() );
541 if (rLocale == Locale() || !rWord.getLength())
544 if (!hasLocale( rLocale ))
547 Reference< XSpellAlternatives > xAlt;
548 if (!isValid( rWord, rLocale, rProperties ))
550 xAlt = GetProposals( rWord, rLocale );
556 MacSpellChecker::addLinguServiceEventListener(
557 const Reference< XLinguServiceEventListener >& rxLstnr )
559 MutexGuard aGuard( GetLinguMutex() );
562 if (!bDisposing && rxLstnr.is())
564 bRes = GetPropHelper().addLinguServiceEventListener( rxLstnr );
571 MacSpellChecker::removeLinguServiceEventListener(
572 const Reference< XLinguServiceEventListener >& rxLstnr )
574 MutexGuard aGuard( GetLinguMutex() );
577 if (!bDisposing && rxLstnr.is())
579 DBG_ASSERT( xPropHelper.is(), "xPropHelper non existent" );
580 bRes = GetPropHelper().removeLinguServiceEventListener( rxLstnr );
587 MacSpellChecker::getServiceDisplayName( const Locale& /*rLocale*/ )
589 MutexGuard aGuard( GetLinguMutex() );
590 return "macOS Spell Checker";
595 MacSpellChecker::initialize( const Sequence< Any >& rArguments )
597 MutexGuard aGuard( GetLinguMutex() );
599 if (!xPropHelper.is())
601 sal_Int32 nLen = rArguments.getLength();
604 Reference< XLinguProperties > xPropSet;
605 rArguments.getConstArray()[0] >>= xPropSet;
606 //rArguments.getConstArray()[1] >>= xDicList;
608 //! Pointer allows for access of the non-UNO functions.
609 //! And the reference to the UNO-functions while increasing
610 //! the ref-count and will implicitly free the memory
611 //! when the object is no longer used.
612 xPropHelper = new PropertyHelper_Spell( static_cast<XSpellChecker *>(this), xPropSet );
613 xPropHelper->AddAsPropListener();
616 OSL_FAIL( "wrong number of arguments in sequence" );
623 MacSpellChecker::dispose()
625 MutexGuard aGuard( GetLinguMutex() );
630 EventObject aEvtObj( static_cast<XSpellChecker *>(this) );
631 aEvtListeners.disposeAndClear( aEvtObj );
637 MacSpellChecker::addEventListener( const Reference< XEventListener >& rxListener )
639 MutexGuard aGuard( GetLinguMutex() );
641 if (!bDisposing && rxListener.is())
642 aEvtListeners.addInterface( rxListener );
647 MacSpellChecker::removeEventListener( const Reference< XEventListener >& rxListener )
649 MutexGuard aGuard( GetLinguMutex() );
651 if (!bDisposing && rxListener.is())
652 aEvtListeners.removeInterface( rxListener );
655 // Service specific part
656 OUString SAL_CALL MacSpellChecker::getImplementationName()
658 return "org.openoffice.lingu.MacOSXSpellChecker";
661 sal_Bool SAL_CALL MacSpellChecker::supportsService( const OUString& ServiceName )
663 return cppu::supportsService(this, ServiceName);
666 Sequence< OUString > SAL_CALL MacSpellChecker::getSupportedServiceNames()
668 return { SN_SPELLCHECKER };
671 extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
672 lingucomponent_MacSpellChecker_get_implementation(
673 css::uno::XComponentContext* , css::uno::Sequence<css::uno::Any> const&)
675 return cppu::acquire(new MacSpellChecker());
678 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */