import QtQuick 2.14
import QtQuick.Controls 2.14
import QtQuick.Layouts 1.14
import QtQuick.Scene3D 2.14
import Qt3D.Core 2.14
import Qt3D.Render 2.14
import Qt3D.Input 2.14
import Qt3D.Extras 2.14
import QtQuick.Controls 2.5
import QtQuick 2.14 as QQ2

Item {
    id: root
    SystemPalette { id: activePalette }
    // FontLoader { id: stdFont; source: "file:fonts/SourceHanSansCN-Regular.otf" }
    MessageWindow { id: messageWindow }

    Scene3D {
        id: scene3d
        width: parent.width
        y: toolBar.height
        height:  parent.height - (toolBar.visible ? toolBar.height : 0) - (bottomPanel.visible ? bottomPanel.height : 0)
        anchors.bottom: bottomPanel.visible ? bottomPanel.top : bottomPanel.bottom
        focus: true
        aspects: ["input", "logic", "render"]
        cameraAspectRatioMode: Scene3D.UserAspectRatio

        entity: Entity {
            id: sceneRoot
            Layer {
                id : layer1
            }
            Layer {
                id : layer2
            }
            Camera {
                id: camera
                projectionType: CameraLens.OrthographicProjection
                fieldOfView: 30
                nearPlane : projectionType == CameraLens.OrthographicProjection ? -8192.0 : 0.05  //Show the point behind the camera in projectionType
                farPlane : 8192.0
                position: Qt.vector3d( 0.0, 0.0, 100.0 )
                upVector: Qt.vector3d( 0.0, -1.0, 0.0 )
                viewCenter: Qt.vector3d( 0.0, 0.0, 0.0 )
                bottom: camera.viewCenter.minus(camera.position).length() * Math.tan(-camera.fieldOfView / 2 * Math.PI / 180)
                left: bottom * camera.aspectRatio
                right: -left
                top: -bottom
            }

            KeyboardDevice {
                id: keyboardDevice
            }

            MouseDevice {
                id: mouseDevice
            }

            CameraController {
                id: cameraController
                camera: camera
            }

            DoubleViewportFrameGraph {
                id: doubleViewportFrameGraph
                leftCamera: camera
                rightCamera: camera
            }
            // RenderSettings {
            //     id: renderSettings
            //     activeFrameGraph: ForwardRenderer {
            //         camera: camera
            //         clearColor: activePalette.base
            //     }
            //     pickingSettings.pickMethod: PickingSettings.PrimitivePicking
            //     pickingSettings.faceOrientationPickingMode: PickingSettings.FrontAndBackFace
            //     pickingSettings.pickResultMode: PickingSettings.NearestPick
            // }
            InputSettings { 
                id: inputSettings
            }
            components: [
                // renderSettings,
                doubleViewportFrameGraph,
                inputSettings,
            ]

            NodeInstantiator {
                model: renderBuffers
                delegate: EntityLoader {
                    source: modelData.source
                }
            }
            Coordinates { id: colorCoordinates }
            Cartesion { id: cartesionCoordinates }
            Polar { id: polarCoordinates }
        }
    }

        MouseArea {
        id: selectArea
        width: scene3d.width
        height: scene3d.height
        anchors.verticalCenter: scene3d.verticalCenter
        anchors.horizontalCenter: scene3d.horizontalCenter
        acceptedButtons:Qt.LeftButton|Qt.MiddleButton|Qt.RightButton
        property var measureEnabled: false
        property var selectEnabled: false
        property Rectangle highlightItem : null
        property real x0: 0.0
        property real y0: 0.0
        property real lastX: 0.0
        property real lastY: 0.0
        property real camerWidth: 0.0
        property real lastWidth: 0.0
        property real lastHeight: 0.0
        signal selectionChanged(matrix4x4 selectionMatrix)
        function clearCanvas() {
            drawingCanvas.clear()
        }
        Canvas {
            id: drawingCanvas
            anchors.fill: parent
            renderTarget: Canvas.FramebufferObject
            property real endX: 0.0
            property real endY: 0.0
            property real distance: 0.0
            function clear() {
                var ctx = getContext("2d")
                ctx.reset()
                requestPaint()
            }
            function drawMeasureLine() {
                var ctx = getContext("2d")
                ctx.reset()
                ctx.lineWidth = 3;
                ctx.strokeStyle = activePalette.text
                ctx.beginPath()
                ctx.moveTo(selectArea.x0, selectArea.y0)
                ctx.lineTo(endX, endY)
                ctx.font = "24px sans-serif"
                ctx.fillStyle = activePalette.text
                ctx.fillText(distance.toFixed(3) + "m", (selectArea.x0+endX)/2, (selectArea.y0+endY)/2)
                ctx.stroke()
                requestPaint()
            }
            onPaint: {}
        }
        onPressed: {
            if (highlightItem != null) {
                highlightItem.destroy()
            }
            if (measureEnabled) {
                drawingCanvas.clear()
            }
            switch(pressedButtons) {
                case 1: // leftButton for selection
                {   
                    if(!(mouse.modifiers & Qt.ShiftModifier)) {
                        x0 = mouse.x
                        y0 = mouse.y                   
                    }
                    lastX = mouseX
                    lastY = mouseY  
                }
                break;
                case 2: // rightButton
                case 4: // middleButton
                {
                    lastX = mouseX
                    lastY = mouseY
                }
                break;
                default:
                break;
            }
        }

        onPositionChanged: {
            switch(pressedButtons) {
                case 1: // leftButton
                {
                    if (measureEnabled) { // leftButton enable for measure
                        drawingCanvas.endX = mouse.x
                        drawingCanvas.endY = mouse.y

                        var w = (camera.right - camera.left) * (drawingCanvas.endX - x0) / selectArea.width
                        var h = (camera.top - camera.bottom) * (drawingCanvas.endY - y0) / selectArea.height
                        // console.log("width: " + w + ", height:" + h)
                        drawingCanvas.distance = Math.sqrt(h*h + w*w)
                        drawingCanvas.drawMeasureLine()
                    }
                    else if (selectEnabled) { // leftButton enable for selection
                        if (highlightItem == null) {
                            highlightItem = selectionComponent.createObject(selectArea, {
                                x: x0,
                                y: y0
                            }) 
                            camerWidth = (camera.right - camera.left)
                            lastHeight = selectArea.height
                            lastWidth = selectArea.width

                        }
                        if (mouse.x > x0) {
                            camerWidth = (camera.right - camera.left) 
                            lastWidth = selectArea.width 
                            highlightItem.x = x0 
                            highlightItem.width = (mouse.x - x0) 
                        } 
                        else {
                            camerWidth = (camera.right - camera.left)
                            lastWidth = selectArea.width 
                            highlightItem.x = mouse.x 
                            highlightItem.width = (x0 - mouse.x) 
                        }

                        if (mouse.y > y0) {
                            lastHeight = selectArea.height
                            highlightItem.y = y0
                            highlightItem.height = mouse.y - y0
                        } 
                        else {
                            lastHeight = selectArea.height
                            highlightItem.y = mouse.y
                            highlightItem.height = y0 - mouse.y
                        }

                        // highlightItem.setSelectionWidthHeight(
                        //     (camera.right - camera.left) * highlightItem.width / selectArea.width,
                        //     (camera.top - camera.bottom) * highlightItem.height / selectArea.height
                        // )
                    }
                    else if(mouse.modifiers & Qt.ShiftModifier) { // shift on pressed for rotation by axis
                        timeline.skipExecution = true

                        var deltX = lastX - mouseX
                        var deltY = lastY - mouseY
                        var disfrontVector = camera.viewCenter.minus(camera.position)
                        var frontVector = disfrontVector.normalized()
                        var dis = disfrontVector.length()
                        var leftVector = camera.upVector.crossProduct(frontVector)
                        var height = 2 * dis * Math.tan(camera.fieldOfView / 2 * Math.PI / 180)
                        var width = height * camera.aspectRatio
                        if(mouseX > selectArea.width / 2){
                            deltY = -deltY
                        }
                        if(mouseY > selectArea.height / 2){
                            deltX = -deltX
                        }
                        var deltXY = (deltX - deltY ) / Math.sqrt(Math.pow((mouseX-selectArea.width / 2), 2) + Math.pow((mouseY-selectArea.height / 2), 2)) /
                                    Math.sqrt(Math.pow((2560 / selectArea.width), 2) + Math.pow((1183 / selectArea.height), 2))
                        var moveRightVector = leftVector.times(28.5 * -deltXY * width / scene3d.width * 100 / dis)
                        camera.upVector = camera.upVector.plus(moveRightVector).normalized()
                        lastX = mouseX
                        lastY = mouseY
                    }
                    else { // leftButton enable for rotation
                        timeline.skipExecution = true

                        var deltX = lastX - mouseX
                        var deltY = lastY - mouseY
                        var disfrontVector = camera.viewCenter.minus(camera.position)                      
                        var frontVector = disfrontVector.normalized()
                        var dis = disfrontVector.length()
                        var leftVector = camera.upVector.crossProduct(frontVector)
                        var height = 2 * dis * Math.tan(camera.fieldOfView / 2 * Math.PI / 180)
                        var width = height * camera.aspectRatio
                        var moveRightVector = leftVector.times(-deltX * width / scene3d.width )
                        var moveDownVector = camera.upVector.times(-deltY * height / scene3d.height )
                        var moveVector = moveRightVector.plus(moveDownVector)
                        var point = camera.position.plus(moveVector.times(9))

                        frontVector = camera.viewCenter.minus(point).normalized()
                        camera.position = camera.viewCenter.minus(frontVector.times(dis))
                        leftVector = camera.upVector.crossProduct(frontVector)
                        camera.upVector = frontVector.crossProduct(leftVector).normalized()
                        lastX = mouseX
                        lastY = mouseY
                    }
                    
                }
                break;
                case 2: // rightButton
                {
                    timeline.skipExecution = true

                    if(mouse.modifiers & Qt.ShiftModifier) { // shift on pressed for translation
                        var deltX = lastX - mouseX
                        var deltY = lastY - mouseY
                        var disfrontVector = camera.viewCenter.minus(camera.position)
                        var frontVector = disfrontVector.normalized()
                        var dis = disfrontVector.length()
                        var height = 2 * dis * Math.tan(camera.fieldOfView / 2 * Math.PI / 180)
                        var width = height * camera.aspectRatio
                        lastX = mouseX
                        lastY = mouseY
                        camera.translate(Qt.vector3d((deltX * width / scene3d.width) , - (deltY * height / scene3d.height) ,0) , Camera.TranslateViewCenter)
                    }
                    else { // zoom in/out
                        var dist = Math.sqrt(mouseX * mouseX + mouseY * mouseY)
                        var lastDist = Math.sqrt(lastX * lastX + lastY * lastY)
                        var disfrontVector = camera.viewCenter.minus(camera.position)
                        var frontVector = disfrontVector.normalized()
                        var proportion = Math.min(0.3, (dist - lastDist) * 0.03)
                        proportion = Math.max(-0.3, proportion)
                        camera.position = camera.position.plus(camera.viewCenter.minus(camera.position).times(proportion))
                        lastX = mouseX
                        lastY = mouseY
                    }

                }
                break;
                case 4: // middleButton on pressed for translation
                {
                    timeline.skipExecution = true

                    var deltX = lastX - mouseX
                    var deltY = lastY - mouseY
                    var disfrontVector = camera.viewCenter.minus(camera.position)
                    var frontVector = disfrontVector.normalized()
                    var dis = disfrontVector.length()
                    var height = 2 * dis * Math.tan(camera.fieldOfView / 2 * Math.PI / 180)
                    var width = height * camera.aspectRatio
                    lastX = mouseX
                    lastY = mouseY
                    camera.translate(Qt.vector3d((deltX * width / scene3d.width) , - (deltY * height / scene3d.height) ,0) , Camera.TranslateViewCenter)
                }
                break;
                default:
                break;

            }
        }
        onReleased: {
            // here you can add you zooming stuff if you want
           if (highlightItem != null) {
               var x1 = highlightItem.x * 2/selectArea.width*2-1
               var x2 = (highlightItem.x * 2+highlightItem.width *2)/selectArea.width*2-1
               var y1 = 1 - (highlightItem.y+highlightItem.height)/selectArea.height*2
               var y2 = 1 - highlightItem.y/selectArea.height*2
               selectionChanged(Qt.matrix4x4(
               2/(x2-x1), 0, 0, (x1+x2)/(x1-x2),
               0, 2/(y2-y1), 0, (y1+y2)/(y1-y2),
               0, 0, 1, 0,
               0, 0, 0, 1
               ).times(camera.projectionMatrix).times(camera.transform.worldMatrix.inverted()))
            }
            timeline.skipExecution = false
        }

        Component {
            id: selectionComponent
            Rectangle {
                id: selectionBorder
                border.width: 1
                border.color: activePalette.windowText
                color: "transparent"
                // Text {
                //     id: selectionWidthTxt
                //     visible: camera.projectionType == CameraLens.OrthographicProjection
                //     anchors.horizontalCenter: selectionBorder.horizontalCenter
                //     anchors.bottom: selectionBorder.top
                //     anchors.bottomMargin: 2
                //     color: activePalette.windowText
                //     font.bold: true
                //     style: Text.Outline
                //     styleColor: activePalette.window
                //     text: "0"
                // }
                // Text {
                //     id: selectionHeightTxt
                //     visible: camera.projectionType == CameraLens.OrthographicProjection
                //     anchors.left: selectionBorder.right
                //     anchors.leftMargin: 2
                //     anchors.verticalCenter: selectionBorder.verticalCenter
                //     color: activePalette.windowText
                //     font.bold: true
                //     style: Text.Outline
                //     styleColor: activePalette.window
                //     text: "0"
                // }
                // function setSelectionWidthHeight(w, h) {
                //     selectionWidthTxt.text = w.toFixed(3) + "m"
                //     selectionHeightTxt.text = h.toFixed(3) + "m"
                // }
            }
        }
    }

    property alias hud : hudColumn
    ScrollView {
        visible: !timeline.fullScreen  
        id: hudScrollView
        // parent: scene3d
        anchors.top: scene3d.top
        anchors.left: parent.left
        anchors.leftMargin: 12
        height: scene3d.height
        ColumnLayout {
            id: hudColumn
            anchors.fill: parent
            spacing: 5
        }
    }
    Item {
        id: invisibleHUD
        visible: false
    }


    property alias rightHUD : rightHUDColumn
    RowLayout {
        layoutDirection : Qt.RightToLeft 
        Layout.alignment : Qt.AlignRight 
        spacing: 0
        visible: !timeline.fullScreen 
        id: rightHUDColumn
        // parent: scene3d
        anchors.top: scene3d.top
        anchors.right: scene3d.right
        anchors.rightMargin: 6
        height: scene3d.height
    }

    Rectangle {
        visible: !timeline.fullScreen  
        id: topHUD
        color: "transparent"
        anchors.topMargin: parent.height * 0.05
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: toolBar.bottom
        height: 20
        width: parent.width * 0.5
    }

    Rectangle {
        visible: !timeline.fullScreen  
        id: bottomHUD
        color: "transparent"
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottom: scene3d.bottom
        height: 20
        width: parent.width * 0.9
    }


    Text {
        id: fpsText
        anchors.right : scene3d.right
        anchors.rightMargin : 5
        anchors.top : scene3d.top
        anchors.topMargin : 5
        visible: !timeline.fullScreen
        text: timeline.fps
        color: activePalette.windowText
        font.bold: true
        style: Text.Outline
        styleColor: activePalette.window
    }
    Timer {
        id : spinTimer
        interval: 30
        running: false 
        repeat: true
        onTriggered: {  
            var disfrontVector = camera.viewCenter.minus(camera.position)
            var frontVector = disfrontVector.normalized()
            if(frontVector.times(Qt.vector3d(1,1,0)).length() == 0 ){
                var leftVector = camera.upVector.crossProduct(frontVector).normalized().times(-0.01)
                camera.upVector = camera.upVector.plus(leftVector).normalized()
            }
            else{
                var dis = disfrontVector.length()
                var leftVector = frontVector.crossProduct(Qt.vector3d(0, 0, 1))
                var height = 2 * dis * Math.tan(camera.fieldOfView / 2 * Math.PI / 180)
                var width = height * camera.aspectRatio
                var moveRightVector = leftVector.times(3 * -1 * width / scene3d.width )
                var moveDownVector = camera.upVector.times(3 * -0 * height / scene3d.height )
                var moveVector = moveRightVector.plus(moveDownVector)
                var point = camera.position.plus(moveVector)
                frontVector = camera.viewCenter.minus(point).normalized()
                camera.position = camera.viewCenter.minus(frontVector.times(dis))
                var a = frontVector.times(Qt.vector3d(1,1,0))
                var b = camera.upVector.times(Qt.vector3d(0,0,1))
                var c = camera.upVector.times(Qt.vector3d(1,1,0))
                a = ((c.normalized().times(0.9)).plus(a.normalized().times(0.1))).normalized().times(c.length())
                camera.upVector = a.plus(b).normalized()
           }
        }
    }

    Rectangle {
        id: bottomPanel
        property var playByFrame: false
        visible: timeline.controlPanelDisplayed
        width: parent.width
        height: 120
        anchors.bottom: parent.bottom
        color: activePalette.window
        Row {
            id: controlTools
            spacing: 1
            y: 12
            Rectangle {
                width: 18
                height: 36
                color: "transparent"
            }
            RowLayout {
                id: leftBottomControlPanel
            }
            BottomToolButton {
                id: recordButton
                // hoverEnabled : true
                checkable: timeline.cursorSeconds > 0.1 && timeline.livingVisible
                icon.source: (timeline.cursorSeconds < 0.1 || !timeline.livingVisible) ? 'file:png/record-on-disable.png' : ((timeline.recording) ? 'file:png/record-off.png' : 'file:png/record-on.png') 
                signal recordingChanged(bool flag)
                onClicked: {
                    if(!checkable)
                        return
                    if (timeline.recording) {
                        recordingChanged(false)
                    }
                    else {
                        recordingChanged(true)
                    }
                }
                Action {
                    shortcut: "Ctrl+V"
                    onTriggered: recordButton.onClicked()
                }
                ToolTip {
                    visible: parent.hovered 
                    delay: 500
                    text: qsTr("Record (Ctrl+V)")
                }
            }

            BottomToolButton {
                id: toBeginButton
                checkable: timeline.cursorSeconds > 0.1 && !timeline.livingVisible
                icon.source: (timeline.cursorSeconds < 0.1 || timeline.livingVisible) ? 'file:png/to-begin-disable.png' : 'file:png/to-begin.png'
                onClicked: {
                    if(!checkable)
                        return
                    timeline.cursorSeconds = timeline.beginSeconds + 0.11 // experienced time shift for user
                    // console.log(timeline.cursorSeconds)
                }
                Action {
                    id: toBeginAction
                    shortcut: "Ctrl+Left"
                    onTriggered: {
                        toBeginButton.onClicked()
                    }
                }
                ToolTip {
                    visible: toBeginButton.hovered
                    delay: 500
                    text: qsTr("To Beginning (Ctrl+Left)")
                }
            }
            BottomToolButton {
                id: speedDownButton
                checkable: timeline.cursorSeconds > 0.1 && !timeline.livingVisible
                icon.source: (timeline.cursorSeconds < 0.1 || timeline.livingVisible) ?  'file:png/speed-down-disable.png' : 'file:png/speed-down.png'
                onClicked: {
                    if(!checkable)
                        return
                    if (timeline.playTimeScale > 1/64)
                        timeline.playTimeScale /= 2.0
                }
                Action {
                    id: speedDownAction
                    shortcut: "Shift+Left"
                    onTriggered: {
                        speedDownButton.onClicked()
                    }
                }
                ToolTip {
                    visible: speedDownButton.hovered
                    delay: 500
                    text: qsTr("Speed Down (Shift+Left)")
                }
            }
            BottomToolButton {
                id: playButton
                checkable: timeline.cursorSeconds > 0.1
                icon.source: timeline.cursorSeconds > 0.1 ? (timeline.playing ? 'file:png/play-pause.png' : 'file:png/play-start.png') : 'file:png/play-start-disable.png'
                signal playingChanged(bool flag)
                onClicked: {
                    if(!checkable)
                        return
                    timeline.playing = !timeline.playing
                    playingChanged(timeline.playing)
                }
                Action {
                    id: playAction
                    shortcut: "Space"
                    onTriggered: {
                        playButton.onClicked()
                    }
                }
                ToolTip {
                    visible: playButton.hovered
                    delay: 500
                    text: qsTr("Play/Pause (Space)")
                }
            }
            BottomToolButton {
                id: speedUpButton
                checkable: timeline.cursorSeconds > 0.1 && !timeline.livingVisible
                icon.source: (timeline.cursorSeconds < 0.1 || timeline.livingVisible) ? 'file:png/speed-up-disable.png' : 'file:png/speed-up.png'
                onClicked: {
                    if(!checkable)
                        return
                    if (timeline.playTimeScale < 64)
                        timeline.playTimeScale *= 2.0
                }
                Action {
                    id: speedUpAction
                    shortcut: "Shift+Right"
                    onTriggered: {
                        speedUpButton.onClicked()
                    }
                }
                ToolTip {
                    visible: speedUpButton.hovered
                    delay: 500
                    text: qsTr("Speed Up (Shift+Right)")
                }
            }
            BottomToolButton {
                id: toEndButton
                checkable: timeline.cursorSeconds > 0.1 && !timeline.livingVisible
                icon.source: (timeline.cursorSeconds < 0.1 || timeline.livingVisible) ? 'file:png/to-end-disable.png' :  'file:png/to-end.png'
                Timer {
                    id: toEndTimer
                    interval: 100
                    repeat: false
                    onTriggered: timeline.cursorSeconds = timeline.endSeconds-0.01
                }
                onClicked: {
                    if(!checkable)
                        return
                    if (timeline.playing) {
                        timeline.playing = false
                        toEndTimer.start()
                    }
                    else {
                        timeline.cursorSeconds = timeline.endSeconds-0.01
                    }
                }
                Action {
                    id: toEndAction
                    shortcut: "Ctrl+Right"
                    onTriggered: {
                        toEndButton.onClicked()
                    }
                }
                ToolTip {
                    visible: toEndButton.hovered
                    delay: 500
                    text: qsTr("To End (Ctrl+Right)")
                }
            }
            Rectangle {
                width: 48
                height: 36
                color: activePalette.button
                RowLayout {
                    anchors.horizontalCenter: parent.horizontalCenter
                    anchors.verticalCenter: parent.verticalCenter
                    spacing: 1
                    Label {
                        text: {
                            if (timeline.playTimeScale < 1) {
                                return ("1/"+Number(1/timeline.playTimeScale))
                            }
                            else {
                                return "x"+Number(timeline.playTimeScale)
                            }
                        }
                        color: timeline.cursorSeconds > 0.1 ? activePalette.text : "#7C7C7C"
                        font.pointSize: 12
                    }
                    // TextInput {
                    //     color: activePalette.text
                    //     font.pointSize: 12
                    //     text:  Number(timeline.playTimeScale)
                    //     selectByMouse: true
                    //     inputMethodHints: Qt.ImhFormattedNumbersOnly
                    //     onActiveFocusChanged: {
                    //         // When we first gain focus, select everything for clearing.
                    //         if (activeFocus) {
                    //             selectAll()
                    //         }
                    //     }
                    //     onEditingFinished: {
                    //         if (focus) {
                    //             timeline.playTimeScale = text
                    //             console.log("The playTimeScale is seted to:", + timeline.playTimeScale)
                    //             focus = false
                    //         }
                    //     }
                    // }
                }
            }
            BottomToolButton {
                id: liveButton
                icon.source: 'file:png/live.png'
                checkable: true
                checked: timeline.living
                visible: timeline.livingVisible 
                highlighted: timeline.living
                onClicked: {
                    timeline.living = !timeline.living
                }
                Action {
                    id: liveAction
                    shortcut: "Ctrl+Space"
                    onTriggered: {
                        liveButton.onClicked()
                    }
                }
                ToolTip {
                    visible: liveButton.hovered
                    delay: 500
                    text: qsTr("Live Streaming (Ctrl+Space)")
                }
            }
            Action {
                shortcut: "Left"
                onTriggered: {
                    timeline.cursorSeconds -= 0.1
                }
            }
            Action {
                shortcut: "Right"
                onTriggered: {
                    timeline.cursorSeconds += 0.1
                }
            }
            Rectangle {
                width: 18
                height: 36
                color: "transparent"
            }
        }
        ControlPanel {
            y: 12
            id: controlPanel
            width: parent.width - controlTools.width
            anchors.right: parent.right
        }
    }


    Rectangle {
        id: toolBar
        visible: !timeline.fullScreen
        implicitHeight: 48
        color: activePalette.window
        width: parent.width
        anchors.left: parent.left
        anchors.top: parent.top
        MouseArea {
            id: mouseArea
            anchors.fill: parent
            onWheel: {
                if (wheel.angleDelta.y > 0) {
                    if (toolBarContent.x < 0)
                        toolBarContent.x += 100
                }
                else {
                    if (toolBarContent.x + toolBarContent.width > toolBar.width)
                        toolBarContent.x -= 100
                }
            }
        }
        RowLayout {
            id: toolBarContent
            spacing: 1
            Rectangle {
                width: 18
                height: 36
                color: "transparent"
            }
            
            RowLayout {
                id: yellowToolBar
                spacing: 1
                DefaultToolButton {
                    id: fileOpenButton
                    icon.source: 'file:png/files.png'
                    onClicked: coremodel.openFileTimerStart()
                    onDoubleClicked: onClicked()
                    ToolTip {
                        visible: parent.hovered
                        delay: 500
                        text: qsTr("Open File (Ctrl+O)")
                    }
                }
                DefaultToolButton {
                    id: listenNetButton
                    icon.source: 'file:png/listenNet.png'
                    onClicked: coremodel.listenNetTimerStart()
                    onDoubleClicked: onClicked()
                    ToolTip {
                        visible: parent.hovered
                        delay: 500
                        text: qsTr("Listen Net (Ctrl+R)")
                    }
                }
            }
            Rectangle {
                width: 18
                height: 36
                color: "transparent"
            }
            RowLayout {
                id: purperToolBar
                spacing: 1
                DefaultToolButton {
                    id: cartesianButton
                    text: "Cartesian"
                    icon.source: 'file:png/cartesionCoordinate.png'
                    highlighted: cartesionCoordinates.visible
                    onClicked: cartesionCoordinates.visible = !cartesionCoordinates.visible
                    onDoubleClicked: cartesionCoordinates.visible = !cartesionCoordinates.visible
                    Action {
                        id:cartesianAction
                        shortcut: "Ctrl+E"
                        onTriggered: {
                            cartesianButton.onClicked()
                        }
                    }
                    ToolTip {
                        visible: cartesianButton.hovered
                        delay: 500
                        text: qsTr("Cartesian (Ctrl+E)")
                    }
                }
                DefaultToolButton {
                    id: polarButton
                    icon.source: 'file:png/grid.png'
                    highlighted: polarCoordinates.visible
                    onClicked: polarCoordinates.visible = !polarCoordinates.visible
                    onDoubleClicked: polarCoordinates.visible = !polarCoordinates.visible
                    Action {
                        id: polarAction
                        shortcut: "Ctrl+G"
                        onTriggered: {
                            polarButton.onClicked()
                        }
                    }
                    ToolTip {
                        visible: polarButton.hovered
                        delay: 500
                        text: qsTr("Polar (Ctrl+G)")
                    }
                }
                DefaultToolButton {
                    id: measureButton
                    text:'Ruler'
                    icon.source: 'file:png/ruler.png'
                    highlighted: selectArea.measureEnabled
                    onClicked: {
                        selectArea.measureEnabled = !selectArea.measureEnabled 
                        drawingCanvas.clear()
                    }
                    onDoubleClicked: onClicked()
                    Action {
                        shortcut: "Ctrl+Shift+R"
                        onTriggered: measureButton.onClicked()
                    }
                    ToolTip {
                        visible: parent.hovered
                        delay: 500
                        text: qsTr("Ruler (Ctrl+Shift+R)")
                    }
                }
                DefaultToolButton {
                    id: coordinatesButton
                    highlighted:colorCoordinates.enabled
                    icon.source: 'file:png/coord.png'
                    onClicked: {
                        colorCoordinates.enabled=!colorCoordinates.enabled;
                        
                    }
                    onDoubleClicked: onClicked()
                    Action {
                        shortcut: "Ctrl+Shift+C"
                        onTriggered: coordinatesButton.onClicked()
                    }
                    ToolTip {
                        visible: parent.hovered
                        delay: 500
                        text: qsTr("Coordinates(Ctrl+Shift+R)")
                    }
                }
            }
            Rectangle {
                width: 18
                height: 36
                color: "transparent"
            }
            DefaultToolButton {
                id: projectionButton
                text: "Projection"
                icon.source: 'file:png/crop-orthographic.png'
                highlighted: camera.projectionType == CameraLens.OrthographicProjection
                onClicked: {
                    camera.projectionType = CameraLens.OrthographicProjection                            
                }
                onDoubleClicked: {
                    camera.projectionType = CameraLens.OrthographicProjection                         
                }
                Action {
                    id: projectionAction
                    shortcut: "Ctrl+1"
                    onTriggered: {
                        projectionButton.onClicked()
                    }
                }
                ToolTip {
                    visible: projectionButton.hovered
                    delay: 500
                    text: qsTr("Orthographic Projection (Ctrl+1)")
                }
            }
            DefaultToolButton {
                id: perspectiveProjectionButton
                text: "Projection"
                icon.source: 'file:png/crop-perspective.png'
                highlighted: camera.projectionType == CameraLens.PerspectiveProjection
                onClicked: {
                    camera.projectionType = CameraLens.PerspectiveProjection                         
                }
                onDoubleClicked: {
                    camera.projectionType = CameraLens.PerspectiveProjection                         
                }
                Action {
                    shortcut: "Ctrl+2"
                    onTriggered: {
                        perspectiveProjectionButton.onClicked()
                    }
                }
                ToolTip {
                    visible: perspectiveProjectionButton.hovered
                    delay: 500
                    text: qsTr("Perspective Projection (Ctrl+2)")
                }
            }
            Rectangle {
                width: 18
                height: 36
                color: "transparent"
            }
            DefaultToolButton {
                id: frontButton
                text: "Front"
                icon.source: 'file:png/FrontSight.png'
                onClicked: {
                    var disfrontVector = camera.viewCenter.minus(camera.position)
                    var dis = disfrontVector.length()
                    camera.position = Qt.vector3d( camera.viewCenter.x, camera.viewCenter.y+dis, camera.viewCenter.z )
                    camera.upVector = Qt.vector3d( 0.0, 0.0, 1.0 )                              
                }
                Action {
                    id: frontAction
                    shortcut: "Ctrl+3"
                    onTriggered: {
                        frontButton.onClicked()
                    }
                }
                ToolTip {
                    visible: frontButton.hovered
                    delay: 500
                    text: qsTr("Front (Ctrl+3)")
                }
            }
            DefaultToolButton {
                id: backButton
                text: "Back"
                icon.source: 'file:png/BackSight.png'
                onClicked: {
                    var disfrontVector = camera.viewCenter.minus(camera.position)   
                    var dis = disfrontVector.length()
                    camera.position = Qt.vector3d( camera.viewCenter.x, camera.viewCenter.y-dis, camera.viewCenter.z )
                    camera.upVector = Qt.vector3d( 0.0, 0.0, 1.0 ) 
                }
                Action {
                    id: backAction
                    shortcut: "Ctrl+4"
                    onTriggered: {
                        backButton.onClicked()
                    }
                }
                ToolTip {
                    visible: backButton.hovered
                    delay: 500
                    text: qsTr("Back (Ctrl+4)")
                }
            }
            DefaultToolButton {
                id: rightButton
                text: "Right"
                icon.source: 'file:png/RightSight.png'
                onClicked: {
                    var disfrontVector = camera.viewCenter.minus(camera.position)
                    var dis = disfrontVector.length()
                    camera.position = Qt.vector3d( camera.viewCenter.x+dis, camera.viewCenter.y, camera.viewCenter.z )
                    camera.upVector = Qt.vector3d( 0.0, 0.0, 1.0 )
                }
                Action {
                    id: rightAction
                    shortcut: "Ctrl+5"
                    onTriggered: {
                        rightButton.onClicked()
                    }
                }
                ToolTip {
                    visible: rightButton.hovered
                    delay: 500
                    text: qsTr("Right (Ctrl+5)")
                }
            }
            DefaultToolButton {
                id: leftButton
                text: "Left"
                icon.source: 'file:png/LeftSight.png'
                onClicked: {
                    var disfrontVector = camera.viewCenter.minus(camera.position)
                    var dis = disfrontVector.length()
                    camera.position = Qt.vector3d( camera.viewCenter.x-dis, camera.viewCenter.y, camera.viewCenter.z )
                    camera.upVector = Qt.vector3d( 0.0, 0.0, 1.0 )                                
                }
                Action {
                    id: leftAction
                    shortcut: "Ctrl+6"
                    onTriggered: {
                        leftButton.onClicked()
                    }
                }
                ToolTip {
                    visible: leftButton.hovered
                    delay: 500
                    text: qsTr("Left (Ctrl+6)")
                }
            }
            DefaultToolButton {
                id: topButton
                text: "Top" 
                icon.source: 'file:png/TopSight.png'                       
                onClicked: {
                    var disfrontVector = camera.viewCenter.minus(camera.position)
                    var dis = disfrontVector.length()
                    camera.position = Qt.vector3d( camera.viewCenter.x, camera.viewCenter.y, camera.viewCenter.z +dis)
                    camera.upVector = Qt.vector3d( 0.0, -1.0, 0.0 )
                }
                Action {
                    id: topAction
                    shortcut: "Ctrl+7"
                    onTriggered: {
                        topButton.onClicked()
                    }
                }
                ToolTip {
                    visible: topButton.hovered
                    delay: 500
                    text: qsTr("Top (Ctrl+7)")
                }
            }
            DefaultToolButton {
                id: spinButton
                text: "Spin"
                icon.source: 'file:png/spin.png'
                highlighted: spinTimer.running
                onClicked: {
                    spinTimer.running = !spinTimer.running                               
                }
                Action {
                    id: spinAction
                    shortcut: "Ctrl+8"
                    onTriggered: {
                        spinButton.onClicked()
                    }
                }
                ToolTip {
                    visible: spinButton.hovered
                    delay: 500
                    text: qsTr("Spin (Ctrl+8)")
                }
            }
            Rectangle {
                width: 18
                height: 36
                color: "transparent"
            }
            DefaultToolButton {
                id: selectButton
                text:'Select'
                icon.source: 'file:png/Crop.png'
                highlighted: selectArea.selectEnabled
                onClicked: {
                    selectArea.selectEnabled = !selectArea.selectEnabled
                    selectArea.selectEnabledChanged(selectArea.selectEnabled)
                    if (selectArea.highlightItem != null) {
                        selectArea.highlightItem.destroy()
                    }
                }
                onDoubleClicked: clicked()
                Action {
                    id: selectPointAction
                    shortcut: "Ctrl+S"
                    onTriggered: {
                        selectButton.onClicked()
                    }
                }
                ToolTip {
                    visible: selectButton.hovered
                    delay: 500
                    text: qsTr("Select (Ctrl+S)")
                }
            }
            RowLayout {
                id: blueToolBar
            }
            Rectangle {
                implicitWidth: 18
                implicitHeight: 36
                color: "transparent"
            }
        
            RowLayout {
                id: aftercolorbar
            }
        }
    }

    Timer {
        id: highlightItemTimer
        interval: 10
        running: true
        repeat: true
        onTriggered: {
            if (selectArea.highlightItem != null) {
                selectArea.highlightItem.x = (selectArea.width / 2 + (selectArea.highlightItem.x - selectArea.lastWidth / 2) /(camera.right - camera.left) /  selectArea.lastWidth * selectArea.camerWidth * selectArea.width) 
                selectArea.highlightItem.width =  selectArea.highlightItem.width * selectArea.height / selectArea.lastHeight  
                selectArea.highlightItem.y = selectArea.highlightItem.y * selectArea.height / selectArea.lastHeight
                selectArea.highlightItem.height = selectArea.highlightItem.height * selectArea.height / selectArea.lastHeight
                selectArea.camerWidth = (camera.right - camera.left)
                selectArea.lastWidth = selectArea.width
                selectArea.lastHeight = selectArea.height
            }
            if(timeline.livingVisible){
                timeline.playTimeScale = 1
            }
            
        }
    }
}
