; #########################################################################
; # my WndProc for asmIRC
; #########################################################################

        include         asmIRC.inc

; #########################################################################
; # procedures
; #########################################################################

	EditProc PROTO :DWORD,:DWORD,:DWORD,:DWORD 	; in this file
	ViewProc PROTO :DWORD,:DWORD,:DWORD,:DWORD 	; in this file
        OnEditString PROTO :DWORD                       ; in this file
	ScrollToBottom PROTO :DWORD			; in this file

; #########################################################################
; # data
; #########################################################################

    .const
	public szAbout
        szAbout db      "asmIRC v",VERSION,	;13,10,
                        " coded in 32bit asm by zathan.",0
	IDC_EDIT 	EQU 	100
	IDC_VIEW	EQU	101
	IDC_STATUS	EQU 	102
        MAX_BUFFER      EQU     100*MAX_STRLEN	; increase to get bigger scrollback
	WM_SOCKET	EQU 	WM_USER+200	; uMsg sendt by an AsyncSocket
        extrn 	szDisplayName	:BYTE		; in WinMain.asm

    .data?
        szView          db MAX_BUFFER dup (?)   ; the view buffer
 	szBuffer	db MAX_STRLEN dup (?)	; the input buffer

    .data
	extrn 	hMain 		:DWORD		; in WinMain.asm
        extrn   hInstance 	:DWORD		; in WinMain.asm
	extrn 	hIRCSocket	:DWORD		; in IRCSocket.asm

	public hStatus 				; for use in IRCSocket.asm
        hStatus 	dd 0                    ; the status window
	hEdit		dd 0			; the edit window
	lpfnEditProc 	dd 0			; lp to original EditProc
	hView		dd 0			; the view window
	lpfnViewProc	dd 0 			; lp to original ViewProc
        nViewPos        dd 0                    ; count of chars in view

	; socket stuff
    	wsadata 	WSAData <>		; for WSAStartup

    .code
; #########################################################################
; # WndProc procedure
; #########################################################################
WndProc proc hWnd :DWORD, uMsg :DWORD, wParam :DWORD, lParam :DWORD

    LOCAL nWidth :DWORD
    LOCAL nHeight:DWORD
;    LOCAL hDC    :DWORD
    LOCAL rect   :RECT
    LOCAL ps     :PAINTSTRUCT
    LOCAL tm	 :TEXTMETRIC

    mov eax, uMsg
    .if eax == WM_CREATE

						;*** create the status bar
        invoke CreateStatusWindow,WS_CHILD or WS_VISIBLE or SBS_SIZEGRIP,
				  0, hWnd, IDC_STATUS
        mov hStatus, eax

						;*** create the edit window
	szText szEdit,"edit"
	invoke CreateWindowEx,WS_EX_CLIENTEDGE, ADDR szEdit, NULL,
               WS_CHILD or WS_VISIBLE or ES_LEFT or ES_AUTOHSCROLL,
               0,0,0,0,hWnd,IDC_EDIT, hInstance,NULL		
   	mov  hEdit,eax
	invoke SetWindowLong,hEdit,GWL_WNDPROC,EditProc	; set new EditProc
	mov lpfnEditProc, eax				; save old

						;*** create the view window
	szText szStatic,"static"
	invoke CreateWindowEx,WS_EX_CLIENTEDGE, ADDR szEdit, NULL,
               WS_CHILD or WS_VISIBLE or WS_VSCROLL or ES_READONLY or \
               ES_MULTILINE or ES_LEFT or ES_AUTOVSCROLL,
               0,0,0,0,hWnd,IDC_VIEW, hInstance,NULL     ; eax = hInstance
	mov  hView,eax
	invoke SetWindowLong,hView,GWL_WNDPROC,ViewProc	; set new ViewProc
	mov lpfnViewProc, eax				; save old

      	invoke SetFocus, hEdit
        invoke AddViewString, ADDR szAbout              

						;*** init WSA and create the socket     	
	invoke WSAStartup, 0101h, addr wsadata 		; Init Winsockets 
	.if eax!=NULL 					; error
		szText szWSAFailed, "ERROR: WSAStartup failed!"
		invoke AddViewString, ADDR szWSAFailed
     	.else 						; ok, display some socket info
		invoke AddViewString, ADDR wsadata.szDescription
		invoke AddViewString, ADDR wsadata.szSystemStatus

		szText szWSAFormat1, "MaxVersion : %#0.4x, MaxSockets : %u."
		xor 	eax,eax				; zero
		mov 	ax, wsadata.wHighVersion	; move word into eax
		xor 	ebx,ebx
		mov	bx, wsadata.iMaxSockets		; ditto
		invoke wsprintf, ADDR szBuffer, ADDR szWSAFormat1, eax, ebx
		invoke AddViewString, ADDR szBuffer
   		
		invoke socket,AF_INET,SOCK_STREAM,0     ; Create the socket
		.if eax!=INVALID_SOCKET 
		    mov hIRCSocket,eax
		    invoke WSAAsyncSelect,eax,hWnd,WM_SOCKET,
         		FD_CONNECT+FD_READ+FD_WRITE+FD_CLOSE 
   		.else 
		    szText szSocketFailed,"ERROR: Failed to create socket!"
		    invoke AddViewString, ADDR szSocketFailed
		.endif
	.endif

    .elseif eax == WM_SIZE
        m2m nWidth , lParam[0]  ; client area width
        m2m nHeight, lParam[2]  ; client area height
							; resize hStatus
	invoke PostMessage,hStatus,WM_SIZE,0,0		; autoresize
        invoke GetWindowRect,hStatus,ADDR rect
        mov eax, rect.bottom
        sub eax, rect.top
	mov ebx, nHeight
        sub ebx, eax
