[BASESRV-CONSRV-WINSRV]
[reactos.git] / win32ss / user / consrv / console.c
index 6c90bc6..870432c 100644 (file)
  * COPYRIGHT:       See COPYING in the top level directory
  * PROJECT:         ReactOS Console Server DLL
  * FILE:            win32ss/user/consrv/console.c
- * PURPOSE:         Console I/O functions
- * PROGRAMMERS:
+ * PURPOSE:         Console Management Functions
+ * PROGRAMMERS:     Hermes Belusca-Maito (hermes.belusca@sfr.fr)
  */
 
-/* INCLUDES ******************************************************************/
+/* INCLUDES *******************************************************************/
+
+#define COBJMACROS
+#define NONAMELESSUNION
 
 #include "consrv.h"
-#include "guiconsole.h"
-#include "tuiconsole.h"
+#include "include/conio.h"
+#include "conio.h"
+#include "handle.h"
+#include "procinit.h"
+#include "alias.h"
+#include "coninput.h"
+#include "conoutput.h"
+#include "lineinput.h"
+#include "include/settings.h"
+
+#include "frontends/gui/guiterm.h"
+
+#ifdef TUI_CONSOLE
+    #include "frontends/tui/tuiterm.h"
+#endif
+
+#include "include/console.h"
+#include "console.h"
+#include "resource.h"
 
-//#define NDEBUG
+#include <shlwapi.h>
+#include <shlobj.h>
+
+#define NDEBUG
 #include <debug.h>
 
-/* FUNCTIONS *****************************************************************/
+/* GLOBALS ********************************************************************/
 
-BOOL FASTCALL
+static LIST_ENTRY ConsoleList;  /* The list of all the allocated consoles */
+static RTL_RESOURCE ListLock;
+
+#define ConSrvLockConsoleListExclusive()    \
+    RtlAcquireResourceExclusive(&ListLock, TRUE)
+
+#define ConSrvLockConsoleListShared()       \
+    RtlAcquireResourceShared(&ListLock, TRUE)
+
+#define ConSrvUnlockConsoleList()           \
+    RtlReleaseResource(&ListLock)
+
+
+/* PRIVATE FUNCTIONS **********************************************************/
+
+#ifdef TUI_CONSOLE
+static BOOL
 DtbgIsDesktopVisible(VOID)
 {
-    HWND VisibleDesktopWindow = GetDesktopWindow(); // DESKTOPWNDPROC
+    return !((BOOL)NtUserCallNoParam(NOPARAM_ROUTINE_ISCONSOLEMODE));
+}
+#endif
+
+static ULONG
+ConSrvConsoleCtrlEventTimeout(DWORD Event,
+                              PCONSOLE_PROCESS_DATA ProcessData,
+                              DWORD Timeout)
+{
+    ULONG Status = ERROR_SUCCESS;
+
+    DPRINT("ConSrvConsoleCtrlEventTimeout Parent ProcessId = %x\n", ProcessData->Process->ClientId.UniqueProcess);
+
+    if (ProcessData->CtrlDispatcher)
+    {
+        _SEH2_TRY
+        {
+            HANDLE Thread = NULL;
+
+            _SEH2_TRY
+            {
+                Thread = CreateRemoteThread(ProcessData->Process->ProcessHandle, NULL, 0,
+                                            ProcessData->CtrlDispatcher,
+                                            UlongToPtr(Event), 0, NULL);
+                if (NULL == Thread)
+                {
+                    Status = GetLastError();
+                    DPRINT1("Failed thread creation (Error: 0x%x)\n", Status);
+                }
+                else
+                {
+                    DPRINT("ProcessData->CtrlDispatcher remote thread creation succeeded, ProcessId = %x, Process = 0x%p\n", ProcessData->Process->ClientId.UniqueProcess, ProcessData->Process);
+                    WaitForSingleObject(Thread, Timeout);
+                }
+            }
+            _SEH2_FINALLY
+            {
+                CloseHandle(Thread);
+            }
+            _SEH2_END;
+        }
+        _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
+        {
+            Status = RtlNtStatusToDosError(_SEH2_GetExceptionCode());
+            DPRINT1("ConSrvConsoleCtrlEventTimeout - Caught an exception, Status = %08X\n", Status);
+        }
+        _SEH2_END;
+    }
+
+    return Status;
+}
+
+static ULONG
+ConSrvConsoleCtrlEvent(DWORD Event,
+                       PCONSOLE_PROCESS_DATA ProcessData)
+{
+    return ConSrvConsoleCtrlEventTimeout(Event, ProcessData, 0);
+}
+
+ULONG FASTCALL
+ConSrvConsoleProcessCtrlEvent(PCONSOLE Console,
+                              ULONG ProcessGroupId,
+                              DWORD Event)
+{
+    ULONG Status = ERROR_SUCCESS;
+    PLIST_ENTRY current_entry;
+    PCONSOLE_PROCESS_DATA current;
+
+    /* If the console is already being destroyed, just return */
+    if (!ConSrvValidateConsole(Console, CONSOLE_RUNNING, FALSE))
+        return STATUS_UNSUCCESSFUL;
+
+    /*
+     * Loop through the process list, from the most recent process
+     * (the active one) to the oldest one (the first created, i.e.
+     * the console leader process), and for each, send an event
+     * (new processes are inserted at the head of the console process list).
+     */
+    current_entry = Console->ProcessList.Flink;
+    while (current_entry != &Console->ProcessList)
+    {
+        current = CONTAINING_RECORD(current_entry, CONSOLE_PROCESS_DATA, ConsoleLink);
+        current_entry = current_entry->Flink;
+
+        /*
+         * Only processes belonging to the same process group are signaled.
+         * If the process group ID is zero, then all the processes are signaled.
+         */
+        if (ProcessGroupId == 0 || current->Process->ProcessGroupId == ProcessGroupId)
+        {
+            Status = ConSrvConsoleCtrlEvent(Event, current);
+        }
+    }
+
+    return Status;
+}
+
+VOID FASTCALL
+ConioPause(PCONSOLE Console, UINT Flags)
+{
+    Console->PauseFlags |= Flags;
+    if (!Console->UnpauseEvent)
+        Console->UnpauseEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
+}
+
+VOID FASTCALL
+ConioUnpause(PCONSOLE Console, UINT Flags)
+{
+    Console->PauseFlags &= ~Flags;
+
+    // if ((Console->PauseFlags & (PAUSED_FROM_KEYBOARD | PAUSED_FROM_SCROLLBAR | PAUSED_FROM_SELECTION)) == 0)
+    if (Console->PauseFlags == 0 && Console->UnpauseEvent)
+    {
+        SetEvent(Console->UnpauseEvent);
+        CloseHandle(Console->UnpauseEvent);
+        Console->UnpauseEvent = NULL;
+
+        CsrNotifyWait(&Console->WriteWaitQueue,
+                      WaitAll,
+                      NULL,
+                      NULL);
+        if (!IsListEmpty(&Console->WriteWaitQueue))
+        {
+            CsrDereferenceWait(&Console->WriteWaitQueue);
+        }
+    }
+}
+
+BOOL FASTCALL
+ConSrvValidateConsolePointer(PCONSOLE Console)
+{
+    PLIST_ENTRY ConsoleEntry;
+    PCONSOLE CurrentConsole = NULL;
+
+    if (!Console) return FALSE;
 
-    if (VisibleDesktopWindow != NULL &&
-            !IsWindowVisible(VisibleDesktopWindow))
+    /* The console list must be locked */
+    // ASSERT(Console_list_locked);
+
+    ConsoleEntry = ConsoleList.Flink;
+    while (ConsoleEntry != &ConsoleList)
     {
-        VisibleDesktopWindow = NULL;
+        CurrentConsole = CONTAINING_RECORD(ConsoleEntry, CONSOLE, Entry);
+        ConsoleEntry = ConsoleEntry->Flink;
+        if (CurrentConsole == Console) return TRUE;
     }
 
-    return VisibleDesktopWindow != NULL;
+    return FALSE;
 }
 
-NTSTATUS FASTCALL
-ConioConsoleFromProcessData(PCONSOLE_PROCESS_DATA ProcessData,
-                            PCONSOLE *Console)
+BOOL FASTCALL
+ConSrvValidateConsoleState(PCONSOLE Console,
+                           CONSOLE_STATE ExpectedState)
 {
+    // if (!Console) return FALSE;
+
+    /* The console must be locked */
+    // ASSERT(Console_locked);
+
+    return (Console->State == ExpectedState);
+}
+
+BOOL FASTCALL
+ConSrvValidateConsoleUnsafe(PCONSOLE Console,
+                            CONSOLE_STATE ExpectedState,
+                            BOOL LockConsole)
+{
+    if (!Console) return FALSE;
+
+    /*
+     * Lock the console to forbid possible console's state changes
+     * (which must be done when the console is already locked).
+     * If we don't want to lock it, it's because the lock is already
+     * held. So there must be no problems.
+     */
+    if (LockConsole) EnterCriticalSection(&Console->Lock);
+
+    // ASSERT(Console_locked);
+
+    /* Check whether the console's state is what we expect */
+    if (!ConSrvValidateConsoleState(Console, ExpectedState))
+    {
+        if (LockConsole) LeaveCriticalSection(&Console->Lock);
+        return FALSE;
+    }
+
+    return TRUE;
+}
+
+BOOL FASTCALL
+ConSrvValidateConsole(PCONSOLE Console,
+                      CONSOLE_STATE ExpectedState,
+                      BOOL LockConsole)
+{
+    BOOL RetVal = FALSE;
+
+    if (!Console) return FALSE;
+
+    /*
+     * Forbid creation or deletion of consoles when
+     * checking for the existence of a console.
+     */
+    ConSrvLockConsoleListShared();
+
+    if (ConSrvValidateConsolePointer(Console))
+    {
+        RetVal = ConSrvValidateConsoleUnsafe(Console,
+                                             ExpectedState,
+                                             LockConsole);
+    }
+
+    /* Unlock the console list and return */
+    ConSrvUnlockConsoleList();
+    return RetVal;
+}
+
+NTSTATUS
+FASTCALL
+ConSrvGetConsole(PCONSOLE_PROCESS_DATA ProcessData,
+                 PCONSOLE* Console,
+                 BOOL LockConsole)
+{
+    NTSTATUS Status = STATUS_SUCCESS;
     PCONSOLE ProcessConsole;
 
     RtlEnterCriticalSection(&ProcessData->HandleTableLock);
     ProcessConsole = ProcessData->Console;
 
-    if (!ProcessConsole)
+    if (ConSrvValidateConsole(ProcessConsole, CONSOLE_RUNNING, LockConsole))
+    {
+        InterlockedIncrement(&ProcessConsole->ReferenceCount);
+        *Console = ProcessConsole;
+    }
+    else
     {
         *Console = NULL;
-        RtlLeaveCriticalSection(&ProcessData->HandleTableLock);
-        return STATUS_INVALID_HANDLE;
+        Status = STATUS_INVALID_HANDLE;
     }
 
-    InterlockedIncrement(&ProcessConsole->ReferenceCount);
     RtlLeaveCriticalSection(&ProcessData->HandleTableLock);
-    EnterCriticalSection(&(ProcessConsole->Lock));
-    *Console = ProcessConsole;
-
-    return STATUS_SUCCESS;
+    return Status;
 }
 
 VOID FASTCALL
