#Include-Once
#include <GUIConstants.au3>
#Include <GUITreeView.au3>

;===============================================================================
;
; Description:      Displays given array in a treeview, with multi-dimensional
;                   and nested arrays supported
; Parameter(s):     $avArray - Array to display
;                   $sTitle  - [optional] Title to use for window
;                   $iWidth  - [optional] Width to use for window
;                   $iHeight - [optional] Height to use for window
; Requirement(s):   None
; Return Value(s):  On Success -  Returns 1
;                   On Failure -  Returns 0 and sets @error to 1
; Author(s):        Ultima
; Note(s):          - This function can theoretically support arrays with an
;                     unlimited number of dimensions, though in reality, it is
;                     limited by VAR_SUBSCRIPT_MAX (an AutoIt hard limit)
;                   - Unlimited nested arrays are supported
;
;===============================================================================
Func _ArrayDisplayTree(Const ByRef $avArray, $sTitle = "Array: TreeView Display", $iWidth = 400, $iHeight = 300)
	If Not IsArray($avArray) Then Return SetError(1, 0, 0)

	Local $iOnEventMode = Opt("GUIOnEventMode", 0)
	Local $hGUI = GUICreate($sTitle, $iWidth, $iHeight, DEFAULT, DEFAULT, $WS_MINIMIZEBOX + $WS_MAXIMIZEBOX)
	Local $iTreeView = GUICtrlCreateTreeView(0, 0, $iWidth-5, $iHeight-30, $GUI_SS_DEFAULT_TREEVIEW + $TVS_NONEVENHEIGHT, $WS_EX_CLIENTEDGE)
	GUICtrlSetResizing($iTreeView, $GUI_DOCKBORDERS)

	__treeAdd($iTreeView, $avArray)
	GUISetState()

	While GUIGetMsg() <> $GUI_EVENT_CLOSE
	WEnd
	GUIDelete($hGUI)

	Opt("GUIOnEventMode", $iOnEventMode)

	Return 1
EndFunc ;==>_ArrayDisplayTree

; Private
Func __treeAdd(ByRef $iTreeView, Const ByRef $avArray, $iParent = 0, $sPath = "", $iDimension = 1)
	If UBound($avArray, 0) > $iDimension Then
		For $i = 0 To UBound($avArray, $iDimension)-1
			__treeAdd($iTreeView, $avArray, _GUICtrlTreeView_InsertItem($iTreeView, "[" & $i & "]", $iParent), $sPath & $i & "][", $iDimension+1)
		Next
	Else
		For $i = 0 To UBound($avArray, $iDimension)-1
			Local $vItem = Execute("$avArray[" & $sPath & $i & "]")
			If IsArray($vItem) Then
				__treeAdd($iTreeView, $vItem, _GUICtrlTreeView_InsertItem($iTreeView, "[" & $i & "]", $iParent))
			Else
				_GUICtrlTreeView_InsertItem($iTreeView, "[" & $i & "] " & $vItem, $iParent)
			EndIf
		Next
	EndIf
EndFunc ;==>__treeAdd
