update for HEAD-2003091401
[reactos.git] / lib / user32 / windows / font.c
1 /*
2  *  ReactOS kernel
3  *  Copyright (C) 1998, 1999, 2000, 2001 ReactOS Team
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program; if not, write to the Free Software
17  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 /* $Id$
20  *
21  * PROJECT:         ReactOS user32.dll
22  * FILE:            lib/user32/windows/input.c
23  * PURPOSE:         Input
24  * PROGRAMMER:      Casper S. Hornstrup (chorns@users.sourceforge.net)
25  * UPDATE HISTORY:
26  *      09-05-2001  CSH  Created
27  */
28
29 /* INCLUDES ******************************************************************/
30
31 #include <windows.h>
32 #include <string.h>
33 #include <user32.h>
34 #include <debug.h>
35
36 /* FUNCTIONS *****************************************************************/
37
38 /*
39  * @unimplemented
40  */
41 DWORD
42 STDCALL
43 GetTabbedTextExtentA(
44   HDC hDC,
45   LPCSTR lpString,
46   int nCount,
47   int nTabPositions,
48   CONST LPINT lpnTabStopPositions)
49 {
50   UNIMPLEMENTED;
51   return 0;
52 }
53
54
55 /*
56  * @unimplemented
57  */
58 DWORD
59 STDCALL
60 GetTabbedTextExtentW(
61   HDC hDC,
62   LPCWSTR lpString,
63   int nCount,
64   int nTabPositions,
65   CONST LPINT lpnTabStopPositions)
66 {
67   UNIMPLEMENTED;
68   return 0;
69 }
70
71 /*********************************************************************
72  *
73  *            DrawText functions
74  *
75  * Copied from Wine.
76  *   Copyright 1993, 1994 Alexandre Julliard
77  *   Copyright 2002 Bill Medland
78  *
79  * Design issues
80  *   How many buffers to use
81  *     While processing in DrawText there are potentially three different forms
82  *     of the text that need to be held.  How are they best held?
83  *     1. The original text is needed, of course, to see what to display.
84  *     2. The text that will be returned to the user if the DT_MODIFYSTRING is
85  *        in effect.
86  *     3. The buffered text that is about to be displayed e.g. the current line.
87  *        Typically this will exclude the ampersands used for prefixing etc.
88  *
89  *     Complications.
90  *     a. If the buffered text to be displayed includes the ampersands then
91  *        we will need special measurement and draw functions that will ignore
92  *        the ampersands (e.g. by copying to a buffer without the prefix and
93  *        then using the normal forms).  This may involve less space but may
94  *        require more processing.  e.g. since a line containing tabs may
95  *        contain several underlined characters either we need to carry around
96  *        a list of prefix locations or we may need to locate them several
97  *        times.
98  *     b. If we actually directly modify the "original text" as we go then we
99  *        will need some special "caching" to handle the fact that when we
100  *        ellipsify the text the ellipsis may modify the next line of text,
101  *        which we have not yet processed.  (e.g. ellipsification of a W at the
102  *        end of a line will overwrite the W, the \n and the first character of
103  *        the next line, and a \0 will overwrite the second.  Try it!!)
104  *
105  *     Option 1.  Three separate storages. (To be implemented)
106  *       If DT_MODIFYSTRING is in effect then allocate an extra buffer to hold
107  *       the edited string in some form, either as the string itself or as some
108  *       sort of "edit list" to be applied just before returning.
109  *       Use a buffer that holds the ellipsified current line sans ampersands
110  *       and accept the need occasionally to recalculate the prefixes (if
111  *       DT_EXPANDTABS and not DT_NOPREFIX and not DT_HIDEPREFIX)
112  */
113
114 #define TAB     9
115 #define LF     10
116 #define CR     13
117 #define SPACE  32
118 #define PREFIX 38
119
120 #define FORWARD_SLASH '/'
121 #define BACK_SLASH '\\'
122
123 static const WCHAR ELLIPSISW[] = {'.','.','.', 0};
124
125 typedef struct tag_ellipsis_data
126 {
127     int before;
128     int len;
129     int under;
130     int after;
131 } ellipsis_data;
132
133 /*********************************************************************
134  *                      TEXT_Ellipsify (static)
135  *
136  *  Add an ellipsis to the end of the given string whilst ensuring it fits.
137  *
138  * If the ellipsis alone doesn't fit then it will be returned anyway.
139  *
140  * See Also TEXT_PathEllipsify
141  *
142  * Arguments
143  *   hdc        [in] The handle to the DC that defines the font.
144  *   str        [in/out] The string that needs to be modified.
145  *   max_str    [in] The dimension of str (number of WCHAR).
146  *   len_str    [in/out] The number of characters in str
147  *   width      [in] The maximum width permitted (in logical coordinates)
148  *   size       [out] The dimensions of the text
149  *   modstr     [out] The modified form of the string, to be returned to the
150  *                    calling program.  It is assumed that the caller has
151  *                    made sufficient space available so we don't need to
152  *                    know the size of the space.  This pointer may be NULL if
153  *                    the modified string is not required.
154  *   len_before [out] The number of characters before the ellipsis.
155  *   len_ellip  [out] The number of characters in the ellipsis.
156  *
157  * See for example Microsoft article Q249678.
158  *
159  * For now we will simply use three dots rather than worrying about whether
160  * the font contains an explicit ellipsis character.
161  */
162 static void TEXT_Ellipsify (HDC hdc, WCHAR *str, unsigned int max_len,
163                             unsigned int *len_str, int width, SIZE *size,
164                             WCHAR *modstr,
165                             int *len_before, int *len_ellip)
166 {
167     unsigned int len_ellipsis;
168     unsigned int lo, mid, hi;
169
170     len_ellipsis = wcslen (ELLIPSISW);
171     if (len_ellipsis > max_len) len_ellipsis = max_len;
172     if (*len_str > max_len - len_ellipsis)
173         *len_str = max_len - len_ellipsis;
174
175     /* First do a quick binary search to get an upper bound for *len_str. */
176     if (*len_str > 0 &&
177         GetTextExtentExPointW(hdc, str, *len_str, width, NULL, NULL, size) &&
178         size->cx > width)
179     {
180         for (lo = 0, hi = *len_str; lo < hi; )
181         {
182             mid = (lo + hi) / 2;
183             if (!GetTextExtentExPointW(hdc, str, mid, width, NULL, NULL, size))
184                 break;
185             if (size->cx > width)
186                 hi = mid;
187             else
188                 lo = mid + 1;
189         }
190         *len_str = hi;
191     }
192     /* Now this should take only a couple iterations at most. */
193     for ( ; ; )
194     {
195         wcsncpy (str + *len_str, ELLIPSISW, len_ellipsis);
196
197         if (!GetTextExtentExPointW (hdc, str, *len_str + len_ellipsis, width,
198                                     NULL, NULL, size)) break;
199
200         if (!*len_str || size->cx <= width) break;
201
202         (*len_str)--;
203     }
204     *len_ellip = len_ellipsis;
205     *len_before = *len_str;
206     *len_str += len_ellipsis;
207
208     if (modstr)
209     {
210         wcsncpy (modstr, str, *len_str);
211         *(str+*len_str) = '\0';
212     }
213 }
214
215 /*********************************************************************
216  *                      TEXT_PathEllipsify (static)
217  *
218  * Add an ellipsis to the provided string in order to make it fit within
219  * the width.  The ellipsis is added as specified for the DT_PATH_ELLIPSIS
220  * flag.
221  *
222  * See Also TEXT_Ellipsify
223  *
224  * Arguments
225  *   hdc        [in] The handle to the DC that defines the font.
226  *   str        [in/out] The string that needs to be modified
227  *   max_str    [in] The dimension of str (number of WCHAR).
228  *   len_str    [in/out] The number of characters in str
229  *   width      [in] The maximum width permitted (in logical coordinates)
230  *   size       [out] The dimensions of the text
231  *   modstr     [out] The modified form of the string, to be returned to the
232  *                    calling program.  It is assumed that the caller has
233  *                    made sufficient space available so we don't need to
234  *                    know the size of the space.  This pointer may be NULL if
235  *                    the modified string is not required.
236  *   pellip     [out] The ellipsification results
237  *
238  * For now we will simply use three dots rather than worrying about whether
239  * the font contains an explicit ellipsis character.
240  *
241  * The following applies, I think to Win95.  We will need to extend it for
242  * Win98 which can have both path and end ellipsis at the same time (e.g.
243  *  C:\MyLongFileName.Txt becomes ...\MyLongFileN...)
244  *
245  * The resulting string consists of as much as possible of the following:
246  * 1. The ellipsis itself
247  * 2. The last \ or / of the string (if any)
248  * 3. Everything after the last \ or / of the string (if any) or the whole
249  *    string if there is no / or \.  I believe that under Win95 this would
250  *    include everything even though some might be clipped off the end whereas
251  *    under Win98 that might be ellipsified too.
252  *    Yet to be investigated is whether this would include wordbreaking if the
253  *    filename is more than 1 word and splitting if DT_EDITCONTROL was in
254  *    effect.  (If DT_EDITCONTROL is in effect then on occasions text will be
255  *    broken within words).
256  * 4. All the stuff before the / or \, which is placed before the ellipsis.
257  */
258 static void TEXT_PathEllipsify (HDC hdc, WCHAR *str, unsigned int max_len,
259                                 unsigned int *len_str, int width, SIZE *size,
260                                 WCHAR *modstr, ellipsis_data *pellip)
261 {
262     unsigned int len_ellipsis;
263     int len_trailing;
264     int len_under;
265     WCHAR *lastBkSlash, *lastFwdSlash, *lastSlash;
266
267     len_ellipsis = wcslen (ELLIPSISW);
268     if (!max_len) return;
269     if (len_ellipsis >= max_len) len_ellipsis = max_len - 1;
270     if (*len_str + len_ellipsis >= max_len)
271         *len_str = max_len - len_ellipsis-1;
272         /* Hopefully this will never happen, otherwise it would probably lose
273          * the wrong character
274          */
275     str[*len_str] = '\0'; /* to simplify things */
276
277     lastBkSlash  = wcsrchr (str, BACK_SLASH);
278     lastFwdSlash = wcsrchr (str, FORWARD_SLASH);
279     lastSlash = lastBkSlash > lastFwdSlash ? lastBkSlash : lastFwdSlash;
280     if (!lastSlash) lastSlash = str;
281     len_trailing = *len_str - (lastSlash - str);
282
283     /* overlap-safe movement to the right */
284     memmove (lastSlash+len_ellipsis, lastSlash, len_trailing * sizeof(WCHAR));
285     wcsncpy (lastSlash, ELLIPSISW, len_ellipsis);
286     len_trailing += len_ellipsis;
287     /* From this point on lastSlash actually points to the ellipsis in front
288      * of the last slash and len_trailing includes the ellipsis
289      */
290
291     len_under = 0;
292     for ( ; ; )
293     {
294         if (!GetTextExtentExPointW (hdc, str, *len_str + len_ellipsis, width,
295                                     NULL, NULL, size)) break;
296
297         if (lastSlash == str || size->cx <= width) break;
298
299         /* overlap-safe movement to the left */
300         memmove (lastSlash-1, lastSlash, len_trailing * sizeof(WCHAR));
301         lastSlash--;
302         len_under++;
303
304         assert (*len_str);
305         (*len_str)--;
306     }
307     pellip->before = lastSlash-str;
308     pellip->len = len_ellipsis;
309     pellip->under = len_under;
310     pellip->after = len_trailing - len_ellipsis;
311     *len_str += len_ellipsis;
312
313     if (modstr)
314     {
315         wcsncpy (modstr, str, *len_str);
316         *(str+*len_str) = '\0';
317     }
318 }
319
320 /*********************************************************************
321  *                      TEXT_WordBreak (static)
322  *
323  *  Perform wordbreak processing on the given string
324  *
325  * Assumes that DT_WORDBREAK has been specified and not all the characters
326  * fit.  Note that this function should even be called when the first character
327  * that doesn't fit is known to be a space or tab, so that it can swallow them.
328  *
329  * Note that the Windows processing has some strange properties.
330  * 1. If the text is left-justified and there is room for some of the spaces
331  *    that follow the last word on the line then those that fit are included on
332  *    the line.
333  * 2. If the text is centred or right-justified and there is room for some of
334  *    the spaces that follow the last word on the line then all but one of those
335  *    that fit are included on the line.
336  * 3. (Reasonable behaviour) If the word breaking causes a space to be the first
337  *    character of a new line it will be skipped.
338  *
339  * Arguments
340  *   hdc        [in] The handle to the DC that defines the font.
341  *   str        [in/out] The string that needs to be broken.
342  *   max_str    [in] The dimension of str (number of WCHAR).
343  *   len_str    [in/out] The number of characters in str
344  *   width      [in] The maximum width permitted
345  *   format     [in] The format flags in effect
346  *   chars_fit  [in] The maximum number of characters of str that are already
347  *              known to fit; chars_fit+1 is known not to fit.
348  *   chars_used [out] The number of characters of str that have been "used" and
349  *              do not need to be included in later text.  For example this will
350  *              include any spaces that have been discarded from the start of
351  *              the next line.
352  *   size       [out] The size of the returned text in logical coordinates
353  *
354  * Pedantic assumption - Assumes that the text length is monotonically
355  * increasing with number of characters (i.e. no weird kernings)
356  *
357  * Algorithm
358  *
359  * Work back from the last character that did fit to either a space or the last
360  * character of a word, whichever is met first.
361  * If there was one or the first character didn't fit then
362  *     If the text is centred or right justified and that one character was a
363  *     space then break the line before that character
364  *     Otherwise break the line after that character
365  *     and if the next character is a space then discard it.
366  * Suppose there was none (and the first character did fit).
367  *     If Break Within Word is permitted
368  *         break the word after the last character that fits (there must be
369  *         at least one; none is caught earlier).
370  *     Otherwise
371  *         discard any trailing space.
372  *         include the whole word; it may be ellipsified later
373  *
374  * Break Within Word is permitted under a set of circumstances that are not
375  * totally clear yet.  Currently our best guess is:
376  *     If DT_EDITCONTROL is in effect and neither DT_WORD_ELLIPSIS nor
377  *     DT_PATH_ELLIPSIS is
378  */
379
380 static void TEXT_WordBreak (HDC hdc, WCHAR *str, unsigned int max_str,
381                             unsigned int *len_str,
382                             int width, int format, unsigned int chars_fit,
383                             unsigned int *chars_used, SIZE *size)
384 {
385     WCHAR *p;
386     int word_fits;
387     assert (format & DT_WORDBREAK);
388     assert (chars_fit < *len_str);
389
390     /* Work back from the last character that did fit to either a space or the
391      * last character of a word, whichever is met first.
392      */
393     p = str + chars_fit; /* The character that doesn't fit */
394     word_fits = TRUE;
395     if (!chars_fit)
396         ; /* we pretend that it fits anyway */
397     else if (*p == SPACE) /* chars_fit < *len_str so this is valid */
398         p--; /* the word just fitted */
399     else
400     {
401         while (p > str && *(--p) != SPACE)
402             ;
403         word_fits = (p != str || *p == SPACE);
404     }
405     /* If there was one or the first character didn't fit then */
406     if (word_fits)
407     {
408         int next_is_space;
409         /* break the line before/after that character */
410         if (!(format & (DT_RIGHT | DT_CENTER)) || *p != SPACE)
411             p++;
412         next_is_space = (unsigned int) (p - str) < *len_str && *p == SPACE;
413         *len_str = p - str;
414         /* and if the next character is a space then discard it. */
415         *chars_used = *len_str;
416         if (next_is_space)
417             (*chars_used)++;
418     }
419     /* Suppose there was none. */
420     else
421     {
422         if ((format & (DT_EDITCONTROL | DT_WORD_ELLIPSIS | DT_PATH_ELLIPSIS)) ==
423             DT_EDITCONTROL)
424         {
425             /* break the word after the last character that fits (there must be
426              * at least one; none is caught earlier).
427              */
428             *len_str = chars_fit;
429             *chars_used = chars_fit;
430
431             /* FIXME - possible error.  Since the next character is now removed
432              * this could make the text longer so that it no longer fits, and
433              * so we need a loop to test and shrink.
434              */
435         }
436         /* Otherwise */
437         else
438         {
439             /* discard any trailing space. */
440             const WCHAR *e = str + *len_str;
441             p = str + chars_fit;
442             while (p < e && *p != SPACE)
443                 p++;
444             *chars_used = p - str;
445             if (p < e) /* i.e. loop failed because *p == SPACE */
446                 (*chars_used)++;
447
448             /* include the whole word; it may be ellipsified later */
449             *len_str = p - str;
450             /* Possible optimisation; if DT_WORD_ELLIPSIS only use chars_fit+1
451              * so that it will be too long
452              */
453         }
454     }
455     /* Remeasure the string */
456     GetTextExtentExPointW (hdc, str, *len_str, 0, NULL, NULL, size);
457 }
458
459 /*********************************************************************
460  *                      TEXT_SkipChars
461  *
462  *  Skip over the given number of characters, bearing in mind prefix
463  *  substitution and the fact that a character may take more than one
464  *  WCHAR (Unicode surrogates are two words long) (and there may have been
465  *  a trailing &)
466  *
467  * Parameters
468  *   new_count  [out] The updated count
469  *   new_str    [out] The updated pointer
470  *   start_count [in] The count of remaining characters corresponding to the
471  *                    start of the string
472  *   start_str  [in] The starting point of the string
473  *   max        [in] The number of characters actually in this segment of the
474  *                   string (the & counts)
475  *   n          [in] The number of characters to skip (if prefix then
476  *                   &c counts as one)
477  *   prefix     [in] Apply prefix substitution
478  *
479  * Return Values
480  *   none
481  *
482  * Remarks
483  *   There must be at least n characters in the string
484  *   We need max because the "line" may have ended with a & followed by a tab
485  *   or newline etc. which we don't want to swallow
486  */
487
488 static void TEXT_SkipChars (int *new_count, const WCHAR **new_str,
489                             int start_count, const WCHAR *start_str,
490                             int max, int n, int prefix)
491 {
492     /* This is specific to wide characters, MSDN doesn't say anything much
493      * about Unicode surrogates yet and it isn't clear if _wcsinc will
494      * correctly handle them so we'll just do this the easy way for now
495      */
496
497     if (prefix)
498     {
499         const WCHAR *str_on_entry = start_str;
500         assert (max >= n);
501         max -= n;
502         while (n--)
503             if (*start_str++ == PREFIX && max--)
504                 start_str++;
505             else;
506         start_count -= (start_str - str_on_entry);
507     }
508     else
509     {
510         start_str += n;
511         start_count -= n;
512     }
513     *new_str = start_str;
514     *new_count = start_count;
515 }
516
517 /*********************************************************************
518  *                      TEXT_Reprefix
519  *
520  *  Reanalyse the text to find the prefixed character.  This is called when
521  *  wordbreaking or ellipsification has shortened the string such that the
522  *  previously noted prefixed character is no longer visible.
523  *
524  * Parameters
525  *   str        [in] The original string segment (including all characters)
526  *   ns         [in] The number of characters in str (including prefixes)
527  *   pe         [in] The ellipsification data
528  *
529  * Return Values
530  *   The prefix offset within the new string segment (the one that contains the
531  *   ellipses and does not contain the prefix characters) (-1 if none)
532  */
533
534 static int TEXT_Reprefix (const WCHAR *str, unsigned int ns,
535                           const ellipsis_data *pe)
536 {
537     int result = -1;
538     unsigned int i = 0;
539     unsigned int n = pe->before + pe->under + pe->after;
540     assert (n <= ns);
541     while (i < n)
542     {
543         if (i == (unsigned int) pe->before)
544         {
545             /* Reached the path ellipsis; jump over it */
546             if (ns < (unsigned int) pe->under) break;
547             str += pe->under;
548             ns -= pe->under;
549             i += pe->under;
550             if (!pe->after) break; /* Nothing after the path ellipsis */
551         }
552         if (!ns) break;
553         ns--;
554         if (*str++ == PREFIX)
555         {
556             if (!ns) break;
557             if (*str != PREFIX)
558                 result = (i < (unsigned int) pe->before || pe->under == 0) ? i : i - pe->under + pe->len;
559                 /* pe->len may be non-zero while pe_under is zero */
560             str++;
561             ns--;
562         }
563         else;
564         i++;
565     }
566     return result;
567 }
568
569 /*********************************************************************
570  *  Returns true if and only if the remainder of the line is a single
571  *  newline representation or nothing
572  */
573
574 static int remainder_is_none_or_newline (int num_chars, const WCHAR *str)
575 {
576     if (!num_chars) return TRUE;
577     if (*str != LF && *str != CR) return FALSE;
578     if (!--num_chars) return TRUE;
579     if (*str == *(str+1)) return FALSE;
580     str++;
581     if (*str != CR && *str != LF) return FALSE;
582     if (--num_chars) return FALSE;
583     return TRUE;
584 }
585
586 /*********************************************************************
587  *  Return next line of text from a string.
588  *
589  * hdc - handle to DC.
590  * str - string to parse into lines.
591  * count - length of str.
592  * dest - destination in which to return line.
593  * len - dest buffer size in chars on input, copied length into dest on output.
594  * width - maximum width of line in pixels.
595  * format - format type passed to DrawText.
596  * retsize - returned size of the line in pixels.
597  * last_line - TRUE if is the last line that will be processed
598  * p_retstr - If DT_MODIFYSTRING this points to a cursor in the buffer in which
599  *            the return string is built.
600  * tabwidth - The width of a tab in logical coordinates
601  * pprefix_offset - Here is where we return the offset within dest of the first
602  *                  prefixed (underlined) character.  -1 is returned if there
603  *                  are none.  Note that there may be more; the calling code
604  *                  will need to use TEXT_Reprefix to find any later ones.
605  * pellip - Here is where we return the information about any ellipsification
606  *          that was carried out.  Note that if tabs are being expanded then
607  *          this data will correspond to the last text segment actually
608  *          returned in dest; by definition there would not have been any
609  *          ellipsification in earlier text segments of the line.
610  *
611  * Returns pointer to next char in str after end of the line
612  * or NULL if end of str reached.
613  */
614 static const WCHAR *TEXT_NextLineW( HDC hdc, const WCHAR *str, int *count,
615                                  WCHAR *dest, int *len, int width, DWORD format,
616                                  SIZE *retsize, int last_line, WCHAR **p_retstr,
617                                  int tabwidth, int *pprefix_offset,
618                                  ellipsis_data *pellip)
619 {
620     int i = 0, j = 0;
621     int plen = 0;
622     SIZE size;
623     int maxl = *len;
624     int seg_i, seg_count, seg_j;
625     int max_seg_width;
626     int num_fit;
627     int word_broken;
628     int line_fits;
629     int j_in_seg;
630     int ellipsified;
631     *pprefix_offset = -1;
632
633     /* For each text segment in the line */
634
635     retsize->cy = 0;
636     while (*count)
637     {
638
639         /* Skip any leading tabs */
640
641         if (str[i] == TAB && (format & DT_EXPANDTABS))
642         {
643             plen = ((plen/tabwidth)+1)*tabwidth;
644             (*count)--; if (j < maxl) dest[j++] = str[i++]; else i++;
645             while (*count && str[i] == TAB)
646             {
647                 plen += tabwidth;
648                 (*count)--; if (j < maxl) dest[j++] = str[i++]; else i++;
649             }
650         }
651
652
653         /* Now copy as far as the next tab or cr/lf or eos */
654
655         seg_i = i;
656         seg_count = *count;
657         seg_j = j;
658
659         while (*count &&
660                (str[i] != TAB || !(format & DT_EXPANDTABS)) &&
661                ((str[i] != CR && str[i] != LF) || (format & DT_SINGLELINE)))
662         {
663             if (str[i] == PREFIX && !(format & DT_NOPREFIX) && *count > 1)
664             {
665                 (*count)--, i++; /* Throw away the prefix itself */
666                 if (str[i] == PREFIX)
667                 {
668                     /* Swallow it before we see it again */
669                     (*count)--; if (j < maxl) dest[j++] = str[i++]; else i++;
670                 }
671                 else if (*pprefix_offset == -1 || *pprefix_offset >= seg_j)
672                 {
673                     *pprefix_offset = j;
674                 }
675                 /* else the previous prefix was in an earlier segment of the
676                  * line; we will leave it to the drawing code to catch this
677                  * one.
678                  */
679             }
680             else
681             {
682                 (*count)--; if (j < maxl) dest[j++] = str[i++]; else i++;
683             }
684         }
685
686
687         /* Measure the whole text segment and possibly WordBreak and
688          * ellipsify it
689          */
690
691         j_in_seg = j - seg_j;
692         max_seg_width = width - plen;
693         GetTextExtentExPointW (hdc, dest + seg_j, j_in_seg, max_seg_width, &num_fit, NULL, &size);
694
695         /* The Microsoft handling of various combinations of formats is weird.
696          * The following may very easily be incorrect if several formats are
697          * combined, and may differ between versions (to say nothing of the
698          * several bugs in the Microsoft versions).
699          */
700         word_broken = 0;
701         line_fits = (num_fit >= j_in_seg);
702         if (!line_fits && (format & DT_WORDBREAK))
703         {
704             const WCHAR *s;
705             int chars_used;
706             TEXT_WordBreak (hdc, dest+seg_j, maxl-seg_j, &j_in_seg,
707                             max_seg_width, format, num_fit, &chars_used, &size);
708             line_fits = (size.cx <= max_seg_width);
709             /* and correct the counts */
710             TEXT_SkipChars (count, &s, seg_count, str+seg_i, i-seg_i,
711                             chars_used, !(format & DT_NOPREFIX));
712             i = s - str;
713             word_broken = 1;
714         }
715         pellip->before = j_in_seg;
716         pellip->under = 0;
717         pellip->after = 0;
718         pellip->len = 0;
719         ellipsified = 0;
720         if (!line_fits && (format & DT_PATH_ELLIPSIS))
721         {
722             TEXT_PathEllipsify (hdc, dest + seg_j, maxl-seg_j, &j_in_seg,
723                                 max_seg_width, &size, *p_retstr, pellip);
724             line_fits = (size.cx <= max_seg_width);
725             ellipsified = 1;
726         }
727         /* NB we may end up ellipsifying a word-broken or path_ellipsified
728          * string */
729         if ((!line_fits && (format & DT_WORD_ELLIPSIS)) ||
730             ((format & DT_END_ELLIPSIS) &&
731               ((last_line && *count) ||
732                (remainder_is_none_or_newline (*count, &str[i]) && !line_fits))))
733         {
734             int before, len_ellipsis;
735             TEXT_Ellipsify (hdc, dest + seg_j, maxl-seg_j, &j_in_seg,
736                             max_seg_width, &size, *p_retstr, &before, &len_ellipsis);
737             if (before > pellip->before)
738             {
739                 /* We must have done a path ellipsis too */
740                 pellip->after = before - pellip->before - pellip->len;
741                 /* Leave the len as the length of the first ellipsis */
742             }
743             else
744             {
745                 /* If we are here after a path ellipsification it must be
746                  * because even the ellipsis itself didn't fit.
747                  */
748                 assert (pellip->under == 0 && pellip->after == 0);
749                 pellip->before = before;
750                 pellip->len = len_ellipsis;
751                 /* pellip->after remains as zero as does
752                  * pellip->under
753                  */
754             }
755             line_fits = (size.cx <= max_seg_width);
756             ellipsified = 1;
757         }
758         /* As an optimisation if we have ellipsified and we are expanding
759          * tabs and we haven't reached the end of the line we can skip to it
760          * now rather than going around the loop again.
761          */
762         if ((format & DT_EXPANDTABS) && ellipsified)
763         {
764             if (format & DT_SINGLELINE)
765                 *count = 0;
766             else
767             {
768                 while ((*count) && str[i] != CR && str[i] != LF)
769                 {
770                     (*count)--, i++;
771                 }
772             }
773         }
774
775         j = seg_j + j_in_seg;
776         if (*pprefix_offset >= seg_j + pellip->before)
777         {
778             *pprefix_offset = TEXT_Reprefix (str + seg_i, i - seg_i, pellip);
779             if (*pprefix_offset != -1)
780                 *pprefix_offset += seg_j;
781         }
782
783         plen += size.cx;
784         if (size.cy > retsize->cy)
785             retsize->cy = size.cy;
786
787         if (word_broken)
788             break;
789         else if (!*count)
790             break;
791         else if (str[i] == CR || str[i] == LF)
792         {
793             (*count)--, i++;
794             if (*count && (str[i] == CR || str[i] == LF) && str[i] != str[i-1])
795             {
796                 (*count)--, i++;
797             }
798             break;
799         }
800         /* else it was a Tab and we go around again */
801     }
802
803     retsize->cx = plen;
804     *len = j;
805     if (*count)
806         return (&str[i]);
807     else
808         return NULL;
809 }
810
811
812 /***********************************************************************
813  *                      TEXT_DrawUnderscore
814  *
815  *  Draw the underline under the prefixed character
816  *
817  * Parameters
818  *   hdc        [in] The handle of the DC for drawing
819  *   x          [in] The x location of the line segment (logical coordinates)
820  *   y          [in] The y location of where the underscore should appear
821  *                   (logical coordinates)
822  *   str        [in] The text of the line segment
823  *   offset     [in] The offset of the underscored character within str
824  */
825
826 static void TEXT_DrawUnderscore (HDC hdc, int x, int y, const WCHAR *str, int offset)
827 {
828     int prefix_x;
829     int prefix_end;
830     SIZE size;
831     HPEN hpen;
832     HPEN oldPen;
833
834     GetTextExtentPointW (hdc, str, offset, &size);
835     prefix_x = x + size.cx;
836     GetTextExtentPointW (hdc, str, offset+1, &size);
837     prefix_end = x + size.cx - 1;
838     /* The above method may eventually be slightly wrong due to kerning etc. */
839
840     hpen = CreatePen (PS_SOLID, 1, GetTextColor (hdc));
841     oldPen = SelectObject (hdc, hpen);
842     MoveToEx (hdc, prefix_x, y, NULL);
843     LineTo (hdc, prefix_end, y);
844     SelectObject (hdc, oldPen);
845     DeleteObject (hpen);
846 }
847
848 /***********************************************************************
849  *           DrawTextExW    (USER32.@)
850  *
851  * The documentation on the extra space required for DT_MODIFYSTRING at MSDN
852  * is not quite complete, especially with regard to \0.  We will assume that
853  * the returned string could have a length of up to i_count+3 and also have
854  * a trailing \0 (which would be 4 more than a not-null-terminated string but
855  * 3 more than a null-terminated string).  If this is not so then increase
856  * the allowance in DrawTextExA.
857  */
858 #define MAX_STATIC_BUFFER 1024
859 /*
860  * @implemented
861  */
862 int STDCALL
863 DrawTextExW( HDC hdc, LPWSTR str, INT i_count,
864              LPRECT rect, UINT flags, LPDRAWTEXTPARAMS dtp )
865 {
866     SIZE size;
867     const WCHAR *strPtr;
868     WCHAR *retstr, *p_retstr;
869     size_t size_retstr;
870     static WCHAR line[MAX_STATIC_BUFFER];
871     int len, lh, count=i_count;
872     TEXTMETRICW tm;
873     int lmargin = 0, rmargin = 0;
874     int x = rect->left, y = rect->top;
875     int width = rect->right - rect->left;
876     int max_width = 0;
877     int last_line;
878     int tabwidth /* to keep gcc happy */ = 0;
879     int prefix_offset;
880     ellipsis_data ellip;
881
882 #if 0
883     TRACE("%s, %d , [(%d,%d),(%d,%d)]\n", debugstr_wn (str, count), count,
884           rect->left, rect->top, rect->right, rect->bottom);
885
886    if (dtp) TRACE("Params: iTabLength=%d, iLeftMargin=%d, iRightMargin=%d\n",
887           dtp->iTabLength, dtp->iLeftMargin, dtp->iRightMargin);
888 #endif
889
890     if (!str) return 0;
891     if (count == -1) count = wcslen(str);
892     if (count == 0) return 0;
893     strPtr = str;
894
895     if (flags & DT_SINGLELINE)
896         flags &= ~DT_WORDBREAK;
897
898     GetTextMetricsW(hdc, &tm);
899     if (flags & DT_EXTERNALLEADING)
900         lh = tm.tmHeight + tm.tmExternalLeading;
901     else
902         lh = tm.tmHeight;
903
904     if (dtp)
905     {
906         lmargin = dtp->iLeftMargin * tm.tmAveCharWidth;
907         rmargin = dtp->iRightMargin * tm.tmAveCharWidth;
908         if (!(flags & (DT_CENTER | DT_RIGHT)))
909             x += lmargin;
910         dtp->uiLengthDrawn = 0;     /* This param RECEIVES number of chars processed */
911     }
912
913     if (flags & DT_EXPANDTABS)
914     {
915         int tabstop = ((flags & DT_TABSTOP) && dtp) ? dtp->iTabLength : 8;
916         tabwidth = tm.tmAveCharWidth * tabstop;
917     }
918
919     if (flags & DT_CALCRECT) flags |= DT_NOCLIP;
920
921     if (flags & DT_MODIFYSTRING)
922     {
923         size_retstr = (count + 4) * sizeof (WCHAR);
924         retstr = HeapAlloc(GetProcessHeap(), 0, size_retstr);
925         if (!retstr) return 0;
926         memcpy (retstr, str, size_retstr);
927     }
928     else
929     {
930         size_retstr = 0;
931         retstr = NULL;
932     }
933     p_retstr = retstr;
934
935     do
936     {
937         len = MAX_STATIC_BUFFER;
938         last_line = !(flags & DT_NOCLIP) && y + ((flags & DT_EDITCONTROL) ? 2*lh-1 : lh) > rect->bottom;
939         strPtr = TEXT_NextLineW(hdc, strPtr, &count, line, &len, width, flags, &size, last_line, &p_retstr, tabwidth, &prefix_offset, &ellip);
940
941         if (flags & DT_CENTER) x = (rect->left + rect->right -
942                                     size.cx) / 2;
943         else if (flags & DT_RIGHT) x = rect->right - size.cx;
944
945         if (flags & DT_SINGLELINE)
946         {
947             if (flags & DT_VCENTER) y = rect->top +
948                 (rect->bottom - rect->top) / 2 - size.cy / 2;
949             else if (flags & DT_BOTTOM) y = rect->bottom - size.cy;
950         }
951
952         if (!(flags & DT_CALCRECT))
953         {
954             const WCHAR *str = line;
955             int xseg = x;
956             while (len)
957             {
958                 int len_seg;
959                 SIZE size;
960                 if ((flags & DT_EXPANDTABS))
961                 {
962                     const WCHAR *p;
963                     p = str; while (p < str+len && *p != TAB) p++;
964                     len_seg = p - str;
965                     if (len_seg != len && !GetTextExtentPointW(hdc, str, len_seg, &size))
966                         return 0;
967                 }
968                 else
969                     len_seg = len;
970
971                 if (!ExtTextOutW( hdc, xseg, y,
972                                  ((flags & DT_NOCLIP) ? 0 : ETO_CLIPPED) |
973                                  ((flags & DT_RTLREADING) ? ETO_RTLREADING : 0),
974                                  rect, str, len_seg, NULL ))  return 0;
975                 if (prefix_offset != -1 && prefix_offset < len_seg)
976                 {
977                     TEXT_DrawUnderscore (hdc, xseg, y + tm.tmAscent + 1, str, prefix_offset);
978                 }
979                 len -= len_seg;
980                 str += len_seg;
981                 if (len)
982                 {
983                     assert ((flags & DT_EXPANDTABS) && *str == TAB);
984                     len--; str++;
985                     xseg += ((size.cx/tabwidth)+1)*tabwidth;
986                     if (prefix_offset != -1)
987                     {
988                         if (prefix_offset < len_seg)
989                         {
990                             /* We have just drawn an underscore; we ought to
991                              * figure out where the next one is.  I am going
992                              * to leave it for now until I have a better model
993                              * for the line, which will make reprefixing easier.
994                              * This is where ellip would be used.
995                              */
996                             prefix_offset = -1;
997                         }
998                         else
999                             prefix_offset -= len_seg;
1000                     }
1001                 }
1002             }
1003         }
1004         else if (size.cx > max_width)
1005             max_width = size.cx;
1006
1007         y += lh;
1008         if (dtp)
1009             dtp->uiLengthDrawn += len;
1010     }
1011     while (strPtr && !last_line);
1012
1013     if (flags & DT_CALCRECT)
1014     {
1015         rect->right = rect->left + max_width;
1016         rect->bottom = y;
1017         if (dtp)
1018             rect->right += lmargin + rmargin;
1019     }
1020     if (retstr)
1021     {
1022         memcpy (str, retstr, size_retstr);
1023         HeapFree (GetProcessHeap(), 0, retstr);
1024     }
1025     return y - rect->top;
1026 }
1027
1028 /***********************************************************************
1029  *           DrawTextExA    (USER32.@)
1030  *
1031  * If DT_MODIFYSTRING is specified then there must be room for up to
1032  * 4 extra characters.  We take great care about just how much modified
1033  * string we return.
1034  *
1035  * @unimplemented
1036  */
1037 int STDCALL
1038 DrawTextExA( HDC hdc, LPSTR str, INT count,
1039              LPRECT rect, UINT flags, LPDRAWTEXTPARAMS dtp )
1040 {
1041    WCHAR *wstr;
1042    WCHAR *p;
1043    INT ret = 0;
1044    int i;
1045    DWORD wcount;
1046    DWORD wmax;
1047    DWORD amax;
1048
1049    if (!str) return 0;
1050    if (count == -1) count = strlen(str);
1051    if (!count) return 0;
1052    wcount = MultiByteToWideChar( CP_ACP, 0, str, count, NULL, 0 );
1053    wmax = wcount;
1054    amax = count;
1055    if (flags & DT_MODIFYSTRING)
1056    {
1057         wmax += 4;
1058         amax += 4;
1059    }
1060    wstr = HeapAlloc(GetProcessHeap(), 0, wmax * sizeof(WCHAR));
1061    if (wstr)
1062    {
1063        MultiByteToWideChar( CP_ACP, 0, str, count, wstr, wcount );
1064        if (flags & DT_MODIFYSTRING)
1065            for (i=4, p=wstr+wcount; i--; p++) *p=0xFFFE;
1066            /* Initialise the extra characters so that we can see which ones
1067             * change.  U+FFFE is guaranteed to be not a unicode character and
1068             * so will not be generated by DrawTextEx itself.
1069             */
1070        ret = DrawTextExW( hdc, wstr, wcount, rect, flags, NULL );
1071        if (flags & DT_MODIFYSTRING)
1072        {
1073             /* Unfortunately the returned string may contain multiple \0s
1074              * and so we need to measure it ourselves.
1075              */
1076             for (i=4, p=wstr+wcount; i-- && *p != 0xFFFE; p++) wcount++;
1077             WideCharToMultiByte( CP_ACP, 0, wstr, wcount, str, amax, NULL, NULL );
1078        }
1079        HeapFree(GetProcessHeap(), 0, wstr);
1080    }
1081    return ret;
1082 }
1083
1084 /***********************************************************************
1085  *           DrawTextW    (USER32.@)
1086  *
1087  * @implemented
1088  */
1089 int STDCALL
1090 DrawTextW( HDC hdc, LPCWSTR str, INT count, LPRECT rect, UINT flags )
1091 {
1092     DRAWTEXTPARAMS dtp;
1093
1094     memset (&dtp, 0, sizeof(dtp));
1095     if (flags & DT_TABSTOP)
1096     {
1097         dtp.iTabLength = (flags >> 8) && 0xff;
1098         flags &= 0xffff00ff;
1099     }
1100     return DrawTextExW(hdc, (LPWSTR)str, count, rect, flags, &dtp);
1101 }
1102
1103 /***********************************************************************
1104  *           DrawTextA    (USER32.@)
1105  *
1106  * @implemented
1107  */
1108 int STDCALL
1109 DrawTextA( HDC hdc, LPCSTR str, INT count, LPRECT rect, UINT flags )
1110 {
1111     DRAWTEXTPARAMS dtp;
1112
1113     memset (&dtp, 0, sizeof(dtp));
1114     if (flags & DT_TABSTOP)
1115     {
1116         dtp.iTabLength = (flags >> 8) && 0xff;
1117         flags &= 0xffff00ff;
1118     }
1119     return DrawTextExA( hdc, (LPSTR)str, count, rect, flags, &dtp );
1120 }