diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4af0907d48..6a5ab483d9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -373,10 +373,12 @@ set (USE_RAPIDJSON OFF CACHE BOOL "${USE_RAPIDJSON_DESCR}")
 set (USE_TBB       OFF CACHE BOOL "${USE_TBB_DESCR}")
 set (USE_EIGEN     OFF CACHE BOOL "${USE_EIGEN_DESCR}")
 
-if (APPLE)
-  set (USE_GLX OFF CACHE BOOL "${USE_GLX_DESCR}")
+if (WIN32 OR ANDROID OR IOS OR EMSCRIPTEN)
+  # no Xlib
+elseif (APPLE)
+  set (USE_XLIB OFF CACHE BOOL "${USE_XLIB_DESCR}")
 else()
-  set (USE_GLX OFF)
+  set (USE_XLIB ON  CACHE BOOL "${USE_XLIB_DESCR}")
 endif()
 
 if (WIN32)
@@ -503,6 +505,7 @@ endif()
 OCCT_IS_PRODUCT_REQUIRED (CSF_FreeImagePlus CAN_USE_FREEIMAGE)
 OCCT_IS_PRODUCT_REQUIRED (CSF_TclLibs USE_TCL)
 OCCT_IS_PRODUCT_REQUIRED (CSF_TclTkLibs CAN_USE_TK)
+OCCT_IS_PRODUCT_REQUIRED (CSF_XwLibs CAN_USE_XLIB)
 OCCT_IS_PRODUCT_REQUIRED (CSF_FREETYPE CAN_USE_FREETYPE)
 OCCT_IS_PRODUCT_REQUIRED (CSF_OpenGlLibs CAN_USE_OPENGL)
 OCCT_IS_PRODUCT_REQUIRED (CSF_OpenGlesLibs CAN_USE_GLES2)
@@ -537,6 +540,19 @@ else()
   OCCT_CHECK_AND_UNSET ("INSTALL_TK")
 endif()
 
+# Xlib
+if (CAN_USE_XLIB)
+  if (USE_XLIB)
+    message (STATUS "Info: Xlib is used by OCCT")
+    add_definitions (-DHAVE_XLIB)
+    if (APPLE)
+      OCCT_INCLUDE_CMAKE_FILE ("adm/cmake/glx")
+    endif()
+  endif()
+else()
+  OCCT_CHECK_AND_UNSET ("USE_XLIB")
+endif()
+
 # FreeType
 if (CAN_USE_FREETYPE)
   if (USE_FREETYPE)
@@ -571,12 +587,6 @@ else()
   endif()
 endif()
 
-# GLX
-if (USE_GLX)
-  add_definitions (-DMACOSX_USE_GLX)
-  OCCT_INCLUDE_CMAKE_FILE ("adm/cmake/glx")
-endif()
-
 # FREEIMAGE
 if (CAN_USE_FREEIMAGE)
   if (USE_FREEIMAGE)
@@ -1232,7 +1242,7 @@ if (WIN32)
   set (SET_OpenCASCADE_WITH_D3D "set (OpenCASCADE_WITH_D3D       ${USE_D3D})")
 endif()
 if (APPLE)
-  set (SET_OpenCASCADE_WITH_GLX "set (OpenCASCADE_WITH_GLX       ${USE_GLX})")
+  set (SET_OpenCASCADE_WITH_GLX "set (OpenCASCADE_WITH_GLX       ${USE_XLIB})")
 endif()
 
 # Configure and install cmake config file
diff --git a/adm/UDLIST b/adm/UDLIST
index 3f3993a157..5a1820665a 100644
--- a/adm/UDLIST
+++ b/adm/UDLIST
@@ -197,7 +197,6 @@ t TKPrim
 t TKShHealing
 t TKTopAlgo
 t TKXMesh
-n InterfaceGraphic
 n AIS
 n Aspect
 n DsgPrs
diff --git a/adm/cmake/occt_csf.cmake b/adm/cmake/occt_csf.cmake
index 5b96a61d93..0938850c69 100644
--- a/adm/cmake/occt_csf.cmake
+++ b/adm/cmake/occt_csf.cmake
@@ -109,7 +109,7 @@ else()
       find_library (OpenGlesLibs_LIB NAMES OpenGLES)
       set (CSF_OpenGlesLibs ${OpenGlesLibs_LIB})
       OCCT_CHECK_AND_UNSET (OpenGlesLibs_LIB)
-    elseif (USE_GLX)
+    elseif (USE_XLIB)
       set (CSF_OpenGlLibs GL)
       set (CSF_XwLibs     "X11 Xext Xmu Xi")
     else()
@@ -124,9 +124,13 @@ else()
     set (CSF_androidlog  "log")
   elseif (UNIX)
     set (CSF_ThreadLibs  "pthread rt stdc++")
-    set (CSF_OpenGlLibs   "GL")
+    if (USE_XLIB)
+      set (CSF_OpenGlLibs "GL")
+      set (CSF_XwLibs     "X11 Xext Xmu Xi")
+    else()
+      set (CSF_OpenGlLibs "GL EGL")
+    endif()
     set (CSF_OpenGlesLibs "EGL GLESv2")
-    set (CSF_XwLibs      "X11 Xext Xmu Xi")
     set (CSF_dl          "dl")
     if (USE_FREETYPE)
       set (CSF_fontconfig "fontconfig")
diff --git a/adm/cmake/vardescr.cmake b/adm/cmake/vardescr.cmake
index 2d07950501..9dffc9f4b0 100644
--- a/adm/cmake/vardescr.cmake
+++ b/adm/cmake/vardescr.cmake
@@ -196,7 +196,7 @@ ToolKit, the technology of Kitware Inc intended for general-purpose scientific
 visualization. OCCT comes with a bridge between CAD data representation and
 VTK by means of its dedicated VIS component (VTK Integration Services).")
 
-set (USE_GLX_DESCR "Indicates whether X11 OpenGl on OSX is used or not")
+set (USE_XLIB_DESCR "Indicates whether X11 is used or not")
 
 set (USE_D3D_DESCR "Indicates whether optional Direct3D wrapper in OCCT visualization module should be build or not")
 
diff --git a/adm/genconf.tcl b/adm/genconf.tcl
index bc8a09ec2b..d7ab6c8b76 100644
--- a/adm/genconf.tcl
+++ b/adm/genconf.tcl
@@ -496,8 +496,8 @@ ttk::label    .myFrame.myChecks.myFFmpegLbl     -text "Use FFmpeg"
 checkbutton   .myFrame.myChecks.myRapidJsonCheck -offvalue "false" -onvalue "true" -variable HAVE_RAPIDJSON -command wokdep:gui:UpdateList
 ttk::label    .myFrame.myChecks.myRapidJsonLbl   -text "Use RapidJSON"
 
-checkbutton   .myFrame.myChecks.myMacGLXCheck   -offvalue "false" -onvalue "true" -variable MACOSX_USE_GLX
-ttk::label    .myFrame.myChecks.myMacGLXLbl     -text "Use X11 for windows drawing"
+checkbutton   .myFrame.myChecks.myXLibCheck     -offvalue "false" -onvalue "true" -variable HAVE_XLIB
+ttk::label    .myFrame.myChecks.myXLibLbl       -text "Use X11 for windows drawing"
 ttk::label    .myFrame.myChecks.myVtkLbl        -text "Use VTK"
 checkbutton   .myFrame.myChecks.myVtkCheck      -offvalue "false" -onvalue "true" -variable HAVE_VTK       -command wokdep:gui:UpdateList
 
@@ -632,9 +632,9 @@ grid .myFrame.myChecks.myTbbLbl        -row $aCheckRowIter -column 3 -sticky w
 if { "$::tcl_platform(platform)" == "windows" } {
   grid .myFrame.myChecks.myD3dCheck    -row $aCheckRowIter -column 4 -sticky e
   grid .myFrame.myChecks.myD3dLbl      -row $aCheckRowIter -column 5 -sticky w
-} elseif { "$::tcl_platform(os)" == "Darwin" } {
-  grid .myFrame.myChecks.myMacGLXCheck -row $aCheckRowIter -column 4 -sticky e
-  grid .myFrame.myChecks.myMacGLXLbl   -row $aCheckRowIter -column 5 -sticky w
+} else {
+  grid .myFrame.myChecks.myXLibCheck   -row $aCheckRowIter -column 4 -sticky e
+  grid .myFrame.myChecks.myXLibLbl     -row $aCheckRowIter -column 5 -sticky w
 }
 grid .myFrame.myChecks.myLzmaCheck     -row $aCheckRowIter -column 6 -sticky e
 grid .myFrame.myChecks.myLzmaLbl       -row $aCheckRowIter -column 7 -sticky w
diff --git a/adm/genconfdeps.tcl b/adm/genconfdeps.tcl
index 8dc5925019..b53f900cd4 100644
--- a/adm/genconfdeps.tcl
+++ b/adm/genconfdeps.tcl
@@ -68,10 +68,11 @@ if { [info exists ::env(SHORTCUT_HEADERS)] } {
 }
 
 # fetch environment variables (e.g. set by custom.sh or custom.bat) and set them as tcl variables with the same name
-set THE_ENV_VARIABLES {HAVE_TK HAVE_FREETYPE HAVE_FREEIMAGE HAVE_FFMPEG HAVE_TBB HAVE_GLES2 HAVE_D3D HAVE_VTK HAVE_ZLIB HAVE_LIBLZMA HAVE_E57 HAVE_RAPIDJSON HAVE_OPENVR HAVE_OPENCL CHECK_QT4 CHECK_JDK MACOSX_USE_GLX HAVE_RelWithDebInfo BUILD_Inspector}
+set THE_ENV_VARIABLES {HAVE_TK HAVE_FREETYPE HAVE_FREEIMAGE HAVE_FFMPEG HAVE_TBB HAVE_GLES2 HAVE_D3D HAVE_VTK HAVE_ZLIB HAVE_LIBLZMA HAVE_E57 HAVE_RAPIDJSON HAVE_OPENVR HAVE_OPENCL CHECK_QT4 CHECK_JDK HAVE_XLIB HAVE_RelWithDebInfo BUILD_Inspector}
 foreach anEnvIter $THE_ENV_VARIABLES { set ${anEnvIter} "false" }
 set HAVE_TK       "true"
 set HAVE_FREETYPE "true"
