AutoHotkey Homepage AutoHotkey Community
Let's help each other out
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Quick testing of script code placed on web

 
Reply to topic    AutoHotkey Community Forum Index -> Scripts & Functions
View previous topic :: View next topic  
Author Message
The gray Cardinal



Joined: 18 May 2006
Posts: 17
Location: Russia

PostPosted: Sat Dec 20, 2008 3:50 pm    Post subject: Quick testing of script code placed on web Reply with quote

This script provides quick testing of script code (or similar code) placed on web pages (for example on forum pages).

The script allows you to automatize the following set of operations: to copy selected code to the clipboard, create on a disk a temporary file with a relevant extension, open the file in a text editor, insert the code in the file, open, if necessary, file manager and/or command interpreter and jump to the directory with the temporary file. The script works only in Firefox, IE and Opera.

How it works: select a text fragment, press Win+T or Win+middle mouse button, choose extension, choose, if necessary, encoding.

All the settings are set in the testing.ini-file that should lie in the same directory as the script. When you run the script for the first time, testing.ini-file will be created, if necessary, automatically.

Section [general] is compulsory:
  • folder parameter is compulsory; it should contain the path to the temporary files directory to create temporary script files;
  • extensions parameter is compulsory; it should contain all the necessary extensions, separated by commas; each extension below requires a section of the same name.

Section [extension_name]:
  • editor parameter is compulsory; it should contain the path to the text editor plus advanced parameters of the command line (if you need them);
  • filemanager parameter is optional and allows you to run the file manager; it should contain the path to the file manager plus advanced parameters of the command line (if you need them);
  • cmd=True parameter is optional and allows you to run command interpreter;
  • selectCoding=True parameter is optional and allows you to choose encoding (UTF-8, OEM or ANSI) for the file being created; if this parameter is not specified, ANSI-file is created.

Code:

;======================================Секция автовыполнения=======================================

CreateINI() ; создаёт INI-файл "по умолчанию", если его нет

;======================================Хоткеи======================================================

#vk54::    ; Win+T
#MButton:: ; Win+Средняя кнопка мыши
    WinGet, hwnd, ID, A
    WinGetClass, class, A
    If(class = "MozillaUIWindowClass" or class = "IEFrame" or class = "OperaWindowClass")
        Gosub, CodeTesting
    Return

;======================================Метки=======================================================

