[WIN32SS][WINSRV] Fullwidth character handling Part 2 (#2240)
[reactos.git] / win32ss / user / winsrv / consrv / frontends / gui / conwnd.c
index 35942be..633317c 100644 (file)
@@ -1,25 +1,27 @@
 /*
  * COPYRIGHT:       See COPYING in the top level directory
  * PROJECT:         ReactOS Console Server DLL
- * FILE:            frontends/gui/conwnd.c
+ * FILE:            win32ss/user/winsrv/consrv/frontends/gui/conwnd.c
  * PURPOSE:         GUI Console Window Class
  * PROGRAMMERS:     Gé van Geldorp
  *                  Johannes Anderwald
  *                  Jeffrey Morlan
  *                  Hermes Belusca-Maito (hermes.belusca@sfr.fr)
+ *                  Katayama Hirofumi MZ (katayama.hirofumi.mz@gmail.com)
  */
 
 /* INCLUDES *******************************************************************/
 
 #include <consrv.h>
-
+#include <intrin.h>
 #include <windowsx.h>
+#include <shellapi.h>
 
 #define NDEBUG
 #include <debug.h>
 
+#include "concfg/font.h"
 #include "guiterm.h"
-#include "conwnd.h"
 #include "resource.h"
 
 /* GLOBALS ********************************************************************/
@@ -137,7 +139,7 @@ RegisterConWndClass(IN HINSTANCE hInstance)
                                  GetSystemMetrics(SM_CXSMICON),
                                  GetSystemMetrics(SM_CYSMICON),
                                  LR_SHARED);
-    ghDefaultCursor = LoadCursorW(NULL, IDC_ARROW);
+    ghDefaultCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_ARROW));
 
     WndClass.cbSize = sizeof(WNDCLASSEXW);
     WndClass.lpszClassName = GUI_CONWND_CLASS;
@@ -147,7 +149,7 @@ RegisterConWndClass(IN HINSTANCE hInstance)
     WndClass.hIcon = ghDefaultIcon;
     WndClass.hIconSm = ghDefaultIconSm;
     WndClass.hCursor = ghDefaultCursor;
-    WndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); // The color of a terminal when it is switched off.
+    WndClass.hbrBackground = NULL;
     WndClass.lpszMenuName = NULL;
     WndClass.cbClsExtra = 0;
     WndClass.cbWndExtra = GWLP_CONWND_ALLOC;
@@ -171,32 +173,6 @@ UnRegisterConWndClass(HINSTANCE hInstance)
     return !!UnregisterClassW(GUI_CONWND_CLASS, hInstance);
 }
 
-
-
-static VOID
-GetScreenBufferSizeUnits(IN PCONSOLE_SCREEN_BUFFER Buffer,
-                         IN PGUI_CONSOLE_DATA GuiData,
-                         OUT PUINT WidthUnit,
-                         OUT PUINT HeightUnit)
-{
-    if (Buffer == NULL || GuiData == NULL ||
-        WidthUnit == NULL || HeightUnit == NULL)
-    {
-        return;
-    }
-
-    if (GetType(Buffer) == TEXTMODE_BUFFER)
-    {
-        *WidthUnit  = GuiData->CharWidth ;
-        *HeightUnit = GuiData->CharHeight;
-    }
-    else /* if (GetType(Buffer) == GRAPHICS_BUFFER) */
-    {
-        *WidthUnit  = 1;
-        *HeightUnit = 1;
-    }
-}
-
 static VOID
 AppendMenuItems(HMENU hMenu,
                 const GUICONSOLE_MENUITEM *Items)
@@ -212,7 +188,7 @@ AppendMenuItems(HMENU hMenu,
             if (LoadStringW(ConSrvDllInstance,
                             Items[i].uID,
                             szMenuString,
-                            sizeof(szMenuString) / sizeof(szMenuString[0])) > 0)
+                            ARRAYSIZE(szMenuString)) > 0)
             {
                 if (Items[i].SubMenu != NULL)
                 {
@@ -250,26 +226,49 @@ AppendMenuItems(HMENU hMenu,
     } while (!(Items[i].uID == 0 && Items[i].SubMenu == NULL && Items[i].wCmdID == 0));
 }
 
-static VOID
+//static
+VOID
 CreateSysMenu(HWND hWnd)
 {
-    HMENU hMenu = GetSystemMenu(hWnd, FALSE);
-    if (hMenu != NULL)
+    MENUITEMINFOW mii;
+    HMENU hMenu;
+    PWCHAR ptrTab;
+    WCHAR szMenuStringBack[255];
+
+    hMenu = GetSystemMenu(hWnd, FALSE);
+    if (hMenu == NULL)
+        return;
+
+    mii.cbSize = sizeof(mii);
+    mii.fMask = MIIM_STRING;
+    mii.dwTypeData = szMenuStringBack;
+    mii.cch = ARRAYSIZE(szMenuStringBack);
+
+    GetMenuItemInfoW(hMenu, SC_CLOSE, FALSE, &mii);
+
+    ptrTab = wcschr(szMenuStringBack, L'\t');
+    if (ptrTab)
     {
-        AppendMenuItems(hMenu, GuiConsoleMainMenuItems);
-        DrawMenuBar(hWnd);
+        *ptrTab = L'\0';
+        mii.cch = wcslen(szMenuStringBack);
+
+        SetMenuItemInfoW(hMenu, SC_CLOSE, FALSE, &mii);
     }
+
+    AppendMenuItems(hMenu, GuiConsoleMainMenuItems);
+    DrawMenuBar(hWnd);
 }
 
 static VOID
-SendMenuEvent(PCONSOLE Console, UINT CmdId)
+SendMenuEvent(PCONSRV_CONSOLE Console, UINT CmdId)
 {
     INPUT_RECORD er;
 
-    DPRINT1("Menu item ID: %d\n", CmdId);
+    DPRINT("Menu item ID: %d\n", CmdId);
 
-    if (!ConDrvValidateConsoleUnsafe(Console, CONSOLE_RUNNING, TRUE)) return;
+    if (!ConDrvValidateConsoleUnsafe((PCONSOLE)Console, CONSOLE_RUNNING, TRUE)) return;
 
+    /* Send a menu event */
     er.EventType = MENU_EVENT;
     er.Event.MenuEvent.dwCommandId = CmdId;
     ConioProcessInputEvent(Console, &er);
@@ -282,7 +281,9 @@ Copy(PGUI_CONSOLE_DATA GuiData);
 static VOID
 Paste(PGUI_CONSOLE_DATA GuiData);
 static VOID
-UpdateSelection(PGUI_CONSOLE_DATA GuiData, PCOORD coord);
+UpdateSelection(PGUI_CONSOLE_DATA GuiData,
+                PCOORD SelectionAnchor OPTIONAL,
+                PCOORD coord);
 
 static VOID
 Mark(PGUI_CONSOLE_DATA GuiData)
@@ -290,30 +291,28 @@ Mark(PGUI_CONSOLE_DATA GuiData)
     PCONSOLE_SCREEN_BUFFER ActiveBuffer = GuiData->ActiveBuffer;
 
     /* Clear the old selection */
-    // UpdateSelection(GuiData, NULL);
     GuiData->Selection.dwFlags = CONSOLE_NO_SELECTION;
 
     /* Restart a new selection */
-    GuiData->dwSelectionCursor.X = ActiveBuffer->ViewOrigin.X;
-    GuiData->dwSelectionCursor.Y = ActiveBuffer->ViewOrigin.Y;
-    GuiData->Selection.dwSelectionAnchor = GuiData->dwSelectionCursor;
-    UpdateSelection(GuiData, &GuiData->Selection.dwSelectionAnchor);
+    GuiData->dwSelectionCursor = ActiveBuffer->ViewOrigin;
+    UpdateSelection(GuiData,
+                    &GuiData->dwSelectionCursor,
+                    &GuiData->dwSelectionCursor);
 }
 
 static VOID
 SelectAll(PGUI_CONSOLE_DATA GuiData)
 {
     PCONSOLE_SCREEN_BUFFER ActiveBuffer = GuiData->ActiveBuffer;
+    COORD SelectionAnchor;
 
     /* Clear the old selection */
-    // UpdateSelection(GuiData, NULL);
     GuiData->Selection.dwFlags = CONSOLE_NO_SELECTION;
 
     /*
      * The selection area extends to the whole screen buffer's width.
      */
-    GuiData->Selection.dwSelectionAnchor.X = 0;
-    GuiData->Selection.dwSelectionAnchor.Y = 0;
+    SelectionAnchor.X = SelectionAnchor.Y = 0;
     GuiData->dwSelectionCursor.X = ActiveBuffer->ScreenBufferSize.X - 1;
 
     /*
@@ -339,14 +338,14 @@ SelectAll(PGUI_CONSOLE_DATA GuiData)
 
     /* Restart a new selection */
     GuiData->Selection.dwFlags |= CONSOLE_MOUSE_SELECTION;
-    UpdateSelection(GuiData, &GuiData->dwSelectionCursor);
+    UpdateSelection(GuiData, &SelectionAnchor, &GuiData->dwSelectionCursor);
 }
 
 static LRESULT
 OnCommand(PGUI_CONSOLE_DATA GuiData, WPARAM wParam, LPARAM lParam)
 {
     LRESULT Ret = TRUE;
-    PCONSOLE Console = GuiData->Console;
+    PCONSRV_CONSOLE Console = GuiData->Console;
 
     /*
      * In case the selected menu item belongs to the user-reserved menu id range,
@@ -428,7 +427,7 @@ ResizeConWnd(PGUI_CONSOLE_DATA GuiData, DWORD WidthUnit, DWORD HeightUnit)
              2 * (GetSystemMetrics(SM_CYFRAME) + GetSystemMetrics(SM_CYEDGE)) + GetSystemMetrics(SM_CYCAPTION);
 
     /* Set scrollbar sizes */
-    sInfo.cbSize = sizeof(SCROLLINFO);
+    sInfo.cbSize = sizeof(sInfo);
     sInfo.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
     sInfo.nMin = 0;
     if (Buff->ScreenBufferSize.Y > Buff->ViewSize.Y)
@@ -459,94 +458,161 @@ ResizeConWnd(PGUI_CONSOLE_DATA GuiData, DWORD WidthUnit, DWORD HeightUnit)
         ShowScrollBar(GuiData->hWindow, SB_HORZ, FALSE);
     }
 
-    /* Resize the window  */
+    /* Resize the window */
     SetWindowPos(GuiData->hWindow, NULL, 0, 0, Width, Height,
                  SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOCOPYBITS);
     // NOTE: The SWP_NOCOPYBITS flag can be replaced by a subsequent call
     // to: InvalidateRect(GuiData->hWindow, NULL, TRUE);
 }
 
