[Editor] CodeQuickTester - Write and run code without saving to a temporary file

Post your working scripts, libraries and tools for AHK v1.1 and older
User avatar
TLM
Posts: 1608
Joined: 01 Oct 2013, 07:52
Contact:

Re: CodeQuickTester

27 Feb 2015, 09:44

keww :>
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: CodeQuickTester

12 Mar 2015, 10:33

I've just added a button that lets you register CodeQuickTester as the default service handler for "ahk:" links. I will be adding a button to the pastebin so that you can open pastes directly in the code tester.
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: CodeQuickTester

13 Mar 2015, 11:14

Flow_Snake asked me to make it so that it doesn't throw an error when you don't enter a URL into the "Fetch" box, so I've done that.
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: CodeQuickTester

24 Mar 2015, 17:17

Now with userscript to add ahk: links to the forums code boxes
Guess

Re: CodeQuickTester

25 Mar 2015, 03:45

GeekDude wrote:Now with userscript to add ahk: links to the forums code boxes
I don't know how can I use this script?
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: CodeQuickTester

26 Mar 2015, 20:11

It's a greasemonkey userscript. How you install it varies from browser to browser.
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: CodeQuickTester

02 May 2015, 21:41

Just updated it with a status bar that tells you code length and caret position
User avatar
BGM
Posts: 507
Joined: 20 Nov 2013, 20:56
Contact:

Re: CodeQuickTester

04 May 2015, 17:06

When I run the script I get an error:

Code: Select all

---------------------------
QuickCodeTester.ahk
---------------------------
Error:  Call to nonexistent function.

Specifically: Format("%{:02X}", Code)

	Line#
	256: Pbin.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")  
	257: Pbin.Send(Form)  
	258: Return,Pbin.Option(1)
	259: }
	262: {
	263: VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0), StrPut(Uri, &Var, "UTF-8")  
	264: While,Code := NumGet(Var, A_Index - 1, "UChar")
