AutoHotkey.ahk, from darwin11

AutoHotkey.ahk, from darwin11

; Tips {{{
; #: win
; !: alt
; ^: ctrl
; +: shift
; &: and
; <: only left, >: only right
; *: wildecard
; ~: pass through
; }}}

; Auto-execute section {{{
; Auto execute section is the region before any return/hotkey

; Windows size
TMargin=5
BMargin=5
LMargin=5
RMargin=155 ; sidebar = 150px
MinSize=0.7

; For Terminal/Vim
GroupAdd Terminal, ahk_class PuTTY
GroupAdd Terminal, ahk_class mintty ; cygwin
GroupAdd TerminalVim, ahk_group Terminal
GroupAdd TerminalVim, ahk_class Vim

#Include  %A_ScriptDir%\vim.ahk

Return
; }}}

; Basic Settings, HotKeys, Functions {{{
; Settings

#UseHook On ; Make it a bit slow, but can avoid infinitude loop
            ; Same as "$" for each hotkey
#InstallKeybdHook ; For checking key history
                  ; Use ~500kB memory?

#HotkeyInterval 2000 ; Hotkey inteval (default 2000 milliseconds).
#MaxHotkeysPerInterval 70 ; Max hotkeys perinterval (default 50).

; For HHK
;vkFFsc079::RAlt
;vkFFsc07b::LAlt
vkFFsc079::RCtrl
vkFFsc07b::LCtrl

;; Ref for IME: http://www6.atwiki.jp/eamat/pages/17.html
;; Get IME Status. 0: Off, 1: On
;IME_GET(WinTitle="A")  {
;  ControlGet,hwnd,HWND,,,%WinTitle%
;  if (WinActive(WinTitle)) {
;    ptrSize := !A_PtrSize ? 4 : A_PtrSize
;    VarSetCapacity(stGTI, cbSize:=4+4+(PtrSize*6)+16, 0)
;    NumPut(cbSize, stGTI,  0, "UInt")   ;   DWORD   cbSize;
;    hwnd := DllCall("GetGUIThreadInfo", Uint,0, Uint,&stGTI)
;        ? NumGet(stGTI,8+PtrSize,"UInt") : hwnd
;  }
;
;  Return DllCall("SendMessage"
;      , UInt, DllCall("imm32\ImmGetDefaultIMEWnd", Uint,hwnd)
;      , UInt, 0x0283  ;Message : WM_IME_CONTROL
;      ,  Int, 0x0005  ;wParam  : IMC_GETOPENSTATUS
;      ,  Int, 0)      ;lParam  : 0
;}
;; Get input status. 1: Converting, 2: Have converting window, 0: Others
;IME_GetConverting(WinTitle="A",ConvCls="",CandCls="") {
;  ; Input windows, candidate windows (Add new IME with "|")
;  ConvCls .= (ConvCls ? "|" : "")                 ;--- Input Window ---
;    .  "ATOK\d+CompStr"                           ; ATOK
;    .  "|imejpstcnv\d+"                           ; MS-IME
;    .  "|WXGIMEConv"                              ; WXG
;    .  "|SKKIME\d+\.*\d+UCompStr"                 ; SKKIME Unicode
;    .  "|MSCTFIME Composition"                    ; Google IME
;  CandCls .= (CandCls ? "|" : "")                 ;--- Candidate Window ---
;    .  "ATOK\d+Cand"                              ; ATOK
;    .  "|imejpstCandList\d+|imejpstcand\d+"       ; MS-IME 2002(8.1)XP
;    .  "|mscandui\d+\.candidate"                  ; MS Office IME-2007
;    .  "|WXGIMECand"                              ; WXG
;    .  "|SKKIME\d+\.*\d+UCand"                    ; SKKIME Unicode
; CandGCls := "GoogleJapaneseInputCandidateWindow" ; Google IME
;
;  ControlGet,hwnd,HWND,,,%WinTitle%
;  if (WinActive(WinTitle)) {
;    ptrSize := !A_PtrSize ? 4 : A_PtrSize
;    VarSetCapacity(stGTI, cbSize:=4+4+(PtrSize*6)+16, 0)
;    NumPut(cbSize, stGTI,  0, "UInt")   ;   DWORD   cbSize;
;    hwnd := DllCall("GetGUIThreadInfo", Uint,0, Uint,&stGTI)
;      ? NumGet(stGTI,8+PtrSize,"UInt") : hwnd
;  }
;
;  WinGet, pid, PID,% "ahk_id " hwnd
;  tmm:=A_TitleMatchMode
;  SetTitleMatchMode, RegEx
;  ret := WinExist("ahk_class " . CandCls . " ahk_pid " pid) ? 2
;      :  WinExist("ahk_class " . CandGCls                 ) ? 2
;      :  WinExist("ahk_class " . ConvCls . " ahk_pid " pid) ? 1
;      :  0
;  SetTitleMatchMode, %tmm%
;  Return ret
;}
;; Set IME, SetSts=0: Off, 1: On, return 0 for success, others for non-success
;IME_SET(SetSts=0, WinTitle="A")    {
;  ControlGet,hwnd,HWND,,,%WinTitle%
;  if(WinActive(WinTitle)){
;    ptrSize := !A_PtrSize ? 4 : A_PtrSize
;    VarSetCapacity(stGTI, cbSize:=4+4+(PtrSize*6)+16, 0)
;    NumPut(cbSize, stGTI,  0, "UInt")   ;   DWORD   cbSize;
;    hwnd := DllCall("GetGUIThreadInfo", Uint,0, Uint,&stGTI)
;        ? NumGet(stGTI,8+PtrSize,"UInt") : hwnd
;  }
;
;  Return DllCall("SendMessage"
;    , UInt, DllCall("imm32\ImmGetDefaultIMEWnd", Uint,hwnd)
;    , UInt, 0x0283  ;Message : WM_IME_CONTROL
;    ,  Int, 0x006   ;wParam  : IMC_SETOPENSTATUS
;    ,  Int, SetSts) ;lParam  : 0 or 1
;}

; }}}

; Terminal/Vim {{{
; ESC + IME
#IfWInActive, ahk_group TerminalVim
Esc:: ; Just send Esc at converting.
  if (VIM_IME_GET(A)) {
    if (VIM_IME_GetConverting(A)) {
      Send,{Esc}
    } else {
      VIM_IME_SET()
    }
  } else {
    Send,{Esc}
  }
  Return
^[:: ; Go to Normal mode (for vim) with IME off even at converting.
  if (VIM_IME_GET(A)) {
    Send,{Esc}
    Sleep 1 ; wait 1 ms (Need to stop converting)
    VIM_IME_SET()
    Send,{Esc}
  } else {
    Send,{Esc}
  }
  Return
#IfWInActive

; Paste
#IfWInActive, ahk_group Terminal
!v::
  StringSplit, strout, clipboard, `n
  If(strout0>1 or InStr(clipboard, "sudo")>0) {
    MsgBox, 308, Clipboard, %clipboard%`n`n Do you want to paste?
    IfMsgBox, No
    {
      Return
    }
  }
  Sleep,200
  MouseClick, Right, 50, 50, 1
  Return
#IfWInActive
#IfWInActive, ahk_class Vim
!v::Send,{Alt}ep
#IfWInActive

; Other than Terminal/Vim
#IfWInNotActive, ahk_group TerminalVim
^[::Send,{Esc}             ; Always C-[ to ESC, like vim
^d::Send,{Del}             ; Always Delete with C-d
#IfWInNotActive
; }}} Terminal/Vim

; Power Point {{{
#IfWInActive, ahk_class PP12FrameClass
; Select one character
^Space::Send,{Right}+{Left}

; Subscript/Superscript
^=::Send,^tb{Enter}
^+=::Send,^tp{Enter}
; For JP keyboards
;^-::Send,^tb{Enter}
;^+-::Send,^tp{Enter}

; Fonts
^+s::Send,^tfsymbol{Enter}
^+a::Send,^tfarial{Enter}
^+h::Send,^tfhelvetica{Enter}
#IfWInActive
; }}} Power Point

; Word {{{
#IfWInActive, ahk_class OpusApp
^Space::Send,{Right}+{Left}
^=::Send,^tb{Enter}
^+=::Send,^tp{Enter}
; for JP keyboards
;^-::Send,^tb{Enter}
;^+-::Send,^tp{Enter}
#IfWInActive
; }}} Word

; Explorer {{{
#IfWInActive, ahk_class CabinetWClass
; Next/Previous page
^i::Send,!{Right}
^o::Send,!{Left}
#IfWInActive
; }}} Explorer

; CLCL {{{
;#IfWInActive, ahk_class CLCLMain
#IfWInActive, CLCL ; both window/title do not working...
j::
  Msgbox, clcl_down
  Send,{Down}
  Return
K::Send,{Up}
#IfWInActive
; }}} Explorer

; Everthing {{{
#IfWInActive, ahk_class EVERYTHING
Enter::
  Send,{Enter}
  Sleep,200
  IfWinActive, ahk_class EVERYTHING
  {
    Send,{Enter}
    Sleep,200
  }
  WinActivate, ahk_class EVERYTHING
  Sleep,100
  Send,{Esc}
  Return
#IfWInActive
; }}} Everything

; Command Prompt {{{
#IfWinActive ahk_class ConsoleWindowClass
^v::
  SendInput %clipboard%
  Return
#IfWInActive
; }}} Command Prompt

; Global Settings {{{
#if
; Basic Settings {{{

; Suspend
;Esc & Tab::
;  Suspend, Toggle
;  Return
; For Alt-Ctrl Swap (swapped by KeySwap)
LCtrl & Tab::AltTab
Alt & Tab::
  if GetKeyState("Shift","P") {
    Send,^+{taB} ; dosen't work ()
  }else{
    Send,^{Tab}
  }
  Return
;!m::Send,^m
;^m::Send,!m
^m::Send,!m
Ctrl & Left::Send,!{Left}
Ctrl & Right::Send,!{Right}

; Other basic settings
!Space::Send,{vkF3sc029}   ; IME by A-Space
^Space::Send,{vkF3sc029}   ; IME by C-Space
; {vkF3sc029}              ; 変換
; {vk1Dsc07B}              ; 無変換
^h::Send,{BS}              ; Always BS with C-h
!a::Send,^{Space}n        ; Minimize window
!4::Send,!{F4}             ; Close window
^4::Send,!{F4}             ; Close window
!d::Send,{Del}             ; Always Delete with A-d
;^o::Send,!{Left}           ; Go to previous page
;^i::Send,!{Right}          ; Go to nexe page
^Space::!`                 ; IME

; For HHK
; ESC to ` like normal keyboard (ESC is placed on the left of 1 in HHK)
!1::!`                ; IME
; }}} Basic Settings

; Cursor, Mouse, Window move/size {{{
; Cursor {{{
!^h::Send,{Left}
!^j::Send,{Down}
!^k::Send,{Up}
!^l::Send,{Right}
; }}} Cursor

; Mouse {{{
; Mouse Move
!^y::MouseMove, -10, 0, 0, R
!^u::MouseMove, 0, 10, 0, R
!^i::MouseMove, 0, -10, 0, R
!^o::MouseMove, 10, 0, 0, R

; Click
!^n::MouseClick, Left
!^p::MouseClick, Right
; Right click on current window

; Mouse wheel
!^m::MouseClick, WheelDown,,,  2
!^,::MouseClick, WheelUp,,,  2
; }}} Mouse

; Window move {{{
^+y::
  WinGetPos, X, Y, , , A ;A for Active Window
  ;Msgbox, Pos At %X% %Y%
  WinMove, A, ,X-20, Y,
  ;Msgbox, Moved At %X%-20 %Y%
  Return ; Necessary for mapping which has at least 2 commands
^+u::
  WinGetPos, X, Y, , , A
  WinMove, A, ,X, Y+20
  Return
^+i::
  WinGetPos, X, Y, , , A
  WinMove, A, ,X, Y-20
  Return
^+o::
  WinGetPos, X, Y, , , A
  WinMove, A, ,X+20, Y
  Return
; }}} Window move

; Window size {{{
^!Enter::
  ;WinGetPos, X, Y, W, H, Program Manager ; Full Desktop
  ;Msgbox, Pos At %X% %Y% %W% %H%
  SysGet, MWA, MonitorWorkArea ; w/o Taskbar
  ;Msgbox, %MWALeft% %MWATop% %MWARight% %MWABottom%
  WinMove, A, ,MWALeft+LMargin, MWATop+TMargin
    , MWARight-MWALeft-LMargin-RMargin
    , MWABottom-MWATop-TMargin-BMargin
  Return
^!+Enter::
  ;WinGetPos, X, Y, W, H, Program Manager ; Full Desktop
  ;Msgbox, Pos At %X% %Y% %W% %H%
  SysGet, MWA, MonitorWorkArea ; w/o Taskbar
  ;Msgbox, %MWALeft% %MWATop% %MWARight% %MWABottom%
  WinMove, A, ,MWALeft+LMargin, MWATop+TMargin
    , (MWARight-MWALeft-LMargin-RMargin)*minsize
    , (MWABottom-MWATop-TMargin-BMargin)*minsize
  Return
; }}} Window size
; }}} Cursor, Mouse, Window move
; }}} Global Settings