-static BOOL
-OnNcCreate(HWND hWnd, LPCREATESTRUCTW Create)
-{
-    PGUI_CONSOLE_DATA GuiData = (PGUI_CONSOLE_DATA)Create->lpCreateParams;
-    PCONSOLE Console;
-    HDC hDC;
-    HFONT OldFont;
-    TEXTMETRICW Metrics;
-    SIZE CharSize;
 
-    if (NULL == GuiData)
+VOID
+DeleteFonts(PGUI_CONSOLE_DATA GuiData)
+{
+    ULONG i;
+    for (i = 0; i < ARRAYSIZE(GuiData->Font); ++i)
     {
-        DPRINT1("GuiConsoleNcCreate: No GUI data\n");
-        return FALSE;
+        if (GuiData->Font[i] != NULL) DeleteObject(GuiData->Font[i]);
+        GuiData->Font[i] = NULL;
     }
+}
 
-    Console = GuiData->Console;
+static HFONT
+CreateDerivedFont(HFONT OrgFont,
+                  // COORD   FontSize,
+                  ULONG   FontWeight,
+                  // BOOLEAN bItalic,
+                  BOOLEAN bUnderline,
+                  BOOLEAN bStrikeOut)
+{
+    LOGFONTW lf;
 
-    GuiData->hWindow = hWnd;
+    /* Initialize the LOGFONT structure */
+    RtlZeroMemory(&lf, sizeof(lf));
+
+    /* Retrieve the details of the current font */
+    if (GetObjectW(OrgFont, sizeof(lf), &lf) == 0)
+        return NULL;
+
+    /* Change the font attributes */
+    // lf.lfHeight = FontSize.Y;
+    // lf.lfWidth  = FontSize.X;
+    lf.lfWeight = FontWeight;
+    // lf.lfItalic = bItalic;
+    lf.lfUnderline = bUnderline;
+    lf.lfStrikeOut = bStrikeOut;
+
+    /* Build a new font */
+    return CreateFontIndirectW(&lf);
+}
 
-    GuiData->Font = CreateFontW(LOWORD(GuiData->GuiInfo.FontSize),
-                                0, // HIWORD(GuiData->GuiInfo.FontSize),
-                                0,
-                                TA_BASELINE,
-                                GuiData->GuiInfo.FontWeight,
-                                FALSE,
-                                FALSE,
-                                FALSE,
-                                OEM_CHARSET,
-                                OUT_DEFAULT_PRECIS,
-                                CLIP_DEFAULT_PRECIS,
-                                NONANTIALIASED_QUALITY,
-                                FIXED_PITCH | GuiData->GuiInfo.FontFamily /* FF_DONTCARE */,
-                                GuiData->GuiInfo.FaceName);
-
-    if (NULL == GuiData->Font)
+BOOL
+InitFonts(PGUI_CONSOLE_DATA GuiData,
+          LPWSTR FaceName, // Points to a WCHAR array of LF_FACESIZE elements.
+          ULONG  FontFamily,
+          COORD  FontSize,
+          ULONG  FontWeight)
+{
+    HDC hDC;
+    HFONT hFont;
+
+    /*
+     * Initialize a new NORMAL font and get its character cell size.
+     */
+    /* NOTE: FontSize is always in cell height/width units (pixels) */
+    hFont = CreateConsoleFontEx((LONG)(ULONG)FontSize.Y,
+                                (LONG)(ULONG)FontSize.X,
+                                FaceName,
+                                FontFamily,
+                                FontWeight,
+                                GuiData->Console->OutputCodePage);
+    if (hFont == NULL)
     {
-        DPRINT1("GuiConsoleNcCreate: CreateFont failed\n");
-        GuiData->hWindow = NULL;
-        SetEvent(GuiData->hGuiInitEvent);
+        DPRINT1("InitFonts: CreateConsoleFontEx failed\n");
         return FALSE;
     }
+
     hDC = GetDC(GuiData->hWindow);
-    if (NULL == hDC)
+    if (!GetFontCellSize(hDC, hFont, &GuiData->CharHeight, &GuiData->CharWidth))
     {
-        DPRINT1("GuiConsoleNcCreate: GetDC failed\n");
-        DeleteObject(GuiData->Font);
-        GuiData->hWindow = NULL;
-        SetEvent(GuiData->hGuiInitEvent);
+        DPRINT1("InitFonts: GetFontCellSize failed\n");
+        ReleaseDC(GuiData->hWindow, hDC);
+        DeleteObject(hFont);
         return FALSE;
     }
-    OldFont = SelectObject(hDC, GuiData->Font);
-    if (NULL == OldFont)
+    ReleaseDC(GuiData->hWindow, hDC);
+
+    /*
+     * Initialization succeeded.
+     */
+    // Delete all the old fonts first.
+    DeleteFonts(GuiData);
+    GuiData->Font[FONT_NORMAL] = hFont;
+
+    /*
+     * Now build the other fonts (bold, underlined, mixed).
+     */
+    GuiData->Font[FONT_BOLD] =
+        CreateDerivedFont(GuiData->Font[FONT_NORMAL],
+                          FontWeight < FW_BOLD ? FW_BOLD : FontWeight,
+                          FALSE,
+                          FALSE);
+    GuiData->Font[FONT_UNDERLINE] =
+        CreateDerivedFont(GuiData->Font[FONT_NORMAL],
+                          FontWeight,
+                          TRUE,
+                          FALSE);
+    GuiData->Font[FONT_BOLD | FONT_UNDERLINE] =
+        CreateDerivedFont(GuiData->Font[FONT_NORMAL],
+                          FontWeight < FW_BOLD ? FW_BOLD : FontWeight,
+                          TRUE,
+                          FALSE);
+
+    /*
+     * Save the settings.
+     */
+    if (FaceName != GuiData->GuiInfo.FaceName)
     {
-        DPRINT1("GuiConsoleNcCreate: SelectObject failed\n");
-        ReleaseDC(GuiData->hWindow, hDC);
-        DeleteObject(GuiData->Font);
-        GuiData->hWindow = NULL;
-        SetEvent(GuiData->hGuiInitEvent);
-        return FALSE;
+        StringCchCopyNW(GuiData->GuiInfo.FaceName, ARRAYSIZE(GuiData->GuiInfo.FaceName),
+                        FaceName, LF_FACESIZE);
     }
-    if (!GetTextMetricsW(hDC, &Metrics))
+    GuiData->GuiInfo.FontFamily = FontFamily;
+    GuiData->GuiInfo.FontSize   = FontSize;
+    GuiData->GuiInfo.FontWeight = FontWeight;
+
+    return TRUE;
+}
+
+
+static BOOL
+OnNcCreate(HWND hWnd, LPCREATESTRUCTW Create)
+{
+    PGUI_CONSOLE_DATA GuiData = (PGUI_CONSOLE_DATA)Create->lpCreateParams;
+    PCONSRV_CONSOLE Console;
+
+    if (GuiData == NULL)
     {
-        DPRINT1("GuiConsoleNcCreate: GetTextMetrics failed\n");
-        SelectObject(hDC, OldFont);
-        ReleaseDC(GuiData->hWindow, hDC);
-        DeleteObject(GuiData->Font);
-        GuiData->hWindow = NULL;
-        SetEvent(GuiData->hGuiInitEvent);
+        DPRINT1("GuiConsoleNcCreate: No GUI data\n");
         return FALSE;
     }
-    GuiData->CharWidth  = Metrics.tmMaxCharWidth;
-    GuiData->CharHeight = Metrics.tmHeight + Metrics.tmExternalLeading;
 
-    /* Measure real char width more precisely if possible. */
-    if (GetTextExtentPoint32W(hDC, L"R", 1, &CharSize))
-        GuiData->CharWidth = CharSize.cx;
-
-    SelectObject(hDC, OldFont);
+    Console = GuiData->Console;
 
-    ReleaseDC(GuiData->hWindow, hDC);
+    GuiData->hWindow = hWnd;
+    GuiData->hSysMenu = GetSystemMenu(hWnd, FALSE);
+
+    /* Initialize the fonts */
+    if (!InitFonts(GuiData,
+                   GuiData->GuiInfo.FaceName,
+                   GuiData->GuiInfo.FontFamily,
+                   GuiData->GuiInfo.FontSize,
+                   GuiData->GuiInfo.FontWeight))
+    {
+        DPRINT1("GuiConsoleNcCreate: InitFonts failed\n");
+        GuiData->hWindow = NULL;
+        NtSetEvent(GuiData->hGuiInitEvent, NULL);
+        return FALSE;
+    }
 
     /* Initialize the terminal framebuffer */
     GuiData->hMemDC  = CreateCompatibleDC(NULL);
@@ -567,32 +633,29 @@ OnNcCreate(HWND hWnd, LPCREATESTRUCTW Create)
 
     SetWindowLongPtrW(GuiData->hWindow, GWLP_USERDATA, (DWORD_PTR)GuiData);
 
-    SetTimer(GuiData->hWindow, CONGUI_UPDATE_TIMER, CONGUI_UPDATE_TIME, NULL);
-    CreateSysMenu(GuiData->hWindow);
+    if (GuiData->IsWindowVisible)
+    {
+        SetTimer(GuiData->hWindow, CONGUI_UPDATE_TIMER, CONGUI_UPDATE_TIME, NULL);
+    }
+
+    // FIXME: HACK: Potential HACK for CORE-8129; see revision 63595.
+    //CreateSysMenu(GuiData->hWindow);
 
     DPRINT("OnNcCreate - setting start event\n");
-    SetEvent(GuiData->hGuiInitEvent);
+    NtSetEvent(GuiData->hGuiInitEvent, NULL);
+
+    /* We accept dropped files */
+    DragAcceptFiles(GuiData->hWindow, TRUE);
 
     return (BOOL)DefWindowProcW(GuiData->hWindow, WM_NCCREATE, 0, (LPARAM)Create);
 }
 
-
-BOOL
-EnterFullScreen(PGUI_CONSOLE_DATA GuiData);
-VOID
-LeaveFullScreen(PGUI_CONSOLE_DATA GuiData);
-VOID
-SwitchFullScreen(PGUI_CONSOLE_DATA GuiData, BOOL FullScreen);
-VOID
-GuiConsoleSwitchFullScreen(PGUI_CONSOLE_DATA GuiData);
-
 static VOID
 OnActivate(PGUI_CONSOLE_DATA GuiData, WPARAM wParam)
 {
-    PCONSOLE Console = GuiData->Console;
     WORD ActivationState = LOWORD(wParam);
 
-    DPRINT1("WM_ACTIVATE - ActivationState = %d\n");
+    DPRINT("WM_ACTIVATE - ActivationState = %d\n", ActivationState);
 
     if ( ActivationState == WA_ACTIVE ||
          ActivationState == WA_CLICKACTIVE )
@@ -616,23 +679,32 @@ OnActivate(PGUI_CONSOLE_DATA GuiData, WPARAM wParam)
     }
 
     /*
-     * When we are in QuickEdit mode, ignore the next mouse signal
-     * when we are going to be enabled again via the mouse, in order
-     * to prevent e.g. an erroneous right-click from the user which
-     * would have as an effect to paste some unwanted text...
+     * Ignore the next mouse signal when we are going to be enabled again via
+     * the mouse, in order to prevent, e.g. when we are in Edit mode, erroneous
+     * mouse actions from the user that could spoil text selection or copy/pastes.
      */
-    if (Console->QuickEdit && (ActivationState == WA_CLICKACTIVE))
+    if (ActivationState == WA_CLICKACTIVE)
         GuiData->IgnoreNextMouseSignal = TRUE;
 }
 
 static VOID
 OnFocus(PGUI_CONSOLE_DATA GuiData, BOOL SetFocus)
 {
-    PCONSOLE Console = GuiData->Console;
+    PCONSRV_CONSOLE Console = GuiData->Console;
     INPUT_RECORD er;
 
-    if (!ConDrvValidateConsoleUnsafe(Console, CONSOLE_RUNNING, TRUE)) return;
+    if (!ConDrvValidateConsoleUnsafe((PCONSOLE)Console, CONSOLE_RUNNING, TRUE)) return;
+
+    /* Set console focus state */
+    Console->HasFocus = SetFocus;
+
+    /*
+     * Set the priority of the processes of this console
+     * in accordance with the console focus state.
+     */
+    ConSrvSetConsoleProcessFocus(Console, SetFocus);
 
+    /* Send a focus event */
     er.EventType = FOCUS_EVENT;
     er.Event.FocusEvent.bSetFocus = SetFocus;
     ConioProcessInputEvent(Console, &er);
@@ -640,37 +712,169 @@ OnFocus(PGUI_CONSOLE_DATA GuiData, BOOL SetFocus)
     LeaveCriticalSection(&Console->Lock);
 
     if (SetFocus)
-        DPRINT1("TODO: Create console caret\n");
+        DPRINT("TODO: Create console caret\n");
+    else
+        DPRINT("TODO: Destroy console caret\n");
+}
+
+VOID
+GetSelectionBeginEnd(PCOORD Begin, PCOORD End,
+                     PCOORD SelectionAnchor,
+                     PSMALL_RECT SmallRect)
+{
+    if (Begin == NULL || End == NULL) return;
+
+    *Begin = *SelectionAnchor;
+    End->X = (SelectionAnchor->X == SmallRect->Left) ? SmallRect->Right
+              /* Case X != Left, must be == Right */ : SmallRect->Left;
+    End->Y = (SelectionAnchor->Y == SmallRect->Top ) ? SmallRect->Bottom
+              /* Case Y != Top, must be == Bottom */ : SmallRect->Top;
+
+    /* Exchange Begin / End if Begin > End lexicographically */
+    if (Begin->Y > End->Y || (Begin->Y == End->Y && Begin->X > End->X))
+    {
+        End->X = _InterlockedExchange16(&Begin->X, End->X);
+        End->Y = _InterlockedExchange16(&Begin->Y, End->Y);
+    }
+}
+
+static HRGN
+CreateSelectionRgn(PGUI_CONSOLE_DATA GuiData,
+                   BOOL LineSelection,
+                   PCOORD SelectionAnchor,
+                   PSMALL_RECT SmallRect)
+{
+    if (!LineSelection)
+    {
+        RECT rect;
+        SmallRectToRect(GuiData, &rect, SmallRect);
+        return CreateRectRgnIndirect(&rect);
+    }
     else
-        DPRINT1("TODO: Destroy console caret\n");
+    {
+        HRGN SelRgn;
+        COORD Begin, End;
+
+        GetSelectionBeginEnd(&Begin, &End, SelectionAnchor, SmallRect);
+
+        if (Begin.Y == End.Y)
+        {
+            SMALL_RECT sr;
+            RECT       r ;
+
+            sr.Left   = Begin.X;
+            sr.Top    = Begin.Y;
+            sr.Right  = End.X;
+            sr.Bottom = End.Y;
+
+            // Debug thingie to see whether I can put this corner case
+            // together with the previous one.
+            if (SmallRect->Left   != sr.Left  ||
+                SmallRect->Top    != sr.Top   ||
+                SmallRect->Right  != sr.Right ||
+                SmallRect->Bottom != sr.Bottom)
+            {
+                DPRINT1("\n"
+                        "SmallRect = (%d, %d, %d, %d)\n"
+                        "sr = (%d, %d, %d, %d)\n"
+                        "\n",
+                        SmallRect->Left, SmallRect->Top, SmallRect->Right, SmallRect->Bottom,
+                        sr.Left, sr.Top, sr.Right, sr.Bottom);
+            }
+
+            SmallRectToRect(GuiData, &r, &sr);
+            SelRgn = CreateRectRgnIndirect(&r);
+        }
+        else
+        {
+            PCONSOLE_SCREEN_BUFFER ActiveBuffer = GuiData->ActiveBuffer;
+
+            HRGN       rg1, rg2, rg3;
+            SMALL_RECT sr1, sr2, sr3;
+            RECT       r1 , r2 , r3 ;
+
+            sr1.Left   = Begin.X;
+            sr1.Top    = Begin.Y;
+            sr1.Right  = ActiveBuffer->ScreenBufferSize.X - 1;
+            sr1.Bottom = Begin.Y;
+
+            sr2.Left   = 0;
+            sr2.Top    = Begin.Y + 1;
+            sr2.Right  = ActiveBuffer->ScreenBufferSize.X - 1;
+            sr2.Bottom = End.Y - 1;
+
+            sr3.Left   = 0;
+            sr3.Top    = End.Y;
+            sr3.Right  = End.X;
+            sr3.Bottom = End.Y;
+
+            SmallRectToRect(GuiData, &r1, &sr1);
+            SmallRectToRect(GuiData, &r2, &sr2);
+            SmallRectToRect(GuiData, &r3, &sr3);
+
+            rg1 = CreateRectRgnIndirect(&r1);
+            rg2 = CreateRectRgnIndirect(&r2);
+            rg3 = CreateRectRgnIndirect(&r3);
+
+            CombineRgn(rg1, rg1, rg2, RGN_XOR);
+            CombineRgn(rg1, rg1, rg3, RGN_XOR);
+            DeleteObject(rg3);
+            DeleteObject(rg2);
+
+            SelRgn = rg1;
+        }
+
+        return SelRgn;
+    }
 }
 
 static VOID