--->	265: Res .= (Chr:=Chr(Code)) ~= RE ? Chr : Format("%{:02X}", Code)  
	266: Return,Res
	267: }
	270: {
	271: AhkPath := A_AhkPath
	272: if RegExMatch(Script, ")^\s*;#!\s*(.+)", Match)  
	273: {
	274: AhkPath := Trim(Match1)

The program will exit.
---------------------------
OK   
---------------------------
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: CodeQuickTester

04 May 2015, 17:07

Update your AutoHotkey version. It's at least 5 months out of date
User avatar
BGM
Posts: 507
Joined: 20 Nov 2013, 20:56
Contact:

Re: CodeQuickTester

04 May 2015, 17:18

How can you tell that? Okay, I admit it is out of date, but the thread header says "requires version 1.1" though; I have AutoHotkey 1.1.15.04. But I'll update it and see if it helps.
Notes:
The run button changes to a kill button while the script is running
It will attempt to close the script nicely for a second or two before killing the scripts process
Requires AHK v1.1
[update]
Okay, it works now!
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: CodeQuickTester

09 May 2015, 20:05

The latest update makes the status bar much more responsive

Note: Even though the code boxes are missing so far on the new forum software, the service handler user script still works for gist tags
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: CodeQuickTester

10 May 2015, 08:49

Added a selection length counter to the status bar. It uses ControlGet, Selected instead of EM_GETSEL so I can remove the `r carriage returns before counting length.
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: CodeQuickTester

10 May 2015, 20:26

I've just updated the user script to work with the new code boxes. If you use my user script, it's time to update it!
ObiWanKenobi
Posts: 3
Joined: 02 May 2015, 10:41

Re: CodeQuickTester

16 May 2015, 03:00

Hello GeekDude, thank you for that great tool!
I have added some lines of code, that CodeQuickTester reopens the last opened ahk file or http url on next start:

Code: Select all

#SingleInstance, Off
#NoEnv
SetBatchLines, -1

FilePath := CheckLastOpenedFile()
if FileExist(FilePath)
	Code := FileOpen(FilePath, "r").Read()
else if (FilePath ~= "^https?://")
	Code := UrlDownloadToVar(FilePath)
 
Title = CodeQuickTester
DefaultDesc =
DefaultName = %A_UserName%
 
Menu, Tray, Icon, %A_AhkPath%, 2
Shell := ComObjCreate("WScript.Shell")
FileEncoding, UTF-8
 
Menu, MenuBar, Add, &Save, SaveButton
Menu, MenuBar, Add, &Load, LoadButton
Menu, MenuBar, Add, &Fetch, FetchButton
Menu, MenuBar, Add, &Paste, PasteButton
Menu, MenuBar, Add, P&arams, ParamsButton
Menu, MenuBar, Add, Install, ServiceHandler
 
Gui, Main:New, +Resize
Gui, Menu, MenuBar
Gui, Margin, 5, 5
Gui, Color,, 3F3F3F
Gui, Font, s10 cEDEDCD, Consolas
Gui, Add, Edit, vCodeEditor hWndhCodeEditor WantTab -Wrap HScroll t14 r2 ; t14 sets tab size to 4 characters
Gui, Font, s8, Microsoft Sans Serif
Gui, Add, Button, gRunButton vRun, &Run
Gui, Show, w640 h480, %Title%
Gui, Add, StatusBar
SB_SetParts(70, 70, 70)
LoadCode(Code)
OnMessage(0x100, "ProcessEditEvents") ; WM_KEYDOWN
OnMessage(0x201, "ProcessEditEvents") ; WM_LBUTTONDOWN
return
 
#If Exec.Status == 0
Escape::Exec.Terminate() ; CheckIfRunning updates the GUI
#If
 
ProcessEditEvents(wParam, lParam, Msg, hWnd)
{
	global hCodeEditor
	if (hWnd == hCodeEditor)
		SetTimer, UpdateStatusBar, -0 ; Spawn new pseudo thread that will run after this function terminates
}
 
UpdateStatusBar()
{
	global hCodeEditor
	Gui, Main:Default
	GuiControlGet, CodeEditor
	SB_SetText("Len " StrLen(CodeEditor), 1)
	ControlGet, Row, CurrentLine,,, ahk_id %hCodeEditor%
	ControlGet, Col, CurrentCol,,, ahk_id %hCodeEditor%
	SB_SetText("Line " Row, 2)
	SB_SetText("Col " Col, 3)
	ControlGet, Selected, Selected,,, ahk_id %hCodeEditor%
	Len := StrLen(StrReplace(Selected, "`r`n", "`n"))
	SB_SetText(Len ? "Selection Length: " Len : "", 4)
}
 
MainGuiClose:
GuiControlGet, CodeEditor
if !CodeEditor
	ExitApp
MsgBox, 308, %Title%, Are you sure you want to exit?
IfMsgBox, Yes
	ExitApp
return
 
MainGuiSize:
Critical
Process, Priority,, R
GuiControl, Move, CodeEditor, % "x" 5 "y" 5 "w" A_GuiWidth-10 "h" A_GuiHeight-60
ButtonWidth := (A_GuiWidth-10)
GuiControl, Move, Run, % "x" 5 "y" A_GuiHeight-50 "w" ButtonWidth "h" 22
SetTimer, Normal, -100
return
 
Normal:
Process, Priority,, N
return
 
MainGuiDropFiles:
LoadCode(FileOpen(StrSplit(A_GuiEvent, "`n")[1], "r").Read())
return
 
RunButton:
if (Exec.Status == 0) ; Running
	Exec.Terminate() ; CheckIfRunning updates the GUI
else ; Not running or doesn't exist
{
	GuiControlGet, CodeEditor, Main:
	GuiControlGet, Params, Params:
	Exec := ExecScript(CodeEditor, Params, DeHashBang(CodeEditor))
	GuiControl, Main:, Run, &Kill
	SetTimer, CheckIfRunning, 100
}
return
 
CheckIfRunning:
if (Exec.Status == 1)
{
	SetTimer, CheckIfRunning, Off
	GuiControl, Main:, Run, &Run
}
return
 
SaveButton:
Gui, +OwnDialogs
FileSelectFile, FilePath, S2
if ErrorLevel
	return
GuiControlGet, CodeEditor
FileOpen(FilePath, "w").Write(CodeEditor)
return
 
LoadButton:
Gui, +OwnDialogs
FileSelectFile, FilePath, 3
if !ErrorLevel
{
	LoadCode(FileOpen(FilePath, "r").Read())
	IniWrite, %FilePath%, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
}
return
 
FetchButton:
Gui, +OwnDialogs
InputBox, Url, %Title%, Enter a URL to fetch code from.
if (Url := Trim(Url))
{
	LoadCode(UrlDownloadToVar(Url))
	IniWrite, %FilePath%, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
}
return
 
PasteButton:
Gui, Paste:New, +OwnerMain +ToolWindow
Gui, Margin, 5, 5
Gui, Font, s8, Microsoft Sans Serif
Gui, Add, Text, xm ym w30 h22 +0x200, Desc:
Gui, Add, Edit, x+5 yp w125 h22 vPasteDesc, %DefaultDesc%
Gui, Add, Button, x+4 yp-1 w52 h24 Default gPaste, Paste
Gui, Add, Text, xm y+5 w30 h22 +0x200, Name:
Gui, Add, Edit, x+5 yp w100 h22 vPasteName, %DefaultName%
Gui, Add, DropDownList, x+5 yp w75 vPasteChan hWndPasteChan, Announce||#ahk|#ahkscript
PostMessage, 0x153, -1, 22-6,, ahk_id %PasteChan% ; Set height of DropDownList
Gui, Show,, Paste
return
 
PasteGuiEscape:
Gui, Destroy
return
 
Paste:
Gui, Submit
Gui, Destroy
GuiControlGet, CodeEditor, Main:
Link := Ahkbin(CodeEditor, PasteName, PasteDesc, PasteChan)
MsgBox, 292, %Title%, Link acquired:`n%Link%`n`nCopy to clipboard?
IfMsgBox, Yes
	Clipboard := Link
return
 
ParamsButton:
Gui, Params:New, +OwnerMain +ToolWindow
Gui, Margin, 5, 5
Gui, Font, s8, Microsoft Sans Serif
Gui, Add, Text, xm ym w300 h22 Center +0x200, Params will be cleared on window exit
Gui, Add, Edit, w300 h22 vParams
Gui, Show,, Command Line Params
return
 
ParamsGuiEscape:
Gui, Destroy
return
 
ServiceHandler:
Gui, +OwnDialogs
if ServiceHandlerInstalled()
{
	MsgBox, 36, , Are you sure you want to remove CodeQuickTester from being the default service handler for "ahk:" links?
	IfMsgBox, Yes
		RemoveServiceHandler()
}
else
{
	MsgBox, 36, , Are you sure you want to install CodeQuickTester as the default service handler for "ahk:" links?
	IfMsgBox, Yes
		AddServiceHandler()
}
return

CheckLastOpenedFile()
{
	IniRead, sRet, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
	if (sRet == "")
		sRet := RegExReplace(%True%, "^ahk:") ; Using True as a dummy var containing 1
	return sRet
}

LoadCode(Code)
{
	GuiControlGet, CodeEditor
	if (CodeEditor && CodeEditor != Code)
	{
		MsgBox, 308, %Title%, Are you sure you want to overwrite your code?
		IfMsgBox, No
			return
	}
	GuiControl,, CodeEditor, %Code%
	UpdateStatusBar()
}
 
UrlDownloadToVar(Url)
{
	try
	{
		http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
		http.Open("GET", Url, false), http.Send()
		return http.ResponseText
	}
	catch
		throw Exception("Something went wrong with the HTTP Request. Invalid URL?")
}
 
; Modified from https://github.com/cocobelgica/AutoHotkey-Util/blob/master/ExecScript.ahk
ExecScript(Script, Params="", AhkPath="")
{
	Name := "AHK_CQT_" A_TickCount
	Pipe := []
	Loop, 2
	{
		Pipe[A_Index] := DllCall("CreateNamedPipe"
		, "Str", "\\.\pipe\" name
		, "UInt", 2, "UInt", 0
		, "UInt", 255, "UInt", 0
		, "UInt", 0, "UPtr", 0
		, "UPtr", 0, "UPtr")
	}
	if !FileExist(AhkPath)
		AhkPath := A_AhkPath
	Call = "%AhkPath%" /CP65001 "\\.\pipe\%Name%"
	Shell := ComObjCreate("WScript.Shell")
	Exec := Shell.Exec(Call " " Params)
	DllCall("ConnectNamedPipe", "UPtr", Pipe[1], "UPtr", 0)
	DllCall("CloseHandle", "UPtr", Pipe[1])
	DllCall("ConnectNamedPipe", "UPtr", Pipe[2], "UPtr", 0)
	FileOpen(Pipe[2], "h", "UTF-8").Write(Script)
	DllCall("CloseHandle", "UPtr", Pipe[2])
	return Exec
}
 
Ahkbin(Content, Name="", Desc="", Channel="")
{
	static URL := "http://ahk.us.to/"
	Form := "code=" UriEncode(Content)
	if Name
		Form .= "&name=" UriEncode(Name)
	if Desc
		Form .= "&desc=" UriEncode(Desc)
	if Channel
		Form .= "&announce=on&channel=" UriEncode(Channel)
	
	Pbin := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	Pbin.Open("POST", URL, False)
	Pbin.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
	Pbin.Send(Form)
	return Pbin.Option(1)
}
 
; Modified by GeekDude from http://goo.gl/0a0iJq
UriEncode(Uri, RE="[0-9A-Za-z]") {
	VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0), StrPut(Uri, &Var, "UTF-8")
	While Code := NumGet(Var, A_Index - 1, "UChar")
		Res .= (Chr:=Chr(Code)) ~= RE ? Chr : Format("%{:02X}", Code)
	Return, Res
}
 
DeHashBang(Script)
{
	AhkPath := A_AhkPath
	if RegExMatch(Script, "`a)^\s*`;#!\s*(.+)", Match)
	{
		AhkPath := Trim(Match1)
		Vars := {"%A_ScriptDir%": A_WorkingDir
		, "%A_WorkingDir%": A_WorkingDir
		, "%A_AppData%": A_AppData
		, "%A_AppDataCommon%": A_AppDataCommon
		, "%A_LineFile%": A_ScriptFullPath
		, "%A_AhkPath%": A_AhkPath}
		for SearchText, Replacement in Vars
			StringReplace, AhkPath, AhkPath, %SearchText%, %Replacement%, All
	}
	return AhkPath
}
 
AddServiceHandler()
{
	RegWrite, REG_SZ, HKCU, Software\Classes\ahk,, URL:AHK Script Protocol
	RegWrite, REG_SZ, HKCU, Software\Classes\ahk, URL Protocol
	RegWrite, REG_SZ, HKCU, Software\Classes\ahk\shell\open\command,, "%A_AhkPath%" "%A_ScriptFullPath%" "`%1"
}
 