CodeTesting:
    extension =
    ; Получаем список расширений:
    IniRead, exts, %A_ScriptDir%\testing.ini, general, extensions
    If(exts = "ERROR")
    {
        MsgBox, Неверный формат INI-файла! Не указан параметр extensions в секции general.
        ExitApp
    }
    ; Разбираем список расширений и генерируем меню:
    Loop, parse, exts, `,
        Menu, SelectMenu, Add, %A_LoopField%, labelExtension
    Menu, SelectMenu, Show ; отображаем меню со списком расширений
    If(extension = "") ; если ничего не выбрано, завершаем работу
        Return
   
    WinActivate, ahk_id%hwnd% ; активизируем окно браузера
    ClipSaved := ClipboardAll ; сохраняем содержимое буфера обмена
    Clipboard := ; очищаем буфер обмена
    SendInput, ^{vk43} ; посылаем Ctrl+C (копировать выделенное в буфер)
    ClipWait, 1 ; ждём появления данных в буфере 1 секунду
    ; Проверяем необходимость выбора кодировки:
    IniRead, selCod, %A_ScriptDir%\testing.ini, %extension%, selectCoding
    codingSel = ANSI ; кодировка по умолчанию
    If(selCod = "True")
    {
        coding =
        Menu, SelectCoding, Add, UTF-8, labelCoding
        Menu, SelectCoding, Add, ANSI, labelCoding
        Menu, SelectCoding, Add, OEM, labelCoding
        Menu, SelectCoding, Show ; выбор кодировки ("UTF-8" или "ANSI")
        If(coding = "") ; если ничего не выбрано, завершаем работу
            Return
        codingSel := coding
    }
    CodeForTesting =
    If(codingSel = "OEM")
        CodeForTesting := Ansi2Oem(Clipboard)
    Else If(codingSel = "ANSI")
        CodeForTesting := Clipboard
    Else ; UTF-8
        Transform, CodeForTesting, Unicode
    Clipboard := ClipSaved ; восстановление содержимого буфера
    If(CodeForTesting = "")
    {
        MsgBox, Не обнаружен код для тестирования! Возможно, при запуске не было ничего выделено.
        Return
    }
   
    ; Получаем папку для расположения скриптов:
    IniRead, fold, %A_ScriptDir%\testing.ini, general, folder
    fold := ExpandEnv(fold)
    If(fold = "ERROR")
    {
        MsgBox, Неверный формат INI-файла! Не указан параметр folder в секции general.
        ExitApp
    }
    FileCreateDir, %fold% ; создаём папку, если её нет
    FileDelete, %fold%\test.%extension% ; удаляем файл, если он есть
    FileAppend, %CodeForTesting%, %fold%\test.%extension% ; записываем файл
   
    ; Получаем путь к текстовому редактору:
    IniRead, ed, %A_ScriptDir%\testing.ini, %extension%, editor
    ed := ExpandEnv(ed)
    If(ed = "ERROR")
    {
        MsgBox, Неверный формат INI-файла! Не указан параметр editor в секции %extension%.
        ExitApp
    }
    Run, %ed% "%fold%\test.%extension%" ; запускаем текстовый редактор
   
    ; Получаем путь к файловому менеджеру:
    IniRead, fileman, %A_ScriptDir%\testing.ini, %extension%, filemanager
    fileman := ExpandEnv(fileman)
    If(fileman != "ERROR")
        Run, %fileman% "%fold%\test.%extension%" ; запускаем файловый менеджер
   
    ; Проверяем необходимость запуска cmd.exe:
    IniRead, commd, %A_ScriptDir%\testing.ini, %extension%, cmd
    If(commd = "True")
        Run, %comspec% /k cd %fold% ; запускаем cmd.exe
   
    Return

labelExtension:
    extension = %A_ThisMenuItem%
    Return

labelCoding:
    coding = %A_ThisMenuItem%
    Return

;======================================Функции=====================================================

; Создаёт INI-файл "по умолчанию", если его нет.
CreateINI()
{
    IfNotExist, %A_ScriptDir%\testing.ini
    {
        FileAppend,
        (
[general]
folder=C:\Temp\Testing
extensions=ahk,bat,cmd,css,html,hta,js,mf,py,pyw,vbs,wsf

[ahk]
editor="%windir%\notepad.exe"
filemanager=explorer /select,

[bat]
editor="%windir%\notepad.exe"
cmd=True

[cmd]
editor="%windir%\notepad.exe"
cmd=True

[css]
editor="%windir%\notepad.exe"

[html]
editor="%windir%\notepad.exe"
filemanager=explorer /select,

[hta]
editor="%windir%\notepad.exe"
filemanager=explorer /select,

[js]
editor="%windir%\notepad.exe"
cmd=True
filemanager=explorer /select,

[py]
editor="%windir%\notepad.exe"
cmd=True
selectCoding=True

[pyw]
editor="%windir%\notepad.exe"
filemanager=explorer /select,
selectCoding=True

[mf]
editor="%windir%\notepad.exe"
filemanager=explorer /select,

[vbs]
editor="%windir%\notepad.exe"
cmd=True
filemanager=explorer /select,

[wsf]
editor="%windir%\notepad.exe"
cmd=True
filemanager=explorer /select,

), %A_ScriptDir%\testing.ini
    }
}

; Разворачивает переменные среды в переданной строке.
; Незакрытые "%" не проверяются.
ExpandEnv(str)
{
    res := ""
    Loop, parse, str, `%
    {
        EnvGet, env, %A_LoopField%
        If(env = "")
            res := res . A_LoopField
        Else
            res := res . env
    }
    Return, res
}

; Преобразует строку ANSI к OEM.
Ansi2Oem(sString)
{
    Ansi2Unicode(sString, wString, 0)
    Unicode2Ansi(wString, zString, 1)
    Return, zString
}

Ansi2Unicode(ByRef sString, ByRef wString, CP = 0)
{
    nSize := DllCall("MultiByteToWideChar"
        , "Uint", CP
        , "Uint", 0
        , "Uint", &sString
        , "int",  -1
        , "Uint", 0
        , "int",  0)
    VarSetCapacity(wString, nSize * 2)
    DllCall("MultiByteToWideChar"
        , "Uint", CP
        , "Uint", 0
        , "Uint", &sString
        , "int",  -1
        , "Uint", &wString
        , "int",  nSize)
}

Unicode2Ansi(ByRef wString, ByRef sString, CP = 0)
{
    nSize := DllCall("WideCharToMultiByte"
        , "Uint", CP
        , "Uint", 0
        , "Uint", &wString
        , "int",  -1
        , "Uint", 0
        , "int",  0
        , "Uint", 0
        , "Uint", 0)
    VarSetCapacity(sString, nSize)
    DllCall("WideCharToMultiByte"
        , "Uint", CP
        , "Uint", 0
        , "Uint", &wString
        , "int",  -1
        , "str",  sString
        , "int",  nSize
        , "Uint", 0
        , "Uint", 0)
}
Back to top
View user's profile Send private message Visit poster's website
wygd



Joined: 04 Nov 2007
Posts: 10

PostPosted: Sat Dec 20, 2008 4:28 pm    Post subject: Reply with quote

good job.Thanks.
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    AutoHotkey Community Forum Index -> Scripts & Functions All times are GMT
Page 1 of 1

 
Jump to:  
You can post new topics in this forum
You can reply to topics in this forum


Powered by phpBB © 2001, 2005 phpBB Group