Sign in to follow this  
Followers 0
wraithdu

Console Progress Display

13 posts in this topic

I don't usually post fluff, but I like the console sometimes. And consoles need love too. This is going to be part of my A3COPY project when I post the next update.

Here's a fancy console progress bar display. It has a customizable inner length, bar body and head characters. Spruce up those consoles dammit!

#include-once

; #FUNCTION# ====================================================================================================
; Name...........:  _ConsoleProgress
; Description....:  Create a progress bar for console applications
; Syntax.........:  _ConsoleProgress($iProgress, $iLength = 50, $sTrail = "=", $sPoint = ">")
; Parameters.....:  $iProgress  - The progress percentage, valid range from 0 to 100
;                   $iLength    - [Optional] The lengh in characters of the inner bar
;                   $sTrail     - [Optional] The character to use for the progress trail
;                   $sPoint     - [Optional] The character to use for the progress point
;
; Return values..:  Success - none
;                   Failure - Sets @error to 1 if $iProgress is out of range
; Author.........:  Erik Pilsits
; Modified.......:  4/18/11
; Remarks........:
; Related........:
; Link...........:
; Example........:
; ===============================================================================================================
Func _ConsoleProgress($iProgress, $iLength = 50, $sTrail = "=", $sPoint = ">")
    ; check range
    If $iProgress < 0 Or $iProgress > 100 Then Return SetError(1, 0, 0)
    ; setup head and tail
    Local $sHead = "0% ["
    Local $sTail = "] " & $iProgress & "%"
    Local $iMax = 4 + $iLength + 6
    ; set progress ticks
    Local $iTicks = Ceiling($iProgress * $iLength / 100)
    ; create progress string
    Local $sPrint = $sHead
    For $i = 1 To $iTicks - 1
        $sPrint &= $sTrail
    Next
    $sPrint &= $sPoint
    ; fix for 0%
    If $iTicks = 0 Then $iTicks = 1
    ; fill in space
    For $i = $iTicks + 1 To $iLength
        $sPrint &= " "
    Next
    $sPrint &= $sTail
    ; print new progress
    ConsoleWrite(_ConsoleProgressClear($iMax) & $sPrint)
EndFunc

; #FUNCTION# ====================================================================================================
; Name...........:  _ConsoleProgressClear
; Description....:  Create a string to clear the progress line and reset the carat to the beginning of the line
; Syntax.........:  _ConsoleProgressClear($iMax = 60)
; Parameters.....:  $iMax   - [Optional] The maximum length of the full line
;
; Return values..:  Success - The string
; Author.........:  Erik Pilsits
; Modified.......:  4/18/11
; Remarks........:
; Related........:
; Link...........:
; Example........:
; ===============================================================================================================
Func _ConsoleProgressClear($iMax = 60)
    Local $aErase[3] = [ChrW(8), " ", ChrW(8)]
    Local $sErase = ""
    For $i = 0 To 2
        For $j = 1 To $iMax
            $sErase &= $aErase[$i]
        Next
    Next
    Return $sErase
EndFunc

Example (must be compiled as CUI):

#AutoIt3Wrapper_Change2CUI=y

#include <_ConsoleProgress.au3>

For $i = 0 To 100 Step 10
    _ConsoleProgress($i)
    Sleep(400)
Next
ConsoleWrite(@CRLF)
For $i = 1 To 10
    _ConsoleProgress(Random(0, 100, 1), 40, "-", "O")
    Sleep(400)
Next
ConsoleWrite(@CRLF)
For $i = 100 To 0 Step -10
    _ConsoleProgress($i, 60, ".", "{")
    Sleep(400)
Next

Share this post


Link to post
Share on other sites



Ive been looking for one of these babies...

Thanks for sharing; definately will use.


ongoing projects:-firestorm: Largescale P2P Social NetworkCompleted Autoit Programs/Scripts: Variable Pickler | Networked Streaming Audio (in pure autoIT) | firenet p2p web messenger | Proxy Checker | Dynamic Execute() Code Generator | P2P UDF | Graph Theory Proof of Concept - Breadth First search

Share this post


Link to post
Share on other sites

Nice.

Here is another example of progress, but with colors:

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Compression=4
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_AU3Check_Stop_OnWarning=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

Global $hdllKernel32 = DllOpen("kernel32.dll")

If @error Then
    ConsoleWrite("!> Error.  Couldn't open kernel32.dll" & @LF)
    Exit
EndIf