+if { "$tcl_platform(os)" != "Darwin" } { set HAVE_XLIB "true" }
 foreach anEnvIter $THE_ENV_VARIABLES {
   if { [info exists ::env(${anEnvIter})] } {
     set ${anEnvIter} "$::env(${anEnvIter})"
@@ -80,12 +81,12 @@ foreach anEnvIter $THE_ENV_VARIABLES {
 # do not export platform-specific variables
 if { "$::tcl_platform(os)" == "Darwin" } {
   set HAVE_GLES2 ""
-} else {
-  set MACOSX_USE_GLX ""
 }
 if { "$tcl_platform(platform)" != "windows" } {
   set HAVE_D3D ""
   set HAVE_RelWithDebInfo ""
+} else {
+  set HAVE_XLIB ""
 }
 foreach anEnvIter {ARCH VCVER VCVARS PRJFMT } {
   if { [info exists ::env(${anEnvIter})] } {
@@ -1195,7 +1196,7 @@ proc wokdep:SearchX11 {theErrInc theErrLib32 theErrLib64 theErrBin32 theErrBin64
   upvar $theErrBin64 anErrBin64
 
   set isFound "true"
-  if { "$::tcl_platform(platform)" == "windows" || ( "$::tcl_platform(os)" == "Darwin" && "$::MACOSX_USE_GLX" != "true" ) } {
+  if { "$::tcl_platform(platform)" == "windows" || ( "$::tcl_platform(os)" == "Darwin" && "$::HAVE_XLIB" != "true" ) } {
     return "$isFound"
   }
 
diff --git a/adm/genproj.tcl b/adm/genproj.tcl
index f12905ff32..ab611805eb 100644
--- a/adm/genproj.tcl
+++ b/adm/genproj.tcl
@@ -1491,7 +1491,11 @@ proc osutils:csfList { theOS theCsfLibsMap theCsfFrmsMap theRelease} {
     }
   } else {
     set aLibsMap(CSF_dl)           "dl"
-    set aLibsMap(CSF_OpenGlLibs)   "GL"
+    if { "$::HAVE_XLIB" == "true" } {
+      set aLibsMap(CSF_OpenGlLibs) "GL"
+    } else {
+      set aLibsMap(CSF_OpenGlLibs) "GL EGL"
+    }
     set aLibsMap(CSF_OpenGlesLibs) "EGL GLESv2"
     if { "$theOS" == "mac" || "$theOS" == "ios" } {
       set aLibsMap(CSF_objc)         "objc"
@@ -1525,8 +1529,10 @@ proc osutils:csfList { theOS theCsfLibsMap theCsfFrmsMap theRelease} {
         if { "$::HAVE_TK" == "true" } {
           set aLibsMap(CSF_TclTkLibs) "tk8.6"
         }
-        set aLibsMap(CSF_XwLibs)     "X11 Xext Xmu Xi"
-        set aLibsMap(CSF_MotifLibs)  "X11"
+        if { "$::HAVE_XLIB" == "true" } {
+          set aLibsMap(CSF_XwLibs)     "X11 Xext Xmu Xi"
+          set aLibsMap(CSF_MotifLibs)  "X11"
+        }
       }
     }
   }
diff --git a/adm/qmake/OccToolkit.pri b/adm/qmake/OccToolkit.pri
index e5c5671549..c4b11d9d66 100644
--- a/adm/qmake/OccToolkit.pri
+++ b/adm/qmake/OccToolkit.pri
@@ -59,11 +59,15 @@ win32 {
 } else {
   CSF_dl = -ldl
   CSF_ThreadLibs = -lpthread -lrt
-  CSF_OpenGlLibs = -lGL
   CSF_OpenGlesLibs = -lEGL -lGLESv2
-  CSF_TclTkLibs  = -lX11 -ltk8.6
-  CSF_XwLibs     = -lX11 -lXext -lXmu -lXi
-  CSF_MotifLibs  = -lX11
+  CSF_TclTkLibs  = -ltk8.6
+  HAVE_XLIB {
+    CSF_OpenGlLibs = -lGL
+    CSF_XwLibs = -lX11 -lXext -lXmu -lXi
+    CSF_MotifLibs  = -lX11
+  } else {
+    CSF_OpenGlLibs = -lGL -lEGL
+  }
   HAVE_FREETYPE  { CSF_fontconfig = -lfontconfig }
 }
 
diff --git a/adm/scripts/wasm_build.bat b/adm/scripts/wasm_build.bat
index 6581b7eaef..af9bfcd14c 100644
--- a/adm/scripts/wasm_build.bat
+++ b/adm/scripts/wasm_build.bat
@@ -13,6 +13,7 @@ rem Paths to 3rd-party tools and libraries
 set "aCmakeBin="
 set "aFreeType="
 set "aRapidJson="
+set "aTcl="
 
 rem Build stages to perform
 set "toCMake=1"
@@ -30,6 +31,7 @@ set "BUILD_ModelingAlgorithms=ON"
 set "BUILD_Visualization=ON"
 set "BUILD_ApplicationFramework=ON"
 set "BUILD_DataExchange=ON"
+set "BUILD_Draw=OFF"
 
 rem Optional 3rd-party libraries to enable
 set "USE_RAPIDJSON=OFF"
@@ -162,11 +164,15 @@ if ["%toCMake%"] == ["1"] (
  -D BUILD_MODULE_Visualization:BOOL="%BUILD_Visualization%" ^
  -D BUILD_MODULE_ApplicationFramework:BOOL="%BUILD_ApplicationFramework%" ^
  -D BUILD_MODULE_DataExchange:BOOL="%BUILD_DataExchange%" ^
- -D BUILD_MODULE_Draw:BOOL="OFF" ^
+ -D BUILD_MODULE_Draw:BOOL="%BUILD_Draw%" ^
  -D BUILD_DOC_Overview:BOOL="OFF" ^
  -D USE_RAPIDJSON:BOOL="%USE_RAPIDJSON%" ^
  -D 3RDPARTY_RAPIDJSON_DIR:PATH="%aRapidJson%" ^
  -D 3RDPARTY_RAPIDJSON_INCLUDE_DIR:PATH="%aRapidJson%/include" ^
+ -D 3RDPARTY_TCL_DIR:PATH="%aTcl%" ^
+ -D 3RDPARTY_TCL_INCLUDE_DIR:PATH="%aTcl%/include" ^
+ -D 3RDPARTY_TCL_LIBRARY_DIR:PATH="%aTcl%/lib" ^
+ -D 3RDPARTY_TCL_LIBRARY:FILEPATH="%aTcl%/lib/libtcl.a" ^
  "%aCasSrc%"
 
   if errorlevel 1 (
diff --git a/adm/templates/env.sh b/adm/templates/env.sh
index 01cdab82f2..b0f29c0d08 100644
--- a/adm/templates/env.sh
+++ b/adm/templates/env.sh
@@ -3,6 +3,8 @@
 # go to the script directory
 aScriptPath=${BASH_SOURCE%/*}; if [ -d "${aScriptPath}" ]; then cd "$aScriptPath"; fi; aScriptPath="$PWD";
 
+aSystem=`uname -s`
+
 # Reset values
 export CASROOT="__CASROOT__"
 export CASDEB=""
@@ -20,7 +22,10 @@ export HAVE_LIBLZMA="false";
 export HAVE_RAPIDJSON="false";
 export HAVE_OPENVR="false";
 export HAVE_E57="false";
-export MACOSX_USE_GLX="false";
+export HAVE_XLIB="true";
+if [ "$aSystem" == "Darwin" ]; then
+  export HAVE_XLIB="false";
+fi
 export CSF_OPT_INC=""
 export CSF_OPT_LIB32=""
 export CSF_OPT_LIB64=""
@@ -60,7 +65,6 @@ else
   export ARCH="64";
 fi
 
-aSystem=`uname -s`
 if [ "$aSystem" == "Darwin" ]; then
   export WOKSTATION="mac";
   export ARCH="64";
@@ -113,8 +117,7 @@ if [ "$HAVE_LIBLZMA"   == "true" ]; then export CSF_OPT_CMPL="${CSF_OPT_CMPL} -D
 if [ "$HAVE_RAPIDJSON" == "true" ]; then export CSF_OPT_CMPL="${CSF_OPT_CMPL} -DHAVE_RAPIDJSON"; fi
 if [ "$HAVE_OPENVR"    == "true" ]; then export CSF_OPT_CMPL="${CSF_OPT_CMPL} -DHAVE_OPENVR"; fi
 if [ "$HAVE_E57"       == "true" ]; then export CSF_OPT_CMPL="${CSF_OPT_CMPL} -DHAVE_E57"; fi
-# Option to compile OCCT with X11 libs on Mac OS X
-if [ "$MACOSX_USE_GLX" == "true" ]; then export CSF_OPT_CMPL="${CSF_OPT_CMPL} -DMACOSX_USE_GLX"; fi
+if [ "$HAVE_XLIB"      == "true" ]; then export CSF_OPT_CMPL="${CSF_OPT_CMPL} -DHAVE_XLIB"; fi
 
 # To split string into array
 aDelimBack=$IFS
diff --git a/src/AIS/AIS_ViewController.hxx b/src/AIS/AIS_ViewController.hxx
index 747e8bf468..982f222235 100644
--- a/src/AIS/AIS_ViewController.hxx
+++ b/src/AIS/AIS_ViewController.hxx
@@ -424,14 +424,14 @@ public: //! @name resize events
 
   //! Handle focus event.
   //! Default implementation does nothing.
-  virtual void ProcessFocus (bool theIsActivated)
+  virtual void ProcessFocus (bool theIsActivated) Standard_OVERRIDE
   {
     (void )theIsActivated;
   }
 
   //! Handle window close event.
   //! Default implementation does nothing.
-  virtual void ProcessClose() {}
+  virtual void ProcessClose() Standard_OVERRIDE {}
 
 public:
 
diff --git a/src/Aspect/Aspect_DisplayConnection.cxx b/src/Aspect/Aspect_DisplayConnection.cxx
index 53a7d3a161..3cadc205ba 100755
--- a/src/Aspect/Aspect_DisplayConnection.cxx
+++ b/src/Aspect/Aspect_DisplayConnection.cxx
@@ -16,6 +16,12 @@
 #include <Aspect_DisplayConnectionDefinitionError.hxx>
 #include <OSD_Environment.hxx>
 
+#if defined(HAVE_XLIB)
+  #include <X11/Xlib.h>
+  #include <X11/Xutil.h>
+  #include <X11/Xatom.h>
+#endif
+
 IMPLEMENT_STANDARD_RTTIEXT(Aspect_DisplayConnection,Standard_Transient)
 
 // =======================================================================
@@ -24,7 +30,7 @@ IMPLEMENT_STANDARD_RTTIEXT(Aspect_DisplayConnection,Standard_Transient)
 // =======================================================================
 Aspect_DisplayConnection::Aspect_DisplayConnection()
 {
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__)
+#if defined(HAVE_XLIB)
   myDisplay = NULL;
   myDefVisualInfo = NULL;
   myDefFBConfig = NULL;
@@ -41,7 +47,7 @@ Aspect_DisplayConnection::Aspect_DisplayConnection()
 // =======================================================================
 Aspect_DisplayConnection::~Aspect_DisplayConnection()
 {
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__)
+#if defined(HAVE_XLIB)
   if (myDefVisualInfo != NULL)
   {
     XFree (myDefVisualInfo);
@@ -49,12 +55,11 @@ Aspect_DisplayConnection::~Aspect_DisplayConnection()
   if (myDisplay != NULL
    && myIsOwnDisplay)
   {
-    XCloseDisplay (myDisplay);
+    XCloseDisplay ((Display* )myDisplay);
   }
 #endif
 }
 
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__)
 // =======================================================================
 // function : Aspect_DisplayConnection
 // purpose  :
@@ -73,7 +78,7 @@ Aspect_DisplayConnection::Aspect_DisplayConnection (const TCollection_AsciiStrin
 // function : Aspect_DisplayConnection
 // purpose  :
 // =======================================================================
-Aspect_DisplayConnection::Aspect_DisplayConnection (Display* theDisplay)
+Aspect_DisplayConnection::Aspect_DisplayConnection (Aspect_XDisplay* theDisplay)
 : myDisplay (NULL),
   myDefVisualInfo (NULL),
   myDefFBConfig (NULL),
@@ -86,12 +91,14 @@ Aspect_DisplayConnection::Aspect_DisplayConnection (Display* theDisplay)
 // function : SetDefaultVisualInfo
 // purpose  :
 // =======================================================================
-void Aspect_DisplayConnection::SetDefaultVisualInfo (XVisualInfo* theVisual,
+void Aspect_DisplayConnection::SetDefaultVisualInfo (Aspect_XVisualInfo* theVisual,
                                                      Aspect_FBConfig theFBConfig)
 {
   if (myDefVisualInfo != NULL)
   {
+  #if defined(HAVE_XLIB)
     XFree (myDefVisualInfo);
+  #endif
   }
   myDefVisualInfo = theVisual;
   myDefFBConfig = theFBConfig;
@@ -101,17 +108,18 @@ void Aspect_DisplayConnection::SetDefaultVisualInfo (XVisualInfo* theVisual,
 // function : Init
 // purpose  :
 // =======================================================================
-void Aspect_DisplayConnection::Init (Display* theDisplay)
+void Aspect_DisplayConnection::Init (Aspect_XDisplay* theDisplay)
 {
+#if defined(HAVE_XLIB)
   if (myDisplay != NULL
    && myIsOwnDisplay)
   {
-    XCloseDisplay (myDisplay);
+    XCloseDisplay ((Display* )myDisplay);
   }
   myIsOwnDisplay = false;
   myAtoms.Clear();
 
-  myDisplay = theDisplay != NULL ? theDisplay : XOpenDisplay (myDisplayName.ToCString());
+  myDisplay = theDisplay != NULL ? theDisplay : (Aspect_XDisplay* )XOpenDisplay (myDisplayName.ToCString());
   if (myDisplay == NULL)
   {
     TCollection_AsciiString aMessage;
@@ -122,18 +130,10 @@ void Aspect_DisplayConnection::Init (Display* theDisplay)
   else
   {
     myIsOwnDisplay = theDisplay == NULL;
-    myAtoms.Bind (Aspect_XA_DELETE_WINDOW, XInternAtom(myDisplay, "WM_DELETE_WINDOW", False));
+    myAtoms.Bind (Aspect_XA_DELETE_WINDOW, (uint64_t )XInternAtom((Display* )myDisplay, "WM_DELETE_WINDOW", False));
   }
-}
-
-// =======================================================================
-// function : GetAtom
-// purpose  :
-// =======================================================================
-Atom Aspect_DisplayConnection::GetAtom (const Aspect_XAtom theAtom) const
-{
-  Atom anAtom = myAtoms.Find(theAtom);
-  return anAtom;
-}
-
+#else
+  myDisplay = theDisplay;
+  myIsOwnDisplay = theDisplay == NULL;
 #endif
+}
diff --git a/src/Aspect/Aspect_DisplayConnection.hxx b/src/Aspect/Aspect_DisplayConnection.hxx
index 2cfba3d422..5bde7a4b90 100755
--- a/src/Aspect/Aspect_DisplayConnection.hxx
+++ b/src/Aspect/Aspect_DisplayConnection.hxx
@@ -16,51 +16,52 @@
 
 #include <Standard_Transient.hxx>
 #include <Aspect_XAtom.hxx>
+#include <Aspect_FBConfig.hxx>
 
 #include <TCollection_AsciiString.hxx>
 #include <NCollection_DataMap.hxx>
 
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__)
-  #include <InterfaceGraphic.hxx>
-  #include <Aspect_FBConfig.hxx>
-#endif
+struct Aspect_XDisplay;
+struct Aspect_XVisualInfo;
 
 //! This class creates and provides connection with X server.
 //! Raises exception if can not connect to X server.
-//! On Windows and Mac OS X (in case when Cocoa used) platforms this class do nothing.
-//! WARRNING: Do not close display connection manualy!
-
+//! On Windows and Mac OS X (in case when Cocoa used) platforms this class does nothing.
+//! WARRNING: Do not close display connection manually!
 class Aspect_DisplayConnection : public Standard_Transient
 {
+  DEFINE_STANDARD_RTTIEXT(Aspect_DisplayConnection, Standard_Transient)
 public:
 
   //! Default constructor. Creates connection with display name taken from "DISPLAY" environment variable
   Standard_EXPORT Aspect_DisplayConnection();
 
   //! Destructor. Close opened connection.
-  Standard_EXPORT ~Aspect_DisplayConnection();
+  Standard_EXPORT virtual ~Aspect_DisplayConnection();
 
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__)
   //! Constructor. Creates connection with display specified in theDisplayName.
   //! Display name should be in format "hostname:number" or "hostname:number.screen_number", where:
   //! hostname      - Specifies the name of the host machine on which the display is physically attached.
   //! number        - Specifies the number of the display server on that host machine.
   //! screen_number - Specifies the screen to be used on that server. Optional variable.
-  Aspect_DisplayConnection (const TCollection_AsciiString& theDisplayName);
+  Standard_EXPORT Aspect_DisplayConnection (const TCollection_AsciiString& theDisplayName);
 
   //! Constructor wrapping existing Display instance.
   //! WARNING! it is a responsibility of application to keep this pointer
   //! valid while Aspect_DisplayConnection is alive and to close Display when it is no more needed.
-  Aspect_DisplayConnection (Display* theDisplay);
+  Standard_EXPORT Aspect_DisplayConnection (Aspect_XDisplay* theDisplay);
 
   //! @return pointer to Display structure that serves as the connection to the X server.
-  Display* GetDisplay() { return myDisplay; }
+  Aspect_XDisplay* GetDisplayAspect() { return myDisplay; }
 
   //! @return TRUE if X Display has been allocated by this class
   Standard_Boolean IsOwnDisplay() const { return myIsOwnDisplay; }
 
   //! @return identifier(atom) for custom named property associated with windows that use current connection to X server.
-  Atom GetAtom (const Aspect_XAtom theAtom) const;
+  uint64_t GetAtom (const Aspect_XAtom theAtom) const
+  {
+    return myAtoms.Find (theAtom);
+  }
 
   //! @return display name for this connection.
   const TCollection_AsciiString& GetDisplayName() { return myDisplayName; }
@@ -71,27 +72,60 @@ public:
   //! to keep this pointer valid while Aspect_DisplayConnection is alive
   //! and to close Display when it is no more needed.
   //! @param theDisplay external pointer to allocated Display, or NULL if new connection should be created
-  void Init (Display* theDisplay);
+  Standard_EXPORT void Init (Aspect_XDisplay* theDisplay);
 
   //! Return default window visual or NULL when undefined.
-  XVisualInfo* GetDefaultVisualInfo() const { return myDefVisualInfo; }
+  Aspect_XVisualInfo* GetDefaultVisualInfo() const { return myDefVisualInfo; }
 
   //! @return native Window FB config (GLXFBConfig on Xlib)
   Aspect_FBConfig GetDefaultFBConfig() const { return myDefFBConfig; }
 
   //! Set default window visual; the visual will be deallocated using XFree().
-  Standard_EXPORT void SetDefaultVisualInfo (XVisualInfo* theVisual,
+  Standard_EXPORT void SetDefaultVisualInfo (Aspect_XVisualInfo* theVisual,
                                              Aspect_FBConfig theFBConfig);
 
+#ifdef X_PROTOCOL
+  //! Constructor wrapping existing Display instance.
+  //! WARNING! it is a responsibility of application to keep this pointer
+  //! valid while Aspect_DisplayConnection is alive and to close Display when it is no more needed.
+  Aspect_DisplayConnection (Display* theDisplay)
+  : Aspect_DisplayConnection ((Aspect_XDisplay* )theDisplay) {}
+
+  //! @return pointer to Display structure that serves as the connection to the X server.
+  Display* GetDisplay() { return (Display* )myDisplay; }
+
+  //! Return default window visual or NULL when undefined.
+  XVisualInfo* GetDefaultVisualInfoX() const { return (XVisualInfo* )myDefVisualInfo; }
+
+  //! Set default window visual; the visual will be deallocated using XFree().
+  void SetDefaultVisualInfo (XVisualInfo* theVisual,
+                             Aspect_FBConfig theFBConfig)
+  {
+    SetDefaultVisualInfo ((Aspect_XVisualInfo* )theVisual, theFBConfig);
+  }
+
+  //! @return identifier(atom) for custom named property associated with windows that use current connection to X server.
+  Atom GetAtomX (const Aspect_XAtom theAtom) const
+  {
+    return (Atom )GetAtom (theAtom);
+  }
+
+  //! Open connection with display specified in myDisplayName class field
+  //! or takes theDisplay parameter when it is not NULL.
+  void Init (Display* theDisplay)
+  {
+    Init ((Aspect_XDisplay* )theDisplay);
+  }
+#endif
+
 private:
 
-  Display*                 myDisplay;
-  XVisualInfo*             myDefVisualInfo;
+  Aspect_XDisplay*         myDisplay;
+  Aspect_XVisualInfo*      myDefVisualInfo;
   Aspect_FBConfig          myDefFBConfig;
-  NCollection_DataMap<Aspect_XAtom, Atom> myAtoms;
+  NCollection_DataMap<Aspect_XAtom, uint64_t> myAtoms;
   TCollection_AsciiString  myDisplayName;
   Standard_Boolean         myIsOwnDisplay;
-#endif
 
 private:
 
@@ -99,10 +133,6 @@ private:
   Aspect_DisplayConnection            (const Aspect_DisplayConnection& );
   Aspect_DisplayConnection& operator= (const Aspect_DisplayConnection& );
 
-public:
-
-  DEFINE_STANDARD_RTTIEXT(Aspect_DisplayConnection,Standard_Transient) // Type definition
-
 };
 
 DEFINE_STANDARD_HANDLE (Aspect_DisplayConnection, Standard_Transient)
diff --git a/src/Aspect/Aspect_FBConfig.hxx b/src/Aspect/Aspect_FBConfig.hxx
index bbed1e4e74..8330995724 100644
--- a/src/Aspect/Aspect_FBConfig.hxx
+++ b/src/Aspect/Aspect_FBConfig.hxx
@@ -14,11 +14,7 @@
 #ifndef _Aspect_FBConfig_HeaderFile
 #define _Aspect_FBConfig_HeaderFile
 
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__)
-  typedef struct __GLXFBConfigRec* GLXFBConfig;
-  typedef GLXFBConfig Aspect_FBConfig; // GLXFBConfig* under UNIX
-#else
-  typedef void* Aspect_FBConfig;       // unused on other systems
-#endif
+typedef struct __GLXFBConfigRec* GLXFBConfig;
+typedef GLXFBConfig Aspect_FBConfig;
 
 #endif // _Aspect_FBConfig_HeaderFile
diff --git a/src/Aspect/Aspect_RenderingContext.hxx b/src/Aspect/Aspect_RenderingContext.hxx
index 55b5e7c371..7eb0a65f83 100644
--- a/src/Aspect/Aspect_RenderingContext.hxx
+++ b/src/Aspect/Aspect_RenderingContext.hxx
@@ -22,7 +22,7 @@
 #ifndef _Aspect_RenderingContext_HeaderFile
 #define _Aspect_RenderingContext_HeaderFile
 
-#if defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#if defined(__APPLE__) && !defined(HAVE_XLIB)
   #import <TargetConditionals.h>
   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
     #ifdef __OBJC__
diff --git a/src/Aspect/Aspect_XWD.hxx b/src/Aspect/Aspect_XWD.hxx
index 7d248402d2..060547195b 100644
--- a/src/Aspect/Aspect_XWD.hxx
+++ b/src/Aspect/Aspect_XWD.hxx
@@ -14,7 +14,7 @@
 #ifndef __Aspect_WNTXWD_HXX
 # define __Aspect_WNTXWD_HXX
 
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__)
+#if !defined(_WIN32) && (!defined(__APPLE__) || defined(HAVE_XLIB)) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__)
 #  include <X11/XWDFile.h>
 # else
 
diff --git a/src/Draw/Draw_BasicCommands.cxx b/src/Draw/Draw_BasicCommands.cxx
index d1441dad5a..9c7d182a25 100644
--- a/src/Draw/Draw_BasicCommands.cxx
+++ b/src/Draw/Draw_BasicCommands.cxx
@@ -348,6 +348,11 @@ static Standard_Integer dversion(Draw_Interpretor& di, Standard_Integer, const c
 #else
   di << "Tk disabled\n";
 #endif
+#ifdef HAVE_XLIB
+  di << "Xlib enabled (HAVE_XLIB)\n";
+#elif !defined(_WIN32)
+  di << "Xlib disabled\n";
+#endif
 #ifdef HAVE_TBB
   di << "TBB enabled (HAVE_TBB)\n";
 #else 
diff --git a/src/Draw/Draw_View.cxx b/src/Draw/Draw_View.cxx
index 6739118543..1f12912728 100644
--- a/src/Draw/Draw_View.cxx
+++ b/src/Draw/Draw_View.cxx
@@ -20,42 +20,17 @@
 //function : Draw_View
 //purpose  : Constructor
 //=======================================================================
-Draw_View::Draw_View(Standard_Integer theId,
-                     Draw_Viewer*     theViewer,
-                     Standard_Integer theX,
-                     Standard_Integer theY,
-                     Standard_Integer theWidth,
-                     Standard_Integer theHeight)
-: Draw_Window("Win", theX, theY, theWidth, theHeight),
-  myId       (theId),
-  myViewer   (theViewer),
-  myIsPers   (Standard_False),
-  myIs2D     (Standard_False),
-  myFocalDistance(0.0),
-  myZoom     (0.0),
-  myDx       (0),
-  myDy       (0),
-  myFrameX0  (0),
-  myFrameY0  (0),
-  myFrameX1  (0),
-  myFrameY1  (0)
-{
-  memset (myType, 0, sizeof (myType));
-}
-
-//=======================================================================
-//function : Draw_View
-//purpose  : Constructor
-//=======================================================================
-#if defined(_WIN32) || defined(__WIN32__)
 Draw_View::Draw_View(Standard_Integer theId,
                      Draw_Viewer*     theViewer,
                      Standard_Integer theX,
                      Standard_Integer theY,
                      Standard_Integer theWidth,
                      Standard_Integer theHeight,
-                     HWND             theWindow)
-: Draw_Window("Win", theX, theY, theWidth, theHeight, theWindow),
+                     Aspect_Drawable  theWindow)
+: Draw_Window ("Win",
+               NCollection_Vec2<int> (theX, theY),
+               NCollection_Vec2<int> (theWidth, theHeight),
+               0, theWindow),
   myId       (theId),
   myViewer   (theViewer),
   myIsPers   (Standard_False),
@@ -72,56 +47,28 @@ Draw_View::Draw_View(Standard_Integer theId,
   memset (myType, 0, sizeof (myType));
 }
 
-//=======================================================================
-//function : Draw_View
-//purpose  : Constructor
-//=======================================================================
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-Draw_View::Draw_View(Standard_Integer theId,
-                     Draw_Viewer*     theViewer,
-                     Standard_Integer theX,
-                     Standard_Integer theY,
-                     Standard_Integer theWidth,
-                     Standard_Integer theHeight,
-                     NSWindow*        theWindow)
-: Draw_Window(theWindow, "Win", theX, theY, theWidth, theHeight),
-  myId       (theId),
-  myViewer   (theViewer),
-  myIsPers   (Standard_False),
-  myIs2D     (Standard_False),
-  myFocalDistance(0.0),
-  myZoom     (0.0),
-  myDx       (0),
-  myDy       (0),
-  myFrameX0  (0),
-  myFrameY0  (0),
-  myFrameX1  (0),
-  myFrameY1  (0)
+//! Find window by it's XID - applicable only to X11.
+static Aspect_Drawable findWindow (const char* theWindow)
 {
-  memset (myType, 0, sizeof (myType));
-}
-#endif
-
-
-//=======================================================================
-//function : Draw_View
-//purpose  : Constructor
-//=======================================================================
-#if defined(_WIN32) || defined (__WIN32__) || (defined(__APPLE__) && !defined(MACOSX_USE_GLX))
-Draw_View::Draw_View(Standard_Integer /*theId*/,
-                     Draw_Viewer*     /*theViewer*/,
-                     const char*      /*theTitle*/)
-: Draw_Window  (),
-  myId         (-1),
-  myViewer     (NULL),
+  Aspect_Drawable aWindow = 0;
+#ifdef HAVE_XLIB
+  sscanf (theWindow, "%lx", &aWindow);
 #else
+  (void )theWindow;
+#endif
+  return aWindow;
+}
+
+//=======================================================================
+//function : Draw_View
+//purpose  : Constructor
+//=======================================================================
 Draw_View::Draw_View(Standard_Integer theId,
                      Draw_Viewer*     theViewer,
                      const char*      theTitle)
-: Draw_Window  (theTitle),
+: Draw_Window  (theTitle, NCollection_Vec2<int>(0), NCollection_Vec2<int>(50), 0, findWindow (theTitle)),
   myId         (theId),
   myViewer     (theViewer),
-#endif
   myIsPers     (Standard_False),
   myIs2D       (Standard_False),
   myFocalDistance(0.0),
diff --git a/src/Draw/Draw_View.hxx b/src/Draw/Draw_View.hxx
index 97eea16fb7..c3acac8bca 100644
--- a/src/Draw/Draw_View.hxx
+++ b/src/Draw/Draw_View.hxx
@@ -24,30 +24,13 @@ class Draw_View : public Draw_Window
 public:
 
   //! Constructor
-  Draw_View(Standard_Integer theId,
-            Draw_Viewer*     theViewer,
-            Standard_Integer theX,
-            Standard_Integer theY,
-            Standard_Integer theWidth,
-            Standard_Integer theHeight);
-
-#if defined(_WIN32) || defined(__WIN32__)
   Draw_View(Standard_Integer theId,
             Draw_Viewer*     theViewer,
             Standard_Integer theX,
             Standard_Integer theY,
             Standard_Integer theWidth,
             Standard_Integer theHeight,
-            HWND             theWindow);
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-  Draw_View(Standard_Integer theId,
-            Draw_Viewer*     theViewer,
-            Standard_Integer theX,
-            Standard_Integer theY,
-            Standard_Integer theWidth,
-            Standard_Integer theHeight,
-            NSWindow*        theWindow);
-#endif
+            Aspect_Drawable  theWindow = 0);
 
   //! Constructor.
   Draw_View(Standard_Integer theId,
@@ -59,85 +42,44 @@ public:
 
 public: // @name getters and setters
 
-  //! Sets horizontal offset.
-  void SetDx(const Standard_Integer theDx)
-  {
-    myDx = theDx;
-  }
-
-  //! Sets vertical offset.
-  void SetDy(const Standard_Integer theDy)
-  {
-    myDy = theDy;
-  }
-
-  //! Sets parameter of zoom.
-  void SetZoom(const Standard_Real theZoom)
-  {
-    myZoom = theZoom;
-  }
-
-  //! Sets view matrix.
-  void SetMatrix(const gp_Trsf& theMatrix)
-  {
-    myMatrix = theMatrix;
-  }
-
-  //! Sets focal distance.
-  void SetFocalDistance(const Standard_Real theDistance)
-  {
-    myFocalDistance = theDistance;
-  }
-
   //! Gets horizontal offset.
-  Standard_Integer GetDx() const
-  {
-    return myDx;
-  }
+  Standard_Integer GetDx() const { return myDx; }
+
+  //! Sets horizontal offset.
+  void SetDx (const Standard_Integer theDx) { myDx = theDx; }
 
   //! Gets vertical offset.
-  Standard_Integer GetDy() const
-  {
-    return myDy;
-  }
+  Standard_Integer GetDy() const { return myDy; }
+
+  //! Sets vertical offset.
+  void SetDy (const Standard_Integer theDy) { myDy = theDy; }
 
   //! Gets parameter of zoom.
-  Standard_Real GetZoom() const
-  {
-    return myZoom;
-  }
+  Standard_Real GetZoom() const { return myZoom; }
+
+  //! Sets parameter of zoom.
+  void SetZoom (const Standard_Real theZoom) { myZoom = theZoom; }
 
   //! Gets matrix of view.
-  const gp_Trsf& GetMatrix() const
-  {
-    return myMatrix;
-  }
+  const gp_Trsf& GetMatrix() const { return myMatrix; }
+
+  //! Sets view matrix.
+  void SetMatrix (const gp_Trsf& theMatrix) { myMatrix = theMatrix; }
 
   //! Gets focal distance.
-  Standard_Real GetFocalDistance() const
-  {
-    return myFocalDistance;
-  }
+  Standard_Real GetFocalDistance() const { return myFocalDistance; }
 
-public: //! @name public inline methods
+  //! Sets focal distance.
+  void SetFocalDistance (const Standard_Real theDistance) { myFocalDistance = theDistance; }
 
   //! Returns type of view.
-  const char* Type()
-  {
-    return myType;
-  }
+  const char* Type() { return myType; }
 
   //! Returns true value if current view in 2D mode.
-  Standard_Boolean Is2D() const
-  {
-    return myIs2D;
-  }
+  Standard_Boolean Is2D() const { return myIs2D; }
 
   //! Returns true value if current view in perspective mode.
-  Standard_Real IsPerspective() const
-  {
-    return myIsPers;
-  }
+  Standard_Real IsPerspective() const { return myIsPers; }
 
 public: //! @name view API
 
@@ -155,7 +97,7 @@ public: //! @name view API
                 Standard_Integer& theX1,Standard_Integer& theY1);
 
   //! Perform window exposing.
-  void WExpose();
+  virtual void WExpose() Standard_OVERRIDE;
 
 protected:
 
diff --git a/src/Draw/Draw_Viewer.cxx b/src/Draw/Draw_Viewer.cxx
index 34fac0d5bf..ac13ec60db 100644
--- a/src/Draw/Draw_Viewer.cxx
+++ b/src/Draw/Draw_Viewer.cxx
@@ -30,7 +30,7 @@ static const Standard_Real DRAWINFINITE = 1e50;
 Standard_EXPORT Standard_Boolean Draw_Bounds = Standard_True;
 extern Standard_Boolean Draw_Batch;
 const Standard_Integer MAXSEGMENT = 1000;
-Segment segm[MAXSEGMENT];
+Draw_XSegment segm[MAXSEGMENT];
 static int nbseg=0;
 static Draw_View* curview = NULL;
 static Standard_Integer curviewId = 0;
@@ -943,12 +943,17 @@ Draw_Display Draw_Viewer::MakeDisplay (const Standard_Integer id) const
 //function : Select
 //purpose  :
 //=======================================================================
-
-void Draw_Viewer::Select (Standard_Integer& id, Standard_Integer& X, Standard_Integer& Y,
-			  Standard_Integer& Button, Standard_Boolean wait)
+void Draw_Viewer::Select (Standard_Integer& theId,
+                          Standard_Integer& theX, Standard_Integer& theY,
+                          Standard_Integer& theButton,
+                          Standard_Boolean  theToWait)
 {
-  if (Draw_Batch) return;
-  id = X = Y = Button = 0;
+  if (Draw_Batch)
+  {
+    return;
+  }
+
+  theId = theX = theY = theButton = 0;
   Standard_Boolean hasView = Standard_False;
   for (int aViewIter = 0; aViewIter < MAXVIEW; ++aViewIter)
   {
@@ -965,105 +970,142 @@ void Draw_Viewer::Select (Standard_Integer& id, Standard_Integer& X, Standard_In
     return;
   }
   Flush();
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
-  if (!wait) {
-    if (id >=0 && id < MAXVIEW) {
-      if (myViews[id]) myViews[id]->Wait(wait);
+
+#ifdef _WIN32
+  HANDLE hWnd = NULL;
+
+  theId = MAXVIEW; //:abv 29.05.02: cycle for working in console mode
+  while (theId >= MAXVIEW)
+  {
+    if (theToWait)
+    {
+      Draw_Window::SelectWait (hWnd, theX, theY, theButton);
+    }
+    else
+    {
+      Draw_Window::SelectNoWait (hWnd, theX, theY, theButton);
+    }
+
+    // Recherche du numero de la vue grace au HANDLE
+    for (int aViewIter = 0; aViewIter < MAXVIEW; ++aViewIter)
+    {
+      if (myViews[aViewIter] != NULL
+       && myViews[aViewIter]->IsEqualWindows (hWnd))
+      {
+        theId = aViewIter;
+      }
     }
   }
-  else {
-    for(int i=0 ; i<MAXVIEW ; i++)
-      if (myViews[i])  myViews[i]->Wait(wait);
+  theX =  theX - myViews[theId]->GetDx();
+  theY = -theY - myViews[theId]->GetDy();
+#elif defined(HAVE_XLIB)
+  if (!theToWait)
+  {
+    if (theId >= 0 && theId < MAXVIEW)
+    {
+      if (myViews[theId] != NULL)
+      {
+        myViews[theId]->Wait (theToWait);
+      }
+    }
+  }
+  else
+  {
+    for (int aViewIter = 0; aViewIter < MAXVIEW; ++aViewIter)
+    {
+      if (myViews[aViewIter] != NULL)
+      {
+        myViews[aViewIter]->Wait (theToWait);
+      }
+    }
   }
 
   Standard_Boolean again = Standard_True;
-  while (again) {
-
-    Event ev;
+  while (again)
+  {
+    Draw_Window::Draw_XEvent ev;
     ev.type = 0;
-
-    GetNextEvent(ev);
-
-    switch (ev.type) {
-
-    case ButtonPress :
-      Standard_Integer iv;
-      for (iv = 0; iv < MAXVIEW; iv++) {
-	if (myViews[iv]) {
-	  if (myViews[iv]->win == ev.window)
-	    break;
-	}
+    Draw_Window::GetNextEvent (ev);
+    switch (ev.type)
+    {
+      case ButtonPress:
+      {
+        Standard_Integer aViewIter = 0;
+        for (; aViewIter < MAXVIEW; ++aViewIter)
+        {
+          if (myViews[aViewIter] != NULL
+           && myViews[aViewIter]->IsEqualWindows (ev.window))
+          {
+            break;
+          }
+        }
+        if (theToWait || theId == aViewIter)
+        {
+          if (aViewIter < MAXVIEW)
+          {
+            theId = aViewIter;
+            theX = ev.x;
+            theY = ev.y;
+            theButton = ev.button;
+          }
+          else
+          {
+            theId = -1;
+          }
+          again = Standard_False;
+        }
+        break;
       }
-      if (wait || id == iv) {
-	if (iv < MAXVIEW) {
-	  id = iv;
-	  X = ev.x;
-	  Y = ev.y;
-	  Button = ev.button;
-	}
-	else {
-	  id = -1;
-	}
-	again = Standard_False;
+      case MotionNotify:
+      {
+        if (theToWait)
+        {
+          break;
+        }
+        theX = ev.x;
+        theY = ev.y;
+        theButton = 0;
+        again = Standard_False;
+        break;
       }
-      break;
-
-    case MotionNotify :
-      if (wait) break;
-      X = ev.x;
-      Y = ev.y;
-      Button = 0;
-      again = Standard_False;
-      break;
     }
   }
 
-  if (id != -1) {
-    X =  X - myViews[id]->GetDx();
-    Y = -Y - myViews[id]->GetDy();
-  }
-  if (!wait) myViews[id]->Wait(!wait);
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-  Standard_Integer aWindowNumber;
-
-  id = MAXVIEW;
-  while (id >= MAXVIEW)
+  if (theId != -1)
   {
-    GetNextEvent(wait, aWindowNumber, X, Y, Button);
-
-    if (Y < 0)
+    theX =  theX - myViews[theId]->GetDx();
+    theY = -theY - myViews[theId]->GetDy();
+  }
+  if (!theToWait)
+  {
+    myViews[theId]->Wait (!theToWait);
+  }
+#elif defined(__APPLE__)
+  theId = MAXVIEW;
+  while (theId >= MAXVIEW)
+  {
+    Standard_Integer aWindowNumber = 0;
+    Draw_Window::GetNextEvent (theToWait, aWindowNumber, theX, theY, theButton);
+    if (theY < 0)
     {
       continue; // mouse clicked on window title
     }
 
-    for (Standard_Integer anIter = 0; anIter < MAXVIEW; anIter++)
+    for (Standard_Integer aViewIter = 0; aViewIter < MAXVIEW; ++aViewIter)
     {
-      if (myViews[anIter] && myViews[anIter]->IsEqualWindows (aWindowNumber))
+      if (myViews[aViewIter] != NULL
+       && myViews[aViewIter]->IsEqualWindows (aWindowNumber))
       {
-        id = anIter;
+        theId = aViewIter;
       }
     }
   }
 
-  X =  X - myViews[id]->GetDx();
-  Y = -Y - myViews[id]->GetDy();
-
+  theX =  theX - myViews[theId]->GetDx();
+  theY = -theY - myViews[theId]->GetDy();
 #else
-  HANDLE hWnd;
-
-  id = MAXVIEW; //:abv 29.05.02: cycle for working in console mode
-  while ( id >= MAXVIEW ) {
-    if (wait)
-      Draw_Window::SelectWait(hWnd, X, Y, Button);
-    else
-      Draw_Window::SelectNoWait(hWnd, X, Y, Button);
-
-    // Recherche du numero de la vue grace au HANDLE
-    for(int i=0 ; i<MAXVIEW ; i++)
-      if (myViews[i] && myViews[i]->win == hWnd )  id = i;
-  }
-  X =  X - myViews[id]->GetDx();
-  Y = -Y - myViews[id]->GetDy();
+  // not implemented
+  (void )theToWait;
 #endif
 }
 
diff --git a/src/Draw/CommandWindow.cxx b/src/Draw/Draw_WNTCommandWindow.cxx
similarity index 98%
rename from src/Draw/CommandWindow.cxx
rename to src/Draw/Draw_WNTCommandWindow.cxx
index 9cc45562be..a519264401 100644
--- a/src/Draw/CommandWindow.cxx
+++ b/src/Draw/Draw_WNTCommandWindow.cxx
@@ -15,14 +15,15 @@
 // commercial license or contractual agreement.
 
 #ifdef _WIN32
+
 #include <windows.h>
 
 #include <Draw_Window.hxx>
 #include <Draw_Appli.hxx>
 #include <TCollection_AsciiString.hxx>
 
-#include <MainWindow.h>
-#include <CommandWindow.h>
+#include "Draw_WNTMainWindow.pxx"
+#include "Draw_WNTCommandWindow.pxx"
 
 #define CLIENTWND 0
 
@@ -49,11 +50,10 @@ HWND CreateCommandWindow(HWND hWnd, int /*nitem*/)
                                     0, 0, 400, 100,
                                     hWnd, NULL, hInstance, NULL);
 
-	ShowWindow(hWndCommand, SW_SHOW);	
+	ShowWindow (hWndCommand, SW_SHOW);
 	return hWndCommand;
 }
 
-
 /*--------------------------------------------------------*\
 |  COMMAND WINDOW PROCEDURE
 \*--------------------------------------------------------*/
@@ -125,7 +125,7 @@ BOOL CommandCreateProc(HWND hWnd)
 
 /*--------------------------------------------------------*\
 |  GET COMMAND
-|    
+|
 \*--------------------------------------------------------*/
 int GetCommand (HWND hWnd, wchar_t* theBuffer)
 {
@@ -141,7 +141,7 @@ int GetCommand (HWND hWnd, wchar_t* theBuffer)
     // Initialization of the 1st WORD to the nb of characters to read
     WORD* aNbMaxChar = (WORD* )aTempBuff;
     *aNbMaxChar = COMMANDSIZE - 1;
-      
+
     const int aNbCharRead = (int )SendMessageW (hWnd, EM_GETLINE, aNbLine - 1, (LPARAM )aTempBuff);
     aNbChar += aNbCharRead;
     const bool isPromp = wcsncmp (aTempBuff, THE_PROMPT, 10) == 0;
@@ -162,7 +162,7 @@ int GetCommand (HWND hWnd, wchar_t* theBuffer)
 \*--------------------------------------------------------*/
 LRESULT APIENTRY EditProc(HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam )
 {
-	static LRESULT nbline; // Process the buffer of the edit window 
+	static LRESULT nbline; // Process the buffer of the edit window
   switch (wMsg)
   {
     case WM_CHAR:
diff --git a/src/Draw/CommandWindow.h b/src/Draw/Draw_WNTCommandWindow.pxx
similarity index 97%
rename from src/Draw/CommandWindow.h
rename to src/Draw/Draw_WNTCommandWindow.pxx
index 01304f33f7..07a835a8a0 100644
--- a/src/Draw/CommandWindow.h
+++ b/src/Draw/Draw_WNTCommandWindow.pxx
@@ -16,25 +16,19 @@
 
 #ifdef _WIN32
 
-
 #define COMMANDCLASS L"COMMANDWINDOW"
 #define COMMANDTITLE L"Command Window"
 
-
 HWND CreateCommandWindow(HWND, int);
 LRESULT APIENTRY CommandProc(HWND, UINT, WPARAM, LPARAM);
 BOOL CommandCreateProc(HWND);
 VOID CommandDestroyProc(HWND);
 BOOL CommandHandler(HWND, WPARAM, LPARAM);
 
-
 #include <sys/stat.h>
 #include <tcl.h>
 #include <Standard_Stream.hxx>
 #include <stdio.h>
-//#include <io.h>
 #include <fcntl.h>
 
-
-
 #endif
diff --git a/src/Draw/init.cxx b/src/Draw/Draw_WNTInit.cxx
similarity index 63%
rename from src/Draw/init.cxx
rename to src/Draw/Draw_WNTInit.cxx
index 7cb6fc4dcd..3c9b3a3195 100644
--- a/src/Draw/init.cxx
+++ b/src/Draw/Draw_WNTInit.cxx
@@ -20,22 +20,19 @@
 #include <windows.h>
 
 #include "Draw_Window.hxx"
-#include "DrawRessource.h"
-#include "init.h"
-#include "MainWindow.h"
-#include "CommandWindow.h"
-
+#include "Draw_WNTRessource.pxx"
+#include "Draw_WNTInit.pxx"
+#include "Draw_WNTMainWindow.pxx"
+#include "Draw_WNTCommandWindow.pxx"
 
 #define USEDEFAULT 200
 
-
 /*--------------------------------------------------------*\
 |  REGISTER APPLICATION CLASS
 |  Enregistrement des classes de fenetres de l'application
 |
-d\*--------------------------------------------------------*/
-
-BOOL RegisterAppClass(HINSTANCE hInstance)
+\*--------------------------------------------------------*/
+BOOL RegisterAppClass (HINSTANCE theInstance)
 {
   WNDCLASSW wndClass;
 
@@ -44,36 +41,35 @@ BOOL RegisterAppClass(HINSTANCE hInstance)
   wndClass.style         = CS_HREDRAW | CS_VREDRAW | CS_CLASSDC;
   wndClass.cbClsExtra    = 0;
   wndClass.hCursor       = LoadCursor (NULL, IDC_ARROW);
-  wndClass.hInstance     = hInstance;
+  wndClass.hInstance     = theInstance;
 
   // Enregistrement de la fenetre principale
   //-----
   wndClass.cbWndExtra    = sizeof(void*);
   wndClass.lpfnWndProc   = (WNDPROC)WndProc;
-  wndClass.hIcon         = LoadIconW (hInstance, MAKEINTRESOURCEW(IDI_ICON1));
+  wndClass.hIcon         = LoadIconW (theInstance, MAKEINTRESOURCEW(IDI_ICON1));
   wndClass.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
   wndClass.lpszMenuName  = MAKEINTRESOURCEW(APPMENU);
   wndClass.lpszClassName = APPCLASS;
-
-  if(!RegisterClassW(&wndClass))
-    return(FALSE);
+  if (!RegisterClassW (&wndClass))
+  {
+    return FALSE;
+  }
 
   // Enregistrement de la fenetre DrawWindow
   //------
   wndClass.cbWndExtra    = sizeof(void*); // Extra Memory
-  wndClass.lpfnWndProc   = (WNDPROC)DrawWindow::DrawProc;
+  wndClass.lpfnWndProc   = (WNDPROC)Draw_Window::DrawProc;
   wndClass.hIcon         = 0;
   wndClass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
   wndClass.lpszMenuName  = NULL;
   wndClass.lpszClassName = DRAWCLASS;
-
-  if(!RegisterClassW(&wndClass))
+  if (!RegisterClassW (&wndClass))
   {
-    UnregisterClassW(APPCLASS, hInstance);
-    return(FALSE);
+    UnregisterClassW (APPCLASS, theInstance);
+    return FALSE;
   }
 
-
   // Enregistrement de la fenetre CommandWindow
   //------
   wndClass.lpfnWndProc   = (WNDPROC)CommandProc;
@@ -81,68 +77,58 @@ BOOL RegisterAppClass(HINSTANCE hInstance)
   wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
   wndClass.lpszMenuName  = NULL;
   wndClass.lpszClassName = COMMANDCLASS;
-
-  if(!RegisterClassW(&wndClass))
+  if (!RegisterClassW (&wndClass))
   {
-    UnregisterClassW(APPCLASS, hInstance);
-    UnregisterClassW(DRAWCLASS, hInstance);
-    return(FALSE);
+    UnregisterClassW (APPCLASS,  theInstance);
+    UnregisterClassW (DRAWCLASS, theInstance);
+    return FALSE;
   }
 
-  return(TRUE);
+  return TRUE;
 }
 
-
 /*--------------------------------------------------------*\
 |  UNREGISTER APPLICATION CLASS
 |    Suppression des classes de fenetres de l'application
 |
 \*--------------------------------------------------------*/
-VOID UnregisterAppClass(HINSTANCE hInstance)
+VOID UnregisterAppClass (HINSTANCE theInstance)
 {
-  UnregisterClassW(APPCLASS, hInstance);
-  UnregisterClassW(DRAWCLASS, hInstance);
+  UnregisterClassW (APPCLASS,  theInstance);
+  UnregisterClassW (DRAWCLASS, theInstance);
 }
 
-
 /*--------------------------------------------------------*\
 |  CREATE APPLICATION WINDOW
 |    Creation de la fenetre Top-Level
 |
 \*--------------------------------------------------------*/
-HWND CreateAppWindow(HINSTANCE hInstance)
+HWND CreateAppWindow (HINSTANCE theInstance)
 {
-  return(CreateWindowW(APPCLASS, APPTITLE,
-			    WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
-			    400,0,
-			    623,767,
-			    NULL, NULL, hInstance, NULL));
+  return CreateWindowW (APPCLASS, APPTITLE,
+                        WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
+                        400, 0,
+                        623,767,
+                        NULL, NULL, theInstance, NULL);
 }
 
-
 /*--------------------------------------------------------*\
 |  CREATE MDI CLIENT WINDOW
 |    Creation de la fenetre qui contient des fenetres MDI
 |
 \*--------------------------------------------------------*/
-HWND CreateMDIClientWindow(HWND hWndFrame)
+HWND CreateMDIClientWindow (HWND theWndFrame)
 {
-  HWND               hWndClient;
-  HANDLE             hInstance;
   CLIENTCREATESTRUCT ccs;
-
-  // Initialisation de la structure client
   ccs.hWindowMenu = NULL;
   ccs.idFirstChild = 0;
 
-  hInstance = (HANDLE)GetWindowLongPtrW(hWndFrame, GWLP_HINSTANCE);
-
-  hWndClient = CreateWindowW(L"MDICLIENT",NULL,
-			     									WS_CHILD | WS_CLIPSIBLINGS | 
-			     									WS_VISIBLE | MDIS_ALLCHILDSTYLES, 
-			     									0, 0, 1, 1,
-			     									hWndFrame, NULL, 
-			     									(HINSTANCE)hInstance, (LPVOID)&ccs);
-  return(hWndClient);
+  HINSTANCE hInstance = (HINSTANCE )GetWindowLongPtrW (theWndFrame, GWLP_HINSTANCE);
+  HWND hWndClient = CreateWindowW (L"MDICLIENT", NULL,
+                                   WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE | MDIS_ALLCHILDSTYLES,
+                                   0, 0, 1, 1,
+                                   theWndFrame, NULL,
+                                   hInstance, (LPVOID )&ccs);
+  return hWndClient;
 }
 #endif
diff --git a/src/Draw/init.h b/src/Draw/Draw_WNTInit.pxx
similarity index 99%
rename from src/Draw/init.h
rename to src/Draw/Draw_WNTInit.pxx
index 478a0eb6a3..61b2b13fbe 100644
--- a/src/Draw/init.h
+++ b/src/Draw/Draw_WNTInit.pxx
@@ -25,5 +25,4 @@ VOID UnregisterAppClass(HINSTANCE);
 HWND CreateAppWindow(HINSTANCE);
 HWND CreateMDIClientWindow(HWND);
 
-
 #endif
diff --git a/src/Draw/MainWindow.cxx b/src/Draw/Draw_WNTMainWindow.cxx
similarity index 94%
rename from src/Draw/MainWindow.cxx
rename to src/Draw/Draw_WNTMainWindow.cxx
index 3e95c96a8f..c5dfadf86f 100644
--- a/src/Draw/MainWindow.cxx
+++ b/src/Draw/Draw_WNTMainWindow.cxx
@@ -17,18 +17,17 @@
 #ifdef _WIN32
 
 #include <windows.h>
-#include <DrawRessource.h>
-#include <init.h>
+
 #include <Draw_Window.hxx>
 
-#include <MainWindow.h>
-#include <CommandWindow.h>
+#include "Draw_WNTCommandWindow.pxx"
+#include "Draw_WNTInit.pxx"
+#include "Draw_WNTMainWindow.pxx"
+#include "Draw_WNTRessource.pxx"
 
 Standard_Boolean Draw_Interprete(const char* command); // Implemented in Draw.cxx
 extern Standard_Boolean Draw_IsConsoleSubsystem;
 
-//extern "C" int  compat_unlink(const char *fname); // Implemente dans TCL
-
 /*--------------------------------------------------------*\
 |  CLIENT WINDOW PROCEDURE
 |
@@ -42,7 +41,7 @@ LRESULT APIENTRY WndProc(HWND hWndFrame, UINT wMsg, WPARAM wParam, LPARAM lParam
     {
       CreateProc (hWndFrame);
       HWND hWndClient = (HWND )GetWindowLongPtrW (hWndFrame, CLIENTWND);
-      DrawWindow::hWndClientMDI = hWndClient;
+      Draw_Window::hWndClientMDI = hWndClient;
       if (!Draw_IsConsoleSubsystem)
       {
         CreateCommandWindow (hWndFrame, 0);
@@ -82,10 +81,9 @@ BOOL CreateProc(HWND hWndFrame)
   return(TRUE);
 }
 
-
 /*--------------------------------------------------------------------------*\
 |  COMMAND PROCEDURE
-|  		Handler for message WM_COMMAND   
+|  		Handler for message WM_COMMAND
 |     It is used when Draw_IsConsoleSubsystem = Standard_False
 |     i.e. in non-console mode (see Draw_main() in Draw_Main.cxx).
 \*--------------------------------------------------------------------------*/
@@ -138,7 +136,6 @@ LRESULT APIENTRY CmdProc(HWND hWndFrame, UINT wMsg, WPARAM /*wParam*/, LPARAM /*
   return 0;
 }
 
-
 /*--------------------------------------------------------------------------*\
 |  CLIENT DESTROY PROCEDURE
 |     Handler for message WM_DESTROY.
@@ -152,4 +149,3 @@ VOID DestroyProc(HWND hWnd)
   PostQuitMessage(0);
 }
 #endif
-
diff --git a/src/Draw/MainWindow.h b/src/Draw/Draw_WNTMainWindow.pxx
similarity index 93%
rename from src/Draw/MainWindow.h
rename to src/Draw/Draw_WNTMainWindow.pxx
index 6957cd29a9..68307b9237 100644
--- a/src/Draw/MainWindow.h
+++ b/src/Draw/Draw_WNTMainWindow.pxx
@@ -15,10 +15,10 @@
 */
 
 /****************************************************\
-*/ 
+*/
 /**  MainWindow.h
-*/ 
-/*\****************************************************/ 
+*/
+/*****************************************************/
 #ifdef _WIN32
 
 #define CLIENTWND 0
@@ -33,5 +33,4 @@ BOOL CreateProc(HWND);
 VOID DestroyProc(HWND);
 LRESULT APIENTRY CmdProc(HWND, UINT, WPARAM, LPARAM);
 
-
 #endif
diff --git a/src/Draw/DrawRessource.h b/src/Draw/Draw_WNTRessource.pxx
similarity index 99%
rename from src/Draw/DrawRessource.h
rename to src/Draw/Draw_WNTRessource.pxx
index eb751f0383..bffb289210 100644
--- a/src/Draw/DrawRessource.h
+++ b/src/Draw/Draw_WNTRessource.pxx
@@ -31,7 +31,7 @@
 #define ID_COMMAND_SHOW                 40006
 
 // Next default values for new objects
-// 
+//
 #ifdef APSTUDIO_INVOKED
 #ifndef APSTUDIO_READONLY_SYMBOLS
 #define _APS_NEXT_RESOURCE_VALUE        109
@@ -41,6 +41,4 @@
 #endif
 #endif
 
-
-
 #endif
diff --git a/src/Draw/Draw_Window.cxx b/src/Draw/Draw_Window.cxx
index e0f3be4882..c30c6bd096 100644
--- a/src/Draw/Draw_Window.cxx
+++ b/src/Draw/Draw_Window.cxx
@@ -19,99 +19,28 @@
 #include <windows.h>
 #endif
 
-#include <Standard_ErrorHandler.hxx>
-
-#include <tcl.h>
-#include <Draw_Interpretor.hxx>
 #include <Draw_Window.hxx>
+
+#include <Aspect_DisplayConnection.hxx>
 #include <Draw_Appli.hxx>
-#include <TCollection_AsciiString.hxx>
-#include <TCollection_ExtendedString.hxx>
+#include <Draw_Interpretor.hxx>
 #include <Image_AlienPixMap.hxx>
 #include <Message.hxx>
 #include <NCollection_List.hxx>
-
-extern Standard_Boolean Draw_Batch;
-extern Standard_Boolean Draw_VirtualWindows;
-static NCollection_List<Draw_Window::FCallbackBeforeTerminate> MyCallbacks;
-
-void Draw_Window::AddCallbackBeforeTerminate(FCallbackBeforeTerminate theCB)
-{
-  MyCallbacks.Append(theCB);
-}
-
-void Draw_Window::RemoveCallbackBeforeTerminate(FCallbackBeforeTerminate theCB)
-{
-  NCollection_List<Draw_Window::FCallbackBeforeTerminate>::Iterator Iter(MyCallbacks);
-  for(; Iter.More(); Iter.Next())
-  {
-    if (Iter.Value() == theCB)
-    {
-      MyCallbacks.Remove(Iter);
-      break;
-    }
-  }
-}
-
-/*
- *----------------------------------------------------------------------
- *
- * Prompt --
- *
- *        Issue a prompt on standard output, or invoke a script
- *        to issue the prompt.
- *
- * Results:
- *        None.
- *
- * Side effects:
- *        A prompt gets output, and a Tcl script may be evaluated
- *        in interp.
- *
- *----------------------------------------------------------------------
- */
-
-static void Prompt(Tcl_Interp *Interp, int partial)
-{
-    Tcl_Channel errChannel;
-    Tcl_Channel outChannel = Tcl_GetStdChannel(TCL_STDOUT);
-    const char* promptCmd = Tcl_GetVar (Interp, partial ? "tcl_prompt2" : "tcl_prompt1", TCL_GLOBAL_ONLY);
-    if (promptCmd == NULL) {
-defaultPrompt:
-      if (!partial && outChannel) {
-        Tcl_Write(outChannel, "% ", 2);
-      }
-    } else {
-      int code = Tcl_Eval(Interp, promptCmd);
-      outChannel = Tcl_GetStdChannel(TCL_STDOUT);
-      errChannel = Tcl_GetStdChannel(TCL_STDERR);
-      if (code != TCL_OK) {
-        if (errChannel) {
-#if ((TCL_MAJOR_VERSION > 8) || ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 5)))
-          Tcl_Write(errChannel, Tcl_GetStringResult(Interp), -1);
-#else
-          Tcl_Write(errChannel, Interp->result, -1);
-#endif
-          Tcl_Write(errChannel, "\n", 1);
-        }
-        Tcl_AddErrorInfo(Interp,
-                         "\n    (script that generates prompt)");
-        goto defaultPrompt;
-      }
-    }
-    if (outChannel) {
-      Tcl_Flush(outChannel);
-    }
-}
-
-#if !defined(_WIN32) && !defined(__WIN32__)
-
+#include <OSD.hxx>
 #include <OSD_Timer.hxx>
-#include <Draw_Window.hxx>
-#include <unistd.h>
+#include <Standard_ErrorHandler.hxx>
+#include <TCollection_AsciiString.hxx>
+#include <TCollection_ExtendedString.hxx>
+
+#include <tcl.h>
+
+#if !defined(_WIN32)
+  #include <unistd.h>
+#endif
 
 #ifdef HAVE_TK
-#if defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#if defined(__APPLE__) && !defined(HAVE_XLIB)
   // use forward declaration for small subset of used Tk functions
   // to workaround broken standard Tk framework installation within OS X SDKs
   // which *HAS* X11 headers in Tk.framework but doesn't install them appropriately
@@ -131,171 +60,216 @@ defaultPrompt:
 #endif
 #endif
 
-/*
- * Global variables used by the main program:
- */
+#if defined(HAVE_XLIB)
+  #include <X11/Xutil.h>
+#endif
 
-char *tcl_RcFileName = NULL;    /* Name of a user-specific startup script
-                                 * to source if the application is being run
-                                 * interactively (e.g. "~/.wishrc").  Set
-                                 * by Tcl_AppInit.  NULL means don't source
-                                 * anything ever. */
+#if defined(_WIN32)
 
-static Tcl_DString command;     /* Used to assemble lines of terminal input
-                                 * into Tcl commands. */
-static Tcl_DString line;        /* Used to read the next line from the
-                                 * terminal input. */
-//static char errorExitCmd[] = "exit 1";
+#include "Draw_WNTRessource.pxx"
+#include "Draw_WNTInit.pxx"
 
-/*
- * Forward declarations for procedures defined later in this file:
- */
+#define PENWIDTH 1
+#define CLIENTWND 0
 
-static void StdinProc (ClientData clientData, int mask);
+//! Creation of color stylos
+static HPEN Draw_colorPenTab[MAXCOLOR] =
+{
+  CreatePen(PS_SOLID, PENWIDTH, RGB(255,255,255)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(255,0,0)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(0,255,0)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(0,0,255)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(0,255,255)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(255,215,0)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(255,0,255)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(255,52,179)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(255,165,0)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(255,228,225)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(255,160,122)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(199,21,133)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(255,255,0)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(240,230,140)),
+  CreatePen(PS_SOLID, PENWIDTH, RGB(255,127,80))
+};
 
-static void Prompt (Tcl_Interp *Interp, int partial);
+// Correspondence mode X11 and WINDOWS NT
+static const int Draw_modeTab[16] =
+{
+  R2_BLACK, R2_MASKPEN, R2_MASKPENNOT, R2_COPYPEN,
+  R2_MASKNOTPEN, R2_NOP, R2_XORPEN, R2_MERGEPEN,
+  R2_NOTMASKPEN, R2_NOTXORPEN, R2_NOT, R2_MERGEPENNOT,
+  R2_NOTCOPYPEN, R2_MERGENOTPEN, R2_NOTMERGEPEN, R2_WHITE
+};
+#endif
 
-static Standard_Boolean tty;        /* Non-zero means standard input is a
-                                 * terminal-like device.  Zero means it's
-                                 * a file. */
-
-Standard_Integer Draw_WindowScreen = 0;
+extern Standard_Boolean Draw_Batch;
+extern Standard_Boolean Draw_VirtualWindows;
 Standard_Boolean Draw_BlackBackGround = Standard_True;
+#if defined(_WIN32)
+// indicates SUBSYSTEM:CONSOLE linker option, to be set to True in main()
+Standard_EXPORT Standard_Boolean Draw_IsConsoleSubsystem = Standard_False;
+HWND Draw_Window::hWndClientMDI = 0;
+#endif
 
+//! Return termination callbacks.
+static NCollection_List<Draw_Window::FCallbackBeforeTerminate>& TermCallbacks()
+{
+  static NCollection_List<Draw_Window::FCallbackBeforeTerminate> MyCallbacks;
+  return MyCallbacks;
+}
 
-// Initialization of static variables of Draw_Window
-//======================================================
-Draw_Window* Draw_Window::firstWindow = NULL;
+//=======================================================================
+//function : AddCallbackBeforeTerminate
+//purpose  :
+//=======================================================================
+void Draw_Window::AddCallbackBeforeTerminate (FCallbackBeforeTerminate theCB)
+{
+  TermCallbacks().Append (theCB);
+}
 
-// X11 specific part
-#if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
-#include <X11/Xutil.h>
-#include <Aspect_DisplayConnection.hxx>
+//=======================================================================
+//function : RemoveCallbackBeforeTerminate
+//purpose  :
+//=======================================================================
+void Draw_Window::RemoveCallbackBeforeTerminate (FCallbackBeforeTerminate theCB)
+{
+  for (NCollection_List<Draw_Window::FCallbackBeforeTerminate>::Iterator anIter (TermCallbacks());
+       anIter.More(); anIter.Next())
+  {
+    if (anIter.Value() == theCB)
+    {
+      TermCallbacks().Remove (anIter);
+      break;
+    }
+  }
+}
 
+//! Issue a prompt on standard output, or invoke a script to issue the prompt.
+//! Side effects: A prompt gets output, and a Tcl script may be evaluated in interp.
+static void Prompt (Tcl_Interp* theInterp, int thePartial)
+{
+  Tcl_Channel errChannel;
+  Tcl_Channel outChannel = Tcl_GetStdChannel(TCL_STDOUT);
+  const char* promptCmd = Tcl_GetVar (theInterp, thePartial ? "tcl_prompt2" : "tcl_prompt1", TCL_GLOBAL_ONLY);
+  if (promptCmd == NULL)
+  {
+defaultPrompt:
+    if (!thePartial && outChannel)
+    {
+      Tcl_Write(outChannel, "% ", 2);
+    }
+  }
+  else
+  {
+    int code = Tcl_Eval (theInterp, promptCmd);
+    outChannel = Tcl_GetStdChannel (TCL_STDOUT);
+    errChannel = Tcl_GetStdChannel (TCL_STDERR);
+    if (code != TCL_OK)
+    {
+      if (errChannel)
+      {
+#if ((TCL_MAJOR_VERSION > 8) || ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 5)))
+        Tcl_Write (errChannel, Tcl_GetStringResult (theInterp), -1);
+#else
+        Tcl_Write (errChannel, theInterp->result, -1);
+#endif
+        Tcl_Write (errChannel, "\n", 1);
+      }
+      Tcl_AddErrorInfo (theInterp,
+                        "\n    (script that generates prompt)");
+      goto defaultPrompt;
+    }
+  }
+  if (outChannel)
+  {
+    Tcl_Flush (outChannel);
+  }
+}
+
+#if !defined(_WIN32)
+
+//! Used to assemble lines of terminal input into Tcl commands.
+static Tcl_DString Draw_TclCommand;
+//! Used to read the next line from the terminal input.
+static Tcl_DString Draw_TclLine;
+
+//! Forward declarations for procedures defined later in this file:
+static void StdinProc (ClientData theClientData, int theMask);
+static void Prompt (Tcl_Interp* theInterp, int thePartial);
+
+//! Non-zero means standard input is a terminal-like device.
+//! Zero means it's a file.
+static Standard_Boolean tty;
+
+#if defined(HAVE_XLIB)
 static unsigned long thePixels[MAXCOLOR];
 
 Display* Draw_WindowDisplay = NULL;
 Colormap Draw_WindowColorMap;
+static Standard_Integer Draw_WindowScreen = 0;
 static Handle(Aspect_DisplayConnection) Draw_DisplayConnection;
 
-// Base_Window struct definition
-//===================================
-struct Base_Window
+//! Return list of windows.
+static NCollection_List<Draw_Window*>& getDrawWindowList()
+{
+  static NCollection_List<Draw_Window*> MyWindows;
+  return MyWindows;
+}
+
+//! Base_Window struct definition
+struct Draw_Window::Base_Window
 {
   GC gc;
   XSetWindowAttributes xswa;
 };
+#endif
+#endif
 
+#if !defined(__APPLE__) || defined(HAVE_XLIB) // implementation for Apple resides in .mm file
 //=======================================================================
 //function : Draw_Window
 //purpose  :
 //=======================================================================
-Draw_Window::Draw_Window() :
-       base(*new Base_Window()),
-       win(0),
-       myBuffer(0),
-       next(firstWindow),
-       previous(NULL),
-       myUseBuffer(Standard_False),
-       withWindowManager(Standard_True)
+Draw_Window::Draw_Window (const char* theTitle,
+                          const NCollection_Vec2<int>& theXY,
+                          const NCollection_Vec2<int>& theSize,
+                          Aspect_Drawable theParent,
+                          Aspect_Drawable theWin)
+: myWindow (0),
+#if defined(_WIN32)
+  myMemHbm (NULL),
+  myCurrPen  (0),
+  myCurrMode (0),
+#elif defined(HAVE_XLIB)
+  myMother ((Window )theParent),
+  myImageBuffer (0),
+  myBase (new Base_Window()),
+#endif
+  myCurrentColor (0),
+  myUseBuffer (Standard_False)
 {
-  myMother = RootWindow(Draw_WindowDisplay,
-                        Draw_WindowScreen);
+  NCollection_Vec2<int> anXY = theXY, aSize = theSize;
+#if defined(_WIN32)
+  myWindow = (HWND )theWin;
+  (void )theParent;
+#elif defined(HAVE_XLIB)
+  myWindow = (Window )theWin;
+  if (theParent == 0)
+  {
+    myMother = RootWindow (Draw_WindowDisplay, Draw_WindowScreen);
+  }
+  if (theWin != 0)
+  {
+    GetPosition (anXY.x(), anXY.y());
+    aSize.x() = HeightWin();
+    aSize.y() = WidthWin();
+  }
 
-  if (firstWindow) firstWindow->previous = this;
-  firstWindow = this;
-}
+  getDrawWindowList().Append (this);
+#endif
 
-//=======================================================================
-//function : Draw_Window
-//purpose  :
-//=======================================================================
-Draw_Window::Draw_Window(Window mother) :
-       base(*new Base_Window()),
-       win(0),
-       myBuffer(0),
-       next(firstWindow),
-       previous(NULL),
-       myUseBuffer(Standard_False),
-       withWindowManager(Standard_True)
-{
-  myMother = mother;
-
-  if (firstWindow) firstWindow->previous = this;
-  firstWindow = this;
-}
-
-//=======================================================================
-//function : Draw_Window
-//purpose  :
-//=======================================================================
-Draw_Window::Draw_Window (const char* title,
-                          Standard_Integer X, Standard_Integer Y,
-                          Standard_Integer DX, Standard_Integer DY) :
-       base(*new Base_Window()),
-       win(0),
-       myBuffer(0),
-       next(firstWindow),
-       previous(NULL),
-       myUseBuffer(Standard_False),
-       withWindowManager(Standard_True)
-{
-  myMother = RootWindow(Draw_WindowDisplay,
-                        Draw_WindowScreen);
-
-  if (firstWindow) firstWindow->previous = this;
-  firstWindow = this;
-  Init(X,Y,DX,DY);
-  SetTitle(title);
-}
-
-//=======================================================================
-//function : Draw_Window
-//purpose  :
-//=======================================================================
-Draw_Window::Draw_Window (const char* window ) :
-       base(*new Base_Window()),
-       win(0),
-       myBuffer(0),
-       next(firstWindow),
-       previous(NULL),
-       myUseBuffer(Standard_False),
-       withWindowManager(Standard_True)
-{
-  sscanf(window,"%lx",&win);
-  Standard_Integer X,Y,DX,DY;
-
-  if (firstWindow) firstWindow->previous = this;
-  firstWindow = this;
-  GetPosition(X,Y);
-  DX=HeightWin();
-  DY=WidthWin();
-
-  Init(X,Y,DX,DY);
-}
-
-//=======================================================================
-//function : Draw_Window
-//purpose  :
-//=======================================================================
-Draw_Window::Draw_Window (Window mother,
-                          char* title,
-                          Standard_Integer X, Standard_Integer Y,
-                          Standard_Integer DX, Standard_Integer DY) :
-       base(*new Base_Window()),
-       win(0),
-       myBuffer(0),
-       next(firstWindow),
-       previous(NULL),
-       myUseBuffer(Standard_False),
-       withWindowManager(Standard_True)
-{
-  myMother = mother;
-
-  if (firstWindow) firstWindow->previous = this;
-  firstWindow = this;
-  Init(X,Y,DX,DY);
-  SetTitle(title);
+  init (anXY, aSize);
+  SetTitle (theTitle);
 }
 
 //=======================================================================
@@ -304,68 +278,103 @@ Draw_Window::Draw_Window (Window mother,
 //=======================================================================
 Draw_Window::~Draw_Window()
 {
-  if (previous)
-    previous->next = next;
-  else
-    firstWindow = next;
-  if (next)
-    next->previous = previous;
-
-  if (myBuffer != 0)
+#ifdef _WIN32
+  // Delete 'off-screen drawing'-related objects
+  if (myMemHbm)
   {
-    XFreePixmap(Draw_WindowDisplay, myBuffer);
-    myBuffer = 0;
+    DeleteObject (myMemHbm);
+    myMemHbm = NULL;
   }
-  // Liberation pointer on Base_Window
-  delete &base;
+#elif defined(HAVE_XLIB)
+  getDrawWindowList().Remove (this);
+  if (myImageBuffer != 0)
+  {
+    XFreePixmap (Draw_WindowDisplay, myImageBuffer);
+    myImageBuffer = 0;
+  }
+#endif
 }
 
 //=======================================================================
-//function : Init
+//function : init
 //purpose  :
 //=======================================================================
-void Draw_Window::Init(Standard_Integer X, Standard_Integer Y,
-                       Standard_Integer DX, Standard_Integer DY)
+void Draw_Window::init (const NCollection_Vec2<int>& theXY,
+                        const NCollection_Vec2<int>& theSize)
 {
-  unsigned long setmask;
+#ifdef _WIN32
+  if (myWindow == NULL)
+  {
+    myWindow = createDrawWindow (hWndClientMDI, 0);
+  }
 
+  // include decorations in the window dimensions
+  // to reproduce same behaviour of Xlib window.
+  DWORD aWinStyle   = GetWindowLongW (myWindow, GWL_STYLE);
+  DWORD aWinStyleEx = GetWindowLongW (myWindow, GWL_EXSTYLE);
+  HMENU aMenu       = GetMenu (myWindow);
+
+  RECT aRect;
+  aRect.top    = theXY.y();
+  aRect.bottom = theXY.y() + theSize.y();
+  aRect.left   = theXY.x();
+  aRect.right  = theXY.x() + theSize.x();
+  AdjustWindowRectEx (&aRect, aWinStyle, aMenu != NULL ? TRUE : FALSE, aWinStyleEx);
+
+  SetPosition  (aRect.left, aRect.top);
+  SetDimension (aRect.right - aRect.left, aRect.bottom - aRect.top);
+  // Save the pointer at the instance associated to the window
+  SetWindowLongPtrW (myWindow, CLIENTWND, (LONG_PTR)this);
+  HDC hDC = GetDC (myWindow);
+  SetBkColor (hDC, RGB(0, 0, 0));
+  myCurrPen  = 3;
+  myCurrMode = 3;
+  SelectObject (hDC, Draw_colorPenTab[myCurrPen]); // Default pencil
+  SelectObject (hDC, GetStockObject(BLACK_BRUSH));
+  SetTextColor (hDC, RGB(0,0,255));
+  ReleaseDC (myWindow, hDC);
+
+  if (Draw_VirtualWindows)
+  {
+    // create a virtual window
+    SetUseBuffer (Standard_True);
+  }
+#elif defined(HAVE_XLIB)
   if (Draw_BlackBackGround)
   {
-    base.xswa.background_pixel = BlackPixel(Draw_WindowDisplay,Draw_WindowScreen);
-    base.xswa.border_pixel     = WhitePixel(Draw_WindowDisplay,Draw_WindowScreen);
+    myBase->xswa.background_pixel = BlackPixel(Draw_WindowDisplay, Draw_WindowScreen);
+    myBase->xswa.border_pixel     = WhitePixel(Draw_WindowDisplay, Draw_WindowScreen);
   }
   else
   {
-    base.xswa.background_pixel = WhitePixel(Draw_WindowDisplay,Draw_WindowScreen);
-    base.xswa.border_pixel     = BlackPixel(Draw_WindowDisplay,Draw_WindowScreen);
+    myBase->xswa.background_pixel = WhitePixel(Draw_WindowDisplay, Draw_WindowScreen);
+    myBase->xswa.border_pixel     = BlackPixel(Draw_WindowDisplay, Draw_WindowScreen);
   }
-  base.xswa.colormap         = Draw_WindowColorMap;
-  setmask               = CWBackPixel | CWBorderPixel ;
+  myBase->xswa.colormap = Draw_WindowColorMap;
+  unsigned long aSetMask = CWBackPixel | CWBorderPixel;
 
-  XSizeHints myHints;
-  myHints.flags = USPosition;
-  myHints.x = (int) X;
-  myHints.y = (int) Y;
-
-  if (win == 0)
+  XSizeHints aWinHints;
+  aWinHints.flags = USPosition;
+  aWinHints.x = theXY.x();
+  aWinHints.y = theXY.y();
+  if (myWindow == 0)
   {
-    win = XCreateWindow(Draw_WindowDisplay,
-                        myMother,
-                        (int) X,(int) Y,
-                        (unsigned int) DX,(unsigned int) DY,
-                        5,
-                        DefaultDepth(Draw_WindowDisplay,Draw_WindowScreen),
-                        InputOutput,
-                        DefaultVisual(Draw_WindowDisplay,Draw_WindowScreen),
-                        setmask,&base.xswa);
-    XSelectInput(Draw_WindowDisplay, win, ButtonPressMask|ExposureMask|
-                                          StructureNotifyMask);
+    myWindow = XCreateWindow (Draw_WindowDisplay,
+                              myMother,
+                              theXY.x(), theXY.y(),
+                              (unsigned int )theSize.x(), (unsigned int )theSize.y(),
+                              5,
+                              DefaultDepth(Draw_WindowDisplay, Draw_WindowScreen),
+                              InputOutput,
+                              DefaultVisual(Draw_WindowDisplay, Draw_WindowScreen),
+                              aSetMask, &myBase->xswa);
+    XSelectInput (Draw_WindowDisplay, myWindow, ButtonPressMask | ExposureMask | StructureNotifyMask);
 
     // advise to the window manager to place it where I need
-    XSetWMNormalHints(Draw_WindowDisplay,win,&myHints);
+    XSetWMNormalHints (Draw_WindowDisplay, myWindow, &aWinHints);
 
     Atom aDeleteWindowAtom = Draw_DisplayConnection->GetAtom (Aspect_XA_DELETE_WINDOW);
-    XSetWMProtocols (Draw_WindowDisplay, win, &aDeleteWindowAtom, 1);
+    XSetWMProtocols (Draw_WindowDisplay, myWindow, &aDeleteWindowAtom, 1);
 
     if (Draw_VirtualWindows)
     {
@@ -374,120 +383,215 @@ void Draw_Window::Init(Standard_Integer X, Standard_Integer Y,
     }
   }
 
-  base.gc = XCreateGC(Draw_WindowDisplay, win, 0, NULL);
+  myBase->gc = XCreateGC (Draw_WindowDisplay, myWindow, 0, NULL);
 
-  XSetPlaneMask(Draw_WindowDisplay,base.gc,AllPlanes);
-  XSetForeground(Draw_WindowDisplay,
-                 base.gc, WhitePixel(Draw_WindowDisplay,Draw_WindowScreen));
-  XSetBackground(Draw_WindowDisplay,
-                 base.gc, BlackPixel(Draw_WindowDisplay,Draw_WindowScreen));
+  XSetPlaneMask (Draw_WindowDisplay, myBase->gc, AllPlanes);
+  XSetForeground (Draw_WindowDisplay,
+                  myBase->gc, WhitePixel(Draw_WindowDisplay, Draw_WindowScreen));
+  XSetBackground (Draw_WindowDisplay,
+                  myBase->gc, BlackPixel(Draw_WindowDisplay, Draw_WindowScreen));
   // save in case of window recovery
 
-  base.xswa.backing_store = Always;
-  XChangeWindowAttributes(Draw_WindowDisplay, win,
-                          CWBackingStore, &base.xswa);
+  myBase->xswa.backing_store = Always;
+  XChangeWindowAttributes (Draw_WindowDisplay, myWindow,
+                           CWBackingStore, &myBase->xswa);
 
-  XSetLineAttributes (Draw_WindowDisplay, base.gc,
+  XSetLineAttributes (Draw_WindowDisplay, myBase->gc,
                       0, LineSolid, CapButt, JoinMiter);
+#else
+  (void )theXY;
+  (void )theSize;
+#endif
 }
 
+//=======================================================================
+//function : SetUseBuffer
+//purpose  :
+//=======================================================================
+void Draw_Window::SetUseBuffer (Standard_Boolean theToUse)
+{
+  myUseBuffer = theToUse;
+  InitBuffer();
+}
+
+#ifdef _WIN32
+//=======================================================================
+//function : getMemDC
+//purpose  :
+//=======================================================================
+HDC Draw_Window::getMemDC (HDC theWinDC)
+{
+  if (!myUseBuffer)
+  {
+    return NULL;
+  }
+
+  HDC aWorkDC = CreateCompatibleDC (theWinDC);
+  myOldHbm = (HBITMAP )SelectObject (aWorkDC, myMemHbm);
+  SetROP2 (aWorkDC, Draw_modeTab[myCurrMode]);
+  SelectObject (aWorkDC, Draw_colorPenTab[myCurrPen]);
+  SetBkColor   (aWorkDC, RGB(0, 0, 0));
+  SelectObject (aWorkDC, GetStockObject(BLACK_BRUSH));
+  SetTextColor (aWorkDC, RGB(0,0,255));
+  return aWorkDC;
+}
+
+//=======================================================================
+//function : releaseMemDC
+//purpose  :
+//=======================================================================
+void Draw_Window::releaseMemDC (HDC theMemDC)
+{
+  if (!myUseBuffer || !theMemDC)
+  {
+    return;
+  }
+
+  if (myOldHbm)
+  {
+    SelectObject (theMemDC, myOldHbm);
+  }
+  DeleteDC (theMemDC);
+}
+#endif
+
 //=======================================================================
 //function : InitBuffer
 //purpose  :
 //=======================================================================
 void Draw_Window::InitBuffer()
 {
-  if (myUseBuffer) {
-    if (myBuffer != 0) {
-      XFreePixmap (Draw_WindowDisplay, myBuffer);
-    }
-    XWindowAttributes winAttr;
-    XGetWindowAttributes (Draw_WindowDisplay, win, &winAttr);
-    myBuffer = XCreatePixmap (Draw_WindowDisplay, win, winAttr.width, winAttr.height, winAttr.depth);
-  }
-  else if (myBuffer != 0)
+#ifdef _WIN32
+  if (myUseBuffer)
   {
-    XFreePixmap (Draw_WindowDisplay, myBuffer);
-    myBuffer = 0;
+    RECT aRect;
+    HDC hDC = GetDC (myWindow);
+    GetClientRect (myWindow, &aRect);
+    if (myMemHbm)
+    {
+      BITMAP aBmp;
+      GetObjectW (myMemHbm, sizeof(BITMAP), &aBmp);
+      if ((aRect.right - aRect.left) == aBmp.bmWidth
+       && (aRect.bottom - aRect.top) == aBmp.bmHeight)
+      {
+        return;
+      }
+      DeleteObject (myMemHbm);
+    }
+    myMemHbm = (HBITMAP )CreateCompatibleBitmap (hDC,
+                                                 aRect.right - aRect.left,
+                                                 aRect.bottom - aRect.top);
+    HDC aMemDC = getMemDC (hDC);
+    FillRect (aMemDC, &aRect, (HBRUSH)GetStockObject(BLACK_BRUSH));
+    releaseMemDC (aMemDC);
+    ReleaseDC (myWindow, hDC);
   }
-}
-
-//=======================================================================
-//function : StopWinManager
-//purpose  :
-//=======================================================================
-void Draw_Window::StopWinManager()
-{
-//  XGCValues winGc;
-  XWindowAttributes winAttr;
-  XGetWindowAttributes (Draw_WindowDisplay, win, &winAttr);
-  Destroy();
-
-  XSizeHints myHints;
-  myHints.flags = USPosition;
-  myHints.x = (int) 30;
-  myHints.y = (int) 100;
-
-  base.xswa.override_redirect = 1;
-  base.xswa.border_pixel = BlackPixel(Draw_WindowDisplay,
-                                 Draw_WindowScreen);
-  base.xswa.background_pixel = WhitePixel(Draw_WindowDisplay,
-                               Draw_WindowScreen);
-
-  withWindowManager = Standard_False;
-
-  win = XCreateWindow(Draw_WindowDisplay, myMother,
-                      winAttr.x, winAttr.y,
-                      winAttr.width, winAttr.height,
-                      2,
-                      CopyFromParent, InputOutput, CopyFromParent,
-                      CWBorderPixel|CWOverrideRedirect|CWBackPixel, &base.xswa);
-
-
-  // adwise to the window manager to place it where I wish
-  XSetWMNormalHints(Draw_WindowDisplay,win,&myHints);
-
-  // all masks of the old window are reassigned to the new one.
-  XSelectInput(Draw_WindowDisplay,win,winAttr.your_event_mask);
+  else
+  {
+    if (myMemHbm)
+    {
+      DeleteObject (myMemHbm);
+      myMemHbm = NULL;
+    }
+  }
+#elif defined(HAVE_XLIB)
+  if (myUseBuffer)
+  {
+    if (myImageBuffer != 0)
+    {
+      XFreePixmap (Draw_WindowDisplay, myImageBuffer);
+    }
+    XWindowAttributes aWinAttr;
+    XGetWindowAttributes (Draw_WindowDisplay, myWindow, &aWinAttr);
+    myImageBuffer = XCreatePixmap (Draw_WindowDisplay, myWindow, aWinAttr.width, aWinAttr.height, aWinAttr.depth);
+  }
+  else if (myImageBuffer != 0)
+  {
+    XFreePixmap (Draw_WindowDisplay, myImageBuffer);
+    myImageBuffer = 0;
+  }
+#endif
 }
 
 //=======================================================================
 //function : SetPosition
 //purpose  :
 //=======================================================================
-void Draw_Window::SetPosition(Standard_Integer NewXpos,
-                              Standard_Integer NewYpos)
+void Draw_Window::SetPosition (Standard_Integer theNewXpos,
+                               Standard_Integer theNewYpos)
 {
-  Standard_Integer x,y;
-  GetPosition(x, y);
-
-  if ( (x != NewXpos) || (y != NewYpos) )
-    XMoveWindow(Draw_WindowDisplay, win, NewXpos, NewYpos);
+#ifdef _WIN32
+  UINT aFlags = SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER;
+  if (Draw_VirtualWindows)
+  {
+    aFlags |= SWP_NOSENDCHANGING;
+  }
+  SetWindowPos (myWindow, 0, theNewXpos, theNewYpos, 0, 0, aFlags);
+#elif defined(HAVE_XLIB)
+  Standard_Integer aPosX = 0, aPosY = 0;
+  GetPosition (aPosX, aPosY);
+  if (aPosX != theNewXpos
+   || aPosY != theNewYpos)
+  {
+    XMoveWindow (Draw_WindowDisplay, myWindow, theNewXpos, theNewYpos);
+  }
+#else
+  (void )theNewXpos;
+  (void )theNewYpos;
+#endif
 }
 
 //=======================================================================
 //function : SetDimension
 //purpose  :
 //=======================================================================
-void Draw_Window::SetDimension(Standard_Integer NewDx,
-                               Standard_Integer NewDy)
+void Draw_Window::SetDimension (Standard_Integer theNewDx,
+                                Standard_Integer theNewDy)
 {
-  if ( (NewDx != WidthWin() ) || (NewDy != HeightWin() ) )
-    XResizeWindow(Draw_WindowDisplay, win, NewDx, NewDy);
+#ifdef _WIN32
+  UINT aFlags = SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER;
+  if (Draw_VirtualWindows)
+  {
+    aFlags |= SWP_NOSENDCHANGING;
+  }
+  SetWindowPos (myWindow, 0, 0, 0, theNewDx, theNewDy, aFlags);
+#elif defined(HAVE_XLIB)
+  if (theNewDx != WidthWin()
+   || theNewDy != HeightWin())
+  {
+    XResizeWindow (Draw_WindowDisplay, myWindow, theNewDx, theNewDy);
+  }
+#else
+  (void )theNewDx;
+  (void )theNewDy;
+#endif
 }
 
 //=======================================================================
 //function : GetPosition
 //purpose  :
 //=======================================================================
-void Draw_Window::GetPosition(Standard_Integer &PosX,
-                              Standard_Integer &PosY)
+void Draw_Window::GetPosition (Standard_Integer& thePosX,
+                               Standard_Integer& thePosY)
 {
-  XWindowAttributes winAttr;
-  XGetWindowAttributes(Draw_WindowDisplay, win, &winAttr);
+  thePosX = thePosY = 0;
+#ifdef _WIN32
+  RECT aRect;
+  GetWindowRect (myWindow, &aRect);
 
-  PosX = winAttr.x;
-  PosY = winAttr.y;
+  POINT aPoint;
+  aPoint.x = aRect.left;
+  aPoint.y = aRect.top;
+
+  ScreenToClient (hWndClientMDI, &aPoint);
+  thePosX = aPoint.x;
+  thePosY = aPoint.y;
+#elif defined(HAVE_XLIB)
+  XWindowAttributes aWinAttr;
+  XGetWindowAttributes (Draw_WindowDisplay, myWindow, &aWinAttr);
+  thePosX = aWinAttr.x;
+  thePosY = aWinAttr.y;
+#endif
 }
 
 //=======================================================================
@@ -496,12 +600,17 @@ void Draw_Window::GetPosition(Standard_Integer &PosX,
 //=======================================================================
 Standard_Integer Draw_Window::HeightWin() const
 {
-  Standard_Integer DY;
-  XWindowAttributes winAttr;
-  XGetWindowAttributes(Draw_WindowDisplay, win, &winAttr);
-
-  DY = winAttr.height;
-  return DY;
+#ifdef _WIN32
+  RECT aRect;
+  GetClientRect (myWindow, &aRect);
+  return aRect.bottom - aRect.top;
+#elif defined(HAVE_XLIB)
+  XWindowAttributes aWinAttr;
+  XGetWindowAttributes (Draw_WindowDisplay, myWindow, &aWinAttr);
+  return aWinAttr.height;
+#else
+  return 1;
+#endif
 }
 
 //=======================================================================
@@ -510,21 +619,33 @@ Standard_Integer Draw_Window::HeightWin() const
 //=======================================================================
 Standard_Integer Draw_Window::WidthWin() const
 {
-  Standard_Integer DX;
-  XWindowAttributes winAttr;
-  XGetWindowAttributes(Draw_WindowDisplay, win, &winAttr);
-
-  DX = winAttr.width;
-  return DX;
+#ifdef _WIN32
+  RECT aRect;
+  GetClientRect (myWindow, &aRect);
+  return aRect.right - aRect.left;
+#elif defined(HAVE_XLIB)
+  XWindowAttributes aWinAttr;
+  XGetWindowAttributes (Draw_WindowDisplay, myWindow, &aWinAttr);
+  return aWinAttr.width;
+#else
+  return 1;
+#endif
 }
 
 //=======================================================================
 //function : SetTitle
 //purpose  :
 //=======================================================================
-void Draw_Window::SetTitle(const TCollection_AsciiString& theTitle)
+void Draw_Window::SetTitle (const TCollection_AsciiString& theTitle)
 {
-  XStoreName (Draw_WindowDisplay, win, theTitle.ToCString());
+#ifdef _WIN32
+  const TCollection_ExtendedString aTitleW (theTitle);
+  SetWindowTextW (myWindow, aTitleW.ToWideString());
+#elif defined(HAVE_XLIB)
+  XStoreName (Draw_WindowDisplay, myWindow, theTitle.ToCString());
+#else
+  (void )theTitle;
+#endif
 }
 
 //=======================================================================
@@ -533,34 +654,43 @@ void Draw_Window::SetTitle(const TCollection_AsciiString& theTitle)
 //=======================================================================
 TCollection_AsciiString Draw_Window::GetTitle() const
 {
+#ifdef _WIN32
+  wchar_t aTitleW[32];
+  GetWindowTextW (myWindow, aTitleW, 30);
+  return TCollection_AsciiString (aTitleW);
+#elif defined(HAVE_XLIB)
   char* aTitle = NULL;
-  XFetchName (Draw_WindowDisplay, win, &aTitle);
+  XFetchName (Draw_WindowDisplay, myWindow, &aTitle);
   return TCollection_AsciiString (aTitle);
-}
-
-//=======================================================================
-//function : GetDrawable
-//purpose  :
-//=======================================================================
-Drawable Draw_Window::GetDrawable() const
-{
-  return myUseBuffer ? myBuffer : win;
+#else
+  return TCollection_AsciiString();
+#endif
 }
 
 //=======================================================================
 //function :DefineColor
 //purpose  :
 //=======================================================================
-Standard_Boolean Draw_Window::DefineColor(const Standard_Integer i, const char* colorName)
+Standard_Boolean Draw_Window::DefineColor (const Standard_Integer theIndex,
+                                           const char* theColorName)
 {
-  XColor color;
-
-  if (!XParseColor(Draw_WindowDisplay,Draw_WindowColorMap,colorName,&color))
+#if defined(HAVE_XLIB)
+  XColor aColor;
+  if (!XParseColor (Draw_WindowDisplay, Draw_WindowColorMap, theColorName, &aColor))
+  {
     return Standard_False;
-  if (!XAllocColor(Draw_WindowDisplay,Draw_WindowColorMap,&color))
+  }
+  if (!XAllocColor (Draw_WindowDisplay, Draw_WindowColorMap, &aColor))
+  {
     return Standard_False;
-  thePixels[i % MAXCOLOR] = color.pixel;
+  }
+  thePixels[theIndex % MAXCOLOR] = aColor.pixel;
   return Standard_True;
+#else
+  (void )theIndex;
+  (void )theColorName;
+  return Standard_True;
+#endif
 }
 
 //=======================================================================
@@ -570,16 +700,24 @@ Standard_Boolean Draw_Window::DefineColor(const Standard_Integer i, const char*
 bool Draw_Window::IsMapped() const
 {
   if (Draw_VirtualWindows
-   || win == 0)
+   || myWindow == 0)
   {
     return false;
   }
 
+#ifdef _WIN32
+  LONG aWinStyle = GetWindowLongW (myWindow, GWL_STYLE);
+  return (aWinStyle & WS_VISIBLE)  != 0
+      && (aWinStyle & WS_MINIMIZE) == 0;
+#elif defined(HAVE_XLIB)
   XFlush (Draw_WindowDisplay);
   XWindowAttributes aWinAttr;
-  XGetWindowAttributes (Draw_WindowDisplay, win, &aWinAttr);
+  XGetWindowAttributes (Draw_WindowDisplay, myWindow, &aWinAttr);
   return aWinAttr.map_state == IsUnviewable
       || aWinAttr.map_state == IsViewable;
+#else
+  return false;
+#endif
 }
 
 //=======================================================================
@@ -592,11 +730,14 @@ void Draw_Window::DisplayWindow()
   {
     return;
   }
-  else
-  {
-    XMapRaised(Draw_WindowDisplay, win);
-  }
-  XFlush(Draw_WindowDisplay);
+
+#ifdef _WIN32
+  ShowWindow (myWindow, SW_SHOW);
+  UpdateWindow (myWindow);
+#elif defined(HAVE_XLIB)
+  XMapRaised (Draw_WindowDisplay, myWindow);
+  XFlush (Draw_WindowDisplay);
+#endif
 }
 
 //=======================================================================
@@ -605,7 +746,11 @@ void Draw_Window::DisplayWindow()
 //=======================================================================
 void Draw_Window::Hide()
 {
-   XUnmapWindow(Draw_WindowDisplay, win);
+#ifdef _WIN32
+  ShowWindow (myWindow, SW_HIDE);
+#elif defined(HAVE_XLIB)
+  XUnmapWindow (Draw_WindowDisplay, myWindow);
+#endif
 }
 
 //=======================================================================
@@ -614,14 +759,18 @@ void Draw_Window::Hide()
 //=======================================================================
 void Draw_Window::Destroy()
 {
-  XFreeGC (Draw_WindowDisplay, base.gc);
-  XDestroyWindow(Draw_WindowDisplay, win);
-  win = 0;
-  if (myBuffer != 0)
+#ifdef _WIN32
+  DestroyWindow (myWindow);
+#elif defined(HAVE_XLIB)
+  XFreeGC (Draw_WindowDisplay, myBase->gc);
+  XDestroyWindow (Draw_WindowDisplay, myWindow);
+  myWindow = 0;
+  if (myImageBuffer != 0)
   {
-    XFreePixmap(Draw_WindowDisplay, myBuffer);
-    myBuffer = 0;
+    XFreePixmap (Draw_WindowDisplay, myImageBuffer);
+    myImageBuffer = 0;
   }
+#endif
 }
 
 //=======================================================================
@@ -630,19 +779,35 @@ void Draw_Window::Destroy()
 //=======================================================================
 void Draw_Window::Clear()
 {
+#ifdef _WIN32
+  HDC hDC = GetDC (myWindow);
+  HDC aWorkDC = myUseBuffer ? getMemDC(hDC) : hDC;
+
+  SaveDC (aWorkDC);
+  SelectObject (aWorkDC, GetStockObject(BLACK_PEN));
+  Rectangle (aWorkDC, 0, 0, WidthWin(), HeightWin());
+  RestoreDC (aWorkDC,-1);
+
+  if (myUseBuffer)
+  {
+    releaseMemDC (aWorkDC);
+  }
+  ReleaseDC (myWindow, hDC);
+#elif defined(HAVE_XLIB)
   if (myUseBuffer)
   {
     // XClearArea only applicable for windows
-    XGCValues currValues;
-    XGetGCValues(Draw_WindowDisplay, base.gc, GCBackground | GCForeground, &currValues);
-    XSetForeground(Draw_WindowDisplay, base.gc, currValues.background);
-    XFillRectangle(Draw_WindowDisplay, myBuffer, base.gc, 0, 0, WidthWin(), HeightWin());
-    XSetForeground(Draw_WindowDisplay, base.gc, currValues.foreground);
+    XGCValues aCurrValues;
+    XGetGCValues (Draw_WindowDisplay, myBase->gc, GCBackground | GCForeground, &aCurrValues);
+    XSetForeground (Draw_WindowDisplay, myBase->gc, aCurrValues.background);
+    XFillRectangle (Draw_WindowDisplay, myImageBuffer, myBase->gc, 0, 0, WidthWin(), HeightWin());
+    XSetForeground (Draw_WindowDisplay, myBase->gc, aCurrValues.foreground);
   }
   else
   {
-    XClearArea(Draw_WindowDisplay, win, 0, 0, 0, 0, False);
+    XClearArea (Draw_WindowDisplay, myWindow, 0, 0, 0, 0, False);
   }
+#endif
 }
 
 //=======================================================================
@@ -651,25 +816,65 @@ void Draw_Window::Clear()
 //=======================================================================
 void Draw_Window::Flush()
 {
-  XFlush(Draw_WindowDisplay);
+#if defined(HAVE_XLIB)
+  XFlush (Draw_WindowDisplay);
+#endif
 }
 
 //=======================================================================
 //function : DrawString
 //purpose  :
 //=======================================================================
-void Draw_Window::DrawString(int X, int Y, char *text)
+void Draw_Window::DrawString (Standard_Integer theX, Standard_Integer theY,
+                              const char* theText)
 {
-  XDrawString(Draw_WindowDisplay, GetDrawable(), base.gc, X, Y, text, strlen(text));
+#ifdef _WIN32
+  HDC hDC = GetDC (myWindow);
+  HDC aWorkDC = myUseBuffer ? getMemDC(hDC) : hDC;
+
+  const TCollection_ExtendedString aTextW (theText);
+  TextOutW (aWorkDC, theX, theY, aTextW.ToWideString(), aTextW.Length());
+
+  if (myUseBuffer)
+  {
+    releaseMemDC (aWorkDC);
+  }
+  ReleaseDC (myWindow, hDC);
+#elif defined(HAVE_XLIB)
+  XDrawString (Draw_WindowDisplay, GetDrawable(), myBase->gc, theX, theY, (char* )theText, strlen(theText));
+#else
+  //
+#endif
 }
 
 //=======================================================================
 //function : DrawSegments
 //purpose  :
 //=======================================================================
-void Draw_Window::DrawSegments(Segment *tab, int nbElem)
+void Draw_Window::DrawSegments (const Draw_XSegment* theSegments,
+                                Standard_Integer theNbElems)
 {
-  XDrawSegments(Draw_WindowDisplay, GetDrawable(), base.gc, (XSegment*) tab, nbElem);
+#ifdef _WIN32
+  HDC hDC = GetDC (myWindow);
+  HDC aWorkDC = myUseBuffer ? getMemDC(hDC) : hDC;
+  for (int aSegIter = 0; aSegIter < theNbElems; ++aSegIter)
+  {
+    const Draw_XSegment& aSeg = theSegments[aSegIter];
+    MoveToEx(aWorkDC, aSeg[0].x(), aSeg[0].y(), NULL);
+    LineTo  (aWorkDC, aSeg[1].x(), aSeg[1].y());
+  }
+  if (myUseBuffer)
+  {
+    releaseMemDC (aWorkDC);
+  }
+  ReleaseDC (myWindow, hDC);
+#elif defined(HAVE_XLIB)
+  Standard_STATIC_ASSERT(sizeof(Draw_XSegment) == sizeof(XSegment));
+  XDrawSegments (Draw_WindowDisplay, GetDrawable(), myBase->gc, (XSegment* )theSegments, theNbElems);
+#else
+  (void )theSegments;
+  (void )theNbElems;
+#endif
 }
 
 //=======================================================================
@@ -678,1075 +883,70 @@ void Draw_Window::DrawSegments(Segment *tab, int nbElem)
 //=======================================================================
 void Draw_Window::Redraw()
 {
-  if (myUseBuffer) {
-    XCopyArea (Draw_WindowDisplay,
-               myBuffer, win, // source, destination Drawables
-               base.gc,
-               0, 0,  // source x, y
-               WidthWin(), HeightWin(),
-               0, 0); // destination x, y
+#ifdef _WIN32
+  if (myUseBuffer)
+  {
+    HDC hDC = GetDC (myWindow);
+    RECT aRect;
+    GetClientRect (myWindow, &aRect);
+    HDC aMemDC = getMemDC (hDC);
+    BitBlt (hDC,
+            aRect.left, aRect.top,
+            aRect.right - aRect.left, aRect.bottom - aRect.top,
+            aMemDC,
+            0, 0, SRCCOPY);
+    releaseMemDC (aMemDC);
+    ReleaseDC (myWindow, hDC);
   }
+#elif defined(HAVE_XLIB)
+  if (myUseBuffer)
+  {
+    XCopyArea (Draw_WindowDisplay,
+               myImageBuffer, myWindow,
+               myBase->gc,
+               0, 0,
+               WidthWin(), HeightWin(),
+               0, 0);
+  }
+#endif
 }
 
 //=======================================================================
 //function : SetColor
 //purpose  :
 //=======================================================================
-void Draw_Window::SetColor(Standard_Integer color)
+void Draw_Window::SetColor (Standard_Integer theColor)
 {
-  XSetForeground(Draw_WindowDisplay, base.gc, thePixels[color]);
+#ifdef _WIN32
+  HDC hDC = GetDC (myWindow);
+  myCurrPen = theColor;
+  SelectObject (hDC, Draw_colorPenTab[theColor]);
+  ReleaseDC (myWindow, hDC);
+#elif defined(HAVE_XLIB)
+  XSetForeground (Draw_WindowDisplay, myBase->gc, thePixels[theColor]);
+#endif
+  myCurrentColor = theColor;
 }
 
 //=======================================================================
 //function : SetMode
 //purpose  :
 //=======================================================================
-void Draw_Window::SetMode( int mode)
+void Draw_Window::SetMode (int theMode)
 {
-  XSetFunction(Draw_WindowDisplay, base.gc, mode);
-}
-
-//=======================================================================
-//function : Save
-//purpose  :
-//=======================================================================
-Standard_Boolean Draw_Window::Save (const char* theFileName) const
-{
-  // make sure all draw operations done
-  XSync (Draw_WindowDisplay, True);
-
-  // the attributes
-  XWindowAttributes winAttr;
-  XGetWindowAttributes (Draw_WindowDisplay, win, &winAttr);
-
-  if (!myUseBuffer)
-  {
-    // make sure that the whole window fit on display to prevent BadMatch error
-    XWindowAttributes winAttrRoot;
-    XGetWindowAttributes (Draw_WindowDisplay, XRootWindowOfScreen (winAttr.screen), &winAttrRoot);
-
-    Window winChildDummy;
-    int winLeft = 0;
-    int winTop = 0;
-    XTranslateCoordinates (Draw_WindowDisplay, win, XRootWindowOfScreen (winAttr.screen),
-                           0, 0, &winLeft, &winTop, &winChildDummy);
-
-    if (((winLeft + winAttr.width) > winAttrRoot.width)  || winLeft < winAttrRoot.x ||
-        ((winTop + winAttr.height) > winAttrRoot.height) || winTop  < winAttrRoot.y)
-    {
-      std::cerr << "The window not fully visible! Can't create the snapshot.\n";
-      return Standard_False;
-    }
-  }
-
-  XVisualInfo aVInfo;
-  if (XMatchVisualInfo (Draw_WindowDisplay, Draw_WindowScreen, 32, TrueColor, &aVInfo) == 0
-   && XMatchVisualInfo (Draw_WindowDisplay, Draw_WindowScreen, 24, TrueColor, &aVInfo) == 0)
-  {
-    std::cerr << "24-bit TrueColor visual is not supported by server!\n";
-    return Standard_False;
-  }
-
-  Image_AlienPixMap anImage;
-  bool isBigEndian = Image_PixMap::IsBigEndianHost();
-  const Standard_Size aSizeRowBytes = Standard_Size(winAttr.width) * 4;
-  if (!anImage.InitTrash (isBigEndian ? Image_Format_RGB32 : Image_Format_BGR32,
-                          Standard_Size(winAttr.width), Standard_Size(winAttr.height), aSizeRowBytes))
-  {
-    return Standard_False;
-  }
-  anImage.SetTopDown (true);
-
-  XImage* anXImage = XCreateImage (Draw_WindowDisplay, aVInfo.visual,
-                                   32, ZPixmap, 0, (char* )anImage.ChangeData(), winAttr.width, winAttr.height, 32, int(aSizeRowBytes));
-  anXImage->bitmap_bit_order = anXImage->byte_order = (isBigEndian ? MSBFirst : LSBFirst);
-  if (XGetSubImage (Draw_WindowDisplay, GetDrawable(),
-                    0, 0, winAttr.width, winAttr.height,
-                    AllPlanes, ZPixmap, anXImage, 0, 0) == NULL)
-  {
-    anXImage->data = NULL;
-    XDestroyImage (anXImage);
-    return Standard_False;
-  }
-
-  // destroy the image
-  anXImage->data = NULL;
-  XDestroyImage (anXImage);
-
-  // save the image
-  return anImage.Save (theFileName);
-}
-
-//=======================================================================
-//function : Wait
-//purpose  :
-//=======================================================================
-
-void Draw_Window::Wait (Standard_Boolean wait)
-{
-  Flush();
-  if (!wait) {
-    XSelectInput(Draw_WindowDisplay,win,
-                 ButtonPressMask|ExposureMask | StructureNotifyMask |
-                 PointerMotionMask);
-  }
-  else {
-    XSelectInput(Draw_WindowDisplay,win,
-                 ButtonPressMask|ExposureMask | StructureNotifyMask);
-  }
-}
-
-//=======================================================================
-//function : ProcessEvent
-//purpose  :
-//=======================================================================
-
-void ProcessEvent(Draw_Window& win, XEvent& xev)
-{
-  Standard_Integer X,Y,button;
-  KeySym keysym;
-  XComposeStatus stat;
-  char chainekey[10];
-
-  switch (xev.type)
-  {
-  case ClientMessage:
-  {
-    if (xev.xclient.data.l[0] == (int )Draw_DisplayConnection->GetAtom (Aspect_XA_DELETE_WINDOW))
-    {
-      // just hide the window
-      win.Hide();
-    }
-    return;
-  }
-  case Expose :
-    win.WExpose();
-    break;
-
-  case ButtonPress :
-    X = xev.xbutton.x;
-    Y = xev.xbutton.y;
-    button = xev.xbutton.button;
-    win.WButtonPress(X,Y,button);
-    break;
-
-  case ButtonRelease :
-    X = xev.xbutton.x;
-    Y = xev.xbutton.y;
-    button = xev.xbutton.button;
-    win.WButtonRelease(X,Y,button);
-    break;
-
-  case KeyPress :
-    XLookupString(&(xev.xkey),
-                         chainekey,
-                         10,
-                         &keysym,
-                         &stat);
-    break;
-
-  case MotionNotify :
-    X = xev.xmotion.x;
-    Y = xev.xmotion.y;
-    win.WMotionNotify(X,Y);
-    break;
-
-  case ConfigureNotify :
-    if (win.withWindowManager)
-      win.WConfigureNotify(xev.xconfigure.x, xev.xconfigure.y,
-                           xev.xconfigure.width,
-                           xev.xconfigure.height);
-    break;
-
-  case UnmapNotify :
-
-    win.WUnmapNotify();
-    break;
-  }
-}
-
-//=======================================================================
-//function : WExpose
-//purpose  :
-//=======================================================================
-void Draw_Window::WExpose()
-{
-}
-
-//=======================================================================
-//function : WButtonPress
-//purpose  :
-//=======================================================================
-void Draw_Window::WButtonPress(const Standard_Integer,
-                               const Standard_Integer,
-                               const Standard_Integer&)
-{
-}
-
-//=======================================================================
-//function : WButtonRelease
-//purpose  :
-//=======================================================================
-void Draw_Window::WButtonRelease(const Standard_Integer,
-                                 const Standard_Integer,
-                                 const Standard_Integer&)
-{
-}
-
-/**************************
-//=======================================================================
-//function : WKeyPress
-//purpose  :
-//=======================================================================
-
-void Draw_Window::WKeyPress(char, KeySym&)
-{
-}
-***************************/
-
-//=======================================================================
-//function : WMotionNotify
-//purpose  :
-//=======================================================================
-void Draw_Window::WMotionNotify(const Standard_Integer ,
-                                const Standard_Integer )
-{
-}
-
-//=======================================================================
-//function : WConfigureNotify
-//purpose  :
-//=======================================================================
-
-void Draw_Window::WConfigureNotify(const Standard_Integer,
-                                   const Standard_Integer,
-                                   const Standard_Integer,
-                                   const Standard_Integer)
-{
-}
-
-//=======================================================================
-//function : WUnmapNotify
-//purpose  :
-//=======================================================================
-void Draw_Window::WUnmapNotify()
-{
-}
-
-//======================================================
-// function : ProcessEvents
-// purpose  : process pending X events
-//======================================================
-static void ProcessEvents(ClientData,int)
-{
-  // test for X Event
-  while (XPending (Draw_WindowDisplay))
-  {
-    XEvent anEvent = {};
-    XNextEvent (Draw_WindowDisplay, &anEvent);
-
-    // search the window in the window list
-    bool isFound = false;
-    for (Draw_Window* aWinIter = Draw_Window::firstWindow; aWinIter != NULL; aWinIter = aWinIter->next)
-    {
-      if (anEvent.xany.window == aWinIter->win)
-      {
-        ProcessEvent (*aWinIter, anEvent);
-        isFound = true;
-        break;
-      }
-    }
-    if (!isFound)
-    {
-    #ifdef _TK
-      Tk_HandleEvent (&anEvent);
-    #endif
-    }
-  }
-}
-
-//======================================================
-// function : GetNextEvent()
-// purpose :
-//======================================================
-void GetNextEvent(Event& ev)
-{
-  XEvent xev;
-  XNextEvent(Draw_WindowDisplay, &xev);
-  switch(xev.type)
-  {
-    case ButtonPress :
-      ev.type = 4;
-      ev.window = xev.xbutton.window;
-      ev.button = xev.xbutton.button;
-      ev.x = xev.xbutton.x;
-      ev.y = xev.xbutton.y;
-      break;
-
-    case MotionNotify :
-      ev.type = 6;
-      ev.window = xev.xmotion.window;
-      ev.button = 0;
-      ev.x = xev.xmotion.x;
-      ev.y = xev.xmotion.y;
-      break;
-  }
-}
-#endif //__APPLE__
-
-//======================================================
-// function :Run_Appli
-// purpose :
-//======================================================
-static Standard_Boolean(*Interprete) (const char*);
-
-void Run_Appli(Standard_Boolean (*interprete) (const char*))
-{
-  Interprete = interprete;
-
-  // Commands will come from standard input, so set up an event handler for standard input.
-  // If the input device is aEvaluate the .rc file, if one has been specified,
-  // set up an event handler for standard input, and print a prompt if the input device is a terminal.
-  Tcl_Channel anInChannel = Tcl_GetStdChannel(TCL_STDIN);
-  if (anInChannel)
-  {
-    Tcl_CreateChannelHandler (anInChannel, TCL_READABLE, StdinProc, (ClientData )anInChannel);
-  }
-
-  // Create a handler for the draw display
-#if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
-  Tcl_CreateFileHandler (ConnectionNumber(Draw_WindowDisplay), TCL_READABLE, ProcessEvents, (ClientData) 0);
-#endif // __APPLE__
-
-  Draw_Interpretor& aCommands = Draw::GetInterpretor();
-
-  if (tty) { Prompt (aCommands.Interp(), 0); }
-  Prompt (aCommands.Interp(), 0);
-
-  Tcl_Channel anOutChannel = Tcl_GetStdChannel(TCL_STDOUT);
-  if (anOutChannel)
-  {
-    Tcl_Flush (anOutChannel);
-  }
-  Tcl_DStringInit (&command);
-
-#ifdef _TK
-  if (Draw_VirtualWindows)
-  {
-    // main window will never shown
-    // but main loop will parse all Xlib messages
-    Tcl_Eval(aCommands.Interp(), "wm withdraw .");
-  }
-  // Loop infinitely, waiting for commands to execute.
-  // When there are no windows left, Tk_MainLoop returns and we exit.
-  Tk_MainLoop();
+#ifdef _WIN32
+  HDC hDC = GetDC (myWindow);
+  myCurrMode = theMode;
+  SetROP2 (hDC, Draw_modeTab[theMode]);
+  ReleaseDC (myWindow, hDC);
+#elif defined(HAVE_XLIB)
+  XSetFunction (Draw_WindowDisplay, myBase->gc, theMode);
 #else
-  for (;;)
-  {
-    Tcl_DoOneEvent (0); // practically the same as Tk_MainLoop()
-  }
+  (void )theMode;
 #endif
-
-  for (NCollection_List<Draw_Window::FCallbackBeforeTerminate>::Iterator anIter (MyCallbacks);
-       anIter.More(); anIter.Next())
-  {
-    (*anIter.Value())();
-  }
-}
-
-//======================================================
-// function : Init_Appli()
-// purpose  :
-//======================================================
-Standard_Boolean Init_Appli()
-{
-  Draw_Interpretor& aCommands = Draw::GetInterpretor();
-  aCommands.Init();
-  Tcl_Interp *interp = aCommands.Interp();
-  Tcl_Init (interp);
-
-#ifdef _TK
-  try
-  {
-    OCC_CATCH_SIGNALS
-    Tk_Init (interp);
-  }
-  catch (Standard_Failure const& theFail)
-  {
-    Message::SendFail() << "TK_Init() failed with " << theFail;
-  }
-
-  Tcl_StaticPackage(interp, "Tk", Tk_Init, (Tcl_PackageInitProc *) NULL);
-
-  Tk_Window aMainWindow = Tk_MainWindow(interp) ;
-  if (aMainWindow == NULL) {
-#if ((TCL_MAJOR_VERSION > 8) || ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 5)))
-    fprintf(stderr, "%s\n", Tcl_GetStringResult(interp));
-#else
-    fprintf(stderr, "%s\n", interp->result);
-#endif
-    exit(1);
-  }
-#if defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-  Tk_SetAppName(aMainWindow, "Draw");
-#else
-  Tk_Name(aMainWindow) = Tk_GetUid(Tk_SetAppName(aMainWindow, "Draw"));
-#endif
-
-  Tk_GeometryRequest (aMainWindow, 200, 200);
-#endif
-
-#if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
-  if (Draw_DisplayConnection.IsNull())
-  {
-    try
-    {
-      Draw_DisplayConnection = new Aspect_DisplayConnection();
-    }
-    catch (Standard_Failure const& theFail)
-    {
-      std::cout << "Cannot open display (" << theFail << "). Interpret commands in batch mode." << std::endl;
-      return Standard_False;
-    }
-  }
-  if (Draw_WindowDisplay == NULL)
-  {
-    Draw_WindowDisplay = Draw_DisplayConnection->GetDisplay();
-  }
-  //
-  // synchronize the display server : could be done within Tk_Init
-  //
-  XSynchronize(Draw_WindowDisplay, True);
-  XSetInputFocus(Draw_WindowDisplay,
-                 PointerRoot,
-                 RevertToPointerRoot,
-                 CurrentTime);
-
-  Draw_WindowScreen   = DefaultScreen(Draw_WindowDisplay);
-  Draw_WindowColorMap = DefaultColormap(Draw_WindowDisplay,
-                                        Draw_WindowScreen);
-#endif // __APPLE__
-
-  tty = isatty(0);
-  Tcl_SetVar(interp,"tcl_interactive",(char*)(tty ? "1" : "0"), TCL_GLOBAL_ONLY);
-//  Tcl_SetVar(interp,"tcl_interactive",tty ? "1" : "0", TCL_GLOBAL_ONLY);
-  return Standard_True;
-}
-
-//======================================================
-// function : Destroy_Appli()
-// purpose  :
-//======================================================
-void Destroy_Appli()
-{
-  //XCloseDisplay(Draw_WindowDisplay);
-}
-
-/*
- *----------------------------------------------------------------------
- *
- * StdinProc --
- *
- *        This procedure is invoked by the event dispatcher whenever
- *        standard input becomes readable.  It grabs the next line of
- *        input characters, adds them to a command being assembled, and
- *        executes the command if it's complete.
- *
- * Results:
- *        None.
- *
- * Side effects:
- *        Could be almost arbitrary, depending on the command that's
- *        typed.
- *
- *----------------------------------------------------------------------
- */
-
-    /* ARGSUSED */
-//static void StdinProc(ClientData clientData, int mask)
-static void StdinProc(ClientData clientData, int )
-{
-  static int gotPartial = 0;
-  char *cmd;
-//  int code, count;
-  int count;
-  Tcl_Channel chan = (Tcl_Channel) clientData;
-
-  // MSV Nov 2, 2001: patch for TCL 8.3: initialize line to avoid exception
-  //                  when first user input is an empty string
-  Tcl_DStringFree(&line);
-  count = Tcl_Gets(chan, &line);
-
-  // MKV 26.05.05
-#if ((TCL_MAJOR_VERSION > 8) || ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 4)))
-  Tcl_DString linetmp;
-  Tcl_DStringInit(&linetmp);
-  Tcl_UniChar * UniCharString;
-  UniCharString = Tcl_UtfToUniCharDString(Tcl_DStringValue(&line),-1,&linetmp);
-  Standard_Integer l = Tcl_UniCharLen(UniCharString);
-  TCollection_AsciiString AsciiString("");
-  Standard_Character Character;
-  Standard_Integer i;
-  for (i=0; i<l; i++) {
-    Character = UniCharString[i];
-    AsciiString.AssignCat(Character);
-  }
-  Tcl_DStringInit(&line);
-  Tcl_DStringAppend(&line, AsciiString.ToCString(), -1);
-#endif
-  if (count < 0) {
-    if (!gotPartial) {
-      if (tty) {
-        Tcl_Exit(0);
-      } else {
-        Tcl_DeleteChannelHandler(chan, StdinProc, (ClientData) chan);
-      }
-      return;
-    } else {
-      count = 0;
-    }
-  }
-
-  (void) Tcl_DStringAppend(&command, Tcl_DStringValue(&line), -1);
-  cmd = Tcl_DStringAppend(&command, "\n", -1);
-  Tcl_DStringFree(&line);
-  try {
-    OCC_CATCH_SIGNALS
-  if (!Tcl_CommandComplete(cmd)) {
-    gotPartial = 1;
-    goto prompt;
-  }
-  gotPartial = 0;
-
-  /*
-   * Disable the stdin channel handler while evaluating the command;
-   * otherwise if the command re-enters the event loop we might
-   * process commands from stdin before the current command is
-   * finished.  Among other things, this will trash the text of the
-   * command being evaluated.
-   */
-
-  Tcl_CreateChannelHandler(chan, 0, StdinProc, (ClientData) chan);
-
-
-  /*
-   * Disable the stdin file handler while evaluating the command;
-   * otherwise if the command re-enters the event loop we might
-   * process commands from stdin before the current command is
-   * finished.  Among other things, this will trash the text of the
-   * command being evaluated.
-   */
-
-#ifdef _TK
-   //  Tk_CreateFileHandler(0, 0, StdinProc, (ClientData) 0);
-#endif
-    //
-    // xab average to avoid an output SIGBUS of DRAW
-    // to ultimately prescise or remove once
-    // the problem of free on the global variable at the average
-    //
-    //
-
-  Interprete(cmd);
-
-
-  Tcl_CreateChannelHandler(chan, TCL_READABLE, StdinProc,
-                           (ClientData) chan);
-  Tcl_DStringFree(&command);
-
-  /*
-   * Output a prompt.
-   */
-
-prompt:
-  if (tty) Prompt(Draw::GetInterpretor().Interp(), gotPartial);
-
- } catch (Standard_Failure const&) {}
-
-}
-
-#else
-
-// Source Specifique WNT
-
-/****************************************************\
-*  Draw_Window.cxx :
-*
-\****************************************************/
-
-#include "Draw_Window.hxx"
-#include "DrawRessource.h"
-#include "init.h"
-
-#include <Draw_Appli.hxx>
-#include <OSD.hxx>
-
-#ifdef HAVE_TK
-  #include <tk.h>
-#endif
-
-#define PENWIDTH 1
-#define CLIENTWND 0
-// Position of information in the extra memory
-
-// indicates SUBSYSTEM:CONSOLE linker option, to be set to True in main()
-Standard_EXPORT
-Standard_Boolean Draw_IsConsoleSubsystem = Standard_False;
-
-
-Standard_Boolean Draw_BlackBackGround = Standard_True;
-
-// Creation of color stylos
-HPEN colorPenTab[MAXCOLOR] = {CreatePen(PS_SOLID, PENWIDTH, RGB(255,255,255)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(255,0,0)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(0,255,0)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(0,0,255)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(0,255,255)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(255,215,0)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(255,0,255)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(255,52,179)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(255,165,0)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(255,228,225)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(255,160,122)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(199,21,133)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(255,255,0)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(240,230,140)),
-                              CreatePen(PS_SOLID, PENWIDTH, RGB(255,127,80))};
-
-// Correspondence mode X11 and WINDOWS NT
-int modeTab[16] = {R2_BLACK, R2_MASKPEN, R2_MASKPENNOT, R2_COPYPEN,
-                   R2_MASKNOTPEN, R2_NOP, R2_XORPEN, R2_MERGEPEN,
-                   R2_NOTMASKPEN, R2_NOTXORPEN, R2_NOT, R2_MERGEPENNOT,
-                   R2_NOTCOPYPEN, R2_MERGENOTPEN, R2_NOTMERGEPEN, R2_WHITE};
-
-/*--------------------------------------------------------*\
-|  CREATE DRAW WINDOW PROCEDURE
-\*--------------------------------------------------------*/
-HWND DrawWindow::CreateDrawWindow(HWND hWndClient, int nitem)
-{
-  if (Draw_IsConsoleSubsystem) {
-    HWND aWin = CreateWindowW (DRAWCLASS, DRAWTITLE,
-                              WS_OVERLAPPEDWINDOW,
-                              1,1,1,1,
-                              NULL, NULL,::GetModuleHandle(NULL), NULL);
-    if (!Draw_VirtualWindows)
-    {
-      SetWindowPos(aWin, HWND_TOPMOST, 1,1,1,1, SWP_NOMOVE);
-      SetWindowPos(aWin, HWND_NOTOPMOST, 1,1,1,1, SWP_NOMOVE);
-    }
-    return aWin;
-  }
-  else {
-    HANDLE hInstance = (HANDLE )GetWindowLongPtrW (hWndClient, GWLP_HINSTANCE);
-
-    return CreateMDIWindowW(DRAWCLASS, DRAWTITLE,
-                           WS_CAPTION | WS_CHILD | WS_THICKFRAME,
-                           1,1,0,0,
-                           hWndClient, (HINSTANCE)hInstance, nitem);
-  }
-}
-
-
-/*--------------------------------------------------------*\
-|  DRAW WINDOW PROCEDURE
-\*--------------------------------------------------------*/
-LRESULT APIENTRY DrawWindow::DrawProc(HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam )
-{
-  DrawWindow* localObjet = (DrawWindow* )GetWindowLongPtrW (hWnd, CLIENTWND);
-  if (!localObjet)
-  {
-    return Draw_IsConsoleSubsystem
-         ? DefWindowProcW   (hWnd, wMsg, wParam, lParam)
-         : DefMDIChildProcW (hWnd, wMsg, wParam, lParam);
-  }
-
-  switch (wMsg)
-  {
-    case WM_CLOSE:
-    {
-      localObjet->Hide();
-      return 0; // do nothing - window destruction should be performed by application
-    }
-    case WM_PAINT:
-    {
-      PAINTSTRUCT ps;
-      BeginPaint (hWnd, &ps);
-      if (localObjet->GetUseBuffer())
-      {
-        localObjet->Redraw();
-      }
-      else
-      {
-        localObjet->WExpose();
-      }
-      EndPaint (hWnd, &ps);
-      return 0;
-    }
-    case WM_SIZE:
-    {
-      if (localObjet->GetUseBuffer())
-      {
-        localObjet->InitBuffer();
-        localObjet->WExpose();
-        localObjet->Redraw();
-        return 0;
-      }
-      break;
-    }
-  }
-  return Draw_IsConsoleSubsystem
-       ? DefWindowProcW   (hWnd, wMsg, wParam, lParam)
-       : DefMDIChildProcW (hWnd, wMsg, wParam, lParam);
-}
-
-
-
-/*
-**  IMPLEMENTATION of the CLASS DRAWWINDOW
- */
-
-/*--------------------------------------------------------*\
-| Initialization of static variables of DrawWindow
-\*--------------------------------------------------------*/
-
-DrawWindow* DrawWindow::firstWindow = NULL;
-HWND DrawWindow::hWndClientMDI = 0;
-
-/*--------------------------------------------------------*\
-| Constructors of Draw_Window
-\*--------------------------------------------------------*/
-
-// Default Constructor
-//________________________
-DrawWindow::DrawWindow() :
-        win(0),
-        next(firstWindow),
-        previous(NULL),
-        myMemHbm(NULL),
-        myUseBuffer(Standard_False),
-        myCurrPen(0),
-        myCurrMode(0)
-{
-  if (firstWindow) firstWindow->previous = this;
-  firstWindow = this;
-}
-
-//________________________
-DrawWindow::DrawWindow(const char* title,
-                       Standard_Integer X, Standard_Integer Y,
-                       Standard_Integer dX,Standard_Integer dY) :
-       win(0),        next(firstWindow), previous(NULL), myMemHbm(NULL), myUseBuffer(Standard_False)
-{
-  if (firstWindow) firstWindow->previous = this;
-  firstWindow = this;
-  Init(X, Y, dX, dY);
-  SetTitle(title);
-}
-DrawWindow::DrawWindow(const char* title,
-                       Standard_Integer X, Standard_Integer Y,
-                       Standard_Integer dX,Standard_Integer dY,
-                       HWND theWin) :
-       win(theWin),next(firstWindow), previous(NULL), myMemHbm(NULL), myUseBuffer(Standard_False)
-{
-  if (firstWindow) firstWindow->previous = this;
-  firstWindow = this;
-  Init(X, Y, dX, dY);
-  SetTitle(title);
-}
-
-
-
-/*--------------------------------------------------------*\
-| Destructor of DrawWindow
-\*--------------------------------------------------------*/
-DrawWindow::~DrawWindow()
-{
-  if (previous)
-    previous->next = next;
-  else
-    firstWindow = next;
-  if (next)
-    next->previous = previous;
-
-  // Delete 'off-screen drawing'-related objects
-  if (myMemHbm) {
-    DeleteObject(myMemHbm);
-    myMemHbm = NULL;
-  }
-}
-
-
-
-/*--------------------------------------------------------*\
-|  Init
-\*--------------------------------------------------------*/
-void DrawWindow::Init(Standard_Integer theXLeft, Standard_Integer theYTop,
-                      Standard_Integer theWidth, Standard_Integer theHeight)
-{
-  if (win == NULL)
-  {
-    win = CreateDrawWindow(hWndClientMDI, 0);
-  }
-
-  // include decorations in the window dimensions
-  // to reproduce same behaviour of Xlib window.
-  DWORD aWinStyle   = GetWindowLongW (win, GWL_STYLE);
-  DWORD aWinStyleEx = GetWindowLongW (win, GWL_EXSTYLE);
-  HMENU aMenu       = GetMenu (win);
-
-  RECT aRect;
-  aRect.top    = theYTop;
-  aRect.bottom = theYTop + theHeight;
-  aRect.left   = theXLeft;
-  aRect.right  = theXLeft + theWidth;
-  AdjustWindowRectEx (&aRect, aWinStyle, aMenu != NULL ? TRUE : FALSE, aWinStyleEx);
-
-  SetPosition  (aRect.left, aRect.top);
-  SetDimension (aRect.right - aRect.left, aRect.bottom - aRect.top);
-  // Save the pointer at the instance associated to the window
-  SetWindowLongPtrW (win, CLIENTWND, (LONG_PTR)this);
-  HDC hDC = GetDC(win);
-  SetBkColor(hDC, RGB(0, 0, 0));
-  myCurrPen  = 3;
-  myCurrMode = 3;
-  SelectObject(hDC, colorPenTab[myCurrPen]); // Default pencil
-  SelectObject(hDC, GetStockObject(BLACK_BRUSH));
-  SetTextColor(hDC, RGB(0,0,255));
-  ReleaseDC(win, hDC);
-
-  if (Draw_VirtualWindows)
-  {
-    // create a virtual window
-    SetUseBuffer (Standard_True);
-  }
-}
-
-/*--------------------------------------------------------*\
-|  SetUseBuffer
-\*--------------------------------------------------------*/
-void DrawWindow::SetUseBuffer(Standard_Boolean use)
-{
-  myUseBuffer = use;
-  InitBuffer();
-}
-
-/*--------------------------------------------------------*\
-|  InitBuffer
-\*--------------------------------------------------------*/
-void DrawWindow::InitBuffer()
-{
-  if (myUseBuffer) {
-    RECT rc;
-    HDC hDC = GetDC(win);
-    GetClientRect(win, &rc);
-    if (myMemHbm) {
-      BITMAP aBmp;
-      GetObjectW (myMemHbm, sizeof(BITMAP), &aBmp);
-      if (rc.right-rc.left == aBmp.bmWidth && rc.bottom-rc.top == aBmp.bmHeight) return;
-      DeleteObject(myMemHbm);
-    }
-    myMemHbm = (HBITMAP)CreateCompatibleBitmap(hDC,
-                                      rc.right-rc.left,
-                                      rc.bottom-rc.top);
-    HDC aMemDC      = GetMemDC(hDC);
-    FillRect(aMemDC, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH));
-    ReleaseMemDC(aMemDC);
-    ReleaseDC(win, hDC);
-  }
-  else {
-    if (myMemHbm) {
-      DeleteObject(myMemHbm);
-      myMemHbm = NULL;
-    }
-  }
-}
-
-/*--------------------------------------------------------*\
-|  GetMemDC
-\*--------------------------------------------------------*/
-HDC DrawWindow::GetMemDC(HDC theWinDC)
-{
-  if (!myUseBuffer) return NULL;
-
-  HDC aWorkDC = CreateCompatibleDC(theWinDC);
-  myOldHbm = (HBITMAP)SelectObject(aWorkDC, myMemHbm);
-  SetROP2(aWorkDC, modeTab[myCurrMode]);
-  SelectObject(aWorkDC, colorPenTab[myCurrPen]);
-  SetBkColor(aWorkDC, RGB(0, 0, 0));
-  SelectObject(aWorkDC, GetStockObject(BLACK_BRUSH));
-  SetTextColor(aWorkDC, RGB(0,0,255));
-  return aWorkDC;
-}
-
-
-/*--------------------------------------------------------*\
-|  ReleaseMemDC
-\*--------------------------------------------------------*/
-void DrawWindow::ReleaseMemDC(HDC theMemDC)
-{
-  if (!myUseBuffer || !theMemDC) return;
-
-  if (myOldHbm) SelectObject(theMemDC, myOldHbm);
-  DeleteDC(theMemDC);
-}
-
-
-/*--------------------------------------------------------*\
-|  SetPosition
-\*--------------------------------------------------------*/
-void DrawWindow::SetPosition(Standard_Integer posX, Standard_Integer posY)
-{
-  UINT aFlags = SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER;
-  if (Draw_VirtualWindows)
-  {
-    aFlags |= SWP_NOSENDCHANGING;
-  }
-  SetWindowPos (win, 0, posX, posY, 0, 0, aFlags);
-}
-
-
-/*--------------------------------------------------------*\
-|  SetDimension
-\*--------------------------------------------------------*/
-void DrawWindow::SetDimension(Standard_Integer dimX, Standard_Integer dimY)
-{
-  UINT aFlags = SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER;
-  if (Draw_VirtualWindows)
-  {
-    aFlags |= SWP_NOSENDCHANGING;
-  }
-  SetWindowPos (win, 0, 0, 0, dimX, dimY, aFlags);
-}
-
-
-/*--------------------------------------------------------*\
-|  GetPosition
-\*--------------------------------------------------------*/
-void DrawWindow::GetPosition(Standard_Integer &dimX,
-                             Standard_Integer &dimY)
-{
-  RECT rect;
-  GetWindowRect(win, &rect);
-
-  POINT point;
-  point.x = rect.left;
-  point.y = rect.top;
-
-  ScreenToClient(hWndClientMDI, &point);
-  dimX = point.x;
-  dimY = point.y;
-}
-
-
-/*--------------------------------------------------------*\
-|  HeightWin
-\*--------------------------------------------------------*/
-Standard_Integer DrawWindow::HeightWin() const
-{
-  RECT rect;
-  GetClientRect(win, &rect);
-  return(rect.bottom-rect.top);
-}
-
-
-/*--------------------------------------------------------*\
-|  WidthWin
-\*--------------------------------------------------------*/
-Standard_Integer DrawWindow::WidthWin() const
-{
-  RECT rect;
-  GetClientRect(win, &rect);
-  return(rect.right-rect.left);
-}
-
-
-/*--------------------------------------------------------*\
-|  SetTitle
-\*--------------------------------------------------------*/
-void DrawWindow::SetTitle (const TCollection_AsciiString& theTitle)
-{
-  const TCollection_ExtendedString aTitleW (theTitle);
-  SetWindowTextW (win, aTitleW.ToWideString());
-}
-
-
-/*--------------------------------------------------------*\
-|  GetTitle
-\*--------------------------------------------------------*/
-TCollection_AsciiString DrawWindow::GetTitle() const
-{
-  wchar_t aTitleW[32];
-  GetWindowTextW (win, aTitleW, 30);
-  return TCollection_AsciiString (aTitleW);
-}
-
-//=======================================================================
-//function : IsMapped
-//purpose  :
-//=======================================================================
-bool Draw_Window::IsMapped() const
-{
-  if (Draw_VirtualWindows
-   || win == NULL)
-  {
-    return false;
-  }
-
-  LONG aWinStyle = GetWindowLongW (win, GWL_STYLE);
-  return (aWinStyle & WS_VISIBLE)  != 0
-      && (aWinStyle & WS_MINIMIZE) == 0;
-}
-
-/*--------------------------------------------------------*\
-|  DisplayWindow
-\*--------------------------------------------------------*/
-void DrawWindow::DisplayWindow()
-{
-  if (Draw_VirtualWindows)
-  {
-    return;
-  }
-  ShowWindow (win, SW_SHOW);
-  UpdateWindow (win);
-}
-
-
-/*--------------------------------------------------------*\
-|  Hide
-\*--------------------------------------------------------*/
-void DrawWindow::Hide()
-{
-  ShowWindow(win, SW_HIDE);
-}
-
-
-/*--------------------------------------------------------*\
-|  Destroy
-\*--------------------------------------------------------*/
-void DrawWindow::Destroy()
-{
-  DestroyWindow(win);
-}
-
-
-
-/*--------------------------------------------------------*\
-|  Clear
-\*--------------------------------------------------------*/
-void DrawWindow::Clear()
-{
-  HDC hDC = GetDC(win);
-  HDC aWorkDC = myUseBuffer ? GetMemDC(hDC) : hDC;
-
-  SaveDC(aWorkDC);
-  SelectObject(aWorkDC,GetStockObject(BLACK_PEN));
-  Rectangle(aWorkDC, 0, 0, WidthWin(), HeightWin());
-  RestoreDC(aWorkDC,-1);
-
-  if (myUseBuffer) ReleaseMemDC(aWorkDC);
-  ReleaseDC(win,hDC);
 }
 
+#ifdef _WIN32
 /*--------------------------------------------------------*\
 |  SaveBitmap
 \*--------------------------------------------------------*/
@@ -1789,25 +989,28 @@ static Standard_Boolean SaveBitmap (HBITMAP     theHBitmap,
   ReleaseDC (NULL, aDC);
   return isSuccess && anImage.Save (theFileName);
 }
+#endif
 
-/*--------------------------------------------------------*\
-|  Save
-\*--------------------------------------------------------*/
-Standard_Boolean DrawWindow::Save (const char* theFileName) const
+//=======================================================================
+//function : Save
+//purpose  :
+//=======================================================================
+Standard_Boolean Draw_Window::Save (const char* theFileName) const
 {
+#ifdef _WIN32
   if (myUseBuffer)
   {
     return SaveBitmap (myMemHbm, theFileName);
   }
 
   RECT aRect;
-  GetClientRect (win, &aRect);
+  GetClientRect (myWindow, &aRect);
   int aWidth  = aRect.right  - aRect.left;
   int aHeight = aRect.bottom - aRect.top;
 
   // Prepare the DCs
   HDC aDstDC = GetDC (NULL);
-  HDC aSrcDC = GetDC (win); // we copy only client area
+  HDC aSrcDC = GetDC (myWindow); // we copy only client area
   HDC aMemDC = CreateCompatibleDC (aDstDC);
 
   // Copy the screen to the bitmap
@@ -1822,166 +1025,582 @@ Standard_Boolean DrawWindow::Save (const char* theFileName) const
   DeleteDC (aMemDC);
 
   return isSuccess;
-}
+#elif defined(HAVE_XLIB)
+  // make sure all draw operations done
+  XSync (Draw_WindowDisplay, True);
 
-/*--------------------------------------------------------*\
-|  DrawString
-\*--------------------------------------------------------*/
-void DrawWindow::DrawString(int x,int y, char* text)
-{
-  HDC hDC = GetDC(win);
-  HDC aWorkDC = myUseBuffer ? GetMemDC(hDC) : hDC;
+  // the attributes
+  XWindowAttributes aWinAttr;
+  XGetWindowAttributes (Draw_WindowDisplay, myWindow, &aWinAttr);
 
-  TCollection_ExtendedString textW (text);
-  TextOutW(aWorkDC, x, y, (const wchar_t*)textW.ToExtString(), (int )strlen(text));
-
-  if (myUseBuffer) ReleaseMemDC(aWorkDC);
-  ReleaseDC(win,hDC);
-}
-
-/*--------------------------------------------------------*\
-|  DrawSegments
-\*--------------------------------------------------------*/
-void DrawWindow::DrawSegments(Segment *tab, int nbElem)
-{
-  HDC hDC = GetDC(win);
-  HDC aWorkDC = myUseBuffer ? GetMemDC(hDC) : hDC;
-
-  for(int i = 0 ; i < nbElem ; i++)
+  if (!myUseBuffer)
   {
-    MoveToEx(aWorkDC, tab[i].x1, tab[i].y1, NULL);
-    LineTo(aWorkDC, tab[i].x2, tab[i].y2);
+    // make sure that the whole window fit on display to prevent BadMatch error
+    XWindowAttributes aWinAttrRoot;
+    XGetWindowAttributes (Draw_WindowDisplay, XRootWindowOfScreen (aWinAttr.screen), &aWinAttrRoot);
+
+    Window aWinChildDummy;
+    int aWinLeft = 0, aWinTop = 0;
+    XTranslateCoordinates (Draw_WindowDisplay, myWindow, XRootWindowOfScreen (aWinAttr.screen),
+                           0, 0, &aWinLeft, &aWinTop, &aWinChildDummy);
+
+    if (((aWinLeft + aWinAttr.width) > aWinAttrRoot.width)  || aWinLeft < aWinAttrRoot.x
+     || ((aWinTop + aWinAttr.height) > aWinAttrRoot.height) || aWinTop  < aWinAttrRoot.y)
+    {
+      std::cerr << "The window not fully visible! Can't create the snapshot.\n";
+      return Standard_False;
+    }
   }
 
-  if (myUseBuffer) ReleaseMemDC(aWorkDC);
-  ReleaseDC(win,hDC);
+  XVisualInfo aVInfo;
+  if (XMatchVisualInfo (Draw_WindowDisplay, Draw_WindowScreen, 32, TrueColor, &aVInfo) == 0
+   && XMatchVisualInfo (Draw_WindowDisplay, Draw_WindowScreen, 24, TrueColor, &aVInfo) == 0)
+  {
+    std::cerr << "24-bit TrueColor visual is not supported by server!\n";
+    return Standard_False;
+  }
+
+  Image_AlienPixMap anImage;
+  bool isBigEndian = Image_PixMap::IsBigEndianHost();
+  const Standard_Size aSizeRowBytes = Standard_Size(aWinAttr.width) * 4;
+  if (!anImage.InitTrash (isBigEndian ? Image_Format_RGB32 : Image_Format_BGR32,
+                          Standard_Size(aWinAttr.width), Standard_Size(aWinAttr.height), aSizeRowBytes))
+  {
+    return Standard_False;
+  }
+  anImage.SetTopDown (true);
+
+  XImage* anXImage = XCreateImage (Draw_WindowDisplay, aVInfo.visual,
+                                   32, ZPixmap, 0, (char* )anImage.ChangeData(), aWinAttr.width, aWinAttr.height, 32, int(aSizeRowBytes));
+  anXImage->bitmap_bit_order = anXImage->byte_order = (isBigEndian ? MSBFirst : LSBFirst);
+  if (XGetSubImage (Draw_WindowDisplay, GetDrawable(),
+                    0, 0, aWinAttr.width, aWinAttr.height,
+                    AllPlanes, ZPixmap, anXImage, 0, 0) == NULL)
+  {
+    anXImage->data = NULL;
+    XDestroyImage (anXImage);
+    return Standard_False;
+  }
+
+  // destroy the image
+  anXImage->data = NULL;
+  XDestroyImage (anXImage);
+
+  // save the image
+  return anImage.Save (theFileName);
+#else
+  (void )theFileName;
+  return false;
+#endif
 }
 
-/*--------------------------------------------------------*\
-|  Redraw
-\*--------------------------------------------------------*/
-void DrawWindow::Redraw()
+#endif // !__APPLE__
+
+#if defined(HAVE_XLIB)
+//=======================================================================
+//function : Wait
+//purpose  :
+//=======================================================================
+void Draw_Window::Wait (Standard_Boolean theToWait)
 {
-  if (myUseBuffer) {
-    HDC hDC = GetDC(win);
-    RECT rc;
-    GetClientRect(win, &rc);
-    HDC aMemDC = GetMemDC(hDC);
-    BitBlt(hDC,
-           rc.left, rc.top,
-           rc.right-rc.left, rc.bottom-rc.top,
-           aMemDC,
-           0, 0, SRCCOPY);
-    ReleaseMemDC(aMemDC);
-    ReleaseDC(win,hDC);
+  Flush();
+  long aMask = ButtonPressMask | ExposureMask | StructureNotifyMask;
+  if (!theToWait) { aMask |= PointerMotionMask; }
+  XSelectInput (Draw_WindowDisplay, myWindow, aMask);
+}
+
+//! Process pending X events.
+static void processXEvents (ClientData , int )
+{
+  // test for X Event
+  while (XPending (Draw_WindowDisplay))
+  {
+    XEvent anEvent;
+    XNextEvent (Draw_WindowDisplay, &anEvent);
+
+    // search the window in the window list
+    bool isFound = false;
+
+    for (NCollection_List<Draw_Window*>::Iterator aWinIter (getDrawWindowList());
+         aWinIter.More(); aWinIter.Next())
+    {
+      Draw_Window* aDrawWin = aWinIter.Value();
+      if (aDrawWin->IsEqualWindows (anEvent.xany.window))
+      {
+        switch (anEvent.type)
+        {
+          case ClientMessage:
+          {
+            if (anEvent.xclient.data.l[0] == (int )Draw_DisplayConnection->GetAtom (Aspect_XA_DELETE_WINDOW))
+            {
+              aDrawWin->Hide(); // just hide the window
+            }
+            break;
+          }
+          case Expose:
+          {
+            aDrawWin->WExpose();
+            break;
+          }
+        }
+
+        isFound = true;
+        break;
+      }
+    }
+    if (!isFound)
+    {
+    #ifdef _TK
+      Tk_HandleEvent (&anEvent);
+    #endif
+    }
+  }
+}
+
+//======================================================
+// function : GetNextEvent()
+// purpose :
+//======================================================
+void Draw_Window::GetNextEvent (Draw_Window::Draw_XEvent& theEvent)
+{
+  XEvent anXEvent;
+  XNextEvent (Draw_WindowDisplay, &anXEvent);
+  switch (anXEvent.type)
+  {
+    case ButtonPress:
+    {
+      theEvent.type = 4;
+      theEvent.window = anXEvent.xbutton.window;
+      theEvent.button = anXEvent.xbutton.button;
+      theEvent.x = anXEvent.xbutton.x;
+      theEvent.y = anXEvent.xbutton.y;
+      break;
+    }
+    case MotionNotify:
+    {
+      theEvent.type = 6;
+      theEvent.window = anXEvent.xmotion.window;
+      theEvent.button = 0;
+      theEvent.x = anXEvent.xmotion.x;
+      theEvent.y = anXEvent.xmotion.y;
+      break;
+    }
+  }
+}
+#endif
+
+#ifndef _WIN32
+//======================================================
+// function :Run_Appli
+// purpose :
+//======================================================
+static Standard_Boolean(*Interprete) (const char*);
+
+void Run_Appli(Standard_Boolean (*interprete) (const char*))
+{
+  Interprete = interprete;
+
+  // Commands will come from standard input, so set up an event handler for standard input.
+  // If the input device is aEvaluate the .rc file, if one has been specified,
+  // set up an event handler for standard input, and print a prompt if the input device is a terminal.
+  Tcl_Channel anInChannel = Tcl_GetStdChannel(TCL_STDIN);
+  if (anInChannel)
+  {
+    Tcl_CreateChannelHandler (anInChannel, TCL_READABLE, StdinProc, (ClientData )anInChannel);
+  }
+
+  // Create a handler for the draw display
+#if defined(HAVE_XLIB)
+  Tcl_CreateFileHandler (ConnectionNumber(Draw_WindowDisplay), TCL_READABLE, processXEvents, (ClientData) 0);
+#endif // __APPLE__
+
+  Draw_Interpretor& aCommands = Draw::GetInterpretor();
+
+  if (tty) { Prompt (aCommands.Interp(), 0); }
+  Prompt (aCommands.Interp(), 0);
+
+  Tcl_Channel anOutChannel = Tcl_GetStdChannel(TCL_STDOUT);
+  if (anOutChannel)
+  {
+    Tcl_Flush (anOutChannel);
+  }
+  Tcl_DStringInit (&Draw_TclCommand);
+
+#ifdef _TK
+  if (Draw_VirtualWindows)
+  {
+    // main window will never shown
+    // but main loop will parse all Xlib messages
+    Tcl_Eval(aCommands.Interp(), "wm withdraw .");
+  }
+  // Loop infinitely, waiting for commands to execute.
+  // When there are no windows left, Tk_MainLoop returns and we exit.
+  Tk_MainLoop();
+#else
+  for (;;)
+  {
+    Tcl_DoOneEvent (0); // practically the same as Tk_MainLoop()
+  }
+#endif
+
+  for (NCollection_List<Draw_Window::FCallbackBeforeTerminate>::Iterator anIter (TermCallbacks());
+       anIter.More(); anIter.Next())
+  {
+    (*anIter.Value())();
+  }
+}
+
+//======================================================
+// function : Init_Appli()
+// purpose  :
+//======================================================
+Standard_Boolean Init_Appli()
+{
+  Draw_Interpretor& aCommands = Draw::GetInterpretor();
+  aCommands.Init();
+  Tcl_Interp *interp = aCommands.Interp();
+  Tcl_Init (interp);
+
+#ifdef _TK
+  try
+  {
+    OCC_CATCH_SIGNALS
+    Tk_Init (interp);
+  }
+  catch (Standard_Failure const& theFail)
+  {
+    Message::SendFail() << "TK_Init() failed with " << theFail;
+  }
+
+  Tcl_StaticPackage(interp, "Tk", Tk_Init, (Tcl_PackageInitProc *) NULL);
+
+  Tk_Window aMainWindow = Tk_MainWindow(interp) ;
+  if (aMainWindow == NULL) {
+#if ((TCL_MAJOR_VERSION > 8) || ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 5)))
+    fprintf(stderr, "%s\n", Tcl_GetStringResult(interp));
+#else
+    fprintf(stderr, "%s\n", interp->result);
+#endif
+    exit(1);
+  }
+#if defined(__APPLE__) && !defined(HAVE_XLIB)
+  Tk_SetAppName(aMainWindow, "Draw");
+#else
+  Tk_Name(aMainWindow) = Tk_GetUid(Tk_SetAppName(aMainWindow, "Draw"));
+#endif
+
+  Tk_GeometryRequest (aMainWindow, 200, 200);
+#endif
+
+#if defined(HAVE_XLIB)
+  if (Draw_DisplayConnection.IsNull())
+  {
+    try
+    {
+      Draw_DisplayConnection = new Aspect_DisplayConnection();
+    }
+    catch (Standard_Failure const& theFail)
+    {
+      std::cout << "Cannot open display (" << theFail << "). Interpret commands in batch mode." << std::endl;
+      return Standard_False;
+    }
+  }
+  if (Draw_WindowDisplay == NULL)
+  {
+    Draw_WindowDisplay = (Display* )Draw_DisplayConnection->GetDisplayAspect();
+  }
+  //
+  // synchronize the display server : could be done within Tk_Init
+  //
+  XSynchronize (Draw_WindowDisplay, True);
+  XSetInputFocus (Draw_WindowDisplay,
+                  PointerRoot,
+                  RevertToPointerRoot,
+                  CurrentTime);
+
+  Draw_WindowScreen   = DefaultScreen(Draw_WindowDisplay);
+  Draw_WindowColorMap = DefaultColormap(Draw_WindowDisplay,
+                                        Draw_WindowScreen);
+#endif // __APPLE__
+
+  tty = isatty(0);
+  Tcl_SetVar(interp,"tcl_interactive",(char*)(tty ? "1" : "0"), TCL_GLOBAL_ONLY);
+//  Tcl_SetVar(interp,"tcl_interactive",tty ? "1" : "0", TCL_GLOBAL_ONLY);
+  return Standard_True;
+}
+
+//======================================================
+// function : Destroy_Appli()
+// purpose  :
+//======================================================
+void Destroy_Appli()
+{
+  //XCloseDisplay(Draw_WindowDisplay);
+}
+
+//! This procedure is invoked by the event dispatcher whenever standard input becomes readable.
+//! It grabs the next line of input characters, adds them to a command being assembled,
+//! and executes the command if it's complete.
+//! Side effects: Could be almost arbitrary, depending on the command that's typed.
+static void StdinProc (ClientData clientData, int theMask)
+{
+  (void )theMask;
+  static int gotPartial = 0;
+//  int code, count;
+  Tcl_Channel chan = (Tcl_Channel) clientData;
+
+  // MSV Nov 2, 2001: patch for TCL 8.3: initialize line to avoid exception
+  //                  when first user input is an empty string
+  Tcl_DStringFree (&Draw_TclLine);
+  int count = Tcl_Gets(chan, &Draw_TclLine);
+
+  // MKV 26.05.05
+#if ((TCL_MAJOR_VERSION > 8) || ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION >= 4)))
+  Tcl_DString aLineTmp;
+  Tcl_DStringInit (&aLineTmp);
+  Tcl_UniChar* aUniCharString = Tcl_UtfToUniCharDString (Tcl_DStringValue (&Draw_TclLine), -1, &aLineTmp);
+  Standard_Integer l = Tcl_UniCharLen (aUniCharString);
+  TCollection_AsciiString anAsciiString;
+  for (Standard_Integer i = 0; i < l; ++i)
+  {
+    Standard_Character aCharacter = aUniCharString[i];
+    anAsciiString.AssignCat (aCharacter);
+  }
+  Tcl_DStringInit (&Draw_TclLine);
+  Tcl_DStringAppend (&Draw_TclLine, anAsciiString.ToCString(), -1);
+#endif
+  if (count < 0)
+  {
+    if (!gotPartial)
+    {
+      if (tty)
+      {
+        Tcl_Exit(0);
+      }
+      else
+      {
+        Tcl_DeleteChannelHandler(chan, StdinProc, (ClientData) chan);
+      }
+      return;
+    }
+    else
+    {
+      count = 0;
+    }
+  }
+
+  (void) Tcl_DStringAppend (&Draw_TclCommand, Tcl_DStringValue (&Draw_TclLine), -1);
+  char* cmd = Tcl_DStringAppend (&Draw_TclCommand, "\n", -1);
+  Tcl_DStringFree (&Draw_TclLine);
+  try
+  {
+    OCC_CATCH_SIGNALS
+    if (!Tcl_CommandComplete (cmd))
+    {
+      gotPartial = 1;
+      goto prompt;
+    }
+    gotPartial = 0;
+
+    /*
+     * Disable the stdin channel handler while evaluating the command;
+     * otherwise if the command re-enters the event loop we might
+     * process commands from stdin before the current command is finished.
+     * Among other things, this will trash the text of the command being evaluated.
+     */
+    Tcl_CreateChannelHandler(chan, 0, StdinProc, (ClientData) chan);
+
+    /*
+     * Disable the stdin file handler while evaluating the command;
+     * otherwise if the command re-enters the event loop we might
+     * process commands from stdin before the current command is finished.
+     * Among other things, this will trash the text of the command being evaluated.
+     */
+
+#ifdef _TK
+    // Tk_CreateFileHandler (0, 0, StdinProc, (ClientData) 0);
+#endif
+    // xab average to avoid an output SIGBUS of DRAW
+    // to ultimately precise or remove once
+    // the problem of free on the global variable at the average
+    //
+    Interprete (cmd);
+
+    Tcl_CreateChannelHandler (chan, TCL_READABLE, StdinProc, (ClientData) chan);
+    Tcl_DStringFree (&Draw_TclCommand);
+
+  /*
+   * Output a prompt.
+   */
+prompt:
+    if (tty)
+    {
+      Prompt (Draw::GetInterpretor().Interp(), gotPartial);
+    }
+
+  } catch (Standard_Failure const&) {}
+}
+
+#else
+
+// Source Specifique WNT
+
+/*--------------------------------------------------------*\
+|  CREATE DRAW WINDOW PROCEDURE
+\*--------------------------------------------------------*/
+HWND Draw_Window::createDrawWindow (HWND hWndClient, int nitem)
+{
+  if (Draw_IsConsoleSubsystem)
+  {
+    HWND aWin = CreateWindowW (DRAWCLASS, DRAWTITLE,
+                               WS_OVERLAPPEDWINDOW,
+                               1,1,1,1,
+                               NULL, NULL,::GetModuleHandle(NULL), NULL);
+    if (!Draw_VirtualWindows)
+    {
+      SetWindowPos (aWin, HWND_TOPMOST,   1,1,1,1, SWP_NOMOVE);
+      SetWindowPos (aWin, HWND_NOTOPMOST, 1,1,1,1, SWP_NOMOVE);
+    }
+    return aWin;
+  }
+  else
+  {
+    HANDLE hInstance = (HANDLE )GetWindowLongPtrW (hWndClient, GWLP_HINSTANCE);
+    return CreateMDIWindowW (DRAWCLASS, DRAWTITLE,
+                             WS_CAPTION | WS_CHILD | WS_THICKFRAME,
+                             1,1,0,0,
+                             hWndClient, (HINSTANCE)hInstance, nitem);
   }
 }
 
 /*--------------------------------------------------------*\
-|  SetMode
+|  DRAW WINDOW PROCEDURE
 \*--------------------------------------------------------*/
-void DrawWindow::SetMode(int mode)
+LRESULT APIENTRY Draw_Window::DrawProc (HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam)
 {
-  HDC hDC = GetDC(win);
-  myCurrMode = mode;
-  SetROP2(hDC, modeTab[mode]);
-  ReleaseDC(win,hDC);
-}
+  Draw_Window* aLocWin = (Draw_Window* )GetWindowLongPtrW (hWnd, CLIENTWND);
+  if (aLocWin == NULL)
+  {
+    return Draw_IsConsoleSubsystem
+         ? DefWindowProcW   (hWnd, wMsg, wParam, lParam)
+         : DefMDIChildProcW (hWnd, wMsg, wParam, lParam);
+  }
 
+  switch (wMsg)
+  {
+    case WM_CLOSE:
+    {
+      aLocWin->Hide();
+      return 0; // do nothing - window destruction should be performed by application
+    }
+    case WM_PAINT:
+    {
+      PAINTSTRUCT ps;
+      BeginPaint (hWnd, &ps);
+      if (aLocWin->GetUseBuffer())
+      {
+        aLocWin->Redraw();
+      }
+      else
+      {
+        aLocWin->WExpose();
+      }
+      EndPaint (hWnd, &ps);
+      return 0;
+    }
+    case WM_SIZE:
+    {
+      if (aLocWin->GetUseBuffer())
+      {
+        aLocWin->InitBuffer();
+        aLocWin->WExpose();
+        aLocWin->Redraw();
+        return 0;
+      }
+      break;
+    }
+  }
+  return Draw_IsConsoleSubsystem
+       ? DefWindowProcW   (hWnd, wMsg, wParam, lParam)
+       : DefMDIChildProcW (hWnd, wMsg, wParam, lParam);
+}
 
 /*--------------------------------------------------------*\
-|  SetColor
+|  SelectWait
 \*--------------------------------------------------------*/
-void DrawWindow::SetColor(Standard_Integer color)
+void Draw_Window::SelectWait (HANDLE& theWindow,
+                              int& theX, int& theY,
+                              int& theButton)
 {
-  HDC hDC = GetDC(win);
-  myCurrPen = color;
-  SelectObject(hDC,colorPenTab[color]);
-  ReleaseDC(win,hDC);
-}
+  MSG aMsg;
+  aMsg.wParam = 1;
+  GetMessageW (&aMsg, NULL, 0, 0);
+  while ((aMsg.message != WM_RBUTTONDOWN
+       && aMsg.message != WM_LBUTTONDOWN)
+       || !(Draw_IsConsoleSubsystem || IsChild(Draw_Window::hWndClientMDI, aMsg.hwnd)))
+  {
+    GetMessageW (&aMsg, NULL, 0, 0);
+  }
 
+  theWindow = aMsg.hwnd;
+  theX = LOWORD(aMsg.lParam);
+  theY = HIWORD(aMsg.lParam);
+  if (aMsg.message == WM_LBUTTONDOWN)
+  {
+    theButton = 1;
+  }
+  else
+  {
+    theButton = 3;
+  }
+}
 
 /*--------------------------------------------------------*\
-|  WExpose
+|  SelectNoWait
 \*--------------------------------------------------------*/
-void DrawWindow::WExpose()
+void Draw_Window::SelectNoWait (HANDLE& theWindow,
+                                int& theX, int& theY,
+                                int& theButton)
 {
+  MSG aMsg;
+  aMsg.wParam = 1;
+  GetMessageW (&aMsg, NULL, 0, 0);
+  while ((aMsg.message != WM_RBUTTONDOWN
+       && aMsg.message != WM_LBUTTONDOWN
+       && aMsg.message != WM_MOUSEMOVE)
+       || !(Draw_IsConsoleSubsystem || IsChild(Draw_Window::hWndClientMDI, aMsg.hwnd)))
+  {
+    GetMessageW (&aMsg, NULL, 0, 0);
+  }
+
+  theWindow = aMsg.hwnd;
+  theX = LOWORD(aMsg.lParam);
+  theY = HIWORD(aMsg.lParam);
+  switch (aMsg.message)
+  {
+    case WM_LBUTTONDOWN:
+      theButton = 1;
+      break;
+    case WM_RBUTTONDOWN:
+      theButton = 3;
+      break;
+    case WM_MOUSEMOVE:
+      theButton = 0;
+      break;
+  }
 }
 
-
-/*--------------------------------------------------------*\
-|  WButtonPress
-\*--------------------------------------------------------*/
-void DrawWindow::WButtonPress(const Standard_Integer,
-                               const Standard_Integer,
-                               const Standard_Integer&)
-{
-}
-
-
-/*--------------------------------------------------------*\
-|  WButtonRelease
-\*--------------------------------------------------------*/
-void DrawWindow::WButtonRelease(const Standard_Integer,
-                                 const Standard_Integer,
-                                 const Standard_Integer&)
-{
-}
-
-
-/*--------------------------------------------------------*\
-|  WMotionNotify
-\*--------------------------------------------------------*/
-void Draw_Window::WMotionNotify(const Standard_Integer ,
-                                const Standard_Integer )
-{
-}
-
-
-/*--------------------------------------------------------*\
-|  WConfigureNotify
-\*--------------------------------------------------------*/
-void DrawWindow::WConfigureNotify(const Standard_Integer,
-                                   const Standard_Integer,
-                                   const Standard_Integer,
-                                   const Standard_Integer)
-{
-}
-
-
-/*--------------------------------------------------------*\
-|  WUnmapNotify
-\*--------------------------------------------------------*/
-void DrawWindow::WUnmapNotify()
-{
-}
-
-
-
-/*
-**  IMPLEMENTATION of the CLASS SEGMENT
- */
-
 /*--------------------------------------------------------*\
 |  Init
 \*--------------------------------------------------------*/
 
-void Segment::Init(Standard_Integer a1, Standard_Integer a2,
-                   Standard_Integer a3, Standard_Integer a4)
-{
-  x1=a1;
-  y1=a2;
-  x2=a3;
-  y2=a4;
-}
-
 static DWORD WINAPI tkLoop (LPVOID theThreadParameter);
 #ifdef _TK
 static Tk_Window mainWindow;
 #endif
 
-//* threads sinchronization *//
-DWORD  dwMainThreadId;
+//* threads synchronization *//
+static DWORD dwMainThreadId;
 console_semaphore_value volatile console_semaphore = WAIT_CONSOLE_COMMAND;
 wchar_t console_command[DRAW_COMMAND_SIZE + 1];
 bool volatile isTkLoopStarted = false;
@@ -2028,12 +1647,18 @@ Standard_Boolean Init_Appli(HINSTANCE hInst,
 
   // san - 06/08/2002 - Time for tkLoop to start; Tk fails to initialize otherwise
   while (!isTkLoopStarted)
-    Sleep(10);
+  {
+    Sleep (10);
+  }
 
   // Saving of window classes
-  if(!hPrevInst)
-    if(!RegisterAppClass(hInst))
-      return(Standard_False);
+  if (!hPrevInst)
+  {
+    if (!RegisterAppClass (hInst))
+    {
+      return Standard_False;
+    }
+  }
 
   /*
    ** Enter the application message-polling loop.  This is the anchor for
@@ -2042,8 +1667,8 @@ Standard_Boolean Init_Appli(HINSTANCE hInst,
   hWndFrame = !Draw_IsConsoleSubsystem ? CreateAppWindow (hInst) : NULL;
   if (hWndFrame != NULL)
   {
-    ShowWindow(hWndFrame,nShow);
-    UpdateWindow(hWndFrame);
+    ShowWindow (hWndFrame, nShow);
+    UpdateWindow (hWndFrame);
   }
 
   return Standard_True;
@@ -2119,10 +1744,10 @@ static DWORD WINAPI readStdinThreadFunc (const LPVOID theThreadParameter)
 \*--------------------------------------------------------*/
 void exitProc(ClientData /*dc*/)
 {
-  NCollection_List<Draw_Window::FCallbackBeforeTerminate>::Iterator Iter(MyCallbacks);
-  for(; Iter.More(); Iter.Next())
+  for (NCollection_List<Draw_Window::FCallbackBeforeTerminate>::Iterator anIter (TermCallbacks());
+       anIter.More(); anIter.Next())
   {
-      (*Iter.Value())();
+    (*anIter.Value())();
   }
   HANDLE proc = GetCurrentProcess();
   TerminateProcess(proc, 0);
@@ -2130,10 +1755,7 @@ void exitProc(ClientData /*dc*/)
 
 // This is fixed version of TclpGetDefaultStdChannel() defined in tclWinChan.c
 // See https://core.tcl.tk/tcl/tktview/91c9bc1c457fda269ae18595944fc3c2b54d961d
-static Tcl_Channel
-TclpGetDefaultStdChannel(
-    int type)			/* One of TCL_STDIN, TCL_STDOUT, or
-				 * TCL_STDERR. */
+static Tcl_Channel TclpGetDefaultStdChannel (int type) // One of TCL_STDIN, TCL_STDOUT, or TCL_STDERR.
 {
     Tcl_Channel channel;
     HANDLE handle;
@@ -2205,7 +1827,7 @@ TclpGetDefaultStdChannel(
     return channel;
 }
 
-// helper functuion
+// helper function
 static void ResetStdChannel (int type)
 {
   Tcl_Channel aChannel = TclpGetDefaultStdChannel (type);
@@ -2226,8 +1848,8 @@ static DWORD WINAPI tkLoop (const LPVOID theThreadParameter)
   
   Draw_Interpretor& aCommands = Draw::GetInterpretor();
   aCommands.Init();
-  Tcl_Interp *interp = aCommands.Interp();
-  Tcl_Init(interp);
+  Tcl_Interp* interp = aCommands.Interp();
+  Tcl_Init (interp);
 
   // Work-around against issue with Tcl standard channels on Windows.
   // These channels by default use OS handles owned by the system which
@@ -2310,10 +1932,15 @@ static DWORD WINAPI tkLoop (const LPVOID theThreadParameter)
   isTkLoopStarted = true;
 
   while (console_semaphore == STOP_CONSOLE)
-    Tcl_DoOneEvent(TCL_ALL_EVENTS | TCL_DONT_WAIT);
+  {
+    Tcl_DoOneEvent (TCL_ALL_EVENTS | TCL_DONT_WAIT);
+  }
 
-  if (Draw_IsConsoleSubsystem && console_semaphore == WAIT_CONSOLE_COMMAND)
-    Prompt(interp, 0);
+  if (Draw_IsConsoleSubsystem
+   && console_semaphore == WAIT_CONSOLE_COMMAND)
+  {
+    Prompt (interp, 0);
+  }
 
   //process a command
   Standard_Boolean toLoop = Standard_True;
@@ -2347,29 +1974,29 @@ static DWORD WINAPI tkLoop (const LPVOID theThreadParameter)
   return 0;
 }
 
-
 /*--------------------------------------------------------*\
 |  Run_Appli
 \*--------------------------------------------------------*/
-void Run_Appli(HWND hWnd)
+void Run_Appli (HWND hWnd)
 {
   MSG msg;
   HACCEL hAccel = NULL;
-
   msg.wParam = 1;
 
 //  if (!(hAccel = LoadAccelerators (hInstance, MAKEINTRESOURCE(ACCEL_ID))))
 //        MessageBox(hWnd, "MDI: Load Accel failure!", "Error", MB_OK);
   DWORD IDThread;
   HANDLE hThread;
-  if (Draw_IsConsoleSubsystem) {
+  if (Draw_IsConsoleSubsystem)
+  {
     hThread = CreateThread (NULL,                // no security attributes
                             0,                   // use default stack size
                             readStdinThreadFunc, // thread function
                             NULL,                // no thread function argument
                             0,                   // use default creation flags
                             &IDThread);          // returns thread identifier
-    if (!hThread) {
+    if (!hThread)
+    {
       std::cout << "pb in creation of the thread reading stdin" << std::endl;
       Draw_IsConsoleSubsystem = Standard_False;
       Init_Appli (GetModuleHandleW (NULL),
@@ -2380,7 +2007,9 @@ void Run_Appli(HWND hWnd)
 
   //turn on the command interpretation mechanism (regardless of the mode)
   if (console_semaphore == STOP_CONSOLE)
+  {
     console_semaphore = WAIT_CONSOLE_COMMAND;
+  }
 
   //simple Win32 message loop
   while (GetMessageW (&msg, NULL, 0, 0) > 0)
@@ -2394,80 +2023,16 @@ void Run_Appli(HWND hWnd)
   ExitProcess(0);
 }
 
-
 /*--------------------------------------------------------*\
 |  Destroy_Appli
 \*--------------------------------------------------------*/
-void Destroy_Appli(HINSTANCE hInst)
+void Destroy_Appli (HINSTANCE hInst)
 {
-  UnregisterAppClass(hInst);
-  for (int i = 0 ; i < MAXCOLOR ; i++)
-    DeleteObject(colorPenTab[i]);
-}
-
-/*--------------------------------------------------------*\
-|  SelectWait
-\*--------------------------------------------------------*/
-void DrawWindow::SelectWait(HANDLE& hWnd, int& x, int& y, int& button)
-{
-  MSG msg;
-
-  msg.wParam = 1;
-
-  GetMessageW (&msg, NULL, 0, 0);
-  while((msg.message != WM_RBUTTONDOWN && msg.message != WM_LBUTTONDOWN) ||
-        ! ( Draw_IsConsoleSubsystem || IsChild(DrawWindow::hWndClientMDI,msg.hwnd)) )
+  UnregisterAppClass (hInst);
+  for (int i = 0; i < MAXCOLOR; ++i)
   {
-    GetMessageW (&msg, NULL, 0, 0);
+    DeleteObject (Draw_colorPenTab[i]);
   }
-
-  hWnd = msg.hwnd;
-  x = LOWORD(msg.lParam);
-  y = HIWORD(msg.lParam);
-  if (msg.message == WM_LBUTTONDOWN)
-    button = 1;
-  else
-    button = 3;
-}
-
-/*--------------------------------------------------------*\
-|  SelectNoWait
-\*--------------------------------------------------------*/
-void DrawWindow::SelectNoWait(HANDLE& hWnd, int& x, int& y, int& button)
-{
-  MSG msg;
-
-  msg.wParam = 1;
-
-  GetMessageW (&msg,NULL,0,0);
-  while((msg.message != WM_RBUTTONDOWN && msg.message != WM_LBUTTONDOWN &&
-        msg.message != WM_MOUSEMOVE) ||
-        ! ( Draw_IsConsoleSubsystem || IsChild(DrawWindow::hWndClientMDI,msg.hwnd) ) )
-  {
-    GetMessageW(&msg,NULL,0,0);
-  }
-  hWnd = msg.hwnd;
-  x = LOWORD(msg.lParam);
-  y = HIWORD(msg.lParam);
-  switch (msg.message)
-  {
-    case WM_LBUTTONDOWN :
-                    button = 1;
-                    break;
-
-    case WM_RBUTTONDOWN :
-                    button = 3;
-                    break;
-
-    case WM_MOUSEMOVE :
-                    button = 0;
-                    break;
-  }
-}
-
-Standard_Boolean DrawWindow::DefineColor (const Standard_Integer, const char*)
-{
-  return Standard_True;
 }
 
 #endif
diff --git a/src/Draw/Draw_Window.hxx b/src/Draw/Draw_Window.hxx
index 7f382fa782..27eced584b 100644
--- a/src/Draw/Draw_Window.hxx
+++ b/src/Draw/Draw_Window.hxx
@@ -17,211 +17,78 @@
 #ifndef Draw_Window_HeaderFile
 #define Draw_Window_HeaderFile
 
+#if defined(_WIN32)
+  #include <windows.h>
+#endif
+
+#include <Aspect_Drawable.hxx>
+#include <NCollection_Vec2.hxx>
 #include <Standard_Boolean.hxx>
 #include <Standard_Integer.hxx>
 #include <TCollection_AsciiString.hxx>
 
-#if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+#include <memory>
 
 const Standard_Integer MAXCOLOR = 15;
 
+//! Segment definition.
+struct Draw_XSegment
+{
+  NCollection_Vec2<short> Points[2]; // same as XSegment
+
+  NCollection_Vec2<short>&       operator[](int theIndex)       { return Points[theIndex]; }
+  const NCollection_Vec2<short>& operator[](int theIndex) const { return Points[theIndex]; }
+
+  void Init (Standard_Integer theXStart, Standard_Integer theYStart, Standard_Integer theXEnd, Standard_Integer theYEnd)
+  {
+    Points[0].SetValues ((short )theXStart, (short )theYStart);
+    Points[1].SetValues ((short )theXEnd,   (short )theYEnd);
+  }
+};
+
+#if defined(_WIN32)
+
+#define DRAWCLASS L"DRAWWINDOW"
+#define DRAWTITLE L"Draw View"
+
+enum console_semaphore_value
+{
+  STOP_CONSOLE,
+  WAIT_CONSOLE_COMMAND,
+  HAS_CONSOLE_COMMAND
+};
+
+// global variable describing console state
+extern console_semaphore_value volatile console_semaphore;
+
+// Console command buffer
+#define DRAW_COMMAND_SIZE 1000
+extern wchar_t console_command[DRAW_COMMAND_SIZE + 1];
+
+// PROCEDURE DE DRAW WINDOW
+Standard_EXPORT Standard_Boolean Init_Appli(HINSTANCE,HINSTANCE,int,HWND&);
+Standard_EXPORT void Run_Appli(HWND);
+Standard_EXPORT void Destroy_Appli(HINSTANCE);
+
+#else
+
+//! Run the application.
+//! interp will be called to interpret a command and return True if the command is complete.
+void Run_Appli (Standard_Boolean (*inteprete) (const char*));
+
+//! Initialize application.
+Standard_Boolean Init_Appli();
+
+//! Destroy application.
+void Destroy_Appli();
+
+#if defined(HAVE_XLIB)
+
 typedef unsigned long Window;
 typedef unsigned long Pixmap;
 typedef unsigned long Drawable;
 
-// Definition de la class Base_Window (Definie dans Draw_Window.cxx)
-//===================================
-struct Base_Window;
-
-// Definition de la classe Segment
-//================================
-struct Segment
-{
-  short xx1;
-  short yy1;
-  short xx2;
-  short yy2;
-
-  void Init(short x1, short y1, short x2, short y2) {
-    xx1 = x1; yy1 = y1; xx2 = x2; yy2 = y2;
-  }
-
-};
-
-// Definition de la structure Event
-//=================================
-typedef struct Event
-{
-  Standard_Integer type;
-  Window window;
-  Standard_Integer button;
-  Standard_Integer x;
-  Standard_Integer y;
-} Event;
-
-// Definition de la classe Draw_Window
-//====================================
-class Draw_Window
-{
-  public :
-
-    /**
-     * Type of the callback function that is to be passed to the method
-     * AddCallbackBeforeTerminate().
-     */
-    typedef void (*FCallbackBeforeTerminate)();
-
-    /**
-     * This method registers a callback function that will be called just before exit.
-     * This is useful especially for Windows platform, on which Draw is normally 
-     * self-terminated instead of exiting.
-     */
-    Standard_EXPORT static void AddCallbackBeforeTerminate(FCallbackBeforeTerminate theCB);
-
-    /**
-     * Just in case method for un-registering a callback previously registered by
-     * AddCallbackBeforeTerminate()
-     */
-    Standard_EXPORT static void RemoveCallbackBeforeTerminate(FCallbackBeforeTerminate theCB);
-
-    Draw_Window (); // the window is not initialized
-    Draw_Window (const char* title,
-		 Standard_Integer X, Standard_Integer Y = 0,
-		 Standard_Integer DX = 50, Standard_Integer DY = 50);
-
-    Draw_Window (Window mother);
-    Draw_Window (Window mother,char* title,
-		 Standard_Integer X = 0, Standard_Integer Y = 0,
-		 Standard_Integer DX = 50, Standard_Integer DY = 50);
-    Draw_Window(const char *window);
-
-    void Init (Standard_Integer X = 0, Standard_Integer Y = 0,
-	       Standard_Integer DX = 50, Standard_Integer DY = 50);
-
-    void Init (Window mother,
-	       Standard_Integer X = 0, Standard_Integer Y = 0,
-	       Standard_Integer DX = 50, Standard_Integer DY = 50);
-
-
-    void StopWinManager();
-
-    void SetPosition (Standard_Integer NewXpos,
-		      Standard_Integer NewYpos);
-
-    void SetDimension(Standard_Integer NewDx,
-		      Standard_Integer NewDy);
-
-    void GetPosition(Standard_Integer &PosX,
-		     Standard_Integer &PosY);
-
-    Standard_Integer HeightWin() const;
-    Standard_Integer WidthWin() const;
-
-    void SetTitle (const TCollection_AsciiString& theTitle);
-    TCollection_AsciiString GetTitle() const;
-
-    //! Return true if window is displayed on the screen.
-    bool IsMapped() const;
-    void DisplayWindow();
-    void Hide();
-    void Destroy();
-    void Clear();
-    void Wait(Standard_Boolean wait = Standard_True);
-
-    Drawable GetDrawable() const;
-    // Initializes off-screen image buffer according to current window size
-    void InitBuffer();
-
-    static Standard_Boolean DefineColor(const Standard_Integer, const char*);
-    void SetColor(int);
-    void SetMode(int);
-    void DrawString(int, int, char*);
-    void DrawSegments(Segment* ,int);
-    void Redraw();
-    static void Flush();
-
-    // save snapshot
-    Standard_Boolean Save(const char* theFileName) const;
-
-    virtual ~Draw_Window ();
-
-    // X Event management
-    virtual void WExpose();
-    virtual void WButtonPress(const Standard_Integer X,
-			      const Standard_Integer Y,
-			      const Standard_Integer& button);
-    virtual void WButtonRelease(const Standard_Integer X,
-				const Standard_Integer Y,
-				const Standard_Integer& button);
-    //virtual void WKeyPress(char, KeySym& );
-    virtual void WMotionNotify(const Standard_Integer X,
-			       const Standard_Integer Y);
-
-    virtual void WConfigureNotify(const Standard_Integer X,
-				  const Standard_Integer Y,
-				  const Standard_Integer dx,
-				  const Standard_Integer dy);
-
-    virtual void WUnmapNotify();
-
-    Base_Window& base;
-    Window win;
-    Window myMother; // default : myMother is the root window
-    Pixmap myBuffer;
-
-    static Draw_Window* firstWindow;
-    Draw_Window* next;
-    Draw_Window* previous;
-
-    Standard_Boolean myUseBuffer;
-    Standard_Boolean withWindowManager;
-
-};
-
-//======================================================
-// function : Run_Appli
-// purpose : run the application
-//           interp will be called to interpret a command
-//           and return True if the command is complete
-//======================================================
-
-void Run_Appli(Standard_Boolean (*inteprete) (const char*));
-
-//======================================================
-// function : Init_Appli
-// purpose :
-//======================================================
-Standard_Boolean Init_Appli();
-
-//======================================================
-// function : Destroy_Appli()
-// purpose :
-//======================================================
-void Destroy_Appli();
-
-//======================================================
-// function : GetNextEvent()
-// purpose :
-//======================================================
-void GetNextEvent(Event&);
-
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-
-const Standard_Integer MAXCOLOR = 15;
-
-struct Segment
-{
-  Standard_Integer myXStart;
-  Standard_Integer myYStart;
-  Standard_Integer myXEnd;
-  Standard_Integer myYEnd;
-
-  void Init(short theXStart, short theYStart, short theXEnd, short theYEnd) {
-    myXStart = theXStart; myYStart = theYStart; myXEnd = theXEnd; myYEnd = theYEnd;
-  }
-
-};
-
+#elif defined(__APPLE__)
 #ifdef __OBJC__
   @class NSView;
   @class NSWindow;
@@ -233,308 +100,198 @@ struct Segment
   struct NSImage;
   struct Draw_CocoaView;
 #endif
+#endif
 
+#endif
 
+//! Draw window.
 class Draw_Window
 {
-  public :
-
-  /**
-   * Type of the callback function that is to be passed to the method
-   * AddCallbackBeforeTerminate().
-   */
-  typedef void (*FCallbackBeforeTerminate)();
-
-  /**
-   * This method registers a callback function that will be called just before exit.
-   * This is useful especially for Windows platform, on which Draw is normally 
-   * self-terminated instead of exiting.
-   */
-  Standard_EXPORT static void AddCallbackBeforeTerminate(FCallbackBeforeTerminate theCB);
-
-  /**
-   * Just in case method for un-registering a callback previously registered by
-   * AddCallbackBeforeTerminate()
-   */
-  Standard_EXPORT static void RemoveCallbackBeforeTerminate(FCallbackBeforeTerminate theCB);
-
-  Draw_Window (); // the window is not initialized
-  Draw_Window (Standard_CString        theTitle,
-               const Standard_Integer& theXLeft = 0,  const Standard_Integer& theYTop   = 0,
-               const Standard_Integer& theWidth = 50, const Standard_Integer& theHeight = 50);
-
-  Draw_Window (NSWindow*               theWindow,     Standard_CString        theTitle,
-               const Standard_Integer& theXLeft = 0,  const Standard_Integer& theYTop   = 0,
-               const Standard_Integer& theWidth = 50, const Standard_Integer& theHeight = 50);
-
-  void Init (const Standard_Integer& theXLeft = 0,  const Standard_Integer& theYLeft  = 0,
-             const Standard_Integer& theWidth = 50, const Standard_Integer& theHeight = 50);
-
-  virtual ~Draw_Window ();
-
-  void SetPosition (const Standard_Integer& theNewXpos,
-                    const Standard_Integer& theNewYpos);
-
-  void SetDimension (const Standard_Integer& theNewWidth,
-                     const Standard_Integer& theNewHeight);
-
-  void GetPosition (Standard_Integer &thePosX,
-                    Standard_Integer &thePosY);
-
-  Standard_Integer HeightWin() const;
-  Standard_Integer WidthWin()  const;
-
-  void  SetTitle (const TCollection_AsciiString& theTitle);
-  TCollection_AsciiString GetTitle() const;
-
-  //! Return true if window is displayed on the screen.
-  bool IsMapped() const;
-  void DisplayWindow();
-  void Hide();
-  void Destroy();
-  void Clear();
-
-  void InitBuffer();
-
-  static Standard_Boolean DefineColor (const Standard_Integer&, Standard_CString);
-  void SetColor     (const Standard_Integer& theColor);
-  void SetMode      (const Standard_Integer& theMode);
-  void DrawString   (const Standard_Integer& theX, const Standard_Integer& theY, char* theText);
-  void DrawSegments (Segment* theSegment, const Standard_Integer& theNumberOfElements);
-  void Redraw();
-  static void Flush();
-  
-  // save snapshot
-  Standard_Boolean Save (Standard_CString theFileName) const;
-  
-  Standard_Boolean IsEqualWindows (const Standard_Integer& theWindowNumber);
-
-private:
-  NSWindow*        myWindow;
-  Draw_CocoaView*  myView;
-  NSImage*         myImageBuffer;
-  Standard_Boolean myUseBuffer;
-  Standard_Integer myCurrentColor;
-
-  static Draw_Window* firstWindow;
-  Draw_Window*        nextWindow;
-  Draw_Window*        previousWindow;
-
-};
-
-//======================================================
-// function : Run_Appli
-// purpose : run the application
-//           interp will be called to interpret a command
-//           and return True if the command is complete
-//======================================================
-
-void Run_Appli(Standard_Boolean (*inteprete) (const char*));
-
-//======================================================
-// function : Init_Appli
-// purpose :
-//======================================================
-Standard_Boolean Init_Appli();
-
-//======================================================
-// function : Destroy_Appli()
-// purpose :
-//======================================================
-void Destroy_Appli();
-
-//======================================================
-// function : GetNextEvent()
-// purpose :
-//======================================================
-void GetNextEvent (Standard_Boolean  theWait,
-                   Standard_Integer& theWindowNumber,
-                   Standard_Integer& theX,
-                   Standard_Integer& theY,
-                   Standard_Integer& theButton);
-#else
-
-// Specifique WNT
-
-#include <windows.h>
-
-#define DRAWCLASS L"DRAWWINDOW"
-#define DRAWTITLE L"Draw View"
-#define MAXCOLOR  15
-
-// definition de la classe Segment
-
-class DrawWindow;
-class Segment
-{
-  friend class DrawWindow;
-  public :
-    //constructeur
-    Segment ()
-    : x1(0),
-      y1(0),
-      x2(0),
-      y2(0)
-    {
-    }
-    //destructeur
-    ~Segment () {}
-
-    //methods
-    void Init(Standard_Integer,
-	      Standard_Integer,
-	      Standard_Integer,
-	      Standard_Integer);
-  private:
-    //atributs :
-    Standard_Integer x1;
-    Standard_Integer y1;
-    Standard_Integer x2;
-    Standard_Integer y2;
-};
-
-//definition de la classe DRAWWINDOW
-
-class DrawWindow
-{
-  //constructeur
 public:
 
-  /**
-   * Type of the callback function that is to be passed to the method
-   * AddCallbackBeforeTerminate().
-   */
+  //! Type of the callback function that is to be passed to the method AddCallbackBeforeTerminate().
   typedef void (*FCallbackBeforeTerminate)();
 
-  /**
-   * This method registers a callback function that will be called just before exit.
-   * This is useful especially for Windows platform, on which Draw is normally 
-   * self-terminated instead of exiting.
-   */
-  Standard_EXPORT static void AddCallbackBeforeTerminate(FCallbackBeforeTerminate theCB);
+  //! This method registers a callback function that will be called just before exit.
+  //! This is useful especially for Windows platform, on which Draw is normally self-terminated instead of exiting.
+  Standard_EXPORT static void AddCallbackBeforeTerminate (FCallbackBeforeTerminate theCB);
 
-  /**
-   * Just in case method for un-registering a callback previously registered by
-   * AddCallbackBeforeTerminate()
-   */
-  Standard_EXPORT static void RemoveCallbackBeforeTerminate(FCallbackBeforeTerminate theCB);
+  //! Just in case method for un-registering a callback previously registered by AddCallbackBeforeTerminate().
+  Standard_EXPORT static void RemoveCallbackBeforeTerminate (FCallbackBeforeTerminate theCB);
 
-  Standard_EXPORT DrawWindow();
-  Standard_EXPORT DrawWindow(const char*, Standard_Integer, Standard_Integer,
-			Standard_Integer, Standard_Integer);
-  Standard_EXPORT DrawWindow(const char*, Standard_Integer, Standard_Integer,
-			Standard_Integer, Standard_Integer, HWND);
-  //destructeur
-  Standard_EXPORT virtual ~DrawWindow();
+  //! @sa SetColor()
+  Standard_EXPORT static Standard_Boolean DefineColor (const Standard_Integer theIndex,
+                                                       const char* theColorName);
+
+  //! XFlush() wrapper (X11), has no effect on other platforms.
+  Standard_EXPORT static void Flush();
 
-  //methods
 public:
-  Standard_EXPORT void Init(Standard_Integer, Standard_Integer,
-		       Standard_Integer, Standard_Integer);
 
-  Standard_EXPORT void SetUseBuffer(Standard_Boolean);
-  // Turns on/off usage of off-screen image buffer (can be used for redrawing optimization)
+  //! Destructor.
+  Standard_EXPORT virtual ~Draw_Window();
 
-  Standard_Boolean GetUseBuffer() const { return myUseBuffer; }
-  // Returns Standard_True if off-screen image buffer is being used
+  //! Get window position.
+  Standard_EXPORT void GetPosition (Standard_Integer& thePosX,
+                                    Standard_Integer& thePosY);
 
-  //taille et position
-  Standard_EXPORT void SetPosition (Standard_Integer,Standard_Integer);
-  Standard_EXPORT void SetDimension(Standard_Integer,Standard_Integer);
-  Standard_EXPORT void GetPosition (Standard_Integer&,Standard_Integer&);
+  //! Set window position.
+  Standard_EXPORT void SetPosition (Standard_Integer theNewXpos,
+                                    Standard_Integer theNewYpos);
+
+  //! Return window height.
   Standard_EXPORT Standard_Integer HeightWin() const;
-  Standard_EXPORT Standard_Integer WidthWin()  const;
 
-  //Title
-  Standard_EXPORT void SetTitle (const TCollection_AsciiString& );
+  //! Return window width.
+  Standard_EXPORT Standard_Integer WidthWin() const;
+
+  //! Set window dimensions.
+  Standard_EXPORT void SetDimension (Standard_Integer theNewDx,
+                                     Standard_Integer theNewDy);
+
+  //! Return window title.
   Standard_EXPORT TCollection_AsciiString GetTitle() const;
 
-  //Affichage
-    //! Return true if window is displayed on the screen.
-    bool IsMapped() const;
+  //! Set window title.
+  Standard_EXPORT void SetTitle (const TCollection_AsciiString& theTitle);
+
+  //! Return true if window is displayed on the screen.
+  Standard_EXPORT bool IsMapped() const;
+
+  //! Display window on the screen.
   Standard_EXPORT void DisplayWindow();
+
+  //! Hide window.
   Standard_EXPORT void Hide();
+
+  //! Destroy window.
   Standard_EXPORT void Destroy();
+
+  //! Clear window content.
   Standard_EXPORT void Clear();
-  static void Flush() {} ;
 
-  // save snapshot
-  Standard_EXPORT Standard_Boolean Save(const char* theFileName) const;
+  //! Returns Standard_True if off-screen image buffer is being used
+  Standard_Boolean GetUseBuffer() const { return myUseBuffer; }
 
-  //Dessin
-  Standard_EXPORT void DrawString(int,int,char*);
-  Standard_EXPORT void DrawSegments(Segment*,int);
+  // Turns on/off usage of off-screen image buffer (can be used for redrawing optimization)
+  Standard_EXPORT void SetUseBuffer (Standard_Boolean theToUse);
 
-  Standard_EXPORT void InitBuffer();
-  // Initializes off-screen image buffer according to current window size
+  //! Set active color index for further paintings.
+  //! @sa DefineColor()
+  Standard_EXPORT void SetColor (Standard_Integer theColor);
 
+  //! Set active paint mode (3 for COPY; 6 for XOR).
+  Standard_EXPORT void SetMode  (Standard_Integer theMode);
+
+  //! Draw the string.
+  Standard_EXPORT void DrawString (Standard_Integer theX, Standard_Integer theY,
+                                   const char* theText);
+
+  //! Draw array of segments.
+  Standard_EXPORT void DrawSegments (const Draw_XSegment* theSegments,
+                                     Standard_Integer theNumberOfElements);
+
+  //! Redraw window content.
   Standard_EXPORT void Redraw();
-  // Copies an image from memory buffer to screen
 
-  //Couleur
-  Standard_EXPORT void SetColor(Standard_Integer);
-  Standard_EXPORT void SetMode(int);
-  Standard_EXPORT static Standard_Boolean DefineColor ( const Standard_Integer,const char*);
+  //! Save snapshot.
+  Standard_EXPORT Standard_Boolean Save (const char* theFileName) const;
 
-  //Gestion des Messages
-  Standard_EXPORT virtual void WExpose ();
-  Standard_EXPORT virtual void WButtonPress(const Standard_Integer,const Standard_Integer,
-				       const Standard_Integer&);
-  Standard_EXPORT virtual void WButtonRelease(const Standard_Integer,const Standard_Integer,
-					 const Standard_Integer&);
-  Standard_EXPORT virtual void WMotionNotify(const Standard_Integer,const Standard_Integer);
-  Standard_EXPORT virtual void WConfigureNotify(const Standard_Integer,const Standard_Integer,
-					   const Standard_Integer,const Standard_Integer);
-  Standard_EXPORT virtual void WUnmapNotify();
+  //! Perform window exposing.
+  virtual void WExpose() = 0;
 
-  //Gestion souris
-  Standard_EXPORT static void SelectWait   (HANDLE&,int&,int&,int&);
-  Standard_EXPORT static void SelectNoWait (HANDLE&,int&,int&,int&);
+  //! (Re)initializes off-screen image buffer according to current window size.
+  Standard_EXPORT void InitBuffer();
 
-  // Procedure de fenetre
-  Standard_EXPORT static LRESULT APIENTRY DrawProc (HWND,UINT,WPARAM,LPARAM);
+protected:
 
-private:
+  //! Main constructor.
+  //! @param theTitle  [in] window title
+  //! @param theXY     [in] top-left position
+  //! @param theSize   [in] window dimensions
+  //! @param theParent [in] optional native parent window
+  //! @param theWin    [in] optional native window
+  Standard_EXPORT Draw_Window (const char* theTitle,
+                               const NCollection_Vec2<int>& theXY,
+                               const NCollection_Vec2<int>& theSize,
+                               Aspect_Drawable theParent,
+                               Aspect_Drawable theWin);
 
-  Standard_EXPORT static HWND CreateDrawWindow(HWND,int);
-  Standard_EXPORT HDC  GetMemDC(HDC);
-  Standard_EXPORT void ReleaseMemDC(HDC);
+  //! Initialize the window.
+  Standard_EXPORT void init (const NCollection_Vec2<int>& theXY,
+                             const NCollection_Vec2<int>& theSize);
 
-  //atributs
 public:
-  HWND win;
+
+#if defined(_WIN32)
+  Standard_Boolean IsEqualWindows (HANDLE theWindow) { return myWindow == theWindow; }
+
+  Standard_EXPORT static void SelectWait   (HANDLE& theWindow, int& theX, int& theY, int& theButton);
+  Standard_EXPORT static void SelectNoWait (HANDLE& theWindow, int& theX, int& theY, int& theButton);
+  // Procedure de fenetre
+  Standard_EXPORT static LRESULT APIENTRY DrawProc (HWND, UINT, WPARAM, LPARAM);
   static HWND hWndClientMDI;
+#elif defined(HAVE_XLIB)
+  Standard_Boolean IsEqualWindows (Window theWindow) { return myWindow  == theWindow; }
+
+  //! Event structure.
+  struct Draw_XEvent
+  {
+    Standard_Integer type;
+    Window window;
+    Standard_Integer button;
+    Standard_Integer x;
+    Standard_Integer y;
+  };
+
+  //! Retrieve event.
+  static void GetNextEvent (Draw_XEvent& theEvent);
+
+  void Wait (Standard_Boolean theToWait = Standard_True);
+#elif defined(__APPLE__)
+  Standard_Boolean IsEqualWindows (const Standard_Integer& theWindowNumber);
+
+  static void GetNextEvent (Standard_Boolean  theWait,
+                            Standard_Integer& theWindowNumber,
+                            Standard_Integer& theX,
+                            Standard_Integer& theY,
+                            Standard_Integer& theButton);
+#endif
 
 private:
-  static DrawWindow* firstWindow;
-  DrawWindow* next;
-  DrawWindow* previous;
-  HBITMAP myMemHbm;
-  HBITMAP myOldHbm;
-  Standard_Boolean myUseBuffer;
+
+#if defined(_WIN32)
+  Standard_EXPORT static HWND createDrawWindow (HWND , int );
+  Standard_EXPORT HDC  getMemDC    (HDC theWinDC);
+  Standard_EXPORT void releaseMemDC(HDC theMemDC);
+#elif defined(HAVE_XLIB)
+  Drawable GetDrawable() const { return myUseBuffer ? myImageBuffer : myWindow; }
+  struct Base_Window; // opaque structure with extra Xlib parameters
+#endif
+
+private:
+
+#if defined(_WIN32)
+  HWND             myWindow;      //!< native window
+  HBITMAP          myMemHbm;
+  HBITMAP          myOldHbm;
   Standard_Integer myCurrPen;
   Standard_Integer myCurrMode;
+#elif defined(HAVE_XLIB)
+  Window           myWindow;      //!< native window
+  Window           myMother;      //!< parent native window
+  Pixmap           myImageBuffer;
+  std::unique_ptr<Base_Window> myBase;
+#elif defined(__APPLE__)
+  NSWindow*        myWindow;      //!< native window
+  Draw_CocoaView*  myView;
+  NSImage*         myImageBuffer;
+#else
+  Aspect_Drawable  myWindow;
+#endif
+  Standard_Integer myCurrentColor;
+  Standard_Boolean myUseBuffer;
+
 };
 
-typedef DrawWindow Draw_Window;
-typedef enum {
-  STOP_CONSOLE,
-  WAIT_CONSOLE_COMMAND,
-  HAS_CONSOLE_COMMAND} console_semaphore_value;
-
-// global variable describing console state
-extern console_semaphore_value volatile console_semaphore;
-
-// Console command buffer
-#define DRAW_COMMAND_SIZE 1000
-extern wchar_t console_command[DRAW_COMMAND_SIZE + 1];
-
-// PROCEDURE DE DRAW WINDOW
-
-Standard_EXPORT Standard_Boolean Init_Appli(HINSTANCE,HINSTANCE,int,HWND&);
-Standard_EXPORT void Run_Appli(HWND);
-Standard_EXPORT void Destroy_Appli(HINSTANCE);
-
-#endif
-
-#endif
+#endif // Draw_Window_HeaderFile
diff --git a/src/Draw/Draw_Window_1.mm b/src/Draw/Draw_Window_1.mm
index ce12c46d3b..4758412470 100644
--- a/src/Draw/Draw_Window_1.mm
+++ b/src/Draw/Draw_Window_1.mm
@@ -11,7 +11,7 @@
 // Alternatively, this file may be used under the terms of Open CASCADE
 // commercial license or contractual agreement.
 
-#if defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#if defined(__APPLE__) && !defined(HAVE_XLIB)
 
 #import <Cocoa/Cocoa.h>
 
@@ -121,52 +121,23 @@ Standard_Real Draw_RGBColorsArray[MAXCOLOR][3] = {{1.0,  1.0,  1.0},
 //function : Draw_Window
 //purpose  :
 //=======================================================================
-Draw_Window::Draw_Window() :
-  myWindow (NULL),
+Draw_Window::Draw_Window (const char* theTitle,
+                          const NCollection_Vec2<int>& theXY,
+                          const NCollection_Vec2<int>& theSize,
+                          Aspect_Drawable theParent,
+                          Aspect_Drawable theWindow)
+: myWindow (NULL),
   myView (NULL),
   myImageBuffer (NULL),
-  myUseBuffer (Standard_False),
-  nextWindow (firstWindow),
-  previousWindow (NULL)
+  myCurrentColor (0),
+  myUseBuffer (Standard_False)
 {
-  if (firstWindow != NULL) firstWindow->previousWindow = this;
-  firstWindow = this;
-}
-
-//=======================================================================
-//function : Draw_Window
-//purpose  :
-//=======================================================================
-Draw_Window::Draw_Window (Standard_CString theTitle,
-                          const Standard_Integer& theXLeft, const Standard_Integer& theYTop,
-                          const Standard_Integer& theWidth, const Standard_Integer& theHeight):
-  myWindow (NULL),
-  myView (NULL),
-  myImageBuffer (NULL),
-  myUseBuffer (Standard_False),
-  nextWindow (firstWindow),
-  previousWindow (NULL)
-{
-  if (firstWindow != NULL) firstWindow->previousWindow = this;
-  firstWindow = this;
-  Init (theXLeft, theYTop, theWidth, theHeight);
-  SetTitle (theTitle);
-}
-
-Draw_Window::Draw_Window (NSWindow*               theWindow, Standard_CString        theTitle,
-                          const Standard_Integer& theXLeft,  const Standard_Integer& theYTop,
-                          const Standard_Integer& theWidth,  const Standard_Integer& theHeight):
-  myWindow (NULL),
-  myView (NULL),
-  myImageBuffer (NULL),
-  myUseBuffer (Standard_False),
-  nextWindow (firstWindow),
-  previousWindow (NULL)
-{
-  myWindow = [theWindow retain];
-  if (firstWindow != NULL) firstWindow->previousWindow = this;
-  firstWindow = this;
-  Init (theXLeft, theYTop, theWidth, theHeight);
+  (void )theParent;
+  if (theWindow != 0)
+  {
+    myWindow = [(NSWindow* )theWindow retain];
+  }
+  init (theXY, theSize);
   SetTitle (theTitle);
 }
 
@@ -176,20 +147,6 @@ Draw_Window::Draw_Window (NSWindow*               theWindow, Standard_CString
 //=======================================================================
 Draw_Window::~Draw_Window()
 {
-  if (previousWindow != NULL)
-  {
-    previousWindow->nextWindow = nextWindow;
-  }
-  else
-  {
-    firstWindow = nextWindow;
-  }
-
-  if (nextWindow != NULL)
-  {
-    nextWindow->previousWindow = previousWindow;
-  }
-
   if (myWindow != NULL)
   { 
     [myWindow release];
@@ -210,20 +167,20 @@ Draw_Window::~Draw_Window()
 }
 
 //=======================================================================
-//function : Init
+//function : init
 //purpose  :
 //=======================================================================
-void Draw_Window::Init (const Standard_Integer& theXLeft, const Standard_Integer& theYTop,
-                        const Standard_Integer& theWidth, const Standard_Integer& theHeight)
+void Draw_Window::init (const NCollection_Vec2<int>& theXY,
+                        const NCollection_Vec2<int>& theSize)
 {
   Cocoa_LocalPool aLocalPool;
 
   // converting left-bottom coordinate to left-top coordinate
-  Standard_Integer anYTop = getScreenBottom() - theYTop - theHeight;
+  Standard_Integer anYTop = getScreenBottom() - theXY.y() - theSize.y();
 
   if (myWindow == NULL)
   {
-    NSRect     aRectNs   = NSMakeRect (theXLeft, anYTop, theWidth, theHeight);
+    NSRect     aRectNs   = NSMakeRect (theXY.x(), anYTop, theSize.x(), theSize.y());
     NSUInteger aWinStyle = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable;
 
     myWindow = [[NSWindow alloc] initWithContentRect: aRectNs
@@ -269,8 +226,8 @@ void Draw_Window::InitBuffer()
 //function : SetPosition
 //purpose  :
 //=======================================================================
-void Draw_Window::SetPosition (const Standard_Integer& theNewXpos,
-                               const Standard_Integer& theNewYpos)
+void Draw_Window::SetPosition (Standard_Integer theNewXpos,
+                               Standard_Integer theNewYpos)
 {
   NSPoint aNewPosition = NSMakePoint (theNewXpos, theNewYpos);
   [myWindow setFrameTopLeftPoint: aNewPosition];
@@ -280,8 +237,8 @@ void Draw_Window::SetPosition (const Standard_Integer& theNewXpos,
 //function : SetDimension
 //purpose  :
 //=======================================================================
-void Draw_Window::SetDimension (const Standard_Integer& theNewWidth,
-                                const Standard_Integer& theNewHeight)
+void Draw_Window::SetDimension (Standard_Integer theNewWidth,
+                                Standard_Integer theNewHeight)
 {
   NSRect aWindowRect = [myWindow frame];
   Standard_Integer aNewY = aWindowRect.origin.y + aWindowRect.size.height - theNewHeight;
@@ -347,7 +304,7 @@ TCollection_AsciiString Draw_Window::GetTitle() const
 //function :DefineColor
 //purpose  :
 //=======================================================================
-Standard_Boolean Draw_Window::DefineColor (const Standard_Integer&, Standard_CString)
+Standard_Boolean Draw_Window::DefineColor (const Standard_Integer , Standard_CString )
 {
   return Standard_True; // unused
 }
@@ -452,7 +409,8 @@ void Draw_Window::Flush()
 //function : DrawString
 //purpose  :
 //=======================================================================
-void Draw_Window::DrawString (const Standard_Integer& theXLeft, const Standard_Integer& theYTop, char* theText)
+void Draw_Window::DrawString (Standard_Integer theXLeft, Standard_Integer theYTop,
+                              const char* theText)
 {
   Cocoa_LocalPool aLocalPool;
 
@@ -477,7 +435,8 @@ void Draw_Window::DrawString (const Standard_Integer& theXLeft, const Standard_I
 //function : DrawSegments
 //purpose  :
 //=======================================================================
-void Draw_Window::DrawSegments (Segment *theSegment, const Standard_Integer& theNumberOfElements)
+void Draw_Window::DrawSegments (const Draw_XSegment* theSegments,
+                                Standard_Integer theNumberOfElements)
 {
   Cocoa_LocalPool aLocalPool;
 
@@ -498,11 +457,12 @@ void Draw_Window::DrawSegments (Segment *theSegment, const Standard_Integer& the
   }
 
 
-  for (; anIter < theNumberOfElements; anIter++)
+  for (; anIter < theNumberOfElements; ++anIter)
   {
-    NSPoint aPoint = NSMakePoint (theSegment[anIter].myXStart, myImageBuffer.size.height - theSegment[anIter].myYStart);
+    const Draw_XSegment& aSeg = theSegments[anIter];
+    NSPoint aPoint = NSMakePoint (aSeg[0].x(), myImageBuffer.size.height - aSeg[0].y());
     [aPath moveToPoint: aPoint];
-    aPoint = NSMakePoint (theSegment[anIter].myXEnd, myImageBuffer.size.height - theSegment[anIter].myYEnd);
+    aPoint = NSMakePoint (aSeg[1].x(), myImageBuffer.size.height - aSeg[1].y());
     [aPath lineToPoint: aPoint];
   }
 
@@ -540,7 +500,7 @@ void Draw_Window::Redraw()
 //function : SetColor
 //purpose  :
 //=======================================================================
-void Draw_Window::SetColor (const Standard_Integer& theColor)
+void Draw_Window::SetColor (Standard_Integer theColor)
 {
   myCurrentColor = theColor;
 }
@@ -549,7 +509,7 @@ void Draw_Window::SetColor (const Standard_Integer& theColor)
 //function : SetMode
 //purpose  :
 //=======================================================================
-void Draw_Window::SetMode (const Standard_Integer& theMode)
+void Draw_Window::SetMode (Standard_Integer theMode)
 {
   // unsupported
   (void )theMode;
@@ -597,11 +557,11 @@ Standard_Boolean Draw_Window::IsEqualWindows (const Standard_Integer& theWindowN
   return ([myWindow windowNumber] == theWindowNumber);
 }
 
-void GetNextEvent (Standard_Boolean  theWait,
-                   Standard_Integer& theWindowNumber,
-                   Standard_Integer& theX,
-                   Standard_Integer& theY,
-                   Standard_Integer& theButton)
+void Draw_Window::GetNextEvent (Standard_Boolean  theWait,
+                                Standard_Integer& theWindowNumber,
+                                Standard_Integer& theX,
+                                Standard_Integer& theY,
+                                Standard_Integer& theButton)
 {
   Cocoa_LocalPool aLocalPool;
 
@@ -642,4 +602,5 @@ void GetNextEvent (Standard_Boolean  theWait,
     theButton = 0;
   }
 }
+
 #endif // __APPLE__
diff --git a/src/Draw/FILES b/src/Draw/FILES
index b0930b9273..fbfb124724 100755
--- a/src/Draw/FILES
+++ b/src/Draw/FILES
@@ -1,5 +1,3 @@
-CommandWindow.cxx
-CommandWindow.h
 Draw.cxx
 Draw.hxx
 Draw_Appli.hxx
@@ -71,8 +69,10 @@ Draw_Viewer.hxx
 Draw_Window.cxx
 Draw_Window.hxx
 Draw_Window_1.mm
-DrawRessource.h
-init.cxx
-init.h
-MainWindow.cxx
-MainWindow.h
+Draw_WNTCommandWindow.cxx
+Draw_WNTCommandWindow.pxx
+Draw_WNTInit.cxx
+Draw_WNTInit.pxx
+Draw_WNTMainWindow.cxx
+Draw_WNTMainWindow.pxx
+Draw_WNTRessource.pxx
diff --git a/src/IVtkDraw/IVtkDraw.cxx b/src/IVtkDraw/IVtkDraw.cxx
index 5ec039e011..80cd7f0c8d 100644
--- a/src/IVtkDraw/IVtkDraw.cxx
+++ b/src/IVtkDraw/IVtkDraw.cxx
@@ -310,7 +310,7 @@ void IVtkDraw::ViewerInit (const IVtkWinParams& theParams)
 #else
     Window aWindowId = GetWindow()->XWindow();
     aRenWin->SetWindowId ((void*)aWindowId);
-    Display *aDisplayId = GetDisplayConnection()->GetDisplay();
+    Display* aDisplayId = (Display* )GetDisplayConnection()->GetDisplayAspect();
     aRenWin->SetDisplayId (aDisplayId);
 
     // Setup XWindow
diff --git a/src/InterfaceGraphic/FILES b/src/InterfaceGraphic/FILES
deleted file mode 100755
index 68a1aa85b6..0000000000
--- a/src/InterfaceGraphic/FILES
+++ /dev/null
@@ -1 +0,0 @@
-InterfaceGraphic.hxx
diff --git a/src/InterfaceGraphic/InterfaceGraphic.hxx b/src/InterfaceGraphic/InterfaceGraphic.hxx
deleted file mode 100644
index c533f68cd5..0000000000
--- a/src/InterfaceGraphic/InterfaceGraphic.hxx
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright (c) 1991-1999 Matra Datavision
-// Copyright (c) 1999-2014 OPEN CASCADE SAS
-//
-// This file is part of Open CASCADE Technology software library.
-//
-// This library is free software; you can redistribute it and/or modify it under
-// the terms of the GNU Lesser General Public License version 2.1 as published
-// by the Free Software Foundation, with special exception defined in the file
-// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
-// distribution for complete text of the license and disclaimer of any warranty.
-//
-// Alternatively, this file may be used under the terms of Open CASCADE
-// commercial license or contractual agreement.
-
-#ifndef __INTERFACE_GRAPHIC_HXX
-#define __INTERFACE_GRAPHIC_HXX
-
-#if defined(_WIN32)
-
-#include <windows.h>
-
-#ifdef DrawText
-  #undef DrawText
-#endif
-
-#elif !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
-
-#include <stdio.h>
-
-// exclude modern definitions and system-provided glext.h, should be defined before gl.h inclusion
-#ifndef GL_GLEXT_LEGACY
-  #define GL_GLEXT_LEGACY
-#endif
-#ifndef GLX_GLXEXT_LEGACY
-  #define GLX_GLXEXT_LEGACY
-#endif
-
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-#include <X11/Xatom.h>
-#include <GL/glx.h>
-
-#endif
-
-#endif // __INTERFACE_GRAPHIC_HXX
diff --git a/src/OpenGl/OpenGl_Context.cxx b/src/OpenGl/OpenGl_Context.cxx
index 736704b7c5..303c398ec1 100644
--- a/src/OpenGl/OpenGl_Context.cxx
+++ b/src/OpenGl/OpenGl_Context.cxx
@@ -57,7 +57,9 @@ IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Context,Standard_Transient)
   #endif
 #elif defined(_WIN32)
   //
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#elif defined(HAVE_XLIB)
+  #include <GL/glx.h> // glXGetProcAddress()
+#elif defined(__APPLE__)
   #include <dlfcn.h>
   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
     //
@@ -66,7 +68,7 @@ IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Context,Standard_Transient)
     #include <CoreGraphics/CoreGraphics.h>
   #endif
 #else
-  #include <GL/glx.h> // glXGetProcAddress()
+  //
 #endif
 
 #ifdef __EMSCRIPTEN__
@@ -192,6 +194,9 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   nvxMem (Standard_False),
   oesSampleVariables (Standard_False),
   oesStdDerivatives (Standard_False),
+  myWindow  (0),
+  myDisplay (0),
+  myGContext(0),
   mySharedResources (new OpenGl_ResourcesMap()),
   myDelayed         (new OpenGl_DelayReleaseMap()),
   myUnusedResources (new OpenGl_ResourcesStack()),
@@ -275,11 +280,7 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   myDisplay  = (Aspect_Display          )EGL_NO_DISPLAY;
   myWindow   = (Aspect_Drawable         )EGL_NO_SURFACE;
   myGContext = (Aspect_RenderingContext )EGL_NO_CONTEXT;
-#elif defined(_WIN32)
-  myWindow   = NULL;
-  myWindowDC = NULL;
-  myGContext = NULL;
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#elif defined(__APPLE__) && !defined(HAVE_XLIB)
   // Vendors can not extend functionality on this system
   // and developers are limited to OpenGL support provided by Mac OS X SDK.
   // We retrieve function pointers from system library
@@ -290,16 +291,10 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   // because function pointers may be available but not functionality itself
   // (depends on renderer).
 #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
-  myGContext    = NULL;
   myGlLibHandle = dlopen ("/System/Library/Frameworks/OpenGLES.framework/OpenGLES", RTLD_LAZY);
 #else
-  myGContext    = NULL;
   myGlLibHandle = dlopen ("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY);
 #endif
-#else
-  myDisplay =  NULL;
-  myWindow   = 0;
-  myGContext = 0;
 #endif
 
   memset (myFuncs.operator->(), 0, sizeof(OpenGl_GlFunctions));
@@ -638,7 +633,7 @@ void OpenGl_Context::Share (const Handle(OpenGl_Context)& theShareCtx)
   }
 }
 
-#if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
+#if !defined(__APPLE__) || defined(HAVE_XLIB)
 
 // =======================================================================
 // function : IsCurrent
@@ -657,13 +652,13 @@ Standard_Boolean OpenGl_Context::IsCurrent() const
        && ((EGLContext )myGContext == eglGetCurrentContext())
        && ((EGLSurface )myWindow   == eglGetCurrentSurface (EGL_DRAW)));
 #elif defined(_WIN32)
-  if (myWindowDC == NULL || myGContext == NULL)
+  if (myDisplay == NULL || myGContext == NULL)
   {
     return Standard_False;
   }
-  return (( (HDC )myWindowDC == wglGetCurrentDC())
+  return (( (HDC )myDisplay  == wglGetCurrentDC())
       && ((HGLRC )myGContext == wglGetCurrentContext()));
-#else
+#elif defined(HAVE_XLIB)
   if (myDisplay == NULL || myWindow == 0 || myGContext == 0)
   {
     return Standard_False;
@@ -672,6 +667,8 @@ Standard_Boolean OpenGl_Context::IsCurrent() const
   return (   ((Display* )myDisplay  == glXGetCurrentDisplay())
        &&  ((GLXContext )myGContext == glXGetCurrentContext())
        && ((GLXDrawable )myWindow   == glXGetCurrentDrawable()));
+#else
+  return Standard_False;
 #endif
 }
 
@@ -698,7 +695,7 @@ Standard_Boolean OpenGl_Context::MakeCurrent()
     return Standard_False;
   }
 #elif defined(_WIN32)
-  if (myWindowDC == NULL || myGContext == NULL)
+  if (myDisplay == NULL || myGContext == NULL)
   {
     Standard_ProgramError_Raise_if (myIsInitialized, "OpenGl_Context::Init() should be called before!");
     return Standard_False;
@@ -711,7 +708,7 @@ Standard_Boolean OpenGl_Context::MakeCurrent()
     myShaderManager->SetContext (this);
     return Standard_True;
   }
-  else if (wglMakeCurrent ((HDC )myWindowDC, (HGLRC )myGContext) != TRUE)
+  else if (wglMakeCurrent ((HDC )myDisplay, (HGLRC )myGContext) != TRUE)
   {
     // notice that glGetError() couldn't be used here!
     wchar_t* aMsgBuff = NULL;
@@ -728,7 +725,7 @@ Standard_Boolean OpenGl_Context::MakeCurrent()
     myIsInitialized = Standard_False;
     return Standard_False;
   }
-#else
+#elif defined(HAVE_XLIB)
   if (myDisplay == NULL || myWindow == 0 || myGContext == 0)
   {
     Standard_ProgramError_Raise_if (myIsInitialized, "OpenGl_Context::Init() should be called before!");
@@ -743,6 +740,12 @@ Standard_Boolean OpenGl_Context::MakeCurrent()
     myIsInitialized = Standard_False;
     return Standard_False;
   }
+#else
+  // not implemented
+  if (!myIsInitialized)
+  {
+    throw Standard_ProgramError ("OpenGl_Context::Init() should be called before!");
+  }
 #endif
   myShaderManager->SetContext (this);
   return Standard_True;
@@ -760,16 +763,18 @@ void OpenGl_Context::SwapBuffers()
     eglSwapBuffers ((EGLDisplay )myDisplay, (EGLSurface )myWindow);
   }
 #elif defined(_WIN32)
-  if ((HDC )myWindowDC != NULL)
+  if ((HDC )myDisplay != NULL)
   {
-    ::SwapBuffers ((HDC )myWindowDC);
+    ::SwapBuffers ((HDC )myDisplay);
     glFlush();
   }
-#else
+#elif defined(HAVE_XLIB)
   if ((Display* )myDisplay != NULL)
   {
     glXSwapBuffers ((Display* )myDisplay, (GLXDrawable )myWindow);
   }
+#else
+  //
 #endif
 }
 
@@ -799,7 +804,7 @@ Standard_Boolean OpenGl_Context::SetSwapInterval (const Standard_Integer theInte
   {
     return Standard_True;
   }
-#else
+#elif defined(HAVE_XLIB)
   if (theInterval == -1
    && myFuncs->glXSwapIntervalEXT != NULL)
   {
@@ -813,6 +818,8 @@ Standard_Boolean OpenGl_Context::SetSwapInterval (const Standard_Integer theInte
     myFuncs->glXSwapIntervalSGI (theInterval);
     return Standard_True;
   }
+#else
+  //
 #endif
   return Standard_False;
 }
@@ -827,10 +834,13 @@ void* OpenGl_Context::findProc (const char* theFuncName)
   return (void* )eglGetProcAddress (theFuncName);
 #elif defined(_WIN32)
   return (void* )wglGetProcAddress (theFuncName);
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#elif defined(HAVE_XLIB)
+  return (void* )glXGetProcAddress ((const GLubyte* )theFuncName);
+#elif defined(__APPLE__)
   return (myGlLibHandle != NULL) ? dlsym (myGlLibHandle, theFuncName) : NULL;
 #else
-  return (void* )glXGetProcAddress ((const GLubyte* )theFuncName);
+  (void )theFuncName;
+  return NULL;
 #endif
 }
 
@@ -914,7 +924,7 @@ Standard_Boolean OpenGl_Context::CheckExtension (const char* theExtString,
   return Standard_False;
 }
 
-#if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
+#if !defined(__APPLE__) || defined(HAVE_XLIB)
 
 // =======================================================================
 // function : Init
@@ -932,12 +942,14 @@ Standard_Boolean OpenGl_Context::Init (const Standard_Boolean theIsCoreProfile)
   myGContext = (Aspect_RenderingContext )eglGetCurrentContext();
   myWindow   = (Aspect_Drawable )eglGetCurrentSurface(EGL_DRAW);
 #elif defined(_WIN32)
-  myWindowDC = (Aspect_Handle )wglGetCurrentDC();
+  myDisplay  = (Aspect_Handle )wglGetCurrentDC();
   myGContext = (Aspect_RenderingContext )wglGetCurrentContext();
-#else
+#elif defined(HAVE_XLIB)
   myDisplay  = (Aspect_Display )glXGetCurrentDisplay();
   myGContext = (Aspect_RenderingContext )glXGetCurrentContext();
   myWindow   = (Aspect_Drawable )glXGetCurrentDrawable();
+#else
+  //
 #endif
   if (myGContext == NULL)
   {
@@ -955,49 +967,15 @@ Standard_Boolean OpenGl_Context::Init (const Standard_Boolean theIsCoreProfile)
 // function : Init
 // purpose  :
 // =======================================================================
-#if defined(HAVE_EGL)
-Standard_Boolean OpenGl_Context::Init (const Aspect_Drawable         theEglSurface,
-                                       const Aspect_Display          theEglDisplay,
-                                       const Aspect_RenderingContext theEglContext,
-                                       const Standard_Boolean        theIsCoreProfile)
-#elif defined(_WIN32)
-Standard_Boolean OpenGl_Context::Init (const Aspect_Handle           theWindow,
-                                       const Aspect_Handle           theWindowDC,
-                                       const Aspect_RenderingContext theGContext,
-                                       const Standard_Boolean        theIsCoreProfile)
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-
-#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
-Standard_Boolean OpenGl_Context::Init (EAGLContext*                  theGContext,
-                                       const Standard_Boolean        theIsCoreProfile)
-#else
-Standard_Boolean OpenGl_Context::Init (NSOpenGLContext*              theGContext,
-                                       const Standard_Boolean        theIsCoreProfile)
-#endif
-
-#else
-Standard_Boolean OpenGl_Context::Init (const Aspect_Drawable         theWindow,
+Standard_Boolean OpenGl_Context::Init (const Aspect_Drawable         theSurface,
                                        const Aspect_Display          theDisplay,
-                                       const Aspect_RenderingContext theGContext,
+                                       const Aspect_RenderingContext theContext,
                                        const Standard_Boolean        theIsCoreProfile)
-#endif
 {
   Standard_ProgramError_Raise_if (myIsInitialized, "OpenGl_Context::Init() should be called only once!");
-#if defined(HAVE_EGL)
-  myWindow   = theEglSurface;
-  myGContext = theEglContext;
-  myDisplay  = theEglDisplay;
-#elif defined(_WIN32)
-  myWindow   = theWindow;
-  myGContext = theGContext;
-  myWindowDC = theWindowDC;
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-  myGContext = theGContext;
-#else
-  myWindow   = theWindow;
-  myGContext = theGContext;
+  myWindow   = theSurface;
   myDisplay  = theDisplay;
-#endif
+  myGContext = theContext;
   if (myGContext == NULL || !MakeCurrent())
   {
     return Standard_False;
@@ -1867,7 +1845,7 @@ void OpenGl_Context::MemoryInfo (TColStd_IndexedDataMapOfStringString& theDict)
 {
 #if defined(GL_ES_VERSION_2_0)
   (void )theDict;
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#elif defined(__APPLE__) && !defined(HAVE_XLIB)
   GLint aGlRendId = 0;
   CGLGetParameter (CGLGetCurrentContext(), kCGLCPCurrentRendererID, &aGlRendId);
 
@@ -2001,12 +1979,10 @@ void OpenGl_Context::DiagnosticInformation (TColStd_IndexedDataMapOfStringString
     if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0
      && myFuncs->wglGetExtensionsStringARB != NULL)
     {
-      const char* aWglExts = myFuncs->wglGetExtensionsStringARB ((HDC )myWindowDC);
+      const char* aWglExts = myFuncs->wglGetExtensionsStringARB ((HDC )myDisplay);
       addInfo (theDict, "WGLExtensions", aWglExts);
     }
-  #elif defined(__APPLE__)
-    //
-  #else
+  #elif defined(HAVE_XLIB)
     Display* aDisplay = (Display*)myDisplay;
     const int aScreen = DefaultScreen(aDisplay);
     addInfo (theDict, "GLXDirectRendering", ::glXIsDirect (aDisplay, (GLXContext )myGContext) ? "Yes" : "No");
@@ -2024,6 +2000,8 @@ void OpenGl_Context::DiagnosticInformation (TColStd_IndexedDataMapOfStringString
     {
       addInfo (theDict, "GLXClientExtensions", ::glXGetClientString (aDisplay, GLX_EXTENSIONS));
     }
+  #else
+    //
   #endif
   }
 
diff --git a/src/OpenGl/OpenGl_Context.hxx b/src/OpenGl/OpenGl_Context.hxx
index 92a8f73e07..3a5274646d 100644
--- a/src/OpenGl/OpenGl_Context.hxx
+++ b/src/OpenGl/OpenGl_Context.hxx
@@ -216,53 +216,75 @@ public:
     return myIsInitialized;
   }
 
-#if defined(HAVE_EGL)
   //! Initialize class from specified surface and rendering context. Method should be called only once.
+  //! The meaning of parameters is platform-specific.
+  //!
+  //! EGL:
+  //! @code
+  //!   Handle(Aspect_Window) theAspWin;
+  //!   EGLSurface theEglSurf = eglCreateWindowSurface (theEglDisp, anEglConfig, (EGLNativeWindowType )theAspWin->NativeHandle(), NULL);
+  //!   EGLDisplay theEglDisp = eglGetDisplay (EGL_DEFAULT_DISPLAY);
+  //!   EGLContext theEglCtx  = eglCreateContext ((EGLDisplay )theEglDisp, anEglConfig, EGL_NO_CONTEXT, anEglCtxAttribs);
+  //!   Handle(OpenGl_Context) aGlCtx = new OpenGl_Context();
+  //!   aGlCtx->Init ((Aspect_Drawable )theEglSurf, (Aspect_Display )theEglDisp,  (Aspect_RenderingContext )theEglCtx);
+  //! @endcode
+  //!
+  //! Windows (Win32):
+  //! @code
+  //!   Handle(WNT_Window) theAspWin;
+  //!   HWND  theWindow   = (HWND )theAspWin->NativeHandle();
+  //!   HDC   theDevCtx   = GetDC(theWindow);
+  //!   HGLRC theGContext = wglCreateContext (theDevCtx);
+  //!   Handle(OpenGl_Context) aGlCtx = new OpenGl_Context();
+  //!   aGlCtx->Init ((Aspect_Drawable )theWindow, (Aspect_Display )theDevCtx, (Aspect_RenderingContext )theGContext);
+  //! @endcode
+  //!
+  //! Linux (Xlib):
+  //! @code
+  //!   Handle(Xw_Window) theAspWin;
+  //!   Window     theXWindow = (Window )theAspWin->NativeHandle();
+  //!   Display*   theXDisp   = (Display* )theAspWin->DisplayConnection()->GetDisplayAspect();
+  //!   GLXContext theGlxCtx  = glXCreateContext (theXDisp, aVis.get(), NULL, GL_TRUE);
+  //!   Handle(OpenGl_Context) aGlCtx = new OpenGl_Context();
+  //!   aGlCtx->Init ((Aspect_Drawable )theXWindow, (Aspect_Display )theXDisp,  (Aspect_RenderingContext )theGlxCtx);
+  //! @endcode
+  //!
+  //! @param theSurface [in] surface / window          (EGLSurface | HWND  | GLXDrawable/Window)
+  //! @param theDisplay [in] display or device context (EGLDisplay | HDC   | Display*)
+  //! @param theContext [in] rendering context         (EGLContext | HGLRC | GLXContext | EAGLContext* | NSOpenGLContext*)
+  //! @param theIsCoreProfile [in] flag indicating that passed GL rendering context has been created with Core Profile
   //! @return false if OpenGL context can not be bound to specified surface
-  Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable         theEglSurface,
-                                         const Aspect_Display          theEglDisplay,
-                                         const Aspect_RenderingContext theEglContext,
-                                         const Standard_Boolean        theIsCoreProfile = Standard_False);
-#elif defined(_WIN32)
-  //! Initialize class from specified window and rendering context. Method should be called only once.
-  //! @return false if OpenGL context can not be bound to specified window
-  Standard_EXPORT Standard_Boolean Init (const Aspect_Handle           theWindow,
-                                         const Aspect_Handle           theWindowDC,
-                                         const Aspect_RenderingContext theGContext,
+  Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable         theSurface,
+                                         const Aspect_Display          theDisplay,
+                                         const Aspect_RenderingContext theContext,
                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
 
-  //! @return the window handle (HWND) currently bound to this OpenGL context
-  inline Aspect_Handle Window() const
-  {
-    return myWindow;
-  }
+  //! Return window handle currently bound to this OpenGL context (EGLSurface | HWND | GLXDrawable).
+  Aspect_Drawable Window() const { return myWindow; }
 
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+  //! Return display / window device context (EGLDisplay | HDC | Display*).
+  Aspect_Display GetDisplay() const { return myDisplay; }
+
+  //! Return rendering context (EGLContext | HGLRC | GLXContext | EAGLContext* | NSOpenGLContext*).
+  Aspect_RenderingContext RenderingContext() const { return myGContext; }
+
+#if defined(__APPLE__) && !defined(HAVE_XLIB)
   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
 
   //! Initialize class from specified OpenGL ES context (EAGLContext). Method should be called only once.
-  Standard_EXPORT Standard_Boolean Init (EAGLContext*                  theGContext,
-                                         const Standard_Boolean        theIsCoreProfile = Standard_False);
-  #else
-
-  //! Initialize class from specified OpenGL context (NSOpenGLContext). Method should be called only once.
-  Standard_EXPORT Standard_Boolean Init (NSOpenGLContext*              theGContext,
-                                         const Standard_Boolean        theIsCoreProfile = Standard_False);
-  #endif
-#else
-
-  //! Initialize class from specified window and rendering context. Method should be called only once.
-  //! @return false if OpenGL context can not be bound to specified window
-  Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable         theWindow,
-                                         const Aspect_Display          theDisplay,
-                                         const Aspect_RenderingContext theGContext,
-                                         const Standard_Boolean        theIsCoreProfile = Standard_False);
-
-  //! @return the window handle (GLXDrawable) currently bound to this OpenGL context
-  inline Aspect_Drawable Window() const
+  Standard_Boolean Init (EAGLContext*           theGContext,
+                         const Standard_Boolean theIsCoreProfile = Standard_False)
   {
-    return myWindow;
+    return Init ((Aspect_Drawable )0, (Aspect_Display )0, (Aspect_RenderingContext )theGContext, theIsCoreProfile);
   }
+  #else
+  //! Initialize class from specified OpenGL context (NSOpenGLContext). Method should be called only once.
+  Standard_Boolean Init (NSOpenGLContext*       theGContext,
+                         const Standard_Boolean theIsCoreProfile = Standard_False)
+  {
+    return Init ((Aspect_Drawable )0, (Aspect_Display )0, (Aspect_RenderingContext )theGContext, theIsCoreProfile);
+  }
+  #endif
 #endif
 
   //! Read OpenGL version information from active context.
@@ -1070,25 +1092,9 @@ public: //! @name public properties tracking current state
 
 private: // system-dependent fields
 
-#if defined(HAVE_EGL)
-  Aspect_Drawable         myWindow;   //!< EGL surface                   : EGLSurface
-  Aspect_Display          myDisplay;  //!< EGL connection to the Display : EGLDisplay
-  Aspect_RenderingContext myGContext; //!< EGL rendering context         : EGLContext
-#elif defined(_WIN32)
-  Aspect_Handle           myWindow;   //!< window handle (owner of GL context) : HWND
-  Aspect_Handle           myWindowDC; //!< Device Descriptor handle : HDC
-  Aspect_RenderingContext myGContext; //!< Rendering Context handle : HGLRC
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-  #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
-  EAGLContext*            myGContext;    //!< Rendering Context handle
-  #else
-  NSOpenGLContext*        myGContext; //!< Rendering Context handle
-  #endif
-#else
-  Aspect_Drawable         myWindow;   //!< window handle (owner of GL context) : GLXDrawable
-  Aspect_Display          myDisplay;  //!< connection to the X-server : Display*
-  Aspect_RenderingContext myGContext; //!< X-GLX rendering context : GLXContext
-#endif
+  Aspect_Drawable         myWindow;   //!< surface           EGLSurface | HWND  | GLXDrawable
+  Aspect_Display          myDisplay;  //!< display           EGLDisplay | HDC   | Display*
+  Aspect_RenderingContext myGContext; //!< rendering context EGLContext | HGLRC | GLXContext | EAGLContext* | NSOpenGLContext*
 
 private: // context info
 
diff --git a/src/OpenGl/OpenGl_Context_1.mm b/src/OpenGl/OpenGl_Context_1.mm
index c8300d9591..cd82bbf955 100644
--- a/src/OpenGl/OpenGl_Context_1.mm
+++ b/src/OpenGl/OpenGl_Context_1.mm
@@ -13,7 +13,7 @@
 // Alternatively, this file may be used under the terms of Open CASCADE
 // commercial license or contractual agreement.
 
-#if defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#if defined(__APPLE__) && !defined(HAVE_XLIB)
 
 #ifndef GL_GLEXT_LEGACY
 #define GL_GLEXT_LEGACY // To prevent inclusion of system glext.h on Mac OS X 10.6.8
diff --git a/src/OpenGl/OpenGl_GlFunctions.cxx b/src/OpenGl/OpenGl_GlFunctions.cxx
index 19581605c5..ead3f3cdb3 100644
--- a/src/OpenGl/OpenGl_GlFunctions.cxx
+++ b/src/OpenGl/OpenGl_GlFunctions.cxx
@@ -26,6 +26,10 @@
 #include <OpenGl_ArbTexBindless.hxx>
 #include <OpenGl_GlCore46.hxx>
 
+#if !defined(HAVE_EGL) && defined(HAVE_XLIB)
+  #include <GL/glx.h>
+#endif
+
 // =======================================================================
 // function : init
 // purpose  :
@@ -572,9 +576,7 @@ void OpenGl_GlFunctions::load (OpenGl_Context& theCtx,
       FindProcShort (wglGetContextGPUIDAMD);
     }
   }
-#elif defined(__APPLE__)
-    //
-#else
+#elif defined(HAVE_XLIB)
     const char* aGlxExts = ::glXQueryExtensionsString ((Display* )theCtx.myDisplay, DefaultScreen ((Display* )theCtx.myDisplay));
     if (checkExtensionShort (aGlxExts, "GLX_EXT_swap_control"))
     {
diff --git a/src/OpenGl/OpenGl_GlFunctions.hxx b/src/OpenGl/OpenGl_GlFunctions.hxx
index 6e10488e95..a8be687e88 100644
--- a/src/OpenGl/OpenGl_GlFunctions.hxx
+++ b/src/OpenGl/OpenGl_GlFunctions.hxx
@@ -65,11 +65,14 @@
   #include <GL/gl.h>
 #endif
 
-#if !defined(HAVE_EGL) && (defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(HAVE_GLES2) || defined(OCCT_UWP))
+#if !defined(HAVE_EGL)
+#if defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(HAVE_GLES2) || defined(OCCT_UWP)
+  #define HAVE_EGL
+#elif !defined(_WIN32) && !defined(__APPLE__) && !defined(HAVE_XLIB)
   #define HAVE_EGL
 #endif
-
-#include <InterfaceGraphic.hxx>
+#endif
+struct Aspect_XDisplay;
 
 #if defined(GL_ES_VERSION_2_0)
   #include <OpenGl_GLESExtensions.hxx>
@@ -1937,11 +1940,11 @@ public: //! @name glX extensions
   #define GLX_RENDERER_ID_MESA                             0x818E
 #endif // GLX_RENDERER_VENDOR_ID_MESA
 
-  typedef Bool (*glXQueryRendererIntegerMESA_t)(Display* theDisplay, int theScreen,
-                                                int theRenderer, int theAttribute,
-                                                unsigned int* theValue);
-  typedef Bool (*glXQueryCurrentRendererIntegerMESA_t)(int theAttribute, unsigned int* theValue);
-  typedef const char* (*glXQueryRendererStringMESA_t)(Display* theDisplay, int theScreen,
+  typedef int (*glXQueryRendererIntegerMESA_t)(Aspect_XDisplay* theDisplay, int theScreen,
+                                               int theRenderer, int theAttribute,
+                                               unsigned int* theValue);
+  typedef int (*glXQueryCurrentRendererIntegerMESA_t)(int theAttribute, unsigned int* theValue);
+  typedef const char* (*glXQueryRendererStringMESA_t)(Aspect_XDisplay* theDisplay, int theScreen,
                                                       int theRenderer, int theAttribute);
   typedef const char* (*glXQueryCurrentRendererStringMESA_t)(int theAttribute);
 
diff --git a/src/OpenGl/OpenGl_GraphicDriver.cxx b/src/OpenGl/OpenGl_GraphicDriver.cxx
index 33bf69c7f1..a23c5826c0 100644
--- a/src/OpenGl/OpenGl_GraphicDriver.cxx
+++ b/src/OpenGl/OpenGl_GraphicDriver.cxx
@@ -38,13 +38,15 @@ IMPLEMENT_STANDARD_RTTIEXT(OpenGl_GraphicDriver,Graphic3d_GraphicDriver)
 
 #if defined(_WIN32)
   #include <WNT_Window.hxx>
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#elif defined(HAVE_XLIB)
+  #include <Xw_Window.hxx>
+#elif defined(__APPLE__)
   #include <Cocoa_Window.hxx>
 #else
-  #include <Xw_Window.hxx>
+  #include <Aspect_NeutralWindow.hxx>
 #endif
 
-#if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+#if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__) && (!defined(__APPLE__) || defined(HAVE_XLIB))
   #include <X11/Xlib.h> // XOpenDisplay()
   #include <GL/glx.h>
 #endif
@@ -110,7 +112,7 @@ namespace
     }
     return aCfg;
   }
-#elif !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+#elif defined(HAVE_XLIB)
   //! Search for RGBA double-buffered visual with stencil buffer.
   static int TheDoubleBuffVisual[] =
   {
@@ -157,14 +159,14 @@ OpenGl_GraphicDriver::OpenGl_GraphicDriver (const Handle(Aspect_DisplayConnectio
   myEglContext = (Aspect_RenderingContext )EGL_NO_CONTEXT;
 #endif
 
-#if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+#if defined(HAVE_XLIB)
   if (myDisplayConnection.IsNull())
   {
     //throw Aspect_GraphicDeviceDefinitionError("OpenGl_GraphicDriver: cannot connect to X server!");
     return;
   }
 
-  Display* aDisplay = myDisplayConnection->GetDisplay();
+  Display* aDisplay = (Display* )myDisplayConnection->GetDisplayAspect();
   Bool toSync = ::getenv ("CSF_GraphicSync") != NULL
              || ::getenv ("CALL_SYNCHRO_X")  != NULL;
   XSynchronize (aDisplay, toSync);
@@ -284,12 +286,12 @@ Standard_Boolean OpenGl_GraphicDriver::InitContext()
   ReleaseContext();
 #if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__)
 
-#if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+#if defined(HAVE_XLIB)
   if (myDisplayConnection.IsNull())
   {
     return Standard_False;
   }
-  Display* aDisplay = myDisplayConnection->GetDisplay();
+  Display* aDisplay = (Display* )myDisplayConnection->GetDisplayAspect();
   myEglDisplay = (Aspect_Display )eglGetDisplay (aDisplay);
 #else
   myEglDisplay = (Aspect_Display )eglGetDisplay (EGL_DEFAULT_DISPLAY);
@@ -367,7 +369,7 @@ Standard_Boolean OpenGl_GraphicDriver::InitEglContext (Aspect_Display          t
 {
   ReleaseContext();
 #if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__)
-#if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+#if defined(HAVE_XLIB)
   if (myDisplayConnection.IsNull())
   {
     return Standard_False;
@@ -412,8 +414,8 @@ void OpenGl_GraphicDriver::chooseVisualInfo()
     return;
   }
 
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__)
-  Display* aDisp = myDisplayConnection->GetDisplay();
+#if defined(HAVE_XLIB)
+  Display* aDisp = (Display* )myDisplayConnection->GetDisplayAspect();
 
   XVisualInfo* aVisInfo = NULL;
   Aspect_FBConfig anFBConfig = NULL;
@@ -472,7 +474,7 @@ void OpenGl_GraphicDriver::chooseVisualInfo()
 #endif
   if (aVisInfo != NULL)
   {
-    myDisplayConnection->SetDefaultVisualInfo (aVisInfo, anFBConfig);
+    myDisplayConnection->SetDefaultVisualInfo ((Aspect_XVisualInfo* )aVisInfo, anFBConfig);
   }
   else
   {
@@ -844,65 +846,30 @@ Handle(OpenGl_Window) OpenGl_GraphicDriver::CreateRenderWindow (const Handle(Asp
 //function : ViewExists
 //purpose  :
 //=======================================================================
-Standard_Boolean OpenGl_GraphicDriver::ViewExists (const Handle(Aspect_Window)& AWindow, Handle(Graphic3d_CView)& theView)
+Standard_Boolean OpenGl_GraphicDriver::ViewExists (const Handle(Aspect_Window)& theWindow,
+                                                   Handle(Graphic3d_CView)& theView)
 {
-  Standard_Boolean isExist = Standard_False;
-
-  // Parse the list of views to find
-  // a view with the specified window
-
-#if defined(_WIN32) && !defined(OCCT_UWP)
-  const Handle(WNT_Window) THEWindow = Handle(WNT_Window)::DownCast (AWindow);
-  Aspect_Handle TheSpecifiedWindowId = THEWindow->HWindow ();
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-  const Handle(Cocoa_Window) THEWindow = Handle(Cocoa_Window)::DownCast (AWindow);
-  #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
-    UIView* TheSpecifiedWindowId = THEWindow->HView();
-  #else
-    NSView* TheSpecifiedWindowId = THEWindow->HView();
-  #endif
-#elif defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(OCCT_UWP)
-  (void )AWindow;
-  int TheSpecifiedWindowId = -1;
-#else
-  const Handle(Xw_Window) THEWindow = Handle(Xw_Window)::DownCast (AWindow);
-  int TheSpecifiedWindowId = int (THEWindow->XWindow ());
-#endif
-
-  NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView);
-  for(; aViewIt.More(); aViewIt.Next())
+  // Parse the list of views to find a view with the specified window
+  const Aspect_Drawable aNativeHandle = theWindow->NativeHandle();
+  for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView); aViewIt.More(); aViewIt.Next())
   {
     const Handle(OpenGl_View)& aView = aViewIt.Value();
-    if (aView->IsDefined() && aView->IsActive())
+    if (!aView->IsDefined()
+     || !aView->IsActive())
     {
-      const Handle(Aspect_Window) AspectWindow = aView->Window();
+      continue;
+    }
 
-#if defined(_WIN32) && !defined(OCCT_UWP)
-      const Handle(WNT_Window) theWindow = Handle(WNT_Window)::DownCast (AspectWindow);
-      Aspect_Handle TheWindowIdOfView = theWindow->HWindow ();
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-      const Handle(Cocoa_Window) theWindow = Handle(Cocoa_Window)::DownCast (AspectWindow);
-      #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
-        UIView* TheWindowIdOfView = theWindow->HView();
-      #else
-        NSView* TheWindowIdOfView = theWindow->HView();
-      #endif
-#elif defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(OCCT_UWP)
-      int TheWindowIdOfView = 0;
-#else
-      const Handle(Xw_Window) theWindow = Handle(Xw_Window)::DownCast (AspectWindow);
-      int TheWindowIdOfView = int (theWindow->XWindow ());
-#endif  // WNT
-      // Comparaison on window IDs
-      if (TheWindowIdOfView == TheSpecifiedWindowId)
-      {
-        isExist = Standard_True;
-        theView = aView;
-      }
+    const Handle(Aspect_Window) anAspectWindow = aView->Window();
+    const Aspect_Drawable aViewNativeHandle = anAspectWindow->NativeHandle();
+    if (aViewNativeHandle == aNativeHandle)
+    {
+      theView = aView;
+      return true;
     }
   }
 
-  return isExist;
+  return false;
 }
 
 //=======================================================================
diff --git a/src/OpenGl/OpenGl_Window.cxx b/src/OpenGl/OpenGl_Window.cxx
index e503759083..ce4b4ce802 100644
--- a/src/OpenGl/OpenGl_Window.cxx
+++ b/src/OpenGl/OpenGl_Window.cxx
@@ -34,10 +34,11 @@ IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Window,Standard_Transient)
 
 #if defined(HAVE_EGL)
   #include <EGL/egl.h>
+#elif defined(HAVE_XLIB)
+  #include <GL/glx.h>
 #endif
 
-
-#if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
+#if !defined(__APPLE__) || defined(HAVE_XLIB)
 
 namespace
 {
@@ -123,7 +124,7 @@ namespace
   {
     return DefWindowProcW (theWin, theMsg, theParamW, theParamL);
   }
-#else
+#elif defined(HAVE_XLIB)
 
   // GLX_ARB_create_context
 #ifndef GLX_CONTEXT_MAJOR_VERSION_ARB
@@ -206,16 +207,40 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_GraphicDriver)& theDriver,
                                         anEglConfig,
                                         (EGLNativeWindowType )myPlatformWindow->NativeHandle(),
                                         NULL);
-    if (anEglSurf == EGL_NO_SURFACE)
+    if (anEglSurf == EGL_NO_SURFACE
+     && myPlatformWindow->NativeHandle() != 0)
     {
       throw Aspect_GraphicDeviceDefinitionError("OpenGl_Window, EGL is unable to create surface for window!");
-      return;
+    }
+    else if (anEglSurf == EGL_NO_SURFACE)
+    {
+      // window-less EGL context (off-screen)
+      //throw Aspect_GraphicDeviceDefinitionError("OpenGl_Window, EGL is unable to retrieve current surface!");
+      if (anEglConfig != NULL)
+      {
+      #if !defined(__EMSCRIPTEN__) // eglCreatePbufferSurface() is not implemented by Emscripten EGL
+        const int aSurfAttribs[] =
+        {
+          EGL_WIDTH,  myWidth,
+          EGL_HEIGHT, myHeight,
+          // EGL_KHR_gl_colorspace extension specifies if OpenGL should write into window buffer as into sRGB or RGB framebuffer
+          //EGL_GL_COLORSPACE_KHR, !theCaps->sRGBDisable ? EGL_GL_COLORSPACE_SRGB_KHR : EGL_GL_COLORSPACE_LINEAR_KHR,
+          EGL_NONE
+        };
+        anEglSurf = eglCreatePbufferSurface (anEglDisplay, anEglConfig, aSurfAttribs);
+        if (anEglSurf == EGL_NO_SURFACE)
+        {
+          throw Aspect_GraphicDeviceDefinitionError("OpenGl_Window, EGL is unable to create off-screen surface!");
+        }
+      #endif
+      }
+      myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
+                                "OpenGl_Window::CreateWindow: WARNING, a Window is created without a EGL Surface!");
     }
   }
   else if (theGContext != anEglContext)
   {
     throw Aspect_GraphicDeviceDefinitionError("OpenGl_Window, EGL is used in unsupported combination!");
-    return;
   }
   else
   {
@@ -502,9 +527,9 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_GraphicDriver)& theDriver,
   }
 
   myGlContext->Init ((Aspect_Handle )aWindow, (Aspect_Handle )aWindowDC, (Aspect_RenderingContext )aGContext, isCoreProfile);
-#else
+#elif defined(HAVE_XLIB)
   Window     aWindow   = (Window )myPlatformWindow->NativeHandle();
-  Display*   aDisp     = theDriver->GetDisplayConnection()->GetDisplay();
+  Display*   aDisp     = (Display* )theDriver->GetDisplayConnection()->GetDisplayAspect();
   GLXContext aGContext = (GLXContext )theGContext;
   GLXContext aSlaveCtx = !theShareCtx.IsNull() ? (GLXContext )theShareCtx->myGContext : NULL;
 
@@ -631,6 +656,9 @@ OpenGl_Window::OpenGl_Window (const Handle(OpenGl_GraphicDriver)& theDriver,
   }
 
   myGlContext->Init ((Aspect_Drawable )aWindow, (Aspect_Display )aDisp, (Aspect_RenderingContext )aGContext, isCoreProfile);
+#else
+  // not implemented
+  (void )isCoreProfile;
 #endif
   myGlContext->Share (theShareCtx);
   myGlContext->SetSwapInterval (mySwapInterval);
@@ -661,7 +689,7 @@ OpenGl_Window::~OpenGl_Window()
   }
 #elif defined(_WIN32)
   HWND  aWindow          = (HWND  )myGlContext->myWindow;
-  HDC   aWindowDC        = (HDC   )myGlContext->myWindowDC;
+  HDC   aWindowDC        = (HDC   )myGlContext->myDisplay;
   HGLRC aWindowGContext  = (HGLRC )myGlContext->myGContext;
   HGLRC aThreadGContext  = wglGetCurrentContext();
   myGlContext.Nullify();
@@ -676,7 +704,7 @@ OpenGl_Window::~OpenGl_Window()
     wglDeleteContext (aWindowGContext);
   }
   ReleaseDC (aWindow, aWindowDC);
-#else
+#elif defined(HAVE_XLIB)
   Display*    aDisplay        = (Display*    )myGlContext->myDisplay;
   GLXContext  aWindowGContext = (GLXContext  )myGlContext->myGContext;
   GLXContext  aThreadGContext = glXGetCurrentContext();
@@ -693,6 +721,8 @@ OpenGl_Window::~OpenGl_Window()
     glXWaitGL();
     glXDestroyContext (aDisplay, aWindowGContext);
   }
+#else
+  // not implemented
 #endif
 }
 
@@ -707,7 +737,7 @@ Standard_Boolean OpenGl_Window::Activate()
   return myGlContext->MakeCurrent();
 }
 
-#if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
+#if !defined(__APPLE__) || defined(HAVE_XLIB)
 
 // =======================================================================
 // function : Resize
diff --git a/src/OpenGl/OpenGl_Window_1.mm b/src/OpenGl/OpenGl_Window_1.mm
index 4b24c53e8f..13c4f1f27c 100644
--- a/src/OpenGl/OpenGl_Window_1.mm
+++ b/src/OpenGl/OpenGl_Window_1.mm
@@ -13,7 +13,7 @@
 // Alternatively, this file may be used under the terms of Open CASCADE
 // commercial license or contractual agreement.
 
-#if defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#if defined(__APPLE__) && !defined(HAVE_XLIB)
 
 #ifndef GL_GLEXT_LEGACY
 #define GL_GLEXT_LEGACY // To prevent inclusion of system glext.h on Mac OS X 10.6.8
diff --git a/src/TKService/PACKAGES b/src/TKService/PACKAGES
index 1196ba0e84..87a69cc7f1 100755
--- a/src/TKService/PACKAGES
+++ b/src/TKService/PACKAGES
@@ -1,5 +1,4 @@
 Aspect
-InterfaceGraphic
 Graphic3d
 Xw
 Image
diff --git a/src/ViewerTest/ViewerTest_ViewerCommands.cxx b/src/ViewerTest/ViewerTest_ViewerCommands.cxx
index ee7db32660..f9d99c16de 100644
--- a/src/ViewerTest/ViewerTest_ViewerCommands.cxx
+++ b/src/ViewerTest/ViewerTest_ViewerCommands.cxx
@@ -101,12 +101,14 @@
   #include <WNT_WClass.hxx>
   #include <WNT_Window.hxx>
   #include <WNT_HIDSpaceMouse.hxx>
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#elif defined(HAVE_XLIB)
+  #include <Xw_Window.hxx>
+  #include <X11/Xlib.h>
+  #include <X11/Xutil.h>
+#elif defined(__APPLE__)
   #include <Cocoa_Window.hxx>
 #else
-  #include <Xw_Window.hxx>
-  #include <X11/Xlib.h> /* contains some dangerous #defines such as Status, True etc. */
-  #include <X11/Xutil.h>
+  #include <Aspect_NeutralWindow.hxx>
 #endif
 
 //==============================================================================
@@ -120,28 +122,24 @@ Standard_EXPORT int ViewerMainLoop(Standard_Integer , const char** argv);
 extern ViewerTest_DoubleMapOfInteractiveAndName& GetMapOfAIS();
 
 #if defined(_WIN32)
-static Handle(WNT_Window)& VT_GetWindow() {
-  static Handle(WNT_Window) WNTWin;
-  return WNTWin;
-}
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-static Handle(Cocoa_Window)& VT_GetWindow()
-{
-  static Handle(Cocoa_Window) aWindow;
-  return aWindow;
-}
+typedef WNT_Window ViewerTest_Window;
+#elif defined(HAVE_XLIB)
+typedef Xw_Window ViewerTest_Window;
+static void VProcessEvents(ClientData,int);
+#elif defined(__APPLE__)
+typedef Cocoa_Window ViewerTest_Window;
 extern void ViewerTest_SetCocoaEventManagerView (const Handle(Cocoa_Window)& theWindow);
 extern void GetCocoaScreenResolution (Standard_Integer& theWidth, Standard_Integer& theHeight);
-
 #else
-static Handle(Xw_Window)& VT_GetWindow(){
-  static Handle(Xw_Window) XWWin;
-  return XWWin;
-}
-
-static void VProcessEvents(ClientData,int);
+typedef Aspect_NeutralWindow ViewerTest_Window;
 #endif
 
+static Handle(ViewerTest_Window)& VT_GetWindow()
+{
+  static Handle(ViewerTest_Window) aWindow;
+  return aWindow;
+}
+
 static Handle(Aspect_DisplayConnection)& GetDisplayConnection()
 {
   static Handle(Aspect_DisplayConnection) aDisplayConnection;
@@ -1706,16 +1704,16 @@ TCollection_AsciiString ViewerTest::ViewerInit (const Standard_Integer thePxLeft
   if (isNewDriver)
   {
     // Get connection string
-  #if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+  #if defined(HAVE_XLIB)
     if (!theDisplayName.IsEmpty())
     {
       SetDisplayConnection (new Aspect_DisplayConnection (theDisplayName));
     }
     else
     {
-      ::Display* aDispX = NULL;
+      Aspect_XDisplay* aDispX = NULL;
       // create dedicated display connection instead of reusing Tk connection
-      // so that to procede events independently through VProcessEvents()/ViewerMainLoop() callbacks
+      // so that to proceed events independently through VProcessEvents()/ViewerMainLoop() callbacks
       /*Draw_Interpretor& aCommands = Draw::GetInterpretor();
       Tcl_Interp* aTclInterp = aCommands.Interp();
       Tk_Window aMainWindow = Tk_MainWindow (aTclInterp);
@@ -1753,17 +1751,20 @@ TCollection_AsciiString ViewerTest::ViewerInit (const Standard_Integer thePxLeft
                      aScreenHeight = 0;
 
     // Get screen resolution
-#if defined(_WIN32) || defined(__WIN32__)
+#if defined(_WIN32)
     RECT aWindowSize;
     GetClientRect(GetDesktopWindow(), &aWindowSize);
     aScreenHeight = aWindowSize.bottom;
     aScreenWidth = aWindowSize.right;
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#elif defined(HAVE_XLIB)
+    ::Display* aDispX = (::Display* )GetDisplayConnection()->GetDisplayAspect();
+    Screen* aScreen = DefaultScreenOfDisplay(aDispX);
+    aScreenWidth  = WidthOfScreen(aScreen);
+    aScreenHeight = HeightOfScreen(aScreen);
+#elif defined(__APPLE__)
     GetCocoaScreenResolution (aScreenWidth, aScreenHeight);
 #else
-    Screen *aScreen = DefaultScreenOfDisplay(GetDisplayConnection()->GetDisplay());
-    aScreenWidth = WidthOfScreen(aScreen);
-    aScreenHeight = HeightOfScreen(aScreen);
+    // not implemented
 #endif
 
     TCollection_AsciiString anOverlappedViewId("");
@@ -1846,16 +1847,20 @@ TCollection_AsciiString ViewerTest::ViewerInit (const Standard_Integer thePxLeft
                                     aPxWidth, aPxHeight,
                                     Quantity_NOC_BLACK);
   VT_GetWindow()->RegisterRawInputDevices (WNT_Window::RawInputMask_SpaceMouse);
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#elif defined(HAVE_XLIB)
+  VT_GetWindow() = new Xw_Window (aGraphicDriver->GetDisplayConnection(),
+                                  aTitle.ToCString(),
+                                  aPxLeft, aPxTop,
+                                  aPxWidth, aPxHeight);
+#elif defined(__APPLE__)
   VT_GetWindow() = new Cocoa_Window (aTitle.ToCString(),
                                      aPxLeft, aPxTop,
                                      aPxWidth, aPxHeight);
   ViewerTest_SetCocoaEventManagerView (VT_GetWindow());
 #else
-  VT_GetWindow() = new Xw_Window (aGraphicDriver->GetDisplayConnection(),
-                                  aTitle.ToCString(),
-                                  aPxLeft, aPxTop,
-                                  aPxWidth, aPxHeight);
+  // not implemented
+  VT_GetWindow() = new Aspect_NeutralWindow();
+  VT_GetWindow()->SetSize (aPxWidth, aPxHeight);
 #endif
   VT_GetWindow()->SetVirtual (isVirtual);
 
@@ -1890,10 +1895,10 @@ TCollection_AsciiString ViewerTest::ViewerInit (const Standard_Integer thePxLeft
     a3DViewer->SetLightOn();
   }
 
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+#if defined(HAVE_XLIB)
   if (isNewDriver)
   {
-    ::Display* aDispX = GetDisplayConnection()->GetDisplay();
+    ::Display* aDispX = (::Display* )GetDisplayConnection()->GetDisplayAspect();
     Tcl_CreateFileHandler (XConnectionNumber (aDispX), TCL_READABLE, VProcessEvents, (ClientData )aDispX);
   }
 #endif
@@ -2225,7 +2230,7 @@ static int VInit (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const cha
     }
   }
 
-#if defined(_WIN32) || (defined(__APPLE__) && !defined(MACOSX_USE_GLX))
+#if !defined(HAVE_XLIB)
   if (!aDisplayName.IsEmpty())
   {
     aDisplayName.Clear();
@@ -2495,8 +2500,8 @@ static int VHLRType (Draw_Interpretor& , Standard_Integer argc, const char** arg
 //function : FindViewIdByWindowHandle
 //purpose  : Find theView Id in the map of views by window handle
 //==============================================================================
-#if defined(_WIN32) || (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
-TCollection_AsciiString FindViewIdByWindowHandle (Aspect_Drawable theWindowHandle)
+#if defined(_WIN32) || defined(HAVE_XLIB)
+static TCollection_AsciiString FindViewIdByWindowHandle (Aspect_Drawable theWindowHandle)
 {
   for (NCollection_DoubleMap<TCollection_AsciiString, Handle(V3d_View)>::Iterator
        anIter(ViewerTest_myViews); anIter.More(); anIter.Next())
@@ -2532,10 +2537,12 @@ void ActivateView (const TCollection_AsciiString& theViewName,
     aView->Window()->SetTitle (TCollection_AsciiString("3D View - ") + theViewName + "(*)");
 #if defined(_WIN32)
     VT_GetWindow() = Handle(WNT_Window)::DownCast(ViewerTest::CurrentView()->Window());
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#elif defined(HAVE_XLIB)
+    VT_GetWindow() = Handle(Xw_Window)::DownCast(ViewerTest::CurrentView()->Window());
+#elif defined(__APPLE__)
     VT_GetWindow() = Handle(Cocoa_Window)::DownCast(ViewerTest::CurrentView()->Window());
 #else
-    VT_GetWindow() = Handle(Xw_Window)::DownCast(ViewerTest::CurrentView()->Window());
+    VT_GetWindow() = Handle(Aspect_NeutralWindow)::DownCast(ViewerTest::CurrentView()->Window());
 #endif
     SetDisplayConnection(ViewerTest::CurrentView()->Viewer()->Driver()->GetDisplayConnection());
     if (theToUpdate)
@@ -2613,8 +2620,8 @@ void ViewerTest::RemoveView (const TCollection_AsciiString& theViewName, const S
   aView->Window()->Unmap();
   aView->Remove();
 
-#if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
-  XFlush (GetDisplayConnection()->GetDisplay());
+#if defined(HAVE_XLIB)
+  XFlush ((::Display* )GetDisplayConnection()->GetDisplayAspect());
 #endif
 
   // Keep context opened only if the closed view is last to avoid
@@ -2642,8 +2649,8 @@ void ViewerTest::RemoveView (const TCollection_AsciiString& theViewName, const S
       if(isRemoveDriver)
       {
         ViewerTest_myDrivers.UnBind2 (aCurrentContext->CurrentViewer()->Driver());
-      #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
-        Tcl_DeleteFileHandler (XConnectionNumber (aCurrentContext->CurrentViewer()->Driver()->GetDisplayConnection()->GetDisplay()));
+      #if defined(HAVE_XLIB)
+        Tcl_DeleteFileHandler (XConnectionNumber ((::Display* )aCurrentContext->CurrentViewer()->Driver()->GetDisplayConnection()->GetDisplayAspect()));
       #endif
       }
 
@@ -3323,7 +3330,7 @@ int ViewerMainLoop (Standard_Integer theNbArgs, const char** theArgVec)
   return 0;
 }
 
-#elif !defined(__APPLE__) || defined(MACOSX_USE_GLX)
+#elif defined(HAVE_XLIB)
 
 int ViewerMainLoop (Standard_Integer theNbArgs, const char** theArgVec)
 {
@@ -3338,7 +3345,7 @@ int ViewerMainLoop (Standard_Integer theNbArgs, const char** theArgVec)
     ViewerTest::CurrentEventManager()->StartPickPoint (theArgVec[1], theArgVec[2], theArgVec[3]);
   }
 
-  Display* aDisplay = GetDisplayConnection()->GetDisplay();
+  Display* aDisplay = (Display* )GetDisplayConnection()->GetDisplayAspect();
   XNextEvent (aDisplay, &aReport);
 
   // Handle event for the chosen display connection
@@ -3398,7 +3405,7 @@ static void VProcessEvents (ClientData theDispX, int)
        aDriverIter (ViewerTest_myDrivers); aDriverIter.More(); aDriverIter.Next())
   {
     const Handle(Aspect_DisplayConnection)& aDispConnTmp = aDriverIter.Key2()->GetDisplayConnection();
-    if (aDispConnTmp->GetDisplay() == aDispX)
+    if ((Display* )aDispConnTmp->GetDisplayAspect() == aDispX)
     {
       aDispConn = aDispConnTmp;
       break;
@@ -3449,47 +3456,55 @@ static void VProcessEvents (ClientData theDispX, int)
     SetDisplayConnection (anActiveCtx->CurrentViewer()->Driver()->GetDisplayConnection());
   }
 }
+#elif !defined(__APPLE__)
+// =======================================================================
+// function : ViewerMainLoop
+// purpose  :
+// =======================================================================
+int ViewerMainLoop (Standard_Integer , const char** )
+{
+  // unused
+  return 0;
+}
 #endif
 
 //==============================================================================
 //function : OSWindowSetup
-//purpose  : Setup for the X11 window to be able to cath the event
+//purpose  : Setup for the X11 window to be able to catch the event
 //==============================================================================
-
-
 static void OSWindowSetup()
 {
-#if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
-  // X11
+#ifdef _WIN32
+  //
 
-  Window  window   = VT_GetWindow()->XWindow();
+#elif defined(HAVE_XLIB)
+  // X11
+  Window anXWin = VT_GetWindow()->XWindow();
   SetDisplayConnection (ViewerTest::CurrentView()->Viewer()->Driver()->GetDisplayConnection());
-  Display *aDisplay = GetDisplayConnection()->GetDisplay();
-  XSynchronize(aDisplay, 1);
+  Display* aDisplay = (Display* )GetDisplayConnection()->GetDisplayAspect();
+  XSynchronize (aDisplay, 1);
 
   // X11 : For keyboard on SUN
-  XWMHints wmhints;
-  wmhints.flags = InputHint;
-  wmhints.input = 1;
+  XWMHints aWmHints;
+  memset (&aWmHints, 0, sizeof(aWmHints));
+  aWmHints.flags = InputHint;
+  aWmHints.input = 1;
+  XSetWMHints (aDisplay, anXWin, &aWmHints);
 
-  XSetWMHints( aDisplay, window, &wmhints);
-
-  XSelectInput( aDisplay, window,  ExposureMask | KeyPressMask | KeyReleaseMask |
-    ButtonPressMask | ButtonReleaseMask |
-    StructureNotifyMask |
-    PointerMotionMask |
-    Button1MotionMask | Button2MotionMask |
-    Button3MotionMask | FocusChangeMask
-    );
-  Atom aDeleteWindowAtom = GetDisplayConnection()->GetAtom(Aspect_XA_DELETE_WINDOW);
-  XSetWMProtocols(aDisplay, window, &aDeleteWindowAtom, 1);
-
-  XSynchronize(aDisplay, 0);
+  XSelectInput (aDisplay, anXWin,
+                ExposureMask | KeyPressMask | KeyReleaseMask
+              | ButtonPressMask | ButtonReleaseMask
+              | StructureNotifyMask
+              | PointerMotionMask
+              | Button1MotionMask | Button2MotionMask
+              | Button3MotionMask | FocusChangeMask);
+  Atom aDeleteWindowAtom = GetDisplayConnection()->GetAtom (Aspect_XA_DELETE_WINDOW);
+  XSetWMProtocols (aDisplay, anXWin, &aDeleteWindowAtom, 1);
 
+  XSynchronize (aDisplay, 0);
 #else
-  // _WIN32
+  //
 #endif
-
 }
 
 //==============================================================================
@@ -14117,7 +14132,7 @@ void ViewerTest::ViewerCommands(Draw_Interpretor& theCommands)
   theCommands.Add("vinit",
           "vinit [-name viewName] [-left leftPx] [-top topPx] [-width widthPx] [-height heightPx]"
     "\n\t\t:     [-exitOnClose] [-closeOnEscape] [-cloneActive] [-virtual {on|off}=off] [-2d_mode {on|off}=off]"
-  #if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+  #if defined(HAVE_XLIB)
     "\n\t\t:     [-display displayName]"
   #endif
     "\n\t\t: Creates new View window with specified name viewName."
@@ -14126,7 +14141,7 @@ void ViewerTest::ViewerCommands(Draw_Interpretor& theCommands)
     "\n\t\t:  -name {driverName/viewerName/viewName | viewerName/viewName | viewName}"
     "\n\t\t: If driverName isn't specified the driver will be shared with active view."
     "\n\t\t: If viewerName isn't specified the viewer will be shared with active view."
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+#if defined(HAVE_XLIB)
     "\n\t\t:  -display HostName.DisplayNumber[:ScreenNumber]"
     "\n\t\t: Display name will be used within creation of graphic driver, when specified."
 #endif
diff --git a/src/ViewerTest/ViewerTest_ViewerCommands_1.mm b/src/ViewerTest/ViewerTest_ViewerCommands_1.mm
index 86576cce22..00337769a4 100644
--- a/src/ViewerTest/ViewerTest_ViewerCommands_1.mm
+++ b/src/ViewerTest/ViewerTest_ViewerCommands_1.mm
@@ -11,7 +11,7 @@
 // Alternatively, this file may be used under the terms of Open CASCADE
 // commercial license or contractual agreement.
 
-#if defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+#if defined(__APPLE__) && !defined(HAVE_XLIB)
 
 #import <Cocoa/Cocoa.h>
 
diff --git a/src/Xw/Xw_Window.cxx b/src/Xw/Xw_Window.cxx
index 47d93dc608..e7e5b05ce4 100644
--- a/src/Xw/Xw_Window.cxx
+++ b/src/Xw/Xw_Window.cxx
@@ -15,16 +15,22 @@
 
 #include <Xw_Window.hxx>
 
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__)
-
 #include <Aspect_Convert.hxx>
 #include <Aspect_ScrollDelta.hxx>
 #include <Aspect_WindowDefinitionError.hxx>
 #include <Aspect_WindowInputListener.hxx>
 #include <Message.hxx>
 #include <Message_Messenger.hxx>
+#include <Standard_NotImplemented.hxx>
 
-//#include <X11/XF86keysym.h>
+#if defined(HAVE_XLIB)
+  #include <X11/Xlib.h>
+  #include <X11/Xutil.h>
+  #include <X11/Xatom.h>
+  //#include <X11/XF86keysym.h>
+#endif
+
+#include <Aspect_DisplayConnection.hxx>
 
 IMPLEMENT_STANDARD_RTTIEXT(Xw_Window, Aspect_Window)
 
@@ -57,17 +63,17 @@ Xw_Window::Xw_Window (const Handle(Aspect_DisplayConnection)& theXDisplay,
     throw Aspect_WindowDefinitionError("Xw_Window, X Display connection is undefined");
   }
 
+#if defined(HAVE_XLIB)
   myFBConfig = theXDisplay->GetDefaultFBConfig();
-  XVisualInfo* aVisInfo = theXDisplay->GetDefaultVisualInfo();
+  XVisualInfo* aVisInfo = theXDisplay->GetDefaultVisualInfoX();
 
   Display* aDisp   = myDisplay->GetDisplay();
   int      aScreen = DefaultScreen(aDisp);
   Window   aParent = RootWindow   (aDisp, aScreen);
 
-
   unsigned long aMask = 0;
   XSetWindowAttributes aWinAttr;
-  memset(&aWinAttr, 0, sizeof(XSetWindowAttributes));
+  memset (&aWinAttr, 0, sizeof(aWinAttr));
   aWinAttr.event_mask = ExposureMask | StructureNotifyMask;
   aMask |= CWEventMask;
   if (aVisInfo != NULL)
@@ -77,7 +83,7 @@ Xw_Window::Xw_Window (const Handle(Aspect_DisplayConnection)& theXDisplay,
   aWinAttr.border_pixel = 0;
   aWinAttr.override_redirect = False;
 
-  myXWindow = XCreateWindow(aDisp, aParent,
+  myXWindow = (Window )XCreateWindow (aDisp, aParent,
                             myXLeft, myYTop, thePxWidth, thePxHeight,
                             0, aVisInfo != NULL ? aVisInfo->depth : CopyFromParent,
                             InputOutput,
@@ -96,17 +102,24 @@ Xw_Window::Xw_Window (const Handle(Aspect_DisplayConnection)& theXDisplay,
   aSizeHints.width  = thePxWidth;
   aSizeHints.height = thePxHeight;
   aSizeHints.flags |= PSize;
-  XSetStandardProperties (aDisp, myXWindow, theTitle, theTitle, None,
+  XSetStandardProperties (aDisp, (Window )myXWindow, theTitle, theTitle, None,
                           NULL, 0, &aSizeHints);
 
   /*XTextProperty aTitleProperty;
   aTitleProperty.encoding = None;
   char* aTitle = (char* )theTitle;
   Xutf8TextListToTextProperty(aDisp, &aTitle, 1, XUTF8StringStyle, &aTitleProperty);
-  XSetWMName      (aDisp, myXWindow, &aTitleProperty);
-  XSetWMProperties(aDisp, myXWindow, &aTitleProperty, &aTitleProperty, NULL, 0, NULL, NULL, NULL);*/
+  XSetWMName      (aDisp, (Window )myXWindow, &aTitleProperty);
+  XSetWMProperties(aDisp, (Window )myXWindow, &aTitleProperty, &aTitleProperty, NULL, 0, NULL, NULL, NULL);*/
 
   XFlush (aDisp);
+#else
+  (void )theTitle;
+  if (myXWindow == 0)
+  {
+    throw Aspect_WindowDefinitionError ("Xw_Window, Unable to create window - not implemented");
+  }
+#endif
 }
 
 // =======================================================================
@@ -114,7 +127,7 @@ Xw_Window::Xw_Window (const Handle(Aspect_DisplayConnection)& theXDisplay,
 // purpose  :
 // =======================================================================
 Xw_Window::Xw_Window (const Handle(Aspect_DisplayConnection)& theXDisplay,
-                      const Window theXWin,
+                      const Aspect_Drawable theXWin,
                       const Aspect_FBConfig theFBConfig)
 : Aspect_Window(),
   myDisplay  (theXDisplay),
@@ -135,10 +148,11 @@ Xw_Window::Xw_Window (const Handle(Aspect_DisplayConnection)& theXDisplay,
     throw Aspect_WindowDefinitionError("Xw_Window, X Display connection is undefined");
   }
 
+#if defined(HAVE_XLIB)
   Display* aDisp = myDisplay->GetDisplay();
 
   XWindowAttributes aWinAttr;
-  XGetWindowAttributes (aDisp, myXWindow, &aWinAttr);
+  XGetWindowAttributes (aDisp, (Window )myXWindow, &aWinAttr);
   XVisualInfo aVisInfoTmp;
   aVisInfoTmp.visualid = aWinAttr.visual->visualid;
   aVisInfoTmp.screen   = DefaultScreen (aDisp);
@@ -151,6 +165,9 @@ Xw_Window::Xw_Window (const Handle(Aspect_DisplayConnection)& theXDisplay,
   XFree (aVisInfo);
 
   DoResize();
+#else
+  //throw Standard_NotImplemented("Xw_Window, not implemented");
+#endif
 }
 
 // =======================================================================
@@ -161,19 +178,12 @@ Xw_Window::~Xw_Window()
 {
   if (myIsOwnWin && myXWindow != 0 && !myDisplay.IsNull())
   {
-    XDestroyWindow (myDisplay->GetDisplay(), myXWindow);
+  #if defined(HAVE_XLIB)
+    XDestroyWindow (myDisplay->GetDisplay(), (Window )myXWindow);
+  #endif
   }
 }
 
-// =======================================================================
-// function : XWindow
-// purpose  :
-// =======================================================================
-Window Xw_Window::XWindow() const
-{
-  return myXWindow;
-}
-
 // =======================================================================
 // function : IsMapped
 // purpose  :
@@ -189,11 +199,15 @@ Standard_Boolean Xw_Window::IsMapped() const
     return Standard_True;
   }
 
+#if defined(HAVE_XLIB)
   XFlush (myDisplay->GetDisplay());
   XWindowAttributes aWinAttr;
-  XGetWindowAttributes (myDisplay->GetDisplay(), myXWindow, &aWinAttr);
+  XGetWindowAttributes (myDisplay->GetDisplay(), (Window )myXWindow, &aWinAttr);
   return aWinAttr.map_state == IsUnviewable
       || aWinAttr.map_state == IsViewable;
+#else
+  return Standard_False;
+#endif
 }
 
 // =======================================================================
@@ -207,8 +221,10 @@ void Xw_Window::Map() const
     return;
   }
 
-  XMapWindow (myDisplay->GetDisplay(), myXWindow);
+#if defined(HAVE_XLIB)
+  XMapWindow (myDisplay->GetDisplay(), (Window )myXWindow);
   XFlush (myDisplay->GetDisplay());
+#endif
 }
 
 // =======================================================================
@@ -222,7 +238,9 @@ void Xw_Window::Unmap() const
     return;
   }
 
-  XIconifyWindow (myDisplay->GetDisplay(), myXWindow, DefaultScreen(myDisplay->GetDisplay()));
+#if defined(HAVE_XLIB)
+  XIconifyWindow (myDisplay->GetDisplay(), (Window )myXWindow, DefaultScreen(myDisplay->GetDisplay()));
+#endif
 }
 
 // =======================================================================
@@ -236,9 +254,11 @@ Aspect_TypeOfResize Xw_Window::DoResize()
     return Aspect_TOR_UNKNOWN;
   }
 
+#if defined(HAVE_XLIB)
   XFlush (myDisplay->GetDisplay());
   XWindowAttributes aWinAttr;
-  XGetWindowAttributes (myDisplay->GetDisplay(), myXWindow, &aWinAttr);
+  memset (&aWinAttr, 0, sizeof(aWinAttr));
+  XGetWindowAttributes (myDisplay->GetDisplay(), (Window )myXWindow, &aWinAttr);
   if (aWinAttr.map_state == IsUnmapped)
   {
     return Aspect_TOR_UNKNOWN;
@@ -270,15 +290,9 @@ Aspect_TypeOfResize Xw_Window::DoResize()
   myYTop    = aWinAttr.y;
   myYBottom = aWinAttr.y + aWinAttr.height;
   return aMode;
-}
-
-// =======================================================================
-// function : DoMapping
-// purpose  :
-// =======================================================================
-Standard_Boolean Xw_Window::DoMapping() const
-{
-  return Standard_True; // IsMapped()
+#else
+  return Aspect_TOR_UNKNOWN;
+#endif
 }
 
 // =======================================================================
@@ -292,10 +306,15 @@ Standard_Real Xw_Window::Ratio() const
     return Standard_Real(myXRight - myXLeft) / Standard_Real(myYBottom - myYTop);
   }
 
+#if defined(HAVE_XLIB)
   XFlush (myDisplay->GetDisplay());
   XWindowAttributes aWinAttr;
-  XGetWindowAttributes (myDisplay->GetDisplay(), myXWindow, &aWinAttr);
+  memset (&aWinAttr, 0, sizeof(aWinAttr));
+  XGetWindowAttributes (myDisplay->GetDisplay(), (Window )myXWindow, &aWinAttr);
   return Standard_Real(aWinAttr.width) / Standard_Real(aWinAttr.height);
+#else
+  return 1.0;
+#endif
 }
 
 // =======================================================================
@@ -314,17 +333,20 @@ void Xw_Window::Position (Standard_Integer& theX1, Standard_Integer& theY1,
     return;
   }
 
+#if defined(HAVE_XLIB)
   XFlush (myDisplay->GetDisplay());
   XWindowAttributes anAttributes;
-  XGetWindowAttributes (myDisplay->GetDisplay(), myXWindow, &anAttributes);
+  memset (&anAttributes, 0, sizeof(anAttributes));
+  XGetWindowAttributes (myDisplay->GetDisplay(), (Window )myXWindow, &anAttributes);
   Window aChild;
-  XTranslateCoordinates (myDisplay->GetDisplay(), anAttributes.root, myXWindow,
+  XTranslateCoordinates (myDisplay->GetDisplay(), anAttributes.root, (Window )myXWindow,
                          0, 0, &anAttributes.x, &anAttributes.y, &aChild);
 
   theX1 = -anAttributes.x;
   theX2 = theX1 + anAttributes.width;
   theY1 = -anAttributes.y;
   theY2 = theY1 + anAttributes.height;
+#endif
 }
 
 // =======================================================================
@@ -341,11 +363,14 @@ void Xw_Window::Size (Standard_Integer& theWidth,
     return;
   }
 
+#if defined(HAVE_XLIB)
   XFlush (myDisplay->GetDisplay());
   XWindowAttributes aWinAttr;
-  XGetWindowAttributes (myDisplay->GetDisplay(), myXWindow, &aWinAttr);
+  memset (&aWinAttr, 0, sizeof(aWinAttr));
+  XGetWindowAttributes (myDisplay->GetDisplay(), (Window )myXWindow, &aWinAttr);
   theWidth  = aWinAttr.width;
   theHeight = aWinAttr.height;
+#endif
 }
 
 // =======================================================================
@@ -356,7 +381,11 @@ void Xw_Window::SetTitle (const TCollection_AsciiString& theTitle)
 {
   if (myXWindow != 0)
   {
-    XStoreName (myDisplay->GetDisplay(), myXWindow, theTitle.ToCString());
+  #if defined(HAVE_XLIB)
+    XStoreName (myDisplay->GetDisplay(), (Window )myXWindow, theTitle.ToCString());
+  #else
+    (void )theTitle;
+  #endif
   }
 }
 
@@ -371,15 +400,19 @@ void Xw_Window::InvalidateContent (const Handle(Aspect_DisplayConnection)& theDi
     return;
   }
 
+#if defined(HAVE_XLIB)
   const Handle(Aspect_DisplayConnection)& aDisp = !theDisp.IsNull() ? theDisp : myDisplay;
   Display* aDispX = aDisp->GetDisplay();
 
   XEvent anEvent;
   memset (&anEvent, 0, sizeof(anEvent));
   anEvent.type = Expose;
-  anEvent.xexpose.window = myXWindow;
-  XSendEvent (aDispX, myXWindow, False, ExposureMask, &anEvent);
+  anEvent.xexpose.window = (Window )myXWindow;
+  XSendEvent (aDispX, (Window )myXWindow, False, ExposureMask, &anEvent);
   XFlush (aDispX);
+#else
+  (void )theDisp;
+#endif
 }
 
 // =======================================================================
@@ -388,6 +421,7 @@ void Xw_Window::InvalidateContent (const Handle(Aspect_DisplayConnection)& theDi
 // =======================================================================
 Aspect_VKey Xw_Window::VirtualKeyFromNative (unsigned long theKey)
 {
+#if defined(HAVE_XLIB)
   if (theKey >= XK_0
    && theKey <= XK_9)
   {
@@ -530,6 +564,9 @@ Aspect_VKey Xw_Window::VirtualKeyFromNative (unsigned long theKey)
     case 0x1008FF29: // XF86Refresh
       return Aspect_VKey_BrowserRefresh;
   }
+#else
+  (void )theKey;
+#endif
   return Aspect_VKey_UNKNOWN;
 }
 
@@ -538,8 +575,13 @@ Aspect_VKey Xw_Window::VirtualKeyFromNative (unsigned long theKey)
 // purpose  :
 // =======================================================================
 bool Xw_Window::ProcessMessage (Aspect_WindowInputListener& theListener,
-                                XEvent& theMsg)
+                                XEvent&
+                                #if defined(HAVE_XLIB) // msvc before VS2015 had problems with (void )theMsg
+                                        theMsg
+                                #endif
+                                )
 {
+#if defined(HAVE_XLIB)
   Display* aDisplay = myDisplay->GetDisplay();
 
   // Handle event for the chosen display connection
@@ -548,7 +590,7 @@ bool Xw_Window::ProcessMessage (Aspect_WindowInputListener& theListener,
     case ClientMessage:
     {
       if ((Atom)theMsg.xclient.data.l[0] == myDisplay->GetAtom (Aspect_XA_DELETE_WINDOW)
-       && theMsg.xclient.window == myXWindow)
+       && theMsg.xclient.window == (Window )myXWindow)
       {
         theListener.ProcessClose();
         return true;
@@ -558,7 +600,7 @@ bool Xw_Window::ProcessMessage (Aspect_WindowInputListener& theListener,
     case FocusIn:
     case FocusOut:
     {
-      if (theMsg.xfocus.window == myXWindow)
+      if (theMsg.xfocus.window == (Window )myXWindow)
       {
         theListener.ProcessFocus (theMsg.type == FocusIn);
       }
@@ -566,7 +608,7 @@ bool Xw_Window::ProcessMessage (Aspect_WindowInputListener& theListener,
     }
     case Expose:
     {
-      if (theMsg.xexpose.window == myXWindow)
+      if (theMsg.xexpose.window == (Window )myXWindow)
       {
         theListener.ProcessExpose();
       }
@@ -574,7 +616,7 @@ bool Xw_Window::ProcessMessage (Aspect_WindowInputListener& theListener,
       // remove all the ExposureMask and process them at once
       for (int aNbMaxEvents = XPending (aDisplay); aNbMaxEvents > 0; --aNbMaxEvents)
       {
-        if (!XCheckWindowEvent (aDisplay, myXWindow, ExposureMask, &theMsg))
+        if (!XCheckWindowEvent (aDisplay, (Window )myXWindow, ExposureMask, &theMsg))
         {
           break;
         }
@@ -587,13 +629,13 @@ bool Xw_Window::ProcessMessage (Aspect_WindowInputListener& theListener,
       // remove all the StructureNotifyMask and process them at once
       for (int aNbMaxEvents = XPending (aDisplay); aNbMaxEvents > 0; --aNbMaxEvents)
       {
-        if (!XCheckWindowEvent (aDisplay, myXWindow, StructureNotifyMask, &theMsg))
+        if (!XCheckWindowEvent (aDisplay, (Window )myXWindow, StructureNotifyMask, &theMsg))
         {
           break;
         }
       }
 
-      if (theMsg.xconfigure.window == myXWindow)
+      if (theMsg.xconfigure.window == (Window )myXWindow)
       {
         theListener.ProcessConfigure (true);
       }
@@ -661,7 +703,7 @@ bool Xw_Window::ProcessMessage (Aspect_WindowInputListener& theListener,
     }
     case MotionNotify:
     {
-      if (theMsg.xmotion.window != myXWindow)
+      if (theMsg.xmotion.window != (Window )myXWindow)
       {
         return false;
       }
@@ -669,7 +711,7 @@ bool Xw_Window::ProcessMessage (Aspect_WindowInputListener& theListener,
       // remove all the ButtonMotionMask and process them at once
       for (int aNbMaxEvents = XPending (aDisplay); aNbMaxEvents > 0; --aNbMaxEvents)
       {
-        if (!XCheckWindowEvent (aDisplay, myXWindow, ButtonMotionMask | PointerMotionMask, &theMsg))
+        if (!XCheckWindowEvent (aDisplay, (Window )myXWindow, ButtonMotionMask | PointerMotionMask, &theMsg))
         {
           break;
         }
@@ -694,7 +736,8 @@ bool Xw_Window::ProcessMessage (Aspect_WindowInputListener& theListener,
       return true;
     }
   }
+#else
+  (void )theListener;
+#endif
   return false;
 }
-
-#endif //  Win32 or Mac OS X
diff --git a/src/Xw/Xw_Window.hxx b/src/Xw/Xw_Window.hxx
index bda1c4d557..13cd5595d2 100644
--- a/src/Xw/Xw_Window.hxx
+++ b/src/Xw/Xw_Window.hxx
@@ -16,20 +16,12 @@
 #ifndef _Xw_Window_H__
 #define _Xw_Window_H__
 
-#if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX)) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__)
-
 #include <Aspect_Window.hxx>
 
 #include <Aspect_VKey.hxx>
-#include <Aspect_DisplayConnection.hxx>
-#include <Aspect_FillMethod.hxx>
-#include <Aspect_GradientFillMethod.hxx>
 #include <Aspect_Handle.hxx>
-#include <Aspect_TypeOfResize.hxx>
-#include <Standard.hxx>
-#include <Standard_Type.hxx>
-#include <Quantity_NameOfColor.hxx>
 
+class Aspect_DisplayConnection;
 class Aspect_WindowDefinitionError;
 class Aspect_WindowError;
 class Aspect_WindowInputListener;
@@ -37,9 +29,12 @@ class Aspect_Background;
 class Quantity_Color;
 class Aspect_GradientBackground;
 
+typedef union _XEvent XEvent;
+
 //! This class defines XLib window intended for creation of OpenGL context.
 class Xw_Window : public Aspect_Window
 {
+  DEFINE_STANDARD_RTTIEXT(Xw_Window, Aspect_Window)
 public:
 
   //! Convert X11 virtual key (KeySym) into Aspect_VKey.
@@ -58,10 +53,10 @@ public:
 
   //! Creates a wrapper over existing Window handle
   Standard_EXPORT Xw_Window (const Handle(Aspect_DisplayConnection)& theXDisplay,
-                             const Window theXWin,
+                             const Aspect_Drawable theXWin,
                              const Aspect_FBConfig theFBConfig = NULL);
 
-  //! Destroys the Window and all resourses attached to it
+  //! Destroys the Window and all resources attached to it
   Standard_EXPORT ~Xw_Window();
 
   //! Opens the window <me>
@@ -74,7 +69,10 @@ public:
   Standard_EXPORT virtual Aspect_TypeOfResize DoResize() Standard_OVERRIDE;
 
   //! Apply the mapping change to the window <me>
-  Standard_EXPORT virtual Standard_Boolean DoMapping() const Standard_OVERRIDE;
+  virtual Standard_Boolean DoMapping() const Standard_OVERRIDE
+  {
+    return Standard_True; // IsMapped()
+  }
 
   //! Returns True if the window <me> is opened
   Standard_EXPORT virtual Standard_Boolean IsMapped() const Standard_OVERRIDE;
@@ -93,7 +91,7 @@ public:
                                      Standard_Integer& theHeight) const Standard_OVERRIDE;
 
   //! @return native Window handle
-  Standard_EXPORT Window XWindow() const;
+  Aspect_Drawable XWindow() const { return myXWindow; }
 
   //! @return connection to X Display
   Standard_EXPORT const Handle(Aspect_DisplayConnection)& DisplayConnection() const;
@@ -101,7 +99,7 @@ public:
   //! @return native Window handle
   virtual Aspect_Drawable NativeHandle() const Standard_OVERRIDE
   {
-    return (Aspect_Drawable )XWindow();
+    return myXWindow;
   }
 
   //! @return parent of native Window handle
@@ -136,7 +134,7 @@ public:
 protected:
 
   Handle(Aspect_DisplayConnection) myDisplay; //!< X Display connection
-  Window           myXWindow;  //!< XLib window handle
+  Aspect_Drawable  myXWindow;  //!< XLib window handle
   Aspect_FBConfig  myFBConfig; //!< GLXFBConfig
   Standard_Integer myXLeft;    //!< left   position in pixels
   Standard_Integer myYTop;     //!< top    position in pixels
@@ -144,13 +142,8 @@ protected:
   Standard_Integer myYBottom;  //!< bottom position in pixels
   Standard_Boolean myIsOwnWin; //!< flag to indicate own window handle (to be deallocated on destruction)
 
-public:
-
-  DEFINE_STANDARD_RTTIEXT(Xw_Window,Aspect_Window)
-
 };
 
 DEFINE_STANDARD_HANDLE(Xw_Window, Aspect_Window)
 
-#endif //  Win32 or Mac OS X
 #endif // _Xw_Window_H__
diff --git a/tools/View/View_Widget.cxx b/tools/View/View_Widget.cxx
index e0c88e05a7..a8fd07c563 100644
--- a/tools/View/View_Widget.cxx
+++ b/tools/View/View_Widget.cxx
@@ -44,11 +44,13 @@
 #include <stdio.h>
 
 #ifdef _WIN32
-#include <WNT_Window.hxx>
-#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-#include <Cocoa_Window.hxx>
+  #include <WNT_Window.hxx>
+#elif defined(HAVE_XLIB)
+  #include <Xw_Window.hxx>
+#elif defined(__APPLE__)
+  #include <Cocoa_Window.hxx>
 #else
-#include <Xw_Window.hxx>
+
 #endif
 
 // =======================================================================
@@ -106,13 +108,15 @@ void View_Widget::Init()
 #ifdef _WIN32
   Aspect_Handle aWindowHandle = (Aspect_Handle)winId();
   Handle(Aspect_Window) aWnd = new WNT_Window (aWindowHandle);
-#elif defined (__APPLE__) && !defined (MACOSX_USE_GLX)
+#elif defined (HAVE_XLIB)
+  Aspect_Drawable aWindowHandle = (Aspect_Drawable )winId();
+  Handle(Aspect_DisplayConnection) aDispConnection = myViewer->GetContext()->CurrentViewer()->Driver()->GetDisplayConnection();
+  Handle(Aspect_Window) aWnd = new Xw_Window (aDispConnection, aWindowHandle);
+#elif defined (__APPLE__)
   NSView* aViewHandle = (NSView*)winId();
   Handle(Aspect_Window) aWnd = new Cocoa_Window (aViewHandle);
 #else
-  Window aWindowHandle = (Window)winId();
-  Handle(Aspect_DisplayConnection) aDispConnection = myViewer->GetContext()->CurrentViewer()->Driver()->GetDisplayConnection();
-  Handle(Aspect_Window) aWnd = new Xw_Window (aDispConnection, aWindowHandle);
+  //
 #endif
   myViewer->SetWindow (aWnd);