-SmallRectToRect(PGUI_CONSOLE_DATA GuiData, PRECT Rect, PSMALL_RECT SmallRect)
+PaintSelectionRect(PGUI_CONSOLE_DATA GuiData, PPAINTSTRUCT pps)
 {
-    PCONSOLE_SCREEN_BUFFER Buffer = GuiData->ActiveBuffer;
-    UINT WidthUnit, HeightUnit;
+    HRGN rgnPaint = CreateRectRgnIndirect(&pps->rcPaint);
+    HRGN rgnSel   = CreateSelectionRgn(GuiData, GuiData->LineSelection,
+                                       &GuiData->Selection.dwSelectionAnchor,
+                                       &GuiData->Selection.srSelection);
 
-    GetScreenBufferSizeUnits(Buffer, GuiData, &WidthUnit, &HeightUnit);
+    /* Invert the selection */
 
-    Rect->left   = (SmallRect->Left       - Buffer->ViewOrigin.X) * WidthUnit ;
-    Rect->top    = (SmallRect->Top        - Buffer->ViewOrigin.Y) * HeightUnit;
-    Rect->right  = (SmallRect->Right  + 1 - Buffer->ViewOrigin.X) * WidthUnit ;
-    Rect->bottom = (SmallRect->Bottom + 1 - Buffer->ViewOrigin.Y) * HeightUnit;
+    int ErrorCode = CombineRgn(rgnPaint, rgnPaint, rgnSel, RGN_AND);
+    if (ErrorCode != ERROR && ErrorCode != NULLREGION)
+    {
+        InvertRgn(pps->hdc, rgnPaint);
+    }
+
+    DeleteObject(rgnSel);
+    DeleteObject(rgnPaint);
 }
 
 static VOID
