Added CTRL+V paste into the console for win32 users.
[xonotic/darkplaces.git] / sys_win.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // sys_win.c -- Win32 system interface code
21
22 #include "quakedef.h"
23 #include <windows.h>
24 #include <dsound.h>
25 #include "errno.h"
26 #include "resource.h"
27 #include "conproc.h"
28 #include "direct.h"
29
30 extern void S_BlockSound (void);
31
32 cvar_t sys_usetimegettime = {CVAR_SAVE, "sys_usetimegettime", "1"};
33
34 // # of seconds to wait on Sys_Error running dedicated before exiting
35 #define CONSOLE_ERROR_TIMEOUT   60.0
36 // sleep time on pause or minimization
37 #define PAUSE_SLEEP             50
38 // sleep time when not focus
39 #define NOT_FOCUS_SLEEP 20
40
41 static qboolean         sc_return_on_enter = false;
42 HANDLE                          hinput, houtput;
43
44 static HANDLE   tevent;
45 static HANDLE   hFile;
46 static HANDLE   heventParent;
47 static HANDLE   heventChild;
48
49
50 /*
51 ===============================================================================
52
53 SYSTEM IO
54
55 ===============================================================================
56 */
57
58 void SleepUntilInput (int time);
59
60 void Sys_Error (const char *error, ...)
61 {
62         va_list         argptr;
63         char            text[1024];
64         static int      in_sys_error0 = 0;
65         static int      in_sys_error1 = 0;
66         static int      in_sys_error2 = 0;
67
68         va_start (argptr, error);
69         vsnprintf (text, sizeof (text), error, argptr);
70         va_end (argptr);
71
72         // close video so the message box is visible, unless we already tried that
73         if (!in_sys_error0 && cls.state != ca_dedicated)
74         {
75                 in_sys_error0 = 1;
76                 VID_Shutdown();
77         }
78         MessageBox(NULL, text, "Quake Error", MB_OK | MB_SETFOREGROUND | MB_ICONSTOP);
79
80         if (!in_sys_error1)
81         {
82                 in_sys_error1 = 1;
83                 Host_Shutdown ();
84         }
85
86 // shut down QHOST hooks if necessary
87         if (!in_sys_error2)
88         {
89                 in_sys_error2 = 1;
90                 DeinitConProc ();
91         }
92
93         exit (1);
94 }
95
96 void Sys_Shutdown (void)
97 {
98         if (tevent)
99                 CloseHandle (tevent);
100
101         if (cls.state == ca_dedicated)
102                 FreeConsole ();
103
104 // shut down QHOST hooks if necessary
105         DeinitConProc ();
106 }
107
108 void Sys_PrintToTerminal(const char *text)
109 {
110         DWORD dummy;
111         extern HANDLE houtput;
112         if (cls.state == ca_dedicated)
113                 WriteFile(houtput, text, strlen (text), &dummy, NULL);
114 }
115
116 /*
117 ================
118 Sys_DoubleTime
119 ================
120 */
121 double Sys_DoubleTime (void)
122 {
123         static int first = true;
124         static double oldtime = 0.0, curtime = 0.0;
125         double newtime;
126         // LordHavoc: note to people modifying this code, DWORD is specifically defined as an unsigned 32bit number, therefore the 65536.0 * 65536.0 is fine.
127         if (sys_usetimegettime.integer)
128         {
129                 static int firsttimegettime = true;
130                 // timeGetTime
131                 // platform:
132                 // Windows 95/98/ME/NT/2000/XP
133                 // features:
134                 // reasonable accuracy (millisecond)
135                 // issues:
136                 // wraps around every 47 days or so (but this is non-fatal to us, odd times are rejected, only causes a one frame stutter)
137
138                 // make sure the timer is high precision, otherwise different versions of windows have varying accuracy
139                 if (firsttimegettime)
140                 {
141                         timeBeginPeriod (1);
142                         firsttimegettime = false;
143                 }
144
145                 newtime = (double) timeGetTime () / 1000.0;
146         }
147         else
148         {
149                 // QueryPerformanceCounter
150                 // platform:
151                 // Windows 95/98/ME/NT/2000/XP
152                 // features:
153                 // very accurate (CPU cycles)
154                 // known issues:
155                 // does not necessarily match realtime too well (tends to get faster and faster in win98)
156                 // wraps around occasionally on some platforms (depends on CPU speed and probably other unknown factors)
157                 double timescale;
158                 LARGE_INTEGER PerformanceFreq;
159                 LARGE_INTEGER PerformanceCount;
160
161                 if (!QueryPerformanceFrequency (&PerformanceFreq))
162                         Sys_Error ("No hardware timer available");
163                 QueryPerformanceCounter (&PerformanceCount);
164
165                 #ifdef __BORLANDC__
166                 timescale = 1.0 / ((double) PerformanceFreq.u.LowPart + (double) PerformanceFreq.u.HighPart * 65536.0 * 65536.0);
167                 newtime = ((double) PerformanceCount.u.LowPart + (double) PerformanceCount.u.HighPart * 65536.0 * 65536.0) * timescale;
168                 #else
169                 timescale = 1.0 / ((double) PerformanceFreq.LowPart + (double) PerformanceFreq.HighPart * 65536.0 * 65536.0);
170                 newtime = ((double) PerformanceCount.LowPart + (double) PerformanceCount.HighPart * 65536.0 * 65536.0) * timescale;
171                 #endif
172         }
173
174         if (first)
175         {
176                 first = false;
177                 oldtime = newtime;
178         }
179
180         if (newtime < oldtime)
181         {
182                 // warn if it's significant
183                 if (newtime - oldtime < -0.01)
184                         Con_Printf("Sys_DoubleTime: time stepped backwards (went from %f to %f, difference %f)\n", oldtime, newtime, newtime - oldtime);
185         }
186         else
187                 curtime += newtime - oldtime;
188         oldtime = newtime;
189
190         return curtime;
191 }
192
193
194 char *Sys_ConsoleInput (void)
195 {
196         static char text[256];
197         static int len;
198         INPUT_RECORD recs[1024];
199         int ch;
200         DWORD numread, numevents, dummy;
201
202         if (cls.state != ca_dedicated)
203                 return NULL;
204
205
206         for ( ;; )
207         {
208                 if (!GetNumberOfConsoleInputEvents (hinput, &numevents))
209                         Sys_Error ("Error getting # of console events");
210
211                 if (numevents <= 0)
212                         break;
213
214                 if (!ReadConsoleInput(hinput, recs, 1, &numread))
215                         Sys_Error ("Error reading console input");
216
217                 if (numread != 1)
218                         Sys_Error ("Couldn't read console input");
219
220                 if (recs[0].EventType == KEY_EVENT)
221                 {
222                         if (!recs[0].Event.KeyEvent.bKeyDown)
223                         {
224                                 ch = recs[0].Event.KeyEvent.uChar.AsciiChar;
225
226                                 switch (ch)
227                                 {
228                                         case '\r':
229                                                 WriteFile(houtput, "\r\n", 2, &dummy, NULL);
230
231                                                 if (len)
232                                                 {
233                                                         text[len] = 0;
234                                                         len = 0;
235                                                         return text;
236                                                 }
237                                                 else if (sc_return_on_enter)
238                                                 {
239                                                 // special case to allow exiting from the error handler on Enter
240                                                         text[0] = '\r';
241                                                         len = 0;
242                                                         return text;
243                                                 }
244
245                                                 break;
246
247                                         case '\b':
248                                                 WriteFile(houtput, "\b \b", 3, &dummy, NULL);
249                                                 if (len)
250                                                 {
251                                                         len--;
252                                                 }
253                                                 break;
254
255                                         default:
256                                                 if (ch >= ' ')
257                                                 {
258                                                         WriteFile(houtput, &ch, 1, &dummy, NULL);
259                                                         text[len] = ch;
260                                                         len = (len + 1) & 0xff;
261                                                 }
262
263                                                 break;
264
265                                 }
266                         }
267                 }
268         }
269
270         return NULL;
271 }
272
273 void Sys_Sleep(int milliseconds)
274 {
275         if (milliseconds < 1)
276                 milliseconds = 1;
277         Sleep(milliseconds);
278 }
279
280 char *Sys_GetClipboardData (void)
281 {
282         char *data = NULL;
283         char *cliptext;
284
285         if (OpenClipboard (NULL) != 0)
286         {
287                 HANDLE hClipboardData;
288
289                 if ((hClipboardData = GetClipboardData (CF_TEXT)) != 0)
290                 {
291                         if ((cliptext = GlobalLock (hClipboardData)) != 0) 
292                         {
293                                 data = malloc (GlobalSize(hClipboardData)+1);
294                                 strcpy (data, cliptext);
295                                 GlobalUnlock (hClipboardData);
296                         }
297                 }
298                 CloseClipboard ();
299         }
300         return data;
301 }
302
303 /*
304 ==============================================================================
305
306 WINDOWS CRAP
307
308 ==============================================================================
309 */
310
311
312 void SleepUntilInput (int time)
313 {
314         MsgWaitForMultipleObjects(1, &tevent, false, time, QS_ALLINPUT);
315 }
316
317
318 /*
319 ==================
320 WinMain
321 ==================
322 */
323 HINSTANCE       global_hInstance;
324 const char      *argv[MAX_NUM_ARGVS];
325 char            program_name[MAX_OSPATH];
326
327 int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
328 {
329         double frameoldtime, framenewtime;
330         MEMORYSTATUS lpBuffer;
331         int t;
332
333         /* previous instances do not exist in Win32 */
334         if (hPrevInstance)
335                 return 0;
336
337         global_hInstance = hInstance;
338
339         lpBuffer.dwLength = sizeof(MEMORYSTATUS);
340         GlobalMemoryStatus (&lpBuffer);
341
342         com_argc = 1;
343         program_name[sizeof(program_name)-1] = 0;
344         GetModuleFileNameA(NULL, program_name, sizeof(program_name) - 1);
345         argv[0] = program_name;
346
347         // FIXME: this tokenizer is rather redundent, call a more general one
348         while (*lpCmdLine && (com_argc < MAX_NUM_ARGVS))
349         {
350                 while (*lpCmdLine && *lpCmdLine <= 32)
351                         lpCmdLine++;
352
353                 if (*lpCmdLine)
354                 {
355                         if (*lpCmdLine == '\"')
356                         {
357                                 // quoted string
358                                 argv[com_argc] = lpCmdLine;
359                                 com_argc++;
360
361                                 while (*lpCmdLine && (*lpCmdLine != '\"'))
362                                         lpCmdLine++;
363
364                                 if (*lpCmdLine)
365                                 {
366                                         *lpCmdLine = 0;
367                                         lpCmdLine++;
368                                 }
369
370                                 if (*lpCmdLine == '\"')
371                                         lpCmdLine++;
372                         }
373                         else
374                         {
375                                 // unquoted word
376                                 argv[com_argc] = lpCmdLine;
377                                 com_argc++;
378
379                                 while (*lpCmdLine && *lpCmdLine > 32)
380                                         lpCmdLine++;
381
382                                 if (*lpCmdLine)
383                                 {
384                                         *lpCmdLine = 0;
385                                         lpCmdLine++;
386                                 }
387                         }
388                 }
389         }
390         com_argv = argv;
391
392         Sys_Shared_EarlyInit();
393
394         Cvar_RegisterVariable(&sys_usetimegettime);
395
396         tevent = CreateEvent(NULL, false, false, NULL);
397
398         if (!tevent)
399                 Sys_Error ("Couldn't create event");
400
401         // LordHavoc: can't check cls.state because it hasn't been initialized yet
402         // if (cls.state == ca_dedicated)
403         if (COM_CheckParm("-dedicated"))
404         {
405                 if (!AllocConsole ())
406                         Sys_Error ("Couldn't create dedicated server console");
407
408                 hinput = GetStdHandle (STD_INPUT_HANDLE);
409                 houtput = GetStdHandle (STD_OUTPUT_HANDLE);
410
411         // give QHOST a chance to hook into the console
412                 if ((t = COM_CheckParm ("-HFILE")) > 0)
413                 {
414                         if (t < com_argc)
415                                 hFile = (HANDLE)atoi (com_argv[t+1]);
416                 }
417
418                 if ((t = COM_CheckParm ("-HPARENT")) > 0)
419                 {
420                         if (t < com_argc)
421                                 heventParent = (HANDLE)atoi (com_argv[t+1]);
422                 }
423
424                 if ((t = COM_CheckParm ("-HCHILD")) > 0)
425                 {
426                         if (t < com_argc)
427                                 heventChild = (HANDLE)atoi (com_argv[t+1]);
428                 }
429
430                 InitConProc (hFile, heventParent, heventChild);
431         }
432
433 // because sound is off until we become active
434         S_BlockSound ();
435
436         Host_Init ();
437
438         Sys_Shared_LateInit();
439
440         frameoldtime = Sys_DoubleTime ();
441         
442         /* main window message loop */
443         while (1)
444         {
445                 if (cls.state != ca_dedicated)
446                 {
447                 // yield the CPU for a little while when paused, minimized, or not the focus
448                         if ((cl.paused && !vid_activewindow) || vid_hidden)
449                         {
450                                 SleepUntilInput (PAUSE_SLEEP);
451                                 scr_skipupdate = 1;             // no point in bothering to draw
452                         }
453                         else if (!vid_activewindow)
454                                 SleepUntilInput (NOT_FOCUS_SLEEP);
455                 }
456
457                 framenewtime = Sys_DoubleTime ();
458                 Host_Frame (framenewtime - frameoldtime);
459                 frameoldtime = framenewtime;
460         }
461
462         /* return success of application */
463         return true;
464 }