Jump to content

All Activity

This stream auto-updates

  1. Past hour
  2. Decided to write something with a little more detail and screenshot to make sense. Your response: $oImgs_checkbox = _WD_FindElement($oIE, , , True, "imgChkBox") $sStrategy - Locator strategy. See defined constant $_WD_LOCATOR_* for allowed values The examples I saw that used $sStrategy/$_WD_LOCATOR_ were finding paths. I have lets say 9 checkboxes on this page. And to create the array of them. It sounds like I need to use $bMultiple parameter because there are numerous. I want to identify them by the name which from the page source looks to be imgChkBox. To use Find elements, do I need to provide the WD_Locator parameter and then also provide the object. I also asked a new question in there. Prior with IE, we had just found the name of the item which was "img" and it created the array of all the checkboxes. Sounds like this is a bit different. From examples i've seen that people are using webdriver for are web base automation. I figured I'd share a screenshot to help express what it is. We have a windows embedded application that is grabbing this HTML pages. Inside the HTML it has dropdown menu's and checkboxes.
  3. Not sure why you started a new thread for this. Did you see my response from several weeks ago in your prior thread?
  4. Today
  5. It doesn't close on me either. Are you running it compiled ? What changed recently that made the script exit ?
  6. Run the code from SciTE and check if there is something in the console when you say the script is closing.
  7. I've run it and no such thing happens to me. Plus I don't see anything that would do it in the code
  8. I have a Number pad script I found a while back. I need it to stay open and on top of all other windows. It used to work until recently. Now it closes after being idle for about 30 seconds. Is there anything I can do to keep it from closing? I will attach the script. I urgently need to fix this, but I'm not the best at scripting languages. Numpad.au3
  9. Changed the colors for my dark theme maybe you can add it in a next build Thanks for sharing. Nice tool to have.
  10. Hello All, I have a script I'm trying to fix. I've gone through the IE functions and I'm trying to fix them to allow the script to get up and running again. I'm currently on the _WD_FindElement function and I'm not sure if I'm modifying this correctly. A question I have is, what is the correct syntax for this function? Syntax ........: _WD_FindElement($sSession, $sStrategy, $sSelector[, $sStartNodeID = Default[, $bMultiple = Default[, $oImgs_checkbox = _WD_FindElement($oIE, , , True, "imgChkBox") What this is trying to do is record the count of how many checkboxes there are. Then check them. I think it put's them all into an array and then checks them. Originally the checkboxes on the page were called "Img" I think they may be "imgChkBox" when I viewed page source that is the name that was displayed. The Autoit Window tool did not locate the items. Maybe I have an issue with the window tool? When I also go into calculator it does not find the buttons in windows calculator. Also if anyone has any alternative methods/ideas to automate something like this I would love to hear! ;---------------------------------------------------------------------------------------------------------------------------------------------- Func BrowserControlFocus() ; Set focus on the Browser control - write which page is being tested and the location of the file. ; Output the name and location of the html page being tested. sleep(5000) $hWnd=WinGetHandle("[CLASS:Chrome_RenderWidgetHostHWND; INSTANCE:1]") $oIE = _WD_Attach($hWnd,"embedded") _WD_LoadWait($oIE) WriteToFile($outputFile,"The displayed page is the: " &_WD_Action($oIE, "title") & " page") WriteToFile($outputFile,"File Location is: " & _WD_Action($oIE, "locationurl")) EndFunc ;_IEPropertyGet ( ByRef $oObject, $sProperty ) ; ;$oObject Object variable of an InternetExplorer.Application or DOM element ;$sProperty Property selection (see remarks) ;WriteToFile($outputFile,"The displayed page is the: " & _WD_Action($sSession, 'title') & " page") ;WriteToFile($outputFile,"File Location is: " & _WD_Action($sSession, 'url')) ; ; ; ; ;---------------------------------------------------------------------------------------------------------------------------------------------- ;Find all the instances of the checkbox, put the ID name of the checkbox image into an array. ID name is hard coded in the ; THis rountine is specific to the ID name in the HTML file. If the name changes then this routine will break. The checkbox id is ; XXi where xx is a number value Func CheckBoxID() _WD_LoadWait($oIE) Global $Checkbox_count = -1 $oImgs_checkbox = _WD_FindElement($oIE, , , True, "imgChkBox") $ClearChecksStr = "ClearChecks Button" ; Count the number of checkboxes and put the id number in an array For $oImg_Checkbox in $oImgs_checkbox If String($oImg_Checkbox.className) = "imgChkBox" Then $Checkbox_count = $Checkbox_count+1 $checkbox_array[$Checkbox_count] = $oImg_Checkbox.id ;WriteToFile($outputFile,"Debug"&$checkbox_array[$Checkbox_count]) EndIf Next if ($Checkbox_count = -1) Then if Not ControlCommand("", "", $SIMPLE_Clearchks_btnID,"IsEnabled") Then WriteToFile($outputFile, "ClearChecks button is not enabled as expected") Else WriteToFile($outputFile, "ClearChecks button is enabled and should not be") $flagFail = 1 EndIf Else if ControlCommand("", "", $SIMPLE_Clearchks_btnID,"IsEnabled") Then WriteToFile($outputFile, "ClearChecks button is enabled as expected") Else WriteToFile($outputFile, "Fail: ClearChecks button is not enabled and should be") $flagFail = 1 EndIf EndIf FlagFail($ClearChecksStr) EndFunc ;These are autoit libraries point to the AutoIT Directory. #include <ie.au3> #include <Array.au3> #include <String.au3> #include "wd_helper.au3" #include "wd_capabilities.au3" ;This is relative path to the script #include "NxViewFunctions.au3" ;AutoItSetOption is required for the click and drag done to open they System Admin Window. AutoItSetOption("MouseClickDragDelay",6000) $testResultFile = "SIMPLETestResults_English_NxView.txt" $SummaryFile = "SIMPLETestResultsSummary_English_NxView.txt" Global $HelpFilePath = "file:///C:/Program%20Files/NxStage/NxView/en-US/" ;Pass in the output strings to the function file. OutputReport($testResultFile, $SummaryFile) ;------------------------------------------------------------------------------------------------------------------------ ; Delete output file if it initially exists If FileExists("SIMPLETestResults_English_NxView.txt") Then FileClose("SIMPLETestResults_English_NxView.txt") FileDelete("SIMPLETestResults_English_NxView.txt") EndIf If FileExists("SIMPLETestResultsSummary_English_NxView.txt") Then FileClose("SIMPLETestResultsSummary_English_NxView.txt") FileDelete("SIMPLETestResultsSummary_English_NxView.txt") EndIf ;------------------------------------------------------------------------------------------ WriteToFile($testResultFile,"Script Start Time is: ") RegistryEdit(0) ;Get the file version from Nx.NxView.exe. $fileVersion = FileGetVersion("C:\Program Files\NxStage\NxView\Nx.NxView.exe") FileWriteLine($SummaryFile , "The Software Version being tested is: " & $fileVersion & @CRLF & @CRLF) FileWriteLine($testResultFile, "The Software Version being tested is: " & $fileVersion & @CRLF & @CRLF) sleep(8000) ;Set the language and open NxView. SetLanguage("en-US") ;------------------------------------------------------------------------------------------ ;Open the SIMPLE window. Screenshot(1, "TherapyPage") ;ButtonClick("", "",$AppBarBtnID) sleep(8000) WinActivate("","Effluent") ButtonClick("", "", $SIMPLEBtnID) sleep(8000) ;Click on the Clear Checks button to start off fresh ButtonClick("frmHelp", "", $SIMPLE_Clearchks_btnID) FileWriteLine($testResultFile,"------------------------------------------------------------------------------------------------------------------------" & @CRLF & @CRLF) FileWriteLine($SummaryFile ,"------------------------------------------------------------------------------------------------------------------------" & @CRLF & @CRLF) ;----------------------------------------------------------------------------------------------------------------------------------- ;Testing the SIMPLE button links. ;The test case numbers correspond to the manual testing test number in the test procedure. WriteToFile($testResultFile,"Test Case TP0186:10 Start Time is: ") WriteToFile($SummaryFile,"Test Case TP0186:10 Start Time is: ") WriteToFile($testResultFile,"This Test case verifies the SIMPLE screen has buttons for each letter of SIMPLE and those button links work for each SIMPLE window.") WriteToFile($SummaryFile,"This Test case verifies the SIMPLE screen has buttons for each letter of SIMPLE and those button links work for each SIMPLE window.") WriteToFile($SummaryFile,"This Test case will also verify the correct page appears with cartridge type 0") ;WriteToFile($testResultFile,"The Following requirements are verified: 150, 665, 666") WinWait("frmHelp", "", 10) SIMPLE_BUTTONS_Setup($HelpFilePath) Sleep (10000) ButtonClick("","",$AppBarBtnID) sleep(8000) ButtonClick("","", $SIMPLEBtnID) WinWait("frmHelp","",10) SIMPLE_BUTTONS_Initiate($HelpFilePath) Sleep (10000) ButtonClick("", "",$AppBarBtnID) sleep(8000) ButtonClick("", "", $SIMPLEBtnID) WinWait("frmHelp","",10) SIMPLE_BUTTONS_Make($HelpFilePath) Sleep (10000) ButtonClick("", "",$AppBarBtnID) sleep(8000) ButtonClick("", "", $SIMPLEBtnID) WinWait("frmHelp","",10) SIMPLE_BUTTONS_Program($HelpFilePath) Sleep (10000) ButtonClick("", "",$AppBarBtnID) sleep(8000) ButtonClick("", "", $SIMPLEBtnID) WinWait("frmHelp","",10) SIMPLE_BUTTONS_Launch($HelpFilePath) sleep(8000) CloseNxView() WriteToFile($testResultFile,"Test Case TP0186:10 End Time is: ") WriteToFile($SummaryFile,"Test Case TP0186:10 End Time is: ") FileWriteLine($testResultFile,"------------------------------------------------------------------------------------------------------------------------" & @CRLF & @CRLF) FileWriteLine($SummaryFile ,"------------------------------------------------------------------------------------------------------------------------" & @CRLF & @CRLF) ;------------------------------------------------------------------------------------------------------------------------ Original IE code script+function. #include <ie.au3> #include <Array.au3> #include <String.au3> ;This is relative path to the script #include "NxViewFunctions.au3" ;AutoItSetOption is required for the click and drag done to open they System Admin Window. AutoItSetOption("MouseClickDragDelay",6000) $testResultFile = "SIMPLETestResults_English_NxView.txt" $SummaryFile = "SIMPLETestResultsSummary_English_NxView.txt" Global $HelpFilePath = "file:///C:/Program%20Files/NxStage/NxView/en-US/" ;Pass in the output strings to the function file. OutputReport($testResultFile, $SummaryFile) ;------------------------------------------------------------------------------------------------------------------------ ; Delete output file if it initially exists If FileExists("SIMPLETestResults_English_NxView.txt") Then FileClose("SIMPLETestResults_English_NxView.txt") FileDelete("SIMPLETestResults_English_NxView.txt") EndIf If FileExists("SIMPLETestResultsSummary_English_NxView.txt") Then FileClose("SIMPLETestResultsSummary_English_NxView.txt") FileDelete("SIMPLETestResultsSummary_English_NxView.txt") EndIf ;------------------------------------------------------------------------------------------ WriteToFile($testResultFile,"Script Start Time is: ") RegistryEdit(0) ;Get the file version from Nx.NxView.exe. $fileVersion = FileGetVersion("C:\Program Files\NxStage\NxView\Nx.NxView.exe") FileWriteLine($SummaryFile , "The Software Version being tested is: " & $fileVersion & @CRLF & @CRLF) FileWriteLine($testResultFile, "The Software Version being tested is: " & $fileVersion & @CRLF & @CRLF) sleep(8000) ;Set the language and open NxView. SetLanguage("en-US") ;------------------------------------------------------------------------------------------ ;Open the SIMPLE window. Screenshot(1, "TherapyPage") ;ButtonClick("", "",$AppBarBtnID) sleep(8000) WinActivate("","Effluent") ButtonClick("", "", $SIMPLEBtnID) sleep(8000) ;Click on the Clear Checks button to start off fresh ButtonClick("frmHelp", "", $SIMPLE_Clearchks_btnID) FileWriteLine($testResultFile,"------------------------------------------------------------------------------------------------------------------------" & @CRLF & @CRLF) FileWriteLine($SummaryFile ,"------------------------------------------------------------------------------------------------------------------------" & @CRLF & @CRLF) ;----------------------------------------------------------------------------------------------------------------------------------- ;Testing the SIMPLE button links. ;The test case numbers correspond to the manual testing test number in the test procedure. WriteToFile($testResultFile,"Test Case TP0186:10 Start Time is: ") WriteToFile($SummaryFile,"Test Case TP0186:10 Start Time is: ") WriteToFile($testResultFile,"This Test case verifies the SIMPLE screen has buttons for each letter of SIMPLE and those button links work for each SIMPLE window.") WriteToFile($SummaryFile,"This Test case verifies the SIMPLE screen has buttons for each letter of SIMPLE and those button links work for each SIMPLE window.") WriteToFile($SummaryFile,"This Test case will also verify the correct page appears with cartridge type 0") ;WriteToFile($testResultFile,"The Following requirements are verified: 150, 665, 666") WinWait("frmHelp", "", 10) SIMPLE_BUTTONS_Setup($HelpFilePath) Sleep (10000) ButtonClick("","",$AppBarBtnID) sleep(8000) ButtonClick("","", $SIMPLEBtnID) WinWait("frmHelp","",10) SIMPLE_BUTTONS_Initiate($HelpFilePath) Sleep (10000) ButtonClick("", "",$AppBarBtnID) sleep(8000) ButtonClick("", "", $SIMPLEBtnID) WinWait("frmHelp","",10) SIMPLE_BUTTONS_Make($HelpFilePath) Sleep (10000) ButtonClick("", "",$AppBarBtnID) sleep(8000) ButtonClick("", "", $SIMPLEBtnID) WinWait("frmHelp","",10) SIMPLE_BUTTONS_Program($HelpFilePath) Sleep (10000) ButtonClick("", "",$AppBarBtnID) sleep(8000) ButtonClick("", "", $SIMPLEBtnID) WinWait("frmHelp","",10) SIMPLE_BUTTONS_Launch($HelpFilePath) sleep(8000) CloseNxView() WriteToFile($testResultFile,"Test Case TP0186:10 End Time is: ") WriteToFile($SummaryFile,"Test Case TP0186:10 End Time is: ") FileWriteLine($testResultFile,"------------------------------------------------------------------------------------------------------------------------" & @CRLF & @CRLF) FileWriteLine($SummaryFile ,"------------------------------------------------------------------------------------------------------------------------" & @CRLF & @CRLF) #include <ie.au3> #include <Array.au3> #include <String.au3> ;This is relative path to the script #include "NxViewFunctions.au3" ;AutoItSetOption is required for the click and drag done to open they System Admin Window. AutoItSetOption("MouseClickDragDelay",6000) $testResultFile = "SIMPLETestResults_English_NxView.txt" $SummaryFile = "SIMPLETestResultsSummary_English_NxView.txt" Global $HelpFilePath = "file:///C:/Program%20Files/NxStage/NxView/en-US/" ;Pass in the output strings to the function file. OutputReport($testResultFile, $SummaryFile) ;------------------------------------------------------------------------------------------------------------------------ ; Delete output file if it initially exists If FileExists("SIMPLETestResults_English_NxView.txt") Then FileClose("SIMPLETestResults_English_NxView.txt") FileDelete("SIMPLETestResults_English_NxView.txt") EndIf If FileExists("SIMPLETestResultsSummary_English_NxView.txt") Then FileClose("SIMPLETestResultsSummary_English_NxView.txt") FileDelete("SIMPLETestResultsSummary_English_NxView.txt") EndIf ;------------------------------------------------------------------------------------------ WriteToFile($testResultFile,"Script Start Time is: ") RegistryEdit(0) ;Get the file version from Nx.NxView.exe. $fileVersion = FileGetVersion("C:\Program Files\NxStage\NxView\Nx.NxView.exe") FileWriteLine($SummaryFile , "The Software Version being tested is: " & $fileVersion & @CRLF & @CRLF) FileWriteLine($testResultFile, "The Software Version being tested is: " & $fileVersion & @CRLF & @CRLF) sleep(8000) ;Set the language and open NxView. SetLanguage("en-US") ;------------------------------------------------------------------------------------------ ;Open the SIMPLE window. Screenshot(1, "TherapyPage") ;ButtonClick("", "",$AppBarBtnID) sleep(8000) WinActivate("","Effluent") ButtonClick("", "", $SIMPLEBtnID) sleep(8000) ;Click on the Clear Checks button to start off fresh ButtonClick("frmHelp", "", $SIMPLE_Clearchks_btnID) FileWriteLine($testResultFile,"------------------------------------------------------------------------------------------------------------------------" & @CRLF & @CRLF) FileWriteLine($SummaryFile ,"------------------------------------------------------------------------------------------------------------------------" & @CRLF & @CRLF) ;----------------------------------------------------------------------------------------------------------------------------------- ;Testing the SIMPLE button links. ;The test case numbers correspond to the manual testing test number in the test procedure. WriteToFile($testResultFile,"Test Case TP0186:10 Start Time is: ") WriteToFile($SummaryFile,"Test Case TP0186:10 Start Time is: ") WriteToFile($testResultFile,"This Test case verifies the SIMPLE screen has buttons for each letter of SIMPLE and those button links work for each SIMPLE window.") WriteToFile($SummaryFile,"This Test case verifies the SIMPLE screen has buttons for each letter of SIMPLE and those button links work for each SIMPLE window.") WriteToFile($SummaryFile,"This Test case will also verify the correct page appears with cartridge type 0") ;WriteToFile($testResultFile,"The Following requirements are verified: 150, 665, 666") WinWait("frmHelp", "", 10) SIMPLE_BUTTONS_Setup($HelpFilePath) Sleep (10000) ButtonClick("","",$AppBarBtnID) sleep(8000) ButtonClick("","", $SIMPLEBtnID) WinWait("frmHelp","",10) SIMPLE_BUTTONS_Initiate($HelpFilePath) Sleep (10000) ButtonClick("", "",$AppBarBtnID) sleep(8000) ButtonClick("", "", $SIMPLEBtnID) WinWait("frmHelp","",10) SIMPLE_BUTTONS_Make($HelpFilePath) Sleep (10000) ButtonClick("", "",$AppBarBtnID) sleep(8000) ButtonClick("", "", $SIMPLEBtnID) WinWait("frmHelp","",10) SIMPLE_BUTTONS_Program($HelpFilePath) Sleep (10000) ButtonClick("", "",$AppBarBtnID) sleep(8000) ButtonClick("", "", $SIMPLEBtnID) WinWait("frmHelp","",10) SIMPLE_BUTTONS_Launch($HelpFilePath) sleep(8000) CloseNxView() WriteToFile($testResultFile,"Test Case TP0186:10 End Time is: ") WriteToFile($SummaryFile,"Test Case TP0186:10 End Time is: ") FileWriteLine($testResultFile,"------------------------------------------------------------------------------------------------------------------------" & @CRLF & @CRLF) FileWriteLine($SummaryFile ,"------------------------------------------------------------------------------------------------------------------------" & @CRLF & @CRLF)
  11. Thank you ! It work this way : _WD_Option('Driver', @ScriptDir&'\include\'&(@Compiled?'':'Exe_externe\')&'geckodriver.exe') _WD_Option('DriverParams', '--log trace ') _WD_Option('Port', 4444) _WD_Option('DriverParams', '--marionette-port 2828') $sDesiredCapabilities = '{"capabilities":{"alwaysMatch": {"moz:firefoxOptions": {"args": ["about:blank", "-profile", "C:/ProWeb/Projets/ProWeb/version/scénarios/k736nmka.default"],"log": {"level": "trace"},"prefs": {"browser.download.improvements_to_download_panel": false}}}}}'
  12. I'm almost done. Spent most of yesterday, when not celebrating my daughter's birthday and dealing with a visitor, modifying my program. The placebo stuff is now redundant of course, so had to get rid of that, which took some doing. Still have to clean up some that is just disabled. I then used that GUI portion for some new buttons, and resized some other controls and added in a CLONE button as well. I've implemented the new compiled Python script, used by the DETERMINE button, and it works well. Not visible in the screenshot is an extra column for the ImageID, which has been present and hidden almost from the beginning of development. And when you select an entry now, that has no images listed, the ImageID displays in a temporarily re-purposed and resized input field along with accompanying pink label. By the way, 5 days ago was the anniversary of when I first started working on this program ... 25 May 2023. I worked on it solidly for almost a month, and then put it aside, until a few days ago. And I have now been able to achieve, at least in theory still, what I could not back then. That said, I did achieve a few useful aspects back then. I could fix things for ebooks that lacked an image or two or had bad images, as many of my side-loaded ones did. The only thing I could not achieve, was where no images existed at all, and so we could not determine what folder to use for the missing three images for an ebook. Those cover images being what you see when browsing your device or the current ebook when the device is put to sleep. I have many such ebooks now, where no cover is displayed when I browse or when my Kobo device is put to sleep. I am looking forward to using my program to fix all that now. Just a few bits more to code to finalize things, and then the ultimate test, which I don't expect to fail. The first thing I will need to do, is refresh everything, because my Kobo has a lot more ebooks on it now, and so I need to retrieve the latest SQL database file from it to use with my program, plus clone all the folders in the .kobo-images folder on my PC again. And because my Kobo's USB connection is a bit flaky sometimes, I need to get things just right, and do things in a quick and timely fashion ... hence the delay, while I have added the new CLONE button, plus re-purposed the ADD button (via checkbox) to be a COPY button. I am essentially using the clone to do all necessary file and folder creation on my PC, then use the COPY button for each ebook I have fixed, using the benefit of the MARK and NEXT buttons. The idea is to spend as short a time as possible working directly with my Kobo device and that temperamental USB connection. As I think I have declared before, the USB connection seems to work fine while my Kobo is charging, but once fully charged it keeps losing the connection. P.S. I have also been held up by needing to do a refresher course of my program, and the code. I've now added some things to make that easier in future. I guess that's pretty normal when not engaging with something for almost a year. By the time I finish coding a program, I do try to make it easy to understand if not used for a while. And I will be the first to admit, that I don't always get it completely right, though I tend to generally be better at doing that these days. Keep it simple, can be a challenge with some programs, both as a user and a coder. While I am providing my still to be completed script, a bunch of things are either not fully finished or tested, so beware. Kobo Cover Fixer.au3 DisplayArray.au3 GDIP.au3 Python App.html 5.94 Mb (MEGA Link in HTML referral page) That DisplayArray include, is a slightly modified _ArrayDisplay function. Basically I needed to overcome the unavoidable ExitScript functionality. No idea why that default button has to kill the whole program, with no parameter to avoid that. Usually I just avoid having that button display in my final code, but it cannot be avoided when utilizing the FUNCTION button. With my amended code it just closes the _ArrayDisplay window now.
  13. Hi Nine, Sorry late reply. I read you post for a long time ago, but I dont understand. And a few weeks ago, I ask this topic again on Vietnam Auto IT Group on Facebook. A guys name Hung sent me this : https://github.com/aipit2/Google-Sheet-API He has full example. And video introduce How to create new API on Google Sheet. This code is very helpful. Please check it. ===== And now, I have new question. How to use Find and Replace on Google Sheet with AutoIT ?
  14. I'm have improve let it support other code page make Image2PDF. (Support single image & multi image. ) MPDF_UDF.au3 Example_Image2PDF.au3
  15. Hi, I bump into an error when uploading any x86 compiled exe into Github repository. The problem remain the same across different browser (Chrome & Edge). Currently Github only accept my x64 compiled exe but x86, but surprisingly, it accept other x86 exe (portable application). This is really weird! I had asked in Github community and they don't believe in x86 structure restriction which is true because other x86 portable application is being accepted. In this case, I think I might need to add something in my script but not sure. Has anyone bump into this?
  16. Yesterday
  17. Have you checked the FAQ section on the wiki? https://www.autoitscript.com/wiki/WebDriver#FAQ
  18. I'll pardon your english but not taking an unrelated topic and just opening your unrelated question. Empty ( by way of edit ) your post and open a thread in the help area. I'll do the same after you.
  19. Thanks @ioa747 now that is working! Interesting how the Scite lite didn't recognize that directive. Sorry @Nine I got it to work on 3 PC's after I updated my Scite to the full version. Both solutions seem nice for their specific uses. I am keeping a couple apps size down and will opt with the @ioa747 native solution for now not needed to add the extra UIA UDF libraries. Thanks again!!
  20. now that I saw the screenshots you posted, it is probably the fault that you have the lite version and not the full version of scite, which means that the script did not run on 64 even though it had the directive #AutoIt3Wrapper_UseX64=y even though you found a tip with your script I would suggest you to upgrade to full (which you find here SciTE4AutoIt3.exe)
  21. Hello, I have been using webdriver on my program quite a lot last few years and everything have been working well. Recently, i have encountered a problem; someone was using my program and his pdf wouldn't open with Firefox. After some research, i have found out that this is something the file "handlers.json" from Firefox profile folder handle. So i created a new Firefox profile and i tried to open a new Webdriver session using this profile. And just by trying to use a specific profile, i'm getting an error. Here is my current code : _WD_Option('Driver', @ScriptDir&'\include\'&(@Compiled?'':'Exe_externe\')&'geckodriver.exe') _WD_Option('DriverParams', '--log trace ') _WD_Option('Port', 4444) _WD_CapabilitiesStartup() _WD_CapabilitiesAdd("alwaysMatch") _WD_CapabilitiesAdd("browserName", "firefox") _WD_CapabilitiesAdd("acceptInsecureCerts", "true") _WD_CapabilitiesAdd("firstMatch", "firefox") _WD_CapabilitiesAdd('args', "about:blank") _WD_CapabilitiesAdd('args', '-profile') _WD_CapabilitiesAdd('args', "C:\Users\JOUGLET-06303\AppData\Roaming\Mozilla\Firefox\Profiles\6ldwjadu.Profile") $sDesiredCapabilities = _WD_CapabilitiesGet() $oSelf.sWDSession=_WD_CreateSession($sDesiredCapabilities) if $oSelf.sWDSession=="" then ConsoleWrite("failed") Else ConsoleWrite("success") Endif Those 2 lines are the only lines i added from what i had before, which trigger the error i get (without those 2 line, everything work well) : _WD_CapabilitiesAdd('args', '-profile') _WD_CapabilitiesAdd('args', "C:\Users\JOUGLET-06303\AppData\Roaming\Mozilla\Firefox\Profiles\6ldwjadu.ProWeb") Error log : _WD_Option ==> Success [0] : Parameters: Option=Driver Value=C:\ProWeb\Projets\ProWeb\version\include\Exe_externe\geckodriver.exe _WD_Option ==> Success [0] : Parameters: Option=DriverParams Value=--log trace _WD_Option ==> Success [0] : Parameters: Option=Port Value=4444 _WD_CapabilitiesAdd ==> Success [0] : Successfully used [alwaysMatch] _WD_CapabilitiesAdd ==> Success [0] : Successfully added capability _WD_CapabilitiesAdd ==> Success [0] : Successfully added capability _WD_CapabilitiesAdd ==> Success [0] : Successfully used [firstMatch] with specified browser: firefox _WD_CapabilitiesAdd ==> Success [0] : Successfully added capability _WD_CapabilitiesAdd ==> Success [0] : Successfully added capability _WD_CapabilitiesAdd ==> Success [0] : Successfully added capability _WD_CapabilitiesAdd ==> Success [0] : Successfully added capability _WD_CapabilitiesAdd ==> Success [0] : Successfully added capability _WD_CapabilitiesAdd ==> Success [0] : Successfully added capability _WD_CapabilitiesAdd ==> Success [0] : Successfully added capability _WD_GetFreePort ==> Success [0 / 4444] : Parameters: MinPort=4444 MaxPort=Default _WD_IsLatestRelease ==> Success [0] : True _WD_Startup: OS: WIN_10 X64 19045 _WD_Startup: AutoIt: 3.3.16.1 _WD_Startup: Webdriver UDF: 1.3.1 (Up to date) _WD_Startup: WinHTTP: 1.6.4.2 _WD_Startup: Driver: C:\ProWeb\Projets\ProWeb\version\include\Exe_externe\geckodriver.exe (64 Bit) _WD_Startup: Params: --log trace _WD_Startup: Port: 4444 _WD_Startup: Command: "C:\ProWeb\Projets\ProWeb\version\include\Exe_externe\geckodriver.exe" --log trace _WD_Startup ==> Success [0] 0 / 0 __WD_Post ==> Send / Recv error [6] : HTTP status = 0 _WD_CreateSession ==> Webdriver Exception [10] I have tried to replace the slash "\" from profile path to "/" and still same result. If anyone has an idea i would really appreciate !
  22. So far looking real good. Thanks all and @Nine for the UIA solution. This demo circles all the icon locations and displays the name above each icon to confirm the coords match the name. Update 1: Just as I marked it as a solution since it was working perfect on my work PC, I logged into another user on the same PC and it's showing 0. I'll have to debug this more... Update 2: This is a second solution that does work but I had to make sure the x64 directive was running correctly by updating my Scite to the full version. I haven't tested but it will probably work also if it is just compiled as 64 bit. #AutoIt3Wrapper_UseX64=Y #include "Includes\CUIAutomation2.au3" Opt("MustDeclareVars", True) #include <GDIPlus.au3> #include <Array.au3> #include <WindowsConstants.au3> #include <WinAPI.au3> #include <GUIConstantsEx.au3> #include <GuiListView.au3> #include <File.au3> Global Const $SC_DRAGMOVE = 0xF012 HotKeySet("{ESC}", _Exit) _GDIPlus_Startup() Local $aCoordsOfIcons = UIA_GetIconInfo() CreateGUIwMarks($aCoordsOfIcons) Func UIA_GetIconInfo() ; Create UI Automation object Local $oUIAutomation = ObjCreateInterface($sCLSID_CUIAutomation, $sIID_IUIAutomation, $dtagIUIAutomation) If Not IsObj($oUIAutomation) Then Exit ConsoleWrite("$oUIAutomation ERR" & @CRLF) ;ConsoleWrite("$oUIAutomation OK" & @CRLF) ; Get Desktop element Local $pDesktop, $oDesktop $oUIAutomation.GetRootElement($pDesktop) $oDesktop = ObjCreateInterface($pDesktop, $sIID_IUIAutomationElement, $dtagIUIAutomationElement) If Not IsObj($oDesktop) Then Exit ConsoleWrite("$oDesktop ERR" & @CRLF) ;ConsoleWrite("$oDesktop OK" & @CRLF) ; Get Shell Local $pCondition, $pShell, $oShell $oUIAutomation.CreatePropertyCondition($UIA_ClassNamePropertyId, "Progman", $pCondition) $oDesktop.FindFirst($TreeScope_Children, $pCondition, $pShell) $oShell = ObjCreateInterface($pShell, $sIID_IUIAutomationElement, $dtagIUIAutomationElement) If Not IsObj($oShell) Then Exit ConsoleWrite("$oShell ERR" & @CRLF) ;ConsoleWrite("$oShell OK" & @CRLF) ; Get all icons Local $pElementArray, $oElementArray, $iElements, $pElement, $oElement $oUIAutomation.CreatePropertyCondition($UIA_ControlTypePropertyId, $UIA_ListItemControlTypeId, $pCondition) $oShell.FindAll($TreeScope_Descendants, $pCondition, $pElementArray) $oElementArray = ObjCreateInterface($pElementArray, $sIID_IUIAutomationElementArray, $dtagIUIAutomationElementArray) If Not IsObj($oElementArray) Then Exit ConsoleWrite("$oElementArray ERR" & @CRLF) $oElementArray.Length($iElements) ;ConsoleWrite("$oElementArray OK" & @CRLF) ;ConsoleWrite($iElements & @CRLF) Local $aCoords[0][3] ; Collect Icon Info to Array Local $sValue, $tRect = DllStructCreate("long Left;long Top;long Right;long Bottom") For $i = 0 To $iElements - 1 $oElementArray.GetElement($i, $pElement) $oElement = ObjCreateInterface($pElement, $sIID_IUIAutomationElement, $dtagIUIAutomationElement) $oElement.GetCurrentPropertyValue($UIA_NamePropertyId, $sValue) ConsoleWrite("Name: " & $sValue) $oElement.CurrentBoundingRectangle($tRect) ConsoleWrite(" -- L:" & $tRect.Left & " T:" & $tRect.Top & " R:" & $tRect.Right & " B:" & $tRect.Bottom & @CRLF) _ArrayAdd($aCoords, $tRect.Left & "|" &$tRect.Top & "|" & $sValue) Next MsgBox(0, "Desktop Icon Count: ", $iElements) Return $aCoords EndFunc ;==>UIA_GetIconInfo Func CreateGUIwMarks($aCoords) Global $myWidth = @DesktopWidth Global $myHeight = @DesktopHeight Global $hGUI = GUICreate('', $myWidth, $myHeight, 0, 0, $WS_POPUP, $WS_EX_LAYERED) GUISetState() ;-- Setup Shape (Small Circle) Global $hBitmap = _GDIPlus_BitmapCreateFromScan0($myWidth, $myHeight) Global $hGraphic = _GDIPlus_ImageGetGraphicsContext($hBitmap) Global $hBuffer = _GDIPlus_ImageGetGraphicsContext($hBitmap) Global $hBrushShape = _GDIPlus_BrushCreateSolid(0xFFFF0000) Global $hBrushText = _GDIPlus_BrushCreateSolid(0xFF000000) Global $hPen = _GDIPlus_PenCreate(0xFFFF0000, 4) ; Red pen color ;_GDIPlus_GraphicsDrawEllipse($hGraphic, 130, 100, 140, 70, $hPen) ;_GDIPlus_GraphicsFillEllipse($hGraphic, 0, 0, 10, 10, $hBrushShape) ;_GDIPlus_GraphicsFillEllipse($hGraphic, 980, 980, 10, 10, $hBrushShape) ;-- Setup String Global $hFormat = _GDIPlus_StringFormatCreate() Global $hFamily = _GDIPlus_FontFamilyCreate("Calibri") Global $hFont = _GDIPlus_FontCreate($hFamily, 9, 0) _GDIPlus_GraphicsSetTextRenderingHint($hBuffer, 4) _GDIPlus_GraphicsSetSmoothingMode($hBuffer, 4) For $aa = 0 To UBound($aCoords) - 1 ;-- Add Shape ;_GDIPlus_GraphicsFillEllipse($hGraphic, $aCoords[$aa][0], $aCoords[$aa][1], 10, 10, $hBrushShape) _GDIPlus_GraphicsDrawEllipse($hGraphic, $aCoords[$aa][0], $aCoords[$aa][1], 75, 60, $hPen) ;-- Add String Global $tLayout = _GDIPlus_RectFCreate($aCoords[$aa][0]+7, $aCoords[$aa][1], 75, 15) ; x,y,w,h (orig w:0/h:0 for unlimited) _GDIPlus_GraphicsDrawStringEx($hGraphic, $aCoords[$aa][2], $hFont, $tLayout, $hFormat, $hBrushText) Next _GDIPlus_GraphicsDispose($hGraphic) Global $hHBitmap = _GDIPlus_BitmapCreateHBITMAPFromBitmap($hBitmap) _WinAPI_BitmapDisplayTransparentInGUI($hHBitmap, $hGUI, 255) GUIRegisterMsg($WM_LBUTTONDOWN, "_WM_LBUTTONDOWN") While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE _Exit() EndSwitch WEnd EndFunc
  23. @Nine, I did a quick test and that looks like it hit the jackpot. Thanks ๐Ÿ˜ I'll work on that now. @DennisFong222 I apologize what did I say that made you think I didn't research newer X64 options? If you thought there was such an option specifically to extract Names w/Coords I'll be more than happy to study and test it out. @ioa747 I apologize if I wasn't clear but I wasn't seeing the error "Subscript used on non-accessible variable" you saw when I tested it on my home and work PC's but then I did see the error on a 3rd PC. I also wasn't successful running the nice code that you provided and I provided a Screenshot1 below to display it was not showing icon names just the red marker positions. After I modified it adding back the shell object thinking I can extract the icon names I was semi-successful in Screenshot2 below but that didn't sync up with the actual icon names when you compare the text at the top and bottom of the icons. Good news is I have a plan to play with the UIA option which requires a large UDF but it so far is looking like the most reliable solution so far.
  24. You could also use UIAutomation : #include "Includes\CUIAutomation2.au3" Opt("MustDeclareVars", True) ; Create UI Automation object Local $oUIAutomation = ObjCreateInterface($sCLSID_CUIAutomation, $sIID_IUIAutomation, $dtagIUIAutomation) If Not IsObj($oUIAutomation) Then Exit ConsoleWrite("$oUIAutomation ERR" & @CRLF) ;ConsoleWrite("$oUIAutomation OK" & @CRLF) ; Get Desktop element Local $pDesktop, $oDesktop $oUIAutomation.GetRootElement($pDesktop) $oDesktop = ObjCreateInterface($pDesktop, $sIID_IUIAutomationElement, $dtagIUIAutomationElement) If Not IsObj($oDesktop) Then Exit ConsoleWrite("$oDesktop ERR" & @CRLF) ;ConsoleWrite("$oDesktop OK" & @CRLF) ; Get Shell Local $pCondition, $pShell, $oShell $oUIAutomation.CreatePropertyCondition($UIA_ClassNamePropertyId, "Progman", $pCondition) $oDesktop.FindFirst($TreeScope_Children, $pCondition, $pShell) $oShell = ObjCreateInterface($pShell, $sIID_IUIAutomationElement, $dtagIUIAutomationElement) If Not IsObj($oShell) Then Exit ConsoleWrite("$oShell ERR" & @CRLF) ;ConsoleWrite("$oShell OK" & @CRLF) ; Get all icons Local $pElementArray, $oElementArray, $iElements, $pElement, $oElement $oUIAutomation.CreatePropertyCondition($UIA_ControlTypePropertyId, $UIA_ListItemControlTypeId, $pCondition) $oShell.FindAll($TreeScope_Descendants, $pCondition, $pElementArray) $oElementArray = ObjCreateInterface($pElementArray, $sIID_IUIAutomationElementArray, $dtagIUIAutomationElementArray) If Not IsObj($oElementArray) Then Exit ConsoleWrite("$oElementArray ERR" & @CRLF) $oElementArray.Length($iElements) ;ConsoleWrite("$oElementArray OK" & @CRLF) ;ConsoleWrite($iElements & @CRLF) Local $sValue, $tRect = DllStructCreate("long Left;long Top;long Right;long Bottom") For $i = 0 To $iElements - 1 $oElementArray.GetElement($i, $pElement) $oElement = ObjCreateInterface($pElement, $sIID_IUIAutomationElement, $dtagIUIAutomationElement) $oElement.GetCurrentPropertyValue($UIA_NamePropertyId, $sValue) ConsoleWrite("Name: " & $sValue) $oElement.CurrentBoundingRectangle($tRect) ConsoleWrite(" -- L:" & $tRect.Left & " T:" & $tRect.Top & " R:" & $tRect.Right & " B:" & $tRect.Bottom & @CRLF) Next
  25. Adjust the code to retrieve icon coordinates and names correctly for the current system by using updated APIs or libraries that support the latest X64 changes.
  26. Hi everybody With the help of this thread, @AspirinJunkie and @Musashi , I was able to add a GUI to Google translation with AutoIt. Please note the 3 colors possible (green / yellow / red) found in these 3 pics, we'll discuss them later (need some sleep now) The maximum number of characters allowed for the original text is 65535, but imho it's too much. If you experience some slowness with 65535, then you can modify this variable at the very beginning of the script and indicate a lower value : Local $iMaxInputLength = 65535 There are different ways to import the text to translate : * Paste it directly from the clipboard (Ctrl+V) inside the upper edit control * Click the "Paste ClipBoard" button in the GUI * Drag a text file inside the upper edit control * Click the "Open File" button in the GUI (only .txt files for the moment) Then choose in each combo box the language you want ("Detect language" is useful for the Original) and click Translate. After the translation is done, if you want to copy the translated text, then a click on the "Copy Translated" button is possible. During the translation process, you have the possibility to press the "Escape" key if you want to stop the translation. ; requires AutoIt 3.3.16.1 (which includes Maps, as Json.au3 requires Maps for some translations) #include "Json.au3" ; by @AspirinJunkie, download from https://github.com/Sylvan86/autoit-json-udf #include <Array.au3> #include <ComboConstants.au3> #include <EditConstants.au3> #include <FileConstants.au3> #include <GUIConstantsEx.au3> #include <GUIEdit.au3> #include <MsgBoxConstants.au3> #include <StaticConstants.au3> #include <StringConstants.au3> #include <WindowsConstants.au3> Opt("MustDeclareVars", 1) ;0=no, 1=require pre-declaration Local $iMaxInputLength = 65535 ; In theory, 65535 is the maximum length of the original encoded string, when it is only composed of ; letters, digits, etc... which have an ascii code < 128 and coded on 1 byte only. ; But in practice, this variable should be much lower (5000 as Google Translate site ?) or 10000, 15000 ... ; to avoid the error message that will appear when the original encoded string becomes > 65535 bytes length. ; Also _JSON_Parse() may take some time on slow computers with "big" original encoded strings. ; Local $iMaxInputLength = 5460 ; this value allows any encoded string to be < 65536 length, even if each character is a Unicode character ; requiring 4 bytes => then each character will be coded on 12 bytes in the string "%..%..%..%.." ; 5460 * 12 = 65520 bytes (which is < 65536) Local $aLang = _FillArrayLang() ; _ArrayDisplay($aLang, Ubound($aLang) & " language codes", Default, $ARRAYDISPLAY_NOROW, Default, 'Language|Code') Local $sLang = "" For $i = 0 To Ubound($aLang) - 1 $sLang &= $aLang[$i][0] & "|" ; no problem if one "|" remains at the very right of the string. Next Local $sIniFile = StringTrimRight(@ScriptFullPath, 3) & "ini" ; ".au3" | ".a3x" | ".exe" => ".ini" Local $aIni = _ReadIniFile($sIniFile) #Region ### START Koda GUI section ### Form=C:\Temp\koda_1.7.3.0\Forms\google translate #2.kxf Local $sGUI_Title = "Google Translation (v6)" Local $hGUI = GUICreate($sGUI_Title, 900, 700, -1, -1, $WS_OVERLAPPEDWINDOW, $WS_EX_ACCEPTFILES) Local $idPasteClip = GUICtrlCreateButton("Paste Clipboard", 10, 10, 100, 30) Local $idOpenFile = GUICtrlCreateButton("Open File", 10, 50, 100, 30) GUICtrlCreateGroup(" Original text options ", 130, 10, 310, 70) GUICtrlCreateLabel("Language From", 146, 32, 94, 17) Local $idLangFrom = GUICtrlCreateCombo("", 146, 50, 115, 25, BitOR($GUI_SS_DEFAULT_COMBO, $CBS_SIMPLE)) GUICtrlSetFont(-1, 9) GUICtrlSetData(-1, "Detect language|" & $sLang) GUICtrlSendMsg($idLangFrom, $CB_SETCURSEL, $aIni[0], 0) GUICtrlCreateLabel("Font size", 290, 32, 54, 17) Local $idFontSizeFrom = GUICtrlCreateInput($aIni[1], 290, 50, 57, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER, $ES_NUMBER)) GUICtrlSetLimit(-1, 2) Local $idUpDownFrom = GUICtrlCreateUpdown($idFontSizeFrom) GUICtrlSetLimit(-1, 72, 8) GUICtrlCreateLabel("Word wrap", 368, 32, 64, 17) Local $idWordWrapFrom = GUICtrlCreateCheckbox("", 384, 46, 17, 25) GUICtrlSetState(-1, $aIni[2]) ; $GUI_CHECKED = 1 , $GUI_UNCHECKED = 4 GUICtrlCreateGroup("", -99, -99, 1, 1) GUICtrlCreateGroup(" Translated text options ", 460, 10, 310, 70) GUICtrlCreateLabel("Language To", 476, 32, 94, 17) Local $idLangTo = GUICtrlCreateCombo("", 476, 50, 115, 25, BitOR($GUI_SS_DEFAULT_COMBO, $CBS_SIMPLE)) GUICtrlSetFont(-1, 9) GUICtrlSetData(-1, $sLang) GUICtrlSendMsg(-1, $CB_SETCURSEL, $aIni[3], 0) GUICtrlCreateLabel("Font size", 620, 32, 54, 17) Local $idFontSizeTo = GUICtrlCreateInput($aIni[4], 620, 50, 57, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER, $ES_NUMBER)) GUICtrlSetLimit(-1, 2) Local $idUpDownTo = GUICtrlCreateUpdown($idFontSizeTo) GUICtrlSetLimit(-1, 72, 8) GUICtrlCreateLabel("Word wrap", 698, 32, 64, 17) Local $idWordWrapTo = GUICtrlCreateCheckbox("", 714, 46, 17, 25) GUICtrlSetState(-1, $aIni[5]) ; $GUI_CHECKED = 1 , $GUI_UNCHECKED = 4 GUICtrlCreateGroup("", -99, -99, 1, 1) Local $idTranslate = GUICtrlCreateButton("Translate", 790, 10, 100, 30) Local $idCopyTrans = GUICtrlCreateButton("Copy Translated", 790, 50, 100, 30) Local $idTextFrom = _EditRecreate_From($aIni[1], $aIni[2]) ; Font size, WordWrap (for edit control containing the original text) Local $idTextTo = _EditRecreate_To ($aIni[4], $aIni[5]) ; same, for edit control containing the translated text. Local $idCharStatus = GUICtrlCreateLabel("", 790, 380, 80, 25, BitOR($SS_CENTER,$SS_CENTERIMAGE)) _UpdateCharStatus() GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### GUIRegisterMsg($WM_COMMAND, "WM_COMMAND") While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE _WriteIniFile($sIniFile) Exit Case $idPasteClip GUICtrlSetData($idTextFrom, StringLeft(ClipGet(), $iMaxInputLength)) _UpdateCharStatus() GUICtrlSetData($idTextTo, "") Case $idOpenFile Local $sFileName = _OpenFile() If $sFileName Then GUICtrlSetData($idTextFrom, StringLeft(FileRead($sFileName), $iMaxInputLength)) _UpdateCharStatus() GUICtrlSetData($idTextTo, "") EndIf Case $GUI_EVENT_DROPPED If @GUI_DragId = -1 Then ; -1 means dragged from a file GUICtrlSetData(@GUI_DropId, StringLeft(FileRead(@GUI_DragFile), $iMaxInputLength)) _UpdateCharStatus() GUICtrlSetData($idTextTo, "") EndIf Case $idFontSizeFrom GUICtrlSetFont($idTextFrom, Int(GUICtrlRead($idFontSizeFrom))) Case $idWordWrapFrom $idTextFrom = _EditRecreate_From(Int(GUICtrlRead($idFontSizeFrom)), GUICtrlRead($idWordWrapFrom)) ; Font size, WordWrap Case $idFontSizeTo GUICtrlSetFont($idTextTo, Int(GUICtrlRead($idFontSizeTo))) Case $idWordWrapTo $idTextTo = _EditRecreate_To(Int(GUICtrlRead($idFontSizeTo)), GUICtrlRead($idWordWrapTo)) ; Font size, WordWrap Case $idTranslate GUICtrlSetState($idTranslate, $GUI_DISABLE) ; prevent accidental double click on the button GUICtrlSetData($idTextTo, "") HotKeySet("{ESC}", "_Wanna_Quit") ; in case user keys Esc during the translation process _Translate() HotKeySet("{ESC}") GUICtrlSetState($idTranslate, $GUI_ENABLE) Case $idCopyTrans ClipPut(GUICtrlRead($idTextTo)) MsgBox($MB_TOPMOST, "", "Done", 1, $hGUI) ; timeout 1s EndSwitch WEnd ;============================================== Func _ReadIniFile(Const ByRef $sIniFile) If FileExists($sIniFile) Then Local $aIni = FileReadToArray($sIniFile) If @extended <> 6 Then Exit MsgBox($MB_TOPMOST, "_FileReadToArray extended = " & @extended, $sIniFile) Else For $i = 0 To 5 $aIni[$i] = Number($aIni[$i]) ; Number, or serious issues later in GUICtrlSendMsg() Next ; _ArrayDisplay($aIni) EndIf Else Local $aIni[6] $aIni[0] = 0 ; Language From (force 'Detect Language' when .ini file doesn't exist) $aIni[1] = 11 ; Font Size $aIni[2] = 1 ; Word wrap (1 = checked, 4 = unchecked) $aIni[3] = _ArraySearch($aLang, "English", Default, Default, Default, Default, Default, 0) ; 0 = search in Col 0 as 2D array ; Language To (force 'English' when .ini file doesn't exist) $aIni[4] = 11 ; Font Size $aIni[5] = 1 ; Word wrap (1 = checked, 4 = unchecked) EndIf Return $aIni EndFunc ;==>_ReadIniFile ;============================================== Func _WriteIniFile(Const ByRef $sIniFile) Local $hIni = FileOpen($sIniFile, $FO_OVERWRITE) If $hIni = -1 Then MsgBox($MB_TOPMOST, "FileOpen error", $sIniFile, 0, $hGUI) ; 5th param prevents clicking inside $hGUI Else FileWrite($hIni, _ GUICtrlSendMsg($idLangFrom, $CB_GETCURSEL, 0, 0) & @crlf & _ Int(GUICtrlRead($idFontSizeFrom)) & @crlf & _ GUICtrlRead($idWordWrapFrom) & @crlf & _ GUICtrlSendMsg($idLangTo, $CB_GETCURSEL, 0, 0) & @crlf & _ Int(GUICtrlRead($idFontSizeTo)) & @crlf & _ GUICtrlRead($idWordWrapTo) & @crlf) FileClose($hIni) EndIf EndFunc ;==>_WriteIniFile ;============================================== Func _EditRecreate_From($iFontSize, $iWordWrap) Local $idEdit_Old = $idTextFrom ; 0 at first passage If $idEdit_Old Then Local $aPos = ControlGetPos($hGUI, "", $idEdit_Old) Else ; 1st passage Local $aPos[4] = [10, 100, 880, 275] EndIf Local $idTextFrom = GUICtrlCreateEdit("", $aPos[0], $aPos[1], $aPos[2], $aPos[3], (($iWordWrap = 1) _ ; Word wrap (1 = unchecked, 4 = checked) ? BitOr($ES_WANTRETURN, $WS_VSCROLL, $ES_AUTOVSCROLL) _ : -1)) ; new control ID GUICtrlSetFont(-1, $iFontSize) GUICtrlSetState(-1, $GUI_DROPACCEPTED) GUICtrlSendMsg(-1, $EM_LIMITTEXT, $iMaxInputLength, 0) If $idEdit_Old Then _GUICtrlEdit_SetText($idTextFrom, GUICtrlRead($idEdit_Old)) Local $aSel = _GUICtrlEdit_GetSel($idEdit_Old) GUICtrlDelete($idEdit_Old) _GUICtrlEdit_SetSel($idTextFrom, $aSel[0], $aSel[1]) EndIf Return $idTextFrom EndFunc ;==>_EditRecreate_From ;============================================== Func _EditRecreate_To($iFontSize, $iWordWrap) Local $idEdit_Old = $idTextTo ; 0 at first passage If $idEdit_Old Then Local $aPos = ControlGetPos($hGUI, "", $idEdit_Old) Else ; 1st passage Local $aPos[4] = [10, 410, 880, 275] EndIf Local $idTextTo = GUICtrlCreateEdit("", $aPos[0], $aPos[1], $aPos[2], $aPos[3], (($iWordWrap = 1) _ ; Word wrap (1 = unchecked, 4 = checked) ? BitOr($ES_WANTRETURN, $WS_VSCROLL, $ES_AUTOVSCROLL) _ : -1)) ; new control ID GUICtrlSetFont(-1, $iFontSize) GUICtrlSendMsg(-1, $EM_LIMITTEXT, -1, 0) ; allow unlimited text size in edit control (translated text) If $idEdit_Old Then _GUICtrlEdit_SetText($idTextTo, GUICtrlRead($idEdit_Old)) Local $aSel = _GUICtrlEdit_GetSel($idEdit_Old) GUICtrlDelete($idEdit_Old) _GUICtrlEdit_SetSel($idTextTo, $aSel[0], $aSel[1]) EndIf Return $idTextTo EndFunc ;==>_EditRecreate_To ;============================================== Func _OpenFile() Local $sFileName = FileOpenDialog( _ "Open Text file", _ @ScriptDir, _ "Text files (*.txt)", _ BitOR($FD_FILEMUSTEXIST, $FD_PATHMUSTEXIST), _ "", _ $hGUI) If @error Then ;~ MsgBox($MB_TOPMOST, "Open File", _ ;~ "No file selected ", 0, $hGUI) ; FileOpenDialog() was exited by Cancel/Red X button, or by Esc key Return EndIf ; Change the working directory (@WorkingDir) back to the location of the script directory as FileOpenDialog sets it to the last accessed folder (on successful return) ; FileChangeDir(@ScriptDir) Return $sFileName EndFunc ;==>_OpenFile ;============================================== Func _Translate() Local $sEncoded = _URIEncode(GUICtrlRead($idTextFrom)) If StringLen($sEncoded) = 0 Then WinSetTitle($hGUI, "", $sGUI_Title) MsgBox($MB_TOPMOST, "No original text", "Nothing to translate", 0, $hGUI) Return EndIf ; ConsoleWrite(BinaryToString(StringToBinary("$sEncoded: " & $sEncoded, $SB_UTF8), $SB_ANSI) & @crlf) Local $iBytes = StringLen($sEncoded) ; ConsoleWrite("Length of $sEncoded : " & $iBytes & @crlf & @crlf) If $iBytes > 65535 Then ; tested (not 65536 !) Local $iYesNo = MsgBox(BitOr($MB_TOPMOST, $MB_YESNO, $MB_DEFBUTTON2, $MB_ICONWARNING), _ "Warning : Encoded text is too big", _ "Encoded text size: " & @Tab & $iBytes & @crlf & _ "Max. allowed:" & @Tab & " 65535" & @crlf & _ "" & @crlf & _ "Do you want to truncate the original text ?", 0, $hGUI) If $iYesNo = $IDNO Then Return $sEncoded = _URIEncode_Truncate(GUICtrlRead($idTextFrom)) EndIf Local $iItemFrom = GUICtrlSendMsg($idLangFrom, $CB_GETCURSEL, 0, 0) Local $sLangFrom = ($iItemFrom = 0) ? "auto" : $aLang[$iItemFrom - 1][1] ; ex. "auto", "en", de", ... Local $iItemTo = GUICtrlSendMsg($idLangTo, $CB_GETCURSEL, 0, 0) Local $sLangTo = $aLang[$iItemTo][1] ; ex. "en", "de", ... Local $sLangUsed, $sTranslated = _GoogleAPITranslate($sEncoded, $sLangFrom, $sLangTo, $sLangUsed) ; ConsoleWrite("Length of $sTranslated : " & StringLen($sTranslated) & @crlf) If $sLangUsed Then ; translation has succeeded and $sLangUsed always contains the code that Google used for translation ; ConsoleWrite("$sLangUsed: >>>" & $sLangUsed & "<<<" & @crlf) _GUICtrlEdit_SetText($idTextTo, $sTranslated) If $sLangFrom = "auto" Then Local $sLangUsedFull For $i = 0 To Ubound($aLang) - 1 If $sLangUsed = $aLang[$i][1] Then $sLangUsedFull = $aLang[$i][0] ; ex. "English", "German" , ... ExitLoop EndIf Next WinSetTitle($hGUI, "", "Translated From " & _ ($sLangUsedFull ? $sLangUsedFull : "???") & _ " To " & $aLang[$iItemTo][0]) Else WinSetTitle($hGUI, "", "Translated From " & $aLang[$iItemFrom - 1][0] & " To " & $aLang[$iItemTo][0]) EndIf Else ; translation failed as $sLangUsed is still empty WinSetTitle($hGUI, "", $sGUI_Title) MsgBox($MB_TOPMOST, "Error", "Something went wrong during translation", 0, $hGUI) EndIf EndFunc ;==>_Translate ;============================================== Func _GoogleAPITranslate(Const ByRef $sEncoded, $sFrom, $sTo, ByRef $sLangUsed) Local $oLocalCOMErrorHandler = ObjEvent("AutoIt.Error", "_ErrFuncLocal") ; format and send request With ObjCreate("WinHttp.WinHttpRequest.5.1") ; thanks AspirinJunkie for correct syntax of the Object methods below. .Open("POST", "https://translate.googleapis.com/translate_a/single", False) .SetRequestHeader("Content-Type", "application/x-www-form-urlencoded") .Send(StringFormat("client=gtx&sl=%s&tl=%s&dt=t&q=%s", $sFrom, $sTo, $sEncoded)) Local $sResponse = .ResponseText EndWith ; ConsoleWrite(BinaryToString(StringToBinary("$sResponse: " & $sResponse, $SB_UTF8), $SB_ANSI) & @crlf) Local $vResponse = _JSON_Parse($sResponse) ; process return Local $sOutput = "" If VarGetType($vResponse) = 'Array' Then ; _ArrayDisplay($vResponse, "$vResponse") Local $aData = $vResponse[0] If VarGetType($aData) = 'Array' Then For $i = 0 To UBound($aData) -1 $sOutput &= ($aData[$i])[0] Next EndIf $sLangUsed = $vResponse[2] ; ex. "en" , "de" , ... (to display which language Google used for translation, in case user choosed "Detect language") EndIf Return $sOutput EndFunc ;==>_GoogleAPITranslate ;============================================== Func _ErrFuncLocal($oError) ; https://www.autoitscript.com/forum/topic/191401-com-error-handling-in-a-udf-best-practice/?do=findComment&comment=1373102 MsgBox($MB_TOPMOST, @ScriptName & " (" & $oError.scriptline & ") : ==> Local COM error handler - COM Error intercepted !", _ @Tab & "err.number is: " & @Tab & @Tab & "0x" & Hex($oError.number) & @crlf & _ @Tab & "err.windescription:" & @Tab & @Tab & StringStripWS($oError.windescription, 2) & @crlf & _ @Tab & "err.description is: " & @Tab & @Tab & StringStripWS($oError.description, 2) & @crlf & _ @Tab & "err.source is: " & @Tab & @Tab & $oError.source & @crlf & _ @Tab & "err.helpfile is: " & @Tab & @Tab & $oError.helpfile & @crlf & _ @Tab & "err.helpcontext is: " & @Tab & @Tab & $oError.helpcontext & @crlf & _ @Tab & "err.lastdllerror is: " & @Tab & @Tab & $oError.lastdllerror & @crlf & _ @Tab & "err.scriptline is: " & @Tab & @Tab & $oError.scriptline & @crlf & _ @Tab & "err.retcode is: " & @Tab & @Tab & "0x" & Hex($oError.retcode), 0, $hGUI) EndFunc ;==>_ErrFuncLocal ;============================================== Func _URIEncode(Const ByRef $sData) ; code below from Prog@ndy (minor changes) : https://www.autoitscript.com/forum/topic/95850-url-encoding/?do=findComment&comment=689060 ; maybe Chr(32) should always be encoded as "%20" and not "+" to be compatible with all browsers (?) we'll see... Local $aData = StringSplit(BinaryToString(StringToBinary($sData, $SB_UTF8), $SB_ANSI), "") ; "" => each character returns as an element Local $nChar, $sEncoded = "" For $i = 1 To $aData[0] $nChar = Asc($aData[$i]) Switch $nChar Case 45, 46, 48 To 57, 65 To 90, 95, 97 To 122, 126 $sEncoded &= $aData[$i] Case 32 $sEncoded &= "+" Case Else $sEncoded &= "%" & Hex($nChar, 2) EndSwitch Next Return $sEncoded EndFunc ;==>_URIEncode ;============================================== Func _URIEncode_Truncate(Const ByRef $sData) Local $dBinary, $nChar, $sEncoded = "", $iGoodLen = 0 For $j = 1 To StringLen($sData) $iGoodLen = StringLen($sEncoded) ; from the previous loop $dBinary = StringToBinary(StringMid($sData, $j, 1), $SB_UTF8) ; for example ะป (russian) becomes 0xD0BB For $i = 1 To BinaryLen($dBinary) $nChar = Number(BinaryMid($dBinary, $i, 1)) Switch $nChar Case 45, 46, 48 To 57, 65 To 90, 95, 97 To 122, 126 $sEncoded &= Chr($nChar) Case 32 $sEncoded &= "+" Case Else $sEncoded &= "%" & Hex($nChar, 2) EndSwitch Next If StringLen($sEncoded) > 65535 Then ; stop encoding... GUICtrlSetData($idTextFrom, StringLeft($sData, $j - 1)) ; ...truncate original text... $sEncoded = StringLeft($sEncoded, $iGoodLen) ;...delete the very last byte(s) in $sEncoded... ExitLoop ; ...return the corresponding encoded string (which will never exceed 65535 bytes) EndIf Next Return $sEncoded EndFunc ;==>_URIEncode_Truncate ;============================================== Func WM_COMMAND($hWnd, $iMsg, $wParam, $lParam) ; Local $hWndFrom = $lParam ; Local $iIDFrom = _WinAPI_LoWord($wParam) Local $iIDFrom = BitAND($wParam, 0xFFFF) ; same (cf WinAPIConv.au3) ; Local $iCode = _WinAPI_HiWord($wParam) Local $iCode = BitShift($wParam, 16) ; same (cf WinAPIConv.au3) Switch $iIDFrom Case $idTextFrom Switch $iCode Case $EN_UPDATE ; Sent when an edit control is about to redraw itself (this is different from $EN_CHANGE) _UpdateCharStatus() EndSwitch EndSwitch Return $GUI_RUNDEFMSG EndFunc ;==>WM_COMMAND ;============================================== Func _UpdateCharStatus() Local $iChars = GUICtrlSendMsg($idTextFrom, $WM_GETTEXTLENGTH, 0, 0) ; same as _GUICtrlEdit_GetTextLen($idTextFrom) ? Select Case $iChars > $iMaxInputLength GUICtrlSetData($idTextFrom, StringLeft(GUICtrlRead($idTextFrom), $iMaxInputLength)) ContinueCase Case $iChars = $iMaxInputLength GUICtrlSetData($idCharStatus, $iMaxInputLength & " / " & $iMaxInputLength) GUICtrlSetBkColor($idCharStatus, 0xFF4040) ; reddish Case Else ; i.e. $iChars < $iMaxInputLength GUICtrlSetData($idCharStatus, $iChars & " / " & $iMaxInputLength) GUICtrlSetBkColor($idCharStatus, ($iChars <= 5460) ? 0x80FF80 : 0xFFFF00) ; greenish => ok, yellow => encoded string may become too long. EndSelect EndFunc ;==>_UpdateCharStatus ;============================================== Func _Wanna_Quit() ; in case user keys Esc during the translation process HotKeySet("{ESC}") If WinActive($hGUI) Then MouseMove(@DesktopWidth / 2, @DesktopHeight / 2, 0) ; 0 = fastest move If MsgBox(BitOr($MB_TOPMOST, $MB_OKCANCEL, $MB_DEFBUTTON2), _ "Esc was keyed", "Quit translation script ?", 0, $hGUI) = $IDOK Then Exit Else ; Esc was keyed when another application was on top Send("{ESC}") EndIf HotKeySet("{ESC}", "_Wanna_Quit") EndFunc ;_Wanna_Quit ;============================================== Func _FillArrayLang() ; list of language codes found at https://cloud.google.com/translate/docs/languages Local $aArray[][2] = [["Afrikaans","af"],["Albanian","sq"],["Amharic","am"],["Arabic","ar"],["Armenian","hy"],["Assamese","as"],["Aymara","ay"],["Azerbaijani","az"],["Bambara","bm"],["Basque","eu"],["Belarusian","be"],["Bengali","bn"],["Bhojpuri","bho"],["Bosnian","bs"],["Bulgarian","bg"],["Catalan","ca"],["Cebuano","ceb"],["Chichewa (Nyanja)","ny"],["Chinese (Simplified)","zh-CN"],["Chinese (Traditional)","zh-TW"],["Corsican","co"],["Croatian","hr"],["Czech","cs"],["Danish","da"],["Dhivehi","dv"],["Dogri","doi"],["Dutch","nl"],["English","en"],["Esperanto","eo"],["Estonian","et"],["Ewe","ee"],["Filipino (Tagalog)","fil"],["Finnish","fi"],["French","fr"],["Frisian","fy"],["Galician","gl"],["Georgian","ka"],["German","de"],["Greek","el"],["Guarani","gn"],["Gujarati","gu"],["Haitian Creole","ht"],["Hausa","ha"],["Hawaiian","haw"],["Hebrew","iw"],["Hindi","hi"],["Hmong","hmn"],["Hungarian","hu"],["Icelandic","is"],["Igbo","ig"],["Ilocano","ilo"],["Indonesian","id"],["Irish","ga"],["Italian","it"],["Japanese","ja"],["Javanese","jw"],["Kannada","kn"],["Kazakh","kk"],["Khmer","km"],["Kinyarwanda","rw"],["Konkani","gom"],["Korean","ko"],["Krio","kri"],["Kurdish","ku"],["Kurdish (Sorani)","ckb"],["Kyrgyz","ky"],["Lao","lo"],["Latin","la"],["Latvian","lv"],["Lingala","ln"],["Lithuanian","lt"],["Luganda","lg"],["Luxembourgish","lb"],["Macedonian","mk"],["Maithili","mai"],["Malagasy","mg"],["Malay","ms"],["Malayalam","ml"],["Maltese","mt"],["Maori","mi"],["Marathi","mr"],["Meiteilon (Manipuri)","mni-Mtei"],["Mizo","lus"],["Mongolian","mn"],["Myanmar (Burmese)","my"],["Nepali","ne"],["Norwegian","no"],["Odia (Oriya)","or"],["Oromo","om"],["Pashto","ps"],["Persian","fa"],["Polish","pl"],["Portuguese (Portugal, Brazil)","pt"],["Punjabi","pa"],["Quechua","qu"],["Romanian","ro"],["Russian","ru"],["Samoan","sm"],["Sanskrit","sa"],["Scots Gaelic","gd"],["Sepedi","nso"],["Serbian","sr"],["Sesotho","st"],["Shona","sn"],["Sindhi","sd"],["Sinhala (Sinhalese)","si"],["Slovak","sk"],["Slovenian","sl"],["Somali","so"],["Spanish","es"],["Sundanese","su"],["Swahili","sw"],["Swedish","sv"],["Tajik","tg"],["Tamil","ta"],["Tatar","tt"],["Telugu","te"],["Thai","th"],["Tigrinya","ti"],["Tsonga","ts"],["Turkish","tr"],["Turkmen","tk"],["Twi (Akan)","ak"],["Ukrainian","uk"],["Urdu","ur"],["Uyghur","ug"],["Uzbek","uz"],["Vietnamese","vi"],["Welsh","cy"],["Xhosa","xh"],["Yiddish","yi"],["Yoruba","yo"],["Zulu","zu"]] Return $aArray EndFunc ;==>_FillArrayLang Please indicate if something doesn't work correctly as I just finished the script a few minutes ago. Have a great day
  1. Load more activity
×
×
  • Create New...