{%MainUnit win32int.pp}
{ $Id: win32winapi.inc 9810 2006-09-04 21:13:20Z micha $ }

{******************************************************************************
                         All Windows API implementations.
                   Initial Revision : Sat Nov 13 12:53:53 1999


  !! Keep alphabetical !!

  Support routines go to win32proc.pp

 ******************************************************************************
 Implementation
 ******************************************************************************

 *****************************************************************************
 *                                                                           *
 *  This file is part of the Lazarus Component Library (LCL)                 *
 *                                                                           *
 *  See the file COPYING.modifiedLGPL, included in this distribution,        *
 *  for details about the copyright.                                         *
 *                                                                           *
 *  This program is distributed in the hope that it will be useful,          *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                     *
 *                                                                           *
 *****************************************************************************
}

{$IFOPT C-}
// Uncomment for local trace
//  {$C+}
//  {$DEFINE ASSERT_IS_ON}
{$ENDIF}

Const
  BOOL_TEXT: Array[Boolean] Of String = ('False', 'True');

//##apiwiz##sps##   // Do not remove

{------------------------------------------------------------------------------
  Method:  Arc
  Params:  DC - handle to device context
           Left - x-coordinate of bounding rectangle's upper-left corner
           Top - y-coordinate of bounding rectangle's upper-left corner
           Right - x-coordinate of bounding rectangle's lower-right corner
           Bottom - y-coordinate of bounding rectangle's lower-right corner
           Angle1 - first angle
           Angle2 - second angle
  Returns: Whether the call was successful

  Use Arc to draw an elliptically curved line with the current Pen.
  The angles angle1 and angle2 are 1/16th of a degree. For example, a full
  circle equals 5760 (16*360). Positive values of Angle and AngleLength mean
  counter-clockwise while negative values mean clockwise direction.
  Zero degrees is at the 3'o clock position.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.Arc(DC: HDC; Left, Top, Right, Bottom, Angle1, Angle2: Integer): Boolean;
var
  SX, SY, EX, EY : Longint;
Begin
  Angles2Coords(Left, Top, Right - Left, Bottom - Top, Angle1, Angle2, SX, SY, EX, EY);
  Result := Boolean(Windows.Arc(DC, Left, Top, Right, Bottom, SX, SY, EX, EY));
End;

{------------------------------------------------------------------------------
  Method:   AngleChord
  Params:   DC, x1, y1, x2, y2, angle1, angle2
  Returns:  Nothing

  Use AngleChord to draw a filled Chord-shape on the canvas. The angles angle1
  and angle2 are 1/16th of a degree. For example, a full circle equals 5760
  16*360). Positive values of Angle and AngleLength mean counter-clockwise while
  negative values mean clockwise direction. Zero degrees is at the 3'o clock
  position.

------------------------------------------------------------------------------}
Function TWin32WidgetSet.AngleChord(DC: HDC; x1, y1, x2, y2, Angle1,
  Angle2: Integer): Boolean;
var
  SX, SY, EX, EY : Longint;
Begin
  Angles2Coords(x1, y1, x2-x1, y2-y1, Angle1, Angle2, SX, SY, EX, EY);
  Result := Boolean(Windows.Chord(DC, x1, y1, x2, y2, SX, SY, EX, EY));
End;