-ConioConsoleCtrlEventTimeout(DWORD Event,
-                             PCONSOLE_PROCESS_DATA ProcessData,
-                             DWORD Timeout)
+ConSrvReleaseConsole(PCONSOLE Console,
+                     BOOL WasConsoleLocked)
 {
-    HANDLE Thread;
+    LONG RefCount = 0;
 
-    DPRINT("ConioConsoleCtrlEvent Parent ProcessId = %x\n", ProcessData->Process->ClientId.UniqueProcess);
+    if (!Console) return;
+    // if (Console->ReferenceCount == 0) return; // This shouldn't happen
+    ASSERT(Console->ReferenceCount > 0);
 
-    if (ProcessData->CtrlDispatcher)
+    /* The console must be locked */
+    // ASSERT(Console_locked);
+
+    /*
+     * Decrement the reference count. Save the new value too,
+     * because Console->ReferenceCount might be modified after
+     * the console gets unlocked but before we check whether we
+     * can destroy it.
+     */
+    RefCount = _InterlockedDecrement(&Console->ReferenceCount);
+
+    /* Unlock the console if needed */
+    if (WasConsoleLocked) LeaveCriticalSection(&Console->Lock);
+
+    /* Delete the console if needed */
+    if (RefCount <= 0) ConSrvDeleteConsole(Console);
+}
+
+VOID WINAPI
+ConSrvInitConsoleSupport(VOID)
+{
+    DPRINT("CONSRV: ConSrvInitConsoleSupport()\n");
+
+    /* Initialize the console list and its lock */
+    InitializeListHead(&ConsoleList);
+    RtlInitializeResource(&ListLock);
+
+    /* Should call LoadKeyboardLayout */
+}
+
+static BOOL
+LoadShellLinkConsoleInfo(IN OUT PCONSOLE_START_INFO ConsoleStartInfo,
+                         IN OUT PCONSOLE_INFO ConsoleInfo,
+                         OUT LPWSTR IconPath,
+                         IN SIZE_T IconPathLength,
+                         OUT PINT piIcon)
+{
+#define PATH_SEPARATOR L'\\'
+
+    BOOL   RetVal = FALSE;
+    LPWSTR LinkName = NULL;
+    SIZE_T Length = 0;
+
+    if ((ConsoleStartInfo->dwStartupFlags & STARTF_TITLEISLINKNAME) == 0)
+        return FALSE;
+
+    if (IconPath == NULL || piIcon == NULL)
+        return FALSE;
+
+    IconPath[0] = L'\0';
+    *piIcon = 0;
+
+    /* 1- Find the last path separator if any */
+    LinkName = wcsrchr(ConsoleStartInfo->ConsoleTitle, PATH_SEPARATOR);
+    if (LinkName == NULL)
     {
-        Thread = CreateRemoteThread(ProcessData->Process->ProcessHandle, NULL, 0,
-                                    ProcessData->CtrlDispatcher,
-                                    UlongToPtr(Event), 0, NULL);
-        if (NULL == Thread)
+        LinkName = ConsoleStartInfo->ConsoleTitle;
+    }
+    else
+    {
+        /* Skip the path separator */
+        ++LinkName;
+    }
+
+    /* 2- Check for the link extension. The name ".lnk" is considered invalid. */
+    Length = wcslen(LinkName);
+    if ( (Length <= 4) || (wcsicmp(LinkName + (Length - 4), L".lnk") != 0) )
+        return FALSE;
+
+    /* 3- It may be a link. Try to retrieve some properties */
+    HRESULT hRes = CoInitialize(NULL);
+    if (SUCCEEDED(hRes))
+    {
+        /* Get a pointer to the IShellLink interface */
+        IShellLinkW* pshl = NULL;
+        hRes = CoCreateInstance(&CLSID_ShellLink,
+                                NULL, 
+                                CLSCTX_INPROC_SERVER,
+                                &IID_IShellLinkW,
+                                (LPVOID*)&pshl);
+        if (SUCCEEDED(hRes))
         {
-            DPRINT1("Failed thread creation (Error: 0x%x)\n", GetLastError());
-            return;
+            /* Get a pointer to the IPersistFile interface */
+            IPersistFile* ppf = NULL;
+            hRes = IPersistFile_QueryInterface(pshl, &IID_IPersistFile, (LPVOID*)&ppf);
+            if (SUCCEEDED(hRes))
+            {
+                /* Load the shortcut */
+                hRes = IPersistFile_Load(ppf, ConsoleStartInfo->ConsoleTitle, STGM_READ);
+                if (SUCCEEDED(hRes))
+                {
+                    /*
+                     * Finally we can get the properties !
+                     * Update the old ones if needed.
+                     */
+                    INT ShowCmd = 0;
+                    // WORD HotKey = 0;
+
+                    /* Reset the name of the console with the name of the shortcut */
+                    Length = min(/*Length*/ Length - 4, // 4 == len(".lnk")
+                                 sizeof(ConsoleInfo->ConsoleTitle) / sizeof(ConsoleInfo->ConsoleTitle[0]) - 1);
+                    wcsncpy(ConsoleInfo->ConsoleTitle, LinkName, Length);
+                    ConsoleInfo->ConsoleTitle[Length] = L'\0';
+
+                    /* Get the window showing command */
+                    hRes = IShellLinkW_GetShowCmd(pshl, &ShowCmd);
+                    if (SUCCEEDED(hRes)) ConsoleStartInfo->ShowWindow = (WORD)ShowCmd;
+
+                    /* Get the hotkey */
+                    // hRes = pshl->GetHotkey(&ShowCmd);
+                    // if (SUCCEEDED(hRes)) ConsoleStartInfo->HotKey = HotKey;
+
+                    /* Get the icon location, if any */
+                    hRes = IShellLinkW_GetIconLocation(pshl, IconPath, IconPathLength, piIcon);
+                    if (!SUCCEEDED(hRes))
+                    {
+                        IconPath[0] = L'\0';
+                    }
+
+                    // FIXME: Since we still don't load console properties from the shortcut,
+                    // return false. When this will be done, we will return true instead.
+                    RetVal = FALSE;
+                }
+                IPersistFile_Release(ppf);
+            }
+            IShellLinkW_Release(pshl);
         }
-
-        DPRINT1("We succeeded at creating ProcessData->CtrlDispatcher remote thread, ProcessId = %x, Process = 0x%p\n", ProcessData->Process->ClientId.UniqueProcess, ProcessData->Process);
-        WaitForSingleObject(Thread, Timeout);
-        CloseHandle(Thread);
     }
-}
+    CoUninitialize();
 
-VOID FASTCALL
-ConioConsoleCtrlEvent(DWORD Event, PCONSOLE_PROCESS_DATA ProcessData)
-{
-    ConioConsoleCtrlEventTimeout(Event, ProcessData, 0);
+    return RetVal;
 }
 
 NTSTATUS WINAPI
