Sign in to follow this  
Followers 0
tonycst

How to get line number using stringregexp ?

29 posts in this topic

Search function is looking for every

;Layer:0

;Layer:1

etc

in the file, and then create listview item according to ;Layer:# found.

I need to insert some text into that file after seleced ;Layer:# listview item.

I dont seem to be able to figure out how to get the line number in which ;Layer:# was found.

Can anybody help ?

Thanks

$SourceRead = FileRead ($source) ;created by fileopendialog
        $res = StringRegExp($SourceRead, "(?im)^.*" & $SearchInput & ".*$", 3) ;i  have no clue how this pattern thing work
        If Not @error Then
            For $line In $res ;dont understand how this works
                $FileLine = "";I need to get line which shows where that ;layer: is found.
                GUICtrlCreateListViewItem($Line & "|" & $FileLine, $ListView); Creare selectable listviewitem
                Assign ("Found",$Found+1)
                _GUICtrlStatusBar_SetText ($StatusBar,$line)
            Next
            ResizeCollumns()
        EndIf

The only way i could do it is to use filereadline, but it will take forever because files can have hundreds od layer numbers abd be over 5mb size text file.

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

The code you provided is incomplete

Can you give a better example

  • The Full source (or a part that helps us understand better)
  • The output that you expect from that source.
Edited by PhoenixXL

My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Sorry

here is entire thing so far.

open attached text file. Rename it to gcode extension first :) (File remove)

#include <GUIConstantsEx.au3>
#include <EditConstants.au3>
#include <WindowsConstants.au3>
#include <File.au3>
#include <GuiListView.au3>
#include <ListviewConstants.au3>
#Include <GuiStatusBar.au3>
#include <StaticConstants.au3>

Opt("TrayOnEventMode",1)
Opt("TrayMenuMode",1+2)
TrayCreateItem("About")
TrayItemSetOnEvent(-1,"AboutFunction") ;function name
TrayCreateItem('')
TrayCreateItem('Exit')
TrayItemSetOnEvent(-1,"ExitFunction") ;function name
TraySetState()
#region ;Create GUI and its components
$MainGUI = GUICreate("G-Code Layer Modifier", 700, 420,-1,-1,$WS_MAXIMIZEBOX+$WS_SIZEBOX)
$StatusBar = _GUICtrlStatusBar_Create ($MainGUI,'','',$SBARS_SIZEGRIP)
GUIRegisterMsg($WM_SIZE, "MY_WM_SIZE")

GUICtrlCreateGroup("G-Code File", 5, 5, 390, 45)
GUICtrlSetResizing (-1,1)
$FilePath = GUICtrlCreateInput("", 90, 20, 300, 20)
GUICtrlSetResizing (-1,512)

GUICtrlCreateGroup("Layers Found", 5, 50, 210, 325)
$ListView = GUICtrlCreateListView("Layer|Line", 10, 65, 200, 305,'',$LVS_EX_GRIDLINES)
$OpenFile = GUICtrlCreateButton("Open G-Code ", 10, 20, 80, 20)
GUICtrlCreateGroup ("Selected Layer G-Code",400,50,295,325)
$Preview = GUICtrlCreateEdit ("",405,65,280,305)
ResizeCollumns()
GUICtrlSetResizing (-1,1)

#Region Changes Group
GUICtrlCreateGroup("Changes for remaining layers", 220, 50, 175, 165)
$NewNozzleTemp = GUICtrlCreateInput ("",360,70,30,20)
    GUICtrlCreateLabel ("Nozzle Temp Celcius",230,75,100,15)
$NewBedTemp = GUICtrlCreateInput ("",360,100,30,20)
    GUICtrlCreateLabel ("Bed Temp Celcius",230,105,100,15)
$NewCoolingFanSpeed = GUICtrlCreateInput ("",360,130,30,20)
    GUICtrlCreateLabel ("Cooling Fan Speed 0-255",230,135,120,25)
$NewSpeed = GUICtrlCreateInput ("",360,160,30,20)
    GUICtrlCreateLabel ("Print Speed %",230,165,100,15)
$NewFeedRate = GUICtrlCreateInput ("",360,190,30,20)
GUICtrlCreateLabel ("Filament Feed Rate %",230,195,110,15)

GUICtrlCreateGroup ("Pause and Resume",220,225,175,110)
$NewPauseResume = GUICtrlCreateCombo ("",350,240,40,15)
    GUICtrlSetData (-1,"Yes|No")
    GUICtrlCreateLabel ("Pause/Resume by User",225,245,120,20)
$MoveAxis = GUICtrlCreateCombo ("",350,260,40,20)
    GUICtrlSetData (-1,"Yes|No")
    GUICtrlCreateLabel ("Move Before Pause ?",225,265,105,15)
