[NTVDM]
[reactos.git] / reactos / subsystems / ntvdm / hardware / vga.c
index 4a4dc1b..5eaa863 100644 (file)
 static CONST DWORD MemoryBase[]  = { 0xA0000, 0xA0000, 0xB0000, 0xB8000 };
 static CONST DWORD MemoryLimit[] = { 0xAFFFF, 0xAFFFF, 0xB7FFF, 0xBFFFF };
 
+/*
+ * Activate this line if you want to use the real
+ * RegisterConsoleVDM API of ReactOS/Windows.
+ */
+// #define USE_REAL_REGISTERCONSOLEVDM
+
 #define USE_REACTOS_COLORS
 // #define USE_DOSBOX_COLORS
 
@@ -171,6 +177,32 @@ static CONST COLORREF VgaDefaultPalette[VGA_MAX_COLORS] =
 
 #endif
 
+/*
+ * Default 16-color palette for foreground and background
+ * (corresponding flags in comments).
+ * Taken from subsystems/win32/winsrv/consrv/frontends/gui/conwnd.c
+ */
+static const COLORREF ConsoleColors[16] =
+{
+    RGB(0, 0, 0),       // (Black)
+    RGB(0, 0, 128),     // BLUE
+    RGB(0, 128, 0),     // GREEN
+    RGB(0, 128, 128),   // BLUE  | GREEN
+    RGB(128, 0, 0),     // RED
+    RGB(128, 0, 128),   // BLUE  | RED
+    RGB(128, 128, 0),   // GREEN | RED
+    RGB(192, 192, 192), // BLUE  | GREEN | RED
+
+    RGB(128, 128, 128), // (Grey)  INTENSITY
+    RGB(0, 0, 255),     // BLUE  | INTENSITY
+    RGB(0, 255, 0),     // GREEN | INTENSITY
+    RGB(0, 255, 255),   // BLUE  | GREEN | INTENSITY
+    RGB(255, 0, 0),     // RED   | INTENSITY
+    RGB(255, 0, 255),   // BLUE  | RED   | INTENSITY
+    RGB(255, 255, 0),   // GREEN | RED   | INTENSITY
+    RGB(255, 255, 255)  // BLUE  | GREEN | RED | INTENSITY
+};
+
 /*
  * Console interface -- VGA-mode-agnostic
  */
@@ -184,6 +216,7 @@ C_ASSERT(sizeof(CHAR_CELL) == 2);
 static LPVOID ConsoleFramebuffer = NULL; // Active framebuffer, points to
                                          // either TextFramebuffer or a valid
                                          // graphics framebuffer.
+static HPALETTE TextPaletteHandle = NULL;
 static HPALETTE PaletteHandle = NULL;
 
 static HANDLE StartEvent = NULL;
@@ -207,7 +240,9 @@ static HANDLE TextConsoleBuffer = NULL;
 /* Graphics mode */
 static HANDLE GraphicsConsoleBuffer = NULL;
 static HANDLE ConsoleMutex = NULL;