-CsrInitConsole(PCONSOLE* NewConsole, int ShowCmd, PCSR_PROCESS ConsoleLeaderProcess)
+ConSrvInitConsole(OUT PCONSOLE* NewConsole,
+                  IN OUT PCONSOLE_START_INFO ConsoleStartInfo,
+                  IN PCSR_PROCESS ConsoleLeaderProcess)
 {
     NTSTATUS Status;
     SECURITY_ATTRIBUTES SecurityAttributes;
+    CONSOLE_INFO ConsoleInfo;
+    SIZE_T Length = 0;
+    DWORD ProcessId = HandleToUlong(ConsoleLeaderProcess->ClientId.UniqueProcess);
     PCONSOLE Console;
     PCONSOLE_SCREEN_BUFFER NewBuffer;
     BOOL GuiMode;
-    WCHAR Title[255];
+    WCHAR Title[128];
+    WCHAR IconPath[MAX_PATH + 1] = L"";
+    INT iIcon = 0;
 
     if (NewConsole == NULL) return STATUS_INVALID_PARAMETER;
-
     *NewConsole = NULL;
 
-    /* Allocate a console structure */
-    Console = HeapAlloc(ConSrvHeap, HEAP_ZERO_MEMORY, sizeof(CONSOLE));
+    /*
+     * Allocate a console structure
+     */
+    Console = RtlAllocateHeap(ConSrvHeap, HEAP_ZERO_MEMORY, sizeof(CONSOLE));
     if (NULL == Console)
     {
         DPRINT1("Not enough memory for console creation.\n");
         return STATUS_NO_MEMORY;
     }
 
-    /* Initialize the console */
-    Console->Title.MaximumLength = Console->Title.Length = 0;
-    Console->Title.Buffer = NULL;
+    /*
+     * Load the console settings
+     */
+
+    /* 1. Load the default settings */
+    ConSrvGetDefaultSettings(&ConsoleInfo, ProcessId);
 
-    if (LoadStringW(ConSrvDllInstance, IDS_COMMAND_PROMPT, Title, sizeof(Title) / sizeof(Title[0])))
+    /* 2. Get the title of the console (initialize ConsoleInfo.ConsoleTitle) */
+    Length = min(wcslen(ConsoleStartInfo->ConsoleTitle),
+                 sizeof(ConsoleInfo.ConsoleTitle) / sizeof(ConsoleInfo.ConsoleTitle[0]) - 1);
+    wcsncpy(ConsoleInfo.ConsoleTitle, ConsoleStartInfo->ConsoleTitle, Length);
+    ConsoleInfo.ConsoleTitle[Length] = L'\0';
+
+    /*
+     * 3. Check whether the process creating the console was launched
+     *    via a shell-link. ConsoleInfo.ConsoleTitle may be updated by
+     *    the name of the shortcut.
+     */
+    if (ConsoleStartInfo->dwStartupFlags & STARTF_TITLEISLINKNAME)
     {
-        RtlCreateUnicodeString(&Console->Title, Title);
+        if (!LoadShellLinkConsoleInfo(ConsoleStartInfo,
+                                      &ConsoleInfo,
+                                      IconPath,
+                                      MAX_PATH,
+                                      &iIcon))
+        {
+            ConsoleStartInfo->dwStartupFlags &= ~STARTF_TITLEISLINKNAME;
+        }
     }
-    else
+
+    /*
+     * 4. Load the remaining console settings via the registry.
+     */
+    if ((ConsoleStartInfo->dwStartupFlags & STARTF_TITLEISLINKNAME) == 0)
     {
-        RtlCreateUnicodeString(&Console->Title, L"Command Prompt");
+        /*
+         * Either we weren't created by an app launched via a shell-link,
+         * or we failed to load shell-link console properties.
+         * Therefore, load the console infos for the application from the registry.
+         */
+        ConSrvReadUserSettings(&ConsoleInfo, ProcessId);
+
+        /*
+         * Now, update them with the properties the user might gave to us
+         * via the STARTUPINFO structure before calling CreateProcess
+         * (and which was transmitted via the ConsoleStartInfo structure).
+         * We therefore overwrite the values read in the registry.
+         */
+        if (ConsoleStartInfo->dwStartupFlags & STARTF_USEFILLATTRIBUTE)
+        {
+            ConsoleInfo.ScreenAttrib = ConsoleStartInfo->FillAttribute;
+        }
+        if (ConsoleStartInfo->dwStartupFlags & STARTF_USECOUNTCHARS)
+        {
+            ConsoleInfo.ScreenBufferSize = ConsoleStartInfo->ScreenBufferSize;
+        }
+        if (ConsoleStartInfo->dwStartupFlags & STARTF_USESIZE)
+        {
+            // ConsoleInfo->ConsoleSize = ConsoleStartInfo->ConsoleWindowSize;
+            ConsoleInfo.ConsoleSize.X = (SHORT)ConsoleStartInfo->ConsoleWindowSize.cx;
+            ConsoleInfo.ConsoleSize.Y = (SHORT)ConsoleStartInfo->ConsoleWindowSize.cy;
+        }
+        /*
+        if (ConsoleStartInfo->dwStartupFlags & STARTF_RUNFULLSCREEN)
+        {
+            ConsoleInfo.FullScreen = TRUE;
+        }
+        */
     }
 
+    /*
+     * Initialize the console
+     */
+    Console->State = CONSOLE_INITIALIZING;
+    InitializeCriticalSection(&Console->Lock);
     Console->ReferenceCount = 0;
-    Console->LineBuffer = NULL;
-    Console->Header.Type = CONIO_CONSOLE_MAGIC;
-    Console->Header.Console = Console;
-    Console->Mode = ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_MOUSE_INPUT;
-    Console->ConsoleLeaderCID = ConsoleLeaderProcess->ClientId;
     InitializeListHead(&Console->ProcessList);
-    InitializeListHead(&Console->BufferList);
-    Console->ActiveBuffer = NULL;
-    InitializeListHead(&Console->ReadWaitQueue);
-    InitializeListHead(&Console->WriteWaitQueue);
-    InitializeListHead(&Console->InputEvents);
-    InitializeListHead(&Console->HistoryBuffers);
-    Console->CodePage = GetOEMCP();
-    Console->OutputCodePage = GetOEMCP();
+    memcpy(Console->Colors, ConsoleInfo.Colors, sizeof(ConsoleInfo.Colors));
+    Console->ConsoleSize = ConsoleInfo.ConsoleSize;
+
+    /*
+     * Initialize the input buffer
+     */
+    Console->InputBuffer.Header.Type = INPUT_BUFFER;
+    Console->InputBuffer.Header.Console = Console;
 
     SecurityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
     SecurityAttributes.lpSecurityDescriptor = NULL;
     SecurityAttributes.bInheritHandle = TRUE;
-
-    Console->ActiveEvent = CreateEventW(&SecurityAttributes, TRUE, FALSE, NULL);
-    if (NULL == Console->ActiveEvent)
+    Console->InputBuffer.ActiveEvent = CreateEventW(&SecurityAttributes, TRUE, FALSE, NULL);
+    if (NULL == Console->InputBuffer.ActiveEvent)
     {
-        RtlFreeUnicodeString(&Console->Title);
-        HeapFree(ConSrvHeap, 0, Console);
+        DeleteCriticalSection(&Console->Lock);
+        RtlFreeHeap(ConSrvHeap, 0, Console);
         return STATUS_UNSUCCESSFUL;
     }
-    Console->PrivateData = NULL;
-    InitializeCriticalSection(&Console->Lock);
 
-    GuiMode = DtbgIsDesktopVisible();
+    Console->InputBuffer.Mode = ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT |
+                                ENABLE_ECHO_INPUT      | ENABLE_MOUSE_INPUT;
+    Console->QuickEdit  = ConsoleInfo.QuickEdit;
+    Console->InsertMode = ConsoleInfo.InsertMode;
+    InitializeListHead(&Console->InputBuffer.ReadWaitQueue);
+    InitializeListHead(&Console->InputBuffer.InputEvents);
+    Console->LineBuffer = NULL;
+    Console->CodePage = GetOEMCP();
+    Console->OutputCodePage = GetOEMCP();
 
-    /* allocate console screen buffer */
-    NewBuffer = HeapAlloc(ConSrvHeap, HEAP_ZERO_MEMORY, sizeof(CONSOLE_SCREEN_BUFFER));
-    if (NULL == NewBuffer)
+    /* Initialize a new screen buffer with default settings */
+    InitializeListHead(&Console->BufferList);
+    Status = ConSrvCreateScreenBuffer(Console,
+                                      &NewBuffer,
+                                      ConsoleInfo.ScreenBufferSize,
+                                      ConsoleInfo.ScreenAttrib,
+                                      ConsoleInfo.PopupAttrib,
+                                      (ConsoleInfo.FullScreen ? CONSOLE_FULLSCREEN_MODE
+                                                              : CONSOLE_WINDOWED_MODE),
+                                      TRUE,
+                                      ConsoleInfo.CursorSize);
+    if (!NT_SUCCESS(Status))
     {
-        RtlFreeUnicodeString(&Console->Title);
+        DPRINT1("ConSrvCreateScreenBuffer: failed, Status = 0x%08lx\n", Status);
+        CloseHandle(Console->InputBuffer.ActiveEvent);
         DeleteCriticalSection(&Console->Lock);
-        CloseHandle(Console->ActiveEvent);
-        HeapFree(ConSrvHeap, 0, Console);
-        return STATUS_INSUFFICIENT_RESOURCES;
+        RtlFreeHeap(ConSrvHeap, 0, Console);
+        return Status;
     }
-    /* init screen buffer with defaults */
-    NewBuffer->CursorInfo.bVisible = TRUE;
-    NewBuffer->CursorInfo.dwSize = CSR_DEFAULT_CURSOR_SIZE;
-    /* make console active, and insert into console list */
-    Console->ActiveBuffer = (PCONSOLE_SCREEN_BUFFER) NewBuffer;
+    /* Make the new screen buffer active */
+    Console->ActiveBuffer = NewBuffer;
+    InitializeListHead(&Console->WriteWaitQueue);
 
     /*
-     * If we are not in GUI-mode, start the text-mode console. If we fail,
-     * try to start the GUI-mode console (win32k will automatically switch
-     * to graphical mode, therefore no additional code is needed).
+     * Initialize the history buffers
      */
+    InitializeListHead(&Console->HistoryBuffers);
+    Console->HistoryBufferSize = ConsoleInfo.HistoryBufferSize;
+    Console->NumberOfHistoryBuffers = ConsoleInfo.NumberOfHistoryBuffers;
+    Console->HistoryNoDup = ConsoleInfo.HistoryNoDup;
+
+    /* Initialize the console title */
+    RtlCreateUnicodeString(&Console->OriginalTitle, ConsoleInfo.ConsoleTitle);
+    if (ConsoleInfo.ConsoleTitle[0] == L'\0')
+    {
+        if (LoadStringW(ConSrvDllInstance, IDS_CONSOLE_TITLE, Title, sizeof(Title) / sizeof(Title[0])))
+        {
+            RtlCreateUnicodeString(&Console->Title, Title);
+        }
+        else
+        {
+            RtlCreateUnicodeString(&Console->Title, L"ReactOS Console");
+        }
+    }
+    else
+    {
+        RtlCreateUnicodeString(&Console->Title, ConsoleInfo.ConsoleTitle);
+    }
+
+    /* Lock the console until its initialization is finished */
+    // EnterCriticalSection(&Console->Lock);
+
+    /*
+     * If we are not in GUI-mode, start the text-mode terminal emulator.
+     * If we fail, try to start the GUI-mode terminal emulator.
+     */
+#ifdef TUI_CONSOLE
+    GuiMode = DtbgIsDesktopVisible();
+#else
+    GuiMode = TRUE;
+#endif
+
+#ifdef TUI_CONSOLE
     if (!GuiMode)
     {
-        DPRINT1("CONSRV: Opening text-mode console\n");
-        Status = TuiInitConsole(Console);
+        DPRINT1("CONSRV: Opening text-mode terminal emulator\n");
+        Status = TuiInitConsole(Console,
+                                ConsoleStartInfo,
+                                &ConsoleInfo,
+                                ProcessId);
         if (!NT_SUCCESS(Status))
         {
-            DPRINT1("Failed to open text-mode console, switching to gui-mode, Status = 0x%08lx\n", Status);
+            DPRINT1("Failed to open text-mode terminal emulator, switching to gui-mode, Status = 0x%08lx\n", Status);
             GuiMode = TRUE;
         }
     }
+#endif
 
     /*
-     * Try to open the GUI-mode console. Two cases are possible:
+     * Try to open the GUI-mode terminal emulator. Two cases are possible:
      * - We are in GUI-mode, therefore GuiMode == TRUE, the previous test-case
-     *   failed and we start GUI-mode console.
+     *   failed and we start GUI-mode terminal emulator.
      * - We are in text-mode, therefore GuiMode == FALSE, the previous test-case
-     *   succeeded BUT we failed at starting text-mode console. Then GuiMode
-     *   was switched to TRUE in order to try to open the console in GUI-mode.
+     *   succeeded BUT we failed at starting text-mode terminal emulator.
+     *   Then GuiMode was switched to TRUE in order to try to open the GUI-mode
+     *   terminal emulator (Win32k will automatically switch to graphical mode,
+     *   therefore no additional code is needed).
      */
     if (GuiMode)
     {
-        DPRINT1("CONSRV: Opening GUI-mode console\n");
-        Status = GuiInitConsole(Console, ShowCmd);
+        DPRINT1("CONSRV: Opening GUI-mode terminal emulator\n");
+        Status = GuiInitConsole(Console,
+                                ConsoleStartInfo,
+                                &ConsoleInfo,
+                                ProcessId,
+                                IconPath,
+                                iIcon);
         if (!NT_SUCCESS(Status))
         {
-            HeapFree(ConSrvHeap,0, NewBuffer);
+            DPRINT1("GuiInitConsole: failed, Status = 0x%08lx\n", Status);
             RtlFreeUnicodeString(&Console->Title);
+            RtlFreeUnicodeString(&Console->OriginalTitle);
+            ConioDeleteScreenBuffer(NewBuffer);
+            CloseHandle(Console->InputBuffer.ActiveEvent);
+            // LeaveCriticalSection(&Console->Lock);
             DeleteCriticalSection(&Console->Lock);
-            CloseHandle(Console->ActiveEvent);
-            DPRINT1("GuiInitConsole: failed, Status = 0x%08lx\n", Status);
-            HeapFree(ConSrvHeap, 0, Console);
+            RtlFreeHeap(ConSrvHeap, 0, Console);
             return Status;
         }
     }
 
-    Status = CsrInitConsoleScreenBuffer(Console, NewBuffer);
-    if (!NT_SUCCESS(Status))
-    {
-        ConioCleanupConsole(Console);
-        RtlFreeUnicodeString(&Console->Title);
-        DeleteCriticalSection(&Console->Lock);
-        CloseHandle(Console->ActiveEvent);
-        HeapFree(ConSrvHeap, 0, NewBuffer);
-        DPRINT1("CsrInitConsoleScreenBuffer: failed\n");
-        HeapFree(ConSrvHeap, 0, Console);
-        return Status;
-    }
+    DPRINT("Terminal initialized\n");
+
+    /* All went right, so add the console to the list */
+    ConSrvLockConsoleListExclusive();
+    DPRINT("Insert in the list\n");
+    InsertTailList(&ConsoleList, &Console->Entry);
+
+    /* The initialization is finished */
+    DPRINT("Change state\n");
+    Console->State = CONSOLE_RUNNING;
+
+    /* Unlock the console */
+    // LeaveCriticalSection(&Console->Lock);
+
+    /* Unlock the console list */
+    ConSrvUnlockConsoleList();
 
     /* Copy buffer contents to screen */
     ConioDrawConsole(Console);
+    DPRINT("Console drawn\n");
 
+    /* Return the newly created console to the caller and a success code too */
     *NewConsole = Console;
-
     return STATUS_SUCCESS;
 }
 
