1# This Source Code Form is subject to the terms of the Mozilla Public
2# License, v. 2.0. If a copy of the MPL was not distributed with this file,
3# You can obtain one at http://mozilla.org/MPL/2.0/.
4
5# -----------------
6# DEPRECATED module
7# -----------------
8# Replace its use in tests when Firefox 45 ESR support ends with
9# marionette_driver.localization.L10n
10
11import copy
12
13from marionette_driver.errors import (
14    NoSuchElementException,
15    UnknownCommandException,
16)
17from marionette_driver.localization import L10n as L10nMarionette
18
19from firefox_puppeteer.base import BaseLib
20
21
22class L10n(BaseLib):
23    """An API which allows Marionette to handle localized content.
24
25    .. deprecated:: 52.2.0
26       Use the localization module from :py:mod:`marionette_driver` instead.
27
28    The `localization`_ of UI elements in Gecko based applications is done via
29    entities and properties. For static values entities are used, which are located
30    in .dtd files. Whereby for dynamically updated content the values come from
31    .property files. Both types of elements can be identifed via a unique id,
32    and the translated content retrieved.
33
34    .. _localization: https://mzl.la/2eUMjyF
35    """
36
37    def __init__(self, marionette):
38        super(L10n, self).__init__(marionette)
39
40        self._l10nMarionette = L10nMarionette(self.marionette)
41
42    def localize_entity(self, dtd_urls, entity_id):
43        """Returns the localized string for the specified DTD entity id.
44
45        To find the entity all given DTD files will be searched for the id.
46
47        :param dtd_urls: A list of dtd files to search.
48        :param entity_id: The id to retrieve the value from.
49
50        :returns: The localized string for the requested entity.
51
52        :raises NoSuchElementException: When entity id is not found in dtd_urls.
53        """
54        # Add xhtml11.dtd to prevent missing entity errors with XHTML files
55        try:
56            return self._l10nMarionette.localize_entity(dtd_urls, entity_id)
57        except UnknownCommandException:
58            dtds = copy.copy(dtd_urls)
59            dtds.append("resource:///res/dtd/xhtml11.dtd")
60
61            dtd_refs = ''
62            for index, item in enumerate(dtds):
63                dtd_id = 'dtd_%s' % index
64                dtd_refs += '<!ENTITY %% %s SYSTEM "%s">%%%s;' % \
65                    (dtd_id, item, dtd_id)
66
67            contents = """<?xml version="1.0"?>
68                <!DOCTYPE elem [%s]>
69
70                <elem id="entity">&%s;</elem>""" % (dtd_refs, entity_id)
71
72            with self.marionette.using_context('chrome'):
73                value = self.marionette.execute_script("""
74                    var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
75                                 .createInstance(Components.interfaces.nsIDOMParser);
76                    var doc = parser.parseFromString(arguments[0], "text/xml");
77                    var node = doc.querySelector("elem[id='entity']");
78
79                    return node ? node.textContent : null;
80                """, script_args=[contents])
81
82            if not value:
83                raise NoSuchElementException('DTD Entity not found: %s' % entity_id)
84
85            return value
86
87    def localize_property(self, property_urls, property_id):
88        """Returns the localized string for the specified property id.
89
90        To find the property all given property files will be searched for
91        the id.
92
93        :param property_urls: A list of property files to search.
94        :param property_id: The id to retrieve the value from.
95
96        :returns: The localized string for the requested entity.
97
98        :raises NoSuchElementException: When property id is not found in
99            property_urls.
100        """
101        try:
102            return self._l10nMarionette.localize_property(property_urls, property_id)
103        except UnknownCommandException:
104            with self.marionette.using_context('chrome'):
105                value = self.marionette.execute_script("""
106                    let property = null;
107                    let property_id = arguments[1];
108
109                    arguments[0].some(aUrl => {
110                      let bundle = Services.strings.createBundle(aUrl);
111
112                      try {
113                        property = bundle.GetStringFromName(property_id);
114                        return true;
115                      }
116                      catch (ex) { }
117                    });
118
119                    return property;
120                """, script_args=[property_urls, property_id])
121
122            if not value:
123                raise NoSuchElementException('Property not found: %s' % property_id)
124
125            return value
126