def __init__(self, text, dictionary): super(spellChecker, self).__init__() log.debug("Creating the SpellChecker object. Dictionary: %s" % (dictionary,)) self.active = True try: if config.app["app-settings"]["language"] == "system": log.debug("Using the system language") self.checker = SpellChecker(filters=[twitterFilter.TwitterFilter, tokenize.EmailFilter, tokenize.URLFilter]) else: log.debug("Using language: %s" % (languageHandler.getLanguage(),)) self.checker = SpellChecker(languageHandler.getLanguage(), filters=[twitterFilter.TwitterFilter, tokenize.EmailFilter, tokenize.URLFilter]) self.checker.set_text(text) except DictNotFoundError: log.exception("Dictionary for language %s not found." % (dictionary,)) wx_ui.dict_not_found_error() self.active = False if self.active == True: log.debug("Creating dialog...") self.dialog = wx_ui.spellCheckerDialog() widgetUtils.connect_event(self.dialog.ignore, widgetUtils.BUTTON_PRESSED, self.ignore) widgetUtils.connect_event(self.dialog.ignoreAll, widgetUtils.BUTTON_PRESSED, self.ignoreAll) widgetUtils.connect_event(self.dialog.replace, widgetUtils.BUTTON_PRESSED, self.replace) widgetUtils.connect_event(self.dialog.replaceAll, widgetUtils.BUTTON_PRESSED, self.replaceAll) self.check() self.dialog.get_response() self.fixed_text = self.checker.get_text()
def onFocus(self, *args,**kwargs): """ Function executed when the item in a list is selected. For this buffer it updates the date of posts in the list.""" post = self.session.db[self.name]["items"][self.tab.list.get_selected()] original_date = arrow.get(post["date"]) created_at = original_date.humanize(locale=languageHandler.getLanguage()) self.tab.list.list.SetStringItem(self.tab.list.get_selected(), 2, created_at)
def get_comments(self): """ Get comments and insert them in a list.""" user = self.post[self.user_identifier] id = self.post[self.post_identifier] self.comments = self.session.vk.client.wall.getComments(owner_id=user, post_id=id, need_likes=1, count=100, extended=1, preview_length=0) comments_ = [] for i in self.comments["items"]: from_ = get_user(i["from_id"], self.comments["profiles"]) if i.has_key("reply_to_user"): extra_info = get_user(i["reply_to_user"], self.comments["profiles"]) from_ = _(u"{0} > {1}").format(from_, extra_info) # As we set the comment reply properly in the from_ field, let's remove the first username from here if it exists. fixed_text = re.sub("^\[id\d+\|\D+\], ", "", i["text"]) if len(fixed_text) > 140: text = fixed_text[:141] else: text = fixed_text original_date = arrow.get(i["date"]) created_at = original_date.humanize(locale=languageHandler.getLanguage()) likes = str(i["likes"]["count"]) comments_.append((from_, text, created_at, likes)) try: self.dialog.insert_comments(comments_) except wx.PyDeadObjectError: pass
def checkForUpdate(auto=False): """Check for an updated version of NVDA. This will block, so it generally shouldn't be called from the main thread. @param auto: Whether this is an automatic check for updates. @type auto: bool @return: Information about the update or C{None} if there is no update. @rtype: dict @raise RuntimeError: If there is an error checking for an update. """ winVer = sys.getwindowsversion() params = { "autoCheck": auto, "version": versionInfo.version, "versionType": versionInfo.updateVersionType, "osVersion": "{v.major}.{v.minor}.{v.build} {v.service_pack}".format(v=winVer), "x64": os.environ.get("PROCESSOR_ARCHITEW6432") == "AMD64", "language": languageHandler.getLanguage(), "installed": config.isInstalledCopy(), } res = urllib.urlopen("%s?%s" % (CHECK_URL, urllib.urlencode(params))) if res.code != 200: raise RuntimeError("Checking for update failed with code %d" % res.code) info = {} for line in res: line = line.rstrip() try: key, val = line.split(": ", 1) except ValueError: raise RuntimeError("Error in update check output") info[key] = val if not info: return None return info
def compose_followers_list(tweet, db): original_date = arrow.get(tweet["created_at"], "ddd MMM D H:m:s Z YYYY", locale="en") if config.main["general"]["relative_times"] == True: ts = original_date.humanize(locale=languageHandler.getLanguage()) else: ts = original_date.replace(seconds=db.settings["utc_offset"]).format(_(u"dddd, MMMM D, YYYY H:m:s"), locale=languageHandler.getLanguage()) if tweet.has_key("status"): if len(tweet["status"]) > 4: original_date2 = arrow.get(tweet["status"]["created_at"], "ddd MMM D H:m:s Z YYYY", locale="en") if config.main["general"]["relative_times"]: ts2 = original_date2.humanize(locale=languageHandler.getLanguage()) else: ts2 = original_date2.replace(seconds=db.settings["utc_offset"]).format(_(u"dddd, MMMM D, YYYY H:m:s"), locale=languageHandler.getLanguage()) else: ts2 = _("Unavailable") return [_(u"%s (@%s). %s followers, %s friends, %s tweets. Last tweet on %s. Joined Twitter on %s") % (tweet["name"], tweet["screen_name"], tweet["followers_count"], tweet["friends_count"], tweet["statuses_count"], ts2, ts)]
def compose_tweet(tweet, db, relative_times): """ It receives a tweet and returns a list with the user, text for the tweet or message, date and the client where user is.""" if system == "Windows": original_date = arrow.get(tweet["created_at"], "ddd MMM DD H:m:s Z YYYY", locale="en") if relative_times == True: ts = original_date.humanize(locale=languageHandler.getLanguage()) else: ts = original_date.replace(seconds=db["utc_offset"]).format(_(u"dddd, MMMM D, YYYY H:m:s"), locale=languageHandler.getLanguage()) else: ts = tweet["created_at"] if tweet.has_key("message"): value = "message" else: value = "text" text = StripChars(tweet[value]) if tweet.has_key("sender"): source = "DM" if db["user_name"] == tweet["sender"]["screen_name"]: user = _(u"Dm to %s ") % (tweet["recipient"]["name"],) else: user = tweet["sender"]["name"] elif tweet.has_key("user"): user = tweet["user"]["name"] source = re.sub(r"(?s)<.*?>", "", tweet["source"]) try: text = "rt @%s: %s" % (tweet["retweeted_status"]["user"]["screen_name"], StripChars(tweet["retweeted_status"]["text"])) except KeyError: pass #text = "%s" % (StripChars(tweet["text"])) if text[-1] in chars: text=text+"." urls = utils.find_urls_in_text(text) for url in range(0, len(urls)): try: text = text.replace(urls[url], tweet["entities"]["urls"][url]["expanded_url"]) except IndexError: pass if config.app['app-settings']['handle_longtweets']: pass # return [user+", ", text, ts+", ", source] return [user+", ", text, ts+", ", source]
def getDocFilePath(self, fileName=None): """Get the path to a documentation file for this add-on. The file should be located in C{doc\lang\file} inside the add-on, where C{lang} is the language code and C{file} is the requested file name. Failing that, the language without country is tried. English is tried as a last resort. An add-on can specify a default documentation file name via the docFileName parameter in its manifest. @param fileName: The requested file name or C{None} for the add-on's default. @type fileName: basestring @return: The path to the requested file or C{None} if it wasn't found. @rtype: basestring """ if not fileName: fileName = self.manifest["docFileName"] if not fileName: return None docRoot = os.path.join(self.path, "doc") lang = languageHandler.getLanguage() langs = [lang] if "_" in lang: lang = lang.split("_", 1)[0] langs.append(lang) if lang != "en": langs.append("en") for lang in langs: docFile = os.path.join(docRoot, lang, fileName) if os.path.isfile(docFile): return docFile return None
def process_usernames(self, data): """ processes user IDS and saves them in a local storage system. Every function wich needs to convert from an ID to user or community name will have to call the get_user_name function in this session object. Every function that needs to save a set ot user ids for a future use needs to pass a data dictionary with a profiles key being a list of user objects. For russian, it gets the genitive case of every name for future use.""" log.debug("Adding usernames to the local database...") ids = "" for i in data["profiles"]: if self.db["users"].has_key(i["id"]) == False: self.db["users"][i["id"]] = dict(nom=u"{0} {1}".format(i["first_name"], i["last_name"])) ids = ids + "{0},".format(i["id"],) gids = "" for i in data["groups"]: self.db["groups"][i["id"]] = dict(nom=i["name"]) gids = "{0},".format(i["id"],) if not "ru" in languageHandler.getLanguage(): return if ids != "": users_genitive = self.vk.client.users.get(user_ids=ids, fields="first_name, last_name", name_case="gen") users_instrumental = self.vk.client.users.get(user_ids=ids, fields="first_name, last_name", name_case="ins") for i in users_genitive: if self.db["users"].has_key(i["id"]): self.db["users"][i["id"]]["gen"] = u"{0} {1}".format(i["first_name"], i["last_name"]) for i in users_instrumental: if self.db["users"].has_key(i["id"]): self.db["users"][i["id"]]["ins"] = u"{0} {1}".format(i["first_name"], i["last_name"])
def speakSpelling(text,locale=None,useCharacterDescriptions=False): global beenCanceled, _speakSpellingGenID import speechViewer if speechViewer.isActive: speechViewer.appendText(text) if speechMode==speechMode_off: return elif speechMode==speechMode_beeps: tones.beep(config.conf["speech"]["beepSpeechModePitch"],speechMode_beeps_ms) return if isPaused: cancelSpeech() beenCanceled=False from languageHandler import getLanguage locale=getLanguage() if not isinstance(text,basestring) or len(text)==0: return getSynth().speakText(processSymbol("")) if not text.isspace(): text=text.rstrip() gen=_speakSpellingGen(text,locale,useCharacterDescriptions) try: # Speak the first character before this function returns. next(gen) except StopIteration: return _speakSpellingGenID=queueHandler.registerGeneratorObject(gen)
def getInitialLanguage(): """Get the language to use the first time UWP OCR is used. The NVDA interface language is used if a matching OCR language is available. Otherwise, this falls back to the first available language. """ nvdaLang = languageHandler.getLanguage() ocrLangs = getLanguages() return _getInitialLanguage(nvdaLang, ocrLangs)
def compose_person(status, session): if status.has_key("last_seen"): original_date = arrow.get(status["last_seen"]["time"]) # Translators: This is the date of last seen last_seen = _(u"{0}").format(original_date.humanize(locale=languageHandler.getLanguage()),) elif status.has_key("last_seen") == False and status.has_key("deactivated"): last_seen = _(u"Account deactivated") return [u"{0} {1}".format(status["first_name"], status["last_name"]), last_seen]
def getTranslationsInstance(self, domain='nvda'): """ Gets the gettext translation instance for this addon. <addon-path<\locale will be used to find .mo files, if exists. If a translation file is not found the default fallback null translation is returned. @param domain: the tranlation domain to retrieve. The 'nvda' default should be used in most cases. @returns: the gettext translation class. """ localedir = os.path.join(self.path, "locale") return gettext.translation(domain, localedir=localedir, languages=[languageHandler.getLanguage()], fallback=True)
def checkForUpdate(auto=False): """Check for an updated version of NVDA. This will block, so it generally shouldn't be called from the main thread. @param auto: Whether this is an automatic check for updates. @type auto: bool @return: Information about the update or C{None} if there is no update. @rtype: dict @raise RuntimeError: If there is an error checking for an update. """ allowUsageStats=config.conf["update"]['allowUsageStats'] params = { "autoCheck": auto, "allowUsageStats":allowUsageStats, "version": versionInfo.version, "versionType": versionInfo.updateVersionType, "osVersion": winVersion.winVersionText, "x64": os.environ.get("PROCESSOR_ARCHITEW6432") == "AMD64", } if auto and allowUsageStats: synthDriverClass=speech.getSynth().__class__ brailleDisplayClass=braille.handler.display.__class__ if braille.handler else None # Following are parameters sent purely for stats gathering. # If new parameters are added here, they must be documented in the userGuide for transparency. extraParams={ "language": languageHandler.getLanguage(), "installed": config.isInstalledCopy(), "synthDriver":getQualifiedDriverClassNameForStats(synthDriverClass) if synthDriverClass else None, "brailleDisplay":getQualifiedDriverClassNameForStats(brailleDisplayClass) if brailleDisplayClass else None, "outputBrailleTable":config.conf['braille']['translationTable'] if brailleDisplayClass else None, } params.update(extraParams) url = "%s?%s" % (CHECK_URL, urllib.urlencode(params)) try: res = urllib.urlopen(url) except IOError as e: if isinstance(e.strerror, ssl.SSLError) and e.strerror.reason == "CERTIFICATE_VERIFY_FAILED": # #4803: Windows fetches trusted root certificates on demand. # Python doesn't trigger this fetch (PythonIssue:20916), so try it ourselves _updateWindowsRootCertificates() # and then retry the update check. res = urllib.urlopen(url) else: raise if res.code != 200: raise RuntimeError("Checking for update failed with code %d" % res.code) info = {} for line in res: line = line.rstrip() try: key, val = line.split(": ", 1) except ValueError: raise RuntimeError("Error in update check output") info[key] = val if not info: return None return info
def loadLocaleGestureMap(self): self.localeGestureMap.clear() lang = languageHandler.getLanguage() try: self.localeGestureMap.load(os.path.join("locale", lang, "gestures.ini")) except IOError: try: self.localeGestureMap.load(os.path.join("locale", lang.split('_')[0], "gestures.ini")) except IOError: log.debugWarning("No locale gesture map for language %s" % lang)
def _translatedManifestPaths(lang=None, forBundle=False): if lang is None: lang = languageHandler.getLanguage() # can't rely on default keyword arguments here. langs=[lang] if '_' in lang: langs.append(lang.split('_')[0]) if lang!='en' and not lang.startswith('en_'): langs.append('en') sep = "/" if forBundle else os.path.sep return [sep.join(("locale", lang, MANIFEST_FILENAME)) for lang in langs]
def onFocus(self, *args, **kwargs): tweet = self.get_tweet() if platform.system() == "Windows" and self.session.settings["general"]["relative_times"] == True: # fix this: original_date = arrow.get(self.session.db[self.name][self.buffer.list.get_selected()]["created_at"], "ddd MMM D H:m:s Z YYYY", locale="en") ts = original_date.humanize(locale=languageHandler.getLanguage()) self.buffer.list.list.SetStringItem(self.buffer.list.get_selected(), 2, ts) if utils.is_audio(tweet): self.session.sound.play("audio.ogg") if utils.is_geocoded(tweet): self.session.sound.play("geo.ogg")
def __init__(self): self.__lib=load_tts_library() self.__cancel_flag=threading.Event() self.__player=audio_player(self.__cancel_flag) self.__sample_rate_callback=sample_rate_callback(self.__lib,self.__player) self.__c_sample_rate_callback=RHVoice_callback_types.set_sample_rate(self.__sample_rate_callback) self.__speech_callback=speech_callback(self.__lib,self.__player,self.__cancel_flag) self.__c_speech_callback=RHVoice_callback_types.play_speech(self.__speech_callback) self.__mark_callback=mark_callback(self.__lib) self.__c_mark_callback=RHVoice_callback_types.process_mark(self.__mark_callback) resource_paths=[os.path.join(addon.path,"data").encode("UTF-8") for addon in addonHandler.getRunningAddons() if (addon.name.startswith("RHVoice-language") or addon.name.startswith("RHVoice-voice"))] c_resource_paths=(c_char_p*(len(resource_paths)+1))(*(resource_paths+[None])) init_params=RHVoice_init_params(None, config_path.encode("utf-8"), c_resource_paths, RHVoice_callbacks(self.__c_sample_rate_callback, self.__c_speech_callback, self.__c_mark_callback, cast(None,RHVoice_callback_types.word_starts), cast(None,RHVoice_callback_types.word_ends), cast(None,RHVoice_callback_types.sentence_starts), cast(None,RHVoice_callback_types.sentence_ends), cast(None,RHVoice_callback_types.play_audio)), 0) self.__tts_engine=self.__lib.RHVoice_new_tts_engine(byref(init_params)) if not self.__tts_engine: raise RuntimeError("RHVoice: initialization error") nvda_language=languageHandler.getLanguage().split("_")[0] number_of_voices=self.__lib.RHVoice_get_number_of_voices(self.__tts_engine) native_voices=self.__lib.RHVoice_get_voices(self.__tts_engine) self.__voice_languages=dict() self.__languages=set() for i in range(number_of_voices): native_voice=native_voices[i] self.__voice_languages[native_voice.name.decode("utf-8")]=native_voice.language.decode("utf-8") self.__languages.add(native_voice.language.decode("utf-8")) self.__profile=None self.__profiles=list() number_of_profiles=self.__lib.RHVoice_get_number_of_voice_profiles(self.__tts_engine) native_profile_names=self.__lib.RHVoice_get_voice_profiles(self.__tts_engine) for i in range(number_of_profiles): name=native_profile_names[i].decode("utf-8") self.__profiles.append(name) if (self.__profile is None) and (nvda_language==self.__voice_languages[name.split("+")[0]]): self.__profile=name if self.__profile is None: self.__profile=self.__profiles[0] self.__rate=50 self.__pitch=50 self.__volume=50 self.__tts_queue=Queue.Queue() self.__tts_thread=TTSThread(self.__tts_queue) self.__tts_thread.start() log.info("Using RHVoice version {}".format(self.__lib.RHVoice_get_version()))
def __init__(self): _festival.initialize() #log.info("Using festival version %s" % _festival.info()) lang=languageHandler.getLanguage() #_festival.setVoiceByLanguage(lang) self._language=lang #self._variantDict=_festival.getVariantDict() #self.variant="max" self.rate=30 self.pitch=40 self.inflection=75
def __init__(self): _espeak.initialize() log.info("Using eSpeak NG version %s" % _espeak.info()) lang=languageHandler.getLanguage() _espeak.setVoiceByLanguage(lang) self._language=lang self._variantDict=_espeak.getVariantDict() self.variant="max" self.rate=30 self.pitch=40 self.inflection=75
def __init__(self): self.app = wx.App() self.lc = wx.Locale() lang=languageHandler.getLanguage() wxLang=self.lc.FindLanguageInfo(lang) if not wxLang and '_' in lang: wxLang=self.lc.FindLanguageInfo(lang.split('_')[0]) if hasattr(sys,'frozen'): self.lc.AddCatalogLookupPathPrefix(paths.app_path("locales")) if wxLang: self.lc.Init(wxLang.Language)
def compose_status(status, session): user = session.get_user_name(status["from_id"]) message = "" original_date = arrow.get(status["date"]) created_at = original_date.humanize(locale=languageHandler.getLanguage()) if status["post_type"] == "post": message += add_text(status) if status.has_key("attachment") and len(status["attachment"]) > 0: message += add_attachment(status["attachment"]) if message == "": message = "no description available" return [user, message, created_at]
def compose_followers_list(tweet, db, relative_times=True): if system == "Windows": original_date = arrow.get(tweet["created_at"], "ddd MMM D H:m:s Z YYYY", locale="en") if relative_times == True: ts = original_date.humanize(locale=languageHandler.getLanguage()) else: ts = original_date.replace(seconds=db["utc_offset"]).format(_(u"dddd, MMMM D, YYYY H:m:s"), locale=languageHandler.getLanguage()) else: ts = tweet["created_at"] if tweet.has_key("status"): if len(tweet["status"]) > 4 and system == "Windows": original_date2 = arrow.get(tweet["status"]["created_at"], "ddd MMM D H:m:s Z YYYY", locale="en") if relative_times: ts2 = original_date2.humanize(locale=languageHandler.getLanguage()) else: ts2 = original_date2.replace(seconds=db["utc_offset"]).format(_(u"dddd, MMMM D, YYYY H:m:s"), locale=languageHandler.getLanguage()) else: ts2 = _("Unavailable") else: ts2 = _("Unavailable") return [_(u"%s (@%s). %s followers, %s friends, %s tweets. Last tweeted %s. Joined Twitter %s") % (tweet["name"], tweet["screen_name"], tweet["followers_count"], tweet["friends_count"], tweet["statuses_count"], ts2, ts)]
def __init__(self, session, comment_object): super(comment, self).__init__() self.session = session self.comment = comment_object self.dialog = postDialogs.comment() from_ = self.comment["from"]["name"] message = self.comment["message"] original_date = arrow.get(self.comment["created_time"], "YYYY-MM-DTHH:m:sZ", locale="en") created_at = original_date.humanize(locale=languageHandler.getLanguage()) self.dialog.set_post(message) self.dialog.set_title(_(u"Comment from {0}").format(from_,)) widgetUtils.connect_event(self.dialog.like, widgetUtils.BUTTON_PRESSED, self.post_like) call_threaded(self.get_likes)
def eciNew(): global avLangs eciCheck() eci = windll.LoadLibrary(eciPath) b=c_int() eci.eciGetAvailableLanguages(0,byref(b)) avLangs=(c_int*b.value)() eci.eciGetAvailableLanguages(byref(avLangs),byref(b)) if 'eci' in config.conf['speech'] and config.conf['speech']['eci']['voice'] != '': handle=eci.eciNewEx(langs[config.conf['speech']['eci']['voice']][0]) else: handle=eci.eciNewEx(langs[getVoiceByLanguage(languageHandler.getLanguage())][0]) for i in (rate, pitch, vlm, fluctuation): vparams[i] = eci.eciGetVoiceParam(handle, 0, i) return eci,handle
def get_comments(self): self.comments = self.session.fb.client.get_connections(id=self.post["id"], connection_name="comments", filter="stream") comments = [] for i in self.comments["data"]: from_ = i["from"]["name"] if len(i["message"]) > 100: comment = i["message"][:100] else: comment = i["message"] original_date = arrow.get(i["created_time"], "YYYY-MM-DTHH:m:sZ", locale="en") created_at = original_date.humanize(locale=languageHandler.getLanguage()) likes = str(i["like_count"]) comments.append([from_, comment, created_at, likes,]) self.dialog.insert_comments(comments)
def getDocFolder(addonDir=_addonDir): langs = [languageHandler.getLanguage(), "en"] for lang in langs: docFolder = os.path.join(addonDir, "doc", lang) if os.path.isdir(docFolder): return docFolder if "_" in lang: tryLang = lang.split("_")[0] docFolder = os.path.join(addonDir, "doc", tryLang) if os.path.isdir(docFolder): return docFolder if tryLang == "en": break if lang == "en": break return None
def compose_status(status, session): user = session.get_user_name(status["from_id"], "nom") if status.has_key("copy_history"): user = _(u"{0} has shared the {1}'s post").format(user, session.get_user_name(status["copy_history"][0]["owner_id"])) message = "" original_date = arrow.get(status["date"]) created_at = original_date.humanize(locale=languageHandler.getLanguage()) if status.has_key("copy_owner_id"): user = _(u"{0} has shared the {1}'s post").format(user, session.get_user_name(status["copy_owner_id"])) if status["post_type"] == "post" or status["post_type"] == "copy": message += add_text(status) if status.has_key("attachment") and len(status["attachment"]) > 0: message += add_attachment(status["attachment"]) if message == "": message = "no description available" return [user, message, created_at]
def __init__(self, text, dictionary): super(spellCheckerDialog, self).__init__(None, 1) try: if config.main["general"]["language"] == "system": self.checker = SpellChecker() else: self.checker = SpellChecker(languageHandler.getLanguage()) self.checker.set_text(text) except DictNotFoundError: wx.MessageDialog(None, _(u"A bug has happened. There are no dictionaries available for the selected language in TW Blue"), _(u"Error"), wx.ICON_ERROR).ShowModal() self.Destroy() panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) word = wx.StaticText(panel, -1, _(u"Mis-spelled word")) self.word = wx.TextCtrl(panel, -1) wordBox = wx.BoxSizer(wx.HORIZONTAL) wordBox.Add(word) wordBox.Add(self.word) context = wx.StaticText(panel, -1, _(u"Context")) self.context = wx.TextCtrl(panel, -1) contextBox = wx.BoxSizer(wx.HORIZONTAL) contextBox.Add(context) contextBox.Add(self.context) suggest = wx.StaticText(panel, -1, _(u"Suggestions")) self.suggestions = wx.ListBox(panel, -1, choices=[], style=wx.LB_SINGLE) suggestionsBox = wx.BoxSizer(wx.HORIZONTAL) suggestionsBox.Add(suggest) suggestionsBox.Add(self.suggestions) ignore = wx.Button(panel, -1, _(u"Ignore")) self.Bind(wx.EVT_BUTTON, self.onIgnore, ignore) ignoreAll = wx.Button(panel, -1, _(u"Ignore all")) self.Bind(wx.EVT_BUTTON, self.onIgnoreAll, ignoreAll) replace = wx.Button(panel, -1, _(u"Replace")) self.Bind(wx.EVT_BUTTON, self.onReplace, replace) replaceAll = wx.Button(panel, -1, _(u"Replace all")) self.Bind(wx.EVT_BUTTON, self.onReplaceAll, replaceAll) close = wx.Button(panel, wx.ID_CANCEL) btnBox = wx.BoxSizer(wx.HORIZONTAL) btnBox.Add(ignore) btnBox.Add(ignoreAll) btnBox.Add(replace) btnBox.Add(replaceAll) btnBox.Add(close) sizer.Add(wordBox) sizer.Add(contextBox) sizer.Add(suggestionsBox) sizer.Add(btnBox) panel.SetSizerAndFit(sizer) self.check()
def compose_new(status, session): """ This method is used to compose an item of the news feed.""" user = session.get_user_name(status["source_id"], case_name="nom") if status.has_key("copy_history"): user = _(u"{0} has shared the {1}'s post").format(user, session.get_user_name(status["copy_history"][0]["owner_id"])) message = "" original_date = arrow.get(status["date"]) created_at = original_date.humanize(locale=languageHandler.getLanguage()) if status["type"] == "post": message += add_text(status) if status.has_key("attachment") and len(status["attachment"]) > 0: message += add_attachment(status["attachment"]) if message == "": message = "no description available" elif status["type"] == "audio": # removes deleted audios. status["audio"] = clean_audio(status["audio"]) if status["audio"]["count"] == 1: message = _(u"{0} has added an audio: {1}").format(user, u", ".join(compose_audio(status["audio"]["items"][0], session)),) else: prem = "" for i in xrange(0, status["audio"]["count"]): composed_audio = compose_audio(status["audio"]["items"][i], session) prem += u"{0} - {1}, ".format(composed_audio[0], composed_audio[1]) message = _(u"{0} has added {1} audios: {2}").format(user, status["audio"]["count"], prem) elif status["type"] == "friend": msg_users = u"" if status.has_key("friends"): for i in status["friends"]["items"]: msg_users = msg_users + u"{0}, ".format(session.get_user_name(i["user_id"], "nom")) else: print status.keys() message = _(u"{0} hadded friends: {1}").format(user, msg_users) elif status["type"] == "video": if status["video"]["count"] == 1: message = _(u"{0} has added a video: {1}").format(user, u", ".join(compose_video(status["video"]["items"][0], session)),) else: prem = "" for i in xrange(0, status["video"]["count"]): composed_video = compose_video(status["video"]["items"][i], session) prem += u"{0} - {1}, ".format(composed_video[0], composed_video[1]) message = _(u"{0} has added {1} videos: {2}").format(user, status["video"]["count"], prem) else: if status["type"] != "post": print status return [user, message, created_at]
def onFocus(self, ev): if self.db.settings[self.name_buffer][self.list.get_selected()].has_key("retweeted_status"): tweet = self.db.settings[self.name_buffer][self.list.get_selected()]["retweeted_status"] else: tweet = self.db.settings[self.name_buffer][self.list.get_selected()] if config.main["general"]["relative_times"] == True: # On windows we need only put the new date on the column, but under linux and mac it isn't possible. if self.system == "Windows": # self.db.settings[self.name_buffer][self.list.get_selected()]["created_at"] = tweet["created_at"].replace("+0000 ", "") original_date = arrow.get(self.db.settings[self.name_buffer][self.list.get_selected()]["created_at"], "ddd MMM D H:m:s Z YYYY", locale="en") # original_date = datetime.datetime.strptime(self.db.settings[self.name_buffer][self.list.get_selected()]["created_at"], "%a %b %d %H:%M:%S +0000 %Y") # date = original_date-datetime.timedelta(seconds=-self.db.settings["utc_offset"]) ts = original_date.humanize(locale=languageHandler.getLanguage()) # prettydate(original_date) self.list.list.SetStringItem(self.list.get_selected(), 2, ts) else: self.list.list.SetString(self.list.get_selected(), " ".join(self.compose_function(self.db.settings[self.name_buffer][self.list.get_selected()], self.db))) if twitter.utils.is_audio(tweet): sound.player.play("audio.ogg", False) if twitter.utils.is_geocoded(tweet): sound.player.play("geo.ogg", False)
def getDocFilePath(fileName, installDir): rootPath = os.path.join(installDir, 'documentation') lang = languageHandler.getLanguage() tryLangs = [lang] if "_" in lang: # This locale has a sub-locale, but documentation might not exist for the sub-locale, so try stripping it. tryLangs.append(lang.split("_")[0]) # If all else fails, use English. tryLangs.append("en") fileName, fileExt = os.path.splitext(fileName) for tryLang in tryLangs: tryDir = os.path.join(rootPath, tryLang) if not os.path.isdir(tryDir): continue # Some out of date translations might include .txt files which are now .html files in newer translations. # Therefore, ignore the extension and try both .html and .txt. for tryExt in ("html", "txt"): tryPath = os.path.join(tryDir, "%s.%s" % (fileName, tryExt)) if os.path.isfile(tryPath): return tryPath
def getDocFilePath(fileName, localized=True): if not getDocFilePath.rootPath: if hasattr(sys, "frozen"): getDocFilePath.rootPath = os.path.join(globalVars.appDir, "documentation") else: getDocFilePath.rootPath = os.path.join(globalVars.appDir, "..", "user_docs") if localized: lang = languageHandler.getLanguage() tryLangs = [lang] if "_" in lang: # This locale has a sub-locale, but documentation might not exist for the sub-locale, so try stripping it. tryLangs.append(lang.split("_")[0]) # If all else fails, use English. tryLangs.append("en") fileName, fileExt = os.path.splitext(fileName) for tryLang in tryLangs: tryDir = os.path.join(getDocFilePath.rootPath, tryLang) if not os.path.isdir(tryDir): continue # Some out of date translations might include .txt files which are now .html files in newer translations. # Therefore, ignore the extension and try both .html and .txt. for tryExt in ("html", "txt"): tryPath = os.path.join(tryDir, f"{fileName}.{tryExt}") if os.path.isfile(tryPath): return tryPath return None else: # Not localized. if not hasattr(sys, "frozen") and fileName in ("copying.txt", "contributors.txt"): # If running from source, these two files are in the root dir. return os.path.join(globalVars.appDir, "..", fileName) else: return os.path.join(getDocFilePath.rootPath, fileName)
#Copyright (C) 2020 Eugene Poplavsky <*****@*****.**> #This file is covered by the GNU General Public License. #See the file LICENSE.txt for more details. import webbrowser import wx import gui import addonHandler from languageHandler import getLanguage from versionInfo import version_year, version_major addonHandler.initTranslation() year = 2018 major = 3 lang = getLanguage().split("_")[0] if lang != "en" and lang != "ru": lang = "en" donations_url = "https://jnsoft.ru/{lang}/articles/nvda/extendedTotalCmd/donation.php".format( lang=lang) def onInstall(): if (version_year, version_major) < (year, major): gui.messageBox(_( "This version of NVDA is incompatible. To install the add-on, NVDA version {year}.{major} or higher is required. Please update NVDA or download an older version of the add-on here: \n{link}" ).format( year=year, major=major, link="https://github.com/jawhien/extendedTotalCmd/releases/tag/2.5" ),
def getFeedLanguage(self): try: return self._main.find(self.buildTag("language", self.ns)).text except Exception: return languageHandler.getLanguage().replace("_", "-")
def main(): """NVDA's core main loop. This initializes all modules such as audio, IAccessible, keyboard, mouse, and GUI. Then it initialises the wx application object and installs the core pump timer, which checks the queues and executes functions every 1 ms. Finally, it starts the wx main loop. """ log.debug("Core starting") import config if not globalVars.appArgs.configPath: globalVars.appArgs.configPath=config.getUserDefaultConfigPath(useInstalledPathIfExists=globalVars.appArgs.launcher) #Initialize the config path (make sure it exists) config.initConfigPath() log.info("Config dir: %s"%os.path.abspath(globalVars.appArgs.configPath)) log.debug("loading config") import config config.load() if not globalVars.appArgs.minimal: try: nvwave.playWaveFile("waves\\start.wav") except: pass logHandler.setLogLevelFromConfig() try: lang = config.conf["general"]["language"] import languageHandler log.debug("setting language to %s"%lang) languageHandler.setLanguage(lang) except: log.warning("Could not set language to %s"%lang) import versionInfo log.info("NVDA version %s" % versionInfo.version) log.info("Using Windows version %r" % (sys.getwindowsversion(),)) log.info("Using Python version %s"%sys.version) log.info("Using comtypes version %s"%comtypes.__version__) # Set a reasonable timeout for any socket connections NVDA makes. import socket socket.setdefaulttimeout(10) log.debug("Initializing addons system.") addonHandler.initialize() import appModuleHandler log.debug("Initializing appModule Handler") appModuleHandler.initialize() import NVDAHelper log.debug("Initializing NVDAHelper") NVDAHelper.initialize() import speechDictHandler log.debug("Speech Dictionary processing") speechDictHandler.initialize() import speech log.debug("Initializing speech") speech.initialize() if not globalVars.appArgs.minimal and (time.time()-globalVars.startTime)>5: log.debugWarning("Slow starting core (%.2f sec)" % (time.time()-globalVars.startTime)) # Translators: This is spoken when NVDA is starting. speech.speakMessage(_("Loading NVDA. Please wait...")) import wx log.info("Using wx version %s"%wx.version()) app = wx.App(redirect=False) # HACK: wx currently raises spurious assertion failures when a timer is stopped but there is already an event in the queue for that timer. # Unfortunately, these assertion exceptions are raised in the middle of other code, which causes problems. # Therefore, disable assertions for now. app.SetAssertMode(wx.PYAPP_ASSERT_SUPPRESS) # We do support QueryEndSession events, but we don't want to do anything for them. app.Bind(wx.EVT_QUERY_END_SESSION, lambda evt: None) def onEndSession(evt): # NVDA will be terminated as soon as this function returns, so save configuration if appropriate. config.saveOnExit() speech.cancelSpeech() if not globalVars.appArgs.minimal: try: nvwave.playWaveFile("waves\\exit.wav",async=False) except: pass log.info("Windows session ending") app.Bind(wx.EVT_END_SESSION, onEndSession) import braille log.debug("Initializing braille") braille.initialize() log.debug("Initializing braille input") import brailleInput brailleInput.initialize() import displayModel log.debug("Initializing displayModel") displayModel.initialize() log.debug("Initializing GUI") import gui gui.initialize() # initialize wxpython localization support locale = wx.Locale() lang=languageHandler.getLanguage() if '_' in lang: wxLang=lang.split('_')[0] else: wxLang=lang if hasattr(sys,'frozen'): locale.AddCatalogLookupPathPrefix(os.path.join(os.getcwdu(),"locale")) try: locale.Init(lang,wxLang) except: pass import api import winUser import NVDAObjects.window desktopObject=NVDAObjects.window.Window(windowHandle=winUser.getDesktopWindow()) api.setDesktopObject(desktopObject) api.setFocusObject(desktopObject) api.setNavigatorObject(desktopObject) api.setMouseObject(desktopObject) import JABHandler log.debug("initializing Java Access Bridge support") try: JABHandler.initialize() except NotImplementedError: log.warning("Java Access Bridge not available") except: log.error("Error initializing Java Access Bridge support", exc_info=True) import winConsoleHandler log.debug("Initializing winConsole support") winConsoleHandler.initialize() import UIAHandler log.debug("Initializing UIA support") try: UIAHandler.initialize() except NotImplementedError: log.warning("UIA not available") except: log.error("Error initializing UIA support", exc_info=True) import IAccessibleHandler log.debug("Initializing IAccessible support") IAccessibleHandler.initialize() log.debug("Initializing input core") import inputCore inputCore.initialize() import keyboardHandler log.debug("Initializing keyboard handler") keyboardHandler.initialize() import mouseHandler log.debug("initializing mouse handler") mouseHandler.initialize() import touchHandler log.debug("Initializing touchHandler") try: touchHandler.initialize() except NotImplementedError: pass import globalPluginHandler log.debug("Initializing global plugin handler") globalPluginHandler.initialize() if globalVars.appArgs.install: import wx import gui.installerGui wx.CallAfter(gui.installerGui.doSilentInstall) elif not globalVars.appArgs.minimal: try: # Translators: This is shown on a braille display (if one is connected) when NVDA starts. braille.handler.message(_("NVDA started")) except: log.error("", exc_info=True) if globalVars.appArgs.launcher: gui.LauncherDialog.run() # LauncherDialog will call doStartupDialogs() afterwards if required. else: wx.CallAfter(doStartupDialogs) import queueHandler # Queue the handling of initial focus, # as API handlers might need to be pumped to get the first focus event. queueHandler.queueFunction(queueHandler.eventQueue, _setInitialFocus) import watchdog import baseObject class CorePump(wx.Timer): "Checks the queues and executes functions." def __init__(self,*args,**kwargs): log.debug("Core pump starting") super(CorePump,self).__init__(*args,**kwargs) def Notify(self): try: JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() braille.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.alive() log.debug("starting core pump") pump = CorePump() pump.Start(1) log.debug("Initializing watchdog") watchdog.initialize() try: import updateCheck except RuntimeError: updateCheck=None log.debug("Update checking not supported") else: log.debug("initializing updateCheck") updateCheck.initialize() log.info("NVDA initialized") log.debug("entering wx application main loop") app.MainLoop() log.info("Exiting") if updateCheck: log.debug("Terminating updateCheck") updateCheck.terminate() log.debug("Terminating watchdog") watchdog.terminate() log.debug("Terminating global plugin handler") globalPluginHandler.terminate() log.debug("Terminating GUI") gui.terminate() config.saveOnExit() try: if globalVars.focusObject and hasattr(globalVars.focusObject,"event_loseFocus"): log.debug("calling lose focus on object with focus") globalVars.focusObject.event_loseFocus() except: log.error("Lose focus error",exc_info=True) try: speech.cancelSpeech() except: pass log.debug("Cleaning up running treeInterceptors") try: import treeInterceptorHandler treeInterceptorHandler.terminate() except: log.error("Error cleaning up treeInterceptors",exc_info=True) log.debug("Terminating IAccessible support") try: IAccessibleHandler.terminate() except: log.error("Error terminating IAccessible support",exc_info=True) log.debug("Terminating UIA support") try: UIAHandler.terminate() except: log.error("Error terminating UIA support",exc_info=True) log.debug("Terminating winConsole support") try: winConsoleHandler.terminate() except: log.error("Error terminating winConsole support",exc_info=True) log.debug("Terminating Java Access Bridge support") try: JABHandler.terminate() except: log.error("Error terminating Java Access Bridge support",exc_info=True) log.debug("Terminating app module handler") appModuleHandler.terminate() log.debug("Terminating NVDAHelper") try: NVDAHelper.terminate() except: log.error("Error terminating NVDAHelper",exc_info=True) log.debug("Terminating touchHandler") try: touchHandler.terminate() except: log.error("Error terminating touchHandler") log.debug("Terminating keyboard handler") try: keyboardHandler.terminate() except: log.error("Error terminating keyboard handler") log.debug("Terminating mouse handler") try: mouseHandler.terminate() except: log.error("error terminating mouse handler",exc_info=True) log.debug("Terminating input core") inputCore.terminate() log.debug("Terminating brailleInput") brailleInput.terminate() log.debug("Terminating braille") try: braille.terminate() except: log.error("Error terminating braille",exc_info=True) log.debug("Terminating speech") try: speech.terminate() except: log.error("Error terminating speech",exc_info=True) try: addonHandler.terminate() except: log.error("Error terminating addonHandler",exc_info=True) if not globalVars.appArgs.minimal: try: nvwave.playWaveFile("waves\\exit.wav",async=False) except: pass log.debug("core done")
def setUp(self): """ `setLocale` doesn't change current NVDA language, so reset the locale using `setLanguage` to the current language for each test. """ languageHandler.setLanguage(languageHandler.getLanguage())
def main(): """NVDA's core main loop. This initializes all modules such as audio, IAccessible, keyboard, mouse, and GUI. Then it initialises the wx application object and sets up the core pump, which checks the queues and executes functions when requested. Finally, it starts the wx main loop. """ log.debug("Core starting") try: # Windows >= Vista ctypes.windll.user32.SetProcessDPIAware() except AttributeError: pass import config if not globalVars.appArgs.configPath: globalVars.appArgs.configPath = config.getUserDefaultConfigPath( useInstalledPathIfExists=globalVars.appArgs.launcher) #Initialize the config path (make sure it exists) config.initConfigPath() log.info("Config dir: %s" % os.path.abspath(globalVars.appArgs.configPath)) log.debug("loading config") import config config.initialize() if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\start.wav") except: pass logHandler.setLogLevelFromConfig() logHandler.setPlayErrorSoundFromConfig() try: lang = config.conf["general"]["language"] import languageHandler log.debug("setting language to %s" % lang) languageHandler.setLanguage(lang) except: log.warning("Could not set language to %s" % lang) import versionInfo log.info("NVDA version %s" % versionInfo.version) log.info("Using Windows version %s" % winVersion.winVersionText) log.info("Using Python version %s" % sys.version) log.info("Using comtypes version %s" % comtypes.__version__) # Set a reasonable timeout for any socket connections NVDA makes. import socket socket.setdefaulttimeout(10) log.debug("Initializing add-ons system") addonHandler.initialize() if globalVars.appArgs.disableAddons: log.info("Add-ons are disabled. Restart NVDA to enable them.") import appModuleHandler log.debug("Initializing appModule Handler") appModuleHandler.initialize() import NVDAHelper log.debug("Initializing NVDAHelper") NVDAHelper.initialize() import speechDictHandler log.debug("Speech Dictionary processing") speechDictHandler.initialize() import speech log.debug("Initializing speech") speech.initialize() if not globalVars.appArgs.minimal and (time.time() - globalVars.startTime) > 5: log.debugWarning("Slow starting core (%.2f sec)" % (time.time() - globalVars.startTime)) # Translators: This is spoken when NVDA is starting. speech.speakMessage(_("Loading NVDA. Please wait...")) import wx log.info("Using wx version %s" % wx.version()) class App(wx.App): def OnAssert(self, file, line, cond, msg): message = "{file}, line {line}:\nassert {cond}: {msg}".format( file=file, line=line, cond=cond, msg=msg) log.debugWarning(message, codepath="WX Widgets", stack_info=True) app = App(redirect=False) # We do support QueryEndSession events, but we don't want to do anything for them. app.Bind(wx.EVT_QUERY_END_SESSION, lambda evt: None) def onEndSession(evt): # NVDA will be terminated as soon as this function returns, so save configuration if appropriate. config.saveOnExit() speech.cancelSpeech() if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\exit.wav", async=False) except: pass log.info("Windows session ending") app.Bind(wx.EVT_END_SESSION, onEndSession) import braille log.debug("Initializing braille") braille.initialize() log.debug("Initializing braille input") import brailleInput brailleInput.initialize() import displayModel log.debug("Initializing displayModel") displayModel.initialize() log.debug("Initializing GUI") import gui gui.initialize() import audioDucking if audioDucking.isAudioDuckingSupported(): # the GUI mainloop must be running for this to work so delay it wx.CallAfter(audioDucking.initialize) # #3763: In wxPython 3, the class name of frame windows changed from wxWindowClassNR to wxWindowNR. # NVDA uses the main frame to check for and quit another instance of NVDA. # To remain compatible with older versions of NVDA, create our own wxWindowClassNR. # We don't need to do anything else because wx handles WM_QUIT for all windows. import windowUtils class MessageWindow(windowUtils.CustomWindow): className = u"wxWindowClassNR" messageWindow = MessageWindow(unicode(versionInfo.name)) # initialize wxpython localization support locale = wx.Locale() lang = languageHandler.getLanguage() wxLang = locale.FindLanguageInfo(lang) if not wxLang and '_' in lang: wxLang = locale.FindLanguageInfo(lang.split('_')[0]) if hasattr(sys, 'frozen'): locale.AddCatalogLookupPathPrefix(os.path.join(os.getcwdu(), "locale")) if wxLang: try: locale.Init(wxLang.Language) except: log.error("Failed to initialize wx locale", exc_info=True) else: log.debugWarning("wx does not support language %s" % lang) import api import winUser import NVDAObjects.window desktopObject = NVDAObjects.window.Window( windowHandle=winUser.getDesktopWindow()) api.setDesktopObject(desktopObject) api.setFocusObject(desktopObject) api.setNavigatorObject(desktopObject) api.setMouseObject(desktopObject) import JABHandler log.debug("initializing Java Access Bridge support") try: JABHandler.initialize() except NotImplementedError: log.warning("Java Access Bridge not available") except: log.error("Error initializing Java Access Bridge support", exc_info=True) import winConsoleHandler log.debug("Initializing winConsole support") winConsoleHandler.initialize() import UIAHandler log.debug("Initializing UIA support") try: UIAHandler.initialize() except NotImplementedError: log.warning("UIA not available") except: log.error("Error initializing UIA support", exc_info=True) import IAccessibleHandler log.debug("Initializing IAccessible support") IAccessibleHandler.initialize() log.debug("Initializing input core") import inputCore inputCore.initialize() import keyboardHandler log.debug("Initializing keyboard handler") keyboardHandler.initialize() import mouseHandler log.debug("initializing mouse handler") mouseHandler.initialize() import touchHandler log.debug("Initializing touchHandler") try: touchHandler.initialize() except NotImplementedError: pass import globalPluginHandler log.debug("Initializing global plugin handler") globalPluginHandler.initialize() if globalVars.appArgs.install or globalVars.appArgs.installSilent: import wx import gui.installerGui wx.CallAfter(gui.installerGui.doSilentInstall, startAfterInstall=not globalVars.appArgs.installSilent) elif not globalVars.appArgs.minimal: try: # Translators: This is shown on a braille display (if one is connected) when NVDA starts. braille.handler.message(_("NVDA started")) except: log.error("", exc_info=True) if globalVars.appArgs.launcher: gui.LauncherDialog.run() # LauncherDialog will call doStartupDialogs() afterwards if required. else: wx.CallAfter(doStartupDialogs) import queueHandler # Queue the handling of initial focus, # as API handlers might need to be pumped to get the first focus event. queueHandler.queueFunction(queueHandler.eventQueue, _setInitialFocus) import watchdog import baseObject # Doing this here is a bit ugly, but we don't want these modules imported # at module level, including wx. log.debug("Initializing core pump") class CorePump(wx.Timer): "Checks the queues and executes functions." def Notify(self): global _isPumpPending _isPumpPending = False watchdog.alive() try: if touchHandler.handler: touchHandler.handler.pump() JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() braille.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.asleep() if _isPumpPending and not _pump.IsRunning(): # #3803: A pump was requested, but the timer was ignored by a modal loop # because timers aren't re-entrant. # Therefore, schedule another pump. _pump.Start(PUMP_MAX_DELAY, True) global _pump _pump = CorePump() requestPump() log.debug("Initializing watchdog") watchdog.initialize() try: import updateCheck except RuntimeError: updateCheck = None log.debug("Update checking not supported") else: log.debug("initializing updateCheck") updateCheck.initialize() log.info("NVDA initialized") log.debug("entering wx application main loop") app.MainLoop() log.info("Exiting") if updateCheck: _terminate(updateCheck) _terminate(watchdog) _terminate(globalPluginHandler, name="global plugin handler") _terminate(gui) config.saveOnExit() try: if globalVars.focusObject and hasattr(globalVars.focusObject, "event_loseFocus"): log.debug("calling lose focus on object with focus") globalVars.focusObject.event_loseFocus() except: log.exception("Lose focus error") try: speech.cancelSpeech() except: pass import treeInterceptorHandler _terminate(treeInterceptorHandler) _terminate(IAccessibleHandler, name="IAccessible support") _terminate(UIAHandler, name="UIA support") _terminate(winConsoleHandler, name="winConsole support") _terminate(JABHandler, name="Java Access Bridge support") _terminate(appModuleHandler, name="app module handler") _terminate(NVDAHelper) _terminate(touchHandler) _terminate(keyboardHandler, name="keyboard handler") _terminate(mouseHandler) _terminate(inputCore) _terminate(brailleInput) _terminate(braille) _terminate(speech) _terminate(addonHandler) if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\exit.wav", async=False) except: pass # #5189: Destroy the message window as late as possible # so new instances of NVDA can find this one even if it freezes during exit. messageWindow.destroy() log.debug("core done")
def __init__(self): self.__lib = load_tts_library() self.__cancel_flag = threading.Event() self.__player = audio_player(self.__cancel_flag) self.__sample_rate_callback = sample_rate_callback( self.__lib, self.__player) self.__c_sample_rate_callback = RHVoice_callback_types.set_sample_rate( self.__sample_rate_callback) self.__speech_callback = speech_callback(self.__lib, self.__player, self.__cancel_flag) self.__c_speech_callback = RHVoice_callback_types.play_speech( self.__speech_callback) self.__mark_callback = mark_callback(self.__lib) self.__c_mark_callback = RHVoice_callback_types.process_mark( self.__mark_callback) resource_paths = [ os.path.join(addon.path, "data").encode("UTF-8") for addon in addonHandler.getRunningAddons() if (addon.name.startswith("RHVoice-language") or addon.name.startswith("RHVoice-voice")) ] c_resource_paths = (c_char_p * (len(resource_paths) + 1))( *(resource_paths + [None])) init_params = RHVoice_init_params( None, config_path.encode("utf-8"), c_resource_paths, RHVoice_callbacks( self.__c_sample_rate_callback, self.__c_speech_callback, self.__c_mark_callback, cast(None, RHVoice_callback_types.word_starts), cast(None, RHVoice_callback_types.word_ends), cast(None, RHVoice_callback_types.sentence_starts), cast(None, RHVoice_callback_types.sentence_ends), cast(None, RHVoice_callback_types.play_audio)), 0) self.__tts_engine = self.__lib.RHVoice_new_tts_engine( byref(init_params)) if not self.__tts_engine: raise RuntimeError("RHVoice: initialization error") nvda_language = languageHandler.getLanguage().split("_")[0] number_of_voices = self.__lib.RHVoice_get_number_of_voices( self.__tts_engine) native_voices = self.__lib.RHVoice_get_voices(self.__tts_engine) self.__voice_languages = dict() self.__languages = set() for i in xrange(number_of_voices): native_voice = native_voices[i] self.__voice_languages[native_voice.name] = native_voice.language self.__languages.add(native_voice.language) self.__profile = None self.__profiles = list() number_of_profiles = self.__lib.RHVoice_get_number_of_voice_profiles( self.__tts_engine) native_profile_names = self.__lib.RHVoice_get_voice_profiles( self.__tts_engine) for i in xrange(number_of_profiles): name = native_profile_names[i] self.__profiles.append(name) if (self.__profile is None) and (nvda_language == self.__voice_languages[name.split("+")[0]]): self.__profile = name if self.__profile is None: self.__profile = self.__profiles[0] self.__rate = 50 self.__pitch = 50 self.__volume = 50 self.__tts_queue = Queue.Queue() self.__tts_thread = TTSThread(self.__tts_queue) self.__tts_thread.start() log.info("Using RHVoice version {}".format( self.__lib.RHVoice_get_version()))
def main(): """NVDA's core main loop. This initializes all modules such as audio, IAccessible, keyboard, mouse, and GUI. Then it initialises the wx application object and sets up the core pump, which checks the queues and executes functions when requested. Finally, it starts the wx main loop. """ log.debug("Core starting") ctypes.windll.user32.SetProcessDPIAware() import config if not globalVars.appArgs.configPath: globalVars.appArgs.configPath = config.getUserDefaultConfigPath( useInstalledPathIfExists=globalVars.appArgs.launcher) #Initialize the config path (make sure it exists) config.initConfigPath() log.info(f"Config dir: {globalVars.appArgs.configPath}") log.debug("loading config") import config config.initialize() if config.conf['development']['enableScratchpadDir']: log.info("Developer Scratchpad mode enabled") if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile( os.path.join(globalVars.appDir, "waves", "start.wav")) except: pass logHandler.setLogLevelFromConfig() if languageHandler.isLanguageForced(): lang = globalVars.appArgs.language else: lang = config.conf["general"]["language"] log.debug(f"setting language to {lang}") languageHandler.setLanguage(lang) log.info(f"Windows version: {winVersion.getWinVer()}") log.info("Using Python version %s" % sys.version) log.info("Using comtypes version %s" % comtypes.__version__) import configobj log.info("Using configobj version %s with validate version %s" % (configobj.__version__, configobj.validate.__version__)) # Set a reasonable timeout for any socket connections NVDA makes. import socket socket.setdefaulttimeout(10) log.debug("Initializing add-ons system") addonHandler.initialize() if globalVars.appArgs.disableAddons: log.info("Add-ons are disabled. Restart NVDA to enable them.") import appModuleHandler log.debug("Initializing appModule Handler") appModuleHandler.initialize() import NVDAHelper log.debug("Initializing NVDAHelper") NVDAHelper.initialize() log.debug("Initializing tones") import tones tones.initialize() import speechDictHandler log.debug("Speech Dictionary processing") speechDictHandler.initialize() import speech log.debug("Initializing speech") speech.initialize() import mathPres log.debug("Initializing MathPlayer") mathPres.initialize() if not globalVars.appArgs.minimal and (time.time() - globalVars.startTime) > 5: log.debugWarning("Slow starting core (%.2f sec)" % (time.time() - globalVars.startTime)) # Translators: This is spoken when NVDA is starting. speech.speakMessage(_("Loading NVDA. Please wait...")) import wx import six log.info("Using wx version %s with six version %s" % (wx.version(), six.__version__)) class App(wx.App): def OnAssert(self, file, line, cond, msg): message = "{file}, line {line}:\nassert {cond}: {msg}".format( file=file, line=line, cond=cond, msg=msg) log.debugWarning(message, codepath="WX Widgets", stack_info=True) def InitLocale(self): """Custom implementation of `InitLocale` which ensures that wxPython does not change the locale. The current wx implementation (as of wxPython 4.1.1) sets Python locale to an invalid one which triggers Python issue 36792 (#12160). The new implementation (wxPython 4.1.2) sets locale to "C" (basic Unicode locale). While this is not wrong as such NVDA manages locale themselves using `languageHandler` and it is better to remove wx from the equation so this method is a No-op. This code may need to be revisited when we update Python / wxPython. """ pass app = App(redirect=False) # We support queryEndSession events, but in general don't do anything for them. # However, when running as a Windows Store application, we do want to request to be restarted for updates def onQueryEndSession(evt): if config.isAppX: # Automatically restart NVDA on Windows Store update ctypes.windll.kernel32.RegisterApplicationRestart(None, 0) app.Bind(wx.EVT_QUERY_END_SESSION, onQueryEndSession) def onEndSession(evt): # NVDA will be terminated as soon as this function returns, so save configuration if appropriate. config.saveOnExit() speech.cancelSpeech() if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile(os.path.join(globalVars.appDir, "waves", "exit.wav"), asynchronous=False) except: pass log.info("Windows session ending") app.Bind(wx.EVT_END_SESSION, onEndSession) log.debug("Initializing braille input") import brailleInput brailleInput.initialize() import braille log.debug("Initializing braille") braille.initialize() import vision log.debug("Initializing vision") vision.initialize() import displayModel log.debug("Initializing displayModel") displayModel.initialize() log.debug("Initializing GUI") import gui gui.initialize() import audioDucking if audioDucking.isAudioDuckingSupported(): # the GUI mainloop must be running for this to work so delay it wx.CallAfter(audioDucking.initialize) # #3763: In wxPython 3, the class name of frame windows changed from wxWindowClassNR to wxWindowNR. # NVDA uses the main frame to check for and quit another instance of NVDA. # To remain compatible with older versions of NVDA, create our own wxWindowClassNR. # We don't need to do anything else because wx handles WM_QUIT for all windows. import windowUtils class MessageWindow(windowUtils.CustomWindow): className = u"wxWindowClassNR" # Windows constants for power / display changes WM_POWERBROADCAST = 0x218 PBT_APMPOWERSTATUSCHANGE = 0xA UNKNOWN_BATTERY_STATUS = 0xFF AC_ONLINE = 0X1 NO_SYSTEM_BATTERY = 0X80 #States for screen orientation ORIENTATION_NOT_INITIALIZED = 0 ORIENTATION_PORTRAIT = 1 ORIENTATION_LANDSCAPE = 2 def __init__(self, windowName=None): super(MessageWindow, self).__init__(windowName) self.oldBatteryStatus = None self.orientationStateCache = self.ORIENTATION_NOT_INITIALIZED self.orientationCoordsCache = (0, 0) self.handlePowerStatusChange() def windowProc(self, hwnd, msg, wParam, lParam): post_windowMessageReceipt.notify(msg=msg, wParam=wParam, lParam=lParam) if msg == self.WM_POWERBROADCAST and wParam == self.PBT_APMPOWERSTATUSCHANGE: self.handlePowerStatusChange() elif msg == winUser.WM_DISPLAYCHANGE: self.handleScreenOrientationChange(lParam) def handleScreenOrientationChange(self, lParam): import ui import winUser # Resolution detection comes from an article found at https://msdn.microsoft.com/en-us/library/ms812142.aspx. #The low word is the width and hiword is height. width = winUser.LOWORD(lParam) height = winUser.HIWORD(lParam) self.orientationCoordsCache = (width, height) if width > height: # If the height and width are the same, it's actually a screen flip, and we do want to alert of those! if self.orientationStateCache == self.ORIENTATION_LANDSCAPE and self.orientationCoordsCache != ( width, height): return #Translators: The screen is oriented so that it is wider than it is tall. ui.message(_("Landscape")) self.orientationStateCache = self.ORIENTATION_LANDSCAPE else: if self.orientationStateCache == self.ORIENTATION_PORTRAIT and self.orientationCoordsCache != ( width, height): return #Translators: The screen is oriented in such a way that the height is taller than it is wide. ui.message(_("Portrait")) self.orientationStateCache = self.ORIENTATION_PORTRAIT def handlePowerStatusChange(self): #Mostly taken from script_say_battery_status, but modified. import ui import winKernel sps = winKernel.SYSTEM_POWER_STATUS() if not winKernel.GetSystemPowerStatus( sps) or sps.BatteryFlag is self.UNKNOWN_BATTERY_STATUS: return if sps.BatteryFlag & self.NO_SYSTEM_BATTERY: return if self.oldBatteryStatus is None: #Just initializing the cache, do not report anything. self.oldBatteryStatus = sps.ACLineStatus return if sps.ACLineStatus == self.oldBatteryStatus: #Sometimes, this double fires. This also fires when the battery level decreases by 3%. return self.oldBatteryStatus = sps.ACLineStatus if sps.ACLineStatus & self.AC_ONLINE: #Translators: Reported when the battery is plugged in, and now is charging. ui.message( _("Charging battery. %d percent") % sps.BatteryLifePercent) else: #Translators: Reported when the battery is no longer plugged in, and now is not charging. ui.message( _("Not charging battery. %d percent") % sps.BatteryLifePercent) import versionInfo messageWindow = MessageWindow(versionInfo.name) # initialize wxpython localization support wxLocaleObj = wx.Locale() wxLang = getWxLangOrNone() if hasattr(sys, 'frozen'): wxLocaleObj.AddCatalogLookupPathPrefix( os.path.join(globalVars.appDir, "locale")) if wxLang: try: wxLocaleObj.Init(wxLang.Language) except: log.error("Failed to initialize wx locale", exc_info=True) finally: # Revert wx's changes to the python locale languageHandler.setLocale(languageHandler.getLanguage()) log.debug("Initializing garbageHandler") garbageHandler.initialize() import api import winUser import NVDAObjects.window desktopObject = NVDAObjects.window.Window( windowHandle=winUser.getDesktopWindow()) api.setDesktopObject(desktopObject) api.setFocusObject(desktopObject) api.setNavigatorObject(desktopObject) api.setMouseObject(desktopObject) import JABHandler log.debug("initializing Java Access Bridge support") try: JABHandler.initialize() log.info("Java Access Bridge support initialized") except NotImplementedError: log.warning("Java Access Bridge not available") except: log.error("Error initializing Java Access Bridge support", exc_info=True) import winConsoleHandler log.debug("Initializing legacy winConsole support") winConsoleHandler.initialize() import UIAHandler log.debug("Initializing UIA support") try: UIAHandler.initialize() except RuntimeError: log.warning("UIA disabled in configuration") except: log.error("Error initializing UIA support", exc_info=True) import IAccessibleHandler log.debug("Initializing IAccessible support") IAccessibleHandler.initialize() log.debug("Initializing input core") import inputCore inputCore.initialize() import keyboardHandler import watchdog log.debug("Initializing keyboard handler") keyboardHandler.initialize(watchdog.WatchdogObserver()) import mouseHandler log.debug("initializing mouse handler") mouseHandler.initialize() import touchHandler log.debug("Initializing touchHandler") try: touchHandler.initialize() except NotImplementedError: pass import globalPluginHandler log.debug("Initializing global plugin handler") globalPluginHandler.initialize() if globalVars.appArgs.install or globalVars.appArgs.installSilent: import gui.installerGui wx.CallAfter(gui.installerGui.doSilentInstall, copyPortableConfig=globalVars.appArgs.copyPortableConfig, startAfterInstall=not globalVars.appArgs.installSilent) elif globalVars.appArgs.portablePath and ( globalVars.appArgs.createPortable or globalVars.appArgs.createPortableSilent): import gui.installerGui wx.CallAfter( gui.installerGui.doCreatePortable, portableDirectory=globalVars.appArgs.portablePath, silent=globalVars.appArgs.createPortableSilent, startAfterCreate=not globalVars.appArgs.createPortableSilent) elif not globalVars.appArgs.minimal: try: # Translators: This is shown on a braille display (if one is connected) when NVDA starts. braille.handler.message(_("NVDA started")) except: log.error("", exc_info=True) if globalVars.appArgs.launcher: from gui.startupDialogs import LauncherDialog LauncherDialog.run() # LauncherDialog will call doStartupDialogs() afterwards if required. else: wx.CallAfter(doStartupDialogs) import queueHandler # Queue the handling of initial focus, # as API handlers might need to be pumped to get the first focus event. queueHandler.queueFunction(queueHandler.eventQueue, _setInitialFocus) import baseObject # Doing this here is a bit ugly, but we don't want these modules imported # at module level, including wx. log.debug("Initializing core pump") class CorePump(gui.NonReEntrantTimer): "Checks the queues and executes functions." def run(self): global _isPumpPending _isPumpPending = False watchdog.alive() try: if touchHandler.handler: touchHandler.handler.pump() JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() braille.pumpAll() vision.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.asleep() if _isPumpPending and not _pump.IsRunning(): # #3803: Another pump was requested during this pump execution. # As our pump is not re-entrant, schedule another pump. _pump.Start(PUMP_MAX_DELAY, True) global _pump _pump = CorePump() requestPump() log.debug("Initializing watchdog") watchdog.initialize() try: import updateCheck except RuntimeError: updateCheck = None log.debug("Update checking not supported") else: log.debug("initializing updateCheck") updateCheck.initialize() log.info("NVDA initialized") # Queue the firing of the postNVDAStartup notification. # This is queued so that it will run from within the core loop, # and initial focus has been reported. def _doPostNvdaStartupAction(): log.debug("Notify of postNvdaStartup action") postNvdaStartup.notify() queueHandler.queueFunction(queueHandler.eventQueue, _doPostNvdaStartupAction) log.debug("entering wx application main loop") app.MainLoop() log.info("Exiting") # If MainLoop is terminated through WM_QUIT, such as starting an NVDA instance older than 2021.1, # triggerNVDAExit has not been called yet if triggerNVDAExit(): log.debug("NVDA not already exiting, hit catch-all exit trigger." " This likely indicates NVDA is exiting due to WM_QUIT.") queueHandler.pumpAll() _terminate(gui) config.saveOnExit() try: if globalVars.focusObject and hasattr(globalVars.focusObject, "event_loseFocus"): log.debug("calling lose focus on object with focus") globalVars.focusObject.event_loseFocus() except: log.exception("Lose focus error") try: speech.cancelSpeech() except: pass import treeInterceptorHandler _terminate(treeInterceptorHandler) _terminate(IAccessibleHandler, name="IAccessible support") _terminate(UIAHandler, name="UIA support") _terminate(winConsoleHandler, name="Legacy winConsole support") _terminate(JABHandler, name="Java Access Bridge support") _terminate(appModuleHandler, name="app module handler") _terminate(tones) _terminate(NVDAHelper) _terminate(touchHandler) _terminate(keyboardHandler, name="keyboard handler") _terminate(mouseHandler) _terminate(inputCore) _terminate(vision) _terminate(brailleInput) _terminate(braille) _terminate(speech) _terminate(addonHandler) _terminate(garbageHandler) # DMP is only started if needed. # Terminate manually (and let it write to the log if necessary) # as core._terminate always writes an entry. try: import diffHandler diffHandler._dmp._terminate() except Exception: log.exception("Exception while terminating DMP") if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile(os.path.join(globalVars.appDir, "waves", "exit.wav"), asynchronous=False) except: pass # #5189: Destroy the message window as late as possible # so new instances of NVDA can find this one even if it freezes during exit. messageWindow.destroy() log.debug("core done")
def main(): """NVDA's core main loop. This initializes all modules such as audio, IAccessible, keyboard, mouse, and GUI. Then it initialises the wx application object and sets up the core pump, which checks the queues and executes functions when requested. Finally, it starts the wx main loop. """ log.debug("Core starting") ctypes.windll.user32.SetProcessDPIAware() import config if not globalVars.appArgs.configPath: globalVars.appArgs.configPath = config.getUserDefaultConfigPath( useInstalledPathIfExists=globalVars.appArgs.launcher) #Initialize the config path (make sure it exists) config.initConfigPath() log.info("Config dir: %s" % os.path.abspath(globalVars.appArgs.configPath)) log.debug("loading config") import config config.initialize() if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\start.wav") except: pass logHandler.setLogLevelFromConfig() try: lang = config.conf["general"]["language"] import languageHandler log.debug("setting language to %s" % lang) languageHandler.setLanguage(lang) except: log.warning("Could not set language to %s" % lang) import versionInfo log.info("NVDA version %s" % versionInfo.version) log.info("Using Windows version %s" % winVersion.winVersionText) log.info("Using Python version %s" % sys.version) log.info("Using comtypes version %s" % comtypes.__version__) # Set a reasonable timeout for any socket connections NVDA makes. import socket socket.setdefaulttimeout(10) log.debug("Initializing add-ons system") addonHandler.initialize() if globalVars.appArgs.disableAddons: log.info("Add-ons are disabled. Restart NVDA to enable them.") import appModuleHandler log.debug("Initializing appModule Handler") appModuleHandler.initialize() import NVDAHelper log.debug("Initializing NVDAHelper") NVDAHelper.initialize() import speechDictHandler log.debug("Speech Dictionary processing") speechDictHandler.initialize() import speech log.debug("Initializing speech") speech.initialize() if not globalVars.appArgs.minimal and (time.time() - globalVars.startTime) > 5: log.debugWarning("Slow starting core (%.2f sec)" % (time.time() - globalVars.startTime)) # Translators: This is spoken when NVDA is starting. speech.speakMessage(_("Loading NVDA. Please wait...")) import wx log.info("Using wx version %s" % wx.version()) class App(wx.App): def OnAssert(self, file, line, cond, msg): message = "{file}, line {line}:\nassert {cond}: {msg}".format( file=file, line=line, cond=cond, msg=msg) log.debugWarning(message, codepath="WX Widgets", stack_info=True) app = App(redirect=False) # We do support QueryEndSession events, but we don't want to do anything for them. app.Bind(wx.EVT_QUERY_END_SESSION, lambda evt: None) def onEndSession(evt): # NVDA will be terminated as soon as this function returns, so save configuration if appropriate. config.saveOnExit() speech.cancelSpeech() if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\exit.wav", async=False) except: pass log.info("Windows session ending") app.Bind(wx.EVT_END_SESSION, onEndSession) log.debug("Initializing braille input") import brailleInput brailleInput.initialize() import braille log.debug("Initializing braille") braille.initialize() import displayModel log.debug("Initializing displayModel") displayModel.initialize() log.debug("Initializing GUI") import gui gui.initialize() import audioDucking if audioDucking.isAudioDuckingSupported(): # the GUI mainloop must be running for this to work so delay it wx.CallAfter(audioDucking.initialize) # #3763: In wxPython 3, the class name of frame windows changed from wxWindowClassNR to wxWindowNR. # NVDA uses the main frame to check for and quit another instance of NVDA. # To remain compatible with older versions of NVDA, create our own wxWindowClassNR. # We don't need to do anything else because wx handles WM_QUIT for all windows. import windowUtils class MessageWindow(windowUtils.CustomWindow): className = u"wxWindowClassNR" #Just define these constants here, so we don't have to import win32con WM_POWERBROADCAST = 0x218 WM_DISPLAYCHANGE = 0x7e PBT_APMPOWERSTATUSCHANGE = 0xA UNKNOWN_BATTERY_STATUS = 0xFF AC_ONLINE = 0X1 NO_SYSTEM_BATTERY = 0X80 #States for screen orientation ORIENTATION_NOT_INITIALIZED = 0 ORIENTATION_PORTRAIT = 1 ORIENTATION_LANDSCAPE = 2 def __init__(self, windowName=None): super(MessageWindow, self).__init__(windowName) self.oldBatteryStatus = None self.orientationStateCache = self.ORIENTATION_NOT_INITIALIZED self.orientationCoordsCache = (0, 0) self.handlePowerStatusChange() def windowProc(self, hwnd, msg, wParam, lParam): if msg == self.WM_POWERBROADCAST and wParam == self.PBT_APMPOWERSTATUSCHANGE: self.handlePowerStatusChange() elif msg == self.WM_DISPLAYCHANGE: self.handleScreenOrientationChange(lParam) def handleScreenOrientationChange(self, lParam): import ui import winUser # Resolution detection comes from an article found at https://msdn.microsoft.com/en-us/library/ms812142.aspx. #The low word is the width and hiword is height. width = winUser.LOWORD(lParam) height = winUser.HIWORD(lParam) self.orientationCoordsCache = (width, height) if width > height: # If the height and width are the same, it's actually a screen flip, and we do want to alert of those! if self.orientationStateCache == self.ORIENTATION_LANDSCAPE and self.orientationCoordsCache != ( width, height): return #Translators: The screen is oriented so that it is wider than it is tall. ui.message(_("Landscape")) self.orientationStateCache = self.ORIENTATION_LANDSCAPE else: if self.orientationStateCache == self.ORIENTATION_PORTRAIT and self.orientationCoordsCache != ( width, height): return #Translators: The screen is oriented in such a way that the height is taller than it is wide. ui.message(_("Portrait")) self.orientationStateCache = self.ORIENTATION_PORTRAIT def handlePowerStatusChange(self): #Mostly taken from script_say_battery_status, but modified. import ui import winKernel sps = winKernel.SYSTEM_POWER_STATUS() if not winKernel.GetSystemPowerStatus( sps) or sps.BatteryFlag is self.UNKNOWN_BATTERY_STATUS: return if sps.BatteryFlag & self.NO_SYSTEM_BATTERY: return if self.oldBatteryStatus is None: #Just initializing the cache, do not report anything. self.oldBatteryStatus = sps.ACLineStatus return if sps.ACLineStatus == self.oldBatteryStatus: #Sometimes, this double fires. This also fires when the battery level decreases by 3%. return self.oldBatteryStatus = sps.ACLineStatus if sps.ACLineStatus & self.AC_ONLINE: #Translators: Reported when the battery is plugged in, and now is charging. ui.message( _("Charging battery. %d percent") % sps.BatteryLifePercent) else: #Translators: Reported when the battery is no longer plugged in, and now is not charging. ui.message( _("Not charging battery. %d percent") % sps.BatteryLifePercent) messageWindow = MessageWindow(unicode(versionInfo.name)) # initialize wxpython localization support locale = wx.Locale() lang = languageHandler.getLanguage() wxLang = locale.FindLanguageInfo(lang) if not wxLang and '_' in lang: wxLang = locale.FindLanguageInfo(lang.split('_')[0]) if hasattr(sys, 'frozen'): locale.AddCatalogLookupPathPrefix(os.path.join(os.getcwdu(), "locale")) if wxLang: try: locale.Init(wxLang.Language) except: log.error("Failed to initialize wx locale", exc_info=True) else: log.debugWarning("wx does not support language %s" % lang) import api import winUser import NVDAObjects.window desktopObject = NVDAObjects.window.Window( windowHandle=winUser.getDesktopWindow()) api.setDesktopObject(desktopObject) api.setFocusObject(desktopObject) api.setNavigatorObject(desktopObject) api.setMouseObject(desktopObject) import JABHandler log.debug("initializing Java Access Bridge support") try: JABHandler.initialize() except NotImplementedError: log.warning("Java Access Bridge not available") except: log.error("Error initializing Java Access Bridge support", exc_info=True) import winConsoleHandler log.debug("Initializing winConsole support") winConsoleHandler.initialize() import UIAHandler log.debug("Initializing UIA support") try: UIAHandler.initialize() except NotImplementedError: log.warning("UIA not available") except: log.error("Error initializing UIA support", exc_info=True) import IAccessibleHandler log.debug("Initializing IAccessible support") IAccessibleHandler.initialize() log.debug("Initializing input core") import inputCore inputCore.initialize() import keyboardHandler log.debug("Initializing keyboard handler") keyboardHandler.initialize() import mouseHandler log.debug("initializing mouse handler") mouseHandler.initialize() import touchHandler log.debug("Initializing touchHandler") try: touchHandler.initialize() except NotImplementedError: pass import globalPluginHandler log.debug("Initializing global plugin handler") globalPluginHandler.initialize() if globalVars.appArgs.install or globalVars.appArgs.installSilent: import wx import gui.installerGui wx.CallAfter(gui.installerGui.doSilentInstall, startAfterInstall=not globalVars.appArgs.installSilent) elif globalVars.appArgs.portablePath and ( globalVars.appArgs.createPortable or globalVars.appArgs.createPortableSilent): import wx import gui.installerGui wx.CallAfter( gui.installerGui.doCreatePortable, portableDirectory=globalVars.appArgs.portablePath, silent=globalVars.appArgs.createPortableSilent, startAfterCreate=not globalVars.appArgs.createPortableSilent) elif not globalVars.appArgs.minimal: try: # Translators: This is shown on a braille display (if one is connected) when NVDA starts. braille.handler.message(_("NVDA started")) except: log.error("", exc_info=True) if globalVars.appArgs.launcher: gui.LauncherDialog.run() # LauncherDialog will call doStartupDialogs() afterwards if required. else: wx.CallAfter(doStartupDialogs) import queueHandler # Queue the handling of initial focus, # as API handlers might need to be pumped to get the first focus event. queueHandler.queueFunction(queueHandler.eventQueue, _setInitialFocus) import watchdog import baseObject # Doing this here is a bit ugly, but we don't want these modules imported # at module level, including wx. log.debug("Initializing core pump") class CorePump(wx.Timer): "Checks the queues and executes functions." def Notify(self): global _isPumpPending _isPumpPending = False watchdog.alive() try: if touchHandler.handler: touchHandler.handler.pump() JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() braille.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.asleep() if _isPumpPending and not _pump.IsRunning(): # #3803: A pump was requested, but the timer was ignored by a modal loop # because timers aren't re-entrant. # Therefore, schedule another pump. _pump.Start(PUMP_MAX_DELAY, True) global _pump _pump = CorePump() requestPump() log.debug("Initializing watchdog") watchdog.initialize() try: import updateCheck except RuntimeError: updateCheck = None log.debug("Update checking not supported") else: log.debug("initializing updateCheck") updateCheck.initialize() log.info("NVDA initialized") log.debug("entering wx application main loop") app.MainLoop() log.info("Exiting") if updateCheck: _terminate(updateCheck) _terminate(watchdog) _terminate(globalPluginHandler, name="global plugin handler") _terminate(gui) config.saveOnExit() try: if globalVars.focusObject and hasattr(globalVars.focusObject, "event_loseFocus"): log.debug("calling lose focus on object with focus") globalVars.focusObject.event_loseFocus() except: log.exception("Lose focus error") try: speech.cancelSpeech() except: pass import treeInterceptorHandler _terminate(treeInterceptorHandler) _terminate(IAccessibleHandler, name="IAccessible support") _terminate(UIAHandler, name="UIA support") _terminate(winConsoleHandler, name="winConsole support") _terminate(JABHandler, name="Java Access Bridge support") _terminate(appModuleHandler, name="app module handler") _terminate(NVDAHelper) _terminate(touchHandler) _terminate(keyboardHandler, name="keyboard handler") _terminate(mouseHandler) _terminate(inputCore) _terminate(brailleInput) _terminate(braille) _terminate(speech) _terminate(addonHandler) if not globalVars.appArgs.minimal and config.conf["general"][ "playStartAndExitSounds"]: try: nvwave.playWaveFile("waves\\exit.wav", async=False) except: pass # #5189: Destroy the message window as late as possible # so new instances of NVDA can find this one even if it freezes during exit. messageWindow.destroy() log.debug("core done")
def isJa(locale=None): if locale is None: return languageHandler.getLanguage()[:2] == 'ja' return locale[:2] == 'ja'
sys.path.append(libs) import html2markdown import html2text import markdown2 import winClipboard import yaml from bs4 import BeautifulSoup from . import virtualDocuments sys.path.remove(libs) _addonDir = os.path.join(baseDir, "..", "..") addonInfos = addonHandler.Addon(_addonDir).manifest addonSummary = addonInfos["summary"] addonVersion = addonInfos["version"] configDir = "%s/markdownForever" % globalVars.appArgs.configPath defaultLanguage = languageHandler.getLanguage() internalAutoNumber = r"\!" internalTocTag = f":\\tableOfContent:{time.time()}/!$£:" curDir = os.path.dirname(__file__) addonPath = '\\'.join(curDir.split('\\')[0:-2]) pathPattern = r"^(?:%|[a-zA-Z]:[\\/])[^:*?\"<>|]+\.html?$" URLPattern = r"^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$" minCharTemplateName = 1 maxCharTemplateName = 28 def realpath(path): path = path.lower() vars = ["appdata", "tmp", "temp", "userprofile"] for var in vars: path = path.replace("%%%s%%" % var, os.environ[var])
manager.manager.get_current_session()) config.setup() lang = config.main['general']['language'] languageHandler.setLanguage(lang) sound.setup() output.setup() configured = True else: ssmg = smGUI.sessionManagerWindow() if configured == True or ssmg.ShowModal() == wx.ID_OK: frame = gui.main.mainFrame() frame.Show() frame.showing = True if config.main != None and config.main["general"][ "hide_gui"] == True and platform.system() == "Windows": frame.show_hide() frame.Hide() app.SetTopWindow(frame) else: app.Exit() ### I should uncomment this #if platform.system() != "Windows": if languageHandler.getLanguage() != "en": local = wx.Locale(wxLangs.getLanguage()) local.AddCatalogLookupPathPrefix(paths.locale_path()) local.AddCatalog("twblue") #languageHandler.setLanguage(lang) #ap = app(redirect=True, useBestVisual=True, filename=paths.logs_path('tracebacks.log')) #wx.CallLater(10, start) app.MainLoop()
def tearDownClass(cls): """ `setLocale` doesn't change current NVDA language, so reset the locale using `setLanguage` to the current language so the tests can continue normally. """ languageHandler.setLanguage(languageHandler.getLanguage())
import json import os import gui import wx import addonHandler import braille import config import controlTypes import languageHandler from .common import configDir addonHandler.initTranslation() CUR_LANG = languageHandler.getLanguage().split('_')[0] PATH_JSON = os.path.join(configDir, f"roleLabels-{CUR_LANG}.json") class SettingsDlg(gui.settingsDialogs.SettingsPanel): # Translators: title of a dialog. title = _("Role labels") roleLabels = {} def makeSettings(self, settingsSizer): self.roleLabels = roleLabels.copy() sHelper = gui.guiHelper.BoxSizerHelper(self, sizer=settingsSizer) self.toggleRoleLabels = sHelper.addItem(wx.CheckBox(self, label=_("Use custom braille &role labels"))) self.toggleRoleLabels.SetValue(config.conf["brailleExtender"]["features"]["roleLabels"])
def getHtmlDocFromBody(body, lang=None): if body is None: return None if not lang: lang = languageHandler.getLanguage().split("_")[0] return DEFAULT_HTML_DOC_TEMPLATE.format(lang=lang, body=body)