$ClearProgress = 0
$processing = "Processing "
$progress = ""
Dim $spin[4] = ['¦', '/', '-', '\']
$elipses = ""

$iCnt = 0
$iCnt2 = 16

For $i = 1 To 22
    For $s = 1 To UBound($spin) - 1
        _SetConsoleColor(BitOR($iCnt, 8, $iCnt2, 128))
        $iCnt += 1
        $iCnt2 += 16
        ConsoleWrite(@CR & $processing & $elipses & "[" & $spin[$s] & "]")
        $elipses &= "."
        If $iCnt = 9 Then $iCnt = 0
        If $iCnt2 = 112 Then $iCnt2 = 16
        Sleep(50)
    Next
Next

_SetConsoleColor(12)
ConsoleWrite(@CRLF & @CRLF & "DONE!" & @CRLF & @CRLF)

$asSplit = StringSplit("Using console colors is fun. ;-)", "")
$iCnt2 = 1

For $iCnt = 1 To UBound($asSplit) - 1
    _SetConsoleColor(BitOR($iCnt2, 8))
    $iCnt2 += 1
    ConsoleWrite($asSplit[$iCnt])
    If $iCnt2 = 9 Then $iCnt2 = 1
Next

Sleep(5000)

Func _SetConsoleColor($iColor)
    Local $aRet, $aRet2
    $aRet = DllCall("Kernel32.dll", "hwnd", "GetStdHandle", "int", -11);$STD_INPUT_HANDLE = -10,$STD_OUTPUT_HANDLE = -11,$STD_ERROR_HANDLE = -12
    If Not UBound($aRet) > 0 Then
        ConsoleWrite("!>Error.  GetStdHandle failed." & @LF)
        Return 0
    EndIf
    $aRet2 = DllCall("Kernel32.dll", "int", "SetConsoleTextAttribute", "hwnd", $aRet[0], "ushort", $iColor)
    If Not UBound($aRet2) > 0 Then
        ConsoleWrite("!>Error.  SetConsoleTextAttribute failed." & @LF)
        Return 0
    EndIf
    ;Note: The StdHandle doesn't need to be closed because the handle wasn't opened.  It was gotten.
    If $aRet2 <> 0 Then
        Return 1
    Else
        Return 0
    EndIf
EndFunc

Func OnAutoItExit()
    DllClose($hdllKernel32)
EndFunc


 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Share this post


Link to post
Share on other sites

Heres my submission using my Console.au3 UDF. Won't work from SciTE but I think it's pretty self explanatory.

#include 'Console.au3'
#include <String.au3>

_Console_Alloc()

Local $aiSize = _Console_GetScreenBufferSize()
If @error Then Exit 1

Local $aiPos = _Console_GetCursorPosition()

Local $sProgress = "[" & _StringRepeat(" ", $aiSize[0] - 2) & "]"


For $i = 1 To 100

    $sProgress = "[" & _StringRepeat("=", Floor(($aiSize[0] - 2) * $i / 100))
    $sProgress &= _StringRepeat(" ", $aiSize[0] - StringLen($sProgress) - 1) & "]"

    $sPer = $i & "%"

    $n = Ceiling((StringLen($sProgress) - StringLen($sPer)) / 2)
    $sProgress = StringLeft($sProgress, $n) & $sPer & StringTrimLeft($sProgress, $n + StringLen($sPer))


    _Console_WriteOutputCharacter(-1, $sProgress, 0, $aiPos[1])

    Sleep(50)
Next

_Console_SetCursorPosition(-1, 0, $aiPos[1] + 1)

_Console_Pause()
_Console_Free()

You are right that consoles need a little love. I wish I had the time or motivation to get my UDF finished.

Mat

Share this post


Link to post
Share on other sites

thanks for sharing :unsure:

Share this post


Link to post
Share on other sites

Heres a more UDF like version:

#include 'Console.au3'
#include <String.au3>

_Console_Alloc()

_Console_Write("Loading file: ")

Local $aiSize = _Console_GetScreenBufferSize()
If @error Then Exit 1

Local $aiPos = _Console_GetCursorPosition()

Local $a = _Console_ProgressCreate(-1, $aiPos[0], $aiPos[1], $aiSize[0] - $aiPos[0])

_Console_SetCursorVisible(-1, False)
For $i = 1 To 100
    _Console_ProgressSet($a, $i)

    Sleep(50)
Next

_Console_SetCursorPosition(-1, 0, $aiPos[1] + 1)
_Console_SetCursorVisible(-1, True)

_Console_Pause()
_Console_Free()


Func _Console_ProgressCreate($hConsole, $x, $y, $w, $sStartChr = "[", $sEndChr = "]", $sEmptyChr = " ", $sFullChr = "=", $fShowPercent = True, $hDll = -1)
    If $hDll = -1 Then $hDll = $__gvKernel32
    If $hConsole = -1 Then $hConsole = _Console_GetStdHandle($STD_OUTPUT_HANDLE, $hDll)

    Local $aRet[10] = [$hConsole, $hDll, $x, $y, $w, $sStartChr, $sEndChr, $sEmptyChr, $sFullChr, $fShowPercent]
    _Console_ProgressSet($aRet, 0)

    Return $aRet
EndFunc   ;==>_Console_ProgressCreate

Func _Console_ProgressSet($aProg, $iPercent)
    Local $iWidth, $sPer, $iPerStart

    $iWidth = Floor(($aProg[4] - StringLen($aProg[5]) - StringLen($aProg[6])) * $iPercent / 100)
    $sPer = Round($iPercent, 1) & "%"
    $iPerStart = Ceiling(($aProg[4] - StringLen($sPer)) / 2)

    Local $s = $aProg[5] & _StringRepeat($aProg[8], $iWidth) & _StringRepeat($aProg[7], $aProg[4] - $iWidth - StringLen($aProg[5]) - StringLen($aProg[6])) & $aProg[6]

    If $aProg[9] Then $s = StringLeft($s, $iPerStart) & $sPer & StringTrimLeft($s, $iPerStart + StringLen($sPer))

    _Console_WriteOutputCharacter($aProg[0], $s, $aProg[2], $aProg[3], Default, $aProg[1])

    Return True
EndFunc   ;==>_Console_ProgressSet

I'm sure there are ways to improve this more.

Oh, and by the way wraithdu, I like that way of clearing the line, but the latest Au3Int source has a function that does exactly the same using FillOutputCharacter and SetCursorPosition. In reality you'd only need SetCursorInfo as it would overwrite the other bits I think...

Mat

Share this post


Link to post
Share on other sites

Heres a more UDF like version

Where is the Console.au3? :unsure:

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

Oh, and by the way wraithdu, I like that way of clearing the line, but the latest Au3Int source has a function that does exactly the same using FillOutputCharacter and SetCursorPosition. In reality you'd only need SetCursorInfo as it would overwrite the other bits I think...

Yep, there certainly are other options. I chose that method cause it was simple. I thought about not erasing the line and just resetting the cursor position, but if the length of the line changes then there's the possibility not everything will be overwritten, ie 100% is longer than 99%, 10% is longer than 9% (if you're counting down).

