user32: Pack the MDINEXTMENU structure in messages to allow crossing 32/64 boundaries.
[wine] / dlls / krnl386.exe16 / vga.c
1 /*
2  * VGA hardware emulation
3  *
4  * Copyright 1998 Ove Kåven (with some help from Marcus Meissner)
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 <stdarg.h>
22 #include <string.h>
23
24 #define NONAMELESSUNION
25 #define NONAMELESSSTRUCT
26 #include "windef.h"
27 #include "winbase.h"
28 #include "wingdi.h"
29 #include "winuser.h"
30 #include "wincon.h"
31 #include "dosexe.h"
32 #include "vga.h"
33 #include "ddraw.h"
34 #include "wine/debug.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(ddraw);
37
38 static IDirectDraw *lpddraw = NULL;
39 static IDirectDrawSurface *lpddsurf;
40 static IDirectDrawPalette *lpddpal;
41 static DDSURFACEDESC sdesc;
42
43 static BOOL vga_retrace_vertical;
44 static BOOL vga_retrace_horizontal;
45
46 /*
47  * Size and location of VGA controller window to framebuffer.
48  *
49  * Note: We support only single window even though some
50  *       controllers support two. This should not be changed unless
51  *       there are programs that depend on having two windows.
52  */
53 #define VGA_WINDOW_SIZE  (64 * 1024)
54 #define VGA_WINDOW_START ((char *)0xa0000)
55
56 /*
57  * Size and location of CGA controller window to framebuffer.
58  */
59 #define CGA_WINDOW_SIZE  (32 * 1024)
60 #define CGA_WINDOW_START ((char *)0xb8000)
61
62 /*
63  * VGA controller memory is emulated using linear framebuffer.
64  * This frambuffer also acts as an interface
65  * between VGA controller emulation and DirectDraw.
66  *
67  * vga_fb_width: Display width in pixels. Can be modified when
68  *               display mode is changed.
69  * vga_fb_height: Display height in pixels. Can be modified when
70  *                display mode is changed.
71  * vga_fb_depth: Number of bits used to store single pixel color information.
72  *               Each pixel uses (vga_fb_depth+7)/8 bytes because
73  *               1-16 color modes are mapped to 256 color mode.
74  *               Can be modified when display mode is changed.
75  * vga_fb_pitch: How many bytes to add to pointer in order to move
76  *               from one row to another. This is fixed in VGA modes,
77  *               but can be modified in SVGA modes.
78  * vga_fb_offset: Offset added to framebuffer start address in order
79  *                to find the display origin. Programs use this to do
80  *                double buffering and to scroll display. The value can
81  *                be modified in VGA and SVGA modes.
82  * vga_fb_size: How many bytes are allocated to framebuffer.
83  *              VGA framebuffers are always larger than display size and
84  *              SVGA framebuffers may also be.
85  * vga_fb_data: Pointer to framebuffer start.
86  * vga_fb_window: Offset of 64k window 0xa0000 in bytes from framebuffer start.
87  *                This value is >= 0, if mode uses linear framebuffer and
88  *                -1, if mode uses color planes. This value is fixed
89  *                in all modes except 0x13 (256 color VGA) where
90  *                0 means normal mode and -1 means Mode-X (unchained mode).
91  */
92 static int   vga_fb_width;
93 static int   vga_fb_height;
94 static int   vga_fb_depth;
95 static int   vga_fb_pitch;
96 static int   vga_fb_offset;
97 static int   vga_fb_size = 0;
98 static char *vga_fb_data = 0;
99 static int   vga_fb_window = 0;
100 static int   vga_fb_window_size;
101 static char *vga_fb_window_data;
102 static PALETTEENTRY *vga_fb_palette;
103 static unsigned vga_fb_palette_index;
104 static unsigned vga_fb_palette_size;
105 static BOOL  vga_fb_bright;
106 static BOOL  vga_fb_enabled;
107
108 /*
109  * VGA text mode data.
110  *
111  * vga_text_attr: Current active attribute.
112  * vga_text_old: Last data sent to console. 
113  *               This is used to optimize console updates.
114  * vga_text_width:  Width of the text display in characters.
115  * vga_text_height: Height of the text display in characters.
116  * vga_text_x: Current cursor X-position. Starts from zero.
117  * vga_text_y: Current cursor Y-position. Starts from zero.
118  * vga_text_console: TRUE if stdout is console, 
119  *                   FALSE if it is regular file.
120  */
121 static BYTE  vga_text_attr;
122 static char *vga_text_old = NULL;
123 static BYTE  vga_text_width;
124 static BYTE  vga_text_height;
125 static BYTE  vga_text_x;
126 static BYTE  vga_text_y;
127 static BOOL  vga_text_console;
128
129 /*
130  * VGA controller ports 0x3c0, 0x3c4, 0x3ce and 0x3d4 are
131  * indexed registers. These ports are used to select VGA controller
132  * subregister that can be written to or read from using ports 0x3c1,
133  * 0x3c5, 0x3cf or 0x3d5. Selected subregister indexes are
134  * stored in variables vga_index_*.
135  *
136  * Port 0x3c0 is special because it is both index and
137  * data-write register. Flip-flop vga_address_3c0 tells whether
138  * the port acts currently as an address register. Reading from port
139  * 0x3da resets the flip-flop to address mode.
140  */
141 static BYTE vga_index_3c0;
142 static BYTE vga_index_3c4;
143 static BYTE vga_index_3ce;
144 static BYTE vga_index_3d4;
145 static BOOL vga_address_3c0 = TRUE;
146
147 /*
148  * List of supported video modes.
149  *
150  * should be expanded to contain most or all information
151  * as required for SVGA VESA mode info block for VESA BIOS subsystem 1 (see _ModeInfoBlock)
152  * this will allow proper support for FIXME items in VGA/VESA mode configuration
153  *
154  * FIXME - verify and define support for VESA modes
155  * FIXME - add # bit planes, # video memory banks, & memory model
156  */
157 static WORD VGA_CurrentMode;
158 static BOOL CGA_ColorComposite = FALSE;  /* behave like composite monitor */
159
160 const VGA_MODE VGA_modelist[] =
161 {
162     /* Mode, ModeType, TextCols, TextRows, CharWidth, CharHeight, Width, Height, Depth, Colors, ScreenPages, Supported*/
163     /* VGA modes */
164     {0x0000,    TEXT, 40, 25,  9, 16,  360,  400,  0,  16, 8, TRUE},   /* VGA/CGA text mode 0 */
165     {0x0001,    TEXT, 40, 25,  9, 16,  360,  400,  0,  16, 8, TRUE},   /* VGA/CGA text mode 1 */
166     {0x0002,    TEXT, 80, 25,  9, 16,  360,  400,  0,  16, 8, TRUE},   /* VGA/CGA text mode 2 */
167     {0x0003,    TEXT, 80, 25,  9, 16,  360,  400,  0,  16, 8, TRUE},   /* VGA/CGA text mode 3 */
168     {0x0004, GRAPHIC, 40, 25,  8,  8,  320,  200,  2,   4, 1, TRUE},   /* VGA/CGA graphics mode 4 */
169     {0x0005, GRAPHIC, 40, 25,  8,  8,  320,  200,  2,   4, 1, TRUE},   /* VGA/CGA graphics mode 5 */
170     {0x0006, GRAPHIC, 80, 25,  8,  8,  640,  200,  1,   2, 1, TRUE},   /* VGA/CGA graphics mode 6 */
171     {0x0007,    TEXT, 80, 25,  9, 16,  720,  400,  0,   0, 8, FALSE},   /* VGA text mode 7 - FIXME bad default address */
172     {0x000d, GRAPHIC, 40, 25,  8,  8,  320,  200,  4,  16, 8, FALSE},   /* VGA graphics mode 13 */
173     {0x000e, GRAPHIC, 80, 25,  8,  8,  640,  200,  4,  16, 4, FALSE},   /* VGA graphics mode 14 */
174     {0x000f, GRAPHIC, 80, 25,  8, 14,  640,  350,  0,   0, 2, FALSE},   /* VGA graphics mode 15 */
175     {0x0010, GRAPHIC, 80, 25,  8, 14,  640,  350,  4,  16, 2, FALSE},   /* VGA graphics mode 16 */
176     {0x0011, GRAPHIC, 80, 30,  8, 16,  640,  480,  1,   2, 1, FALSE},   /* VGA graphics mode 17 */
177     {0x0012, GRAPHIC, 80, 30,  8, 16,  640,  480,  4,  16, 1, FALSE},   /* VGA graphics mode 18 */
178     {0x0013, GRAPHIC, 40, 25,  8,  8,  320,  200,  8, 256, 1, TRUE},   /* VGA graphics mode 19 */
179     /* VESA 7-bit modes */
180     {0x006a, GRAPHIC,  0,  0,  0,  0,  800,  600,  4,  16, 1, TRUE},   /* VESA graphics mode, same as 0x102 */
181     /* VESA 15-bit modes */
182     {0x0100, GRAPHIC,  0,  0,  0,  0,  640,  400,  8, 256, 1, TRUE},   /* VESA graphics mode */
183     {0x0101, GRAPHIC,  0,  0,  0,  0,  640,  480,  8, 256, 1, TRUE},   /* VESA graphics mode */
184     {0x0102, GRAPHIC,  0,  0,  0,  0,  800,  600,  4,  16, 1, TRUE},   /* VESA graphics mode */
185     {0x0103, GRAPHIC,  0,  0,  0,  0,  800,  600,  8, 256, 1, TRUE},   /* VESA graphics mode */
186     {0x0104, GRAPHIC,  0,  0,  0,  0, 1024,  768,  4,  16, 1, TRUE},   /* VESA graphics mode */
187     {0x0105, GRAPHIC,  0,  0,  0,  0, 1024,  768,  8, 256, 1, TRUE},   /* VESA graphics mode */
188     {0x0106, GRAPHIC,  0,  0,  0,  0, 1280, 1024,  4,  16, 1, TRUE},   /* VESA graphics mode */
189     {0x0107, GRAPHIC,  0,  0,  0,  0, 1280, 1024,  8, 256, 1, TRUE},   /* VESA graphics mode */
190     {0x0108,    TEXT,  0,  0,  0,  0,   80,   60,  0,   0, 1, TRUE},   /* VESA text mode */
191     {0x0109,    TEXT,  0,  0,  0,  0,  132,   25,  0,   0, 1, TRUE},   /* VESA text mode */
192     {0x010a,    TEXT,  0,  0,  0,  0,  132,   43,  0,   0, 1, TRUE},   /* VESA text mode */
193     {0x010b,    TEXT,  0,  0,  0,  0,  132,   50,  0,   0, 1, TRUE},   /* VESA text mode */
194     {0x010c,    TEXT,  0,  0,  0,  0,  132,   60,  0,   0, 1, TRUE},   /* VESA text mode */
195     /* VESA 1.2 modes */
196     {0x010d, GRAPHIC,  0,  0,  0,  0,  320,  200, 15,   0, 1, TRUE},   /* VESA graphics mode, 32K colors */
197     {0x010e, GRAPHIC,  0,  0,  0,  0,  320,  200, 16,   0, 1, TRUE},   /* VESA graphics mode, 64K colors */
198     {0x010f, GRAPHIC,  0,  0,  0,  0,  320,  200, 24,   0, 1, TRUE},   /* VESA graphics mode, 16.8 Million colors */
199     {0x0110, GRAPHIC,  0,  0,  0,  0,  640,  480, 15,   0, 1, TRUE},   /* VESA graphics mode, 32K colors */
200     {0x0111, GRAPHIC,  0,  0,  0,  0,  640,  480, 16,   0, 1, TRUE},   /* VESA graphics mode, 64K colors */
201     {0x0112, GRAPHIC,  0,  0,  0,  0,  640,  480, 24,   0, 1, TRUE},   /* VESA graphics mode, 16.8 Million colors */
202     {0x0113, GRAPHIC,  0,  0,  0,  0,  800,  600, 15,   0, 1, TRUE},   /* VESA graphics mode, 32K colors */
203     {0x0114, GRAPHIC,  0,  0,  0,  0,  800,  600, 16,   0, 1, TRUE},   /* VESA graphics mode, 64K colors */
204     {0x0115, GRAPHIC,  0,  0,  0,  0,  800,  600, 24,   0, 1, TRUE},   /* VESA graphics mode, 16.8 Million colors */
205     {0x0116, GRAPHIC,  0,  0,  0,  0, 1024,  768, 15,   0, 1, TRUE},   /* VESA graphics mode, 32K colors */
206     {0x0117, GRAPHIC,  0,  0,  0,  0, 1024,  768, 16,   0, 1, TRUE},   /* VESA graphics mode, 64K colors */
207     {0x0118, GRAPHIC,  0,  0,  0,  0, 1024,  768, 24,   0, 1, TRUE},   /* VESA graphics mode, 16.8 Million colors */
208     {0x0119, GRAPHIC,  0,  0,  0,  0, 1280, 1024, 15,   0, 1, TRUE},   /* VESA graphics mode, 32K colors */
209     {0x011a, GRAPHIC,  0,  0,  0,  0, 1280, 1024, 16,   0, 1, TRUE},   /* VESA graphics mode, 64K colors */
210     {0x011b, GRAPHIC,  0,  0,  0,  0, 1280, 1024, 24,   0, 1, TRUE},   /* VESA graphics mode, 16.8 Million colors */
211     {0xffff,    TEXT,  0,  0,  0,  0,    0,    0,  0,   0, 1, FALSE}
212 };
213
214 /*
215  * This mutex is used to protect VGA state during asynchronous
216  * screen updates (see VGA_Poll). It makes sure that VGA state changes
217  * are atomic and the user interface is protected from flicker and
218  * corruption.
219  *
220  * The mutex actually serializes VGA operations and the screen update. 
221  * Which means that whenever VGA_Poll occurs, application stalls if it 
222  * tries to modify VGA state. This is not how real VGA adapters work,
223  * but it makes timing and correctness issues much easier to deal with.
224  */
225 static CRITICAL_SECTION vga_lock;
226 static CRITICAL_SECTION_DEBUG critsect_debug =
227 {
228     0, 0, &vga_lock,
229     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
230       0, 0, { (DWORD_PTR)(__FILE__ ": vga_lock") }
231 };
232 static CRITICAL_SECTION vga_lock = { &critsect_debug, -1, 0, 0, 0, 0 };
233
234 static void CALLBACK VGA_Poll( LPVOID arg, DWORD low, DWORD high );
235
236 static HWND vga_hwnd = NULL;
237
238 /*
239  * CGA palette 1
240  */
241 static PALETTEENTRY cga_palette1[] = {
242   {0x00, 0x00, 0x00}, /* 0 - Black */
243   {0x00, 0xAA, 0xAA}, /* 1 - Cyan */
244   {0xAA, 0x00, 0xAA}, /* 2 - Magenta */
245   {0xAA, 0xAA, 0xAA}  /* 3 - White */
246 };
247
248 /*
249  * CGA palette 1 in the bright variant
250  * intensities, when signalled to do so
251  * in register 0x3d9
252  */
253 static PALETTEENTRY cga_palette1_bright[] = {
254   {0x00, 0x00, 0x00}, /* 0 - Black */
255   {0x55, 0xFF, 0xFF}, /* 1 - Light cyan */
256   {0xFF, 0x55, 0xFF}, /* 2 - Light magenta */
257   {0xFF, 0xFF, 0xFF}, /* 3 - Bright White */
258 };
259
260 /*
261  * CGA palette 2
262  */
263 static PALETTEENTRY cga_palette2[] = {
264   {0x00, 0x00, 0x00}, /* 0 - Black */
265   {0x00, 0xAA, 0x00}, /* 1 - Green */
266   {0xAA, 0x00, 0x00}, /* 2 - Red */
267   {0xAA, 0x55, 0x00}  /* 3 - Brown */
268 };
269
270 /*
271  * CGA palette 2 in the bright variant
272  * intensities, when signalled to do so
273  * in register 0x3d9
274  */
275 static PALETTEENTRY cga_palette2_bright[] = {
276   {0x00, 0x00, 0x00}, /* 0 - Black */
277   {0x55, 0xFF, 0x55}, /* 1 - Light green */
278   {0xFF, 0x55, 0x55}, /* 2 - Light red */
279   {0xFF, 0xFF, 0x55}, /* 3 - Yellow */
280 };
281
282 /*
283  *  VGA Palette Registers, in actual 16 bit color
284  *  port 3C0H - 6 bit rgbRGB format
285  *
286  *  16 color accesses will use these pointers and insert
287  *  entries from the 64-color palette (mode 18) into the default
288  *  palette.   --Robert 'Admiral' Coeyman
289  */
290 static char vga_16_palette[17]={
291   0x00,  /* 0 - Black         */
292   0x01,  /* 1 - Blue          */
293   0x02,  /* 2 - Green         */
294   0x03,  /* 3 - Cyan          */
295   0x04,  /* 4 - Red           */
296   0x05,  /* 5 - Magenta       */
297   0x14,  /* 6 - Brown         */
298   0x07,  /* 7 - White (Light gray)        */
299   0x38,  /* 8 - Dark gray     */
300   0x39,  /* 9 - Light blue    */
301   0x3a,  /* A - Light green   */
302   0x3b,  /* B - Light cyan    */
303   0x3c,  /* C - Light red     */
304   0x3d,  /* D - Light magenta */
305   0x3e,  /* E - Yellow        */
306   0x3f,  /* F - Bright White (White) */
307   0x00   /* Border Color      */
308 };
309
310 /*
311  *  Mode 19 Default Color Register Setting
312  *  DAC palette registers, converted from actual 18 bit color to 24.
313  */
314 static PALETTEENTRY vga_def_palette[256]={
315 /* red  green  blue */
316   /* 16 colors in IRGB values */
317   {0x00, 0x00, 0x00}, /* 0 (0) - Black */
318   {0x00, 0x00, 0xAA}, /* 1 (1) - Blue */
319   {0x00, 0xAA, 0x00}, /* 2 (2) - Green */
320   {0x00, 0xAA, 0xAA}, /* 3 (3) - Cyan */
321   {0xAA, 0x00, 0x00}, /* 4 (4) - Red */
322   {0xAA, 0x00, 0xAA}, /* 5 (5) - Magenta */
323   {0xAA, 0x55, 0x00}, /* 6 (6) - Brown */
324   {0xAA, 0xAA, 0xAA}, /* 7 (7) - White (Light gray) */
325   {0x55, 0x55, 0x55}, /* 8 (8) - Dark gray */
326   {0x55, 0x55, 0xFF}, /* 9 (9) - Light blue */
327   {0x55, 0xFF, 0x55}, /* 10 (A) - Light green */
328   {0x55, 0xFF, 0xFF}, /* 11 (B) - Light cyan */
329   {0xFF, 0x55, 0x55}, /* 12 (C) - Light red */
330   {0xFF, 0x55, 0xFF}, /* 13 (D) - Light magenta */
331   {0xFF, 0xFF, 0x55}, /* 14 (E) -  Yellow */
332   {0xFF, 0xFF, 0xFF}, /* 15 (F) - Bright White (White) */
333   /* 16 shades of gray */
334   {0x00, 0x00, 0x00}, /* 16 (10) */
335   {0x10, 0x10, 0x10}, /* 17 (11) */
336   {0x20, 0x20, 0x20}, /* 18 (12) */
337   {0x35, 0x35, 0x35}, /* 19 (13) */
338   {0x45, 0x45, 0x45}, /* 20 (14) */
339   {0x55, 0x55, 0x55}, /* 21 (15) */
340   {0x65, 0x65, 0x65}, /* 22 (16) */
341   {0x75, 0x75, 0x75}, /* 23 (17) */
342   {0x8A, 0x8A, 0x8A}, /* 24 (18) */
343   {0x9A, 0x9A, 0x9A}, /* 25 (19) */
344   {0xAA, 0xAA, 0xAA}, /* 26 (1A) */
345   {0xBA, 0xBA, 0xBA}, /* 27 (1B) */
346   {0xCA, 0xCA, 0xCA}, /* 28 (1C) */
347   {0xDF, 0xDF, 0xDF}, /* 29 (1D) */
348   {0xEF, 0xEF, 0xEF}, /* 30 (1E) */
349   {0xFF, 0xFF, 0xFF}, /* 31 (1F) */
350   /* High Intensity group - 72 colors in 1/3 saturation groups (20H-37H high) */
351   {0x00, 0x00, 0xFF}, /* 32 (20) */
352   {0x41, 0x00, 0xFF}, /* 33 (21) */
353   {0x82, 0x00, 0xFF}, /* 34 (22) */
354   {0xBE, 0x00, 0xFF}, /* 35 (23) */
355   {0xFF, 0x00, 0xFF}, /* 36 (24) */
356   {0xFF, 0x00, 0xBE}, /* 37 (25) */
357   {0xFF, 0x00, 0x82}, /* 38 (26) */
358   {0xFF, 0x00, 0x41}, /* 39 (27) */
359   {0xFF, 0x00, 0x00}, /* 40 (28) */
360   {0xFF, 0x41, 0x00}, /* 41 (29) */
361   {0xFF, 0x82, 0x00}, /* 42 (2A) */
362   {0xFF, 0xBE, 0x00}, /* 43 (2B) */
363   {0xFF, 0xFF, 0x00}, /* 44 (2C) */
364   {0xBE, 0xFF, 0x00}, /* 45 (2D) */
365   {0x82, 0xFF, 0x00}, /* 46 (2E) */
366   {0x41, 0xFF, 0x00}, /* 47 (2F) */
367   {0x00, 0xFF, 0x00}, /* 48 (30) */
368   {0x00, 0xFF, 0x41}, /* 49 (31) */
369   {0x00, 0xFF, 0x82}, /* 50 (32) */
370   {0x00, 0xFF, 0xBE}, /* 51 (33) */
371   {0x00, 0xFF, 0xFF}, /* 52 (34) */
372   {0x00, 0xBE, 0xFF}, /* 53 (35) */
373   {0x00, 0x82, 0xFF}, /* 54 (36) */
374   {0x00, 0x41, 0xFF}, /* 55 (37) */
375   /* High Intensity group - 72 colors in 2/3 saturation groups (38H-4FH moderate) */
376   {0x82, 0x82, 0xFF}, /* 56 (38) */
377   {0x9E, 0x82, 0xFF}, /* 57 (39) */
378   {0xBE, 0x82, 0xFF}, /* 58 (3A) */
379   {0xDF, 0x82, 0xFF}, /* 59 (3B) */
380   {0xFF, 0x82, 0xFF}, /* 60 (3C) */
381   {0xFF, 0x82, 0xDF}, /* 61 (3D) */
382   {0xFF, 0x82, 0xBE}, /* 62 (3E) */
383   {0xFF, 0x82, 0x9E}, /* 63 (3F) */
384   {0xFF, 0x82, 0x82}, /* 64 (40) */
385   {0xFF, 0x9E, 0x82}, /* 65 (41) */
386   {0xFF, 0xBE, 0x82}, /* 66 (42) */
387   {0xFF, 0xDF, 0x82}, /* 67 (43) */
388   {0xFF, 0xFF, 0x82}, /* 68 (44) */
389   {0xDF, 0xFF, 0x82}, /* 69 (45) */
390   {0xBE, 0xFF, 0x82}, /* 70 (46) */
391   {0x9E, 0xFF, 0x82}, /* 71 (47) */
392   {0x82, 0xFF, 0x82}, /* 72 (48) */
393   {0x82, 0xFF, 0x9E}, /* 73 (49) */
394   {0x82, 0xFF, 0xBE}, /* 74 (4A) */
395   {0x82, 0xFF, 0xDF}, /* 75 (4B) */
396   {0x82, 0xFF, 0xFF}, /* 76 (4C) */
397   {0x82, 0xDF, 0xFF}, /* 77 (4D) */
398   {0x82, 0xBE, 0xFF}, /* 78 (4E) */
399   {0x82, 0x9E, 0xFF}, /* 79 (4F) */
400   /* High Intensity group - 72 colors in 3/3 saturation groups (50H-67H low) */
401   {0xBA, 0xBA, 0xFF}, /* 80 (50) */
402   {0xCA, 0xBA, 0xFF}, /* 81 (51) */
403   {0xDF, 0xBA, 0xFF}, /* 82 (52) */
404   {0xEF, 0xBA, 0xFF}, /* 83 (53) */
405   {0xFF, 0xBA, 0xFF}, /* 84 (54) */
406   {0xFF, 0xBA, 0xEF}, /* 85 (55) */
407   {0xFF, 0xBA, 0xDF}, /* 86 (56) */
408   {0xFF, 0xBA, 0xCA}, /* 87 (57) */
409   {0xFF, 0xBA, 0xBA}, /* 88 (58) */
410   {0xFF, 0xCA, 0xBA}, /* 89 (59) */
411   {0xFF, 0xDF, 0xBA}, /* 90 (5A) */
412   {0xFF, 0xEF, 0xBA}, /* 91 (5B) */
413   {0xFF, 0xFF, 0xBA}, /* 92 (5C) */
414   {0xEF, 0xFF, 0xBA}, /* 93 (5D) */
415   {0xDF, 0xFF, 0xBA}, /* 94 (5E) */
416   {0xCA, 0xFF, 0xBA}, /* 95 (5F) */
417   {0xBA, 0xFF, 0xBA}, /* 96 (60) */
418   {0xBA, 0xFF, 0xCA}, /* 97 (61) */
419   {0xBA, 0xFF, 0xDF}, /* 98 (62) */
420   {0xBA, 0xFF, 0xEF}, /* 99 (63) */
421   {0xBA, 0xFF, 0xFF}, /* 100 (64) */
422   {0xBA, 0xEF, 0xFF}, /* 101 (65) */
423   {0xBA, 0xDF, 0xFF}, /* 102 (66) */
424   {0xBA, 0xCA, 0xFF}, /* 103 (67) */
425   /* Medium Intensity group - 72 colors in 1/3 saturation groups (68H-7FH high) */
426   {0x00, 0x00, 0x71}, /* 104 (68) */
427   {0x1C, 0x00, 0x71}, /* 105 (69) */
428   {0x39, 0x00, 0x71}, /* 106 (6A) */
429   {0x55, 0x00, 0x71}, /* 107 (6B) */
430   {0x71, 0x00, 0x71}, /* 108 (6C) */
431   {0x71, 0x00, 0x55}, /* 109 (6D) */
432   {0x71, 0x00, 0x39}, /* 110 (6E) */
433   {0x71, 0x00, 0x1C}, /* 111 (6F) */
434   {0x71, 0x00, 0x00}, /* 112 (70) */
435   {0x71, 0x1C, 0x00}, /* 113 (71) */
436   {0x71, 0x39, 0x00}, /* 114 (72) */
437   {0x71, 0x55, 0x00}, /* 115 (73) */
438   {0x71, 0x71, 0x00}, /* 116 (74) */
439   {0x55, 0x71, 0x00}, /* 117 (75) */
440   {0x39, 0x71, 0x00}, /* 118 (76) */
441   {0x1C, 0x71, 0x00}, /* 119 (77) */
442   {0x00, 0x71, 0x00}, /* 120 (78) */
443   {0x00, 0x71, 0x1C}, /* 121 (79) */
444   {0x00, 0x71, 0x39}, /* 122 (7A) */
445   {0x00, 0x71, 0x55}, /* 123 (7B) */
446   {0x00, 0x71, 0x71}, /* 124 (7C) */
447   {0x00, 0x55, 0x71}, /* 125 (7D) */
448   {0x00, 0x39, 0x71}, /* 126 (7E) */
449   {0x00, 0x1C, 0x71}, /* 127 (7F) */
450   /* Medium Intensity group - 72 colors in 2/3 saturation groups (80H-97H moderate) */
451   {0x39, 0x39, 0x71}, /* 128 (80) */
452   {0x45, 0x39, 0x71}, /* 129 (81) */
453   {0x55, 0x39, 0x71}, /* 130 (82) */
454   {0x61, 0x39, 0x71}, /* 131 (83) */
455   {0x71, 0x39, 0x71}, /* 132 (84) */
456   {0x71, 0x39, 0x61}, /* 133 (85) */
457   {0x71, 0x39, 0x55}, /* 134 (86) */
458   {0x71, 0x39, 0x45}, /* 135 (87) */
459   {0x71, 0x39, 0x39}, /* 136 (88) */
460   {0x71, 0x45, 0x39}, /* 137 (89) */
461   {0x71, 0x55, 0x39}, /* 138 (8A) */
462   {0x71, 0x61, 0x39}, /* 139 (8B) */
463   {0x71, 0x71, 0x39}, /* 140 (8C) */
464   {0x61, 0x71, 0x39}, /* 141 (8D) */
465   {0x55, 0x71, 0x39}, /* 142 (8E) */
466   {0x45, 0x71, 0x39}, /* 143 (8F) */
467   {0x39, 0x71, 0x39}, /* 144 (90) */
468   {0x39, 0x71, 0x45}, /* 145 (91) */
469   {0x39, 0x71, 0x55}, /* 146 (92) */
470   {0x39, 0x71, 0x61}, /* 147 (93) */
471   {0x39, 0x71, 0x71}, /* 148 (94) */
472   {0x39, 0x61, 0x71}, /* 149 (95) */
473   {0x39, 0x55, 0x71}, /* 150 (96) */
474   {0x39, 0x45, 0x71}, /* 151 (97) */
475   /* Medium Intensity group - 72 colors in 3/3 saturation groups (98H-AFH low) */
476   {0x51, 0x51, 0x71}, /* 152 (98) */
477   {0x59, 0x51, 0x71}, /* 153 (99) */
478   {0x61, 0x51, 0x71}, /* 154 (9A) */
479   {0x69, 0x51, 0x71}, /* 155 (9B) */
480   {0x71, 0x51, 0x71}, /* 156 (9C) */
481   {0x71, 0x51, 0x69}, /* 157 (9D) */
482   {0x71, 0x51, 0x61}, /* 158 (9E) */
483   {0x71, 0x51, 0x59}, /* 159 (9F) */
484   {0x71, 0x51, 0x51}, /* 160 (A0) */
485   {0x71, 0x59, 0x51}, /* 161 (A1) */
486   {0x71, 0x61, 0x51}, /* 162 (A2) */
487   {0x71, 0x69, 0x51}, /* 163 (A3) */
488   {0x71, 0x71, 0x51}, /* 164 (A4) */
489   {0x69, 0x71, 0x51}, /* 165 (A5) */
490   {0x61, 0x71, 0x51}, /* 166 (A6) */
491   {0x59, 0x71, 0x51}, /* 167 (A7) */
492   {0x51, 0x71, 0x51}, /* 168 (A8) */
493   {0x51, 0x71, 0x59}, /* 169 (A9) */
494   {0x51, 0x71, 0x61}, /* 170 (AA) */
495   {0x51, 0x71, 0x69}, /* 171 (AB) */
496   {0x51, 0x71, 0x71}, /* 172 (AC) */
497   {0x51, 0x69, 0x71}, /* 173 (AD) */
498   {0x51, 0x61, 0x71}, /* 174 (AE) */
499   {0x51, 0x59, 0x71}, /* 175 (AF) */
500   /* Low Intensity group - 72 colors in 1/3 saturation groups (B0H-C7H high) */
501   {0x00, 0x00, 0x41}, /* 176 (B0) */
502   {0x10, 0x00, 0x41}, /* 177 (B1) */
503   {0x20, 0x00, 0x41}, /* 178 (B2) */
504   {0x31, 0x00, 0x41}, /* 179 (B3) */
505   {0x41, 0x00, 0x41}, /* 180 (B4) */
506   {0x41, 0x00, 0x31}, /* 181 (B5) */
507   {0x41, 0x00, 0x20}, /* 182 (B6) */
508   {0x41, 0x00, 0x10}, /* 183 (B7) */
509   {0x41, 0x00, 0x00}, /* 184 (B8) */
510   {0x41, 0x10, 0x00}, /* 185 (B9) */
511   {0x41, 0x20, 0x00}, /* 186 (BA) */
512   {0x41, 0x31, 0x00}, /* 187 (BB) */
513   {0x41, 0x41, 0x00}, /* 188 (BC) */
514   {0x31, 0x41, 0x00}, /* 189 (BD) */
515   {0x20, 0x41, 0x00}, /* 190 (BE) */
516   {0x10, 0x41, 0x00}, /* 191 (BF) */
517   {0x00, 0x41, 0x00}, /* 192 (C0) */
518   {0x00, 0x41, 0x10}, /* 193 (C1) */
519   {0x00, 0x41, 0x20}, /* 194 (C2) */
520   {0x00, 0x41, 0x31}, /* 195 (C3) */
521   {0x00, 0x41, 0x41}, /* 196 (C4) */
522   {0x00, 0x31, 0x41}, /* 197 (C5) */
523   {0x00, 0x20, 0x41}, /* 198 (C6) */
524   {0x00, 0x10, 0x41}, /* 199 (C7) */
525   /* Low Intensity group - 72 colors in 2/3 saturation groups (C8H-DFH moderate) */
526   {0x20, 0x20, 0x41}, /* 200 (C8) */
527   {0x28, 0x20, 0x41}, /* 201 (C9) */
528   {0x31, 0x20, 0x41}, /* 202 (CA) */
529   {0x39, 0x20, 0x41}, /* 203 (CB) */
530   {0x41, 0x20, 0x41}, /* 204 (CC) */
531   {0x41, 0x20, 0x39}, /* 205 (CD) */
532   {0x41, 0x20, 0x31}, /* 206 (CE) */
533   {0x41, 0x20, 0x28}, /* 207 (CF) */
534   {0x41, 0x20, 0x20}, /* 208 (D0) */
535   {0x41, 0x28, 0x20}, /* 209 (D1) */
536   {0x41, 0x31, 0x20}, /* 210 (D2) */
537   {0x41, 0x39, 0x20}, /* 211 (D3) */
538   {0x41, 0x41, 0x20}, /* 212 (D4) */
539   {0x39, 0x41, 0x20}, /* 213 (D5) */
540   {0x31, 0x41, 0x20}, /* 214 (D6) */
541   {0x28, 0x41, 0x20}, /* 215 (D7) */
542   {0x20, 0x41, 0x20}, /* 216 (D8) */
543   {0x20, 0x41, 0x28}, /* 217 (D9) */
544   {0x20, 0x41, 0x31}, /* 218 (DA) */
545   {0x20, 0x41, 0x39}, /* 219 (DB) */
546   {0x20, 0x41, 0x41}, /* 220 (DC) */
547   {0x20, 0x39, 0x41}, /* 221 (DD) */
548   {0x20, 0x31, 0x41}, /* 222 (DE) */
549   {0x20, 0x28, 0x41}, /* 223 (DF) */
550   /* Low Intensity group - 72 colors in 3/3 saturation groups (E0H-F7H low) */
551   {0x2D, 0x2D, 0x41}, /* 223 (E0) */
552   {0x31, 0x2D, 0x41}, /* 224 (E1) */
553   {0x35, 0x2D, 0x41}, /* 225 (E2) */
554   {0x3D, 0x2D, 0x41}, /* 226 (E3) */
555   {0x41, 0x2D, 0x41}, /* 227 (E4) */
556   {0x41, 0x2D, 0x3D}, /* 228 (E5) */
557   {0x41, 0x2D, 0x35}, /* 229 (E6) */
558   {0x41, 0x2D, 0x31}, /* 230 (E7) */
559   {0x41, 0x2D, 0x2D}, /* 231 (E8) */
560   {0x41, 0x31, 0x2D}, /* 232 (E9) */
561   {0x41, 0x35, 0x2D}, /* 233 (EA) */
562   {0x41, 0x3D, 0x2D}, /* 234 (EB) */
563   {0x41, 0x41, 0x2D}, /* 235 (EC) */
564   {0x3D, 0x41, 0x2D}, /* 236 (ED) */
565   {0x35, 0x41, 0x2D}, /* 237 (EE) */
566   {0x31, 0x41, 0x2D}, /* 238 (EF) */
567   {0x2D, 0x41, 0x2D}, /* 239 (F0) */
568   {0x2D, 0x41, 0x31}, /* 240 (F1) */
569   {0x2D, 0x41, 0x35}, /* 241 (F2) */
570   {0x2D, 0x41, 0x3D}, /* 242 (F3) */
571   {0x2D, 0x41, 0x41}, /* 243 (F4) */
572   {0x2D, 0x3D, 0x41}, /* 244 (F5) */
573   {0x2D, 0x35, 0x41}, /* 245 (F6) */
574   {0x2D, 0x31, 0x41}, /* 246 (F7) */
575   /* Fill up remainder of palettes with black */
576   {0,0,0}
577 };
578
579 /*
580  *  Mode 18 Default Color Register Setting
581  *  DAC palette registers, converted from actual 18 bit color to 24.
582  *
583  *  This palette is the dos default, converted from 18 bit color to 24.
584  *  It contains only 64 entries of colors--all others are zeros.
585  *      --Robert 'Admiral' Coeyman
586  */
587 static PALETTEENTRY vga_def64_palette[256]={
588 /* red  green  blue */
589   {0x00, 0x00, 0x00}, /* 0x00      Black      */
590   {0x00, 0x00, 0xaa}, /* 0x01      Blue       */
591   {0x00, 0xaa, 0x00}, /* 0x02      Green      */
592   {0x00, 0xaa, 0xaa}, /* 0x03      Cyan       */
593   {0xaa, 0x00, 0x00}, /* 0x04      Red        */
594   {0xaa, 0x00, 0xaa}, /* 0x05      Magenta    */
595   {0xaa, 0xaa, 0x00}, /* 0x06      */
596   {0xaa, 0xaa, 0xaa}, /* 0x07      White (Light Gray) */
597   {0x00, 0x00, 0x55}, /* 0x08      */
598   {0x00, 0x00, 0xff}, /* 0x09      */
599   {0x00, 0xaa, 0x55}, /* 0x0a      */
600   {0x00, 0xaa, 0xff}, /* 0x0b      */
601   {0xaa, 0x00, 0x55}, /* 0x0c      */
602   {0xaa, 0x00, 0xff}, /* 0x0d      */
603   {0xaa, 0xaa, 0x55}, /* 0x0e      */
604   {0xaa, 0xaa, 0xff}, /* 0x0f      */
605   {0x00, 0x55, 0x00}, /* 0x10      */
606   {0x00, 0x55, 0xaa}, /* 0x11      */
607   {0x00, 0xff, 0x00}, /* 0x12      */
608   {0x00, 0xff, 0xaa}, /* 0x13      */
609   {0xaa, 0x55, 0x00}, /* 0x14      Brown      */
610   {0xaa, 0x55, 0xaa}, /* 0x15      */
611   {0xaa, 0xff, 0x00}, /* 0x16      */
612   {0xaa, 0xff, 0xaa}, /* 0x17      */
613   {0x00, 0x55, 0x55}, /* 0x18      */
614   {0x00, 0x55, 0xff}, /* 0x19      */
615   {0x00, 0xff, 0x55}, /* 0x1a      */
616   {0x00, 0xff, 0xff}, /* 0x1b      */
617   {0xaa, 0x55, 0x55}, /* 0x1c      */
618   {0xaa, 0x55, 0xff}, /* 0x1d      */
619   {0xaa, 0xff, 0x55}, /* 0x1e      */
620   {0xaa, 0xff, 0xff}, /* 0x1f      */
621   {0x55, 0x00, 0x00}, /* 0x20      */
622   {0x55, 0x00, 0xaa}, /* 0x21      */
623   {0x55, 0xaa, 0x00}, /* 0x22      */
624   {0x55, 0xaa, 0xaa}, /* 0x23      */
625   {0xff, 0x00, 0x00}, /* 0x24      */
626   {0xff, 0x00, 0xaa}, /* 0x25      */
627   {0xff, 0xaa, 0x00}, /* 0x26      */
628   {0xff, 0xaa, 0xaa}, /* 0x27      */
629   {0x55, 0x00, 0x55}, /* 0x28      */
630   {0x55, 0x00, 0xff}, /* 0x29      */
631   {0x55, 0xaa, 0x55}, /* 0x2a      */
632   {0x55, 0xaa, 0xff}, /* 0x2b      */
633   {0xff, 0x00, 0x55}, /* 0x2c      */
634   {0xff, 0x00, 0xff}, /* 0x2d      */
635   {0xff, 0xaa, 0x55}, /* 0x2e      */
636   {0xff, 0xaa, 0xff}, /* 0x2f      */
637   {0x55, 0x55, 0x00}, /* 0x30      */
638   {0x55, 0x55, 0xaa}, /* 0x31      */
639   {0x55, 0xff, 0x00}, /* 0x32      */
640   {0x55, 0xff, 0xaa}, /* 0x33      */
641   {0xff, 0x55, 0x00}, /* 0x34      */
642   {0xff, 0x55, 0xaa}, /* 0x35      */
643   {0xff, 0xff, 0x00}, /* 0x36      */
644   {0xff, 0xff, 0xaa}, /* 0x37      */
645   {0x55, 0x55, 0x55}, /* 0x38      Dark Gray     */
646   {0x55, 0x55, 0xff}, /* 0x39      Light Blue    */
647   {0x55, 0xff, 0x55}, /* 0x3a      Light Green   */
648   {0x55, 0xff, 0xff}, /* 0x3b      Light Cyan    */
649   {0xff, 0x55, 0x55}, /* 0x3c      Light Red     */
650   {0xff, 0x55, 0xff}, /* 0x3d      Light Magenta */
651   {0xff, 0xff, 0x55}, /* 0x3e      Yellow        */
652   {0xff, 0xff, 0xff}, /* 0x3f      White         */
653   {0,0,0} /* The next 192 entries are all zeros  */
654 };
655
656 static HANDLE VGA_timer;
657 static HANDLE VGA_timer_thread;
658
659 /* set the timer rate; called in the polling thread context */
660 static void CALLBACK set_timer_rate( ULONG_PTR arg )
661 {
662     LARGE_INTEGER when;
663
664     when.u.LowPart = when.u.HighPart = 0;
665     SetWaitableTimer( VGA_timer, &when, arg, VGA_Poll, 0, FALSE );
666 }
667
668 static DWORD CALLBACK VGA_TimerThread( void *dummy )
669 {
670     for (;;) SleepEx( INFINITE, TRUE );
671     return 0;
672 }
673
674 static void VGA_DeinstallTimer(void)
675 {
676     if (VGA_timer_thread)
677     {
678         /*
679          * Make sure the update thread is not holding
680          * system resources when we kill it.
681          *
682          * Now, we only need to worry about update thread
683          * getting terminated while in EnterCriticalSection 
684          * or WaitForMultipleObjectsEx.
685          *
686          * FIXME: Is this a problem?
687          */
688         EnterCriticalSection(&vga_lock);
689
690         CancelWaitableTimer( VGA_timer );
691         CloseHandle( VGA_timer );
692         TerminateThread( VGA_timer_thread, 0 );
693         CloseHandle( VGA_timer_thread );
694         VGA_timer_thread = 0;
695
696         LeaveCriticalSection(&vga_lock);
697
698         /*
699          * Synchronize display. This makes sure that
700          * changes to display become visible even if program 
701          * terminates before update thread had time to run.
702          */
703         VGA_Poll( 0, 0, 0 );
704     }
705 }
706
707 static void VGA_InstallTimer(unsigned Rate)
708 {
709     if (!VGA_timer_thread)
710     {
711         VGA_timer = CreateWaitableTimerA( NULL, FALSE, NULL );
712         VGA_timer_thread = CreateThread( NULL, 0, VGA_TimerThread, NULL, 0, NULL );
713     }
714     QueueUserAPC( set_timer_rate, VGA_timer_thread, (ULONG_PTR)Rate );
715 }
716
717 static BOOL VGA_IsTimerRunning(void)
718 {
719     return VGA_timer_thread ? TRUE : FALSE;
720 }
721
722 static HANDLE VGA_AlphaConsole(void)
723 {
724     /* this assumes that no Win32 redirection has taken place, but then again,
725      * only 16-bit apps are likely to use this part of Wine... */
726     return GetStdHandle(STD_OUTPUT_HANDLE);
727 }
728
729 static char*VGA_AlphaBuffer(void)
730 {
731     return (char *)0xb8000;
732 }
733
734 /*** GRAPHICS MODE ***/
735
736 typedef struct {
737   unsigned Xres, Yres, Depth;
738   int ret;
739 } ModeSet;
740
741
742 /**********************************************************************
743  *         VGA_SyncWindow
744  *
745  * Copy VGA window into framebuffer (if argument is TRUE) or
746  * part of framebuffer into VGA window (if argument is FALSE).
747  */
748 static void VGA_SyncWindow( BOOL target_is_fb )
749 {
750     int size = vga_fb_window_size;
751
752     /* Window does not overlap framebuffer. */
753     if (vga_fb_window >= vga_fb_size)
754         return;
755
756     /* Check if window overlaps framebuffer only partially. */
757     if (vga_fb_size - vga_fb_window < vga_fb_window_size)
758         size = vga_fb_size - vga_fb_window;
759
760     if (target_is_fb)
761         memmove( vga_fb_data + vga_fb_window, vga_fb_window_data, size );
762     else
763         memmove( vga_fb_window_data, vga_fb_data + vga_fb_window, size );
764 }
765
766
767 static void WINAPI VGA_DoExit(ULONG_PTR arg)
768 {
769     VGA_DeinstallTimer();
770     IDirectDrawSurface_SetPalette(lpddsurf,NULL);
771     IDirectDrawSurface_Release(lpddsurf);
772     lpddsurf=NULL;
773     IDirectDrawPalette_Release(lpddpal);
774     lpddpal=NULL;
775     IDirectDraw_Release(lpddraw);
776     lpddraw=NULL;
777 }
778
779 static void WINAPI VGA_DoSetMode(ULONG_PTR arg)
780 {
781     HRESULT     res;
782     ModeSet *par = (ModeSet *)arg;
783     par->ret=1;
784
785     if (lpddraw) VGA_DoExit(0);
786     if (!lpddraw) {
787         res = DirectDrawCreate(NULL,&lpddraw,NULL);
788         if (!lpddraw) {
789             ERR("DirectDraw is not available (res = 0x%x)\n",res);
790             return;
791         }
792         if (!vga_hwnd) {
793             vga_hwnd = CreateWindowExA(0,"STATIC","WINEDOS VGA",
794                                        WS_POPUP|WS_VISIBLE|SS_NOTIFY,0,0,
795                                        par->Xres,par->Yres,0,0,0,NULL);
796             if (!vga_hwnd) {
797                 ERR("Failed to create user window.\n");
798                 IDirectDraw_Release(lpddraw);
799                 lpddraw=NULL;
800                 return;
801             }
802         }
803         else
804             SetWindowPos(vga_hwnd,0,0,0,par->Xres,par->Yres,SWP_NOMOVE|SWP_NOZORDER);
805
806         res=IDirectDraw_SetCooperativeLevel(lpddraw,vga_hwnd,DDSCL_FULLSCREEN|DDSCL_EXCLUSIVE);
807         if (res != S_OK) {
808             ERR("Could not set cooperative level to exclusive (0x%x)\n",res);
809         }
810
811         res=IDirectDraw_SetDisplayMode(lpddraw,par->Xres,par->Yres,par->Depth);
812         if (res != S_OK) {
813             ERR("DirectDraw does not support requested display mode (%dx%dx%d), res = 0x%x!\n",par->Xres,par->Yres,par->Depth,res);
814             IDirectDraw_Release(lpddraw);
815             lpddraw=NULL;
816             return;
817         }
818
819         res=IDirectDraw_CreatePalette(lpddraw,DDPCAPS_8BIT,NULL,&lpddpal,NULL);
820         if (res != S_OK) {
821             ERR("Could not create palette (res = 0x%x)\n",res);
822             IDirectDraw_Release(lpddraw);
823             lpddraw=NULL;
824             return;
825         }
826
827         res=IDirectDrawPalette_SetEntries(lpddpal,0,0,vga_fb_palette_size,vga_fb_palette);
828         if (res != S_OK) {
829            ERR("Could not set default palette entries (res = 0x%x)\n", res);
830         }
831
832         memset(&sdesc,0,sizeof(sdesc));
833         sdesc.dwSize=sizeof(sdesc);
834         sdesc.dwFlags = DDSD_CAPS;
835         sdesc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
836         res=IDirectDraw_CreateSurface(lpddraw,&sdesc,&lpddsurf,NULL);
837         if (res != S_OK || !lpddsurf) {
838             ERR("DirectDraw surface is not available\n");
839             IDirectDraw_Release(lpddraw);
840             lpddraw=NULL;
841             return;
842         }
843         IDirectDrawSurface_SetPalette(lpddsurf,lpddpal);
844         vga_retrace_vertical = vga_retrace_horizontal = FALSE;
845         /* poll every 20ms (50fps should provide adequate responsiveness) */
846         VGA_InstallTimer(20);
847     }
848     par->ret=0;
849     return;
850 }
851
852 /**********************************************************************\
853 * VGA_GetModeInfo
854 *
855 * Returns mode information, given mode number
856 \**********************************************************************/
857 const VGA_MODE *VGA_GetModeInfo(WORD mode)
858 {
859     const VGA_MODE *ModeInfo = VGA_modelist;
860
861     /*
862      * Filter out flags.
863      */
864     mode &= 0x17f;
865
866     while (ModeInfo->Mode != 0xffff)
867     {
868         if (ModeInfo->Mode == mode)
869             return ModeInfo;
870         ModeInfo++;
871     }
872     return NULL;
873 }
874
875 static int VGA_SetGraphicMode(WORD mode)
876 {
877     ModeSet par;
878     int     newSize;
879
880     /* get info on VGA mode & set appropriately */
881     const VGA_MODE *ModeInfo = VGA_GetModeInfo(VGA_CurrentMode);
882     /* check if we're assuming composite display */
883     if ((mode == 6) && (CGA_ColorComposite))
884     {
885        vga_fb_width = (ModeInfo->Width / 4);
886        vga_fb_height = ModeInfo->Height;
887        vga_fb_depth = (ModeInfo->Depth * 4);
888     }
889     else
890     {
891        vga_fb_width = ModeInfo->Width;
892        vga_fb_height = ModeInfo->Height;
893        vga_fb_depth = ModeInfo->Depth;
894     }
895     vga_fb_offset = 0;
896     vga_fb_pitch = vga_fb_width * ((vga_fb_depth + 7) / 8);
897
898     newSize = vga_fb_width * vga_fb_height * ((vga_fb_depth + 7) / 8);
899     if(newSize < 256 * 1024)
900       newSize = 256 * 1024;
901
902     if(vga_fb_size < newSize) {
903       HeapFree(GetProcessHeap(), 0, vga_fb_data);
904       vga_fb_data = HeapAlloc(GetProcessHeap(), 0, newSize);
905       vga_fb_size = newSize;
906     }
907
908     if(vga_fb_width >= 640 || vga_fb_height >= 480) {
909       par.Xres = vga_fb_width;
910       par.Yres = vga_fb_height;
911     } else {
912       par.Xres = 640;
913       par.Yres = 480;
914     }
915
916     /* Setup window */
917     if(vga_fb_depth >= 8)
918     {
919       vga_fb_window_data = VGA_WINDOW_START;
920       vga_fb_window_size = VGA_WINDOW_SIZE;
921       vga_fb_palette = vga_def_palette;
922       vga_fb_palette_size = 256;
923     }
924     else
925     {
926       vga_fb_window_data = CGA_WINDOW_START;
927       vga_fb_window_size = CGA_WINDOW_SIZE;
928       if(vga_fb_depth == 2)
929       {
930         /* Select default 2 bit CGA palette */
931         vga_fb_palette = cga_palette1;
932         vga_fb_palette_size = 4;
933       }
934       else
935       {
936         /* Top of VGA palette is same as 4 bit CGA palette */
937         vga_fb_palette = vga_def_palette;
938         vga_fb_palette_size = 16;
939       }
940
941       vga_fb_palette_index = 0;
942       vga_fb_bright = 0;
943     }
944
945     /* Clean the HW buffer */
946     memset(vga_fb_window_data, 0x00, vga_fb_window_size);
947
948     /* Reset window start */
949     VGA_SetWindowStart(0);
950
951     par.Depth = (vga_fb_depth < 8) ? 8 : vga_fb_depth;
952
953     MZ_RunInThread(VGA_DoSetMode, (ULONG_PTR)&par);
954     return par.ret;
955 }
956
957 int VGA_SetMode(WORD mode)
958 {
959     const VGA_MODE *ModeInfo;
960     /* get info on VGA mode & set appropriately */
961     VGA_CurrentMode = mode;
962     ModeInfo = VGA_GetModeInfo(VGA_CurrentMode);
963
964     /* check if mode is supported */
965     if (ModeInfo->Supported)
966     {
967        FIXME("Setting VGA mode %i - Supported mode - Improve reporting of missing capabilities for modes & modetypes.\n", mode);
968     }
969     else
970     {
971        FIXME("Setting VGA mode %i - Unsupported mode - Will doubtfully work at all, but we'll try anyways.\n", mode);
972     }
973
974     /* set up graphic or text display */
975     if (ModeInfo->ModeType == TEXT)
976     {
977        VGA_SetAlphaMode(ModeInfo->TextCols, ModeInfo->TextRows);
978     }
979     else
980     {
981        return VGA_SetGraphicMode(mode);
982     }
983     return 0; /* assume all good & return zero */
984 }
985
986 int VGA_GetMode(unsigned*Height,unsigned*Width,unsigned*Depth)
987 {
988     if (!lpddraw) return 1;
989     if (!lpddsurf) return 1;
990     if (Height) *Height=sdesc.dwHeight;
991     if (Width) *Width=sdesc.dwWidth;
992     if (Depth) *Depth=sdesc.ddpfPixelFormat.u1.dwRGBBitCount;
993     return 0;
994 }
995
996 static void VGA_Exit(void)
997 {
998     if (lpddraw) MZ_RunInThread(VGA_DoExit, 0);
999 }
1000
1001 void VGA_SetPalette(PALETTEENTRY*pal,int start,int len)
1002 {
1003     if (!lpddraw) return;
1004     IDirectDrawPalette_SetEntries(lpddpal,0,start,len,pal);
1005 }
1006
1007 /* set a single [char wide] color in 16 color mode. */
1008 void VGA_SetColor16(int reg,int color)
1009 {
1010         PALETTEENTRY *pal;
1011
1012     if (!lpddraw) return;
1013         pal= &vga_def64_palette[color];
1014         IDirectDrawPalette_SetEntries(lpddpal,0,reg,1,pal);
1015         vga_16_palette[reg]=(char)color;
1016 }
1017
1018 /* Get a single [char wide] color in 16 color mode. */
1019 char VGA_GetColor16(int reg)
1020 {
1021
1022     if (!lpddraw) return 0;
1023         return vga_16_palette[reg];
1024 }
1025
1026 /* set all 17 [char wide] colors at once in 16 color mode. */
1027 void VGA_Set16Palette(char *Table)
1028 {
1029         PALETTEENTRY *pal;
1030         int c;
1031
1032     if (!lpddraw) return;         /* return if we're in text only mode */
1033     memcpy( Table, vga_16_palette, 17 ); /* copy the entries into the table */
1034
1035     for (c=0; c<17; c++) {                                /* 17 entries */
1036         pal= &vga_def64_palette[(int)vga_16_palette[c]];  /* get color  */
1037         IDirectDrawPalette_SetEntries(lpddpal,0,c,1,pal); /* set entry  */
1038         TRACE("Palette register %d set to %d\n",c,(int)vga_16_palette[c]);
1039    } /* end of the counting loop */
1040 }
1041
1042 /* Get all 17 [ char wide ] colors at once in 16 color mode. */
1043 void VGA_Get16Palette(char *Table)
1044 {
1045
1046     if (!lpddraw) return;         /* return if we're in text only mode */
1047     memcpy( vga_16_palette, Table, 17 ); /* copy the entries into the table */
1048 }
1049
1050 static LPSTR VGA_Lock(unsigned*Pitch,unsigned*Height,unsigned*Width,unsigned*Depth)
1051 {
1052     if (!lpddraw) return NULL;
1053     if (!lpddsurf) return NULL;
1054     if (IDirectDrawSurface_Lock(lpddsurf,NULL,&sdesc,0,0) != S_OK) {
1055         ERR("could not lock surface!\n");
1056         return NULL;
1057     }
1058     if (Pitch) *Pitch=sdesc.u1.lPitch;
1059     if (Height) *Height=sdesc.dwHeight;
1060     if (Width) *Width=sdesc.dwWidth;
1061     if (Depth) *Depth=sdesc.ddpfPixelFormat.u1.dwRGBBitCount;
1062     return sdesc.lpSurface;
1063 }
1064
1065 static void VGA_Unlock(void)
1066 {
1067     IDirectDrawSurface_Unlock(lpddsurf,sdesc.lpSurface);
1068 }
1069
1070 /*
1071  * Set start of 64k window at 0xa0000 in bytes.
1072  * If value is -1, initialize color plane support.
1073  * If value is >= 0, window contains direct copy of framebuffer.
1074  */
1075 void VGA_SetWindowStart(int start)
1076 {
1077     if(start == vga_fb_window)
1078         return;
1079
1080     EnterCriticalSection(&vga_lock);
1081
1082     if(vga_fb_window == -1)
1083         FIXME("Remove VGA memory emulation.\n");
1084     else
1085         VGA_SyncWindow( TRUE );
1086
1087     vga_fb_window = start;
1088
1089     if(vga_fb_window == -1)
1090         FIXME("Install VGA memory emulation.\n");
1091     else
1092         VGA_SyncWindow( FALSE );
1093
1094     LeaveCriticalSection(&vga_lock);
1095 }
1096
1097 /*
1098  * Get start of 64k window at 0xa0000 in bytes.
1099  * Value is -1 in color plane modes.
1100  */
1101 int VGA_GetWindowStart(void)
1102 {
1103     return vga_fb_window;
1104 }
1105
1106
1107 /**********************************************************************
1108  *         VGA_DoShowMouse
1109  *
1110  * Callback for VGA_ShowMouse.
1111  */
1112 static void WINAPI VGA_DoShowMouse( ULONG_PTR show )
1113 {
1114     INT rv;
1115
1116     do
1117     {
1118         rv = ShowCursor( show );
1119     }
1120     while( show ? (rv < 0) : (rv >= 0) );
1121 }
1122
1123
1124 /**********************************************************************
1125  *         VGA_ShowMouse
1126  *
1127  * If argument is TRUE, unconditionally show mouse cursor.
1128  * If argument is FALSE, unconditionally hide mouse cursor.
1129  * This only works in graphics mode.
1130  */
1131 void VGA_ShowMouse( BOOL show )
1132 {
1133     if (lpddraw)
1134         MZ_RunInThread( VGA_DoShowMouse, (ULONG_PTR)show );
1135 }
1136
1137
1138 /**********************************************************************
1139  *         VGA_UpdatePalette
1140  *
1141  * Update the current palette
1142  *
1143  * Note: When updating the current CGA palette, palette index 0
1144  * refers to palette2, and index 1 is palette1 (default palette)
1145  */
1146 void VGA_UpdatePalette(void)
1147 {
1148   /* Figure out which palette is used now */
1149   if(vga_fb_bright)
1150   {
1151     if(vga_fb_palette_index == 0)
1152     {
1153       vga_fb_palette = cga_palette2_bright;
1154     }
1155     else if(vga_fb_palette_index == 1)
1156     {
1157       vga_fb_palette = cga_palette1_bright;
1158     }
1159   }
1160   else
1161   {
1162     if(vga_fb_palette_index == 0)
1163     {
1164       vga_fb_palette = cga_palette2;
1165     }
1166     else if(vga_fb_palette_index == 1)
1167     {
1168       vga_fb_palette = cga_palette1;
1169     }
1170   }
1171
1172   /* Now update the palette */
1173   VGA_SetPalette(vga_fb_palette,0,4);
1174 }
1175
1176 /**********************************************************************
1177  *         VGA_SetBright
1178  *
1179  * Select if using a "bright" palette or not.
1180  * This is a property of the CGA controller
1181  */
1182 void VGA_SetBright(BOOL bright)
1183 {
1184   TRACE("%i\n", bright);
1185
1186   /* Remember the "bright" value used by the CGA controller */
1187   vga_fb_bright = bright;
1188 }
1189
1190 /**********************************************************************
1191  *         VGA_SetEnabled
1192  *
1193  * Select if output is enabled or disabled
1194  * This is a property of the CGA controller
1195  */
1196 static void VGA_SetEnabled(BOOL enabled)
1197 {
1198   TRACE("%i\n", enabled);
1199
1200   /* Check if going from enabled to disabled */
1201   if(vga_fb_enabled && !enabled)
1202   {
1203     /* Clear frame buffer */
1204     memset(vga_fb_window_data, 0x00, vga_fb_window_size);
1205   }
1206
1207   /* Remember the "enabled" value */
1208   vga_fb_enabled = enabled;
1209 }
1210
1211 /**********************************************************************
1212  *         VGA_SetPaletteIndex
1213  *
1214  * Select the index of the palette which is currently in use
1215  * This is a property of the CGA controller
1216  */
1217 void VGA_SetPaletteIndex(unsigned index)
1218 {
1219   TRACE("%i\n", index);
1220
1221   /* Remember the palette index, which is only used by CGA for now */
1222   vga_fb_palette_index = index;
1223 }
1224
1225 /**********************************************************************
1226  *         VGA_WritePixel
1227  *
1228  * Write data to the framebuffer
1229  * This is a property of the CGA controller, but might be supported
1230  * later by other framebuffer types
1231  */
1232 void VGA_WritePixel(unsigned color, unsigned page, unsigned col, unsigned row)
1233 {
1234   int off;
1235   int bits;
1236   int pos;
1237
1238   /* Calculate CGA byte offset */
1239   char *data = vga_fb_window_data;
1240   off = row & 1 ? (8 * 1024) : 0;
1241   off += (80 * (row/2));
1242   off += col/4;
1243
1244   /* Calculate bits offset */
1245   pos = 6 - (col%4 * 2);
1246
1247   /* Clear current data */
1248   bits = 0x03 << pos;
1249   data[off] &= ~bits;
1250
1251   /* Set new data */
1252   bits = color << pos;
1253   data[off] |= bits;
1254 }
1255
1256 /*** TEXT MODE ***/
1257
1258 /* prepare the text mode video memory copy that is used to only
1259  * update the video memory line that did get updated. */
1260 static void VGA_PrepareVideoMemCopy(unsigned Xres, unsigned Yres)
1261 {
1262     char *p, *p2;
1263     unsigned int i;
1264
1265     /*
1266      * Allocate space for char + attr.
1267      */
1268
1269     if (vga_text_old)
1270         vga_text_old = HeapReAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 
1271                                 vga_text_old, Xres * Yres * 2 );
1272     else
1273         vga_text_old = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 
1274                                  Xres * Yres * 2 );
1275     p = VGA_AlphaBuffer();
1276     p2 = vga_text_old;
1277
1278     /* make sure the video mem copy contains the exact opposite of our
1279      * actual text mode memory area to make sure the screen
1280      * does get updated fully initially */
1281     for (i=0; i < Xres*Yres*2; i++)
1282         *p2++ = *p++ ^ 0xff; /* XOR it */
1283 }
1284
1285 /**********************************************************************
1286  *         VGA_SetAlphaMode
1287  *
1288  * Set VGA emulation to text mode.
1289  */
1290 void VGA_SetAlphaMode(unsigned Xres,unsigned Yres)
1291 {
1292     VGA_Exit();
1293     VGA_DeinstallTimer();
1294     
1295     VGA_PrepareVideoMemCopy(Xres, Yres);
1296     vga_text_width = Xres;
1297     vga_text_height = Yres;
1298
1299     if (vga_text_x >= vga_text_width || vga_text_y >= vga_text_height)
1300         VGA_SetCursorPos(0,0);
1301
1302     if(vga_text_console) {
1303         COORD size;
1304         size.X = Xres;
1305         size.Y = Yres;
1306         SetConsoleScreenBufferSize( VGA_AlphaConsole(), size );
1307
1308         /* poll every 30ms (33fps should provide adequate responsiveness) */
1309         VGA_InstallTimer(30);
1310     }
1311 }
1312
1313 /**********************************************************************
1314  *         VGA_InitAlphaMode
1315  *
1316  * Initialize VGA text mode handling and return default text mode.
1317  * This function does not set VGA emulation to text mode.
1318  */
1319 void VGA_InitAlphaMode(unsigned*Xres,unsigned*Yres)
1320 {
1321     CONSOLE_SCREEN_BUFFER_INFO info;
1322
1323     if(GetConsoleScreenBufferInfo( VGA_AlphaConsole(), &info ))
1324     {
1325         vga_text_console = TRUE;
1326         vga_text_x = info.dwCursorPosition.X;
1327         vga_text_y = info.dwCursorPosition.Y;
1328         vga_text_attr = info.wAttributes;
1329         *Xres = info.dwSize.X;
1330         *Yres = info.dwSize.Y;
1331     } 
1332     else
1333     {
1334         vga_text_console = FALSE;
1335         vga_text_x = 0;
1336         vga_text_y = 0;
1337         vga_text_attr = 0x0f;
1338         *Xres = 80;
1339         *Yres = 25;
1340     }
1341 }
1342
1343 /**********************************************************************
1344  *         VGA_GetAlphaMode
1345  *
1346  * Get current text mode. Returns TRUE and sets resolution if
1347  * any VGA text mode has been initialized.
1348  */
1349 BOOL VGA_GetAlphaMode(unsigned*Xres,unsigned*Yres)
1350 {
1351     if (vga_text_width != 0 && vga_text_height != 0) {
1352         *Xres = vga_text_width;
1353         *Yres = vga_text_height;
1354         return TRUE;
1355     } else
1356         return FALSE;
1357 }
1358
1359 void VGA_SetCursorShape(unsigned char start_options, unsigned char end)
1360 {
1361     CONSOLE_CURSOR_INFO cci;
1362
1363     /* standard cursor settings:
1364      * 0x0607 == CGA, 0x0b0c == monochrome, 0x0d0e == EGA/VGA */
1365
1366     /* calculate percentage from bottom - assuming VGA (bottom 0x0e) */
1367     cci.dwSize = ((end & 0x1f) - (start_options & 0x1f))/0x0e * 100;
1368     if (!cci.dwSize) cci.dwSize++; /* NULL cursor would make SCCI() fail ! */
1369     cci.bVisible = ((start_options & 0x60) != 0x20); /* invisible ? */
1370
1371     SetConsoleCursorInfo(VGA_AlphaConsole(),&cci);
1372 }
1373
1374 void VGA_SetCursorPos(unsigned X,unsigned Y)
1375 {
1376     vga_text_x = X;
1377     vga_text_y = Y;
1378 }
1379
1380 void VGA_GetCursorPos(unsigned*X,unsigned*Y)
1381 {
1382     if (X) *X = vga_text_x;
1383     if (Y) *Y = vga_text_y;
1384 }
1385
1386 static void VGA_PutCharAt(unsigned x, unsigned y, BYTE ascii, int attr)
1387 {
1388     const VGA_MODE *ModeInfo = VGA_GetModeInfo(VGA_CurrentMode);
1389     if ( ModeInfo->ModeType == TEXT )
1390     {
1391        char *dat = VGA_AlphaBuffer() + ((vga_text_width * y + x) * 2);
1392        dat[0] = ascii;
1393        if (attr>=0)
1394           dat[1] = attr;
1395     }
1396     else
1397     {
1398        FIXME("Write %c at (%i,%i) - not yet supported in graphic modes.\n", (char)ascii, x, y);
1399     }
1400 }
1401
1402 void VGA_WriteChars(unsigned X,unsigned Y,unsigned ch,int attr,int count)
1403 {
1404     EnterCriticalSection(&vga_lock);
1405
1406     while (count--) 
1407         VGA_PutCharAt(X + count, Y, ch, attr);
1408
1409     LeaveCriticalSection(&vga_lock);
1410 }
1411
1412 void VGA_PutChar(BYTE ascii)
1413 {
1414     DWORD w;
1415
1416     EnterCriticalSection(&vga_lock);
1417
1418     switch(ascii) {
1419     case '\b':
1420         if (vga_text_x)
1421         {
1422             vga_text_x--;
1423             VGA_PutCharAt(vga_text_x, vga_text_y, ' ', 0);
1424         }
1425         break;
1426
1427     case '\t':
1428         vga_text_x += ((vga_text_x + 8) & ~7) - vga_text_x;
1429         break;
1430
1431     case '\n':
1432         vga_text_y++;
1433         vga_text_x = 0;
1434         break;
1435
1436     case '\a':
1437         break;
1438
1439     case '\r':
1440         vga_text_x = 0;
1441         break;
1442
1443     default:
1444         VGA_PutCharAt(vga_text_x, vga_text_y, ascii, vga_text_attr);
1445         vga_text_x++;
1446     }
1447
1448     if (vga_text_x >= vga_text_width)
1449     {
1450         vga_text_x = 0;
1451         vga_text_y++;
1452     }
1453
1454     if (vga_text_y >= vga_text_height)
1455     {
1456         vga_text_y = vga_text_height - 1;
1457         VGA_ScrollUpText( 0, 0, 
1458                           vga_text_height - 1, vga_text_width - 1, 
1459                           1, vga_text_attr );
1460     }
1461
1462     /*
1463      * If we don't have a console, write directly to standard output.
1464      */
1465     if(!vga_text_console)
1466         WriteFile(VGA_AlphaConsole(), &ascii, 1, &w, NULL);
1467
1468     LeaveCriticalSection(&vga_lock);
1469 }
1470
1471 void VGA_ClearText(unsigned row1, unsigned col1,
1472                    unsigned row2, unsigned col2,
1473                    BYTE attr)
1474 {
1475     unsigned x, y;
1476
1477     EnterCriticalSection(&vga_lock);
1478
1479     for(y=row1; y<=row2; y++)
1480         for(x=col1; x<=col2; x++)
1481             VGA_PutCharAt(x, y, 0x20, attr);
1482
1483     LeaveCriticalSection(&vga_lock);
1484 }
1485
1486 void VGA_ScrollUpText(unsigned row1,  unsigned col1,
1487                       unsigned row2,  unsigned col2,
1488                       unsigned lines, BYTE attr)
1489 {
1490     char    *buffer = VGA_AlphaBuffer();
1491     unsigned y;
1492
1493     EnterCriticalSection(&vga_lock);
1494
1495     /*
1496      * Scroll buffer.
1497      */
1498     for (y = row1; y <= row2 - lines; y++)
1499         memmove( buffer + col1 + y * vga_text_width * 2,
1500                  buffer + col1 + (y + lines) * vga_text_width * 2,
1501                  (col2 - col1 + 1) * 2 );
1502
1503     /*
1504      * Fill exposed lines.
1505      */
1506     for (y = max(row1, row2 - lines + 1); y <= row2; y++)
1507         VGA_WriteChars( col1, y, ' ', attr, col2 - col1 + 1 );
1508
1509     LeaveCriticalSection(&vga_lock);
1510 }
1511
1512 void VGA_ScrollDownText(unsigned row1,  unsigned col1,
1513                         unsigned row2,  unsigned col2,
1514                         unsigned lines, BYTE attr)
1515 {
1516     char    *buffer = VGA_AlphaBuffer();
1517     unsigned y;
1518
1519     EnterCriticalSection(&vga_lock);
1520
1521     /*
1522      * Scroll buffer.
1523      */
1524     for (y = row2; y >= row1 + lines; y--)
1525         memmove( buffer + col1 + y * vga_text_width * 2,
1526                  buffer + col1 + (y - lines) * vga_text_width * 2,
1527                  (col2 - col1 + 1) * 2 );
1528
1529     /*
1530      * Fill exposed lines.
1531      */
1532     for (y = row1; y <= min(row1 + lines - 1, row2); y++)
1533         VGA_WriteChars( col1, y, ' ', attr, col2 - col1 + 1 );
1534
1535     LeaveCriticalSection(&vga_lock);
1536 }
1537
1538 void VGA_GetCharacterAtCursor(BYTE *ascii, BYTE *attr)
1539 {
1540     char *dat;
1541
1542     dat = VGA_AlphaBuffer() + ((vga_text_width * vga_text_y + vga_text_x) * 2);
1543
1544     *ascii = dat[0];
1545     *attr = dat[1];
1546 }
1547
1548
1549 /*** CONTROL ***/
1550
1551 /* FIXME: optimize by doing this only if the data has actually changed
1552  *        (in a way similar to DIBSection, perhaps) */
1553 static void VGA_Poll_Graphics(void)
1554 {
1555   unsigned int Pitch, Height, Width, X, Y;
1556   char *surf;
1557   char *dat = vga_fb_data + vga_fb_offset;
1558   int   bpp = (vga_fb_depth + 7) / 8;
1559
1560   surf = VGA_Lock(&Pitch,&Height,&Width,NULL);
1561   if (!surf) return;
1562
1563   /*
1564    * Synchronize framebuffer contents.
1565    */
1566   if (vga_fb_window != -1)
1567       VGA_SyncWindow( TRUE );
1568
1569   /*
1570    * CGA framebuffer (160x200) - CGA_ColorComposite, special subtype of mode 6
1571    * This buffer is encoded as following:
1572    * - 4 bit pr. pixel, 2 pixels per byte
1573    * - 80 bytes per row
1574    * - Every second line has an offset of 8096
1575    */
1576   if(vga_fb_depth == 4 && vga_fb_width == 160 && vga_fb_height == 200){
1577     WORD off = 0;
1578     BYTE bits = 4;
1579     BYTE value;
1580     for(Y=0; Y<vga_fb_height; Y++, surf+=(Pitch*2)){
1581       for(X=0; X<vga_fb_width; X++){
1582         off = Y & 1 ? (8 * 1024) : 0;
1583         off += (80 * (Y/2));
1584         off += X/2;
1585         value = (dat[off] >> bits) & 0xF;
1586         surf[(X*4)+0] = value;
1587         surf[(X*4)+1] = value;
1588         surf[(X*4)+2] = value;
1589         surf[(X*4)+3] = value;
1590         surf[(X*4)+Pitch+0] = value;
1591         surf[(X*4)+Pitch+1] = value;
1592         surf[(X*4)+Pitch+2] = value;
1593         surf[(X*4)+Pitch+3] = value;
1594         bits -= 4;
1595         bits &= 7;
1596       }
1597     }
1598   }
1599
1600   /*
1601    * CGA framebuffer (320x200)
1602    * This buffer is encoded as following:
1603    * - 2 bits per color, 4 pixels per byte
1604    * - 80 bytes per row
1605    * - Every second line has an offset of 8096
1606    */
1607   else if(vga_fb_depth == 2 && vga_fb_width == 320 && vga_fb_height == 200){
1608     WORD off = 0;
1609     BYTE bits = 6;
1610     BYTE value;
1611     /* Go thru rows */
1612     for(Y=0; Y<vga_fb_height; Y++, surf+=(Pitch*2)){
1613       for(X=0; X<vga_fb_width; X++){
1614         off = Y & 1 ? (8 * 1024) : 0;
1615         off += (80 * (Y/2));
1616         off += X/4;
1617         value = (dat[off] >> bits) & 0x3;
1618         surf[(X*2)] = value;
1619         surf[(X*2)+1] = value;
1620         surf[(X*2)+Pitch] = value;
1621         surf[(X*2)+Pitch+1] = value;
1622         bits -= 2;
1623         bits &= 7;
1624       }
1625     }
1626   }
1627
1628   /*
1629    * Double VGA framebuffer (320x200 -> 640x400), if needed.
1630    */
1631   else if(Height >= 2 * vga_fb_height && Width >= 2 * vga_fb_width && bpp == 1)
1632     for (Y=0; Y<vga_fb_height; Y++,surf+=Pitch*2,dat+=vga_fb_pitch)
1633       for (X=0; X<vga_fb_width; X++) {
1634        BYTE value = dat[X];
1635        surf[X*2] = value;
1636        surf[X*2+1] = value;
1637        surf[X*2+Pitch] = value;
1638        surf[X*2+Pitch+1] = value;
1639       }
1640   /*
1641    * Linear Buffer, including mode 19
1642    */
1643   else
1644     for (Y=0; Y<vga_fb_height; Y++,surf+=Pitch,dat+=vga_fb_pitch)
1645       memcpy(surf, dat, vga_fb_width * bpp);
1646
1647   VGA_Unlock();
1648 }
1649
1650 static void VGA_Poll_Text(void)
1651 {
1652     char *dat, *old, *p_line;
1653     unsigned int X, Y;
1654     CHAR_INFO ch[256]; /* that should suffice for the largest text width */
1655     COORD siz, off;
1656     SMALL_RECT dest;
1657     HANDLE con = VGA_AlphaConsole();
1658     BOOL linechanged = FALSE; /* video memory area differs from stored copy? */
1659
1660     /* Synchronize cursor position. */
1661     off.X = vga_text_x;
1662     off.Y = vga_text_y;
1663     SetConsoleCursorPosition(con,off);
1664
1665     dat = VGA_AlphaBuffer();
1666     old = vga_text_old; /* pointer to stored video mem copy */
1667     siz.X = vga_text_width; siz.Y = 1;
1668     off.X = 0; off.Y = 0;
1669
1670     /* copy from virtual VGA frame buffer to console */
1671     for (Y=0; Y<vga_text_height; Y++) {
1672         linechanged = memcmp(dat, old, vga_text_width*2);
1673         if (linechanged)
1674         {
1675             /*TRACE("line %d changed\n", Y);*/
1676             p_line = dat;
1677             for (X=0; X<vga_text_width; X++) {
1678                 ch[X].Char.AsciiChar = *p_line++;
1679                 /* WriteConsoleOutputA doesn't like "dead" chars */
1680                 if (ch[X].Char.AsciiChar == '\0')
1681                     ch[X].Char.AsciiChar = ' ';
1682                 ch[X].Attributes = *p_line++;
1683             }
1684             dest.Top=Y; dest.Bottom=Y;
1685             dest.Left=0; dest.Right=vga_text_width+1;
1686             WriteConsoleOutputA(con, ch, siz, off, &dest);
1687             memcpy(old, dat, vga_text_width*2);
1688         }
1689         /* advance to next text line */
1690         dat += vga_text_width*2;
1691         old += vga_text_width*2;
1692     }
1693 }
1694
1695 static void CALLBACK VGA_Poll( LPVOID arg, DWORD low, DWORD high )
1696 {
1697     EnterCriticalSection(&vga_lock);
1698
1699     if (lpddraw)
1700         VGA_Poll_Graphics();
1701     else
1702         VGA_Poll_Text();
1703
1704     /*
1705      * Fake start of retrace.
1706      */
1707     vga_retrace_vertical = TRUE;
1708
1709     LeaveCriticalSection(&vga_lock);
1710 }
1711
1712 static BYTE palreg,palcnt;
1713 static PALETTEENTRY paldat;
1714
1715 void VGA_ioport_out( WORD port, BYTE val )
1716 {
1717     switch (port) {
1718         /* General Register - Feature Control */
1719         case 0x3ba:
1720            FIXME("Unsupported VGA register: general register - feature control 0x%04x (value 0x%02x)\n", port, val);
1721            break;
1722         /* Attribute Controller - Address/Other */
1723         case 0x3c0:
1724            if (vga_address_3c0)
1725                vga_index_3c0 = val;
1726            else
1727                FIXME("Unsupported index, VGA attribute controller register 0x3c0: 0x%02x (value 0x%02x)\n",
1728                      vga_index_3c0, val);
1729            vga_address_3c0 = !vga_address_3c0;
1730            break;
1731         /* General Register - Misc output */
1732         case 0x3c2:
1733            FIXME("Unsupported VGA register: general register - misc output 0x%04x (value 0x%02x)\n", port, val);
1734            break;
1735         /* General Register - Video subsystem enable */
1736         case 0x3c3:
1737            FIXME("Unsupported VGA register: general register - video subsystem enable 0x%04x (value 0x%02x)\n", port, val);
1738            break;
1739         /* Sequencer Register - Address */
1740         case 0x3c4:
1741            vga_index_3c4 = val;
1742            break;
1743         /* Sequencer Register - Other */
1744         case 0x3c5:
1745           switch(vga_index_3c4) {
1746                case 0x04: /* Sequencer: Memory Mode Register */
1747                   if(vga_fb_depth == 8)
1748                       VGA_SetWindowStart((val & 8) ? 0 : -1);
1749                   else
1750                       FIXME("Memory Mode Register not supported in this mode.\n");
1751                   break;
1752                default:
1753                   FIXME("Unsupported index, VGA sequencer register 0x3c4: 0x%02x (value 0x%02x)\n",
1754                         vga_index_3c4, val);
1755            }
1756            break;
1757         case 0x3c8:
1758             palreg=val; palcnt=0; break;
1759         case 0x3c9:
1760             ((BYTE*)&paldat)[palcnt++]=val << 2;
1761             if (palcnt==3) {
1762                 VGA_SetPalette(&paldat,palreg++,1);
1763                 palcnt=0;
1764             }
1765             break;
1766         /* Graphics Controller Register - Address */
1767         case 0x3ce:
1768             vga_index_3ce = val;
1769            break;
1770         /* Graphics Controller Register - Other */
1771         case 0x3cf:
1772            FIXME("Unsupported index, VGA graphics controller register - other 0x3ce: 0x%02x (value 0x%02x)\n",
1773                  vga_index_3ce, val);
1774            break;
1775         /* CRT Controller Register - Index (MDA) */
1776         case 0x3b4:
1777         /* CRT Controller Register - Index (CGA) */
1778         case 0x3d4:
1779            vga_index_3d4 = val;
1780            break;
1781         /* CRT Controller Register - Other (MDA) */
1782         case 0x3b5:
1783         /* CRT Controller Register - Other (CGA) */
1784         case 0x3d5:
1785            FIXME("Unsupported index, VGA crt controller register 0x3b4/0x3d4: 0x%02x (value 0x%02x)\n",
1786                  vga_index_3d4, val);
1787            break;
1788         /* Mode control register - 6845 Motorola (MDA) */
1789         case 0x3b8:
1790         /* Mode control register - 6845 Motorola (CGA) */
1791         case 0x3d8:
1792            /*
1793             *  xxxxxxx1 = 80x25 text
1794             *  xxxxxxx0 = 40x25 text (default)
1795             *  xxxxxx1x = graphics (320x200)
1796             *  xxxxxx0x = text
1797             *  xxxxx1xx = B/W
1798             *  xxxxx0xx = color
1799             *  xxxx1xxx = enable video signal
1800             *  xxx1xxxx = 640x200 B/W graphics
1801             *  xx1xxxxx = blink
1802             */
1803
1804            /* check bits 6 and 7 */
1805            if (val & 0xC0)
1806            {
1807               FIXME("Unsupported value, VGA register 0x3d8: 0x%02x - bits 7 and 6 not supported.\n", val);
1808            }
1809            /* check bits 5 - blink on */
1810            if (val & 0x20)
1811            {
1812               FIXME("Unsupported value, VGA register 0x3d8: 0x%02x (bit 5) - blink is not supported.\n", val);
1813            }
1814            /* Enable Video Signal (bit 3) - Set the enabled bit */
1815            VGA_SetEnabled((val & 0x08) != 0);
1816
1817            /* xxx1x010 - Detect 160x200, 16 color mode (CGA composite) */
1818            if( (val & 0x17) == 0x12 )
1819            {
1820              /* Switch to 160x200x4 composite mode - special case of mode 6 */
1821              CGA_ColorComposite = TRUE;
1822              VGA_SetMode(6);
1823            }
1824            else
1825            {
1826              /* turn off composite colors otherwise, including 320x200 (80x200 16 color) */
1827              CGA_ColorComposite = FALSE;
1828            }
1829
1830            /* xxx0x100 - Detect VGA mode 0 */
1831            if( (val & 0x17) == 0x04 )
1832            {
1833              VGA_SetMode(0);
1834            }
1835            /* xxx0x000 - Detect VGA mode 1 */
1836            else if( (val & 0x17) == 0x00 )
1837            {
1838              VGA_SetMode(1);
1839            }
1840            /* xxx0x101 - Detect VGA mode 2 */
1841            else if( (val & 0x17) == 0x05 )
1842            {
1843              VGA_SetMode(2);
1844            }
1845            /* xxx0x001 - Detect VGA mode 3 */
1846            else if( (val & 0x17) == 0x01 )
1847            {
1848              VGA_SetMode(3);
1849            }
1850            /* xxx0x010 - Detect VGA mode 4 */
1851            else if( (val & 0x17) == 0x02 )
1852            {
1853              VGA_SetMode(4);
1854            }
1855            /* xxx0x110 - Detect VGA mode 5 */
1856            else if( (val & 0x17) == 0x06 )
1857            {
1858              VGA_SetMode(5);
1859            }
1860            /* xxx1x110 - Detect VGA mode 6 */
1861            else if( (val & 0x17) == 0x16 )
1862            {
1863              VGA_SetMode(6);
1864            }
1865            /* unsupported mode */
1866            else
1867            {
1868              FIXME("Unsupported value, VGA register 0x3d8: 0x%02x - unrecognized MDA/CGA mode\n", val); /* Set the enabled bit */
1869            }
1870
1871            break;
1872
1873         /* Colour control register (CGA) */
1874         case 0x3d9:
1875            /* Set bright */
1876            VGA_SetBright((val & 0x10) != 0);
1877
1878            /* Set palette index */
1879            VGA_SetPaletteIndex((val & 0x20) != 0);
1880
1881            /* Now update the palette */
1882            VGA_UpdatePalette();
1883            break;
1884         default:
1885             FIXME("Unsupported VGA register: 0x%04x (value 0x%02x)\n", port, val);
1886     }
1887 }
1888
1889 BYTE VGA_ioport_in( WORD port )
1890 {
1891     BYTE ret;
1892
1893     switch (port) {
1894         /* Attribute Controller - Other */
1895         case 0x3c1:
1896            FIXME("Unsupported index, VGA attribute controller register 0x3c0: 0x%02x\n",
1897                  vga_index_3c0);
1898            return 0xff;
1899         /* General Register - Input status 0 */
1900         case 0x3c2:
1901            ret=0xff;
1902            FIXME("Unsupported VGA register: general register - input status 0 0x%04x\n", port);
1903            break;
1904         /* General Register - Video subsystem enable */
1905         case 0x3c3:
1906            ret=0xff;
1907            FIXME("Unsupported VGA register: general register - video subsystem enable 0x%04x\n", port);
1908            break;
1909         /* Sequencer Register - Other */
1910         case 0x3c5:
1911            switch(vga_index_3c4) {
1912                case 0x04: /* Sequencer: Memory Mode Register */
1913                     return (VGA_GetWindowStart() == -1) ? 0xf7 : 0xff;
1914                default:
1915                    FIXME("Unsupported index, register 0x3c4: 0x%02x\n",
1916                          vga_index_3c4);
1917                    return 0xff;
1918            }
1919         /* General Register -  DAC State */
1920         case 0x3c7:
1921            ret=0xff;
1922            FIXME("Unsupported VGA register: general register - DAC State 0x%04x\n", port);
1923            break;
1924         /* General Register - Feature control */
1925         case 0x3ca:
1926            ret=0xff;
1927            FIXME("Unsupported VGA register: general register - Feature control 0x%04x\n", port);
1928            break;
1929         /* General Register - Misc output */
1930         case 0x3cc:
1931            ret=0xff;
1932            FIXME("Unsupported VGA register: general register - Feature control 0x%04x\n", port);
1933            break;
1934         /* Graphics Controller Register - Other */
1935         case 0x3cf:
1936            FIXME("Unsupported index, register 0x3ce: 0x%02x\n",
1937                  vga_index_3ce);
1938            return 0xff;
1939         /* CRT Controller Register - Other (MDA) */
1940         case 0x3b5:
1941         /* CRT Controller Register - Other (CGA) */
1942         case 0x3d5:
1943            FIXME("Unsupported index, VGA crt controller register 0x3b4/0x3d4: 0x%02x\n",
1944                  vga_index_3d4);
1945            return 0xff;
1946         /* General Register - Input status 1 (MDA) */
1947         case 0x3ba:
1948         /* General Register - Input status 1 (CGA) */
1949         case 0x3da:
1950             /*
1951              * Read from this register resets register 0x3c0 address flip-flop.
1952              */
1953             vga_address_3c0 = TRUE;
1954
1955             /*
1956              * Read from this register returns following bits:
1957              *   xxxx1xxx = Vertical retrace in progress if set.
1958              *   xxxxx1xx = Light pen switched on.
1959              *   xxxxxx1x = Light pen trigger set.
1960              *   xxxxxxx1 = Either vertical or horizontal retrace 
1961              *              in progress if set.
1962              */
1963             ret = 0;
1964             if (vga_retrace_vertical)
1965                 ret |= 9;
1966             if (vga_retrace_horizontal)
1967                 ret |= 3;
1968             
1969             /*
1970              * If VGA mode has been set, vertical retrace is
1971              * turned on once a frame and cleared after each read.
1972              * This might cause applications that synchronize with
1973              * vertical retrace to actually skip one frame but that
1974              * is probably not a problem.
1975              * 
1976              * If no VGA mode has been set, vertical retrace is faked
1977              * by toggling the value after every read.
1978              */
1979             if (VGA_IsTimerRunning())
1980                 vga_retrace_vertical = FALSE;
1981             else
1982                 vga_retrace_vertical = !vga_retrace_vertical;
1983
1984             /*
1985              * Toggle horizontal retrace.
1986              */
1987             vga_retrace_horizontal = !vga_retrace_horizontal;
1988             break;
1989
1990         default:
1991             ret=0xff;
1992             FIXME("Unsupported VGA register: 0x%04x\n", port);
1993     }
1994     return ret;
1995 }
1996
1997 void VGA_Clean(void)
1998 {
1999     VGA_Exit();
2000     VGA_DeinstallTimer();
2001 }