'#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\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

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

    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

    '------------------------------------------------------
    ' disable menus
    '------------------------------------------------------
    Call EnableMenu(m, False)

    '------------------------------------------------------
    ' save project
    '------------------------------------------------------
    If (m.ProjectData.Changed) Then
        If (Ask(MSG_CLOSE_APPLICATION)) Then
            m.ProjectData.Save
        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
 
    '------------------------------------------------------
    ' save project
    '------------------------------------------------------
    OnProjectSave = m.ProjectData.Save
 
    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(1003, "Doc")
        ts.Caption = "Data Sheet"
        ts.Text = "DataSheet"
        ts.SetPicture Index:=0, Picture:=pic, Color:=QBColor(5)

        Set ts = bs.Tools.Add(1004, "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/microcontrollers" '*** 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
    
	'msgbox "rag: end enablemenu"
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 = DefGetValue("Name")
    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