; Tips {{{
; #: win
; !: alt
; ^: ctrl
; +: shift
; &: and
; <: only left, >: only right
; *: wildecard
; ~: pass through
; }}}

; Auto-execute section {{{
; Auto execute section is the region before any return/hotkey

; Windows size
TMargin=5
BMargin=5
LMargin=5
RMargin=155 ; sidebar = 150px
MinSize=0.7

; For Terminal/Vim
GroupAdd Terminal, ahk_class PuTTY
GroupAdd Terminal, ahk_class mintty ; cygwin
GroupAdd TerminalVim, ahk_group Terminal
GroupAdd TerminalVim, ahk_class Vim

#Include  %A_ScriptDir%\vim.ahk

Return
; }}}

; Basic Settings, HotKeys, Functions {{{
; Settings

#UseHook On ; Make it a bit slow, but can avoid infinitude loop
            ; Same as "$" for each hotkey
#InstallKeybdHook ; For checking key history
                  ; Use ~500kB memory?

#HotkeyInterval 2000 ; Hotkey inteval (default 2000 milliseconds).
#MaxHotkeysPerInterval 70 ; Max hotkeys perinterval (default 50).

; For HHK
;vkFFsc079::RAlt
;vkFFsc07b::LAlt
vkFFsc079::RCtrl
vkFFsc07b::LCtrl

;; Ref for IME: http://www6.atwiki.jp/eamat/pages/17.html
;; Get IME Status. 0: Off, 1: On
;IME_GET(WinTitle="A")  {
;  ControlGet,hwnd,HWND,,,%WinTitle%
;  if (WinActive(WinTitle)) {
;    ptrSize := !A_PtrSize ? 4 : A_PtrSize
;    VarSetCapacity(stGTI, cbSize:=4+4+(PtrSize*6)+16, 0)
;    NumPut(cbSize, stGTI,  0, "UInt")   ;   DWORD   cbSize;
;    hwnd := DllCall("GetGUIThreadInfo", Uint,0, Uint,&stGTI)
;        ? NumGet(stGTI,8+PtrSize,"UInt") : hwnd
;  }
;
;  Return DllCall("SendMessage"
;      , UInt, DllCall("imm32\ImmGetDefaultIMEWnd", Uint,hwnd)
;      , UInt, 0x0283  ;Message : WM_IME_CONTROL
;      ,  Int, 0x0005  ;wParam  : IMC_GETOPENSTATUS
;      ,  Int, 0)      ;lParam  : 0
;}
;; Get input status. 1: Converting, 2: Have converting window, 0: Others
;IME_GetConverting(WinTitle="A",ConvCls="",CandCls="") {
;  ; Input windows, candidate windows (Add new IME with "|")
;  ConvCls .= (ConvCls ? "|" : "")                 ;--- Input Window ---
;    .  "ATOK\d+CompStr"                           ; ATOK
;    .  "|imejpstcnv\d+"                           ; MS-IME
;    .  "|WXGIMEConv"                              ; WXG
;    .  "|SKKIME\d+\.*\d+UCompStr"                 ; SKKIME Unicode
;    .  "|MSCTFIME Composition"                    ; Google IME
;  CandCls .= (CandCls ? "|" : "")                 ;--- Candidate Window ---
;    .  "ATOK\d+Cand"                              ; ATOK
;    .  "|imejpstCandList\d+|imejpstcand\d+"       ; MS-IME 2002(8.1)XP
;    .  "|mscandui\d+\.candidate"                  ; MS Office IME-2007
;    .  "|WXGIMECand"                              ; WXG
;    .  "|SKKIME\d+\.*\d+UCand"                    ; SKKIME Unicode
; CandGCls := "GoogleJapaneseInputCandidateWindow" ; Google IME
;
;  ControlGet,hwnd,HWND,,,%WinTitle%
;  if (WinActive(WinTitle)) {
;    ptrSize := !A_PtrSize ? 4 : A_PtrSize
;    VarSetCapacity(stGTI, cbSize:=4+4+(PtrSize*6)+16, 0)
;    NumPut(cbSize, stGTI,  0, "UInt")   ;   DWORD   cbSize;
;    hwnd := DllCall("GetGUIThreadInfo", Uint,0, Uint,&stGTI)
;      ? NumGet(stGTI,8+PtrSize,"UInt") : hwnd
;  }
;
;  WinGet, pid, PID,% "ahk_id " hwnd
;  tmm:=A_TitleMatchMode
;  SetTitleMatchMode, RegEx
;  ret := WinExist("ahk_class " . CandCls . " ahk_pid " pid) ? 2
;      :  WinExist("ahk_class " . CandGCls                 ) ? 2
;      :  WinExist("ahk_class " . ConvCls . " ahk_pid " pid) ? 1
;      :  0
;  SetTitleMatchMode, %tmm%
;  Return ret
;}
;; Set IME, SetSts=0: Off, 1: On, return 0 for success, others for non-success
;IME_SET(SetSts=0, WinTitle="A")    {
;  ControlGet,hwnd,HWND,,,%WinTitle%
;  if(WinActive(WinTitle)){
;    ptrSize := !A_PtrSize ? 4 : A_PtrSize
;    VarSetCapacity(stGTI, cbSize:=4+4+(PtrSize*6)+16, 0)
;    NumPut(cbSize, stGTI,  0, "UInt")   ;   DWORD   cbSize;
;    hwnd := DllCall("GetGUIThreadInfo", Uint,0, Uint,&stGTI)
;        ? NumGet(stGTI,8+PtrSize,"UInt") : hwnd
;  }
;
;  Return DllCall("SendMessage"
;    , UInt, DllCall("imm32\ImmGetDefaultIMEWnd", Uint,hwnd)
;    , UInt, 0x0283  ;Message : WM_IME_CONTROL
;    ,  Int, 0x006   ;wParam  : IMC_SETOPENSTATUS
;    ,  Int, SetSts) ;lParam  : 0 or 1
;}

; }}}