-CSR_API(SrvOpenConsole)
+VOID WINAPI
+ConSrvDeleteConsole(PCONSOLE Console)
 {
-    NTSTATUS Status = STATUS_SUCCESS;
-    PCONSOLE_OPENCONSOLE OpenConsoleRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.OpenConsoleRequest;
-    PCONSOLE_PROCESS_DATA ProcessData = ConsoleGetPerProcessData(CsrGetClientThread()->Process);
+    DPRINT("ConSrvDeleteConsole\n");
+
+    /*
+     * Forbid validation of any console by other threads
+     * during the deletion of this console.
+     */
+    ConSrvLockConsoleListExclusive();
+
+    /* Check the existence of the console, and if it's ok, continue */
+    if (!ConSrvValidateConsolePointer(Console))
+    {
+        /* Unlock the console list and return */
+        ConSrvUnlockConsoleList();
+        return;
+    }
 
-    DPRINT("SrvOpenConsole\n");
+    /*
+     * If the console is already being destroyed
+     * (thus not running), just return.
+     */
+    if (!ConSrvValidateConsoleUnsafe(Console, CONSOLE_RUNNING, TRUE))
+    {
+        /* Unlock the console list and return */
+        ConSrvUnlockConsoleList();
+        return;
+    }
 
-    OpenConsoleRequest->ConsoleHandle = INVALID_HANDLE_VALUE;
+    /*
+     * We are about to be destroyed. Signal it to other people
+     * so that they can terminate what they are doing, and that
+     * they cannot longer validate the console.
+     */
+    Console->State = CONSOLE_TERMINATING;
 
-    RtlEnterCriticalSection(&ProcessData->HandleTableLock);
+    /*
+     * Allow other threads to finish their job: basically, unlock
+     * all other calls to EnterCriticalSection(&Console->Lock); by
+     * ConSrvValidateConsole(Unsafe) functions so that they just see
+     * that we are not in CONSOLE_RUNNING state anymore, or unlock
+     * other concurrent calls to ConSrvDeleteConsole so that they
+     * can see that we are in fact already deleting the console.
+     */
+    LeaveCriticalSection(&Console->Lock);
+    ConSrvUnlockConsoleList();
+
+    /* FIXME: Send a terminate message to all the processes owning this console */
+
+    /* Cleanup the UI-oriented part */
+    ConioCleanupConsole(Console);
 
-    DPRINT1("SrvOpenConsole - Checkpoint 1\n");
-    DPRINT1("ProcessData = 0x%p ; ProcessData->Console = 0x%p\n", ProcessData, ProcessData->Console);
+    /***
+     * Check that the console is in terminating state before continuing
+     * (the cleanup code must not change the state of the console...
+     * ...unless to cancel console deletion ?).
+     ***/
+
+    ConSrvLockConsoleListExclusive();
+
+    /* Re-check the existence of the console, and if it's ok, continue */
+    if (!ConSrvValidateConsolePointer(Console))
+    {
+        /* Unlock the console list and return */
+        ConSrvUnlockConsoleList();
+        return;
+    }
 
-    if (ProcessData->Console)
+    if (!ConSrvValidateConsoleUnsafe(Console, CONSOLE_TERMINATING, TRUE))
     {
-        DWORD DesiredAccess = OpenConsoleRequest->Access;
-        DWORD ShareMode = OpenConsoleRequest->ShareMode;
+        ConSrvUnlockConsoleList();
+        return;
+    }
 
-        PCONSOLE Console = ProcessData->Console;
-        Object_t *Object;
+    /* We are in destruction */
+    Console->State = CONSOLE_IN_DESTRUCTION;
 
-        DPRINT1("SrvOpenConsole - Checkpoint 2\n");
-        EnterCriticalSection(&Console->Lock);
-        DPRINT1("SrvOpenConsole - Checkpoint 3\n");
+    /* Remove the console from the list */
+    RemoveEntryList(&Console->Entry);
 
-        if (OpenConsoleRequest->HandleType == HANDLE_OUTPUT)
-            Object = &Console->ActiveBuffer->Header;
-        else // HANDLE_INPUT
-            Object = &Console->Header;
+    /* Reset the count to be sure */
+    Console->ReferenceCount = 0;
 
-        if (((DesiredAccess & GENERIC_READ)  && Object->ExclusiveRead  != 0) ||
-            ((DesiredAccess & GENERIC_WRITE) && Object->ExclusiveWrite != 0) ||
-            (!(ShareMode & FILE_SHARE_READ)  && Object->AccessRead     != 0) ||
-            (!(ShareMode & FILE_SHARE_WRITE) && Object->AccessWrite    != 0))
-        {
-            DPRINT1("Sharing violation\n");
-            Status = STATUS_SHARING_VIOLATION;
-        }
-        else
-        {
-            Status = Win32CsrInsertObject(ProcessData,
-                                          &OpenConsoleRequest->ConsoleHandle,
-                                          Object,
-                                          DesiredAccess,
-                                          OpenConsoleRequest->Inheritable,
-                                          ShareMode);
-        }
+    /* Discard all entries in the input event queue */
+    PurgeInputBuffer(Console);
+
+    if (Console->LineBuffer) RtlFreeHeap(ConSrvHeap, 0, Console->LineBuffer);
+
+    IntDeleteAllAliases(Console);
+    HistoryDeleteBuffers(Console);
 
-        LeaveCriticalSection(&Console->Lock);
+    ConioDeleteScreenBuffer(Console->ActiveBuffer);
+    if (!IsListEmpty(&Console->BufferList))
+    {
+        DPRINT1("BUG: screen buffer list not empty\n");
     }
 
-    RtlLeaveCriticalSection(&ProcessData->HandleTableLock);
+    // CloseHandle(Console->InputBuffer.ActiveEvent);
+    if (Console->UnpauseEvent) CloseHandle(Console->UnpauseEvent);
 
-    return Status;
+    RtlFreeUnicodeString(&Console->OriginalTitle);
+    RtlFreeUnicodeString(&Console->Title);
+
+    DPRINT("ConSrvDeleteConsole - Unlocking\n");
+    LeaveCriticalSection(&Console->Lock);
+    DPRINT("ConSrvDeleteConsole - Destroying lock\n");
+    DeleteCriticalSection(&Console->Lock);
+    DPRINT("ConSrvDeleteConsole - Lock destroyed ; freeing console\n");
+
+    RtlFreeHeap(ConSrvHeap, 0, Console);
+    DPRINT("ConSrvDeleteConsole - Console freed\n");
+
+    /* Unlock the console list and return */
+    ConSrvUnlockConsoleList();
 }
 