Edit:

Oh, how should we submit changes for your Conosle.au3 UDF? There are a few syntax errors and one misspelling in v .26.

Edited by wraithdu

Share this post


Link to post
Share on other sites

#11 ·  Posted (edited)

Console.au3 is not on my project page. If you can download it from there it is almost certainly out of date:

http://code.google.com/p/consoleau3/

@Wraithdu, I fixed the syntax errors (2 of them), where is the typo?

If you want to submit corrections then I'll need to add you as a contributor on the google code page, if not just add issues to the tracker of pm me and I'll fix stuff. I use it for various bits so I don't mind, it's all the examples I need to get round to doing :unsure: That said, the above is a good one to add for all functions used.

Mat

Console.au3 updated to solve syntax errors. They were already fixed on my machine. Also added examples relating to console progress bar. There may have been other untracked changes as I haven't looked at it for a while

Edit: @Wakillon, you are linking to a deprecated file.

Edited by Mat

Share this post


Link to post
Share on other sites

where is the typo?

Rev .27 looks good now. It was some discrepancy between use of $aResult and $fResult. Which begs the question, why use $fResult at all?

Share this post


Link to post
Share on other sites

The reason for that error was I added the function _Console_ScrollScreenBufferEx that lets the user deal directly with the structures, whilst the _Console_ScrollScreenBuffer function is now a user friendly wrapper. As a result, it now calls _Console_ScrollScreenBufferEx rather than making a DllCall directly, so is returned a bool rather than an array, I updated the line but nothing else. The next line needed to be corrected as well as it was treating the return like an array. You are (of course) right that it doesn't need to be used at all as it's now a straight return. I have amended my copy and it will be in the next revision as it's not broken in any way with the current one.

I fixed that as one of the syntax errors you mentioned.

None of the following had any examples: _Console_WriteOutputCharacter, _Console_SetCursorVisible, _Console_SetCursorPosition, _Console_GetCursorPosition. They all now have the same example as I posted above for a progress bar.

Mat

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