-static BOOLEAN DoubleVision = FALSE;
+/* DoubleVision support */
+static BOOLEAN DoubleWidth  = FALSE;
+static BOOLEAN DoubleHeight = FALSE;
 
 /*
  * VGA Hardware
@@ -261,44 +296,12 @@ static SMALL_RECT UpdateRectangle = { 0, 0, 0, 0 };
 
 #include <ntddvdeo.h>
 
-typedef
-BOOL
-(WINAPI *pRegisterConsoleVDM)
-(
-    BOOL IsDosVDM_flag,
-    HANDLE EventHandle_1,
-    HANDLE EventHandle_2,
-    HANDLE EventHandle_3,
-    int Unused1,
-    PVOID returned_val_1,
-    PVOID *returned_val_2,
-    PVOID lpUnknownBuffer,
-    DWORD theUnknownBufferLength,
-    COORD theVDMBufferSize,
-    PCHAR *lpVDMBuffer
-);
-
-#if 0
-BOOL
-WINAPI
-RegisterConsoleVDM
-(
-    BOOL IsDosVDM_flag,
-    HANDLE EventHandle_1,
-    HANDLE EventHandle_2,
-    HANDLE EventHandle_3,
-    int Unused1,
-    PVOID returned_val_1,
-    PVOID *returned_val_2,
-    PVOID lpUnknownBuffer,
-    DWORD theUnknownBufferLength,
-    COORD theVDMBufferSize,
-    PVOID *lpVDMBuffer
-);
-
-HMODULE hKernel32 = NULL;
-pRegisterConsoleVDM RegisterConsoleVDM = NULL;
-#endif
+#ifdef USE_REAL_REGISTERCONSOLEVDM
+
+#define __RegisterConsoleVDM        RegisterConsoleVDM
+#define __InvalidateConsoleDIBits   InvalidateConsoleDIBits
+
+#else
 
 /*
  * This private buffer, per-console, is used by
@@ -313,49 +316,49 @@ static PCHAR_INFO CharBuff  = NULL; // This is a hack, which is unneeded
 
 BOOL
 WINAPI
-__RegisterConsoleVDM(BOOL IsDosVDM_flag,
-                     HANDLE EventHandle_1,
-                     HANDLE EventHandle_2,
-                     HANDLE EventHandle_3,
-                     int Unused1,
-                     PVOID returned_val_1,
-                     PVOID *returned_val_2,
-                     PVOID lpUnknownBuffer,
-                     DWORD theUnknownBufferLength,
-                     COORD theVDMBufferSize,
-                     PCHAR *lpVDMBuffer)
+__RegisterConsoleVDM(IN DWORD dwRegisterFlags,
+                     IN HANDLE hStartHardwareEvent,
+                     IN HANDLE hEndHardwareEvent,
+                     IN HANDLE hErrorHardwareEvent,
+                     IN DWORD dwUnusedVar,
+                     OUT LPDWORD lpVideoStateLength,
+                     OUT PVOID* lpVideoState, // PVIDEO_HARDWARE_STATE_HEADER*
+                     IN PVOID lpUnusedBuffer,
+                     IN DWORD dwUnusedBufferLength,
+                     IN COORD dwVDMBufferSize,
+                     OUT PVOID* lpVDMBuffer)
 {
-    UNREFERENCED_PARAMETER(EventHandle_3);
-    UNREFERENCED_PARAMETER(Unused1);
-    UNREFERENCED_PARAMETER(returned_val_1);
-    UNREFERENCED_PARAMETER(returned_val_2);
-    UNREFERENCED_PARAMETER(lpUnknownBuffer);
-    UNREFERENCED_PARAMETER(theUnknownBufferLength);
+    UNREFERENCED_PARAMETER(hErrorHardwareEvent);
+    UNREFERENCED_PARAMETER(dwUnusedVar);
+    UNREFERENCED_PARAMETER(lpVideoStateLength);
+    UNREFERENCED_PARAMETER(lpVideoState);
+    UNREFERENCED_PARAMETER(lpUnusedBuffer);
+    UNREFERENCED_PARAMETER(dwUnusedBufferLength);
 
     SetLastError(0);
-    DPRINT1("__RegisterConsoleVDM(%d)\n", IsDosVDM_flag);
+    DPRINT1("__RegisterConsoleVDM(%d)\n", dwRegisterFlags);
 
     if (lpVDMBuffer == NULL) return FALSE;
 
-    if (IsDosVDM_flag)
+    if (dwRegisterFlags != 0)
     {
-        // if (EventHandle_1 == NULL || EventHandle_2 == NULL) return FALSE;
+        // if (hStartHardwareEvent == NULL || hEndHardwareEvent == NULL) return FALSE;
         if (VDMBuffer != NULL) return FALSE;
 
-        VDMBufferSize = theVDMBufferSize;
+        VDMBufferSize = dwVDMBufferSize;
 
         /* HACK: Cache -- to be removed in the real implementation */
         CharBuff = HeapAlloc(GetProcessHeap(),
                              HEAP_ZERO_MEMORY,
-                             theVDMBufferSize.X * theVDMBufferSize.Y
-                                                * sizeof(CHAR_INFO));
+                             VDMBufferSize.X * VDMBufferSize.Y
+                                             * sizeof(CHAR_INFO));
         ASSERT(CharBuff);
 
         VDMBuffer = HeapAlloc(GetProcessHeap(),
                               HEAP_ZERO_MEMORY,
-                              theVDMBufferSize.X * theVDMBufferSize.Y
-                                                 * sizeof(CHAR_CELL));
-        *lpVDMBuffer = (PCHAR)VDMBuffer;
+                              VDMBufferSize.X * VDMBufferSize.Y
+                                              * sizeof(CHAR_CELL));
+        *lpVDMBuffer = VDMBuffer;
         return (VDMBuffer != NULL);
     }
     else
@@ -405,6 +408,8 @@ __InvalidateConsoleDIBits(IN HANDLE hConsoleOutput,
     return InvalidateConsoleDIBits(hConsoleOutput, lpRect);
 }
 
+#endif
+
 /* PRIVATE FUNCTIONS **********************************************************/
 
 static inline DWORD VgaGetAddressSize(VOID);
@@ -421,7 +426,7 @@ static VOID VgaUpdateCursorPosition(VOID)
     VgaCrtcRegisters[VGA_CRTC_CURSOR_LOC_LOW_REG]  = LOBYTE(Offset);
     VgaCrtcRegisters[VGA_CRTC_CURSOR_LOC_HIGH_REG] = HIBYTE(Offset);
 
-    VidBiosSyncCursorPosition();
+    // VidBiosSyncCursorPosition();
     VgaUpdateTextCursor();
 }
 
@@ -431,6 +436,9 @@ static BOOL VgaAttachToConsoleInternal(PCOORD Resolution)
     ULONG Length = 0;
     PVIDEO_HARDWARE_STATE_HEADER State;
 
+#ifdef USE_REAL_REGISTERCONSOLEVDM
+    PCHAR_INFO CharBuff = NULL;
+#endif
     SHORT i, j;
     DWORD AddressSize, ScanlineSize;
     DWORD Address = 0;