+
+/* PUBLIC SERVER APIS *********************************************************/
+
 CSR_API(SrvAllocConsole)
 {
     NTSTATUS Status = STATUS_SUCCESS;
     PCONSOLE_ALLOCCONSOLE AllocConsoleRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.AllocConsoleRequest;
-    PCSR_PROCESS ConsoleLeader = CsrGetClientThread()->Process;
-    PCONSOLE_PROCESS_DATA ProcessData = ConsoleGetPerProcessData(ConsoleLeader);
-
-    DPRINT("SrvAllocConsole\n");
+    PCSR_PROCESS CsrProcess = CsrGetClientThread()->Process;
+    PCONSOLE_PROCESS_DATA ProcessData = ConsoleGetPerProcessData(CsrProcess);
 
     if (ProcessData->Console != NULL)
     {
@@ -304,13 +852,16 @@ CSR_API(SrvAllocConsole)
         return STATUS_ACCESS_DENIED;
     }
 
-/******************************************************************************/
-/** This comes from ConsoleConnect!!                                         **/
-    DPRINT1("SrvAllocConsole - Checkpoint 1\n");
-
-#if 0000
+    if (!CsrValidateMessageBuffer(ApiMessage,
+                                  (PVOID*)&AllocConsoleRequest->ConsoleStartInfo,
+                                  1,
+                                  sizeof(CONSOLE_START_INFO)))
+    {
+        return STATUS_INVALID_PARAMETER;
+    }
+
     /*
-     * We are about to create a new console. However when ConsoleNewProcess
+     * We are about to create a new console. However when ConSrvNewProcess
      * was called, we didn't know that we wanted to create a new console and
      * therefore, we by default inherited the handles table from our parent
      * process. It's only now that we notice that in fact we do not need
@@ -319,123 +870,31 @@ CSR_API(SrvAllocConsole)
      * Therefore, free the console we can have and our handles table,
      * and recreate a new one later on.
      */
-    Win32CsrReleaseConsole(ProcessData);
-    // Win32CsrFreeHandlesTable(ProcessData);
-#endif
+    ConSrvRemoveConsole(ProcessData);
 
     /* Initialize a new Console owned by the Console Leader Process */
-    Status = CsrInitConsole(&ProcessData->Console, AllocConsoleRequest->ShowCmd, ConsoleLeader);
+    Status = ConSrvAllocateConsole(ProcessData,
+                                   &AllocConsoleRequest->InputHandle,
+                                   &AllocConsoleRequest->OutputHandle,
+                                   &AllocConsoleRequest->ErrorHandle,
+                                   AllocConsoleRequest->ConsoleStartInfo);
     if (!NT_SUCCESS(Status))
     {
-        DPRINT1("Console initialization failed\n");
+        DPRINT1("Console allocation failed\n");
         return Status;
     }
 
-    /* Add a reference count because the process is tied to the console */
-    _InterlockedIncrement(&ProcessData->Console->ReferenceCount);
-
-    /* Insert the process into the processes list of the console */
-    InsertHeadList(&ProcessData->Console->ProcessList, &ProcessData->ConsoleLink);
-
     /* Return it to the caller */
     AllocConsoleRequest->Console = ProcessData->Console;
 
-
-    /*
-     * Create a new handle table - Insert the IO handles
-     */
-
-    RtlEnterCriticalSection(&ProcessData->HandleTableLock);
-
-    /* Insert the Input handle */
-    Status = Win32CsrInsertObject(ProcessData,
-                                  &AllocConsoleRequest->InputHandle,
-                                  &ProcessData->Console->Header,
-                                  GENERIC_READ | GENERIC_WRITE,
-                                  TRUE,
-                                  FILE_SHARE_READ | FILE_SHARE_WRITE);
-    if (!NT_SUCCESS(Status))
-    {
-        DPRINT1("Failed to insert the input handle\n");
-        RtlLeaveCriticalSection(&ProcessData->HandleTableLock);
-        Win32CsrReleaseConsole(ProcessData);
-        // ConioDeleteConsole(ProcessData->Console);
-        // ProcessData->Console = NULL;
-        return Status;
-    }
-
-    /* Insert the Output handle */
-    Status = Win32CsrInsertObject(ProcessData,
-                                  &AllocConsoleRequest->OutputHandle,
-                                  &ProcessData->Console->ActiveBuffer->Header,
-                                  GENERIC_READ | GENERIC_WRITE,
-                                  TRUE,
-                                  FILE_SHARE_READ | FILE_SHARE_WRITE);
-    if (!NT_SUCCESS(Status))
-    {
-        DPRINT1("Failed to insert the output handle\n");
-        RtlLeaveCriticalSection(&ProcessData->HandleTableLock);
-        Win32CsrReleaseConsole(ProcessData);
-        // Win32CsrReleaseObject(ProcessData,
-                              // AllocConsoleRequest->InputHandle);
-        // ConioDeleteConsole(ProcessData->Console);
-        // ProcessData->Console = NULL;
-        return Status;
-    }
-
-    /* Insert the Error handle */
-    Status = Win32CsrInsertObject(ProcessData,
-                                  &AllocConsoleRequest->ErrorHandle,
-                                  &ProcessData->Console->ActiveBuffer->Header,
-                                  GENERIC_READ | GENERIC_WRITE,
-                                  TRUE,
-                                  FILE_SHARE_READ | FILE_SHARE_WRITE);
-    if (!NT_SUCCESS(Status))
-    {
-        DPRINT1("Failed to insert the error handle\n");
-        RtlLeaveCriticalSection(&ProcessData->HandleTableLock);
-        Win32CsrReleaseConsole(ProcessData);
-        // Win32CsrReleaseObject(ProcessData,
-                              // AllocConsoleRequest->OutputHandle);
-        // Win32CsrReleaseObject(ProcessData,
-                              // AllocConsoleRequest->InputHandle);
-        // ConioDeleteConsole(ProcessData->Console);
-        // ProcessData->Console = NULL;
-        return Status;
-    }
-
-    RtlLeaveCriticalSection(&ProcessData->HandleTableLock);
-
-    /* Duplicate the Event */
-    Status = NtDuplicateObject(NtCurrentProcess(),
-                               ProcessData->Console->ActiveEvent,
-                               ProcessData->Process->ProcessHandle,
-                               &ProcessData->ConsoleEvent,
-                               EVENT_ALL_ACCESS, 0, 0);
-    if (!NT_SUCCESS(Status))
-    {
-        DPRINT1("NtDuplicateObject() failed: %lu\n", Status);
-        Win32CsrReleaseConsole(ProcessData);
-        // if (NewConsole)
-        // {
-            // Win32CsrReleaseObject(ProcessData,
-                                  // AllocConsoleRequest->ErrorHandle);
-            // Win32CsrReleaseObject(ProcessData,
-                                  // AllocConsoleRequest->OutputHandle);
-            // Win32CsrReleaseObject(ProcessData,
-                                  // AllocConsoleRequest->InputHandle);
-        // }
-        // ConioDeleteConsole(ProcessData->Console); // FIXME: Just release the console ?
-        // ProcessData->Console = NULL;
-        return Status;
-    }
     /* Input Wait Handle */
     AllocConsoleRequest->InputWaitHandle = ProcessData->ConsoleEvent;
 
+    /* Set the Property Dialog Handler */
+    ProcessData->PropDispatcher = AllocConsoleRequest->PropDispatcher;
+
     /* Set the Ctrl Dispatcher */
     ProcessData->CtrlDispatcher = AllocConsoleRequest->CtrlDispatcher;
-    DPRINT("CONSRV: CtrlDispatcher address: %x\n", ProcessData->CtrlDispatcher);
-/******************************************************************************/
 
     return STATUS_SUCCESS;
 }
@@ -449,8 +908,6 @@ CSR_API(SrvAttachConsole)
     HANDLE ProcessId = ULongToHandle(AttachConsoleRequest->ProcessId);
     PCONSOLE_PROCESS_DATA SourceProcessData, TargetProcessData;
 
-    DPRINT("SrvAttachConsole\n");
-
     TargetProcessData = ConsoleGetPerProcessData(TargetProcess);
 
     if (TargetProcessData->Console != NULL)
@@ -459,6 +916,7 @@ CSR_API(SrvAttachConsole)
         return STATUS_ACCESS_DENIED;
     }
 
+    /* Check whether we try to attach to the parent's console */
     if (ProcessId == ULongToHandle(ATTACH_PARENT_PROCESS))
     {
         PROCESS_BASIC_INFORMATION ProcessInfo;
@@ -476,259 +934,209 @@ CSR_API(SrvAttachConsole)
             return Status;
         }
 
-        DPRINT("We, process (ID) %lu;%lu\n", TargetProcess->ClientId.UniqueProcess, TargetProcess->ClientId.UniqueThread);
         ProcessId = ULongToHandle(ProcessInfo.InheritedFromUniqueProcessId);
-        DPRINT("Parent process ID = %lu\n", ProcessId);
     }
 
-    /* Lock the target process via its PID */
-    DPRINT1("Lock process Id %lu\n", ProcessId);
+    /* Lock the source process via its PID */
     Status = CsrLockProcessByClientId(ProcessId, &SourceProcess);
-    DPRINT1("Lock process Status %lu\n", Status);
     if (!NT_SUCCESS(Status)) return Status;
-    DPRINT1("AttachConsole OK\n");
 
-/******************************************************************************/
-/** This comes from ConsoleNewProcess!!                                      **/
     SourceProcessData = ConsoleGetPerProcessData(SourceProcess);
 
-    /*
-     * Inherit the console from the parent,
-     * if any, otherwise return an error.
-     */
-    DPRINT1("SourceProcessData->Console = 0x%p\n", SourceProcessData->Console);
     if (SourceProcessData->Console == NULL)
     {
         Status = STATUS_INVALID_HANDLE;
         goto Quit;
     }
-    TargetProcessData->Console = SourceProcessData->Console;
 
-    DPRINT1("SrvAttachConsole - Copy the handle table (1)\n");
-    Status = Win32CsrInheritHandlesTable(SourceProcessData, TargetProcessData);
-    DPRINT1("SrvAttachConsole - Copy the handle table (2)\n");
+    /*
+     * We are about to create a new console. However when ConSrvNewProcess
+     * was called, we didn't know that we wanted to create a new console and
+     * therefore, we by default inherited the handles table from our parent
+     * process. It's only now that we notice that in fact we do not need
+     * them, because we've created a new console and thus we must use it.
+     *
+     * Therefore, free the console we can have and our handles table,
+     * and recreate a new one later on.
+     */
+    ConSrvRemoveConsole(TargetProcessData);
+
+    /*
+     * Inherit the console from the parent,
+     * if any, otherwise return an error.
+     */
+    Status = ConSrvInheritConsole(TargetProcessData,
+                                  SourceProcessData->Console,
+                                  TRUE,
+                                  &AttachConsoleRequest->InputHandle,
+                                  &AttachConsoleRequest->OutputHandle,
+                                  &AttachConsoleRequest->ErrorHandle);
     if (!NT_SUCCESS(Status))
     {
+        DPRINT1("Console inheritance failed\n");
         goto Quit;
     }
 
