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