RemoveServiceHandler()
{
	RegDelete, HKCU, Software\Classes\ahk
}
 
ServiceHandlerInstalled()
{
	RegRead, Out, HKCU, Software\Classes\ahk
	return !ErrorLevel
}
Oops, forgot to add

Code: Select all

IniWrite, %FilePath%, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
In line 122 of your script (above "return" in SaveButton:)

Hello, it's me again, i have modified your script again, now it can read out any ahk files found in subdirectory /CodeQuickTesterAutoInclude/

Where to find (it will be automatically created):
C:\CodeQuickTester\CodeQuickTesterAutoInclude\

There you can place any ahk files and they will be read out automatically be the script (recursive) and merged with your original script, that you run.

Example:
C:\CodeQuickTester\CodeQuickTesterAutoInclude\mylib.ahk
C:\CodeQuickTester\CodeQuickTesterAutoInclude\myanotherlib.ahk
C:\CodeQuickTester\CodeQuickTesterAutoInclude\mylib3.ahk

Here is my code (with prevous modification):

Code: Select all

#SingleInstance, Off
#NoEnv
SetBatchLines, -1

glsAutoIncludeDir=%A_ScriptDir%\CodeQuickTesterAutoInclude
IfNotExist, %glsAutoIncludeDir%
	FileCreateDir, %glsAutoIncludeDir%

FilePath := CheckLastOpenedFile()
if FileExist(FilePath)
	Code := FileOpen(FilePath, "r").Read()
else if (FilePath ~= "^https?://")
	Code := UrlDownloadToVar(FilePath)
 
Title = CodeQuickTester
DefaultDesc =
DefaultName = %A_UserName%
 
Menu, Tray, Icon, %A_AhkPath%, 2
Shell := ComObjCreate("WScript.Shell")
FileEncoding, UTF-8
 
Menu, MenuBar, Add, &Save, SaveButton
Menu, MenuBar, Add, &Load, LoadButton
Menu, MenuBar, Add, &Fetch, FetchButton
Menu, MenuBar, Add, &Paste, PasteButton
Menu, MenuBar, Add, P&arams, ParamsButton
Menu, MenuBar, Add, Install, ServiceHandler
 
Gui, Main:New, +Resize
Gui, Menu, MenuBar
Gui, Margin, 5, 5
Gui, Color,, 3F3F3F
Gui, Font, s10 cEDEDCD, Consolas
Gui, Add, Edit, vCodeEditor hWndhCodeEditor WantTab -Wrap HScroll t14 r2 ; t14 sets tab size to 4 characters
Gui, Font, s8, Microsoft Sans Serif
Gui, Add, Button, gRunButton vRun, &Run
Gui, Show, w640 h480, %Title%
Gui, Add, StatusBar
SB_SetParts(70, 70, 70)
LoadCode(Code)
OnMessage(0x100, "ProcessEditEvents") ; WM_KEYDOWN
OnMessage(0x201, "ProcessEditEvents") ; WM_LBUTTONDOWN
return
 
#If Exec.Status == 0
Escape::Exec.Terminate() ; CheckIfRunning updates the GUI
#If
 
ProcessEditEvents(wParam, lParam, Msg, hWnd)
{
	global hCodeEditor
	if (hWnd == hCodeEditor)
		SetTimer, UpdateStatusBar, -0 ; Spawn new pseudo thread that will run after this function terminates
}
 
UpdateStatusBar()
{
	global hCodeEditor
	Gui, Main:Default
	GuiControlGet, CodeEditor
	SB_SetText("Len " StrLen(CodeEditor), 1)
	ControlGet, Row, CurrentLine,,, ahk_id %hCodeEditor%
	ControlGet, Col, CurrentCol,,, ahk_id %hCodeEditor%
	SB_SetText("Line " Row, 2)
	SB_SetText("Col " Col, 3)
	ControlGet, Selected, Selected,,, ahk_id %hCodeEditor%
	Len := StrLen(StrReplace(Selected, "`r`n", "`n"))
	SB_SetText(Len ? "Selection Length: " Len : "", 4)
}
 
MainGuiClose:
GuiControlGet, CodeEditor
if !CodeEditor
	ExitApp
MsgBox, 308, %Title%, Are you sure you want to exit?
IfMsgBox, Yes
	ExitApp
return
 
MainGuiSize:
Critical
Process, Priority,, R
GuiControl, Move, CodeEditor, % "x" 5 "y" 5 "w" A_GuiWidth-10 "h" A_GuiHeight-60
ButtonWidth := (A_GuiWidth-10)
GuiControl, Move, Run, % "x" 5 "y" A_GuiHeight-50 "w" ButtonWidth "h" 22
SetTimer, Normal, -100
return
 
Normal:
Process, Priority,, N
return
 
MainGuiDropFiles:
LoadCode(FileOpen(StrSplit(A_GuiEvent, "`n")[1], "r").Read())
return
 
RunButton:
if (Exec.Status == 0) ; Running
	Exec.Terminate() ; CheckIfRunning updates the GUI
else ; Not running or doesn't exist
{
	GuiControlGet, CodeEditor, Main:
	GuiControlGet, Params, Params:
	CodeEditor := AutoInclude(CodeEditor)
	Exec := ExecScript(CodeEditor, Params, DeHashBang(CodeEditor))
	GuiControl, Main:, Run, &Kill
	SetTimer, CheckIfRunning, 100
}
return
 
CheckIfRunning:
if (Exec.Status == 1)
{
	SetTimer, CheckIfRunning, Off
	GuiControl, Main:, Run, &Run
}
return
 
SaveButton:
Gui, +OwnDialogs
FileSelectFile, FilePath, S2
if ErrorLevel
	return
GuiControlGet, CodeEditor
FileOpen(FilePath, "w").Write(CodeEditor)
IniWrite, %FilePath%, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
return
 
LoadButton:
Gui, +OwnDialogs
FileSelectFile, FilePath, 3
if !ErrorLevel
{
	LoadCode(FileOpen(FilePath, "r").Read())
	IniWrite, %FilePath%, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
}
return
 
FetchButton:
Gui, +OwnDialogs
InputBox, Url, %Title%, Enter a URL to fetch code from.
if (Url := Trim(Url))
{
	LoadCode(UrlDownloadToVar(Url))
	IniWrite, %FilePath%, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
}
return
 
PasteButton:
Gui, Paste:New, +OwnerMain +ToolWindow
Gui, Margin, 5, 5
Gui, Font, s8, Microsoft Sans Serif
Gui, Add, Text, xm ym w30 h22 +0x200, Desc:
Gui, Add, Edit, x+5 yp w125 h22 vPasteDesc, %DefaultDesc%
Gui, Add, Button, x+4 yp-1 w52 h24 Default gPaste, Paste
Gui, Add, Text, xm y+5 w30 h22 +0x200, Name:
Gui, Add, Edit, x+5 yp w100 h22 vPasteName, %DefaultName%
Gui, Add, DropDownList, x+5 yp w75 vPasteChan hWndPasteChan, Announce||#ahk|#ahkscript
PostMessage, 0x153, -1, 22-6,, ahk_id %PasteChan% ; Set height of DropDownList
Gui, Show,, Paste
return
 
PasteGuiEscape:
Gui, Destroy
return
 