;        invoke MoveWindow,hStatus,0,ebx,nWidth,ebx,TRUE	
							; resize hEdit
	sub ebx, 20	; gotta change this later to the font height... 
	invoke MoveWindow,hEdit,0,ebx,nWidth,20,TRUE	; assume 20 pixels 
							; resize hView
	invoke MoveWindow,hView,0,0,nWidth,ebx,TRUE		
	invoke ScrollToBottom, hView			; go to bottom

    .elseif eax == WM_COMMAND
	mov eax, wParam
	.if lParam==0				; menu messages
		.if ax == IDM_EXIT
            		invoke SendMessage,hWnd,WM_SYSCOMMAND,SC_CLOSE,NULL
        	.elseif ax == IDM_ABOUT
		        invoke MessageBox, hWnd, ADDR szAbout, \
                               ADDR szDisplayName,MB_OK
	        .endif
	.else					; control messages
		.if ax == IDC_EDIT		; message from Edit box
			shr eax,16
		.elseif ax == IDC_VIEW		; message from View
			shr eax,16
		.elseif ax == IDC_STATUS        ; message from Status
			shr eax,16
		.endif
	.endif
    
    .elseif eax == WM_PAINT
        invoke BeginPaint,hWnd, ADDR ps
;        mov    hDC,eax
	invoke SetFocus, hEdit
        invoke EndPaint, hWnd, ADDR ps