-/******************************************************************************/
-
-/******************************************************************************/
-/** This comes from ConsoleConnect / SrvAllocConsole!!                       **/
-    /* Add a reference count because the process is tied to the console */
-    _InterlockedIncrement(&TargetProcessData->Console->ReferenceCount);
-
-    /* Insert the process into the processes list of the console */
-    InsertHeadList(&TargetProcessData->Console->ProcessList, &TargetProcessData->ConsoleLink);
-
     /* Return it to the caller */
     AttachConsoleRequest->Console = TargetProcessData->Console;
 
-    /** Here, we inherited the console handles from the "source" process,
-     ** so no need to reinitialize the handles table. **/
-
-    DPRINT1("SrvAttachConsole - Checkpoint\n");
-
-    /* Duplicate the Event */
-    Status = NtDuplicateObject(NtCurrentProcess(),
-                               TargetProcessData->Console->ActiveEvent,
-                               TargetProcessData->Process->ProcessHandle,
-                               &TargetProcessData->ConsoleEvent,
-                               EVENT_ALL_ACCESS, 0, 0);
-    if (!NT_SUCCESS(Status))
-    {
-        DPRINT1("NtDuplicateObject() failed: %lu\n", Status);
-        Win32CsrReleaseConsole(TargetProcessData);
-// #if 0
-        // if (NewConsole)
-        // {
-            // Win32CsrReleaseObject(TargetProcessData,
-                                  // AttachConsoleRequest->ErrorHandle);
-            // Win32CsrReleaseObject(TargetProcessData,
-                                  // AttachConsoleRequest->OutputHandle);
-            // Win32CsrReleaseObject(TargetProcessData,
-                                  // AttachConsoleRequest->InputHandle);
-        // }
-// #endif
-        // ConioDeleteConsole(TargetProcessData->Console); // FIXME: Just release the console ?
-        // TargetProcessData->Console = NULL;
-        goto Quit;
-    }
     /* Input Wait Handle */
     AttachConsoleRequest->InputWaitHandle = TargetProcessData->ConsoleEvent;
 
+    /* Set the Property Dialog Handler */
+    TargetProcessData->PropDispatcher = AttachConsoleRequest->PropDispatcher;
+
     /* Set the Ctrl Dispatcher */
     TargetProcessData->CtrlDispatcher = AttachConsoleRequest->CtrlDispatcher;
-    DPRINT("CONSRV: CtrlDispatcher address: %x\n", TargetProcessData->CtrlDispatcher);
 
     Status = STATUS_SUCCESS;
-/******************************************************************************/
 
 Quit:
-    DPRINT1("SrvAttachConsole - exiting 1\n");
-    /* Unlock the "source" process */
+    /* Unlock the "source" process and exit */
     CsrUnlockProcess(SourceProcess);
-    DPRINT1("SrvAttachConsole - exiting 2\n");
-
     return Status;
 }
 
 CSR_API(SrvFreeConsole)
 {
-    DPRINT1("SrvFreeConsole\n");
-    Win32CsrReleaseConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process));
+    ConSrvRemoveConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process));
     return STATUS_SUCCESS;
 }
 
-VOID WINAPI
-ConioDeleteConsole(PCONSOLE Console)
-{
-    ConsoleInput *Event;
-
-    DPRINT("ConioDeleteConsole\n");
-
-    /* Drain input event queue */
-    while (Console->InputEvents.Flink != &Console->InputEvents)
-    {
-        Event = (ConsoleInput *) Console->InputEvents.Flink;
-        Console->InputEvents.Flink = Console->InputEvents.Flink->Flink;
-        Console->InputEvents.Flink->Flink->Blink = &Console->InputEvents;
-        HeapFree(ConSrvHeap, 0, Event);
-    }
-
-    ConioCleanupConsole(Console);
-    if (Console->LineBuffer)
-        RtlFreeHeap(ConSrvHeap, 0, Console->LineBuffer);
-    while (!IsListEmpty(&Console->HistoryBuffers))
-        HistoryDeleteBuffer((struct _HISTORY_BUFFER *)Console->HistoryBuffers.Flink);
-
-    ConioDeleteScreenBuffer(Console->ActiveBuffer);
-    if (!IsListEmpty(&Console->BufferList))
-    {
-        DPRINT1("BUG: screen buffer list not empty\n");
-    }
-
-    CloseHandle(Console->ActiveEvent);
-    if (Console->UnpauseEvent) CloseHandle(Console->UnpauseEvent);
-    DeleteCriticalSection(&Console->Lock);
-    RtlFreeUnicodeString(&Console->Title);
-    IntDeleteAllAliases(Console->Aliases);
-    HeapFree(ConSrvHeap, 0, Console);
-}
-
-VOID WINAPI
-CsrInitConsoleSupport(VOID)
-{
-    DPRINT("CSR: CsrInitConsoleSupport()\n");
-
-    /* Should call LoadKeyboardLayout */
-}
-
-VOID FASTCALL
-ConioPause(PCONSOLE Console, UINT Flags)
-{
-    Console->PauseFlags |= Flags;
-    if (!Console->UnpauseEvent)
-        Console->UnpauseEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
-}
-
-VOID FASTCALL
-ConioUnpause(PCONSOLE Console, UINT Flags)
-{
-    Console->PauseFlags &= ~Flags;
-
-    // if ((Console->PauseFlags & (PAUSED_FROM_KEYBOARD | PAUSED_FROM_SCROLLBAR | PAUSED_FROM_SELECTION)) == 0)
-    if (Console->PauseFlags == 0 && Console->UnpauseEvent)
-    {
-        SetEvent(Console->UnpauseEvent);
-        CloseHandle(Console->UnpauseEvent);
-        Console->UnpauseEvent = NULL;
-
-        CsrNotifyWait(&Console->WriteWaitQueue,
-                      WaitAll,
-                      NULL,
-                      NULL);
-    }
-}
-
-CSR_API(SrvSetConsoleMode)
+CSR_API(SrvGetConsoleMode)
 {
     NTSTATUS Status;
     PCONSOLE_GETSETCONSOLEMODE ConsoleModeRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.ConsoleModeRequest;
-    PCONSOLE Console;
-    PCONSOLE_SCREEN_BUFFER Buff;
-
-    DPRINT("SrvSetConsoleMode\n");
+    PCONSOLE_IO_OBJECT Object = NULL;
 
-    Status = Win32CsrLockObject(ConsoleGetPerProcessData(CsrGetClientThread()->Process),
-                                ConsoleModeRequest->ConsoleHandle,
-                                (Object_t **) &Console, GENERIC_WRITE, 0);
+    Status = ConSrvGetObject(ConsoleGetPerProcessData(CsrGetClientThread()->Process),
+                             ConsoleModeRequest->ConsoleHandle,
+                             &Object, NULL, GENERIC_READ, TRUE, 0);
     if (!NT_SUCCESS(Status)) return Status;
 
-    Buff = (PCONSOLE_SCREEN_BUFFER)Console;
+    Status = STATUS_SUCCESS;
 
-    if (CONIO_CONSOLE_MAGIC == Console->Header.Type)
+    if (INPUT_BUFFER == Object->Type)
     {
-        Console->Mode = ConsoleModeRequest->ConsoleMode & CONSOLE_INPUT_MODE_VALID;
+        PCONSOLE_INPUT_BUFFER InputBuffer = (PCONSOLE_INPUT_BUFFER)Object;
+        PCONSOLE Console  = InputBuffer->Header.Console;
+        DWORD ConsoleMode = InputBuffer->Mode;
+
+        if (Console->QuickEdit || Console->InsertMode)
+        {
+            // Windows does this, even if it's not documented on MSDN
+            ConsoleMode |= ENABLE_EXTENDED_FLAGS;
+
+            if (Console->QuickEdit ) ConsoleMode |= ENABLE_QUICK_EDIT_MODE;
+            if (Console->InsertMode) ConsoleMode |= ENABLE_INSERT_MODE;
+        }
+
+        ConsoleModeRequest->ConsoleMode = ConsoleMode;
     }
-    else if (CONIO_SCREEN_BUFFER_MAGIC == Console->Header.Type)
+    else if (SCREEN_BUFFER == Object->Type)
     {
-        Buff->Mode = ConsoleModeRequest->ConsoleMode & CONSOLE_OUTPUT_MODE_VALID;
+        PCONSOLE_SCREEN_BUFFER Buffer = (PCONSOLE_SCREEN_BUFFER)Object;
+        ConsoleModeRequest->ConsoleMode = Buffer->Mode;
     }
     else
     {
         Status = STATUS_INVALID_HANDLE;
     }
 
-    Win32CsrUnlockObject((Object_t *)Console);
-
+    ConSrvReleaseObject(Object, TRUE);
     return Status;
 }
 
-CSR_API(SrvGetConsoleMode)
+CSR_API(SrvSetConsoleMode)
 {
+#define CONSOLE_VALID_CONTROL_MODES ( ENABLE_EXTENDED_FLAGS   | ENABLE_INSERT_MODE  | ENABLE_QUICK_EDIT_MODE )
+#define CONSOLE_VALID_INPUT_MODES   ( ENABLE_PROCESSED_INPUT  | ENABLE_LINE_INPUT   | \
+                                      ENABLE_ECHO_INPUT       | ENABLE_WINDOW_INPUT | \
+                                      ENABLE_MOUSE_INPUT )
+#define CONSOLE_VALID_OUTPUT_MODES  ( ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT )
+
     NTSTATUS Status;
     PCONSOLE_GETSETCONSOLEMODE ConsoleModeRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.ConsoleModeRequest;
-    PCONSOLE Console;
-    PCONSOLE_SCREEN_BUFFER Buff;
+    DWORD ConsoleMode = ConsoleModeRequest->ConsoleMode;
+    PCONSOLE_IO_OBJECT Object  = NULL;
 