@@ -445,7 +453,7 @@ static BOOL VgaAttachToConsoleInternal(PCOORD Resolution)
     /*
      * Windows 2k3 winsrv.dll calls NtVdmControl(VdmQueryVdmProcess == 14, &ConsoleHandle);
      * in the two following APIs:
-     * SrvRegisterConsoleVDM  (corresponding win32 API: RegisterConsoleVDM)
+     * SrvRegisterConsoleVDM  (corresponding Win32 API: RegisterConsoleVDM)
      * SrvVDMConsoleOperation (corresponding Win32 API: )
      * to check whether the current process is a VDM process, and fails otherwise with the
      * error 0xC0000022 ().
@@ -465,7 +473,7 @@ static BOOL VgaAttachToConsoleInternal(PCOORD Resolution)
                          NULL,
                          0,
                          TextResolution,
-                         (PCHAR*)&TextFramebuffer);
+                         (PVOID*)&TextFramebuffer);
     if (!Success)
     {
         DisplayMessage(L"RegisterConsoleVDM failed with error %d\n", GetLastError());
@@ -473,6 +481,14 @@ static BOOL VgaAttachToConsoleInternal(PCOORD Resolution)
         return FALSE;
     }
 
+#ifdef USE_REAL_REGISTERCONSOLEVDM
+    CharBuff = HeapAlloc(GetProcessHeap(),
+                         HEAP_ZERO_MEMORY,
+                         TextResolution.X * TextResolution.Y
+                                          * sizeof(CHAR_INFO));
+    ASSERT(CharBuff);
+#endif
+
     /*
      * Resize the console
      */
@@ -533,66 +549,15 @@ static BOOL VgaAttachToConsoleInternal(PCOORD Resolution)
         Address += ScanlineSize;
     }
 
+#ifdef USE_REAL_REGISTERCONSOLEVDM
+    if (CharBuff) HeapFree(GetProcessHeap(), 0, CharBuff);
+#endif
+
     VgaUpdateCursorPosition();
 
     return TRUE;
 }
 