Paste:
Gui, Submit
Gui, Destroy
GuiControlGet, CodeEditor, Main:
Link := Ahkbin(CodeEditor, PasteName, PasteDesc, PasteChan)
MsgBox, 292, %Title%, Link acquired:`n%Link%`n`nCopy to clipboard?
IfMsgBox, Yes
	Clipboard := Link
return
 
ParamsButton:
Gui, Params:New, +OwnerMain +ToolWindow
Gui, Margin, 5, 5
Gui, Font, s8, Microsoft Sans Serif
Gui, Add, Text, xm ym w300 h22 Center +0x200, Params will be cleared on window exit
Gui, Add, Edit, w300 h22 vParams
Gui, Show,, Command Line Params
return
 
ParamsGuiEscape:
Gui, Destroy
return
 
ServiceHandler:
Gui, +OwnDialogs
if ServiceHandlerInstalled()
{
	MsgBox, 36, , Are you sure you want to remove CodeQuickTester from being the default service handler for "ahk:" links?
	IfMsgBox, Yes
		RemoveServiceHandler()
}
else
{
	MsgBox, 36, , Are you sure you want to install CodeQuickTester as the default service handler for "ahk:" links?
	IfMsgBox, Yes
		AddServiceHandler()
}
return

AutoInclude(psScript)
{
	global glsAutoIncludeDir
	IfExist, %glsAutoIncludeDir%
	{
		Loop, %glsAutoIncludeDir%\*.ahk,,1 ; Recurse into subfolders.
			FileRead, sFileContent, %A_LoopFileFullPath%
			if (sFileContent != "")
				sRet .= sFileContent . "`r`n"
	}
	else
	{
		FileCreateDir, %glsAutoIncludeDir%
	}
	return sRet . psScript
}

CheckLastOpenedFile()
{
	IniRead, sRet, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
	if (sRet == "")
		sRet := RegExReplace(%True%, "^ahk:") ; Using True as a dummy var containing 1
	return sRet
}

LoadCode(Code)
{
	GuiControlGet, CodeEditor
	if (CodeEditor && CodeEditor != Code)
	{
		MsgBox, 308, %Title%, Are you sure you want to overwrite your code?
		IfMsgBox, No
			return
	}
	GuiControl,, CodeEditor, %Code%
	UpdateStatusBar()
}
 
UrlDownloadToVar(Url)
{
	try
	{
		http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
		http.Open("GET", Url, false), http.Send()
		return http.ResponseText
	}
	catch
		throw Exception("Something went wrong with the HTTP Request. Invalid URL?")
}
 
; Modified from https://github.com/cocobelgica/AutoHotkey-Util/blob/master/ExecScript.ahk
ExecScript(Script, Params="", AhkPath="")
{
	Name := "AHK_CQT_" A_TickCount
	Pipe := []
	Loop, 2
	{
		Pipe[A_Index] := DllCall("CreateNamedPipe"
		, "Str", "\\.\pipe\" name
		, "UInt", 2, "UInt", 0
		, "UInt", 255, "UInt", 0
		, "UInt", 0, "UPtr", 0
		, "UPtr", 0, "UPtr")
	}
	if !FileExist(AhkPath)
		AhkPath := A_AhkPath
	Call = "%AhkPath%" /CP65001 "\\.\pipe\%Name%"
	Shell := ComObjCreate("WScript.Shell")
	Exec := Shell.Exec(Call " " Params)
	DllCall("ConnectNamedPipe", "UPtr", Pipe[1], "UPtr", 0)
	DllCall("CloseHandle", "UPtr", Pipe[1])
	DllCall("ConnectNamedPipe", "UPtr", Pipe[2], "UPtr", 0)
	FileOpen(Pipe[2], "h", "UTF-8").Write(Script)
	DllCall("CloseHandle", "UPtr", Pipe[2])
	return Exec
}
 
Ahkbin(Content, Name="", Desc="", Channel="")
{
	static URL := "http://ahk.us.to/"
	Form := "code=" UriEncode(Content)
	if Name
		Form .= "&name=" UriEncode(Name)
	if Desc
		Form .= "&desc=" UriEncode(Desc)
	if Channel
		Form .= "&announce=on&channel=" UriEncode(Channel)
	
	Pbin := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	Pbin.Open("POST", URL, False)
	Pbin.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
	Pbin.Send(Form)
	return Pbin.Option(1)
}
 
; Modified by GeekDude from http://goo.gl/0a0iJq
UriEncode(Uri, RE="[0-9A-Za-z]") {
	VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0), StrPut(Uri, &Var, "UTF-8")
	While Code := NumGet(Var, A_Index - 1, "UChar")
		Res .= (Chr:=Chr(Code)) ~= RE ? Chr : Format("%{:02X}", Code)
	Return, Res
}
 
DeHashBang(Script)
{
	AhkPath := A_AhkPath
	if RegExMatch(Script, "`a)^\s*`;#!\s*(.+)", Match)
	{
		AhkPath := Trim(Match1)
		Vars := {"%A_ScriptDir%": A_WorkingDir
		, "%A_WorkingDir%": A_WorkingDir
		, "%A_AppData%": A_AppData
		, "%A_AppDataCommon%": A_AppDataCommon
		, "%A_LineFile%": A_ScriptFullPath
		, "%A_AhkPath%": A_AhkPath}
		for SearchText, Replacement in Vars
			StringReplace, AhkPath, AhkPath, %SearchText%, %Replacement%, All
	}
	return AhkPath
}
 
AddServiceHandler()
{
	RegWrite, REG_SZ, HKCU, Software\Classes\ahk,, URL:AHK Script Protocol
	RegWrite, REG_SZ, HKCU, Software\Classes\ahk, URL Protocol
	RegWrite, REG_SZ, HKCU, Software\Classes\ahk\shell\open\command,, "%A_AhkPath%" "%A_ScriptFullPath%" "`%1"
}
 
RemoveServiceHandler()
{
	RegDelete, HKCU, Software\Classes\ahk
}
 
ServiceHandlerInstalled()
{
	RegRead, Out, HKCU, Software\Classes\ahk
	return !ErrorLevel
}
Ok, for more completeness, i've added new button in menu bar ...

Code: Select all

#SingleInstance, Off
#NoEnv
SetBatchLines, -1

glsAutoIncludeDir=%A_ScriptDir%\CodeQuickTesterAutoInclude
IfNotExist, %glsAutoIncludeDir%
	FileCreateDir, %glsAutoIncludeDir%

FilePath := CheckLastOpenedFile()
if FileExist(FilePath)
	Code := FileOpen(FilePath, "r").Read()
else if (FilePath ~= "^https?://")
	Code := UrlDownloadToVar(FilePath)
 
Title = CodeQuickTester
DefaultDesc =
DefaultName = %A_UserName%
 
Menu, Tray, Icon, %A_AhkPath%, 2
Shell := ComObjCreate("WScript.Shell")
FileEncoding, UTF-8

Menu, MenuBar, Add, &New, NewButton
Menu, MenuBar, Add, &Load, LoadButton
Menu, MenuBar, Add, &Fetch, FetchButton
Menu, MenuBar, Add, &Save, SaveButton
Menu, MenuBar, Add, &Paste, PasteButton
Menu, MenuBar, Add, P&arams, ParamsButton
Menu, MenuBar, Add, Install, ServiceHandler
 
Gui, Main:New, +Resize
Gui, Menu, MenuBar
Gui, Margin, 5, 5
Gui, Color,, 3F3F3F
Gui, Font, s10 cEDEDCD, Consolas
Gui, Add, Edit, vCodeEditor hWndhCodeEditor WantTab -Wrap HScroll t14 r2 ; t14 sets tab size to 4 characters
Gui, Font, s8, Microsoft Sans Serif
Gui, Add, Button, gRunButton vRun, &Run
Gui, Show, w640 h480, %Title%
Gui, Add, StatusBar
SB_SetParts(70, 70, 70)
LoadCode(Code)
OnMessage(0x100, "ProcessEditEvents") ; WM_KEYDOWN
OnMessage(0x201, "ProcessEditEvents") ; WM_LBUTTONDOWN
return
 