$MoveX = GUICtrlCreateInput ("",270,285,40,20)
GUICtrlSetTip (-1,"All Movement will be reversed beffore resumiugn print.")
    GUICtrlCreateLabel ("Move X",225,290,40,15)
$MoveY = GUICtrlCreateInput ("",350,285,40,20)
GUICtrlSetTip (-1,"All Movement will be reversed beffore resumiugn print.")
    GUICtrlCreateLabel ("Move Y",310,290,40,15)

$CustomCommand = GUICtrlCreateCombo ("",310,310,80,20)
    GUICtrlSetData (-1,"Yes|No")
    GUICtrlCreateLabel ("Custom Code",230,315,80,15)

$CopyContext = GUICtrlCreateContextMenu($ListView)
$Copy = GUICtrlCreateMenuItem("Copy This Text", $CopyContext)
$UpdateButton = GUICtrlCreateButton("Aply to selected Layer", 220, 340, 175, 30)
GUICtrlSetTip (-1,"Changes you apply to any Layer, will effect all layers that go after selected layer." & @CRLF & "If you need to restore changes in later layers, you have to select Layer you want to restore and enter old values")
GUICtrlSetResizing (-1,1)
#EndRegion Changes Group
#endregion
GUISetState(@SW_SHOW, $MainGUI)
While 1
    $msg = GUIGetMsg()
    If $msg = $GUI_EVENT_CLOSE Then
        Exit
    EndIf
    If $msg = $OpenFile Then
        $source =FileOpenDialog("Open G-Code file","","G-Code files(*.gcode)|(*.gco)|(*.g)") ;Open Gcode file
        If $source > "" Then
            GUICtrlSetData ($FilePath,$source)
        Else
            MsgBox(16,"Error","No file selected.")
        EndIf
        $Found = 0
        $SearchInput = ";Layer:"
        _GUICtrlListView_DeleteAllItems(GUICtrlGetHandle($ListView))
        _GUICtrlStatusBar_SetText ($StatusBar,"Searching")
        $SourceRead = FileRead ($source)
        $res = StringRegExp($SourceRead, "(?im)^.*" & $SearchInput & ".*$", 3)
        If Not @error Then
            For $line In $res
                $FileLine = "";I need to get line which shows where that layer is found.
                GUICtrlCreateListViewItem($Line & "|" & $FileLine, $ListView); Creare selectable listviewitem
                Assign ("Found",$Found+1)
                _GUICtrlStatusBar_SetText ($StatusBar,$line)
            Next
            ResizeCollumns()
        EndIf
        _GUICtrlStatusBar_SetText ($StatusBar,"Found " & $Found & " instances")
    EndIf
    If $msg = $UpdateButton Then
        ;Get seleced layer line number in the file and write to next line what ever codes have been entered.
        MsgBox (32,"G-Code Layer Modifier","Code Saved.")
    EndIf
    $GetClickedItem = GUICtrlRead($listview) ;Found layer number string seleted and line is read into edit control
    If $msg = $GetClickedItem Then
        If $GetClickedItem = 0 Then
        ElseIf $GetClickedItem = "" Then
        ElseIf $GetClickedItem > "" Then
            Local $Text
            $Text = "Need to show what is betwin curently selected layer and next"
            GUICtrlSetData ($Preview,$Text)
        EndIf
    EndIf
    If $msg = $Copy Then ClipPut (StringTrimRight(GUICtrlRead(GUICtrlRead($listview)),1))
WEnd
Func MY_WM_SIZE($hWnd, $iMsg, $iwParam, $ilParam) ;this function is for resizing status bar with the window
    _GUICtrlStatusBar_Resize($StatusBar)
    Return $GUI_RUNDEFMSG
EndFunc   ;==>MY_WM_SIZE
Func AboutFunction()
    GUISetState (@SW_DISABLE,$MainGUI)
    $AboutGUI = GUICreate ("Information",400,200,-1,-1,-1,-1,$MainGUI)
    GUICtrlCreateLabel ("G-Code Layer Modifier" & @CRLF & "Coded using AUTOIT V3",10,10,380,30,$SS_CENTER)
    GUICtrlCreateLabel ("",10,50,380,30,$SS_CENTER)
    GUICtrlCreateLabel ("Special thanks to: jchd from AUTOIT FORUM for faster search function." & @CRLF & 'Coded by tonycstech' ,10,80,380,200,$SS_CENTER)
    GUISetState (@SW_SHOW,$AboutGUI)
    ;MsgBox(32,"Information",'Special thanks to: jchd from AUTOIT FORUM for faster search function.' & @CRLF & 'Coded by Anatoliy Filippov' & @CRLF & 'If you have any questions, email me at tonycst@hotmail.com','',$MainGUI)
    While 1
        $msg1 = GUIGetMsg()
        If $msg1 = $GUI_EVENT_CLOSE Then ExitLoop
    WEnd
    GUIDelete ($AboutGUI)
    GUISetState (@SW_ENABLE,$MainGUI)