-BOOL VgaAttachToConsole(VOID)
-{
-    if (TextResolution.X == 0 || TextResolution.Y == 0)
-        DPRINT1("VgaAttachToConsole -- TextResolution uninitialized\n");
-
-    if (TextResolution.X == 0) TextResolution.X = 80;
-    if (TextResolution.Y == 0) TextResolution.Y = 25;
-
-    return VgaAttachToConsoleInternal(&TextResolution);
-}
-
-VOID VgaDetachFromConsole(BOOL ChangingMode)
-{
-    ULONG dummyLength;
-    PVOID dummyPtr;
-    COORD dummySize = {0};
-
-    __RegisterConsoleVDM(0,
-                         NULL,
-                         NULL,
-                         NULL,
-                         0,
-                         &dummyLength,
-                         &dummyPtr,
-                         NULL,
-                         0,
-                         dummySize,
-                         (PCHAR*)&dummyPtr);
-
-    TextFramebuffer = NULL;
-
-    if (!ChangingMode)
-    {
-        SMALL_RECT ConRect;
-
-        /* Restore the old screen buffer */
-        SetConsoleActiveScreenBuffer(TextConsoleBuffer);
-
-        /* Restore the original console size */
-        ConRect.Left   = 0;
-        ConRect.Top    = 0;
-        ConRect.Right  = ConRect.Left + OrgConsoleBufferInfo.srWindow.Right  - OrgConsoleBufferInfo.srWindow.Left;
-        ConRect.Bottom = ConRect.Top  + OrgConsoleBufferInfo.srWindow.Bottom - OrgConsoleBufferInfo.srWindow.Top ;
-        /*
-         * See the following trick explanation in VgaAttachToConsoleInternal.
-         */
-        SetConsoleScreenBufferSize(TextConsoleBuffer, OrgConsoleBufferInfo.dwSize);
-        SetConsoleWindowInfo(TextConsoleBuffer, TRUE, &ConRect);
-        SetConsoleScreenBufferSize(TextConsoleBuffer, OrgConsoleBufferInfo.dwSize);
-
-        /* Restore the original cursor shape */
-        SetConsoleCursorInfo(TextConsoleBuffer, &OrgConsoleCursorInfo);
-    }
-}
-
 static BOOL IsConsoleHandle(HANDLE hHandle)
 {
     DWORD dwMode;
@@ -829,7 +794,7 @@ static VOID VgaWriteCrtc(BYTE Data)
 
 static VOID VgaWriteDac(BYTE Data)
 {
-    INT PaletteIndex;
+    INT i, PaletteIndex;
     PALETTEENTRY Entry;
 
     /* Set the value */
@@ -844,8 +809,20 @@ static VOID VgaWriteDac(BYTE Data)
     Entry.peBlue = VGA_DAC_TO_COLOR(VgaDacRegisters[PaletteIndex * 3 + 2]);
     Entry.peFlags = 0;
 
-    /* Update the palette entry and set the palette change flag */
+    /* Update the palette entry */
     SetPaletteEntries(PaletteHandle, PaletteIndex, 1, &Entry);
+
+    /* Check which text palette entries are affected */
+    for (i = 0; i <= VGA_AC_PAL_F_REG; i++)
+    {
+        if (VgaAcRegisters[i] == PaletteIndex)
+        {
+            /* Update the text palette entry */
+            SetPaletteEntries(TextPaletteHandle, i, 1, &Entry);
+        }
+    }
+
+    /* Set the palette changed flag */
     PaletteChanged = TRUE;
 
     /* Update the index */
@@ -855,6 +832,8 @@ static VOID VgaWriteDac(BYTE Data)
 
 static VOID VgaWriteAc(BYTE Data)
 {
+    PALETTEENTRY Entry;
+
     ASSERT(VgaAcIndex < VGA_AC_MAX_REG);
 
     /* Save the value */
@@ -865,8 +844,17 @@ static VOID VgaWriteAc(BYTE Data)
         // DbgPrint("    AC Palette Writing %d to index %d\n", Data, VgaAcIndex);
         if (VgaAcRegisters[VgaAcIndex] != Data)
         {
-            /* Update the AC register and set the palette change flag */
+            /* Update the AC register */
             VgaAcRegisters[VgaAcIndex] = Data;
+
+            /* Fill the entry structure */
+            Entry.peRed = VGA_DAC_TO_COLOR(VgaDacRegisters[Data * 3]);
+            Entry.peGreen = VGA_DAC_TO_COLOR(VgaDacRegisters[Data * 3 + 1]);
+            Entry.peBlue = VGA_DAC_TO_COLOR(VgaDacRegisters[Data * 3 + 2]);
+            Entry.peFlags = 0;
+
+            /* Update the palette entry and set the palette change flag */
+            SetPaletteEntries(TextPaletteHandle, VgaAcIndex, 1, &Entry);
             PaletteChanged = TRUE;
         }
     }
@@ -898,33 +886,72 @@ static VOID VgaRestoreDefaultPalette(PPALETTEENTRY Entries, USHORT NumOfEntries)
 
 static BOOLEAN VgaInitializePalette(VOID)
 {
-    LPLOGPALETTE Palette;
+    INT i;
+    BOOLEAN Result = FALSE;
+    LPLOGPALETTE Palette, TextPalette;
 
-    /* Allocate storage space for the palette */
+    /* Allocate storage space for the palettes */
     Palette = (LPLOGPALETTE)HeapAlloc(GetProcessHeap(),
                                       HEAP_ZERO_MEMORY,
                                       sizeof(LOGPALETTE) +
-                                        VGA_MAX_COLORS * sizeof(PALETTEENTRY));
-    if (Palette == NULL) return FALSE;
-
-    /* Initialize the palette */
-    Palette->palVersion = 0x0300;
+                                      VGA_MAX_COLORS * sizeof(PALETTEENTRY));
+    TextPalette = (LPLOGPALETTE)HeapAlloc(GetProcessHeap(),
+                                          HEAP_ZERO_MEMORY,
+                                          sizeof(LOGPALETTE) + 
+                                          (VGA_AC_PAL_F_REG + 1) * sizeof(PALETTEENTRY));
+    if ((Palette == NULL) || (TextPalette == NULL)) goto Cleanup;
+
+    /* Initialize the palettes */
+    Palette->palVersion = TextPalette->palVersion = 0x0300;
     Palette->palNumEntries = VGA_MAX_COLORS;
+    TextPalette->palNumEntries = VGA_AC_PAL_F_REG + 1;
 
-    /* Restore the default palette */
+    /* Restore the default graphics palette */
     VgaRestoreDefaultPalette(Palette->palPalEntry, Palette->palNumEntries);
 
-    /* Create the palette */
+    /* Set the default text palette */
+    for (i = 0; i < TextPalette->palNumEntries; i++)
+    {
+        /* Set the palette entries */
+        TextPalette->palPalEntry[i].peRed   = GetRValue(ConsoleColors[i]);
+        TextPalette->palPalEntry[i].peGreen = GetGValue(ConsoleColors[i]);
+        TextPalette->palPalEntry[i].peBlue  = GetBValue(ConsoleColors[i]);
+        TextPalette->palPalEntry[i].peFlags = 0;
+    }
+
+    /* Create the palettes */
     PaletteHandle = CreatePalette(Palette);
+    TextPaletteHandle = CreatePalette(TextPalette);
 
-    /* Free the palette */
-    HeapFree(GetProcessHeap(), 0, Palette);
+    if (PaletteHandle != NULL && TextPaletteHandle != NULL)
+    {
+        /* The palettes have been created successfully */
+        Result = TRUE;
+    }
 
-    /* Fail if the palette wasn't successfully created... */
-    if (PaletteHandle == NULL) return FALSE;
+Cleanup:
+    /* Free the palettes */
+    if (Palette) HeapFree(GetProcessHeap(), 0, Palette);
+    if (TextPalette) HeapFree(GetProcessHeap(), 0, TextPalette);
 
-    /* ... otherwise return success */
-    return TRUE;
+    if (!Result)
+    {
+        /* Something failed, delete the palettes */
+        if (PaletteHandle) DeleteObject(PaletteHandle);
+        if (TextPaletteHandle) DeleteObject(TextPaletteHandle);
+    }
+
+    return Result;
+}
+
+static VOID VgaSetActiveScreenBuffer(HANDLE ScreenBuffer)
+{
+    /* Set the active buffer */
+    SetConsoleActiveScreenBuffer(ScreenBuffer);
+
+    /* Reinitialize the VDM menu */
+    DestroyVdmMenu();
+    CreateVdmMenu(ScreenBuffer);
 }
 
 static BOOL VgaEnterGraphicsMode(PCOORD Resolution)
@@ -939,20 +966,14 @@ static BOOL VgaEnterGraphicsMode(PCOORD Resolution)
     LONG Height = Resolution->Y;
 
     /* Use DoubleVision mode if the resolution is too small */
-    if (Width < VGA_MINIMUM_WIDTH && Height < VGA_MINIMUM_HEIGHT)
-    {
-        DoubleVision = TRUE;
-        Width  *= 2;
-        Height *= 2;
-    }
-    else
-    {
-        DoubleVision = FALSE;
-    }
+    DoubleWidth = (Width < VGA_MINIMUM_WIDTH);
+    if (DoubleWidth) Width *= 2;
+    DoubleHeight = (Height < VGA_MINIMUM_HEIGHT);
+    if (DoubleHeight) Height *= 2;
 
     /* Fill the bitmap info header */
-    ZeroMemory(&BitmapInfo->bmiHeader, sizeof(BITMAPINFOHEADER));
-    BitmapInfo->bmiHeader.biSize   = sizeof(BITMAPINFOHEADER);
+    RtlZeroMemory(&BitmapInfo->bmiHeader, sizeof(BitmapInfo->bmiHeader));
+    BitmapInfo->bmiHeader.biSize   = sizeof(BitmapInfo->bmiHeader);
     BitmapInfo->bmiHeader.biWidth  = Width;
     BitmapInfo->bmiHeader.biHeight = Height;
     BitmapInfo->bmiHeader.biBitCount = 8;
@@ -981,10 +1002,10 @@ static BOOL VgaEnterGraphicsMode(PCOORD Resolution)
     ConsoleMutex = GraphicsBufferInfo.hMutex;
 
     /* Clear the framebuffer */
-    ZeroMemory(ConsoleFramebuffer, BitmapInfo->bmiHeader.biSizeImage);
+    RtlZeroMemory(ConsoleFramebuffer, BitmapInfo->bmiHeader.biSizeImage);
 
     /* Set the active buffer */
-    SetConsoleActiveScreenBuffer(GraphicsConsoleBuffer);
+    VgaSetActiveScreenBuffer(GraphicsConsoleBuffer);
 
     /* Set the graphics mode palette */
     SetConsolePalette(GraphicsConsoleBuffer,
@@ -1003,7 +1024,7 @@ static VOID VgaLeaveGraphicsMode(VOID)
     ReleaseMutex(ConsoleMutex);
 
     /* Switch back to the default console text buffer */
-    // SetConsoleActiveScreenBuffer(TextConsoleBuffer);
+    // VgaSetActiveScreenBuffer(TextConsoleBuffer);
 
     /* Cleanup the video data */
     CloseHandle(ConsoleMutex);
@@ -1011,7 +1032,9 @@ static VOID VgaLeaveGraphicsMode(VOID)
     ConsoleFramebuffer = NULL;
     CloseHandle(GraphicsConsoleBuffer);
     GraphicsConsoleBuffer = NULL;
-    DoubleVision = FALSE;
+
+    DoubleWidth  = FALSE;
+    DoubleHeight = FALSE;
 }
 
 static BOOL VgaEnterTextMode(PCOORD Resolution)
@@ -1019,7 +1042,7 @@ static BOOL VgaEnterTextMode(PCOORD Resolution)
     DPRINT1("VgaEnterTextMode\n");
 
     /* Switch to the text buffer */
-    SetConsoleActiveScreenBuffer(TextConsoleBuffer);
+    VgaSetActiveScreenBuffer(TextConsoleBuffer);
 
     /* Adjust the text framebuffer if we changed the resolution */
     if (TextResolution.X != Resolution->X ||
@@ -1038,7 +1061,10 @@ static BOOL VgaEnterTextMode(PCOORD Resolution)
             return FALSE;
         }
     }
-    else VgaUpdateCursorPosition();
+    else
+    {
+        VgaUpdateCursorPosition();
+    }
 
     /* The active framebuffer is now the text framebuffer */
     ConsoleFramebuffer = TextFramebuffer;
@@ -1053,7 +1079,7 @@ static BOOL VgaEnterTextMode(PCOORD Resolution)
      * screen-buffers, which is a new feature on ReactOS).
      */
     SetConsolePalette(TextConsoleBuffer,
-                      PaletteHandle,
+                      TextPaletteHandle,
                       SYSPAL_NOSTATIC256);
 
     /* Set the screen mode flag */
@@ -1089,7 +1115,7 @@ static VOID VgaChangeMode(VOID)
         /* Enter new text mode */
         if (!VgaEnterTextMode(&Resolution))
         {
-            DisplayMessage(L"An unexpected VGA error occurred while switching into text mode.");
+            DisplayMessage(L"An unexpected VGA error occurred while switching into text mode. Error: %u", GetLastError());
             EmulatorTerminate();
             return;
         }
@@ -1099,7 +1125,7 @@ static VOID VgaChangeMode(VOID)
         /* Enter graphics mode */
         if (!VgaEnterGraphicsMode(&Resolution))
         {
-            DisplayMessage(L"An unexpected VGA error occurred while switching into graphics mode.");
+            DisplayMessage(L"An unexpected VGA error occurred while switching into graphics mode. Error: %u", GetLastError());
             EmulatorTerminate();
             return;
         }
@@ -1136,6 +1162,7 @@ static VOID VgaUpdateFramebuffer(VOID)
     {
         /* Graphics mode */
         PBYTE GraphicsBuffer = (PBYTE)ConsoleFramebuffer;
+        DWORD InterlaceHighBit = VGA_INTERLACE_HIGH_BIT;
 
         /*
          * Synchronize access to the graphics framebuffer
@@ -1143,9 +1170,21 @@ static VOID VgaUpdateFramebuffer(VOID)
          */
         WaitForSingleObject(ConsoleMutex, INFINITE);
 
+        /* Shift the high bit right by 1 in odd/even mode */
+        if (VgaGcRegisters[VGA_GC_MODE_REG] & VGA_GC_MODE_OE)
+        {
+            InterlaceHighBit >>= 1;
+        }
+
         /* Loop through the scanlines */
         for (i = 0; i < Resolution.Y; i++)
         {
+            if ((VgaGcRegisters[VGA_GC_MISC_REG] & VGA_GC_MISC_OE) && (i & 1))
+            {
+                /* Odd-numbered line in interlaced mode - set the high bit */
+                Address |= InterlaceHighBit;
+            }
+
             /* Loop through the pixels */
             for (j = 0; j < Resolution.X; j++)
             {
@@ -1161,16 +1200,16 @@ static VOID VgaUpdateFramebuffer(VOID)
                     {
                         /* One byte per pixel */
                         PixelData = VgaMemory[(j % VGA_NUM_BANKS) * VGA_BANK_SIZE
-                                              + (Address + (j / VGA_NUM_BANKS))
-                                                * AddressSize];
+                                              + LOWORD((Address + (j / VGA_NUM_BANKS))
+                                              * AddressSize)];
                     }
                     else
                     {
                         /* 4-bits per pixel */
 
                         PixelData = VgaMemory[(j % VGA_NUM_BANKS) * VGA_BANK_SIZE
-                                              + (Address + (j / (VGA_NUM_BANKS * 2)))
-                                                * AddressSize];
+                                              + LOWORD((Address + (j / (VGA_NUM_BANKS * 2)))
+                                              * AddressSize)];
 
                         /* Check if we should use the highest 4 bits or lowest 4 */
                         if (((j / VGA_NUM_BANKS) % 2) == 0)
@@ -1199,10 +1238,10 @@ static VOID VgaUpdateFramebuffer(VOID)
                          * 2 bits shifted from plane 0 and 2 for the first 4 pixels,
                          * then 2 bits shifted from plane 1 and 3 for the next 4
                          */
-                        BYTE LowPlaneData = VgaMemory[((j / 4) % 2) * VGA_BANK_SIZE
-                                                      + (Address + (j / 8)) * AddressSize];
-                        BYTE HighPlaneData = VgaMemory[(((j / 4) % 2) + 2) * VGA_BANK_SIZE
-                                                       + (Address + (j / 8)) * AddressSize];
+                        DWORD BankNumber = (j / 4) % 2;
+                        DWORD Offset = Address + (j / 8);
+                        BYTE LowPlaneData = VgaMemory[BankNumber * VGA_BANK_SIZE + LOWORD(Offset * AddressSize)];
+                        BYTE HighPlaneData = VgaMemory[(BankNumber + 2) * VGA_BANK_SIZE + LOWORD(Offset * AddressSize)];
 
                         /* Extract the two bits from each plane */
                         LowPlaneData = (LowPlaneData >> (6 - ((j % 4) * 2))) & 3;
@@ -1225,8 +1264,8 @@ static VOID VgaUpdateFramebuffer(VOID)
                         {
                             /* The data is on plane k, 4 pixels per byte */
                             BYTE PlaneData = VgaMemory[k * VGA_BANK_SIZE
-                                                       + (Address + (j / VGA_NUM_BANKS))
-                                                         * AddressSize];
+                                                       + LOWORD((Address + (j / VGA_NUM_BANKS))
+                                                       * AddressSize)];
 
                             /* The mask of the first bit in the pair */
                             BYTE BitMask = 1 << (((3 - (j % VGA_NUM_BANKS)) * 2) + 1);
@@ -1245,8 +1284,8 @@ static VOID VgaUpdateFramebuffer(VOID)
                         for (k = 0; k < VGA_NUM_BANKS; k++)
                         {
                             BYTE PlaneData = VgaMemory[k * VGA_BANK_SIZE
-                                                       + (Address + (j / (VGA_NUM_BANKS * 2)))
-                                                         * AddressSize];
+                                                       + LOWORD((Address + (j / (VGA_NUM_BANKS * 2)))
+                                                       * AddressSize)];
 
                             /* If the bit on that plane is set, set it */
                             if (PlaneData & (1 << (7 - (j % 8)))) PixelData |= 1 << k;
@@ -1266,14 +1305,14 @@ static VOID VgaUpdateFramebuffer(VOID)
                 }
 
                 /* Take into account DoubleVision mode when checking for pixel updates */
-                if (DoubleVision)
+                if (DoubleWidth && DoubleHeight)
                 {
                     /* Now check if the resulting pixel data has changed */
-                    if (GraphicsBuffer[(i * Resolution.X * 4) + (j * 2)] != PixelData)
+                    if (GraphicsBuffer[(i * 2 * Resolution.X * 2) + (j * 2)] != PixelData)
                     {
                         /* Yes, write the new value */
-                        GraphicsBuffer[(i * Resolution.X * 4) + (j * 2)] = PixelData;
-                        GraphicsBuffer[(i * Resolution.X * 4) + (j * 2 + 1)] = PixelData;
+                        GraphicsBuffer[(i * 2 * Resolution.X * 2) + (j * 2)] = PixelData;
+                        GraphicsBuffer[(i * 2 * Resolution.X * 2) + (j * 2 + 1)] = PixelData;
                         GraphicsBuffer[((i * 2 + 1) * Resolution.X * 2) + (j * 2)] = PixelData;
                         GraphicsBuffer[((i * 2 + 1) * Resolution.X * 2) + (j * 2 + 1)] = PixelData;
 
@@ -1281,7 +1320,33 @@ static VOID VgaUpdateFramebuffer(VOID)
                         VgaMarkForUpdate(i, j);
                     }
                 }
-                else
+                else if (DoubleWidth && !DoubleHeight)
+                {
+                    /* Now check if the resulting pixel data has changed */
+                    if (GraphicsBuffer[(i * Resolution.X * 2) + (j * 2)] != PixelData)
+                    {
+                        /* Yes, write the new value */
+                        GraphicsBuffer[(i * Resolution.X * 2) + (j * 2)] = PixelData;
+                        GraphicsBuffer[(i * Resolution.X * 2) + (j * 2 + 1)] = PixelData;
+
+                        /* Mark the specified pixel as changed */
+                        VgaMarkForUpdate(i, j);
+                    }
+                }
+                else if (!DoubleWidth && DoubleHeight)
+                {
+                    /* Now check if the resulting pixel data has changed */
+                    if (GraphicsBuffer[(i * 2 * Resolution.X) + j] != PixelData)
+                    {
+                        /* Yes, write the new value */
+                        GraphicsBuffer[(i * 2 * Resolution.X) + j] = PixelData;
+                        GraphicsBuffer[((i * 2 + 1) * Resolution.X) + j] = PixelData;
+
+                        /* Mark the specified pixel as changed */
+                        VgaMarkForUpdate(i, j);
+                    }
+                }
+                else // if (!DoubleWidth && !DoubleHeight)
                 {
                     /* Now check if the resulting pixel data has changed */
                     if (GraphicsBuffer[i * Resolution.X + j] != PixelData)
@@ -1295,8 +1360,17 @@ static VOID VgaUpdateFramebuffer(VOID)
                 }
             }
 
