usp10: Rewrite of ScriptXtoCP to handle pwLogClust for LTR and RTL runs.
[wine] / dlls / usp10 / usp10.c
1 /*
2  * Implementation of Uniscribe Script Processor (usp10.dll)
3  *
4  * Copyright 2005 Steven Edwards for CodeWeavers
5  * Copyright 2006 Hans Leidekker
6  * Copyright 2010 CodeWeavers, Aric Stewart
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  *
22  * Notes:
23  * Uniscribe allows for processing of complex scripts such as joining
24  * and filtering characters and bi-directional text with custom line breaks.
25  */
26
27 #include <stdarg.h>
28
29 #include "windef.h"
30 #include "winbase.h"
31 #include "wingdi.h"
32 #include "winuser.h"
33 #include "winnls.h"
34 #include "usp10.h"
35
36 #include "usp10_internal.h"
37
38 #include "wine/debug.h"
39 #include "wine/unicode.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(uniscribe);
42
43 typedef struct _scriptRange
44 {
45     WORD script;
46     WORD rangeFirst;
47     WORD rangeLast;
48     WORD numericScript;
49     WORD punctScript;
50 } scriptRange;
51
52 static const scriptRange scriptRanges[] = {
53     /* Basic Latin: U+0000–U+007A */
54     /* Latin-1 Supplement: U+0080–U+00FF */
55     /* Latin Extended-A: U+0100–U+017F */
56     /* Latin Extended-B: U+0180–U+024F */
57     /* IPA Extensions: U+0250–U+02AF */
58     { Script_Latin,      0x00,   0x2af ,  Script_Numeric, Script_Punctuation},
59     /* Greek: U+0370–U+03FF */
60     { Script_Greek,      0x370,  0x3ff,  0, 0},
61     /* Cyrillic: U+0400–U+04FF */
62     /* Cyrillic Supplement: U+0500–U+052F */
63     { Script_Cyrillic,   0x400,  0x52f,  0, 0},
64     /* Armenian: U+0530–U+058F */
65     { Script_Armenian,   0x530,  0x58f,  0, 0},
66     /* Hebrew: U+0590–U+05FF */
67     { Script_Hebrew,     0x590,  0x5ff,  0, 0},
68     /* Arabic: U+0600–U+06FF */
69     { Script_Arabic,     0x600,  0x6ef,  Script_Arabic_Numeric, 0},
70     /* Defined by Windows */
71     { Script_Persian,    0x6f0,  0x6f9,  0, 0},
72     /* Continue Arabic: U+0600–U+06FF */
73     { Script_Arabic,     0x6fa,  0x6ff,  0, 0},
74     /* Syriac: U+0700–U+074F*/
75     { Script_Syriac,     0x700,  0x74f,  0, 0},
76     /* Arabic Supplement: U+0750–U+077F */
77     { Script_Arabic,     0x750,  0x77f,  0, 0},
78     /* Thaana: U+0780–U+07BF */
79     { Script_Thaana,     0x780,  0x7bf,  0, 0},
80     /* Sinhala: U+0D80–U+0DFF */
81     { Script_Sinhala,   0xd80,  0xdff,  0, 0},
82     /* Thai: U+0E00–U+0E7F */
83     { Script_Thai,      0xe00,  0xe7f,  Script_Thai_Numeric, 0},
84     /* Lao: U+0E80–U+0EFF */
85     { Script_Lao,       0xe80,  0xeff,  Script_Lao_Numeric, 0},
86     /* Tibetan: U+0F00–U+0FFF */
87     { Script_Tibetan,   0xf00,  0xfff,  Script_Tibetan_Numeric, 0},
88     /* Georgian: U+10A0–U+10FF */
89     { Script_Georgian,   0x10a0,  0x10ff,  0, 0},
90     /* Phonetic Extensions: U+1D00–U+1DBF */
91     { Script_Latin,      0x1d00, 0x1dbf, 0, 0},
92     /* Latin Extended Additional: U+1E00–U+1EFF */
93     { Script_Latin,      0x1e00, 0x1eff, 0, 0},
94     /* Greek Extended: U+1F00–U+1FFF */
95     { Script_Greek,      0x1f00, 0x1fff, 0, 0},
96     /* Latin Extended-C: U+2C60–U+2C7F */
97     { Script_Latin,      0x2c60, 0x2c7f, 0, 0},
98     /* Georgian: U+2D00–U+2D2F */
99     { Script_Georgian,   0x2d00,  0x2d2f,  0, 0},
100     /* Cyrillic Extended-A: U+2DE0–U+2DFF */
101     { Script_Cyrillic,   0x2de0, 0x2dff,  0, 0},
102     /* Cyrillic Extended-B: U+A640–U+A69F */
103     { Script_Cyrillic,   0xa640, 0xa69f,  0, 0},
104     /* Modifier Tone Letters: U+A700–U+A71F */
105     /* Latin Extended-D: U+A720–U+A7FF */
106     { Script_Latin,      0xa700, 0xa7ff, 0, 0},
107     /* Phags-pa: U+A840–U+A87F */
108     { Script_Phags_pa,   0xa840, 0xa87f, 0, 0},
109     /* Latin Ligatures: U+FB00–U+FB06 */
110     { Script_Latin,      0xfb00, 0xfb06, 0, 0},
111     /* Armenian ligatures U+FB13..U+FB17 */
112     { Script_Armenian,   0xfb13, 0xfb17,  0, 0},
113     /* Alphabetic Presentation Forms: U+FB1D–U+FB4F */
114     { Script_Hebrew,     0xfb1d, 0xfb4f, 0, 0},
115     /* Arabic Presentation Forms-A: U+FB50–U+FDFF*/
116     { Script_Arabic,     0xfb50, 0xfdff, 0, 0},
117     /* Arabic Presentation Forms-B: U+FE70–U+FEFF*/
118     { Script_Arabic,     0xfe70, 0xfeff, 0, 0},
119     /* END */
120     { SCRIPT_UNDEFINED,  0, 0, 0}
121 };
122
123 typedef struct _scriptData
124 {
125     SCRIPT_ANALYSIS a;
126     SCRIPT_PROPERTIES props;
127 } scriptData;
128
129 /* the must be in order so that the index matches the Script value */
130 static const scriptData scriptInformation[] = {
131     {{SCRIPT_UNDEFINED, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
132      {LANG_NEUTRAL, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
133     {{Script_Latin, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
134      {LANG_ENGLISH, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0}},
135     {{Script_CR, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
136      {LANG_NEUTRAL, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
137     {{Script_Numeric, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
138      {LANG_ENGLISH, 1, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
139     {{Script_Control, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
140      {LANG_ENGLISH, 0, 1, 0, 0, ANSI_CHARSET, 1, 0, 0, 0, 0, 0, 1, 0, 0}},
141     {{Script_Punctuation, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
142      {LANG_NEUTRAL, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
143     {{Script_Arabic, 1, 1, 0, 0, 0, 0, { 1,0,0,0,0,0,0,0,0,0,0}},
144      {LANG_ARABIC, 0, 1, 0, 0, ARABIC_CHARSET, 0, 0, 0, 0, 0, 0, 1, 1, 0}},
145     {{Script_Arabic_Numeric, 1, 1, 0, 0, 0, 0, { 1,0,0,0,0,0,0,0,0,0,0}},
146      {LANG_ARABIC, 1, 1, 0, 0, ARABIC_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0}},
147     {{Script_Hebrew, 1, 1, 0, 0, 0, 0, { 1,0,0,0,0,0,0,0,0,0,0}},
148      {LANG_HEBREW, 0, 1, 0, 1, HEBREW_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
149     {{Script_Syriac, 1, 1, 0, 0, 0, 0, { 1,0,0,0,0,0,0,0,0,0,0}},
150      {LANG_SYRIAC, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 1, 0, 0, 1, 0}},
151     {{Script_Persian, 1, 1, 0, 0, 0, 0, { 1,0,0,0,0,0,0,0,0,0,0}},
152      {LANG_PERSIAN, 1, 1, 0, 0, ARABIC_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
153     {{Script_Thaana, 1, 1, 0, 0, 0, 0, { 1,0,0,0,0,0,0,0,0,0,0}},
154      {LANG_DIVEHI, 0, 1, 0, 1, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
155     {{Script_Greek, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
156      {LANG_GREEK, 0, 0, 0, 0, GREEK_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
157     {{Script_Cyrillic, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
158      {LANG_RUSSIAN, 0, 0, 0, 0, RUSSIAN_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
159     {{Script_Armenian, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
160      {LANG_ARMENIAN, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0}},
161     {{Script_Georgian, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
162      {LANG_GEORGIAN, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, 0, 0, 0, 1, 0, 0}},
163     {{Script_Sinhala, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
164      {LANG_SINHALESE, 0, 1, 0, 1, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
165     {{Script_Tibetan, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
166      {LANG_TIBETAN, 0, 1, 1, 1, DEFAULT_CHARSET, 0, 0, 1, 0, 1, 0, 0, 0, 0}},
167     {{Script_Tibetan_Numeric, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
168      {LANG_TIBETAN, 1, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
169     {{Script_Phags_pa, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
170      {LANG_MONGOLIAN, 0, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
171     {{Script_Thai, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
172      {LANG_THAI, 0, 1, 1, 1, THAI_CHARSET, 0, 0, 1, 0, 1, 0, 0, 0, 1}},
173     {{Script_Thai_Numeric, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
174      {LANG_THAI, 1, 1, 0, 0, THAI_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
175     {{Script_Lao, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
176      {LANG_LAO, 0, 1, 1, 1, DEFAULT_CHARSET, 0, 0, 1, 0, 1, 0, 0, 0, 0}},
177     {{Script_Lao_Numeric, 0, 0, 0, 0, 0, 0, { 0,0,0,0,0,0,0,0,0,0,0}},
178      {LANG_LAO, 1, 1, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
179 };
180
181 static const SCRIPT_PROPERTIES *script_props[] =
182 {
183     &scriptInformation[0].props, &scriptInformation[1].props,
184     &scriptInformation[2].props, &scriptInformation[3].props,
185     &scriptInformation[4].props, &scriptInformation[5].props,
186     &scriptInformation[6].props, &scriptInformation[7].props,
187     &scriptInformation[8].props, &scriptInformation[9].props,
188     &scriptInformation[10].props, &scriptInformation[11].props,
189     &scriptInformation[12].props, &scriptInformation[13].props,
190     &scriptInformation[14].props, &scriptInformation[15].props,
191     &scriptInformation[16].props, &scriptInformation[17].props,
192     &scriptInformation[18].props, &scriptInformation[19].props,
193     &scriptInformation[20].props, &scriptInformation[21].props,
194     &scriptInformation[22].props, &scriptInformation[23].props
195 };
196
197 typedef struct {
198     int numGlyphs;
199     WORD* glyphs;
200     WORD* pwLogClust;
201     int* piAdvance;
202     SCRIPT_VISATTR* psva;
203     GOFFSET* pGoffset;
204     ABC* abc;
205 } StringGlyphs;
206
207 typedef struct {
208     HDC hdc;
209     BOOL invalid;
210     int clip_len;
211     ScriptCache *sc;
212     int cItems;
213     int cMaxGlyphs;
214     SCRIPT_ITEM* pItem;
215     int numItems;
216     StringGlyphs* glyphs;
217     SCRIPT_LOGATTR* logattrs;
218     SIZE* sz;
219 } StringAnalysis;
220
221 static inline void *heap_alloc(SIZE_T size)
222 {
223     return HeapAlloc(GetProcessHeap(), 0, size);
224 }
225
226 static inline void *heap_alloc_zero(SIZE_T size)
227 {
228     return HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
229 }
230
231 static inline void *heap_realloc_zero(LPVOID mem, SIZE_T size)
232 {
233     return HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, mem, size);
234 }
235
236 static inline BOOL heap_free(LPVOID mem)
237 {
238     return HeapFree(GetProcessHeap(), 0, mem);
239 }
240
241 static inline WCHAR get_cache_default_char(SCRIPT_CACHE *psc)
242 {
243     return ((ScriptCache *)*psc)->tm.tmDefaultChar;
244 }
245
246 static inline LONG get_cache_height(SCRIPT_CACHE *psc)
247 {
248     return ((ScriptCache *)*psc)->tm.tmHeight;
249 }
250
251 static inline BYTE get_cache_pitch_family(SCRIPT_CACHE *psc)
252 {
253     return ((ScriptCache *)*psc)->tm.tmPitchAndFamily;
254 }
255
256 static inline WORD get_cache_glyph(SCRIPT_CACHE *psc, WCHAR c)
257 {
258     WORD *block = ((ScriptCache *)*psc)->glyphs[c >> GLYPH_BLOCK_SHIFT];
259
260     if (!block) return 0;
261     return block[c & GLYPH_BLOCK_MASK];
262 }
263
264 static inline WORD set_cache_glyph(SCRIPT_CACHE *psc, WCHAR c, WORD glyph)
265 {
266     WORD **block = &((ScriptCache *)*psc)->glyphs[c >> GLYPH_BLOCK_SHIFT];
267
268     if (!*block && !(*block = heap_alloc_zero(sizeof(WORD) * GLYPH_BLOCK_SIZE))) return 0;
269     return ((*block)[c & GLYPH_BLOCK_MASK] = glyph);
270 }
271
272 static inline BOOL get_cache_glyph_widths(SCRIPT_CACHE *psc, WORD glyph, ABC *abc)
273 {
274     static const ABC nil;
275     ABC *block = ((ScriptCache *)*psc)->widths[glyph >> GLYPH_BLOCK_SHIFT];
276
277     if (!block || !memcmp(&block[glyph & GLYPH_BLOCK_MASK], &nil, sizeof(ABC))) return FALSE;
278     memcpy(abc, &block[glyph & GLYPH_BLOCK_MASK], sizeof(ABC));
279     return TRUE;
280 }
281
282 static inline BOOL set_cache_glyph_widths(SCRIPT_CACHE *psc, WORD glyph, ABC *abc)
283 {
284     ABC **block = &((ScriptCache *)*psc)->widths[glyph >> GLYPH_BLOCK_SHIFT];
285
286     if (!*block && !(*block = heap_alloc_zero(sizeof(ABC) * GLYPH_BLOCK_SIZE))) return FALSE;
287     memcpy(&(*block)[glyph & GLYPH_BLOCK_MASK], abc, sizeof(ABC));
288     return TRUE;
289 }
290
291 static HRESULT init_script_cache(const HDC hdc, SCRIPT_CACHE *psc)
292 {
293     ScriptCache *sc;
294
295     if (!psc) return E_INVALIDARG;
296     if (*psc) return S_OK;
297     if (!hdc) return E_PENDING;
298
299     if (!(sc = heap_alloc_zero(sizeof(ScriptCache)))) return E_OUTOFMEMORY;
300     if (!GetTextMetricsW(hdc, &sc->tm))
301     {
302         heap_free(sc);
303         return E_INVALIDARG;
304     }
305     if (!GetObjectW(GetCurrentObject(hdc, OBJ_FONT), sizeof(LOGFONTW), &sc->lf))
306     {
307         heap_free(sc);
308         return E_INVALIDARG;
309     }
310     *psc = sc;
311     TRACE("<- %p\n", sc);
312     return S_OK;
313 }
314
315 static WCHAR mirror_char( WCHAR ch )
316 {
317     extern const WCHAR wine_mirror_map[];
318     return ch + wine_mirror_map[wine_mirror_map[ch >> 8] + (ch & 0xff)];
319 }
320
321 static WORD get_char_script( WCHAR ch)
322 {
323     WORD type = 0;
324     int i;
325
326     if (ch == 0xc || ch == 0x20 || ch == 0x202f)
327         return Script_CR;
328
329     GetStringTypeW(CT_CTYPE1, &ch, 1, &type);
330
331     if (type == 0)
332         return SCRIPT_UNDEFINED;
333
334     if (type & C1_CNTRL)
335         return Script_Control;
336
337     i = 0;
338     do
339     {
340         if (ch < scriptRanges[i].rangeFirst || scriptRanges[i].script == SCRIPT_UNDEFINED)
341             break;
342
343         if (ch >= scriptRanges[i].rangeFirst && ch <= scriptRanges[i].rangeLast)
344         {
345             if (scriptRanges[i].numericScript && type & C1_DIGIT)
346                 return scriptRanges[i].numericScript;
347             if (scriptRanges[i].punctScript && type & C1_PUNCT)
348                 return scriptRanges[i].punctScript;
349             return scriptRanges[i].script;
350         }
351         i++;
352     } while (1);
353
354     return SCRIPT_UNDEFINED;
355 }
356
357 /***********************************************************************
358  *      DllMain
359  *
360  */
361 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpv)
362 {
363     switch(fdwReason)
364     {
365     case DLL_PROCESS_ATTACH:
366         DisableThreadLibraryCalls(hInstDLL);
367         break;
368     case DLL_PROCESS_DETACH:
369         break;
370     }
371     return TRUE;
372 }
373
374 /***********************************************************************
375  *      ScriptFreeCache (USP10.@)
376  *
377  * Free a script cache.
378  *
379  * PARAMS
380  *   psc [I/O] Script cache.
381  *
382  * RETURNS
383  *  Success: S_OK
384  *  Failure: Non-zero HRESULT value.
385  */
386 HRESULT WINAPI ScriptFreeCache(SCRIPT_CACHE *psc)
387 {
388     TRACE("%p\n", psc);
389
390     if (psc && *psc)
391     {
392         unsigned int i;
393         for (i = 0; i < GLYPH_MAX / GLYPH_BLOCK_SIZE; i++)
394         {
395             heap_free(((ScriptCache *)*psc)->glyphs[i]);
396             heap_free(((ScriptCache *)*psc)->widths[i]);
397         }
398         heap_free(((ScriptCache *)*psc)->GSUB_Table);
399         heap_free(((ScriptCache *)*psc)->features);
400         heap_free(*psc);
401         *psc = NULL;
402     }
403     return S_OK;
404 }
405
406 /***********************************************************************
407  *      ScriptGetProperties (USP10.@)
408  *
409  * Retrieve a list of script properties.
410  *
411  * PARAMS
412  *  props [I] Pointer to an array of SCRIPT_PROPERTIES pointers.
413  *  num   [I] Pointer to the number of scripts.
414  *
415  * RETURNS
416  *  Success: S_OK
417  *  Failure: Non-zero HRESULT value.
418  *
419  * NOTES
420  *  Behaviour matches WinXP.
421  */
422 HRESULT WINAPI ScriptGetProperties(const SCRIPT_PROPERTIES ***props, int *num)
423 {
424     TRACE("(%p,%p)\n", props, num);
425
426     if (!props && !num) return E_INVALIDARG;
427
428     if (num) *num = sizeof(script_props)/sizeof(script_props[0]);
429     if (props) *props = script_props;
430
431     return S_OK;
432 }
433
434 /***********************************************************************
435  *      ScriptGetFontProperties (USP10.@)
436  *
437  * Get information on special glyphs.
438  *
439  * PARAMS
440  *  hdc [I]   Device context.
441  *  psc [I/O] Opaque pointer to a script cache.
442  *  sfp [O]   Font properties structure.
443  */
444 HRESULT WINAPI ScriptGetFontProperties(HDC hdc, SCRIPT_CACHE *psc, SCRIPT_FONTPROPERTIES *sfp)
445 {
446     HRESULT hr;
447
448     TRACE("%p,%p,%p\n", hdc, psc, sfp);
449
450     if (!sfp) return E_INVALIDARG;
451     if ((hr = init_script_cache(hdc, psc)) != S_OK) return hr;
452
453     if (sfp->cBytes != sizeof(SCRIPT_FONTPROPERTIES))
454         return E_INVALIDARG;
455
456     /* return something sensible? */
457     sfp->wgBlank = 0;
458     sfp->wgDefault = get_cache_default_char(psc);
459     sfp->wgInvalid = 0;
460     sfp->wgKashida = 0xffff;
461     sfp->iKashidaWidth = 0;
462
463     return S_OK;
464 }
465
466 /***********************************************************************
467  *      ScriptRecordDigitSubstitution (USP10.@)
468  *
469  *  Record digit substitution settings for a given locale.
470  *
471  *  PARAMS
472  *   locale [I] Locale identifier.
473  *   sds    [I] Structure to record substitution settings.
474  *
475  *  RETURNS
476  *   Success: S_OK
477  *   Failure: E_POINTER if sds is NULL, E_INVALIDARG otherwise.
478  *
479  *  SEE ALSO
480  *   http://blogs.msdn.com/michkap/archive/2006/02/22/536877.aspx
481  */
482 HRESULT WINAPI ScriptRecordDigitSubstitution(LCID locale, SCRIPT_DIGITSUBSTITUTE *sds)
483 {
484     DWORD plgid, sub;
485
486     TRACE("0x%x, %p\n", locale, sds);
487
488     /* This implementation appears to be correct for all languages, but it's
489      * not clear if sds->DigitSubstitute is ever set to anything except 
490      * CONTEXT or NONE in reality */
491
492     if (!sds) return E_POINTER;
493
494     locale = ConvertDefaultLocale(locale);
495
496     if (!IsValidLocale(locale, LCID_INSTALLED))
497         return E_INVALIDARG;
498
499     plgid = PRIMARYLANGID(LANGIDFROMLCID(locale));
500     sds->TraditionalDigitLanguage = plgid;
501
502     if (plgid == LANG_ARABIC || plgid == LANG_FARSI)
503         sds->NationalDigitLanguage = plgid;
504     else
505         sds->NationalDigitLanguage = LANG_ENGLISH;
506
507     if (!GetLocaleInfoW(locale, LOCALE_IDIGITSUBSTITUTION | LOCALE_RETURN_NUMBER,
508                         (LPWSTR)&sub, sizeof(sub)/sizeof(WCHAR))) return E_INVALIDARG;
509
510     switch (sub)
511     {
512     case 0: 
513         if (plgid == LANG_ARABIC || plgid == LANG_FARSI)
514             sds->DigitSubstitute = SCRIPT_DIGITSUBSTITUTE_CONTEXT;
515         else
516             sds->DigitSubstitute = SCRIPT_DIGITSUBSTITUTE_NONE;
517         break;
518     case 1:
519         sds->DigitSubstitute = SCRIPT_DIGITSUBSTITUTE_NONE;
520         break;
521     case 2:
522         sds->DigitSubstitute = SCRIPT_DIGITSUBSTITUTE_NATIONAL;
523         break;
524     default:
525         sds->DigitSubstitute = SCRIPT_DIGITSUBSTITUTE_TRADITIONAL;
526         break;
527     }
528
529     sds->dwReserved = 0;
530     return S_OK;
531 }
532
533 /***********************************************************************
534  *      ScriptApplyDigitSubstitution (USP10.@)
535  *
536  *  Apply digit substitution settings.
537  *
538  *  PARAMS
539  *   sds [I] Structure with recorded substitution settings.
540  *   sc  [I] Script control structure.
541  *   ss  [I] Script state structure.
542  *
543  *  RETURNS
544  *   Success: S_OK
545  *   Failure: E_INVALIDARG if sds is invalid. Otherwise an HRESULT.
546  */
547 HRESULT WINAPI ScriptApplyDigitSubstitution(const SCRIPT_DIGITSUBSTITUTE *sds, 
548                                             SCRIPT_CONTROL *sc, SCRIPT_STATE *ss)
549 {
550     SCRIPT_DIGITSUBSTITUTE psds;
551
552     TRACE("%p, %p, %p\n", sds, sc, ss);
553
554     if (!sc || !ss) return E_POINTER;
555     if (!sds)
556     {
557         sds = &psds;
558         if (ScriptRecordDigitSubstitution(LOCALE_USER_DEFAULT, &psds) != S_OK)
559             return E_INVALIDARG;
560     }
561
562     sc->uDefaultLanguage = LANG_ENGLISH;
563     sc->fContextDigits = 0;
564     ss->fDigitSubstitute = 0;
565
566     switch (sds->DigitSubstitute) {
567         case SCRIPT_DIGITSUBSTITUTE_CONTEXT:
568         case SCRIPT_DIGITSUBSTITUTE_NATIONAL:
569         case SCRIPT_DIGITSUBSTITUTE_NONE:
570         case SCRIPT_DIGITSUBSTITUTE_TRADITIONAL:
571             return S_OK;
572         default:
573             return E_INVALIDARG;
574     }
575 }
576
577 /***********************************************************************
578  *      ScriptItemize (USP10.@)
579  *
580  * Split a Unicode string into shapeable parts.
581  *
582  * PARAMS
583  *  pwcInChars [I] String to split.
584  *  cInChars   [I] Number of characters in pwcInChars.
585  *  cMaxItems  [I] Maximum number of items to return.
586  *  psControl  [I] Pointer to a SCRIPT_CONTROL structure.
587  *  psState    [I] Pointer to a SCRIPT_STATE structure.
588  *  pItems     [O] Buffer to receive SCRIPT_ITEM structures.
589  *  pcItems    [O] Number of script items returned.
590  *
591  * RETURNS
592  *  Success: S_OK
593  *  Failure: Non-zero HRESULT value.
594  */
595 HRESULT WINAPI ScriptItemize(const WCHAR *pwcInChars, int cInChars, int cMaxItems,
596                              const SCRIPT_CONTROL *psControl, const SCRIPT_STATE *psState,
597                              SCRIPT_ITEM *pItems, int *pcItems)
598 {
599
600 #define Numeric_space 0x0020
601
602     int   cnt = 0, index = 0, str = 0;
603     int   New_Script = SCRIPT_UNDEFINED;
604     WORD  *levels = NULL;
605     WORD  *strength = NULL;
606     WORD  baselevel = 0;
607
608     TRACE("%s,%d,%d,%p,%p,%p,%p\n", debugstr_wn(pwcInChars, cInChars), cInChars, cMaxItems, 
609           psControl, psState, pItems, pcItems);
610
611     if (!pwcInChars || !cInChars || !pItems || cMaxItems < 2)
612         return E_INVALIDARG;
613
614     if (psState && psControl)
615     {
616         int i;
617         levels = heap_alloc_zero(cInChars * sizeof(WORD));
618         if (!levels)
619             return E_OUTOFMEMORY;
620
621         BIDI_DetermineLevels(pwcInChars, cInChars, psState, psControl, levels);
622         baselevel = levels[0];
623         for (i = 0; i < cInChars; i++)
624             if (levels[i]!=levels[0])
625                 break;
626         if (i >= cInChars && !odd(baselevel))
627         {
628             heap_free(levels);
629             levels = NULL;
630         }
631         else
632         {
633             if (!psControl->fMergeNeutralItems)
634             {
635                 strength = heap_alloc_zero(cInChars * sizeof(WORD));
636                 BIDI_GetStrengths(pwcInChars, cInChars, psControl, strength);
637             }
638         }
639     }
640
641     while (pwcInChars[cnt] == Numeric_space && cnt < cInChars)
642         cnt++;
643
644     if (cnt == cInChars) /* All Spaces */
645     {
646         cnt = 0;
647         New_Script = get_char_script(pwcInChars[cnt]);
648     }
649
650     pItems[index].iCharPos = 0;
651     pItems[index].a = scriptInformation[get_char_script(pwcInChars[cnt])].a;
652
653     if (strength)
654         str = strength[cnt];
655
656     cnt = 0;
657     if (levels)
658     {
659         pItems[index].a.fRTL = odd(levels[cnt]);
660         pItems[index].a.fLayoutRTL = odd(levels[cnt]);
661         pItems[index].a.s.uBidiLevel = levels[cnt];
662     }
663     else if (!pItems[index].a.s.uBidiLevel)
664     {
665         pItems[index].a.s.uBidiLevel = baselevel;
666         pItems[index].a.fLayoutRTL = odd(baselevel);
667         pItems[index].a.fRTL = odd(baselevel);
668     }
669
670     TRACE("New_Level=%i New_Strength=%i New_Script=%d, eScript=%d index=%d cnt=%d iCharPos=%d\n",
671           levels?levels[cnt]:-1, str, New_Script, pItems[index].a.eScript, index, cnt,
672           pItems[index].iCharPos);
673
674     for (cnt=1; cnt < cInChars; cnt++)
675     {
676         if (levels && (levels[cnt] == pItems[index].a.s.uBidiLevel && (!strength || (strength[cnt] == 0 || strength[cnt] == str))))
677             continue;
678
679         if(pwcInChars[cnt] != Numeric_space)
680             New_Script = get_char_script(pwcInChars[cnt]);
681         else if (levels)
682         {
683             int j = 1;
684             while (cnt + j < cInChars - 1 && pwcInChars[cnt+j] == Numeric_space)
685                 j++;
686             New_Script = get_char_script(pwcInChars[cnt+j]);
687         }
688
689         if ((levels && (levels[cnt] != pItems[index].a.s.uBidiLevel || (strength && (strength[cnt] != str)))) || New_Script != pItems[index].a.eScript || New_Script == Script_Control)
690         {
691             TRACE("New_Level = %i, New_Strength = %i, New_Script=%d, eScript=%d\n", levels?levels[cnt]:-1, strength?strength[cnt]:str, New_Script, pItems[index].a.eScript);
692
693             if (strength && strength[cnt] != 0)
694                 str = strength[cnt];
695
696             index++;
697             if  (index+1 > cMaxItems)
698                 return E_OUTOFMEMORY;
699
700             pItems[index].iCharPos = cnt;
701             memset(&pItems[index].a, 0, sizeof(SCRIPT_ANALYSIS));
702
703             pItems[index].a = scriptInformation[New_Script].a;
704             if (levels)
705             {
706                 pItems[index].a.fRTL = odd(levels[cnt]);
707                 pItems[index].a.fLayoutRTL = odd(levels[cnt]);
708                 pItems[index].a.s.uBidiLevel = levels[cnt];
709             }
710             else if (!pItems[index].a.s.uBidiLevel)
711             {
712                 pItems[index].a.s.uBidiLevel = baselevel;
713                 pItems[index].a.fLayoutRTL = odd(baselevel);
714                 pItems[index].a.fRTL = odd(baselevel);
715             }
716
717             TRACE("index=%d cnt=%d iCharPos=%d\n", index, cnt, pItems[index].iCharPos);
718         }
719     }
720
721     /* While not strictly necessary according to the spec, make sure the n+1
722      * item is set up to prevent random behaviour if the caller erroneously
723      * checks the n+1 structure                                              */
724     index++;
725     memset(&pItems[index].a, 0, sizeof(SCRIPT_ANALYSIS));
726
727     TRACE("index=%d cnt=%d iCharPos=%d\n", index, cnt, pItems[index].iCharPos);
728
729     /*  Set one SCRIPT_STATE item being returned  */
730     if  (index + 1 > cMaxItems) return E_OUTOFMEMORY;
731     if (pcItems) *pcItems = index;
732
733     /*  Set SCRIPT_ITEM                                     */
734     pItems[index].iCharPos = cnt;         /* the last item contains the ptr to the lastchar */
735     heap_free(levels);
736     heap_free(strength);
737     return S_OK;
738 }
739
740 /***********************************************************************
741  *      ScriptStringAnalyse (USP10.@)
742  *
743  */
744 HRESULT WINAPI ScriptStringAnalyse(HDC hdc, const void *pString, int cString,
745                                    int cGlyphs, int iCharset, DWORD dwFlags,
746                                    int iReqWidth, SCRIPT_CONTROL *psControl,
747                                    SCRIPT_STATE *psState, const int *piDx,
748                                    SCRIPT_TABDEF *pTabdef, const BYTE *pbInClass,
749                                    SCRIPT_STRING_ANALYSIS *pssa)
750 {
751     HRESULT hr = E_OUTOFMEMORY;
752     StringAnalysis *analysis = NULL;
753     int i, num_items = 255;
754
755     TRACE("(%p,%p,%d,%d,%d,0x%x,%d,%p,%p,%p,%p,%p,%p)\n",
756           hdc, pString, cString, cGlyphs, iCharset, dwFlags, iReqWidth,
757           psControl, psState, piDx, pTabdef, pbInClass, pssa);
758
759     if (iCharset != -1)
760     {
761         FIXME("Only Unicode strings are supported\n");
762         return E_INVALIDARG;
763     }
764     if (cString < 1 || !pString) return E_INVALIDARG;
765     if ((dwFlags & SSA_GLYPHS) && !hdc) return E_PENDING;
766
767     if (!(analysis = heap_alloc_zero(sizeof(StringAnalysis)))) return E_OUTOFMEMORY;
768     if (!(analysis->pItem = heap_alloc_zero(num_items * sizeof(SCRIPT_ITEM) + 1))) goto error;
769
770     /* FIXME: handle clipping */
771     analysis->clip_len = cString;
772     analysis->hdc = hdc;
773
774     hr = ScriptItemize(pString, cString, num_items, psControl, psState, analysis->pItem,
775                        &analysis->numItems);
776
777     while (hr == E_OUTOFMEMORY)
778     {
779         SCRIPT_ITEM *tmp;
780
781         num_items *= 2;
782         if (!(tmp = heap_realloc_zero(analysis->pItem, num_items * sizeof(SCRIPT_ITEM) + 1)))
783             goto error;
784
785         analysis->pItem = tmp;
786         hr = ScriptItemize(pString, cString, num_items, psControl, psState, analysis->pItem,
787                            &analysis->numItems);
788     }
789     if (hr != S_OK) goto error;
790
791     if ((analysis->logattrs = heap_alloc(sizeof(SCRIPT_LOGATTR) * cString)))
792         ScriptBreak(pString, cString, (SCRIPT_STRING_ANALYSIS)analysis, analysis->logattrs);
793     else
794         goto error;
795
796     if (!(analysis->glyphs = heap_alloc_zero(sizeof(StringGlyphs) * analysis->numItems)))
797         goto error;
798
799     for (i = 0; i < analysis->numItems; i++)
800     {
801         SCRIPT_CACHE *sc = (SCRIPT_CACHE *)&analysis->sc;
802         int cChar = analysis->pItem[i+1].iCharPos - analysis->pItem[i].iCharPos;
803         int numGlyphs = 1.5 * cChar + 16;
804         WORD *glyphs = heap_alloc_zero(sizeof(WORD) * numGlyphs);
805         WORD *pwLogClust = heap_alloc_zero(sizeof(WORD) * cChar);
806         int *piAdvance = heap_alloc_zero(sizeof(int) * numGlyphs);
807         SCRIPT_VISATTR *psva = heap_alloc_zero(sizeof(SCRIPT_VISATTR) * cChar);
808         GOFFSET *pGoffset = heap_alloc_zero(sizeof(GOFFSET) * numGlyphs);
809         ABC *abc = heap_alloc_zero(sizeof(ABC));
810         int numGlyphsReturned;
811
812         /* FIXME: non unicode strings */
813         const WCHAR* pStr = (const WCHAR*)pString;
814         hr = ScriptShape(hdc, sc, &pStr[analysis->pItem[i].iCharPos],
815                          cChar, numGlyphs, &analysis->pItem[i].a,
816                          glyphs, pwLogClust, psva, &numGlyphsReturned);
817         hr = ScriptPlace(hdc, sc, glyphs, numGlyphsReturned, psva, &analysis->pItem[i].a,
818                          piAdvance, pGoffset, abc);
819
820         analysis->glyphs[i].numGlyphs = numGlyphsReturned;
821         analysis->glyphs[i].glyphs = glyphs;
822         analysis->glyphs[i].pwLogClust = pwLogClust;
823         analysis->glyphs[i].piAdvance = piAdvance;
824         analysis->glyphs[i].psva = psva;
825         analysis->glyphs[i].pGoffset = pGoffset;
826         analysis->glyphs[i].abc = abc;
827     }
828
829     *pssa = analysis;
830     return S_OK;
831
832 error:
833     heap_free(analysis->glyphs);
834     heap_free(analysis->logattrs);
835     heap_free(analysis->pItem);
836     heap_free(analysis->sc);
837     heap_free(analysis);
838     return hr;
839 }
840
841 /***********************************************************************
842  *      ScriptStringOut (USP10.@)
843  *
844  * This function takes the output of ScriptStringAnalyse and joins the segments
845  * of glyphs and passes the resulting string to ScriptTextOut.  ScriptStringOut
846  * only processes glyphs.
847  *
848  * Parameters:
849  *  ssa       [I] buffer to hold the analysed string components
850  *  iX        [I] X axis displacement for output
851  *  iY        [I] Y axis displacement for output
852  *  uOptions  [I] flags controling output processing
853  *  prc       [I] rectangle coordinates
854  *  iMinSel   [I] starting pos for substringing output string
855  *  iMaxSel   [I] ending pos for substringing output string
856  *  fDisabled [I] controls text highlighting
857  *
858  *  RETURNS
859  *   Success: S_OK
860  *   Failure: is the value returned by ScriptTextOut
861  */
862 HRESULT WINAPI ScriptStringOut(SCRIPT_STRING_ANALYSIS ssa,
863                                int iX,
864                                int iY, 
865                                UINT uOptions, 
866                                const RECT *prc, 
867                                int iMinSel, 
868                                int iMaxSel,
869                                BOOL fDisabled)
870 {
871     StringAnalysis *analysis;
872     WORD *glyphs;
873     int   item, cnt, x;
874     HRESULT hr;
875
876     TRACE("(%p,%d,%d,0x%1x,%p,%d,%d,%d)\n",
877          ssa, iX, iY, uOptions, prc, iMinSel, iMaxSel, fDisabled);
878
879     if (!(analysis = ssa)) return E_INVALIDARG;
880
881     /*
882      * Get storage for the output buffer for the consolidated strings
883      */
884     cnt = 0;
885     for (item = 0; item < analysis->numItems; item++)
886     {
887         cnt += analysis->glyphs[item].numGlyphs;
888     }
889     if (!(glyphs = heap_alloc(sizeof(WCHAR) * cnt))) return E_OUTOFMEMORY;
890
891     /*
892      * ScriptStringOut only processes glyphs hence set ETO_GLYPH_INDEX
893      */
894     uOptions |= ETO_GLYPH_INDEX;
895     analysis->pItem[0].a.fNoGlyphIndex = FALSE; /* say that we have glyphs */
896
897     /*
898      * Copy the string items into the output buffer
899      */
900
901     TRACE("numItems %d\n", analysis->numItems);
902
903     cnt = 0;
904     for (item = 0; item < analysis->numItems; item++)
905     {
906         memcpy(&glyphs[cnt], analysis->glyphs[item].glyphs,
907               sizeof(WCHAR) * analysis->glyphs[item].numGlyphs);
908
909         TRACE("Item %d, Glyphs %d ", item, analysis->glyphs[item].numGlyphs);
910         for (x = cnt; x < analysis->glyphs[item].numGlyphs + cnt; x ++)
911             TRACE("%04x", glyphs[x]);
912         TRACE("\n");
913
914         cnt += analysis->glyphs[item].numGlyphs; /* point to the end of the copied text */
915     }
916
917     hr = ScriptTextOut(analysis->hdc, (SCRIPT_CACHE *)&analysis->sc, iX, iY,
918                        uOptions, prc, &analysis->pItem->a, NULL, 0, glyphs, cnt,
919                        analysis->glyphs->piAdvance, NULL, analysis->glyphs->pGoffset);
920     TRACE("ScriptTextOut hr=%08x\n", hr);
921
922     /*
923      * Free the output buffer and script cache
924      */
925     heap_free(glyphs);
926     return hr;
927 }
928
929 /***********************************************************************
930  *      ScriptStringCPtoX (USP10.@)
931  *
932  */
933 HRESULT WINAPI ScriptStringCPtoX(SCRIPT_STRING_ANALYSIS ssa, int icp, BOOL fTrailing, int* pX)
934 {
935     int i, j;
936     int runningX = 0;
937     int runningCp = 0;
938     StringAnalysis* analysis = ssa;
939     BOOL itemTrailing;
940
941     TRACE("(%p), %d, %d, (%p)\n", ssa, icp, fTrailing, pX);
942
943     if (!ssa || !pX) return S_FALSE;
944
945     /* icp out of range */
946     if(icp < 0)
947     {
948         analysis->invalid = TRUE;
949         return E_INVALIDARG;
950     }
951
952     for(i=0; i<analysis->numItems; i++)
953     {
954         if (analysis->pItem[i].a.fRTL)
955             itemTrailing = !fTrailing;
956         else
957             itemTrailing = fTrailing;
958         for(j=0; j<analysis->glyphs[i].numGlyphs; j++)
959         {
960             if(runningCp == icp && itemTrailing == FALSE)
961             {
962                 *pX = runningX;
963                 return S_OK;
964             }
965             runningX += analysis->glyphs[i].piAdvance[j];
966             if(runningCp == icp && itemTrailing == TRUE)
967             {
968                 *pX = runningX;
969                 return S_OK;
970             }
971             runningCp++;
972         }
973     }
974
975     /* icp out of range */
976     analysis->invalid = TRUE;
977     return E_INVALIDARG;
978 }
979
980 /***********************************************************************
981  *      ScriptStringXtoCP (USP10.@)
982  *
983  */
984 HRESULT WINAPI ScriptStringXtoCP(SCRIPT_STRING_ANALYSIS ssa, int iX, int* piCh, int* piTrailing) 
985 {
986     StringAnalysis* analysis = ssa;
987     int i;
988     int j;
989     int runningX = 0;
990     int runningCp = 0;
991     int width;
992
993     TRACE("(%p), %d, (%p), (%p)\n", ssa, iX, piCh, piTrailing);
994
995     if (!ssa || !piCh || !piTrailing) return S_FALSE;
996
997     /* out of range */
998     if(iX < 0)
999     {
1000         if (analysis->pItem[0].a.fRTL)
1001         {
1002             *piCh = 1;
1003             *piTrailing = FALSE;
1004         }
1005         else
1006         {
1007             *piCh = -1;
1008             *piTrailing = TRUE;
1009         }
1010         return S_OK;
1011     }
1012
1013     for(i=0; i<analysis->numItems; i++)
1014     {
1015         for(j=0; j<analysis->glyphs[i].numGlyphs; j++)
1016         {
1017             width = analysis->glyphs[i].piAdvance[j];
1018             if(iX < (runningX + width))
1019             {
1020                 *piCh = runningCp;
1021                 if((iX - runningX) > width/2)
1022                     *piTrailing = TRUE;
1023                 else
1024                     *piTrailing = FALSE;
1025
1026                 if (analysis->pItem[i].a.fRTL)
1027                     *piTrailing = !*piTrailing;
1028                 return S_OK;
1029             }
1030             runningX += width;
1031             runningCp++;
1032         }
1033     }
1034
1035     /* out of range */
1036     *piCh = analysis->pItem[analysis->numItems].iCharPos;
1037     *piTrailing = FALSE;
1038
1039     return S_OK;
1040 }
1041
1042
1043 /***********************************************************************
1044  *      ScriptStringFree (USP10.@)
1045  *
1046  * Free a string analysis.
1047  *
1048  * PARAMS
1049  *  pssa [I] string analysis.
1050  *
1051  * RETURNS
1052  *  Success: S_OK
1053  *  Failure: Non-zero HRESULT value.
1054  */
1055 HRESULT WINAPI ScriptStringFree(SCRIPT_STRING_ANALYSIS *pssa)
1056 {
1057     StringAnalysis* analysis;
1058     BOOL invalid;
1059     int i;
1060
1061     TRACE("(%p)\n", pssa);
1062
1063     if (!pssa || !(analysis = *pssa)) return E_INVALIDARG;
1064
1065     invalid = analysis->invalid;
1066     ScriptFreeCache((SCRIPT_CACHE *)&analysis->sc);
1067
1068     for (i = 0; i < analysis->numItems; i++)
1069     {
1070         heap_free(analysis->glyphs[i].glyphs);
1071         heap_free(analysis->glyphs[i].pwLogClust);
1072         heap_free(analysis->glyphs[i].piAdvance);
1073         heap_free(analysis->glyphs[i].psva);
1074         heap_free(analysis->glyphs[i].pGoffset);
1075         heap_free(analysis->glyphs[i].abc);
1076     }
1077
1078     heap_free(analysis->glyphs);
1079     heap_free(analysis->pItem);
1080     heap_free(analysis->logattrs);
1081     heap_free(analysis->sz);
1082     heap_free(analysis->sc);
1083     heap_free(analysis);
1084
1085     if (invalid) return E_INVALIDARG;
1086     return S_OK;
1087 }
1088
1089 /***********************************************************************
1090  *      ScriptCPtoX (USP10.@)
1091  *
1092  */
1093 HRESULT WINAPI ScriptCPtoX(int iCP,
1094                            BOOL fTrailing,
1095                            int cChars,
1096                            int cGlyphs,
1097                            const WORD *pwLogClust,
1098                            const SCRIPT_VISATTR *psva,
1099                            const int *piAdvance,
1100                            const SCRIPT_ANALYSIS *psa,
1101                            int *piX)
1102 {
1103     int item;
1104     float iPosX;
1105     int iSpecial = -1;
1106     int iCluster = -1;
1107     int clust_size = 1;
1108     float special_size = 0.0;
1109     int iMaxPos = 0;
1110     BOOL rtl = FALSE;
1111
1112     TRACE("(%d,%d,%d,%d,%p,%p,%p,%p,%p)\n",
1113           iCP, fTrailing, cChars, cGlyphs, pwLogClust, psva, piAdvance,
1114           psa, piX);
1115
1116     if (psa->fRTL && ! psa->fLogicalOrder)
1117         rtl = TRUE;
1118
1119     if (fTrailing)
1120         iCP++;
1121
1122     if (rtl)
1123     {
1124         int max_clust = pwLogClust[0];
1125
1126         for (item=0; item < cGlyphs; item++)
1127             if (pwLogClust[item] > max_clust)
1128             {
1129                 ERR("We do not handle non reversed clusters properly\n");
1130                 break;
1131             }
1132
1133         iMaxPos = 0;
1134         for (item = max_clust; item >=0; item --)
1135             iMaxPos += piAdvance[item];
1136     }
1137
1138     iPosX = 0.0;
1139     for (item=0; item < iCP && item < cGlyphs; item++)
1140     {
1141         if (iSpecial == -1 && (iCluster == -1 || (iCluster != -1 && iCluster+clust_size <= item)))
1142         {
1143             int check;
1144             int clust = pwLogClust[item];
1145
1146             clust_size = 1;
1147             iCluster = -1;
1148
1149             for (check = item+1; check < cGlyphs; check++)
1150             {
1151                 if (pwLogClust[check] == clust)
1152                 {
1153                     clust_size ++;
1154                     if (iCluster == -1)
1155                         iCluster = item;
1156                 }
1157                 else break;
1158             }
1159
1160             if (check >= cGlyphs && !iMaxPos)
1161             {
1162                 for (check = clust; check < cGlyphs; check++)
1163                     special_size += piAdvance[check];
1164                 iSpecial = item;
1165                 special_size /= (cChars - item);
1166                 iPosX += special_size;
1167             }
1168             else
1169                 iPosX += piAdvance[clust] / (float)clust_size;
1170         }
1171         else if (iSpecial != -1)
1172             iPosX += special_size;
1173         else /* (iCluster != -1) */
1174             iPosX += piAdvance[pwLogClust[iCluster]] / (float)clust_size;
1175     }
1176
1177     if (iMaxPos > 0)
1178     {
1179         iPosX = iMaxPos - iPosX;
1180         if (iPosX < 0)
1181             iPosX = 0;
1182     }
1183
1184     *piX = iPosX;
1185     TRACE("*piX=%d\n", *piX);
1186     return S_OK;
1187 }
1188
1189 /***********************************************************************
1190  *      ScriptXtoCP (USP10.@)
1191  *
1192  */
1193 HRESULT WINAPI ScriptXtoCP(int iX,
1194                            int cChars,
1195                            int cGlyphs,
1196                            const WORD *pwLogClust,
1197                            const SCRIPT_VISATTR *psva,
1198                            const int *piAdvance,
1199                            const SCRIPT_ANALYSIS *psa,
1200                            int *piCP,
1201                            int *piTrailing)
1202 {
1203     int item;
1204     float iPosX;
1205     float iLastPosX;
1206     int iSpecial = -1;
1207     int iCluster = -1;
1208     int clust_size = 1;
1209     float special_size = 0.0;
1210     int direction = 1;
1211
1212     TRACE("(%d,%d,%d,%p,%p,%p,%p,%p,%p)\n",
1213           iX, cChars, cGlyphs, pwLogClust, psva, piAdvance,
1214           psa, piCP, piTrailing);
1215
1216     if (psa->fRTL && ! psa->fLogicalOrder)
1217         direction = -1;
1218
1219     if (direction<0)
1220     {
1221         int max_clust = pwLogClust[0];
1222
1223         if (iX < 0)
1224         {
1225             *piCP = cGlyphs;
1226             *piTrailing = 0;
1227             return S_OK;
1228         }
1229
1230         for (item=0; item < cGlyphs; item++)
1231             if (pwLogClust[item] > max_clust)
1232             {
1233                 ERR("We do not handle non reversed clusters properly\n");
1234                 break;
1235             }
1236     }
1237
1238     if (iX < 0)
1239     {
1240         *piCP = -1;
1241         *piTrailing = 1;
1242         return S_OK;
1243     }
1244
1245     iPosX = iLastPosX = 0;
1246     if (direction > 0)
1247         item = 0;
1248     else
1249         item = cGlyphs - 1;
1250     for (; iPosX <= iX && item < cGlyphs && item >= 0; item+=direction)
1251     {
1252         iLastPosX = iPosX;
1253         if (iSpecial == -1 &&
1254              (iCluster == -1 ||
1255               (iCluster != -1 &&
1256                  ((direction > 0 && iCluster+clust_size <= item) ||
1257                   (direction < 0 && iCluster-clust_size >= item))
1258               )
1259              )
1260             )
1261         {
1262             int check;
1263             int clust = pwLogClust[item];
1264
1265             clust_size = 1;
1266             iCluster = -1;
1267
1268             for (check = item+direction; check < cGlyphs && check >= 0; check+=direction)
1269             {
1270                 if (pwLogClust[check] == clust)
1271                 {
1272                     clust_size ++;
1273                     if (iCluster == -1)
1274                         iCluster = item;
1275                 }
1276                 else break;
1277             }
1278
1279             if (check >= cGlyphs && direction > 0)
1280             {
1281                 for (check = clust; check < cGlyphs; check++)
1282                     special_size += piAdvance[check];
1283                 iSpecial = item;
1284                 special_size /= (cChars - item);
1285                 iPosX += special_size;
1286             }
1287             else
1288                 iPosX += piAdvance[clust] / (float)clust_size;
1289         }
1290         else if (iSpecial != -1)
1291             iPosX += special_size;
1292         else /* (iCluster != -1) */
1293             iPosX += piAdvance[pwLogClust[iCluster]] / (float)clust_size;
1294     }
1295
1296     if (direction > 0)
1297     {
1298         if (iPosX > iX)
1299             item--;
1300         if (item < cGlyphs && ((iPosX - iLastPosX) / 2.0) + iX > iPosX)
1301             *piTrailing = 1;
1302         else
1303             *piTrailing = 0;
1304     }
1305     else
1306     {
1307         if (iX == iLastPosX)
1308             item++;
1309         if (iX >= iLastPosX && iX <= iPosX)
1310             item++;
1311
1312         if (iLastPosX == iX)
1313             *piTrailing = 0;
1314         else if (item < 0 || ((iLastPosX - iPosX) / 2.0) + iX <= iLastPosX)
1315             *piTrailing = 1;
1316         else
1317             *piTrailing = 0;
1318     }
1319
1320     *piCP = item;
1321
1322     TRACE("*piCP=%d\n", *piCP);
1323     TRACE("*piTrailing=%d\n", *piTrailing);
1324     return S_OK;
1325 }
1326
1327 /***********************************************************************
1328  *      ScriptBreak (USP10.@)
1329  *
1330  *  Retrieve line break information.
1331  *
1332  *  PARAMS
1333  *   chars [I] Array of characters.
1334  *   sa    [I] String analysis.
1335  *   la    [I] Array of logical attribute structures.
1336  *
1337  *  RETURNS
1338  *   Success: S_OK
1339  *   Failure: S_FALSE
1340  */
1341 HRESULT WINAPI ScriptBreak(const WCHAR *chars, int count, const SCRIPT_ANALYSIS *sa, SCRIPT_LOGATTR *la)
1342 {
1343     int i;
1344
1345     TRACE("(%s, %d, %p, %p)\n", debugstr_wn(chars, count), count, sa, la);
1346
1347     if (!la) return S_FALSE;
1348
1349     for (i = 0; i < count; i++)
1350     {
1351         memset(&la[i], 0, sizeof(SCRIPT_LOGATTR));
1352
1353         /* FIXME: set the other flags */
1354         la[i].fWhiteSpace = (chars[i] == ' ');
1355         la[i].fCharStop = 1;
1356
1357         if (i > 0 && la[i - 1].fWhiteSpace)
1358         {
1359             la[i].fSoftBreak = 1;
1360             la[i].fWordStop = 1;
1361         }
1362     }
1363     return S_OK;
1364 }
1365
1366 /***********************************************************************
1367  *      ScriptIsComplex (USP10.@)
1368  *
1369  *  Determine if a string is complex.
1370  *
1371  *  PARAMS
1372  *   chars [I] Array of characters to test.
1373  *   len   [I] Length in characters.
1374  *   flag  [I] Flag.
1375  *
1376  *  RETURNS
1377  *   Success: S_OK
1378  *   Failure: S_FALSE
1379  *
1380  */
1381 HRESULT WINAPI ScriptIsComplex(const WCHAR *chars, int len, DWORD flag)
1382 {
1383     int i;
1384
1385     TRACE("(%s,%d,0x%x)\n", debugstr_wn(chars, len), len, flag);
1386
1387     for (i = 0; i < len; i++)
1388     {
1389         int script;
1390
1391         if ((flag & SIC_ASCIIDIGIT) && chars[i] >= 0x30 && chars[i] <= 0x39)
1392             return S_OK;
1393
1394         script = get_char_script(chars[i]);
1395         if ((scriptInformation[script].props.fComplex && (flag & SIC_COMPLEX))||
1396             (!scriptInformation[script].props.fComplex && (flag & SIC_NEUTRAL)))
1397             return S_OK;
1398     }
1399     return S_FALSE;
1400 }
1401
1402 /***********************************************************************
1403  *      ScriptShape (USP10.@)
1404  *
1405  * Produce glyphs and visual attributes for a run.
1406  *
1407  * PARAMS
1408  *  hdc         [I]   Device context.
1409  *  psc         [I/O] Opaque pointer to a script cache.
1410  *  pwcChars    [I]   Array of characters specifying the run.
1411  *  cChars      [I]   Number of characters in pwcChars.
1412  *  cMaxGlyphs  [I]   Length of pwOutGlyphs.
1413  *  psa         [I/O] Script analysis.
1414  *  pwOutGlyphs [O]   Array of glyphs.
1415  *  pwLogClust  [O]   Array of logical cluster info.
1416  *  psva        [O]   Array of visual attributes.
1417  *  pcGlyphs    [O]   Number of glyphs returned.
1418  *
1419  * RETURNS
1420  *  Success: S_OK
1421  *  Failure: Non-zero HRESULT value.
1422  */
1423 HRESULT WINAPI ScriptShape(HDC hdc, SCRIPT_CACHE *psc, const WCHAR *pwcChars, 
1424                            int cChars, int cMaxGlyphs,
1425                            SCRIPT_ANALYSIS *psa, WORD *pwOutGlyphs, WORD *pwLogClust,
1426                            SCRIPT_VISATTR *psva, int *pcGlyphs)
1427 {
1428     HRESULT hr;
1429     unsigned int i;
1430     BOOL rtl;
1431
1432     TRACE("(%p, %p, %s, %d, %d, %p, %p, %p, %p, %p)\n", hdc, psc, debugstr_wn(pwcChars, cChars),
1433           cChars, cMaxGlyphs, psa, pwOutGlyphs, pwLogClust, psva, pcGlyphs);
1434
1435     if (psa) TRACE("psa values: %d, %d, %d, %d, %d, %d, %d\n", psa->eScript, psa->fRTL, psa->fLayoutRTL,
1436                    psa->fLinkBefore, psa->fLinkAfter, psa->fLogicalOrder, psa->fNoGlyphIndex);
1437
1438     if (!psva || !pcGlyphs) return E_INVALIDARG;
1439     if (cChars > cMaxGlyphs) return E_OUTOFMEMORY;
1440     rtl = (!psa->fLogicalOrder && psa->fRTL);
1441
1442     *pcGlyphs = cChars;
1443     if ((hr = init_script_cache(hdc, psc)) != S_OK) return hr;
1444     if (!pwLogClust) return E_FAIL;
1445
1446     /* Initialize a SCRIPT_VISATTR and LogClust for each char in this run */
1447     for (i = 0; i < cChars; i++)
1448     {
1449         int idx = i;
1450         if (rtl) idx = cChars - 1 - i;
1451         /* FIXME: set to better values */
1452         psva[i].uJustification = (pwcChars[idx] == ' ') ? SCRIPT_JUSTIFY_BLANK : SCRIPT_JUSTIFY_CHARACTER;
1453         psva[i].fClusterStart  = 1;
1454         psva[i].fDiacritic     = 0;
1455         psva[i].fZeroWidth     = 0;
1456         psva[i].fReserved      = 0;
1457         psva[i].fShapeReserved = 0;
1458
1459         pwLogClust[i] = idx;
1460     }
1461
1462     if (!psa->fNoGlyphIndex)
1463     {
1464         WCHAR *rChars;
1465         if ((hr = SHAPE_CheckFontForRequiredFeatures(hdc, (ScriptCache *)*psc, psa)) != S_OK) return hr;
1466
1467         rChars = heap_alloc(sizeof(WCHAR) * cChars);
1468         if (!rChars) return E_OUTOFMEMORY;
1469         for (i = 0; i < cChars; i++)
1470         {
1471             int idx = i;
1472             WCHAR chInput;
1473             if (rtl) idx = cChars - 1 - i;
1474             if (psa->fRTL)
1475                 chInput = mirror_char(pwcChars[idx]);
1476             else
1477                 chInput = pwcChars[idx];
1478             if (!(pwOutGlyphs[i] = get_cache_glyph(psc, chInput)))
1479             {
1480                 WORD glyph;
1481                 if (!hdc) return E_PENDING;
1482                 if (GetGlyphIndicesW(hdc, &chInput, 1, &glyph, 0) == GDI_ERROR) return S_FALSE;
1483                 pwOutGlyphs[i] = set_cache_glyph(psc, chInput, glyph);
1484             }
1485             rChars[i] = chInput;
1486         }
1487
1488         if (get_cache_pitch_family(psc) & TMPF_TRUETYPE)
1489         {
1490             SHAPE_ContextualShaping(hdc, (ScriptCache *)*psc, psa, rChars, cChars, pwOutGlyphs, pcGlyphs, cMaxGlyphs, pwLogClust);
1491             SHAPE_ApplyDefaultOpentypeFeatures(hdc, (ScriptCache *)*psc, psa, pwOutGlyphs, pcGlyphs, cMaxGlyphs, cChars, pwLogClust);
1492         }
1493         heap_free(rChars);
1494     }
1495     else
1496     {
1497         TRACE("no glyph translation\n");
1498         for (i = 0; i < cChars; i++)
1499         {
1500             int idx = i;
1501             /* No mirroring done here */
1502             if (rtl) idx = cChars - 1 - i;
1503             pwOutGlyphs[i] = pwcChars[idx];
1504         }
1505     }
1506
1507     return S_OK;
1508 }
1509
1510 /***********************************************************************
1511  *      ScriptPlace (USP10.@)
1512  *
1513  * Produce advance widths for a run.
1514  *
1515  * PARAMS
1516  *  hdc       [I]   Device context.
1517  *  psc       [I/O] Opaque pointer to a script cache.
1518  *  pwGlyphs  [I]   Array of glyphs.
1519  *  cGlyphs   [I]   Number of glyphs in pwGlyphs.
1520  *  psva      [I]   Array of visual attributes.
1521  *  psa       [I/O] String analysis.
1522  *  piAdvance [O]   Array of advance widths.
1523  *  pGoffset  [O]   Glyph offsets.
1524  *  pABC      [O]   Combined ABC width.
1525  *
1526  * RETURNS
1527  *  Success: S_OK
1528  *  Failure: Non-zero HRESULT value.
1529  */
1530 HRESULT WINAPI ScriptPlace(HDC hdc, SCRIPT_CACHE *psc, const WORD *pwGlyphs, 
1531                            int cGlyphs, const SCRIPT_VISATTR *psva,
1532                            SCRIPT_ANALYSIS *psa, int *piAdvance, GOFFSET *pGoffset, ABC *pABC )
1533 {
1534     HRESULT hr;
1535     int i;
1536
1537     TRACE("(%p, %p, %p, %d, %p, %p, %p, %p, %p)\n",  hdc, psc, pwGlyphs, cGlyphs, psva, psa,
1538           piAdvance, pGoffset, pABC);
1539
1540     if (!psva) return E_INVALIDARG;
1541     if ((hr = init_script_cache(hdc, psc)) != S_OK) return hr;
1542     if (!pGoffset) return E_FAIL;
1543
1544     if (pABC) memset(pABC, 0, sizeof(ABC));
1545     for (i = 0; i < cGlyphs; i++)
1546     {
1547         ABC abc;
1548         if (!get_cache_glyph_widths(psc, pwGlyphs[i], &abc))
1549         {
1550             if (!hdc) return E_PENDING;
1551             if ((get_cache_pitch_family(psc) & TMPF_TRUETYPE) && !psa->fNoGlyphIndex)
1552             {
1553                 if (!GetCharABCWidthsI(hdc, 0, 1, (WORD *)&pwGlyphs[i], &abc)) return S_FALSE;
1554             }
1555             else
1556             {
1557                 INT width;
1558                 if (!GetCharWidth32W(hdc, pwGlyphs[i], pwGlyphs[i], &width)) return S_FALSE;
1559                 abc.abcB = width;
1560                 abc.abcA = abc.abcC = 0;
1561             }
1562             set_cache_glyph_widths(psc, pwGlyphs[i], &abc);
1563         }
1564         if (pABC)
1565         {
1566             pABC->abcA += abc.abcA;
1567             pABC->abcB += abc.abcB;
1568             pABC->abcC += abc.abcC;
1569         }
1570         /* FIXME: set to more reasonable values */
1571         pGoffset[i].du = pGoffset[i].dv = 0;
1572         if (piAdvance) piAdvance[i] = abc.abcA + abc.abcB + abc.abcC;
1573     }
1574
1575     if (pABC) TRACE("Total for run: abcA=%d, abcB=%d, abcC=%d\n", pABC->abcA, pABC->abcB, pABC->abcC);
1576     return S_OK;
1577 }
1578
1579 /***********************************************************************
1580  *      ScriptGetCMap (USP10.@)
1581  *
1582  * Retrieve glyph indices.
1583  *
1584  * PARAMS
1585  *  hdc         [I]   Device context.
1586  *  psc         [I/O] Opaque pointer to a script cache.
1587  *  pwcInChars  [I]   Array of Unicode characters.
1588  *  cChars      [I]   Number of characters in pwcInChars.
1589  *  dwFlags     [I]   Flags.
1590  *  pwOutGlyphs [O]   Buffer to receive the array of glyph indices.
1591  *
1592  * RETURNS
1593  *  Success: S_OK
1594  *  Failure: Non-zero HRESULT value.
1595  */
1596 HRESULT WINAPI ScriptGetCMap(HDC hdc, SCRIPT_CACHE *psc, const WCHAR *pwcInChars,
1597                              int cChars, DWORD dwFlags, WORD *pwOutGlyphs)
1598 {
1599     HRESULT hr;
1600     int i;
1601
1602     TRACE("(%p,%p,%s,%d,0x%x,%p)\n", hdc, psc, debugstr_wn(pwcInChars, cChars),
1603           cChars, dwFlags, pwOutGlyphs);
1604
1605     if ((hr = init_script_cache(hdc, psc)) != S_OK) return hr;
1606
1607     hr = S_OK;
1608
1609     if ((get_cache_pitch_family(psc) & TMPF_TRUETYPE))
1610     {
1611         for (i = 0; i < cChars; i++)
1612         {
1613             WCHAR inChar;
1614             if (dwFlags == SGCM_RTL)
1615                 inChar = mirror_char(pwcInChars[i]);
1616             else
1617                 inChar = pwcInChars[i];
1618             if (!(pwOutGlyphs[i] = get_cache_glyph(psc, inChar)))
1619             {
1620                 WORD glyph;
1621                 if (!hdc) return E_PENDING;
1622                 if (GetGlyphIndicesW(hdc, &inChar, 1, &glyph, GGI_MARK_NONEXISTING_GLYPHS) == GDI_ERROR) return S_FALSE;
1623                 if (glyph == 0xffff)
1624                 {
1625                     hr = S_FALSE;
1626                     glyph = 0x0;
1627                 }
1628                 pwOutGlyphs[i] = set_cache_glyph(psc, inChar, glyph);
1629             }
1630         }
1631     }
1632     else
1633     {
1634         TRACE("no glyph translation\n");
1635         for (i = 0; i < cChars; i++)
1636         {
1637             WCHAR inChar;
1638             if (dwFlags == SGCM_RTL)
1639                 inChar = mirror_char(pwcInChars[i]);
1640             else
1641                 inChar = pwcInChars[i];
1642             pwOutGlyphs[i] = inChar;
1643         }
1644     }
1645     return hr;
1646 }
1647
1648 /***********************************************************************
1649  *      ScriptTextOut (USP10.@)
1650  *
1651  */
1652 HRESULT WINAPI ScriptTextOut(const HDC hdc, SCRIPT_CACHE *psc, int x, int y, UINT fuOptions, 
1653                              const RECT *lprc, const SCRIPT_ANALYSIS *psa, const WCHAR *pwcReserved, 
1654                              int iReserved, const WORD *pwGlyphs, int cGlyphs, const int *piAdvance,
1655                              const int *piJustify, const GOFFSET *pGoffset)
1656 {
1657     HRESULT hr = S_OK;
1658
1659     TRACE("(%p, %p, %d, %d, %04x, %p, %p, %p, %d, %p, %d, %p, %p, %p)\n",
1660          hdc, psc, x, y, fuOptions, lprc, psa, pwcReserved, iReserved, pwGlyphs, cGlyphs,
1661          piAdvance, piJustify, pGoffset);
1662
1663     if (!hdc || !psc) return E_INVALIDARG;
1664     if (!piAdvance || !psa || !pwGlyphs) return E_INVALIDARG;
1665
1666     fuOptions &= ETO_CLIPPED + ETO_OPAQUE;
1667     fuOptions |= ETO_IGNORELANGUAGE;
1668     if  (!psa->fNoGlyphIndex)                                     /* Have Glyphs?                      */
1669         fuOptions |= ETO_GLYPH_INDEX;                             /* Say don't do translation to glyph */
1670
1671     if (psa->fRTL && psa->fLogicalOrder)
1672     {
1673         int i;
1674         WORD *rtlGlyphs;
1675
1676         rtlGlyphs = heap_alloc(cGlyphs * sizeof(WORD));
1677         if (!rtlGlyphs)
1678             return E_OUTOFMEMORY;
1679
1680         for (i = 0; i < cGlyphs; i++)
1681             rtlGlyphs[i] = pwGlyphs[cGlyphs-1-i];
1682
1683         if (!ExtTextOutW(hdc, x, y, fuOptions, lprc, rtlGlyphs, cGlyphs, NULL))
1684             hr = S_FALSE;
1685         heap_free(rtlGlyphs);
1686     }
1687     else
1688         if (!ExtTextOutW(hdc, x, y, fuOptions, lprc, pwGlyphs, cGlyphs, NULL))
1689             hr = S_FALSE;
1690
1691     return hr;
1692 }
1693
1694 /***********************************************************************
1695  *      ScriptCacheGetHeight (USP10.@)
1696  *
1697  * Retrieve the height of the font in the cache.
1698  *
1699  * PARAMS
1700  *  hdc    [I]    Device context.
1701  *  psc    [I/O]  Opaque pointer to a script cache.
1702  *  height [O]    Receives font height.
1703  *
1704  * RETURNS
1705  *  Success: S_OK
1706  *  Failure: Non-zero HRESULT value.
1707  */
1708 HRESULT WINAPI ScriptCacheGetHeight(HDC hdc, SCRIPT_CACHE *psc, LONG *height)
1709 {
1710     HRESULT hr;
1711
1712     TRACE("(%p, %p, %p)\n", hdc, psc, height);
1713
1714     if (!height) return E_INVALIDARG;
1715     if ((hr = init_script_cache(hdc, psc)) != S_OK) return hr;
1716
1717     *height = get_cache_height(psc);
1718     return S_OK;
1719 }
1720
1721 /***********************************************************************
1722  *      ScriptGetGlyphABCWidth (USP10.@)
1723  *
1724  * Retrieve the width of a glyph.
1725  *
1726  * PARAMS
1727  *  hdc    [I]    Device context.
1728  *  psc    [I/O]  Opaque pointer to a script cache.
1729  *  glyph  [I]    Glyph to retrieve the width for.
1730  *  abc    [O]    ABC widths of the glyph.
1731  *
1732  * RETURNS
1733  *  Success: S_OK
1734  *  Failure: Non-zero HRESULT value.
1735  */
1736 HRESULT WINAPI ScriptGetGlyphABCWidth(HDC hdc, SCRIPT_CACHE *psc, WORD glyph, ABC *abc)
1737 {
1738     HRESULT hr;
1739
1740     TRACE("(%p, %p, 0x%04x, %p)\n", hdc, psc, glyph, abc);
1741
1742     if (!abc) return E_INVALIDARG;
1743     if ((hr = init_script_cache(hdc, psc)) != S_OK) return hr;
1744
1745     if (!get_cache_glyph_widths(psc, glyph, abc))
1746     {
1747         if (!hdc) return E_PENDING;
1748         if ((get_cache_pitch_family(psc) & TMPF_TRUETYPE))
1749         {
1750             if (!GetCharABCWidthsI(hdc, 0, 1, &glyph, abc)) return S_FALSE;
1751         }
1752         else
1753         {
1754             INT width;
1755             if (!GetCharWidth32W(hdc, glyph, glyph, &width)) return S_FALSE;
1756             abc->abcB = width;
1757             abc->abcA = abc->abcC = 0;
1758         }
1759         set_cache_glyph_widths(psc, glyph, abc);
1760     }
1761     return S_OK;
1762 }
1763
1764 /***********************************************************************
1765  *      ScriptLayout (USP10.@)
1766  *
1767  * Map embedding levels to visual and/or logical order.
1768  *
1769  * PARAMS
1770  *  runs     [I] Size of level array.
1771  *  level    [I] Array of embedding levels.
1772  *  vistolog [O] Map of embedding levels from visual to logical order.
1773  *  logtovis [O] Map of embedding levels from logical to visual order.
1774  *
1775  * RETURNS
1776  *  Success: S_OK
1777  *  Failure: Non-zero HRESULT value.
1778  *
1779  * BUGS
1780  *  This stub works correctly for any sequence of a single
1781  *  embedding level but not for sequences of different
1782  *  embedding levels, i.e. mixtures of RTL and LTR scripts.
1783  */
1784 HRESULT WINAPI ScriptLayout(int runs, const BYTE *level, int *vistolog, int *logtovis)
1785 {
1786     int* indexs;
1787     int ich;
1788
1789     TRACE("(%d, %p, %p, %p)\n", runs, level, vistolog, logtovis);
1790
1791     if (!level || (!vistolog && !logtovis))
1792         return E_INVALIDARG;
1793
1794     indexs = heap_alloc(sizeof(int) * runs);
1795     if (!indexs)
1796         return E_OUTOFMEMORY;
1797
1798
1799     if (vistolog)
1800     {
1801         for( ich = 0; ich < runs; ich++)
1802             indexs[ich] = ich;
1803
1804         ich = 0;
1805         while (ich < runs)
1806             ich += BIDI_ReorderV2lLevel(0, indexs+ich, level+ich, runs - ich, FALSE);
1807         for (ich = 0; ich < runs; ich++)
1808             vistolog[ich] = indexs[ich];
1809     }
1810
1811
1812     if (logtovis)
1813     {
1814         for( ich = 0; ich < runs; ich++)
1815             indexs[ich] = ich;
1816
1817         ich = 0;
1818         while (ich < runs)
1819             ich += BIDI_ReorderL2vLevel(0, indexs+ich, level+ich, runs - ich, FALSE);
1820         for (ich = 0; ich < runs; ich++)
1821             logtovis[ich] = indexs[ich];
1822     }
1823     heap_free(indexs);
1824
1825     return S_OK;
1826 }
1827
1828 /***********************************************************************
1829  *      ScriptStringGetLogicalWidths (USP10.@)
1830  *
1831  * Returns logical widths from a string analysis.
1832  *
1833  * PARAMS
1834  *  ssa  [I] string analysis.
1835  *  piDx [O] logical widths returned.
1836  *
1837  * RETURNS
1838  *  Success: S_OK
1839  *  Failure: a non-zero HRESULT.
1840  */
1841 HRESULT WINAPI ScriptStringGetLogicalWidths(SCRIPT_STRING_ANALYSIS ssa, int *piDx)
1842 {
1843     int i, j, next = 0;
1844     StringAnalysis *analysis = ssa;
1845
1846     TRACE("%p, %p\n", ssa, piDx);
1847
1848     if (!analysis) return S_FALSE;
1849
1850     for (i = 0; i < analysis->numItems; i++)
1851     {
1852         for (j = 0; j < analysis->glyphs[i].numGlyphs; j++)
1853         {
1854             piDx[next] = analysis->glyphs[i].piAdvance[j];
1855             next++;
1856         }
1857     }
1858     return S_OK;
1859 }
1860
1861 /***********************************************************************
1862  *      ScriptStringValidate (USP10.@)
1863  *
1864  * Validate a string analysis.
1865  *
1866  * PARAMS
1867  *  ssa [I] string analysis.
1868  *
1869  * RETURNS
1870  *  Success: S_OK
1871  *  Failure: S_FALSE if invalid sequences are found
1872  *           or a non-zero HRESULT if it fails.
1873  */
1874 HRESULT WINAPI ScriptStringValidate(SCRIPT_STRING_ANALYSIS ssa)
1875 {
1876     StringAnalysis *analysis = ssa;
1877
1878     TRACE("(%p)\n", ssa);
1879
1880     if (!analysis) return E_INVALIDARG;
1881     return (analysis->invalid) ? S_FALSE : S_OK;
1882 }
1883
1884 /***********************************************************************
1885  *      ScriptString_pSize (USP10.@)
1886  *
1887  * Retrieve width and height of an analysed string.
1888  *
1889  * PARAMS
1890  *  ssa [I] string analysis.
1891  *
1892  * RETURNS
1893  *  Success: Pointer to a SIZE structure.
1894  *  Failure: NULL
1895  */
1896 const SIZE * WINAPI ScriptString_pSize(SCRIPT_STRING_ANALYSIS ssa)
1897 {
1898     int i, j;
1899     StringAnalysis *analysis = ssa;
1900
1901     TRACE("(%p)\n", ssa);
1902
1903     if (!analysis) return NULL;
1904
1905     if (!analysis->sz)
1906     {
1907         if (!(analysis->sz = heap_alloc(sizeof(SIZE)))) return NULL;
1908         analysis->sz->cy = analysis->sc->tm.tmHeight;
1909
1910         analysis->sz->cx = 0;
1911         for (i = 0; i < analysis->numItems; i++)
1912             for (j = 0; j < analysis->glyphs[i].numGlyphs; j++)
1913                 analysis->sz->cx += analysis->glyphs[i].piAdvance[j];
1914     }
1915     return analysis->sz;
1916 }
1917
1918 /***********************************************************************
1919  *      ScriptString_pLogAttr (USP10.@)
1920  *
1921  * Retrieve logical attributes of an analysed string.
1922  *
1923  * PARAMS
1924  *  ssa [I] string analysis.
1925  *
1926  * RETURNS
1927  *  Success: Pointer to an array of SCRIPT_LOGATTR structures.
1928  *  Failure: NULL
1929  */
1930 const SCRIPT_LOGATTR * WINAPI ScriptString_pLogAttr(SCRIPT_STRING_ANALYSIS ssa)
1931 {
1932     StringAnalysis *analysis = ssa;
1933
1934     TRACE("(%p)\n", ssa);
1935
1936     if (!analysis) return NULL;
1937     return analysis->logattrs;
1938 }
1939
1940 /***********************************************************************
1941  *      ScriptString_pcOutChars (USP10.@)
1942  *
1943  * Retrieve the length of a string after clipping.
1944  *
1945  * PARAMS
1946  *  ssa [I] String analysis.
1947  *
1948  * RETURNS
1949  *  Success: Pointer to the length.
1950  *  Failure: NULL
1951  */
1952 const int * WINAPI ScriptString_pcOutChars(SCRIPT_STRING_ANALYSIS ssa)
1953 {
1954     StringAnalysis *analysis = ssa;
1955
1956     TRACE("(%p)\n", ssa);
1957
1958     if (!analysis) return NULL;
1959     return &analysis->clip_len;
1960 }
1961
1962 /***********************************************************************
1963  *      ScriptStringGetOrder (USP10.@)
1964  *
1965  * Retrieve a glyph order map.
1966  *
1967  * PARAMS
1968  *  ssa   [I]   String analysis.
1969  *  order [I/O] Array of glyph positions.
1970  *
1971  * RETURNS
1972  *  Success: S_OK
1973  *  Failure: a non-zero HRESULT.
1974  */
1975 HRESULT WINAPI ScriptStringGetOrder(SCRIPT_STRING_ANALYSIS ssa, UINT *order)
1976 {
1977     int i, j;
1978     unsigned int k;
1979     StringAnalysis *analysis = ssa;
1980
1981     TRACE("(%p)\n", ssa);
1982
1983     if (!analysis) return S_FALSE;
1984
1985     /* FIXME: handle RTL scripts */
1986     for (i = 0, k = 0; i < analysis->numItems; i++)
1987         for (j = 0; j < analysis->glyphs[i].numGlyphs; j++, k++)
1988             order[k] = k;
1989
1990     return S_OK;
1991 }
1992
1993 /***********************************************************************
1994  *      ScriptGetLogicalWidths (USP10.@)
1995  *
1996  * Convert advance widths to logical widths.
1997  *
1998  * PARAMS
1999  *  sa          [I] Script analysis.
2000  *  nbchars     [I] Number of characters.
2001  *  nbglyphs    [I] Number of glyphs.
2002  *  glyph_width [I] Array of glyph widths.
2003  *  log_clust   [I] Array of logical clusters.
2004  *  sva         [I] Visual attributes.
2005  *  widths      [O] Array of logical widths.
2006  *
2007  * RETURNS
2008  *  Success: S_OK
2009  *  Failure: a non-zero HRESULT.
2010  */
2011 HRESULT WINAPI ScriptGetLogicalWidths(const SCRIPT_ANALYSIS *sa, int nbchars, int nbglyphs,
2012                                       const int *glyph_width, const WORD *log_clust,
2013                                       const SCRIPT_VISATTR *sva, int *widths)
2014 {
2015     int i;
2016
2017     TRACE("(%p, %d, %d, %p, %p, %p, %p)\n",
2018           sa, nbchars, nbglyphs, glyph_width, log_clust, sva, widths);
2019
2020     /* FIXME */
2021     for (i = 0; i < nbchars; i++) widths[i] = glyph_width[i];
2022     return S_OK;
2023 }
2024
2025 /***********************************************************************
2026  *      ScriptApplyLogicalWidth (USP10.@)
2027  *
2028  * Generate glyph advance widths.
2029  *
2030  * PARAMS
2031  *  dx          [I]   Array of logical advance widths.
2032  *  num_chars   [I]   Number of characters.
2033  *  num_glyphs  [I]   Number of glyphs.
2034  *  log_clust   [I]   Array of logical clusters.
2035  *  sva         [I]   Visual attributes.
2036  *  advance     [I]   Array of glyph advance widths.
2037  *  sa          [I]   Script analysis.
2038  *  abc         [I/O] Summed ABC widths.
2039  *  justify     [O]   Array of glyph advance widths.
2040  *
2041  * RETURNS
2042  *  Success: S_OK
2043  *  Failure: a non-zero HRESULT.
2044  */
2045 HRESULT WINAPI ScriptApplyLogicalWidth(const int *dx, int num_chars, int num_glyphs,
2046                                        const WORD *log_clust, const SCRIPT_VISATTR *sva,
2047                                        const int *advance, const SCRIPT_ANALYSIS *sa,
2048                                        ABC *abc, int *justify)
2049 {
2050     int i;
2051
2052     FIXME("(%p, %d, %d, %p, %p, %p, %p, %p, %p)\n",
2053           dx, num_chars, num_glyphs, log_clust, sva, advance, sa, abc, justify);
2054
2055     for (i = 0; i < num_chars; i++) justify[i] = advance[i];
2056     return S_OK;
2057 }
2058
2059 HRESULT WINAPI ScriptJustify(const SCRIPT_VISATTR *sva, const int *advance,
2060                              int num_glyphs, int dx, int min_kashida, int *justify)
2061 {
2062     int i;
2063
2064     FIXME("(%p, %p, %d, %d, %d, %p)\n", sva, advance, num_glyphs, dx, min_kashida, justify);
2065
2066     for (i = 0; i < num_glyphs; i++) justify[i] = advance[i];
2067     return S_OK;
2068 }