-    DPRINT("SrvGetConsoleMode\n");
-
-    Status = Win32CsrLockObject(ConsoleGetPerProcessData(CsrGetClientThread()->Process),
-                                ConsoleModeRequest->ConsoleHandle,
-                                (Object_t **) &Console, GENERIC_READ, 0);
+    Status = ConSrvGetObject(ConsoleGetPerProcessData(CsrGetClientThread()->Process),
+                             ConsoleModeRequest->ConsoleHandle,
+                             &Object, NULL, GENERIC_WRITE, TRUE, 0);
     if (!NT_SUCCESS(Status)) return Status;
 
     Status = STATUS_SUCCESS;
-    Buff = (PCONSOLE_SCREEN_BUFFER) Console;
 
-    if (CONIO_CONSOLE_MAGIC == Console->Header.Type)
+    if (INPUT_BUFFER == Object->Type)
     {
-        ConsoleModeRequest->ConsoleMode = Console->Mode;
+        PCONSOLE_INPUT_BUFFER InputBuffer = (PCONSOLE_INPUT_BUFFER)Object;
+        PCONSOLE Console = InputBuffer->Header.Console;
+
+        DPRINT("SetConsoleMode(Input, %d)\n", ConsoleMode);
+
+        /*
+         * 1. Only the presence of valid mode flags is allowed.
+         */
+        if (ConsoleMode & ~(CONSOLE_VALID_INPUT_MODES | CONSOLE_VALID_CONTROL_MODES))
+        {
+            Status = STATUS_INVALID_PARAMETER;
+            goto Quit;
+        }
+
+        /*
+         * 2. If we use control mode flags without ENABLE_EXTENDED_FLAGS,
+         *    then consider the flags invalid.
+         *
+        if ( (ConsoleMode & CONSOLE_VALID_CONTROL_MODES) &&
+             (ConsoleMode & ENABLE_EXTENDED_FLAGS) == 0 )
+        {
+            Status = STATUS_INVALID_PARAMETER;
+            goto Quit;
+        }
+        */
+
+        /*
+         * 3. Now we can continue.
+         */
+        if (ConsoleMode & CONSOLE_VALID_CONTROL_MODES)
+        {
+            Console->QuickEdit  = !!(ConsoleMode & ENABLE_QUICK_EDIT_MODE);
+            Console->InsertMode = !!(ConsoleMode & ENABLE_INSERT_MODE);
+        }
+        InputBuffer->Mode = (ConsoleMode & CONSOLE_VALID_INPUT_MODES);
     }
-    else if (CONIO_SCREEN_BUFFER_MAGIC == Buff->Header.Type)
+    else if (SCREEN_BUFFER == Object->Type)
     {
-        ConsoleModeRequest->ConsoleMode = Buff->Mode;
+        PCONSOLE_SCREEN_BUFFER Buffer = (PCONSOLE_SCREEN_BUFFER)Object;
+
+        DPRINT("SetConsoleMode(Output, %d)\n", ConsoleMode);
+
+        if (ConsoleMode & ~CONSOLE_VALID_OUTPUT_MODES)
+        {
+            Status = STATUS_INVALID_PARAMETER;
+        }
+        else
+        {
+            Buffer->Mode = (ConsoleMode & CONSOLE_VALID_OUTPUT_MODES);
+        }
     }
     else
     {
         Status = STATUS_INVALID_HANDLE;
     }
 
-    Win32CsrUnlockObject((Object_t *)Console);
+Quit:
+    ConSrvReleaseObject(Object, TRUE);
     return Status;
 }
 
-CSR_API(SrvSetConsoleTitle)
+CSR_API(SrvGetConsoleTitle)
 {
     NTSTATUS Status;
     PCONSOLE_GETSETCONSOLETITLE TitleRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.TitleRequest;
     // PCSR_PROCESS Process = CsrGetClientThread()->Process;
     PCONSOLE Console;
-    PWCHAR Buffer;
-
-    DPRINT("SrvSetConsoleTitle\n");
+    DWORD Length;
 
     if (!CsrValidateMessageBuffer(ApiMessage,
                                   (PVOID)&TitleRequest->Title,
@@ -738,47 +1146,34 @@ CSR_API(SrvSetConsoleTitle)
         return STATUS_INVALID_PARAMETER;
     }
 
-    Status = ConioConsoleFromProcessData(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console);
-    if(NT_SUCCESS(Status))
+    Status = ConSrvGetConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console, TRUE);
+    if (!NT_SUCCESS(Status))
     {
-        Buffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, TitleRequest->Length);
-        if (Buffer)
-        {
-            /* Copy title to console */
-            RtlFreeUnicodeString(&Console->Title);
-            Console->Title.Buffer = Buffer;
-            Console->Title.Length = Console->Title.MaximumLength = TitleRequest->Length;
-            memcpy(Console->Title.Buffer, TitleRequest->Title, Console->Title.Length);
-
-            if (!ConioChangeTitle(Console))
-            {
-                Status = STATUS_UNSUCCESSFUL;
-            }
-            else
-            {
-                Status = STATUS_SUCCESS;
-            }
-        }
-        else
-        {
-            Status = STATUS_NO_MEMORY;
-        }
+        DPRINT1("Can't get console\n");
+        return Status;
+    }
 
-        ConioUnlockConsole(Console);
+    /* Copy title of the console to the user title buffer */
+    if (TitleRequest->Length >= sizeof(WCHAR))
+    {
+        Length = min(TitleRequest->Length - sizeof(WCHAR), Console->Title.Length);
+        memcpy(TitleRequest->Title, Console->Title.Buffer, Length);
+        TitleRequest->Title[Length / sizeof(WCHAR)] = L'\0';
     }
 
-    return Status;
+    TitleRequest->Length = Console->Title.Length;
+
+    ConSrvReleaseConsole(Console, TRUE);
+    return STATUS_SUCCESS;
 }
 
-CSR_API(SrvGetConsoleTitle)
+CSR_API(SrvSetConsoleTitle)
 {
     NTSTATUS Status;
     PCONSOLE_GETSETCONSOLETITLE TitleRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.TitleRequest;
     // PCSR_PROCESS Process = CsrGetClientThread()->Process;
     PCONSOLE Console;
-    DWORD Length;
-
-    DPRINT("SrvGetConsoleTitle\n");
+    PWCHAR Buffer;
 
     if (!CsrValidateMessageBuffer(ApiMessage,
                                   (PVOID)&TitleRequest->Title,
@@ -788,25 +1183,39 @@ CSR_API(SrvGetConsoleTitle)
         return STATUS_INVALID_PARAMETER;
     }
 
-    Status = ConioConsoleFromProcessData(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console);
+    Status = ConSrvGetConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console, TRUE);
     if (!NT_SUCCESS(Status))
     {
         DPRINT1("Can't get console\n");
         return Status;
     }
 
-    /* Copy title of the console to the user title buffer */
-    if (TitleRequest->Length >= sizeof(WCHAR))
+    /* Allocate a new buffer to hold the new title (NULL-terminated) */
+    Buffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, TitleRequest->Length + sizeof(WCHAR));
+    if (Buffer)
     {
-        Length = min(TitleRequest->Length - sizeof(WCHAR), Console->Title.Length);
-        memcpy(TitleRequest->Title, Console->Title.Buffer, Length);
-        TitleRequest->Title[Length / sizeof(WCHAR)] = L'\0';
-    }
+        /* Free the old title */
+        RtlFreeUnicodeString(&Console->Title);
 
-    TitleRequest->Length = Console->Title.Length;
+        /* Copy title to console */
+        Console->Title.Buffer = Buffer;
+        Console->Title.Length = TitleRequest->Length;
+        Console->Title.MaximumLength = Console->Title.Length + sizeof(WCHAR);
+        RtlCopyMemory(Console->Title.Buffer,
+                      TitleRequest->Title,
+                      Console->Title.Length);
+        Console->Title.Buffer[Console->Title.Length / sizeof(WCHAR)] = L'\0';
+
+        ConioChangeTitle(Console);
+        Status = STATUS_SUCCESS;
+    }
+    else
+    {
+        Status = STATUS_NO_MEMORY;
+    }
 
-    ConioUnlockConsole(Console);
-    return STATUS_SUCCESS;
+    ConSrvReleaseConsole(Console, TRUE);
+    return Status;
 }
 
 /**********************************************************************
@@ -824,7 +1233,7 @@ CSR_API(SrvGetConsoleTitle)
  *      with NT's, but values are not.
  */
 static NTSTATUS FASTCALL
-SetConsoleHardwareState(PCONSOLE Console, DWORD ConsoleHwState)
+SetConsoleHardwareState(PCONSOLE Console, ULONG ConsoleHwState)
 {
     DPRINT1("Console Hardware State: %d\n", ConsoleHwState);
 
@@ -848,24 +1257,24 @@ CSR_API(SrvGetConsoleHardwareState)
 {
     NTSTATUS Status;
     PCONSOLE_GETSETHWSTATE HardwareStateRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.HardwareStateRequest;
+    PCONSOLE_SCREEN_BUFFER Buff;
     PCONSOLE Console;
 
-    DPRINT("SrvGetConsoleHardwareState\n");
-
-    Status = ConioLockConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process),
-                              HardwareStateRequest->OutputHandle,
-                              &Console,
-                              GENERIC_READ);
+    Status = ConSrvGetScreenBuffer(ConsoleGetPerProcessData(CsrGetClientThread()->Process),
+                                  HardwareStateRequest->OutputHandle,
+                                  &Buff,
+                                  GENERIC_READ,
+                                  TRUE);
     if (!NT_SUCCESS(Status))
     {
         DPRINT1("Failed to get console handle in SrvGetConsoleHardwareState\n");
         return Status;
     }
 
+    Console = Buff->Header.Console;
     HardwareStateRequest->State = Console->HardwareState;
 
-    ConioUnlockConsole(Console);
-
+    ConSrvReleaseScreenBuffer(Buff, TRUE);
     return Status;
 }
 