-            /* Move to the next scanline */
-            Address += ScanlineSize;
+            if ((VgaGcRegisters[VGA_GC_MISC_REG] & VGA_GC_MISC_OE) && (i & 1))
+            {
+                /* Clear the high bit */
+                Address &= ~InterlaceHighBit;
+            }
+
+            if (!(VgaGcRegisters[VGA_GC_MISC_REG] & VGA_GC_MISC_OE) || (i & 1))
+            {
+                /* Move to the next scanline */
+                Address += ScanlineSize;
+            }
         }
 
         /*
@@ -1388,7 +1462,7 @@ static VOID VgaUpdateTextCursor(VOID)
     CursorMoved = FALSE;
 }
 
-static BYTE WINAPI VgaReadPort(ULONG Port)
+static BYTE WINAPI VgaReadPort(USHORT Port)
 {
     DPRINT("VgaReadPort: Port 0x%X\n", Port);
 
@@ -1480,7 +1554,7 @@ static BYTE WINAPI VgaReadPort(ULONG Port)
     return 0;
 }
 
-static VOID WINAPI VgaWritePort(ULONG Port, BYTE Data)
+static VOID WINAPI VgaWritePort(USHORT Port, BYTE Data)
 {
     DPRINT("VgaWritePort: Port 0x%X, Data 0x%02X\n", Port, Data);
 
@@ -1747,11 +1821,14 @@ VOID VgaRefreshDisplay(VOID)
         ConsoleBufferHandle = GraphicsConsoleBuffer;
 
         /* In DoubleVision mode, scale the update rectangle */
-        if (DoubleVision)
+        if (DoubleWidth)
         {
             UpdateRectangle.Left *= 2;
-            UpdateRectangle.Top  *= 2;
-            UpdateRectangle.Right  = UpdateRectangle.Right  * 2 + 1;
+            UpdateRectangle.Right = UpdateRectangle.Right * 2 + 1;
+        }
+        if (DoubleHeight)
+        {
+            UpdateRectangle.Top *= 2;
             UpdateRectangle.Bottom = UpdateRectangle.Bottom * 2 + 1;
         }
     }
@@ -1789,15 +1866,15 @@ VOID VgaReadMemory(DWORD Address, LPBYTE Buffer, DWORD Size)
     {
         VideoAddress = VgaTranslateReadAddress(Address + i);
 
-        /* Load the latch registers */
-        VgaLatchRegisters[0] = VgaMemory[LOWORD(VideoAddress)];
-        VgaLatchRegisters[1] = VgaMemory[VGA_BANK_SIZE + LOWORD(VideoAddress)];
-        VgaLatchRegisters[2] = VgaMemory[(2 * VGA_BANK_SIZE) + LOWORD(VideoAddress)];
-        VgaLatchRegisters[3] = VgaMemory[(3 * VGA_BANK_SIZE) + LOWORD(VideoAddress)];
-
         /* Copy the value to the buffer */
         Buffer[i] = VgaMemory[VideoAddress];
     }
