'#Reference {A3B5C45B-F842-44fc-A5E5-50CED69BA86E}#2.0#0#C:\Program Files\Mindjet\MindManager 6\Mm5WebExport.dll#Mm5webexport 2.0 Type Library
' Web Presentation Layout
' Page generation

'#Uses "ParameterNames.mmbas"
'#Uses "GlobalParameterNames.mmbas"
'#Uses "GlobalUtilities.mmbas"

' Global data
Dim m_Addin As Mm5WebExportAddIn
Dim m_Webex As WebExport
Dim m_Topic As Topic
Dim m_Page As Page
Dim m_GraphicExport As GraphicExport
Dim m_FillColor As Color ' Selection frame fill colour
Dim m_LineColor As Color ' Selection frame line colour
Dim b_FocusFrame As Boolean ' display frame around current topic
Dim b_FloatingTopics As Boolean ' always include Floating Topics in the image

Option Explicit

Sub Main

    ' Local data
    Dim s_Template As String ' template file
    Dim s_HeaderFile As String ' filename of header file for this topic
    Dim s_MapFile As String ' filename of map file for this topic
    Dim s_ImageFile As String ' filename of image file for this topic
    Dim s_FullImageFile As String ' full path of image file
    Dim s_CSIMname As String ' Client Side Imagemap name
    Dim s_CSIMblock As String ' Client Side Imagemap for this topic
    Dim s_RelativeMapMarkerPath As String
    Dim i_NavDepth As Integer ' maximum navigation depth
    Dim i_ZoomFactor As Double ' display zoom factor
    Dim m_OneIconCollection As Icons
    Dim m_OneIcon As Icon


    Dim s_1 As String

    On Error GoTo ReportError

    Set m_Addin = WebExportHelper.WebExportAddIn
    Set m_Webex = m_Addin.ActiveWebExport
    i_NavDepth = m_Webex.GetParameter(TdNavigationDepth)

    ' Pernanent inclusion of Floating Topics is controlled by a hidden parameter
    ' Currently the GraphicExport object gives an error if a Floating Topic is added to the map when
    ' the Central Topic is also added; the CentralTopic must be referenced directly to add a frame around it
    ' Floating topics get added when the central topic is added to the GraphicExport, so only appear
    ' on the start page, which is not bad
    b_FloatingTopics = m_Webex.GetParameter("Strings.Show.FloatingTopics")

    m_Webex.Trace("Entering GeneratePage, navigation depth=" & CStr(i_NavDepth), 2)

    Set m_Page = m_Webex.ActivePage

    If m_Page.TopicCount > 0 Then ' there are topics on this page

        Set m_Topic = m_Page.GetTopic(1) ' primary topic for this page

        If f_ValidateTopic(m_Topic) Then ' generate a page for this topic

            ' check whether we are displaying a frame around the focused topic
            b_FocusFrame = m_Webex.GetParameter("Strings.Show.FocusFrame")
            If b_FocusFrame Then ' set up frame colours
                Set m_FillColor = New Color
                Set m_LineColor = New Color
                m_FillColor.SetARGB(0, 255, 255, 255) ' Fully transparent
                ' Convert RGB character from parameters to ARB value for the Color object
                s_1 = Hex(m_Webex.GetParameter("Strings.Show.FocusFrameColor")) ' read RGB value from parameters
                s_1 = Right("000000" & s_1, 6) ' pad out to 6 chars
                m_LineColor.SetARGB(255, f_UnHexByte(Left(s_1, 2)), f_UnHexByte(Mid(s_1, 3, 2)), _
                    f_UnHexByte(Right(s_1, 2)))
            End If

            m_Webex.SetParameter("CustomParameter.PageTitle", VerifyTopicText(m_Webex, m_Topic)) ' set up page title
            m_Webex.SetParameter("CustomParameter.MapName", VerifyTopicText(m_Webex, m_Topic)) ' use same for map name

            ' Store icons used in a variant list (to determine what items to include in the icon legend)
            Set m_OneIconCollection = m_Topic.Icons(True)
            If m_OneIconCollection.Count > 0 Then
                For Each m_OneIcon In m_OneIconCollection
                    If Not m_Webex.IsSuccessful Then
                        Exit For
                    End If

            		' don't export the controlstrip icons
            		Select Case m_OneIcon.Type
                	Case mmIconTypeAutomaticHyperlink, mmIconTypeAutomaticNotes
                    	' do nothing
                	Case Else
                    	m_Webex.VariantSets(weVariantSetIcons).Add(m_OneIcon.Name)

                    	' Save the graphic to the export directory
                    	s_RelativeMapMarkerPath = RelativeMapMarkerPath(m_Webex, m_OneIcon.Name)
                    	m_OneIcon.Save(m_Webex.FullExportFilename(s_RelativeMapMarkerPath), mmGraphicTypeGif)
            		End Select
                Next
            End If

            ' Generate custom header page
            s_HeaderFile = f_AdaptFileName(m_Webex.ActivePage.Filename, "-hdr", True) ' insert "-hdr" into basic page name
            m_Webex.SetParameter("CustomParameter.HeaderFile", s_HeaderFile)
            s_Template = m_Webex.ReadFile("PreHd.htm")
            ProcessString m_Webex, s_Template
            m_Webex.WriteFile(s_HeaderFile, s_Template) ' write page back to the header file for this topic

            ' Generate custom image file
            s_ImageFile = f_AdaptFileName(m_Webex.ActivePage.Filename, "-img", False) & ".jpg" ' append "-img" to basic page name
            s_FullImageFile = m_Webex.FullExportFilename(s_ImageFile) ' generate full path version for writing out
            m_Webex.SetParameter("CustomParameter.ImageFile", s_ImageFile)

            Set m_GraphicExport = m_Topic.Document.GraphicExport ' get graphic export object
            ' Include Central Topic if required, add topics and hyperlinks down to maximum navigation depth
            Call p_PrepareImage(m_Webex.GetParameter("Strings.Show.CentralTopic"), i_NavDepth)
            ' Write out the imagemap graphic, export with 100% zoom
            i_ZoomFactor = m_Webex.GetParameter("Strings.Show.ZoomFactor") / 100 ' read zoom factor, convert from %
            m_GraphicExport.ExportZoomed(s_FullImageFile, mmGraphicTypeJpeg, i_ZoomFactor, True, 0, 0)

            ' Now create Client Side Imagemap
            s_CSIMname = "Topic_CSIM"
            s_CSIMblock = m_GraphicExport.GetImageMap(s_CSIMname)
            s_CSIMblock = Replace(s_CSIMblock, "alt=", "target='_parent' alt=" ) ' hack the targets in the CSIM

            ' Set up placeholders
            m_Webex.SetParameter("CustomParameter.ImageFile", s_ImageFile)
            m_Webex.SetParameter("CustomParameter.CSIMname", s_CSIMname)
            m_Webex.SetParameter("CustomParameter.CSIMblock", s_CSIMblock)
            Set m_GraphicExport = Nothing ' Release object

            ' Generate custom body page - the map image
            s_MapFile = f_AdaptFileName(m_Webex.ActivePage.Filename, "-map", True) ' insert "-map" into basic page name
            m_Webex.SetParameter("CustomParameter.MapFile", s_MapFile)
            s_Template = m_Webex.ReadFile("PreMap.htm")
            ProcessString m_Webex, s_Template
            m_Webex.WriteFile(s_MapFile, s_Template) ' write page back to the map file for this topic

            ' Generate main page for topic: this contains a frameset for this topic's specific pages
            s_Template = m_Webex.ReadFile("PrePage.htm")
            ProcessString m_Webex, s_Template
            m_Webex.WriteFile(m_Webex.ActivePage.Filename, s_Template) ' write page back to the filename for this topic

        End If

    End If

    m_Webex.Trace("Exiting GeneratePage", 2)
    Exit Sub
   