; Terminal/Vim {{{
; ESC + IME
#IfWInActive, ahk_group TerminalVim
Esc:: ; Just send Esc at converting.
  if (VIM_IME_GET(A)) {
    if (VIM_IME_GetConverting(A)) {
      Send,{Esc}
    } else {
      VIM_IME_SET()
    }
  } else {
    Send,{Esc}
  }
  Return
^[:: ; Go to Normal mode (for vim) with IME off even at converting.
  if (VIM_IME_GET(A)) {
    Send,{Esc}
    Sleep 1 ; wait 1 ms (Need to stop converting)
    VIM_IME_SET()
    Send,{Esc}
  } else {
    Send,{Esc}
  }
  Return
#IfWInActive

; Paste
#IfWInActive, ahk_group Terminal
!v::
  StringSplit, strout, clipboard, `n
  If(strout0>1 or InStr(clipboard, "sudo")>0) {
    MsgBox, 308, Clipboard, %clipboard%`n`n Do you want to paste?
    IfMsgBox, No
    {
      Return
    }
  }
  Sleep,200
  MouseClick, Right, 50, 50, 1
  Return
#IfWInActive
#IfWInActive, ahk_class Vim
!v::Send,{Alt}ep
#IfWInActive

; Other than Terminal/Vim
#IfWInNotActive, ahk_group TerminalVim
^[::Send,{Esc}             ; Always C-[ to ESC, like vim
#IfWInNotActive
; }}} Terminal/Vim

; Power Point {{{
#IfWInActive, ahk_class PP12FrameClass
; Select one character
^Space::Send,{Right}+{Left}

; Subscript/Superscript
^=::Send,^tb{Enter}
^+=::Send,^tp{Enter}
; For JP keyboards
;^-::Send,^tb{Enter}
;^+-::Send,^tp{Enter}

; Fonts
^+s::Send,^tfsymbol{Enter}
^+a::Send,^tfarial{Enter}
^+h::Send,^tfhelvetica{Enter}
#IfWInActive
; }}} Power Point

; Word {{{
#IfWInActive, ahk_class OpusApp
^Space::Send,{Right}+{Left}
^=::Send,^tb{Enter}
^+=::Send,^tp{Enter}
; for JP keyboards
;^-::Send,^tb{Enter}
;^+-::Send,^tp{Enter}
#IfWInActive
; }}} Word

; Explorer {{{
#IfWInActive, ahk_class CabinetWClass
; Next/Previous page
^i::Send,!{Right}
^o::Send,!{Left}
#IfWInActive
; }}} Explorer

; CLCL {{{
;#IfWInActive, ahk_class CLCLMain
#IfWInActive, CLCL ; both window/title do not working...
j::
  Msgbox, clcl_down
  Send,{Down}
  Return
K::Send,{Up}
#IfWInActive
; }}} Explorer

; Everthing {{{
#IfWInActive, ahk_class EVERYTHING
Enter::
  Send,{Enter}
  Sleep,200
  IfWinActive, ahk_class EVERYTHING
  {
    Send,{Enter}
    Sleep,200
  }
  WinActivate, ahk_class EVERYTHING
  Sleep,100
  Send,{Esc}
  Return
#IfWInActive
; }}} Everything

; Command Prompt {{{
#IfWinActive ahk_class ConsoleWindowClass
^v::
  SendInput %clipboard%
  Return
#IfWInActive
; }}} Command Prompt

; Global Settings {{{
#if
; Basic Settings {{{

; Suspend
;Esc & Tab::
;  Suspend, Toggle
;  Return
; For Alt-Ctrl Swap (swapped by KeySwap)
LCtrl & Tab::AltTab
Alt & Tab::
  if GetKeyState("Shift","P") {
    Send,^+{taB} ; dosen't work ()
  }else{
    Send,^{Tab}
  }
  Return
;!m::Send,^m
;^m::Send,!m
^m::Send,!m
Ctrl & Left::Send,!{Left}
Ctrl & Right::Send,!{Right}

; Other basic settings
!Space::Send,{vkF3sc029}   ; IME by A-Space
^Space::Send,{vkF3sc029}   ; IME by C-Space
; {vkF3sc029}              ; 変換
; {vk1Dsc07B}              ; 無変換
^h::Send,{BS}              ; Always BS with C-h
!a::Send,^{Space}n        ; Minimize window
!4::Send,!{F4}             ; Close window
^4::Send,!{F4}             ; Close window
!d::Send,{Del}             ; Always Delete with A-d
;^o::Send,!{Left}           ; Go to previous page
;^i::Send,!{Right}          ; Go to nexe page
^Space::!`                 ; IME

; For HHK
; ESC to ` like normal keyboard (ESC is placed on the left of 1 in HHK)
!1::!`                ; IME
; }}} Basic Settings

; Cursor, Mouse, Window move/size {{{
; Cursor {{{
!^h::Send,{Left}
!^j::Send,{Down}
!^k::Send,{Up}
!^l::Send,{Right}
; }}} Cursor

; Mouse {{{
; Mouse Move
!^y::MouseMove, -10, 0, 0, R
!^u::MouseMove, 0, 10, 0, R
!^i::MouseMove, 0, -10, 0, R
!^o::MouseMove, 10, 0, 0, R

; Click
!^n::MouseClick, Left
!^p::MouseClick, Right
; Right click on current window

; Mouse wheel
!^m::MouseClick, WheelDown,,,  2
!^,::MouseClick, WheelUp,,,  2
; }}} Mouse

; Window move {{{
^+y::
  WinGetPos, X, Y, , , A ;A for Active Window
  ;Msgbox, Pos At %X% %Y%
  WinMove, A, ,X-20, Y,
  ;Msgbox, Moved At %X%-20 %Y%
  Return ; Necessary for mapping which has at least 2 commands
^+u::
  WinGetPos, X, Y, , , A
  WinMove, A, ,X, Y+20
  Return
^+i::
  WinGetPos, X, Y, , , A
  WinMove, A, ,X, Y-20
  Return
^+o::
  WinGetPos, X, Y, , , A
  WinMove, A, ,X+20, Y
  Return
; }}} Window move

; Window size {{{
^!Enter::
  ;WinGetPos, X, Y, W, H, Program Manager ; Full Desktop
  ;Msgbox, Pos At %X% %Y% %W% %H%
  SysGet, MWA, MonitorWorkArea ; w/o Taskbar
  ;Msgbox, %MWALeft% %MWATop% %MWARight% %MWABottom%
  WinMove, A, ,MWALeft+LMargin, MWATop+TMargin
    , MWARight-MWALeft-LMargin-RMargin
    , MWABottom-MWATop-TMargin-BMargin
  Return
^!+Enter::
  ;WinGetPos, X, Y, W, H, Program Manager ; Full Desktop
  ;Msgbox, Pos At %X% %Y% %W% %H%
  SysGet, MWA, MonitorWorkArea ; w/o Taskbar
  ;Msgbox, %MWALeft% %MWATop% %MWARight% %MWABottom%
  WinMove, A, ,MWALeft+LMargin, MWATop+TMargin
    , (MWARight-MWALeft-LMargin-RMargin)*minsize
    , (MWABottom-MWATop-TMargin-BMargin)*minsize
  Return
; }}} Window size
; }}} Cursor, Mouse, Window move
; }}} Global Settings


shift space for _

shift space for _

#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::RemoteLogin()
#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
#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)
;}

RemoteLogin()
{
    global Home, Work
    if Home
    {
        Run C:\cygwin64\bin\mintty.exe -w max -i /Cygwin-Terminal.ico /usr/bin/ssh chris@fe80::a00:27ff:fe7d:51d1
    }
    if Work
    {
        SetWinDelay 10
        Run C:\cygwin64\bin\mintty.exe -w max -i /Cygwin-Terminal.ico --title mintty /usr/bin/ssh cwatrous@t14hstbuild04
        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::RemoteLogin()
#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
#z::Run Firefox
#]::WinMinimize A

; 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)
;}

RemoteLogin()
{
    global Home, Work
    if Home
    {
        Run C:\cygwin64\bin\mintty.exe -w max -i /Cygwin-Terminal.ico /usr/bin/ssh chris@fe80::a00:27ff:fe7d:51d1
    }
    if Work
    {
        SetWinDelay 10
        Run C:\cygwin64\bin\mintty.exe -w max -i /Cygwin-Terminal.ico --title mintty /usr/bin/ssh cwatrous@t14hstbuild04
        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}
}


yet another bugfix. m & k work with numerals now.