EndFunc
Func ResizeCollumns()
    _GUICtrlListView_SetColumnWidth($ListView, 0, 100)
    _GUICtrlListView_SetColumnWidth($ListView, 1, 95)
Endfunc
Func ExitFunction()
    Exit
EndFunc
Edited by tonycst

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

What is the font used in the text document,

As I don't see any Layer used in it, rather this is the text

Дух святой будет свами до скончания века
Апостолы спрасили признак кончины века и иссус сказал.

Так как кочина века это то до каких пор дух с нами то естесвенно он неможет 
быть взят до кончины века.

В оригинале вообще нет никакого напоминания о взятии кого либо, так что
недумайте быть вяты до пришествия. так как ангелы соберут избранных только тогда когда придёт
Христос, посредством чего Он и убьёт антихриста.
Edited by PhoenixXL

My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

Share this post


Link to post
Share on other sites

Sorry, gave wrong document.

Test.txt

Share this post


Link to post
Share on other sites

I tried to do

$SourceRead = FileRead ($source)
        $TotalLinesToRead = _FileCountLines ($source)
        For $lineToRead=1 to $TotalLinesToRead
            $SourceReadLine = FileReadLine ($source,$lineToRead)
            If StringInStr ($SourceReadLine,";Layer:") > 0 Then GUICtrlCreateListViewItem($SourceReadLine & "|" & $lineToRead, $ListView); Creare selectable listviewitem
        Next

but it takes forever because it read file every time it loops until the end.

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

If you read line by line it would take time, but in this case file operations would be better rather than regular expressions .

Here we go

#include <Array.au3>

$SourceRead = FileRead ("Test.txt") ;created by fileopendialog

$aLayers = FileReadToArray("Test.txt")
$aLineNumber = _ArrayFindAll($aLayers, ";Layer:", 0, 0, 0, 1)

For $i = 0 To UBound($aLineNumber) - 1
    ConsoleWrite($aLayers[$aLineNumber[$i]] & @TAB & "LineNo.: " & $aLineNumber[$i] + 1 & @CRLF)
Next

Regards :)

Edited by PhoenixXL
1 person likes this

My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

Share this post


Link to post
Share on other sites

Had to update autoit for FileReadToArray to work.

Thanks.

I wish i would understand how you did it, but all i understand is how to modify it :)

Share this post


Link to post
Share on other sites

The regex way remains faster than the file operating way, even with an incomplete checking

#include <Array.au3>

$hTimer = TimerInit()
$file = FileRead("Test.txt")
$lines = StringRegExp($file, '(?m)(^.*)\R?', 3)
$n = UBound($lines)
Dim $array[$n][2], $k
For $i = 0 to $n-1
   If StringRegExp($lines[$i], '(?i);layer') Then
       $array[$k][0] = $i+1          ; line number
       $array[$k][1] = $lines[$i]   ; line content
       $k += 1
   EndIf
Next
Redim $array[$k][2]   
ConsoleWrite(TimerDiff($hTimer)/1000 & @crlf)
;_ArrayDisplay($array)
Sleep(100)

$hTimer = TimerInit()
$SourceRead = FileRead ("Test.txt") ;created by fileopendialog
$aLayers = FileReadToArray("Test.txt")
$aLineNumber = _ArrayFindAll($aLayers, ";Layer:", 0, 0, 0, 1)
ConsoleWrite(TimerDiff($hTimer)/1000 & @crlf)

;_ArrayDisplay($aLineNumber)
;For $i = 0 To UBound($aLineNumber) - 1
 ;   ConsoleWrite($aLayers[$aLineNumber[$i]] & @TAB & "LineNo.: " & $aLineNumber[$i] + 1 & @CRLF)
;Next

Share this post


Link to post
Share on other sites

No, if you check correctly _ArrayFindAll takes up all the time, due to its multifunctional capability

#include <Array.au3>

$file = FileRead("Test.txt")
$lines = StringRegExp($file, '(?m)(^.*)\R?', 3)
$n = UBound($lines)
Local $array[$n][2], $k
$hTimer = TimerInit()
For $i = 0 to $n-1
   If StringRegExp($lines[$i], '(?i);layer') Then
       $array[$k][0] = $i+1          ; line number
       $array[$k][1] = $lines[$i]   ; line content
       $k += 1
   EndIf
Next
Redim $array[$k][2]
ConsoleWrite(TimerDiff($hTimer) & @crlf)
Sleep(100)


$aLayers = FileReadToArray("Test.txt")
$hTimer = TimerInit()
$aLineNumber = _ArrayFindAll($aLayers, ";Layer:", 0, 0, 0, 1)
ConsoleWrite(TimerDiff($hTimer) & @crlf)

