Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(154)

Side by Side Diff: src/extensions/i18n/date-format.cc

Issue 22411003: Move i18n extension's date-format C++ code to runtime (Closed) Base URL: https://v8.googlecode.com/svn/branches/bleeding_edge
Patch Set: rebase Created 7 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « src/extensions/i18n/date-format.h ('k') | src/extensions/i18n/date-format.js » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 // limitations under the License.
28
29 #include "date-format.h"
30
31 #include <string.h>
32
33 #include "i18n-utils.h"
34 #include "unicode/calendar.h"
35 #include "unicode/dtfmtsym.h"
36 #include "unicode/dtptngen.h"
37 #include "unicode/locid.h"
38 #include "unicode/numsys.h"
39 #include "unicode/smpdtfmt.h"
40 #include "unicode/timezone.h"
41
42 namespace v8_i18n {
43
44 static icu::SimpleDateFormat* InitializeDateTimeFormat(v8::Handle<v8::String>,
45 v8::Handle<v8::Object>,
46 v8::Handle<v8::Object>);
47 static icu::SimpleDateFormat* CreateICUDateFormat(const icu::Locale&,
48 v8::Handle<v8::Object>);
49 static void SetResolvedSettings(const icu::Locale&,
50 icu::SimpleDateFormat*,
51 v8::Handle<v8::Object>);
52
53 icu::SimpleDateFormat* DateFormat::UnpackDateFormat(
54 v8::Handle<v8::Object> obj) {
55 v8::HandleScope handle_scope;
56
57 if (obj->HasOwnProperty(v8::String::New("dateFormat"))) {
58 return static_cast<icu::SimpleDateFormat*>(
59 obj->GetAlignedPointerFromInternalField(0));
60 }
61
62 return NULL;
63 }
64
65 void DateFormat::DeleteDateFormat(v8::Isolate* isolate,
66 v8::Persistent<v8::Object>* object,
67 void* param) {
68 // First delete the hidden C++ object.
69 // Unpacking should never return NULL here. That would only happen if
70 // this method is used as the weak callback for persistent handles not
71 // pointing to a date time formatter.
72 v8::HandleScope handle_scope(isolate);
73 v8::Local<v8::Object> handle = v8::Local<v8::Object>::New(isolate, *object);
74 delete UnpackDateFormat(handle);
75
76 // Then dispose of the persistent handle to JS object.
77 object->Dispose(isolate);
78 }
79
80 void DateFormat::JSInternalFormat(
81 const v8::FunctionCallbackInfo<v8::Value>& args) {
82 double millis = 0.0;
83 if (args.Length() != 2 || !args[0]->IsObject() || !args[1]->IsDate()) {
84 v8::ThrowException(v8::Exception::Error(
85 v8::String::New(
86 "Internal error. Formatter and date value have to be specified.")));
87 return;
88 } else {
89 millis = v8::Date::Cast(*args[1])->NumberValue();
90 }
91
92 icu::SimpleDateFormat* date_format = UnpackDateFormat(args[0]->ToObject());
93 if (!date_format) {
94 v8::ThrowException(v8::Exception::Error(
95 v8::String::New("DateTimeFormat method called on an object "
96 "that is not a DateTimeFormat.")));
97 return;
98 }
99
100 icu::UnicodeString result;
101 date_format->format(millis, result);
102
103 args.GetReturnValue().Set(v8::String::New(
104 reinterpret_cast<const uint16_t*>(result.getBuffer()), result.length()));
105 }
106
107 void DateFormat::JSInternalParse(
108 const v8::FunctionCallbackInfo<v8::Value>& args) {
109 icu::UnicodeString string_date;
110 if (args.Length() != 2 || !args[0]->IsObject() || !args[1]->IsString()) {
111 v8::ThrowException(v8::Exception::Error(
112 v8::String::New(
113 "Internal error. Formatter and string have to be specified.")));
114 return;
115 } else {
116 if (!Utils::V8StringToUnicodeString(args[1], &string_date)) {
117 string_date = "";
118 }
119 }
120
121 icu::SimpleDateFormat* date_format = UnpackDateFormat(args[0]->ToObject());
122 if (!date_format) {
123 v8::ThrowException(v8::Exception::Error(
124 v8::String::New("DateTimeFormat method called on an object "
125 "that is not a DateTimeFormat.")));
126 return;
127 }
128
129 UErrorCode status = U_ZERO_ERROR;
130 UDate date = date_format->parse(string_date, status);
131 if (U_FAILURE(status)) {
132 return;
133 }
134
135 args.GetReturnValue().Set(v8::Date::New(static_cast<double>(date)));
136 }
137
138 void DateFormat::JSCreateDateTimeFormat(
139 const v8::FunctionCallbackInfo<v8::Value>& args) {
140 if (args.Length() != 3 ||
141 !args[0]->IsString() ||
142 !args[1]->IsObject() ||
143 !args[2]->IsObject()) {
144 v8::ThrowException(v8::Exception::Error(
145 v8::String::New("Internal error, wrong parameters.")));
146 return;
147 }
148
149 v8::Isolate* isolate = args.GetIsolate();
150 v8::Local<v8::ObjectTemplate> date_format_template =
151 Utils::GetTemplate(isolate);
152
153 // Create an empty object wrapper.
154 v8::Local<v8::Object> local_object = date_format_template->NewInstance();
155 // But the handle shouldn't be empty.
156 // That can happen if there was a stack overflow when creating the object.
157 if (local_object.IsEmpty()) {
158 args.GetReturnValue().Set(local_object);
159 return;
160 }
161
162 // Set date time formatter as internal field of the resulting JS object.
163 icu::SimpleDateFormat* date_format = InitializeDateTimeFormat(
164 args[0]->ToString(), args[1]->ToObject(), args[2]->ToObject());
165
166 if (!date_format) {
167 v8::ThrowException(v8::Exception::Error(v8::String::New(
168 "Internal error. Couldn't create ICU date time formatter.")));
169 return;
170 } else {
171 local_object->SetAlignedPointerInInternalField(0, date_format);
172
173 v8::TryCatch try_catch;
174 local_object->Set(v8::String::New("dateFormat"), v8::String::New("valid"));
175 if (try_catch.HasCaught()) {
176 v8::ThrowException(v8::Exception::Error(
177 v8::String::New("Internal error, couldn't set property.")));
178 return;
179 }
180 }
181
182 v8::Persistent<v8::Object> wrapper(isolate, local_object);
183 // Make object handle weak so we can delete iterator once GC kicks in.
184 wrapper.MakeWeak<void>(NULL, &DeleteDateFormat);
185 args.GetReturnValue().Set(wrapper);
186 wrapper.ClearAndLeak();
187 }
188
189 static icu::SimpleDateFormat* InitializeDateTimeFormat(
190 v8::Handle<v8::String> locale,
191 v8::Handle<v8::Object> options,
192 v8::Handle<v8::Object> resolved) {
193 // Convert BCP47 into ICU locale format.
194 UErrorCode status = U_ZERO_ERROR;
195 icu::Locale icu_locale;
196 char icu_result[ULOC_FULLNAME_CAPACITY];
197 int icu_length = 0;
198 v8::String::AsciiValue bcp47_locale(locale);
199 if (bcp47_locale.length() != 0) {
200 uloc_forLanguageTag(*bcp47_locale, icu_result, ULOC_FULLNAME_CAPACITY,
201 &icu_length, &status);
202 if (U_FAILURE(status) || icu_length == 0) {
203 return NULL;
204 }
205 icu_locale = icu::Locale(icu_result);
206 }
207
208 icu::SimpleDateFormat* date_format = CreateICUDateFormat(icu_locale, options);
209 if (!date_format) {
210 // Remove extensions and try again.
211 icu::Locale no_extension_locale(icu_locale.getBaseName());
212 date_format = CreateICUDateFormat(no_extension_locale, options);
213
214 // Set resolved settings (pattern, numbering system, calendar).
215 SetResolvedSettings(no_extension_locale, date_format, resolved);
216 } else {
217 SetResolvedSettings(icu_locale, date_format, resolved);
218 }
219
220 return date_format;
221 }
222
223 static icu::SimpleDateFormat* CreateICUDateFormat(
224 const icu::Locale& icu_locale, v8::Handle<v8::Object> options) {
225 // Create time zone as specified by the user. We have to re-create time zone
226 // since calendar takes ownership.
227 icu::TimeZone* tz = NULL;
228 icu::UnicodeString timezone;
229 if (Utils::ExtractStringSetting(options, "timeZone", &timezone)) {
230 tz = icu::TimeZone::createTimeZone(timezone);
231 } else {
232 tz = icu::TimeZone::createDefault();
233 }
234
235 // Create a calendar using locale, and apply time zone to it.
236 UErrorCode status = U_ZERO_ERROR;
237 icu::Calendar* calendar =
238 icu::Calendar::createInstance(tz, icu_locale, status);
239
240 // Make formatter from skeleton. Calendar and numbering system are added
241 // to the locale as Unicode extension (if they were specified at all).
242 icu::SimpleDateFormat* date_format = NULL;
243 icu::UnicodeString skeleton;
244 if (Utils::ExtractStringSetting(options, "skeleton", &skeleton)) {
245 icu::DateTimePatternGenerator* generator =
246 icu::DateTimePatternGenerator::createInstance(icu_locale, status);
247 icu::UnicodeString pattern;
248 if (U_SUCCESS(status)) {
249 pattern = generator->getBestPattern(skeleton, status);
250 delete generator;
251 }
252
253 date_format = new icu::SimpleDateFormat(pattern, icu_locale, status);
254 if (U_SUCCESS(status)) {
255 date_format->adoptCalendar(calendar);
256 }
257 }
258
259 if (U_FAILURE(status)) {
260 delete calendar;
261 delete date_format;
262 date_format = NULL;
263 }
264
265 return date_format;
266 }
267
268 static void SetResolvedSettings(const icu::Locale& icu_locale,
269 icu::SimpleDateFormat* date_format,
270 v8::Handle<v8::Object> resolved) {
271 UErrorCode status = U_ZERO_ERROR;
272 icu::UnicodeString pattern;
273 date_format->toPattern(pattern);
274 resolved->Set(v8::String::New("pattern"),
275 v8::String::New(reinterpret_cast<const uint16_t*>(
276 pattern.getBuffer()), pattern.length()));
277
278 // Set time zone and calendar.
279 if (date_format) {
280 const icu::Calendar* calendar = date_format->getCalendar();
281 const char* calendar_name = calendar->getType();
282 resolved->Set(v8::String::New("calendar"), v8::String::New(calendar_name));
283
284 const icu::TimeZone& tz = calendar->getTimeZone();
285 icu::UnicodeString time_zone;
286 tz.getID(time_zone);
287
288 icu::UnicodeString canonical_time_zone;
289 icu::TimeZone::getCanonicalID(time_zone, canonical_time_zone, status);
290 if (U_SUCCESS(status)) {
291 if (canonical_time_zone == UNICODE_STRING_SIMPLE("Etc/GMT")) {
292 resolved->Set(v8::String::New("timeZone"), v8::String::New("UTC"));
293 } else {
294 resolved->Set(v8::String::New("timeZone"),
295 v8::String::New(reinterpret_cast<const uint16_t*>(
296 canonical_time_zone.getBuffer()),
297 canonical_time_zone.length()));
298 }
299 }
300 }
301
302 // Ugly hack. ICU doesn't expose numbering system in any way, so we have
303 // to assume that for given locale NumberingSystem constructor produces the
304 // same digits as NumberFormat/Calendar would.
305 status = U_ZERO_ERROR;
306 icu::NumberingSystem* numbering_system =
307 icu::NumberingSystem::createInstance(icu_locale, status);
308 if (U_SUCCESS(status)) {
309 const char* ns = numbering_system->getName();
310 resolved->Set(v8::String::New("numberingSystem"), v8::String::New(ns));
311 } else {
312 resolved->Set(v8::String::New("numberingSystem"), v8::Undefined());
313 }
314 delete numbering_system;
315
316 // Set the locale
317 char result[ULOC_FULLNAME_CAPACITY];
318 status = U_ZERO_ERROR;
319 uloc_toLanguageTag(
320 icu_locale.getName(), result, ULOC_FULLNAME_CAPACITY, FALSE, &status);
321 if (U_SUCCESS(status)) {
322 resolved->Set(v8::String::New("locale"), v8::String::New(result));
323 } else {
324 // This would never happen, since we got the locale from ICU.
325 resolved->Set(v8::String::New("locale"), v8::String::New("und"));
326 }
327 }
328
329 } // namespace v8_i18n
OLDNEW
« no previous file with comments | « src/extensions/i18n/date-format.h ('k') | src/extensions/i18n/date-format.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698