summaryrefslogtreecommitdiff
path: root/mysys/my_conio.c
blob: dc87b83f6b44a6ad10613ce7e337894dd8f2a387 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/* Copyright (C) 2000 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA */


#include "mysys_priv.h"

#ifdef __WIN__

static HANDLE my_coninpfh= 0;     /* console input */

/*
  functions my_pthread_auto_mutex_lock & my_pthread_auto_mutex_free
  are experimental at this moment, they are intended to bring
  ability of protecting code sections without necessity to explicitly
  initialize synchronization object in one of threads

  if found useful they are to be exported in mysys
*/


/*
  int my_pthread_auto_mutex_lock(HANDLE* ph, const char* name, 
                                 int id, int time)
  NOTES
    creates a mutex with given name and tries to lock it time msec.
    mutex name is appended with id to allow system wide or process wide
    locks. Handle to created mutex returned in ph argument.

  RETURN
    0	              thread owns mutex
    <>0	            error
*/

static
int my_pthread_auto_mutex_lock(HANDLE* ph, const char* name, int id, int time)
{
  int res;
  char tname[FN_REFLEN];
  
  sprintf(tname, "%s-%08X", name, id);
  
  *ph= CreateMutex(NULL, FALSE, tname);
  if (*ph == NULL)
    return GetLastError();

  res= WaitForSingleObject(*ph, time);
  
  if (res == WAIT_TIMEOUT)
    return ERROR_SEM_TIMEOUT;

  if (res == WAIT_FAILED)
    return GetLastError();

  return 0;
}

/*
  int my_pthread_auto_mutex_free(HANDLE* ph)

  NOTES
    releases a mutex.

  RETURN
    0	              thread released mutex
    <>0	            error

*/
static
int my_pthread_auto_mutex_free(HANDLE* ph)
{
  if (*ph)
  {
    ReleaseMutex(*ph);
    CloseHandle(*ph);
    *ph= NULL;
  }

  return 0;
}


#define pthread_auto_mutex_decl(name)                           \
  HANDLE __h##name= NULL;

#define pthread_auto_mutex_lock(name, proc, time)               \
  my_pthread_auto_mutex_lock(&__h##name, #name, (proc), (time))

#define pthread_auto_mutex_free(name)                           \
  my_pthread_auto_mutex_free(&__h##name)


/*
  char* my_cgets()

  NOTES
    Replaces _cgets from libc to support input of more than 255 chars.
    Reads from the console via ReadConsole into buffer which 
    should be at least clen characters.
    Actual length of string returned in plen.

  WARNING
    my_cgets() does NOT check the pushback character buffer (i.e., _chbuf).
    Thus, my_cgets() will not return any character that is pushed back by 
    the _ungetch() call.

  RETURN
    string pointer	ok
    NULL	          Error

*/

char* my_cgets(char *buffer, size_t clen, size_t* plen)
{
  ULONG state;
  char *result;
  DWORD plen_res;
  CONSOLE_SCREEN_BUFFER_INFO csbi;
  
  pthread_auto_mutex_decl(my_conio_cs);
 
  /* lock the console for the current process*/
  if (pthread_auto_mutex_lock(my_conio_cs, GetCurrentProcessId(), INFINITE))
  {
    /* can not lock console */
    pthread_auto_mutex_free(my_conio_cs);  
    return NULL;
  }

  /* init console input */
  if (my_coninpfh == 0)
  {
    /* same handle will be used until process termination */
    my_coninpfh= CreateFile("CONIN$", GENERIC_READ | GENERIC_WRITE,
                            FILE_SHARE_READ | FILE_SHARE_WRITE,
                            NULL, OPEN_EXISTING, 0, NULL);
  }

  if (my_coninpfh == INVALID_HANDLE_VALUE) 
  {
    /* unlock the console */
    pthread_auto_mutex_free(my_conio_cs);  
    return(NULL);
  }

  GetConsoleMode((HANDLE)my_coninpfh, &state);
  SetConsoleMode((HANDLE)my_coninpfh, ENABLE_LINE_INPUT | 
                 ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT);

  GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);

  /* 
    there is no known way to determine allowed buffer size for input
    though it is known it should not be more than 64K               
    so we cut 64K and try first size of screen buffer               
    if it is still to large we cut half of it and try again         
    later we may want to cycle from min(clen, 65535) to allowed size
    with small decrement to determine exact allowed buffer           
  */
  clen= min(clen, 65535);
  do
  {
    clen= min(clen, (size_t) csbi.dwSize.X*csbi.dwSize.Y);
    if (!ReadConsole((HANDLE)my_coninpfh, (LPVOID)buffer, (DWORD) clen - 1, &plen_res,
                     NULL))
    {
      result= NULL;
      clen>>= 1;
    }
    else
    {
      result= buffer;
      break;
    }
  }
  while (GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
  *plen= plen_res;

  /* We go here on error reading the string (Ctrl-C for example) */
  if (!*plen)
    result= NULL;                              /* purecov: inspected */

  if (result != NULL)
  {
    if (*plen > 1 && buffer[*plen - 2] == '\r')
    {
      *plen= *plen - 2;
    }
    else 
    {
      if (*plen > 0 && buffer[*plen - 1] == '\r')
      {
        char tmp[3];
        int  tmplen= sizeof(tmp);

        *plen= *plen - 1;
        /* read /n left in the buffer */
        ReadConsole((HANDLE)my_coninpfh, (LPVOID)tmp, tmplen, &tmplen, NULL);
      }
    }
    buffer[*plen]= '\0';
  }

  SetConsoleMode((HANDLE)my_coninpfh, state);
  /* unlock the console */
  pthread_auto_mutex_free(my_conio_cs);  

  return result;
}

#endif /* __WIN__ */