#If Exec.Status == 0
Escape::Exec.Terminate() ; CheckIfRunning updates the GUI
#If
 
ProcessEditEvents(wParam, lParam, Msg, hWnd)
{
	global hCodeEditor
	if (hWnd == hCodeEditor)
		SetTimer, UpdateStatusBar, -0 ; Spawn new pseudo thread that will run after this function terminates
}
 
UpdateStatusBar()
{
	global hCodeEditor
	Gui, Main:Default
	GuiControlGet, CodeEditor
	SB_SetText("Len " StrLen(CodeEditor), 1)
	ControlGet, Row, CurrentLine,,, ahk_id %hCodeEditor%
	ControlGet, Col, CurrentCol,,, ahk_id %hCodeEditor%
	SB_SetText("Line " Row, 2)
	SB_SetText("Col " Col, 3)
	ControlGet, Selected, Selected,,, ahk_id %hCodeEditor%
	Len := StrLen(StrReplace(Selected, "`r`n", "`n"))
	SB_SetText(Len ? "Selection Length: " Len : "", 4)
}
 
MainGuiClose:
GuiControlGet, CodeEditor
if !CodeEditor
	ExitApp
MsgBox, 308, %Title%, Are you sure you want to exit?
IfMsgBox, Yes
	ExitApp
return
 
MainGuiSize:
Critical
Process, Priority,, R
GuiControl, Move, CodeEditor, % "x" 5 "y" 5 "w" A_GuiWidth-10 "h" A_GuiHeight-60
ButtonWidth := (A_GuiWidth-10)
GuiControl, Move, Run, % "x" 5 "y" A_GuiHeight-50 "w" ButtonWidth "h" 22
SetTimer, Normal, -100
return
 
Normal:
Process, Priority,, N
return
 
MainGuiDropFiles:
LoadCode(FileOpen(StrSplit(A_GuiEvent, "`n")[1], "r").Read())
return
 
RunButton:
if (Exec.Status == 0) ; Running
	Exec.Terminate() ; CheckIfRunning updates the GUI
else ; Not running or doesn't exist
{
	GuiControlGet, CodeEditor, Main:
	GuiControlGet, Params, Params:
	CodeEditor := AutoInclude(CodeEditor)
	Exec := ExecScript(CodeEditor, Params, DeHashBang(CodeEditor))
	GuiControl, Main:, Run, &Kill
	SetTimer, CheckIfRunning, 100
}
return
 
CheckIfRunning:
if (Exec.Status == 1)
{
	SetTimer, CheckIfRunning, Off
	GuiControl, Main:, Run, &Run
}
return

NewButton:
Gui, +OwnDialogs

GuiControlGet, CodeEditor
if (CodeEditor && CodeEditor != Code)
{
	MsgBox, 308, %Title%, Are you sure you want to overwrite your code?
	IfMsgBox, No
		return
}
GuiControl,, CodeEditor
UpdateStatusBar()
IniWrite, %FilePath%, %A_ScriptDir%\CodeQuickTester.ini, Default
return
 
SaveButton:
Gui, +OwnDialogs
FileSelectFile, FilePath, S2
if ErrorLevel
	return
GuiControlGet, CodeEditor
FileOpen(FilePath, "w").Write(CodeEditor)
IniWrite, %FilePath%, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
return
 
LoadButton:
Gui, +OwnDialogs
FileSelectFile, FilePath, 3
if !ErrorLevel
{
	LoadCode(FileOpen(FilePath, "r").Read())
	IniWrite, %FilePath%, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
}
return
 
FetchButton:
Gui, +OwnDialogs
InputBox, Url, %Title%, Enter a URL to fetch code from.
if (Url := Trim(Url))
{
	LoadCode(UrlDownloadToVar(Url))
	IniWrite, %FilePath%, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
}
return
 
PasteButton:
Gui, Paste:New, +OwnerMain +ToolWindow
Gui, Margin, 5, 5
Gui, Font, s8, Microsoft Sans Serif
Gui, Add, Text, xm ym w30 h22 +0x200, Desc:
Gui, Add, Edit, x+5 yp w125 h22 vPasteDesc, %DefaultDesc%
Gui, Add, Button, x+4 yp-1 w52 h24 Default gPaste, Paste
Gui, Add, Text, xm y+5 w30 h22 +0x200, Name:
Gui, Add, Edit, x+5 yp w100 h22 vPasteName, %DefaultName%
Gui, Add, DropDownList, x+5 yp w75 vPasteChan hWndPasteChan, Announce||#ahk|#ahkscript
PostMessage, 0x153, -1, 22-6,, ahk_id %PasteChan% ; Set height of DropDownList
Gui, Show,, Paste
return
 
PasteGuiEscape:
Gui, Destroy
return
 