ReportError:
    ProcessError(m_Webex)

End Sub

Function f_ValidateTopic(ByVal m_b1 As Topic) As Boolean
' check that this topic is exportable, i.e. is a topic connected to the map title and not anywhere else

    f_ValidateTopic = False ' assume not valid
    While True
        If m_b1.IsCalloutTopic Then
            Exit While ' callout topics not supported
        ElseIf m_b1.IsSummaryTopic Then
            Exit While ' summary topics not allowed
        ElseIf m_b1.IsFloatingTopic Then
            Exit While ' floating topics not allowed
        ElseIf m_b1.IsCentralTopic Then
            f_ValidateTopic = True ' this is a valid topic
            Exit While
        Else
            Set m_b1 = m_b1.ParentTopic ' go up to parent
        End If
    Wend

End Function

Function f_AdaptFileName(ByVal s_Filename As String, ByVal s_Insert As String, ByVal b_KeepExt As Boolean) As String
' Adapt a file name by inserting a string before the last "."
' If b_KeepExt is set then the extension is preserved, otherwise it is discarded
Dim i_1 As Long
Dim s_1 As String

    i_1 = InStrRev(s_Filename, ".") ' find last . character in filename
    If i_1 > 1 Then ' found OK
        s_1 = Left(s_Filename, (i_1 - 1)) & s_Insert
        If b_KeepExt Then s_1 = s_1 & Right(s_Filename, (Len(s_Filename) - i_1) + 1) ' add the original extension
    Else
        Err.Raise(1000,,"Failed to adapt filename",,) ' unrecoverable: cannot adapt
    End If
    f_AdaptFileName = s_1 ' return filename

