Update RefreshDashboard.ahk

Update RefreshDashboard.ahk

; "Internet Explorer_Server14" may change
ControlFocus, Internet Explorer_Server14, IBM BigFix Console
Send ^{F5}


Activate window only if pass -a option or enable use_tmux

#NoTrayIcon
#NoEnv

; Read ini file {{{1
ini_file = %A_ScriptDir%\etc\wsl-terminal.conf
IniRead, title, %ini_file%, config, title, "        "
IniRead, shell, %ini_file%, config, shell, "bash"
IniRead, use_cbwin, %ini_file%, config, use_cbwin, 0
IniRead, use_tmux, %ini_file%, config, use_tmux, 0
IniRead, mintty_options, %ini_file%, config, mintty_options,
IniRead, icon, %ini_file%, config, icon,
IniRead, distro_guid, %ini_file%, config, distro_guid,
IniRead, keep_wsl_running, %ini_file%, config, keep_wsl_running, 0

if (mintty_options == "ERROR") {
    mintty_options =
}

; Prepare mintty_base and wslbridge_base {{{1
icon_path = %A_ScriptFullPath%
if (icon != "" && FileExist(icon)) {
    icon_path = %icon%
}

distro_option := ""
if (distro_guid != "ERROR") {
    distro_option = --distro-guid %distro_guid%
}

mintty_path = "%A_ScriptDir%\bin\mintty"
mintty_base = %mintty_path% --wsl --rootfs=// --configdir "%A_ScriptDir%\etc" -i "%icon_path%"
wslbridge_base = -e /bin/wslbridge %distro_option% -e SHELL="%shell%" -e LANG

; Run as run-wsl-file or any editor {{{1
SplitPath, A_ScriptName, , , , exe_name
if (exe_name == "run-wsl-file") {
    arg = %1%

    if (arg == "") {
        MsgBox, Open .sh/.py/.pl/... with %exe_name%.exe to run it in WSL.
        ExitApp
    }

    SplitPath, arg, filename, dir
    SetWorkingDir, %dir%

    Run, %mintty_base% %mintty_options% -t "%arg%" %wslbridge_base% -t ./"%filename%"
    ExitApp
} else if (exe_name != "open-wsl" && exe_name != "cmd") {
    argc = %0%
    filepath := ""
    filename := ""
    options := ""

    if (argc > 0) {
        filepath := %argc%

        Loop, % argc - 1 {
            options .= " " %A_Index%
        }

        SplitPath, filepath, filename, dir
        SetWorkingDir, %dir%

        if (InStr(filename, " ")) {
            filename = "%filename%"
        }
    }

    Run, %mintty_base% %mintty_options% -t "%filepath%" %wslbridge_base% -t "%exe_name%" %options% %filename%
    ExitApp
}

; Parse arguments {{{1
argc = %0%
args := []
Loop, %argc% {
    args.Insert(%A_Index%)
}

activate_window := False
change_directory := ""
distro := ""
login_shell := False
wslbridge_options := ""
user_command := ""

i := 0
while (i++ < argc) {
    c := args[i]
    if (c == "-a") {
        activate_window := True
    } else if (c == "-C") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require directory arg.
            ExitApp, 1
        }

        change_directory := args[i]
    } else if (c == "-W") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require directory arg.
            ExitApp, 1
        }

        SetWorkingDir, % args[i]
    } else if (c == "-l") {
        login_shell := True
    } else if (c == "-d") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require distro name arg.
            ExitApp, 1
        }

        distro := args[i]
    } else if (c == "-b") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require additional wslbridge options arg.
            ExitApp, 1
        }

        wslbridge_options := args[i]
    } else if (c == "-B") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require additional mintty options arg.
            ExitApp, 1
        }

        mintty_options .= " " args[i]
    } else if (c == "-c") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require command arg.
            ExitApp, 1
        }

        user_command := args[i]
    } else if (c == "-e") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require command arg.
            ExitApp, 1
        }

        user_command := shell " -c """ args[i]
        while (++i <= argc) {
            user_command .= " " args[i]
        }
        user_command .= """"
        StringReplace, user_command, user_command, `", `\`", All
    } else if (c == "-h") {
        help =
        (
        Usage: open-wsl [OPTION]...
          -a: activate an existing wsl-terminal window.
              if use_tmux=1, attach the running tmux session.
          -l: start terminal in your home directory (doesn't work with tmux).
          -c "command": run command (e.g. -c "echo a b; echo c; cat").
          -e commands: run commands (e.g. -e echo a b; echo c; cat).
          -C dir: change directory to a WSL dir (e.g. /home/username).
          -W dir: change directory to a Windows dir (e.g. c:\Users\username).
          -d distro: switch distros.
          -b "options": pass additional options to wslbridge.
          -B "options": pass additional options to mintty.
          -h: show help.
        )
        MsgBox, %help%
        ExitApp
    }
}

if (user_command != "") {
    if (change_directory != "") {
        wslbridge_options = %wslbridge_options% -C "%change_directory%"
    }

    Run, %mintty_base% %mintty_options% -t "%user_command%" %wslbridge_base% %wslbridge_options% -t %shell% -c "%user_command%"
    ExitApp
}

; Find bash.exe {{{1
bash_exe = %A_WinDir%\sysnative\bash.exe
if (!FileExist(bash_exe)) {
    bash_exe = %A_WinDir%\system32\bash.exe
} if (!FileExist(bash_exe)) {
    MsgBox, 0x10, , WSL(Windows Subsystem for Linux) must be installed.
    ExitApp, 1
}

; Switch distro {{{1
if (distro != "") {
    Run, % StrReplace(bash_exe, "bash.exe", "wslconfig.exe") " /s " distro
}

; Build command line {{{1
cmd =
opts = %wslbridge_options% -t

if (activate_window && WinExist(title)) {
} else if (!use_tmux) {
    if (login_shell) {
        cmd = %shell% -l
        if (change_directory == "") {
            change_directory = ~
        }
    } else {
        cmd = %shell%
    }
} else {
    if (WinExist(title)) {
        Run, "%bash_exe%" -c 'tmux new-window -c "$PWD"', , Hide
    } else {
        cmd = %shell%
        opts = %opts% -e USE_TMUX=1

        if (activate_window) {
            opts = %opts% -e ATTACH_ONLY=1
        }
    }
}

if (change_directory != "") {
    opts = %opts% -C "%change_directory%"
}

if (cmd != "") {
    lnk_args = %mintty_base% %mintty_options% -t "%title%" %wslbridge_base% %opts% %cmd%
    lnk_args := StrReplace(lnk_args, mintty_path)

    FileCreateShortcut, %A_ScriptDir%\bin\mintty.exe, %A_ScriptDir%\wsl-terminal.lnk, %A_WorkingDir%, %lnk_args%, wsl-terminal temp shortcut, %icon_path%
    Run, %A_ScriptDir%\wsl-terminal.lnk

    ;Run, %mintty_base% %mintty_options% -t "%title%" %wslbridge_base% %opts% %cmd%
}

; Activate window {{{1

if (activate_window || use_tmux) {
    Loop, 5 {
        WinActivate, %title%
        if (WinActive(title)) {
            break
        }

        Sleep, 50
    }
}

if (keep_wsl_running) {
    Process, Exist, sleep

    if (ErrorLevel == 0) {
        Run, "%bash_exe%" -c 'exec sleep 10000000d', , Hide
    }
}

#NoTrayIcon
#NoEnv

; Read ini file {{{1
ini_file = %A_ScriptDir%\etc\wsl-terminal.conf
IniRead, title, %ini_file%, config, title, "        "
IniRead, shell, %ini_file%, config, shell, "bash"
IniRead, use_cbwin, %ini_file%, config, use_cbwin, 0
IniRead, use_tmux, %ini_file%, config, use_tmux, 0
IniRead, mintty_options, %ini_file%, config, mintty_options,
IniRead, icon, %ini_file%, config, icon,
IniRead, distro_guid, %ini_file%, config, distro_guid,
IniRead, keep_wsl_running, %ini_file%, config, keep_wsl_running, 0

if (mintty_options == "ERROR") {
    mintty_options =
}

; Prepare mintty_base and wslbridge_base {{{1
icon_path = %A_ScriptFullPath%
if (icon != "" && FileExist(icon)) {
    icon_path = %icon%
}

distro_option := ""
if (distro_guid != "ERROR") {
    distro_option = --distro-guid %distro_guid%
}

mintty_path = "%A_ScriptDir%\bin\mintty"
mintty_base = %mintty_path% --wsl --rootfs=// --configdir "%A_ScriptDir%\etc" -i "%icon_path%"
wslbridge_base = -e /bin/wslbridge %distro_option% -e SHELL="%shell%" -e LANG

; Run as run-wsl-file or any editor {{{1
SplitPath, A_ScriptName, , , , exe_name
if (exe_name == "run-wsl-file") {
    arg = %1%

    if (arg == "") {
        MsgBox, Open .sh/.py/.pl/... with %exe_name%.exe to run it in WSL.
        ExitApp
    }

    SplitPath, arg, filename, dir
    SetWorkingDir, %dir%

    Run, %mintty_base% %mintty_options% -t "%arg%" %wslbridge_base% -t ./"%filename%"
    ExitApp
} else if (exe_name != "open-wsl" && exe_name != "cmd") {
    argc = %0%
    filepath := ""
    filename := ""
    options := ""

    if (argc > 0) {
        filepath := %argc%

        Loop, % argc - 1 {
            options .= " " %A_Index%
        }

        SplitPath, filepath, filename, dir
        SetWorkingDir, %dir%

        if (InStr(filename, " ")) {
            filename = "%filename%"
        }
    }

    Run, %mintty_base% %mintty_options% -t "%filepath%" %wslbridge_base% -t "%exe_name%" %options% %filename%
    ExitApp
}

; Parse arguments {{{1
argc = %0%
args := []
Loop, %argc% {
    args.Insert(%A_Index%)
}

activate_window := False
change_directory := ""
distro := ""
login_shell := False
wslbridge_options := ""
user_command := ""

i := 0
while (i++ < argc) {
    c := args[i]
    if (c == "-a") {
        activate_window := True
    } else if (c == "-C") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require directory arg.
            ExitApp, 1
        }

        change_directory := args[i]
    } else if (c == "-W") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require directory arg.
            ExitApp, 1
        }

        SetWorkingDir, % args[i]
    } else if (c == "-l") {
        login_shell := True
    } else if (c == "-d") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require distro name arg.
            ExitApp, 1
        }

        distro := args[i]
    } else if (c == "-b") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require additional wslbridge options arg.
            ExitApp, 1
        }

        wslbridge_options := args[i]
    } else if (c == "-B") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require additional mintty options arg.
            ExitApp, 1
        }

        mintty_options .= " " args[i]
    } else if (c == "-c") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require command arg.
            ExitApp, 1
        }

        user_command := args[i]
    } else if (c == "-e") {
        if (argc < ++i) {
            MsgBox, 0x10, , Require command arg.
            ExitApp, 1
        }

        user_command := shell " -c """ args[i]
        while (++i <= argc) {
            user_command .= " " args[i]
        }
        user_command .= """"
        StringReplace, user_command, user_command, `", `\`", All
    } else if (c == "-h") {
        help =
        (
        Usage: open-wsl [OPTION]...
          -a: activate an existing wsl-terminal window.
              if use_tmux=1, attach the running tmux session.
          -l: start terminal in your home directory (doesn't work with tmux).
          -c "command": run command (e.g. -c "echo a b; echo c; cat").
          -e commands: run commands (e.g. -e echo a b; echo c; cat).
          -C dir: change directory to a WSL dir (e.g. /home/username).
          -W dir: change directory to a Windows dir (e.g. c:\Users\username).
          -d distro: switch distros.
          -b "options": pass additional options to wslbridge.
          -B "options": pass additional options to mintty.
          -h: show help.
        )
        MsgBox, %help%
        ExitApp
    }
}

if (user_command != "") {
    if (change_directory != "") {
        wslbridge_options = %wslbridge_options% -C "%change_directory%"
    }

    Run, %mintty_base% %mintty_options% -t "%user_command%" %wslbridge_base% %wslbridge_options% -t %shell% -c "%user_command%"
    ExitApp
}

; Find bash.exe {{{1
bash_exe = %A_WinDir%\sysnative\bash.exe
if (!FileExist(bash_exe)) {
    bash_exe = %A_WinDir%\system32\bash.exe
} if (!FileExist(bash_exe)) {
    MsgBox, 0x10, , WSL(Windows Subsystem for Linux) must be installed.
    ExitApp, 1
}

; Switch distro {{{1
if (distro != "") {
    Run, % StrReplace(bash_exe, "bash.exe", "wslconfig.exe") " /s " distro
}

; Build command line {{{1
cmd =
opts = %wslbridge_options% -t

if (activate_window && WinExist(title)) {
} else if (!use_tmux) {
    if (login_shell) {
        cmd = %shell% -l
        if (change_directory == "") {
            change_directory = ~
        }
    } else {
        cmd = %shell%
    }
} else {
    if (WinExist(title)) {
        Run, "%bash_exe%" -c 'tmux new-window -c "$PWD"', , Hide
    } else {
        cmd = %shell%
        opts = %opts% -e USE_TMUX=1

        if (activate_window) {
            opts = %opts% -e ATTACH_ONLY=1
        }
    }
}

if (change_directory != "") {
    opts = %opts% -C "%change_directory%"
}

if (cmd != "") {
    lnk_args = %mintty_base% %mintty_options% -t "%title%" %wslbridge_base% %opts% %cmd%
    lnk_args := StrReplace(lnk_args, mintty_path)

    FileCreateShortcut, %A_ScriptDir%\bin\mintty.exe, %A_ScriptDir%\wsl-terminal.lnk, %A_WorkingDir%, %lnk_args%, wsl-terminal temp shortcut, %icon_path%
    Run, %A_ScriptDir%\wsl-terminal.lnk

    ;Run, %mintty_base% %mintty_options% -t "%title%" %wslbridge_base% %opts% %cmd%
}

; Activate window {{{1
Loop, 5 {
    WinActivate, %title%
    if (WinActive(title)) {
        break
    }

    Sleep, 50
}

if (keep_wsl_running) {
    Process, Exist, sleep

    if (ErrorLevel == 0) {
        Run, "%bash_exe%" -c 'exec sleep 10000000d', , Hide
    }
}


shift+space 한영전환 추가

shift+space 한영전환 추가

/*
  @Author : johngrib82@gmail.com
  @Created : 2015. NOV. 19
*/

/*
  Korean/English switch
*/
CapsLock & Space::Send, {VK15}
CapsLock & t::WinSet, AlwaysOnTop, Toggle, A

#If WinExist("avl_insert") or  WinExist("avl_capslock")
  ~+SC027::
    if(IME_CHECK("A"))
      Send, {VK15}    ; input Korean/English switch key
  return
#if

#If not WinActive("ahk_class XLMAIN")
  +Space:: Send, {VK15}    ; input Korean/English switch key
#IF

/*
  ^c -> push to clipboard register
*/
~^c::
  Sleep 500
  new_value := Clipboard
  CLIP.num_unshift(new_value)
return

/*
  use ^v on ms cmd.com console.
*/
#IfWinActive ahk_class ConsoleWindowClass
	^V::
		SendInput {Raw}%clipboard%
	return
#IfWinActive

/*
  IME check (MS Windows Korean character input mode check)
*/
IME_CHECK(WinTitle) {
  WinGet,hWnd,ID,%WinTitle%
  Return Send_ImeControl(ImmGetDefaultIMEWnd(hWnd),0x005,"")
}
Send_ImeControl(DefaultIMEWnd, wParam, lParam) {
  DetectSave := A_DetectHiddenWindows
  DetectHiddenWindows,ON
   SendMessage 0x283, wParam,lParam,,ahk_id %DefaultIMEWnd%
  if (DetectSave <> A_DetectHiddenWindows)
      DetectHiddenWindows,%DetectSave%
  return ErrorLevel
}
ImmGetDefaultIMEWnd(hWnd) {
  return DllCall("imm32\ImmGetDefaultIMEWnd", Uint,hWnd, Uint)
}

/*
  @Author : johngrib82@gmail.com
  @Created : 2015. NOV. 19
*/

/*
  Korean/English switch
*/
CapsLock & Space::Send, {VK15}
CapsLock & t::WinSet, AlwaysOnTop, Toggle, A

#If WinExist("avl_insert") or  WinExist("avl_capslock")
  ~+SC027::
    if(IME_CHECK("A"))
      Send, {VK15}    ; input Korean/English switch key
  return
#if

/*
  ^c -> push to clipboard register
*/
~^c::
  Sleep 500
  new_value := Clipboard
  CLIP.num_unshift(new_value)
return

/*
  use ^v on ms cmd.com console.
*/
#IfWinActive ahk_class ConsoleWindowClass
	^V::
		SendInput {Raw}%clipboard%
	return
#IfWinActive

/*
  IME check (MS Windows Korean character input mode check)
*/
IME_CHECK(WinTitle) {
  WinGet,hWnd,ID,%WinTitle%
  Return Send_ImeControl(ImmGetDefaultIMEWnd(hWnd),0x005,"")
}
Send_ImeControl(DefaultIMEWnd, wParam, lParam) {
  DetectSave := A_DetectHiddenWindows
  DetectHiddenWindows,ON
   SendMessage 0x283, wParam,lParam,,ahk_id %DefaultIMEWnd%
  if (DetectSave <> A_DetectHiddenWindows)
      DetectHiddenWindows,%DetectSave%
  return ErrorLevel
}
ImmGetDefaultIMEWnd(hWnd) {
  return DllCall("imm32\ImmGetDefaultIMEWnd", Uint,hWnd, Uint)
}


change address of fileserver

change address of fileserver

#NoEnv
#Persistent
if FileExist("C:/Users/Chris") != ""
{
    Home = 1
    WordProcessor = C:\Program Files (x86)\LibreOffice 4\program\swriter.exe
    Spreadsheet = C:\Program Files (x86)\LibreOffice 4\program\scalc.exe
    VisualStudio = C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe
    VisualStudioProjects = Explorer C:\Users\chris\Documents\Visual Studio 2012\Projects
    GoogleEarth = C:\Program Files (x86)\Google\Google Earth\client\googleearth.exe
}
if FileExist("C:/Users/cwatrous") != ""
{
    Work = 1
    WordProcessor = C:\Program Files (x86)\Microsoft Office\Office15\WINWORD.EXE
    Spreadsheet = C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE
}
Return

^Capslock::Capslock
Capslock::LCtrl

!#a::Run "C:\Program Files (x86)\Vim\vim74\gvim.exe" %A_MyDocuments%/AutoHotkey.ahk
^#a::Run AutoHotkey

#a::Run %VisualStudioProjects%
#c::Run Chrome
#g::Run %GoogleEarth%
#h::Run C:\cygwin64\bin\mintty.exe -w max -i /Cygwin-Terminal.ico -
#+h::Run %A_MyDocuments%/../Program Files/Cygwin-setup-x86_64.exe
#j::RemoteLogin1()
#+j::RemoteLogin2()
#^j::RemoteLogin3()
#n::Run Notepad
#o::StartOctave()
#q::Run Explorer %A_MyDocuments%
#s::Run acrord32
#v::Run %VisualStudio%
#w::Run %WordProcessor%
#x::Run %Spreadsheet%
#y::Run powershell
#+y::Run "C:\Program Files (x86)\Vim\vim74\gvim.exe" C:\Users\Chris\Documents\WindowsPowerShell\profile.ps1
#z::Run Firefox
#]::WinMinimize A

+Space::_

; Unused Keys Win+Key combinations
;#Escape
;#k
;#`
;#,
;#i
;#.
;#;
;#/
;#[
;#'
;#]
;#\
;#Backspace
;#Enter
;#Insert
;#Delete
;#Home
;#End
;#PageDown
;#PageUp

; Don't use these key combinations
;#e opens explorer
;#d shows desktop
;#r opens run dialog
;#f opens windows search
;#t focuses task bar
;#b focuses notification area
;#u opens ease of use control panel
;#m opens start menu along with program
;#l locks workstation when regular windows key is used
;#p opens some kind of screen management menu
;win + top row numberkeys, selects programs from the task bar
;#- windows magnifier zoom out
;#= windows magnifier zoom in
;#Space
;win + arrow keys, manipulates windows

#Numpad0::PlaceActiveWindow(0, 0, 1, 1)

#Numpad1::PlacePattern1()
PlacePattern1()
{
    global LastPattern
    global Spot
    if (LastPattern != 1)
        Spot := -1
    LastPattern := 1
    Spot := mod(Spot + 1, 2)
    if (Spot == 0)
        PlaceActiveWindow(0, 0, 1, 1/2)
    if (Spot == 1)
        PlaceActiveWindow(0, 1/2, 1, 1/2)
}

#Numpad2::PlacePattern2()
PlacePattern2()
{
    global LastPattern
    global Spot
    if (LastPattern != 2)
        Spot := -1
    LastPattern := 2
    Spot := mod(Spot + 1, 2)
    if (Spot == 0)
        PlaceActiveWindow(0, 0, 1/2, 1)
    if (Spot == 1)
        PlaceActiveWindow(1/2, 0, 1/2, 1)
}

#Numpad3::PlacePattern3()
PlacePattern3()
{
    global LastPattern
    global Spot
    if (LastPattern != 3)
        Spot := -1
    LastPattern := 3
    Spot := mod(Spot + 1, 4)
    if (Spot == 0)
        PlaceActiveWindow(0, 0, 1/2, 1/2)
    if (Spot == 1)
        PlaceActiveWindow(1/2, 0, 1/2, 1/2)
    if (Spot == 2)
        PlaceActiveWindow(0, 1/2, 1/2, 1/2)
    if (Spot == 3)
        PlaceActiveWindow(1/2, 1/2, 1/2, 1/2)
}

#Numpad4::PlacePattern4()
PlacePattern4()
{
    global LastPattern
    global Spot
    if (LastPattern != 4)
        Spot := -1
    LastPattern := 4
    Spot := mod(Spot + 1, 2)
    if (Spot == 0)
        PlaceActiveWindow(0, 0, 1, 2/3)
    if (Spot == 1)
        PlaceActiveWindow(0, 2/3, 1, 1/3)
}

#Numpad5::PlacePattern5()
PlacePattern5()
{
    global LastPattern
    global Spot
    if (LastPattern != 5)
        Spot := -1
    LastPattern := 5
    Spot := mod(Spot + 1, 2)
    if (Spot == 0)
        PlaceActiveWindow(0, 0, 1, 3/4)
    if (Spot == 1)
        PlaceActiveWindow(0, 3/4, 1, 1/4)
}

#`::ToggleWindowBorder()
#\::ToggleWindowBorder()
ToggleWindowBorder()
{
    SetWinDelay 10
    WinGet state, MinMax, A
    if (state == 1)
        PlaceActiveWindow(0, 0, 1, 1)
    WinSet Style, ^0x840000, A
    WinGetPos X, Y, Width, Height, A
    WinMove A, , X, Y, Width, Height + 1
    WinMove A, , X, Y, Width, Height
}

;#^f::ToggleFocusFollow()
;FocusFollow = 0
;ToggleFocusFollow()
;{
;    global FocusFollow
;    FocusFollow := !FocusFollow
;    SetFocusFollow(FocusFollow)
;}
;SetFocusFollow(enabled)
;{
;    SPI_SETACTIVEWINDOWTRACKING = 0x1001
;    SPIF_UPDATEINIFILE = 1
;    SPIF_SENDCHANGE = 2
;    DllCall("SystemParametersInfo",UInt,SPI_SETACTIVEWINDOWTRACKING,UInt,0,UInt,enabled,UInt,SPIF_UPDATEINIFILE | SPIF_SENDCHANGE)
;}

RemoteLogin1()
{
    global Home, Work
    if Home
    {
        Run C:\cygwin64\bin\mintty.exe -w max -i /Cygwin-Terminal.ico /usr/bin/ssh chris@192.168.1.101
    }
    if Work
    {
        WorkLogin("t14hstbuild01")
    }
}

RemoteLogin2()
{
    global Work
    if Work
    {
        WorkLogin("t14hstbuild04")
    }
}

RemoteLogin3()
{
    global Work
    if Work
    {
        WorkLogin("peologin06")
    }
}

WorkLogin(server)
{
    SetWinDelay 10
    Run C:\cygwin64\bin\mintty.exe -w max -i /Cygwin-Terminal.ico --title mintty /usr/bin/ssh cwatrous@%server%
    WinWait mintty
    SendInput . .bashrc{Enter}
}

StartOctave()
{
    Run C:\cygwin64\bin\mintty.exe --title mintty -w max -i /Cygwin-Terminal.ico -
    WinWait mintty
    SendInput octave -q{Enter}
}

#NoEnv
#Persistent
if FileExist("C:/Users/Chris") != ""
{
    Home = 1
    WordProcessor = C:\Program Files (x86)\LibreOffice 4\program\swriter.exe
    Spreadsheet = C:\Program Files (x86)\LibreOffice 4\program\scalc.exe
    VisualStudio = C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe
    VisualStudioProjects = Explorer C:\Users\chris\Documents\Visual Studio 2012\Projects
    GoogleEarth = C:\Program Files (x86)\Google\Google Earth\client\googleearth.exe
}
if FileExist("C:/Users/cwatrous") != ""
{
    Work = 1
    WordProcessor = C:\Program Files (x86)\Microsoft Office\Office15\WINWORD.EXE
    Spreadsheet = C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE
}
Return

^Capslock::Capslock
Capslock::LCtrl

!#a::Run "C:\Program Files (x86)\Vim\vim74\gvim.exe" %A_MyDocuments%/AutoHotkey.ahk
^#a::Run AutoHotkey

#a::Run %VisualStudioProjects%
#c::Run Chrome
#g::Run %GoogleEarth%
#h::Run C:\cygwin64\bin\mintty.exe -w max -i /Cygwin-Terminal.ico -
#+h::Run %A_MyDocuments%/../Program Files/Cygwin-setup-x86_64.exe
#j::RemoteLogin1()
#+j::RemoteLogin2()
#^j::RemoteLogin3()
#n::Run Notepad
#o::StartOctave()
#q::Run Explorer %A_MyDocuments%
#s::Run acrord32
#v::Run %VisualStudio%
#w::Run %WordProcessor%
#x::Run %Spreadsheet%
#y::Run powershell
#+y::Run "C:\Program Files (x86)\Vim\vim74\gvim.exe" C:\Users\Chris\Documents\WindowsPowerShell\profile.ps1
#z::Run Firefox
#]::WinMinimize A

+Space::_

; Unused Keys Win+Key combinations
;#Escape
;#k
;#`
;#,
;#i
;#.
;#;
;#/
;#[
;#'
;#]
;#\
;#Backspace
;#Enter
;#Insert
;#Delete
;#Home
;#End
;#PageDown
;#PageUp

; Don't use these key combinations
;#e opens explorer
;#d shows desktop
;#r opens run dialog
;#f opens windows search
;#t focuses task bar
;#b focuses notification area
;#u opens ease of use control panel
;#m opens start menu along with program
;#l locks workstation when regular windows key is used
;#p opens some kind of screen management menu
;win + top row numberkeys, selects programs from the task bar
;#- windows magnifier zoom out
;#= windows magnifier zoom in
;#Space
;win + arrow keys, manipulates windows

#Numpad0::PlaceActiveWindow(0, 0, 1, 1)

#Numpad1::PlacePattern1()
PlacePattern1()
{
    global LastPattern
    global Spot
    if (LastPattern != 1)
        Spot := -1
    LastPattern := 1
    Spot := mod(Spot + 1, 2)
    if (Spot == 0)
        PlaceActiveWindow(0, 0, 1, 1/2)
    if (Spot == 1)
        PlaceActiveWindow(0, 1/2, 1, 1/2)
}

#Numpad2::PlacePattern2()
PlacePattern2()
{
    global LastPattern
    global Spot
    if (LastPattern != 2)
        Spot := -1
    LastPattern := 2
    Spot := mod(Spot + 1, 2)
    if (Spot == 0)
        PlaceActiveWindow(0, 0, 1/2, 1)
    if (Spot == 1)
        PlaceActiveWindow(1/2, 0, 1/2, 1)
}

#Numpad3::PlacePattern3()
PlacePattern3()
{
    global LastPattern
    global Spot
    if (LastPattern != 3)
        Spot := -1
    LastPattern := 3
    Spot := mod(Spot + 1, 4)
    if (Spot == 0)
        PlaceActiveWindow(0, 0, 1/2, 1/2)
    if (Spot == 1)
        PlaceActiveWindow(1/2, 0, 1/2, 1/2)
    if (Spot == 2)
        PlaceActiveWindow(0, 1/2, 1/2, 1/2)
    if (Spot == 3)
        PlaceActiveWindow(1/2, 1/2, 1/2, 1/2)
}

#Numpad4::PlacePattern4()
PlacePattern4()
{
    global LastPattern
    global Spot
    if (LastPattern != 4)
        Spot := -1
    LastPattern := 4
    Spot := mod(Spot + 1, 2)
    if (Spot == 0)
        PlaceActiveWindow(0, 0, 1, 2/3)
    if (Spot == 1)
        PlaceActiveWindow(0, 2/3, 1, 1/3)
}

#Numpad5::PlacePattern5()
PlacePattern5()
{
    global LastPattern
    global Spot
    if (LastPattern != 5)
        Spot := -1
    LastPattern := 5
    Spot := mod(Spot + 1, 2)
    if (Spot == 0)
        PlaceActiveWindow(0, 0, 1, 3/4)
    if (Spot == 1)
        PlaceActiveWindow(0, 3/4, 1, 1/4)
}

#`::ToggleWindowBorder()
#\::ToggleWindowBorder()
ToggleWindowBorder()
{
    SetWinDelay 10
    WinGet state, MinMax, A
    if (state == 1)
        PlaceActiveWindow(0, 0, 1, 1)
    WinSet Style, ^0x840000, A
    WinGetPos X, Y, Width, Height, A
    WinMove A, , X, Y, Width, Height + 1
    WinMove A, , X, Y, Width, Height
}

;#^f::ToggleFocusFollow()
;FocusFollow = 0
;ToggleFocusFollow()
;{
;    global FocusFollow
;    FocusFollow := !FocusFollow
;    SetFocusFollow(FocusFollow)
;}
;SetFocusFollow(enabled)
;{
;    SPI_SETACTIVEWINDOWTRACKING = 0x1001
;    SPIF_UPDATEINIFILE = 1
;    SPIF_SENDCHANGE = 2
;    DllCall("SystemParametersInfo",UInt,SPI_SETACTIVEWINDOWTRACKING,UInt,0,UInt,enabled,UInt,SPIF_UPDATEINIFILE | SPIF_SENDCHANGE)
;}

RemoteLogin1()
{
    global Home, Work
    if Home
    {
        Run C:\cygwin64\bin\mintty.exe -w max -i /Cygwin-Terminal.ico /usr/bin/ssh chris@192.168.0.98
    }
    if Work
    {
        WorkLogin("t14hstbuild01")
    }
}

RemoteLogin2()
{
    global Work
    if Work
    {
        WorkLogin("t14hstbuild04")
    }
}

RemoteLogin3()
{
    global Work
    if Work
    {
        WorkLogin("peologin06")
    }
}

WorkLogin(server)
{
    SetWinDelay 10
    Run C:\cygwin64\bin\mintty.exe -w max -i /Cygwin-Terminal.ico --title mintty /usr/bin/ssh cwatrous@%server%
    WinWait mintty
    SendInput . .bashrc{Enter}
}

StartOctave()
{
    Run C:\cygwin64\bin\mintty.exe --title mintty -w max -i /Cygwin-Terminal.ico -
    WinWait mintty
    SendInput octave -q{Enter}
}


Add SendToClip function

Add SendToClip function

global Arg

Functions:
    @("Help", "帮助信息")
    @("KeyHelp", "置顶的按键帮助信息")
    @("AhkRun", "使用 Ahk 的 Run() 运行 `; command", true)
    @("CmdRun", "使用 cmd 运行 : command", true)
    @("CmdRunOnly", "只使用 cmd 运行")
    @("WinRRun", "使用 win + r 运行", true)
    @("Dictionary", "有道词典在线翻译", true)
    @("RunAndDisplay", "使用 cmd 运行，并显示结果", true)
    @("ReindexFiles", "重新索引待搜索文件")
    @("Clip", "显示剪切板内容")
    @("Calc", "计算器")
    @("SearchOnBaidu", "使用 Baidu（百度）搜索剪切板或输入内容", true)
    @("SearchOnGoogle", "使用 Google（谷歌）搜索剪切板或输入内容", true)
    @("SearchOnBing", "使用 Bing（必应）搜索剪切板或输入内容", true)
    @("SearchOnTaobao", "使用 Taobao（淘宝）搜索剪切板或输入内容")
    @("SearchOnJingdong", "使用 JD（京东）搜索剪切板或输入内容")
    @("EditConfig", "编辑配置文件")
    @("ClearClipboardFormat", "清除剪切板中文字的格式")
    @("RunClipboard", "使用 ahk 的 Run 运行剪切板内容")
    @("EmptyRecycle", "清空回收站")
    @("Logoff", "注销 登出")
    @("RestartMachine", "重启")
    @("ShutdownMachine", "关机")
    @("SuspendMachine", "挂起 睡眠 待机")
    @("HibernateMachine", "休眠")
    @("TurnMonitorOff", "关闭显示器")
    @("T2S", "将剪切板或输入内容中的繁体转成简体")
    @("S2T", "将剪切板或输入内容中的简体转成繁体")
    @("ShowIp", "显示 IP")
    @("Calendar", "用浏览器打开万年历")
    @("CleanupRank", "清理命令权重中的无效命令")
    @("CurrencyRate", "汇率 使用示例： hl JPY EUR 2")
    @("CNY2USD", "汇率 人民币兑换美元")
    @("USD2CNY", "汇率 美元兑换人民币")
    @("ProcessList", "进程列表")
    @("UrlEncode", "URL 编码")
    @("DiskSpace", "查看磁盘空间 df")
    @("ArgTest", "参数测试：ArgTest arg1,arg2,...")
    @("AhkTest", "运行参数或者剪切板中的 AHK 代码")
    @("IncreaseVolume", "提高音量")
    @("DecreaseVolume", "降低音量")
    @("SystemState", "系统状态 top")
    @("KillProcess", "杀死进程")
    @("SendToClip", "发送到剪切板")

    if (IsLabel("ReservedFunctions"))
    {
        GoSub, ReservedFunctions
    }
return

Help:
    DisplayResult(KeyHelpText() . GetAllFunctions())
return

KeyHelp:
    ToolTip, % KeyHelpText()
    SetTimer, RemoveToolTip, 5000
return

CmdRun:
    RunWithCmd(Arg)
return

CmdRunOnly:
    RunWithCmd(Arg, true)
return

AhkRun:
    Run, %Arg%
return

Clip:
    DisplayResult("剪切板内容长度 " . StrLen(clipboard) . " ：`n`n" . clipboard)
return

CNY2USD:
    DisplayResult("查询中，可能会比较慢或者查询失败，请稍后...")
    DisplayResult(QueryCurrencyRate("CNY", "USD", Arg))
return

USD2CNY:
    DisplayResult("查询中，可能会比较慢或者查询失败，请稍后...")
    DisplayResult(QueryCurrencyRate("USD", "CNY", Arg))
return

CurrencyRate:
    args := StrSplit(Arg, " ")
    if (args.Length() != 3)
    {
        DisplayResult("使用示例：`n    CurrencyRate USD CNY 2")
        return
    }

    DisplayResult("查询中，可能会比较慢或者查询失败，请稍后...")
    DisplayResult(QueryCurrencyRate(args[1], args[2], args[3]))
return

QueryCurrencyRate(fromCurrency, toCurrency, amount)
{
    headers := Object()
    headers["apikey"] := "c9098c96599be340bbd9551e2b061f63"

    jsonText := UrlDownloadToString("http://apis.baidu.com/apistore/currencyservice/currency?"
        . "fromCurrency=" fromCurrency "&toCurrency=" toCurrency "&amount=" amount, headers)
    parsed := JSON.Load(jsonText)

    if (parsed.errNum != 0 && parsed.errMsg != "success")
    {
        return "查询失败，错误信息：`n`n" jsonText
    }

    result := fromCurrency " 兑换 " toCurrency " 当前汇率：`n`n" parsed.retData.currency "`n`n`n"
    result .= amount " " fromCurrency " = " parsed.retData.convertedamount " " toCurrency "`n"

    return result
}

ArgTest:
    args := StrSplit(Arg, ",")
    result := "共有 " . args.Length() . " 个参数。`n`n"

    for index, argument in args
    {
        result .= "第 " . index . " 个参数：" . argument . "`n"
    }

    DisplayResult(result)
return

ShowIp:
    DisplayResult(A_IPAddress1
            . "`r`n" . A_IPAddress2
            . "`r`n" . A_IPAddress3
            . "`r`n" . A_IPAddress4)
return

Dictionary:
    word := Arg == "" ? clipboard : Arg

    url := "http://fanyi.youdao.com/openapi.do?keyfrom=YouDaoCV&key=659600698&"
            . "type=data&doctype=json&version=1.2&q=" UrlEncode(word)

    jsonText := StrReplace(UrlDownloadToString(url), "-phonetic", "_phonetic")

    if (jsonText == "no query")
    {
        DisplayResult("未查到结果")
        return
    }

    parsed := JSON.Load(jsonText)
    result := parsed.query

    if (parsed.basic.uk_phonetic != "" && parsed.basic.us_phonetic != "")
    {
        result .= " UK: [" parsed.basic.uk_phonetic "], US: [" parsed.basic.us_phonetic "]`n"
    }
    else if (parsed.basic.phonetic != "")
    {
        result .= " [" parsed.basic.phonetic "]`n"
    }
    else
    {
        result .= "`n"
    }

    if (parsed.basic.explains.Length() > 0)
    {
        result .= "`n"
        for index, explain in parsed.basic.explains
        {
            result .= "    * " explain "`n"
        }
    }

    if (parsed.web.Length() > 0)
    {
        result .= "`n----`n"

        for i, element in parsed.web
        {
            result .= "`n    * " element.key
            for j, value in element.value
            {
                if (j == 1)
                {
                    result .= "`n       "
                }
                else
                {
                    result .= "`; "
                }

                result .= value
            }
        }
    }

    DisplayResult(result)
    clipboard := result
return

Calendar:
    Run % "http://www.baidu.com/baidu?wd=%CD%F2%C4%EA%C0%FA"
return

T2S:
    text := Arg == "" ? clipboard : Arg
    clipboard := ""
    clipboard := Kanji_t2s(text)
    ClipWait
    DisplayResult(clipboard)
return

S2T:
    text := Arg == "" ? clipboard : Arg
    clipboard := ""
    clipboard := Kanji_s2t(text)
    ClipWait
    DisplayResult(clipboard)
return

ClearClipboardFormat:
    clipboard := clipboard
return

SearchOnBaidu:
    word := Arg == "" ? clipboard : Arg

    Run, https://www.baidu.com/s?wd=%word%
return

SearchOnGoogle:
    word := UrlEncode(Arg == "" ? clipboard : Arg)

    Run, https://www.google.com.hk/#newwindow=1&safe=strict&q=%word%
return

SearchOnBing:
    word := Arg == "" ? clipboard : Arg

    Run, http://cn.bing.com/search?q=%word%
return

SearchOnTaobao:
    word := Arg == "" ? clipboard : Arg

    Run, https://s.taobao.com/search?q=%word%
return

SearchOnJingdong:
    word := Arg == "" ? clipboard : Arg

    Run, http://search.jd.com/Search?keyword=%word%&enc=utf-8
return

RunClipboard:
    Run, %clipboard%
return

Calc:
    result := Eval(Arg)
    DisplayResult(result)
    clipboard := result
    TurnOnRealtimeExec()
return

RunAndDisplay:
    DisplayResult(RunAndGetOutput(Arg))
return

WinRRun:
    Send, #r
    Sleep, 100
    Send, %Arg%
    Send, {enter}
return

Logoff:
    MsgBox, 4, , 将要注销，是否执行？
    {
        Shutdown, 0
    }
return

ShutdownMachine:
    MsgBox, 4, , 将要关机，是否执行？
    IfMsgBox Yes
    {
        Shutdown, 1
    }
return

RestartMachine:
    MsgBox, 4, , 将要重启机器，是否执行？
    IfMsgBox Yes
    {
        Shutdown, 2
    }
return

HibernateMachine:
    MsgBox, 4, , 将要休眠，是否执行？
    IfMsgBox Yes
    {
        ; 参数 #1: 使用 1 代替 0 来进行休眠而不是挂起。
        ; 参数 #2: 使用 1 代替 0 来立即挂起而不询问每个应用程序以获得许可。
        ; 参数 #3: 使用 1 而不是 0 来禁止所有的唤醒事件。
        DllCall("PowrProf\SetSuspendState", "int", 1, "int", 0, "int", 0)
    }
return

SuspendMachine:
    MsgBox, 4, , 将要待机，是否执行？
    IfMsgBox Yes
    {
        DllCall("PowrProf\SetSuspendState", "int", 0, "int", 0, "int", 0)
    }
return

TurnMonitorOff:
    ; 关闭显示器:
    SendMessage, 0x112, 0xF170, 2,, Program Manager
    ; 0x112 is WM_SYSCOMMAND, 0xF170 is SC_MONITORPOWER.
    ; 对上面命令的注释: 使用 -1 代替 2 来打开显示器.
    ; 使用 1 代替 2 来激活显示器的节能模式.
return

EmptyRecycle:
    MsgBox, 4, , 将要清空回收站，是否执行？
    IfMsgBox Yes
    {
        FileRecycleEmpty,
    }
return

ProcessList:
    result := ""

    for process in ComObjGet("winmgmts:").ExecQuery("Select * from Win32_Process")
        result .= "* | 进程 | " process.Name " | " process.CommandLine "`n"
    Sort, result

    DisplayResult(FilterResult(AlignText(result), Arg))
    TurnOnResultFilter()
return

UrlEncode:
    text := Arg == "" ? clipboard : Arg
    clipboard := UrlEncode(text)
    DisplayResult(clipboard)
return

DiskSpace:
    result := ""

    DriveGet, list, list
    Loop, Parse, list
    {
        drive := A_LoopField ":"
        DriveGet, label, label, %drive%
        DriveGet, cap, capacity, %drive%
        DrivespaceFree, free, %drive%
        SetFormat, float, 5.2
        percent := 100 * (cap - free) / cap
        SetFormat, float, 6.2
        cap /= 1024.0
        free /= 1024.0
        result = %result%* | %drive% | 总共: %cap% G  可用: %free% G | 已使用：%percent%`%  卷标: %label%`n
    }

	DisplayResult(AlignText(result))
return

AhkTest:
    text := Arg == "" ? clipboard : Arg
    FileDelete, %A_Temp%\RunZ.AhkTest.ahk
    FileAppend, %text%, %A_Temp%\RunZ.AhkTest.ahk
    Run, %A_Temp%\RunZ.AhkTest.ahk
return

IncreaseVolume:
    SoundSet, +5
return

DecreaseVolume:
    SoundSet, -5
return

SystemState:
    if (!SetExecInterval(1))
    {
        return
    }

    GMSEx := GlobalMemoryStatusEx()
    result := "* | 状态 | 运行时间 | " Round(A_TickCount / 1000 / 3600, 3) " 小时`n"
    result .= "* | 状态 | CPU 占用 | " CPULoad() "% `n"
    result .= "* | 状态 | 内存占用 | " Round(100 * (GMSEx[2] - GMSEx[3]) / GMSEx[2], 2) "% `n"
    result .= "* | 状态 | 进程总数 | " GetProcessCount() "`n"
    result .= "* | 状态 | 内存总量 | " Round(GMSEx[2] / 1024**2, 2) "MB `n"
    result .= "* | 状态 | 可用内存 | " Round(GMSEx[3] / 1024**2, 2) "MB `n"
    DisplayResult(AlignText(result))
return

KillProcess:
    args := StrSplit(Arg, " ")
    for index, argument in args
    {
        Process, Close, %argument%
    }
return

SendToClip:
    clipboard := Arg
    GoSub, Clip
return

global Arg

Functions:
    @("Help", "帮助信息")
    @("KeyHelp", "置顶的按键帮助信息")
    @("AhkRun", "使用 Ahk 的 Run() 运行 `; command", true)
    @("CmdRun", "使用 cmd 运行 : command", true)
    @("CmdRunOnly", "只使用 cmd 运行")
    @("WinRRun", "使用 win + r 运行", true)
    @("Dictionary", "有道词典在线翻译", true)
    @("RunAndDisplay", "使用 cmd 运行，并显示结果", true)
    @("ReindexFiles", "重新索引待搜索文件")
    @("Clip", "显示剪切板内容")
    @("Calc", "计算器")
    @("SearchOnBaidu", "使用 Baidu（百度）搜索剪切板或输入内容", true)
    @("SearchOnGoogle", "使用 Google（谷歌）搜索剪切板或输入内容", true)
    @("SearchOnBing", "使用 Bing（必应）搜索剪切板或输入内容", true)
    @("SearchOnTaobao", "使用 Taobao（淘宝）搜索剪切板或输入内容")
    @("SearchOnJingdong", "使用 JD（京东）搜索剪切板或输入内容")
    @("EditConfig", "编辑配置文件")
    @("ClearClipboardFormat", "清除剪切板中文字的格式")
    @("RunClipboard", "使用 ahk 的 Run 运行剪切板内容")
    @("EmptyRecycle", "清空回收站")
    @("Logoff", "注销 登出")
    @("RestartMachine", "重启")
    @("ShutdownMachine", "关机")
    @("SuspendMachine", "挂起 睡眠 待机")
    @("HibernateMachine", "休眠")
    @("TurnMonitorOff", "关闭显示器")
    @("T2S", "将剪切板或输入内容中的繁体转成简体")
    @("S2T", "将剪切板或输入内容中的简体转成繁体")
    @("ShowIp", "显示 IP")
    @("Calendar", "用浏览器打开万年历")
    @("CleanupRank", "清理命令权重中的无效命令")
    @("CurrencyRate", "汇率 使用示例： hl JPY EUR 2")
    @("CNY2USD", "汇率 人民币兑换美元")
    @("USD2CNY", "汇率 美元兑换人民币")
    @("ProcessList", "进程列表")
    @("UrlEncode", "URL 编码")
    @("DiskSpace", "查看磁盘空间 df")
    @("ArgTest", "参数测试：ArgTest arg1,arg2,...")
    @("AhkTest", "运行参数或者剪切板中的 AHK 代码")
    @("IncreaseVolume", "提高音量")
    @("DecreaseVolume", "降低音量")
    @("SystemState", "系统状态 top")
    @("KillProcess", "杀死进程")

    if (IsLabel("ReservedFunctions"))
    {
        GoSub, ReservedFunctions
    }
return

Help:
    DisplayResult(KeyHelpText() . GetAllFunctions())
return

KeyHelp:
    ToolTip, % KeyHelpText()
    SetTimer, RemoveToolTip, 5000
return

CmdRun:
    RunWithCmd(Arg)
return

CmdRunOnly:
    RunWithCmd(Arg, true)
return

AhkRun:
    Run, %Arg%
return

Clip:
    DisplayResult("剪切板内容长度 " . StrLen(clipboard) . " ：`n`n" . clipboard)
return

CNY2USD:
    DisplayResult("查询中，可能会比较慢或者查询失败，请稍后...")
    DisplayResult(QueryCurrencyRate("CNY", "USD", Arg))
return

USD2CNY:
    DisplayResult("查询中，可能会比较慢或者查询失败，请稍后...")
    DisplayResult(QueryCurrencyRate("USD", "CNY", Arg))
return

CurrencyRate:
    args := StrSplit(Arg, " ")
    if (args.Length() != 3)
    {
        DisplayResult("使用示例：`n    CurrencyRate USD CNY 2")
        return
    }

    DisplayResult("查询中，可能会比较慢或者查询失败，请稍后...")
    DisplayResult(QueryCurrencyRate(args[1], args[2], args[3]))
return

QueryCurrencyRate(fromCurrency, toCurrency, amount)
{
    headers := Object()
    headers["apikey"] := "c9098c96599be340bbd9551e2b061f63"

    jsonText := UrlDownloadToString("http://apis.baidu.com/apistore/currencyservice/currency?"
        . "fromCurrency=" fromCurrency "&toCurrency=" toCurrency "&amount=" amount, headers)
    parsed := JSON.Load(jsonText)

    if (parsed.errNum != 0 && parsed.errMsg != "success")
    {
        return "查询失败，错误信息：`n`n" jsonText
    }

    result := fromCurrency " 兑换 " toCurrency " 当前汇率：`n`n" parsed.retData.currency "`n`n`n"
    result .= amount " " fromCurrency " = " parsed.retData.convertedamount " " toCurrency "`n"

    return result
}

ArgTest:
    args := StrSplit(Arg, ",")
    result := "共有 " . args.Length() . " 个参数。`n`n"

    for index, argument in args
    {
        result .= "第 " . index . " 个参数：" . argument . "`n"
    }

    DisplayResult(result)
return

ShowIp:
    DisplayResult(A_IPAddress1
            . "`r`n" . A_IPAddress2
            . "`r`n" . A_IPAddress3
            . "`r`n" . A_IPAddress4)
return

Dictionary:
    word := Arg == "" ? clipboard : Arg

    url := "http://fanyi.youdao.com/openapi.do?keyfrom=YouDaoCV&key=659600698&"
            . "type=data&doctype=json&version=1.2&q=" UrlEncode(word)

    jsonText := StrReplace(UrlDownloadToString(url), "-phonetic", "_phonetic")

    if (jsonText == "no query")
    {
        DisplayResult("未查到结果")
        return
    }

    parsed := JSON.Load(jsonText)
    result := parsed.query

    if (parsed.basic.uk_phonetic != "" && parsed.basic.us_phonetic != "")
    {
        result .= " UK: [" parsed.basic.uk_phonetic "], US: [" parsed.basic.us_phonetic "]`n"
    }
    else if (parsed.basic.phonetic != "")
    {
        result .= " [" parsed.basic.phonetic "]`n"
    }
    else
    {
        result .= "`n"
    }

    if (parsed.basic.explains.Length() > 0)
    {
        result .= "`n"
        for index, explain in parsed.basic.explains
        {
            result .= "    * " explain "`n"
        }
    }

    if (parsed.web.Length() > 0)
    {
        result .= "`n----`n"

        for i, element in parsed.web
        {
            result .= "`n    * " element.key
            for j, value in element.value
            {
                if (j == 1)
                {
                    result .= "`n       "
                }
                else
                {
                    result .= "`; "
                }

                result .= value
            }
        }
    }

    DisplayResult(result)
    clipboard := result
return

Calendar:
    Run % "http://www.baidu.com/baidu?wd=%CD%F2%C4%EA%C0%FA"
return

T2S:
    text := Arg == "" ? clipboard : Arg
    clipboard := ""
    clipboard := Kanji_t2s(text)
    ClipWait
    DisplayResult(clipboard)
return

S2T:
    text := Arg == "" ? clipboard : Arg
    clipboard := ""
    clipboard := Kanji_s2t(text)
    ClipWait
    DisplayResult(clipboard)
return

ClearClipboardFormat:
    clipboard := clipboard
return

SearchOnBaidu:
    word := Arg == "" ? clipboard : Arg

    Run, https://www.baidu.com/s?wd=%word%
return

SearchOnGoogle:
    word := UrlEncode(Arg == "" ? clipboard : Arg)

    Run, https://www.google.com.hk/#newwindow=1&safe=strict&q=%word%
return

SearchOnBing:
    word := Arg == "" ? clipboard : Arg

    Run, http://cn.bing.com/search?q=%word%
return

SearchOnTaobao:
    word := Arg == "" ? clipboard : Arg

    Run, https://s.taobao.com/search?q=%word%
return

SearchOnJingdong:
    word := Arg == "" ? clipboard : Arg

    Run, http://search.jd.com/Search?keyword=%word%&enc=utf-8
return

RunClipboard:
    Run, %clipboard%
return

Calc:
    result := Eval(Arg)
    DisplayResult(result)
    clipboard := result
    TurnOnRealtimeExec()
return

RunAndDisplay:
    DisplayResult(RunAndGetOutput(Arg))
return

WinRRun:
    Send, #r
    Sleep, 100
    Send, %Arg%
    Send, {enter}
return

Logoff:
    MsgBox, 4, , 将要注销，是否执行？
    {
        Shutdown, 0
    }
return

ShutdownMachine:
    MsgBox, 4, , 将要关机，是否执行？
    IfMsgBox Yes
    {
        Shutdown, 1
    }
return

RestartMachine:
    MsgBox, 4, , 将要重启机器，是否执行？
    IfMsgBox Yes
    {
        Shutdown, 2
    }
return

HibernateMachine:
    MsgBox, 4, , 将要休眠，是否执行？
    IfMsgBox Yes
    {
        ; 参数 #1: 使用 1 代替 0 来进行休眠而不是挂起。
        ; 参数 #2: 使用 1 代替 0 来立即挂起而不询问每个应用程序以获得许可。
        ; 参数 #3: 使用 1 而不是 0 来禁止所有的唤醒事件。
        DllCall("PowrProf\SetSuspendState", "int", 1, "int", 0, "int", 0)
    }
return

SuspendMachine:
    MsgBox, 4, , 将要待机，是否执行？
    IfMsgBox Yes
    {
        DllCall("PowrProf\SetSuspendState", "int", 0, "int", 0, "int", 0)
    }
return

TurnMonitorOff:
    ; 关闭显示器:
    SendMessage, 0x112, 0xF170, 2,, Program Manager
    ; 0x112 is WM_SYSCOMMAND, 0xF170 is SC_MONITORPOWER.
    ; 对上面命令的注释: 使用 -1 代替 2 来打开显示器.
    ; 使用 1 代替 2 来激活显示器的节能模式.
return

EmptyRecycle:
    MsgBox, 4, , 将要清空回收站，是否执行？
    IfMsgBox Yes
    {
        FileRecycleEmpty,
    }
return

ProcessList:
    result := ""

    for process in ComObjGet("winmgmts:").ExecQuery("Select * from Win32_Process")
        result .= "* | 进程 | " process.Name " | " process.CommandLine "`n"
    Sort, result

    DisplayResult(FilterResult(AlignText(result), Arg))
    TurnOnResultFilter()
return

UrlEncode:
    text := Arg == "" ? clipboard : Arg
    clipboard := UrlEncode(text)
    DisplayResult(clipboard)
return

DiskSpace:
    result := ""

    DriveGet, list, list
    Loop, Parse, list
    {
        drive := A_LoopField ":"
        DriveGet, label, label, %drive%
        DriveGet, cap, capacity, %drive%
        DrivespaceFree, free, %drive%
        SetFormat, float, 5.2
        percent := 100 * (cap - free) / cap
        SetFormat, float, 6.2
        cap /= 1024.0
        free /= 1024.0
        result = %result%* | %drive% | 总共: %cap% G  可用: %free% G | 已使用：%percent%`%  卷标: %label%`n
    }

	DisplayResult(AlignText(result))
return

AhkTest:
    text := Arg == "" ? clipboard : Arg
    FileDelete, %A_Temp%\RunZ.AhkTest.ahk
    FileAppend, %text%, %A_Temp%\RunZ.AhkTest.ahk
    Run, %A_Temp%\RunZ.AhkTest.ahk
return

IncreaseVolume:
    SoundSet, +5
return

DecreaseVolume:
    SoundSet, -5
return

SystemState:
    if (!SetExecInterval(1))
    {
        return
    }

    GMSEx := GlobalMemoryStatusEx()
    result := "* | 状态 | 运行时间 | " Round(A_TickCount / 1000 / 3600, 3) " 小时`n"
    result .= "* | 状态 | CPU 占用 | " CPULoad() "% `n"
    result .= "* | 状态 | 内存占用 | " Round(100 * (GMSEx[2] - GMSEx[3]) / GMSEx[2], 2) "% `n"
    result .= "* | 状态 | 进程总数 | " GetProcessCount() "`n"
    result .= "* | 状态 | 内存总量 | " Round(GMSEx[2] / 1024**2, 2) "MB `n"
    result .= "* | 状态 | 可用内存 | " Round(GMSEx[3] / 1024**2, 2) "MB `n"
    DisplayResult(AlignText(result))
return

KillProcess:
    args := StrSplit(Arg, " ")
    for index, argument in args
    {
        Process, Close, %argument%
    }
return


fixed order in array

fixed order in array

; ===================================================================================
; AutoHotkey Version ..: 1.1.*
; Version .............: 1.08 (AHK)
; Release Date ........: 2017-04-07
; GitHub ..............: https://github.com/chao-samu/demo-file-renamer
; Author ..............: chao-samu
;------------------------------------------------------------------------------------
; Script Name..........: demo file renamer
; Description .........: Integrate mapname into demofile (*.dem).
;                        Support: TF2, CS 1.6, CS:S and CS:GO
; License..............: MIT License (https://github.com/chao-samu/demo-file-renamer/blob/master/LICENSE)
; ===================================================================================

#NoEnv
#NoTrayIcon
SendMode Input
SetWorkingDir %A_ScriptDir%

;############################### Programm Info ###############################
PrgName := "demo file renamer"
PrgVersion := "1.08 (AHK)"

;############################### OS Detections ###############################
If (A_PtrSize = 4)
{
    BitVersion := "x86"
}
else
{
    BitVersion := "x64"
}

;############################### Functions ###############################
HasVal(haystack, needle) {                                              ;HasVal function from https://autohotkey.com/boards/viewtopic.php?p=109617#p109617
    for index, value in haystack
        if (value = needle)
            return index
    if !(IsObject(haystack))
        throw Exception("Bad haystack!", -1, haystack)
    return 0
}

ParsingDemofiles(RenamingMaskNumber, counter_files_quotient)
{
    Loop, Files, *.dem
    {

        counter_prog := counter_files_quotient * A_Index
        GuiControl,, ProgressBar, %counter_prog%
        mapstring := ""
        mapstring_formated := ""
        File := FileOpen(A_LoopFileName, "r")
        while !File.AtEOF
        {
            demofile := File.ReadLine()
            RegExMatch(demofile, "maps[\/\\].+\.bsp", mapstring)
            If mapstring
            {
                File.Close()
                mapstring_formated := Format("{1:s}", mapstring)
                continue
            }
        }

        If (InStr(mapstring_formated, "maps") and InStr(mapstring_formated, "bsp"))
        {
            RegExMatch(mapstring_formated, "(?<=maps[\/\\]).+(?=\.bsp)", Mapname) ;RegEx lookahead and lookbehind
            Mapname := Format("{1:s}", Mapname)
            If (InStr(Mapname, "/") or InStr(Mapname, "\"))
            {
                Mapname := RegExReplace(Mapname, ".+[\/\\]", "")
            }
            SplitPath, A_LoopFileName,,,, FileNameNoExt
            If (RenamingMaskNumber = 3) or (RenamingMaskNumber = 4)
            {
                FormatTime, mod_date, %A_LoopFileTimeModified%, yyyy-MM-dd
            }
            RenamingMask := []
            RenamingMask[1] := filelist . A_LoopFileName . "`t" . FileNameNoExt . "_" . Mapname . "." . A_LoopFileExt . "`n"
            RenamingMask[2] := filelist . A_LoopFileName . "`t" . Mapname . "_" . FileNameNoExt . "." . A_LoopFileExt . "`n"
            RenamingMask[3] := filelist . A_LoopFileName . "`t" . mod_date . "_" . Mapname . "_" . FileNameNoExt . "." . A_LoopFileExt . "`n"
            RenamingMask[4] := filelist . A_LoopFileName . "`t" . mod_date . "_" . FileNameNoExt . "_" . Mapname . "." . A_LoopFileExt . "`n"
            filelist := RenamingMask[RenamingMaskNumber]
        }
        else
        {
            filelist_failed := filelist_failed . A_LoopFileName . "`n"
            counter_failed += 1
        }

    }
    return [filelist, filelist_failed, counter_failed]
}

ParsingFullDemofiles(RenamingMaskNumber, counter_files_quotient)
{
    Loop, Files, *.dem
    {
        counter_prog := counter_files_quotient * A_Index
        GuiControl,, ProgressBar, %counter_prog%
        mapstring := ""
        File := FileOpen(A_LoopFileName, "r")
        mapstring_formated := [] ;init Array Object (same as var := Object())
        while !File.AtEOF
        {
            demofile := File.ReadLine()
            RegExMatch(demofile, "maps[\/\\].+\.bsp", mapstring)
            If mapstring
            {
                mapstring_formated.insert(Format("{1:s}", mapstring))
            }
        }
        File.Close()

        Mapname := []
        x := 0
        while A_Index <= mapstring_formated.MaxIndex()
        {
            needle := ""
            If (InStr(mapstring_formated[A_Index], "maps") and InStr(mapstring_formated[A_Index], "bsp"))
            {
                RegExMatch(mapstring_formated[A_Index], "(?<=maps[\/\\]).+(?=\.bsp)", needle) ;RegEx lookahead and lookbehind
                needle := Format("{1:s}", needle)
                If (InStr(needle, "/") or InStr(needle, "\"))
                {
                    needle := RegExReplace(needle, ".+[\/\\]", "")
                }
                arraypos := HasVal(Mapname, needle)
                If !arraypos
                {
                    ; MsgBox % "Mapname: " . Mapname . " needle: " . needle . " arraypos: " . arraypos "`n if"
                    Mapname.Push(needle)
                }
            }
        }

        If Mapname.MaxIndex()
        {
            Mapnames_all := ""
            while A_Index <= Mapname.MaxIndex()
            {
                If Mapnames_all
                {
                    Mapnames_all := Mapnames_all . "+"
                }
                Mapnames_all := Mapnames_all . Mapname[A_Index]
            }
            SplitPath, A_LoopFileName,,,, FileNameNoExt
            If (RenamingMaskNumber = 3) or (RenamingMaskNumber = 4)
            {
                FormatTime, mod_date, %A_LoopFileTimeModified%, yyyy-MM-dd
            }
            RenamingMask := []
            RenamingMask[1] := filelist . A_LoopFileName . "`t" . FileNameNoExt . "_" . Mapnames_all . "." . A_LoopFileExt . "`n"
            RenamingMask[2] := filelist . A_LoopFileName . "`t" . Mapnames_all . "_" . FileNameNoExt . "." . A_LoopFileExt . "`n"
            RenamingMask[3] := filelist . A_LoopFileName . "`t" . mod_date . "_" . Mapnames_all . "_" . FileNameNoExt . "." . A_LoopFileExt . "`n"
            RenamingMask[4] := filelist . A_LoopFileName . "`t" . mod_date . "_" . FileNameNoExt . "_" . Mapnames_all . "." . A_LoopFileExt . "`n"
            filelist := RenamingMask[RenamingMaskNumber]
        }
        else
        {
            filelist_failed := filelist_failed . A_LoopFileName . "`n"
            counter_failed += 1
        }
    }
    return [filelist, filelist_failed, counter_failed]
}

;############################### GUI ###############################
Menu, helpmenu, Add, Help , MenuHelp
Menu, helpmenu, Add
Menu, helpmenu, Add, License, MenuLicense
Menu, helpmenu, Add, About, MenuAbout
Menu, topmenu, Add, &Help, :helpmenu
Gui, Menu, topmenu

Gui, Add, Button, x12 y180 w90 h20 , Cancel
Gui, Add, Button, x212 y180 w90 h20 , Start
Gui, Add, Text, x12 y120 w290 h20 vtext_prog, Extracting mapname
Gui, Add, ListBox, x12 y30 w290 h30 vRenamingMaskNumber AltSubmit gpressListBox, OLDNAME_MAPNAME||MAPNAME_OLDNAME|YYYY-MM-DD_MAPNAME_OLDNAME|YYYY-MM-DD_OLDNAME_MAPNAME
Gui, Add, Text, x12 y10 w290 h20 , Choose renaming mask
Gui, Add, Text, x12 y70 w290 h40 vtext_example, Example: `n"samurai-vs-ninja.dem" will be renamed to "samurai-vs-ninja_de_dust2.dem"

Gui, Add, Progress, x12 y140 w290 h10 Backgroundsilver vProgressBar
Gui, Add, Checkbox, x12 y157 w290 h20 vOption_1, Parsing full demofile (processing intese)
; Generated using SmartGUI Creator for SciTE
Gui, Show, w323 h221, %PrgName%
return

MenuHelp:
Gui, Help:+owner1
Gui +Disabled
Gui, Help:Add, Text,,
(
What can do this Tool?
This tool was manly made to extract out the mapname of
GoldSrc- and Source Engine demofiles and place it in the name of the demofile itself.

Which kind of demofiles this tool can handle?
Currently this tool support Counter-Strike 1.6, Counter-Strike Source,
Counter-Strike Global Offensive and Team Fortress 2 demofiles.

How to use?
1. Select your renaming mask you want
2. Press start and select in the following window your folder with the supported demofiles
    (please note, all demofiles with the ending "dem" in this folder will be renamed, subfolder
    are not included).
    In a protected folder (like "ProgramFiles") you have to start this program in admin mode!
3. Press OK and wait until you will hopefully be happy :)

Options Info:
Parsing full demofile: This option is recommended for old demofiles (CS 1.6 etc.),
because it was able to record into the same file when a mapchange occur. So the hole
file have to be read to detect all played maps in one file. This was fixed in newer
games (CS:GO etc.), so it isn't necessary there. Use this option if you are unsure.
)

Gui, Help:Add, Button, Default, OK
Gui, Help:Show, w450 h320, Help
return

MenuLicense:
Gui, License:+owner1
Gui +Disabled
Gui, License:Add, Text, r9 vMeinEdit,
(
The MIT License (MIT)

Copyright (c) 2017 chao-samu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
)
Gui, License:Add, Button, Default, OK
Gui, License:Show, w540 h320, License
return

MenuAbout:
Gui, About:+owner1
Gui +Disabled
Gui, About:Add, Link,, %PrgName% - Version %PrgVersion% `n`nTool compiled with: AHK %A_AhkVersion% %BitVersion% `n`nLook for updates:`n<a href="https://github.com/chao-samu">https://github.com/chao-samu</a>`n`nMade by chao-samu
Gui, About:Add, Button, Default, OK
Gui, About:Show, w250 h150, About
return

HelpButtonOK:
HelpGuiClose:
HelpGuiEscape:
AboutButtonOK:
AboutGuiClose:
AboutGuiEscape:
LicenseButtonOK:
LicenseGuiClose:
LicenseGuiEscape:
Gui, 1:-Disabled
Gui Destroy
return

pressListBox:
    Gui, Submit, NoHide
    if (RenamingMaskNumber = 1)
    GuiControl,, text_example, Example: `n"samurai-vs-ninja.dem" will be renamed to "samurai-vs-ninja_de_dust2.dem"
    else if (RenamingMaskNumber = 2)
    GuiControl,, text_example, Example: `n"samurai-vs-ninja.dem" will be renamed to "de_dust2_samurai-vs-ninja.dem"
    else if (RenamingMaskNumber = 3)
    GuiControl,, text_example, Example: `n"samurai-vs-ninja.dem" will be renamed to "2007-05-03_de_dust2_samurai-vs-ninja.dem"
    else
    GuiControl,, text_example, Example: `n"samurai-vs-ninja.dem" will be renamed to "2007-05-03_samurai-vs-ninja_de_dust2.dem"
return

; pressOption_1:
    ; Gui, Submit, NoHide
    ; if (Option_1 = 1)
    ; GuiControl,, text_example, %text_example% (Look into Help for additional informations)
    ; else
    ; GoTo pressListBox
; return

ButtonCancel:
GuiClose:
ExitApp

;############################### MAIN Programm ###############################
ButtonStart:
FormatTime, current_time
ParsingDemofiles.Delete(1, 3)
folder_demofiles := ""
filelist := ""
filelist_failed := ""
counter_files := ""
counter_failed := ""
counter_successfully := ""
logfile_counter := 1
GuiControl, Disable, Start
GuiControl, Disable, RenamingMaskNumber
GuiControl, Disable, Option_1
GuiControlGet, RenamingMaskNumber
GuiControlGet, Option_1
FileSelectFolder, folder_demofiles,, 0, Please select your folder where your demofiles are. `nAll files with the ending *.dem will be renamed.
if ErrorLevel=0
{
    SetWorkingDir %folder_demofiles%
    Loop, Files, *.dem
    {
        counter_files += 1
    }
    If counter_files
    {
        counter_files_quotient := 100 / counter_files
        If Option_1
        {
            ParsingInfo := ParsingFullDemofiles(RenamingMaskNumber, counter_files_quotient)
        }
        else
        {
            ParsingInfo := ParsingDemofiles(RenamingMaskNumber, counter_files_quotient)
        }
        filelist := ParsingInfo[1]
        filelist_failed := ParsingInfo[2]
        counter_failed := ParsingInfo[3]
        GuiControl, Disable, Cancel
        GuiControl,, text_prog, Renaming Files
        Loop, Parse, filelist, `n
        {
             filelist_array := StrSplit(A_LoopField, A_Tab)
             Source := filelist_array[1]
             Destination := filelist_array[2]
             FileMove, %Source%, %Destination%
        }
        If filelist_failed
        {
            logfile_name := "demo-file-renamer_logfile.txt"
            logfile := "Renaming from " current_time " in " A_WorkingDir " `n`nThe following files aren't renamed because the map wasn't found in the demofile: `n`n" . filelist_failed . "`n`nWhat you can do: `n- Execute the demofile in your game or `n- Open the file in an editor and search for the word ""maps"" `n`nBe sure the demofile is a CS 1.6, CS:S, CS:GO or TF2 demofile."
            IfExist, %A_ScriptDir%\%logfile_name%
            {
                filetrue := "A"
                while filetrue
                {
                    logfile_counter +=1
                    logfile_name := "demo-file-renamer_logfile(" . logfile_counter . ").txt"
                    filetrue := FileExist(A_ScriptDir . "\" . logfile_name)
                }
                FileAppend, %logfile%, %A_ScriptDir%\%logfile_name%
            }
            else
            {
                FileAppend, %logfile%, %A_ScriptDir%\%logfile_name%
            }

            counter_successfully := counter_files - counter_failed
            logfile_path := A_ScriptDir . "\" . logfile_name
            msgbox % counter_successfully " out of " counter_files " files were successfully renamed. `n" "There are " counter_failed " that aren't renamed. `n`nLogfile is generated, please look for further information in logfile: `n" logfile_path
        }
        else
        {
            MsgBox, 0, , All demofiles successfully renamed!
        }
        GuiControl,, ProgressBar, 0
        GuiControl,, text_prog, Extracting mapname
        GuiControl, Enable, RenamingMaskNumber
        GuiControl, Enable, Option_1
        GuiControl, Enable, Cancel
        GuiControl, Enable, Start
        return
    }
    else
    {
        MsgBox % "No files found!"
        GuiControl,, ProgressBar, 0
        GuiControl, Enable, RenamingMaskNumber
        GuiControl, Enable, Option_1
        GuiControl, Enable, Cancel
        GuiControl, Enable, Start
        return
    }
}
else
{
    GuiControl,, ProgressBar, 0
    GuiControl, Enable, RenamingMaskNumber
    GuiControl, Enable, Option_1
    GuiControl, Enable, Start
    return
}

; ===================================================================================
; AutoHotkey Version ..: 1.1.*
; Version .............: 1.07 (AHK)
; Release Date ........: 2017-04-07
; GitHub ..............: https://github.com/chao-samu/demo-file-renamer
; Author ..............: chao-samu
;------------------------------------------------------------------------------------
; Script Name..........: demo file renamer
; Description .........: Integrate mapname into demofile (*.dem).
;                        Support: TF2, CS 1.6, CS:S and CS:GO
; License..............: MIT License (https://github.com/chao-samu/demo-file-renamer/blob/master/LICENSE)
; ===================================================================================

#NoEnv
#NoTrayIcon
SendMode Input
SetWorkingDir %A_ScriptDir%

;############################### Programm Info ###############################
PrgName := "demo file renamer"
PrgVersion := "1.07 (AHK)"

;############################### OS Detections ###############################
If (A_PtrSize = 4)
{
    BitVersion := "x86"
}
else
{
    BitVersion := "x64"
}

;############################### Functions ###############################
HasVal(haystack, needle) {                                              ;HasVal function from https://autohotkey.com/boards/viewtopic.php?p=109617#p109617
    for index, value in haystack
        if (value = needle)
            return index
    if !(IsObject(haystack))
        throw Exception("Bad haystack!", -1, haystack)
    return 0
}

ParsingDemofiles(RenamingMaskNumber, counter_files_quotient)
{
    Loop, Files, *.dem
    {

        counter_prog := counter_files_quotient * A_Index
        GuiControl,, ProgressBar, %counter_prog%
        mapstring := ""
        mapstring_formated := ""
        File := FileOpen(A_LoopFileName, "r")
        while !File.AtEOF
        {
            demofile := File.ReadLine()
            RegExMatch(demofile, "maps[\/\\].+\.bsp", mapstring)
            If mapstring
            {
                File.Close()
                mapstring_formated := Format("{1:s}", mapstring)
                continue
            }
        }

        If (InStr(mapstring_formated, "maps") and InStr(mapstring_formated, "bsp"))
        {
            RegExMatch(mapstring_formated, "(?<=maps[\/\\]).+(?=\.bsp)", Mapname) ;RegEx lookahead and lookbehind
            Mapname := Format("{1:s}", Mapname)
            If (InStr(Mapname, "/") or InStr(Mapname, "\"))
            {
                Mapname := RegExReplace(Mapname, ".+[\/\\]", "")
            }
            SplitPath, A_LoopFileName,,,, FileNameNoExt
            If (RenamingMaskNumber = 3) or (RenamingMaskNumber = 4)
            {
                FormatTime, mod_date, %A_LoopFileTimeModified%, yyyy-MM-dd
            }
            RenamingMask := []
            RenamingMask[1] := filelist . A_LoopFileName . "`t" . FileNameNoExt . "_" . Mapname . "." . A_LoopFileExt . "`n"
            RenamingMask[2] := filelist . A_LoopFileName . "`t" . Mapname . "_" . FileNameNoExt . "." . A_LoopFileExt . "`n"
            RenamingMask[3] := filelist . A_LoopFileName . "`t" . mod_date . "_" . Mapname . "_" . FileNameNoExt . "." . A_LoopFileExt . "`n"
            RenamingMask[4] := filelist . A_LoopFileName . "`t" . mod_date . "_" . FileNameNoExt . "_" . Mapname . "." . A_LoopFileExt . "`n"
            filelist := RenamingMask[RenamingMaskNumber]
        }
        else
        {
            filelist_failed := filelist_failed . A_LoopFileName . "`n"
            counter_failed += 1
        }

    }
    return [filelist, filelist_failed, counter_failed]
}

ParsingFullDemofiles(RenamingMaskNumber, counter_files_quotient)
{
    Loop, Files, *.dem
    {
        counter_prog := counter_files_quotient * A_Index
        GuiControl,, ProgressBar, %counter_prog%
        mapstring := ""
        File := FileOpen(A_LoopFileName, "r")
        mapstring_formated := [] ;init Array Object (same as var := Object())
        while !File.AtEOF
        {
            demofile := File.ReadLine()
            RegExMatch(demofile, "maps[\/\\].+\.bsp", mapstring)
            If mapstring
            {
                mapstring_formated.insert(Format("{1:s}", mapstring))
            }
        }
        File.Close()

        Mapname := []
        x := 0
        while A_Index <= mapstring_formated.MaxIndex()
        {
            needle := ""
            If (InStr(mapstring_formated[A_Index], "maps") and InStr(mapstring_formated[A_Index], "bsp"))
            {
                RegExMatch(mapstring_formated[A_Index], "(?<=maps[\/\\]).+(?=\.bsp)", needle) ;RegEx lookahead and lookbehind
                needle := Format("{1:s}", needle)
                If (InStr(needle, "/") or InStr(needle, "\"))
                {
                    needle := RegExReplace(needle, ".+[\/\\]", "")
                }
                arraypos := HasVal(Mapname, needle)
                If !arraypos
                {
                    ; MsgBox % "Mapname: " . Mapname . " needle: " . needle . " arraypos: " . arraypos "`n if"
                    Mapname.InsertAt(1,needle)
                }
            }
        }

        If Mapname.MaxIndex()
        {
            Mapnames_all := ""
            while A_Index <= Mapname.MaxIndex()
            {
                If Mapnames_all
                {
                    Mapnames_all := Mapnames_all . "+"
                }
                Mapnames_all := Mapnames_all . Mapname[A_Index]
            }
            SplitPath, A_LoopFileName,,,, FileNameNoExt
            If (RenamingMaskNumber = 3) or (RenamingMaskNumber = 4)
            {
                FormatTime, mod_date, %A_LoopFileTimeModified%, yyyy-MM-dd
            }
            RenamingMask := []
            RenamingMask[1] := filelist . A_LoopFileName . "`t" . FileNameNoExt . "_" . Mapnames_all . "." . A_LoopFileExt . "`n"
            RenamingMask[2] := filelist . A_LoopFileName . "`t" . Mapnames_all . "_" . FileNameNoExt . "." . A_LoopFileExt . "`n"
            RenamingMask[3] := filelist . A_LoopFileName . "`t" . mod_date . "_" . Mapnames_all . "_" . FileNameNoExt . "." . A_LoopFileExt . "`n"
            RenamingMask[4] := filelist . A_LoopFileName . "`t" . mod_date . "_" . FileNameNoExt . "_" . Mapnames_all . "." . A_LoopFileExt . "`n"
            filelist := RenamingMask[RenamingMaskNumber]
        }
        else
        {
            filelist_failed := filelist_failed . A_LoopFileName . "`n"
            counter_failed += 1
        }
    }
    return [filelist, filelist_failed, counter_failed]
}

;############################### GUI ###############################
Menu, helpmenu, Add, Help , MenuHelp
Menu, helpmenu, Add
Menu, helpmenu, Add, License, MenuLicense
Menu, helpmenu, Add, About, MenuAbout
Menu, topmenu, Add, &Help, :helpmenu
Gui, Menu, topmenu

Gui, Add, Button, x12 y180 w90 h20 , Cancel
Gui, Add, Button, x212 y180 w90 h20 , Start
Gui, Add, Text, x12 y120 w290 h20 vtext_prog, Extracting mapname
Gui, Add, ListBox, x12 y30 w290 h30 vRenamingMaskNumber AltSubmit gpressListBox, OLDNAME_MAPNAME||MAPNAME_OLDNAME|YYYY-MM-DD_MAPNAME_OLDNAME|YYYY-MM-DD_OLDNAME_MAPNAME
Gui, Add, Text, x12 y10 w290 h20 , Choose renaming mask
Gui, Add, Text, x12 y70 w290 h40 vtext_example, Example: `n"samurai-vs-ninja.dem" will be renamed to "samurai-vs-ninja_de_dust2.dem"

Gui, Add, Progress, x12 y140 w290 h10 Backgroundsilver vProgressBar
Gui, Add, Checkbox, x12 y157 w290 h20 vOption_1, Parsing full demofile (processing intese)
; Generated using SmartGUI Creator for SciTE
Gui, Show, w323 h221, %PrgName%
return

MenuHelp:
Gui, Help:+owner1
Gui +Disabled
Gui, Help:Add, Text,,
(
What can do this Tool?
This tool was manly made to extract out the mapname of
GoldSrc- and Source Engine demofiles and place it in the name of the demofile itself.

Which kind of demofiles this tool can handle?
Currently this tool support Counter-Strike 1.6, Counter-Strike Source,
Counter-Strike Global Offensive and Team Fortress 2 demofiles.

How to use?
1. Select your renaming mask you want
2. Press start and select in the following window your folder with the supported demofiles
    (please note, all demofiles with the ending "dem" in this folder will be renamed, subfolder
    are not included).
    In a protected folder (like "ProgramFiles") you have to start this program in admin mode!
3. Press OK and wait until you will hopefully be happy :)

Options Info:
Parsing full demofile: This option is recommended for old demofiles (CS 1.6 etc.),
because it was able to record into the same file when a mapchange occur. So the hole
file have to be read to detect all played maps in one file. This was fixed in newer
games (CS:GO etc.), so it isn't necessary there. Use this option if you are unsure.
)

Gui, Help:Add, Button, Default, OK
Gui, Help:Show, w450 h320, Help
return

MenuLicense:
Gui, License:+owner1
Gui +Disabled
Gui, License:Add, Text, r9 vMeinEdit,
(
The MIT License (MIT)

Copyright (c) 2017 chao-samu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
)
Gui, License:Add, Button, Default, OK
Gui, License:Show, w540 h320, License
return

MenuAbout:
Gui, About:+owner1
Gui +Disabled
Gui, About:Add, Link,, %PrgName% - Version %PrgVersion% `n`nTool compiled with: AHK %A_AhkVersion% %BitVersion% `n`nLook for updates:`n<a href="https://github.com/chao-samu">https://github.com/chao-samu</a>`n`nMade by chao-samu
Gui, About:Add, Button, Default, OK
Gui, About:Show, w250 h150, About
return

HelpButtonOK:
HelpGuiClose:
HelpGuiEscape:
AboutButtonOK:
AboutGuiClose:
AboutGuiEscape:
LicenseButtonOK:
LicenseGuiClose:
LicenseGuiEscape:
Gui, 1:-Disabled
Gui Destroy
return

pressListBox:
    Gui, Submit, NoHide
    if (RenamingMaskNumber = 1)
    GuiControl,, text_example, Example: `n"samurai-vs-ninja.dem" will be renamed to "samurai-vs-ninja_de_dust2.dem"
    else if (RenamingMaskNumber = 2)
    GuiControl,, text_example, Example: `n"samurai-vs-ninja.dem" will be renamed to "de_dust2_samurai-vs-ninja.dem"
    else if (RenamingMaskNumber = 3)
    GuiControl,, text_example, Example: `n"samurai-vs-ninja.dem" will be renamed to "2007-05-03_de_dust2_samurai-vs-ninja.dem"
    else
    GuiControl,, text_example, Example: `n"samurai-vs-ninja.dem" will be renamed to "2007-05-03_samurai-vs-ninja_de_dust2.dem"
return

; pressOption_1:
    ; Gui, Submit, NoHide
    ; if (Option_1 = 1)
    ; GuiControl,, text_example, %text_example% (Look into Help for additional informations)
    ; else
    ; GoTo pressListBox
; return

ButtonCancel:
GuiClose:
ExitApp

;############################### MAIN Programm ###############################
ButtonStart:
FormatTime, current_time
ParsingDemofiles.Delete(1, 3)
folder_demofiles := ""
filelist := ""
filelist_failed := ""
counter_files := ""
counter_failed := ""
counter_successfully := ""
logfile_counter := 1
GuiControl, Disable, Start
GuiControl, Disable, RenamingMaskNumber
GuiControl, Disable, Option_1
GuiControlGet, RenamingMaskNumber
GuiControlGet, Option_1
FileSelectFolder, folder_demofiles,, 0, Please select your folder where your demofiles are. `nAll files with the ending *.dem will be renamed.
if ErrorLevel=0
{
    SetWorkingDir %folder_demofiles%
    Loop, Files, *.dem
    {
        counter_files += 1
    }
    If counter_files
    {
        counter_files_quotient := 100 / counter_files
        If Option_1
        {
            ParsingInfo := ParsingFullDemofiles(RenamingMaskNumber, counter_files_quotient)
        }
        else
        {
            ParsingInfo := ParsingDemofiles(RenamingMaskNumber, counter_files_quotient)
        }
        filelist := ParsingInfo[1]
        filelist_failed := ParsingInfo[2]
        counter_failed := ParsingInfo[3]
        GuiControl, Disable, Cancel
        GuiControl,, text_prog, Renaming Files
        Loop, Parse, filelist, `n
        {
             filelist_array := StrSplit(A_LoopField, A_Tab)
             Source := filelist_array[1]
             Destination := filelist_array[2]
             FileMove, %Source%, %Destination%
        }
        If filelist_failed
        {
            logfile_name := "demo-file-renamer_logfile.txt"
            logfile := "Renaming from " current_time " in " A_WorkingDir " `n`nThe following files aren't renamed because the map wasn't found in the demofile: `n`n" . filelist_failed . "`n`nWhat you can do: `n- Execute the demofile in your game or `n- Open the file in an editor and search for the word ""maps"" `n`nBe sure the demofile is a CS 1.6, CS:S, CS:GO or TF2 demofile."
            IfExist, %A_ScriptDir%\%logfile_name%
            {
                filetrue := "A"
                while filetrue
                {
                    logfile_counter +=1
                    logfile_name := "demo-file-renamer_logfile(" . logfile_counter . ").txt"
                    filetrue := FileExist(A_ScriptDir . "\" . logfile_name)
                }
                FileAppend, %logfile%, %A_ScriptDir%\%logfile_name%
            }
            else
            {
                FileAppend, %logfile%, %A_ScriptDir%\%logfile_name%
            }

            counter_successfully := counter_files - counter_failed
            logfile_path := A_ScriptDir . "\" . logfile_name
            msgbox % counter_successfully " out of " counter_files " files were successfully renamed. `n" "There are " counter_failed " that aren't renamed. `n`nLogfile is generated, please look for further information in logfile: `n" logfile_path
        }
        else
        {
            MsgBox, 0, , All demofiles successfully renamed!
        }
        GuiControl,, ProgressBar, 0
        GuiControl,, text_prog, Extracting mapname
        GuiControl, Enable, RenamingMaskNumber
        GuiControl, Enable, Option_1
        GuiControl, Enable, Cancel
        GuiControl, Enable, Start
        return
    }
    else
    {
        MsgBox % "No files found!"
        GuiControl,, ProgressBar, 0
        GuiControl, Enable, RenamingMaskNumber
        GuiControl, Enable, Option_1
        GuiControl, Enable, Cancel
        GuiControl, Enable, Start
        return
    }
}
else
{
    GuiControl,, ProgressBar, 0
    GuiControl, Enable, RenamingMaskNumber
    GuiControl, Enable, Option_1
    GuiControl, Enable, Start
    return
}