1/*
2 *******************************************************************************
3 *
4 *   Copyright (C) 1999-2014, International Business Machines
5 *   Corporation and others.  All Rights Reserved.
6 *
7 *******************************************************************************
8 *   file name:  letsutil.cpp
9 *
10 *   created on: 04/25/2006
11 *   created by: Eric R. Mader
12 */
13
14#include "unicode/utypes.h"
15#include "unicode/unistr.h"
16#include "unicode/ubidi.h"
17
18#include "layout/LETypes.h"
19#include "layout/LEScripts.h"
20#include "layout/LayoutEngine.h"
21#include "layout/LELanguages.h"
22
23#ifndef USING_ICULEHB
24#include "OpenTypeLayoutEngine.h"
25#endif
26
27#include "letest.h"
28#include "letsutil.h"
29
30U_NAMESPACE_USE
31
32char *getCString(const UnicodeString *uString)
33{
34    if (uString == NULL) {
35        return NULL;
36    }
37
38    le_int32 uLength = uString->length();
39    le_int32 cLength = uString->extract(0, uLength, NULL, 0, US_INV);
40    char *cString = NEW_ARRAY(char, cLength + 1);
41
42    uString->extract(0, uLength, cString, cLength, US_INV);
43    cString[cLength] = '\0';
44
45    return cString;
46}
47
48char *getCString(const LEUnicode16 *uChars)
49{
50    if (uChars == NULL) {
51        return NULL;
52    }
53
54    const UnicodeString ustring(uChars);
55
56    return getCString(&ustring);
57}
58
59char *getUTF8String(const UnicodeString *uString)
60{
61    if (uString == NULL) {
62        return NULL;
63    }
64
65    le_int32 uLength = uString->length();
66    le_int32 cLength = uString->extract(0, uLength, NULL, 0, "UTF-8");
67    char *cString = NEW_ARRAY(char, cLength + 1);
68
69    uString->extract(0, uLength, cString, cLength, "UTF-8");
70
71    cString[cLength] = '\0';
72
73    return cString;
74}
75
76void freeCString(char *cString)
77{
78    DELETE_ARRAY(cString);
79}
80
81le_bool getRTL(const UnicodeString &text)
82{
83    UBiDiLevel level = 0;
84    UErrorCode status = U_ZERO_ERROR;
85    le_int32 charCount = text.length();
86    le_int32 limit = -1;
87    UBiDi *ubidi = ubidi_openSized(charCount, 0, &status);
88
89    ubidi_setPara(ubidi, text.getBuffer(), charCount, UBIDI_DEFAULT_LTR, NULL, &status);
90
91    // TODO: Should check that there's only a single logical run...
92    ubidi_getLogicalRun(ubidi, 0, &limit, &level);
93
94    ubidi_close(ubidi);
95
96    return level & 1;
97}
98
99le_int32 getLanguageCode(const char *lang)
100{
101    if (strlen(lang) != 3) {
102        return -1;
103    }
104
105    LETag langTag = (LETag) ((lang[0] << 24) + (lang[1] << 16) + (lang[2] << 8) + 0x20);
106
107#ifndef USING_ICULEHB
108    for (le_int32 i = 0; i < languageCodeCount; i += 1) {
109        if (langTag == OpenTypeLayoutEngine::languageTags[i]) {
110            return i;
111        }
112    }
113#endif
114
115    return -1;
116}
117
118