End Function

Sub p_PrepareImage(ByVal b_ShowCentralTopic As Boolean, ByVal i_NavDepth As Integer)

    ' Prepare the graphic export object for the current Topic
    ' It is not allowed to add a topic to the graphics export object that is the ancestor of one already added
    ' For topics that are at the maximum depth, all their children are displayed on a final image
    ' If b_IncludeCentral is set then the Central Topic is always included, otherwise topics up to the current
    ' topic's parent are included
    ' If b_Frame is set then include a frame around current topic, requires different algorithm to avoid repeating
    ' same topic
    
    Dim m_b1 As Topic
    Dim m_b2 As Topic
    Dim m_prev As Topic ' remember previous topic while traversing up
    Dim i_1 As Integer
    Dim m_Top As Topic ' topic at top level of displayed tree
    Dim theLevelOfDetail As Long

    m_GraphicExport.Reset

    ' Call the Floating Topics into view
    If b_FloatingTopics Then
        For i_1 = 1 To m_Topic.Document.Range(mmRangeAllTopics).Count
            Set m_b1 = m_Topic.Document.Range(mmRangeAllTopics).Item(i_1)
            If m_b1.IsFloatingTopic Then
                If m_b1.IsVisible Then ' only show if in view
                    m_GraphicExport.AddTopic(m_b1) ' display it as currently shown in map
                End If
            End If
        Next i_1
    End If

    ' Check if this is the top level
    If b_ShowCentralTopic Or m_Topic.IsCentralTopic Then ' we are either including central topic or already there
        Set m_Top = m_Topic.Document.CentralTopic ' top level is the central topic
    Else ' not at map title, so top level is this topic's grandparent, if available
        Set m_Top = m_Topic.ParentTopic ' default to parent
        If Not m_Top.IsCentralTopic Then Set m_Top = m_Top.ParentTopic ' go up again
    End If

    Set m_b1 = m_Topic
    Set m_prev = Nothing
    While True
        If m_b1.SubTopics(False).Count > 0 Then ' we have children so display them
            If Not (m_b1 Is m_Topic) Then ' not the current topic, so never framed
                For Each m_b2 In m_b1.SubTopics(False)
                    ' don't re-add a previously added topic, breaks image rules
                    If Not (m_b2 Is m_prev) Then ' just display at level 0
                        m_GraphicExport.AddCustomizedTopic(m_b2, 0)
                    End If
                    ' Add a link to subtopic, unless it is us
                    If Not (m_b2 Is m_Topic) Then
                        m_GraphicExport.AddLink(m_b2, mmLinkTypeTopic, _
                                TopicPageUrl(m_Webex, m_b2), VerifyTopicText(m_Webex, m_b2))
                    End If
                Next ' m_b2
            Else ' is the current topic so is eligible for framing
                If m_b1.Level >= i_NavDepth Then ' at maximum depth
                    If b_FocusFrame Then
                        ' To get the frame on the current topic we assume no more than 10 sublevels under here
                        m_GraphicExport.AddTopicWithFrame(m_b1, 10, m_FillColor, m_LineColor, 2, mmLineDashStyleSolid)
                    Else
                        m_GraphicExport.AddTopic(m_b1) ' export it as viewed in UI
                    End If
                Else
                    If b_FocusFrame Then ' not at final depth, display subtopics
                        m_GraphicExport.AddCustomizedTopicWithFrame(m_b1, 1, 0, m_FillColor, m_LineColor, 2, mmLineDashStyleSolid)
                    Else
                        m_GraphicExport.AddCustomizedTopic(m_b1, 1) ' export topic at LoD 1
                    End If
                    For Each m_b2 In m_b1.SubTopics(False) ' add links to subtopics
                        m_GraphicExport.AddLink(m_b2, mmLinkTypeTopic, _
                                TopicPageUrl(m_Webex, m_b2), VerifyTopicText(m_Webex, m_b2))
                    Next
                End If
            End If
        Else ' no children, just add self
        
            ' central topic can't have level of detail 0
            If m_b1.IsCentralTopic Then
                theLevelOfDetail = 1
            Else
                theLevelOfDetail = 0
            End If

            If b_FocusFrame Then
                m_GraphicExport.AddCustomizedTopicWithFrame(m_b1, theLevelOfDetail, 0, m_FillColor, m_LineColor, 2, mmLineDashStyleSolid)
            Else ' no frame
                m_GraphicExport.AddCustomizedTopic(m_b1, theLevelOfDetail) ' has no children anyway, no link added
            End If
        End If
        ' Display our siblings at level of detail zero
        If Not (m_b1 Is m_Top) Then ' not at the top level yet
            For i_1 = 1 To m_b1.ParentTopic.SubTopics(False).Count
                Set m_b2 = m_b1.ParentTopic.SubTopics(False).Item(i_1)
                If Not m_b1 Is m_b2 Then ' not us
                    m_GraphicExport.AddCustomizedTopic(m_b2, 0)
                    ' If a sibling has children of its own, add a link to it
                    If m_b2.SubTopics(False).Count > 0 Then
                        m_GraphicExport.AddLink(m_b2, mmLinkTypeTopic, _
                                TopicPageUrl(m_Webex, m_b2), VerifyTopicText(m_Webex, m_b2))
                    End If
                End If
            Next i_1
            ' Now go up to parent
            Set m_prev = m_b1
            Set m_b1 = m_b1.ParentTopic
        Else ' we are at the top level now, add final link here
            If Not (m_b1 Is m_Topic) Then
                m_GraphicExport.AddLink(m_b1, mmLinkTypeTopic, _
                        TopicPageUrl(m_Webex, m_b1), VerifyTopicText(m_Webex, m_b1))
            End If
            Exit While
        End If
    Wend

    ' Tidy up
    Set m_b1 = Nothing
    Set m_b2 = Nothing
    Set m_prev = Nothing

End Sub

Function f_UnHexByte(ByVal s_Byte As String) As Integer

    ' convert 2-character Hex byte to integer

    f_UnHexByte = (16 * f_UnHexChar(Asc(UCase(Left(s_Byte, 1))))) + f_UnHexChar(Asc(UCase(Right(s_Byte, 1))))

End Function

Function f_UnHexChar(ByVal i_chr As Integer) As Integer

    ' Convert hex ASCII character to decimal: intolerant of imperfect hex
    Dim i_1 As Integer

    If i_chr >= 65 Then i_chr = i_chr - 7
    f_UnHexChar = i_chr - 48

End Function
