stringBundle.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Copyright (c) <2015-Present> Tzutalin
  2. # Copyright (C) 2013 MIT, Computer Science and Artificial Intelligence Laboratory. Bryan Russell, Antonio Torralba,
  3. # William T. Freeman. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
  4. # associated documentation files (the "Software"), to deal in the Software without restriction, including without
  5. # limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
  6. # Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  7. # The above copyright notice and this permission notice shall be included in all copies or substantial portions of
  8. # the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
  9. # NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  10. # SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  11. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  12. # THE SOFTWARE.
  13. #!/usr/bin/env python
  14. # -*- coding: utf-8 -*-
  15. import re
  16. import os
  17. import sys
  18. import locale
  19. from libs.ustr import ustr
  20. __dir__ = os.path.dirname(os.path.abspath(__file__)) # 获取本程序文件路径
  21. __dirpath__ = os.path.abspath(os.path.join(__dir__, '../resources/strings'))
  22. try:
  23. from PyQt5.QtCore import *
  24. except ImportError:
  25. if sys.version_info.major >= 3:
  26. import sip
  27. sip.setapi('QVariant', 2)
  28. from PyQt4.QtCore import *
  29. class StringBundle:
  30. __create_key = object()
  31. def __init__(self, create_key, localeStr):
  32. assert(create_key == StringBundle.__create_key), "StringBundle must be created using StringBundle.getBundle"
  33. self.idToMessage = {}
  34. paths = self.__createLookupFallbackList(localeStr)
  35. for path in paths:
  36. self.__loadBundle(path)
  37. @classmethod
  38. def getBundle(cls, localeStr=None):
  39. if localeStr is None:
  40. try:
  41. localeStr = locale.getlocale()[0] if locale.getlocale() and len(
  42. locale.getlocale()) > 0 else os.getenv('LANG')
  43. except:
  44. print('Invalid locale')
  45. localeStr = 'en'
  46. return StringBundle(cls.__create_key, localeStr)
  47. def getString(self, stringId):
  48. assert(stringId in self.idToMessage), "Missing string id : " + stringId
  49. return self.idToMessage[stringId]
  50. def __createLookupFallbackList(self, localeStr):
  51. resultPaths = []
  52. basePath = "\strings" if os.name == 'nt' else "/strings"
  53. resultPaths.append(basePath)
  54. if localeStr is not None:
  55. # Don't follow standard BCP47. Simple fallback
  56. tags = re.split('[^a-zA-Z]', localeStr)
  57. for tag in tags:
  58. lastPath = resultPaths[-1]
  59. resultPaths.append(lastPath + '-' + tag)
  60. resultPaths[-1] = __dirpath__ + resultPaths[-1] + ".properties"
  61. return resultPaths
  62. def __loadBundle(self, path):
  63. PROP_SEPERATOR = '='
  64. f = QFile(path)
  65. if f.exists():
  66. if f.open(QIODevice.ReadOnly | QFile.Text):
  67. text = QTextStream(f)
  68. text.setCodec("UTF-8")
  69. while not text.atEnd():
  70. line = ustr(text.readLine())
  71. key_value = line.split(PROP_SEPERATOR)
  72. key = key_value[0].strip()
  73. value = PROP_SEPERATOR.join(key_value[1:]).strip().strip('"')
  74. self.idToMessage[key] = value
  75. f.close()