/
NativeStringInterface.cpp
432 lines (377 loc) · 12.9 KB
/
NativeStringInterface.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include "NativeStringInterface.h"
#include "NativeMessageStrings.h"
#include "TiMessageStrings.h"
#include <QDate>
#include <QLocale>
#include <QRegExp>
#include <QString>
#include <QTextStream>
#include <QTime>
using namespace v8;
// Prototypes
static QString formatInt(QString s, Local<Value> arg);
static QString formatUInt(QString s, Local<Value> arg);
static QString formatDouble(QString s, Local<Value> arg);
static QString formatString(QString s, Local<Value> arg);
static QString formatPointer(QString s, Local<Value> arg);
static QLocale::FormatType parseFormat(Local<Value> format);
/* static const char* DATE_FORMAT_SHORT = "short"; */
static const char* DATE_FORMAT_MEDIUM = "medium";
static const char* DATE_FORMAT_LONG = "long";
static NativeStringInterface* s_theInstance = NULL;
const NativeStringInterface* NativeStringInterface::instance()
{
if (s_theInstance == NULL)
{
s_theInstance = new NativeStringInterface;
}
return s_theInstance;
}
void NativeStringInterface::deleteInstance()
{
delete s_theInstance;
s_theInstance = NULL;
}
Handle<Value> NativeStringInterface::format(const Arguments& args)
{
if (args.Length() < 1)
{
ThrowException(String::New(Native::Msg::Expected_argument_of_type_string));
return Undefined();
}
Local<Value> format = args[0]->ToString();
const String::Utf8Value utf8(format);
QString str = QString::fromUtf8(*utf8);
/* Define a regex to match the % tokens of the format string
* cap(0): the whole matched token
* cap(1): the 'n$' token if present (numbered args)
* cap(2): the 'n' token from the above 'n$' token
* cap(3): the specifier char
*/
QRegExp rx("%((\\d+)\\$)?.*([diouxXfFeEgGaAcspCSn%])");
rx.setMinimal(true);
QString res;
QTextStream ts(&res);
int start = 0, end = 0, i = 0;
while ((end = rx.indexIn(str, end)) != -1 && ++i < args.Length())
{
end += rx.matchedLength();
QString tmp = str.mid(start, end - start);
int argN = i;
/* Look for numbered argument */
if (!rx.cap(2).isEmpty())
{
bool ok;
argN = rx.cap(2).toInt(&ok);
if (!ok)
{
ThrowException(String::New(Native::Msg::An_error_occurred_converting_to_int));
return Undefined();
}
if (argN >= args.Length() || argN <= 0)
{
ThrowException(String::New(Native::Msg::Numbered_argument_exceeds_the_length_of_provided_arguments));
return Undefined();
}
/* Remove the 'n$' token from the string as qt doesn't do numbered args */
tmp.remove(rx.cap(1));
/* Don't consume an argument as with numbered args there can be less args than placeholders
due to args being allowed to be used more than once */
--i;
}
switch (rx.cap(3).at(0).toAscii())
{
/* Specifiers that don't take an argument */
case '%':
--i;
continue;
/* %n: doesn't make sense in the JS context */
case 'n':
/* rewind end and remove the token from the format string, ignore the associated arg */
end -= rx.matchedLength();
str.remove(end, rx.matchedLength());
continue;
/* Signed int */
case 'd':
case 'i':
case 'c':
case 'C': // same as %lc
ts << formatInt(tmp, args[argN]);
break;
/* Unsigned int */
case 'o':
case 'u':
case 'x':
case 'X':
ts << formatUInt(tmp, args[argN]);
break;
/* Double */
case 'f':
case 'F':
case 'e':
case 'E':
case 'g':
case 'G':
case 'a':
case 'A':
ts << formatDouble(tmp, args[argN]);
break;
/* String */
case 's':
case 'S': // same as %ls
ts << formatString(tmp, args[argN]);
break;
/* Pointer */
case 'p':
ts << formatPointer(tmp, args[argN]);
break;
default:
ThrowException(String::New(Native::Msg::INTERNAL__An_error_occurred_while_parsing_the_format_string));
break;
}
start = end;
}
ts << str.sprintf(str.mid(start).toLatin1().constData());
// Warning str contains the result of the sprintf call at this point
Handle<String> result = String::New(res.toUtf8());
return (result);
}
Handle<Value> NativeStringInterface::formatCurrency(const Arguments& args)
{
if (args.Length() < 1 || (!args[0]->IsNumber() && !args[0]->IsNumberObject()))
{
ThrowException(String::New(Native::Msg::Expected_argument_of_type_integer));
return Undefined();
}
Handle<Number> num = Handle<Number>::Cast(args[0]);
QString strRes = QLocale().toCurrencyString(num->Value());
Handle<String> result = String::New(strRes.toUtf8());
return (result);
}
Handle<Value> NativeStringInterface::formatDate(const Arguments& args)
{
// TODO: Revisit format part when R6 available
if (args.Length() < 1 || !args[0]->IsDate())
{
ThrowException(String::New(Native::Msg::Expected_argument_of_type_Date));
return Undefined();
}
Local<Value> value = args[0];
unsigned int year = 0, month = 0, day = 0;
Local<Object> obj = Object::Cast(*value);
// Get year property
Local<Value> getYear_prop = (obj->Get(String::New("getFullYear")));
if (getYear_prop->IsFunction())
{
Local<Function> getYear_func = Function::Cast(*getYear_prop);
Local<Value> yearValue = getYear_func->Call(obj, 0, NULL);
year = yearValue->NumberValue();
}
// Get month property
Local<Value> getMonth_prop = (obj->Get(String::New("getMonth")));
if (getMonth_prop->IsFunction())
{
Local<Function> getMonth_func = Function::Cast(*getMonth_prop);
Local<Value> monthValue = getMonth_func->Call(obj, 0, NULL);
month = monthValue->NumberValue();
}
// Get day property
Local<Value> getDay_prop = (obj->Get(String::New("getDate")));
if (getDay_prop->IsFunction())
{
Local<Function> getDay_func = Function::Cast(*getDay_prop);
Local<Value> dayValue = getDay_func->Call(obj, 0, NULL);
day = dayValue->NumberValue();
}
// Defaults to NarrowFormat
QLocale::FormatType fType = QLocale::NarrowFormat;
// Try to parse optional format argument
if (args.Length() > 1)
{
fType = parseFormat(args[1]);
}
// Adding +1 to month, since it starting from 0
QDate date(year, month + 1, day);
QString strRes = QLocale().toString(date, fType);
Handle<String> result = String::New(strRes.toUtf8());
return (result);
}
Handle<Value> NativeStringInterface::formatDecimal(const Arguments& args)
{
if (args.Length() < 1 || (!args[0]->IsNumber() && !args[0]->IsNumberObject()))
{
ThrowException(String::New(Native::Msg::Expected_argument_of_type_integer));
return Undefined();
}
Handle<Number> num = Handle<Number>::Cast(args[0]);
QString strRes = QLocale().toString(num->Value());
// TODO: parse optional parameters: locale & pattern
Handle<String> result = String::New(strRes.toUtf8());
return (result);
}
Handle<Value> NativeStringInterface::formatTime(const Arguments& args)
{
// TODO: Revisit format part when R6 available
if (args.Length() < 1 || !args[0]->IsDate())
{
ThrowException(String::New(Native::Msg::Expected_argument_of_type_Date));
return Undefined();
}
Local<Value> value = args[0];
int hours = 0, minutes = 0, seconds = 0, msecs = 0;
Local<Object> obj = Object::Cast(*value);
// Get hours property
Local<Value> getHours_prop = (obj->Get(String::New("getHours")));
if (getHours_prop->IsFunction())
{
Local<Function> getHours_func = Function::Cast(*getHours_prop);
Local<Value> hoursValue = getHours_func->Call(obj, 0, NULL);
hours = hoursValue->NumberValue();
}
// Get minute property
Local<Value> getMinutes_prop = (obj->Get(String::New("getMinutes")));
if (getMinutes_prop->IsFunction())
{
Local<Function> getMinutes_func = Function::Cast(*getMinutes_prop);
Local<Value> minutesValue = getMinutes_func->Call(obj, 0, NULL);
minutes = minutesValue->NumberValue();
}
// Get seconds property
Local<Value> getSeconds_prop = (obj->Get(String::New("getSeconds")));
if (getSeconds_prop->IsFunction())
{
Local<Function> getSeconds_func = Function::Cast(*getSeconds_prop);
Local<Value> secondsValue = getSeconds_func->Call(obj, 0, NULL);
seconds = secondsValue->NumberValue();
}
// Get milliseconds property
Local<Value> getMsecs_prop = (obj->Get(String::New("getMilliseconds")));
if (getMsecs_prop->IsFunction())
{
Local<Function> getMsecs_func = Function::Cast(*getMsecs_prop);
Local<Value> msecsValue = getMsecs_func->Call(obj, 0, NULL);
msecs = msecsValue->NumberValue();
}
// Defaults to NarrowFormat
QLocale::FormatType fType = QLocale::NarrowFormat;
// Try to parse optional format argument
if (args.Length() > 1)
{
fType = parseFormat(args[1]);
}
QTime time = QTime(hours, minutes, seconds, msecs);
QString strRes = QLocale().toString(time, fType);
Handle<String> result = String::New(strRes.toUtf8());
return (result);
}
/* Static Helpers */
static QString formatInt(QString s, Local<Value> arg)
{
if (arg->IsNumber() || arg->IsNumberObject())
{
if (s.endsWith('C'))
{
// QString::sprintf doesn't support %C
s.replace(s.size() - 1, 1, "lc");
}
if (s.right(3).startsWith("ll"))
{
int64_t v = arg->IntegerValue();
return s.sprintf(s.toLatin1().constData(), v);
}
int v = arg->Int32Value();
return s.sprintf(s.toLatin1().constData(), v);
}
ThrowException(String::New(Native::Msg::Expected_argument_of_type_integer));
return QString();
}
static QString formatUInt(QString s, Local<Value> arg)
{
if (arg->IsNumber() || arg->IsNumberObject())
{
if (s.right(3).startsWith("ll"))
{
int64_t v = arg->IntegerValue();
return s.sprintf(s.toLatin1().constData(), v);
}
unsigned int v = arg->Uint32Value();
return s.sprintf(s.toLatin1().constData(), v);
}
ThrowException(String::New(Native::Msg::Expected_argument_of_type_unsigned_integer));
return QString();
}
static QString formatDouble(QString s, Local<Value> arg)
{
if (arg->IsNumber() || arg->IsNumberObject())
{
if (s.right(2).startsWith('L'))
{
// cast to long double to match the specifier although V8 only has double precision
long double v = static_cast<long double>(arg->NumberValue());
return s.sprintf(s.toLatin1().constData(), v);
}
double v = arg->NumberValue();
return s.sprintf(s.toLatin1().constData(), v);
}
ThrowException(String::New(Native::Msg::Expected_argument_of_type_double));
return QString();
}
static QString formatString(QString s, Local<Value> arg)
{
if (s.endsWith('S'))
{
// QString::sprintf doesn't support %S
s.replace(s.size() - 1, 1, "ls");
}
bool longChar = s.endsWith("ls");
arg = arg->ToString();
if (longChar)
{
String::Value utf16(arg);
return s.sprintf(s.toLatin1().constData(), *utf16);
}
else
{
String::Utf8Value utf8(arg);
return s.sprintf(s.toLatin1().constData(), *utf8);
}
}
static QString formatPointer(QString s, Local<Value> arg)
{
if (arg->IsObject() && s.endsWith('p'))
{
s.replace(s.size() - 1, 1, "i");
return s.sprintf(s.toLatin1().constData(), arg->ToObject()->GetIdentityHash());
}
else if (arg->IsExternal())
{
return s.sprintf(s.toLatin1().constData(), External::Unwrap(arg));
}
ThrowException(String::New(Native::Msg::Expected_argument_of_type_object_or_external));
return QString();
}
static QLocale::FormatType parseFormat(Local<Value> format)
{
QLocale::FormatType fType = QLocale::NarrowFormat;
if (!format->IsString())
{
format = format->ToString();
}
const String::Utf8Value utf8(format);
QString strFormat = QString::fromUtf8(*utf8);
if (strFormat.compare(DATE_FORMAT_MEDIUM) == 0)
{
fType = QLocale::ShortFormat;
}
else if (strFormat.compare(DATE_FORMAT_LONG) == 0)
{
fType = QLocale::LongFormat;
}
return fType;
}