But if speed is more concerned the following would be more efficient and its faster than RegExp

#include <Array.au3>

$hTimer = TimerInit()
$file = FileRead("Test.txt")
$lines = StringRegExp($file, '(?m)(^.*)\R?', 3)
$n = UBound($lines)
Dim $array[$n][2], $k
For $i = 0 to $n - 1
    If StringRegExp($lines[$i], '(?i);layer') Then
        $array[$k][0] = $i + 1 ; line number
        $array[$k][1] = $lines[$i] ; line content
        $k += 1
    EndIf
Next
Redim $array[$k][2]
ConsoleWrite(TimerDiff($hTimer) / 1000 & @crlf)
;_ArrayDisplay($array)
Sleep(100)

$hTimer = TimerInit()
$aLayers = FileReadToArray("Test.txt")
$aLineNumber = _ArrayFindAllEx($aLayers, ";Layer:", 7)
ConsoleWrite(TimerDiff($hTimer) / 1000 & @crlf)


Func _ArrayFindAllEx(ByRef $aArray, $String, $iCount)
    Local $iUbound = UBound($aArray), $aRet[$iUbound], $iIndex
    For $i = 0 To UBound($aArray) - 1
        If StringLeft($aArray[$i], $iCount) = $String Then
            $iIndex += 1
            $aRet[$iIndex - 1] = $i
        EndIf
    Next

    ReDim $aRet[$iIndex]
    Return $aRet
EndFunc   ;==>_ArrayFindAllEx

Note: the above comparisons are not sufficient to say which would be more faster. As cache comes in between that would create conflicting alternating results.

Sufficient is the fact that when Regular Expressions are used. They are used when we have to detect something that is based on a specific pattern that the file operations can't go with. From this perspective, file operations would be better.

 

Regards :)


My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

Share this post


Link to post
Share on other sites

What about:

Local $searchedLayer = 95

Local $search = ";LAYER:" & $searchedLayer
Local $s = FileRead("test.txt")
Local $good = StringRegExpReplace($s, "(?s)(" & $search & ".*)", "")
If @extended Then
    StringRegExpReplace($good, "\R", "")
    Local $LineNumber = @extended + 1
    ConsoleWrite($search & " found at line " & $LineNumber & @LF)
Else
    ConsoleWrite($search & " not found" & @LF)
EndIf

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

jhcd,

Awesome approach to find out LineNo. using Replace statements. :)

Hats off to you :bike: .

I was wondering about how to use replace in this case, and couldn't find the way. Thanks for the code. :D

Edited by PhoenixXL

My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

Share this post


Link to post
Share on other sites

And a non-StringRegExpReplace method. The idea is from >here.

Local $searchedLayer = 95
Local $search = ";LAYER:" & $searchedLayer

Local $s = FileRead("test.txt")
Local $iCharPos = StringInStr($s, $search)
If $iCharPos Then
    Local $good = StringLeft($s, $iCharPos)
    Local $LineNumber = StringLen(StringAddCR($good)) - $iCharPos + 1
    ConsoleWrite($search & " found at line " & $LineNumber & @LF)
Else
    ConsoleWrite($search & " not found" & @LF)
EndIf

Share this post


Link to post
Share on other sites

You guys all have contributed to my app getting out to public.

Users love it and its all thanks to you.

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=Icon.ico
#AutoIt3Wrapper_Outfile=G-Code Modifier.exe
#AutoIt3Wrapper_Res_Fileversion=1.0.0.7
#AutoIt3Wrapper_Res_Fileversion_AutoIncrement=p
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include <GUIConstantsEx.au3>
#include <EditConstants.au3>
#include <WindowsConstants.au3>
#include <File.au3>
#include <GuiListView.au3>
#include <ListviewConstants.au3>
#Include <GuiStatusBar.au3>
#include <StaticConstants.au3>
$Version = 1.04
$INI = (@ScriptDir & "\Settings.ini")
Opt("TrayOnEventMode",1)
Opt("TrayMenuMode",1+2)
TrayCreateItem("About")
TrayItemSetOnEvent(-1,"AboutFunction") ;function name
TrayCreateItem('')
TrayCreateItem('Exit')
TrayItemSetOnEvent(-1,"ExitFunction") ;function name
TraySetState()
TraySetToolTip ("G-Code Mofidier V" & $Version)
#region ;Create GUI and its components
$MainGUI = GUICreate("G-Code Layer Modifier", 400, 420,-1,-1,$WS_MAXIMIZEBOX+$WS_SIZEBOX)
$StatusBar = _GUICtrlStatusBar_Create ($MainGUI,'','',$SBARS_SIZEGRIP)
GUIRegisterMsg($WM_SIZE, "MY_WM_SIZE")

