Attribute VB_Name = "Module1"
'#Uses "..\include\Global.inc"
'#Uses "..\include\Const.inc"
'#Uses "..\include\Format.inc"
'#Uses "..\include\Install.inc"
'#Uses "..\classes\ModuleClass.cls"
'#Uses "..\classes\InterruptClass.cls"
'#Uses "..\classes\PortPin.cls"
'#Uses "..\classes\LinFrame.cls"
'#Uses "..\classes\LinSignal.cls"
'#Uses "..\classes\ManualLinkClass.cls"
Option Explicit
'*****************************************************************************
' Module:
'        START
'-----------------------------------------------------------------------------
' Description:
'        This file contains functions which are create controls for the
'        module 'START'.
'        Furthermore it contains functions for the event handling of
'        these controls.
'
'-----------------------------------------------------------------------------
' History:
'
'        Rev. Author         Date        Description
'        ---------------------------------------------------------------------
'        2.0   ahe         23.06.00     final version for C167CS
'
'        ---------------------------------------------------------------------
'        2.1   ahe         28.07.00    final version for C161PI
'                                      - added 'ObjectCollection.Add ps, "SETTINGS"
'                                        and 'ObjectCollection.Add gc, "GRAPH"
'              ahe         03.08.00    - changes s to p be [Version] ...
'
'        ---------------------------------------------------------------------
'        4.0   ahe         17.12.01    final version for Pegasus
'
'*****************************************************************************


'*****************************************************************************
'Description:
'-----------------------------------------------------------------------------
'Parameters:
'        m               reference to the main MDI window
'-----------------------------------------------------------------------------
'Returns:
'        True            on successfull operation
'        False           else
'*****************************************************************************
Function OnProjectNew(m As MainMDI) As Boolean
    On Error GoTo OnProjectNewError

    Dim ps          As Peripherals
    Dim d           As DAvECollection
    Dim sc          As Script
    Dim sMainDialog As String

    OnProjectNew = False
    '------------------------------------------------------
    ' create project specific collections, display the graphics window
    '------------------------------------------------------
    If (Not InstallProject(m)) Then Exit Function

    '------------------------------------------------------
    ' initialize the project variables and registers
    ' by calling the "Initialize" function of the main module
    ' (the first module in the collection)
    '------------------------------------------------------
    Set d = ObjectCollection("MODULENAMES")
    sMainDialog = DefGetPath("Scripts") & d(1).ModuleDirectory & "\Dialog.dave"

    Set sc = New Script
    sc.Load (sMainDialog)
    If (Not sc.Functions.Initialize(m.ProjectData, d(1).ParameterValue)) Then Exit Function

    '------------------------------------------------------
    ' show project settings
    '------------------------------------------------------
    Set ps = New Peripherals
    Set ps.ProjectData = m.ProjectData
    ps.Caption = "Project Settings"
    ps.Scriptfile = sMainDialog
    ps.Show
                ' only for the test scripts
    On Error Resume Next
                'ObjectCollection.Add ps, "SETTINGS"
    On Error GoTo OnProjectNewError

    OnProjectNew = True
    Exit Function

OnProjectNewError:
    errorbox "Can not create a new project", Err.Description
    Exit Function
End Function


'*****************************************************************************
'Description:
'-----------------------------------------------------------------------------
'Parameters:
'        m               reference to the main MDI window
'-----------------------------------------------------------------------------
'Returns:
'        True            on successfull operation
'        False           else
'*****************************************************************************
Function OnProjectOpen(m As MainMDI) As Boolean
    On Error GoTo OnProjectOpenError
    OnProjectOpen = False
    
    Dim f As Variant
    Dim r  As ProjectData
    Dim uFrame As New LinFrame
    Dim cFrame As New DAvECollection
    Dim uSignal As New LinSignal
    Dim cSignal As New DAvECollection
    
    Dim sName As String
    Dim ID    As Integer
    Dim Size  As Integer
    
    Set r = m.ProjectData
    Set cFrame = New DAvECollection
    '------------------------------------------------------
    ' create project specific collections, display the graphics window
    '------------------------------------------------------
    If (Not InstallProject(m)) Then Exit Function