+
+    /* Load the latch registers */
+    VgaLatchRegisters[0] = VgaMemory[LOWORD(VideoAddress)];
+    VgaLatchRegisters[1] = VgaMemory[VGA_BANK_SIZE + LOWORD(VideoAddress)];
+    VgaLatchRegisters[2] = VgaMemory[(2 * VGA_BANK_SIZE) + LOWORD(VideoAddress)];
+    VgaLatchRegisters[3] = VgaMemory[(3 * VGA_BANK_SIZE) + LOWORD(VideoAddress)];
 }
 
 VOID VgaWriteMemory(DWORD Address, LPBYTE Buffer, DWORD Size)
@@ -1851,7 +1928,7 @@ VOID VgaWriteMemory(DWORD Address, LPBYTE Buffer, DWORD Size)
 
 VOID VgaClearMemory(VOID)
 {
-    ZeroMemory(VgaMemory, sizeof(VgaMemory));
+    RtlZeroMemory(VgaMemory, sizeof(VgaMemory));
 }
 
 VOID VgaResetPalette(VOID)
@@ -1864,6 +1941,96 @@ VOID VgaResetPalette(VOID)
     PaletteChanged = TRUE;
 }
 
+VOID VgaWriteFont(UINT FontNumber, CONST UCHAR *FontData, UINT Height)
+{
+    UINT i, j;
+    PUCHAR FontMemory = (PUCHAR)&VgaMemory[VGA_BANK_SIZE * VGA_FONT_BANK + (FontNumber * VGA_FONT_SIZE)];
+
+    ASSERT(Height <= VGA_MAX_FONT_HEIGHT);
+
+    for (i = 0 ; i < VGA_FONT_CHARACTERS; i++)
+    {
+        /* Write the character */
+        for (j = 0; j < Height; j++)
+        {
+            FontMemory[i * VGA_MAX_FONT_HEIGHT + j] = FontData[i * Height + j];
+        }
+
+        /* Clear the unused part */
+        for (j = Height; j < VGA_MAX_FONT_HEIGHT; j++)
+        {
+            FontMemory[i * VGA_MAX_FONT_HEIGHT + j] = 0;
+        }
+    }
+}
+
+VOID ScreenEventHandler(PWINDOW_BUFFER_SIZE_RECORD ScreenEvent)
+{
+    DPRINT1("Screen events not handled\n");
+}
+
+BOOL VgaAttachToConsole(VOID)
+{
+    //
+    // FIXME: We should go back to the saved screen state
+    //
+    if (TextResolution.X == 0 || TextResolution.Y == 0)
+        DPRINT1("VgaAttachToConsole -- TextResolution uninitialized\n");
+
+    if (TextResolution.X == 0) TextResolution.X = 80;
+    if (TextResolution.Y == 0) TextResolution.Y = 25;
+
+    return VgaAttachToConsoleInternal(&TextResolution);
+}
+
+VOID VgaDetachFromConsole(BOOL ChangingMode)
+{
+    ULONG dummyLength;
+    PVOID dummyPtr;
+    COORD dummySize = {0};
+
+    //
+    // FIXME: We should save the screen state
+    //
+
+    __RegisterConsoleVDM(0,
+                         NULL,
+                         NULL,
+                         NULL,
+                         0,
+                         &dummyLength,
+                         &dummyPtr,
+                         NULL,
+                         0,
+                         dummySize,
+                         &dummyPtr);
+
+    TextFramebuffer = NULL;
+
+    if (!ChangingMode)
+    {
+        SMALL_RECT ConRect;
+
+        /* Restore the old screen buffer */
+        VgaSetActiveScreenBuffer(TextConsoleBuffer);
+
+        /* Restore the original console size */
+        ConRect.Left   = 0;
+        ConRect.Top    = 0;
+        ConRect.Right  = ConRect.Left + OrgConsoleBufferInfo.srWindow.Right  - OrgConsoleBufferInfo.srWindow.Left;
+        ConRect.Bottom = ConRect.Top  + OrgConsoleBufferInfo.srWindow.Bottom - OrgConsoleBufferInfo.srWindow.Top ;
+        /*
+         * See the following trick explanation in VgaAttachToConsoleInternal.
+         */
+        SetConsoleScreenBufferSize(TextConsoleBuffer, OrgConsoleBufferInfo.dwSize);
+        SetConsoleWindowInfo(TextConsoleBuffer, TRUE, &ConRect);
+        SetConsoleScreenBufferSize(TextConsoleBuffer, OrgConsoleBufferInfo.dwSize);
+
+        /* Restore the original cursor shape */
+        SetConsoleCursorInfo(TextConsoleBuffer, &OrgConsoleCursorInfo);
+    }
+}
+
 BOOLEAN VgaInitialize(HANDLE TextHandle)
 {
     /* Save the default text-mode console output handle */
@@ -1883,7 +2050,7 @@ BOOLEAN VgaInitialize(HANDLE TextHandle)
     /***/ VgaResetPalette(); /***/
 
     /* Switch to the text buffer */
-    SetConsoleActiveScreenBuffer(TextConsoleBuffer);
+    VgaSetActiveScreenBuffer(TextConsoleBuffer);
 
     /* Clear the VGA memory */
     VgaClearMemory();
@@ -1925,11 +2092,6 @@ VOID VgaCleanup(VOID)
     CloseHandle(AnotherEvent);
     CloseHandle(EndEvent);
     CloseHandle(StartEvent);
-
-#if 0
-    RegisterConsoleVDM = NULL;
-    FreeLibrary(hKernel32);
-#endif
 }
 
 /* EOF */