@@ -873,14 +1282,14 @@ CSR_API(SrvSetConsoleHardwareState)
 {
     NTSTATUS Status;
     PCONSOLE_GETSETHWSTATE HardwareStateRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.HardwareStateRequest;
+    PCONSOLE_SCREEN_BUFFER Buff;
     PCONSOLE Console;
 
-    DPRINT("SrvSetConsoleHardwareState\n");
-
-    Status = ConioLockConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process),
-                              HardwareStateRequest->OutputHandle,
-                              &Console,
-                              GENERIC_READ);
+    Status = ConSrvGetScreenBuffer(ConsoleGetPerProcessData(CsrGetClientThread()->Process),
+                                  HardwareStateRequest->OutputHandle,
+                                  &Buff,
+                                  GENERIC_WRITE,
+                                  TRUE);
     if (!NT_SUCCESS(Status))
     {
         DPRINT1("Failed to get console handle in SrvSetConsoleHardwareState\n");
@@ -888,10 +1297,71 @@ CSR_API(SrvSetConsoleHardwareState)
     }
 
     DPRINT("Setting console hardware state.\n");
+    Console = Buff->Header.Console;
     Status = SetConsoleHardwareState(Console, HardwareStateRequest->State);
 
-    ConioUnlockConsole(Console);
+    ConSrvReleaseScreenBuffer(Buff, TRUE);
+    return Status;
+}
+
+CSR_API(SrvGetConsoleDisplayMode)
+{
+    NTSTATUS Status;
+    PCONSOLE_GETDISPLAYMODE GetDisplayModeRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.GetDisplayModeRequest;
+    PCONSOLE Console;
+    ULONG DisplayMode = 0;
+
+    Status = ConSrvGetConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process),
+                              &Console, TRUE);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT1("Failed to get console handle in SrvGetConsoleDisplayMode\n");
+        return Status;
+    }
+
+    if (Console->ActiveBuffer->DisplayMode & CONSOLE_FULLSCREEN_MODE)
+        DisplayMode |= CONSOLE_FULLSCREEN_HARDWARE; // CONSOLE_FULLSCREEN
+    else if (Console->ActiveBuffer->DisplayMode & CONSOLE_WINDOWED_MODE)
+        DisplayMode |= CONSOLE_WINDOWED;
+
+    GetDisplayModeRequest->DisplayMode = DisplayMode;
+    Status = STATUS_SUCCESS;
+
+    ConSrvReleaseConsole(Console, TRUE);
+    return Status;
+}
+
+CSR_API(SrvSetConsoleDisplayMode)
+{
+    NTSTATUS Status;
+    PCONSOLE_SETDISPLAYMODE SetDisplayModeRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.SetDisplayModeRequest;
+    PCONSOLE_SCREEN_BUFFER Buff;
+
+    Status = ConSrvGetScreenBuffer(ConsoleGetPerProcessData(CsrGetClientThread()->Process),
+                                   SetDisplayModeRequest->OutputHandle,
+                                   &Buff,
+                                   GENERIC_WRITE,
+                                   TRUE);
+    if (!NT_SUCCESS(Status))
+    {
+        DPRINT1("Failed to get console handle in SrvSetConsoleDisplayMode\n");
+        return Status;
+    }
+
+    if (SetDisplayModeRequest->DisplayMode & ~(CONSOLE_FULLSCREEN_MODE | CONSOLE_WINDOWED_MODE))
+    {
+        Status = STATUS_INVALID_PARAMETER;
+    }
+    else
+    {
+        Buff->DisplayMode = SetDisplayModeRequest->DisplayMode;
+        // TODO: Change the display mode
+        SetDisplayModeRequest->NewSBDim = Buff->ScreenBufferSize;
+
+        Status = STATUS_SUCCESS;
+    }
 
+    ConSrvReleaseScreenBuffer(Buff, TRUE);
     return Status;
 }
 
@@ -901,13 +1371,11 @@ CSR_API(SrvGetConsoleWindow)
     PCONSOLE_GETWINDOW GetWindowRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.GetWindowRequest;
     PCONSOLE Console;
 
-    DPRINT("SrvGetConsoleWindow\n");
-
-    Status = ConioConsoleFromProcessData(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console);
+    Status = ConSrvGetConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console, TRUE);
     if (!NT_SUCCESS(Status)) return Status;
 
-    GetWindowRequest->WindowHandle = Console->hWindow;
-    ConioUnlockConsole(Console);
+    GetWindowRequest->WindowHandle = ConioGetConsoleWindowHandle(Console);
+    ConSrvReleaseConsole(Console, TRUE);
 
     return STATUS_SUCCESS;
 }
@@ -918,16 +1386,14 @@ CSR_API(SrvSetConsoleIcon)
     PCONSOLE_SETICON SetIconRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.SetIconRequest;
     PCONSOLE Console;
 
-    DPRINT("SrvSetConsoleIcon\n");
-
-    Status = ConioConsoleFromProcessData(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console);
+    Status = ConSrvGetConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console, TRUE);
     if (!NT_SUCCESS(Status)) return Status;
 
     Status = (ConioChangeIcon(Console, SetIconRequest->WindowIcon)
                 ? STATUS_SUCCESS
                 : STATUS_UNSUCCESSFUL);
 
-    ConioUnlockConsole(Console);
+    ConSrvReleaseConsole(Console, TRUE);
 
     return Status;
 }
@@ -941,12 +1407,12 @@ CSR_API(SrvGetConsoleCP)
     DPRINT("SrvGetConsoleCP, getting %s Code Page\n",
             ConsoleCPRequest->InputCP ? "Input" : "Output");
 
-    Status = ConioConsoleFromProcessData(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console);
+    Status = ConSrvGetConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console, TRUE);
     if (!NT_SUCCESS(Status)) return Status;
 
     ConsoleCPRequest->CodePage = (ConsoleCPRequest->InputCP ? Console->CodePage
                                                             : Console->OutputCodePage);
-    ConioUnlockConsole(Console);
+    ConSrvReleaseConsole(Console, TRUE);
     return STATUS_SUCCESS;
 }
 
@@ -959,7 +1425,7 @@ CSR_API(SrvSetConsoleCP)
     DPRINT("SrvSetConsoleCP, setting %s Code Page\n",
             ConsoleCPRequest->InputCP ? "Input" : "Output");
 
-    Status = ConioConsoleFromProcessData(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console);
+    Status = ConSrvGetConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console, TRUE);
     if (!NT_SUCCESS(Status)) return Status;
 
     if (IsValidCodePage(ConsoleCPRequest->CodePage))
@@ -969,11 +1435,11 @@ CSR_API(SrvSetConsoleCP)
         else
             Console->OutputCodePage = ConsoleCPRequest->CodePage;
 
-        ConioUnlockConsole(Console);
+        ConSrvReleaseConsole(Console, TRUE);
         return STATUS_SUCCESS;
     }
 
-    ConioUnlockConsole(Console);
+    ConSrvReleaseConsole(Console, TRUE);
     return STATUS_INVALID_PARAMETER;
 }
 
@@ -988,8 +1454,6 @@ CSR_API(SrvGetConsoleProcessList)
     PLIST_ENTRY current_entry;
     ULONG nItems = 0;
 
-    DPRINT("SrvGetConsoleProcessList\n");
-
     if (!CsrValidateMessageBuffer(ApiMessage,
                                   (PVOID)&GetProcessListRequest->pProcessIds,
                                   GetProcessListRequest->nMaxIds,
@@ -1000,7 +1464,7 @@ CSR_API(SrvGetConsoleProcessList)
 
     Buffer = GetProcessListRequest->pProcessIds;
 
-    Status = ConioConsoleFromProcessData(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console);
+    Status = ConSrvGetConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console, TRUE);
     if (!NT_SUCCESS(Status)) return Status;
 
     for (current_entry = Console->ProcessList.Flink;
@@ -1014,7 +1478,7 @@ CSR_API(SrvGetConsoleProcessList)
         }
     }
 
-    ConioUnlockConsole(Console);
+    ConSrvReleaseConsole(Console, TRUE);
 
     GetProcessListRequest->nProcessIdsTotal = nItems;
     return STATUS_SUCCESS;
@@ -1025,29 +1489,15 @@ CSR_API(SrvGenerateConsoleCtrlEvent)
     NTSTATUS Status;
     PCONSOLE_GENERATECTRLEVENT GenerateCtrlEventRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.GenerateCtrlEventRequest;
     PCONSOLE Console;
-    PCONSOLE_PROCESS_DATA current;
-    PLIST_ENTRY current_entry;
-    DWORD Group;
 
-    Status = ConioConsoleFromProcessData(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console);
+    Status = ConSrvGetConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console, TRUE);
     if (!NT_SUCCESS(Status)) return Status;
 
-    Group = GenerateCtrlEventRequest->ProcessGroup;
-    Status = STATUS_INVALID_PARAMETER;
-    for (current_entry  = Console->ProcessList.Flink;
-         current_entry != &Console->ProcessList;
-         current_entry  = current_entry->Flink)
-    {
-        current = CONTAINING_RECORD(current_entry, CONSOLE_PROCESS_DATA, ConsoleLink);
-        if (Group == 0 || current->Process->ProcessGroupId == Group)
-        {
-            ConioConsoleCtrlEvent(GenerateCtrlEventRequest->Event, current);
-            Status = STATUS_SUCCESS;
-        }
-    }
-
-    ConioUnlockConsole(Console);
+    Status = ConSrvConsoleProcessCtrlEvent(Console,
+                                           GenerateCtrlEventRequest->ProcessGroup,
+                                           GenerateCtrlEventRequest->Event);
 
+    ConSrvReleaseConsole(Console, TRUE);
     return Status;
 }
 
@@ -1057,13 +1507,13 @@ CSR_API(SrvGetConsoleSelectionInfo)
     PCONSOLE_GETSELECTIONINFO GetSelectionInfoRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.GetSelectionInfoRequest;
     PCONSOLE Console;
 
-    Status = ConioConsoleFromProcessData(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console);
+    Status = ConSrvGetConsole(ConsoleGetPerProcessData(CsrGetClientThread()->Process), &Console, TRUE);
     if (NT_SUCCESS(Status))
     {
         memset(&GetSelectionInfoRequest->Info, 0, sizeof(CONSOLE_SELECTION_INFO));
         if (Console->Selection.dwFlags != 0)
             GetSelectionInfoRequest->Info = Console->Selection;
-        ConioUnlockConsole(Console);
+        ConSrvReleaseConsole(Console, TRUE);
     }
 
     return Status;