GUICtrlCreateGroup("G-Code File", 5, 5, 390, 45)
GUICtrlSetResizing (-1,1)
$Default = GUICtrlCreateInput ("Default Values", 90, 20, 160, 20)
GUICtrlSetState (-1,$GUI_DISABLE)
GUICtrlSetResizing (-1,512)
;GUICtrlSetFont (-1,10,800)
$Status = GUICtrlCreateInput ("Waiting for User..",250,20,140,20)

GUICtrlCreateGroup("Layers Found", 5, 50, 210, 325)
$ListView = GUICtrlCreateListView("Layer|Line", 10, 65, 200, 305,'',$LVS_EX_GRIDLINES)
$OpenFile = GUICtrlCreateButton("Open G-Code ", 10, 20, 80, 20)
ResizeCollumns()
GUICtrlSetResizing (-1,1)

#Region Changes Group
GUICtrlCreateGroup("Changes for remaining layers", 220, 50, 175, 165)
$NewNozzleTemp = GUICtrlCreateInput ("",360,70,30,20)
    GUICtrlCreateLabel ("Nozzle Temp Celcius",230,75,100,15)
$NewBedTemp = GUICtrlCreateInput ("",360,100,30,20)
    GUICtrlCreateLabel ("Bed Temp Celcius",230,105,100,15)
$NewCoolingFanSpeed = GUICtrlCreateInput ("",360,130,30,20)
    GUICtrlCreateLabel ("Cooling Fan Speed 0-255",230,135,120,25)
$NewSpeed = GUICtrlCreateInput ("",360,160,30,20)
    GUICtrlCreateLabel ("Print Speed %",230,165,100,15)
$NewFeedRate = GUICtrlCreateInput ("",360,190,30,20)
GUICtrlCreateLabel ("Filament Feed Rate %",230,195,110,15)

GUICtrlCreateGroup ("Pause and Resume",220,225,175,110)
$PauseResume = GUICtrlCreateCombo ("",350,240,40,15)
    GUICtrlSetData (-1,"Yes|No","No")
    GUICtrlCreateLabel ("Pause/Resume by User",225,245,120,20)
$MoveAxis = GUICtrlCreateCombo ("",350,260,40,20)
    GUICtrlSetData (-1,"Yes|No","No")
    GUICtrlCreateLabel ("Move Before Pause ?",225,265,105,15)
$MoveX = GUICtrlCreateInput ("0",270,285,40,20)
GUICtrlSetTip (-1,"All Movement will be reversed beffore resumiugn print.")
    GUICtrlCreateLabel ("Move X",225,290,40,15)
$MoveY = GUICtrlCreateInput ("0",350,285,40,20)
GUICtrlSetTip (-1,"All Movement will be reversed beffore resumiugn print.")
    GUICtrlCreateLabel ("Move Y",310,290,40,15)

$CustomCommand = GUICtrlCreateInput("",310,310,80,20)
    GUICtrlCreateLabel ("Custom Code",230,315,80,15)

