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/diagnose.h>
38 #include <osl/file.hxx>
39 #include <rtl/ref.hxx>
40 #include <rtl/ustrbuf.hxx>
44 using namespace com::sun::star;
45 using namespace com::sun::star::beans;
46 using namespace com::sun::star::lang;
47 using namespace com::sun::star::uno;
48 using namespace com::sun::star::linguistic2;
49 using namespace linguistic;
51 MacSpellChecker::MacSpellChecker() :
52 aEvtListeners( GetLinguMutex() )
61 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
62 macTag = [NSSpellChecker uniqueSpellDocumentTag];
65 pChecker = [[UITextChecker alloc] init];
70 MacSpellChecker::~MacSpellChecker()
73 if (aDEncs) delete[] aDEncs;
75 if (aDLocs) delete[] aDLocs;
77 if (aDNames) delete[] aDNames;
80 xPropHelper->RemoveAsPropListener();
84 PropertyHelper_Spell & MacSpellChecker::GetPropHelper_Impl()
86 if (!xPropHelper.is())
88 Reference< XLinguProperties > xPropSet( GetLinguProperties() );
90 xPropHelper = new PropertyHelper_Spell( static_cast<XSpellChecker *>(this), xPropSet );
91 xPropHelper->AddAsPropListener();
97 Sequence< Locale > SAL_CALL MacSpellChecker::getLocales()
99 MutexGuard aGuard( GetLinguMutex() );
101 // this routine should return the locales supported by the installed
102 // dictionaries. So here we need to parse both the user edited
103 // dictionary list and the shared dictionary list
104 // to see what dictionaries the admin/user has installed
106 int numshr; // number of shared dictionary entries
107 rtl_TextEncoding aEnc = RTL_TEXTENCODING_UTF8;
109 std::vector<NSString *> postspdict;
113 // invoke a dictionary manager to get the user dictionary list
114 // TODO How on macOS?
116 // invoke a second dictionary manager to get the shared dictionary list
118 NSArray *aSpellCheckLanguages = [[NSSpellChecker sharedSpellChecker] availableLanguages];
120 NSArray *aSpellCheckLanguages = [UITextChecker availableLanguages];
123 for (NSUInteger i = 0; i < [aSpellCheckLanguages count]; i++)
125 NSString* pLangStr = static_cast<NSString*>([aSpellCheckLanguages objectAtIndex:i]);
127 // Fix up generic languages (without territory code) and odd combinations that LO
129 if ([pLangStr isEqualToString:@"ar"])
131 const std::vector<NSString*> aAR
132 { @"AE", @"BH", @"DJ", @"DZ", @"EG", @"ER", @"IL", @"IQ", @"JO",
133 @"KM", @"KW", @"LB", @"LY", @"MA", @"MR", @"OM", @"PS", @"QA",
134 @"SA", @"SD", @"SO", @"SY", @"TD", @"TN", @"YE" };
137 pLangStr = [@"ar_" stringByAppendingString: c];
138 postspdict.push_back( pLangStr );
141 else if ([pLangStr isEqualToString:@"da"])
143 postspdict.push_back( @"da_DK" );
145 else if ([pLangStr isEqualToString:@"de"])
147 // Not de_CH and de_LI, though. They need separate dictionaries.
148 const std::vector<NSString*> aDE
149 { @"AT", @"BE", @"DE", @"LU" };
152 pLangStr = [@"de_" stringByAppendingString: c];
153 postspdict.push_back( pLangStr );
157 // iOS says it has specifically de_DE. Let's assume it is good enough for German as
158 // written in Austria, Belgium, and Luxembourg, too. (Not for German in Switzerland and
159 // Liechtenstein. For those you need to bundle the myspell dictionary.)
160 else if ([pLangStr isEqualToString:@"de_DE"])
162 const std::vector<NSString*> aDE
163 { @"AT", @"BE", @"DE", @"LU" };
166 pLangStr = [@"de_" stringByAppendingString: c];
167 postspdict.push_back( pLangStr );
171 else if ([pLangStr isEqualToString:@"en"])
173 // System has en_AU, en_CA, en_GB, and en_IN. Add the rest.
174 const std::vector<NSString*> aEN
175 { @"BW", @"BZ", @"GH", @"GM", @"IE", @"JM", @"MU", @"MW", @"MY", @"NA",
176 @"NZ", @"PH", @"TT", @"US", @"ZA", @"ZW" };
179 pLangStr = [@"en_" stringByAppendingString: c];
180 postspdict.push_back( pLangStr );
183 else if ([pLangStr isEqualToString:@"en_JP"]
184 || [pLangStr isEqualToString:@"en_SG"])
186 // Just skip, LO doesn't have those yet in this context.
188 else if ([pLangStr isEqualToString:@"es"])
190 const std::vector<NSString*> aES
191 { @"AR", @"BO", @"CL", @"CO", @"CR", @"CU", @"DO", @"EC", @"ES", @"GT",
192 @"HN", @"MX", @"NI", @"PA", @"PE", @"PR", @"PY", @"SV", @"UY", @"VE" };
195 pLangStr = [@"es_" stringByAppendingString: c];
196 postspdict.push_back( pLangStr );
199 else if ([pLangStr isEqualToString:@"fi"])
201 postspdict.push_back( @"fi_FI" );
203 else if ([pLangStr isEqualToString:@"fr"])
205 const std::vector<NSString*> aFR
206 { @"BE", @"BF", @"BJ", @"CA", @"CH", @"CI", @"FR", @"LU", @"MC", @"ML",
207 @"MU", @"NE", @"SN", @"TG" };
210 pLangStr = [@"fr_" stringByAppendingString: c];
211 postspdict.push_back( pLangStr );
215 else if ([pLangStr isEqualToString:@"fr_FR"])
217 const std::vector<NSString*> aFR
218 { @"BE", @"BF", @"BJ", @"CA", @"CH", @"CI", @"FR", @"LU", @"MC", @"ML",
219 @"MU", @"NE", @"SN", @"TG" };
222 pLangStr = [@"fr_" stringByAppendingString: c];
223 postspdict.push_back( pLangStr );
227 else if ([pLangStr isEqualToString:@"it"])
229 postspdict.push_back( @"it_CH" );
230 postspdict.push_back( @"it_IT" );
233 else if ([pLangStr isEqualToString:@"it_IT"])
235 const std::vector<NSString*> aIT
239 pLangStr = [@"it_" stringByAppendingString: c];
240 postspdict.push_back( pLangStr );
244 else if ([pLangStr isEqualToString:@"ko"])
246 postspdict.push_back( @"ko_KR" );
248 else if ([pLangStr isEqualToString:@"nl"])
250 postspdict.push_back( @"nl_BE" );
251 postspdict.push_back( @"nl_NL" );
253 else if ([pLangStr isEqualToString:@"nb"])
255 postspdict.push_back( @"nb_NO" );
257 else if ([pLangStr isEqualToString:@"pl"])
259 postspdict.push_back( @"pl_PL" );
261 else if ([pLangStr isEqualToString:@"ru"])
263 postspdict.push_back( @"ru_RU" );
265 else if ([pLangStr isEqualToString:@"sv"])
267 postspdict.push_back( @"sv_FI" );
268 postspdict.push_back( @"sv_SE" );
271 else if ([pLangStr isEqualToString:@"sv_SE"])
273 postspdict.push_back( @"sv_FI" );
274 postspdict.push_back( @"sv_SE" );
277 else if ([pLangStr isEqualToString:@"tr"])
279 postspdict.push_back( @"tr_TR" );
282 postspdict.push_back( pLangStr );
284 // System has pt_BR and pt_PT, add pt_AO.
285 postspdict.push_back( @"pt_AO" );
287 numshr = postspdict.size();
289 // we really should merge these and remove duplicates but since
290 // users can name their dictionaries anything they want it would
291 // be impossible to know if a real duplication exists unless we
292 // add some unique key to each myspell dictionary
296 aDLocs = new Locale [numdict];
297 aDEncs = new rtl_TextEncoding [numdict];
298 aDNames = new OUString [numdict];
299 aSuppLocales.realloc(numdict);
300 Locale * pLocale = aSuppLocales.getArray();
306 //first add the user dictionaries
309 // now add the shared dictionaries
310 for (i = 0; i < numshr; i++) {
311 NSDictionary *aLocDict = [ NSLocale componentsFromLocaleIdentifier:postspdict[i] ];
312 NSString* aLang = [ aLocDict objectForKey:NSLocaleLanguageCode ];
313 NSString* aCountry = [ aLocDict objectForKey:NSLocaleCountryCode ];
314 OUString lang([aLang cStringUsingEncoding: NSUTF8StringEncoding], [aLang length], aEnc);
315 OUString country([ aCountry cStringUsingEncoding: NSUTF8StringEncoding], [aCountry length], aEnc);
316 Locale nLoc( lang, country, OUString() );
318 //eliminate duplicates (is this needed for MacOS?)
319 for (j = 0; j < numlocs; j++) {
320 if (nLoc == pLocale[j]) newloc = 0;
323 pLocale[numlocs] = nLoc;
331 aSuppLocales.realloc(numlocs);
334 /* no dictionary.lst found so register no dictionaries */
339 aSuppLocales.realloc(0);
348 sal_Bool SAL_CALL MacSpellChecker::hasLocale(const Locale& rLocale)
350 MutexGuard aGuard( GetLinguMutex() );
353 if (!aSuppLocales.getLength())
356 sal_Int32 nLen = aSuppLocales.getLength();
357 for (sal_Int32 i = 0; i < nLen; ++i)
359 const Locale *pLocale = aSuppLocales.getConstArray();
360 if (rLocale == pLocale[i])
370 sal_Int16 MacSpellChecker::GetSpellFailure( const OUString &rWord, const Locale &rLocale )
372 // initialize a myspell object for each dictionary once
373 // (note: mutex is held higher up in isValid)
378 // first handle smart quotes both single and double
379 OUStringBuffer rBuf(rWord);
380 sal_Int32 n = rBuf.getLength();
382 for (sal_Int32 ix=0; ix < n; ix++) {
384 if ((c == 0x201C) || (c == 0x201D)) rBuf[ix] = u'"';
385 if ((c == 0x2018) || (c == 0x2019)) rBuf[ix] = u'\'';
387 OUString nWord(rBuf.makeStringAndClear());
391 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
392 NSString* aNSStr = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(nWord.getStr()) length: nWord.getLength()]autorelease];
393 NSString* aLang = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Language.getStr()) length: rLocale.Language.getLength()]autorelease];
394 if(rLocale.Country.getLength()>0)
396 NSString* aCountry = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Country.getStr()) length: rLocale.Country.getLength()]autorelease];
397 NSString* aTaggedCountry = [@"_" stringByAppendingString:aCountry];
398 aLang = [aLang stringByAppendingString:aTaggedCountry];
403 NSRange range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:aNSStr startingAt:0 language:aLang wrap:false inSpellDocumentWithTag:macTag wordCount:&aCount];
405 NSRange range = [pChecker rangeOfMisspelledWordInString:aNSStr range:NSMakeRange(0, [aNSStr length]) startingAt:0 wrap:NO language:aLang];
419 nRes = SpellFailure::SPELLING_ERROR;
430 MacSpellChecker::isValid( const OUString& rWord, const Locale& rLocale,
431 const css::uno::Sequence<PropertyValue>& rProperties )
433 MutexGuard aGuard( GetLinguMutex() );
435 if (rLocale == Locale() || !rWord.getLength())
438 if (!hasLocale( rLocale ))
441 // Get property values to be used.
442 // These are be the default values set in the SN_LINGU_PROPERTIES
443 // PropertySet which are overridden by the supplied ones from the
445 // You'll probably like to use a simpler solution than the provided
446 // one using the PropertyHelper_Spell.
448 PropertyHelper_Spell &rHelper = GetPropHelper();
449 rHelper.SetTmpPropVals( rProperties );
451 sal_Int16 nFailure = GetSpellFailure( rWord, rLocale );
454 LanguageType nLang = LinguLocaleToLanguage( rLocale );
455 // postprocess result for errors that should be ignored
456 if ( (!rHelper.IsSpellUpperCase() && IsUpper( rWord, nLang ))
457 || (!rHelper.IsSpellWithDigits() && HasDigits( rWord ))
462 return (nFailure == -1);
465 Reference< XSpellAlternatives >
466 MacSpellChecker::GetProposals( const OUString &rWord, const Locale &rLocale )
468 // Retrieves the return values for the 'spell' function call in case
469 // of a misspelled word.
470 // Especially it may give a list of suggested (correct) words:
472 Reference< XSpellAlternatives > xRes;
473 // note: mutex is held by higher up by spell which covers both
475 LanguageType nLang = LinguLocaleToLanguage( rLocale );
477 Sequence< OUString > aStr( 0 );
479 // first handle smart quotes (single and double)
480 OUStringBuffer rBuf(rWord);
481 sal_Int32 n = rBuf.getLength();
483 for (sal_Int32 ix=0; ix < n; ix++) {
485 if ((c == 0x201C) || (c == 0x201D)) rBuf[ix] = u'"';
486 if ((c == 0x2018) || (c == 0x2019)) rBuf[ix] = u'\'';
488 OUString nWord(rBuf.makeStringAndClear());
492 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
493 NSString* aNSStr = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(nWord.getStr()) length: nWord.getLength()]autorelease];
494 NSString* aLang = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Language.getStr()) length: rLocale.Language.getLength()]autorelease];
495 if(rLocale.Country.getLength()>0)
497 NSString* aCountry = [[[NSString alloc] initWithCharacters: reinterpret_cast<unichar const *>(rLocale.Country.getStr()) length: rLocale.Country.getLength()]autorelease];
498 NSString* aTaggedCountry = [@"_" stringByAppendingString:aCountry];
499 aLang = [aLang stringByAppendingString:aTaggedCountry];
502 [[NSSpellChecker sharedSpellChecker] setLanguage:aLang];
503 NSArray *guesses = [[NSSpellChecker sharedSpellChecker] guessesForWordRange:NSMakeRange(0, [aNSStr length]) inString:aNSStr language:aLang inSpellDocumentWithTag:0];
504 (void) this; // avoid loplugin:staticmethods, the !MACOSX case uses 'this'
506 NSArray *guesses = [pChecker guessesForWordRange:NSMakeRange(0, [aNSStr length]) inString:aNSStr language:aLang];
508 count = [guesses count];
511 aStr.realloc( count );
512 OUString *pStr = aStr.getArray();
513 for (int ii=0; ii < count; ii++)
515 // if needed add: if (suglst[ii] == NULL) continue;
516 NSString* guess = [guesses objectAtIndex:ii];
517 OUString cvtwrd(reinterpret_cast<const sal_Unicode*>([guess cStringUsingEncoding:NSUnicodeStringEncoding]), static_cast<sal_Int32>([guess length]));
524 // now return an empty alternative for no suggestions or the list of alternatives if some found
525 rtl::Reference<SpellAlternatives> pAlt = new SpellAlternatives;
526 pAlt->SetWordLanguage( rWord, nLang );
527 pAlt->SetFailureType( SpellFailure::SPELLING_ERROR );
528 pAlt->SetAlternatives( aStr );
534 Reference< XSpellAlternatives > SAL_CALL
535 MacSpellChecker::spell( const OUString& rWord, const Locale& rLocale,
536 const css::uno::Sequence<PropertyValue>& rProperties )
538 MutexGuard aGuard( GetLinguMutex() );
540 if (rLocale == Locale() || !rWord.getLength())
543 if (!hasLocale( rLocale ))
546 Reference< XSpellAlternatives > xAlt;
547 if (!isValid( rWord, rLocale, rProperties ))
549 xAlt = GetProposals( rWord, rLocale );
555 MacSpellChecker::addLinguServiceEventListener(
556 const Reference< XLinguServiceEventListener >& rxLstnr )
558 MutexGuard aGuard( GetLinguMutex() );
561 if (!bDisposing && rxLstnr.is())
563 bRes = GetPropHelper().addLinguServiceEventListener( rxLstnr );
570 MacSpellChecker::removeLinguServiceEventListener(
571 const Reference< XLinguServiceEventListener >& rxLstnr )
573 MutexGuard aGuard( GetLinguMutex() );
576 if (!bDisposing && rxLstnr.is())
578 DBG_ASSERT( xPropHelper.is(), "xPropHelper non existent" );
579 bRes = GetPropHelper().removeLinguServiceEventListener( rxLstnr );
586 MacSpellChecker::getServiceDisplayName( const Locale& /*rLocale*/ )
588 MutexGuard aGuard( GetLinguMutex() );
589 return "macOS Spell Checker";
594 MacSpellChecker::initialize( const Sequence< Any >& rArguments )
596 MutexGuard aGuard( GetLinguMutex() );
598 if (!xPropHelper.is())
600 sal_Int32 nLen = rArguments.getLength();
603 Reference< XLinguProperties > xPropSet;
604 rArguments.getConstArray()[0] >>= xPropSet;
605 //rArguments.getConstArray()[1] >>= xDicList;
607 //! Pointer allows for access of the non-UNO functions.
608 //! And the reference to the UNO-functions while increasing
609 //! the ref-count and will implicitly free the memory
610 //! when the object is no longer used.
611 xPropHelper = new PropertyHelper_Spell( static_cast<XSpellChecker *>(this), xPropSet );
612 xPropHelper->AddAsPropListener();
615 OSL_FAIL( "wrong number of arguments in sequence" );
622 MacSpellChecker::dispose()
624 MutexGuard aGuard( GetLinguMutex() );
629 EventObject aEvtObj( static_cast<XSpellChecker *>(this) );
630 aEvtListeners.disposeAndClear( aEvtObj );
636 MacSpellChecker::addEventListener( const Reference< XEventListener >& rxListener )
638 MutexGuard aGuard( GetLinguMutex() );
640 if (!bDisposing && rxListener.is())
641 aEvtListeners.addInterface( rxListener );
646 MacSpellChecker::removeEventListener( const Reference< XEventListener >& rxListener )
648 MutexGuard aGuard( GetLinguMutex() );
650 if (!bDisposing && rxListener.is())
651 aEvtListeners.removeInterface( rxListener );
654 // Service specific part
655 OUString SAL_CALL MacSpellChecker::getImplementationName()
657 return "org.openoffice.lingu.MacOSXSpellChecker";
660 sal_Bool SAL_CALL MacSpellChecker::supportsService( const OUString& ServiceName )
662 return cppu::supportsService(this, ServiceName);
665 Sequence< OUString > SAL_CALL MacSpellChecker::getSupportedServiceNames()
667 return { SN_SPELLCHECKER };
670 extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
671 lingucomponent_MacSpellChecker_get_implementation(
672 css::uno::XComponentContext* , css::uno::Sequence<css::uno::Any> const&)
674 return cppu::acquire(new MacSpellChecker());
677 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */