Code development platform for open source projects from the European Union institutions

Skip to content
Snippets Groups Projects
MainForm.vb 75.9 KiB
Newer Older
' This file is part of VECTO.
'
' Copyright © 2012-2016 European Union
'
' Developed by Graz University of Technology,
'              Institute of Internal Combustion Engines and Thermodynamics,
'              Institute of Technical Informatics
'
' VECTO is licensed under the EUPL, Version 1.1 or - as soon they will be approved
' by the European Commission - subsequent versions of the EUPL (the "Licence");
' You may not use VECTO except in compliance with the Licence.
' You may obtain a copy of the Licence at:
'
' https://joinup.ec.europa.eu/community/eupl/og_page/eupl
'
' Unless required by applicable law or agreed to in writing, VECTO
' distributed under the Licence is distributed on an "AS IS" basis,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the Licence for the specific language governing permissions and
' limitations under the Licence.
'
' Authors:
'   Stefan Hausberger, hausberger@ivt.tugraz.at, IVT, Graz University of Technology
'   Christian Kreiner, christian.kreiner@tugraz.at, ITI, Graz University of Technology
'   Michael Krisper, michael.krisper@tugraz.at, ITI, Graz University of Technology
'   Raphael Luz, luz@ivt.tugraz.at, IVT, Graz University of Technology
'   Markus Quaritsch, markus.quaritsch@tugraz.at, IVT, Graz University of Technology
'   Martin Rexeis, rexeis@ivt.tugraz.at, IVT, Graz University of Technology

Imports System.Collections.Generic
Markus Quaritsch's avatar
Markus Quaritsch committed
Imports System.Reflection
Imports TUGraz.VectoCore.Models.Simulation.Impl
Imports TUGraz.VectoCore.InputData.FileIO.JSON
Imports System.Text
Imports System.Threading
Imports System.Xml
Imports System.Xml.Linq
Imports Microsoft.VisualBasic.FileIO
Imports TUGraz.VectoCommon.Exceptions
Imports TUGraz.VectoCommon.Models
Imports TUGraz.VectoCore.InputData.FileIO.XML.Declaration
Imports TUGraz.VectoCore.InputData.FileIO.XML.Engineering
Imports TUGraz.VectoCore.OutputData
Imports TUGraz.VectoCore.OutputData.FileIO
''' <summary>
''' Main application form. Loads at application start. Closing form ends application.
''' </summary>
''' <remarks></remarks>
    Public Class MainForm
    Private _jobListView As FileListView
    Private _cycleListView As FileListView
    Private _lastModeName As String
    Private _conMenTarget As ListView
    Private _conMenTarJob As Boolean
    Private _guIlocked As Boolean
    Private _checkLock As Boolean
    Private _genChecked As Integer
    Private _genCheckAllLock As Boolean
    Private _cbDeclLock As Boolean = False

#Region "SLEEP Control - Prevent sleep while VECTO is running"
    Private Declare Function SetThreadExecutionState Lib "kernel32"(esFlags As Long) As Long
    Private Shared Sub AllowSleepOff()
#If Not PLATFORM = "x86" Then
        SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS Or EXECUTION_STATE.ES_SYSTEM_REQUIRED)
    Private Shared Sub AllowSleepOn()