$UpdateButton = GUICtrlCreateButton("Aply to selected Layer", 220, 340, 175, 30)
GUICtrlSetTip (-1,"Changes you apply to any Layer, will effect all layers that go after selected layer." & @CRLF & "If you need to restore changes in later layers, you have to select Layer you want to restore and enter old values")
GUICtrlSetResizing (-1,1)
#EndRegion Changes Group
#endregion
GUISetState(@SW_SHOW, $MainGUI)
While 1
    $msg = GUIGetMsg()
    If $msg = $GUI_EVENT_CLOSE Then
        Exit
    EndIf
    If $msg = $OpenFile Then
        $source = FileOpenDialog("Open G-Code file","","G-Code files(*.gcode)|(*.gco)|(*.g)") ;Open Gcode file
        If $source > "" Then
            Local $SourceRead,$Found,$SearchInput,$aLayers,$aLineNumber,$i ;these are local caz they are used in the modify function same way
            $SourceRead = FileRead ($source) ;created by fileopendialog
            $Found = 1
            $SearchInput = ";Layer:";This is what i am searching for in the entire file. Every one found is displayed.
            _GUICtrlListView_DeleteAllItems(GUICtrlGetHandle($ListView))
            _GUICtrlStatusBar_SetText ($StatusBar,"Searching")

            $DefBed = ""
            $DefNoz1 = ""
            $DefNoz2 = ""
            For $d = 0 to 24 ;Find defaut values:
                $SearchForDef = FileReadLine ($source,$d)
                If StringInStr ($SearchForDef,"M140 S") > 0 Then Assign ("DefBed",$SearchForDef);Found Bed temp
                If StringInStr ($SearchForDef,"M109 T0 S") > 0 Then Assign ("DefNoz1",$SearchForDef);Found BNozzle temp
                If StringInStr ($SearchForDef,"M109 T1 S") > 0 Then Assign ("DefNoz2",$SearchForDef);Found BNozzle temp
            Next
            $FinalNoz1 = StringTrimRight (StringTrimLeft ($DefNoz1,StringInStr($DefNoz1,"S")),7)
            $FinalNoz2 = StringTrimRight (StringTrimLeft ($DefNoz2,StringInStr($DefNoz2,"S")),7)
            $FinalBed = StringTrimRight (StringTrimLeft ($DefBed,StringInStr($DefBed,"S")),7)
            GUICtrlSetData ($Default,"Noz1 " & $FinalNoz1 & " Noz2 " & $FinalNoz2 &" Bed " & $FinalBed)

            $aLayers = FileReadToArray($source)
            $aLineNumber = _ArrayFindAll($aLayers, ";Layer:", 0, 0, 0, 1) ;Search for this array containing given text
            For $i = 0 To UBound($aLineNumber) - 1
                If StringInStr ($aLayers[$aLineNumber[$i]],";Layer:-") > 0 Then
                    GUICtrlCreateListViewItem("RAFT Layer" & $i & "|" & $aLineNumber[$i], $ListView)
                    Assign ("Found",$Found+1)
                Else
                    GUICtrlCreateListViewItem("Layer " & $Found & "|" & $aLineNumber[$i], $ListView)
                    Assign ("Found",$Found+1)
                EndIf
                If StringInStr ($aLayers[$aLineNumber[$i]],";Layer:-") > 0 Then
                    GUICtrlCreateListViewItem("Fill" & $i & "|" & $aLineNumber[$i], $ListView)
                EndIf
            Next
        _GUICtrlStatusBar_SetText ($StatusBar,"Found " & $Found & " Layer records")
        GUICtrlSetData ($Status,"Please select Layer")
        Else
            MsgBox(16,"Error","No file selected.")
        EndIf
    EndIf
    If $msg = $UpdateButton Then
        _ModifyLayer() ;go to function
    EndIf
    $GetClickedItem = GUICtrlRead($listview) ;Found layer number string seleted and line is read into edit control
    If $msg = $GetClickedItem Then
        If $GetClickedItem = 0 Then
        ElseIf $GetClickedItem = "" Then
        ElseIf $GetClickedItem > "" Then
            Local $Text,$Layer,$Line
            $Index = _GUICtrlListView_GetHotItem($listview) ;Get selected item index
            $Layer = _GUICtrlListView_GetItemText ($listview,$Index) ;Read 1st collumn for selected item
            $Line = _GUICtrlListView_GetItemText ($listview,$Index,1) ;Read 2nd collumn for selected item
            _GUICtrlStatusBar_SetText ($StatusBar,"Selected layer " & $Layer & " in line " & $Line)
            GUICtrlSetData ($Status,$Layer & " selected.")
        EndIf
    EndIf
