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

Side by Side Diff: src/extensions/experimental/datetime-format.cc

Issue 7014019: Adding DateTimeFormat class to i18n API. (Closed) Base URL: http://v8.googlecode.com/svn/branches/bleeding_edge/
Patch Set: '' Created 9 years, 7 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
Property Changes:
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
1 // Copyright 2011 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
28 #include "datetime-format.h"
29
30 #include "i18n-utils.h"
31 #include "unicode/dtfmtsym.h"
32 #include "unicode/dtptngen.h"
33 #include "unicode/locid.h"
34 #include "unicode/smpdtfmt.h"
35
36 namespace v8 {
37 namespace internal {
38
39 v8::Persistent<v8::FunctionTemplate> DateTimeFormat::datetime_format_template_;
40
41 static icu::DateFormat* CreateDateTimeFormat(v8::Handle<v8::String>,
42 v8::Handle<v8::Object>);
43 static v8::Handle<v8::Value> GetSymbols(
44 const v8::Arguments&, const icu::UnicodeString*, int32_t,
45 const icu::UnicodeString*, int32_t);
46 static v8::Handle<v8::Value> ThrowUnexpectedObjectError();
47
48 icu::SimpleDateFormat* DateTimeFormat::UnpackDateTimeFormat(
49 v8::Handle<v8::Object> obj) {
50 if (datetime_format_template_->HasInstance(obj)) {
51 return static_cast<icu::SimpleDateFormat*>(
52 obj->GetPointerFromInternalField(0));
53 }
54
55 return NULL;
56 }
57
58 void DateTimeFormat::DeleteDateTimeFormat(v8::Persistent<v8::Value> object,
59 void* param) {
60 v8::Persistent<v8::Object> persistent_object =
61 v8::Persistent<v8::Object>::Cast(object);
62
63 // First delete the hidden C++ object.
64 // Unpacking should never return NULL here. That would only happen if
65 // this method is used as the weak callback for persistent handles not
66 // pointing to a date time formatter.
67 delete UnpackDateTimeFormat(persistent_object);
68
69 // Then dispose of the persistent handle to JS object.
70 persistent_object.Dispose();
71 }
72
73 v8::Handle<v8::Value> DateTimeFormat::Format(const v8::Arguments& args) {
74 v8::HandleScope handle_scope;
75
76 double millis = 0.0;
77 if (args.Length() != 1 || !args[0]->IsDate()) {
78 // Create a new date.
79 v8::TryCatch try_catch;
80 v8::Local<v8::Script> date_script =
81 v8::Script::Compile(v8::String::New("eval('new Date()')"));
82 millis = date_script->Run()->NumberValue();
83 if (try_catch.HasCaught()) {
84 return v8::ThrowException(v8::Exception::Error(
Mads Ager (chromium) 2011/05/18 05:36:35 In case of an exception here, do you want to catch
Nebojša Ćirić 2011/05/18 17:50:13 Re-throwing is what I wanted to do. Thanks. On 20
85 v8::String::New("Cannot create current date with new Date().")));
86 }
87 } else {
88 millis = v8::Date::Cast(*args[0])->NumberValue();
89 }
90
91 icu::SimpleDateFormat* date_format = UnpackDateTimeFormat(args.Holder());
92 if (!date_format) {
93 return ThrowUnexpectedObjectError();
94 }
95
96 icu::UnicodeString result;
97 date_format->format(millis, result);
98
99 return v8::String::New(
100 reinterpret_cast<const uint16_t*>(result.getBuffer()), result.length());
101 }
102
103 v8::Handle<v8::Value> DateTimeFormat::GetMonths(const v8::Arguments& args) {
104 icu::SimpleDateFormat* date_format = UnpackDateTimeFormat(args.Holder());
105 if (!date_format) {
106 return ThrowUnexpectedObjectError();
107 }
108
109 const icu::DateFormatSymbols* symbols = date_format->getDateFormatSymbols();
110
111 int32_t narrow_count;
112 const icu::UnicodeString* narrow = symbols->getShortMonths(narrow_count);
113 int32_t wide_count;
114 const icu::UnicodeString* wide = symbols->getMonths(wide_count);
115
116 return GetSymbols(args, narrow, narrow_count, wide, wide_count);
117 }
118
119 v8::Handle<v8::Value> DateTimeFormat::GetWeekdays(const v8::Arguments& args) {
120 icu::SimpleDateFormat* date_format = UnpackDateTimeFormat(args.Holder());
121 if (!date_format) {
122 ThrowUnexpectedObjectError();
123 }
124
125 const icu::DateFormatSymbols* symbols = date_format->getDateFormatSymbols();
126
127 int32_t narrow_count;
128 const icu::UnicodeString* narrow = symbols->getShortWeekdays(narrow_count);
129 int32_t wide_count;
130 const icu::UnicodeString* wide = symbols->getWeekdays(wide_count);
131
132 // getXXXWeekdays always returns 8 elements.
133 CHECK_EQ(8, narrow_count);
134 CHECK_EQ(8, wide_count);
135
136 // ICU documentation says we should ignore element 0 of the returned array.
137 return GetSymbols(
138 args, narrow + 1, narrow_count -1 , wide + 1, wide_count - 1);
139 }
140
141 v8::Handle<v8::Value> DateTimeFormat::GetEras(const v8::Arguments& args) {
142 icu::SimpleDateFormat* date_format = UnpackDateTimeFormat(args.Holder());
143 if (!date_format) {
144 return ThrowUnexpectedObjectError();
145 }
146
147 const icu::DateFormatSymbols* symbols = date_format->getDateFormatSymbols();
148
149 int32_t narrow_count;
150 const icu::UnicodeString* narrow = symbols->getNarrowEras(narrow_count);
151 int32_t wide_count;
152 const icu::UnicodeString* wide = symbols->getEraNames(wide_count);
153
154 return GetSymbols(args, narrow, narrow_count, wide, wide_count);
155 }
156
157 v8::Handle<v8::Value> DateTimeFormat::GetAmPm(const v8::Arguments& args) {
158 icu::SimpleDateFormat* date_format = UnpackDateTimeFormat(args.Holder());
159 if (!date_format) {
160 return ThrowUnexpectedObjectError();
161 }
162
163 const icu::DateFormatSymbols* symbols = date_format->getDateFormatSymbols();
164
165 int32_t narrow_count;
166 const icu::UnicodeString* narrow = symbols->getAmPmStrings(narrow_count);
167 int32_t wide_count = narrow_count;
168 const icu::UnicodeString* wide = narrow;
169
170 return GetSymbols(args, narrow, narrow_count, wide, wide_count);
171 }
172
173 v8::Handle<v8::Value> DateTimeFormat::JSDateTimeFormat(
174 const v8::Arguments& args) {
175 v8::HandleScope handle_scope;
176
177 CHECK_EQ(2, args.Length());
Mads Ager (chromium) 2011/05/18 05:36:35 Ah, so this can only ever be called with two strin
Nebojša Ćirić 2011/05/18 17:50:13 It's called with languageID (a string) and setting
178 CHECK(args[0]->IsString());
179 CHECK(args[1]->IsObject());
180
181 icu::SimpleDateFormat* date_format = static_cast<icu::SimpleDateFormat*>(
182 CreateDateTimeFormat(args[0]->ToString(), args[1]->ToObject()));
183
184 if (datetime_format_template_.IsEmpty()) {
185 v8::Local<v8::FunctionTemplate> raw_template(v8::FunctionTemplate::New());
186
187 raw_template->SetClassName(v8::String::New("v8Locale.DateTimeFormat"));
188
189 // Define internal field count on instance template.
190 v8::Local<v8::ObjectTemplate> object_template =
191 raw_template->InstanceTemplate();
192
193 // Set aside internal field for icu date time formatter.
194 object_template->SetInternalFieldCount(1);
195
196 // Define all of the prototype methods on prototype template.
197 v8::Local<v8::ObjectTemplate> proto = raw_template->PrototypeTemplate();
198 proto->Set(v8::String::New("format"),
199 v8::FunctionTemplate::New(Format));
200 proto->Set(v8::String::New("getMonths"),
201 v8::FunctionTemplate::New(GetMonths));
202 proto->Set(v8::String::New("getWeekdays"),
203 v8::FunctionTemplate::New(GetWeekdays));
204 proto->Set(v8::String::New("getEras"),
205 v8::FunctionTemplate::New(GetEras));
206 proto->Set(v8::String::New("getAmPm"),
207 v8::FunctionTemplate::New(GetAmPm));
208
209 datetime_format_template_ =
210 v8::Persistent<v8::FunctionTemplate>::New(raw_template);
211 }
212
213 // Create an empty object wrapper.
214 v8::Local<v8::Object> local_object =
215 datetime_format_template_->GetFunction()->NewInstance();
216 v8::Persistent<v8::Object> wrapper =
217 v8::Persistent<v8::Object>::New(local_object);
218
219 // Set date time formatter as internal field of the resulting JS object.
220 wrapper->SetPointerInInternalField(0, date_format);
221
222 // Set resolved pattern in options.pattern.
223 icu::UnicodeString pattern;
224 date_format->toPattern(pattern);
225 v8::Local<v8::Object> options = v8::Object::New();
226 options->Set(v8::String::New("pattern"),
227 v8::String::New(reinterpret_cast<const uint16_t*>(
228 pattern.getBuffer()), pattern.length()));
229 wrapper->Set(v8::String::New("options"), options);
230
231 // Make object handle weak so we can delete iterator once GC kicks in.
232 wrapper.MakeWeak(NULL, DeleteDateTimeFormat);
233
234 return wrapper;
235 }
236
237 // Returns SimpleDateFormat.
238 static icu::DateFormat* CreateDateTimeFormat(
239 v8::Handle<v8::String> locale, v8::Handle<v8::Object> settings) {
240 v8::HandleScope handle_scope;
241
242 v8::String::AsciiValue ascii_locale(locale);
243 icu::Locale icu_locale(*ascii_locale);
244
245 // Make formatter from skeleton.
246 icu::SimpleDateFormat* date_format = NULL;
247 UErrorCode status = U_ZERO_ERROR;
248 icu::UnicodeString skeleton;
249 if (I18NUtils::ExtractStringSetting(settings, "skeleton", &skeleton)) {
250 v8::Local<icu::DateTimePatternGenerator> generator(
251 icu::DateTimePatternGenerator::createInstance(icu_locale, status));
252 icu::UnicodeString pattern =
253 generator->getBestPattern(skeleton, status);
254
255 date_format = new icu::SimpleDateFormat(pattern, icu_locale, status);
256 if (U_SUCCESS(status)) {
257 return date_format;
258 } else {
259 delete date_format;
260 }
261 }
262
263 // Extract date type and time type from settings.
264 icu::UnicodeString short_dt = icu::UnicodeString::fromUTF8("short");
265 icu::UnicodeString date_type;
266 icu::DateFormat::EStyle date_style = icu::DateFormat::kNone;
267 if (I18NUtils::ExtractStringSetting(settings, "dateType", &date_type)) {
268 if (date_type == short_dt) {
269 date_style = icu::DateFormat::kShort;
270 } else {
271 date_style = icu::DateFormat::kLong;
272 }
273 }
274
275 icu::UnicodeString time_type;
276 icu::DateFormat::EStyle time_style = icu::DateFormat::kNone;
277 if (I18NUtils::ExtractStringSetting(settings, "timeType", &time_type)) {
278 if (time_type == short_dt) {
279 time_style = icu::DateFormat::kShort;
280 } else {
281 time_style = icu::DateFormat::kMedium;
282 }
283 }
284
285 // Try all combinations of date/time types.
286 if (date_style == icu::DateFormat::kNone &&
287 time_style == icu::DateFormat::kNone) {
288 // Return default short date, short
289 return icu::DateFormat::createDateTimeInstance(
290 icu::DateFormat::kShort, icu::DateFormat::kShort, icu_locale);
291 } else if (date_style != icu::DateFormat::kNone &&
292 time_style != icu::DateFormat::kNone) {
293 return icu::DateFormat::createDateTimeInstance(
294 date_style, time_style, icu_locale);
295 } else if (date_style != icu::DateFormat::kNone) {
296 return icu::DateFormat::createDateInstance(date_style, icu_locale);
297 } else {
298 // time_style != icu::DateFormat::kNone
299 return icu::DateFormat::createTimeInstance(time_style, icu_locale);
300 }
301 }
302
303 // Creates a v8::Array of narrow or wide symbols.
304 static v8::Handle<v8::Value> GetSymbols(const v8::Arguments& args,
305 const icu::UnicodeString* narrow,
306 int32_t narrow_count,
307 const icu::UnicodeString* wide,
308 int32_t wide_count) {
309 v8::HandleScope handle_scope;
310
311 const icu::UnicodeString* result = wide;
312 int32_t count = wide_count;
313
314 if (args.Length() == 1 && args[0]->IsString()) {
315 v8::String::AsciiValue ascii_value(args[0]);
316 if (strcmp(*ascii_value, "narrow") == 0) {
317 result = narrow;
318 count = narrow_count;
319 }
320 }
321
322 v8::Handle<v8::Array> symbols = v8::Array::New();
323 for (int32_t i = 0; i < count; ++i) {
324 symbols->Set(i, v8::String::New(
325 reinterpret_cast<const uint16_t*>(result[i].getBuffer()),
326 result[i].length()));
327 }
328
329 return handle_scope.Close(symbols);
330 }
331
332 // Throws a JavaScript exception.
333 static v8::Handle<v8::Value> ThrowUnexpectedObjectError() {
334 // Returns undefined, and schedules an exception to be thrown.
335 return v8::ThrowException(v8::Exception::Error(
336 v8::String::New("DateTimeFormat method called on an object "
337 "that is not a DateTimeFormat.")));
338 }
339
340 } } // namespace v8::internal
OLDNEW
« no previous file with comments | « src/extensions/experimental/datetime-format.h ('k') | src/extensions/experimental/experimental.gyp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698