-UpdateSelection(PGUI_CONSOLE_DATA GuiData, PCOORD coord)
+UpdateSelection(PGUI_CONSOLE_DATA GuiData,
+                PCOORD SelectionAnchor OPTIONAL,
+                PCOORD coord)
 {
-    PCONSOLE Console = GuiData->Console;
-    RECT oldRect;
+    PCONSRV_CONSOLE Console = GuiData->Console;
+    HRGN oldRgn = CreateSelectionRgn(GuiData, GuiData->LineSelection,
+                                     &GuiData->Selection.dwSelectionAnchor,
+                                     &GuiData->Selection.srSelection);
+
+    /* Update the anchor if needed (use the old one if NULL) */
+    if (SelectionAnchor)
+        GuiData->Selection.dwSelectionAnchor = *SelectionAnchor;
 
-    SmallRectToRect(GuiData, &oldRect, &GuiData->Selection.srSelection);
+    // TODO: Scroll buffer to bring 'coord' into view
 
     if (coord != NULL)
     {
-        RECT newRect;
         SMALL_RECT rc;
+        HRGN newRgn;
+
+        /*
+         * Pressing the Control key while selecting text, allows us to enter
+         * into line-selection mode, the selection mode of *nix terminals.
+         */
+        BOOL OldLineSel = GuiData->LineSelection;
+        GuiData->LineSelection = !!(GetKeyState(VK_CONTROL) & KEY_PRESSED);
 
         /* Exchange left/top with right/bottom if required */
         rc.Left   = min(GuiData->Selection.dwSelectionAnchor.X, coord->X);
@@ -678,64 +882,72 @@ UpdateSelection(PGUI_CONSOLE_DATA GuiData, PCOORD coord)
         rc.Right  = max(GuiData->Selection.dwSelectionAnchor.X, coord->X);
         rc.Bottom = max(GuiData->Selection.dwSelectionAnchor.Y, coord->Y);
 
-        SmallRectToRect(GuiData, &newRect, &rc);
+        newRgn = CreateSelectionRgn(GuiData, GuiData->LineSelection,
+                                    &GuiData->Selection.dwSelectionAnchor,
+                                    &rc);
 
         if (GuiData->Selection.dwFlags & CONSOLE_SELECTION_NOT_EMPTY)
         {
-            if (memcmp(&rc, &GuiData->Selection.srSelection, sizeof(SMALL_RECT)) != 0)
+            if (OldLineSel != GuiData->LineSelection ||
+                memcmp(&rc, &GuiData->Selection.srSelection, sizeof(SMALL_RECT)) != 0)
             {
-                HRGN rgn1, rgn2;
-
                 /* Calculate the region that needs to be updated */
-                if ((rgn1 = CreateRectRgnIndirect(&oldRect)))
+                if (oldRgn && newRgn && CombineRgn(newRgn, newRgn, oldRgn, RGN_XOR) != ERROR)
                 {
-                    if ((rgn2 = CreateRectRgnIndirect(&newRect)))
-                    {
-                        if (CombineRgn(rgn1, rgn2, rgn1, RGN_XOR) != ERROR)
-                        {
-                            InvalidateRgn(GuiData->hWindow, rgn1, FALSE);
-                        }
-                        DeleteObject(rgn2);
-                    }
-                    DeleteObject(rgn1);
+                    InvalidateRgn(GuiData->hWindow, newRgn, FALSE);
                 }
             }
         }
         else
         {
-            InvalidateRect(GuiData->hWindow, &newRect, FALSE);
+            InvalidateRgn(GuiData->hWindow, newRgn, FALSE);
         }
 
+        DeleteObject(newRgn);
+
         GuiData->Selection.dwFlags |= CONSOLE_SELECTION_NOT_EMPTY;
         GuiData->Selection.srSelection = rc;
         GuiData->dwSelectionCursor = *coord;
 
         if ((GuiData->Selection.dwFlags & CONSOLE_SELECTION_IN_PROGRESS) == 0)
         {
-            LPWSTR SelectionType, WindowTitle = NULL;
-            SIZE_T Length = 0;
+            LPWSTR SelTypeStr = NULL   , WindowTitle = NULL;
+            SIZE_T SelTypeStrLength = 0, Length = 0;
 
             /* Clear the old selection */
             if (GuiData->Selection.dwFlags & CONSOLE_SELECTION_NOT_EMPTY)
             {
-                InvalidateRect(GuiData->hWindow, &oldRect, FALSE);
+                InvalidateRgn(GuiData->hWindow, oldRgn, FALSE);
             }
 
-            if (GuiData->Selection.dwFlags & CONSOLE_MOUSE_SELECTION)
-            {
-                SelectionType = L"Selection - ";
-            }
-            else
+            /*
+             * When passing a zero-length buffer size, LoadString(...) returns
+             * a read-only pointer buffer to the program's resource string.
+             */
+            SelTypeStrLength =
+                LoadStringW(ConSrvDllInstance,
+                            (GuiData->Selection.dwFlags & CONSOLE_MOUSE_SELECTION)
+                                ? IDS_SELECT_TITLE : IDS_MARK_TITLE,
+                            (LPWSTR)&SelTypeStr, 0);
+
+            /*
+             * Prepend the selection type string to the current console title
+             * if we succeeded in retrieving a valid localized string.
+             */
+            if (SelTypeStr)
             {
-                SelectionType = L"Mark - ";
-            }
+                // 3 for " - " and 1 for NULL
+                Length = Console->Title.Length + (SelTypeStrLength + 3 + 1) * sizeof(WCHAR);
+                WindowTitle = ConsoleAllocHeap(0, Length);
 
-            Length = Console->Title.Length + wcslen(SelectionType) + 1;
-            WindowTitle = ConsoleAllocHeap(0, Length * sizeof(WCHAR));
-            wcscpy(WindowTitle, SelectionType);
-            wcscat(WindowTitle, Console->Title.Buffer);
-            SetWindowText(GuiData->hWindow, WindowTitle);
-            ConsoleFreeHeap(WindowTitle);
+                wcsncpy(WindowTitle, SelTypeStr, SelTypeStrLength);
+                WindowTitle[SelTypeStrLength] = UNICODE_NULL;
+                wcscat(WindowTitle, L" - ");
+                wcscat(WindowTitle, Console->Title.Buffer);
+
+                SetWindowTextW(GuiData->hWindow, WindowTitle);
+                ConsoleFreeHeap(WindowTitle);
+            }
 
             GuiData->Selection.dwFlags |= CONSOLE_SELECTION_IN_PROGRESS;
             ConioPause(Console, PAUSED_FROM_SELECTION);
@@ -746,36 +958,28 @@ UpdateSelection(PGUI_CONSOLE_DATA GuiData, PCOORD coord)
         /* Clear the selection */
         if (GuiData->Selection.dwFlags & CONSOLE_SELECTION_NOT_EMPTY)
         {
-            InvalidateRect(GuiData->hWindow, &oldRect, FALSE);
+            InvalidateRgn(GuiData->hWindow, oldRgn, FALSE);
         }
 
         GuiData->Selection.dwFlags = CONSOLE_NO_SELECTION;
         ConioUnpause(Console, PAUSED_FROM_SELECTION);
 
-        SetWindowText(GuiData->hWindow, Console->Title.Buffer);
+        /* Restore the console title */
+        SetWindowTextW(GuiData->hWindow, Console->Title.Buffer);
     }
-}
-
 
-VOID
-GuiPaintTextModeBuffer(PTEXTMODE_SCREEN_BUFFER Buffer,
-                       PGUI_CONSOLE_DATA GuiData,
-                       PRECT rcView,
-                       PRECT rcFramebuffer);
-VOID
-GuiPaintGraphicsBuffer(PGRAPHICS_SCREEN_BUFFER Buffer,
-                       PGUI_CONSOLE_DATA GuiData,
-                       PRECT rcView,
-                       PRECT rcFramebuffer);
+    DeleteObject(oldRgn);
+}
 
 static VOID
 OnPaint(PGUI_CONSOLE_DATA GuiData)
 {
-    PCONSOLE_SCREEN_BUFFER ActiveBuffer;
+    PCONSOLE_SCREEN_BUFFER ActiveBuffer = GuiData->ActiveBuffer;
     PAINTSTRUCT ps;
     RECT rcPaint;
 
-    ActiveBuffer = GuiData->ActiveBuffer;
+    /* Do nothing if the window is hidden */
+    if (!GuiData->IsWindowVisible) return;
 
     BeginPaint(GuiData->hWindow, &ps);
     if (ps.hdc != NULL &&
@@ -807,17 +1011,14 @@ OnPaint(PGUI_CONSOLE_DATA GuiData)
                rcPaint.top,
                SRCCOPY);
 
+        /* Draw the selection region if needed */
         if (GuiData->Selection.dwFlags & CONSOLE_SELECTION_NOT_EMPTY)
         {
-            SmallRectToRect(GuiData, &rcPaint, &GuiData->Selection.srSelection);
-
-            /* Invert the selection */
-            if (IntersectRect(&rcPaint, &ps.rcPaint, &rcPaint))
-            {
-                InvertRect(ps.hdc, &rcPaint);
-            }
+            PaintSelectionRect(GuiData, &ps);
         }
 
+        // TODO: Move cursor display here!
+
         LeaveCriticalSection(&GuiData->Lock);
     }
     EndPaint(GuiData->hWindow, &ps);