'''
'    f = FreeFile
'    Open CStr(StripFilenameAndExtension(r.LoadedFile)) & "\LIN_Frame.lin" For Input As f
'    Do While Not EOF(f)
'        Input #f, sName, ID, Size
'        Set uFrame = New LinFrame
'        uFrame.Name = sName
'        uFrame.ID = ID
'        uFrame.Size = Size
'        cFrame.Add uFrame
''        MsgBox (uFrame.Name)
'    Loop
'    Close f
'
'    f = FreeFile
'    Open CStr(StripFilenameAndExtension(r.LoadedFile)) & "\LIN_Signal.lin" For Input As f
'    Do While Not EOF(f)
'        Input #f, sName, ID, Size
'        Set uSignal = New LinSignal
'        uSignal.Name = sName
'        uSignal.InitVal = ID
'        uSignal.Size = Size
'        cSignal.Add uSignal
'
'    Loop
'    Close f
'
'    ObjectCollection.Add cFrame, "LinFrames"
'    ObjectCollection.Add cSignal, "LinSignals"
    OnProjectOpen = True
    Exit Function

OnProjectOpenError:
    errorbox "Can not open the project", Err.Description
    Exit Function
End Function


'*****************************************************************************
'Description:
'-----------------------------------------------------------------------------
'Parameters:
'        m               reference to the main MDI window
'-----------------------------------------------------------------------------
'Returns:
'        True            on successfull operation
'        False           else
'*****************************************************************************
Function OnProjectClose(m As MainMDI) As Boolean
    On Error GoTo OnProjectCloseError

    OnProjectClose = False
    
    Dim f As Variant
    Dim r  As ProjectData
    Dim uFrame As New LinFrame
    Dim cFrame As New DAvECollection
    Dim uSignal As New LinSignal
    Dim cSignal As New DAvECollection
    
    '------------------------------------------------------
    ' disable menus
    '------------------------------------------------------
    Call EnableMenu(m, False)

    '------------------------------------------------------
    ' save project
    '------------------------------------------------------
    If (m.ProjectData.Changed) Then
        If (Ask(MSG_CLOSE_APPLICATION)) Then
            m.ProjectData.Save
'            If (r.v("LIN_EXIST") = 1) Then
'
'                f = FreeFile
'                Open CStr(StripFilenameAndExtension(r.LoadedFile)) & "\LIN_Frame.lin" For Output As f
'                For Each uFrame In cFrame
'                    Write #f, uFrame.Name, uFrame.ID, uFrame.Length
'                Next uFrame
'                Close f
'
'                f = FreeFile
'                Open CStr(StripFilenameAndExtension(r.LoadedFile)) & "\LIN_Signal.lin" For Output As f
'                For Each uSignal In cSignal
'                    Write #f, uSignal.Name, uSignal.InitVal, uSignal.Size
'                Next uSignal
'                Close f
'
'
'            End If
        End If
    End If
    
    OnProjectClose = True
    Exit Function

OnProjectCloseError:
    Exit Function
End Function


'*****************************************************************************
'Description:
'-----------------------------------------------------------------------------
'Parameters:
'        m               reference to the main MDI window
'-----------------------------------------------------------------------------
'*****************************************************************************
Function OnProjectSave(m As MainMDI)
    On Error GoTo OnProjectSaveError
    
    Dim f As Variant
    Dim r  As ProjectData
    Dim uFrame As New LinFrame
    Dim cFrame As New DAvECollection
    Dim uSignal As New LinSignal
    Dim cSignal As New DAvECollection
        
    Set r = m.ProjectData
    '------------------------------------------------------
    ' save project
    '------------------------------------------------------
    OnProjectSave = m.ProjectData.Save
    
'    If (r.v("LIN_EXIST") = 1) Then
    
'        Set cFrame = ObjectCollection("LinFrames")
'        f = FreeFile
'        Open CStr(StripFilenameAndExtension(r.LoadedFile)) & "\LIN_Frame.lin" For Output As f
'        For Each uFrame In cFrame
'            Write #f, uFrame.Name, uFrame.ID, uFrame.Length
'        Next uFrame
'        Close f
'
'        Set cSignal = ObjectCollection("LinSignal")
'        f = FreeFile
'        Open CStr(StripFilenameAndExtension(r.LoadedFile)) & "\LIN_Signal.lin" For Output As f
'        For Each uSignal In cSignal
'            Write #f, uSignal.Name, uSignal.InitVal, uSignal.Size
'        Next uSignal
'        Close f
        
'    End If
    
    Exit Function
 
OnProjectSaveError:
    Exit Function
End Function


'*****************************************************************************
'Description:
'-----------------------------------------------------------------------------
'Parameters:
'        m               reference to the main MDI window
'        Toolname
'        ToolId
'        Tooltext
'-----------------------------------------------------------------------------
'Returns:
'        True            on successfull operation
'        False           else
'*****************************************************************************
Function OnMenuClick(m As MainMDI, Toolname As String, ToolId As Long, Tooltext As String) As Boolean
  On Error GoTo OnMenuClickError


  Dim r As ProjectData
  Dim sc As Script
  Dim p As Parameters
  Dim ps As Peripherals
  Dim cp As DAvECollection
  Dim mo As ModuleClass

  OnMenuClick = False

  Set cp = ObjectCollection("MODULENAMES")
  Set r = m.ProjectData


  Select Case Toolname
      Case "Settings"
          If (Ask(MSG_CALL_PROJECTSETTINGS)) Then
            Set ps = New Peripherals
            Set ps.ProjectData = m.ProjectData
            ps.Caption = "Project Settings "
            ps.Scriptfile = DefGetPath("Scripts") & "Main\Dialog.DAVE"
            ps.Show
          End If

      Case "Generate"
        'If (Ask(MSG_CALL_CODEGENERATOR)) Then
          If (m.ProjectSave) Then
                                        StartClip
              If (Not r.ResetFiles()) Then Exit Function
                For Each mo In cp
                If (mo.ModuleWithCG) Then
                  If (mo.ModuleName <> "MAIN") Then
                    If (r.v(mo.ModuleName & "_Use_Init") = 1) Then
                      Set sc = New Script
                      sc.Load (DefGetPath("Scripts") & mo.ModuleDirectory & "\Codegenerator.dave")
                      If (Not sc.Functions.StartGenerateCode(r, mo.ParameterValue)) Then Exit Function
                    End If
                  Else
                    Set sc = New Script
                    sc.Load (DefGetPath("Scripts") & mo.ModuleDirectory & "\Codegenerator.dave")
                    If (Not sc.Functions.StartGenerateCode(r, mo.ParameterValue)) Then Exit Function
                  End If
                End If
              Next mo
              If (Not GenerateAssemblerFile(r, StripExtension(r.LoadedFile) & ".asm")) Then Exit Function
              If (Not r.AddFile(StripPath(StripExtension(r.LoadedFile)) & ".asm", "ASM")) Then Exit Function
                     
                      
              If (Not Rtf.GenerateRTFFile(r, StripExtension(r.LoadedFile) & ".rtf", r.s("MAIN_CPU_TYPE"), (r.s("MAIN_COMPILER")), r.s("MAIN_MEMORY"))) Then Exit Function
              If (Not r.AddFile(StripPath(StripExtension(r.LoadedFile) & ".rtf"))) Then Exit Function
              
              If (Not GenerateProjectFile(r, StripExtension(r.LoadedFile) & ".dpt")) Then Exit Function
              If (Not r.AddFile(StripPath(StripExtension(r.LoadedFile)) & ".dpt")) Then Exit Function
               
                                        StopClip
                                        If (GetShowCodegenerationProtocol()) Then
                                                m.ShowFileView (StripExtension(m.ProjectData.LoadedFile) & ".rtf")
                                        Else
                                                m.RefreshFileView()
                                        End If
          End If
        'End If 'end if ask

      Case "Info"
          UserMessage FormatMessageBoxText(MSG_DOCU_BUTTON)
      Case "Help"
          HelpContext 1008
      Case "Doc"
          ShowDocument(Tooltext, "Main")
      Case "WWW"
          StartDoc (Tooltext)
      Case Else
  End Select

  OnMenuClick = True
  Exit Function

OnMenuClickError:
         StopClip
  Call errorbox("Code generation failed", Error$)
  Exit Function
End Function

'-----------------------------------------------------------------------------
' local functions
'-----------------------------------------------------------------------------

'*****************************************************************************
'Description:
'-----------------------------------------------------------------------------
'Parameters:
'        m               reference to the main MDI window
'        b               requested state of the menu
'                        True=Enabled, False=Disabled
'*****************************************************************************
Private Sub EnableMenu(m As MainMDI, b As Boolean)
    On Error Resume Next
    
    Dim ts As Tool
    Dim bs As Band
    Dim pic As Object
    
    
    m.Menu.Bands("File").Tools("Generate").Enabled = b
    m.Menu.Bands("Main").Tools("Generate").Enabled = b
    m.Menu.Bands("File").Tools("Settings").Enabled = b
    m.Menu.Bands("Main").Tools("Info").Enabled = b
    m.Menu.Bands("View").Tools("Files").Enabled = b
    m.Menu.Bands("Main").Tools("Files").Enabled = b
    m.Menu.Bands("View").Tools("Registers").Enabled = b
    m.Menu.Bands("Main").Tools("Registers").Enabled = b
    
    Set bs = m.Menu.Bands("Info")
    
    If (b) Then
        Set pic = LoadBitmap(DefGetPath("Icons") & "DOC.BMP")
        If (IsNull(pic)) Then Exit Sub

'        Set ts = bs.Tools.Add(1000, "Doc")
'        ts.Caption = "Product Info"
'        ts.Text = "ProductInfo"
'        ts.SetPicture Index:=0, Picture:=pic, Color:=QBColor(5)

        Set ts = bs.Tools.Add(1001, "Doc")
        ts.Caption = "User's Manual (Peripheral Units)"
        ts.Text = "UsersManualPU"
        ts.SetPicture Index:=0, Picture:=pic, Color:=QBColor(5)
                ts.BeginGroup = True

        Set ts = bs.Tools.Add(1002, "Doc")
        ts.Caption = "User's Manual (System Units)"
        ts.Text = "UsersManualSU"
        ts.SetPicture Index:=0, Picture:=pic, Color:=QBColor(5)

'        Set ts = bs.Tools.Add(1002, "Doc")
'        ts.Caption = "Data Sheet"
'        ts.Text = "DataSheet"
'        ts.SetPicture Index:=0, Picture:=pic, Color:=QBColor(5)

        Set ts = bs.Tools.Add(1003, "Doc")
        ts.Caption = "Instruction Set Manual"
        ts.Text = "InstructionSetManual"
        ts.SetPicture Index:=0, Picture:=pic, Color:=QBColor(5)
                ts.BeginGroup = True

        Set pic = LoadBitmap(DefGetPath("Icons") & "IE.BMP") '*** NEU ***
        If (IsNull(pic)) Then Exit Sub '*** NEU ***
        Set ts = bs.Tools.Add(1005, "WWW") '*** NEU ***
        ts.Caption = "Additional Information" '*** NEU ***
        ts.Text = "http://www.infineon.com/products/micro/micro.htm" '*** NEU ***
        ts.SetPicture Index:=0, Picture:=pic, Color:=QBColor(5) '*** NEU ***
        ts.BeginGroup = True ' hier wird ein Trenner erzeugt '*** NEU ***
    Else
        bs.Tools.RemoveAll
    End If
    
End Sub

'*****************************************************************************
'Description:
'        This functions creates project specific collections
'        (modules, interrupts, ports and portpins),
'        then creates and displays the window that contains the controller
'        controller graphics, and enables the menu of the main MDI window.
'-----------------------------------------------------------------------------
'Parameters:
'        m               reference to the main MDI window
'-----------------------------------------------------------------------------
'Returns:
'        True            on successfull operation
'        False           else
'*****************************************************************************
Private Function InstallProject(m As MainMDI) As Boolean
    On Error GoTo InstallProjectError

    Dim gc          As New GraphicConfigure
    Dim d           As DAvECollection
    Dim c           As DAvECollection
    Dim cPorts      As DAvECollection
    Dim cPortPins   As PortPin
    Dim cLinks      As ManualLinkClass

    InstallProject = False
    Set d = New DAvECollection
    Set c = New DAvECollection
    Set cPorts = New DAvECollection
    Set cPortPins = New PortPin
    Set cLinks = New ManualLinkClass

    '------------------------------------------------------
    ' create a collection of the modules
    '------------------------------------------------------
    If (Not InstallModule(d)) Then Exit Function
    ObjectCollection.Add d, "MODULENAMES"

    '------------------------------------------------------
    ' create a collection of the interrupts
    '------------------------------------------------------
    If (Not InstallInterrupts(c)) Then Exit Function
    ObjectCollection.Add c, "IRSOURCES"

    '------------------------------------------------------
    ' create a collection of the port pins
    '------------------------------------------------------
    If (Not InstallPorts(cPorts)) Then Exit Function
    ObjectCollection.Add cPorts, "PORTS"

    If (Not InstallPortPins(cPortPins)) Then Exit Function
    ObjectCollection.Add cPortPins, "PORTPINS"

    '------------------------------------------------------
    ' create a collection of the manual links
    '------------------------------------------------------
    If (Not InstallManualLinks(cLinks)) Then Exit Function
    ObjectCollection.Add cLinks, "MANUALLINKS"

    '------------------------------------------------------
    ' create a graphics configure window
    '------------------------------------------------------
    Set gc.ProjectData = m.ProjectData
    gc.Caption = "DAvE " & DefGetValue("Name") & " ( Release v" & DefGetValue("ProductVersion") & " )"
    gc.Scriptfile = DefGetPath("Startup") & "GRAPH.DAVE"
    If (Not gc.Show()) Then Exit Function

    ' only for the test scripts
    On Error Resume Next
    'ObjectCollection.Add gc, "GRAPH"
    On Error GoTo InstallProjectError

    '------------------------------------------------------
    ' enable menus
    '------------------------------------------------------
    Call EnableMenu(m, True)

    InstallProject = True
    Exit Function

InstallProjectError:
    Exit Function
End Function

'*****************************************************************************
'Description:
'        Generates the project file.
'-----------------------------------------------------------------------------
'Parameters:
'        r               reference to the ProjectData object
'        szFile
'-----------------------------------------------------------------------------
'Returns:
'        True            on successfull operation
'        False           else
'*****************************************************************************
Function GenerateProjectFile(r As ProjectData, szFile As String) As Boolean
  On Error GoTo GenerateProjectFileError

        Dim l As Long
         Dim s As String
         Dim p As String

  GenerateProjectFile = False
    
        s = ""
        p = ""

        ' create version section
        p = p & "[Version]" & vbCrLf
        p = p & "Format=1" & vbCrLf
        p = p & "Product=" & DefGetValue("ProductVersion") & vbCrLf
        p = p & "Register=" & r.Regs.Revision & vbCrLf
        p = p & vbCrLf

        ' create general section
        s = s & "[General]" & vbCrLf
        s = s & "Device=""" & DefGetValue("Name") & """" & vbCrLf
        s = s & "DeviceType=""" & r.s("MAIN_CPU_TYPE") & """" & vbCrLf
        s = s & vbCrLf

        ' create interface section
        s = s & "[Interface]" & vbCrLf
        s = s & "Compiler=""" & r.s("MAIN_COMPILER") & """" & vbCrLf
        s = s & "MemoryModel=""" & StrConv(r.s("MAIN_MEMORY"), vbUpperCase) & """" & vbCrLf
        s = s & vbCrLf

        ' create environment section
        s = s & "[Environment]" & vbCrLf
        s = s & "OscillatorFrequency=" & r.d("MAIN_OSC") & vbCrLf
        s = s & "DeviceFrequency=" & GetSystemClock(r) & vbCrLf
        s = s & vbCrLf

        ' create files section
        s = s & "[Files]" & vbCrLf
        For l = 1 To r.CountFiles
                s = s & "File" & Format$(l) & "=""" & r.File(l) & """" & vbCrLf
                s = s & "Type" & Format$(l) & "=""" & r.FileType(l) & """" & vbCrLf
        Next l
        s = s & vbCrLf


        If (Not GenerateDescriptionFile(r, szFile, s, p)) Then Exit Function

  GenerateProjectFile = True
  Exit Function
    
GenerateProjectFileError:
  Call errorbox("Can not generate the project file", Error$)
  Exit Function
End Function

