-pulizia codice script

This commit is contained in:
Demetrio Cassarino
2025-03-12 09:47:40 +01:00
parent 1a5d6a5ab5
commit c7debc8c31
13 changed files with 373 additions and 195 deletions
+178 -177
View File
@@ -12,6 +12,22 @@ Public Class ScriptWindowVM
Public textChangedTimer As DispatcherTimer
#Region "Script Color"
' Dizionario con Regex Precompilate e Colori Associati
Private patterns As New Dictionary(Of Regex, System.Windows.Media.Color) From {
{RegexM.KeywordRegex, ColorScriptM.KeywordColor},
{RegexM.ValueRegex, ColorScriptM.ValueColor},
{RegexM.FunctionRegex, ColorScriptM.FunctionColor},
{RegexM.InfoRegex, ColorScriptM.InfoColor},
{RegexM.EgtRegex, ColorScriptM.EgtColor},
{RegexM.BracketRegex, ColorScriptM.BracketColor},
{RegexM.TextRegex, ColorScriptM.TextColor},
{RegexM.NumberRegex, ColorScriptM.NumberColor}
}
#End Region ' Script Color
Private m_sNameFile As String = String.Empty
Public Property sNameFile As String
Get
@@ -274,16 +290,10 @@ Public Class ScriptWindowVM
#Region "METHODS"
Public Function SaveProject() As Boolean
Dim sFile As String = ""
Dim sFileName As String = ""
' Se nome vuoto, assegno "New"
If String.IsNullOrWhiteSpace(m_sNameFile) Then
sFile = "New.lua"
Else
sFile = m_sNameFile & ".lua"
End If
' Eventuale sistemazione estensione
' Determina il nome del file di default
Dim sFile As String = If(String.IsNullOrWhiteSpace(m_sNameFile), "New.lua", $"{m_sNameFile}.lua")
sFile = IO.Path.ChangeExtension(sFile, "lua")
' Assegnazione nome file con dialogo
Dim SaveFileDialog As New EgtManageFileDialogV(Application.Current.MainWindow, New EgtManageFileDialogVM()) With {
.Title = EgtMsg(110013), ' Salva
@@ -295,200 +305,177 @@ Public Class ScriptWindowVM
.OverwritePrompt = True,
.Mode = 1
}
If SaveFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
If Path.GetExtension(SaveFileDialog.SafeFileName).Equals(String.Empty) Then
sFileName = SaveFileDialog.InitialDirectory & "\" & SaveFileDialog.SafeFileName & SaveFileDialog.SelFilter.sExstension.Trim("*"c)
Else
sFileName = SaveFileDialog.InitialDirectory & "\" & SaveFileDialog.SafeFileName
End If
' Mostra la finestra di dialogo e ottieni il percorso del file selezionato
Dim sFileName As String = String.Empty
If SaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim fileExtension = IO.Path.GetExtension(SaveFileDialog.SafeFileName)
sFileName = IO.Path.Combine(SaveFileDialog.InitialDirectory,
SaveFileDialog.SafeFileName & If(String.IsNullOrEmpty(fileExtension),
SaveFileDialog.SelFilter.sExstension.Trim("*"c), String.Empty))
End If
' Verifica se il nome del file è stato selezionato
If String.IsNullOrWhiteSpace(sFileName) Then Return False
' Salva il progetto e scrive lo script Lua
Dim bOk = Map.refSceneHostVM.SaveProj(sFileName)
WriteTextScriptLua(sFileName)
' Imposto stato gestione mouse diretto della scena a nessuno
' Imposta lo stato della scena
Map.refSceneHostVM.MainScene.SetStatusNull()
Return True
Return bOk
End Function
Private Sub WriteTextScriptLua(sFileName As String)
Dim sFileScript As String = RichTextBox(sFileName)
File.WriteAllText(sFileName, sFileScript)
If String.IsNullOrWhiteSpace(sFileName) Then Return ' Validazione input
Dim sFileScript As String = RichTextBox(sFileName) ' Ottieni contenuto da RichTextBox
File.WriteAllText(sFileName, sFileScript, Encoding.UTF8) ' Salva il file con codifica UTF-8
End Sub
Private Sub SaveScript(sPathFileScript As String, sRichTextParagraph As String)
Map.refSceneHostVM.SaveProj(sPathFileScript)
File.WriteAllText(sPathFileScript, sRichTextParagraph, Encoding.UTF8)
If String.IsNullOrWhiteSpace(sPathFileScript) OrElse String.IsNullOrWhiteSpace(sRichTextParagraph) Then Return ' Validazione input
Map.refSceneHostVM.SaveProj(sPathFileScript) ' Salva il progetto nel percorso specificato
File.WriteAllText(sPathFileScript, sRichTextParagraph, Encoding.UTF8) ' Salva il contenuto con codifica UTF-8
End Sub
Public Function RichTextBox(sPathFileScript As String) As String
' Recupero richtextbox
' Recupero il RichTextBox e il FlowDocument
Dim myRichTextBox As RichTextBox = Map.refScriptWindowV.sNameFile_RichTxBx
' Recupero flowdocument
Dim myFlowDoc As FlowDocument = Map.refScriptWindowV.FDocumentFile
' Assegno al richtextbox il flowdocument
' Cancella il contenuto del documento e assegna un nuovo FlowDocument
myRichTextBox.Document.Blocks.Clear()
myRichTextBox.Document = myFlowDoc
' Leggo il richtextbox dall'inizio alla fine
' Ottiene il testo completo del documento
Dim textRange As New TextRange(myRichTextBox.Document.ContentStart, myRichTextBox.Document.ContentEnd)
Return textRange.Text
End Function
Private Sub CreateFontSizeList()
For Size As Integer = 8 To 20
If Size Mod 2 = 0 Then
m_nFontSizeList.Add(Size)
End If
Next
' Aggiunge solo font-size pari alla lista, con un semplice iteratore
m_nFontSizeList.AddRange(Enumerable.Range(8, 13).Where(Function(size) size Mod 2 = 0))
End Sub
''' <summary>
''' Funzione che permette di cambiare la dimensione della font
''' </summary>
''' <param name="nSelFontSize">fontsize selezionata</param>
Private Sub ChangeFontSize(nSelFontSize As Integer)
If nSelFontSize = GDB_ID.NULL Then Return
Dim pixelSize As Double = Convert.ToDouble(nSelFontSize) * (96 / 72)
Dim textRange = New TextRange(Map.refScriptWindowV.sNameFile_RichTxBx.Selection.Start, Map.refScriptWindowV.sNameFile_RichTxBx.Selection.[End])
Dim pixelSize As Double = nSelFontSize * (96.0 / 72.0)
Dim textRange = New TextRange(Map.refScriptWindowV.sNameFile_RichTxBx.Selection.Start, Map.refScriptWindowV.sNameFile_RichTxBx.Selection.End)
textRange.ApplyPropertyValue(TextElement.FontSizeProperty, pixelSize)
End Sub
Private Sub CreateFontFamilyList()
For Each FontFamily As FontFamily In Fonts.SystemFontFamilies
m_sFontFamilyList.Add(FontFamily)
Next
' Aggiunge direttamente tutte le famiglie di font alla lista
m_sFontFamilyList.AddRange(Fonts.SystemFontFamilies)
End Sub
Private Sub ChangeFontFamily(sSelFontFamily As FontFamily)
If sSelFontFamily Is Nothing Then Return
Dim fontFamily As String = sSelFontFamily.ToString()
Dim textRange = New TextRange(Map.refScriptWindowV.sNameFile_RichTxBx.Selection.Start, Map.refScriptWindowV.sNameFile_RichTxBx.Selection.[End])
textRange.ApplyPropertyValue(TextElement.FontFamilyProperty, fontFamily)
Dim textRange = New TextRange(Map.refScriptWindowV.sNameFile_RichTxBx.Selection.Start, Map.refScriptWindowV.sNameFile_RichTxBx.Selection.End)
textRange.ApplyPropertyValue(TextElement.FontFamilyProperty, sSelFontFamily)
End Sub
Friend Sub SetToolbar()
Dim textRange = New TextRange(Map.refScriptWindowV.sNameFile_RichTxBx.Selection.Start, Map.refScriptWindowV.sNameFile_RichTxBx.Selection.[End])
Dim fontFamily As Object = textRange.GetPropertyValue(TextElement.FontFamilyProperty)
SetSelFontFamily(fontFamily)
Dim fontSize As Object = textRange.GetPropertyValue(TextElement.FontSizeProperty)
SetSelFontSize(fontSize)
Dim textRange As New TextRange(Map.refScriptWindowV.sNameFile_RichTxBx.Selection.Start, Map.refScriptWindowV.sNameFile_RichTxBx.Selection.[End])
If Not String.IsNullOrEmpty(textRange.Text) Then
m_bBoldIsChecked = textRange.GetPropertyValue(TextElement.FontWeightProperty).Equals(FontWeights.Bold)
m_bItalicIsChecked = textRange.GetPropertyValue(TextElement.FontStyleProperty).Equals(FontStyles.Italic)
m_bUnderlineChecked = textRange.GetPropertyValue(Inline.TextDecorationsProperty).Equals(TextDecorations.Underline)
' Recupera font e dimensione
SetSelFontFamily(textRange.GetPropertyValue(TextElement.FontFamilyProperty))
SetSelFontSize(textRange.GetPropertyValue(TextElement.FontSizeProperty))
If Not String.IsNullOrWhiteSpace(textRange.Text) Then
' Recupera proprietà di formattazione (Bold, Italic, Underline)
m_bBoldIsChecked = Equals(textRange.GetPropertyValue(TextElement.FontWeightProperty), FontWeights.Bold)
m_bItalicIsChecked = Equals(textRange.GetPropertyValue(TextElement.FontStyleProperty), FontStyles.Italic)
m_bUnderlineChecked = Equals(textRange.GetPropertyValue(Inline.TextDecorationsProperty), TextDecorations.Underline)
End If
m_bLeftIsChecked = textRange.GetPropertyValue(FlowDocument.TextAlignmentProperty).Equals(TextAlignment.Left)
m_bCenterIsChecked = textRange.GetPropertyValue(FlowDocument.TextAlignmentProperty).Equals(TextAlignment.Center)
m_bJustifyIsChecked = textRange.GetPropertyValue(FlowDocument.TextAlignmentProperty).Equals(TextAlignment.Justify)
' Recupera proprietà di allineamento
Dim alignment = textRange.GetPropertyValue(FlowDocument.TextAlignmentProperty)
m_bLeftIsChecked = Equals(alignment, TextAlignment.Left)
m_bCenterIsChecked = Equals(alignment, TextAlignment.Center)
m_bJustifyIsChecked = Equals(alignment, TextAlignment.Justify)
End Sub
Public Sub InsertText(ByVal sRichTextBox As RichTextBox, ByVal content As String)
If Not String.IsNullOrEmpty(content) Then
sRichTextBox?.BeginChange()
' Verifica nullità e contenuto non vuoto
If String.IsNullOrWhiteSpace(content) OrElse sRichTextBox Is Nothing Then Return
If Not String.IsNullOrEmpty(sRichTextBox.Selection.Text) Then
sRichTextBox.Selection.Text = String.Empty
End If
' Sospende gli aggiornamenti visivi per migliorare le prestazioni
sRichTextBox.BeginChange()
Try
' Rimuove il testo selezionato (se esiste)
If Not String.IsNullOrEmpty(sRichTextBox.Selection.Text) Then sRichTextBox.Selection.Text = String.Empty
Dim textPointer As TextPointer = sRichTextBox.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward)
sRichTextBox.CaretPosition.InsertTextInRun(content)
sRichTextBox.CaretPosition = textPointer
' Inserisce il contenuto e riposiziona il cursore
Dim textPointer As TextPointer = sRichTextBox.CaretPosition
textPointer.InsertTextInRun(content)
sRichTextBox.CaretPosition = textPointer.GetPositionAtOffset(content.Length, LogicalDirection.Forward)
Finally
' Ripristina gli aggiornamenti visivi
sRichTextBox.EndChange()
' Imposta il focus sulla RichTextBox
Keyboard.Focus(sRichTextBox)
End If
End Try
End Sub
Public Sub SyntaxHighlighting(rtb As RichTextBox)
Dim textRange As New TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd)
Dim text As String = textRange.Text
' Sospendere gli aggiornamenti visivi per migliorare le prestazioni
rtb.BeginChange()
Dim keywords As String() = {"local ", "function", "end", " if ", " then ", " else ", "for ", "while", "do", "return", "true", "nil", "_ENV", "_G"}
Dim ValueKey As String() = {".CMP_Draw", ".N1", ".V1", ".T1", ".Npar", ".Nome", ".INFO", ".WithInt", ".CMP", ".GLOB", ".ROOT"}
Try
' Recupera il testo dalla RichTextBox
Dim textRange As New TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd)
Dim text As String = textRange.Text
Dim keywordColor As Color = Colors.Blue
Dim commentColor As Color = Colors.Green
Dim valueColor As Color = Colors.MediumSeaGreen
Dim egtColor As Color = Colors.Gold
Dim infoColor As New System.Windows.Media.Color With {
.A = 255,
.R = 206,
.G = 145,
.B = 120
}
Dim functionColor As Color = Colors.BlueViolet
' Applicare evidenziazione per ogni regex nel dizionario
For Each kvp In patterns
Dim regex As Regex = kvp.Key
Dim color As Color = kvp.Value
Dim pattern As String = "(?<=function\s)[^(]+"
Dim pattern2 As String = "'([^']*)'"
Dim pattern3 As String = "(?<!')\bEgt\w*\b(?!')"
' Evidenzia le corrispondenze
Dim matches As MatchCollection = regex.Matches(text)
For Each match As Match In matches
HighlightText(rtb, match.Index, match.Length, color)
Next
Next
' Instantiate the regular expression object.
Dim regex As New Regex(pattern, RegexOptions.IgnoreCase)
Dim regex2 As New Regex(pattern2, RegexOptions.IgnoreCase)
Dim regex3 As New Regex(pattern3, RegexOptions.IgnoreCase)
' Ottieni tutte le corrispondenze
Dim matches As MatchCollection = regex.Matches(text)
Dim matches2 As MatchCollection = regex2.Matches(text)
Dim matches3 As MatchCollection = regex3.Matches(text)
' Itera attraverso tutte le corrispondenze e stampale
For Each match As Match In matches
If match.Length > 2 Then HighlightText(rtb, text, " " & match.ToString(), functionColor)
Next
' Evidenzia le info
For Each match2 As Match In matches2
If match2.Length > 2 Then HighlightText(rtb, text, match2.ToString(), infoColor)
Next
' Evidenzia le parole che iniziano per Egt
For Each match3 As Match In matches3
If match3.Length > 2 Then HighlightText(rtb, text, match3.ToString(), egtColor)
Next
' Evidenzia le parole chiave
For Each valueItem In ValueKey
HighlightText(rtb, text, valueItem, valueColor)
Next
' Evidenzia le value chiave
For Each keyword In keywords
HighlightText(rtb, text, keyword, keywordColor)
Next
' Evidenzia i commenti
HighlightText(rtb, text, "--", commentColor, True)
' Evidenzia commenti (esempio di commento Lua: "--")
Dim commentMatches = patterns.FirstOrDefault(Function(p) p.Key.ToString().Contains("--"))
If commentMatches.Key IsNot Nothing Then
HighlightComments(rtb, text, "--", ColorScriptM.CommentColor)
End If
Finally
' Riprendere gli aggiornamenti visivi
rtb.EndChange()
End Try
End Sub
Private Sub HighlightText(rtb As RichTextBox, text As String, word As String, color As Color, Optional isComment As Boolean = False)
Private Sub HighlightText(rtb As RichTextBox, startIndex As Integer, length As Integer, color As Color)
Dim startPointer As TextPointer = GetTextPosition(rtb.Document.ContentStart, startIndex)
Dim endPointer As TextPointer = GetTextPosition(startPointer, length)
Dim range As New TextRange(startPointer, endPointer)
range.ApplyPropertyValue(TextElement.ForegroundProperty, New SolidColorBrush(color))
End Sub
Private Sub HighlightComments(rtb As RichTextBox, text As String, commentSymbol As String, color As Color)
Dim startIndex As Integer = 0
While startIndex < text.Length
If text.Contains(word) Then
startIndex = text.IndexOf(word, startIndex)
If startIndex = -1 Then Exit While
startIndex = text.IndexOf(commentSymbol, startIndex)
If startIndex = -1 Then Exit While
Dim startPointer As TextPointer = GetTextPosition(rtb.Document.ContentStart, startIndex)
Dim endPointer As TextPointer = GetTextPosition(startPointer, word.Length)
Dim endIndex As Integer = text.IndexOf(Environment.NewLine, startIndex)
If endIndex = -1 Then endIndex = text.Length
Dim range As New TextRange(startPointer, endPointer)
range.ApplyPropertyValue(TextElement.ForegroundProperty, New SolidColorBrush(color))
If isComment Then
Dim commentEndIndex As Integer = text.IndexOf(Environment.NewLine, startIndex)
If commentEndIndex = -1 Then commentEndIndex = text.Length
endPointer = GetTextPosition(startPointer, commentEndIndex - startIndex)
range = New TextRange(startPointer, endPointer)
range.ApplyPropertyValue(TextElement.ForegroundProperty, New SolidColorBrush(color))
End If
End If
startIndex += word.Length
HighlightText(rtb, startIndex, endIndex - startIndex, color)
startIndex = endIndex
End While
End Sub
Private Function GetTextPosition(start As TextPointer, position As Integer) As TextPointer
Dim navigator As TextPointer = start
While navigator IsNot Nothing AndAlso position > 0
If navigator.GetPointerContext(LogicalDirection.Forward) = TextPointerContext.Text Then
Dim context = navigator.GetPointerContext(LogicalDirection.Forward)
If context = TextPointerContext.Text Then
Dim run As String = navigator.GetTextInRun(LogicalDirection.Forward)
Dim count As Integer = Math.Min(run.Length, position)
navigator = navigator.GetPositionAtOffset(count)
@@ -497,6 +484,7 @@ Public Class ScriptWindowVM
navigator = navigator.GetPositionAtOffset(1)
End If
End While
Return navigator
End Function
@@ -511,20 +499,23 @@ Public Class ScriptWindowVM
AddHandler textChangedTimer.Tick, AddressOf OnTextChangedTimerTick
End If
textChangedTimer.Stop()
textChangedTimer.Start()
textChangedTimer?.Stop()
textChangedTimer?.Start()
End Sub
Public Sub Tabulation(ByVal sRichTextBox As RichTextBox)
' Ottieni la posizione corrente del cursore
Dim caretPosition As TextPointer = sRichTextBox.CaretPosition
If sRichTextBox Is Nothing Then Return ' Verifica nullità dell'oggetto
' Inserisci un carattere di tabulazione (3 spazi)
Dim tabString As String = " "
Dim run As New Run(tabString)
Dim textRange As New TextRange(caretPosition, caretPosition)
textRange.Text = tabString
' Aggiorna la posizione del cursore
sRichTextBox.CaretPosition = textRange.End
' Gestisci il punto di inserimento del cursore
Dim caretPosition As TextPointer = sRichTextBox.CaretPosition
If caretPosition IsNot Nothing Then
caretPosition.InsertTextInRun(tabString)
' Aggiorna la posizione del cursore dopo il testo inserito
sRichTextBox.CaretPosition = caretPosition.GetPositionAtOffset(tabString.Length, LogicalDirection.Forward)
End If
End Sub
#End Region ' Methods
@@ -552,13 +543,15 @@ Public Class ScriptWindowVM
End Property
Public Sub Conferma()
' Recupero il file script
Dim sFileScript As String = RichTextBox(Map.refMainWindowVM.MainWindowM.sTempDir & "\" & m_sNameFile & ".lua")
' Salvo il file
SaveScript(Map.refMainWindowVM.MainWindowM.sTempDir & "\" & m_sNameFile & ".lua", sFileScript)
' Eseguo il file
EgtLuaExecFile(Map.refMainWindowVM.MainWindowM.sTempDir & "\" & m_sNameFile & ".lua")
' Imposto stato gestione mouse diretto della scena a nessuno
' Genera il percorso del file script
Dim scriptFilePath As String = IO.Path.Combine(Map.refMainWindowVM.MainWindowM.sTempDir, $"{m_sNameFile}.lua")
' Recupera il contenuto del file script
Dim sFileScript As String = RichTextBox(scriptFilePath)
' Salva il file script
SaveScript(scriptFilePath, sFileScript)
' Esegue il file script
EgtLuaExecFile(scriptFilePath)
' Imposta lo stato della gestione mouse diretto della scena a "nessuno"
Map.refSceneHostVM.MainScene.SetStatusNull()
End Sub
@@ -611,31 +604,39 @@ Public Class ScriptWindowVM
Public Sub TextColor()
' Recupero colori custom
Dim Col As New Color3d(10, 122, 150)
Dim sCustomColors As String = ""
Dim defaultColor As New Color3d(10, 122, 150)
Dim sCustomColors As String = String.Empty
GetMainPrivateProfileString(S_COLORS, K_CUSTOMCOLORS, "", sCustomColors)
Dim CustomColors() As String = sCustomColors.Split(","c)
Dim nCustomColors As New List(Of Integer)
For Each Color In CustomColors
Dim nColor As Integer
If Integer.TryParse(Color, nColor) Then
nCustomColors.Add(nColor)
End If
Next
' Creo dialogo colori
Dim ColorDlg As New EgtColorPickerV(Application.Current.MainWindow, New EgtColorPickerVM()) With {
.CustomColors = nCustomColors.ToArray(),
.Color = Col.ToColor()
' Parsing dei colori custom in una lista di interi
Dim nCustomColors = sCustomColors.Split(","c).
Select(Function(color)
Dim nColor As Integer
Return If(Integer.TryParse(color, nColor), nColor, Nothing)
End Function).
Where(Function(nColor) nColor > 0).Cast(Of Integer)().ToList()
' Configurazione dialogo colori
Dim colorDialog As New EgtColorPickerV(Application.Current.MainWindow, New EgtColorPickerVM()) With {
.CustomColors = nCustomColors.ToArray(),
.Color = defaultColor.ToColor()
}
' Visualizzo dialogo
If ColorDlg.ShowDialog() <> Windows.Forms.DialogResult.OK Then Return
'Recupero colore scelto
Dim selColor As New SolidColorBrush(System.Windows.Media.Color.FromArgb(CByte(ColorDlg.Color.A),
CByte(ColorDlg.Color.R),
CByte(ColorDlg.Color.G),
CByte(ColorDlg.Color.B)))
Dim textRange = New TextRange(Map.refScriptWindowV.sNameFile_RichTxBx.Selection.Start, Map.refScriptWindowV.sNameFile_RichTxBx.Selection.[End])
textRange.ApplyPropertyValue(TextElement.ForegroundProperty, selColor)
' Visualizzo il dialogo e gestisco l'output
If colorDialog.ShowDialog() <> Windows.Forms.DialogResult.OK Then Return
' Conversione colore selezionato
Dim selectedColor As System.Windows.Media.Color = System.Windows.Media.Color.FromArgb(
CByte(colorDialog.Color.A),
CByte(colorDialog.Color.R),
CByte(colorDialog.Color.G),
CByte(colorDialog.Color.B)
)
Dim selColorBrush As New SolidColorBrush(selectedColor)
' Applicazione del colore al testo selezionato
Dim textRange As New TextRange(Map.refScriptWindowV.sNameFile_RichTxBx.Selection.Start, Map.refScriptWindowV.sNameFile_RichTxBx.Selection.End)
textRange.ApplyPropertyValue(TextElement.ForegroundProperty, selColorBrush)
End Sub
#End Region ' TextColorCmd