; exit right away for now (I'm tired of this stupid box... :)
;    .elseif eax == WM_CLOSE
;        szText TheText,"Exit?"
;        invoke MessageBox,hWnd,ADDR TheText, ADDR szDisplayName,MB_YESNO
;          .if eax == IDNO
;            return 0
;          .endif

    .elseif eax == WM_ERASEBKGND	; don't erase the background
	return 0			; to avoid blinking

    .elseif eax == WM_DESTROY
	.if hIRCSocket!=NULL
 	    invoke closesocket, hIRCSocket	; close the socket
	    mov hIRCSocket,0
	.endif
	invoke WSACleanup 			; clean up sockets
        invoke PostQuitMessage,NULL
        return 0

    .elseif eax == WM_SOCKET  	; the message we specified in WSAAsyncSelect
        mov eax,lParam 
        .if ax==FD_CONNECT      ; the low word of lParam contains the event code. 
             shr eax,16   	; the error code (if any) is in the high word of lParam 
             .if ax==NULL 
	     	invoke OnConnect 
             .else 
             .endif 
        .elseif ax==FD_READ 
             shr eax,16 
             .if ax==NULL 
	        invoke ReadSocket
             .else 
             .endif 
	.elseif ax==FD_WRITE
	     shr eax,16
	     .if ax==NULL
		invoke WriteSocket
	     .else
	     .endif
        .elseif ax==FD_CLOSE 
             shr eax,16 
             .if ax==NULL 
		invoke OnDisconnect
             .else 
             .endif
 	.endif 
    .endif
    invoke DefWindowProc,hWnd,uMsg,wParam,lParam

    ret

WndProc endp ; ############################################################

; #########################################################################
; # EditProc, template made with MASM32 Control Subclass Builder
; #########################################################################
EditProc proc hCtl :DWORD, uMsg :DWORD, wParam :DWORD, lParam :DWORD

; ---------------------------------------------------
; EditProc PROTO :DWORD,:DWORD,:DWORD,:DWORD
;
; Put ' lpfnEditProc dd 0 ' in .data section
; Put ' hEdit        dd 0 ' in .data section
;
; The folowing function call should be placed on the lines
; following the function call that creates the control
;
; invoke SetWindowLong,hEdit,GWL_WNDPROC,EditProc
; mov lpfnEditProc, eax
; ---------------------------------------------------

    ; -----------------------------
    ; Process control messages here
    ; -----------------------------

    .if uMsg == WM_CHAR
	mov eax, wParam
	.if ax==VK_RETURN				; enter?
            invoke GetWindowText, hCtl, ADDR szBuffer, MAX_STRLEN 
	    invoke SetWindowText, hCtl, NULL		; empty edit
            invoke OnEditString, ADDR szBuffer  	; process string
	    return 0;
	.endif
    .elseif uMsg == WM_LBUTTONDBLCLK
    .endif
    invoke CallWindowProc,lpfnEditProc,hCtl,uMsg,wParam,lParam

    ret

EditProc endp ; ###########################################################

; #########################################################################
; # ViewProc, template made with MASM32 Control Subclass Builder
; #########################################################################
ViewProc proc hCtl :DWORD, uMsg :DWORD, wParam :DWORD, lParam :DWORD

    .if uMsg == WM_COPY
	invoke SetFocus,hEdit	; set focus back to edit box after copy...
;    .elseif uMsg == WM_ERASEBKGND
;	return 0
    .endif

    invoke CallWindowProc,lpfnViewProc,hCtl,uMsg,wParam,lParam

    ret
	
ViewProc endp ; ###########################################################

; #########################################################################
; # OnEditString, Processes string/command from edit box
; #########################################################################
OnEditString proc lpszString:DWORD

    mov edx, lpszString				
    mov al, byte ptr [edx]			; get first char into al
    .if al == '/'				; is it an irc command?
	invoke IRCCommand, lpszString	
    .else
        invoke AddViewString, lpszString	; echo input to view
	invoke SendIRCString, lpszString	
    .endif
    ret

OnEditString endp ; #######################################################

; #########################################################################
; # AddViewString, adds a string to the bottom of the view and updates it
; #########################################################################
AddViewString proc lpszString:DWORD

@l1:
    invoke lstrlen, lpszString	; get string length
    .if eax!=0                      ; ignore empty strings

        mov ecx, eax                ; ecx = length of string
        add eax, nViewPos           ; eax = room needed in buffer
        add eax, 3                  ; take into count the cr,lf,null

        .if eax>MAX_BUFFER          ; not room in buffer?
	    	        	    ; no, so remove the first line
	    lea edi, szView
	    mov al, 0Ah		    ; search for cr/lf
            mov ecx, nViewPos 	    ; don't search past end of buffer.
	    repnz scasb		
	    
            .if ecx==0              ; no room in buffer, erase all
		xor eax,eax	    ; (this will never happen as long as
		mov nViewPos,eax    ;  sizeof(szView)>sizeof(szBuffer)...
                jmp @l1		    ; start over
	    .else
		mov nViewPos, ecx
		inc ecx
		m2m esi,edi	    ; edi points past lf (rest of buffer)
		lea edi, szView	    ; move the rest up to beginning.
		rep movsb	    
		jmp @l1		    ; start over
            .endif
            
        .else                       ; room in buffer
            lea edi, szView
            add edi, nViewPos
            .if nViewPos !=0        ; if this is not the first string
                mov ax,0A0Dh        ; add Cr,Lf to last string
                cld
                stosw
                add nViewPos,2
            .endif
            add nViewPos,ecx
            mov esi,lpszString
            rep movsb          
            mov al,0		    ; zero terminate the string
            stosb
        .endif
        invoke SetWindowText, hView, ADDR szView
        invoke ScrollToBottom, hView
	invoke SetFocus, hEdit
    .endif
    
    ret

AddViewString endp ; ######################################################

; #########################################################################
; # ScrollToBottom, scrolls an edit window to the bottom line
; #########################################################################
ScrollToBottom proc hWnd:DWORD
    LOCAL MinPos:DWORD
    LOCAL MaxPos:DWORD

    invoke GetScrollRange, hWnd, SB_VERT, ADDR MinPos, ADDR MaxPos
    invoke PostMessage, hWnd, EM_LINESCROLL,0,MaxPos
    ret
ScrollToBottom endp ; #####################################################

end