#If Not PLATFORM = "x86" Then
        SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS)
    Private Enum EXECUTION_STATE As Integer
        ''' Informs the system that the state being set should remain in effect until the next call that uses ES_CONTINUOUS and one of the other state flags is cleared.
        ES_CONTINUOUS = &H80000000
        ''' Forces the display to be on by resetting the display idle timer.
        ES_DISPLAY_REQUIRED = &H2
        ''' Forces the system to be in the working state by resetting the system idle timer.
        ES_SYSTEM_REQUIRED = &H1
    End Enum

#End Region

#Region "FileBrowser Init/Close"
    Private Sub FB_Initialize()
        FileBrowserFolderHistoryIninialized = False
        Try
            COREvers = VectoSimulationCore.VersionNumber()
        Catch ex As Exception
            LogFile.WriteToLog(MessageType.Err, ex.StackTrace)
        End Try


        FolderFileBrowser = New FileBrowser("WorkDir", True)
        TextFileBrowser = New FileBrowser("FileLists")
        JobfileFileBrowser = New FileBrowser("vecto")
        VehicleFileBrowser = New FileBrowser("vveh")
        VehicleXMLFileBrowser = New FileBrowser("vveh_xml")
        ManRXMLFileBrowser = new FileBrowser("xml")
        FuelConsumptionMapFileBrowser = New FileBrowser("vmap")
        DrivingCycleFileBrowser = New FileBrowser("vdri")
        FullLoadCurveFileBrowser = New FileBrowser("vfld")
        EngineFileBrowser = New FileBrowser("veng")
        GearboxFileBrowser = New FileBrowser("vgbx")
        DriverAccelerationFileBrowser = New FileBrowser("vacc")
        AuxFileBrowser = New FileBrowser("vaux")
        GearboxShiftPolygonFileBrowser = New FileBrowser("vgbs")
        RetarderLossMapFileBrowser = New FileBrowser("vrlm")
        TransmissionLossMapFileBrowser = New FileBrowser("vtlm")
        PtoLossMapFileBrowser = New FileBrowser("vptol")
        PTODrivingCycleFileBrowser = New FileBrowser("vptoc")
        TorqueConverterFileBrowser = New FileBrowser("vtcc")
        TorqueConverterShiftPolygonFileBrowser = New FileBrowser("vgbs")
        CrossWindCorrectionFileBrowser = New FileBrowser("vcdx")
        DriverDecisionFactorVelocityDropFileBrowser = New FileBrowser("DfVelocityDrop")
        DriverDecisionFactorTargetSpeedFileBrowser = New FileBrowser("DfTargetSpeed")
        DriverDecisionFactorVelocityDropFileBrowser.Extensions = New String() {"csv"}
        DriverDecisionFactorTargetSpeedFileBrowser.Extensions = New String() {"csv"}

        ModalResultsFileBrowser = New FileBrowser("vmod")


        '-------------------------------------------------------
        TextFileBrowser.Extensions = New String() {"txt"}
        JobfileFileBrowser.Extensions = New String() {"vecto"}
        VehicleFileBrowser.Extensions = New String() {"vveh"}
        VehicleXMLFileBrowser.Extensions = New String() {"xml"}
        ManRXMLFileBrowser.Extensions = New String() {"xml"}
        FuelConsumptionMapFileBrowser.Extensions = New String() {"vmap"}
        DrivingCycleFileBrowser.Extensions = New String() {"vdri"}
        FullLoadCurveFileBrowser.Extensions = New String() {"vfld"}
        EngineFileBrowser.Extensions = New String() {"veng"}
        GearboxFileBrowser.Extensions = New String() {"vgbx"}
        DriverAccelerationFileBrowser.Extensions = New String() {"vacc"}
        AuxFileBrowser.Extensions = New String() {"vaux"}
        GearboxShiftPolygonFileBrowser.Extensions = New String() {"vgbs"}
        RetarderLossMapFileBrowser.Extensions = New String() {"vrlm"}
        TransmissionLossMapFileBrowser.Extensions = New String() {"vtlm"}
        PtoLossMapFileBrowser.Extensions = New String() {"vptol"}
        PTODrivingCycleFileBrowser.Extensions = New String() {"vptoc"}
        TorqueConverterFileBrowser.Extensions = New String() {"vtcc"}
        TorqueConverterShiftPolygonFileBrowser.Extensions = New String() {"vgbs"}
        CrossWindCorrectionFileBrowser.Extensions = New String() {"vcdv", "vcdb"}

        ModalResultsFileBrowser.Extensions = New String() {"vmod"}
    End Sub

    Private Sub FB_Close()
        FolderFileBrowser.Close()
        TextFileBrowser.Close()
        JobfileFileBrowser.Close()
        VehicleFileBrowser.Close()
        VehicleXMLFileBrowser.Close()
        ManRXMLFileBrowser.Close()
        FuelConsumptionMapFileBrowser.Close()
        DrivingCycleFileBrowser.Close()
        FullLoadCurveFileBrowser.Close()
        EngineFileBrowser.Close()
        GearboxFileBrowser.Close()
        DriverAccelerationFileBrowser.Close()
        AuxFileBrowser.Close()
        GearboxShiftPolygonFileBrowser.Close()
        RetarderLossMapFileBrowser.Close()
        TransmissionLossMapFileBrowser.Close()
        PtoLossMapFileBrowser.Close()
        PTODrivingCycleFileBrowser.Close()
        TorqueConverterFileBrowser.Close()
        TorqueConverterShiftPolygonFileBrowser.Close()
        CrossWindCorrectionFileBrowser.Close()
        ModalResultsFileBrowser.Close()
    End Sub
    'Lock certain GUI elements while VECTO is running
    Private Sub LockGUI(lock As Boolean)
        _guIlocked = lock
        PanelOptAllg.Enabled = Not lock
        BtGENup.Enabled = Not lock
        BtGENdown.Enabled = Not lock
        ButtonGENadd.Enabled = Not lock
        ButtonGENremove.Enabled = Not lock
        LvGEN.LabelEdit = Not lock
        ChBoxAllGEN.Enabled = Not lock
        btStartV3.Enabled = Not lock
    End Sub
    'Initialise
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim x As Integer
        _guIlocked = False
        _checkLock = False
        _genCheckAllLock = False
        _genChecked = 0
        'Load Tabs properly (otherwise problem with ListViews)
        For x = 0 To TabControl1.TabCount - 1
            TabControl1.TabPages(x).Show()
        Next
        _lastModeName = ""
        FB_Initialize()
        Text = "VECTO " & VECTOvers & " / VectoCore " & COREvers
        'FileLists
        _jobListView = New FileListView(MyConfPath & "joblist.txt")
        _jobListView.LVbox = LvGEN
        _cycleListView = New FileListView(MyConfPath & "cyclelist.txt")
        _jobListView.LoadList()
        LoadOptions()
        'Resize columns ... after Loading the @file-lists
        LvGEN.Columns(1).Width = - 2
        LvMsg.Columns(2).Width = - 2
        'Initialize BackgroundWorker
        VectoWorkerV3 = New BackgroundWorker()
        AddHandler VectoWorkerV3.DoWork, AddressOf VectoWorkerV3_OnDoWork
        AddHandler VectoWorkerV3.ProgressChanged, AddressOf VectoWorkerV3_OnProgressChanged
        AddHandler VectoWorkerV3.RunWorkerCompleted, AddressOf VectoWorkerV3_OnRunWorkerCompleted
        VectoWorkerV3.WorkerReportsProgress = True
        VectoWorkerV3.WorkerSupportsCancellation = True
        'Set mode (Batch/Standard)
        ModeUpdate()
        DeclOnOff()
    End Sub
    ' ReSharper disable once UnusedMember.Global -- used via Logging Framework! 
    Public Shared Sub LogMethod(level As String, message As String)
        If VectoWorkerV3.IsBusy AndAlso Not VectoWorkerV3.CancellationPending Then
            If level = "Warn" Then
                VectoWorkerV3.ReportProgress(100,
                                             New VectoProgress With {.Target = "ListBoxWarning", .Message = message})
            ElseIf level = "Error" Or level = "Fatal" Then
                VectoWorkerV3.ReportProgress(100, New VectoProgress With {.Target = "ListBoxError", .Message = message})
            End If
        End If
    End Sub
    'Declaration mode GUI settings
    Private Sub DeclOnOff()
        If Cfg.DeclMode Then
            Text = "VECTO " & COREvers & " - Declaration Mode"
            Cfg.DeclInit()
        Else
            Text = "VECTO " & COREvers
        End If
        If Cfg.DeclMode Then
            _lastModeName = "Declaration"
        Else
            _lastModeName = "Engineering"
        End If
        Status(_lastModeName & " Mode")
        LoadOptions()
        LbDecl.Visible = Cfg.DeclMode
    End Sub
    'Shown Event (Form-Load finished) ... here StartUp Forms are loaded (DEV, GEN/ADV- Editor ..)
    Private Sub F01_MAINForm_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        Dim fwelcome As WelcomeDialog
        If Cfg.FirstRun Then
            Cfg.FirstRun = False
            fwelcome = New WelcomeDialog
            fwelcome.ShowDialog()
        End If
    End Sub
    'Open file
    'Close
    Private Sub F01_MAINForm_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        'Save File-Lists
        SaveFileLists()
        'Close log
        LogFile.CloseLog()
        'Config save
        SetOptions()
        Cfg.Save()
        'File browser instances close
        FB_Close()
    End Sub
    'Open file - Job, vehicle, engine, gearbox or signature file
    Public Sub OpenVectoFile(file As String)

        If Not IO.File.Exists(file) Then

            GUIMsg(MessageType.Err, "File not found! (" & file & ")")
            MsgBox("File not found! (" & file & ")", MsgBoxStyle.Critical)

        Else

            Select Case UCase(GetExtension(file))
                Case ".VGBX"
                    If Not GearboxForm.Visible Then
                        GearboxForm.Show()
                    Else
                        GearboxForm.JobDir = ""
                        If GearboxForm.WindowState = FormWindowState.Minimized Then _
                            GearboxForm.WindowState = FormWindowState.Normal
                        GearboxForm.BringToFront()
                    End If
                    Try
                        GearboxForm.OpenGbx(file, VehicleCategory.RigidTruck)
                    Catch ex As Exception
                        MsgBox("Failed to open Gearbox File: " + ex.Message)
                    End Try
                Case ".VVEH"
                    If Not VehicleForm.Visible Then
                        VehicleForm.Show()
                    Else
                        VehicleForm.JobDir = ""
                        If VehicleForm.WindowState = FormWindowState.Minimized Then _
                            VehicleForm.WindowState = FormWindowState.Normal
                        VehicleForm.BringToFront()
                    End If
                    Try
                        VehicleForm.OpenVehicle(file)
                    Catch ex As Exception
                        MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Error loading Vehicle File")
                    End Try
                Case ".VENG"
                    If Not EngineForm.Visible Then
                        EngineForm.Show()
                    Else
                        EngineForm.JobDir = ""
                        If EngineForm.WindowState = FormWindowState.Minimized Then _
                            EngineForm.WindowState = FormWindowState.Normal
                        EngineForm.BringToFront()
                    End If
                    Try
                        EngineForm.OpenEngineFile(file)
                    Catch ex As Exception
                        MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Error loading Engine File")
                    End Try
                Case ".VECTO"
                    OpenVECTOeditor(file)
                Case Else
                    MsgBox("Type '" & GetExtension(file) & "' unknown!", MsgBoxStyle.Critical)
            End Select

        End If
    End Sub
    Private Sub ButtonGENremove_Click(sender As Object, e As EventArgs) _
        Handles ButtonGENremove.Click
        RemoveJobFile()
    End Sub

    Private Sub ButtonGENadd_Click(sender As Object, e As EventArgs) _
        Handles ButtonGENadd.Click
        AddJobFile()
    End Sub

    Private Sub ListViewGEN_KeyDown(sender As Object, e As KeyEventArgs) _
        Handles LvGEN.KeyDown
        Select Case e.KeyCode
            Case Keys.Delete, Keys.Back
                If Not _guIlocked Then RemoveJobFile()
            Case Keys.Enter
                OpenJobFile()
        End Select
    End Sub

    Private Sub ListViewGEN_DoubleClick(sender As Object, e As EventArgs) Handles LvGEN.DoubleClick
        If LvGEN.SelectedItems.Count > 0 Then
            LvGEN.SelectedItems(0).Checked = Not LvGEN.SelectedItems(0).Checked
            OpenJobFile()
        End If
    End Sub

    Private Sub LvGEN_ItemChecked(sender As Object, e As ItemCheckedEventArgs) _
        Handles LvGEN.ItemChecked

        If e.Item.Checked Then
            _genChecked += 1
        Else
            _genChecked -= 1
        End If

        If _checkLock Then Exit Sub
        UpdateJobTabText()
    End Sub

    Private Sub ChBoxAllGEN_CheckedChanged(sender As Object, e As EventArgs) _
        Handles ChBoxAllGEN.CheckedChanged

        If _genCheckAllLock And ChBoxAllGEN.CheckState = CheckState.Indeterminate Then Exit Sub

        CheckAllGen(ChBoxAllGEN.Checked)
    End Sub

    Private Sub CheckAllGen(check As Boolean)
        Dim x As ListViewItem

        _checkLock = True
        LvGEN.BeginUpdate()

        For Each x In LvGEN.Items
            x.Checked = check
        Next

        LvGEN.EndUpdate()
        _checkLock = False

        _genChecked = LvGEN.CheckedItems.Count
        UpdateJobTabText()
    End Sub

    Private Sub ListGEN_DragEnter(sender As Object, e As DragEventArgs) _
        Handles LvGEN.DragEnter
        If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
            e.Effect = DragDropEffects.Copy
        End If
    End Sub

    Private Sub ListGEN_DragDrop(sender As Object, e As DragEventArgs) _
        Handles LvGEN.DragDrop
        Dim f As String()
        f = CType(e.Data.GetData(DataFormats.FileDrop), String())
        AddToJobListView(f)
    End Sub

    Private Sub BtGENup_Click(sender As Object, e As EventArgs) Handles BtGENup.Click
        MoveItem(LvGEN, True)
    End Sub

    Private Sub BtGENdown_Click(sender As Object, e As EventArgs) Handles BtGENdown.Click
        MoveItem(LvGEN, False)
    End Sub
    'Remove selected file(s) from job list
    Private Sub RemoveJobFile()
        Dim lastindx As Integer
        Dim selIx() As Integer
        Dim i As Integer

        If LvGEN.SelectedItems.Count < 1 Then
            If LvGEN.Items.Count = 1 Then
                LvGEN.Items(0).Selected = True
            Else
                Exit Sub
            End If
        End If

        LvGEN.BeginUpdate()
        _checkLock = True

        ReDim selIx(LvGEN.SelectedItems.Count - 1)
        LvGEN.SelectedIndices.CopyTo(selIx, 0)

        lastindx = LvGEN.SelectedIndices(LvGEN.SelectedItems.Count - 1)

        For i = UBound(selIx) To 0 Step - 1
            LvGEN.Items.RemoveAt(selIx(i))
        Next

        If lastindx < LvGEN.Items.Count Then
            LvGEN.Items(lastindx).Selected = True
        Else
            If LvGEN.Items.Count > 0 Then LvGEN.Items(LvGEN.Items.Count - 1).Selected = True
        End If

        LvGEN.EndUpdate()
        _checkLock = False

        _genChecked = LvGEN.CheckedItems.Count
        UpdateJobTabText()
    End Sub

    'Browse for job file(s) and add to job list with AddToJobListView
    Private Sub AddJobFile()
        Dim x As String()
        Dim chck As Boolean = False

        x = New String() {""}

        Dim extensions As String = "vecto"
        Dim inputDataExtensions As String() = New String() {"xml"}
        If (inputDataExtensions.Any()) Then _
            extensions = String.Join(",", extensions, String.Join(",", inputDataExtensions))

        'STANDARD/BATCH
        If JobfileFileBrowser.OpenDialog("", True, extensions) Then
            chck = True
            x = JobfileFileBrowser.Files
        End If

        If chck Then AddToJobListView(x)
    End Sub

    'Open file in list
    Private Sub OpenJobFile()
        Dim f As String

        If LvGEN.SelectedItems.Count < 1 Then
            If LvGEN.Items.Count = 1 Then
                LvGEN.Items(0).Selected = True
            Else
                Exit Sub
            End If
        End If

        f = LvGEN.SelectedItems(0).SubItems(0).Text
        f = FileRepl(f)
        If Path.GetExtension(f) <> VectoCore.Configuration.Constants.FileExtensions.VectoJobFile Then
            MsgBox("Job File " + f + " can not be opened in Job Editor. Try importing the file.")
            Exit Sub
        End If
        If Not File.Exists(f) Then
            MsgBox(f & " not found!")
        Else
            OpenVECTOeditor(f)
        End If
    End Sub

    'Add File to job listview (multiple files)
    Private Sub AddToJobListView(path As String(), Optional ByVal txt As String = " ")
        Dim pDim As Integer
        Dim p As Integer
        Dim f As Integer
        Dim fList As String()
        Dim fListDim As Integer = - 1
        Dim listViewItem As ListViewItem

        'If VECTO runs: Cancel operation (because Mode-change during calculation is not very clever)
        If VectoWorkerV3.IsBusy Then Exit Sub

        pDim = UBound(path)
        ReDim fList(0)	   'um Nullverweisausnahme-Warnung zu verhindern

        '******************************************* Begin Update '*******************************************
        LvGEN.BeginUpdate()
        _checkLock = True

        LvGEN.SelectedIndices.Clear()

        If pDim = 0 Then
            fListDim = LvGEN.Items.Count - 1
            ReDim fList(fListDim)
            For f = 0 To fListDim
                fList(f) = FileRepl(LvGEN.Items(f).SubItems(0).Text)
            Next
        End If

        For p = 0 To pDim

            If pDim = 0 Then

                For f = 0 To fListDim

                    'If file already exists in the list: Do not append (only when a single file)
                    If UCase(path(p)) = UCase(fList(f)) Then

                        'Status reset
                        LvGEN.Items(f).SubItems(1).Text = txt
                        LvGEN.Items(f).BackColor = Color.FromKnownColor(KnownColor.Window)
                        LvGEN.Items(f).ForeColor = Color.FromKnownColor(KnownColor.WindowText)

                        'Element auswählen und anhaken |@@| Element selection and hook
                        LvGEN.Items(f).Selected = True
                        LvGEN.Items(f).Checked = True
                        LvGEN.Items(f).EnsureVisible()

                        GoTo lbFound
                    End If
                Next

            End If

            'Otherwise: Add File (without WorkDir)
            listViewItem = New ListViewItem(path(p))	'fFileWD(Path(p)))
            listViewItem.SubItems.Add(" ")
            listViewItem.Checked = True
            listViewItem.Selected = True
            LvGEN.Items.Add(listViewItem)
            listViewItem.EnsureVisible()
            lbFound:
        Next

        LvGEN.EndUpdate()
        _checkLock = False
        '******************************************* End Update '*******************************************

        'Number update
        _genChecked = LvGEN.CheckedItems.Count
        UpdateJobTabText()
    End Sub

    'Add File to job listview (single file)
    Public Sub AddToJobListView(path As String, Optional ByVal txt As String = " ")
        Dim p(0) As String
        p(0) = path
        AddToJobListView(p, txt)
    End Sub

    'Update job files counter in tab titel
    Private Sub UpdateJobTabText()
        Dim count As Integer = LvGEN.Items.Count

        TabPageGEN.Text = String.Format("Job Files ( {0} / {1} )", _genChecked, count)

        _genCheckAllLock = True

        If _genChecked = 0 Then
            ChBoxAllGEN.CheckState = CheckState.Unchecked
        ElseIf _genChecked = count Then
            ChBoxAllGEN.CheckState = CheckState.Checked
        Else
            ChBoxAllGEN.CheckState = CheckState.Indeterminate
        End If

        _genCheckAllLock = False
    End Sub
    'New Job file
    Private Sub ToolStripBtNew_Click(sender As Object, e As EventArgs) Handles ToolStripBtNew.Click
        OpenVECTOeditor("<New>")
    End Sub

    'Open input file
    Private Sub ToolStripBtOpen_Click(sender As Object, e As EventArgs) Handles ToolStripBtOpen.Click

        If JobfileFileBrowser.OpenDialog("", False, "vecto,vveh,vgbx,veng") Then
            OpenVectoFile(JobfileFileBrowser.Files(0))
        End If
    End Sub

    Private Sub GENEditorToolStripMenuItem1_Click(sender As Object, e As EventArgs) _
        Handles GENEditorToolStripMenuItem1.Click
        OpenVECTOeditor("<New>")
    End Sub

    Private Sub VEHEditorToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles VEHEditorToolStripMenuItem.Click
        If Not VehicleForm.Visible Then
            VehicleForm.Show()
        Else
            If VehicleForm.WindowState = FormWindowState.Minimized Then VehicleForm.WindowState = FormWindowState.Normal
            VehicleForm.BringToFront()
        End If
    End Sub

    Private Sub EngineEditorToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles EngineEditorToolStripMenuItem.Click
        If Not EngineForm.Visible Then
            EngineForm.Show()
        Else
            If EngineForm.WindowState = FormWindowState.Minimized Then EngineForm.WindowState = FormWindowState.Normal
            EngineForm.BringToFront()
        End If
    End Sub

    Private Sub GearboxEditorToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles GearboxEditorToolStripMenuItem.Click
        If Not GearboxForm.Visible Then
            GearboxForm.Show()
        Else
            If GearboxForm.WindowState = FormWindowState.Minimized Then GearboxForm.WindowState = FormWindowState.Normal
            GearboxForm.BringToFront()
        End If
    End Sub

    Private Sub GraphToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles GraphToolStripMenuItem.Click
        Dim graphForm As New GraphForm
        graphForm.Show()
    End Sub

    Private Sub OpenLogToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles OpenLogToolStripMenuItem.Click
        Process.Start(MyAppPath & "log.txt")
    End Sub

    Private Sub SettingsToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles SettingsToolStripMenuItem.Click
        Settings.ShowDialog()
    End Sub

    Private Sub UserManualToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles UserManualToolStripMenuItem.Click
        If File.Exists(MyAppPath & "User Manual\help.html") Then
            Dim defaultBrowserPath As String = BrowserUtils.GetDefaultBrowserPath()
            Process.Start(defaultBrowserPath, String.Format("""file://{0}{1}""", MyAppPath, "User Manual\help.html"))
        Else
            MsgBox("User Manual not found!", MsgBoxStyle.Critical)
        End If
    End Sub

    Private Sub UpdateNotesToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles UpdateNotesToolStripMenuItem.Click
        If File.Exists(MyAppPath & "User Manual\Release Notes.pdf") Then
            Process.Start(MyAppPath & "User Manual\Release Notes.pdf")
        Else
            MsgBox("Release Notes not found!", MsgBoxStyle.Critical)
        End If
    End Sub

    Private Sub ReportBugViaCITnetToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles ReportBugViaCITnetToolStripMenuItem.Click
        JiraDialog.ShowDialog()
    End Sub

    Private Sub AboutVECTOToolStripMenuItem1_Click(sender As Object, e As EventArgs) _
        Handles AboutVECTOToolStripMenuItem1.Click
        AboutBox.ShowDialog()
    End Sub
    'Move job/cycle file up or down in list view
    Private Sub MoveItem(ByRef listView As ListView, moveUp As Boolean)
        Dim x As Integer
        Dim y As Integer
        Dim y1 As Integer
        Dim items() As String
        Dim check() As Boolean
        Dim index() As Integer
        Dim listViewItem As ListViewItem

        If _guIlocked Then Exit Sub

        'Cache Selected Items
        y1 = listView.SelectedItems.Count - 1
        ReDim items(y1)
        ReDim check(y1)
        ReDim index(y1)
        y = 0
        For Each x In listView.SelectedIndices
            items(y) = listView.Items(x).SubItems(0).Text
            check(y) = listView.Items(x).Checked
            If moveUp Then
                If x = 0 Then Exit Sub
                index(y) = x - 1
            Else
                If x = listView.Items.Count - 1 Then Exit Sub
                index(y) = x + 1
            End If
            y += 1
        Next

        listView.BeginUpdate()

        'Delete Selected Items
        For Each listViewItem In listView.SelectedItems
            listViewItem.Remove()
        Next

        'Items select and Insert
        For y = 0 To y1
            If Not check(y) Then _genChecked += 1
            listViewItem = listView.Items.Insert(index(y), items(y))
            listViewItem.SubItems.Add(" ")
            listViewItem.Checked = check(y)
            listView.SelectedIndices.Add(index(y))
        Next

        listView.EndUpdate()
    End Sub
#Region "job/cycle file List - Context Menu"
    'Save List
    Private Sub SaveListToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles SaveListToolStripMenuItem.Click
        If TextFileBrowser.SaveDialog("") Then
            If _conMenTarJob Then
                _jobListView.SaveList(TextFileBrowser.Files(0))
            Else
                _cycleListView.SaveList(TextFileBrowser.Files(0))
            End If
        End If
    End Sub
    'Load List
    Private Sub LoadListToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles LoadListToolStripMenuItem.Click
        If _guIlocked Then Exit Sub
        If TextFileBrowser.OpenDialog("") Then
            If _conMenTarJob Then 'GEN
                _jobListView.LoadList(TextFileBrowser.Files(0))
                _genChecked = LvGEN.CheckedItems.Count
                UpdateJobTabText()
            Else 'DRI
                'Mode toggle 
                _cycleListView.LoadList(TextFileBrowser.Files(0))
            End If
        End If
    End Sub
    'Load Default List
    Private Sub LoadDefaultListToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles LoadDefaultListToolStripMenuItem.Click
        If _guIlocked Then Exit Sub
        If _conMenTarJob Then
            _jobListView.LoadList()
            _genChecked = LvGEN.CheckedItems.Count
            UpdateJobTabText()
        Else
            _cycleListView.LoadList()
        End If
    End Sub
    'Clear List
    Private Sub ClearListToolStripMenuItem_Click(sender As Object, e As EventArgs) _
        Handles ClearListToolStripMenuItem.Click
        If _guIlocked Then Exit Sub
        _conMenTarget.Items.Clear()
        If _conMenTarJob Then
            _genChecked = LvGEN.CheckedItems.Count
            UpdateJobTabText()
        End If
    End Sub
    'VECTO Start button - Calls VECTO_Launcher or aborts calculation

    Private Sub btStartV3_Click(sender As Object, e As EventArgs) Handles btStartV3.Click
        If Not VectoWorkerV3.IsBusy Then
            'Save Lists for Crash
            SaveFileLists()

            LvGEN.SelectedItems.Clear()

            If LvGEN.CheckedItems.Count = 0 Then
                GUIMsg(MessageType.Err, "No job file selected!")
                Exit Sub
            End If

            Status("Launching VECTO ...")
            JobFileList.Clear()
            JobFileList.AddRange(
                From listViewItem As ListViewItem In LvGEN.CheckedItems.Cast (Of ListViewItem)()
                                    Select fFileRepl = FileRepl(listViewItem.SubItems(0).Text))

            SetOptions()
            Cfg.Save()
            ClearMsg()

            LockGUI(True)
            btStartV3.Enabled = True
            btStartV3.Text = "STOP"
            btStartV3.Image = My.Resources.Stop_icon

            ToolStripProgBarOverall.Value = 0
            ToolStripProgBarOverall.Style = ProgressBarStyle.Continuous
            ToolStripProgBarOverall.Visible = True

            VectoWorkerV3.RunWorkerAsync()
        Else
            btStartV3.Enabled = False
            btStartV3.Text = "Aborting..."
            btStartV3.Image = My.Resources.Play_icon_gray
            VectoWorkerV3.CancelAsync()
        End If
    End Sub


    Private Sub VectoWorkerV3_OnDoWork(theSender As Object, e As DoWorkEventArgs)
        Dim sender As BackgroundWorker = TryCast(theSender, BackgroundWorker)
        If sender Is Nothing Then Exit Sub

        AllowSleepOff()

        Dim sumFileWriter As FileOutputWriter = New FileOutputWriter(JobFileList(0))
        Dim sumWriter As SummaryDataContainer = New SummaryDataContainer(sumFileWriter)
        Dim jobContainer As JobContainer = New JobContainer(sumWriter)

        Dim mode As ExecutionMode
        If Cfg.DeclMode Then
            mode = ExecutionMode.Declaration
        Else
            mode = ExecutionMode.Engineering
            Physics.AirDensity = Cfg.AirDensity.SI (Of KilogramPerCubicMeter)()
        End If

        'dictionary of run-identifiers to fileWriters (used for output directory of modfile)
        Dim fileWriters As Dictionary(Of Integer, FileOutputWriter) = New Dictionary(Of Integer, FileOutputWriter)

        'list of finished runs
        Dim finishedRuns As List(Of Integer) = New List(Of Integer)
        For Each jobFile As String In JobFileList
            Try
                sender.ReportProgress(0,
                                      New VectoProgress _
                                         With {.Target = "ListBox", .Message = "Reading File " + jobFile,
                                         .Link = jobFile})

                Dim extension As String = Path.GetExtension(jobFile)
                Dim input As IInputDataProvider = Nothing
                Select Case extension
                    Case VectoCore.Configuration.Constants.FileExtensions.VectoJobFile
                        input = JSONInputDataFactory.ReadJsonJob(jobFile)
                    Case ".xml"
                        Dim xDocument As XDocument = xDocument.Load(jobFile)
                        Dim rootNode As String = If(xDocument Is Nothing, "", xDocument.Root.Name.LocalName)
                        Select Case rootNode
                            Case XMLNames.VectoInputEngineering
                                input = New XMLEngineeringInputDataProvider(jobFile, True)
                            Case XMLNames.VectoInputDeclaration
                                input = New XMLDeclarationInputDataProvider(XmlReader.Create(jobFile), True)
                        End Select
                End Select

                If input Is Nothing Then
                    sender.ReportProgress(0,
                                          New VectoProgress _
                                             With {.Target = "ListBoxError",
                                             .Message = "No Input Provider for job: " + jobFile})
                    Continue For
                End If

                Dim fileWriter As FileOutputWriter = New FileOutputWriter(jobFile)

                Dim runsFactory As SimulatorFactory = New SimulatorFactory(mode, input, fileWriter)
                runsFactory.WriteModalResults = Cfg.ModOut
                runsFactory.ModalResults1Hz = Cfg.Mod1Hz
                runsFactory.Validate = cbValidateRunData.Checked
                runsFactory.ActualModalData = cbActVmod.Checked

                For Each runId As Integer In jobContainer.AddRuns(runsFactory)
                    fileWriters.Add(runId, fileWriter)
                Next


                sender.ReportProgress(0,
                                      New VectoProgress _
                                         With {.Target = "ListBox",
                                         .Message = "Finished Reading Data for job: " + jobFile})