kernel32: Implement CompareStringOrdinal.
[wine] / dlls / kernel32 / editline.c
1 /*
2  * line edition function for Win32 console
3  *
4  * Copyright 2001 Eric Pouech
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <stdarg.h>
25 #include <string.h>
26
27 #include "windef.h"
28 #include "winbase.h"
29 #include "wincon.h"
30 #include "wine/unicode.h"
31 #include "winnls.h"
32 #include "wine/debug.h"
33 #include "console_private.h"
34
35 WINE_DEFAULT_DEBUG_CHANNEL(console);
36
37 struct WCEL_Context;
38
39 typedef struct
40 {
41     WCHAR                       val;            /* vk or unicode char */
42     void                        (*func)(struct WCEL_Context* ctx);
43 } KeyEntry;
44
45 typedef struct
46 {
47     DWORD                       keyState;       /* keyState (from INPUT_RECORD) to match */
48     BOOL                        chkChar;        /* check vk or char */
49     const KeyEntry*             entries;        /* array of entries */
50 } KeyMap;
51
52 typedef struct WCEL_Context {
53     WCHAR*                      line;           /* the line being edited */
54     size_t                      alloc;          /* number of WCHAR in line */
55     unsigned                    len;            /* number of chars in line */
56     unsigned                    last_rub;       /* number of chars to rub to get to start
57                                                    (for consoles that can't change cursor pos) */
58     unsigned                    last_max;       /* max number of chars written
59                                                    (for consoles that can't change cursor pos) */
60     unsigned                    ofs;            /* offset for cursor in current line */
61     WCHAR*                      yanked;         /* yanked line */
62     unsigned                    mark;           /* marked point (emacs mode only) */
63     CONSOLE_SCREEN_BUFFER_INFO  csbi;           /* current state (initial cursor, window size, attribute) */
64     HANDLE                      hConIn;
65     HANDLE                      hConOut;
66     unsigned                    done : 1,       /* to 1 when we're done with editing */
67                                 error : 1,      /* to 1 when an error occurred in the editing */
68                                 can_wrap : 1,   /* to 1 when multi-line edition can take place */
69                                 shall_echo : 1, /* to 1 when characters should be echo:ed when keyed-in */
70                                 insert : 1,     /* to 1 when new characters are inserted (otherwise overwrite) */
71                                 can_pos_cursor : 1; /* to 1 when console can (re)position cursor */
72     unsigned                    histSize;
73     unsigned                    histPos;
74     WCHAR*                      histCurr;
75 } WCEL_Context;
76
77 #if 0
78 static void WCEL_Dump(WCEL_Context* ctx, const char* pfx)
79 {
80     MESSAGE("%s: [line=%s[alloc=%u] ofs=%u len=%u start=(%d,%d) mask=%c%c%c]\n"
81             "\t\thist=(size=%u pos=%u curr=%s)\n"
82             "\t\tyanked=%s\n",
83             pfx, debugstr_w(ctx->line), ctx->alloc, ctx->ofs, ctx->len,
84             ctx->csbi.dwCursorPosition.X, ctx->csbi.dwCursorPosition.Y,
85             ctx->done ? 'D' : 'd', ctx->error ? 'E' : 'e', ctx->can_wrap ? 'W' : 'w',
86             ctx->histSize, ctx->histPos, debugstr_w(ctx->histCurr),
87             debugstr_w(ctx->yanked));
88 }
89 #endif
90
91 /* ====================================================================
92  *
93  * Console helper functions
94  *
95  * ====================================================================*/
96
97 static BOOL WCEL_Get(WCEL_Context* ctx, INPUT_RECORD* ir)
98 {
99     if (ReadConsoleInputW(ctx->hConIn, ir, 1, NULL)) return TRUE;
100     ctx->error = 1;
101     return FALSE;
102 }
103
104 static inline void WCEL_Beep(WCEL_Context* ctx)
105 {
106     Beep(400, 300);
107 }
108
109 static inline BOOL WCEL_IsSingleLine(WCEL_Context* ctx, size_t len)
110 {
111     return ctx->csbi.dwCursorPosition.X + ctx->len + len <= ctx->csbi.dwSize.X;
112 }
113
114 static inline int WCEL_CharWidth(WCHAR wch)
115 {
116     return wch < ' ' ? 2 : 1;
117 }
118
119 static inline int WCEL_StringWidth(const WCHAR* str, int beg, int len)
120 {
121     int         i, ofs;
122
123     for (i = 0, ofs = 0; i < len; i++)
124         ofs += WCEL_CharWidth(str[beg + i]);
125     return ofs;
126 }
127
128 static inline COORD WCEL_GetCoord(WCEL_Context* ctx, int strofs)
129 {
130     COORD       c;
131     int         len = ctx->csbi.dwSize.X - ctx->csbi.dwCursorPosition.X;
132     int         ofs;
133
134     ofs = WCEL_StringWidth(ctx->line, 0, strofs);
135
136     c.Y = ctx->csbi.dwCursorPosition.Y;
137     if (ofs >= len)
138     {
139         ofs -= len;
140         c.X = ofs % ctx->csbi.dwSize.X;
141         c.Y += 1 + ofs / ctx->csbi.dwSize.X;
142     }
143     else c.X = ctx->csbi.dwCursorPosition.X + ofs;
144     return c;
145 }
146
147 static DWORD WCEL_WriteConsole(WCEL_Context* ctx, DWORD beg, DWORD len)
148 {
149     DWORD i, last, dw, ret = 0;
150     WCHAR tmp[2];
151
152     for (i = last = 0; i < len; i++)
153     {
154         if (ctx->line[beg + i] < ' ')
155         {
156             if (last != i)
157             {
158                 WriteConsoleW(ctx->hConOut, &ctx->line[beg + last], i - last, &dw, NULL);
159                 ret += dw;
160             }
161             tmp[0] = '^';
162             tmp[1] = '@' + ctx->line[beg + i];
163             WriteConsoleW(ctx->hConOut, tmp, 2, &dw, NULL);
164             last = i + 1;
165             ret += dw;
166         }
167     }
168     if (last != len)
169     {
170         WriteConsoleW(ctx->hConOut, &ctx->line[beg + last], len - last, &dw, NULL);
171         ret += dw;
172     }
173     return ret;
174 }
175
176 static inline void WCEL_WriteNChars(WCEL_Context* ctx, char ch, int count)
177 {
178     DWORD       dw;
179
180     if (count > 0)
181     {
182         while (count--) WriteFile(ctx->hConOut, &ch, 1, &dw, NULL);
183     }
184 }
185
186 static inline void WCEL_Update(WCEL_Context* ctx, int beg, int len)
187 {
188     int         i, last;
189     DWORD       count;
190     WCHAR       tmp[2];
191
192     /* bare console case is handled in CONSOLE_ReadLine (we always reprint the whole string) */
193     if (!ctx->shall_echo || !ctx->can_pos_cursor) return;
194
195     for (i = last = beg; i < beg + len; i++)
196     {
197         if (ctx->line[i] < ' ')
198         {
199             if (last != i)
200             {
201                 WriteConsoleOutputCharacterW(ctx->hConOut, &ctx->line[last], i - last,
202                                              WCEL_GetCoord(ctx, last), &count);
203                 FillConsoleOutputAttribute(ctx->hConOut, ctx->csbi.wAttributes, i - last,
204                                            WCEL_GetCoord(ctx, last), &count);
205             }
206             tmp[0] = '^';
207             tmp[1] = '@' + ctx->line[i];
208             WriteConsoleOutputCharacterW(ctx->hConOut, tmp, 2,
209                                          WCEL_GetCoord(ctx, i), &count);
210             FillConsoleOutputAttribute(ctx->hConOut, ctx->csbi.wAttributes, 2,
211                                        WCEL_GetCoord(ctx, i), &count);
212             last = i + 1;
213         }
214     }
215     if (last != beg + len)
216     {
217         WriteConsoleOutputCharacterW(ctx->hConOut, &ctx->line[last], i - last,
218                                      WCEL_GetCoord(ctx, last), &count);
219         FillConsoleOutputAttribute(ctx->hConOut, ctx->csbi.wAttributes, i - last,
220                                    WCEL_GetCoord(ctx, last), &count);
221     }
222 }
223
224 /* ====================================================================
225  *
226  * context manipulation functions
227  *
228  * ====================================================================*/
229
230 static BOOL WCEL_Grow(WCEL_Context* ctx, size_t len)
231 {
232     if (!WCEL_IsSingleLine(ctx, len) && !ctx->can_wrap)
233     {
234         FIXME("Mode doesn't allow to wrap. However, we should allow to overwrite current string\n");
235         return FALSE;
236     }
237
238     if (ctx->len + len >= ctx->alloc)
239     {
240         WCHAR*  newline;
241         size_t  newsize;
242
243         /* round up size to 32 byte-WCHAR boundary */
244         newsize = (ctx->len + len + 1 + 31) & ~31;
245
246         if (ctx->line)
247             newline = HeapReAlloc(GetProcessHeap(), 0, ctx->line, sizeof(WCHAR) * newsize);
248         else
249             newline = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * newsize);
250
251         if (!newline) return FALSE;
252         ctx->line = newline;
253         ctx->alloc = newsize;
254     }
255     return TRUE;
256 }
257
258 static void WCEL_DeleteString(WCEL_Context* ctx, int beg, int end)
259 {
260     unsigned    str_len = end - beg;
261
262     if (end < ctx->len)
263         memmove(&ctx->line[beg], &ctx->line[end], (ctx->len - end) * sizeof(WCHAR));
264     /* we need to clean from ctx->len - str_len to ctx->len */
265
266     if (ctx->shall_echo)
267     {
268         COORD       cbeg = WCEL_GetCoord(ctx, ctx->len - str_len);
269         COORD       cend = WCEL_GetCoord(ctx, ctx->len);
270         CHAR_INFO   ci;
271
272         ci.Char.UnicodeChar = ' ';
273         ci.Attributes = ctx->csbi.wAttributes;
274
275         if (cbeg.Y == cend.Y)
276         {
277             /* partial erase of sole line */
278             CONSOLE_FillLineUniform(ctx->hConOut, cbeg.X, cbeg.Y,
279                                     cend.X - cbeg.X, &ci);
280         }
281         else
282         {
283             int         i;
284             /* erase til eol on first line */
285             CONSOLE_FillLineUniform(ctx->hConOut, cbeg.X, cbeg.Y,
286                                     ctx->csbi.dwSize.X - cbeg.X, &ci);
287             /* completely erase all the others (full lines) */
288             for (i = cbeg.Y + 1; i < cend.Y; i++)
289                 CONSOLE_FillLineUniform(ctx->hConOut, 0, i, ctx->csbi.dwSize.X, &ci);
290             /* erase from beginning of line until last pos on last line */
291             CONSOLE_FillLineUniform(ctx->hConOut, 0, cend.Y, cend.X, &ci);
292         }
293     }
294     ctx->len -= str_len;
295     WCEL_Update(ctx, 0, ctx->len);
296     ctx->line[ctx->len] = 0;
297 }
298
299 static void WCEL_InsertString(WCEL_Context* ctx, const WCHAR* str)
300 {
301     size_t      len = lstrlenW(str), updtlen;
302
303     if (!len) return;
304     if (ctx->insert)
305     {
306         if (!WCEL_Grow(ctx, len)) return;
307         if (ctx->len > ctx->ofs)
308             memmove(&ctx->line[ctx->ofs + len], &ctx->line[ctx->ofs], (ctx->len - ctx->ofs) * sizeof(WCHAR));
309         ctx->len += len;
310         updtlen = ctx->len - ctx->ofs;
311     }
312     else
313     {
314         if (ctx->ofs + len > ctx->len)
315         {
316             if (!WCEL_Grow(ctx, (ctx->ofs + len) - ctx->len)) return;
317             ctx->len = ctx->ofs + len;
318         }
319         updtlen = len;
320     }
321     memcpy(&ctx->line[ctx->ofs], str, len * sizeof(WCHAR));
322     ctx->line[ctx->len] = 0;
323     WCEL_Update(ctx, ctx->ofs, updtlen);
324     ctx->ofs += len;
325 }
326
327 static void WCEL_InsertChar(WCEL_Context* ctx, WCHAR c)
328 {
329     WCHAR       buffer[2];
330
331     buffer[0] = c;
332     buffer[1] = 0;
333     WCEL_InsertString(ctx, buffer);
334 }
335
336 static void WCEL_FreeYank(WCEL_Context* ctx)
337 {
338     HeapFree(GetProcessHeap(), 0, ctx->yanked);
339     ctx->yanked = NULL;
340 }
341
342 static void WCEL_SaveYank(WCEL_Context* ctx, int beg, int end)
343 {
344     int len = end - beg;
345     if (len <= 0) return;
346
347     WCEL_FreeYank(ctx);
348     /* After WCEL_FreeYank ctx->yanked is empty */
349     ctx->yanked = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
350     if (!ctx->yanked) return;
351     memcpy(ctx->yanked, &ctx->line[beg], len * sizeof(WCHAR));
352     ctx->yanked[len] = 0;
353 }
354
355 /* FIXME NTDLL doesn't export iswalnum, and I don't want to link in msvcrt when most
356  * of the data lay in unicode lib
357  */
358 static inline BOOL WCEL_iswalnum(WCHAR wc)
359 {
360     return get_char_typeW(wc) & (C1_ALPHA|C1_DIGIT|C1_LOWER|C1_UPPER);
361 }
362
363 static int WCEL_GetLeftWordTransition(WCEL_Context* ctx, int ofs)
364 {
365     ofs--;
366     while (ofs >= 0 && !WCEL_iswalnum(ctx->line[ofs])) ofs--;
367     while (ofs >= 0 && WCEL_iswalnum(ctx->line[ofs])) ofs--;
368     if (ofs >= 0) ofs++;
369     return max(ofs, 0);
370 }
371
372 static int WCEL_GetRightWordTransition(WCEL_Context* ctx, int ofs)
373 {
374     ofs++;
375     while (ofs <= ctx->len && WCEL_iswalnum(ctx->line[ofs])) ofs++;
376     while (ofs <= ctx->len && !WCEL_iswalnum(ctx->line[ofs])) ofs++;
377     return min(ofs, ctx->len);
378 }
379
380 static WCHAR* WCEL_GetHistory(WCEL_Context* ctx, int idx)
381 {
382     WCHAR*      ptr;
383
384     if (idx == ctx->histSize - 1)
385     {
386         ptr = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(ctx->histCurr) + 1) * sizeof(WCHAR));
387         lstrcpyW(ptr, ctx->histCurr);
388     }
389     else
390     {
391         int     len = CONSOLE_GetHistory(idx, NULL, 0);
392
393         if ((ptr = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR))))
394         {
395             CONSOLE_GetHistory(idx, ptr, len);
396         }
397     }
398     return ptr;
399 }
400
401 static void     WCEL_HistoryInit(WCEL_Context* ctx)
402 {
403     ctx->histPos  = CONSOLE_GetNumHistoryEntries();
404     ctx->histSize = ctx->histPos + 1;
405     ctx->histCurr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WCHAR));
406 }
407
408 static void    WCEL_MoveToHist(WCEL_Context* ctx, int idx)
409 {
410     WCHAR*      data = WCEL_GetHistory(ctx, idx);
411     int         len = lstrlenW(data) + 1;
412
413     /* save current line edition for recall when needed (FIXME seems broken to me) */
414     if (ctx->histPos == ctx->histSize - 1)
415     {
416         HeapFree(GetProcessHeap(), 0, ctx->histCurr);
417         ctx->histCurr = HeapAlloc(GetProcessHeap(), 0, (ctx->len + 1) * sizeof(WCHAR));
418         memcpy(ctx->histCurr, ctx->line, (ctx->len + 1) * sizeof(WCHAR));
419     }
420     /* need to clean also the screen if new string is shorter than old one */
421     WCEL_DeleteString(ctx, 0, ctx->len);
422     ctx->ofs = 0;
423     /* insert new string */
424     if (WCEL_Grow(ctx, len))
425     {
426         WCEL_InsertString(ctx, data);
427         HeapFree(GetProcessHeap(), 0, data);
428         ctx->histPos = idx;
429     }
430 }
431
432 static void    WCEL_FindPrevInHist(WCEL_Context* ctx)
433 {
434     int startPos = ctx->histPos;
435     WCHAR*      data;
436     unsigned int    len, oldofs;
437
438     if (ctx->histPos && ctx->histPos == ctx->histSize) {
439         startPos--;
440         ctx->histPos--;
441     }
442
443     do {
444        data = WCEL_GetHistory(ctx, ctx->histPos);
445
446        if (ctx->histPos) ctx->histPos--;
447        else ctx->histPos = (ctx->histSize-1);
448
449        len = lstrlenW(data) + 1;
450        if ((len >= ctx->ofs) &&
451            (memcmp(ctx->line, data, ctx->ofs * sizeof(WCHAR)) == 0)) {
452
453            /* need to clean also the screen if new string is shorter than old one */
454            WCEL_DeleteString(ctx, 0, ctx->len);
455
456            if (WCEL_Grow(ctx, len))
457            {
458               oldofs = ctx->ofs;
459               ctx->ofs = 0;
460               WCEL_InsertString(ctx, data);
461               ctx->ofs = oldofs;
462               if (ctx->shall_echo)
463                   SetConsoleCursorPosition(ctx->hConOut, WCEL_GetCoord(ctx, ctx->ofs));
464               HeapFree(GetProcessHeap(), 0, data);
465               return;
466            }
467        }
468     } while (ctx->histPos != startPos);
469
470     return;
471 }
472
473 /* ====================================================================
474  *
475  * basic edition functions
476  *
477  * ====================================================================*/
478
479 static void WCEL_Done(WCEL_Context* ctx)
480 {
481     WCHAR       nl = '\n';
482     if (!WCEL_Grow(ctx, 2)) return;
483     ctx->line[ctx->len++] = '\r';
484     ctx->line[ctx->len++] = '\n';
485     ctx->line[ctx->len] = 0;
486     WriteConsoleW(ctx->hConOut, &nl, 1, NULL, NULL);
487     ctx->done = 1;
488 }
489
490 static void WCEL_MoveLeft(WCEL_Context* ctx)
491 {
492     if (ctx->ofs > 0) ctx->ofs--;
493 }
494
495 static void WCEL_MoveRight(WCEL_Context* ctx)
496 {
497     if (ctx->ofs < ctx->len) ctx->ofs++;
498 }
499
500 static void WCEL_MoveToLeftWord(WCEL_Context* ctx)
501 {
502     unsigned int        new_ofs = WCEL_GetLeftWordTransition(ctx, ctx->ofs);
503     if (new_ofs != ctx->ofs) ctx->ofs = new_ofs;
504 }
505
506 static void WCEL_MoveToRightWord(WCEL_Context* ctx)
507 {
508     unsigned int        new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
509     if (new_ofs != ctx->ofs) ctx->ofs = new_ofs;
510 }
511
512 static void WCEL_MoveToBeg(WCEL_Context* ctx)
513 {
514     ctx->ofs = 0;
515 }
516
517 static void WCEL_MoveToEnd(WCEL_Context* ctx)
518 {
519     ctx->ofs = ctx->len;
520 }
521
522 static void WCEL_SetMark(WCEL_Context* ctx)
523 {
524     ctx->mark = ctx->ofs;
525 }
526
527 static void WCEL_ExchangeMark(WCEL_Context* ctx)
528 {
529     unsigned tmp;
530
531     if (ctx->mark > ctx->len) return;
532     tmp = ctx->ofs;
533     ctx->ofs = ctx->mark;
534     ctx->mark = tmp;
535 }
536
537 static void WCEL_CopyMarkedZone(WCEL_Context* ctx)
538 {
539     unsigned beg, end;
540
541     if (ctx->mark > ctx->len || ctx->mark == ctx->ofs) return;
542     if (ctx->mark > ctx->ofs)
543     {
544         beg = ctx->ofs;         end = ctx->mark;
545     }
546     else
547     {
548         beg = ctx->mark;        end = ctx->ofs;
549     }
550     WCEL_SaveYank(ctx, beg, end);
551 }
552
553 static void WCEL_TransposeChar(WCEL_Context* ctx)
554 {
555     WCHAR       c;
556
557     if (!ctx->ofs || ctx->ofs == ctx->len) return;
558
559     c = ctx->line[ctx->ofs];
560     ctx->line[ctx->ofs] = ctx->line[ctx->ofs - 1];
561     ctx->line[ctx->ofs - 1] = c;
562
563     WCEL_Update(ctx, ctx->ofs - 1, 2);
564     ctx->ofs++;
565 }
566
567 static void WCEL_TransposeWords(WCEL_Context* ctx)
568 {
569     unsigned int        left_ofs = WCEL_GetLeftWordTransition(ctx, ctx->ofs),
570         right_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
571     if (left_ofs < ctx->ofs && right_ofs > ctx->ofs)
572     {
573         unsigned len_r = right_ofs - ctx->ofs;
574         unsigned len_l = ctx->ofs - left_ofs;
575
576         char*   tmp = HeapAlloc(GetProcessHeap(), 0, len_r * sizeof(WCHAR));
577         if (!tmp) return;
578
579         memcpy(tmp, &ctx->line[ctx->ofs], len_r * sizeof(WCHAR));
580         memmove(&ctx->line[left_ofs + len_r], &ctx->line[left_ofs], len_l * sizeof(WCHAR));
581         memcpy(&ctx->line[left_ofs], tmp, len_r * sizeof(WCHAR));
582
583         HeapFree(GetProcessHeap(), 0, tmp);
584         WCEL_Update(ctx, left_ofs, len_l + len_r);
585         ctx->ofs = right_ofs;
586     }
587 }
588
589 static void WCEL_LowerCaseWord(WCEL_Context* ctx)
590 {
591     unsigned int        new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
592     if (new_ofs != ctx->ofs)
593     {
594         unsigned int    i;
595         for (i = ctx->ofs; i <= new_ofs; i++)
596             ctx->line[i] = tolowerW(ctx->line[i]);
597         WCEL_Update(ctx, ctx->ofs, new_ofs - ctx->ofs + 1);
598         ctx->ofs = new_ofs;
599     }
600 }
601
602 static void WCEL_UpperCaseWord(WCEL_Context* ctx)
603 {
604     unsigned int        new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
605     if (new_ofs != ctx->ofs)
606     {
607         unsigned int    i;
608         for (i = ctx->ofs; i <= new_ofs; i++)
609             ctx->line[i] = toupperW(ctx->line[i]);
610         WCEL_Update(ctx, ctx->ofs, new_ofs - ctx->ofs + 1);
611         ctx->ofs = new_ofs;
612     }
613 }
614
615 static void WCEL_CapitalizeWord(WCEL_Context* ctx)
616 {
617     unsigned int        new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
618     if (new_ofs != ctx->ofs)
619     {
620         unsigned int    i;
621
622         ctx->line[ctx->ofs] = toupperW(ctx->line[ctx->ofs]);
623         for (i = ctx->ofs + 1; i <= new_ofs; i++)
624             ctx->line[i] = tolowerW(ctx->line[i]);
625         WCEL_Update(ctx, ctx->ofs, new_ofs - ctx->ofs + 1);
626         ctx->ofs = new_ofs;
627     }
628 }
629
630 static void WCEL_Yank(WCEL_Context* ctx)
631 {
632     WCEL_InsertString(ctx, ctx->yanked);
633 }
634
635 static void WCEL_KillToEndOfLine(WCEL_Context* ctx)
636 {
637     WCEL_SaveYank(ctx, ctx->ofs, ctx->len);
638     WCEL_DeleteString(ctx, ctx->ofs, ctx->len);
639 }
640
641 static void WCEL_KillFromBegOfLine(WCEL_Context* ctx)
642 {
643     if (ctx->ofs)
644     {
645         WCEL_SaveYank(ctx, 0, ctx->ofs);
646         WCEL_DeleteString(ctx, 0, ctx->ofs);
647         ctx->ofs = 0;
648     }
649 }
650
651 static void WCEL_KillMarkedZone(WCEL_Context* ctx)
652 {
653     unsigned beg, end;
654
655     if (ctx->mark > ctx->len || ctx->mark == ctx->ofs) return;
656     if (ctx->mark > ctx->ofs)
657     {
658         beg = ctx->ofs;         end = ctx->mark;
659     }
660     else
661     {
662         beg = ctx->mark;        end = ctx->ofs;
663     }
664     WCEL_SaveYank(ctx, beg, end);
665     WCEL_DeleteString(ctx, beg, end);
666     ctx->ofs = beg;
667 }
668
669 static void WCEL_DeletePrevChar(WCEL_Context* ctx)
670 {
671     if (ctx->ofs)
672     {
673         WCEL_DeleteString(ctx, ctx->ofs - 1, ctx->ofs);
674         ctx->ofs--;
675     }
676 }
677
678 static void WCEL_DeleteCurrChar(WCEL_Context* ctx)
679 {
680     if (ctx->ofs < ctx->len)
681         WCEL_DeleteString(ctx, ctx->ofs, ctx->ofs + 1);
682 }
683
684 static void WCEL_DeleteLeftWord(WCEL_Context* ctx)
685 {
686     unsigned int        new_ofs = WCEL_GetLeftWordTransition(ctx, ctx->ofs);
687     if (new_ofs != ctx->ofs)
688     {
689         WCEL_DeleteString(ctx, new_ofs, ctx->ofs);
690         ctx->ofs = new_ofs;
691     }
692 }
693
694 static void WCEL_DeleteRightWord(WCEL_Context* ctx)
695 {
696     unsigned int        new_ofs = WCEL_GetRightWordTransition(ctx, ctx->ofs);
697     if (new_ofs != ctx->ofs)
698     {
699         WCEL_DeleteString(ctx, ctx->ofs, new_ofs);
700     }
701 }
702
703 static void WCEL_MoveToPrevHist(WCEL_Context* ctx)
704 {
705     if (ctx->histPos) WCEL_MoveToHist(ctx, ctx->histPos - 1);
706 }
707
708 static void WCEL_MoveToNextHist(WCEL_Context* ctx)
709 {
710     if (ctx->histPos < ctx->histSize - 1) WCEL_MoveToHist(ctx, ctx->histPos + 1);
711 }
712
713 static void WCEL_MoveToFirstHist(WCEL_Context* ctx)
714 {
715     if (ctx->histPos != 0) WCEL_MoveToHist(ctx, 0);
716 }
717
718 static void WCEL_MoveToLastHist(WCEL_Context* ctx)
719 {
720     if (ctx->histPos != ctx->histSize - 1) WCEL_MoveToHist(ctx, ctx->histSize - 1);
721 }
722
723 static void WCEL_Redraw(WCEL_Context* ctx)
724 {
725     if (ctx->shall_echo)
726     {
727         COORD       c = WCEL_GetCoord(ctx, ctx->len);
728         CHAR_INFO   ci;
729
730         WCEL_Update(ctx, 0, ctx->len);
731
732         ci.Char.UnicodeChar = ' ';
733         ci.Attributes = ctx->csbi.wAttributes;
734
735         CONSOLE_FillLineUniform(ctx->hConOut, c.X, c.Y, ctx->csbi.dwSize.X - c.X, &ci);
736     }
737 }
738
739 static void WCEL_RepeatCount(WCEL_Context* ctx)
740 {
741 #if 0
742 /* FIXME: wait until all console code is in kernel32 */
743     INPUT_RECORD        ir;
744     unsigned            repeat = 0;
745
746     while (WCEL_Get(ctx, &ir, FALSE))
747     {
748         if (ir.EventType != KEY_EVENT) break;
749         if (ir.Event.KeyEvent.bKeyDown)
750         {
751             if ((ir.Event.KeyEvent.dwControlKeyState & ~(NUMLOCK_ON|SCROLLLOCK_ON|CAPSLOCK_ON)) != 0)
752                 break;
753             if (ir.Event.KeyEvent.uChar.UnicodeChar < '0' ||
754                 ir.Event.KeyEvent.uChar.UnicodeChar > '9')
755                 break;
756             repeat = repeat * 10 + ir.Event.KeyEvent.uChar.UnicodeChar - '0';
757         }
758         WCEL_Get(ctx, &ir, TRUE);
759     }
760     FIXME("=> %u\n", repeat);
761 #endif
762 }
763
764 static void WCEL_ToggleInsert(WCEL_Context* ctx)
765 {
766     DWORD               mode;
767     CONSOLE_CURSOR_INFO cinfo;
768
769     if (GetConsoleMode(ctx->hConIn, &mode) && GetConsoleCursorInfo(ctx->hConOut, &cinfo))
770     {
771         if ((mode & (ENABLE_INSERT_MODE|ENABLE_EXTENDED_FLAGS)) == (ENABLE_INSERT_MODE|ENABLE_EXTENDED_FLAGS))
772         {
773             mode &= ~ENABLE_INSERT_MODE;
774             cinfo.dwSize = 100;
775             ctx->insert = FALSE;
776         }
777         else
778         {
779             mode |= ENABLE_INSERT_MODE | ENABLE_EXTENDED_FLAGS;
780             cinfo.dwSize = 25;
781             ctx->insert = TRUE;
782         }
783         SetConsoleMode(ctx->hConIn, mode);
784         SetConsoleCursorInfo(ctx->hConOut, &cinfo);
785     }
786 }
787
788 /* ====================================================================
789  *
790  *              Key Maps
791  *
792  * ====================================================================*/
793
794 #define CTRL(x) ((x) - '@')
795 static const KeyEntry StdKeyMap[] =
796 {
797     {/*BACK*/0x08,      WCEL_DeletePrevChar     },
798     {/*RETURN*/0x0d,    WCEL_Done               },
799     {/*DEL*/127,        WCEL_DeleteCurrChar     },
800     {   0,              NULL                    }
801 };
802
803 static const KeyEntry EmacsKeyMapCtrl[] =
804 {
805     {   CTRL('@'),      WCEL_SetMark            },
806     {   CTRL('A'),      WCEL_MoveToBeg          },
807     {   CTRL('B'),      WCEL_MoveLeft           },
808     /* C: done in server */
809     {   CTRL('D'),      WCEL_DeleteCurrChar     },
810     {   CTRL('E'),      WCEL_MoveToEnd          },
811     {   CTRL('F'),      WCEL_MoveRight          },
812     {   CTRL('G'),      WCEL_Beep               },
813     {   CTRL('H'),      WCEL_DeletePrevChar     },
814     /* I: meaningless (or tab ???) */
815     {   CTRL('J'),      WCEL_Done               },
816     {   CTRL('K'),      WCEL_KillToEndOfLine    },
817     {   CTRL('L'),      WCEL_Redraw             },
818     {   CTRL('M'),      WCEL_Done               },
819     {   CTRL('N'),      WCEL_MoveToNextHist     },
820     /* O; insert line... meaningless */
821     {   CTRL('P'),      WCEL_MoveToPrevHist     },
822     /* Q: [NIY] quoting... */
823     /* R: [NIY] search backwards... */
824     /* S: [NIY] search forwards... */
825     {   CTRL('T'),      WCEL_TransposeChar      },
826     {   CTRL('U'),      WCEL_RepeatCount        },
827     /* V: paragraph down... meaningless */
828     {   CTRL('W'),      WCEL_KillMarkedZone     },
829     {   CTRL('X'),      WCEL_ExchangeMark       },
830     {   CTRL('Y'),      WCEL_Yank               },
831     /* Z: meaningless */
832     {   0,              NULL                    }
833 };
834
835 static const KeyEntry EmacsKeyMapAlt[] =
836 {
837     {/*DEL*/127,        WCEL_DeleteLeftWord     },
838     {   '<',            WCEL_MoveToFirstHist    },
839     {   '>',            WCEL_MoveToLastHist     },
840     {   '?',            WCEL_Beep               },
841     {   'b',            WCEL_MoveToLeftWord     },
842     {   'c',            WCEL_CapitalizeWord     },
843     {   'd',            WCEL_DeleteRightWord    },
844     {   'f',            WCEL_MoveToRightWord    },
845     {   'l',            WCEL_LowerCaseWord      },
846     {   't',            WCEL_TransposeWords     },
847     {   'u',            WCEL_UpperCaseWord      },
848     {   'w',            WCEL_CopyMarkedZone     },
849     {   0,              NULL                    }
850 };
851
852 static const KeyEntry EmacsStdKeyMap[] =
853 {
854     {/*VK_PRIOR*/0x21,  WCEL_MoveToPrevHist     },
855     {/*VK_NEXT*/ 0x22,  WCEL_MoveToNextHist     },
856     {/*VK_END*/  0x23,  WCEL_MoveToEnd          },
857     {/*VK_HOME*/ 0x24,  WCEL_MoveToBeg          },
858     {/*VK_RIGHT*/0x27,  WCEL_MoveRight          },
859     {/*VK_LEFT*/ 0x25,  WCEL_MoveLeft           },
860     {/*VK_DEL*/  0x2e,  WCEL_DeleteCurrChar     },
861     {/*VK_INSERT*/0x2d, WCEL_ToggleInsert       },
862     {   0,              NULL                    }
863 };
864
865 static const KeyMap EmacsKeyMap[] =
866 {
867     {0,                  1, StdKeyMap},
868     {0,                  0, EmacsStdKeyMap},
869     {RIGHT_ALT_PRESSED,  1, EmacsKeyMapAlt},    /* right alt  */
870     {LEFT_ALT_PRESSED,   1, EmacsKeyMapAlt},    /* left  alt  */
871     {RIGHT_CTRL_PRESSED, 1, EmacsKeyMapCtrl},   /* right ctrl */
872     {LEFT_CTRL_PRESSED,  1, EmacsKeyMapCtrl},   /* left  ctrl */
873     {0,                  0, NULL}
874 };
875
876 static const KeyEntry Win32StdKeyMap[] =
877 {
878     {/*VK_LEFT*/ 0x25,  WCEL_MoveLeft           },
879     {/*VK_RIGHT*/0x27,  WCEL_MoveRight          },
880     {/*VK_HOME*/ 0x24,  WCEL_MoveToBeg          },
881     {/*VK_END*/  0x23,  WCEL_MoveToEnd          },
882     {/*VK_UP*/   0x26,  WCEL_MoveToPrevHist     },
883     {/*VK_DOWN*/ 0x28,  WCEL_MoveToNextHist     },
884     {/*VK_DEL*/  0x2e,  WCEL_DeleteCurrChar     },
885     {/*VK_INSERT*/0x2d, WCEL_ToggleInsert       },
886     {/*VK_F8*/   0x77,  WCEL_FindPrevInHist     },
887     {   0,              NULL                    }
888 };
889
890 static const KeyEntry Win32KeyMapCtrl[] =
891 {
892     {/*VK_LEFT*/ 0x25,  WCEL_MoveToLeftWord     },
893     {/*VK_RIGHT*/0x27,  WCEL_MoveToRightWord    },
894     {/*VK_END*/  0x23,  WCEL_KillToEndOfLine    },
895     {/*VK_HOME*/ 0x24,  WCEL_KillFromBegOfLine  },
896     {   0,              NULL                    }
897 };
898
899 static const KeyMap Win32KeyMap[] =
900 {
901     {0,                  1, StdKeyMap},
902     {0,                  0, Win32StdKeyMap},
903     {RIGHT_CTRL_PRESSED, 0, Win32KeyMapCtrl},
904     {LEFT_CTRL_PRESSED,  0, Win32KeyMapCtrl},
905     {0,                  0, NULL}
906 };
907 #undef CTRL
908
909 /* ====================================================================
910  *
911  *              Read line master function
912  *
913  * ====================================================================*/
914
915 WCHAR* CONSOLE_Readline(HANDLE hConsoleIn, BOOL can_pos_cursor)
916 {
917     WCEL_Context        ctx;
918     INPUT_RECORD        ir;
919     const KeyMap*       km;
920     const KeyEntry*     ke;
921     unsigned            ofs;
922     void                (*func)(struct WCEL_Context* ctx);
923     DWORD               mode, ks;
924     int                 use_emacs;
925
926     memset(&ctx, 0, sizeof(ctx));
927     ctx.hConIn = hConsoleIn;
928     WCEL_HistoryInit(&ctx);
929
930     if (!CONSOLE_GetEditionMode(hConsoleIn, &use_emacs))
931         use_emacs = 0;
932
933     if ((ctx.hConOut = CreateFileA("CONOUT$", GENERIC_READ|GENERIC_WRITE, 0, NULL,
934                                     OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE ||
935         !GetConsoleScreenBufferInfo(ctx.hConOut, &ctx.csbi))
936         return NULL;
937     if (!GetConsoleMode(hConsoleIn, &mode)) mode = 0;
938     ctx.shall_echo = (mode & ENABLE_ECHO_INPUT) ? 1 : 0;
939     ctx.insert = (mode & (ENABLE_INSERT_MODE|ENABLE_EXTENDED_FLAGS)) == (ENABLE_INSERT_MODE|ENABLE_EXTENDED_FLAGS) ? 1 : 0;
940     if (!GetConsoleMode(ctx.hConOut, &mode)) mode = 0;
941     ctx.can_wrap = (mode & ENABLE_WRAP_AT_EOL_OUTPUT) ? 1 : 0;
942     ctx.can_pos_cursor = can_pos_cursor;
943
944     if (!WCEL_Grow(&ctx, 1))
945     {
946         CloseHandle(ctx.hConOut);
947         return NULL;
948     }
949     ctx.line[0] = 0;
950
951 /* EPP     WCEL_Dump(&ctx, "init"); */
952
953     while (!ctx.done && !ctx.error && WCEL_Get(&ctx, &ir))
954     {
955         if (ir.EventType != KEY_EVENT) continue;
956         TRACE("key%s repeatCount=%u, keyCode=%02x scanCode=%02x char=%02x keyState=%08x\n",
957               ir.Event.KeyEvent.bKeyDown ? "Down" : "Up  ", ir.Event.KeyEvent.wRepeatCount,
958               ir.Event.KeyEvent.wVirtualKeyCode, ir.Event.KeyEvent.wVirtualScanCode,
959               ir.Event.KeyEvent.uChar.UnicodeChar, ir.Event.KeyEvent.dwControlKeyState);
960         if (!ir.Event.KeyEvent.bKeyDown) continue;
961
962 /* EPP          WCEL_Dump(&ctx, "before func"); */
963         ofs = ctx.ofs;
964         /* mask out some bits which don't interest us */
965         ks = ir.Event.KeyEvent.dwControlKeyState & ~(NUMLOCK_ON|SCROLLLOCK_ON|CAPSLOCK_ON|ENHANCED_KEY);
966
967         func = NULL;
968         for (km = (use_emacs) ? EmacsKeyMap : Win32KeyMap; km->entries != NULL; km++)
969         {
970             if (km->keyState != ks)
971                 continue;
972             if (km->chkChar)
973             {
974                 for (ke = &km->entries[0]; ke->func != 0; ke++)
975                     if (ke->val == ir.Event.KeyEvent.uChar.UnicodeChar) break;
976             }
977             else
978             {
979                 for (ke = &km->entries[0]; ke->func != 0; ke++)
980                     if (ke->val == ir.Event.KeyEvent.wVirtualKeyCode) break;
981
982             }
983             if (ke->func)
984             {
985                 func = ke->func;
986                 break;
987             }
988         }
989
990         if (func)
991             (func)(&ctx);
992         else if (!(ir.Event.KeyEvent.dwControlKeyState & LEFT_ALT_PRESSED))
993             WCEL_InsertChar(&ctx, ir.Event.KeyEvent.uChar.UnicodeChar);
994         else TRACE("Dropped event\n");
995
996 /* EPP         WCEL_Dump(&ctx, "after func"); */
997         if (!ctx.shall_echo) continue;
998         if (ctx.can_pos_cursor)
999         {
1000             if (ctx.ofs != ofs)
1001                 SetConsoleCursorPosition(ctx.hConOut, WCEL_GetCoord(&ctx, ctx.ofs));
1002         }
1003         else if (!ctx.done && !ctx.error)
1004         {
1005             DWORD last;
1006             /* erase previous chars */
1007             WCEL_WriteNChars(&ctx, '\b', ctx.last_rub);
1008
1009             /* write chars up to cursor */
1010             ctx.last_rub = WCEL_WriteConsole(&ctx, 0, ctx.ofs);
1011             /* write chars past cursor */
1012             last = ctx.last_rub + WCEL_WriteConsole(&ctx, ctx.ofs, ctx.len - ctx.ofs);
1013             if (last < ctx.last_max) /* ctx.line has been shortened, erase */
1014             {
1015                 WCEL_WriteNChars(&ctx, ' ', ctx.last_max - last);
1016                 WCEL_WriteNChars(&ctx, '\b', ctx.last_max - last);
1017                 ctx.last_max = last;
1018             }
1019             else ctx.last_max = last;
1020             /* reposition at cursor */
1021             WCEL_WriteNChars(&ctx, '\b', last - ctx.last_rub);
1022         }
1023     }
1024     if (ctx.error)
1025     {
1026         HeapFree(GetProcessHeap(), 0, ctx.line);
1027         ctx.line = NULL;
1028     }
1029     WCEL_FreeYank(&ctx);
1030     if (ctx.line)
1031         CONSOLE_AppendHistory(ctx.line);
1032
1033     CloseHandle(ctx.hConOut);
1034     HeapFree(GetProcessHeap(), 0, ctx.histCurr);
1035     return ctx.line;
1036 }