{------------------------------------------------------------------------------
  Method:  BitBlt
  Params:  DestDC        - The destination device context
           X, Y          - The left/top corner of the destination rectangle
           Width, Height - The size of the destination rectangle
           SrcDC         - The source devicecontext
           XSrc, YSrc    - The left/top corner of the source rectangle
           Rop           - The raster operation to be performed
  Returns: True if succesful

  The BitBlt function copies a bitmap from a source context into a destination
  context using the specified raster operation.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.BitBlt(DestDC: HDC; X, Y, Width, Height: Integer; SrcDC: HDC; XSrc, YSrc: Integer; Rop: DWORD): Boolean;
Begin
  Result := Boolean(Windows.BitBlt(DestDC, X, Y, Width, Height, SrcDC, XSrc, YSrc, Rop));
End;

{------------------------------------------------------------------------------
  Method:  BeginPaint
  Params:  Handle        - Handle to window to begin painting in
           PS            - PAINTSTRUCT variable that will receive painting information.
  Returns: A device context for the specified window if succesful otherwise nil

  The BeginPaint function prepares the specified window for painting and fills
  a PAINTSTRUCT structure with information about the painting.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.BeginPaint(Handle: HWND; var PS: TPaintStruct): HDC;
Begin
  Result := Windows.BeginPaint(Handle, @PS);
End;

{------------------------------------------------------------------------------
  Method:  CallDefaultWndHandler
  Params:  Sender - object, that sent the message
           Message - a TLMessage
  Returns: -

  Called by TWinControl.DefaultHandler to let the interface call some default
  functions for the message.
 ------------------------------------------------------------------------------}
Procedure TWin32WidgetSet.CallDefaultWndHandler(Sender: TObject; var Message);
var
  Handle: HWND;

  procedure CallWin32PaintHandler;
  var
    ClientBoundRect: TRect;
    PaintMsg: TLMPaint absolute Message;
  begin
    // the LCL creates paint messages, with a DC origin set to the client
    // origin of the emitting control. The paint handler of win32 expects the
    // DC origin at the origin of the control.
    // -> move the windoworigin
    ClientBoundRect:=Rect(0,0,0,0);
    if Sender is TWinControl then
      if not GetClientBounds(Handle,ClientBoundRect) then exit;
    MoveWindowOrgEx(PaintMsg.DC,-ClientBoundRect.Left,-ClientBoundRect.Top);
    try
      // call win32 paint handler
      CallDefaultWindowProc(Handle, WM_PAINT, PaintMsg.DC, 0);
    finally
      // restore DC origin
      MoveWindowOrgEx(PaintMsg.DC, ClientBoundRect.Left, ClientBoundRect.Top);
    end;
  end;

  procedure CallMouseWheelHandler;
  var
    ScrollInfo: Windows.tagScrollInfo;
    WParam: Windows.WParam;
    ScrollMsg, ScrollBar: dword;
  begin
    if not TWinControl(Sender).HandleAllocated then
      exit;

    // send scroll message
    FillChar(ScrollInfo, sizeof(ScrollInfo), #0);
    ScrollInfo.cbSize := sizeof(ScrollInfo);
    ScrollInfo.fMask := SIF_PAGE or SIF_POS or SIF_RANGE;
    // if mouse is over horizontal scrollbar, scroll horizontally
    WParam := (TLMMouseEvent(Message).X and $FFFF) or ((TLMMouseEvent(Message).Y and $FFFF) shl 16);
    if Windows.SendMessage(Handle, WM_NCHITTEST, 0, WParam) = HTHSCROLL then
    begin
      ScrollBar := SB_HORZ;
      ScrollMsg := WM_HSCROLL;
    end else begin
      ScrollBar := SB_VERT;
      ScrollMsg := WM_VSCROLL;
    end;
    if Windows.GetScrollInfo(Handle, ScrollBar, ScrollInfo) then
    begin
      with TLMMouseEvent(Message) do
      begin
        WParam := Windows.WParam(ScrollInfo.nPos - (WheelDelta * Integer(ScrollInfo.nPage)) div (120 * 8));
        if WParam > ScrollInfo.nMax - integer(ScrollInfo.nPage) + 1 then
          WParam := ScrollInfo.nMax - integer(ScrollInfo.nPage) + 1;
        if WParam < ScrollInfo.nMin then
          WParam := ScrollInfo.nMin;
        WParam := SB_THUMBPOSITION or (WParam shl 16);
      end;
      Windows.PostMessage(Handle, ScrollMsg, WParam, HWND(nil));
    end;
  end;

  procedure DrawCheckListBoxItem(CheckListBox: TCheckListBox; Data: PDrawItemStruct);
  var
    Selected: Boolean;
    lgBrush: LOGBRUSH;
    Brush: HBRUSH;
    Rect: Windows.Rect;
    Flags: Cardinal;
    OldColor: COLORREF;
    OldBackColor: COLORREF;

  begin
    Selected := (Data^.itemState AND ODS_SELECTED)>0;

    // fill the background
    if Selected then
      lgBrush.lbColor := Windows.GetSysColor(COLOR_HIGHLIGHT)
    else
      lgBrush.lbColor := Windows.GetSysColor(COLOR_WINDOW);
    lgBrush.lbStyle := BS_SOLID;
    Brush := CreateBrushIndirect(lgBrush);
    Windows.FillRect(Data^._HDC, Windows.Rect(Data^.rcItem), Brush);
    DeleteObject(Brush);

    // draw checkbox
    Flags := DFCS_BUTTONCHECK;
    if CheckListBox.Checked[Data^.ItemID] then
      Flags := Flags or DFCS_CHECKED;
    Rect.Left := Data^.rcItem.Left + 2;
    Rect.Top := Data^.rcItem.Top + 2;
    Rect.Bottom := Data^.rcItem.Bottom - 2;
    Rect.Right := Rect.Left + Rect.Bottom - Rect.Top;
    Windows.DrawFrameControl(Data^._HDC, Rect, DFC_BUTTON, Flags);

    // draw text
    Rect := Windows.Rect(Data^.rcItem);
    Rect.Right := Data^.rcItem.Right;
    Rect.Left := Rect.Bottom-Rect.Top + 5;
    if Selected then begin
      OldColor := Windows.SetTextColor(Data^._HDC, Windows.GetSysColor(COLOR_HIGHLIGHTTEXT));
      OldBackColor := Windows.SetBkColor(Data^._HDC, Windows.GetSysColor(COLOR_HIGHLIGHT));
    end;
    Windows.DrawText(Data^._HDC, PChar(CheckListBox.Items[Data^.ItemID]), -1,
      Rect, DT_SINGLELINE or DT_VCENTER or DT_NOPREFIX);
    if Selected then begin
      Windows.SetTextColor(Data^._HDC, OldColor);
      Windows.SetBkColor(Data^._HDC, OldBackColor);
    end;
  end;

begin
  Handle := ObjectToHwnd(Sender);
  case TLMessage(Message).Msg of

    LM_PAINT:
      CallWin32PaintHandler;

    LM_DRAWITEM:
    begin
      with TLMDrawItems(Message) do
      begin
        if Sender is TCheckListBox then
        begin
          // ItemID not UINT(-1)
          if DrawItemStruct^.ItemID <> DWORD($FFFFFFFF) then
            DrawCheckListBoxItem(TCheckListBox(Sender), DrawItemStruct);
        end;
      end;
    end;

    LM_MEASUREITEM:
    begin
      with TLMMeasureItem(Message).MeasureItemStruct^ do
      begin
        if Sender is TCustomListBox then
        begin
          itemHeight := TCustomListBox(Sender).ItemHeight;
          if TCustomListBox(Sender).Style = lbOwnerDrawVariable then
            TCustomListBox(Sender).MeasureItem(itemID, integer(itemHeight));
        end;
      end;
    end;

    LM_MOUSEWHEEL:
    begin
      // provide default wheel scrolling functionality
      CallMouseWheelHandler;
    end;

    LM_GETDLGCODE:
    begin
      TLMessage(Message).Result := CallDefaultWindowProc(Handle, WM_GETDLGCODE, 0, 0);
    end;

{$ifdef PassWin32MessagesToLCL}
  else
    if TLMessage(Message).Msg >= WM_USER then
    with TLMessage(Message) do
      Result := CallDefaultWindowProc(Handle, Msg, WParam, LParam);
{$endif}
  end;
end;

{------------------------------------------------------------------------------
  Method:  CallNextHookEx
  Params:  HHk    - handle of the current hook
           NCode  - Hook code
           WParam - Word parameter
           LParam - Long-integer parameter
  Returns: The handle of the next hook procedure

  Calls the next procedure in the hook chain
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CallNextHookEx(HHk: HHOOK; NCode: Integer; WParam: WParam; LParam: LParam): Integer;
Begin
  Result := Windows.CallNextHookEx(hhk, ncode, Windows.WPARAM(wParam), Windows.LPARAM(lParam));
End;

{------------------------------------------------------------------------------
  Method:  CallWindowProc
  Params: LPPrevWndFunc - Address of specified window procedure
          Handle        - Handle of window receiving messages
          Msg           - The message sent
          WParam        - Word parameter
          LParam        - Long-integer parameter
  Returns: Message result

  Passes message information to the specified window procedure
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CallWindowProc(LPPrevWndFunc: TFarProc; Handle: HWND;
    Msg: UINT; WParam: WParam; LParam: LParam): Integer;
Begin
  Result := Windows.CallWindowProc(WNDPROC(LPPrevWndFunc), Handle, Msg, Windows.WPARAM(WParam), Windows.LPARAM(LParam));
End;

{------------------------------------------------------------------------------
  Method:  ClientToScreen
  Params:  Handle - Handle of window
           P      - container that contains coordinates
  Returns: Whether the call was successful

  Converts client coordinates to screen coordinates
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.ClientToScreen(Handle: HWND; Var P: TPoint): Boolean;
var
  ORect: TRect;
Begin
  Result := Boolean(Windows.ClientToScreen(Handle, @P));
  if not Result then exit;
  Result := GetLCLClientBoundsOffset(Handle, ORect);
  if not Result then exit;
  inc(P.X, ORect.Left);
  inc(P.Y, ORect.Top);
End;

{------------------------------------------------------------------------------
  Method:  ClipboardFormatToMimeType
  Params:  FormatID - a registered format identifier (0 is invalid)
  Returns: the corresponding mime type as string
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.ClipboardFormatToMimeType(FormatID: TClipboardFormat): String;
Begin
  Assert(False, 'Trace:TWin32WidgetSet.ClipboardFormatToMimeType - Start');
  SetLength(Result,1000);
  Windows.GetClipboardFormatName(FormatID, PChar(Result), 1000);
  SetLength(Result,StrLen(PChar(Result)));
  {$IFDEF VerboseWin32Clipbrd}
  debugln('TWin32WidgetSet.ClipboardFormatToMimeType FormatID=',dbgs(FormatID),' ',Result);
  {$ENDIF}
  Assert(False, 'Trace:TWin32WidgetSet.ClipboardFormatToMimeType - Exit');
End;

{------------------------------------------------------------------------------
  Method:  ClipboardGetData
  Params:  ClipboardType - clipboard type
           FormatID      - a registered format identifier (0 is invalid)
           Stream        - If format is available, it will be appended to this
                           stream
  Returns: true on success
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.ClipboardGetData(ClipboardType: TClipboardType;
  FormatID: TClipboardFormat; Stream: TStream): Boolean;
var
  DataHandle: HGLOBAL;
  Data: pointer;
  Size: integer;
Begin
  Assert(False, 'TWin32WidgetSet.ClipboardGetData - Start');
  Result := false;
  {$IFDEF VerboseWin32Clipbrd}
  debugln('TWin32WidgetSet.ClipboardGetData FormatID=',dbgs(FormatID));
  {$ENDIF}
  if (FormatID=0) or (Stream=nil) or
    not Windows.IsClipboardFormatAvailable(FormatID) then exit;

  if Windows.OpenClipboard(Windows.HWND(nil)) then
    try
      DataHandle := Windows.GetClipboardData(FormatID);
      if DataHandle<>HWND(0) then begin
        Size := Windows.GlobalSize(DataHandle);
        if Size>0 then begin
          Data := Windows.GlobalLock(DataHandle);
          try
            Stream.Write(Data^, Size);
          finally
            Windows.GlobalUnlock(DataHandle);
          end;
          Result := true;
        end;
      end;
    finally
      Windows.CloseClipboard;
    end;
  Assert(False, 'TWin32WidgetSet.ClipboardGetData - Exit');
End;

{------------------------------------------------------------------------------
  Method:  ClipboardGetFormats
  Params:  ClipboardType - the type of clipboard operation (GTK only; ignored here)
           Count         - the number of clipboard formats
           List          - Pointer to an array of supported formats
                           (you must free it yourself)
  Returns: true on success
 ------------------------------------------------------------------------------}
function TWin32WidgetSet.ClipboardGetFormats(ClipboardType: TClipboardType;
  var Count: Integer; var List: PClipboardFormat): Boolean;
var
  FormatID: UINT;
  c: integer;

Begin
  Result := false;
  List := nil;
  {$IFDEF VerboseWin32Clipbrd}
  debugln('TWin32WidgetSet.ClipboardGetData ');
  {$ENDIF}
  if not Windows.OpenClipboard(HWND(AppHandle)) then begin
    {$IFDEF VerboseWin32Clipbrd}
    debugln('TWin32WidgetSet.ClipboardGetData OpenClipboard failed');
    {$ENDIF}
    exit;
  end;
  Count := CountClipboardFormats;
  GetMem(List, Count * SizeOf(TClipboardFormat));
  try
    c := 0;
    FormatID := 0;
    repeat
      FormatID := EnumClipboardFormats(FormatID);
      if (FormatID<>0) then begin
        List[c] := FormatID;
        inc(c);
      end;
    until (c>=Count) or (FormatID=0);
    Count := c;
  finally
    Windows.CloseClipboard;
  end;

  Result := true;
End;

{------------------------------------------------------------------------------
  Method:  ClipboardGetOwnerShip
  Params:  ClipboardType - Type of clipboard, the win32 interface only handles
                           ctClipBoard
           OnRequestProc - TClipboardRequestEvent is defined in LCLType.pp
                           If OnRequestProc is nil the onwership will end.
           FormatCount - number of formats
           Formats - array of TClipboardFormat. The supported formats the owner
                      provides.

  Returns: true on success

  Sets the supported formats and requests ownership for the clipboard.
  The OnRequestProc is used to get the data from the LCL and to put it on the
  clipboard.
  If someone else requests the ownership, the OnRequestProc will be executed
  with the invalid FormatID 0 to notify the old owner of the lost of ownership.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.ClipboardGetOwnerShip(ClipboardType: TClipboardType;
  OnRequestProc: TClipboardRequestEvent; FormatCount: Integer;
  Formats: PClipboardFormat): Boolean;

  procedure PutOnClipBoard(FormatID: integer);
  var
    DataStream: TStream;
    Bitmap: TBitmap;
    DataHandle : THandle;//Windows.HGLOBAL;
    DataPtr: pointer;
  begin
    DataStream := TMemoryStream.Create;
    try
      OnClipBoardRequest(FormatID, DataStream);
      DataStream.Position:=0;
      if FormatID=CF_BITMAP then begin
        Bitmap:= TBitmap.Create;
        Bitmap.TransparentColor := clNone;
        Bitmap.LoadFromStream(DataStream);
        Windows.SetClipboardData(FormatID, Bitmap.Handle);
        Bitmap.Free;
      end else
      begin
        DataHandle := Windows.GlobalAlloc(Windows.GMEM_MOVEABLE, DataStream.Size);
        if (DataHandle=HWND(0)) then begin
          debugln('TWin32WidgetSet.ClipboardGetOwnerShip DataHandle=',dbgs(DataHandle),' DataSize=',dbgs(DataStream.Size));
          Result := false;
          exit;
        end;
        DataPtr := GlobalLock(DataHandle);
        try
          DataStream.Read(DataPtr^, DataStream.Size);
        finally
          Windows.GlobalUnlock(DataHandle);
        end;
        Windows.SetClipboardData(FormatID, DataHandle);
      end;
    finally
      DataStream.Free;
    end;
  end;

Var
  I: Integer;
Begin
  Result := false;

  {$IFDEF VerboseWin32Clipbrd}
  debugln('TWin32WidgetSet.ClipboardGetOwnerShip START FormatCount=',dbgs(FormatCount),' OnRequestProc=',dbgs(OnRequestProc=nil));
  {$ENDIF}

  if ClipboardType<>ctClipBoard then begin
  { the win32 interface does not support this kind of clipboard,
    so the application can have the ownership at any time.
    The TClipboard in clipbrd.pp has an internal cache system, so that an
    application can use all types of clipboards even if the underlying
    platform does not support it.
    Of course this will only be a local clipboard, invisible to other
    applications. }
    {$IFDEF VerboseWin32Clipbrd}
    debugln('TWin32WidgetSet.ClipboardGetOwnerShip unsupported ClipboardType under win32');
    {$ENDIF}
    Result := true;
    exit;
  end;

  if (FormatCount=0) or (OnRequestProc=nil) then begin
  { The LCL indicates it doesn't have the clipboard data anymore
    and the interface can't use the OnRequestProc anymore.}
    {$IFDEF VerboseWin32Clipbrd}
    debugln('TWin32WidgetSet.ClipboardGetOwnerShip clearing OnClipBoardRequest');
    {$ENDIF}
    OnClipBoardRequest := nil;
    Result := true;
  end else begin
  { clear OnClipBoardRequest to prevent destroying the LCL clipboard,
    when emptying the clipboard}
    OnClipBoardRequest := nil;
    if not Windows.OpenClipboard(FAppHandle) then begin
      {$IFDEF VerboseWin32Clipbrd}
      debugln('TWin32WidgetSet.ClipboardGetOwnerShip A OpenClipboard failed');
      {$ENDIF}
      exit;
    end;
    try
      if not Windows.EmptyClipboard then begin
        debugln('TWin32WidgetSet.ClipboardGetOwnerShip A EmptyClipboard failed');
        exit;
      end;
      Result := true;
      OnClipBoardRequest := OnRequestProc;
      for I := 0 To FormatCount-1 do begin
        {$IFDEF VerboseWin32Clipbrd}
        debugln('TWin32WidgetSet.ClipboardGetOwnerShip A Formats['+dbgs(i)+']=',dbgs(Formats[i]));
        {$ENDIF}
        PutOnClipBoard(Formats[i]);
      end;
    finally
      if not Windows.CloseClipboard then begin
        debugln('TWin32WidgetSet.ClipboardGetOwnerShip A CloseClipboard failed');
      end;
    end;
  end;
End;

{------------------------------------------------------------------------------
  Method:  ClipboardRegisterFormat
  Params:  AMimeType - a string (usually a MIME type) identifying a new format
                       type to register
  Returns: the registered Format identifier (TClipboardFormat)
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.ClipboardRegisterFormat(Const AMimeType: String): TClipboardFormat;
Begin
  if AMimeType=PredefinedClipboardMimeTypes[pcfText] then
    Result := Windows.CF_TEXT
  else if AMimeType=PredefinedClipboardMimeTypes[pcfBitmap] then
    Result := Windows.CF_BITMAP
  else
    Result := Windows.RegisterClipboardFormat(PChar(AMimeType));
  {$IFDEF VerboseWin32Clipbrd}
  debugln('TWin32WidgetSet.ClipboardRegisterFormat AMimeType="',AMimeType,'" Result=',dbgs(Result));
  {$ENDIF}
End;

{------------------------------------------------------------------------------
  Function: CombineRgn
  Params:  Dest, Src1, Src2, fnCombineMode
  Returns: longint

  Combine the 2 Source Regions into the Destination Region using the specified
  Combine Mode. The Destination must already be initialized. The Return value
  is the Destination's Region type, or ERROR.

  The Combine Mode can be one of the following:
      RGN_AND  : Gets a region of all points which are in both source regions

      RGN_COPY : Gets an exact copy of the first source region

      RGN_DIFF : Gets a region of all points which are in the first source
                 region but not in the second.(Source1 - Source2)

      RGN_OR   : Gets a region of all points which are in either the first
                 source region or in the second.(Source1 + Source2)

      RGN_XOR  : Gets all points which are in either the first Source Region
                 or in the second, but not in both.

  The result can be one of the following constants
      Error
      NullRegion
      SimpleRegion
      ComplexRegion

 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CombineRgn(Dest, Src1, Src2 : HRGN; fnCombineMode : Longint) : Longint;
begin
  Result := Windows.CombineRgn(Dest, Src1, Src2, fnCombineMode);
end;

{------------------------------------------------------------------------------
  Method:  CreateBitmap
  Params:  Width      - bitmap width, in pixels
           Height     - bitmap height, in pixels
           Planes     - number of color planes
           BitCount   - number of bits required to identify a color
           BitmapBits - pointer to array containing color data
  Returns: A handle to a bitmap

  The CreateBitmap function creates a bitmap with the specified width, height,
  and color format (color planes and bits per pixel).
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CreateBitmap(Width, Height: Integer; Planes, BitCount: LongInt; BitmapBits: Pointer): HBITMAP;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.CreateBitmap] Width: %d, Height: %d, Planes: %d, BitCount: %d, BitmapBits: 0x%x', [Width, Height, Planes, BitCount, PtrInt(BitmapBits)]));
  Result := Windows.CreateBitmap(Width, Height, Planes, BitCount, BitmapBits);
  Assert(False, Format('Trace:< [TWin32WidgetSet.CreateBitmap] --> 0x%x', [Integer(Result)]));
End;

{------------------------------------------------------------------------------
  Method:   CreateBrushIndirect
  Params:  LogBrush - record describing brush
  Returns: identifier of a logical brush

  The CreateBrushIndirect function creates a logical brush that has the
  specified style, color, and pattern.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CreateBrushIndirect(Const LogBrush: TLogBrush): HBRUSH;
Var
  LB: Windows.LogBrush;
Begin
  LB.lbStyle := LogBrush.lbStyle;
  LB.lbColor := Windows.COLORREF(ColorToRGB(LogBrush.lbColor));
  LB.lbHatch := LogBrush.lbHatch;
  Assert(False, Format('Trace:> [TWin32WidgetSet.CreateBrushIndirect]  Style: %d, Color: %8x', [lb.lbStyle, lb.lbColor]));
  Result := Windows.CreateBrushIndirect(LB);
  Assert(False, Format('Trace:< [TWin32WidgetSet.CreateBrushIndirect] Got --> %x', [Result]));
End;

{------------------------------------------------------------------------------
  Method:  CreateCaret
  Params:  Handle - handle to owner window
           Bitmap - handle to bitmap for caret shape
           Width  - caret width
           Height - caret height
  Returns: Whether the function succeeded

  Creates a new shape for the system caret and assigns ownership of the caret
  to the specified window
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CreateCaret(Handle: HWND; Bitmap: HBITMAP; Width, Height: Integer): Boolean;
Begin
{$ifdef DEBUG_CARET}
  DebugLn('[CreateCaret] for window ', IntToHex(Handle, 8));
{$endif}
  Result := Boolean(Windows.CreateCaret(Handle, Bitmap, Width, Height));
  Assert(False, 'Trace:TODO: [TWin32WidgetSet.CreateCaret] Finish');
End;

{------------------------------------------------------------------------------
  Method:  CreateCompatibleBitmap
  Params: DC     - handle to device context
          Width  - width of bitmap, in pixels
          Height - height of bitmap, in pixels
  Returns: a handle to the bitmap

  Creates a bitmap compatible with the specified device context.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CreateCompatibleBitmap(DC: HDC; Width, Height: Integer): HBITMAP;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.CreateCompatibleBitmap] DC: 0x%x, W: %d, H: %d', [DC, Width, Height]));
  Result := Windows.CreateCompatibleBitmap(DC, Width, Height);
  Assert(False, Format('Trace:< [TWin32WidgetSet.CreateCompatibleBitmap] DC: 0x%x --> 0x%x', [DC, Result]));
End;

{------------------------------------------------------------------------------
  Method:  CreateCompatibleDC
  Params:  DC - handle to memory device context
  Returns: handle to a memory device context

  Creates a memory device context (DC) compatible with the specified device.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CreateCompatibleDC(DC: HDC): HDC;
Begin
  Result := Windows.CreateCompatibleDC(DC);
  Assert(False, Format('Trace:[TWin32WidgetSet.CreateCompatibleDC] DC: 0x%x --> 0x%x', [Integer(DC), Integer(Result)]));
End;

{------------------------------------------------------------------------------
  Method:  CreateFontIndirect
  Params:  LogFont - logical font record
  Returns: a handle to a logical font

  Creates a logical font that has the characteristics specified in the
  specified record.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CreateFontIndirect(Const LogFont: TLogFont): HFONT;
Var
  TempLogFont: TLogFont;
Begin
  TempLogFont := LogFont;
  if String(TempLogFont.lfFaceName) = DefFontData.Name then
  begin
    Move(FMetrics.lfMessageFont.lfFaceName, TempLogFont.lfFaceName, LF_FACESIZE);
    if TempLogFont.lfHeight = 0 then
      TempLogFont.lfHeight := FMetrics.lfMessageFont.lfHeight;
  end;
  Result := Windows.CreateFontIndirect(@TempLogFont);
End;

{------------------------------------------------------------------------------
  Method:  CreatePenIndirect
  Params:  LogPen - record that defines the style, width, and color of a pen
  Returns: a handle that identifies a logical cosmetic pen

  Creates a logical cosmetic pen that has the style, width, and color specified
  in a record.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CreatePenIndirect(Const LogPen: TLogPen): HPEN;
Var
  LP: TLogPen;
Begin
  LP := LogPen;
  Lp.lopnColor := Windows.COLORREF(ColorToRGB(Lp.lopnColor));
  Assert(False, 'Trace:[TWin32WidgetSet.CreatePenIndirect]');
  Result := Windows.CreatePenIndirect(Windows.LOGPEN(LP));
End;

{------------------------------------------------------------------------------
  Method:  CreatePixmapIndirect
  Params:  Data       - Raw pixmap data
           TransColor - Color of transparent spots
  Returns: Handle to LCL bitmap

  Creates a bitmap from raw pixmap data.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CreatePixmapIndirect(Const Data: Pointer; Const TransColor: LongInt): HBITMAP;
Type
  PColorMap = ^TColorMap;
  TColorMap = Record
    Alias: String;
    Color: DWORD;
  End;
  PPixmapArray = ^TPixmapArray;
  TPixmapArray = Array[0..1000] Of PChar;
Var
  AliasLen      : Cardinal;
  AList         : TList;
  ColorCount    : Cardinal;
  hdcScreen     : HDC;
  hdcBitmap     : HDC;
  hbmBitmap     : HBITMAP ;
  Height, Width : Integer;
  OldObject     : HGDIOBJ;
  PixmapArray   : PPixmapArray;
  Info          : String;
  PixmapInfo    : TStringList;

  Procedure NormalizeString(Var Str: String);
  Var
    S: String;
  Const
    keyTab  = #9;
  Begin
    Assert(False, 'Trace:NormalizeString - Start');
    Str := Replace(Str, keyTab, ' ', True);
    S := '';
    While True Do Begin
      Str := Replace(Str, '  ', ' ', True);
      If Str = S Then Break;
      S := Str;
    End;
    Assert(False, 'Trace:NormalizeString - Exit');
  End;

  Function StrToInt(Const Str: String): DWORD;
  Var
    S: String;
  Begin
    Assert(False, 'Trace:StrToInt - Start');
    S := Trim(Str);
    Result := SysUtils.StrToInt(S);
    Assert(False, 'Trace:StrToInt - Exit');
  End;

  procedure CreateColorMap;
  Var
    Elem: String;
    I, Idx: Integer;
    ColorMap: PColorMap;
  Begin
    Assert(False, 'Trace:CreateColorMap - Start');
    If ColorCount = 0 Then Begin
      Assert(False, 'Trace:CreateColorMap - Color count was not retrieved; can''t create color map');
      AList := Nil;
      Exit;
    End;

    AList := TList.Create;
    For I := 1 To ColorCount Do Begin
      Try
        Elem := String(PixmapArray^[I]);

        While Pos(Elem[Length(Elem)],'",')>0 do Elem:=Copy(Elem,1,Length(Elem)-1);

        Idx := Cardinal(Pos(Elem, '"'))+AliasLen+4;
        New(ColorMap);
        ColorMap^.Alias := Copy(Elem, 1, AliasLen);
        If Copy(Elem, idx, 1) = '#' Then begin
          //ColorMap^.Color := StrToInt('$'+Copy(Elem,Idx,6));
          ColorMap^.Color := RGB(
            Byte(StrToInt('$'+Copy(Elem,Idx+1,2))),
            Byte(StrToInt('$'+Copy(Elem,Idx+3,2))),
            Byte(StrToInt('$'+Copy(Elem,Idx+5,2))));
        end
        Else
          ColorMap^.Color := TransColor;
        Assert(False, Format('Trace:CreateColorMap - color-map entry info --> item: %D, data: %S, alias: %S, color:0x%X', [I, String(PixmapArray^[I]), ColorMap^.Alias, ColorMap^.Color]));
        AList.Add(ColorMap);
      Except
        On E: Exception Do Assert(False, Format('Trace:CreateColorMap - Could not create color-map entry --> %S', [E.Message]));
      End;
    End;
    Assert(False, 'Trace:CreateColorMap - Exit');
  End;

  Procedure DestroyColorMap;
  var
    ColorMap : PColorMap;
  Begin
    Assert(False, 'Trace:DestroyColorMap - Start');
    While AList.Count>0 do begin
      ColorMap:=PColorMap(AList.Items[0]);
      Dispose(ColorMap);
      AList.Delete(0);
    end;
    If AList <> Nil Then Begin
      AList.Free;
      AList := Nil;
    End;
    Assert(False, 'Trace:DestroyColorMap - Exit');
  End;

  function GetColorFromAlias(Alias:String):DWORD;
  var
    i : Cardinal;
  begin
    result:=0;
    i     :=0;
    if AList.Count>0 then begin
      repeat
        if (TColorMap(AList.Items[i]^).Alias=Alias) then begin
          result:=TColorMap(AList.Items[i]^).Color;
          break;
        end;
        Inc(i);
      until (i>=ColorCount);
    end;
  end;

  Procedure DoDrawBitmap;
  Var
    CX,CY      : Cardinal;
    Line,Alias : String;
  Begin
    Assert(False, 'Trace:DoDrawBitmap - Start');

    If (ColorCount = 0) Or (AList = Nil) Then
    Begin
      Assert(False, 'Trace:DoDrawBitmap - No information to create bitmap');
      Exit;
    End;

    for CY:=0 to Height-1 do begin
      Line:=String(PixmapArray^[1+ColorCount+CY]);
      While Pos(Line[Length(Line)],'",')>0 do Line:=Copy(Line,1,Length(Line)-1);
      for CX:=0 to Width-1 do begin
        Alias:=Copy(Line,1+CX*AliasLen,AliasLen);
        Windows.SetPixel(hdcBitmap,CX,CY,GetColorFromAlias(Alias));
      end;
    end;
    Assert(False, 'Trace:DoDrawBitmap - Exit');
  End;

Begin
  Assert(False, 'Trace:TWin32WidgetSet.   - Start');

  Height      := 0;
  Width       := 0;
  ColorCount  := 0;
  AliasLen    := 0;
  Result      := HBITMAP(Nil);
  PixmapArray := PPixmapArray(Data);
  Info        := String(PixmapArray^[0]);
  PixmapInfo  := TStringList.Create;;

  NormalizeString(Info);
  //My own Split:
  while Pos(' ',Info)>0 do begin
    PixmapInfo.Add(Copy(Info,1,Pos(' ',Info)-1)); //Add first String to list
    Delete(Info,1,Pos(' ',Info));                 //Delete String + Space
  end;
  if Length(Info)>0 then PixmapInfo.Add(Info);     //Add last String;

  // I don't know where this Split is defines, but it does something weired
  //  PixmapInfo := Split(String(PixmapArray^[0]), ' ', 3, False);
  If PixmapInfo.Count = 6 Then Assert(False, 'Trace:TODO: TWin32WidgetSet.CreatePixmapIndirect - Get Pixmaps with six sections working');

  Try
    Width      := StrToInt(PixmapInfo[0]);             Assert(False, Format('Trace: Pixmap width --> %D', [Width]));
    Height     := StrToInt(PixmapInfo[1]);             Assert(False, Format('Trace: Pixmap height --> %D', [Height]));
    ColorCount := StrToInt(PixmapInfo[2]);             Assert(False, Format('Trace: number of colors --> %D', [ColorCount]));

    While Pos(PixmapInfo[3][Length(PixmapInfo[3])],'",')>0 do
      PixmapInfo[3]:=Copy(PixmapInfo[3],1,Length(PixMapInfo[3])-1);

    AliasLen := StrToInt(PixmapInfo[3]);

    Assert(False, Format('Trace: characters per pixel --> %D', [AliasLen]));
    Assert(False, Format('Trace:TWin32WidgetSet.CreatePixmapIndirect - Pixmap info: Width - %D; Height - %D; Number of Colors - %D; Characters per pixel - %D; Transparent color - 0x%X', [Width, Height, ColorCount, AliasLen, TransColor]));
  Except
    On E: Exception Do
    Begin
      Assert(False, 'Trace:Error: TWin32WidgetSet.CreatePixmapIndirect - could not retrieve pixmap info --> ' + E.Message);
    End;
  End;

  If (Width <> 0) And (Height <> 0) Then Begin
    hdcScreen := Windows.GetDC(GetDesktopWindow);
    hdcBitmap := CreateCompatibleDC(hdcScreen);
    hbmBitmap := CreateCompatibleBitmap(hdcScreen, Width, Height);
    OldObject := SelectObject(hdcBitmap, hbmBitmap);
    CreateColorMap;
    DoDrawBitmap;
    DestroyColorMap;
    ReleaseDC(GetDesktopWindow, hdcScreen);
    SelectObject(hdcBitmap, OldObject);
    DeleteDC(hdcBitmap);
    Result:=hbmBitmap;
  end;
  PixmapInfo.Free;
  PixmapInfo  := Nil;
  PixmapArray := Nil;

  Assert(False, 'Trace:TWin32WidgetSet.CreatePixmapIndirect - Exit');
End;

{------------------------------------------------------------------------------
  Method:  CreatePolygonRgn
  Params:  Points, NumPts, FillMode
  Returns: the handle to the region

  Creates a Polygon, a closed many-sided shaped region. The Points parameter is
  an array of points that give the vertices of the polygon. FillMode=Winding
  determines what points are going to be included in the region. When Winding
  is True, points are selected by using the Winding fill algorithm. When Winding
  is False, points are selected by using using the even-odd (alternative) fill
  algorithm. NumPts indicates the number of points to use.
  The first point is always connected to the last point.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CreatePolygonRgn(Points: PPoint; NumPts: Integer;
  FillMode: integer): HRGN;
Begin
  Result := Windows.CreatePolygonRgn(LPPOINT(Points)^, NumPts, FillMode);
End;

{------------------------------------------------------------------------------
  Method:  CreateRectRgn
  Params:  X1 - x-coordinate of region's upper-left corner
           Y1 - y-coordinate of region's upper-left corner
           X2 - x-coordinate of region's lower-right corner
           Y2 - y-coordinate of region's lower-right corner
  Returns: the handle to the region

  Creates a rectangular region.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.CreateRectRgn(X1, Y1, X2, Y2: Integer): HRGN;
Begin
  Result := Windows.CreateRectRgn(X1, Y1, X2, Y2);
End;

{------------------------------------------------------------------------------
  Method:  DeleteDC
  Params:  HDC - handle to device context
  Returns: If the function succeeds.

  Deletes the specified device context (DC).
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.DeleteDC(HDC: HDC): Boolean;
Begin
  Result := Boolean(Windows.DeleteDC(HDC));
End;

{------------------------------------------------------------------------------
  Method:  DeleteObject
  Params:  GDIObject - handle to graphic object
  Returns: If the function succeeds.

  Deletes a graphic object, freeing all system resources associated with the
  object.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.DeleteObject(GDIObject: HGDIOBJ): Boolean;
Begin
  { Find out if we want to release internal GDI object }
  Result := Boolean(Windows.DeleteObject(GDIObject));
End;

{------------------------------------------------------------------------------
  Method:  DestroyCaret
  Params:  Handle - handle to the window with a caret (on Windows, there is
           only one, global caret, so this parameter is ignored)
  Returns: If the function succeeds

  Destroys the caret but doesn't free the bitmap.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.DestroyCaret(Handle: HWND): Boolean;
Begin
{$ifdef DEBUG_CARET}
  DebugLn('[DestroyCaret] for window ', IntToHex(Handle, 8));
{$endif}
  Assert(False, 'Trace:TODO: [TWin32WidgetSet.DestroyCaret]');
  Result := Boolean(Windows.DestroyCaret);
End;

{------------------------------------------------------------------------------
  Method:  DrawFrameControl
  Params: DC     - handle to device context
          Rect   - bounding rectangle
          UType  - frame-control type
          UState - frame-control state
  Returns: If the function succeeds

  Draws a frame control of the specified type and style.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.DrawFrameControl(DC: HDC; Var Rect: TRect; UType, UState: Cardinal): Boolean;
var
  Flags: dword;
Begin
  // flat button border cannot be drawn by DrawFrameControl, draw ourselves
  if (UType = DFC_BUTTON) or ((UState and DFCS_FLAT) <> 0) then
  begin
    if (UState and DFCS_PUSHED) <> 0 then
      Flags := BDR_SUNKENOUTER
    else
      if (UState and DFCS_FLAT) <> 0 then Flags := 0
      else Flags := BDR_RAISEDINNER;
    Result := Boolean(Windows.DrawEdge(DC, @Rect, Flags, BF_RECT));
  end else begin
    Result := Boolean(Windows.DrawFrameControl(DC, @Rect, UType, UState));
  end;
End;

function TWin32WidgetSet.DrawFocusRect(DC: HDC; const Rect: TRect): boolean;
var
  lRect: Windows.RECT;
begin
  {$message warn TWin32WidgetSet.DrawFocusRect TODO: optimize Rect copying}
  lRect:=Rect;
  Result:= Windows.DrawFocusRect(DC, lRect);
end;

{------------------------------------------------------------------------------
  Method:  DrawEdge
  Params: DC       - handle to device context
          Rect     - rectangle coordinates
          Edge     - type of inner and outer edge to draw
          GrfFlags - type of border
  Returns: If the function succeeds.

  Draws one or more edges of a rectangle, not including the
  right and bottom edge.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.DrawEdge(DC: HDC; Var Rect: TRect; Edge: Cardinal; GrfFlags: Cardinal): Boolean;
Begin
  Assert(False, Format('trace:> [TWin32WidgetSet.DrawEdge] DC:0x%x, Rect = %d,%d,%d,%d', [DC, Rect.Left, Rect.Top, Rect.Right, Rect.Bottom]));
  Result := Boolean(Windows.DrawEdge(DC, @Rect, edge, grfFlags));
  Assert(False, Format('trace:< [TWin32WidgetSet.DrawEdge] DC:0x%x, Rect = %d,%d,%d,%d', [DC, Rect.Left, Rect.Top, Rect.Right, Rect.Bottom]));
End;

{------------------------------------------------------------------------------
  Method:  DrawText
  Params:  DC, Str, Count, Rect, Flags
  Returns: If the string was drawn, or CalcRect run

 ------------------------------------------------------------------------------}
function TWin32WidgetSet.DrawText(DC: HDC; Str: PChar; Count: Integer; var Rect: TRect; Flags: Cardinal): Integer;
begin
  Assert(False, Format('trace:> [TWin32WidgetSet.DrawText] DC:0x%x, Str:''%s'', Count: %d, Rect = %d,%d,%d,%d, Flags:%d',
    [DC, Str, Count, Rect.Left, Rect.Top, Rect.Right, Rect.Bottom, Flags]));
  Result := Windows.DrawText(DC, Str, Count, @Rect, Flags);
  Assert(False, Format('trace:> [TWin32WidgetSet.DrawText] DC:0x%x, Str:''%s'', Count: %d, Rect = %d,%d,%d,%d, Flags:%d',
    [DC, Str, Count, Rect.Left, Rect.Top, Rect.Right, Rect.Bottom, Flags]));
end;

{------------------------------------------------------------------------------
  Method:   Ellipse
  Params:
            DC - handle to device context
            X1 - x-coord. of bounding rectangle's upper-left corner
            Y1 - y-coord. of bounding rectangle's upper-left corner
            X2 - x-coord. of bounding rectangle's lower-right corner
            Y2 - y-coord. of bounding rectangle's lower-right corner
  Returns:  If the function succeeds

  Use Ellipse to draw a filled circle or ellipse.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.Ellipse(DC: HDC; X1, Y1, X2, Y2: Integer): Boolean;
Begin
  Result := Boolean(Windows.Ellipse(DC, X1, Y1, X2, Y2));
End;

{------------------------------------------------------------------------------
  Method:  EmptyClipBoard
  Params: none
  Returns: If the function succeeds

  Empties the clipboard, frees handles to data in the clipboard, and ssigns
  ownership of the clipboard to the window that currently has the clipboard
  open.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.EmptyClipBoard: Boolean;
Begin
  Result := Boolean(Windows.EmptyClipboard);
End;

{------------------------------------------------------------------------------
  Method:  EnableScrollBar
  Params:  Wnd      - handle to window or scroll bar
           WSBFlags - scroll bar type flag
           WArrows  - scroll bar arrow flag
  Returns: Nothing


 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.EnableScrollBar(Wnd: HWND; WSBFlags, WArrows: Cardinal): Boolean;
Begin
  Assert(False, 'Trace:TODO: [TWin32WidgetSet.EnableScrollBar]');
  //TODO: Implement this;
  Result := Boolean(Windows.EnableScrollBar(Wnd, WSBFlags, WArrows));
End;

{------------------------------------------------------------------------------
  Method:  EnableWindow
  Params: HWnd    - handle to window
          BEnable -  whether to enable the window
  Returns: If the window was previously disabled

  Enables or disables mouse and keyboard input to the specified window or
  control.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.EnableWindow(hWnd: HWND; bEnable: Boolean): Boolean;
Begin
  Assert(False, Format('Trace:[TWin32WidgetSet.EnableWindow] HWnd: 0x%x, BEnable: %s', [HWnd, BOOL_TEXT[BEnable]]));
  Result := Boolean(Windows.EnableWindow(HWnd, BEnable));
End;

{------------------------------------------------------------------------------
  Method:  EndPaint
  Params:  Handle        - Handle to window
           PS            - PAINTSTRUCT variable with painting information
  Returns: always nonzero.

  The EndPaint function marks the end of painting in the specified window.
  This function is required for each call to the BeginPaint function, but only
  after painting is complete.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.EndPaint(Handle : hwnd; var PS : TPaintStruct): Integer;
Begin
  Result := Integer(Windows.EndPaint(Handle, @PS));
End;

function TWin32WidgetSet.EnumFontFamilies(DC: HDC; Family: Pchar;
  EnumFontFamProc: FontEnumProc; LParam:Lparam):longint;
begin
  result := Windows.EnumFontFamilies(DC,Family,
    Windows.FontEnumProc(EnumFontFamProc), Lparam);
end;

function TWin32WidgetSet.EnumFontFamiliesEx(DC:HDC; lpLogFont:PLogFont;
  Callback: FontEnumExProc; LParam:Lparam; flags:dword):longint;
begin
  result := Windows.EnumFontFamiliesEx(DC,
    windows.LPLOGFONT(lpLogFont),
    windows.FontEnumExProc(Callback), Lparam, Flags);
end;

{------------------------------------------------------------------------------
  Function: ExcludeClipRect
  Params:  dc, Left, Top, Right, Bottom
  Returns: integer

  Subtracts all intersecting points of the passed bounding rectangle
  (Left, Top, Right, Bottom) from the Current clipping region in the
  device context (dc).

  The result can be one of the following constants
      Error
      NullRegion
      SimpleRegion
      ComplexRegion


 ------------------------------------------------------------------------------}
function TWin32WidgetSet.ExcludeClipRect(dc: hdc;
  Left, Top, Right, Bottom : Integer) : Integer;
begin
  Result := Windows.ExcludeClipRect(dc, Left, Top, Right, Bottom);
end;

{------------------------------------------------------------------------------
  Method:  ExtTextOut
  Params:  DC      - handle to device context
           X       - x-coordinate of reference point
           Y       - x-coordinate of reference point
           Options - text-output options
           Rect    - optional clipping and/or opaquing rectangle
           Str     - character string to be drawn
           Count   - number of characters in string
           Dx      - pointer to array of intercharacter spacing values
  Returns: If the string was drawn.

  Draws a character string by using the currently selected font.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.ExtTextOut(DC: HDC; X, Y: Integer; Options: Longint; Rect: PRect; Str: PChar; Count: Longint; Dx: PInteger): Boolean;
Begin
  Assert(False, Format('trace:> [TWin32WidgetSet.ExtTextOut] DC:0x%x, X:%d, Y:%d, Options:%d, Str:''%s'', Count: %d', [DC, X, Y, Options, Str, Count]));
  Result := Boolean(Windows.ExtTextOut(DC, X, Y, Options, LPRECT(Rect), Str, Count, Dx));
  Assert(False, Format('trace:< [TWin32WidgetSet.ExtTextOut] DC:0x%x, X:%d, Y:%d, Options:%d, Str:''%s'', Count: %d', [DC, X, Y, Options, Str, Count]));
End;

{------------------------------------------------------------------------------
  Function: ExtSelectClipRGN
  Params:  dc, RGN, Mode
  Returns: integer

  Combines the passed Region with the current clipping region in the device
  context (dc), using the specified mode.

  The Combine Mode can be one of the following:
      RGN_AND  : all points which are in both regions

      RGN_COPY : an exact copy of the source region, same as SelectClipRGN

      RGN_DIFF : all points which are in the Clipping Region but
                 but not in the Source.(Clip - RGN)

      RGN_OR   : all points which are in either the Clip Region or
                 in the Source.(Clip + RGN)

      RGN_XOR  : all points which are in either the Clip Region
                 or in the Source, but not in both.

  The result can be one of the following constants
      Error
      NullRegion
      SimpleRegion
      ComplexRegion


 ------------------------------------------------------------------------------}
function TWin32WidgetSet.ExtSelectClipRGN(dc: hdc; rgn : hrgn; Mode : Longint) : Integer;
begin
  Result := Windows.ExtSelectClipRGN(DC, RGN, Mode);
end;

{------------------------------------------------------------------------------
  Method:  FillRect
  Params:  DC    - handle to device context
           Rect  - record with rectangle
           Brush - handle to brush
  Returns: If the function succeeds

  The FillRect Function fills a rectangle by using the specified brush.
  This Function includes the left and top borders, but excludes the right and
  bottom borders of the rectangle.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.FillRect(DC: HDC; Const Rect: TRect; Brush: HBRUSH): Boolean;
Var
  R: TRect;
Begin
  R := Rect;
  Assert(False, Format('trace:> [TWin32WidgetSet.FillRect] DC: 0x%x; Rect: ((%d,%d)(%d,%d)); Brush: %x', [Integer(DC), R.left, R.top, R.right, R.bottom, brush]));
  Result := Boolean(Windows.FillRect(DC, Windows.RECT(r), Brush));
  Assert(False, Format('trace:< [TWin32WidgetSet.FillRect] DC: 0x%x; Rect: ((%d,%d)(%d,%d)); Brush: %x', [Integer(DC), R.left, R.top, R.right, R.bottom, brush]));
End;

{------------------------------------------------------------------------------
  Method: Frame3D
  Params: DC         - handle to device context
          Rect       - bounding rectangle
          FrameWidth - width of the frame (ignored on win32)
          Style      - frame style
  Returns: Whether the function was successful

  Draws a 3D border in GTK native style.
  NOTE: This function is mapped to DrawEdge on Windows.
------------------------------------------------------------------------------}
Function TWin32WidgetSet.Frame3D(DC: HDC; var Rect: TRect;
  Const FrameWidth: Integer; Const Style: TBevelCut): Boolean;
Const
  Edge: Array[TBevelCut] Of Integer = (0, BDR_SUNKENOUTER, BDR_RAISEDINNER, 0);
Begin
  Result := Boolean(DrawEdge(DC, Rect, Edge[Style], BF_RECT));
End;

function TWin32WidgetSet.FrameRect(DC: HDC; const ARect: TRect;
  hBr: HBRUSH) : integer;
var
  lRect: Windows.RECT;
begin
  {$message warn TWin32WidgetSet.FrameRect TODO: optimize ARect copying}
  lRect := ARect;
  Result := Windows.FrameRect(DC, lRect, hBr);
end;

{------------------------------------------------------------------------------
  Method:  GetActiveWindow
  Params: none
  Returns: The handle to the active window

  Retrieves the window handle to the active window associated with the thread
  that calls the function.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetActiveWindow: HWND;
Begin
  Result := Windows.GetActiveWindow;
End;

{------------------------------------------------------------------------------
  Method:  GetCapture
  Params:  none
  Returns: the handle of the capture window

  Retrieves the handle of the window (if any) that has captured the mouse.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetCapture: HWND;
Begin
  Result := Windows.GetCapture;
End;

{------------------------------------------------------------------------------
  Method:  GetCaretPos
  Params:  LPPoint - record to receive coordinates
  Returns: If the function succeeds

  Gets the caret's position, in client coordinates.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetCaretPos(Var LPPoint: TPoint): Boolean;
Begin
  Result := Boolean(Windows.GetCaretPos(@LPPoint));
End;

{------------------------------------------------------------------------------
  Method:  GetCharABCWidths
  Params:  DC         - handle of device context
           P2         - first character in range to query
           P3         - last character in range to query
           ABCStructs - character-width record
  Returns: If the function succeeds

  Retrieves the widths, in logical units, of consecutive characters in a given
  range from the current TrueType font.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetCharABCWidths(DC: HDC; P2, P3: UINT; Const ABCStructs): Boolean;
Begin
  Result := Boolean(Windows.GetCharABCWidths(DC, P2, P3, ABCStructs));
End;

{------------------------------------------------------------------------------
  Method:  GetClientRect
  Params: Handle - handle of window
          Rect   - record for client coordinates
  Returns: If the function succeeds

  Retrieves the coordinates of a window's client area.
 ------------------------------------------------------------------------------}
function TWin32WidgetSet.GetClientBounds(Handle: HWND; var Rect: TRect): Boolean;
var
  ARect: TRect;
begin
  Result := Boolean(Windows.GetClientRect(Handle, @Rect));
  if not Result then exit;
  if not GetLCLClientBoundsOffset(Handle, ARect) then exit;
  Inc(Rect.Left, ARect.Left);
  Inc(Rect.Top, ARect.Top);
  Inc(Rect.Right, ARect.Right);
  Inc(Rect.Bottom, ARect.Bottom);
end;

{------------------------------------------------------------------------------
  Method:  GetClientRect
  Params: Handle - handle of window
          Rect   - record for client coordinates
  Returns: If the function succeeds

  Retrieves the dimension of a window's client area.
  Left and Top are always 0,0
 ------------------------------------------------------------------------------}
function TWin32WidgetSet.GetClientRect(Handle: HWND; var Rect: TRect): Boolean;
begin
  Result := GetClientBounds(Handle, Rect);
  OffsetRect(Rect, -Rect.Left, -Rect.Top);
end;

{------------------------------------------------------------------------------
  Function: GetClipBox
  Params: dc, lprect
  Returns: Integer

  Returns the smallest rectangle which includes the entire current
  Clipping Region.

  The result can be one of the following constants
      Error
      NullRegion
      SimpleRegion
      ComplexRegion


 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetClipBox(DC : hDC; lpRect : PRect) : Longint;
begin
  Result := Windows.GetClipBox(DC, Windows.LPRECT(lpRect));
end;

{------------------------------------------------------------------------------
  Function: GetClipRGN
  Params: dc, rgn
  Returns: Integer

  Returns the current Clipping Region.

  The result can be one of the following constants
      Error
      NullRegion
      SimpleRegion
      ComplexRegion


 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetClipRGN(DC : hDC; RGN : hRGN) : Integer;
begin
  Result := Windows.GetClipRGN(DC, RGN);
end;

{------------------------------------------------------------------------------
  Method:  GetCursorPos
  Params:  LPPoint - record to receive coordinates
  Returns: True if the function succeeds

  Gets the cursor position, in screen coordinates.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetCursorPos(Var LPPoint: TPoint): Boolean;
Begin
  Result := Boolean(Windows.GetCursorPos(@LPPoint));
End;

{------------------------------------------------------------------------------
  Method:  GetDC
  Params:  HWND - handle of window
  Returns: value identifying the device context for the given window's client
           area

  Retrieves a handle of a display device context (DC) for the client area of
  the specified window.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetDC(HWnd: HWND): HDC;
var
  ORect: TRect;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.GetDC] HWND: 0x%x', [HWnd]));
  Result := Windows.GetDC(HWnd);
  if (Result<>0) and (HWnd<>0)
  and GetLCLClientBoundsOffset(HWnd, ORect) then begin
    MoveWindowOrgEx(Result, ORect.Left, ORect.Top);
  end;
  Assert(False, Format('Trace:< [TWin32WidgetSet.GetDC] Got 0x%x', [Result]));
End;

{------------------------------------------------------------------------------
  Method: GetDeviceCaps
  Params: DC - display device context
          Index - index of needed capability

  Returns device specific information
 ------------------------------------------------------------------------------}
function TWin32WidgetSet.GetDeviceCaps(DC: HDC; Index: Integer): Integer;
begin
  Result := Windows.GetDeviceCaps(DC, Index);
end;

function TWin32WidgetSet.GetDesignerDC(WindowHandle: HWND): HDC;
var
  OverlayWindow: HWND;
  ARect: Windows.RECT;
  WindowInfo, OverlayWindowInfo: PWindowInfo;
begin
  WindowInfo := GetWindowInfo(WindowHandle);
  OverlayWindow := WindowInfo^.Overlay;
  if OverlayWindow = HWND(nil) then
  begin
    // create 'overlay' window
    Windows.GetClientRect(WindowHandle, @ARect);
    OverlayWindow := Windows.CreateWindowEx(WS_EX_TRANSPARENT,
        @ClsName, '', WS_CHILD or WS_VISIBLE,
        ARect.Left, ARect.Top, ARect.Right, ARect.Bottom,
        WindowHandle, HMENU(nil), HInstance, nil);
    OverlayWindowInfo := AllocWindowInfo(OverlayWindow);
    OverlayWindowInfo^.DefWndProc := Windows.WNDPROC(SetWindowLong(
        OverlayWindow, GWL_WNDPROC, PtrInt(@OverlayWindowProc)));
    OverlayWindowInfo^.WinControl := WindowInfo^.WinControl;
    WindowInfo^.Overlay := OverlayWindow;
  end;
  // bring overlay window to front
  Windows.SetWindowPos(OverlayWindow, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE);
  Result := Windows.GetDC(OverlayWindow);
end;

function TWin32WidgetSet.GetDCOriginRelativeToWindow(PaintDC: HDC;
  WindowHandle: HWND; var OriginDiff: TPoint): boolean;
var
  DCOrg, winOrg: Windows.POINT;
  ORect: TRect;
begin
  OriginDiff.X := 0;
  OriginDiff.Y := 0;
  Result := Windows.GetDCOrgEx(PaintDC, DCOrg);
  if not Result then exit;
  winOrg.X := 0;
  winOrg.Y := 0;
  Result := Windows.ClientToScreen(WindowHandle, winOrg);
  if not Result then exit;
  Result := GetLCLClientBoundsOffset(WindowHandle, ORect);
  if not Result then exit;
  OriginDiff.X := DCOrg.X - winOrg.X - ORect.Left;
  OriginDiff.Y := DCOrg.Y - winOrg.Y - ORect.Top;
  Result := Windows.GetWindowOrgEx(PaintDC, winOrg);
  if not Result then exit;
  dec(OriginDiff.X, winOrg.X);
  dec(OriginDiff.Y, winOrg.Y);
end;

function TWin32WidgetSet.GetDeviceSize(DC: HDC; var P: TPoint): Boolean;
var
  hBitmap: HGDIOBJ;
  hWindow: HWND;
  BitmapInfo: BITMAP;
  ClientRect: TRect;
begin
  // check if memory dc with bitmap
  Result := false;
  case GetObjectType(DC) of
    OBJ_MEMDC:
      begin
        hBitmap := GetCurrentObject(DC, OBJ_BITMAP);
        if hBitmap <> HGDIOBJ(nil) then
        begin
          GetObject(hBitmap, SizeOf(BITMAP), @BitmapInfo);
          P.x := BitmapInfo.bmWidth;
          P.y := BitmapInfo.bmHeight;
          Result := true;
        end;
      end;
    OBJ_DC:
      begin
        hWindow := WindowFromDC(DC);
        if hWindow <> HWND(nil) then
        begin
          Result := GetClientRect(hWindow, ClientRect);
          P.x := ClientRect.Right;
          P.y := ClientRect.Bottom;
        end;
      end;
  else
  end;

  if not Result then
  begin
    // do default
    Result := inherited GetDeviceSize(DC, P);
  end;
end;

function TWin32WidgetSet.GetDIBits(DC: HDC; Bitmap: HBitmap; StartScan, NumScans: UINT; Bits: Pointer; var BitInfo: BitmapInfo; Usage: UINT): Integer;
begin
  Result := Windows.GetDIBits(DC, Bitmap, StartScan, NumScans, Bits, Windows.PBitmapInfo(@BitInfo)^, Usage)
end;

function TWin32WidgetSet.GetBitmapBits(Bitmap: HBITMAP; Count: Longint;  Bits: Pointer): Longint;
begin
  Result := Windows.GetBitmapBits(Bitmap, Count, Bits);
end;

procedure TWin32WidgetSet.FillRawImageDescriptionColors(Desc: PRawImageDescription);
begin
  case Desc^.BitsPerPixel of
    1,4,8:
      begin
        // palette mode, no offsets
        Desc^.Format := ricfGray;
        Desc^.RedPrec := Desc^.BitsPerPixel;
        Desc^.GreenPrec := 0;
        Desc^.BluePrec := 0;
        Desc^.RedShift := 0;
        Desc^.GreenShift := 0;
        Desc^.BlueShift := 0;
      end;
    16:
      begin
        // 5-5-5 mode
        Desc^.RedPrec := 5;
        Desc^.GreenPrec := 5;
        Desc^.BluePrec := 5;
        Desc^.RedShift := 10;
        Desc^.GreenShift := 5;
        Desc^.BlueShift := 0;
        Desc^.Depth := 15;
      end;
    24:
      begin
        // 8-8-8 mode
        Desc^.RedPrec := 8;
        Desc^.GreenPrec := 8;
        Desc^.BluePrec := 8;
        Desc^.RedShift := 16;
        Desc^.GreenShift := 8;
        Desc^.BlueShift := 0;
      end;
  else    //  32:
    // 0-8-8-8 mode, high byte is not used
    Desc^.RedPrec := 8;
    Desc^.GreenPrec := 8;
    Desc^.BluePrec := 8;
    Desc^.RedShift := 16;
    Desc^.GreenShift := 8;
    Desc^.BlueShift := 0;
    Desc^.Depth := 24;
  end;
end;

procedure TWin32WidgetSet.FillRawImageDescription(const BitmapInfo: Windows.TBitmap;
    Desc: PRawImageDescription);
begin
  Desc^.Format := ricfRGBA;
  Desc^.HasPalette := BitmapInfo.bmBitsPixel <= 8;   // if true, each pixel is an index in the palette
  Desc^.Depth := BitmapInfo.bmBitsPixel;          // used bits per pixel
  Desc^.Width := BitmapInfo.bmWidth;
  Desc^.Height := BitmapInfo.bmHeight;
  Desc^.PaletteColorCount := 0;             // TODO, also `ColorCount'
  Desc^.BitOrder := riboReversedBits;
  Desc^.ByteOrder := riboLSBFirst;
  Desc^.LineOrder := riloTopToBottom;
  Desc^.ColorCount := 0;                // entries in color palette. Ignore when no palette.
  Desc^.BitsPerPixel := BitmapInfo.bmBitsPixel;    // bits per pixel. can be greater than Depth.
  Desc^.LineEnd := rileDWordBoundary;
  FillRawImageDescriptionColors(Desc);
  Desc^.AlphaShift := 0;
  Desc^.AlphaSeparate := true; // the alpha is stored as separate Mask
  // The next values are only valid, if there is a separate alpha mask
  Desc^.AlphaBitsPerPixel := 1; // bits per alpha mask pixel.
  Desc^.AlphaPrec := 1;
  Desc^.AlphaLineEnd := rileDWordBoundary;
  Desc^.AlphaBitOrder := riboReversedBits;
  Desc^.AlphaByteOrder := riboLSBFirst;
end;

function TWin32WidgetSet.GetBitmapRawImageDescription(Bitmap: HBITMAP;
  Desc: PRawImageDescription): Boolean;
var
  BitmapInfo: Windows.TBitmap;
begin
  Result := Windows.GetObject(Bitmap, SizeOf(BitmapInfo), @BitmapInfo) > 0;
  if Result then
    FillRawImageDescription(BitmapInfo, Desc);
end;

function TWin32WidgetSet.GetDeviceRawImageDescription(DC: HDC; Desc: PRawImageDescription): boolean;
begin
  Result := true;

  FillChar(Desc^, SizeOf(Desc^), 0);
  Desc^.Format := ricfRGBA;
  Desc^.HasPalette := (Windows.GetDeviceCaps(DC, RASTERCAPS) and RC_PALETTE) <> 0;
  Desc^.Depth := Windows.GetDeviceCaps(DC, BITSPIXEL) * Windows.GetDeviceCaps(DC, PLANES);
  // Width and Height not relevant
  Desc^.PaletteColorCount := Windows.GetDeviceCaps(DC, SIZEPALETTE);
  Desc^.BitOrder := riboReversedBits;
  Desc^.ByteOrder := riboLSBFirst;
  Desc^.LineOrder := riloTopToBottom;
  Desc^.ColorCount := Desc^.PaletteColorCount;
  if Desc^.HasPalette then
    Desc^.BitsPerPixel := Windows.GetDeviceCaps(DC, COLORRES)
  else
    Desc^.BitsPerPixel := Desc^.Depth;
  Desc^.LineEnd := rileDWordBoundary;
  FillRawImageDescriptionColors(Desc);
  Desc^.AlphaPrec := 1;
  Desc^.AlphaSeparate := true; // the alpha is stored as separate Mask
  // The next values are only valid, if there is a separate alpha mask
  Desc^.AlphaBitsPerPixel := 1; // bits per alpha mask pixel.
  Desc^.AlphaBitOrder := riboReversedBits;
  Desc^.AlphaByteOrder := riboLSBFirst;
  // CreateBitmap winapi call wants word-aligned data
  Desc^.AlphaLineEnd := rileWordBoundary;
  Desc^.AlphaShift := 0;
end;

function TWin32WidgetSet.GetRawImageFromDevice(SrcDC: HDC; const SrcRect: TRect; var NewRawImage: TRawImage): boolean;
var
  SrcWidth, SrcHeight: Integer;
  hMemDC: HDC;
  hMemBitmap: HBITMAP;
  hOldObject: HGDIOBJ;
begin
  FillChar(NewRawImage, SizeOf(NewRawImage), 0);

  // make bitmap compatible to src device
  SrcWidth := SrcRect.Right - SrcRect.Left;
  SrcHeight := SrcRect.Bottom - SrcRect.Top;
  hMemBitmap := Windows.CreateCompatibleBitmap(SrcDC, SrcWidth, SrcHeight);
  Result := hMemBitmap <> 0;
  if not Result then exit;

  // make memory device context compatible to device, to select bitmap in for copying
  hMemDC := Windows.CreateCompatibleDC(SrcDC);
  Result := hMemDC <> 0;
  hOldObject := Windows.SelectObject(hMemDC, hMemBitmap);

  // copy srcdc -> membitmap
  Result := Result and Windows.BitBlt(hMemDC, 0, 0, SrcWidth, SrcHeight,
        SrcDC, SrcRect.Left, SrcRect.Top, SRCCOPY);

  // done copying, deselect bitmap from dc
  Windows.SelectObject(hMemDC, hOldObject);

  // copy membitmap -> rawimage
  Result := Result and GetRawImageFromBitmap(hMemBitmap, 0,
    Rect(0, 0, SrcWidth, SrcHeight), NewRawImage);

  // free temporary stuff
  Windows.DeleteDC(hMemDC);
  Windows.DeleteObject(hMemBitmap);
end;

procedure TWin32WidgetSet.AllocAndCopy(const BitmapInfo: Windows.TBitmap;
  const BitmapHandle: HBITMAP; const SrcRect: TRect; var Data: PByte;
  var Size: PtrUInt);
var
  bmInfoBuffer: array[0..sizeof(TBitmapInfo)+256*sizeof(Windows.RGBQUAD)] of byte;
  bmInfo: TBitmapInfo absolute bmInfoBuffer;
  ScreenDC: HDC;
begin
  // initialize bitmapinfo structure
  bmInfo.bmiHeader.biSize := sizeof(bmInfo.bmiHeader);
  bmInfo.bmiHeader.biWidth := BitmapInfo.bmWidth;
  bmInfo.bmiHeader.biHeight := BitmapInfo.bmHeight;
  // request a top-down DIB
  if bmInfo.bmiHeader.biHeight > 0 then
    bmInfo.bmiHeader.biHeight := -bmInfo.bmiHeader.biHeight;
  bmInfo.bmiHeader.biPlanes := 1;
  bmInfo.bmiHeader.biBitCount := BitmapInfo.bmBitsPixel;
  bmInfo.bmiHeader.biCompression := BI_RGB;
  bmInfo.bmiHeader.biSizeImage := 0;
  Size := ((BitmapInfo.bmWidthBytes+3) and not 3) * (SrcRect.Bottom-SrcRect.Top);
  ScreenDC := GetDC(0);
  GetMem(Data, Size);
  GetDIBits(ScreenDC, BitmapHandle, SrcRect.Top, SrcRect.Bottom-SrcRect.Top, Data, bmInfo, DIB_RGB_COLORS);
  // release resources
  ReleaseDC(0, ScreenDC);
end;

function TWin32WidgetSet.GetRawImageFromBitmap(SrcBitmap, SrcMaskBitmap: HBITMAP; const SrcRect: TRect; var NewRawImage: TRawImage): boolean;
var
  BitmapInfo: Windows.TBitmap;
  ARect: TRect;
begin
  FillChar(NewRawImage, SizeOf(NewRawImage), 0);
  Result := Windows.GetObject(SrcBitmap, SizeOf(BitmapInfo), @BitmapInfo) > 0;
  if not Result then exit;

  FillRawImageDescription(BitmapInfo, @NewRawImage.Description);
  ARect := SrcRect;
  if ARect.Top > BitmapInfo.bmHeight then
    ARect.Top := BitmapInfo.bmHeight;
  if ARect.Bottom > BitmapInfo.bmHeight then
    ARect.Bottom := BitmapInfo.bmHeight;
  if ARect.Left > BitmapInfo.bmWidth then
    ARect.Left := BitmapInfo.bmWidth;
  if ARect.Right > BitmapInfo.bmWidth then
    ARect.Right := BitmapInfo.bmWidth;

  // copy bitmap
  AllocAndCopy(BitmapInfo, SrcBitmap, ARect, NewRawImage.Data, NewRawImage.DataSize);

  // check mask
  if SrcMaskBitmap <> 0 then
  begin
    Result := Windows.GetObject(SrcMaskBitmap, SizeOf(BitmapInfo), @BitmapInfo) > 0;
    if not Result then exit;

    AllocAndCopy(BitmapInfo, SrcMaskBitmap, ARect, NewRawImage.Mask, NewRawImage.MaskSize);
    NewRawImage.Description.AlphaSeparate := true;
  end;
end;

function TWin32WidgetSet.CreateBitmapFromRawImage(const RawImage: TRawImage;
  var Bitmap, MaskBitmap: HBitmap; AlwaysCreateMask: boolean): boolean;
var
  BitmapInfo: TBitmapInfo;
  hScreenDC: HDC;
begin
  FillChar(BitmapInfo, SizeOf(BitmapInfo), 0);
  BitmapInfo.bmiHeader.biSize := SizeOf(BitmapInfo.bmiHeader);
  BitmapInfo.bmiHeader.biWidth := RawImage.Description.Width;
  BitmapInfo.bmiHeader.biHeight := -RawImage.Description.Height;
  BitmapInfo.bmiHeader.biPlanes := 1;
  BitmapInfo.bmiHeader.biBitCount := RawImage.Description.BitsPerPixel;
  BitmapInfo.bmiHeader.biCompression := BI_RGB;
  {BitmapInfo.bmiHeader.biSizeImage := 0;}

  hScreenDC := Windows.GetDC(0);
  MaskBitmap := 0;
  Bitmap := Windows.CreateDIBitmap(hScreenDC, Windows.TBitmapInfoHeader(BitmapInfo.bmiHeader), CBM_INIT, RawImage.Data,
    Windows.TBitmapInfo(BitmapInfo), DIB_RGB_COLORS);
  Result := Bitmap <> 0;
  if Result then
  begin
    if (AlwaysCreateMask or (not RawImageMaskIsEmpty(@RawImage,true))) then
    begin
      if RawImage.Description.AlphaSeparate then
      begin
        MaskBitmap := Windows.CreateBitmap(RawImage.Description.Width,
                              RawImage.Description.Height, 1, 1, RawImage.Mask);
        Result := Result and (MaskBitmap <> 0);
      end;
    end;
  end;
  Windows.ReleaseDC(0, hScreenDC);
end;

function TWin32WidgetSet.CreateDIBSection(DC: HDC; const p2: tagBitmapInfo; p3: UINT;
  var p4: Pointer; p5: THandle; p6: DWORD): HBITMAP;
begin
  Result := Windows.CreateDIBSection(DC, Windows.PBitmapInfo(@p2)^,  p3, p4, p5, p6)
end;

{------------------------------------------------------------------------------
  Method:  GetFocus
  Params:  none
  Returns: The handle of the window with focus

  The GetFocus function retrieves the handle of the window that has the focus.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetFocus: HWND;
Begin
  Result := Windows.GetFocus;
End;

{------------------------------------------------------------------------------
  Method:  GetForegroundWindow
  Params:  none
  Returns: The handle of the foreground window

  The GetForegroundWindow function returns the window that the user is
  currently working with, session wide.
 ------------------------------------------------------------------------------}
function TWin32WidgetSet.GetForegroundWindow: HWND;
begin
  Result := Windows.GetForegroundWindow;
end;

{------------------------------------------------------------------------------
  Method:  GetKeyState
  Params:  NVirtKey - The requested key
  Returns: If the Function succeeds, the return value specifies the status of
           the given virtual key. If the high-order bit is 1, the key is down;
           otherwise, it is up. If the low-order bit is 1, the key is toggled.

  The GetKeyState Function retrieves the status of the specified virtual key.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetKeyState(nVirtKey: Integer): Smallint;
Begin
  Result := Windows.GetKeyState(nVirtKey);
End;

{------------------------------------------------------------------------------
  Method:  GetObject
  Params:  GDIObj  - handle to graphics object of interest
           BufSize - size of buffer for object information
           Buf     - pointer to buffer for object information
  Returns: the number of bytes stored into the buffer

  Gets information about a specified graphics object.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetObject(GDIObj: HGDIOBJ; BufSize: Integer; Buf: Pointer): Integer;
Begin
  Assert(False, 'Trace:[TWin32WidgetSet.GetObject]');
  Result := Windows.GetObject(GDIObj, BufSize, Buf);
End;

{------------------------------------------------------------------------------
  Method:  GetParent
  Params: Handle - handle of child window
  Returns: the handle of the parent window

  Retrieves the handle of the specified child window's parent window.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetParent(Handle: HWND): HWND;
Begin
  Result := Windows.GetParent(Handle);
End;


{------------------------------------------------------------------------------
  Method:  GetProp
  Params: Handle - handle of window
          Str    - string
  Returns: the associated data

  Retrieves a pointer to data from the property list of the given window.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetProp(Handle: HWND; Str: PChar): Pointer;
Begin
  Result := Pointer(Windows.GetProp(Handle, Str));
End;


{------------------------------------------------------------------------------
  Method:  GetROP2
  Params: DC - Handle of the device context

  Returns: 0 if unsuccessful, the current Foreground Mixing Mode if successul

  Retrieves the current Foreground Mixing Mode in the given device context
 ------------------------------------------------------------------------------}
function TWin32WidgetSet.GetROP2(DC: HDC): Integer;
begin
	Result := Windows.GetROP2(DC);
end;

{------------------------------------------------------------------------------
  Method:  GetScrollInfo
  Params:  Handle     - handle of window with scroll bar
           BarFlag    - scroll bar flag
           ScrollInfo - record for scroll parameters
  Returns: If the function retrieved any values.

  Retrieves the parameters of a scroll bar.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetScrollInfo(Handle: HWND; BarFlag: Integer; var ScrollInfo: TScrollInfo): Boolean;
Begin
  ScrollInfo.cbSize:=sizeof(ScrollInfo);
  Assert(False, 'Trace:TODO: [TWin32WidgetSet.GetScrollInfo]');
  Result := Boolean(Windows.GetScrollInfo(Handle, BarFlag, @ScrollInfo));
End;

{------------------------------------------------------------------------------
  Method:  GetStockObject
  Params:  Value - type of stock object
  Returns: a value identifying the logical object requested

  Retrieves a handle to one of the predefined stock objects.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetStockObject(Value: Integer): THandle;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.GetStockObject] %d ', [Value]));
  Result := Windows.GetStockObject(Value);
  Assert(False, Format('Trace:< [TWin32WidgetSet.GetStockObject] %d --> 0x%x', [Value, Result]));
End;

{------------------------------------------------------------------------------
  Method:  GetSysColor
  Params:   NIndex - display element whose color is to be retrieved
  Returns:  RGB value

  Retrieves the current color of the specified display element.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetSysColor(NIndex: Integer): DWORD;
Begin
  if NIndex = COLOR_FORM then
    NIndex := COLOR_BTNFACE;
  Result := Windows.GetSysColor(nIndex);
End;

{------------------------------------------------------------------------------
  Method:  GetSystemMetrics
  Params: NIndex - system metric to retrieve
  Returns: the requested system metric

  Retrieves various system metrics.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetSystemMetrics(NIndex: Integer): Integer;
Begin
  Assert(False, Format('Trace:[TWin32WidgetSet.GetSystemMetrics] %s', [IntToStr(NIndex)]));
  Result := Windows.GetSystemMetrics(NIndex);
  Assert(False, Format('Trace:[TWin32WidgetSet.GetSystemMetrics] %s --> 0x%S (%s)', [IntToStr(NIndex), IntToHex(Result, 8), IntToStr(Result)]));
End;

Function TWin32WidgetSet.GetTextColor(DC: HDC): TColorRef;
Begin
  Result := Windows.GetTextColor(DC);
End;

{------------------------------------------------------------------------------
  Method:  GetTextExtentPoint
  Params:  DC    - handle of device context
           Str   - text string
           Count - number of characters in string
           Size  - TSize record in which the dimensions of the string are to be
                   returned
  Returns: If the function succeeded

  Computes the width and height of the specified string of text.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetTextExtentPoint(DC: HDC; Str: PChar; Count: Integer; Var Size: TSize): Boolean;
Begin
  Assert(False, 'Trace:[TWin32WidgetSet.GetTextExtentPoint] - Start');
  Result := Boolean(Windows.GetTextExtentPoint32(DC, Str, Count, @Size));
  Assert(False, 'Trace:[TWin32WidgetSet.GetTextExtentPoint] - Exit');
End;

{------------------------------------------------------------------------------
  Method:  GetTextMetrics
  Params:  DC - handle of device context
           TM - text metrics record
  Returns: If the function succeeds

  Fills the specified buffer with the metrics for the currently selected font.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetTextMetrics(DC: HDC; Var TM: TTextMetric): Boolean;
Begin
  Assert(False, Format('Trace:> TODO FINISH[TWin32WidgetSet.GetTextMetrics] DC: 0x%x', [DC]));
  Result := Boolean(Windows.GetTextMetrics(DC, @TM));
  Assert(False, Format('Trace:< TODO FINISH[TWin32WidgetSet.GetTextMetrics] DC: 0x%x', [DC]));
End;

{------------------------------------------------------------------------------
  Method:  GetWindowLong
  Params:  Handle - handle of window
           Int    - value to retrieve
  Returns: the requested 32-bit value

  Retrieves information about the specified window.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetWindowLong(Handle: HWND; Int: Integer): PtrInt;
Begin
  //TODO:Started but not finished
  Assert(False, Format('Trace:> [TWin32WidgetSet.GETWINDOWLONG] HWND: 0x%x, int: 0x%x (%d)', [Handle, int, int]));
{$ifdef ver2_0}
  Result := Windows.GetWindowLong(Handle, int);
{$else}
  Result := Windows.GetWindowLongPtr(Handle, int);
{$endif}
  Assert(False, Format('Trace:< [TWin32WidgetSet.GETWINDOWLONG] HWND: 0x%x, int: 0x%x (%d) --> 0x%x (%d)', [Handle, int, int, Result, Result]));
End;

{------------------------------------------------------------------------------
  Method:  GetWindowOrgEx
  Params:  DC - handle of device context
           P  - record receiving the window origin
  Returns: 0 if the function fails; non-zero integer otherwise

  Retrieves the x-coordinates and y-coordinates of the window origin for the
  specified device context.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetWindowOrgEx(DC: HDC; P: PPoint): Integer;
Begin
  Result := Integer(Windows.GetWindowOrgEx(DC, LPPoint(P)));
End;

{------------------------------------------------------------------------------
  Method:  GetWindowRect
  Params:  Handle - handle of window
           Rect   - record for window coordinates
  Returns: if the function succeeds, the return value is nonzero; if the
           function fails, the return value is zero

  Retrieves the dimensions of the bounding rectangle of the specified window.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetWindowRect(Handle: HWND; Var Rect: TRect): Integer;
Begin
  Result := Integer(Windows.GetWindowRect(Handle, @Rect));
End;

{------------------------------------------------------------------------------
  Function: GetWindowRelativePosition
  Params:  Handle : HWND;
  Returns: true on success

  returns the current widget Left, Top, relative to the client origin of its
  parent
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetWindowRelativePosition(Handle : HWND;
  var Left, Top:integer): boolean;
var
  LeftTop:TPoint;
  R: TRect;
  ParentHandle: THandle;
  WindowInfo: PWindowInfo;
begin
  Result:=false;
  WindowInfo := GetWindowInfo(Handle);
  if (WindowInfo^.WinControl is TCustomFloatSpinEdit) then
    Handle := Windows.SendMessage(Handle, UDM_GETBUDDY, 0, 0);
  if not Windows.GetWindowRect(Handle,@R) then exit;
  LeftTop.X:=R.Left;
  LeftTop.Y:=R.Top;
  ParentHandle:=Windows.GetParent(Handle);
  if ParentHandle<>0 then
  begin
    if not Windows.ScreenToClient(ParentHandle,@LeftTop) then exit;
    if not GetLCLClientBoundsOffset(ParentHandle, R) then
      exit;
    dec(LeftTop.X, R.Left);
    dec(LeftTop.Y, R.Top);
  end;
  Left:=LeftTop.X;
  Top:=LeftTop.Y;
  Result:=true;
end;

{------------------------------------------------------------------------------
  Function: GetWindowSize
  Params:  Handle : hwnd;
  Returns: true on success

  Returns the current widget Width and Height
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.GetWindowSize(Handle : hwnd;
  var Width, Height: integer): boolean;
var
  WP: WINDOWPLACEMENT;
  R: TRect;
  Style, ExStyle: PtrInt;
  WindowInfo: PWindowInfo;

    procedure AdjustForBuddySize;
    var
      BuddyHandle: HWND;
      BuddyWP: WINDOWPLACEMENT;
    begin
      BuddyHandle := Windows.SendMessage(Handle, UDM_GETBUDDY, 0, 0);
      if (BuddyHandle<>HWND(nil)) and Windows.GetWindowPlacement(BuddyHandle, BuddyWP)
        then Width := WP.rcNormalPosition.Right - BuddyWP.rcNormalPosition.Left;
    end;

begin
  WP.length := SizeOf(WP);
  Result := Boolean(Windows.GetWindowPlacement(Handle, WP));
  if (WP.showCmd=SW_MAXIMIZE) then begin
    // if the form is maximized, you can't use the normal size
    Result := Boolean(Windows.GetWindowRect(Handle,@R));
    with R Do
    begin
      Width := Right - Left;
      Height := Bottom - Top;
    end;
  end
  else
    with WP.rcNormalPosition do
    begin
      Width := Right - Left;
      Height := Bottom - Top;
    end;
  WindowInfo := GetWindowInfo(Handle);

  //debugln('TWin32WidgetSet.GetWindowSize ',DbgSName(WindowInfo^.WinControl),' SW_MAXIMIZE=',dbgs(WP.showCmd=SW_MAXIMIZE),' ',dbgs(WP.rcNormalPosition));

  // convert top level lcl window coordinaties to win32 coord
  Style := GetWindowLong(Handle, GWL_STYLE);
  ExStyle := GetWindowLong(Handle, GWL_EXSTYLE);
  if (Style and WS_THICKFRAME) <> 0 then
  begin
    // thick, sizing border
    // add twice, top+bottom border
    Dec(Width, 2*Windows.GetSystemMetrics(SM_CXSIZEFRAME));
    Dec(Height, 2*Windows.GetSystemMetrics(SM_CYSIZEFRAME));
  end else
  if (Style and WS_BORDER) <> 0 then
  begin
    // thin, non-sizing border
    Dec(Width, 2*Windows.GetSystemMetrics(SM_CXFIXEDFRAME));
    Dec(Height, 2*Windows.GetSystemMetrics(SM_CYFIXEDFRAME));
  end;
  if (Style and WS_CAPTION) <> 0 then
    if (ExStyle and WS_EX_TOOLWINDOW) <> 0 then
      Dec(Height, Windows.GetSystemMetrics(SM_CYSMCAPTION))
    else
      Dec(Height, Windows.GetSystemMetrics(SM_CYCAPTION));

  if (WindowInfo^.WinControl is TCustomFloatSpinEdit) then
    AdjustForBuddySize;
end;

{------------------------------------------------------------------------------
  Method:  HideCaret
  Params:  HWnd - handle to the window with the caret
  Returns: Whether the window owns the caret

  Removes the caret from the screen.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.HideCaret(HWnd: HWND): Boolean;
Begin
{$ifdef DEBUG_CARET}
  DebugLn('[HideCaret] for window ', IntToHex(HWnd, 8));
{$endif}
  Assert(False, Format('Trace:  [TWin32WidgetSet.HideCaret] HWND: 0x%x', [HWnd]));
  Result := Boolean(Windows.HideCaret(hWnd));
End;

{------------------------------------------------------------------------------
  Method:  InvalidateRect
  Params: AHandle - handle of window with changed update region
          Rect    - address of rectangle coordinates
          BErase  - specifies whether the background is to be erased
  Returns: if the function succeeds

  Adds a rectangle to the specified window's update region.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.InvalidateRect(aHandle: HWND; Rect: PRect; BErase: Boolean): Boolean;
Var
  Flags: UINT;
  ORect: TRect;
Begin
  Flags := RDW_INVALIDATE or RDW_ALLCHILDREN;
  if BErase then
    Flags := Flags or RDW_ERASE;
  if Rect <> nil then
  begin
    GetLCLClientBoundsOffset(aHandle, ORect);
    OffsetRect(Rect^, ORect.Left, ORect.Top);
  end;
  Result := Boolean(Windows.RedrawWindow(aHandle, Rect, 0, Flags));
End;

{------------------------------------------------------------------------------
  Function: IntersectClipRect
  Params:  dc, Left, Top, Right, Bottom
  Returns: Integer

  Shrinks the clipping region in the device context dc to a region of all
  intersecting points between the boundary defined by Left, Top, Right,
  Bottom , and the Current clipping region.

  The result can be one of the following constants
      Error
      NullRegion
      SimpleRegion
      ComplexRegion

 ------------------------------------------------------------------------------}
function TWin32WidgetSet.IntersectClipRect(dc: hdc;
  Left, Top, Right, Bottom: Integer): Integer;
begin
  Result := Windows.IntersectClipRect(DC, Left, Top, Right, Bottom);
end;

{------------------------------------------------------------------------------
  Method: IsWindowEnabled
  Params: handle - window handle
  Returns: true if window is enabled, false otherwise
 ------------------------------------------------------------------------------}
function TWin32WidgetSet.IsWindowEnabled(handle: HWND): boolean;
begin
  Result := Boolean(Windows.IsWindowEnabled(handle));
end;

{------------------------------------------------------------------------------
  Method: IsWindowVisible
  Params: handle - window handle
  Returns: true if window is visible, false otherwise
 ------------------------------------------------------------------------------}
function TWin32WidgetSet.IsWindowVisible(handle: HWND): boolean;
begin
  Result := Boolean(Windows.IsWindowVisible(handle));
end;

{------------------------------------------------------------------------------
  Method:  LineTo
  Params:  DC - device context handle
           X  - x-coordinate of line's ending point
           Y  - y-coordinate of line's ending point
  Returns: if the function succeeds

  Draws a line from the current position up to, but not including, the specified point.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.LineTo(DC: HDC; X, Y: Integer): Boolean;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.LineTo] DC:0x%x, X:%d, Y:%d', [DC, X, Y]));
  Result := Boolean(Windows.LineTo(DC, X, Y));
  Assert(False, Format('Trace:< [TWin32WidgetSet.LineTo] DC:0x%x, X:%d, Y:%d', [DC, X, Y]));
End;

{------------------------------------------------------------------------------
  Method:  MaskBlt
  Params:  DestDC        - The destination device context
           X, Y          - The left/top corner of the destination rectangle
           Width, Height - The size of the destination rectangle
           SrcDC         - The source device context
           XSrc, YSrc    - The left/top corner of the source rectangle
           Mask          - The handle of a monochrome bitmap
           XMask, YMask  - The left/top corner of the mask rectangle
           Rop           - The raster operation to be performed
  Returns: True if succesful

  The MaskBlt Function copies a bitmap from a source context into a destination
  context using the specified mask and raster operation.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.MaskBlt(DestDC: HDC; X, Y, Width, Height: Integer; SrcDC: HDC; XSrc, YSrc: Integer; Mask: HBITMAP; XMask, YMask: Integer; Rop: DWORD): Boolean;
Begin
  Result := Boolean(Windows.MaskBlt(DestDC, X, Y, Width, Height, SrcDC, XSrc, YSrc, Mask, XMask, YMask, Rop));
End;

Function TWin32WidgetSet.MaskBlt(DestDC: HDC; X, Y, Width, Height: Integer; SrcDC: HDC; XSrc, YSrc: Integer; Mask: HBITMAP; XMask, YMask: Integer): Boolean;
begin
  Result := StretchMaskBlt(DestDC, X, Y, Width, Height, SrcDC, XSrc, YSrc, Width, Height, Mask, XMask, YMask, SRCCOPY);
end;

{------------------------------------------------------------------------------
  Method:  MessageBox
  Params:  HWnd      - The handle of parent window
           LPText    - text in message box
           LPCaption - title of message box
           UType     - style of message box
  Returns: 0 if not successful (out of memory), otherwise one of the defined
           values:
             IDABORT
             IDCANCEL
             IDIGNORE
             IDNO
             IDOK
             IDRETRY
             IDYES

 The MessageBox function displays a modal dialog, with text and caption defined,
 and includes buttons.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.MessageBox(HWnd: HWND; LPText, LPCaption: PChar; UType: Cardinal): Integer;
Begin
  Result := Windows.MessageBox(HWnd, LPText, LPCaption, UType);
End;

{------------------------------------------------------------------------------
  Method:  MoveToEx
  Params:  DC       - handle of device context
           X        - x-coordinate of new current position
           Y        - x-coordinate of new current position
           OldPoint - address of old current position
  Returns: If the function succeeds.

  Updates the current position to the specified point.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.MoveToEx(DC: HDC; X, Y: Integer; OldPoint: PPoint): Boolean;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.MoveToEx] DC:0x%x, X:%d, Y:%d', [DC, X, Y]));
  Result := Boolean(Windows.MoveToEx(DC, X, Y, LPPOINT(OldPoint)));
  Assert(False, Format('Trace:< [TWin32WidgetSet.MoveToEx] DC:0x%x, X:%d, Y:%d', [DC, X, Y]));
End;


{------------------------------------------------------------------------------
  Method:  PeekMessage
  Params:  LPMsg         - Where it should put the message
           Handle        - Handle of the window (thread)
           WMsgFilterMin - Lowest MSG to grab
           WMsgFilterMax - Highest MSG to grab
           WRemoveMsg    - Should message be pulled out of the queue
  Returns: Boolean if an event was there

  Checks a thread message queue for a message.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.PeekMessage(Var LPMsg: TMsg; Handle: HWND; WMsgFilterMin, WMsgFilterMax, WRemoveMsg: UINT): Boolean;
Begin
  Result := Boolean(Windows.PeekMessage(@LPMsg, Handle, WMsgFilterMin, WMsgFilterMax, WRemoveMsg));
End;

{------------------------------------------------------------------------------
  Method:  PolyBezier
  Params:  DC, Points, NumPts, Filled, Continous
  Returns: Boolean

  Use Polybezier to draw cubic Bézier curves. The first curve is drawn from the
  first point to the fourth point with the second and third points being the
  control points. If the Continuous flag is TRUE then each subsequent curve
  requires three more points, using the end-point of the previous Curve as its
  starting point, the first and second points being used as its control points,
  and the third point its end-point. If the continous flag is set to FALSE,
  then each subsequent Curve requires 4 additional points, which are used
  excatly as in the first curve. Any additonal points which do not add up to
  a full bezier(4 for Continuous, 3 otherwise) are ingored. There must be at
  least 4 points for an drawing to occur. If the Filled Flag is set to TRUE
  then the resulting Poly-Bézier will be drawn as a Polygon.

 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.PolyBezier(DC: HDC; Points: PPoint; NumPts: Integer;
  Filled, Continuous: Boolean): Boolean;
Begin
  If Filled or (not Continuous) then
    Result := Inherited PolyBezier(DC,Points,NumPts, Filled, Continuous)
  else
    Result := Boolean(Windows.PolyBezier(DC, LPPOINT(Points)^, NumPts));
End;

{------------------------------------------------------------------------------
  Method:  Polygon
  Params:  DC - handle to device context
           Points - pointer to polygon's vertices
           NumPts - count of polygon's vertices
           Winding
  Returns: If the function succeeds

  Use Polygon to draw a closed, many-sided shape on the canvas, using the value
  of Pen. After drawing the complete shape, Polygon fills the shape using the
  value of Brush.
  The Points parameter is an array of points that give the vertices of the
  polygon.
  Winding determines how the polygon is filled.
  When Winding is True, Polygon
  fills the shape using the Winding fill algorithm. When Winding is False,
  Polygon uses the even-odd (alternative) fill algorithm.
  NumPts indicates the number of points to use.
  The first point is always connected to the last point.
  To draw a polygon on the canvas, without filling it, use the Polyline method,
  specifying the first point a second time at the end.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.Polygon(DC: HDC; Points: PPoint; NumPts: Integer; Winding: Boolean): Boolean;
var
  PFMode : Longint;
Begin
  Assert(False, Format('Trace:TWin32WidgetSet.Polygon --> DC: 0x%X, Number of points: %D, Use winding fill: %S', [DC, NumPts, BOOL_RESULT[Winding]]));
  If Winding then
    PFMode := SetPolyFillMode(DC, Windows.WINDING)
  else
    PFMode := SetPolyFillMode(DC, Windows.ALTERNATE);
  Result := Boolean(Windows.Polygon(DC, LPPOINT(Points)^, NumPts));
  SetPolyFillMode(DC, PFMode);
End;

{------------------------------------------------------------------------------
  Method:  Polyline
  Params:  DC - handle of device context
           Points - address of array containing endpoints
           NumPts - number of points in the array
  Returns: If the function succeeds

  Draws a series of line segments by connecting the points in the specified
  array.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.Polyline(DC: HDC; Points: PPoint; NumPts: Integer): Boolean;
Begin
  Result := Boolean(Windows.Polyline(DC, LPPOINT(Points)^, NumPts));
End;

{------------------------------------------------------------------------------
  Method:  PostMessage
  Params: Handle - handle of destination window
          Msg - message to post
          WParam - first message parameter
          LParam - second message parameter
  Returns: True if succesful

  The PostMessage Function places (posts) a message in the message queue and
  then returns without waiting.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.PostMessage(Handle: HWND; Msg: Cardinal; WParam: WParam; LParam: LParam): Boolean;
Begin
  Result := Boolean(Windows.PostMessage(Handle, Msg, WParam, LParam));
End;

{------------------------------------------------------------------------------
  Method:   RadialArc
  Params:   DC, left, top, right, bottom, sx, sy, ex, ey
  Returns:  Nothing

  Use RadialArc to draw an elliptically curved line with the current Pen. The
  values sx,sy, and ex,ey represent the starting and ending radial-points
  between which the Arc is drawn.

------------------------------------------------------------------------------}
function TWin32WidgetSet.RadialArc(DC: HDC; left, top, right, bottom, sx, sy, ex, ey: Integer): Boolean;
Begin
  Result := Boolean(Windows.Arc(DC, left, top, right, bottom, sx, sy, ex, ey));
End;

{------------------------------------------------------------------------------
  Method:   RadialChord
  Params:   DC, x1, y1, x2, y2, sx, sy, ex, ey
  Returns:  Nothing

  Use RadialChord to draw a filled Chord-shape on the canvas. The values sx,sy,
  and ex,ey represent the starting and ending radial-points between which
  the bounding-Arc is drawn.

------------------------------------------------------------------------------}
function TWin32WidgetSet.RadialChord(DC: HDC; x1, y1, x2, y2, sx, sy, ex, ey: Integer): Boolean;
Begin
  Result := Boolean(Windows.Chord(DC, x1, y1, x2, y2, sx, sy, ex, ey));
End;

{------------------------------------------------------------------------------
  Method:   RadialPie
  Params:   DC, x1, y1, x2, y2, sx, sy, ex, ey
  Returns:  Nothing

  Use RadialPie to draw a filled Pie-shaped Wedge on the canvas. The values
  sx,sy, and ex,ey represent the starting and ending radial-points between which
  the bounding-Arc is drawn.

------------------------------------------------------------------------------}
function TWin32WidgetSet.RadialPie(DC: HDC; x1, y1, x2, y2, sx, sy, ex, ey: Integer): Boolean;
Begin
  Result := Boolean(Windows.Pie(DC, x1, y1, x2, y2, sx, sy, ex, ey));
End;

{------------------------------------------------------------------------------
  Method:  RealizePalette
  Params:  DC - handle of device context
  Returns: number of entries in the logical palette mapped to the system
           palette

  Maps palette entries from the current logical palette to the system palette.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.RealizePalette(DC: HDC): Cardinal;
Begin
  Assert(False, 'Trace:TODO: [TWin32WidgetSet.RealizePalette]');
  //TODO: Implement this;
  Result := Windows.RealizePalette(DC);
End;

{------------------------------------------------------------------------------
  Method:  Rectangle
  Params:  DC - handle of device context
           X1 - x-coordinate of bounding rectangle's upper-left corner
           Y1 - y-coordinate of bounding rectangle's upper-left corner
           X2 - x-coordinate of bounding rectangle's lower-right corner
           Y2 - y-coordinate of bounding rectangle's lower-right corner
  Returns: If the function succeeds

  The Rectangle function draws a rectangle. The rectangle is outlined by using
  the current pen and filled by using the current brush.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.Rectangle(DC: HDC; X1, Y1, X2, Y2: Integer): Boolean;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.Rectangle] DC:0x%x, X1:%d, Y1:%d, X2:%d, Y2:%d', [DC, X1, Y1, X2, Y2]));
  Result := Boolean(Windows.Rectangle(DC, X1, Y1, X2+1, Y2+1));
  Assert(False, Format('Trace:< [TWin32WidgetSet.Rectangle] DC:0x%x, X1:%d, Y1:%d, X2:%d, Y2:%d', [DC, X1, Y1, X2, Y2]));
End;

function TWin32WidgetSet.RectVisible(dc : hdc; const ARect: TRect) : Boolean;
begin
  Result := Boolean(Windows.RectVisible(DC, LPRECT(@ARect)^));
end;

{------------------------------------------------------------------------------
  Function: RemoveProp
  Params: Handle: Handle of the object
          Str: Name of the property to remove
  Returns: The handle of the property (0=failure)

 ------------------------------------------------------------------------------}
function TWin32WidgetSet.RemoveProp(Handle: hwnd; Str: PChar): THandle;
begin
  Result := Windows.RemoveProp(Handle, Str);
end;

{------------------------------------------------------------------------------
  Method:  ReleaseCapture
  Params:  none
  Returns: True if succesful

  The ReleaseCapture Function releases the mouse capture from a window
  and restores normal mouse input processing.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.ReleaseCapture: Boolean;
Begin
  Result := Boolean(Windows.ReleaseCapture);
End;

{------------------------------------------------------------------------------
  Method:  ReleaseDC
  Params:  HWnd - handle of window
           DC   - handle of device context
  Returns: 1 if the device context was released or 0 if it wasn't

  Releases a device context (DC), freeing it for use by other applications.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.ReleaseDC(Window: HWND; DC: HDC): Integer;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.ReleaseDC] DC:0x%x', [DC]));
  Result := Windows.ReleaseDC(Window, DC);
  Assert(False, Format('Trace:< [TWin32WidgetSet.ReleaseDC] DC:0x%x', [DC]));
End;

Function TWin32WidgetSet.ReleaseDesignerDC(Window: HWND; DC: HDC): Integer;
var
  OverlayWindow: HWND;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.ReleaseDC] DC:0x%x', [DC]));
  OverlayWindow := GetWindowInfo(Window)^.Overlay;
  if OverlayWindow <> HWND(nil) then
    Result := Windows.ReleaseDC(OverlayWindow, DC);
  Assert(False, Format('Trace:< [TWin32WidgetSet.ReleaseDC] DC:0x%x', [DC]));
End;

{------------------------------------------------------------------------------
  Method:  RestoreDC
  Params:  DC - handle of device context
           SavedDC - state to be restored
  Returns: if the function succeeds

  Restores a device context (DC) to the specified state.
-------------------------------------------------------------------------------}
Function TWin32WidgetSet.RestoreDC(DC: HDC; SavedDC: Integer): Boolean;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.RestoreDC] DC:0x%x, SavedDC: %d', [DC, SavedDC]));
  Result := Boolean(Windows.RestoreDC(DC, SavedDC));
  Assert(False, Format('Trace:< [TWin32WidgetSet.RestoreDC] DC:0x%x, Saved: %d --> %s', [Integer(DC), SavedDC, BOOL_TEXT[Result]]));
End;

{------------------------------------------------------------------------------
  Method:   RoundRect
  Params:   DC, X1, Y1, X2, Y2, RX, RY
  Returns:  true if succesfull, false otherwise

  Draws a Rectangle with optional rounded corners. RY is the radial height
  of the corner arcs, RX is the radial width.
 ------------------------------------------------------------------------------}
function TWin32WidgetSet.RoundRect(DC: HDC; X1, Y1, X2, Y2: Integer; RX, RY : Integer): Boolean;
begin
  Result := Windows.RoundRect(DC, X1, Y1, X2, Y2, RX, RY);
end;

{------------------------------------------------------------------------------
  Method:  SaveDC
  Params:  DC - a DC to save
  Returns: 0 if the functions fails otherwise a positive integer identifing
           the saved DC

  The SaveDC function saves the current state of the specified device
  context (DC) by copying its elements to a context stack.
-------------------------------------------------------------------------------}
Function TWin32WidgetSet.SaveDC(DC: HDC): Integer;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.SaveDC]  0x%x', [Integer(DC)]));
  Result := Windows.SaveDC(DC);
  Assert(False, Format('Trace:< [TWin32WidgetSet.SaveDC]  0x%x --> %d', [Integer(DC), Result]));
End;

{------------------------------------------------------------------------------
  Method:  ScreenToClient
  Params: Handle - window handle for source coordinates
          P      - record containing coordinates
  Returns: if the function succeeds, the return value is nonzero; if the
           function fails, the return value is zero

  Converts the screen coordinates of a specified point on the screen to client
  coordinates.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.ScreenToClient(Handle: HWND; Var P: TPoint): Integer;
Begin
  Result := Integer(Windows.ScreenToClient(Handle, @P));
End;

{------------------------------------------------------------------------------
  Method:  ScrollWindowEx
  Params:  HWnd       - handle of window to scroll
           DX         - horizontal amount to scroll
           DY         - vertical amount to scroll
           PRcScroll  - pointer to scroll rectangle
           PRcClip    - pointer to clip rectangle
           HRgnUpdate - handle of update region
           PRcUpdate  - pointer to update rectangle
           Flags      - scrolling flags

  Returns: True if succesfull

  The ScrollWindowEx function scrolls the content of the specified window's
  client area
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.ScrollWindowEx(HWnd: HWND; DX, DY: Integer; PRcScroll, PRcClip: PRect; HRgnUpdate: HRGN; PRcUpdate: PRect; Flags: UINT): Boolean;
Begin
  Result := Windows.ScrollWindowEx(HWnd, DX, DY, Windows.RECT(PRcScroll^), Windows.RECT(PRcClip^), HRgnUpdate, LPRECT(PRcUpdate), Flags) <> ERROR;
End;

{------------------------------------------------------------------------------
  Function: SelectClipRGN
  Params:  DC, RGN
  Returns: longint

  Sets the DeviceContext's ClipRegion. The Return value
  is the new clip regions type, or ERROR.

  The result can be one of the following constants
      Error
      NullRegion
      SimpleRegion
      ComplexRegion

 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SelectClipRGN(DC : hDC; RGN : HRGN) : Longint;
begin
  Result := Windows.SelectClipRGN(DC, RGN);
end;

{------------------------------------------------------------------------------
  Method:  SelectObject
  Params:  DC - handle of device context
           GDIObj - handle of object
  Returns: he handle of the object being replaced

  Selects an object into the specified device context.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SelectObject(DC: HDC; GDIObj: HGDIOBJ): HGDIOBJ;
Begin
  //TODO: Finish this;
  Assert(False, Format('Trace:> [TWin32WidgetSet.SelectObject] DC: 0x%x', [DC]));
  Result := Windows.SelectObject(DC, GDIObj);
  Assert(False, Format('Trace:< [TWin32WidgetSet.SelectObject] DC: 0x%x  --> 0x%x', [DC, Result]));
End;

{------------------------------------------------------------------------------
  Method:  SelectPalette
  Params:  DC - handle of device context
           Palette - handle of logical color palette
           ForceBackground - whether the logical palette is forced to be a
                             background palette
  Returns: the device context's previous logical palette

  Selects the specified logical palette into a device context.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SelectPalette(DC: HDC; Palette: HPALETTE; ForceBackground: Boolean): HPALETTE;
Begin
  Assert(False, 'Trace:TODO: [TWin32WidgetSet.SelectPalette]');
  //TODO: Implement this;
  Result := Windows.SelectPalette(DC, Palette, ForceBackground);
End;

{------------------------------------------------------------------------------
  Method:  SendMessage
  Params: HandleWnd   - handle of destination window
          Msg         - message to send
          WParam      - first message parameter
          LParam      - second message parameter
  Returns: the result of the message processing

  The SendMessage function sends the specified message to a window or windows.
  The function calls the window procedure for the specified window and does
  not return until the window procedure has processed the message.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SendMessage(HandleWnd: HWND; Msg: Cardinal; WParam: WParam; LParam: LParam): LResult;
Begin
  Result := Windows.SendMessage(HandleWnd, Msg, WParam, LParam);
End;

{------------------------------------------------------------------------------
  Method:  SetActiveWindow
  Params:  Window - Window to focus
  Returns: Old active window

  Sets focus to the specified window, if the current process is on top
 ------------------------------------------------------------------------------}
function TWin32WidgetSet.SetActiveWindow(Window: HWND): HWND;
begin
  Result := Windows.SetActiveWindow(Window);
end;

{------------------------------------------------------------------------------
  Method:  SetBkColor
  Params:  DC    - Device context to change the text background color
           Color - background color value
  Returns: Old Background color

  Sets the current background color to the specified color value.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetBKColor(DC: HDC; Color: TColorRef): TColorRef;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.SetBKColor] DC: 0x%x Color: %8x', [Integer(DC), Color]));
  Result := Windows.SetBkColor(DC, Windows.COLORREF(ColorToRGB(Color)));
  Assert(False, Format('Trace:< [TWin32WidgetSet.SetBKColor] DC: 0x%x Color: %8x --> %8x', [Integer(DC), Color, Result]));
End;

{------------------------------------------------------------------------------
  Method:  SetBkMode
  Params: DC     - handle of device context
          BkMode - flag specifying background mode
  Returns: the previous background mode

  Sets the background mix mode of the specified device context.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetBkMode(DC: HDC; BkMode: Integer): Integer;
Begin
  // Your code here
  Result := Windows.SetBkMode(DC, BkMode);
End;

{------------------------------------------------------------------------------
  Method:  SetCapture
  Params:  Value - Handle of window to capture
  Returns: the handle of the window that had previously captured the mouse

  Sets the mouse capture to the specified window.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetCapture(Value: HWND): HWND;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.SetCapture] 0x%x', [Value]));
  Result := Windows.SetCapture(Value);
  Assert(False, Format('Trace:< [TWin32WidgetSet.SetCapture] 0x%x --> 0x%x', [Value, Result]));
End;

{------------------------------------------------------------------------------
  Method:  SetCaretPos
  Params:  new position x, y
  Returns: true on success

  Moves the caret to the specified coordinates.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetCaretPos(X, Y: Integer): Boolean;
Begin
{$ifdef DEBUG_CARET}
  DebugLn('[SetCaretPos]');
{$endif}
  Result := Boolean(Windows.SetCaretPos(X, Y));
End;

{------------------------------------------------------------------------------
  Method:  SetCaretPosEx
  Params:  Handle - handle of window
           X      - horizontal mouse coordinate
           Y      - vertical mouse coordinate
  Returns: true on success

  Moves the caret to the specified coordinates in the specified window.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetCaretPosEx(Handle: HWND; X, Y: Integer): Boolean;
Begin
{$ifdef DEBUG_CARET}
  DebugLn('[SetCaretPosEx] for window ', IntToHex(Handle, 8));
{$endif}
  Result := Windows.SetCaretPos(X, Y);
End;

function TWin32WidgetSet.SetCursor(hCursor: HICON): HCURSOR;
begin
  Result := Windows.SetCursor(Windows.LoadCursor(0, LclCursorToWin32CursorMap[hCursor]));
end;

{------------------------------------------------------------------------------
  Function: SetCursorPos
  Params: X:
          Y:
  Returns:

 ------------------------------------------------------------------------------}
function TWin32WidgetSet.SetCursorPos(X, Y: Integer): Boolean;
begin
  Result := False;
  Windows.SetCursorPos(X, Y);
  Result := True;
end;

{------------------------------------------------------------------------------
  Method:  SetFocus
  Params:  HWnd - Handle of new focus window
  Returns: The old focus window

  The SetFocus function sets the keyboard focus to the specified window
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetFocus(HWnd: HWND): HWND;
Begin
  Result := Windows.SetFocus(HWnd);
End;

{------------------------------------------------------------------------------
  Method:  SetForegroundWindow
  Params:  HWnd - The handle of the window
  Returns: True if succesful

  The SetForegroundWindow function brings the specified window to top
    (highest z-index level).
 ------------------------------------------------------------------------------}
function TWin32WidgetSet.SetForegroundWindow(HWnd: HWND): boolean;
Begin
  Assert(False, 'Trace:TWin32WidgetSet.SetForegroundWindow - Start');
  Result := Windows.SetForegroundWindow(HWnd);
  Assert(False, 'Trace:TWin32WidgetSet.SetForegroundWindow - Exit');
End;

{------------------------------------------------------------------------------
  Method:  SetProp
  Params:  Handle - handle of window
           Str    - string
           Data   - pointer to data
  Returns: Whether the string and data were successfully added to the property
           list.

  Adds a new entry or changes an existing entry in the property list of the
  specified window.

  NOTE: LCLLinux has no RemoveProp function but Windows API requires all set
  properties to be removed, so I'm keeping a list of windows with properties
  for a properties-enumeration function that's called when the program is quit.

  MWE: that is not really needed anymore since the RemoveProp is now implemented
 ------------------------------------------------------------------------------}
function TWin32WidgetSet.SetProp(Handle: HWND; Str: PChar; Data: Pointer): Boolean;
begin
  Assert(False, 'Trace:TWin32WidgetSet.SetProp - Start');
  Result := Boolean(Windows.SetProp(Handle, Str, Windows.HANDLE(Data)));
  Assert(False, Format('Trace:TWin32WidgetSet.SetProp --> Window handle: 0x%X, Propery to set: %S, Data to set: 0x%P, Property was successfully set: %S', [Handle, String(Str), Data, BOOL_RESULT[Result]]));
End;

{------------------------------------------------------------------------------
  Method:  SetROP2
  Params:  DC			- Device Context
           Mode		- Foreground mixing mode

  Returns: 0 if unsuccessful or the old Mode if successful
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetROP2(DC: HDC; Mode: Integer): Integer;
begin
	result := Windows.SetROP2(DC, Mode);
end;

{------------------------------------------------------------------------------
  Method:  SetScrollInfo
  Params:  Handle     - handle of window with scroll bar
           SBStyle    - scroll bar flag
           ScrollInfo - record with scroll parameters
           BRedraw    - is the scroll bar is redrawn?
  Returns: The old position value

  Sets the parameters of a scroll bar.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetScrollInfo(Handle: HWND; SBStyle: Integer; ScrollInfo: TScrollInfo; BRedraw: Boolean): Integer;
Begin
//  Assert(False, 'Trace:[TWin32WidgetSet.SetScrollInfo]');
  //With ScrollInfo Do
   // Assert(False, Format('Trace:> [TWin32WidgetSet.SetScrollInfo] Mask:0x%x, Min:%d, Max:%d, Page:%d, Pos:%d', [FMask, NMin, NMax, NPage, NPos]));
  ScrollInfo.cbSize:=sizeof(ScrollInfo);
  Result := Windows.SetScrollInfo(Handle, SBStyle, @ScrollInfo, BRedraw);
  With ScrollInfo Do
    Assert(False, Format('Trace:> [TWin32WidgetSet.SetScrollInfo] --> %d', [Result]));
End;

{------------------------------------------------------------------------------
  Method:  SetSysColors
  Params:  CElements    - the number of elements
           LPAElements  - array with element numbers
           LPARGBValues - array with colors
  Returns: 0 if unsuccesful

  The SetSysColors function sets the colors for one or more display elements.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetSysColors(CElements: Integer; Const LPAElements; Const LPARGBValues): Boolean;
Begin
  Result := Boolean(Windows.SetSysColors(CElements, PInteger(@LPAElements)^, LPColorRef(@LPARGBValues)^));
End;

{------------------------------------------------------------------------------
  Method:  SetTextCharacterExtra
  Params: _HDC       - handle of device context
          NCharExtra - extra-space value
  Returns: the previous intercharacter spacing

  Sets the intercharacter spacing.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetTextCharacterExtra(_HDC: HDC; NCharExtra: Integer): Integer;
Begin
  // Your code here
  Result := Windows.SetTextCharacterExtra(_HDC, NCharExtra);
End;

{------------------------------------------------------------------------------
  Method:  SetTextColor
  Params:  DC    - Identifies the device context.
           Color - Specifies the color of the text.
  Returns: The previous color if succesful, CLR_INVALID otherwise

  The SetTextColor function sets the text color for the specified device
  context to the specified color.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetTextColor(DC: HDC; Color: TColorRef): TColorRef;
Begin
  Assert(False, Format('Trace:> [TWin32WidgetSet.SetTextColor] DC: 0x%x Color: %8x', [Integer(DC), Color]));
  Result := Windows.SetTextColor(DC, Windows.COLORREF(ColorToRGB(Color)));
  Assert(False, Format('Trace:< [TWin32WidgetSet.SetTextColor] DC: 0x%x Color: %8x --> %8x', [Integer(DC), Color, Result]));
End;

{------------------------------------------------------------------------------
  Procedure: GetWindowLong
  Params:  Handle  - handle of window
           Idx     - value to set
           NewLong - new value
  Returns: Nothing

  Changes an attribute of the specified window.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetWindowLong(Handle: HWND; Idx: Integer; NewLong: PtrInt): PtrInt;
Begin
  //TODO: Finish this;
  Assert(False, Format('Trace:> [TWin32WidgetSet.SetWindowLong] HWND: 0x%x, Idx: 0x%x(%d), Value: 0x%x(%d)', [Handle, Idx, Idx, NewLong, NewLong]));
{$ifdef ver2_0}
  Result := Windows.SetWindowLong(Handle, Idx, NewLong);
{$else}
  Result := Windows.SetWindowLongPtr(Handle, Idx, NewLong);
{$endif}
  Assert(False, Format('Trace:< [TWin32WidgetSet.SetWindowLong] HWND: 0x%x, Idx: 0x%x(%d), Value: 0x%x(%d) --> 0x%x(%d)', [Handle, Idx, Idx, NewLong, NewLong, Result, Result]));
End;

{------------------------------------------------------------------------------
  Method:  SetWindowOrgEx
  Params:  DC    - handle of device context
           NewX  - new x-coordinate of window origin
           NewY  - new y-coordinate of window origin
           Point - record receiving original origin
  Returns: Whether the call was successful

  Sets the window origin of the device context by using the specified coordinates.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetWindowOrgEx(DC: HDC; NewX, NewY: Integer;
  OldPoint: PPoint): Boolean;
Begin
  Result := Boolean(Windows.SetWindowOrgEx(DC, NewX, NewY, LPPoint(OldPoint)));
End;

{------------------------------------------------------------------------------
  Method:  SetWindowPos
  Params: HWnd            - handle of window
          HWndInsertAfter - placement-order handle
          X               - horizontal position
          Y               - vertical position
          CX              - width
          CY              - height
          UFlags          - window-positioning flags
  Returns: If the function succeeds

  Changes the size, position, and Z order of a child, pop-up, or top-level
  window.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.SetWindowPos(HWnd: HWND; HWndInsertAfter: HWND; X, Y, CX, CY: Integer; UFlags: UINT): Boolean;
var
  Style, ExStyle: PtrInt;
  OldRect, OldClientRect: Windows.RECT;
Begin
  //debugln('[TWin32WidgetSet.SetWindowPos] Top=',HWndInsertAfter=HWND_TOP);
  Style := GetWindowLong(HWnd, GWL_STYLE);
  ExStyle := GetWindowLong(HWnd, GWL_EXSTYLE);
  Windows.GetWindowRect(HWnd, @OldRect);
  Windows.GetClientRect(HWnd, @OldClientRect);
  if (Style and WS_BORDER) <> 0 then
  begin
    // convert top level lcl window coordinaties to win32 coord
    // add twice, top+bottom border
    Inc(CX, 2*Windows.GetSystemMetrics(SM_CXSIZEFRAME));
    Inc(CY, 2*Windows.GetSystemMetrics(SM_CYSIZEFRAME));
  end;
  if (Style and WS_CAPTION) <> 0 then
    if (ExStyle and WS_EX_TOOLWINDOW) <> 0 then
      Inc(CY, Windows.GetSystemMetrics(SM_CYSMCAPTION))
    else
      Inc(CY, Windows.GetSystemMetrics(SM_CYCAPTION));
  Result := Boolean(Windows.SetWindowPos(HWnd, HWndInsertAfter, X, Y, CX, CY, UFlags));
End;

{------------------------------------------------------------------------------
  Method:  ShowCaret
  Params:  HWnd - handle of window with caret
  Returns: if the function succeeds

  Makes the caret visible on the screen at the caret's current position.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.ShowCaret(HWnd: HWND): Boolean;
Begin
//writeln('[TWin32WidgetSet.ShowCaret] A');
{$ifdef DEBUG_CARET}
  DebugLn('[ShowCaret] for window ', IntToHex(HWnd, 8));
{$endif}
  Assert(False, Format('Trace:> [TWin32WidgetSet.ShowCaret] HWND: 0x%x', [HWnd]));
  Result := Boolean(Windows.ShowCaret(HWnd));
  Assert(False, Format('Trace:< [TWin32WidgetSet.ShowCaret] HWND: 0x%x --> %s', [HWnd, BOOL_TEXT[Result]]));
End;

{------------------------------------------------------------------------------
  Method:   ShowScrollBar
  Params:  Handle - handle of window with scroll bar
           WBar   - scroll bar flag
           BShow  - is the scroll bar visible?
  Returns: If the function succeeds

  Shows or hides the specified scroll bar.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.ShowScrollBar(Handle: HWND; WBar: Integer; BShow: Boolean): Boolean;
Begin
  Assert(False, 'Trace:[TWin32WidgetSet.ShowScrollBar]');
  Result := Boolean(Windows.ShowScrollBar(Handle, WBar, BShow));
End;

{------------------------------------------------------------------------------
  Method: ShowWindow
  Params: hWnd     - Window handle
          nCmdShow - (SW_SHOWNORMAL, SW_MINIMIZE, SW_SHOWMAXIMIZED)
  Returns: If the function succeeds
------------------------------------------------------------------------------}
Function TWin32WidgetSet.ShowWindow(hWnd: HWND; nCmdShow: Integer): Boolean;
begin
  Result := Boolean(Windows.ShowWindow(hWnd, nCmdShow));
end;

{------------------------------------------------------------------------------
  Method:  StretchBlt
  Params:  DestDC              - The destination device context
           X, Y                - The left/top corner of the destination rectangle
           Width, Height       - The size of the destination rectangle
           SrcDC               - The source device context
           XSrc, YSrc          - The left/top corner of the source rectangle
           SrcWidth, SrcHeight - The size of the source rectangle
           Rop                 - The raster operation to be performed
  Returns: True if succesful

  The StretchBlt function copies a bitmap from a source rectangle into a
  destination rectangle using the specified raster operation. If needed it
  resizes the bitmap to fit the dimensions of the destination rectangle.
  Sizing is done according to the stretching mode currently set in the
  destination device context.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.StretchBlt(DestDC: HDC; X, Y, Width, Height: Integer; SrcDC: HDC; XSrc, YSrc, SrcWidth, SrcHeight: Integer; Rop: Cardinal): Boolean;
Begin
  Assert(True, Format('Trace:> [TWin32WidgetSet.StretchBlt] DestDC:0x%x; X:%d, Y:%d, Width:%d, Height:%d; SrcDC:0x%x; XSrc:%d, YSrc:%d, SrcWidth:%d, SrcHeight:%d; Rop:0x%x', [DestDC, X, Y, Width, Height, SrcDC, XSrc, YSrc, SrcWidth, SrcHeight, Rop]));
  Result := Boolean(Windows.StretchBlt(DestDc, X, Y, Width, Height, SrcDC, XSrc, YSrc, SrcWidth, SrcHeight, Rop));
  Assert(True, Format('Trace:< [TWin32WidgetSet.StretchBlt] DestDC:0x%x --> %s', [DestDC, BOOL_TEXT[Result]]));
End;

{------------------------------------------------------------------------------
  Method:  StretchMaskBlt
  Params:  DestDC:                The destination devicecontext
           X, Y:                  The left/top corner of the destination rectangle
           Width, Height:         The size of the destination rectangle
           SrcDC:                 The source devicecontext
           XSrc, YSrc:            The left/top corner of the source rectangle
           SrcWidth, SrcHeight:   The size of the source rectangle
           Mask:                  The handle of a monochrome bitmap
           XMask, YMask:          The left/top corner of the mask rectangle
           Rop:                   The raster operation to be performed
  Returns: True if succesful

  The StretchMaskBlt function copies a bitmap from a source rectangle into a
  destination rectangle using the specified mask and raster operations. If
  needed it resizes the bitmap to fit the dimensions of the destination
  rectangle.  Sizing is done according to the stretching mode currently set in
  the destination device context.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.StretchMaskBlt(DestDC: HDC; X, Y, Width, Height: Integer; SrcDC: HDC; XSrc, YSrc, SrcWidth, SrcHeight: Integer; Mask: HBITMAP; XMask, YMask: Integer; Rop: DWORD): Boolean;
Var
  MaskDC: HDC;
  SaveObj: HGDIOBJ;
  PrevTextColor, PrevBkColor: COLORREF;
Begin
  if Mask = 0 then
  begin
    if (Width = SrcWidth) and (Height = SrcHeight) then
    begin
      Result := Windows.BitBlt(DestDC, X, Y, Width, Height, SrcDC, XSrc, YSrc, SRCCOPY);
    end else begin
      Result := Windows.StretchBlt(DestDC, X, Y, Width, Height, SrcDC, XSrc, YSrc, SrcWidth, SrcHeight, SRCCOPY);
    end;
  end else begin
    MaskDC := Windows.CreateCompatibleDC(0);
    SaveObj := Windows.SelectObject(MaskDC, Mask);
    PrevTextColor := Windows.SetTextColor(DestDC, RGB(255,255,255));
    PrevBkColor := Windows.SetBkColor(DestDC, RGB(0,0,0));
    if (Width = SrcWidth) and (Height = SrcHeight) then
    begin
      Windows.BitBlt(DestDC, X, Y, Width, Height, SrcDC,  XSrc, YSrc, SRCINVERT);
      Windows.BitBlt(DestDC, X, Y, Width, Height, MaskDC, XSrc, YSrc, SRCAND);
      Windows.BitBlt(DestDC, X, Y, Width, Height, SrcDC,  XSrc, YSrc, SRCINVERT);
    end else begin
      Windows.StretchBlt(DestDC, X, Y, Width, Height, SrcDC,  XSrc, YSrc, SrcWidth, SrcHeight, SRCINVERT);
      Windows.StretchBlt(DestDC, X, Y, Width, Height, MaskDC, XSrc, YSrc, SrcWidth, SrcHeight, SRCAND);
      Windows.StretchBlt(DestDC, X, Y, Width, Height, SrcDC,  XSrc, YSrc, SrcWidth, SrcHeight, SRCINVERT);
    end;
    Windows.SetTextColor(DestDC, PrevTextColor);
    Windows.SetBkColor(DestDC, PrevBkColor);
    Windows.SelectObject(MaskDC, SaveObj);
    Windows.DeleteDC(MaskDC);
  end;
  Result := true;
end;

{------------------------------------------------------------------------------
  Method:  TextOut
  Params: DC    - handle of device context
          X     - x-coordinate of starting position
          Y     - y-coordinate of starting position
          Str   - string
          Count - number of characters in string
  Returns: If the function succeeds

  Writes a character string at the specified location, using the currently
  selected font.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.TextOut(DC: HDC; X, Y: Integer; Str: PChar; Count: Integer): Boolean;
Begin
  Result := Boolean(Windows.TextOut(DC, X, Y, Str, Count));
End;

{------------------------------------------------------------------------------
  Method:  WindowFromPoint
  Params: Point: Specifies the x and y Coords
  Returns: The handle of the window.

  Retrieves the handle of the window that contains the specified point.
 ------------------------------------------------------------------------------}
Function TWin32WidgetSet.WindowFromPoint(Point: TPoint): HWND;
Var
  ProcessID: DWORD;
Begin
  Result := Windows.WindowFromPoint(Windows.POINT(Point));
  // check if window created by this process
  Windows.GetWindowThreadProcessId(Result, @ProcessID);
  if ProcessID <> Windows.GetCurrentProcessID then
    Result := 0;
End;


{We interprete CritSection as a pointer to a LPCRITICAL_SECTION structure}
Procedure TWin32WidgetSet.InitializeCriticalSection(var CritSection: TCriticalSection);
var
  Crit : LPCRITICAL_SECTION;
begin
  { An OS Compatible TCriticalSection needs to be defined}
  If CritSection <> 0 then
    DeleteCriticalSection(CritSection);
  New(Crit);
  Windows.InitializeCriticalSection(Crit);
  CritSection := TCriticalSection(Crit);
end;

Procedure TWin32WidgetSet.EnterCriticalSection(var CritSection: TCriticalSection);
begin
  { An OS Compatible TCriticalSection needs to be defined}
  Windows.EnterCriticalSection(LPCRITICAL_SECTION(CritSection));
end;

Procedure TWin32WidgetSet.LeaveCriticalSection(var CritSection: TCriticalSection);
begin
  { An OS Compatible TCriticalSection needs to be defined}
  Windows.LeaveCriticalSection(LPCRITICAL_SECTION(CritSection));
end;

Procedure TWin32WidgetSet.DeleteCriticalSection(var CritSection: TCriticalSection);
begin
  { An OS Compatible TCriticalSection needs to be defined}
  if CritSection<>0 then
  begin
    Windows.DeleteCriticalSection(LPCRITICAL_SECTION(CritSection));
    Try
      Dispose(LPCRITICAL_SECTION(CritSection));
    finally
      CritSection := 0;
    end;
  end;
end;

//##apiwiz##eps##   // Do not remove

{$IFDEF ASSERT_IS_ON}
  {$UNDEF ASSERT_IS_ON}
  {$C-}
{$ENDIF}