@@ -830,6 +1031,9 @@ OnPaletteChanged(PGUI_CONSOLE_DATA GuiData)
 {
     PCONSOLE_SCREEN_BUFFER ActiveBuffer = GuiData->ActiveBuffer;
 
+    /* Do nothing if the window is hidden */
+    if (!GuiData->IsWindowVisible) return;
+
     // See WM_PALETTECHANGED message
     // if ((HWND)wParam == hWnd) break;
 
@@ -872,10 +1076,10 @@ IsSystemKey(WORD VirtualKeyCode)
 static VOID
 OnKey(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
 {
-    PCONSOLE Console = GuiData->Console;
+    PCONSRV_CONSOLE Console = GuiData->Console;
     PCONSOLE_SCREEN_BUFFER ActiveBuffer;
 
-    if (!ConDrvValidateConsoleUnsafe(Console, CONSOLE_RUNNING, TRUE)) return;
+    if (!ConDrvValidateConsoleUnsafe((PCONSOLE)Console, CONSOLE_RUNNING, TRUE)) return;
 
     ActiveBuffer = GuiData->ActiveBuffer;
 
@@ -892,10 +1096,10 @@ OnKey(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
             goto Quit;
         }
         else if ( VirtualKeyCode == VK_ESCAPE ||
-                 (VirtualKeyCode == 'C' && GetKeyState(VK_CONTROL) & 0x8000) )
+                 (VirtualKeyCode == 'C' && (GetKeyState(VK_CONTROL) & KEY_PRESSED)) )
         {
             /* Cancel selection if ESC or Ctrl-C are pressed */
-            UpdateSelection(GuiData, NULL);
+            UpdateSelection(GuiData, NULL, NULL);
             goto Quit;
         }
 
@@ -903,7 +1107,7 @@ OnKey(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
         {
             /* Keyboard selection mode */
             BOOL Interpreted = FALSE;
-            BOOL MajPressed  = (GetKeyState(VK_SHIFT) & 0x8000);
+            BOOL MajPressed  = !!(GetKeyState(VK_SHIFT) & KEY_PRESSED);
 
             switch (VirtualKeyCode)
             {
@@ -984,10 +1188,9 @@ OnKey(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
 
             if (Interpreted)
             {
-                if (!MajPressed)
-                    GuiData->Selection.dwSelectionAnchor = GuiData->dwSelectionCursor;
-
-                UpdateSelection(GuiData, &GuiData->dwSelectionCursor);
+                UpdateSelection(GuiData,
+                                !MajPressed ? &GuiData->dwSelectionCursor : NULL,
+                                &GuiData->dwSelectionCursor);
             }
             else if (!IsSystemKey(VirtualKeyCode))
             {
@@ -1004,7 +1207,7 @@ OnKey(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
             if (!IsSystemKey(VirtualKeyCode))
             {
                 /* Clear the selection and send the key into the input buffer */
-                UpdateSelection(GuiData, NULL);
+                UpdateSelection(GuiData, NULL, NULL);
             }
             else
             {
@@ -1038,12 +1241,15 @@ InvalidateCell(PGUI_CONSOLE_DATA GuiData,
 static VOID
 OnTimer(PGUI_CONSOLE_DATA GuiData)
 {
-    PCONSOLE Console = GuiData->Console;
+    PCONSRV_CONSOLE Console = GuiData->Console;
     PCONSOLE_SCREEN_BUFFER Buff;
 
+    /* Do nothing if the window is hidden */
+    if (!GuiData->IsWindowVisible) return;
+
     SetTimer(GuiData->hWindow, CONGUI_UPDATE_TIMER, CURSOR_BLINK_TIME, NULL);
 
-    if (!ConDrvValidateConsoleUnsafe(Console, CONSOLE_RUNNING, TRUE)) return;
+    if (!ConDrvValidateConsoleUnsafe((PCONSOLE)Console, CONSOLE_RUNNING, TRUE)) return;
 
     Buff = GuiData->ActiveBuffer;
 
@@ -1055,15 +1261,15 @@ OnTimer(PGUI_CONSOLE_DATA GuiData)
         if ((GuiData->OldCursor.x != Buff->CursorPosition.X) ||
             (GuiData->OldCursor.y != Buff->CursorPosition.Y))
         {
-            SCROLLINFO xScroll;
+            SCROLLINFO sInfo;
             int OldScrollX = -1, OldScrollY = -1;
             int NewScrollX = -1, NewScrollY = -1;
 
-            xScroll.cbSize = sizeof(SCROLLINFO);
-            xScroll.fMask = SIF_POS;
+            sInfo.cbSize = sizeof(sInfo);
+            sInfo.fMask = SIF_POS;
             // Capture the original position of the scroll bars and save them.
-            if (GetScrollInfo(GuiData->hWindow, SB_HORZ, &xScroll)) OldScrollX = xScroll.nPos;
-            if (GetScrollInfo(GuiData->hWindow, SB_VERT, &xScroll)) OldScrollY = xScroll.nPos;
+            if (GetScrollInfo(GuiData->hWindow, SB_HORZ, &sInfo)) OldScrollX = sInfo.nPos;
+            if (GetScrollInfo(GuiData->hWindow, SB_VERT, &sInfo)) OldScrollY = sInfo.nPos;
 
             // If we successfully got the info for the horizontal scrollbar
             if (OldScrollX >= 0)
@@ -1118,13 +1324,13 @@ OnTimer(PGUI_CONSOLE_DATA GuiData)
                                SW_INVALIDATE);
                 if (NewScrollX >= 0)
                 {
-                    xScroll.nPos = NewScrollX;
-                    SetScrollInfo(GuiData->hWindow, SB_HORZ, &xScroll, TRUE);
+                    sInfo.nPos = NewScrollX;
+                    SetScrollInfo(GuiData->hWindow, SB_HORZ, &sInfo, TRUE);
                 }
                 if (NewScrollY >= 0)
                 {
-                    xScroll.nPos = NewScrollY;
-                    SetScrollInfo(GuiData->hWindow, SB_VERT, &xScroll, TRUE);
+                    sInfo.nPos = NewScrollY;
+                    SetScrollInfo(GuiData->hWindow, SB_VERT, &sInfo, TRUE);
                 }
                 UpdateWindow(GuiData->hWindow);
                 // InvalidateRect(GuiData->hWindow, NULL, FALSE);
@@ -1143,9 +1349,9 @@ OnTimer(PGUI_CONSOLE_DATA GuiData)
 static BOOL
 OnClose(PGUI_CONSOLE_DATA GuiData)
 {
-    PCONSOLE Console = GuiData->Console;
+    PCONSRV_CONSOLE Console = GuiData->Console;
 
-    if (!ConDrvValidateConsoleUnsafe(Console, CONSOLE_RUNNING, TRUE))
+    if (!ConDrvValidateConsoleUnsafe((PCONSOLE)Console, CONSOLE_RUNNING, TRUE))
         return TRUE;
 
     // TODO: Prompt for termination ? (Warn the user about possible apps running in this console)
@@ -1166,24 +1372,135 @@ OnNcDestroy(HWND hWnd)
 {
     PGUI_CONSOLE_DATA GuiData = GuiGetGuiData(hWnd);
 
-    KillTimer(hWnd, CONGUI_UPDATE_TIMER);
+    /* Free the GuiData registration */
+    SetWindowLongPtrW(hWnd, GWLP_USERDATA, (DWORD_PTR)NULL);
+
+    /* Reset the system menu back to default and destroy the previous menu */
     GetSystemMenu(hWnd, TRUE);
 
     if (GuiData)
     {
+        if (GuiData->IsWindowVisible)
+            KillTimer(hWnd, CONGUI_UPDATE_TIMER);
+
         /* Free the terminal framebuffer */
         if (GuiData->hMemDC ) DeleteDC(GuiData->hMemDC);
         if (GuiData->hBitmap) DeleteObject(GuiData->hBitmap);
         // if (GuiData->hSysPalette) DeleteObject(GuiData->hSysPalette);
-        if (GuiData->Font) DeleteObject(GuiData->Font);
+        DeleteFonts(GuiData);
     }
 
-    /* Free the GuiData registration */
-    SetWindowLongPtrW(hWnd, GWLP_USERDATA, (DWORD_PTR)NULL);
-
     return DefWindowProcW(hWnd, WM_NCDESTROY, 0, 0);
 }
 
+static VOID
+OnScroll(PGUI_CONSOLE_DATA GuiData, INT nBar, WORD sbCode)
+{
+    PCONSRV_CONSOLE Console = GuiData->Console;
+    PCONSOLE_SCREEN_BUFFER Buff;
+    SCROLLINFO sInfo;
+    INT oldPos, Maximum;
+    PSHORT pOriginXY;
+
+    ASSERT(nBar == SB_HORZ || nBar == SB_VERT);
+
+    if (!ConDrvValidateConsoleUnsafe((PCONSOLE)Console, CONSOLE_RUNNING, TRUE)) return;
+
+    Buff = GuiData->ActiveBuffer;
+
+    if (nBar == SB_HORZ)
+    {
+        Maximum = Buff->ScreenBufferSize.X - Buff->ViewSize.X;
+        pOriginXY = &Buff->ViewOrigin.X;
+    }
+    else // if (nBar == SB_VERT)
+    {
+        Maximum = Buff->ScreenBufferSize.Y - Buff->ViewSize.Y;
+        pOriginXY = &Buff->ViewOrigin.Y;
+    }
+
+    /* Set scrollbar sizes */
+    sInfo.cbSize = sizeof(sInfo);
+    sInfo.fMask = SIF_RANGE | SIF_POS | SIF_PAGE | SIF_TRACKPOS;
+
+    if (!GetScrollInfo(GuiData->hWindow, nBar, &sInfo)) goto Quit;
+
+    oldPos = sInfo.nPos;
+
+    switch (sbCode)
+    {
+        case SB_LINEUP:   // SB_LINELEFT:
+            sInfo.nPos--;
+            break;
+
+        case SB_LINEDOWN: // SB_LINERIGHT:
+            sInfo.nPos++;
+            break;
+
+        case SB_PAGEUP:   // SB_PAGELEFT:
+            sInfo.nPos -= sInfo.nPage;
+            break;
+
+        case SB_PAGEDOWN: // SB_PAGERIGHT:
+            sInfo.nPos += sInfo.nPage;
+            break;
+
+        case SB_THUMBTRACK:
+            sInfo.nPos = sInfo.nTrackPos;
+            ConioPause(Console, PAUSED_FROM_SCROLLBAR);
+            break;
+
+        case SB_THUMBPOSITION:
+            sInfo.nPos = sInfo.nTrackPos;
+            ConioUnpause(Console, PAUSED_FROM_SCROLLBAR);
+            break;
+
+        case SB_TOP:    // SB_LEFT:
+            sInfo.nPos = sInfo.nMin;
+            break;
+
+        case SB_BOTTOM: // SB_RIGHT:
+            sInfo.nPos = sInfo.nMax;
+            break;
+
+        default:
+            break;
+    }
+
+    sInfo.nPos = min(max(sInfo.nPos, 0), Maximum);
+
+    if (oldPos != sInfo.nPos)
+    {
+        USHORT OldX = Buff->ViewOrigin.X;
+        USHORT OldY = Buff->ViewOrigin.Y;
+        UINT   WidthUnit, HeightUnit;
+
+        /* We now modify Buff->ViewOrigin */
+        *pOriginXY = sInfo.nPos;
+
+        GetScreenBufferSizeUnits(Buff, GuiData, &WidthUnit, &HeightUnit);
+
+        ScrollWindowEx(GuiData->hWindow,
+                       (OldX - Buff->ViewOrigin.X) * WidthUnit ,
+                       (OldY - Buff->ViewOrigin.Y) * HeightUnit,
+                       NULL,
+                       NULL,
+                       NULL,
+                       NULL,
+                       SW_INVALIDATE);
+
+        sInfo.fMask = SIF_POS;
+        SetScrollInfo(GuiData->hWindow, nBar, &sInfo, TRUE);
+
+        UpdateWindow(GuiData->hWindow);
+        // InvalidateRect(GuiData->hWindow, NULL, FALSE);
+    }
+
+Quit:
+    LeaveCriticalSection(&Console->Lock);
+    return;
+}
+
 static COORD
 PointToCoord(PGUI_CONSOLE_DATA GuiData, LPARAM lParam)
 {
@@ -1213,36 +1530,55 @@ PointToCoord(PGUI_CONSOLE_DATA GuiData, LPARAM lParam)
 static LRESULT
 OnMouse(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
 {
-    BOOL Err = FALSE;
-    PCONSOLE Console = GuiData->Console;
+    BOOL DoDefault = FALSE;
+    PCONSRV_CONSOLE Console = GuiData->Console;
+
+    /*
+     * HACK FOR CORE-8394 (Part 2):
+     *
+     * Check whether we should ignore the next mouse move event.
+     * In either case we reset the HACK flag.
+     *
+     * See Part 1 of this hack below.
+     */
+    if (GuiData->HackCORE8394IgnoreNextMove && msg == WM_MOUSEMOVE)
+    {
+        GuiData->HackCORE8394IgnoreNextMove = FALSE;
+        goto Quit;
+    }
+    GuiData->HackCORE8394IgnoreNextMove = FALSE;
+
+    // FIXME: It's here that we need to check whether we have focus or not
+    // and whether we are or not in edit mode, in order to know if we need
+    // to deal with the mouse.
 
     if (GuiData->IgnoreNextMouseSignal)
     {
         if (msg != WM_LBUTTONDOWN &&
             msg != WM_MBUTTONDOWN &&
             msg != WM_RBUTTONDOWN &&
-            msg != WM_MOUSEMOVE)
+            msg != WM_XBUTTONDOWN)
         {
             /*
-             * If this mouse signal is not a button-down action or a move,
-             * then it is the last signal being ignored.
+             * If this mouse signal is not a button-down action
+             * then this is the last one being ignored.
              */
             GuiData->IgnoreNextMouseSignal = FALSE;
         }
         else
         {
             /*
-             * This mouse signal is a button-down action or a move.
+             * This mouse signal is a button-down action.
              * Ignore it and perform default action.
              */
-            Err = TRUE;
+            DoDefault = TRUE;
         }
         goto Quit;
     }
 
-    if (!ConDrvValidateConsoleUnsafe(Console, CONSOLE_RUNNING, TRUE))
+    if (!ConDrvValidateConsoleUnsafe((PCONSOLE)Console, CONSOLE_RUNNING, TRUE))
     {
-        Err = TRUE;
+        DoDefault = TRUE;
         goto Quit;
     }
 
@@ -1253,28 +1589,43 @@ OnMouse(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
         {
             case WM_LBUTTONDOWN:
             {
-                /* Clear the old selection */
-                // UpdateSelection(GuiData, NULL);
-                GuiData->Selection.dwFlags = CONSOLE_NO_SELECTION;
+                /* Check for selection state */
+                if ( (GuiData->Selection.dwFlags & CONSOLE_SELECTION_IN_PROGRESS) &&
+                     (GuiData->Selection.dwFlags & CONSOLE_MOUSE_SELECTION)       &&
+                     (GetKeyState(VK_SHIFT) & KEY_PRESSED) )
+                {
+                    /*
+                     * A mouse selection is currently in progress and the user
+                     * has pressed the SHIFT key and clicked somewhere, update
+                     * the selection.
+                     */
+                    GuiData->dwSelectionCursor = PointToCoord(GuiData, lParam);
+                    UpdateSelection(GuiData, NULL, &GuiData->dwSelectionCursor);
+                }
+                else
+                {
+                    /* Clear the old selection */
+                    GuiData->Selection.dwFlags = CONSOLE_NO_SELECTION;
 
-                /* Restart a new selection */
-                GuiData->Selection.dwSelectionAnchor = PointToCoord(GuiData, lParam);
-                SetCapture(GuiData->hWindow);
-                GuiData->Selection.dwFlags |= CONSOLE_MOUSE_SELECTION | CONSOLE_MOUSE_DOWN;
-                UpdateSelection(GuiData, &GuiData->Selection.dwSelectionAnchor);
+                    /* Restart a new selection */
+                    GuiData->dwSelectionCursor = PointToCoord(GuiData, lParam);
+                    SetCapture(GuiData->hWindow);
+                    GuiData->Selection.dwFlags |= CONSOLE_MOUSE_SELECTION | CONSOLE_MOUSE_DOWN;
+                    UpdateSelection(GuiData,
+                                    &GuiData->dwSelectionCursor,
+                                    &GuiData->dwSelectionCursor);
+                }
 
                 break;
             }
 
             case WM_LBUTTONUP:
             {
-                // COORD c;
-
                 if (!(GuiData->Selection.dwFlags & CONSOLE_MOUSE_DOWN)) break;
 
-                // c = PointToCoord(GuiData, lParam);
+                // GuiData->dwSelectionCursor = PointToCoord(GuiData, lParam);
                 GuiData->Selection.dwFlags &= ~CONSOLE_MOUSE_DOWN;
-                // UpdateSelection(GuiData, &c);
+                // UpdateSelection(GuiData, NULL, &GuiData->dwSelectionCursor);
                 ReleaseCapture();
 
                 break;
@@ -1286,10 +1637,7 @@ OnMouse(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
 
                 if (GetType(Buffer) == TEXTMODE_BUFFER)
                 {
-#ifdef IS_WHITESPACE
-#undef IS_WHITESPACE
-#endif
-#define IS_WHITESPACE(c)    \
+#define IS_WORD_SEP(c)  \
     ((c) == L'\0' || (c) == L' ' || (c) == L'\t' || (c) == L'\r' || (c) == L'\n')
 
                     PTEXTMODE_SCREEN_BUFFER TextBuffer = (PTEXTMODE_SCREEN_BUFFER)Buffer;
@@ -1301,15 +1649,15 @@ OnMouse(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
                     ptrL = ptrR = ConioCoordToPointer(TextBuffer, cL.X, cL.Y);
 
                     /* Enlarge the selection by checking for whitespace */
-                    while ((0 < cL.X) && !IS_WHITESPACE(ptrL->Char.UnicodeChar)
-                                      && !IS_WHITESPACE((ptrL-1)->Char.UnicodeChar))
+                    while ((0 < cL.X) && !IS_WORD_SEP(ptrL->Char.UnicodeChar)
+                                      && !IS_WORD_SEP((ptrL-1)->Char.UnicodeChar))
                     {
                         --cL.X;
                         --ptrL;
                     }
                     while ((cR.X < TextBuffer->ScreenBufferSize.X - 1) &&
-                           !IS_WHITESPACE(ptrR->Char.UnicodeChar)      &&
-                           !IS_WHITESPACE((ptrR+1)->Char.UnicodeChar))
+                           !IS_WORD_SEP(ptrR->Char.UnicodeChar)        &&
+                           !IS_WORD_SEP((ptrR+1)->Char.UnicodeChar))
                     {
                         ++cR.X;
                         ++ptrR;
@@ -1319,14 +1667,12 @@ OnMouse(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
                      * Update the selection started with the single
                      * left-click that preceded this double-click.
                      */
-                    GuiData->Selection.dwSelectionAnchor = cL;
-                    GuiData->dwSelectionCursor           = cR;
-
                     GuiData->Selection.dwFlags |= CONSOLE_MOUSE_SELECTION | CONSOLE_MOUSE_DOWN;
-                    UpdateSelection(GuiData, &GuiData->dwSelectionCursor);
+                    UpdateSelection(GuiData, &cL, &cR);
 
                     /* Ignore the next mouse move signal */
                     GuiData->IgnoreNextMouseSignal = TRUE;
+#undef IS_WORD_SEP
                 }
 
                 break;
@@ -1351,19 +1697,16 @@ OnMouse(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
 
             case WM_MOUSEMOVE:
             {
-                COORD c;
-
-                if (!(wParam & MK_LBUTTON)) break;
+                if (!(GET_KEYSTATE_WPARAM(wParam) & MK_LBUTTON)) break;
                 if (!(GuiData->Selection.dwFlags & CONSOLE_MOUSE_DOWN)) break;
 
-                c = PointToCoord(GuiData, lParam); /* TODO: Scroll buffer to bring c into view */
-                UpdateSelection(GuiData, &c);
-
+                GuiData->dwSelectionCursor = PointToCoord(GuiData, lParam);
+                UpdateSelection(GuiData, NULL, &GuiData->dwSelectionCursor);
                 break;
             }
 
             default:
-                Err = FALSE; // TRUE;
+                DoDefault = TRUE; // FALSE;
                 break;
         }
     }
@@ -1395,6 +1738,26 @@ OnMouse(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
                 dwEventFlags  = 0;
                 break;
 
+            case WM_XBUTTONDOWN:
+            {
+                /* Get which X-button was pressed */
+                WORD wButton = GET_XBUTTON_WPARAM(wParam);
+
+                /* Check for X-button validity */
+                if (wButton & ~(XBUTTON1 | XBUTTON2))
+                {
+                    DPRINT1("X-button 0x%04x invalid\n", wButton);
+                    DoDefault = TRUE;
+                    break;
+                }
+
+                SetCapture(GuiData->hWindow);
+                dwButtonState = (wButton == XBUTTON1 ? FROM_LEFT_3RD_BUTTON_PRESSED
+                                                     : FROM_LEFT_4TH_BUTTON_PRESSED);
+                dwEventFlags  = 0;
+                break;
+            }
+
             case WM_LBUTTONUP:
                 ReleaseCapture();
                 dwButtonState = 0;
@@ -1413,6 +1776,24 @@ OnMouse(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
                 dwEventFlags  = 0;
                 break;
 
+            case WM_XBUTTONUP:
+            {
+                /* Get which X-button was released */
+                WORD wButton = GET_XBUTTON_WPARAM(wParam);
+
+                /* Check for X-button validity */
+                if (wButton & ~(XBUTTON1 | XBUTTON2))
+                {
+                    DPRINT1("X-button 0x%04x invalid\n", wButton);
+                    /* Ok, just release the button anyway... */
+                }
+
+                ReleaseCapture();
+                dwButtonState = 0;
+                dwEventFlags  = 0;
+                break;
+            }
+
             case WM_LBUTTONDBLCLK:
                 dwButtonState = FROM_LEFT_1ST_BUTTON_PRESSED;
                 dwEventFlags  = DOUBLE_CLICK;
@@ -1428,6 +1809,25 @@ OnMouse(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
                 dwEventFlags  = DOUBLE_CLICK;
                 break;
 
+            case WM_XBUTTONDBLCLK:
+            {
+                /* Get which X-button was double-clicked */
+                WORD wButton = GET_XBUTTON_WPARAM(wParam);
+
+                /* Check for X-button validity */
+                if (wButton & ~(XBUTTON1 | XBUTTON2))
+                {
+                    DPRINT1("X-button 0x%04x invalid\n", wButton);
+                    DoDefault = TRUE;
+                    break;
+                }
+
+                dwButtonState = (wButton == XBUTTON1 ? FROM_LEFT_3RD_BUTTON_PRESSED
+                                                     : FROM_LEFT_4TH_BUTTON_PRESSED);
+                dwEventFlags  = DOUBLE_CLICK;
+                break;
+            }
+
             case WM_MOUSEMOVE:
                 dwButtonState = 0;
                 dwEventFlags  = MOUSE_MOVED;
@@ -1444,11 +1844,35 @@ OnMouse(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
                 break;
 
             default:
-                Err = TRUE;
+                DoDefault = TRUE;
+                break;
+        }
+
+        /*
+         * HACK FOR CORE-8394 (Part 1):
+         *
+         * It appears that depending on which VM ReactOS runs, the next mouse
+         * signal coming after a button-down action can be a mouse-move (e.g.
+         * on VBox, whereas on QEMU it is not the case). However it is NOT a
+         * rule, so that we cannot use the IgnoreNextMouseSignal flag to just
+         * "ignore" the next mouse event, thinking it would always be a mouse-
+         * move signal.
+         *
+         * To work around this problem (that should really be fixed in Win32k),
+         * we use a second flag to ignore this possible next mouse move signal.
+         */
+        switch (msg)
+        {
+            case WM_LBUTTONDOWN:
+            case WM_MBUTTONDOWN:
+            case WM_RBUTTONDOWN:
+            case WM_XBUTTONDOWN:
+                GuiData->HackCORE8394IgnoreNextMove = TRUE;
+            default:
                 break;
         }
 
-        if (!Err)
+        if (!DoDefault)
         {
             if (wKeyState & MK_LBUTTON)
                 dwButtonState |= FROM_LEFT_1ST_BUTTON_PRESSED;
@@ -1456,27 +1880,32 @@ OnMouse(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
                 dwButtonState |= FROM_LEFT_2ND_BUTTON_PRESSED;
             if (wKeyState & MK_RBUTTON)
                 dwButtonState |= RIGHTMOST_BUTTON_PRESSED;
+            if (wKeyState & MK_XBUTTON1)
+                dwButtonState |= FROM_LEFT_3RD_BUTTON_PRESSED;
+            if (wKeyState & MK_XBUTTON2)
+                dwButtonState |= FROM_LEFT_4TH_BUTTON_PRESSED;
 
-            if (GetKeyState(VK_RMENU) & 0x8000)
+            if (GetKeyState(VK_RMENU) & KEY_PRESSED)
                 dwControlKeyState |= RIGHT_ALT_PRESSED;
-            if (GetKeyState(VK_LMENU) & 0x8000)
+            if (GetKeyState(VK_LMENU) & KEY_PRESSED)
                 dwControlKeyState |= LEFT_ALT_PRESSED;
-            if (GetKeyState(VK_RCONTROL) & 0x8000)
+            if (GetKeyState(VK_RCONTROL) & KEY_PRESSED)
                 dwControlKeyState |= RIGHT_CTRL_PRESSED;
-            if (GetKeyState(VK_LCONTROL) & 0x8000)
+            if (GetKeyState(VK_LCONTROL) & KEY_PRESSED)
                 dwControlKeyState |= LEFT_CTRL_PRESSED;
-            if (GetKeyState(VK_SHIFT) & 0x8000)
+            if (GetKeyState(VK_SHIFT) & KEY_PRESSED)
                 dwControlKeyState |= SHIFT_PRESSED;
-            if (GetKeyState(VK_NUMLOCK) & 0x0001)
+            if (GetKeyState(VK_NUMLOCK) & KEY_TOGGLED)
                 dwControlKeyState |= NUMLOCK_ON;
-            if (GetKeyState(VK_SCROLL) & 0x0001)
+            if (GetKeyState(VK_SCROLL) & KEY_TOGGLED)
                 dwControlKeyState |= SCROLLLOCK_ON;
-            if (GetKeyState(VK_CAPITAL) & 0x0001)
+            if (GetKeyState(VK_CAPITAL) & KEY_TOGGLED)
                 dwControlKeyState |= CAPSLOCK_ON;
             /* See WM_CHAR MSDN documentation for instance */
             if (lParam & 0x01000000)
                 dwControlKeyState |= ENHANCED_KEY;
 
+            /* Send a mouse event */
             er.EventType = MOUSE_EVENT;
             er.Event.MouseEvent.dwMousePosition   = PointToCoord(GuiData, lParam);
             er.Event.MouseEvent.dwButtonState     = dwButtonState;
@@ -1488,29 +1917,49 @@ OnMouse(PGUI_CONSOLE_DATA GuiData, UINT msg, WPARAM wParam, LPARAM lParam)
     }
     else
     {
-        Err = TRUE;
+        DoDefault = TRUE;
     }
 
     LeaveCriticalSection(&Console->Lock);
 
 Quit:
-    if (Err)
-        return DefWindowProcW(GuiData->hWindow, msg, wParam, lParam);
-    else
+    if (!DoDefault)
         return 0;
+
+    if (msg == WM_MOUSEWHEEL || msg == WM_MOUSEHWHEEL)
+    {
+        INT   nBar;
+        WORD  sbCode;
+        // WORD  wKeyState = GET_KEYSTATE_WPARAM(wParam);
+        SHORT wDelta    = GET_WHEEL_DELTA_WPARAM(wParam);
+
+        if (msg == WM_MOUSEWHEEL)
+            nBar = SB_VERT;
+        else // if (msg == WM_MOUSEHWHEEL)
+            nBar = SB_HORZ;
+
+        // NOTE: We currently do not support zooming...
+        // if (wKeyState & MK_CONTROL)
+
+        // FIXME: For some reason our win32k does not set the key states
+        // when sending WM_MOUSEWHEEL or WM_MOUSEHWHEEL ...
+        // if (wKeyState & MK_SHIFT)
+        if (GetKeyState(VK_SHIFT) & KEY_PRESSED)
+            sbCode = (wDelta >= 0 ? SB_PAGEUP : SB_PAGEDOWN);
+        else
+            sbCode = (wDelta >= 0 ? SB_LINEUP : SB_LINEDOWN);
+
+        OnScroll(GuiData, nBar, sbCode);
+    }
+
+    return DefWindowProcW(GuiData->hWindow, msg, wParam, lParam);
 }
 
-VOID
-GuiCopyFromTextModeBuffer(PTEXTMODE_SCREEN_BUFFER Buffer,
-                          PGUI_CONSOLE_DATA GuiData);
-VOID
-GuiCopyFromGraphicsBuffer(PGRAPHICS_SCREEN_BUFFER Buffer,
-                          PGUI_CONSOLE_DATA GuiData);
 
 static VOID
 Copy(PGUI_CONSOLE_DATA GuiData)
 {
-    if (OpenClipboard(GuiData->hWindow) == TRUE)
+    if (OpenClipboard(GuiData->hWindow))
     {
         PCONSOLE_SCREEN_BUFFER Buffer = GuiData->ActiveBuffer;
 
@@ -1527,20 +1976,13 @@ Copy(PGUI_CONSOLE_DATA GuiData)
     }
 
     /* Clear the selection */
-    UpdateSelection(GuiData, NULL);
+    UpdateSelection(GuiData, NULL, NULL);
 }
 
-VOID
-GuiPasteToTextModeBuffer(PTEXTMODE_SCREEN_BUFFER Buffer,
-                         PGUI_CONSOLE_DATA GuiData);
-VOID
-GuiPasteToGraphicsBuffer(PGRAPHICS_SCREEN_BUFFER Buffer,
-                         PGUI_CONSOLE_DATA GuiData);
-
 static VOID
 Paste(PGUI_CONSOLE_DATA GuiData)
 {
-    if (OpenClipboard(GuiData->hWindow) == TRUE)
+    if (OpenClipboard(GuiData->hWindow))
     {
         PCONSOLE_SCREEN_BUFFER Buffer = GuiData->ActiveBuffer;
 
@@ -1560,12 +2002,12 @@ Paste(PGUI_CONSOLE_DATA GuiData)
 static VOID
 OnGetMinMaxInfo(PGUI_CONSOLE_DATA GuiData, PMINMAXINFO minMaxInfo)
 {
-    PCONSOLE Console = GuiData->Console;
+    PCONSRV_CONSOLE Console = GuiData->Console;
     PCONSOLE_SCREEN_BUFFER ActiveBuffer;
     DWORD windx, windy;
     UINT  WidthUnit, HeightUnit;
 
-    if (!ConDrvValidateConsoleUnsafe(Console, CONSOLE_RUNNING, TRUE)) return;
+    if (!ConDrvValidateConsoleUnsafe((PCONSOLE)Console, CONSOLE_RUNNING, TRUE)) return;
 
     ActiveBuffer = GuiData->ActiveBuffer;
 
@@ -1580,8 +2022,8 @@ OnGetMinMaxInfo(PGUI_CONSOLE_DATA GuiData, PMINMAXINFO minMaxInfo)
     windx = (ActiveBuffer->ScreenBufferSize.X) * WidthUnit  + 2 * (GetSystemMetrics(SM_CXFRAME) + GetSystemMetrics(SM_CXEDGE));
     windy = (ActiveBuffer->ScreenBufferSize.Y) * HeightUnit + 2 * (GetSystemMetrics(SM_CYFRAME) + GetSystemMetrics(SM_CYEDGE)) + GetSystemMetrics(SM_CYCAPTION);
 
-    if (ActiveBuffer->ViewSize.X < ActiveBuffer->ScreenBufferSize.X) windy += GetSystemMetrics(SM_CYHSCROLL);    // window currently has a horizontal scrollbar
-    if (ActiveBuffer->ViewSize.Y < ActiveBuffer->ScreenBufferSize.Y) windx += GetSystemMetrics(SM_CXVSCROLL);    // window currently has a vertical scrollbar
+    if (ActiveBuffer->ViewSize.X < ActiveBuffer->ScreenBufferSize.X) windy += GetSystemMetrics(SM_CYHSCROLL); // Window currently has a horizontal scrollbar
+    if (ActiveBuffer->ViewSize.Y < ActiveBuffer->ScreenBufferSize.Y) windx += GetSystemMetrics(SM_CXVSCROLL); // Window currently has a vertical scrollbar
 
     minMaxInfo->ptMaxTrackSize.x = windx;
     minMaxInfo->ptMaxTrackSize.y = windy;
@@ -1592,11 +2034,14 @@ OnGetMinMaxInfo(PGUI_CONSOLE_DATA GuiData, PMINMAXINFO minMaxInfo)
 static VOID
 OnSize(PGUI_CONSOLE_DATA GuiData, WPARAM wParam, LPARAM lParam)
 {
-    PCONSOLE Console = GuiData->Console;
+    PCONSRV_CONSOLE Console = GuiData->Console;
+
+    /* Do nothing if the window is hidden */
+    if (!GuiData->IsWindowVisible || IsIconic(GuiData->hWindow)) return;
 
-    if (!ConDrvValidateConsoleUnsafe(Console, CONSOLE_RUNNING, TRUE)) return;
+    if (!ConDrvValidateConsoleUnsafe((PCONSOLE)Console, CONSOLE_RUNNING, TRUE)) return;
 
-    if ((GuiData->WindowSizeLock == FALSE) &&
+    if (!GuiData->WindowSizeLock &&
         (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED || wParam == SIZE_MINIMIZED))
     {
         PCONSOLE_SCREEN_BUFFER Buff = GuiData->ActiveBuffer;
@@ -1610,38 +2055,38 @@ OnSize(PGUI_CONSOLE_DATA GuiData, WPARAM wParam, LPARAM lParam)
         windx = LOWORD(lParam);
         windy = HIWORD(lParam);
 
-        // Compensate for existing scroll bars (because lParam values do not accommodate scroll bar)
-        if (Buff->ViewSize.X < Buff->ScreenBufferSize.X) windy += GetSystemMetrics(SM_CYHSCROLL);    // window currently has a horizontal scrollbar
-        if (Buff->ViewSize.Y < Buff->ScreenBufferSize.Y) windx += GetSystemMetrics(SM_CXVSCROLL);    // window currently has a vertical scrollbar
+        /* Compensate for existing scroll bars (because lParam values do not accommodate scroll bar) */
+        if (Buff->ViewSize.X < Buff->ScreenBufferSize.X) windy += GetSystemMetrics(SM_CYHSCROLL); // Window currently has a horizontal scrollbar
+        if (Buff->ViewSize.Y < Buff->ScreenBufferSize.Y) windx += GetSystemMetrics(SM_CXVSCROLL); // Window currently has a vertical scrollbar
 
         charx = windx / (int)WidthUnit ;
         chary = windy / (int)HeightUnit;
 
-        // Character alignment (round size up or down)
+        /* Character alignment (round size up or down) */
         if ((windx % WidthUnit ) >= (WidthUnit  / 2)) ++charx;
         if ((windy % HeightUnit) >= (HeightUnit / 2)) ++chary;
 
-        // Compensate for added scroll bars in new window
-        if (charx < Buff->ScreenBufferSize.X) windy -= GetSystemMetrics(SM_CYHSCROLL);    // new window will have a horizontal scroll bar
-        if (chary < Buff->ScreenBufferSize.Y) windx -= GetSystemMetrics(SM_CXVSCROLL);    // new window will have a vertical scroll bar
+        /* Compensate for added scroll bars in window */
+        if (Buff->ViewSize.X < Buff->ScreenBufferSize.X) windy -= GetSystemMetrics(SM_CYHSCROLL); // Window will have a horizontal scroll bar
+        if (Buff->ViewSize.Y < Buff->ScreenBufferSize.Y) windx -= GetSystemMetrics(SM_CXVSCROLL); // Window will have a vertical scroll bar
 
         charx = windx / (int)WidthUnit ;
         chary = windy / (int)HeightUnit;
 
-        // Character alignment (round size up or down)
+        /* Character alignment (round size up or down) */
         if ((windx % WidthUnit ) >= (WidthUnit  / 2)) ++charx;
         if ((windy % HeightUnit) >= (HeightUnit / 2)) ++chary;
 
-        // Resize window
+        /* Resize window */
         if ((charx != Buff->ViewSize.X) || (chary != Buff->ViewSize.Y))
         {
-            Buff->ViewSize.X = (charx <= Buff->ScreenBufferSize.X) ? charx : Buff->ScreenBufferSize.X;
-            Buff->ViewSize.Y = (chary <= Buff->ScreenBufferSize.Y) ? chary : Buff->ScreenBufferSize.Y;
+            Buff->ViewSize.X = (charx <= (DWORD)Buff->ScreenBufferSize.X) ? charx : Buff->ScreenBufferSize.X;
+            Buff->ViewSize.Y = (chary <= (DWORD)Buff->ScreenBufferSize.Y) ? chary : Buff->ScreenBufferSize.Y;
         }
 
         ResizeConWnd(GuiData, WidthUnit, HeightUnit);
 
-        // Adjust the start of the visible area if we are attempting to show nonexistent areas
+        /* Adjust the start of the visible area if we are attempting to show nonexistent areas */
         if ((Buff->ScreenBufferSize.X - Buff->ViewOrigin.X) < Buff->ViewSize.X) Buff->ViewOrigin.X = Buff->ScreenBufferSize.X - Buff->ViewSize.X;
         if ((Buff->ScreenBufferSize.Y - Buff->ViewOrigin.Y) < Buff->ViewSize.Y) Buff->ViewOrigin.Y = Buff->ScreenBufferSize.Y - Buff->ViewSize.Y;
         InvalidateRect(GuiData->hWindow, NULL, TRUE);
@@ -1666,6 +2111,30 @@ OnMove(PGUI_CONSOLE_DATA GuiData)
     GuiData->GuiInfo.WindowOrigin.y = rcWnd.top;
 }
 
+static VOID
+OnDropFiles(PCONSRV_CONSOLE Console, HDROP hDrop)
+{
+    LPWSTR pszPath;
+    WCHAR szPath[MAX_PATH + 2];
+
+    szPath[0] = L'"';
+
+    DragQueryFileW(hDrop, 0, &szPath[1], ARRAYSIZE(szPath) - 1);
+    DragFinish(hDrop);
+
+    if (wcschr(&szPath[1], L' ') != NULL)
+    {
+        StringCchCatW(szPath, ARRAYSIZE(szPath), L"\"");
+        pszPath = szPath;
+    }
+    else
+    {
+        pszPath = &szPath[1];
+    }
+
+    PasteText(Console, pszPath, wcslen(pszPath));
+}
+
 /*
 // HACK: This functionality is standard for general scrollbars. Don't add it by hand.
 
@@ -1694,121 +2163,12 @@ GuiConsoleHandleScrollbarMenu(VOID)
 }
 */
 
-static LRESULT
-OnScroll(PGUI_CONSOLE_DATA GuiData, UINT uMsg, WPARAM wParam)
-{
-    PCONSOLE Console = GuiData->Console;
-    PCONSOLE_SCREEN_BUFFER Buff;
-    SCROLLINFO sInfo;
-    int fnBar;
-    int old_pos, Maximum;
-    PSHORT pShowXY;
-
-    if (!ConDrvValidateConsoleUnsafe(Console, CONSOLE_RUNNING, TRUE)) return 0;
-
-    Buff = GuiData->ActiveBuffer;
-
-    if (uMsg == WM_HSCROLL)
-    {
-        fnBar = SB_HORZ;
-        Maximum = Buff->ScreenBufferSize.X - Buff->ViewSize.X;
-        pShowXY = &Buff->ViewOrigin.X;
-    }
-    else
-    {
-        fnBar = SB_VERT;
-        Maximum = Buff->ScreenBufferSize.Y - Buff->ViewSize.Y;
-        pShowXY = &Buff->ViewOrigin.Y;
-    }
-
-    /* set scrollbar sizes */
-    sInfo.cbSize = sizeof(SCROLLINFO);
-    sInfo.fMask = SIF_RANGE | SIF_POS | SIF_PAGE | SIF_TRACKPOS;
-
-    if (!GetScrollInfo(GuiData->hWindow, fnBar, &sInfo)) goto Quit;
-
-    old_pos = sInfo.nPos;
-
-    switch (LOWORD(wParam))
-    {
-        case SB_LINELEFT:
-            sInfo.nPos -= 1;
-            break;
-
-        case SB_LINERIGHT:
-            sInfo.nPos += 1;
-            break;
-
-        case SB_PAGELEFT:
-            sInfo.nPos -= sInfo.nPage;
-            break;
-
-        case SB_PAGERIGHT:
-            sInfo.nPos += sInfo.nPage;
-            break;
-
-        case SB_THUMBTRACK:
-            sInfo.nPos = sInfo.nTrackPos;
-            ConioPause(Console, PAUSED_FROM_SCROLLBAR);
-            break;
-
-        case SB_THUMBPOSITION:
-            ConioUnpause(Console, PAUSED_FROM_SCROLLBAR);
-            break;
-
-        case SB_TOP:
-            sInfo.nPos = sInfo.nMin;
-            break;
-
-        case SB_BOTTOM:
-            sInfo.nPos = sInfo.nMax;
-            break;
-
-        default:
-            break;
-    }
-
-    sInfo.nPos = max(sInfo.nPos, 0);
-    sInfo.nPos = min(sInfo.nPos, Maximum);
-
-    if (old_pos != sInfo.nPos)
-    {
-        USHORT OldX = Buff->ViewOrigin.X;
-        USHORT OldY = Buff->ViewOrigin.Y;
-        UINT   WidthUnit, HeightUnit;
-
-        *pShowXY = sInfo.nPos;
-
-        GetScreenBufferSizeUnits(Buff, GuiData, &WidthUnit, &HeightUnit);
-
-        ScrollWindowEx(GuiData->hWindow,
-                       (OldX - Buff->ViewOrigin.X) * WidthUnit ,
-                       (OldY - Buff->ViewOrigin.Y) * HeightUnit,
-                       NULL,
-                       NULL,
-                       NULL,
-                       NULL,
-                       SW_INVALIDATE);
-
-        sInfo.fMask = SIF_POS;
-        SetScrollInfo(GuiData->hWindow, fnBar, &sInfo, TRUE);
-
-        UpdateWindow(GuiData->hWindow);
-        // InvalidateRect(GuiData->hWindow, NULL, FALSE);
-    }
-
-Quit:
-    LeaveCriticalSection(&Console->Lock);
-    return 0;
-}
-
-
 static LRESULT CALLBACK
 ConWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
 {
     LRESULT Result = 0;
     PGUI_CONSOLE_DATA GuiData = NULL;
-    PCONSOLE Console = NULL;
+    PCONSRV_CONSOLE Console = NULL;
 
     /*
      * - If it's the first time we create a window for the terminal,
@@ -1854,6 +2214,9 @@ ConWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
             if (OnClose(GuiData)) goto Default;
             break;
 
+        case WM_ERASEBKGND:
+            return TRUE;
+
         case WM_PAINT:
             OnPaint(GuiData);
             break;
@@ -1905,6 +2268,11 @@ ConWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
 
                 break;
             }
+            /* Detect Alt-Esc/Space/Tab presses defer to DefWindowProc */
+            if ( (HIWORD(lParam) & KF_ALTDOWN) && (wParam == VK_ESCAPE || wParam == VK_SPACE || wParam == VK_TAB))
+            {
+                return DefWindowProcW(hWnd, msg, wParam, lParam);
+            }
 
             OnKey(GuiData, msg, wParam, lParam);
             break;
@@ -1912,6 +2280,9 @@ ConWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
 
         case WM_SETCURSOR:
         {
+            /* Do nothing if the window is hidden */
+            if (!GuiData->IsWindowVisible) goto Default;
+
             /*
              * The message was sent because we are manually triggering a change.
              * Check whether the mouse is indeed present on this console window
@@ -1961,12 +2332,15 @@ ConWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
         case WM_LBUTTONDOWN:
         case WM_MBUTTONDOWN:
         case WM_RBUTTONDOWN:
+        case WM_XBUTTONDOWN:
         case WM_LBUTTONUP:
         case WM_MBUTTONUP:
         case WM_RBUTTONUP:
+        case WM_XBUTTONUP:
         case WM_LBUTTONDBLCLK:
         case WM_MBUTTONDBLCLK:
         case WM_RBUTTONDBLCLK:
+        case WM_XBUTTONDBLCLK:
         case WM_MOUSEMOVE:
         case WM_MOUSEWHEEL:
         case WM_MOUSEHWHEEL:
@@ -1976,14 +2350,18 @@ ConWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
         }
 
         case WM_HSCROLL:
+            OnScroll(GuiData, SB_HORZ, LOWORD(wParam));
+            break;
+
         case WM_VSCROLL:
-        {
-            Result = OnScroll(GuiData, msg, wParam);
+            OnScroll(GuiData, SB_VERT, LOWORD(wParam));
             break;
-        }
 
         case WM_CONTEXTMENU:
         {
+            /* Do nothing if the window is hidden */
+            if (!GuiData->IsWindowVisible) break;
+
             if (DefWindowProcW(hWnd /*GuiData->hWindow*/, WM_NCHITTEST, 0, lParam) == HTCLIENT)
             {
                 HMENU hMenu = CreatePopupMenu();
@@ -2046,6 +2424,10 @@ ConWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
             break;
         }
 
+        case WM_DROPFILES:
+            OnDropFiles(Console, (HDROP)wParam);
+            break;
+
         case WM_SETFOCUS:
         case WM_KILLFOCUS:
             OnFocus(GuiData, (msg == WM_SETFOCUS));
@@ -2112,6 +2494,9 @@ ConWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
             DWORD Width, Height;
             UINT  WidthUnit, HeightUnit;
 
+            /* Do nothing if the window is hidden */
+            if (!GuiData->IsWindowVisible) break;
+
             GetScreenBufferSizeUnits(Buff, GuiData, &WidthUnit, &HeightUnit);
 
             Width  = Buff->ScreenBufferSize.X * WidthUnit ;
@@ -2135,20 +2520,26 @@ ConWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
             break;
         }
 
-        case PM_APPLY_CONSOLE_INFO:
+        /*
+         * Undocumented message sent by Windows' console.dll for applying console info.
+         * See http://www.catch22.net/sites/default/source/files/setconsoleinfo.c
+         * and http://www.scn.rain.com/~neighorn/PDF/MSBugPaper.pdf
+         * for more information.
+         */
+        case WM_SETCONSOLEINFO:
         {
-            GuiApplyUserSettings(GuiData, (HANDLE)wParam, (BOOL)lParam);
+            GuiApplyUserSettings(GuiData, (HANDLE)wParam);
             break;
         }
 
         case PM_CONSOLE_BEEP:
-            DPRINT1("Beep !!\n");
+            DPRINT1("Beep\n");
             Beep(800, 200);
             break;
 
-        // case PM_CONSOLE_SET_TITLE:
-            // SetWindowText(GuiData->hWindow, GuiData->Console->Title.Buffer);
-            // break;
+         case PM_CONSOLE_SET_TITLE:
+            SetWindowTextW(GuiData->hWindow, GuiData->Console->Title.Buffer);
+            break;
 
         default: Default:
             Result = DefWindowProcW(hWnd, msg, wParam, lParam);