; AutoHotkey Version: 1.1x
; Language:       English
; Author:         8thSeaOfRhye
;
;                     #####         Parent2Gem.ahk - Version 2       #####
;
;                     ##### Description of Purpose and Functionality #####
;
; ###            General             ###
; This script translates a String containing the Parenthesis-( i.e. Bracket-)Version of
; a speccing or combining scheme for gemcraft into actual commands for the gems creation.
; Works best in a STANDALONE FLASHPLAYER set to FULLSCREEN.
; It is hopefully easy to use and customize.
; The section which has to be changed is almost right at the top of the following code,
; namely under the command "!C::", and is commented to indicate the exact usage.
;
; The STANDARD HOTKEY is  Alt + c (No shift!!). This corresponds to "!C".
; Check ahkscript.org for Hotkey usage.
;
; CombiningMode is turned on by default. Speccing still works. Suggestion: Don't turn it off...
;
;
; ###  Syntax for the Bracket-Formula ###
;
; Obviously:
; 		r = Red / b = Black / o = orange / y = yellow / w = white
;
; Maybe a little less obviously:
;
;		g / k = copy of gem in the BOTTOM-LEFT! corner of the 12*3 craftingfield
;
; Furthermore:   ### New Features ###
;
;		the numerals 2 to 9 followed by any of the above = Corresponding color (or duplicate, respectively), upgraded 1 to 8 times
;
;		Examples: 9o / 2g = Orange upgraded 8 times (grade 9) / Base-gem (BottomLeft corner) upgraded once
;		(Needless to say, the upgrading happens via the "u"-button.)
;
; And:
;
;		a / s / d  =  use (left / middle / right) gem in the top row of the 3*12 craftingfield
;
;		(The order is inspired by the position of the keys on a standard keyboard.
;		 Attention: Those three can't be used in combination with numerals.)

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
;
;
;
;

!C::
;             I
; #####      V V       																					 #########
; #####       V        INSERT THE SCHEME TO BE COMBINED INBETWEEN THE QUTATION-MARKS IN THE LINE BELOW   #########
ParentStr := "(((((((g+g)+(g+g))+((g+g)+(g+g)))+(((g+g)+(g+g))+((g+g)+(g+g))))+((((g+g)+(g+g))+((g+g)+(g+g)))+(((g+g)+(g+g))+((g+g)+(g+(g+(g+(g+g))))))))+(((((g+g)+(g+g))+((g+g)+(g+g)))+(((g+g)+(g+g))+((g+g)+(g+(g+(g+(g+g)))))))+((((g+g)+(g+g))+((g+g)+(g+(g+(g+(g+g))))))+(((g+g)+(g+(g+(g+(g+g)))))+((g+(g+(g+g)))+((g+(g+g))+((g+g)+((g+g)+(g+(g+(g+(g+g))))))))))))+((((((g+g)+(g+g))+((g+g)+(g+g)))+(((g+g)+(g+g))+((g+g)+(g+(g+(g+(g+g)))))))+((((g+g)+(g+g))+((g+g)+(g+(g+(g+(g+g))))))+(((g+g)+(g+(g+(g+(g+g)))))+((g+(g+(g+g)))+((g+(g+g))+((g+g)+((g+g)+(g+(g+(g+(g+g)))))))))))+(((((g+g)+(g+g))+((g+g)+(g+(g+(g+(g+g))))))+(((g+g)+(g+(g+(g+(g+g)))))+((g+(g+(g+g)))+((g+(g+g))+((g+g)+((g+g)+(g+(g+(g+(g+g))))))))))+((((g+g)+(g+(g+(g+(g+g)))))+((g+(g+(g+g)))+((g+(g+g))+((g+g)+((g+g)+(g+(g+(g+(g+g)))))))))+(((g+(g+(g+g)))+((g+(g+g))+((g+g)+(g+(g+(g+(g+g)))))))+(((g+(g+g))+((g+g)+(g+(g+(g+(g+(g+g)))))))+(((g+g)+((g+g)+(g+(g+(g+(g+g))))))+((g+(g+(g+(g+(g+g)))))+((g+(g+(g+g)))+((g+(g+g))+((g+(g+g))+((g+g)+(g+(g+(g+(g+(g+g)))))))))))))))))"

; #####   						The default example is some random 1024 combine							 #########

CombineMode := True
LastGemPos := 1

TopLeftCornerX := 1127 				;  ####### ENTER THE COORDINATES OF THE 3*12 CRAFTINGFIELD ON YOUR SCREEN #########
TopLeftCornerY := 175 				;	###### If you don't know how to obtain those values, you'd better  ########
BottomRightCornerX := 1234 			;    ##### ask somebody. They don't have to be really precise.     #######
BottomRightCornerY := 602 			;	  #### AND THAT'S IT! The script should work for you now!  ######

FieldWidth := (BottomRightCornerX - TopLeftCornerX) / 3
FieldHeight := (BottomRightCornerY - TopLeftCornerY) / 12
CraftingField := [BottomRightCornerX -(FieldWidth / 2), BottomRightCornerY -(FieldHeight / 2)]

SetDefaultMouseSpeed, 0
i := 0
j := 0
StkCount := 1
initPos := [TopLeftCornerX + (FieldWidth / 2), BottomRightCornerY - (FieldHeight * 1.5)]
StackFields := []
While i < 12
{
	while j < 3
	{
		StackFields[StkCount, 1] := initPos[1] + (j * FieldWidth)
		StackFields[StkCount, 2] := initPos[2] - (i * FieldHeight)
		StkCount := StkCount + 1
		j := j + 1
	}
	j := 0
	i := i + 1
}

; For FieldNum, FieldValue in StackFields
;	MsgBox % " Coordinates of Stack-Field #" . FieldNum .  ": " . FieldValue[1] . FieldValue[2]

CurrentStk := 0
WGem() {
	global CraftingField
	Send {Numpad9}
	MouseClick, left, CraftingField[1], CraftingField[2]
}
OGem() {
	global CraftingField
	Send {Numpad7}
	MouseClick, left, CraftingField[1], CraftingField[2]
}
YGem() {
	global CraftingField
	Send {Numpad8}
	MouseClick, left, CraftingField[1], CraftingField[2]
}
BGem() {
	global CraftingField
	Send {Numpad1}
	MouseClick, left, CraftingField[1], CraftingField[2]
}
RGem() {
	global CraftingField
	Send {Numpad4}
	MouseClick, left, CraftingField[1], CraftingField[2]
}

GGem() {
	global CraftingField
	global FieldWidth
	MouseMove, CraftingField[1]-(2*FieldWidth), CraftingField[2]
	send d
}

AddtoStk() {
	global CraftingField
	global CurrentStk
	global StackFields
	if CurrentStk != 0
		{
		Send g
		MouseClickDrag, L, CraftingField[1], CraftingField[2], StackFields[CurrentStk][1], StackFields[CurrentStk][2]
		}
}

MovetoStk() {
	global CraftingField
	global CurrentStk
	global StackFields
	CurrentStk := CurrentStk + 1
	MouseClickDrag, L, CraftingField[1], CraftingField[2], StackFields[CurrentStk][1], StackFields[CurrentStk][2]
}

PopStk() {
	global CraftingField
	global CurrentStk
	global StackFields
	if CurrentStk > 1
		{
		Send g
		MouseClickDrag, L, StackFields[CurrentStk][1], StackFields[CurrentStk][2], StackFields[CurrentStk - 1][1], StackFields[CurrentStk - 1][2]
		CurrentStk := CurrentStk - 1
		}
}

if (CombineMode = True) {
	StrPosEnd := StrLen(ParentStr)
	ElementFound := False
	While ElementFound = False {
		if (SubStr(ParentStr, StrPosEnd, 1) != ")") {
			ElementFound := True
			LastGemPos := StrPosEnd
		}
		StrPosEnd := StrPosEnd - 1
	}
}

StrPos := 1
Parents := []

While StrPos < StrLen(ParentStr) {
	if (SubStr(ParentStr, StrPos, 1) = "(") {
		if ((SubStr(ParentStr, StrPos - 1, 1) = "(") or (StrPos = 1))
			Parents.Insert(False)
		else
			Parents.Insert(True)
	}

	if (SubStr(ParentStr, StrPos, 1) = ")") {
		if (Parents[Parents.MaxIndex()] = True)
			PopStk()
		Parents.remove(Parents.MaxIndex())
	}

	if (SubStr(ParentStr, StrPos, 1) = "w") {
		WGem()
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
	}

	if (SubStr(ParentStr, StrPos, 1) = "o") {
		OGem()
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
	}

	if (SubStr(ParentStr, StrPos, 1) = "r") {
		RGem()
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
	}

	if (SubStr(ParentStr, StrPos, 1) = "b") {
		BGem()
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
	}

	if (SubStr(ParentStr, StrPos, 1) = "y") {
		YGem()
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
	}

	if ((SubStr(ParentStr, StrPos, 1) = "g") or (SubStr(ParentStr, StrPos, 1) = "k") or (SubStr(ParentStr, StrPos, 1) = "m")) {
		if (LastGemPos != StrPos)
			GGem()
		else
			MouseClickDrag, L, CraftingField[1]-(2*FieldWidth), CraftingField[2], CraftingField[1], CraftingField[2]
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
	}

	if ((SubStr(ParentStr, StrPos, 1) < 10) and (SubStr(ParentStr, StrPos, 1) > 1)) {
		if (SubStr(ParentStr, StrPos + 1, 1) = "w")
			WGem()
		if (SubStr(ParentStr, StrPos + 1, 1) = "o")
			OGem()
		if (SubStr(ParentStr, StrPos + 1, 1) = "y")
			YGem()
		if (SubStr(ParentStr, StrPos + 1, 1) = "b")
			BGem()
		if (SubStr(ParentStr, StrPos + 1, 1) = "r")
			RGem()
		if ((SubStr(ParentStr, StrPos + 1, 1) = "g")  or (SubStr(ParentStr, StrPos, 1) = "k") or (SubStr(ParentStr, StrPos, 1) = "m")) {
			if (LastGemPos != StrPos + 1)
				GGem()
			else
				MouseClickDrag, L, CraftingField[1]-(2*FieldWidth), CraftingField[2], CraftingField[1], CraftingField[2]
		}
		UCount := 1
		While UCount <= SubStr(ParentStr, StrPos + 1, 1) {
			MouseMove, CraftingField[1], CraftingField[2]
			send u
			UCount := UCount + 1
		}

		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
		StrPos := StrPos + 1
	}

	if (SubStr(ParentStr, StrPos, 1) = "a") {
		MouseClickDrag, L, TopLeftCornerX + (FieldWidth / 2), TopLeftCornerY + (FieldHeight / 2), CraftingField[1], CraftingField[2]
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()

	}
	if (SubStr(ParentStr, StrPos, 1) = "s") {
		MouseClickDrag, L, TopLeftCornerX + (FieldWidth * 1.5), TopLeftCornerY + (FieldHeight / 2), CraftingField[1], CraftingField[2]
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()

	}
	if (SubStr(ParentStr, StrPos, 1) = "d") {
		MouseClickDrag, L, TopLeftCornerX + (FieldWidth * 2.5), TopLeftCornerY + (FieldHeight / 2), CraftingField[1], CraftingField[2]
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()

	}
	StrPos := StrPos + 1
}
Return

; AutoHotkey Version: 1.1x
; Language:       English
; Author:         8thSeaOfRhye
;
;                     #####         Parent2Gem.ahk - Version 2       #####
;
;                     ##### Description of Purpose and Functionality #####
;
; ###            General             ###
; This script translates a String containing the Parenthesis-( i.e. Bracket-)Version of
; a speccing or combining scheme for gemcraft into actual commands for the gems creation.
; Works best in a STANDALONE FLASHPLAYER set to FULLSCREEN.
; It is hopefully easy to use and customize.
; The section which has to be changed is almost right at the top of the following code,
; namely under the command "!C::", and is commented to indicate the exact usage.
;
; The STANDARD HOTKEY is  Alt + c (No shift!!). This corresponds to "!C".
; Check ahkscript.org for Hotkey usage.
;
; CombiningMode is turned on by default. Speccing still works. Suggestion: Don't turn it off...
;
;
; ###  Syntax for the Bracket-Formula ###
;
; Obviously:
; 		r = Red / b = Black / o = orange / y = yellow / w = white
;
; Maybe a little less obviously:
;
;		g / k = copy of gem in the BOTTOM-LEFT! corner of the 12*3 craftingfield
;
; Furthermore:   ### New Features ###
;
;		the numerals 2 to 9 followed by any of the above = Corresponding color (or duplicate, respectively), upgraded 1 to 8 times
;
;		Examples: 9o / 2g = Orange upgraded 8 times (grade 9) / Base-gem (BottomLeft corner) upgraded once
;		(Needless to say, the upgrading happens via the "u"-button.)
;
; And:
;
;		a / s / d  =  use (left / middle / right) gem in the top row of the 3*12 craftingfield
;
;		(The order is inspired by the position of the keys on a standard keyboard.
;		 Attention: Those three can't be used in combination with numerals.)

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
;
;
;
;

!C::
;             I
; #####      V V       																					 #########
; #####       V        INSERT THE SCHEME TO BE COMBINED INBETWEEN THE QUTATION-MARKS IN THE LINE BELOW   #########
ParentStr := "(((((((g+g)+(g+g))+((g+g)+(g+g)))+(((g+g)+(g+g))+((g+g)+(g+g))))+((((g+g)+(g+g))+((g+g)+(g+g)))+(((g+g)+(g+g))+((g+g)+(g+(g+(g+(g+g))))))))+(((((g+g)+(g+g))+((g+g)+(g+g)))+(((g+g)+(g+g))+((g+g)+(g+(g+(g+(g+g)))))))+((((g+g)+(g+g))+((g+g)+(g+(g+(g+(g+g))))))+(((g+g)+(g+(g+(g+(g+g)))))+((g+(g+(g+g)))+((g+(g+g))+((g+g)+((g+g)+(g+(g+(g+(g+g))))))))))))+((((((g+g)+(g+g))+((g+g)+(g+g)))+(((g+g)+(g+g))+((g+g)+(g+(g+(g+(g+g)))))))+((((g+g)+(g+g))+((g+g)+(g+(g+(g+(g+g))))))+(((g+g)+(g+(g+(g+(g+g)))))+((g+(g+(g+g)))+((g+(g+g))+((g+g)+((g+g)+(g+(g+(g+(g+g)))))))))))+(((((g+g)+(g+g))+((g+g)+(g+(g+(g+(g+g))))))+(((g+g)+(g+(g+(g+(g+g)))))+((g+(g+(g+g)))+((g+(g+g))+((g+g)+((g+g)+(g+(g+(g+(g+g))))))))))+((((g+g)+(g+(g+(g+(g+g)))))+((g+(g+(g+g)))+((g+(g+g))+((g+g)+((g+g)+(g+(g+(g+(g+g)))))))))+(((g+(g+(g+g)))+((g+(g+g))+((g+g)+(g+(g+(g+(g+g)))))))+(((g+(g+g))+((g+g)+(g+(g+(g+(g+(g+g)))))))+(((g+g)+((g+g)+(g+(g+(g+(g+g))))))+((g+(g+(g+(g+(g+g)))))+((g+(g+(g+g)))+((g+(g+g))+((g+(g+g))+((g+g)+(g+(g+(g+(g+(g+g)))))))))))))))))"

; #####   						The default example is some random 1024 combine							 #########

CombineMode := True
LastGemPos := 1

TopLeftCornerX := 1127 				;  ####### ENTER THE COORDINATES OF THE 3*12 CRAFTINGFIELD ON YOUR SCREEN #########
TopLeftCornerY := 175 				;	###### If you don't know how to obtain those values, you'd better  ########
BottomRightCornerX := 1234 			;    ##### ask somebody. They don't have to be really precise.     #######
BottomRightCornerY := 602 			;	  #### AND THAT'S IT! The script should work for you now!  ######

FieldWidth := (BottomRightCornerX - TopLeftCornerX) / 3
FieldHeight := (BottomRightCornerY - TopLeftCornerY) / 12
CraftingField := [BottomRightCornerX -(FieldWidth / 2), BottomRightCornerY -(FieldHeight / 2)]

SetDefaultMouseSpeed, 0
i := 0
j := 0
StkCount := 1
initPos := [TopLeftCornerX + (FieldWidth / 2), BottomRightCornerY - (FieldHeight * 1.5)]
StackFields := []
While i < 12
{
	while j < 3
	{
		StackFields[StkCount, 1] := initPos[1] + (j * FieldWidth)
		StackFields[StkCount, 2] := initPos[2] - (i * FieldHeight)
		StkCount := StkCount + 1
		j := j + 1
	}
	j := 0
	i := i + 1
}

; For FieldNum, FieldValue in StackFields
;	MsgBox % " Coordinates of Stack-Field #" . FieldNum .  ": " . FieldValue[1] . FieldValue[2]

CurrentStk := 0
WGem() {
	global CraftingField
	Send {Numpad9}
	MouseClick, left, CraftingField[1], CraftingField[2]
}
OGem() {
	global CraftingField
	Send {Numpad7}
	MouseClick, left, CraftingField[1], CraftingField[2]
}
YGem() {
	global CraftingField
	Send {Numpad8}
	MouseClick, left, CraftingField[1], CraftingField[2]
}
BGem() {
	global CraftingField
	Send {Numpad1}
	MouseClick, left, CraftingField[1], CraftingField[2]
}
RGem() {
	global CraftingField
	Send {Numpad4}
	MouseClick, left, CraftingField[1], CraftingField[2]
}

GGem() {
	global CraftingField
	global FieldWidth
	MouseMove, CraftingField[1]-(2*FieldWidth), CraftingField[2]
	send d
}

AddtoStk() {
	global CraftingField
	global CurrentStk
	global StackFields
	if CurrentStk != 0
		{
		Send g
		MouseClickDrag, L, CraftingField[1], CraftingField[2], StackFields[CurrentStk][1], StackFields[CurrentStk][2]
		}
}

MovetoStk() {
	global CraftingField
	global CurrentStk
	global StackFields
	CurrentStk := CurrentStk + 1
	MouseClickDrag, L, CraftingField[1], CraftingField[2], StackFields[CurrentStk][1], StackFields[CurrentStk][2]
}

PopStk() {
	global CraftingField
	global CurrentStk
	global StackFields
	if CurrentStk > 1
		{
		Send g
		MouseClickDrag, L, StackFields[CurrentStk][1], StackFields[CurrentStk][2], StackFields[CurrentStk - 1][1], StackFields[CurrentStk - 1][2]
		CurrentStk := CurrentStk - 1
		}
}

if (CombineMode = True) {
	StrPosEnd := StrLen(ParentStr)
	ElementFound := False
	While ElementFound = False {
		if (SubStr(ParentStr, StrPosEnd, 1) != ")") {
			ElementFound := True
			LastGemPos := StrPosEnd
		}
		StrPosEnd := StrPosEnd - 1
	}
}

StrPos := 1
Parents := []

While StrPos < StrLen(ParentStr) {
	if (SubStr(ParentStr, StrPos, 1) = "(") {
		if ((SubStr(ParentStr, StrPos - 1, 1) = "(") or (StrPos = 1))
			Parents.Insert(False)
		else
			Parents.Insert(True)
	}

	if (SubStr(ParentStr, StrPos, 1) = ")") {
		if (Parents[Parents.MaxIndex()] = True)
			PopStk()
		Parents.remove(Parents.MaxIndex())
	}

	if (SubStr(ParentStr, StrPos, 1) = "w") {
		WGem()
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
	}

	if (SubStr(ParentStr, StrPos, 1) = "o") {
		OGem()
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
	}

	if (SubStr(ParentStr, StrPos, 1) = "r") {
		RGem()
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
	}

	if (SubStr(ParentStr, StrPos, 1) = "b") {
		BGem()
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
	}

	if (SubStr(ParentStr, StrPos, 1) = "y") {
		YGem()
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
	}

	if ((SubStr(ParentStr, StrPos, 1) = "g") or (SubStr(ParentStr, StrPos, 1) = "k") or (SubStr(ParentStr, StrPos, 1) = "m")) {
		if (LastGemPos != StrPos)
			GGem()
		else
			MouseClickDrag, L, CraftingField[1]-(2*FieldWidth), CraftingField[2], CraftingField[1], CraftingField[2]
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
	}

	if ((SubStr(ParentStr, StrPos, 1) < 10) and (SubStr(ParentStr, StrPos, 1) > 1)) {
		if (SubStr(ParentStr, StrPos + 1, 1) = "w")
			WGem()
		if (SubStr(ParentStr, StrPos + 1, 1) = "o")
			OGem()
		if (SubStr(ParentStr, StrPos + 1, 1) = "y")
			YGem()
		if (SubStr(ParentStr, StrPos + 1, 1) = "b")
			BGem()
		if (SubStr(ParentStr, StrPos + 1, 1) = "r")
			RGem()
		if (SubStr(ParentStr, StrPos + 1, 1) = "g") {
			if (LastGemPos != StrPos + 1)
				GGem()
			else
				MouseClickDrag, L, CraftingField[1]-(2*FieldWidth), CraftingField[2], CraftingField[1], CraftingField[2]
		}
		UCount := 1
		While UCount <= SubStr(ParentStr, StrPos + 1, 1) {
			MouseMove, CraftingField[1], CraftingField[2]
			send u
			UCount := UCount + 1
		}

		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()
		StrPos := StrPos + 1
	}

	if (SubStr(ParentStr, StrPos, 1) = "a") {
		MouseClickDrag, L, TopLeftCornerX + (FieldWidth / 2), TopLeftCornerY + (FieldHeight / 2), CraftingField[1], CraftingField[2]
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()

	}
	if (SubStr(ParentStr, StrPos, 1) = "s") {
		MouseClickDrag, L, TopLeftCornerX + (FieldWidth * 1.5), TopLeftCornerY + (FieldHeight / 2), CraftingField[1], CraftingField[2]
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()

	}
	if (SubStr(ParentStr, StrPos, 1) = "d") {
		MouseClickDrag, L, TopLeftCornerX + (FieldWidth * 2.5), TopLeftCornerY + (FieldHeight / 2), CraftingField[1], CraftingField[2]
		if (SubStr(ParentStr, StrPos - 1, 1) = "(")
			MovetoStk()
		else
			AddtoStk()

	}
	StrPos := StrPos + 1
}
Return


Force shutdown

Force shutdown

Force shutdown to close applications more quickly http://www.autohotkey.com/docs/commands/Shutdown.htm

#NoEnv
#SingleInstance, Force
SendMode, Input
SetWorkingDir, %A_ScriptDir%

FileInstall, veryseriousbutton-listener.ico, veryseriousbutton-listener.ico

Menu, Tray, Icon, veryseriousbutton-listener.ico
Menu, Tray, Tip, Very Serious Button

:*:285Hp1Py2N0Z6k6ow3XLb6ejY::
  Shutdown, 5
  return

#NoEnv
#SingleInstance, Force
SendMode, Input
SetWorkingDir, %A_ScriptDir%

FileInstall, veryseriousbutton-listener.ico, veryseriousbutton-listener.ico

Menu, Tray, Icon, veryseriousbutton-listener.ico
Menu, Tray, Tip, Very Serious Button

:*:285Hp1Py2N0Z6k6ow3XLb6ejY::
  Shutdown, 1
  return


cfg/ahk: remove unused shortcut

cfg/ahk: remove unused shortcut

;Control key Ctrl- ^
;Alt key Alt- !
;Shift key Shift- +
;Windows key Win- #

#Persistent
#SingleInstance Force

A_DetectHiddenWindows := true
A_DetectHiddenText := true
A_TitleMatchMode := "RegEx" ;match titles and classes using regular expressions
A_TitleMatchModeSpeed := "Slow" ;match titles and classes using regular expressions
A_CoordModeMouse := "Screen"
A_CoordModeToolTip := "Screen"

;detect cygwin
CygPath := "C:\Program Files (x86)\cygwin"
if !FileExist(CygPath) {
    CygPath := "C:\Cygwin"
}
If !FileExist(CygPath) {
    CygPath := "C:\Cygwin64"
}

;detect browser
BrowserPath := "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
if !FileExist(BrowserPath) {
    BrowserPath := "C:\Program Files\Mozilla Firefox\firefox.exe"
}
if !FileExist(BrowserPath) {
    BrowserPath := "C:\Users\rr-\AppData\Local\Google\Chrome\Application\chrome.exe"
}

;activate/run a program
FRun(window, path, folder)
{
    if !window || !WinExist(window) {
        Run(path, folder)
    } else {
        WinShow
        WinActivate
    }
    return
}

;fix URLs copied by some browsers so they're clickable in popular programs
ClipboardChanged(type)
{
    if (SubStr(clipboard, 1, 7) == "http://") || SubStr(clipboard, 1, 8) == "https://" {
        clipboard := StrReplace(clipboard, "[", "%5b", All)
        clipboard := StrReplace(clipboard, "\", "%5c", All)
        clipboard := StrReplace(clipboard, "]", "%5d", All)
    }
    return
}
OnClipboardChange("ClipboardChanged")

;enforce same keyboard layout across all programs
global Locale1 := 0x4150415
global Locale2 := 0x4110411
global CurrentLocale := Locale1

GetActiveLocale()
{
    win_id := WinGetID("A")
    thread_id := DllCall("GetWindowThreadProcessId", "Int", win_id, "Int", "0")
    return DllCall("GetKeyboardLayout", "Int", thread_id)
}

ApplyLocale(locale)
{
    global CurrentLocale := locale
    SendMessage(0x50, 0, locale, "", "A")
}

CycleLocale()
{
    if CurrentLocale == Locale1 {
        ApplyLocale(locale2)
    } else if CurrentLocale == Locale2 {
        ApplyLocale(Locale1)
    }
}

ShellMessage(wparam, lparam)
{
    title := WinGetTitle(lparam)
    if wParam == 4 { ;HSHELL_WINDOWACTIVATED
        ApplyLocale(CurrentLocale)
    }
}

gui := GuiCreate("", "")
gui.Opt("+LastFound")
hwnd := WinExist()
DllCall("RegisterShellHookWindow", uint, hwnd)
msgnum := DllCall("RegisterWindowMessage", str, "SHELLHOOK")
OnMessage(msgnum, "ShellMessage")

return

#If FileExist(CygPath)
    ;cygwin - activate/run
    #Enter::
    {
        Run(CygPath . "\\bin\\mintty.exe --title Terminal --class mintty_thetty --exec /bin/zsh -i -l", CygPath)
        return
    }
    +^![::
    {
        Run(CygPath . "\\bin\\mintty.exe --title Terminal --class mintty_thetty --exec /bin/zsh -i -l", CygPath)
        return
    }
    ^![::
    {
        if !WinExist("ahk_class mintty_thetty") {
            Run(CygPath . "\\bin\\mintty.exe --title Terminal --class mintty_thetty --exec /bin/zsh -i -l", CygPath)
            WinWait("ahk_class mintty_thetty")
        } else {
            WinShow
            WinActivate
        }
        return
    }

    ;ssh to cyclone - activate/run
    +^!]::
    {
        Run(CygPath . "\\bin\\mintty.exe --title 'Remote terminal' --class mintty_ssh --exec /bin/ssh cyclone", CygPath . "/bin")
        return
    }
    ^!]::
    {
        if !WinExist("ahk_class mintty_ssh") {
            Run(CygPath . "\\bin\\mintty.exe --title 'Remote terminal' --class mintty_ssh --exec /bin/ssh cyclone", CygPath . "/bin")
            WinWait("ahk_class mintty_ssh")
        } else {
            WinShow
            WinActivate
        }
        return
    }

    ;vifm - activate/run
    #e::
    {
        If WinExist("ahk_class Vifm") {
            WinShow
            WinActivate
        } else {
            Run(CygPath . "\\bin\\mintty.exe --window max --class Vifm --exec /bin/zsh -l -i -c vifm", CygPath . "/bin")
            WinWait("ahk_class Vifm")
        }
        return
    }

    ;vifm - just run
    +#e::
    {
        Run(CygPath . "\\bin\\mintty.exe --window max --class Vifm --exec /bin/zsh -l -i -c vifm", CygPath . "/bin")
        return
    }
#If

;browser
#If FileExist(BrowserPath)
    ;web browser - activate/run
    ^!;::
        if WinExist("Mozilla Firefox") {
            WinShow
            WinActivate
            ;Send("!d")
        } else if WinExist("Vimperator") {
            WinShow
            WinActivate
            ;Send("!d")
        } else if WinExist("ahk_class Chrome_WidgetWin_1") {
            WinActivate
            ControlFocus("Chrome_OmniboxView1")
            ;SendInput("{Home}+{End}")
        } else {
            if FileExist(BrowserPath) {
                Run(BrowserPath)
            }
        }
        return
#If

;adobe products
#IfWinActive ahk_group adobe
    ~LAlt::return
    LAlt UP::Send("{Escape}")
#IfWinActive
#IfWinActive ahk_class illustrator
+wheelup::
    Send("{Ctrl Down}{=}{Ctrl Up}")
    return
+wheeldown::
    Send("{Ctrl Down}-{Ctrl Up}")
    return
#IfWinActive

;close active window
#q::
{
    active_hwnd := WinExist("A")
    WinClose
    return
}

;fullscreen
#f::
{
    if WinGetMinMax("A") {
        WinRestore("A")
    } else {
        WinMaximize("A")
    }
    return
}

;restore active window
#s::
{
    active_hwnd := WinExist("A")
    PostMessage(0x112, 0xf120) ;WM_SYSCOMMAND, SC_RESTORE
    return
}

;minimize active window
#w::
{
    if WinActive("WTW$") {
        WinHide
    } else if WinActive("Buddy List") {
        WinHide
    } else {
        active_hwnd := WinExist("A")
        PostMessage(0x112, 0xF020) ;WM_SYSCOMMAND, SC_MINIMIZE
    }
    return
}

;set active window as always on top
#a::WinSetAlwaysOnTop("Toggle", "A")

;transparency
AddTransparency(delta)
{
    transparency := WinGetTransparent("A")
    if !transparency {
        transparency := 255
    }
    transparency := transparency + delta
    if transparency <= 10 {
        WinSetTransparent(10, "A")
    } else if Transparency >= 255 {
        WinSetTransparent(255, "A")
        WinSetTransparent("OFF", "A")
    } else {
        WinSetTransparent(transparency, "A")
    }
}
#WheelUp::AddTransparency(12)
#WheelDown::AddTransparency(-12)
#z::AddTransparency(-12)
+#z::AddTransparency(12)

;music
#x::Volume_Up
+#x::Volume_Down
#c::Media_Next
+#c::Media_Prev
#v::Media_Play_Pause

;screenshots
+#i::Run(CygPath . "\\bin\\zsh.exe -i -l -c 'shot -w -i --output=Z:/'", , Hide)
#i::Run(CygPath . "\\bin\\zsh.exe -i -l -c 'shot -i --output=Z:/'", , Hide)

;reload autohotkey
!F12::Reload

;linux-compatible useful keys
RAlt & -::Send(GetKeyState("Shift") ? "{U+2014}" : "{U+2013}")
RAlt & k::Send("{U+2026}")

;hepburn macrons
RAlt & =::
{
    key := Input("L1", "{delete}{esc}{home}{end}") ; pressing any of these will terminate the input
    if key == "A" {
        Send("{U+0100}")
    } else if key == "I" {
        Send("{U+012A}")
    } else if key == "U" {
        Send("{U+016A}")
    } else if key == "E" {
        Send("{U+0112}")
    } else if key == "O" {
        Send("{U+014C}")
    } else if key == "a" {
        Send("{U+0101}")
    } else if key == "i" {
        Send("{U+012B}")
    } else if key == "u" {
        Send("{U+016B}")
    } else if key == "e" {
        Send("{U+0113}")
    } else if key == "o" {
        Send("{U+014D}")
    }
     return
}

#n::
{
    CycleLocale()
}

;Control key Ctrl- ^
;Alt key Alt- !
;Shift key Shift- +
;Windows key Win- #

#Persistent
#SingleInstance Force

A_DetectHiddenWindows := true
A_DetectHiddenText := true
A_TitleMatchMode := "RegEx" ;match titles and classes using regular expressions
A_TitleMatchModeSpeed := "Slow" ;match titles and classes using regular expressions
A_CoordModeMouse := "Screen"
A_CoordModeToolTip := "Screen"

;detect cygwin
CygPath := "C:\Program Files (x86)\cygwin"
if !FileExist(CygPath) {
    CygPath := "C:\Cygwin"
}
If !FileExist(CygPath) {
    CygPath := "C:\Cygwin64"
}

;detect browser
BrowserPath := "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
if !FileExist(BrowserPath) {
    BrowserPath := "C:\Program Files\Mozilla Firefox\firefox.exe"
}
if !FileExist(BrowserPath) {
    BrowserPath := "C:\Users\rr-\AppData\Local\Google\Chrome\Application\chrome.exe"
}

;activate/run a program
FRun(window, path, folder)
{
    if !window || !WinExist(window) {
        Run(path, folder)
    } else {
        WinShow
        WinActivate
    }
    return
}

;fix URLs copied by some browsers so they're clickable in popular programs
ClipboardChanged(type)
{
    if (SubStr(clipboard, 1, 7) == "http://") || SubStr(clipboard, 1, 8) == "https://" {
        clipboard := StrReplace(clipboard, "[", "%5b", All)
        clipboard := StrReplace(clipboard, "\", "%5c", All)
        clipboard := StrReplace(clipboard, "]", "%5d", All)
    }
    return
}
OnClipboardChange("ClipboardChanged")

;enforce same keyboard layout across all programs
global Locale1 := 0x4150415
global Locale2 := 0x4110411
global CurrentLocale := Locale1

GetActiveLocale()
{
    win_id := WinGetID("A")
    thread_id := DllCall("GetWindowThreadProcessId", "Int", win_id, "Int", "0")
    return DllCall("GetKeyboardLayout", "Int", thread_id)
}

ApplyLocale(locale)
{
    global CurrentLocale := locale
    SendMessage(0x50, 0, locale, "", "A")
}

CycleLocale()
{
    if CurrentLocale == Locale1 {
        ApplyLocale(locale2)
    } else if CurrentLocale == Locale2 {
        ApplyLocale(Locale1)
    }
}

ShellMessage(wparam, lparam)
{
    title := WinGetTitle(lparam)
    if wParam == 4 { ;HSHELL_WINDOWACTIVATED
        ApplyLocale(CurrentLocale)
    }
}

gui := GuiCreate("", "")
gui.Opt("+LastFound")
hwnd := WinExist()
DllCall("RegisterShellHookWindow", uint, hwnd)
msgnum := DllCall("RegisterWindowMessage", str, "SHELLHOOK")
OnMessage(msgnum, "ShellMessage")

return

#If FileExist(CygPath)
    ;cygwin - activate/run
    #Enter::
    {
        Run(CygPath . "\\bin\\mintty.exe --title Terminal --class mintty_thetty --exec /bin/zsh -i -l", CygPath)
        return
    }
    +^![::
    {
        Run(CygPath . "\\bin\\mintty.exe --title Terminal --class mintty_thetty --exec /bin/zsh -i -l", CygPath)
        return
    }
    ^![::
    {
        if !WinExist("ahk_class mintty_thetty") {
            Run(CygPath . "\\bin\\mintty.exe --title Terminal --class mintty_thetty --exec /bin/zsh -i -l", CygPath)
            WinWait("ahk_class mintty_thetty")
        } else {
            WinShow
            WinActivate
        }
        return
    }

    ;ssh to cyclone - activate/run
    +^!]::
    {
        Run(CygPath . "\\bin\\mintty.exe --title 'Remote terminal' --class mintty_ssh --exec /bin/ssh cyclone", CygPath . "/bin")
        return
    }
    ^!]::
    {
        if !WinExist("ahk_class mintty_ssh") {
            Run(CygPath . "\\bin\\mintty.exe --title 'Remote terminal' --class mintty_ssh --exec /bin/ssh cyclone", CygPath . "/bin")
            WinWait("ahk_class mintty_ssh")
        } else {
            WinShow
            WinActivate
        }
        return
    }

    ;text editor - activate/run
    +^!N::
    {
        If WinExist("ahk_class Vim") {
            WinShow
            WinActivate
        } else {
            Run(CygPath . "\\bin\\mintty.exe --class Vim --exec /bin/zsh -l -i -c /bin/vim", CygPath . "/bin")
            WinWait("ahk_class Vim")
        }
        return
    }

    ;vifm - activate/run
    #e::
    {
        If WinExist("ahk_class Vifm") {
            WinShow
            WinActivate
        } else {
            Run(CygPath . "\\bin\\mintty.exe --window max --class Vifm --exec /bin/zsh -l -i -c vifm", CygPath . "/bin")
            WinWait("ahk_class Vifm")
        }
        return
    }

    ;vifm - just run
    +#e::
    {
        Run(CygPath . "\\bin\\mintty.exe --window max --class Vifm --exec /bin/zsh -l -i -c vifm", CygPath . "/bin")
        return
    }
#If

;browser
#If FileExist(BrowserPath)
    ;web browser - activate/run
    ^!;::
        if WinExist("Mozilla Firefox") {
            WinShow
            WinActivate
            ;Send("!d")
        } else if WinExist("Vimperator") {
            WinShow
            WinActivate
            ;Send("!d")
        } else if WinExist("ahk_class Chrome_WidgetWin_1") {
            WinActivate
            ControlFocus("Chrome_OmniboxView1")
            ;SendInput("{Home}+{End}")
        } else {
            if FileExist(BrowserPath) {
                Run(BrowserPath)
            }
        }
        return
#If

;adobe products
#IfWinActive ahk_group adobe
    ~LAlt::return
    LAlt UP::Send("{Escape}")
#IfWinActive
#IfWinActive ahk_class illustrator
+wheelup::
    Send("{Ctrl Down}{=}{Ctrl Up}")
    return
+wheeldown::
    Send("{Ctrl Down}-{Ctrl Up}")
    return
#IfWinActive

;close active window
#q::
{
    active_hwnd := WinExist("A")
    WinClose
    return
}

;fullscreen
#f::
{
    if WinGetMinMax("A") {
        WinRestore("A")
    } else {
        WinMaximize("A")
    }
    return
}

;restore active window
#s::
{
    active_hwnd := WinExist("A")
    PostMessage(0x112, 0xf120) ;WM_SYSCOMMAND, SC_RESTORE
    return
}

;minimize active window
#w::
{
    if WinActive("WTW$") {
        WinHide
    } else if WinActive("Buddy List") {
        WinHide
    } else {
        active_hwnd := WinExist("A")
        PostMessage(0x112, 0xF020) ;WM_SYSCOMMAND, SC_MINIMIZE
    }
    return
}

;set active window as always on top
#a::WinSetAlwaysOnTop("Toggle", "A")

;transparency
AddTransparency(delta)
{
    transparency := WinGetTransparent("A")
    if !transparency {
        transparency := 255
    }
    transparency := transparency + delta
    if transparency <= 10 {
        WinSetTransparent(10, "A")
    } else if Transparency >= 255 {
        WinSetTransparent(255, "A")
        WinSetTransparent("OFF", "A")
    } else {
        WinSetTransparent(transparency, "A")
    }
}
#WheelUp::AddTransparency(12)
#WheelDown::AddTransparency(-12)
#z::AddTransparency(-12)
+#z::AddTransparency(12)

;music
#x::Volume_Up
+#x::Volume_Down
#c::Media_Next
+#c::Media_Prev
#v::Media_Play_Pause

;screenshots
+#i::Run(CygPath . "\\bin\\zsh.exe -i -l -c 'shot -w -i --output=Z:/'", , Hide)
#i::Run(CygPath . "\\bin\\zsh.exe -i -l -c 'shot -i --output=Z:/'", , Hide)

;reload autohotkey
!F12::Reload

;linux-compatible useful keys
RAlt & -::Send(GetKeyState("Shift") ? "{U+2014}" : "{U+2013}")
RAlt & k::Send("{U+2026}")

;hepburn macrons
RAlt & =::
{
    key := Input("L1", "{delete}{esc}{home}{end}") ; pressing any of these will terminate the input
    if key == "A" {
        Send("{U+0100}")
    } else if key == "I" {
        Send("{U+012A}")
    } else if key == "U" {
        Send("{U+016A}")
    } else if key == "E" {
        Send("{U+0112}")
    } else if key == "O" {
        Send("{U+014C}")
    } else if key == "a" {
        Send("{U+0101}")
    } else if key == "i" {
        Send("{U+012B}")
    } else if key == "u" {
        Send("{U+016B}")
    } else if key == "e" {
        Send("{U+0113}")
    } else if key == "o" {
        Send("{U+014D}")
    }
     return
}

#n::
{
    CycleLocale()
}


Create 5. Domain Page - No Domain.ahk

Create 5. Domain Page - No Domain.ahk

templates/autohotkey_scripts/5. Domain Page - No Domain.ahk


AutoHotkey: Fix for Spotify ahk_class bugs

; Ignore duplicate presses while this subroutine is already running
#MaxThreadsPerHotkey 1
; Keeps a script permanently running, enabling timers. Closes on ExitApp still
#Persistent
; Ignore attempts to launch already-running script
#SingleInstance, ignore
SetBatchLines, -1
SendMode, Input
; Detect Spotify even if it's minimized
DetectHiddenWindows, On

; NOTE: As of Spotify 1.0.75.483.g7ff4a0dc, released around 2018-03-09,
;   `ahk_class SpotifyMainWindow` doesn't work so I had to replace it temporarily
;   with `ahk_exe Spotify.exe`
;   Reported here: https://community.spotify.com/t5/Ongoing-Issues/Windows-Desktop-app-now-uses-default-chrome-class-name/idi-p/4409722

; ctrl + shift + p = play/pause in Spotify
$^+p::
If (!Active2Flag) ; If the flag is not active do this
{
    ; IfWinExist ahk_class SpotifyMainWindow
    IfWinExist ahk_exe Spotify.exe
    {
        ; Play/Pause via clicking with the SendControl is busted
        ; spotify = ahk_class SpotifyMainWindow
        ; CoordMode, Mouse, Screen
        ; MouseGetPos, OrigX, OrigY
        ; WinActivate, %spotify%
        ; WinGetPos, X, Y, Width, Height, %spotify%
        ; MouseClick, Left, X+81, Y+1377
        ; WinMinimize, %spotify%
        ; MouseMove, OrigX, OrigY

        ; Activate Spotify window, send hotkey, minimize and activate previous window
        ; WinGetTitle, wintit
        ; WinActivate, ahk_exe spotify.exe
        ; Sleep, 50
        ; Send, {Space}, ahk_exe spotify.exe
        ; WinMinimize, ahk_exe spotify.exe
        ; WinActivate, wintit

        ; System wide Play/Pause seems to work but it activates foobar2000 too
        Send {Media_Play_Pause}

        ; Doesn't work with latest spotify update
        ; ControlSend, ahk_parent, {Space}, ahk_class SpotifyMainWindow ; Pause/Unpause
        Tooltip, Spotify Play/Pause
    }
    else
    {
        SetTitleMatchMode 2
        IfWinExist, foobar2000
        {
            ControlSend, ahk_parent, {Space} ; Pause/Unpause
            Tooltip, foobar2000 Play/Pause
        }
    }
    Active2Flag := 1 ; activate the flag
    SetTimer, Reactivate2, -1000 ; Reactivates once in 1000 ms = 1 seconds
}
return

; ctrl + shift + ] = Next Song in music player
$^+]::
If (!Active2Flag) ; If the flag is not active do this
{
    ; IfWinExist ahk_class SpotifyMainWindow
    IfWinExist ahk_exe Spotify.exe
    {
        ControlSend, ahk_parent, ^{Right}
        Tooltip, Spotify Next Song
    }
    else
    {
      ; TODO: Figure out how to set this as an else if, with the match mode
        SetTitleMatchMode 2
        IfWinExist foobar2000
        {
            ControlSend, ahk_parent, ^+]
            Tooltip, foobar2000 Next Song
        }
    }
    Active2Flag := 1 ; activate the flag
    SetTimer, Reactivate2, -1000 ; Reactivates once in 1000 ms = 1 seconds
}
return

; ctrl + shift + [ = Previous Song in music player
$^+[::
If (!Active2Flag) ; If the flag is not active do this
{
    ; IfWinExist ahk_class ahk_class SpotifyMainWindow
    IfWinExist ahk_exe Spotify.exe
    {
        ControlSend, ahk_parent, ^{Left}
        Tooltip, Spotify Previous Song
    }
    else
    {
        SetTitleMatchMode 2
        IfWinExist foobar2000
        {
            ControlSend, ahk_parent, ^+[
            Tooltip, foobar2000 Previous Song
        }
    }
    Active2Flag := 1 ; activate the flag
    SetTimer, Reactivate2, -1000 ; Reactivates once in 1000 ms = 1 seconds
}
return

Reactivate2:
    Active2Flag := 0 ; Deactivates the flag
    Tooltip
return

; Ignore duplicate presses while this subroutine is already running
#MaxThreadsPerHotkey 1
; Keeps a script permanently running, enabling timers. Closes on ExitApp still
#Persistent
; Ignore attempts to launch already-running script
#SingleInstance, ignore
SetBatchLines, -1
SendMode, Input
; Detect Spotify even if it's minimized
DetectHiddenWindows, On

; ctrl + shift + p = play/pause in Spotify
$^+p::
If (!Active2Flag) ; If the flag is not active do this
{
    IfWinExist ahk_class SpotifyMainWindow
    {
        ; Play/Pause via clicking with the SendControl is busted
        ; spotify = ahk_class SpotifyMainWindow
        ; CoordMode, Mouse, Screen
        ; MouseGetPos, OrigX, OrigY
        ; WinActivate, %spotify%
        ; WinGetPos, X, Y, Width, Height, %spotify%
        ; MouseClick, Left, X+81, Y+1377
        ; WinMinimize, %spotify%
        ; MouseMove, OrigX, OrigY

        ; Activate Spotify window, send hotkey, minimize and activate previous window
        ; WinGetTitle, wintit
        ; WinActivate, ahk_exe spotify.exe
        ; Sleep, 50
        ; Send, {Space}, ahk_exe spotify.exe
        ; WinMinimize, ahk_exe spotify.exe
        ; WinActivate, wintit

        ; System wide Play/Pause seems to work but it activates foobar2000 too
        Send {Media_Play_Pause}

        ; Doesn't work with latest spotify update
        ; ControlSend, ahk_parent, {Space}, ahk_class SpotifyMainWindow ; Pause/Unpause
        Tooltip, Spotify Play/Pause
    }
    else
    {
        SetTitleMatchMode 2
        IfWinExist, foobar2000
        {
            ControlSend, ahk_parent, {Space} ; Pause/Unpause
            Tooltip, foobar2000 Play/Pause
        }
    }
    Active2Flag := 1 ; activate the flag
    SetTimer, Reactivate2, -1000 ; Reactivates once in 1000 ms = 1 seconds
}
return

; ctrl + shift + ] = Next Song in music player
$^+]::
If (!Active2Flag) ; If the flag is not active do this
{
    IfWinExist ahk_class SpotifyMainWindow
    {
        ControlSend, ahk_parent, ^{Right}
        Tooltip, Spotify Next Song
    }
    else
    {
      ; TODO: Figure out how to set this as an else if, with the match mode
        SetTitleMatchMode 2
        IfWinExist foobar2000
        {
            ControlSend, ahk_parent, ^+]
            Tooltip, foobar2000 Next Song
        }
    }
    Active2Flag := 1 ; activate the flag
    SetTimer, Reactivate2, -1000 ; Reactivates once in 1000 ms = 1 seconds
}
return

; ctrl + shift + [ = Previous Song in music player
$^+[::
If (!Active2Flag) ; If the flag is not active do this
{
    IfWinExist ahk_class SpotifyMainWindow
    {
        ControlSend, ahk_parent, ^{Left}
        Tooltip, Spotify Previous Song
    }
    else
    {
        SetTitleMatchMode 2
        IfWinExist foobar2000
        {
            ControlSend, ahk_parent, ^+[
            Tooltip, foobar2000 Previous Song
        }
    }
    Active2Flag := 1 ; activate the flag
    SetTimer, Reactivate2, -1000 ; Reactivates once in 1000 ms = 1 seconds
}
return

Reactivate2:
    Active2Flag := 0 ; Deactivates the flag
    Tooltip
return


update backup

update backup

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

SetKeyDelay , 30, 30 ; first is delay between keypresses, and second is press duration

#WinActivateForce
DetectHiddenWindows, On

;#MaxHotkeysPerInterval 200

; https://stackoverflow.com/questions/49009176/autohotkey-causing-control-key-to-get-stuck
; https://www.autohotkey.com/docs/commands/_MenuMaskKey.htm
#MenuMaskKey vkFF

Return() {
    For Each, Modifier in ["Shift","LWin","RWin","Alt","LControl", "RControl"]
        If GetKeyState(Modifier) And !GetKeyState(Modifier,"P")
            Send, {%Modifier% Up}
    Exit
}
global ShiftDownTicks := 0
global ShiftPressed := 0

Loop
{
    if (ShiftPressed = 0) && GetKeyState("Shift")
    {
        ShiftPressed := 1
        ShiftDownTicks := A_TickCount
    }
    Sleep, 50
}

Shift UP::
    sleep 10
    ElapsedTime := A_TickCount - ShiftDownTicks
    ;MsgBox %ShiftDownTicks% DOWN %ElapsedTime% Up
    If ElapsedTime < 250
    {
        Send {Escape}
    }
    ShiftPressed := 0
return()

Shift & F13::

^Tab::
    Send #{Tab}
return()

^!o::
IfWinActive, ahk_exe Obsidian.exe
    sleep 10
else
    WinShow ahk_exe Obsidian.exe
    WinActivate ahk_exe Obsidian.exe
    sleep 10
    WinSet Top
return()

^!g::
IfWinActive, ahk_exe msedge.exe
    sleep 10
else
    ; WinShow will cause the search bar in Edge shown
    ; in about://flags, enable `Use Aura for Find on page`
    ; can make it better, but still a bit messy, some time not
    ; getting focus
    WinShow ahk_exe msedge.exe
    WinActivate ahk_exe msedge.exe
    sleep 10
    WinSet Top
return()

^!m::
IfWinActive, ahk_exe chrome.exe
    sleep 10
else
    WinShow ahk_exe chrome.exe
    WinActivate ahk_exe chrome.exe
    sleep 10
    WinSet Top
return()

^!Space::
Process,close,explorer.exe
sleep 50 ;This sleep 5000 is to let you see what actually happens. Decrease it later
run, explorer.exe
WinWait, ahk_class CabinetWClass
WinClose ;close the new explorer window
return()

global ChineseLayout := 0

SetCapsLockState, AlwaysOff
+CapsLock::CapsLock

CapsLock::
    Send, #{space}
    ChineseLayout := !ChineseLayout
    If ChineseLayout = 1
        KeyboardLED(4, "on")
    Else
        KeyboardLED(4, "off")
return()

^CapsLock::
    ChineseLayout := 0
    KeyboardLED(4, "off")
return()

/*

    Keyboard LED control for AutoHotkey_L
        http://www.autohotkey.com/forum/viewtopic.php?p=468000#468000

    KeyboardLED(LEDvalue, "Cmd", Kbd)
        LEDvalue  - ScrollLock=1, NumLock=2, CapsLock=4
        Cmd       - on/off/switch
        Kbd       - index of keyboard (probably 0 or 2)

*/

KeyboardLED(LEDvalue, Cmd, Kbd=0)
{
  SetUnicodeStr(fn,"\Device\KeyBoardClass" Kbd)
  h_device:=NtCreateFile(fn,0+0x00000100+0x00000080+0x00100000,1,1,0x00000040+0x00000020,0)

  If Cmd= switch  ;switches every LED according to LEDvalue
   KeyLED:= LEDvalue
  If Cmd= on  ;forces all choosen LED's to ON (LEDvalue= 0 ->LED's according to keystate)
   KeyLED:= LEDvalue | (GetKeyState("ScrollLock", "T") + 2*GetKeyState("NumLock", "T") + 4*GetKeyState("CapsLock", "T"))
  If Cmd= off  ;forces all choosen LED's to OFF (LEDvalue= 0 ->LED's according to keystate)
    {
    LEDvalue:= LEDvalue ^ 7
    KeyLED:= LEDvalue & (GetKeyState("ScrollLock", "T") + 2*GetKeyState("NumLock", "T") + 4*GetKeyState("CapsLock", "T"))
    }

  success := DllCall( "DeviceIoControl"
              ,  "ptr", h_device
              , "uint", CTL_CODE( 0x0000000b     ; FILE_DEVICE_KEYBOARD
                        , 2
                        , 0             ; METHOD_BUFFERED
                        , 0  )          ; FILE_ANY_ACCESS
              , "int*", KeyLED << 16
              , "uint", 4
              ,  "ptr", 0
              , "uint", 0
              ,  "ptr*", output_actual
              ,  "ptr", 0 )

  NtCloseFile(h_device)
  return success
}

CTL_CODE( p_device_type, p_function, p_method, p_access )
{
  Return, ( p_device_type << 16 ) | ( p_access << 14 ) | ( p_function << 2 ) | p_method
}

NtCreateFile(ByRef wfilename,desiredaccess,sharemode,createdist,flags,fattribs)
{
  VarSetCapacity(objattrib,6*A_PtrSize,0)
  VarSetCapacity(io,2*A_PtrSize,0)
  VarSetCapacity(pus,2*A_PtrSize)
  DllCall("ntdll\RtlInitUnicodeString","ptr",&pus,"ptr",&wfilename)
  NumPut(6*A_PtrSize,objattrib,0)
  NumPut(&pus,objattrib,2*A_PtrSize)
  status:=DllCall("ntdll\ZwCreateFile","ptr*",fh,"UInt",desiredaccess,"ptr",&objattrib
                  ,"ptr",&io,"ptr",0,"UInt",fattribs,"UInt",sharemode,"UInt",createdist
                  ,"UInt",flags,"ptr",0,"UInt",0, "UInt")
  return % fh
}

NtCloseFile(handle)
{
  return DllCall("ntdll\ZwClose","ptr",handle)
}

SetUnicodeStr(ByRef out, str_)
{
  VarSetCapacity(out,2*StrPut(str_,"utf-16"))
  StrPut(str_,&out,"utf-16")
}

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

SetKeyDelay , 30, 30 ; first is delay between keypresses, and second is press duration

#WinActivateForce
DetectHiddenWindows, On

;#MaxHotkeysPerInterval 200

; https://stackoverflow.com/questions/49009176/autohotkey-causing-control-key-to-get-stuck
; https://www.autohotkey.com/docs/commands/_MenuMaskKey.htm
#MenuMaskKey vkFF

Return() {
    For Each, Modifier in ["Shift","LWin","RWin","Alt","LControl", "RControl"]
        If GetKeyState(Modifier) And !GetKeyState(Modifier,"P")
            Send, {%Modifier% Up}
    Exit
}
global ShiftDownTicks := 0
global ShiftPressed := 0

Loop
{
    if (ShiftPressed = 0) && GetKeyState("Shift")
    {
        ShiftPressed := 1
        ShiftDownTicks := A_TickCount
    }
    Sleep, 50
}

Shift UP::
    sleep 10
    ElapsedTime := A_TickCount - ShiftDownTicks
    MsgBox %ShiftDownTicks% DOWN %ElapsedTime% Up
    If ElapsedTime < 250
    {
        Send {Escape}
    }
    ShiftPressed := 0
return()

Shift & F13::

^Tab::
    Send #{Tab}
return()

^!o::
IfWinActive, ahk_exe Obsidian.exe
    sleep 10
else
    WinShow ahk_exe Obsidian.exe
    WinActivate ahk_exe Obsidian.exe
    sleep 10
    WinSet Top
return()

^!g::
IfWinActive, ahk_exe msedge.exe
    sleep 10
else
    ; WinShow will cause the search bar in Edge shown
    ; in about://flags, enable `Use Aura for Find on page`
    ; can make it better, but still a bit messy, some time not
    ; getting focus
    WinShow ahk_exe msedge.exe
    WinActivate ahk_exe msedge.exe
    sleep 10
    WinSet Top
return()

^!m::
IfWinActive, ahk_exe chrome.exe
    sleep 10
else
    WinShow ahk_exe chrome.exe
    WinActivate ahk_exe chrome.exe
    sleep 10
    WinSet Top
return()

^!Space::
Process,close,explorer.exe
sleep 50 ;This sleep 5000 is to let you see what actually happens. Decrease it later
run, explorer.exe
WinWait, ahk_class CabinetWClass
WinClose ;close the new explorer window
return()

global ChineseLayout := 0

SetCapsLockState, AlwaysOff
+CapsLock::CapsLock

CapsLock::
    Send, #{space}
    ChineseLayout := !ChineseLayout
    If ChineseLayout = 1
        KeyboardLED(4, "on")
    Else
        KeyboardLED(4, "off")
return()

^CapsLock::
    ChineseLayout := 0
    KeyboardLED(4, "off")
return()

/*

    Keyboard LED control for AutoHotkey_L
        http://www.autohotkey.com/forum/viewtopic.php?p=468000#468000

    KeyboardLED(LEDvalue, "Cmd", Kbd)
        LEDvalue  - ScrollLock=1, NumLock=2, CapsLock=4
        Cmd       - on/off/switch
        Kbd       - index of keyboard (probably 0 or 2)

*/

KeyboardLED(LEDvalue, Cmd, Kbd=0)
{
  SetUnicodeStr(fn,"\Device\KeyBoardClass" Kbd)
  h_device:=NtCreateFile(fn,0+0x00000100+0x00000080+0x00100000,1,1,0x00000040+0x00000020,0)

  If Cmd= switch  ;switches every LED according to LEDvalue
   KeyLED:= LEDvalue
  If Cmd= on  ;forces all choosen LED's to ON (LEDvalue= 0 ->LED's according to keystate)
   KeyLED:= LEDvalue | (GetKeyState("ScrollLock", "T") + 2*GetKeyState("NumLock", "T") + 4*GetKeyState("CapsLock", "T"))
  If Cmd= off  ;forces all choosen LED's to OFF (LEDvalue= 0 ->LED's according to keystate)
    {
    LEDvalue:= LEDvalue ^ 7
    KeyLED:= LEDvalue & (GetKeyState("ScrollLock", "T") + 2*GetKeyState("NumLock", "T") + 4*GetKeyState("CapsLock", "T"))
    }

  success := DllCall( "DeviceIoControl"
              ,  "ptr", h_device
              , "uint", CTL_CODE( 0x0000000b     ; FILE_DEVICE_KEYBOARD
                        , 2
                        , 0             ; METHOD_BUFFERED
                        , 0  )          ; FILE_ANY_ACCESS
              , "int*", KeyLED << 16
              , "uint", 4
              ,  "ptr", 0
              , "uint", 0
              ,  "ptr*", output_actual
              ,  "ptr", 0 )

  NtCloseFile(h_device)
  return success
}

