language_mac.mm 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #include "spellcheck/platform/mac/language_mac.h"
  8. #include "base/platform/mac/base_utilities_mac.h"
  9. #import <NaturalLanguage/NLLanguageRecognizer.h>
  10. using Platform::Q2NSString;
  11. using Platform::NS2QString;
  12. namespace Platform::Language {
  13. LanguageId Recognize(QStringView text) {
  14. if (@available(macOS 10.14, *)) {
  15. constexpr auto kMaxHypotheses = 3;
  16. static auto r = [[NLLanguageRecognizer alloc] init];
  17. [r processString:Q2NSString(text)];
  18. const auto hypotheses =
  19. [r languageHypothesesWithMaximum:kMaxHypotheses];
  20. [r reset];
  21. auto maxProbability = 0.;
  22. auto language = NLLanguage(nil);
  23. for (NLLanguage lang in hypotheses) {
  24. const auto probability = [hypotheses[lang] floatValue];
  25. if (probability > maxProbability) {
  26. maxProbability = probability;
  27. language = lang;
  28. }
  29. }
  30. if (language) {
  31. return { QLocale(NS2QString(language)).language() };
  32. }
  33. }
  34. return {};
  35. }
  36. } // namespace Platform::Language