Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 05/11/2025 in all areas

  1. ioa747

    SciTE AI assistant

    SciTE AI assistant The first approach, to integrate an AI assistant into SciTE works directly with the ollama. I use a small model qwen2.5-coder:3b as default, so that I don't have to wait too long for a response. However, I have set as a parameter which model it calls, so that it changes the model per job if necessary The first job is to make function headers Simply run the script, select a function body within SciTE and press the {F10} key It's not perfect, but it's a template. ; https://www.autoitscript.com/forum/topic/212888-scite-ai-assistant ;---------------------------------------------------------------------------------------- ; Title...........: SciTE_AI_Assistant.au3 ; Description.....: SciTE AI assistant - first feature: Function headers generator ; Simply select a function within SciTE and press the {F10} key. ; AutoIt Version..: 3.3.16.1 Author: ioa747 Script Version: 0.7 ; Note............: Testet in Win10 22H2 ;---------------------------------------------------------------------------------------- #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7 #include <File.au3> #include <SendMessage.au3> #include <WindowsConstants.au3> Global $DebugInfo = True ; True = debug info * <-- HotKeySet("{F10}", "GenerateFunctionHeader") ; * <-- While 1 Sleep(100) WEnd ;--------------------------------------------------------------------------------------- Func GenerateFunctionHeader() HotKeySet("{F10}") Local $hWnd = WinActivate("[CLASS:SciTEWindow]") If Not $hWnd Then Return SetError(HotKeySet("{F10}", "GenerateFunctionHeader")) Local $sSelected = _SciteIO() ;Get Selection If @error Then ToolTip(" Copy failed.") Else If StringLeft($sSelected, 4) = "func" Then Send('{UP}') Local $sOut = AI_GenerateFunctionHeader($sSelected) If @error Then ToolTip(@error) Else _SciteIO(@CRLF & @CRLF & $sOut & @CRLF & @CRLF) EndIf Else ToolTip("No Func selected") EndIf EndIf Sleep(2000) ToolTip("") HotKeySet("{F10}", "GenerateFunctionHeader") EndFunc ;==>GenerateFunctionHeader ;--------------------------------------------------------------------------------------- Func AI_GenerateFunctionHeader($sFullFunction, $sAssistant = -1) If $sAssistant = -1 Then $sAssistant = "qwen2.5-coder:3b" Local $sInstruction, $sSystem, $sOut $sInstruction = "Generate a function header for the given AutoIt function." & @CRLF $sInstruction &= "Use the exact standard UDF comment format, as shown in the example." & @CRLF $sInstruction &= "DO NOT invent or assume any parameters, return values, or behavior not explicitly visible in the function." & @CRLF $sInstruction &= "If the function has no parameters, leave 'Parameters' empty." & @CRLF $sInstruction &= "If it does not return a value, then in 'Return values' write 'None'." & @CRLF $sInstruction &= "Align all parameter names to the same column width using consistent spaces. The hyphen (-) must appear in the same column for all parameters." & @CRLF $sInstruction &= "If the function interacts with GUI elements, include that in the 'Remarks' section." & @CRLF $sInstruction &= "If the 'Remarks' line exceeds 130 characters, break it into multiple lines starting each with '; ' like in the example." & @CRLF $sInstruction &= "Optional parameters must be shown using nested brackets as per the example." & @CRLF $sInstruction &= "Match spacing exactly as in the example (e.g., align parameter names and descriptions)." & @CRLF $sInstruction &= "Use concise, factual language—do not embellish or rephrase beyond what's explicit in the function." & @CRLF $sInstruction &= "In 'Return values', include detailed descriptions of any @error values that may be set." & @CRLF $sInstruction &= "Use the following format for @error documentation: '@error = X: Explanation' as shown in the example." & @CRLF $sInstruction &= "If applicable, describe both the success and failure outcomes clearly, using 'Success:' and 'Failure:'." & @CRLF $sInstruction &= "The 'Author' is ioa747. Dependencies must match actual function calls only. Do not invent links or libraries." & @CRLF $sInstruction &= "Avoid unnecessary technical jargon. Keep lines compact and accurate." & @CRLF & @CRLF $sInstruction &= "Example format:" & @CRLF $sInstruction &= "; #FUNCTION# ====================================================================================================================" & @CRLF $sInstruction &= "; Name...........: StreamToEdit" & @CRLF $sInstruction &= "; Description....: Generate response from the AI assistant with streaming support." & @CRLF $sInstruction &= "; Syntax.........: StreamToEdit( $sPrompt [, $sAssistant = ""qwen2.5-coder:1.5b"" [, $sSystem = ""You are an AI assistant."" [, $fTemperature = 0.3 [, $iSeed = 0]]]] )" & @CRLF $sInstruction &= "; Parameters.....: $sPrompt - The prompt to be sent to the assistant." & @CRLF $sInstruction &= "; $sAssistant - [optional] The name of the AI assistant. (Default is ""qwen2.5-coder:3b"")" & @CRLF $sInstruction &= "; $sSystem - [optional] The system instruction provided by the user. (Default is ""You are an AI assistant."")" & @CRLF $sInstruction &= "; $fTemperature - [optional] The temperature value for the assistant's output. (Default is 0.3)" & @CRLF $sInstruction &= "; $iSeed - [optional] The seed value for the assistant's response. (Default is 0)" & @CRLF $sInstruction &= "; Return values .: Success: Returns the available models if the specified model is found." & @CRLF $sInstruction &= "; Failure: Sets @error and returns an empty string with a custom message." & @CRLF $sInstruction &= "; @error = 1: Ollama is not running at the default URL." & @CRLF $sInstruction &= "; @error = 2: The specified model was not found." & @CRLF $sInstruction &= "; Author ........: ioa747" & @CRLF $sInstruction &= "; Modified ......: " & @CRLF $sInstruction &= "; Remarks .......: This function uses a WinHttp request to communicate with the Ollama API." & @CRLF $sInstruction &= "; Related .......: " & @CRLF $sInstruction &= "; Link ..........: " & @CRLF $sInstruction &= "; Example .......: " & @CRLF $sInstruction &= "; ===============================================================================================================================" & @CRLF & @CRLF $sInstruction &= "Now generate a header comment for the following function:" & @CRLF $sInstruction &= "```AutoIt" & @CRLF $sInstruction &= $sFullFunction & @CRLF $sInstruction &= "```" & @CRLF Local $hTimer = TimerInit() $sOut = AskToAI($sInstruction, $sAssistant, $sSystem, 0, 1) If @error Then Return SetError(@error, 0, $sOut) Return "> " & $sAssistant & " processed in: " & Round(TimerDiff($hTimer) / 1000, 3) & " seconds " & @CRLF & $sOut EndFunc ;==>AI_GenerateFunctionHeader ;--------------------------------------------------------------------------------------- Func AskToAI($sPrompt, $sAssistant = -1, $sSystem = -1, $iTemperature = -1, $iSeed = -1) If $sSystem = "" Or $sSystem = -1 Or $sSystem = Default Then $sSystem = "You are an AI assistant designed to analyze AutoIt code." ; best mini models result with: qwen2.5-coder:1.5b ; qwen2.5-coder:3b 1.8 GB ; llama3.2:3b-instruct-q8_0 3.2 GB If $sAssistant = "" Or $sAssistant = -1 Or $sAssistant = Default Then $sAssistant = "qwen2.5-coder:3b" If $iTemperature = "" Or $iTemperature = -1 Or $iTemperature = Default Then $iTemperature = 0.3 If $iSeed = "" Or $iSeed = -1 Or $iSeed = Default Then $iSeed = 0 Json_EscapeString($sAssistant) Json_EscapeString($sSystem) Json_EscapeString($sPrompt) Local $sRequest = '{' $sRequest &= '"model": "' & $sAssistant & '", ' $sRequest &= '"system": "' & $sSystem & '", ' $sRequest &= '"prompt": "' & $sPrompt & '", ' $sRequest &= '"stream": false, ' $sRequest &= '"temperature": ' & $iTemperature & ', ' $sRequest &= '"seed": ' & $iSeed $sRequest &= '}' DW("$sRequest=>" & $sRequest & @CRLF) ;_FileWriteLog(StringTrimRight(@ScriptFullPath, 4) & ".log", $sRequest) Local $oHttp = ObjCreate("WinHttp.WinHttpRequest.5.1") ; ResolveTimeout: 5 sec ; ConnectTimeout: 10 sec ; SendTimeout: 30 sec ; ReceiveTimeout: 120 sec $oHttp.SetTimeouts(5000, 10000, 30000, 120000) $oHttp.Open("POST", "http://localhost:11434/api/generate", False) $oHttp.SetRequestHeader("Content-Type", "application/json") $oHttp.Send($sRequest) ; Check if request was successful If $oHttp.Status <> 200 Then Local $aErr = HTTP_STATUS_CODES($oHttp.Status, $oHttp.ResponseText) MsgBox(16, " ( " & $aErr[0] & " ) " & $aErr[1], $aErr[2]) Return SetError(1, 0, $oHttp.ResponseText) EndIf Local $sResponse = $oHttp.ResponseText DW("$sResponse=>" & $sResponse & @CRLF) ; Parse response => suporting value: .model ; .created_at ; .response ; .done_reason Local $mJson = Json_Map($sResponse) ; DW("$mJson.response=" & $mJson.response & @CRLF) MapExists($mJson, "response") If @error Then MsgBox(16, "AskToAI() l: " & @ScriptLineNumber, "_JsonMap() fail to response") Return SetError(2, 0, "_JsonMap() fail to response") EndIf $sResponse = $mJson.response Return $sResponse EndFunc ;==>AskToAI ;--------------------------------------------------------------------------------------- Func _SciteIO($sTxt = "") Local $hWnd = WinActivate("[CLASS:SciTEWindow]") If Not $hWnd Then Return SetError(1) Local $ClipBack = ClipGet() ; backup clip data Local $hCtrlHnd, $ClipData, $iTimeout = 2000 ClipPut("<empty>") Local $iStartTime = TimerInit() If $sTxt = "" Then ; ### get selection to clip ### $hCtrlHnd = ControlGetHandle($hWnd, '', 'Scintilla1') _SendMessage($hCtrlHnd, $WM_COPY) While TimerDiff($iStartTime) < $iTimeout ; Wait until the timeout $ClipData = ClipGet() If $ClipData <> "<empty>" Then ExitLoop Sleep(10) WEnd Else ; ### set Txt to Console ### $hCtrlHnd = ControlGetHandle($hWnd, '', 'Scintilla2') ClipPut($sTxt) While TimerDiff($iStartTime) < $iTimeout ; Wait until the timeout $ClipData = ClipGet() If $ClipData <> "<empty>" Then ExitLoop Sleep(10) WEnd If $ClipData <> "<empty>" Then Local $iWndHeight = ControlGetPos ($hWnd, "", $hCtrlHnd) If $iWndHeight[3] = 0 Then WinMenuSelectItem($hWnd, "", "&View", "&Output") Sleep(10) ControlSend($hWnd, "", $hCtrlHnd, "^{DOWN}") If Not $DebugInfo Then WinMenuSelectItem($hWnd, "", "&Tools", "Clear &Output") ;* Clear console Output Sleep(10) _SendMessage($hCtrlHnd, $WM_PASTE) EndIf EndIf ClipPut($ClipBack) ; Restore clip data Return ($ClipData = "<empty>" ? SetError(2) : $ClipData) EndFunc ;==>_SciteIO ;--------------------------------------------------------------------------------------- Func HTTP_STATUS_CODES($iStatus, $sResponseText = "") Local $aResult[3] = [$iStatus, "Unknown Status", "An unknown HTTP status code was returned."] Local $HTTP_STATUS_CODES[41][3] = [[40, "HTTP status", "description"] _ , [100, "HTTP_STATUS_CONTINUE", "The request can be continued."] _ , [101, "HTTP_STATUS_SWITCH_PROTOCOLS", "The server has switched protocols in an upgrade header."] _ , [200, "HTTP_STATUS_OK", "The request completed successfully."] _ , [201, "HTTP_STATUS_CREATED", "The request has been fulfilled and resulted in the creation of a new resource."] _ , [202, "HTTP_STATUS_ACCEPTED", "The request has been accepted for processing, but the processing has not been completed."] _ , [203, "HTTP_STATUS_PARTIAL", "The returned meta information in the entity-header is not the definitive set available from the originating server."] _ , [204, "HTTP_STATUS_NO_CONTENT", "The server has fulfilled the request, but there is no new information to send back."] _ , [205, "HTTP_STATUS_RESET_CONTENT", "The request has been completed, and the client program should reset the document view that caused the request to be sent to allow the user to easily initiate another input action."] _ , [206, "HTTP_STATUS_PARTIAL_CONTENT", "The server has fulfilled the partial GET request for the resource."] _ , [207, "HTTP_STATUS_WEBDAV_MULTI_STATUS", "During a World Wide Web Distributed Authoring and Versioning (WebDAV) operation, this indicates multiple status codes for a single response. The response body contains Extensible Markup Language (XML) that describes the status codes."] _ , [300, "HTTP_STATUS_AMBIGUOUS", "The requested resource is available at one or more locations."] _ , [301, "HTTP_STATUS_MOVED", "The requested resource has been assigned to a new permanent Uniform Resource Identifier (URI), and any future references to this resource should be done using one of the returned URIs."] _ , [302, "HTTP_STATUS_REDIRECT", "The requested resource resides temporarily under a different URI."] _ , [303, "HTTP_STATUS_REDIRECT_METHOD", "The response to the request can be found under a different URI and should be retrieved using a GET HTTP verb on that resource."] _ , [304, "HTTP_STATUS_NOT_MODIFIED", "The requested resource has not been modified."] _ , [305, "HTTP_STATUS_USE_PROXY", "The requested resource must be accessed through the proxy given by the location field."] _ , [307, "HTTP_STATUS_REDIRECT_KEEP_VERB", "The redirected request keeps the same HTTP verb. HTTP/1.1 behavior."] _ , [400, "HTTP_STATUS_BAD_REQUEST", "The request could not be processed by the server due to invalid syntax."] _ , [401, "HTTP_STATUS_DENIED", "The requested resource requires user authentication."] _ , [402, "HTTP_STATUS_PAYMENT_REQ", "Not implemented in the HTTP protocol."] _ , [403, "HTTP_STATUS_FORBIDDEN", "The server understood the request, but cannot fulfill it."] _ , [404, "HTTP_STATUS_NOT_FOUND", "The server has not found anything that matches the requested URI."] _ , [405, "HTTP_STATUS_BAD_METHOD", "The HTTP verb used is not allowed."] _ , [406, "HTTP_STATUS_NONE_ACCEPTABLE", "No responses acceptable to the client were found."] _ , [407, "HTTP_STATUS_PROXY_AUTH_REQ", "Proxy authentication required."] _ , [408, "HTTP_STATUS_REQUEST_TIMEOUT", "The server timed out waiting for the request."] _ , [409, "HTTP_STATUS_CONFLICT", "The request could not be completed due to a conflict with the current state of the resource. The user should resubmit with more information."] _ , [410, "HTTP_STATUS_GONE", "The requested resource is no longer available at the server, and no forwarding address is known."] _ , [411, "HTTP_STATUS_LENGTH_REQUIRED", "The server cannot accept the request without a defined content length."] _ , [412, "HTTP_STATUS_PRECOND_FAILED", "The precondition given in one or more of the request header fields evaluated to false when it was tested on the server."] _ , [413, "HTTP_STATUS_REQUEST_TOO_LARGE", "The server cannot process the request because the request entity is larger than the server is able to process."] _ , [414, "HTTP_STATUS_URI_TOO_LONG", "The server cannot service the request because the request URI is longer than the server can interpret."] _ , [415, "HTTP_STATUS_UNSUPPORTED_MEDIA", "The server cannot service the request because the entity of the request is in a format not supported by the requested resource for the requested method."] _ , [449, "HTTP_STATUS_RETRY_WITH", "The request should be retried after doing the appropriate action."] _ , [500, "HTTP_STATUS_SERVER_ERROR", "The server encountered an unexpected condition that prevented it from fulfilling the request."] _ , [501, "HTTP_STATUS_NOT_SUPPORTED", "The server does not support the functionality required to fulfill the request."] _ , [502, "HTTP_STATUS_BAD_GATEWAY", "The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request."] _ , [503, "HTTP_STATUS_SERVICE_UNAVAIL", "The service is temporarily overloaded."] _ , [504, "HTTP_STATUS_GATEWAY_TIMEOUT", "The request was timed out waiting for a gateway."] _ , [505, "HTTP_STATUS_VERSION_NOT_SUP", "The server does not support the HTTP protocol version that was used in the request message."]] For $i = 1 To $HTTP_STATUS_CODES[0][0] If $HTTP_STATUS_CODES[$i][0] = $iStatus Then ;$aResult[0] = $HTTP_STATUS_CODES[$i][0] $aResult[1] = $HTTP_STATUS_CODES[$i][1] $aResult[2] = $HTTP_STATUS_CODES[$i][2] ExitLoop EndIf Next ConsoleWrite("! $aResult[0]=" & $aResult[0] & ", [1]=" & $aResult[1] & ", [2]=" & $aResult[2] & @TAB & "( " & $sResponseText & " )" & @CRLF) $aResult[2] &= @CRLF & @CRLF & "Details: " & $sResponseText Return $aResult EndFunc ;==>HTTP_STATUS_CODES ;--------------------------------------------------------------------------------------- Func DW($sString, $iLine = @ScriptLineNumber) If Not $DebugInfo Then Return ConsoleWrite("(" & $iLine & ") " & $sString) EndFunc ;==>DW ;--------------------------------------------------------------------------------------- Func Json_EscapeString(ByRef $sString) ;=== Converts normal string to a JSON-safe string === ; Escape backslashes first to avoid double-processing $sString = StringReplace($sString, '\', '\\', 0, 1) ; Escape known JSON control characters $sString = StringReplace($sString, Chr(8), '\b', 0, 1) ; Backspace $sString = StringReplace($sString, Chr(12), '\f', 0, 1) ; Formfeed $sString = StringReplace($sString, @CRLF, '\n', 0, 1) ; CRLF → \n $sString = StringReplace($sString, @LF, '\n', 0, 1) ; LF → \n $sString = StringReplace($sString, @CR, '\r', 0, 1) ; CR → \r $sString = StringReplace($sString, @TAB, '\t', 0, 1) ; Tab → \t ; Escape double quotes $sString = StringReplace($sString, '"', '\"', 0, 1) ; Escape \u00XX characters ; nothing yet Return $sString EndFunc ;==>Json_EscapeString ;--------------------------------------------------------------------------------------- Func Json_UnEscapeString(ByRef $sString) ;=== Converts a JSON-escaped string back into normal string === If StringInStr($sString, '\') = 0 Then Return $sString ; Unescape quotes and backslashes first $sString = StringReplace($sString, '\"', '"', 0, 1) $sString = StringReplace($sString, '\\', '\', 0, 1) ; Unescape standard control characters $sString = StringReplace($sString, '\b', Chr(8), 0, 1) $sString = StringReplace($sString, '\f', Chr(12), 0, 1) $sString = StringReplace($sString, '\n', @LF, 0, 1) $sString = StringReplace($sString, '\r', @CR, 0, 1) $sString = StringReplace($sString, '\t', @TAB, 0, 1) ; Unescape \u00XX characters $sString = StringReplace($sString, '\u003c', '<', 0, 1) $sString = StringReplace($sString, '\u003e', '>', 0, 1) Return $sString EndFunc ;==>Json_UnEscapeString ;--------------------------------------------------------------------------------------- Func Json_Map($sJson) ;=== It not support numbers, booleans, arrays or nested objects. === Local $mJson[] ; Remove curly braces and trim $sJson = StringStripWS(StringTrimLeft(StringTrimRight($sJson, 1), 1), 3) ; Match all "key": "value" pairs Local $aPairs = StringRegExp($sJson, '"([^"]+)"\s*:\s*"((?:\\.|[^"\\])*)"', 3) If @error Then Return SetError(2, 0, 0) For $i = 0 To UBound($aPairs) - 1 Step 2 Local $sKey = $aPairs[$i] Local $sVal = $aPairs[$i + 1] Json_UnEscapeString($sVal) $mJson[$sKey] = $sVal ;ConsoleWrite("$sKey=" & $sKey & @CRLF) Next Return $mJson EndFunc ;==>Json_Map ;--------------------------------------------------------------------------------------- I will update the thread as soon as anything new comes up. Please, every comment is appreciated! leave your comments and experiences here! Thank you very much
    2 points
  2. ioa747

    _StringToTable

    _StringToTable() – Convert Text\array to a text formatted table The _StringToTable() function allows you to convert structured text (like tab-separated data), or array into a formatted, aligned table using Unicode box-drawing characters. Ideal for displaying readable output in console-based tools or logs. Example1: string to table Local $sData = _ "Company" & @TAB & "Contact" & @TAB & "Revenue" & @CRLF & _ "Alfreds Futterkiste" & @TAB & "Maria Anders" & @TAB & "1200" & @CRLF & _ "Centro Moctezuma" & @TAB & "Francisco Chang" & @TAB & "950" & @CRLF & _ "Island Trading" & @TAB & "Helen Bennett" & @TAB & "15800" ConsoleWrite(_StringToTable($sData, 3, @TAB, "L,C,R") & @CRLF) ┌──────────────────────┬───────────────────┬──────────┐ │ Company │ Contact │ Revenue │ ├──────────────────────┼───────────────────┼──────────┤ │ Alfreds Futterkiste │ Maria Anders │ 1200 │ │ Centro Moctezuma │ Francisco Chang │ 950 │ │ Island Trading │ Helen Bennett │ 15800 │ └──────────────────────┴───────────────────┴──────────┘ Example2: array to table ; Make example array Local $aArray[10][5] For $i = 0 To 9 For $j = 0 To 4 $aArray[$i][$j] = $i & "-" & $j Next Next ;_ArrayDisplay($aArray, "example array") ; Make header and insert to array (when needed) Local $sHeader = "Column 0|Column 1|Column 2|Column 3|Column 4" _ArrayInsert($aArray, 0, $sHeader) If @error Then Exit MsgBox(16, "@error: " & @error, "Something went wrong with _ArrayInsert()") Local $sOut = _StringToTable($aArray, 3, @TAB, "C,C,C,C,C") ConsoleWrite($sOut & @CRLF & @CRLF) ┌──────────┬──────────┬──────────┬──────────┬──────────┐ │ Column 0 │ Column 1 │ Column 2 │ Column 3 │ Column 4 │ ├──────────┼──────────┼──────────┼──────────┼──────────┤ │ 0-0 │ 0-1 │ 0-2 │ 0-3 │ 0-4 │ │ 1-0 │ 1-1 │ 1-2 │ 1-3 │ 1-4 │ │ 2-0 │ 2-1 │ 2-2 │ 2-3 │ 2-4 │ │ 3-0 │ 3-1 │ 3-2 │ 3-3 │ 3-4 │ │ 4-0 │ 4-1 │ 4-2 │ 4-3 │ 4-4 │ │ 5-0 │ 5-1 │ 5-2 │ 5-3 │ 5-4 │ │ 6-0 │ 6-1 │ 6-2 │ 6-3 │ 6-4 │ │ 7-0 │ 7-1 │ 7-2 │ 7-3 │ 7-4 │ │ 8-0 │ 8-1 │ 8-2 │ 8-3 │ 8-4 │ │ 9-0 │ 9-1 │ 9-2 │ 9-3 │ 9-4 │ └──────────┴──────────┴──────────┴──────────┴──────────┘ Example4: Example floating point format $sData = "" ; from https://www.autoitscript.com/forum/topic/212833-json-udf-using-json-c/#findComment-1542670 $sData &= " name | time[ms] | factor | Std. Dev | Std. Err. | min | max | range |" & @CRLF $sData &= " StringRegExp only | 1.691 | 1 | 0.351 | 0.035 | 1.304 | 3.167 | 1.863 |" & @CRLF $sData &= " jq UDF | 32.933 | 19.48 | 2.929 | 0.293 | 29.308 | 43.169 | 13.861 |" & @CRLF $sData &= " JsonC-UDF | 51.086 | 30.21 | 3.205 | 0.321 | 45.625 | 63.46 | 17.835 |" & @CRLF $sData &= " pure AutoIt JSON-UDF | 97.916 | 57.9 | 5.685 | 0.569 | 86.362 | 113.467 | 27.105 |" & @CRLF $sData &= " JSMN-based JSON-UDF | 108.248 | 64.01 | 5.512 | 0.551 | 99.029 | 130.864 | 31.835 |" & @CRLF $sOut = _StringToTable($sData, 3, "|", "L,3,2,3,3,3,3,3") ConsoleWrite($sOut & @CRLF & @CRLF) ┌──────────────────────┬──────────┬────────┬──────────┬───────────┬────────┬─────────┬────────┐ │ name │ time[ms] │ factor │ Std. Dev │ Std. Err. │ min │ max │ range │ ├──────────────────────┼──────────┼────────┼──────────┼───────────┼────────┼─────────┼────────┤ │ StringRegExp only │ 1.691 │ 1.00 │ 0.351 │ 0.035 │ 1.304 │ 3.167 │ 1.863 │ │ jq UDF │ 32.933 │ 19.48 │ 2.929 │ 0.293 │ 29.308 │ 43.169 │ 13.861 │ │ JsonC-UDF │ 51.086 │ 30.21 │ 3.205 │ 0.321 │ 45.625 │ 63.460 │ 17.835 │ │ pure AutoIt JSON-UDF │ 97.916 │ 57.90 │ 5.685 │ 0.569 │ 86.362 │ 113.467 │ 27.105 │ │ JSMN-based JSON-UDF │ 108.248 │ 64.01 │ 5.512 │ 0.551 │ 99.029 │ 130.864 │ 31.835 │ └──────────────────────┴──────────┴────────┴──────────┴───────────┴────────┴─────────┴────────┘ Made with ❤️ for readable and elegant output. ; https://www.autoitscript.com/forum/topic/212876-_stringtotable/ ;---------------------------------------------------------------------------------------- ; Title...........: _StringToTable.au3 ; Description.....: Converts a string to a formatted table with alignment and frame options. ; AutoIt Version..: 3.3.16.1 Author: ioa747 Script Version: 0.5 ; Note............: Testet in Win10 22H2 ;---------------------------------------------------------------------------------------- #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7 #include <Array.au3> #include <String.au3> Example1() ; Example string to table ;~ Example2() ; Example 2D array to table ;~ Example3() ; Example 1D array to table ;~ Example4() ; Example floating point format ;~ Example5() ; Example for new frame style ;--------------------------------------------------------------------------------------- Func Example1() ; Example string to table Local $sSum, $sOut Local $sData = _ "Company" & @TAB & "Contact" & @TAB & "Revenue" & @CRLF & _ "Alfreds Futterkiste" & @TAB & "Maria Anders" & @TAB & "1200" & @CRLF & _ "Centro Moctezuma" & @TAB & "Francisco Chang" & @TAB & "950" & @CRLF & _ "Island Trading" & @TAB & "Helen Bennett" & @TAB & "15800" $sOut = _StringToTable($sData, 0, @TAB, "L,C,R") ConsoleWrite($sOut & @CRLF & @CRLF) $sSum &= $sOut & @CRLF & @CRLF $sOut = _StringToTable($sData, 1, @TAB, "L,C,R") ConsoleWrite($sOut & @CRLF & @CRLF) $sSum &= $sOut & @CRLF & @CRLF $sOut = _StringToTable($sData, 2, @TAB, "L,C,R") ConsoleWrite($sOut & @CRLF & @CRLF) $sSum &= $sOut & @CRLF & @CRLF & @CRLF $sSum &= "Notes: For the correct display of output, it is recommended to use a MonoSpace font." & @CRLF $sSum &= "Window MonoSpace font: Consolas, DejaVu Sans Mono, Courier New, Lucida Console" & @CRLF ClipPut($sSum) ShellExecute("notepad.exe") WinWaitActive("[CLASS:Notepad]", "", 5) Sleep(100) Send("^v") EndFunc ;==>Example1 ;--------------------------------------------------------------------------------------- Func Example2() ; Example 2D array to table ; Make example array Local $aArray[10][5] For $i = 0 To 9 For $j = 0 To 4 $aArray[$i][$j] = $i & "-" & $j Next Next ;_ArrayDisplay($aArray, "example array") ; Make header and insert to array (when needed) Local $sHeader = "Column 0|Column 1|Column 2|Column 3|Column 4" _ArrayInsert($aArray, 0, $sHeader) If @error Then Exit MsgBox(16, "@error: " & @error, "Something went wrong with _ArrayInsert()") Local $sOut = _StringToTable($aArray, 3, -1, "C,C,C,C,C") ConsoleWrite($sOut & @CRLF & @CRLF) ClipPut($sOut) ShellExecute("notepad.exe") WinWaitActive("[CLASS:Notepad]", "", 5) Sleep(100) Send("^v") EndFunc ;==>Example2 ;--------------------------------------------------------------------------------------- Func Example3() ; Example 1D array to table Local $sMonth = "Months, January, February, March, April, May, June, July, August, September, October, November, December" Local $aMonth = StringSplit($sMonth, ", ", 3) Local $sOut = _StringToTable($aMonth, 3, -1, "C") ConsoleWrite($sOut & @CRLF & @CRLF) ClipPut($sOut) ShellExecute("notepad.exe") WinWaitActive("[CLASS:Notepad]", "", 5) Sleep(100) Send("^v") EndFunc ;==>Example3 ;--------------------------------------------------------------------------------------- Func Example4() ; Example floating point format Local $sData = "" ; from https://www.autoitscript.com/forum/topic/212833-json-udf-using-json-c/#findComment-1542670 $sData &= " name | time[ms] | factor | Std. Dev | Std. Err. | min | max | range |" & @CRLF $sData &= " StringRegExp only | 1.691 | 1 | 0.351 | 0.035 | 1.304 | 3.167 | 1.863 |" & @CRLF $sData &= " jq UDF | 32.933 | 19.48 | 2.929 | 0.293 | 29.308 | 43.169 | 13.861 |" & @CRLF $sData &= " JsonC-UDF | 51.086 | 30.21 | 3.205 | 0.321 | 45.625 | 63.46 | 17.835 |" & @CRLF $sData &= " pure AutoIt JSON-UDF | 97.916 | 57.9 | 5.685 | 0.569 | 86.362 | 113.467 | 27.105 |" & @CRLF $sData &= " JSMN-based JSON-UDF | 108.248 | 64.01 | 5.512 | 0.551 | 99.029 | 130.864 | 31.835 |" & @CRLF Local $sOut = _StringToTable($sData, 3, "|", "L,3,2,3,3,3,3,3") ConsoleWrite($sOut & @CRLF & @CRLF) ClipPut($sOut) ShellExecute("notepad.exe") WinWaitActive("[CLASS:Notepad]", "", 5) Sleep(100) Send("^v") EndFunc ;==>Example4 ;--------------------------------------------------------------------------------------- Func Example5() ; Example for new frame style Local $sData = "" ; from https://www.autoitscript.com/forum/topic/212833-json-udf-using-json-c/#findComment-1542670 $sData &= " name | time[ms] | factor | Std. Dev | Std. Err. | min | max | range |" & @CRLF $sData &= " StringRegExp only | 1.691 | 1 | 0.351 | 0.035 | 1.304 | 3.167 | 1.863 |" & @CRLF $sData &= " jq UDF | 32.933 | 19.48 | 2.929 | 0.293 | 29.308 | 43.169 | 13.861 |" & @CRLF $sData &= " JsonC-UDF | 51.086 | 30.21 | 3.205 | 0.321 | 45.625 | 63.46 | 17.835 |" & @CRLF $sData &= " pure AutoIt JSON-UDF | 97.916 | 57.9 | 5.685 | 0.569 | 86.362 | 113.467 | 27.105 |" & @CRLF $sData &= " JSMN-based JSON-UDF | 108.248 | 64.01 | 5.512 | 0.551 | 99.029 | 130.864 | 31.835 |" & @CRLF Local $sOut = _DblFrame($sData, "|", "L,3,2,3,3,3,3,3") ConsoleWrite($sOut & @CRLF & @CRLF) ClipPut($sOut) ShellExecute("notepad.exe") WinWaitActive("[CLASS:Notepad]", "", 5) Sleep(100) Send("^v") EndFunc ;==>Example5 ;--------------------------------------------------------------------------------------- ; #FUNCTION# -------------------------------------------------------------------------------------------------------------------- ; Name...........: _StringToTable ; Description....: Converts a string or array to a formatted table with alignment and frame options. ; Syntax.........: _StringToTable( $vString [, $iFrame = 2 [, $sSeparator = @TAB [, $sAlign = ""]]] ) ; Parameters.....: $vString - The input string or array containing data values. ; $iFrame - [optional] Frame type (0=NoFrame, 1=FrameNoHeader, 2=FrameAndHeader. (Default is 2) ; $sSeparator - [optional] Separator used in the input string. (Default is @TAB) ; $sAlign - [optional] Alignment options for each column "L,R,C,[0-9]". (Default is "" (left-aligned)) ; Return values..: The formatted table as a string. ; Author ........: ioa747 ; Notes .........: For the correct display of output, it is recommended to use a MonoSpace font. ; Window MonoSpace font: Consolas, DejaVu Sans Mono, Courier New, Lucida Console ; Link ..........: https://www.autoitscript.com/forum/topic/212876-_stringtotable/ ; Dependencies...: __FormatCell() ;-------------------------------------------------------------------------------------------------------------------------------- Func _StringToTable($vString, $iFrame = 2, $sSeparator = @TAB, $sAlign = "") ;Local $hTimer = TimerInit() If $iFrame < 0 Or $iFrame > 2 Or $iFrame = Default Then $iFrame = 2 If $sSeparator = Default Or $sSeparator = -1 Then $sSeparator = @TAB ; Convert array to string If IsArray($vString) Then Local $b2D = (UBound($vString, 0) = 1 ? False : True) If Not $b2D Then _ArrayColInsert($vString, 1) $vString = _ArrayToString($vString, $sSeparator) EndIf ;Prepare string $vString = StringRegExpReplace($vString, "(\r\n|\n)", @CRLF) $vString = StringReplace($vString, $sSeparator & @CRLF, @CRLF) $vString = StringReplace($vString, @CRLF & $sSeparator, @CRLF) $vString = StringStripCR(StringRegExpReplace($vString, "(\r\n)$", "")) ;ConsoleWrite($vString & @CRLF) Local $aRows = StringSplit($vString, @LF, 1) If $aRows[0] = 0 Then Return SetError(1, 0, "") Local $aTable[UBound($aRows)][0] Local $iLen, $iCols = 0 ; initialize rows and columns For $i = 1 To $aRows[0] Local $aCols = StringSplit($aRows[$i], $sSeparator, 1) If $i = 1 Then $iCols = $aCols[0] ReDim $aTable[$aRows[0]][$iCols] Else If $aCols[0] < $iCols Then ReDim $aCols[$iCols + 1] ;** EndIf For $j = 0 To $iCols - 1 $aTable[$i - 1][$j] = StringStripWS($aCols[$j + 1], 3) Next Next ; find the max column widths Local $aColWidths[$iCols] For $j = 0 To $iCols - 1 $aColWidths[$j] = 0 For $i = 0 To UBound($aTable) - 1 $iLen = StringLen($aTable[$i][$j]) If $aColWidths[$j] < $iLen Then $aColWidths[$j] = $iLen Next Next ; Alignment initialize Local $aAlign[$iCols] If $sAlign <> "" Then Local $aRawAlign = StringSplit($sAlign, ",", 2) Local $iRawCnt = UBound($aRawAlign) For $j = 0 To $iCols - 1 If $j >= $iRawCnt Then $aAlign[$j] = "L" Else $aAlign[$j] = StringStripWS($aRawAlign[$j], 3) If Not StringRegExp($aAlign[$j], "(?i)^(L|R|C|[0-9])$") Then $aAlign[$j] = "L" If StringRegExp($aAlign[$j], "^([0-9])$") Then ; re-find the max column widths For $i = 0 To UBound($aTable) - 1 $iLen = StringLen(StringFormat("%." & $aAlign[$j] & "f", $aTable[$i][$j])) $aColWidths[$j] = $aColWidths[$j] > $iLen ? $aColWidths[$j] : $iLen Next EndIf EndIf Next Else For $j = 0 To $iCols - 1 $aAlign[$j] = "L" Next EndIf Local Const $TL = "┌", $TR = "┐", $BL = "└", $BR = "┘", $H = "─", $V = "│", _ $C = "┼", $TH = "┬", $CH = "┴", $LH = "├", $RH = "┤" Local $bHeader = ($iFrame = 2) Local $bBorder = ($iFrame = 1 Or $iFrame = 2) Local $sPre = ($iFrame = 0 ? "" : " ") Local $sResult = "" ; Top border If $bBorder Then $sResult &= $TL For $j = 0 To $iCols - 1 $sResult &= _StringRepeat($H, $aColWidths[$j] + 2) $sResult &= ($j < $iCols - 1) ? $TH : $TR Next $sResult &= @LF EndIf ; Header row If $bHeader Then If $bBorder Then $sResult &= $V For $j = 0 To $iCols - 1 $sResult &= $sPre & __FormatCell($aTable[0][$j], $aColWidths[$j], $aAlign[$j]) & " " If $j < $iCols - 1 Then $sResult &= ($bBorder ? $V : "") Next If $bBorder Then $sResult &= $V $sResult &= @LF ; Header separator If $bBorder Then $sResult &= $LH For $j = 0 To $iCols - 1 $sResult &= _StringRepeat($H, $aColWidths[$j] + 2) If $j < $iCols - 1 Then $sResult &= ($bBorder ? $C : "") Else If $bBorder Then $sResult &= $RH EndIf Next $sResult &= @LF EndIf ; Data rows For $i = ($bHeader ? 1 : 0) To UBound($aTable) - 1 If $bBorder = 2 Then $sResult &= $V For $j = 0 To $iCols - 1 $sResult &= $sPre & __FormatCell($aTable[$i][$j], $aColWidths[$j], $aAlign[$j]) & " " If $j < $iCols - 1 Then $sResult &= $bBorder ? $V : "" Next If $bBorder Then $sResult &= $V $sResult &= @LF Next ; Bottom border If $bBorder Then $sResult &= $BL For $j = 0 To $iCols - 1 $sResult &= _StringRepeat($H, $aColWidths[$j] + 2) $sResult &= ($j < $iCols - 1) ? $CH : $BR Next EndIf ;$sResult = BinaryToString(StringToBinary($sResult, 4), 1) ; * ?? ;ConsoleWrite("> processed in: " & Round(TimerDiff($hTimer)) & " ms " & @LF) Return $sResult EndFunc ;==>_StringToTable ;--------------------------------------------------------------------------------------- Func __FormatCell($text, $width, $align) ; internal Local $Num = $align If StringRegExp($align, "^([0-9])$") Then $align = "N" Switch $align Case "N" ; "%.2f" If StringRegExp($text, "^[+-]?(\d*\.\d+|\d+\.?)$") Then Return StringFormat("%" & $width & "s", StringFormat("%." & $Num & "f", $text)) Else Return StringFormat("%" & $width & "s", $text) EndIf Case "R" Return StringFormat("%" & $width & "s", $text) Case "C" Local $pad = $width - StringLen($text) Local $left = Floor($pad / 2) Local $right = $pad - $left Return _StringRepeat(" ", $left) & $text & _StringRepeat(" ", $right) Case Else ; "L" Return StringFormat("%-" & $width & "s", $text) EndSwitch EndFunc ;==>__FormatCell ;--------------------------------------------------------------------------------------- Func _DblFrame($vString, $sSeparator = @TAB, $sAlign = "") ; * style template Local $sData = _StringToTable($vString, 3, $sSeparator, $sAlign) Local $aData = StringSplit($sData, @LF, 3) Local $iCnt = UBound($aData) - 1 Local $sOut For $i = 0 To $iCnt Switch $i Case 0 $aData[$i] = StringReplace($aData[$i], "┌", "╔", 1, 2) $aData[$i] = StringReplace($aData[$i], "─", "═", 0, 2) $aData[$i] = StringReplace($aData[$i], "┬", "╤", 0, 2) $aData[$i] = StringReplace($aData[$i], "┐", "╗", -1, 2) Case 2 $aData[$i] = StringReplace($aData[$i], "├", "╟", 1, 2) $aData[$i] = StringReplace($aData[$i], "┤", "╢", -1, 2) Case $iCnt $aData[$i] = StringReplace($aData[$i], "└", "╚", 1, 2) $aData[$i] = StringReplace($aData[$i], "─", "═", 0, 2) $aData[$i] = StringReplace($aData[$i], "┴", "╧", 0, 2) $aData[$i] = StringReplace($aData[$i], "┘", "╝", -1, 2) Case Else $aData[$i] = StringReplace($aData[$i], "│", "║", 1, 2) $aData[$i] = StringReplace($aData[$i], "│", "║", -1, 2) EndSwitch $sOut &= $aData[$i] & @CRLF Next $sOut = StringReplace($sOut, @CRLF, "", -1, 2) Return $sOut EndFunc ;==>_DblFrame ;--------------------------------------------------------------------------------------- Please, every comment is appreciated! leave your comments and experiences here! Thank you very much Relative: https://www.autoitscript.com/forum/topic/211237-treestructuredir/
    1 point
  3. argumentum

    SciTE AI assistant

    edited my 1st post and added OllamaAssistant_DefaultURL() It'll be much better if helper functions are used for default values. I guess the same should be done for the model to be used and any other default.
    1 point
  4. argumentum

    SciTE AI assistant

    ... ... Global $__g_OllamaAssistant_DefaultURL = "http://localhost:11434" Func OllamaAssistant_DefaultURL($sStr = Default) If $sStr <> Default Then $__g_OllamaAssistant_DefaultURL = $sStr Return $__g_OllamaAssistant_DefaultURL EndFunc ConsoleWrite(Ollama_IsModelAvailable() & @CRLF) If @error Then Exit 5 Func Ollama_IsModelAvailable($sStr = "qwen2.5-coder") Local $sRet = OllamaAPI() ; default is get models at default URL If @error Then ConsoleWrite("! Ollama is not running there =(" & @CRLF) Return SetError(1, 0, "") EndIf If StringInStr($sRet, $sStr) Then Return $sRet ConsoleWrite(@CRLF & $sRet & @CRLF & "! the model was not found. Pull it ! =)" & @CRLF ) Return SetError(2, 0, $sRet) EndFunc ; "/api/tags" ; List models that are available locally. ; "/api/ps" ; List models that are currently loaded into memory. ; "/api/pull" '{"model": "qwen2.5-coder:3b"}' ; well, pull the model Func OllamaAPI($sAPI = "/api/tags", $sURL = $__g_OllamaAssistant_DefaultURL) Local $sStr = BinaryToString(InetRead($sURL & $sAPI)) ; this is not the function I should use, but it works to present the idea Return SetError(@error, @extended, $sStr) EndFunc ; ..you may need to retry at times ?, ..I don't have much experience with it to know much ConsoleWrite('HotKeySet = ' & HotKeySet("{END}", "GenerateFunctionHeader") & @CRLF) ; * <-- ... ... Nice !. I was thinking yesterday that "I don't wanna leave SciTE" in a child tantrum kind of childish voice So, I highlighted a function, pressed the end key and got me a "1" in the console. But I don't know if is all that is so, add a start and end line, like: ---- 8< ---- start 1 ---- >8 ---- end so I get some feedback. Again, thanks for working on my wish
    1 point
  5. pixelsearch

    _StringToTable

    I won't be at home all day (spending some nice time with family) so I'll take a deep look at your post tomorrow. Just a word concerning BinaryToString(StringToBinary()) : as noone else complained about the Console output, I suggest you do nothing for now. Have a great sunday
    1 point
  6. pixelsearch

    _StringToTable

    Glad we thought alike Wish I entered this thread earlier, to suggest 0-9 (instead of 0-3) and also a 4th parameter string without "F" at all, so the user doesn't need to type all the useless "F", then the code could be : ; $sOut = _StringToTable($sData, Default, Default, "C, 2F, 6F, 3F, 3F, 0F") $sOut = _StringToTable($sData, Default, Default, "c, 2, 6, 3, 3, 0") Now the 4th parameter, when splitted, is composed in all cases of only 1 character (easier to handle in UDF), then you can add the mandatory lowercase "f" for StringFormat where needed in __FormatCell() I guess it's a bit late to think about it and after all, if someone (me !) wants to get rid of the numerous "F", he can tweak your UDF at his wish. The "problem" when tweaking the UDF is that each time you'll upload a new release, all personal tweaks should be re-applied to the new release. That's why I start keeping your original source code (starting with version 0.4) in a read-only file, like this : When you'll upload version 0.5, then I'll save it to a new protected file (guess its name !) and compare it to your preceding version 0.4, so I can apply your new changes to my personal version (instead of applying my numerous tweaks to your new version) For the record, I got already another mandatory tweak, for instance : ; ConsoleWrite($sOut & @CRLF & @CRLF) ConsoleWrite(BinaryToString(StringToBinary($sOut, 4), 1) & @crlf & @crlf) Probably a wrong code page on my computer (or I don't know what), but I won't spend any more time to fix this on my computer, it's just wasted time. Glad @jchd suggested once the "BinaryToString(StringToBinary())" way to solve this, it works fine, all the time, thanks jchd ! For the record (ioa747) I'm very happy with the "box-drawing characters" you choosed for your UDF. I'm not into the "double line" characters at all but I understand some users like them a lot. To each his own and everybody's happy. Thanks for reading and have a great evening
    1 point
  7. I haven't touched AutoIt in over a year, so I'm a bit rusty. Here is an attempt to incorporate the Get/Set property into @trancexx ObjectFromTag code, similar to the AutoItObject UDF. Example 1: #include "ObjFromTag_v1a UDF.au3" Global $oError = ObjEvent("AutoIt.Error", "_ErrFunc") __Example1() Func __Example1() ConsoleWrite("> __Example4() " & @CRLF) Local $t_TestObj Local $o_TestObj = __ObjectFromTag("__MyInterface_", '', $t_TestObj, 'int Ln;char Msg[30];') __SetProperty($o_TestObj, "Ln", 555) __SetProperty($o_TestObj, "Msg", 'Is it working.') ConsoleWrite("+>>> Ln : " & __GetProperty($o_TestObj, "Ln") & @CRLF) ConsoleWrite("+>>> Msg : " & __GetProperty($o_TestObj, "Msg") & @CRLF) If IsObj($o_TestObj) Then $o_TestObj = 0 __DeleteObjectFromTag($t_TestObj) ConsoleWrite("----The End----" & @CRLF) EndFunc Func __MyInterface_QueryInterface($pSelf, $pRIID, $pObj) Return __QueryInterface($pSelf, $pRIID, $pObj) EndFunc Func __MyInterface_AddRef($pSelf) Return __AddRef($pSelf) EndFunc Func __MyInterface_Release($pSelf) Return __Release($pSelf) EndFunc Func _ErrFunc() ConsoleWrite("! COM Error ! Number: 0x" & Hex($oError.number, 8) & " ScriptLine: " & $oError.scriptline & " - " & $oError.windescription & @CRLF) Return EndFunc ;==>_ErrFunc Example 2: #include "ObjFromTag_v1a UDF.au3" Global $oError = ObjEvent("AutoIt.Error", "_ErrFunc") __Example2() Func __Example2() ConsoleWrite("> __Example2() " & @CRLF) Local $t_TestObj Local $o_TestObj = __ObjectFromTag("__MyInterface_", 'Open hresult();Close hresult();', $t_TestObj, 'handle WinHnd;', False) If Not IsObj($o_TestObj) Then Return $o_TestObj.Open() MsgBox(0, '', 'Clicked to closed Notepad....') $o_TestObj.Close() If IsObj($o_TestObj) Then $o_TestObj = 0 __DeleteObjectFromTag($t_TestObj) EndFunc Func __MyInterface_Open($pSelf) Run("notepad.exe") WinWait("[CLASS:Notepad]", "", 10) Local $hWnd = WinGetHandle("[CLASS:Notepad]") __SetProperty($pSelf, "WinHnd", $hWnd) Return 0 EndFunc Func __MyInterface_Close($pSelf) WinClose(__GetProperty($pSelf, "WinHnd")) Return 0 EndFunc Func _ErrFunc() ConsoleWrite("! COM Error ! Number: 0x" & Hex($oError.number, 8) & " ScriptLine: " & $oError.scriptline & " - " & $oError.windescription & @CRLF) Return EndFunc ;==>_ErrFunc Example 3: #include "ObjFromTag_v1a UDF.au3" Global $oError = ObjEvent("AutoIt.Error", "_ErrFunc") __Example3() Func __Example3() ConsoleWrite("> __Example3() " & @CRLF) Local $t_TestObj Local $o_TestObj = __ObjectFromTag("__MyInterface_", 'MsgBox hresult();', $t_TestObj, 'char Title[10];char Text[30];int Flag;', False) If Not IsObj($o_TestObj) Then Return __SetProperty($o_TestObj, "Title", "Something") __SetProperty($o_TestObj, "Text", 'Is it working.') __SetProperty($o_TestObj, "Flag", 64 + 262144) $o_TestObj.MsgBox() If IsObj($o_TestObj) Then $o_TestObj = 0 __DeleteObjectFromTag($t_TestObj) ConsoleWrite("----The End----" & @CRLF) EndFunc Func __MyInterface_MsgBox($pSelf) MsgBox(__GetProperty($pSelf, "Flag"), __GetProperty($pSelf, "Title"), __GetProperty($pSelf, "Text")) EndFunc Func _ErrFunc() ConsoleWrite("! COM Error ! Number: 0x" & Hex($oError.number, 8) & " ScriptLine: " & $oError.scriptline & " - " & $oError.windescription & @CRLF) Return EndFunc ;==>_ErrFunc Example 4: #include "ObjFromTag_v1a UDF.au3" Global $oError = ObjEvent("AutoIt.Error", "_ErrFunc") __Example3() Func __Example3() ConsoleWrite("> __Example3() " & @CRLF) Local $t_TestObj Local $o_TestObj = __ObjectFromTag("", 'DisplayBook str();', $t_TestObj, 'char book[50];char author[15];int year;', False) If Not IsObj($o_TestObj) Then Return __SetProperty($o_TestObj, "book", "Harry Potter and the Sorcerer's Stone") __SetProperty($o_TestObj, "author", 'J. K. Rowling') __SetProperty($o_TestObj, "year", 1997) MsgBox(0, 'Book', $o_TestObj.DisplayBook) If IsObj($o_TestObj) Then $o_TestObj = 0 __DeleteObjectFromTag($t_TestObj) ConsoleWrite("----The End----" & @CRLF) EndFunc Func DisplayBook($pSelf) Local $sString = 'The novel ' & __GetProperty($pSelf, "book") & ' ,' & _ ' written by author ' & __GetProperty($pSelf, "author") & _ ' and published in ' & __GetProperty($pSelf, "year") & '.' Local Static $tString = DllStructCreate(StringFormat("char str[%d]", StringLen($sString) + 1)) ;+1 to null terminate! $tString.str = $sString Return DllStructGetPtr($tString) EndFunc Func _ErrFunc() ConsoleWrite("! COM Error ! Number: 0x" & Hex($oError.number, 8) & " ScriptLine: " & $oError.scriptline & " - " & $oError.windescription & @CRLF) Return EndFunc ;==>_ErrFunc Example 5: #include "ObjFromTag_v1a UDF.au3" Global $oError = ObjEvent("AutoIt.Error", "_ErrFunc") __Example3() Func __Example3() ConsoleWrite("> __Example3() " & @CRLF) Local $t_TestObj Local $o_TestObj = __ObjectFromTag("", 'Call_DisplayBook hresult();DisplayBook str();', $t_TestObj, 'char book[50];char author[15];int year;', False) If Not IsObj($o_TestObj) Then Return __SetProperty($o_TestObj, "book", "Harry Potter and the Sorcerer's Stone") __SetProperty($o_TestObj, "author", 'J. K. Rowling') __SetProperty($o_TestObj, "year", 1997) $o_TestObj.Call_DisplayBook If IsObj($o_TestObj) Then $o_TestObj = 0 __DeleteObjectFromTag($t_TestObj) ConsoleWrite("----The End----" & @CRLF) EndFunc Func Call_DisplayBook($pSelf) Local $o_Tag = 'Call_DisplayBook hresult();DisplayBook str();' Local $o__TestObj = ObjCreateInterface($pSelf, '{00000000-0000-0000-C000-000000000046}', $o_Tag, False) MsgBox(0, "", $o__TestObj.DisplayBook) $o__TestObj = 0 Return 0 EndFunc Func DisplayBook($pSelf) Local $sString = 'The novel ' & __GetProperty($pSelf, "book") & ' ,' & _ ' written by author ' & __GetProperty($pSelf, "author") & _ ' and published in ' & __GetProperty($pSelf, "year") & '.' Local Static $tString = DllStructCreate(StringFormat("char str[%d]", StringLen($sString) + 1)) ;+1 to null terminate! $tString.str = $sString Return DllStructGetPtr($tString) EndFunc Func _ErrFunc() ConsoleWrite("! COM Error ! Number: 0x" & Hex($oError.number, 8) & " ScriptLine: " & $oError.scriptline & " - " & $oError.windescription & @CRLF) Return EndFunc ;==>_ErrFunc Example 6: #include "ObjFromTag_v1a UDF.au3" Global $oError = ObjEvent("AutoIt.Error", "_ErrFunc") __Example3() Func __Example3() ConsoleWrite("> __Example3() " & @CRLF) Local $o_Dict = ObjCreate( "Scripting.Dictionary" ) $o_Dict.add("book", "Harry Potter and the Sorcerer's Stone") $o_Dict.add("author", "J. K. Rowling") $o_Dict.add("year", 1997) Local $t_TestObj Local $o_TestObj = __ObjectFromTag("", 'DisplayBook str();', $t_TestObj, 'ptr oDist;', False) If Not IsObj($o_TestObj) Then Return __SetProperty($o_TestObj, "oDist", $o_Dict) MsgBox(0, 'Book', $o_TestObj.DisplayBook) If IsObj($o_Dict) Then $o_Dict = 0 If IsObj($o_TestObj) Then $o_TestObj = 0 __DeleteObjectFromTag($t_TestObj) ConsoleWrite("----The End----" & @CRLF) EndFunc Func DisplayBook($pSelf) Local $oo_Dict = __ConvertPtrToIDispatch(__GetProperty($pSelf, "oDist")) Local $sString = 'The novel ' & $oo_Dict.Item("book") & ' ,' & _ ' written by author ' & $oo_Dict.Item("author") & _ ' and published in ' & $oo_Dict.Item("year") & '.' Local Static $tString = DllStructCreate(StringFormat("char str[%d]", StringLen($sString) + 1)) ;+1 to null terminate! $tString.str = $sString $oo_Dict = 0 Return DllStructGetPtr($tString) EndFunc Func __ConvertPtrToIDispatch($pIDispatch) ; https://www.autoitscript.com/forum/topic/107678-hooking-into-the-idispatch-interface/#comments ; This would have been 10000x easier if autoit had supported the idispatch* type in dllstructs... ; Fortunetely memcpy can copy the pointer into a idispatch*, lucky us. Local $aCall = DllCall("kernel32.dll", "none", "RtlMoveMemory", _ "idispatch*", 0, _ "ptr*", $pIDispatch, _ "dword", 4) If @error Then Return SetError(1, 0, 0) Return $aCall[1] EndFunc ;==>ConvertPtrToIDispatch Func _ErrFunc() ConsoleWrite("! COM Error ! Number: 0x" & Hex($oError.number, 8) & " ScriptLine: " & $oError.scriptline & " - " & $oError.windescription & @CRLF) Return EndFunc ;==>_ErrFunc Example 7: #include "ObjFromTag_v1a UDF.au3" Global $oError = ObjEvent("AutoIt.Error", "_ErrFunc") __Example3() Func __Example3() ConsoleWrite("> __Example3() " & @CRLF) Local $t_BookObj, $t_AuthorObj Local $o_BookObj = __ObjectFromTag("", 'BookList hresult(bstr;bstr);', $t_BookObj, 'char book[50];int year;', False) Local $o_AuthorObj = __ObjectFromTag("", 'DisplayBook str(bstr);', $t_AuthorObj, 'char author[15];ptr oBook;', False) __SetProperty($o_AuthorObj, "oBook", $o_BookObj()) $o_BookObj.BookList("Harry Potter and the Sorcerer's Stone", 1997) MsgBox(0, 'Book', $o_AuthorObj.DisplayBook('J. K. Rowling')) If IsObj($o_AuthorObj) Then $o_AuthorObj = 0 If IsObj($o_BookObj) Then $o_BookObj = 0 __DeleteObjectFromTag($t_AuthorObj) __DeleteObjectFromTag($t_BookObj) ConsoleWrite("----The End----" & @CRLF) EndFunc Func BookList($pSelf, $pStrA, $pStrB) __SetProperty($pSelf, "book", __Bstr_ToString($pStrA)) __SetProperty($pSelf, "year", __Bstr_ToString($pStrB)) EndFunc Func DisplayBook($pSelf, $pStrA) __SetProperty($pSelf, "author", __Bstr_ToString($pStrA)) Local $pBookList = __GetProperty($pSelf, "oBook") Local $sString = 'The novel ' & __GetProperty($pBookList, "book") & ' ,' & _ ' written by author ' & __GetProperty($pSelf, "author") & _ ' and published in ' & __GetProperty($pBookList, "year") & '.' Local Static $tString = DllStructCreate(StringFormat("char str[%d]", StringLen($sString) + 1)) ;+1 to null terminate! $tString.str = $sString Return DllStructGetPtr($tString) EndFunc Func __Bstr_ToString($pString) Local $o_Data = DllStructGetData(DllStructCreate("wchar[" & _ DllStructGetData(DllStructCreate("dword", $pString - 4), 1) / 2 & "]", $pString), 1) Return $o_Data EndFunc Func _ErrFunc() ConsoleWrite("! COM Error ! Number: 0x" & Hex($oError.number, 8) & " ScriptLine: " & $oError.scriptline & " - " & $oError.windescription & @CRLF) Return EndFunc ;==>_ErrFunc Example 8: #include "ObjFromTag_v1a UDF.au3" Global $oError = ObjEvent("AutoIt.Error", "_ErrFunc") __Example3() Func __Example3() ConsoleWrite("> __Example3() " & @CRLF) Local $t_TestObj Local $o_TestObj = __ObjectFromTag("", 'Call_DisplayBook hresult();DisplayBook str();', $t_TestObj, 'char book[50];char author[15];int year;', False) If Not IsObj($o_TestObj) Then Return __SetProperty($o_TestObj, "book", "Harry Potter and the Sorcerer's Stone") __SetProperty($o_TestObj, "author", 'J. K. Rowling') __SetProperty($o_TestObj, "year", 1997) $o_TestObj.Call_DisplayBook If IsObj($o_TestObj) Then $o_TestObj = 0 __DeleteObjectFromTag($t_TestObj) ConsoleWrite("----The End----" & @CRLF) EndFunc Func Call_DisplayBook($pSelf) Local $pEntryPoint = __DereferencePointer($pSelf) Local $pDisplayBook = __DereferencePointer($pEntryPoint + 1 * 4) Local $aRet = DllCallAddress("str", $pDisplayBook, "ptr", $pSelf) MsgBox(0, "", $aRet[0]) Return 0 EndFunc Func DisplayBook($pSelf) Local $sString = 'The novel ' & __GetProperty($pSelf, "book") & ' ,' & _ ' written by author ' & __GetProperty($pSelf, "author") & _ ' and published in ' & __GetProperty($pSelf, "year") & '.' Local Static $tString = DllStructCreate(StringFormat("char str[%d]", StringLen($sString) + 1)) ;+1 to null terminate! $tString.str = $sString Return DllStructGetPtr($tString) EndFunc Func __DereferencePointer($ptr) Local $tempstruct = DllStructCreate("ptr", $ptr) Return DllStructGetData($tempstruct, 1) EndFunc Func _ErrFunc() ConsoleWrite("! COM Error ! Number: 0x" & Hex($oError.number, 8) & " ScriptLine: " & $oError.scriptline & " - " & $oError.windescription & @CRLF) Return EndFunc ;==>_ErrFunc for more about objectfromtag you can follow this thread created by @LarsJ https://www.autoitscript.com/forum/topic/205154-using-objcreateinterface-and-objectfromtag-functions/ and do check out code posted by @trancexx @ProgAndy @monoceres @wolf9228 @LarsJ @Danyfirex and @Bilgus. on this topic. Note: You can also register this object, created using __ObjectFromTag, within the Running Object Table (ROT). ObjFromTag_v1a UDF.au3
    1 point
  8. #include <Constants.au3> $run = Run("taskkill /F /T /IM processnametokill.exe", "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD) While 1 $line = StdoutRead($run) If @error Then ExitLoop MsgBox(0, "Sucessfull:", $line) Wend While 1 $line = StderrRead($run) If @error Then ExitLoop MsgBox(0, "Error:", $line) WEnd
    1 point
×
×
  • Create New...