CTL_CODE( p_device_type, p_function, p_method, p_access )
{
  Return, ( p_device_type << 16 ) | ( p_access << 14 ) | ( p_function << 2 ) | p_method
}

NtCreateFile(ByRef wfilename,desiredaccess,sharemode,createdist,flags,fattribs)
{
  VarSetCapacity(objattrib,6*A_PtrSize,0)
  VarSetCapacity(io,2*A_PtrSize,0)
  VarSetCapacity(pus,2*A_PtrSize)
  DllCall("ntdll\RtlInitUnicodeString","ptr",&pus,"ptr",&wfilename)
  NumPut(6*A_PtrSize,objattrib,0)
  NumPut(&pus,objattrib,2*A_PtrSize)
  status:=DllCall("ntdll\ZwCreateFile","ptr*",fh,"UInt",desiredaccess,"ptr",&objattrib
                  ,"ptr",&io,"ptr",0,"UInt",fattribs,"UInt",sharemode,"UInt",createdist
                  ,"UInt",flags,"ptr",0,"UInt",0, "UInt")
  return % fh
}

NtCloseFile(handle)
{
  return DllCall("ntdll\ZwClose","ptr",handle)
}

SetUnicodeStr(ByRef out, str_)
{
  VarSetCapacity(out,2*StrPut(str_,"utf-16"))
  StrPut(str_,&out,"utf-16")
}