Imports System.ComponentModel
Imports System.Globalization
Imports System.Text.RegularExpressions
Imports DigitalData.Modules.Logging
Imports Independentsoft.Msg
Imports DevExpress.Spreadsheet
Imports GdPicture14
Imports DevExpress
Imports DevExpress.Office.Utils
Imports System.IO

Public Class DocumentViewer
    Private Enum ZoomMode
        Zoom50
        Zoom100
        Zoom150
        Zoom200
        ZoomSelectedArea
        ZoomFitToViewer
        ZoomFitWidth
        ZoomFitHeight
    End Enum

    Private _currentSearchOccurence As Integer = 0
    Private _toggleGamma As Boolean = True
    Private _licenseKey As String = String.Empty
    Private _licenseManager As New GdPicture14.LicenseManager()
    Private _logConfig As LogConfig
    Private _logger As Logger

    Private _hide_file_info_from_user As Boolean = False

    ' List of all created temp files when converting msg files
    Private _TempFiles As New List(Of String)

    Private Sub DocumentViewer_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim zoomModes As New Dictionary(Of ZoomMode, String) From {
            {ZoomMode.Zoom50, "50%"},
            {ZoomMode.Zoom100, "100%"},
            {ZoomMode.Zoom150, "150%"},
            {ZoomMode.Zoom200, "200%"},
            {ZoomMode.ZoomSelectedArea, "Zoom to selected area"},
            {ZoomMode.ZoomFitToViewer, "Fit to viewer"},
            {ZoomMode.ZoomFitWidth, "Fit to viewer width"},
            {ZoomMode.ZoomFitHeight, "Fit to viewer height"}
        }

        For Each item In zoomModes
            cbZoom.Items.Add(item.Value)
        Next

        _TempFiles.Clear()

        UpdateMainUi()
    End Sub

    ''' <summary>
    ''' Initialize the Viewer
    ''' </summary>
    ''' <param name="LogConfig">A LogConfig object</param>
    ''' <param name="LicenseKey">The GDPicture.NET License Key</param>
    Public Sub Init(LogConfig As LogConfig, LicenseKey As String)
        _logConfig = LogConfig
        _logger = LogConfig.GetLogger()

        _licenseKey = LicenseKey
        _licenseManager.RegisterKEY(_licenseKey)
    End Sub

    ''' <summary>
    ''' Terminate Viewer, freeing up resources and deleting temp files
    ''' </summary>
    Public Sub Done()
        DeleteTempFiles()
    End Sub

    ''' <summary>
    ''' Load a file and display it
    ''' </summary>
    ''' <param name="FilePath"></param>
    Public Sub LoadFile(FilePath As String)
        If _licenseKey = String.Empty Then
            _logger.Warn("License key was not provided. File {0} not loaded.", FilePath)
            Exit Sub
        End If

        _logger.Info("Loading File {0}", FilePath)

        DoLoadFile(FilePath)

        UpdateMainUi()
    End Sub

    Public Sub LoadFile(FileName As String, Stream As Stream)
        If _licenseKey = String.Empty Then
            _logger.Warn("License key was not provided. File [{0}] not loaded.", FileName)
            Exit Sub
        End If

        Dim oExtension As String = FileName.Substring(FileName.LastIndexOf("."))

        _logger.Info("Loading File [{0}]", FileName)

        DoLoadFile(Stream, oExtension)

        UpdateMainUi()
    End Sub

    Public Sub CloseDocument()
        GdViewer.CloseDocument()
        UpdateMainUi()
    End Sub

    Public Sub DeleteTempFiles()
        For Each oFile In _TempFiles
            Try
                IO.File.Delete(oFile)
            Catch ex As Exception
                _logger.Warn("Could not delete temp file {0}", oFile)
            End Try
        Next
        _TempFiles.Clear()
    End Sub

    Private Sub DoLoadFile(FilePath As String)
        Try
            Dim oFileInfo = New IO.FileInfo(FilePath)
            Dim oExtension As String = oFileInfo.Extension.ToUpper

            RichEditControl1.Visible = False
            RichEditControl1.Dock = DockStyle.None

            SpreadsheetControl1.Visible = False
            SpreadsheetControl1.Dock = DockStyle.None

            mainToolStrip.Visible = False

            Select Case oExtension.ToUpper
                Case ".MSG"
                    Dim oMsg As New Message(FilePath)
                    ' TODO: Improve Encoding, maybe convert based on encoding
                    oMsg.Encoding = System.Text.Encoding.UTF32
                    Dim oMime = oMsg.ConvertToMimeMessage()
                    Dim oTempFileName = IO.Path.GetTempFileName()
                    oMime.Save(oTempFileName, True)

                    RichEditControl1.LoadDocument(oTempFileName, XtraRichEdit.DocumentFormat.Mht)

                    _TempFiles.Add(oTempFileName)

                    RichEditControl1.Visible = True
                    RichEditControl1.Dock = DockStyle.Fill

                Case ".EML", ".DOC", ".DOCX", ".ODT", ".RTF", ".TXT"
                    RichEditControl1.LoadDocument(FilePath, GetDocumentFormat(oExtension))

                    RichEditControl1.Visible = True
                    RichEditControl1.Dock = DockStyle.Fill

                Case ".XLSX", ".XLS", "CSV"
                    SpreadsheetControl1.LoadDocument(FilePath, GetSpreadsheetFormat(oExtension))

                    Dim oRange = SpreadsheetControl1.ActiveWorksheet.GetUsedRange()
                    oRange.AutoFitColumns()

                    SpreadsheetControl1.Visible = True
                    SpreadsheetControl1.Dock = DockStyle.Fill

                Case Else
                    mainToolStrip.Visible = True

                    GdViewer.ZoomMode = ViewerZoomMode.ZoomModeWidthViewer
                    GdViewer.DocumentAlignment = ViewerDocumentAlignment.DocumentAlignmentTopCenter

                    GdViewer.DisplayFromFile(FilePath)
            End Select

            UpdateMainUi()
        Catch ex As Exception
            _logger.Error(ex)
        End Try
    End Sub

    Private Sub DoLoadFile(Stream As Stream, Extension As String)
        Try
            RichEditControl1.Visible = False
            RichEditControl1.Dock = DockStyle.None

            SpreadsheetControl1.Visible = False
            SpreadsheetControl1.Dock = DockStyle.None

            mainToolStrip.Visible = False

            Select Case Extension.ToUpper
                Case ".MSG"
                    Dim oMsg As New Message(Stream)

                    ' TODO: Improve Encoding, maybe convert based on encoding
                    oMsg.Encoding = System.Text.Encoding.UTF32
                    Dim oMime = oMsg.ConvertToMimeMessage()
                    Dim oTempFileName = IO.Path.GetTempFileName()
                    oMime.Save(oTempFileName, True)

                    RichEditControl1.LoadDocument(oTempFileName, XtraRichEdit.DocumentFormat.Mht)

                    _TempFiles.Add(oTempFileName)

                    RichEditControl1.Visible = True
                    RichEditControl1.Dock = DockStyle.Fill

                Case ".EML", ".DOC", ".DOCX", ".ODT", ".RTF", ".TXT"
                    RichEditControl1.LoadDocument(Stream, GetDocumentFormat(Extension))

                    RichEditControl1.Visible = True
                    RichEditControl1.Dock = DockStyle.Fill

                Case ".XLSX", ".XLS", "CSV"
                    SpreadsheetControl1.LoadDocument(Stream, GetSpreadsheetFormat(Extension))

                    Dim oRange = SpreadsheetControl1.ActiveWorksheet.GetUsedRange()
                    oRange.AutoFitColumns()

                    SpreadsheetControl1.Visible = True
                    SpreadsheetControl1.Dock = DockStyle.Fill

                Case Else
                    mainToolStrip.Visible = True

                    GdViewer.ZoomMode = ViewerZoomMode.ZoomModeWidthViewer
                    GdViewer.DocumentAlignment = ViewerDocumentAlignment.DocumentAlignmentTopCenter

                    GdViewer.DisplayFromStream(Stream)
            End Select

            UpdateMainUi()
        Catch ex As Exception
            _logger.Error(ex)
        End Try
    End Sub

    Private Function GetSpreadsheetFormat(Extension) As Spreadsheet.DocumentFormat
        Dim oFormat As Spreadsheet.DocumentFormat = Spreadsheet.DocumentFormat.Undefined

        Select Case Extension.ToUpper
            Case "XLSX" : oFormat = Spreadsheet.DocumentFormat.Xlsx
            Case "XLS" : oFormat = Spreadsheet.DocumentFormat.Xls
            Case "CSV" : oFormat = Spreadsheet.DocumentFormat.Csv
        End Select

        Return oFormat
    End Function

    Private Function GetDocumentFormat(Extension)
        Dim oFormat As XtraRichEdit.DocumentFormat = XtraRichEdit.DocumentFormat.Undefined

        Select Case Extension.ToUpper
            Case ".EML" : oFormat = XtraRichEdit.DocumentFormat.Mht
            Case ".DOC" : oFormat = XtraRichEdit.DocumentFormat.Doc
            Case ".DOCX" : oFormat = XtraRichEdit.DocumentFormat.OpenXml
            Case ".ODT" : oFormat = XtraRichEdit.DocumentFormat.OpenDocument
            Case ".RTF" : oFormat = XtraRichEdit.DocumentFormat.Rtf
            Case ".TXT" : oFormat = XtraRichEdit.DocumentFormat.PlainText
        End Select

        Return oFormat
    End Function


    Private Sub btnOpen_Click(sender As Object, e As EventArgs)
        GdViewer.ZoomMode = ViewerZoomMode.ZoomModeWidthViewer
        GdViewer.DocumentAlignment = ViewerDocumentAlignment.DocumentAlignmentTopCenter

        If OpenFileDialog.ShowDialog() = DialogResult.OK Then
            GdViewer.DisplayFromFile(OpenFileDialog.FileName)
        End If

        GdViewer.Focus()
        UpdateMainUi()
    End Sub

    ''' <summary>
    ''' Configures the viewer to hide the file path to the end-user.
    ''' </summary>
    ''' <param name="ViewOnly">
    ''' True means that all file info should be hidden from the end-user
    ''' False means the end user may see the filepath or other info about the file
    ''' </param>
    Public Sub RightOnlyView(ViewOnly As Boolean)
        If ViewOnly Then
            btnPrint.Visible = False
        Else
            btnPrint.Visible = True
        End If

        _hide_file_info_from_user = Not ViewOnly
    End Sub
    Private Sub UpdateMainUi()
        Exit Sub

        If GdViewer.PageCount = 0 Then
            btnPrint.Enabled = False
            btnFirstPage.Enabled = False
            btnPreviousPage.Enabled = False
            tbCurrentPage.Enabled = False
            lblPageCount.Enabled = False
            btnNextPage.Enabled = False
            btnLastPage.Enabled = False
            btnZoomOut.Enabled = False
            cbZoom.Enabled = False
            btnZoomIn.Enabled = False
            btnFitPage.Enabled = False
            btnFitWidth.Enabled = False
            btnRotateLeft.Enabled = False
            btnRotateRight.Enabled = False
            btnFlipX.Enabled = False
            btnFlipY.Enabled = False
            tbCurrentPage.Text = "0"
            lblPageCount.Text = "/ 0"
            cbZoom.SelectedIndex = -1
        Else
            btnPrint.Enabled = True
            btnFirstPage.Enabled = True
            btnPreviousPage.Enabled = True
            tbCurrentPage.Enabled = True
            lblPageCount.Enabled = True
            btnNextPage.Enabled = True
            btnLastPage.Enabled = True
            btnZoomOut.Enabled = True
            cbZoom.Enabled = True
            btnZoomIn.Enabled = True
            btnFitPage.Enabled = True
            btnFitWidth.Enabled = True
            btnRotateLeft.Enabled = True
            btnRotateRight.Enabled = True
            btnFlipX.Enabled = True
            btnFlipY.Enabled = True
            UpdateaNavigationToolbar()
        End If
    End Sub

    Private Sub btnFirstPage_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnFirstPage.Click
        GdViewer.DisplayFirstPage()
    End Sub

    Private Sub btnPreviousPage_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnPreviousPage.Click
        GdViewer.DisplayPreviousPage()
    End Sub

    Private Sub btnNextPage_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnNextPage.Click
        GdViewer.DisplayNextPage()
    End Sub

    Private Sub btnLastPage_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnLastPage.Click
        GdViewer.DisplayLastPage()
    End Sub

    Private Sub tbCurrentPage_Leave(ByVal sender As System.Object, ByVal e As EventArgs) Handles tbCurrentPage.Leave
        Dim page As Integer = 0
        If Integer.TryParse(tbCurrentPage.Text, page) Then
            If page > 0 And page <= GdViewer.PageCount Then
                GdViewer.DisplayPage(page)
                UpdateaNavigationToolbar()
            End If
        End If
    End Sub

    Private Sub GdViewer1_PageChanged() Handles GdViewer.PageChanged
        UpdateaNavigationToolbar()
    End Sub

    Private Sub ChangeZoomValue()
        If cbZoom.SelectedIndex <> -1 Then
            Select Case cbZoom.SelectedIndex
                Case ZoomMode.Zoom50
                    GdViewer.Zoom = 50.0F / 100
                Case ZoomMode.Zoom100
                    GdViewer.Zoom = 100.0F / 100
                Case ZoomMode.Zoom150
                    GdViewer.Zoom = 150.0F / 100
                Case ZoomMode.Zoom200
                    GdViewer.Zoom = 250.0F / 100
                Case ZoomMode.ZoomSelectedArea
                    If GdViewer.IsRect() Then
                        GdViewer.ZoomRect()
                    Else
                        GdViewer.MouseMode = ViewerMouseMode.MouseModeAreaSelection
                        GdViewer.Focus()
                    End If
                Case ZoomMode.ZoomFitToViewer
                    GdViewer.ZoomMode = ViewerZoomMode.ZoomModeFitToViewer
                Case ZoomMode.ZoomFitWidth
                    GdViewer.ZoomMode = ViewerZoomMode.ZoomModeWidthViewer
                Case ZoomMode.ZoomFitHeight
                    GdViewer.ZoomMode = ViewerZoomMode.ZoomModeHeightViewer
            End Select
        Else
            If (IsNumeric(Regex.Replace(cbZoom.Text, "[^0-9,.]", ""))) Then
                GdViewer.Zoom = Val(Regex.Replace(cbZoom.Text, "[^0-9,.]", "")) / 100
            End If
        End If
        UpdateaNavigationToolbar()
    End Sub

    Private Sub cbZoom_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As EventArgs) Handles cbZoom.SelectedIndexChanged
        ChangeZoomValue()
    End Sub

    Private Sub GdViewer1_AfterZoomChange() Handles GdViewer.AfterZoomChange
        UpdateaNavigationToolbar()
        If GdViewer.MouseMode = ViewerMouseMode.MouseModeAreaZooming Then
            GdViewer.MouseMode = ViewerMouseMode.MouseModePan
        End If
    End Sub

    Private Sub btnZoomOut_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnZoomOut.Click
        GdViewer.ZoomOUT()
    End Sub

    Private Sub btnZoomIn_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnZoomIn.Click
        GdViewer.ZoomIN()
    End Sub

    Private Sub cbZoom_TextUpdate(ByVal sender As System.Object, ByVal e As EventArgs) Handles cbZoom.Validating
        ChangeZoomValue()
    End Sub

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnPrint.Click
        If GdViewer.PageCount = 0 Then
            Return
        End If
        Using f As New frmViewerPrint(GdViewer)
            f.ShowDialog(Me)
            If f.DialogResult <> DialogResult.OK Then
                Return
            End If
            Dim printSettings As frmViewerPrint.PrintSettings = f.printConfiguration
            If Not GdViewer.PrintSetActivePrinter(printSettings.Printer) Then
                Return
            End If
            GdViewer.PrintSetDocumentName("GdPicture Print Job " + DateTime.Now.ToString("yyyy-MM-dd HH\mm"))
            GdViewer.PrintSetAlignment(printSettings.PrintAlignment)
            Select Case printSettings.Orientation
                Case frmViewerPrint.PrintOrientation.AutoDetection
                    GdViewer.PrintSetAutoRotation(True)
                    Exit Select
                Case frmViewerPrint.PrintOrientation.Portrait
                    GdViewer.PrintSetAutoRotation(False)
                    GdViewer.PrintSetOrientation(PrinterOrientation.PrinterOrientationPortrait)
                    Exit Select
                Case frmViewerPrint.PrintOrientation.Paysage
                    GdViewer.PrintSetAutoRotation(False)
                    GdViewer.PrintSetOrientation(PrinterOrientation.PrinterOrientationLandscape)
                    Exit Select
            End Select
            GdViewer.PrintSetCopies(printSettings.Copies)
            If printSettings.Copies > 1 Then
                GdViewer.PrintSetCollate(printSettings.Collate)
            End If
            Select Case printSettings.PagesToPrint
                Case frmViewerPrint.PagesToPrint.All
                    GdViewer.PrintSetFromToPage(1, GdViewer.PageCount)
                    GdViewer.Print(printSettings.PrintSize)
                    Exit Select
                Case frmViewerPrint.PagesToPrint.Current
                    GdViewer.PrintSetFromToPage(GdViewer.CurrentPage, GdViewer.CurrentPage)
                    GdViewer.Print(printSettings.PrintSize)
                    Exit Select
                Case frmViewerPrint.PagesToPrint.Range
                    If printSettings.PageRange IsNot Nothing And printSettings.PageRange <> String.Empty Then
                        If printSettings.PageRange.Contains("-") Then
                            Dim pageStart As Integer = 0
                            If Integer.TryParse(printSettings.PageRange.Split("-"c)(0), pageStart) Then
                                Dim pageEnd As Integer = 0
                                If Integer.TryParse(printSettings.PageRange.Split("-"c)(1), pageEnd) Then
                                    If pageEnd < pageStart Then
                                        GdViewer.PrintSetFromToPage(pageEnd, pageStart)
                                        GdViewer.Print(printSettings.PrintSize)
                                    Else
                                        GdViewer.PrintSetFromToPage(pageStart, pageEnd)
                                        GdViewer.Print(printSettings.PrintSize)
                                    End If
                                Else
                                    MessageBox.Show("Page range is invalid.", "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                                End If
                            Else
                                MessageBox.Show("Page range is invalid.", "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                            End If
                        Else
                            Dim page As Integer = 0
                            If Integer.TryParse(printSettings.PageRange, page) Then
                                GdViewer.PrintSetFromToPage(page, page)
                                GdViewer.Print(printSettings.PrintSize)
                            Else
                                MessageBox.Show("Page range is invalid.", "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                            End If
                        End If
                    Else
                        MessageBox.Show("Page range is invalid.", "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                    End If
                    Exit Select
            End Select
        End Using
    End Sub

    Private Sub btnRotateLeft_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnRotateLeft.Click
        GdViewer.Rotate(RotateFlipType.Rotate270FlipNone)
    End Sub

    Private Sub btnRotateRight_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnRotateRight.Click
        GdViewer.Rotate(RotateFlipType.Rotate90FlipNone)
    End Sub

    Private Sub btnFlipX_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnFlipX.Click
        GdViewer.Rotate(RotateFlipType.RotateNoneFlipX)
    End Sub

    Private Sub btnFlipY_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnFlipY.Click
        GdViewer.Rotate(RotateFlipType.RotateNoneFlipY)
    End Sub

    Private Sub GdViewer1_TransferEnded(ByVal status As GdPictureStatus, ByVal download As System.Boolean) Handles GdViewer.TransferEnded
        GdViewer.Focus()
        UpdateMainUi()
    End Sub

    Private Sub cbZoom_Validating(ByVal sender As System.Object, ByVal e As CancelEventArgs) Handles cbZoom.Validating
        ChangeZoomValue()
    End Sub

    Private Sub AddSearchRegion(ByVal occurence As Integer, ByVal leftCoordinate As Single, ByVal topCoordinate As Single, ByVal regionWidth As Single, ByVal regionheight As Single, ByVal ensureVisibility As Boolean)
        Dim searchRegion As Integer = GdViewer.AddRegionInches("SearchResult" & occurence, leftCoordinate, topCoordinate, regionWidth, regionheight, ForegroundMixMode.ForegroundMixModeMASKPEN, Color.Yellow)
        GdViewer.SetRegionEditable(searchRegion, False)
        If ensureVisibility Then
            GdViewer.EnsureRegionVisibility(searchRegion)
        End If
    End Sub

    Private Sub btnSettings_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSettings.Click
        Using frmSettings As New frmViewerSettings(GdViewer)
            frmSettings.ShowDialog(Me)
        End Using
        UpdateaNavigationToolbar()
    End Sub

    Private Sub UpdateaNavigationToolbar()
        Dim currentPage As Integer = GdViewer.CurrentPage()
        tbCurrentPage.Text = currentPage.ToString()
        lblPageCount.Text = "/ " & GdViewer.PageCount.ToString()
        If currentPage = 1 Then
            btnFirstPage.Enabled = False
            btnPreviousPage.Enabled = False
        Else
            btnFirstPage.Enabled = True
            btnPreviousPage.Enabled = True
        End If
        If currentPage = GdViewer.PageCount Then
            btnNextPage.Enabled = False
            btnLastPage.Enabled = False
        Else
            btnNextPage.Enabled = True
            btnLastPage.Enabled = True
        End If
        cbZoom.Text = String.Format(CultureInfo.InvariantCulture, "{0:#0.##%}", GdViewer.Zoom)
    End Sub

    Private Sub btnFitWidth_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFitWidth.Click
        GdViewer.ZoomMode = ViewerZoomMode.ZoomModeWidthViewer
    End Sub

    Private Sub btnFitPage_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFitPage.Click
        GdViewer.ZoomMode = ViewerZoomMode.ZoomModeFitToViewer
    End Sub

    Private Sub DefaultToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles DefaultToolStripMenuItem.Click
        GdViewer.MouseMode = ViewerMouseMode.MouseModeDefault
        DefaultToolStripMenuItem.Checked = True
        AreaSelectionToolStripMenuItem.Checked = False
        PanToolStripMenuItem.Checked = False
        AreaZoomingToolStripMenuItem.Checked = False
        MagnifierToolStripMenuItem.Checked = False
        GdViewer.Focus()
    End Sub

    Private Sub AreaSelectionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles AreaSelectionToolStripMenuItem.Click
        GdViewer.MouseMode = ViewerMouseMode.MouseModeAreaSelection
        DefaultToolStripMenuItem.Checked = False
        AreaSelectionToolStripMenuItem.Checked = True
        PanToolStripMenuItem.Checked = False
        AreaZoomingToolStripMenuItem.Checked = False
        MagnifierToolStripMenuItem.Checked = False
        GdViewer.Focus()
    End Sub

    Private Sub PanToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles PanToolStripMenuItem.Click
        GdViewer.MouseMode = ViewerMouseMode.MouseModePan
        DefaultToolStripMenuItem.Checked = False
        AreaSelectionToolStripMenuItem.Checked = False
        PanToolStripMenuItem.Checked = True
        AreaZoomingToolStripMenuItem.Checked = False
        MagnifierToolStripMenuItem.Checked = False
        GdViewer.Focus()
    End Sub

    Private Sub AreaZoomingToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles AreaZoomingToolStripMenuItem.Click
        GdViewer.MouseMode = ViewerMouseMode.MouseModeAreaZooming
        DefaultToolStripMenuItem.Checked = False
        AreaSelectionToolStripMenuItem.Checked = False
        PanToolStripMenuItem.Checked = False
        AreaZoomingToolStripMenuItem.Checked = True
        MagnifierToolStripMenuItem.Checked = False
        GdViewer.Focus()
    End Sub

    Private Sub MagnifierToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles MagnifierToolStripMenuItem.Click
        GdViewer.MouseMode = ViewerMouseMode.MouseModeMagnifier
        DefaultToolStripMenuItem.Checked = False
        AreaSelectionToolStripMenuItem.Checked = False
        PanToolStripMenuItem.Checked = False
        AreaZoomingToolStripMenuItem.Checked = False
        MagnifierToolStripMenuItem.Checked = True
        GdViewer.Focus()
    End Sub

    Private Sub RichEditControl1_SizeChanged(sender As Object, e As EventArgs) Handles RichEditControl1.SizeChanged
        Dim oControlWidth = RichEditControl1.Width - 100
        Dim oPageWidth = Units.DocumentsToPixelsF(RichEditControl1.Document.Sections(0).Page.Width, RichEditControl1.DpiX)
        RichEditControl1.Views.PrintLayoutView.ZoomFactor = oControlWidth / oPageWidth
    End Sub
End Class