WEnd
Func _ModifyLayer()
    If GUICtrlRead ($listview) = "" Then
        MsgBox(16,'Error','Please select layer first')
    Else
    ;file has to be reloaded each time after update is done
    Local $SourceRead,$Found,$SearchInput,$aLayers,$aLineNumber,$i
    ;M104 S Set Extruder Temperature (no wait till hot)
    ;M140 S Set bed temperature (no wait till hot)
    ;M106 S Fan speed 0-255
    ;M220 S set speed factor override percentage
    ;M221 S Set Feedrate/Extrusion percentage override
    $CurrentLine = 2 ;1 added top each time code is written so it writes it in next line rather then previous.
    If GUICtrlRead ($NewNozzleTemp) > "" Then
        _FileWriteToLine ($source,$Line+$CurrentLine,"M104 S" & GUICtrlRead ($NewNozzleTemp))
        Assign ("CurrentLine",$CurrentLine+1)
    EndIf
    If GUICtrlRead ($NewBedTemp) > "" Then
        _FileWriteToLine ($source,$Line+$CurrentLine,"M140 S" & GUICtrlRead ($NewBedTemp))
        Assign ("CurrentLine",$CurrentLine+1)
    EndIf
    If GUICtrlRead ($NewCoolingFanSpeed) > "" Then
        _FileWriteToLine ($source,$Line+$CurrentLine,"M106 S" & GUICtrlRead ($NewCoolingFanSpeed))
        Assign ("CurrentLine",$CurrentLine+1)
    EndIf
    If GUICtrlRead ($NewSpeed) > "" Then
        _FileWriteToLine ($source,$Line+$CurrentLine,"M220 S" & GUICtrlRead ($NewSpeed))
        Assign ("CurrentLine",$CurrentLine+1)
    EndIf
    If GUICtrlRead ($NewFeedRate) > "" Then
        _FileWriteToLine ($source,$Line+$CurrentLine,"M221 S" & GUICtrlRead ($NewFeedRate))
        Assign ("CurrentLine",$CurrentLine+1)
    EndIf
    If GUICtrlRead ($PauseResume) = "Yes" Then
        If GUICtrlRead ($MoveAxis) = "Yes" Then
            $X = GUICtrlRead ($MoveX)
            $Y = GUICtrlRead ($MoveY)
            _FileWriteToLine ($source,$Line+$CurrentLine,"M114") ;Remember current position
            Assign ("CurrentLine",$CurrentLine+1)
            _FileWriteToLine ($source,$Line+$CurrentLine,"G1 X" & $X & " Y" & $Y) ;Move away
            Assign ("CurrentLine",$CurrentLine+1)
            _FileWriteToLine ($source,$Line+$CurrentLine,"M0") ;pause
            Assign ("CurrentLine",$CurrentLine+1)
            _FileWriteToLine ($source,$Line+$CurrentLine,"G92") ;Move back to remembered position
            Assign ("CurrentLine",$CurrentLine+1)
        Else
            _FileWriteToLine ($source,$Line+$CurrentLine,"M0")
            Assign ("CurrentLine",$CurrentLine+1)
        EndIf
    EndIf
    If GUICtrlRead ($CustomCommand) > "" Then _FileWriteToLine ($source,$Line+$CurrentLine,GUICtrlRead ($CustomCommand))
    ;$MoveAxis
    ;$MoveX
    ;$MoveY
    ;$CustomCommand
    ;_FileWriteToLine ($source,$Line,@CRLF & "Code")
    MsgBox (32,"G-Code Layer Modifier","Code Saved. Code will now reload.")
    $SourceRead = FileRead ($source) ;created by fileopendialog
    $Found = 0
    $SearchInput = ";Layer:";This is what i am searching for in the entire file. Every one found is displayed.
    _GUICtrlListView_DeleteAllItems(GUICtrlGetHandle($ListView))
    _GUICtrlStatusBar_SetText ($StatusBar,"Searching")
    $aLayers = FileReadToArray($source)
    $aLineNumber = _ArrayFindAll($aLayers, ";Layer:", 0, 0, 0, 1)
    For $i = 0 To UBound($aLineNumber) - 1
        GUICtrlCreateListViewItem($aLayers[$aLineNumber[$i]] & "|" & $aLineNumber[$i], $ListView)
        Assign ("Found",$Found+1)
    Next
    _GUICtrlStatusBar_SetText ($StatusBar,"Found " & $Found & " Layer records")
    GUICtrlSetData ($Status,"Please select Layer")
    EndIf
EndFunc
Func MY_WM_SIZE($hWnd, $iMsg, $iwParam, $ilParam) ;this function is for resizing status bar with the window
    _GUICtrlStatusBar_Resize($StatusBar)
    Return $GUI_RUNDEFMSG
EndFunc   ;==>MY_WM_SIZE
Func AboutFunction()
    GUISetState (@SW_DISABLE,$MainGUI)
    $AboutGUI = GUICreate ("Information",400,200,-1,-1,-1,-1,$MainGUI)
    GUICtrlCreateLabel ("G-Code Layer Modifier" & $Version & @CRLF & "Coded using AUTOIT V3",10,10,380,30,$SS_CENTER)
    GUICtrlCreateLabel ("",10,50,380,30,$SS_CENTER)
    GUICtrlCreateLabel ("Special thanks to: jchd and PhoenixXL from AUTOIT FORUM for faster search function." & @CRLF & 'Coded by tonycstech' ,10,80,380,200,$SS_CENTER)
    GUISetState (@SW_SHOW,$AboutGUI)
    ;MsgBox(32,"Information",'Special thanks to: jchd from AUTOIT FORUM for faster search function.' & @CRLF & 'Coded by Anatoliy Filippov' & @CRLF & 'If you have any questions, email me at tonycst@hotmail.com','',$MainGUI)
    While 1
        $msg1 = GUIGetMsg()
        If $msg1 = $GUI_EVENT_CLOSE Then ExitLoop
    WEnd
    GUIDelete ($AboutGUI)
    GUISetState (@SW_ENABLE,$MainGUI)
EndFunc
Func ResizeCollumns()
    _GUICtrlListView_SetColumnWidth($ListView, 0, 100)
    _GUICtrlListView_SetColumnWidth($ListView, 1, 95)
Endfunc
Func ExitFunction()
    Exit
EndFunc

Share this post


Link to post
Share on other sites

Is that for a 3D printer?


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

#16 ·  Posted (edited)

Yes

Its to modify printer behavior per layer rather then per height by editing generated G-Code.

Programs that generate the G-Code have visual representation of layers as well as their numbers (CURA does).

