intl.lua 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. local intl_dir = mp.get_script_directory() .. '/intl/'
  2. local locale = {}
  3. local cache = {}
  4. -- https://learn.microsoft.com/en-us/windows/apps/publish/publish-your-app/supported-languages?pivots=store-installer-msix#list-of-supported-languages
  5. function get_languages()
  6. local languages = {}
  7. for _, lang in ipairs(comma_split(options.languages)) do
  8. if (lang == 'slang') then
  9. local slang = mp.get_property_native('slang')
  10. if slang then
  11. itable_append(languages, slang)
  12. end
  13. else
  14. languages[#languages +1] = lang
  15. end
  16. end
  17. return languages
  18. end
  19. ---@param path string
  20. function get_locale_from_json(path)
  21. local expand_path = mp.command_native({'expand-path', path})
  22. local meta, meta_error = utils.file_info(expand_path)
  23. if not meta or not meta.is_file then
  24. return nil
  25. end
  26. local json_file = io.open(expand_path, 'r')
  27. if not json_file then
  28. return nil
  29. end
  30. local json = json_file:read('*all')
  31. json_file:close()
  32. local json_table = utils.parse_json(json)
  33. return json_table
  34. end
  35. ---@param text string
  36. function t(text, a)
  37. if not text then return '' end
  38. local key = text
  39. if a then key = key .. '|' .. a end
  40. if cache[key] then return cache[key] end
  41. cache[key] = string.format(locale[text] or text, a or '')
  42. return cache[key]
  43. end
  44. -- Load locales
  45. local languages = get_languages()
  46. for i = #languages, 1, -1 do
  47. lang = languages[i]
  48. if (lang:match('.json$')) then
  49. table_assign(locale, get_locale_from_json(lang))
  50. elseif (lang == 'en') then
  51. locale = {}
  52. else
  53. table_assign(locale, get_locale_from_json(intl_dir .. lang:lower() .. '.json'))
  54. end
  55. end
  56. return {t = t}