Paste:
Gui, Submit
Gui, Destroy
GuiControlGet, CodeEditor, Main:
Link := Ahkbin(CodeEditor, PasteName, PasteDesc, PasteChan)
MsgBox, 292, %Title%, Link acquired:`n%Link%`n`nCopy to clipboard?
IfMsgBox, Yes
	Clipboard := Link
return
 
ParamsButton:
Gui, Params:New, +OwnerMain +ToolWindow
Gui, Margin, 5, 5
Gui, Font, s8, Microsoft Sans Serif
Gui, Add, Text, xm ym w300 h22 Center +0x200, Params will be cleared on window exit
Gui, Add, Edit, w300 h22 vParams
Gui, Show,, Command Line Params
return
 
ParamsGuiEscape:
Gui, Destroy
return
 
ServiceHandler:
Gui, +OwnDialogs
if ServiceHandlerInstalled()
{
	MsgBox, 36, , Are you sure you want to remove CodeQuickTester from being the default service handler for "ahk:" links?
	IfMsgBox, Yes
		RemoveServiceHandler()
}
else
{
	MsgBox, 36, , Are you sure you want to install CodeQuickTester as the default service handler for "ahk:" links?
	IfMsgBox, Yes
		AddServiceHandler()
}
return

AutoInclude(psScript)
{
	global glsAutoIncludeDir
	IfExist, %glsAutoIncludeDir%
	{
		Loop, %glsAutoIncludeDir%\*.ahk,,1 ; Recurse into subfolders.
			FileRead, sFileContent, %A_LoopFileFullPath%
			if (sFileContent != "")
				sRet .= sFileContent . "`r`n"
	}
	else
	{
		FileCreateDir, %glsAutoIncludeDir%
	}
	return sRet . psScript
}

CheckLastOpenedFile()
{
	IniRead, sRet, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
	if (sRet == "")
		sRet := RegExReplace(%True%, "^ahk:") ; Using True as a dummy var containing 1
	return sRet
}

LoadCode(Code)
{
	GuiControlGet, CodeEditor
	if (CodeEditor && CodeEditor != Code)
	{
		MsgBox, 308, %Title%, Are you sure you want to overwrite your code?
		IfMsgBox, No
			return
	}
	GuiControl,, CodeEditor, %Code%
	UpdateStatusBar()
}
 
UrlDownloadToVar(Url)
{
	try
	{
		http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
		http.Open("GET", Url, false), http.Send()
		return http.ResponseText
	}
	catch
		throw Exception("Something went wrong with the HTTP Request. Invalid URL?")
}
 
; Modified from https://github.com/cocobelgica/AutoHotkey-Util/blob/master/ExecScript.ahk
ExecScript(Script, Params="", AhkPath="")
{
	Name := "AHK_CQT_" A_TickCount
	Pipe := []
	Loop, 2
	{
		Pipe[A_Index] := DllCall("CreateNamedPipe"
		, "Str", "\\.\pipe\" name
		, "UInt", 2, "UInt", 0
		, "UInt", 255, "UInt", 0
		, "UInt", 0, "UPtr", 0
		, "UPtr", 0, "UPtr")
	}
	if !FileExist(AhkPath)
		AhkPath := A_AhkPath
	Call = "%AhkPath%" /CP65001 "\\.\pipe\%Name%"
	Shell := ComObjCreate("WScript.Shell")
	Exec := Shell.Exec(Call " " Params)
	DllCall("ConnectNamedPipe", "UPtr", Pipe[1], "UPtr", 0)
	DllCall("CloseHandle", "UPtr", Pipe[1])
	DllCall("ConnectNamedPipe", "UPtr", Pipe[2], "UPtr", 0)
	FileOpen(Pipe[2], "h", "UTF-8").Write(Script)
	DllCall("CloseHandle", "UPtr", Pipe[2])
	return Exec
}
 
Ahkbin(Content, Name="", Desc="", Channel="")
{
	static URL := "http://ahk.us.to/"
	Form := "code=" UriEncode(Content)
	if Name
		Form .= "&name=" UriEncode(Name)
	if Desc
		Form .= "&desc=" UriEncode(Desc)
	if Channel
		Form .= "&announce=on&channel=" UriEncode(Channel)
	
	Pbin := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	Pbin.Open("POST", URL, False)
	Pbin.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
	Pbin.Send(Form)
	return Pbin.Option(1)
}
 
; Modified by GeekDude from http://goo.gl/0a0iJq
UriEncode(Uri, RE="[0-9A-Za-z]") {
	VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0), StrPut(Uri, &Var, "UTF-8")
	While Code := NumGet(Var, A_Index - 1, "UChar")
		Res .= (Chr:=Chr(Code)) ~= RE ? Chr : Format("%{:02X}", Code)
	Return, Res
}
 
DeHashBang(Script)
{
	AhkPath := A_AhkPath
	if RegExMatch(Script, "`a)^\s*`;#!\s*(.+)", Match)
	{
		AhkPath := Trim(Match1)
		Vars := {"%A_ScriptDir%": A_WorkingDir
		, "%A_WorkingDir%": A_WorkingDir
		, "%A_AppData%": A_AppData
		, "%A_AppDataCommon%": A_AppDataCommon
		, "%A_LineFile%": A_ScriptFullPath
		, "%A_AhkPath%": A_AhkPath}
		for SearchText, Replacement in Vars
			StringReplace, AhkPath, AhkPath, %SearchText%, %Replacement%, All
	}
	return AhkPath
}
 
AddServiceHandler()
{
	RegWrite, REG_SZ, HKCU, Software\Classes\ahk,, URL:AHK Script Protocol
	RegWrite, REG_SZ, HKCU, Software\Classes\ahk, URL Protocol
	RegWrite, REG_SZ, HKCU, Software\Classes\ahk\shell\open\command,, "%A_AhkPath%" "%A_ScriptFullPath%" "`%1"
}
 
RemoveServiceHandler()
{
	RegDelete, HKCU, Software\Classes\ahk
}
 
ServiceHandlerInstalled()
{
	RegRead, Out, HKCU, Software\Classes\ahk
	return !ErrorLevel
}
ObiWanKenobi
Posts: 3
Joined: 02 May 2015, 10:41

Re: CodeQuickTester

17 May 2015, 12:19

Dear @Admin, you can delete my last posting - in this posting is my latest code (bugfixed and optimized) for CodeQuickTester:

- added new button for a clean new editor bix
- reopens last opened quicktest file, otherwise last edit box input
- it can read out any ahk files found in subdirectory /CodeQuickTesterAutoInclude/ and merge it with CodeQuickTester code

Example where you can find this subdirectory (automatically created if it does not exist):
C:\CodeQuickTester\CodeQuickTesterAutoInclude\

Place some libs in there:
C:\CodeQuickTester\CodeQuickTesterAutoInclude\mylib.ahk
C:\CodeQuickTester\CodeQuickTesterAutoInclude\sub\myanotherlib.ahk
C:\CodeQuickTester\CodeQuickTesterAutoInclude\mylib3.ahk

Code: Select all

#SingleInstance, Off
#NoEnv
SetBatchLines, -1

glsAutoIncludeDir=%A_ScriptDir%\CodeQuickTesterAutoInclude
IfNotExist, %glsAutoIncludeDir%
	FileCreateDir, %glsAutoIncludeDir%

FilePath := CheckLastOpenedFile()
if FileExist(FilePath)
	Code := FileOpen(FilePath, "r").Read()
else if (FilePath ~= "^https?://")
	Code := UrlDownloadToVar(FilePath)
else
{
	IniRead, sCodeEditorEncoded, %A_ScriptDir%\CodeQuickTester.ini, Default, CodeEditorEncoded
	if (sCodeEditorEncoded != "")
		Code := Base64Decode(sCodeEditorEncoded)
	sCodeEditorEncoded=
}
 
Title = CodeQuickTester
DefaultDesc =
DefaultName = %A_UserName%
 
Menu, Tray, Icon, %A_AhkPath%, 2
Shell := ComObjCreate("WScript.Shell")
FileEncoding, UTF-8

Menu, MenuBar, Add, &New, NewButton
Menu, MenuBar, Add, &Load, LoadButton
Menu, MenuBar, Add, &Fetch, FetchButton
Menu, MenuBar, Add, &Save, SaveButton
Menu, MenuBar, Add, &Paste, PasteButton
Menu, MenuBar, Add, P&arams, ParamsButton
Menu, MenuBar, Add, Install, ServiceHandler
 
Gui, Main:New, +Resize
Gui, Menu, MenuBar
Gui, Margin, 5, 5
Gui, Color,, 3F3F3F
Gui, Font, s10 cEDEDCD, Consolas
Gui, Add, Edit, vCodeEditor hWndhCodeEditor WantTab -Wrap HScroll t14 r2 ; t14 sets tab size to 4 characters
Gui, Font, s8, Microsoft Sans Serif
Gui, Add, Button, gRunButton vRun, &Run
Gui, Show, w640 h480, %Title%
Gui, Add, StatusBar
SB_SetParts(70, 70, 70)
LoadCode(Code)
OnMessage(0x100, "ProcessEditEvents") ; WM_KEYDOWN
OnMessage(0x201, "ProcessEditEvents") ; WM_LBUTTONDOWN
return
 
#If Exec.Status == 0
Escape::Exec.Terminate() ; CheckIfRunning updates the GUI
#If
 
ProcessEditEvents(wParam, lParam, Msg, hWnd)
{
	global hCodeEditor
	if (hWnd == hCodeEditor)
		SetTimer, UpdateStatusBar, -0 ; Spawn new pseudo thread that will run after this function terminates
}
 
