user32: Don't flush window surfaces while waiting for a sent message reply.
[wine] / dlls / user32 / text.c
1 /*
2  * USER text functions
3  *
4  * Copyright 1993, 1994 Alexandre Julliard
5  * Copyright 2002 Bill Medland
6  *
7  * Contains
8  *   1.  DrawText functions
9  *   2.  GrayString functions
10  *   3.  TabbedText functions
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with this library; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25  */
26
27 #include "config.h"
28 #include "wine/port.h"
29
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <assert.h>
34
35 #include "windef.h"
36 #include "winbase.h"
37 #include "wingdi.h"
38 #include "wine/unicode.h"
39 #include "winnls.h"
40 #include "controls.h"
41 #include "user_private.h"
42 #include "wine/debug.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(text);
45
46 /*********************************************************************
47  *
48  *            DrawText functions
49  *
50  * Design issues
51  *   How many buffers to use
52  *     While processing in DrawText there are potentially three different forms
53  *     of the text that need to be held.  How are they best held?
54  *     1. The original text is needed, of course, to see what to display.
55  *     2. The text that will be returned to the user if the DT_MODIFYSTRING is
56  *        in effect.
57  *     3. The buffered text that is about to be displayed e.g. the current line.
58  *        Typically this will exclude the ampersands used for prefixing etc.
59  *
60  *     Complications.
61  *     a. If the buffered text to be displayed includes the ampersands then
62  *        we will need special measurement and draw functions that will ignore
63  *        the ampersands (e.g. by copying to a buffer without the prefix and
64  *        then using the normal forms).  This may involve less space but may
65  *        require more processing.  e.g. since a line containing tabs may
66  *        contain several underlined characters either we need to carry around
67  *        a list of prefix locations or we may need to locate them several
68  *        times.
69  *     b. If we actually directly modify the "original text" as we go then we
70  *        will need some special "caching" to handle the fact that when we
71  *        ellipsify the text the ellipsis may modify the next line of text,
72  *        which we have not yet processed.  (e.g. ellipsification of a W at the
73  *        end of a line will overwrite the W, the \n and the first character of
74  *        the next line, and a \0 will overwrite the second.  Try it!!)
75  *
76  *     Option 1.  Three separate storages. (To be implemented)
77  *       If DT_MODIFYSTRING is in effect then allocate an extra buffer to hold
78  *       the edited string in some form, either as the string itself or as some
79  *       sort of "edit list" to be applied just before returning.
80  *       Use a buffer that holds the ellipsified current line sans ampersands
81  *       and accept the need occasionally to recalculate the prefixes (if
82  *       DT_EXPANDTABS and not DT_NOPREFIX and not DT_HIDEPREFIX)
83  */
84
85 #define TAB     9
86 #define LF     10
87 #define CR     13
88 #define SPACE  32
89 #define PREFIX 38
90 #define ALPHA_PREFIX 30 /* Win16: Alphabet prefix */
91 #define KANA_PREFIX  31 /* Win16: Katakana prefix */
92
93 #define FORWARD_SLASH '/'
94 #define BACK_SLASH '\\'
95
96 static const WCHAR ELLIPSISW[] = {'.','.','.', 0};
97
98 typedef struct tag_ellipsis_data
99 {
100     int before;
101     int len;
102     int under;
103     int after;
104 } ellipsis_data;
105
106 /*********************************************************************
107  *                      TEXT_Ellipsify (static)
108  *
109  *  Add an ellipsis to the end of the given string whilst ensuring it fits.
110  *
111  * If the ellipsis alone doesn't fit then it will be returned anyway.
112  *
113  * See Also TEXT_PathEllipsify
114  *
115  * Arguments
116  *   hdc        [in] The handle to the DC that defines the font.
117  *   str        [in/out] The string that needs to be modified.
118  *   max_str    [in] The dimension of str (number of WCHAR).
119  *   len_str    [in/out] The number of characters in str
120  *   width      [in] The maximum width permitted (in logical coordinates)
121  *   size       [out] The dimensions of the text
122  *   modstr     [out] The modified form of the string, to be returned to the
123  *                    calling program.  It is assumed that the caller has
124  *                    made sufficient space available so we don't need to
125  *                    know the size of the space.  This pointer may be NULL if
126  *                    the modified string is not required.
127  *   len_before [out] The number of characters before the ellipsis.
128  *   len_ellip  [out] The number of characters in the ellipsis.
129  *
130  * See for example Microsoft article Q249678.
131  *
132  * For now we will simply use three dots rather than worrying about whether
133  * the font contains an explicit ellipsis character.
134  */
135 static void TEXT_Ellipsify (HDC hdc, WCHAR *str, unsigned int max_len,
136                             unsigned int *len_str, int width, SIZE *size,
137                             WCHAR *modstr,
138                             int *len_before, int *len_ellip)
139 {
140     unsigned int len_ellipsis;
141     unsigned int lo, mid, hi;
142
143     len_ellipsis = strlenW (ELLIPSISW);
144     if (len_ellipsis > max_len) len_ellipsis = max_len;
145     if (*len_str > max_len - len_ellipsis)
146         *len_str = max_len - len_ellipsis;
147
148     /* First do a quick binary search to get an upper bound for *len_str. */
149     if (*len_str > 0 &&
150         GetTextExtentExPointW(hdc, str, *len_str, width, NULL, NULL, size) &&
151         size->cx > width)
152     {
153         for (lo = 0, hi = *len_str; lo < hi; )
154         {
155             mid = (lo + hi) / 2;
156             if (!GetTextExtentExPointW(hdc, str, mid, width, NULL, NULL, size))
157                 break;
158             if (size->cx > width)
159                 hi = mid;
160             else
161                 lo = mid + 1;
162         }
163         *len_str = hi;
164     }
165     /* Now this should take only a couple iterations at most. */
166     for ( ; ; )
167     {
168         memcpy(str + *len_str, ELLIPSISW, len_ellipsis*sizeof(WCHAR));
169
170         if (!GetTextExtentExPointW (hdc, str, *len_str + len_ellipsis, width,
171                                     NULL, NULL, size)) break;
172
173         if (!*len_str || size->cx <= width) break;
174
175         (*len_str)--;
176     }
177     *len_ellip = len_ellipsis;
178     *len_before = *len_str;
179     *len_str += len_ellipsis;
180
181     if (modstr)
182     {
183         memcpy (modstr, str, *len_str * sizeof(WCHAR));
184         modstr[*len_str] = '\0';
185     }
186 }
187
188 /*********************************************************************
189  *                      TEXT_PathEllipsify (static)
190  *
191  * Add an ellipsis to the provided string in order to make it fit within
192  * the width.  The ellipsis is added as specified for the DT_PATH_ELLIPSIS
193  * flag.
194  *
195  * See Also TEXT_Ellipsify
196  *
197  * Arguments
198  *   hdc        [in] The handle to the DC that defines the font.
199  *   str        [in/out] The string that needs to be modified
200  *   max_str    [in] The dimension of str (number of WCHAR).
201  *   len_str    [in/out] The number of characters in str
202  *   width      [in] The maximum width permitted (in logical coordinates)
203  *   size       [out] The dimensions of the text
204  *   modstr     [out] The modified form of the string, to be returned to the
205  *                    calling program.  It is assumed that the caller has
206  *                    made sufficient space available so we don't need to
207  *                    know the size of the space.  This pointer may be NULL if
208  *                    the modified string is not required.
209  *   pellip     [out] The ellipsification results
210  *
211  * For now we will simply use three dots rather than worrying about whether
212  * the font contains an explicit ellipsis character.
213  *
214  * The following applies, I think to Win95.  We will need to extend it for
215  * Win98 which can have both path and end ellipsis at the same time (e.g.
216  *  C:\MyLongFileName.Txt becomes ...\MyLongFileN...)
217  *
218  * The resulting string consists of as much as possible of the following:
219  * 1. The ellipsis itself
220  * 2. The last \ or / of the string (if any)
221  * 3. Everything after the last \ or / of the string (if any) or the whole
222  *    string if there is no / or \.  I believe that under Win95 this would
223  *    include everything even though some might be clipped off the end whereas
224  *    under Win98 that might be ellipsified too.
225  *    Yet to be investigated is whether this would include wordbreaking if the
226  *    filename is more than 1 word and splitting if DT_EDITCONTROL was in
227  *    effect.  (If DT_EDITCONTROL is in effect then on occasions text will be
228  *    broken within words).
229  * 4. All the stuff before the / or \, which is placed before the ellipsis.
230  */
231 static void TEXT_PathEllipsify (HDC hdc, WCHAR *str, unsigned int max_len,
232                                 unsigned int *len_str, int width, SIZE *size,
233                                 WCHAR *modstr, ellipsis_data *pellip)
234 {
235     int len_ellipsis;
236     int len_trailing;
237     int len_under;
238     WCHAR *lastBkSlash, *lastFwdSlash, *lastSlash;
239
240     len_ellipsis = strlenW (ELLIPSISW);
241     if (!max_len) return;
242     if (len_ellipsis >= max_len) len_ellipsis = max_len - 1;
243     if (*len_str + len_ellipsis >= max_len)
244         *len_str = max_len - len_ellipsis-1;
245         /* Hopefully this will never happen, otherwise it would probably lose
246          * the wrong character
247          */
248     str[*len_str] = '\0'; /* to simplify things */
249
250     lastBkSlash  = strrchrW (str, BACK_SLASH);
251     lastFwdSlash = strrchrW (str, FORWARD_SLASH);
252     lastSlash = lastBkSlash > lastFwdSlash ? lastBkSlash : lastFwdSlash;
253     if (!lastSlash) lastSlash = str;
254     len_trailing = *len_str - (lastSlash - str);
255
256     /* overlap-safe movement to the right */
257     memmove (lastSlash+len_ellipsis, lastSlash, len_trailing * sizeof(WCHAR));
258     memcpy (lastSlash, ELLIPSISW, len_ellipsis*sizeof(WCHAR));
259     len_trailing += len_ellipsis;
260     /* From this point on lastSlash actually points to the ellipsis in front
261      * of the last slash and len_trailing includes the ellipsis
262      */
263
264     len_under = 0;
265     for ( ; ; )
266     {
267         if (!GetTextExtentExPointW (hdc, str, *len_str + len_ellipsis, width,
268                                     NULL, NULL, size)) break;
269
270         if (lastSlash == str || size->cx <= width) break;
271
272         /* overlap-safe movement to the left */
273         memmove (lastSlash-1, lastSlash, len_trailing * sizeof(WCHAR));
274         lastSlash--;
275         len_under++;
276
277         assert (*len_str);
278         (*len_str)--;
279     }
280     pellip->before = lastSlash-str;
281     pellip->len = len_ellipsis;
282     pellip->under = len_under;
283     pellip->after = len_trailing - len_ellipsis;
284     *len_str += len_ellipsis;
285
286     if (modstr)
287     {
288         memcpy(modstr, str, *len_str * sizeof(WCHAR));
289         modstr[*len_str] = '\0';
290     }
291 }
292
293 /*********************************************************************
294  *                      TEXT_WordBreak (static)
295  *
296  *  Perform wordbreak processing on the given string
297  *
298  * Assumes that DT_WORDBREAK has been specified and not all the characters
299  * fit.  Note that this function should even be called when the first character
300  * that doesn't fit is known to be a space or tab, so that it can swallow them.
301  *
302  * Note that the Windows processing has some strange properties.
303  * 1. If the text is left-justified and there is room for some of the spaces
304  *    that follow the last word on the line then those that fit are included on
305  *    the line.
306  * 2. If the text is centered or right-justified and there is room for some of
307  *    the spaces that follow the last word on the line then all but one of those
308  *    that fit are included on the line.
309  * 3. (Reasonable behaviour) If the word breaking causes a space to be the first
310  *    character of a new line it will be skipped.
311  *
312  * Arguments
313  *   hdc        [in] The handle to the DC that defines the font.
314  *   str        [in/out] The string that needs to be broken.
315  *   max_str    [in] The dimension of str (number of WCHAR).
316  *   len_str    [in/out] The number of characters in str
317  *   width      [in] The maximum width permitted
318  *   format     [in] The format flags in effect
319  *   chars_fit  [in] The maximum number of characters of str that are already
320  *              known to fit; chars_fit+1 is known not to fit.
321  *   chars_used [out] The number of characters of str that have been "used" and
322  *              do not need to be included in later text.  For example this will
323  *              include any spaces that have been discarded from the start of
324  *              the next line.
325  *   size       [out] The size of the returned text in logical coordinates
326  *
327  * Pedantic assumption - Assumes that the text length is monotonically
328  * increasing with number of characters (i.e. no weird kernings)
329  *
330  * Algorithm
331  *
332  * Work back from the last character that did fit to either a space or the last
333  * character of a word, whichever is met first.
334  * If there was one or the first character didn't fit then
335  *     If the text is centered or right justified and that one character was a
336  *     space then break the line before that character
337  *     Otherwise break the line after that character
338  *     and if the next character is a space then discard it.
339  * Suppose there was none (and the first character did fit).
340  *     If Break Within Word is permitted
341  *         break the word after the last character that fits (there must be
342  *         at least one; none is caught earlier).
343  *     Otherwise
344  *         discard any trailing space.
345  *         include the whole word; it may be ellipsified later
346  *
347  * Break Within Word is permitted under a set of circumstances that are not
348  * totally clear yet.  Currently our best guess is:
349  *     If DT_EDITCONTROL is in effect and neither DT_WORD_ELLIPSIS nor
350  *     DT_PATH_ELLIPSIS is
351  */
352
353 static void TEXT_WordBreak (HDC hdc, WCHAR *str, unsigned int max_str,
354                             unsigned int *len_str,
355                             int width, int format, unsigned int chars_fit,
356                             unsigned int *chars_used, SIZE *size)
357 {
358     WCHAR *p;
359     int word_fits;
360     assert (format & DT_WORDBREAK);
361     assert (chars_fit < *len_str);
362
363     /* Work back from the last character that did fit to either a space or the
364      * last character of a word, whichever is met first.
365      */
366     p = str + chars_fit; /* The character that doesn't fit */
367     word_fits = TRUE;
368     if (!chars_fit)
369         ; /* we pretend that it fits anyway */
370     else if (*p == SPACE) /* chars_fit < *len_str so this is valid */
371         p--; /* the word just fitted */
372     else
373     {
374         while (p > str && *(--p) != SPACE)
375             ;
376         word_fits = (p != str || *p == SPACE);
377     }
378     /* If there was one or the first character didn't fit then */
379     if (word_fits)
380     {
381         int next_is_space;
382         /* break the line before/after that character */
383         if (!(format & (DT_RIGHT | DT_CENTER)) || *p != SPACE)
384             p++;
385         next_is_space = (p - str) < *len_str && *p == SPACE;
386         *len_str = p - str;
387         /* and if the next character is a space then discard it. */
388         *chars_used = *len_str;
389         if (next_is_space)
390             (*chars_used)++;
391     }
392     /* Suppose there was none. */
393     else
394     {
395         if ((format & (DT_EDITCONTROL | DT_WORD_ELLIPSIS | DT_PATH_ELLIPSIS)) ==
396             DT_EDITCONTROL)
397         {
398             /* break the word after the last character that fits (there must be
399              * at least one; none is caught earlier).
400              */
401             *len_str = chars_fit;
402             *chars_used = chars_fit;
403
404             /* FIXME - possible error.  Since the next character is now removed
405              * this could make the text longer so that it no longer fits, and
406              * so we need a loop to test and shrink.
407              */
408         }
409         /* Otherwise */
410         else
411         {
412             /* discard any trailing space. */
413             const WCHAR *e = str + *len_str;
414             p = str + chars_fit;
415             while (p < e && *p != SPACE)
416                 p++;
417             *chars_used = p - str;
418             if (p < e) /* i.e. loop failed because *p == SPACE */
419                 (*chars_used)++;
420
421             /* include the whole word; it may be ellipsified later */
422             *len_str = p - str;
423             /* Possible optimisation; if DT_WORD_ELLIPSIS only use chars_fit+1
424              * so that it will be too long
425              */
426         }
427     }
428     /* Remeasure the string */
429     GetTextExtentExPointW (hdc, str, *len_str, 0, NULL, NULL, size);
430 }
431
432 /*********************************************************************
433  *                      TEXT_SkipChars
434  *
435  *  Skip over the given number of characters, bearing in mind prefix
436  *  substitution and the fact that a character may take more than one
437  *  WCHAR (Unicode surrogates are two words long) (and there may have been
438  *  a trailing &)
439  *
440  * Parameters
441  *   new_count  [out] The updated count
442  *   new_str    [out] The updated pointer
443  *   start_count [in] The count of remaining characters corresponding to the
444  *                    start of the string
445  *   start_str  [in] The starting point of the string
446  *   max        [in] The number of characters actually in this segment of the
447  *                   string (the & counts)
448  *   n          [in] The number of characters to skip (if prefix then
449  *                   &c counts as one)
450  *   prefix     [in] Apply prefix substitution
451  *
452  * Return Values
453  *   none
454  *
455  * Remarks
456  *   There must be at least n characters in the string
457  *   We need max because the "line" may have ended with a & followed by a tab
458  *   or newline etc. which we don't want to swallow
459  */
460
461 static void TEXT_SkipChars (int *new_count, const WCHAR **new_str,
462                             int start_count, const WCHAR *start_str,
463                             int max, int n, int prefix)
464 {
465     /* This is specific to wide characters, MSDN doesn't say anything much
466      * about Unicode surrogates yet and it isn't clear if _wcsinc will
467      * correctly handle them so we'll just do this the easy way for now
468      */
469
470     if (prefix)
471     {
472         const WCHAR *str_on_entry = start_str;
473         assert (max >= n);
474         max -= n;
475         while (n--)
476         {
477             if ((*start_str == PREFIX || *start_str == ALPHA_PREFIX) && max--)
478                 start_str++;
479             start_str++;
480         }
481         start_count -= (start_str - str_on_entry);
482     }
483     else
484     {
485         start_str += n;
486         start_count -= n;
487     }
488     *new_str = start_str;
489     *new_count = start_count;
490 }
491
492 /*********************************************************************
493  *                      TEXT_Reprefix
494  *
495  *  Reanalyse the text to find the prefixed character.  This is called when
496  *  wordbreaking or ellipsification has shortened the string such that the
497  *  previously noted prefixed character is no longer visible.
498  *
499  * Parameters
500  *   str        [in] The original string segment (including all characters)
501  *   ns         [in] The number of characters in str (including prefixes)
502  *   pe         [in] The ellipsification data
503  *
504  * Return Values
505  *   The prefix offset within the new string segment (the one that contains the
506  *   ellipses and does not contain the prefix characters) (-1 if none)
507  */
508
509 static int TEXT_Reprefix (const WCHAR *str, unsigned int ns,
510                           const ellipsis_data *pe)
511 {
512     int result = -1;
513     unsigned int i;
514     unsigned int n = pe->before + pe->under + pe->after;
515     assert (n <= ns);
516     for (i = 0; i < n; i++, str++)
517     {
518         if (i == pe->before)
519         {
520             /* Reached the path ellipsis; jump over it */
521             if (ns < pe->under) break;
522             str += pe->under;
523             ns -= pe->under;
524             i += pe->under;
525             if (!pe->after) break; /* Nothing after the path ellipsis */
526         }
527         if (!ns) break;
528         ns--;
529         if (*str == PREFIX || *str == ALPHA_PREFIX)
530         {
531             str++;
532             if (!ns) break;
533             if (*str != PREFIX)
534                 result = (i < pe->before || pe->under == 0) ? i : i - pe->under + pe->len;
535                 /* pe->len may be non-zero while pe_under is zero */
536             ns--;
537         }
538     }
539     return result;
540 }
541
542 /*********************************************************************
543  *  Returns true if and only if the remainder of the line is a single
544  *  newline representation or nothing
545  */
546
547 static int remainder_is_none_or_newline (int num_chars, const WCHAR *str)
548 {
549     if (!num_chars) return TRUE;
550     if (*str != LF && *str != CR) return FALSE;
551     if (!--num_chars) return TRUE;
552     if (*str == *(str+1)) return FALSE;
553     str++;
554     if (*str != CR && *str != LF) return FALSE;
555     if (--num_chars) return FALSE;
556     return TRUE;
557 }
558
559 /*********************************************************************
560  *  Return next line of text from a string.
561  *
562  * hdc - handle to DC.
563  * str - string to parse into lines.
564  * count - length of str.
565  * dest - destination in which to return line.
566  * len - dest buffer size in chars on input, copied length into dest on output.
567  * width - maximum width of line in pixels.
568  * format - format type passed to DrawText.
569  * retsize - returned size of the line in pixels.
570  * last_line - TRUE if is the last line that will be processed
571  * p_retstr - If DT_MODIFYSTRING this points to a cursor in the buffer in which
572  *            the return string is built.
573  * tabwidth - The width of a tab in logical coordinates
574  * pprefix_offset - Here is where we return the offset within dest of the first
575  *                  prefixed (underlined) character.  -1 is returned if there
576  *                  are none.  Note that there may be more; the calling code
577  *                  will need to use TEXT_Reprefix to find any later ones.
578  * pellip - Here is where we return the information about any ellipsification
579  *          that was carried out.  Note that if tabs are being expanded then
580  *          this data will correspond to the last text segment actually
581  *          returned in dest; by definition there would not have been any
582  *          ellipsification in earlier text segments of the line.
583  *
584  * Returns pointer to next char in str after end of the line
585  * or NULL if end of str reached.
586  */
587 static const WCHAR *TEXT_NextLineW( HDC hdc, const WCHAR *str, int *count,
588                                  WCHAR *dest, int *len, int width, DWORD format,
589                                  SIZE *retsize, int last_line, WCHAR **p_retstr,
590                                  int tabwidth, int *pprefix_offset,
591                                  ellipsis_data *pellip)
592 {
593     int i = 0, j = 0;
594     int plen = 0;
595     SIZE size;
596     int maxl = *len;
597     int seg_i, seg_count, seg_j;
598     int max_seg_width;
599     int num_fit;
600     int word_broken;
601     int line_fits;
602     unsigned int j_in_seg;
603     int ellipsified;
604     *pprefix_offset = -1;
605
606     /* For each text segment in the line */
607
608     retsize->cy = 0;
609     while (*count)
610     {
611
612         /* Skip any leading tabs */
613
614         if (str[i] == TAB && (format & DT_EXPANDTABS))
615         {
616             plen = ((plen/tabwidth)+1)*tabwidth;
617             (*count)--; if (j < maxl) dest[j++] = str[i++]; else i++;
618             while (*count && str[i] == TAB)
619             {
620                 plen += tabwidth;
621                 (*count)--; if (j < maxl) dest[j++] = str[i++]; else i++;
622             }
623         }
624
625
626         /* Now copy as far as the next tab or cr/lf or eos */
627
628         seg_i = i;
629         seg_count = *count;
630         seg_j = j;
631
632         while (*count &&
633                (str[i] != TAB || !(format & DT_EXPANDTABS)) &&
634                ((str[i] != CR && str[i] != LF) || (format & DT_SINGLELINE)))
635         {
636             if ((format & DT_NOPREFIX) || *count <= 1)
637             {
638                 (*count)--; if (j < maxl) dest[j++] = str[i++]; else i++;
639                 continue;
640             }
641
642             if (str[i] == PREFIX || str[i] == ALPHA_PREFIX) {
643                 (*count)--, i++; /* Throw away the prefix itself */
644                 if (str[i] == PREFIX)
645                 {
646                     /* Swallow it before we see it again */
647                     (*count)--; if (j < maxl) dest[j++] = str[i++]; else i++;
648                 }
649                 else if (*pprefix_offset == -1 || *pprefix_offset >= seg_j)
650                 {
651                     *pprefix_offset = j;
652                 }
653                 /* else the previous prefix was in an earlier segment of the
654                  * line; we will leave it to the drawing code to catch this
655                  * one.
656                  */
657             }
658             else if (str[i] == KANA_PREFIX)
659             {
660                 /* Throw away katakana access keys */
661                 (*count)--, i++; /* skip the prefix */
662                 (*count)--, i++; /* skip the letter */
663             }
664             else
665             {
666                 (*count)--; if (j < maxl) dest[j++] = str[i++]; else i++;
667             }
668         }
669
670
671         /* Measure the whole text segment and possibly WordBreak and
672          * ellipsify it
673          */
674
675         j_in_seg = j - seg_j;
676         max_seg_width = width - plen;
677         GetTextExtentExPointW (hdc, dest + seg_j, j_in_seg, max_seg_width, &num_fit, NULL, &size);
678
679         /* The Microsoft handling of various combinations of formats is weird.
680          * The following may very easily be incorrect if several formats are
681          * combined, and may differ between versions (to say nothing of the
682          * several bugs in the Microsoft versions).
683          */
684         word_broken = 0;
685         line_fits = (num_fit >= j_in_seg);
686         if (!line_fits && (format & DT_WORDBREAK))
687         {
688             const WCHAR *s;
689             unsigned int chars_used;
690             TEXT_WordBreak (hdc, dest+seg_j, maxl-seg_j, &j_in_seg,
691                             max_seg_width, format, num_fit, &chars_used, &size);
692             line_fits = (size.cx <= max_seg_width);
693             /* and correct the counts */
694             TEXT_SkipChars (count, &s, seg_count, str+seg_i, i-seg_i,
695                             chars_used, !(format & DT_NOPREFIX));
696             i = s - str;
697             word_broken = 1;
698         }
699         pellip->before = j_in_seg;
700         pellip->under = 0;
701         pellip->after = 0;
702         pellip->len = 0;
703         ellipsified = 0;
704         if (!line_fits && (format & DT_PATH_ELLIPSIS))
705         {
706             TEXT_PathEllipsify (hdc, dest + seg_j, maxl-seg_j, &j_in_seg,
707                                 max_seg_width, &size, *p_retstr, pellip);
708             line_fits = (size.cx <= max_seg_width);
709             ellipsified = 1;
710         }
711         /* NB we may end up ellipsifying a word-broken or path_ellipsified
712          * string */
713         if ((!line_fits && (format & DT_WORD_ELLIPSIS)) ||
714             ((format & DT_END_ELLIPSIS) &&
715               ((last_line && *count) ||
716                (remainder_is_none_or_newline (*count, &str[i]) && !line_fits))))
717         {
718             int before, len_ellipsis;
719             TEXT_Ellipsify (hdc, dest + seg_j, maxl-seg_j, &j_in_seg,
720                             max_seg_width, &size, *p_retstr, &before, &len_ellipsis);
721             if (before > pellip->before)
722             {
723                 /* We must have done a path ellipsis too */
724                 pellip->after = before - pellip->before - pellip->len;
725                 /* Leave the len as the length of the first ellipsis */
726             }
727             else
728             {
729                 /* If we are here after a path ellipsification it must be
730                  * because even the ellipsis itself didn't fit.
731                  */
732                 assert (pellip->under == 0 && pellip->after == 0);
733                 pellip->before = before;
734                 pellip->len = len_ellipsis;
735                 /* pellip->after remains as zero as does
736                  * pellip->under
737                  */
738             }
739             ellipsified = 1;
740         }
741         /* As an optimisation if we have ellipsified and we are expanding
742          * tabs and we haven't reached the end of the line we can skip to it
743          * now rather than going around the loop again.
744          */
745         if ((format & DT_EXPANDTABS) && ellipsified)
746         {
747             if (format & DT_SINGLELINE)
748                 *count = 0;
749             else
750             {
751                 while ((*count) && str[i] != CR && str[i] != LF)
752                 {
753                     (*count)--, i++;
754                 }
755             }
756         }
757
758         j = seg_j + j_in_seg;
759         if (*pprefix_offset >= seg_j + pellip->before)
760         {
761             *pprefix_offset = TEXT_Reprefix (str + seg_i, i - seg_i, pellip);
762             if (*pprefix_offset != -1)
763                 *pprefix_offset += seg_j;
764         }
765
766         plen += size.cx;
767         if (size.cy > retsize->cy)
768             retsize->cy = size.cy;
769
770         if (word_broken)
771             break;
772         else if (!*count)
773             break;
774         else if (str[i] == CR || str[i] == LF)
775         {
776             (*count)--, i++;
777             if (*count && (str[i] == CR || str[i] == LF) && str[i] != str[i-1])
778             {
779                 (*count)--, i++;
780             }
781             break;
782         }
783         /* else it was a Tab and we go around again */
784     }
785
786     retsize->cx = plen;
787     *len = j;
788     if (*count)
789         return (&str[i]);
790     else
791         return NULL;
792 }
793
794
795 /***********************************************************************
796  *                      TEXT_DrawUnderscore
797  *
798  *  Draw the underline under the prefixed character
799  *
800  * Parameters
801  *   hdc        [in] The handle of the DC for drawing
802  *   x          [in] The x location of the line segment (logical coordinates)
803  *   y          [in] The y location of where the underscore should appear
804  *                   (logical coordinates)
805  *   str        [in] The text of the line segment
806  *   offset     [in] The offset of the underscored character within str
807  *   rect       [in] Clipping rectangle (if not NULL)
808  */
809
810 static void TEXT_DrawUnderscore (HDC hdc, int x, int y, const WCHAR *str, int offset, const RECT *rect)
811 {
812     int prefix_x;
813     int prefix_end;
814     SIZE size;
815     HPEN hpen;
816     HPEN oldPen;
817
818     GetTextExtentPointW (hdc, str, offset, &size);
819     prefix_x = x + size.cx;
820     GetTextExtentPointW (hdc, str, offset+1, &size);
821     prefix_end = x + size.cx - 1;
822     /* The above method may eventually be slightly wrong due to kerning etc. */
823
824     /* Check for clipping */
825     if (rect){
826         if (prefix_x > rect->right || prefix_end < rect->left || y < rect->top || y > rect->bottom)
827             return; /* Completely outside */
828         /* Partially outside */
829         if (prefix_x   < rect->left ) prefix_x   = rect->left;
830         if (prefix_end > rect->right) prefix_end = rect->right;
831     }
832     
833     hpen = CreatePen (PS_SOLID, 1, GetTextColor (hdc));
834     oldPen = SelectObject (hdc, hpen);
835     MoveToEx (hdc, prefix_x, y, NULL);
836     LineTo (hdc, prefix_end, y);
837     SelectObject (hdc, oldPen);
838     DeleteObject (hpen);
839 }
840
841 /***********************************************************************
842  *           DrawTextExW    (USER32.@)
843  *
844  * The documentation on the extra space required for DT_MODIFYSTRING at MSDN
845  * is not quite complete, especially with regard to \0.  We will assume that
846  * the returned string could have a length of up to i_count+3 and also have
847  * a trailing \0 (which would be 4 more than a not-null-terminated string but
848  * 3 more than a null-terminated string).  If this is not so then increase
849  * the allowance in DrawTextExA.
850  */
851 #define MAX_BUFFER 1024
852 INT WINAPI DrawTextExW( HDC hdc, LPWSTR str, INT i_count,
853                         LPRECT rect, UINT flags, LPDRAWTEXTPARAMS dtp )
854 {
855     SIZE size;
856     const WCHAR *strPtr;
857     WCHAR *retstr, *p_retstr;
858     size_t size_retstr;
859     WCHAR line[MAX_BUFFER];
860     int len, lh, count=i_count;
861     TEXTMETRICW tm;
862     int lmargin = 0, rmargin = 0;
863     int x = rect->left, y = rect->top;
864     int width = rect->right - rect->left;
865     int max_width = 0;
866     int last_line;
867     int tabwidth /* to keep gcc happy */ = 0;
868     int prefix_offset;
869     ellipsis_data ellip;
870     int invert_y=0;
871
872     TRACE("%s, %d, [%s] %08x\n", debugstr_wn (str, count), count,
873         wine_dbgstr_rect(rect), flags);
874
875    if (dtp) TRACE("Params: iTabLength=%d, iLeftMargin=%d, iRightMargin=%d\n",
876           dtp->iTabLength, dtp->iLeftMargin, dtp->iRightMargin);
877
878     if (!str) return 0;
879
880     strPtr = str;
881
882     if (flags & DT_SINGLELINE)
883         flags &= ~DT_WORDBREAK;
884
885     GetTextMetricsW(hdc, &tm);
886     if (flags & DT_EXTERNALLEADING)
887         lh = tm.tmHeight + tm.tmExternalLeading;
888     else
889         lh = tm.tmHeight;
890
891     if (str[0] && count == 0)
892         return lh;
893
894     if (dtp && dtp->cbSize != sizeof(DRAWTEXTPARAMS))
895         return 0;
896
897     if (count == -1)
898     {
899         count = strlenW(str);
900         if (count == 0)
901         {
902             if( flags & DT_CALCRECT)
903             {
904                 rect->right = rect->left;
905                 if( flags & DT_SINGLELINE)
906                     rect->bottom = rect->top + lh;
907                 else
908                     rect->bottom = rect->top;
909             }
910             return lh;
911         }
912     }
913
914     if (GetGraphicsMode(hdc) == GM_COMPATIBLE)
915     {
916         SIZE window_ext, viewport_ext;
917         GetWindowExtEx(hdc, &window_ext);
918         GetViewportExtEx(hdc, &viewport_ext);
919         if ((window_ext.cy > 0) != (viewport_ext.cy > 0))
920             invert_y = 1;
921     }
922
923     if (dtp)
924     {
925         lmargin = dtp->iLeftMargin;
926         rmargin = dtp->iRightMargin;
927         if (!(flags & (DT_CENTER | DT_RIGHT)))
928             x += lmargin;
929         dtp->uiLengthDrawn = 0;     /* This param RECEIVES number of chars processed */
930     }
931
932     if (flags & DT_EXPANDTABS)
933     {
934         int tabstop = ((flags & DT_TABSTOP) && dtp) ? dtp->iTabLength : 8;
935         tabwidth = tm.tmAveCharWidth * tabstop;
936     }
937
938     if (flags & DT_CALCRECT) flags |= DT_NOCLIP;
939
940     if (flags & DT_MODIFYSTRING)
941     {
942         size_retstr = (count + 4) * sizeof (WCHAR);
943         retstr = HeapAlloc(GetProcessHeap(), 0, size_retstr);
944         if (!retstr) return 0;
945         memcpy (retstr, str, size_retstr);
946     }
947     else
948     {
949         size_retstr = 0;
950         retstr = NULL;
951     }
952     p_retstr = retstr;
953
954     do
955     {
956         len = sizeof(line)/sizeof(line[0]);
957         if (invert_y)
958             last_line = !(flags & DT_NOCLIP) && y - ((flags & DT_EDITCONTROL) ? 2*lh-1 : lh) < rect->bottom;
959         else
960             last_line = !(flags & DT_NOCLIP) && y + ((flags & DT_EDITCONTROL) ? 2*lh-1 : lh) > rect->bottom;
961         strPtr = TEXT_NextLineW(hdc, strPtr, &count, line, &len, width, flags, &size, last_line, &p_retstr, tabwidth, &prefix_offset, &ellip);
962
963         if (flags & DT_CENTER) x = (rect->left + rect->right -
964                                     size.cx) / 2;
965         else if (flags & DT_RIGHT) x = rect->right - size.cx;
966
967         if (flags & DT_SINGLELINE)
968         {
969             if (flags & DT_VCENTER) y = rect->top +
970                 (rect->bottom - rect->top) / 2 - size.cy / 2;
971             else if (flags & DT_BOTTOM) y = rect->bottom - size.cy;
972         }
973
974         if (!(flags & DT_CALCRECT))
975         {
976             const WCHAR *str = line;
977             int xseg = x;
978             while (len)
979             {
980                 int len_seg;
981                 SIZE size;
982                 if ((flags & DT_EXPANDTABS))
983                 {
984                     const WCHAR *p;
985                     p = str; while (p < str+len && *p != TAB) p++;
986                     len_seg = p - str;
987                     if (len_seg != len && !GetTextExtentPointW(hdc, str, len_seg, &size))
988                         return 0;
989                 }
990                 else
991                     len_seg = len;
992
993                 if (!ExtTextOutW( hdc, xseg, y,
994                                  ((flags & DT_NOCLIP) ? 0 : ETO_CLIPPED) |
995                                  ((flags & DT_RTLREADING) ? ETO_RTLREADING : 0),
996                                  rect, str, len_seg, NULL ))  return 0;
997                 if (prefix_offset != -1 && prefix_offset < len_seg)
998                 {
999                     TEXT_DrawUnderscore (hdc, xseg, y + tm.tmAscent + 1, str, prefix_offset, (flags & DT_NOCLIP) ? NULL : rect);
1000                 }
1001                 len -= len_seg;
1002                 str += len_seg;
1003                 if (len)
1004                 {
1005                     assert ((flags & DT_EXPANDTABS) && *str == TAB);
1006                     len--; str++;
1007                     xseg += ((size.cx/tabwidth)+1)*tabwidth;
1008                     if (prefix_offset != -1)
1009                     {
1010                         if (prefix_offset < len_seg)
1011                         {
1012                             /* We have just drawn an underscore; we ought to
1013                              * figure out where the next one is.  I am going
1014                              * to leave it for now until I have a better model
1015                              * for the line, which will make reprefixing easier.
1016                              * This is where ellip would be used.
1017                              */
1018                             prefix_offset = -1;
1019                         }
1020                         else
1021                             prefix_offset -= len_seg;
1022                     }
1023                 }
1024             }
1025         }
1026         else if (size.cx > max_width)
1027             max_width = size.cx;
1028
1029         if (invert_y)
1030             y -= lh;
1031         else
1032             y += lh;
1033         if (dtp)
1034             dtp->uiLengthDrawn += len;
1035     }
1036     while (strPtr && !last_line);
1037
1038     if (flags & DT_CALCRECT)
1039     {
1040         rect->right = rect->left + max_width;
1041         rect->bottom = y;
1042         if (dtp)
1043             rect->right += lmargin + rmargin;
1044     }
1045     if (retstr)
1046     {
1047         memcpy (str, retstr, size_retstr);
1048         HeapFree (GetProcessHeap(), 0, retstr);
1049     }
1050     return y - rect->top;
1051 }
1052
1053 /***********************************************************************
1054  *           DrawTextExA    (USER32.@)
1055  *
1056  * If DT_MODIFYSTRING is specified then there must be room for up to
1057  * 4 extra characters.  We take great care about just how much modified
1058  * string we return.
1059  */
1060 INT WINAPI DrawTextExA( HDC hdc, LPSTR str, INT count,
1061                         LPRECT rect, UINT flags, LPDRAWTEXTPARAMS dtp )
1062 {
1063    WCHAR *wstr;
1064    WCHAR *p;
1065    INT ret = 0;
1066    int i;
1067    DWORD wcount;
1068    DWORD wmax;
1069    DWORD amax;
1070    UINT cp;
1071
1072    if (!count) return 0;
1073    if (!str && count > 0) return 0;
1074    if( !str || ((count == -1) && !(count = strlen(str))))
1075    {
1076         int lh;
1077         TEXTMETRICA tm;
1078
1079         if (dtp && dtp->cbSize != sizeof(DRAWTEXTPARAMS))
1080             return 0;
1081
1082         GetTextMetricsA(hdc, &tm);
1083         if (flags & DT_EXTERNALLEADING)
1084             lh = tm.tmHeight + tm.tmExternalLeading;
1085         else
1086             lh = tm.tmHeight;
1087
1088         if( flags & DT_CALCRECT)
1089         {
1090             rect->right = rect->left;
1091             if( flags & DT_SINGLELINE)
1092                 rect->bottom = rect->top + lh;
1093             else
1094                 rect->bottom = rect->top;
1095         }
1096         return lh;
1097    }
1098    cp = GdiGetCodePage( hdc );
1099    wcount = MultiByteToWideChar( cp, 0, str, count, NULL, 0 );
1100    wmax = wcount;
1101    amax = count;
1102    if (flags & DT_MODIFYSTRING)
1103    {
1104         wmax += 4;
1105         amax += 4;
1106    }
1107    wstr = HeapAlloc(GetProcessHeap(), 0, wmax * sizeof(WCHAR));
1108    if (wstr)
1109    {
1110        MultiByteToWideChar( cp, 0, str, count, wstr, wcount );
1111        if (flags & DT_MODIFYSTRING)
1112            for (i=4, p=wstr+wcount; i--; p++) *p=0xFFFE;
1113            /* Initialise the extra characters so that we can see which ones
1114             * change.  U+FFFE is guaranteed to be not a unicode character and
1115             * so will not be generated by DrawTextEx itself.
1116             */
1117        ret = DrawTextExW( hdc, wstr, wcount, rect, flags, dtp );
1118        if (flags & DT_MODIFYSTRING)
1119        {
1120             /* Unfortunately the returned string may contain multiple \0s
1121              * and so we need to measure it ourselves.
1122              */
1123             for (i=4, p=wstr+wcount; i-- && *p != 0xFFFE; p++) wcount++;
1124             WideCharToMultiByte( cp, 0, wstr, wcount, str, amax, NULL, NULL );
1125        }
1126        HeapFree(GetProcessHeap(), 0, wstr);
1127    }
1128    return ret;
1129 }
1130
1131 /***********************************************************************
1132  *           DrawTextW    (USER32.@)
1133  */
1134 INT WINAPI DrawTextW( HDC hdc, LPCWSTR str, INT count, LPRECT rect, UINT flags )
1135 {
1136     DRAWTEXTPARAMS dtp;
1137
1138     memset (&dtp, 0, sizeof(dtp));
1139     dtp.cbSize = sizeof(dtp);
1140     if (flags & DT_TABSTOP)
1141     {
1142         dtp.iTabLength = (flags >> 8) & 0xff;
1143         flags &= 0xffff00ff;
1144     }
1145     return DrawTextExW(hdc, (LPWSTR)str, count, rect, flags, &dtp);
1146 }
1147
1148 /***********************************************************************
1149  *           DrawTextA    (USER32.@)
1150  */
1151 INT WINAPI DrawTextA( HDC hdc, LPCSTR str, INT count, LPRECT rect, UINT flags )
1152 {
1153     DRAWTEXTPARAMS dtp;
1154
1155     memset (&dtp, 0, sizeof(dtp));
1156     dtp.cbSize = sizeof(dtp);
1157     if (flags & DT_TABSTOP)
1158     {
1159         dtp.iTabLength = (flags >> 8) & 0xff;
1160         flags &= 0xffff00ff;
1161     }
1162     return DrawTextExA( hdc, (LPSTR)str, count, rect, flags, &dtp );
1163 }
1164
1165 /***********************************************************************
1166  *
1167  *           GrayString functions
1168  */
1169
1170 /* callback for ASCII gray string proc */
1171 static BOOL CALLBACK gray_string_callbackA( HDC hdc, LPARAM param, INT len )
1172 {
1173     return TextOutA( hdc, 0, 0, (LPCSTR)param, len );
1174 }
1175
1176 /* callback for Unicode gray string proc */
1177 static BOOL CALLBACK gray_string_callbackW( HDC hdc, LPARAM param, INT len )
1178 {
1179     return TextOutW( hdc, 0, 0, (LPCWSTR)param, len );
1180 }
1181
1182 /***********************************************************************
1183  *           TEXT_GrayString
1184  */
1185 static BOOL TEXT_GrayString(HDC hdc, HBRUSH hb, GRAYSTRINGPROC fn, LPARAM lp, INT len,
1186                             INT x, INT y, INT cx, INT cy )
1187 {
1188     HBITMAP hbm, hbmsave;
1189     HBRUSH hbsave;
1190     HFONT hfsave;
1191     HDC memdc;
1192     int slen = len;
1193     BOOL retval = TRUE;
1194     COLORREF fg, bg;
1195
1196     if(!hdc) return FALSE;
1197     if (!(memdc = CreateCompatibleDC(hdc))) return FALSE;
1198
1199     hbm = CreateBitmap(cx, cy, 1, 1, NULL);
1200     hbmsave = SelectObject(memdc, hbm);
1201     hbsave = SelectObject( memdc, GetStockObject(BLACK_BRUSH) );
1202     PatBlt( memdc, 0, 0, cx, cy, PATCOPY );
1203     SelectObject( memdc, hbsave );
1204     SetTextColor(memdc, RGB(255, 255, 255));
1205     SetBkColor(memdc, RGB(0, 0, 0));
1206     hfsave = SelectObject(memdc, GetCurrentObject(hdc, OBJ_FONT));
1207
1208     retval = fn(memdc, lp, slen);
1209     SelectObject(memdc, hfsave);
1210
1211 /*
1212  * Windows doc says that the bitmap isn't grayed when len == -1 and
1213  * the callback function returns FALSE. However, testing this on
1214  * win95 showed otherwise...
1215 */
1216 #ifdef GRAYSTRING_USING_DOCUMENTED_BEHAVIOUR
1217     if(retval || len != -1)
1218 #endif
1219     {
1220         hbsave = SelectObject(memdc, SYSCOLOR_55AABrush);
1221         PatBlt(memdc, 0, 0, cx, cy, 0x000A0329);
1222         SelectObject(memdc, hbsave);
1223     }
1224
1225     if(hb) hbsave = SelectObject(hdc, hb);
1226     fg = SetTextColor(hdc, RGB(0, 0, 0));
1227     bg = SetBkColor(hdc, RGB(255, 255, 255));
1228     BitBlt(hdc, x, y, cx, cy, memdc, 0, 0, 0x00E20746);
1229     SetTextColor(hdc, fg);
1230     SetBkColor(hdc, bg);
1231     if(hb) SelectObject(hdc, hbsave);
1232
1233     SelectObject(memdc, hbmsave);
1234     DeleteObject(hbm);
1235     DeleteDC(memdc);
1236     return retval;
1237 }
1238
1239
1240 /***********************************************************************
1241  *           GrayStringA   (USER32.@)
1242  */
1243 BOOL WINAPI GrayStringA( HDC hdc, HBRUSH hbr, GRAYSTRINGPROC gsprc,
1244                          LPARAM lParam, INT cch, INT x, INT y,
1245                          INT cx, INT cy )
1246 {
1247     if (!cch) cch = strlen( (LPCSTR)lParam );
1248     if ((cx == 0 || cy == 0) && cch != -1)
1249     {
1250         SIZE s;
1251         GetTextExtentPoint32A( hdc, (LPCSTR)lParam, cch, &s );
1252         if (cx == 0) cx = s.cx;
1253         if (cy == 0) cy = s.cy;
1254     }
1255     if (!gsprc) gsprc = gray_string_callbackA;
1256     return TEXT_GrayString( hdc, hbr, gsprc, lParam, cch, x, y, cx, cy );
1257 }
1258
1259
1260 /***********************************************************************
1261  *           GrayStringW   (USER32.@)
1262  */
1263 BOOL WINAPI GrayStringW( HDC hdc, HBRUSH hbr, GRAYSTRINGPROC gsprc,
1264                          LPARAM lParam, INT cch, INT x, INT y,
1265                          INT cx, INT cy )
1266 {
1267     if (!cch) cch = strlenW( (LPCWSTR)lParam );
1268     if ((cx == 0 || cy == 0) && cch != -1)
1269     {
1270         SIZE s;
1271         GetTextExtentPoint32W( hdc, (LPCWSTR)lParam, cch, &s );
1272         if (cx == 0) cx = s.cx;
1273         if (cy == 0) cy = s.cy;
1274     }
1275     if (!gsprc) gsprc = gray_string_callbackW;
1276     return TEXT_GrayString( hdc, hbr, gsprc, lParam, cch, x, y, cx, cy );
1277 }
1278
1279
1280 /***********************************************************************
1281  *           TEXT_TabbedTextOut
1282  *
1283  * Helper function for TabbedTextOut() and GetTabbedTextExtent().
1284  * Note: this doesn't work too well for text-alignment modes other
1285  *       than TA_LEFT|TA_TOP. But we want bug-for-bug compatibility :-)
1286  */
1287 static LONG TEXT_TabbedTextOut( HDC hdc, INT x, INT y, LPCWSTR lpstr,
1288                                 INT count, INT cTabStops, const INT *lpTabPos, INT nTabOrg,
1289                                 BOOL fDisplayText )
1290 {
1291     INT defWidth;
1292     SIZE extent;
1293     int i, j;
1294     int start = x;
1295
1296     if (!lpstr || count == 0) return 0;
1297
1298     if (!lpTabPos)
1299         cTabStops=0;
1300
1301     if (cTabStops == 1)
1302     {
1303         defWidth = *lpTabPos;
1304         cTabStops = 0;
1305     }
1306     else
1307     {
1308         TEXTMETRICW tm;
1309         GetTextMetricsW( hdc, &tm );
1310         defWidth = 8 * tm.tmAveCharWidth;
1311     }
1312
1313     while (count > 0)
1314     {
1315         RECT r;
1316         INT x0;
1317         x0 = x;
1318         r.left = x0;
1319         /* chop the string into substrings of 0 or more <tabs> 
1320          * possibly followed by 1 or more normal characters */
1321         for (i = 0; i < count; i++)
1322             if (lpstr[i] != '\t') break;
1323         for (j = i; j < count; j++)
1324             if (lpstr[j] == '\t') break;
1325         /* get the extent of the normal character part */
1326         GetTextExtentPointW( hdc, lpstr + i, j - i , &extent );
1327         /* and if there is a <tab>, calculate its position */
1328         if( i) {
1329             /* get x coordinate for the drawing of this string */
1330             for (; cTabStops >= i; lpTabPos++, cTabStops--)
1331             {
1332                 if( nTabOrg + abs( *lpTabPos) > x) {
1333                     if( lpTabPos[ i - 1] >= 0) {
1334                         /* a left aligned tab */
1335                         x0 = nTabOrg + lpTabPos[i-1];
1336                         x = x0 + extent.cx;
1337                         break;
1338                     }
1339                     else
1340                     {
1341                         /* if tab pos is negative then text is right-aligned
1342                          * to tab stop meaning that the string extends to the
1343                          * left, so we must subtract the width of the string */
1344                         if (nTabOrg - lpTabPos[ i - 1] - extent.cx > x)
1345                         {
1346                             x = nTabOrg - lpTabPos[ i - 1];
1347                             x0 = x - extent.cx;
1348                             break;
1349                         }
1350                     }
1351                 }
1352             }
1353             /* if we have run out of tab stops and we have a valid default tab
1354              * stop width then round x up to that width */
1355             if ((cTabStops < i) && (defWidth > 0)) {
1356                 x0 = nTabOrg + ((x - nTabOrg) / defWidth + i) * defWidth;
1357                 x = x0 + extent.cx;
1358             } else if ((cTabStops < i) && (defWidth < 0)) {
1359                 x = nTabOrg + ((x - nTabOrg + extent.cx) / -defWidth + i)
1360                     * -defWidth;
1361                 x0 = x - extent.cx;
1362             }
1363         } else
1364             x += extent.cx;
1365         
1366         if (fDisplayText)
1367         {
1368             r.top    = y;
1369             r.right  = x;
1370             r.bottom = y + extent.cy;
1371             ExtTextOutW( hdc, x0, y, GetBkMode(hdc) == OPAQUE ? ETO_OPAQUE : 0,
1372                          &r, lpstr + i, j - i, NULL );
1373         }
1374         count -= j;
1375         lpstr += j;
1376     }
1377     return MAKELONG(x - start, extent.cy);
1378 }
1379
1380
1381 /***********************************************************************
1382  *           TabbedTextOutA    (USER32.@)
1383  *
1384  * See TabbedTextOutW.
1385  */
1386 LONG WINAPI TabbedTextOutA( HDC hdc, INT x, INT y, LPCSTR lpstr, INT count,
1387                             INT cTabStops, const INT *lpTabPos, INT nTabOrg )
1388 {
1389     LONG ret;
1390     DWORD len = MultiByteToWideChar( CP_ACP, 0, lpstr, count, NULL, 0 );
1391     LPWSTR strW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1392     if (!strW) return 0;
1393     MultiByteToWideChar( CP_ACP, 0, lpstr, count, strW, len );
1394     ret = TabbedTextOutW( hdc, x, y, strW, len, cTabStops, lpTabPos, nTabOrg );
1395     HeapFree( GetProcessHeap(), 0, strW );
1396     return ret;
1397 }
1398
1399
1400 /***********************************************************************
1401  *           TabbedTextOutW    (USER32.@)
1402  *
1403  * Draws tabbed text aligned using the specified tab stops.
1404  *
1405  * PARAMS
1406  *  hdc       [I] Handle to device context to draw to.
1407  *  x         [I] X co-ordinate to start drawing the text at in logical units.
1408  *  y         [I] Y co-ordinate to start drawing the text at in logical units.
1409  *  str       [I] Pointer to the characters to draw.
1410  *  count     [I] Number of WCHARs pointed to by str.
1411  *  cTabStops [I] Number of tab stops pointed to by lpTabPos.
1412  *  lpTabPos  [I] Tab stops in logical units. Should be sorted in ascending order.
1413  *  nTabOrg   [I] Starting position to expand tabs from in logical units.
1414  *
1415  * RETURNS
1416  *  The dimensions of the string drawn. The height is in the high-order word
1417  *  and the width is in the low-order word.
1418  *
1419  * NOTES
1420  *  The tabs stops can be negative, in which case the text is right aligned to
1421  *  that tab stop and, despite what MSDN says, this is supported on
1422  *  Windows XP SP2.
1423  *
1424  * BUGS
1425  *  MSDN says that the TA_UPDATECP from GetTextAlign causes this function to
1426  *  ignore the x and y co-ordinates, but this is unimplemented at the moment.
1427  */
1428 LONG WINAPI TabbedTextOutW( HDC hdc, INT x, INT y, LPCWSTR str, INT count,
1429                             INT cTabStops, const INT *lpTabPos, INT nTabOrg )
1430 {
1431     TRACE("%p %d,%d %s %d\n", hdc, x, y, debugstr_wn(str,count), count );
1432     return TEXT_TabbedTextOut( hdc, x, y, str, count, cTabStops, lpTabPos, nTabOrg, TRUE );
1433 }
1434
1435
1436 /***********************************************************************
1437  *           GetTabbedTextExtentA    (USER32.@)
1438  */
1439 DWORD WINAPI GetTabbedTextExtentA( HDC hdc, LPCSTR lpstr, INT count,
1440                                    INT cTabStops, const INT *lpTabPos )
1441 {
1442     LONG ret;
1443     DWORD len = MultiByteToWideChar( CP_ACP, 0, lpstr, count, NULL, 0 );
1444     LPWSTR strW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1445     if (!strW) return 0;
1446     MultiByteToWideChar( CP_ACP, 0, lpstr, count, strW, len );
1447     ret = GetTabbedTextExtentW( hdc, strW, len, cTabStops, lpTabPos );
1448     HeapFree( GetProcessHeap(), 0, strW );
1449     return ret;
1450 }
1451
1452
1453 /***********************************************************************
1454  *           GetTabbedTextExtentW    (USER32.@)
1455  */
1456 DWORD WINAPI GetTabbedTextExtentW( HDC hdc, LPCWSTR lpstr, INT count,
1457                                    INT cTabStops, const INT *lpTabPos )
1458 {
1459     TRACE("%p %s %d\n", hdc, debugstr_wn(lpstr,count), count );
1460     return TEXT_TabbedTextOut( hdc, 0, 0, lpstr, count, cTabStops, lpTabPos, 0, FALSE );
1461 }