Looking at the layer number i can tell exactly where i need to make print change or pause and/or swap the filament etc.

I can use plugins for it, but they are all height based, not layer based change.

Its simply too inacurate to calculate height at which you want to do things, much easier to use a slider to see what layer u want to tweak and then use my app (which was made possible by you) to make modification to that layer at the most exact spot.

Edited by tonycst

Share this post


Link to post
Share on other sites

If you read line by line it would take time, but in this case file operations would be better rather than regular expressions .

Here we go

#include <Array.au3>

$SourceRead = FileRead ("Test.txt") ;created by fileopendialog

$aLayers = FileReadToArray("Test.txt")
$aLineNumber = _ArrayFindAll($aLayers, ";Layer:", 0, 0, 0, 1)

For $i = 0 To UBound($aLineNumber) - 1
    ConsoleWrite($aLayers[$aLineNumber[$i]] & @TAB & "LineNo.: " & $aLineNumber[$i] + 1 & @CRLF)
Next

Regards :)

Dude ! Can  you look at this one and see if it can be done faster ?

Func _Open()
    If $source = "" Then
        $source = FileOpenDialog("Open G-Code file","","G-Code files(*.gcode)|(*.gco)|(*.g)")
    EndIf
    Assign ("Found",1)
    Local $SourceRead,$aLayers,$aLineNumber,$i
    $SourceRead = FileRead ($source) ;created by fileopendialog
    _GUICtrlListView_DeleteAllItems(GUICtrlGetHandle($ListView))
    _GUICtrlStatusBar_SetText ($StatusBar,"Searching")
    $aLayers = FileReadToArray($source)
    $aLineNumber = _ArrayFindAll($aLayers, ";Layer:", 0, 0, 0, 1) ;Search for this array containing given text
    For $i = 0 To UBound($aLineNumber) - 1
        If StringInStr ($aLayers[$aLineNumber[$i]],";Layer:-") > 0 Then
            $NewItem = GUICtrlCreateListViewItem("RAFT Layer" & $i & "|" & $aLineNumber[$i], $ListView)
            Assign ("Found",$Found+1)
        Else
            $Item = GUICtrlCreateListViewItem("Layer " & $Found & "|" & $aLineNumber[$i], $ListView)
            If IniRead (@ScriptDir & "\Settings.ini","Settings","SearchAtOpen","") = "Yes" Then
            $localIndex = _GUICtrlListView_MapIDToIndex ($listview,$Item)
            For $s = 1 to 14 ;read 10 lines ahead because i only have 10 parameters that would create 10 lines max
                $SearchLine = FileReadLine ($source,$aLineNumber[$i]+$s)
                If $SearchLine = ";G-Code Modifier DATA Start" Then
                    _GUICtrlListView_SetItemText ($listview,$Found-1 ,$aLineNumber[$i]+$s,2) ;Item index is -1 from found count.
                EndIf
                If $SearchLine = ";G-Code Modifier DATA End" Then
                    _GUICtrlListView_SetItemText ($listview,$Found-1,$aLineNumber[$i]+$s,3) ;Item index is -1 from found count.
                EndIf
            Next
            EndIf
            Assign ("Found",$Found+1)
        EndIf
    Next
    _GUICtrlStatusBar_SetText ($StatusBar,"Found " & $Found & " Layer records")
    Assign ("Found",1)
Endfunc

I strugge with "For $s = 1 to 14" statement.

Each searching ;Layer needs to be searched for a string 13 lines ahead to find aditional entries that i make with my program in order to identify its entries, so i can modify them

But doing it my way is very slow, in fact its 26 times slower if not more because it looks for Start and End of my possibly entered text.

Thanks

Share this post


Link to post
Share on other sites

Thought i'd give u entire script as well as test file to search.

When INI reads SearchAtOpen=Yes, then search will highlight found items with the icon.

This is done to give user immidiate sigh that layer has been modified.

IT slows down search by 26 operations because it searches for 2 strings 13 lines down.

I cant think of another way to do this, someone must be smarter then me.

Thanks in advance.

Here are all source files;

Source.zip

Open file and click  layer 1 or 2.

You will see that they get a warning icon and aditional details assigned to 2 collumns.

I want that to happen when it searches in the _Open() function.

KIt already does it there, but it does it very very slow same way it does when u click item.

Its ok when u click because it does it only once X26 times.

Please look at the code and see if maybe there is a way to speed up search and have it display icon and details faster.

Thanks.

Share this post


Link to post
Share on other sites

I'm looking and fixing few bugs first.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

Like what ? It works fine the way it is but OK. I just want to know what bugs there are so i dont get too confused with change you propose.

I dont exactly follow strict rules of coding, i just kinda code as i go and hit F5 each line to test if it works :)

Thanks.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0