UpdateStatusBar()
{
	global hCodeEditor
	Gui, Main:Default
	GuiControlGet, CodeEditor
	SB_SetText("Len " StrLen(CodeEditor), 1)
	ControlGet, Row, CurrentLine,,, ahk_id %hCodeEditor%
	ControlGet, Col, CurrentCol,,, ahk_id %hCodeEditor%
	SB_SetText("Line " Row, 2)
	SB_SetText("Col " Col, 3)
	ControlGet, Selected, Selected,,, ahk_id %hCodeEditor%
	Len := StrLen(StrReplace(Selected, "`r`n", "`n"))
	SB_SetText(Len ? "Selection Length: " Len : "", 4)
}
 
MainGuiClose:
GuiControlGet, CodeEditor
if !CodeEditor
{
	gosub WriteIniFile
	ExitApp	
}
MsgBox, 308, %Title%, Are you sure you want to exit?
IfMsgBox, Yes
{
	gosub WriteIniFile
	ExitApp
}
return
 
MainGuiSize:
Critical
Process, Priority,, R
GuiControl, Move, CodeEditor, % "x" 5 "y" 5 "w" A_GuiWidth-10 "h" A_GuiHeight-60
ButtonWidth := (A_GuiWidth-10)
GuiControl, Move, Run, % "x" 5 "y" A_GuiHeight-50 "w" ButtonWidth "h" 22
SetTimer, Normal, -100
return
 
Normal:
Process, Priority,, N
return
 
MainGuiDropFiles:
LoadCode(FileOpen(StrSplit(A_GuiEvent, "`n")[1], "r").Read())
return
 
RunButton:
if (Exec.Status == 0) ; Running
	Exec.Terminate() ; CheckIfRunning updates the GUI
else ; Not running or doesn't exist
{
	GuiControlGet, CodeEditor, Main:
	GuiControlGet, Params, Params:
	CodeEditor := AutoInclude(CodeEditor)
	Exec := ExecScript(CodeEditor, Params, DeHashBang(CodeEditor))
	GuiControl, Main:, Run, &Kill
	SetTimer, CheckIfRunning, 100
}
return
 
CheckIfRunning:
if (Exec.Status == 1)
{
	SetTimer, CheckIfRunning, Off
	GuiControl, Main:, Run, &Run
}
return

NewButton:
Gui, +OwnDialogs

GuiControlGet, CodeEditor
glsLastOpenedFile=
if (CodeEditor && CodeEditor != Code)
{
	MsgBox, 308, %Title%, Are you sure you want to overwrite your code?
	IfMsgBox, No
		return
}
GuiControl,, CodeEditor
UpdateStatusBar()
return
 
SaveButton:
Gui, +OwnDialogs
FileSelectFile, FilePath, S2
if ErrorLevel
	return
GuiControlGet, CodeEditor
FileOpen(FilePath, "w").Write(CodeEditor)
glsLastOpenedFile := FilePath
return
 
LoadButton:
Gui, +OwnDialogs
FileSelectFile, FilePath, 3
if !ErrorLevel
{
	LoadCode(FileOpen(FilePath, "r").Read())
	glsLastOpenedFile := FilePath
}
return
 
FetchButton:
Gui, +OwnDialogs
InputBox, Url, %Title%, Enter a URL to fetch code from.
if (Url := Trim(Url))
{
	LoadCode(UrlDownloadToVar(Url))
	glsLastOpenedFile := FilePath
}
return
 
PasteButton:
Gui, Paste:New, +OwnerMain +ToolWindow
Gui, Margin, 5, 5
Gui, Font, s8, Microsoft Sans Serif
Gui, Add, Text, xm ym w30 h22 +0x200, Desc:
Gui, Add, Edit, x+5 yp w125 h22 vPasteDesc, %DefaultDesc%
Gui, Add, Button, x+4 yp-1 w52 h24 Default gPaste, Paste
Gui, Add, Text, xm y+5 w30 h22 +0x200, Name:
Gui, Add, Edit, x+5 yp w100 h22 vPasteName, %DefaultName%
Gui, Add, DropDownList, x+5 yp w75 vPasteChan hWndPasteChan, Announce||#ahk|#ahkscript
PostMessage, 0x153, -1, 22-6,, ahk_id %PasteChan% ; Set height of DropDownList
Gui, Show,, Paste
return
 
PasteGuiEscape:
Gui, Destroy
return
 
Paste:
Gui, Submit
Gui, Destroy
GuiControlGet, CodeEditor, Main:
Link := Ahkbin(CodeEditor, PasteName, PasteDesc, PasteChan)
MsgBox, 292, %Title%, Link acquired:`n%Link%`n`nCopy to clipboard?
IfMsgBox, Yes
	Clipboard := Link
return
 
ParamsButton:
Gui, Params:New, +OwnerMain +ToolWindow
Gui, Margin, 5, 5
Gui, Font, s8, Microsoft Sans Serif
Gui, Add, Text, xm ym w300 h22 Center +0x200, Params will be cleared on window exit
Gui, Add, Edit, w300 h22 vParams
Gui, Show,, Command Line Params
return
 
ParamsGuiEscape:
Gui, Destroy
return
 
ServiceHandler:
Gui, +OwnDialogs
if ServiceHandlerInstalled()
{
	MsgBox, 36, , Are you sure you want to remove CodeQuickTester from being the default service handler for "ahk:" links?
	IfMsgBox, Yes
		RemoveServiceHandler()
}
else
{
	MsgBox, 36, , Are you sure you want to install CodeQuickTester as the default service handler for "ahk:" links?
	IfMsgBox, Yes
		AddServiceHandler()
}
return

WriteIniFile:
	if (glsLastOpenedFile == "")
	{
		GuiControlGet, CodeEditor
		sCodeEditorEncoded=
		if (CodeEditor != "")
			glsCodeEditorEncoded := Base64Encode(CodeEditor)
	}
	else
	{
		glsCodeEditorEncoded=
	}
	IniWrite, %glsLastOpenedFile%, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
	IniWrite, %glsCodeEditorEncoded%, %A_ScriptDir%\CodeQuickTester.ini, Default, CodeEditorEncoded
return

AutoInclude(psScript)
{
	global glsAutoIncludeDir
	IfExist, %glsAutoIncludeDir%
	{
		Loop, %glsAutoIncludeDir%\*.ahk,,1 ; Recurse into subfolders.
			FileRead, sFileContent, %A_LoopFileFullPath%
			if (sFileContent != "")
				sRet .= sFileContent . "`r`n"
	}
	else
	{
		FileCreateDir, %glsAutoIncludeDir%
	}
	return sRet . psScript
}

CheckLastOpenedFile()
{
	IniRead, sRet, %A_ScriptDir%\CodeQuickTester.ini, Default, LastOpenedFile
	if (sRet == "")
		sRet := RegExReplace(%True%, "^ahk:") ; Using True as a dummy var containing 1
	return sRet
}

LoadCode(Code)
{
	GuiControlGet, CodeEditor
	if (CodeEditor && CodeEditor != Code)
	{
		MsgBox, 308, %Title%, Are you sure you want to overwrite your code?
		IfMsgBox, No
			return
	}
	GuiControl,, CodeEditor, %Code%
	UpdateStatusBar()
}
 
UrlDownloadToVar(Url)
{
	try
	{
		http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
		http.Open("GET", Url, false), http.Send()
		return http.ResponseText
	}
	catch
		throw Exception("Something went wrong with the HTTP Request. Invalid URL?")
}
 
; Modified from https://github.com/cocobelgica/AutoHotkey-Util/blob/master/ExecScript.ahk
ExecScript(Script, Params="", AhkPath="")
{
	Name := "AHK_CQT_" A_TickCount
	Pipe := []
	Loop, 2
	{
		Pipe[A_Index] := DllCall("CreateNamedPipe"
		, "Str", "\\.\pipe\" name
		, "UInt", 2, "UInt", 0
		, "UInt", 255, "UInt", 0
		, "UInt", 0, "UPtr", 0
		, "UPtr", 0, "UPtr")
	}
	if !FileExist(AhkPath)
		AhkPath := A_AhkPath
	Call = "%AhkPath%" /CP65001 "\\.\pipe\%Name%"
	Shell := ComObjCreate("WScript.Shell")
	Exec := Shell.Exec(Call " " Params)
	DllCall("ConnectNamedPipe", "UPtr", Pipe[1], "UPtr", 0)
	DllCall("CloseHandle", "UPtr", Pipe[1])
	DllCall("ConnectNamedPipe", "UPtr", Pipe[2], "UPtr", 0)
	FileOpen(Pipe[2], "h", "UTF-8").Write(Script)
	DllCall("CloseHandle", "UPtr", Pipe[2])
	return Exec
}
 
Ahkbin(Content, Name="", Desc="", Channel="")
{
	static URL := "http://ahk.us.to/"
	Form := "code=" UriEncode(Content)
	if Name
		Form .= "&name=" UriEncode(Name)
	if Desc
		Form .= "&desc=" UriEncode(Desc)
	if Channel
		Form .= "&announce=on&channel=" UriEncode(Channel)
	
	Pbin := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	Pbin.Open("POST", URL, False)
	Pbin.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
	Pbin.Send(Form)
	return Pbin.Option(1)
}
 
; Modified by GeekDude from http://goo.gl/0a0iJq
UriEncode(Uri, RE="[0-9A-Za-z]") {
	VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0), StrPut(Uri, &Var, "UTF-8")
	While Code := NumGet(Var, A_Index - 1, "UChar")
		Res .= (Chr:=Chr(Code)) ~= RE ? Chr : Format("%{:02X}", Code)
	Return, Res
}
 
DeHashBang(Script)
{
	AhkPath := A_AhkPath
	if RegExMatch(Script, "`a)^\s*`;#!\s*(.+)", Match)
	{
		AhkPath := Trim(Match1)
		Vars := {"%A_ScriptDir%": A_WorkingDir
		, "%A_WorkingDir%": A_WorkingDir
		, "%A_AppData%": A_AppData
		, "%A_AppDataCommon%": A_AppDataCommon
		, "%A_LineFile%": A_ScriptFullPath
		, "%A_AhkPath%": A_AhkPath}
		for SearchText, Replacement in Vars
			StringReplace, AhkPath, AhkPath, %SearchText%, %Replacement%, All
	}
	return AhkPath
}
 
AddServiceHandler()
{
	RegWrite, REG_SZ, HKCU, Software\Classes\ahk,, URL:AHK Script Protocol
	RegWrite, REG_SZ, HKCU, Software\Classes\ahk, URL Protocol
	RegWrite, REG_SZ, HKCU, Software\Classes\ahk\shell\open\command,, "%A_AhkPath%" "%A_ScriptFullPath%" "`%1"
}
 
RemoveServiceHandler()
{
	RegDelete, HKCU, Software\Classes\ahk
}
 
ServiceHandlerInstalled()
{
	RegRead, Out, HKCU, Software\Classes\ahk
	return !ErrorLevel
}

; *** Base64 ***
Base64Encode(String)
{
    static CharSet := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    VarSetCapacity(Output,Ceil(Length / 3) << 2)
    Index := 1, Length := StrLen(String)
    Loop, % Length // 3
    {
        Value := Asc(SubStr(String,Index,1)) << 16
            | Asc(SubStr(String,Index + 1,1)) << 8
            | Asc(SubStr(String,Index + 2,1))
        Index += 3
        Output .= SubStr(CharSet,(Value >> 18) + 1,1)
            . SubStr(CharSet,((Value >> 12) & 63) + 1,1)
            . SubStr(CharSet,((Value >> 6) & 63) + 1,1)
            . SubStr(CharSet,(Value & 63) + 1,1)
    }
    Length := Mod(Length,3)
    If Length = 0 ;no characters remain
        Return, Output
    Value := Asc(SubStr(String,Index,1)) << 10
    If Length = 1
    {
        Return, Output ;one character remains
            . SubStr(CharSet,(Value >> 12) + 1,1)
            . SubStr(CharSet,((Value >> 6) & 63) + 1,1) . "=="
    }
    Value |= Asc(SubStr(String,Index + 1,1)) << 2 ;insert the third character
    Return, Output ;two characters remain
        . SubStr(CharSet,(Value >> 12) + 1,1)
        . SubStr(CharSet,((Value >> 6) & 63) + 1,1)
        . SubStr(CharSet,(Value & 63) + 1,1) . "="
}

;string based base64 decode
Base64Decode(Code)
{
    static CharSet := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    Length := StrLen(Code)

    ;remove padding if present
    If SubStr(Code,0) = "="
    {
        If SubStr(Code,-1,1) = "="
            Length -= 2
        Else
            Length --
    }

    BufferSize := Ceil((Length / 4) * 3), VarSetCapacity(Data,BufferSize) ;calculate the correct buffer size
    Index := 1, BinPos := 0
    Loop, % Length >> 2 ;process 4 characters per iteration
    {
        ;decode the characters and store them in the output buffer
        Value := ((InStr(CharSet,SubStr(Code,Index,1),1) - 1) << 18)
            | ((InStr(CharSet,SubStr(Code,Index + 1,1),1) - 1) << 12)
            | ((InStr(CharSet,SubStr(Code,Index + 2,1),1) - 1) << 6)
            | (InStr(CharSet,SubStr(Code,Index + 3,1),1) - 1)
        Index += 4
        Data .= Chr(Value >> 16) . Chr((Value >> 8) & 255) . Chr(Value & 255)
    }
    Length &= 3 ;determine the number of characters that remain
    If Length > 0 ;characters remain
    {
        ;decode the first of the remaining characters and store it in the output buffer
        Value := ((InStr(CharSet,SubStr(Code,Index,1),1) - 1) << 18)
            | ((InStr(CharSet,SubStr(Code,Index + 1,1),1) - 1) << 12)
        Data .= Chr(Value >> 16)

        ;another character remains
        If Length = 3
        {
            ;decode the character and store it in the output buffer
            Value |= (InStr(CharSet,SubStr(Code,Index + 2,1),1) - 1) << 6
            Data .= Chr((Value >> 8) & 255)
        }
    }
    Return, Data
}
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: CodeQuickTester

17 May 2015, 13:04

Isn't that what a lib folder is for?
ObiWanKenobi
Posts: 3
Joined: 02 May 2015, 10:41

Re: CodeQuickTester

17 May 2015, 13:35

i have added this directory /CodeQuickTesterAutoInclude, because:
- /lib or #include didn't work for code in CodeQuickTester editor box
- no need to manually insert #include ... for every quick testing, just put in any ahk and it will loaded automatically when hitting "run"; much faster
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: CodeQuickTester

29 May 2015, 07:11

Greasemonkey extension updated. It now works correctly again
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: CodeQuickTester

30 May 2015, 14:32

Question time! Should I make the code tester open the script template by default? The one located at C:\Windows\ShellNew\Template.ahk
User avatar
BGM
Posts: 507
Joined: 20 Nov 2013, 20:56
Contact:

Re: CodeQuickTester

30 May 2015, 15:17

GeekDude wrote:Greasemonkey extension updated. It now works correctly again
Say, what's this about a Greasemonkey extension? I missed something.

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: No registered users and 118 guests